From 6186036a08fe14fd40e65c3b52f7700025a35e98 Mon Sep 17 00:00:00 2001 From: Mikhail <99481254+DCFApixels@users.noreply.github.com> Date: Thu, 30 Mar 2023 16:43:22 +0800 Subject: [PATCH] Implement IComponentReset --- src/EcsPool.cs | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/EcsPool.cs b/src/EcsPool.cs index cb73ef7..58804ae 100644 --- a/src/EcsPool.cs +++ b/src/EcsPool.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using System; using System.Reflection; using System.Linq; +using UnityEngine; namespace DCFApixels.DragonECS { @@ -47,6 +48,8 @@ namespace DCFApixels.DragonECS private readonly SparseSet _sparseSet; private T[] _denseItems; + private IEcsComponentReset _componentResetHandler; + #region Properites public IEcsWorld World => _source; public int ID => _id; @@ -60,6 +63,8 @@ namespace DCFApixels.DragonECS _sparseSet = new SparseSet(capacity, capacity); _denseItems =new T[capacity]; + + _componentResetHandler = ComponentResetHandler.New(); } #endregion @@ -72,18 +77,14 @@ namespace DCFApixels.DragonECS [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T Write(int entity) { - if (_sparseSet.Contains(entity)) - { - return ref _denseItems[_sparseSet.IndexOf(entity)]; - } - else + if (!_sparseSet.Contains(entity)) { _sparseSet.Add(entity); _sparseSet.Normalize(ref _denseItems); _source.OnEntityComponentAdded(entity, _id); - int indexof = _sparseSet.IndexOf(entity); - return ref _denseItems[indexof]; + _componentResetHandler.Reset(ref _denseItems[_sparseSet.IndexOf(entity)]); } + return ref _denseItems[_sparseSet.IndexOf(entity)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -114,4 +115,30 @@ namespace DCFApixels.DragonECS public override int GetHashCode() => _source.GetHashCode() + ID; #endregion } + + internal static class ComponentResetHandler + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static IEcsComponentReset New() + { + Type targetType = typeof(T); + if (targetType.GetInterfaces().Contains(typeof(IEcsComponentReset<>).MakeGenericType(targetType))) + { + return (IEcsComponentReset)Activator.CreateInstance(typeof(ComponentResetHandler<>).MakeGenericType(targetType)); + } + return (IEcsComponentReset)Activator.CreateInstance(typeof(ComponentResetDummy<>).MakeGenericType(targetType)); + } + } + internal sealed class ComponentResetDummy : IEcsComponentReset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reset(ref T component) => component = default; + } + internal sealed class ComponentResetHandler : IEcsComponentReset + where T : IEcsComponentReset + { + private T _fakeInstnace = default; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reset(ref T component) => _fakeInstnace.Reset(ref component); + } }