Merge branch 'dev'

This commit is contained in:
Mikhail 2023-05-28 06:37:16 +08:00
commit c830f3a4cc
18 changed files with 280 additions and 249 deletions

View File

@ -2,6 +2,7 @@
namespace DCFApixels.DragonECS
{
#region Interfaces
public interface IEcsPreInitProcess : IEcsSystem
{
void PreInit(EcsPipeline pipeline);
@ -18,7 +19,8 @@ namespace DCFApixels.DragonECS
{
void Destroy(EcsPipeline pipeline);
}
public interface IEcsBaseSystem : IEcsInitProcess, IEcsRunProcess, IEcsDestroyProcess { }
#endregion
namespace Internal
{
@ -40,7 +42,6 @@ namespace DCFApixels.DragonECS
foreach (var item in targets) item.PreInit(pipeline);
#endif
}
#if DEBUG && !DISABLE_DEBUG
protected override void OnSetup()
{
@ -70,7 +71,6 @@ namespace DCFApixels.DragonECS
foreach (var item in targets) item.Init(pipeline);
#endif
}
#if DEBUG && !DISABLE_DEBUG
protected override void OnSetup()
{
@ -101,7 +101,6 @@ namespace DCFApixels.DragonECS
foreach (var item in targets) item.Run(pipeline);
#endif
}
#if DEBUG && !DISABLE_DEBUG
protected override void OnSetup()
{
@ -131,7 +130,6 @@ namespace DCFApixels.DragonECS
foreach (var item in targets) item.Destroy(pipeline);
#endif
}
#if DEBUG && !DISABLE_DEBUG
protected override void OnSetup()
{

View File

@ -4,9 +4,6 @@ using System.Linq;
namespace DCFApixels.DragonECS
{
//TODO развить идею инжектов
//добавить контейнер, который автоматически создается, собирает в себя все пре-инжекты и авто-инжектится во все системы.
//но это спорная идея
public interface IEcsPreInject : IEcsSystem
{
void PreInject(object obj);

View File

@ -6,10 +6,10 @@ namespace DCFApixels.DragonECS
namespace Internal
{
[DebugHide, DebugColor(DebugColor.Black)]
public class SystemsBlockMarkerSystem : IEcsSystem
public class SystemsLayerMarkerSystem : IEcsSystem
{
public readonly string name;
public SystemsBlockMarkerSystem(string name) => this.name = name;
public SystemsLayerMarkerSystem(string name) => this.name = name;
}
[DebugHide, DebugColor(DebugColor.Grey)]
public class DeleteEmptyEntitesSystem : IEcsRunProcess, IEcsPreInject

View File

@ -1,9 +1,5 @@
namespace DCFApixels.DragonECS
{
internal sealed class EcsNullWorld : EcsWorld<EcsNullWorld>
{
public EcsNullWorld() : base(false) { }
}
public sealed class EcsDefaultWorld : EcsWorld<EcsDefaultWorld> { }
public sealed class EcsEventWorld : EcsWorld<EcsEventWorld> { }
}

View File

@ -10,45 +10,31 @@ namespace DCFApixels.DragonECS
public byte r => color.r;
public byte g => color.g;
public byte b => color.b;
/// <summary>normalized R channel </summary>
public float rn => color.r / 255f;
/// <summary>normalized G channel </summary>
public float gn => color.g / 255f;
/// <summary>normalized B channel </summary>
public float bn => color.b / 255f;
public DebugColorAttribute(byte r, byte g, byte b)
{
color = new ColorRecord(r, g, b);
}
public DebugColorAttribute(DebugColor color)
{
this.color = new ColorRecord((int)color);
}
public DebugColorAttribute(byte r, byte g, byte b) => color = new ColorRecord(r, g, b);
public DebugColorAttribute(DebugColor color) => this.color = new ColorRecord((int)color);
[StructLayout(LayoutKind.Explicit, Pack = 1, Size = 4)]
private readonly struct ColorRecord // Union
{
[FieldOffset(0)]
public readonly int full;
[FieldOffset(3)]
public readonly byte r;
[FieldOffset(2)]
public readonly byte g;
[FieldOffset(1)]
public readonly byte b;
[FieldOffset(0)] public readonly int full;
[FieldOffset(3)] public readonly byte r;
[FieldOffset(2)] public readonly byte g;
[FieldOffset(1)] public readonly byte b;
public ColorRecord(byte r, byte g, byte b) : this()
{
this.r = r;
this.g = g;
this.b = b;
}
public ColorRecord(int full) : this()
{
this.full = full;
}
public ColorRecord(int full) : this() => this.full = full;
}
}
public enum DebugColor
{
/// <summary> Red. RGB is (255, 0, 0)</summary>

View File

@ -6,9 +6,6 @@ namespace DCFApixels.DragonECS
public sealed class DebugDescriptionAttribute : Attribute
{
public readonly string description;
public DebugDescriptionAttribute(string description)
{
this.description = description;
}
public DebugDescriptionAttribute(string description) => this.description = description;
}
}

View File

@ -6,9 +6,6 @@ namespace DCFApixels.DragonECS
public sealed class DebugNameAttribute : Attribute
{
public readonly string name;
public DebugNameAttribute(string name)
{
this.name = name;
}
public DebugNameAttribute(string name) => this.name = name;
}
}

View File

@ -17,7 +17,6 @@ namespace DCFApixels.DragonECS
public void End() => EcsDebug.ProfileMarkEnd(id);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public AutoScope Auto() => new AutoScope(id);
public readonly ref struct AutoScope
{
private readonly int _id;
@ -36,7 +35,14 @@ namespace DCFApixels.DragonECS
public static void Set(DebugService service) => DebugService.Set(service);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Print(object v) => DebugService.Instance.Print(v);
public static void PrintWarning(object v) => Print(EcsConsts.DEBUG_WARNING_TAG, v);
public static void PrintError(object v) => Print(EcsConsts.DEBUG_ERROR_TAG, v);
public static void Print(object v)
{
#if !DISABLE_DRAGONECS_DEBUGGER
DebugService.Instance.Print(v);
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Print(string tag, object v)
{
@ -139,7 +145,6 @@ namespace DCFApixels.DragonECS
{
private Stopwatch[] _stopwatchs;
private string[] _stopwatchsNames;
public DefaultDebugService()
{
#if !DISABLE_DRAGONECS_DEBUGGER
@ -147,17 +152,14 @@ namespace DCFApixels.DragonECS
_stopwatchsNames= new string[64];
#endif
}
public override void Print(string tag, object v)
{
Console.WriteLine($"[{tag}] {v}");
}
public override void ProfileMarkBegin(int id)
{
_stopwatchs[id].Start();
}
public override void ProfileMarkEnd(int id)
{
_stopwatchs[id].Stop();
@ -165,12 +167,10 @@ namespace DCFApixels.DragonECS
_stopwatchs[id].Reset();
Print(_stopwatchsNames[id] + " s:" + time.TotalSeconds);
}
protected override void OnDelMark(int id)
{
_stopwatchs[id] = null;
}
protected override void OnNewMark(int id, string name)
{
if (id >= _stopwatchs.Length)

View File

@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if (DEBUG && !DISABLE_DEBUG) || !DISABLE_DRAGONECS_ASSERT_CHEKS
@ -8,6 +9,7 @@ using static DCFApixels.DragonECS.EcsGroup.ThrowHalper;
namespace DCFApixels.DragonECS
{
[StructLayout(LayoutKind.Sequential, Pack = 0, Size = 8)]
[DebuggerTypeProxy(typeof(DebuggerProxy))]
public readonly ref struct EcsReadonlyGroup
{
private readonly EcsGroup _source;
@ -65,12 +67,7 @@ namespace DCFApixels.DragonECS
#endregion
#region Object
public override string ToString()
{
if (_source != null)
return _source.ToString();
return "NULL";
}
public override string ToString() => _source != null ? _source.ToString() : "NULL";
public override int GetHashCode() => _source.GetHashCode();
public override bool Equals(object obj) => obj is EcsGroup group && group == this;
public bool Equals(EcsReadonlyGroup other) => _source == other._source;
@ -88,15 +85,23 @@ namespace DCFApixels.DragonECS
public static bool operator !=(EcsReadonlyGroup a, EcsReadonlyGroup b) => !a.Equals(b);
public static bool operator !=(EcsReadonlyGroup a, EcsGroup b) => !a.Equals(b);
#endregion
#region DebuggerProxy
internal class DebuggerProxy : EcsGroup.DebuggerProxy
{
public DebuggerProxy(EcsReadonlyGroup group) : base(group._source) { }
}
#endregion
}
[DebuggerTypeProxy(typeof(DebuggerProxy))]
public unsafe class EcsGroup : IDisposable, IEquatable<EcsGroup>
{
private EcsWorld _source;
private int[] _dense;
private int[] _sparse;
private int _count;
private bool _isReleased = true;
internal bool _isReleased = true;
#region Properties
public EcsWorld World => _source;
@ -219,12 +224,11 @@ namespace DCFApixels.DragonECS
}
#endregion
#region Sort/Clear
//public void Sort() { } //TODO прошлай реализация сортировки не удачная, так как в dense могут храниться занчения больше чем dense.Length
#region Clear
public void Clear()
{
_count = 0;
//массив _dense нет смысла очищать, испольщуется только область от 1 до _count
//массив _dense нет смысла очищать
for (int i = 0; i < _sparse.Length; i++)
_sparse[i] = 0;
}
@ -392,10 +396,7 @@ namespace DCFApixels.DragonECS
#endregion
#region Object
public override string ToString()
{
return string.Join(", ", _dense.AsSpan(1, _count).ToArray());
}
public override string ToString() => string.Join(", ", _dense.AsSpan(1, _count).ToArray());
public override bool Equals(object obj) => obj is EcsGroup group && Equals(group);
public bool Equals(EcsReadonlyGroup other) => Equals(other.GetGroupInternal());
public bool Equals(EcsGroup other)
@ -449,13 +450,9 @@ namespace DCFApixels.DragonECS
#endregion
#region IDisposable/Release
public void Dispose()
{
Release();
}
public void Dispose() => Release();
public void Release()
{
_isReleased = true;
_source.ReleaseGroup(this);
}
#endregion
@ -473,21 +470,30 @@ namespace DCFApixels.DragonECS
}
#endif
#endregion
}
#region Extensions
public static class EcsGroupExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Normalize<T>(this EcsGroup self, ref T[] array)
#region DebuggerProxy
internal class DebuggerProxy
{
if (array.Length < self.CapacityDense) Array.Resize(ref array, self.CapacityDense);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Normalize<T>(this EcsReadonlyGroup self, ref T[] array)
{
if (array.Length < self.CapacityDense) Array.Resize(ref array, self.CapacityDense);
private EcsGroup _group;
public EcsWorld World => _group.World;
public bool IsReleased => _group.IsReleased;
public entlong[] Entities
{
get
{
entlong[] result = new entlong[_group.Count];
int i = 0;
foreach (var e in _group)
result[i++] = _group.World.GetEntityLong(e);
return result;
}
}
public int Count => _group.Count;
public int CapacityDense => _group.CapacityDense;
public int CapacitySparce => _group.CapacitySparce;
public DebuggerProxy(EcsGroup group) => _group = group;
}
#endregion
}
#endregion
}
}

View File

@ -20,7 +20,6 @@ namespace DCFApixels.DragonECS
private bool _isInit;
private bool _isDestoryed;
private bool _isEmptyDummy;
#region Properties
public ReadOnlyCollection<IEcsSystem> AllSystems => _allSystemsSealed;
@ -39,7 +38,6 @@ namespace DCFApixels.DragonECS
_allRunnersSealed = new ReadOnlyDictionary<Type, IEcsRunner>(_runners);
_isInit = false;
_isEmptyDummy = false;
_isDestoryed = false;
}
#endregion
@ -64,9 +62,6 @@ namespace DCFApixels.DragonECS
#region LifeCycle
public void Init()
{
if (_isEmptyDummy)
return;
if (_isInit == true)
{
EcsDebug.Print("[Warning]", $"This {nameof(EcsPipeline)} has already been initialized");
@ -98,9 +93,6 @@ namespace DCFApixels.DragonECS
}
public void Destroy()
{
if (_isEmptyDummy)
return;
#if (DEBUG && !DISABLE_DEBUG) || !DISABLE_DRAGONECS_ASSERT_CHEKS
CheckBeforeInitForMethod(nameof(Run));
#endif
@ -135,10 +127,7 @@ namespace DCFApixels.DragonECS
#endregion
#region Builder
public static Builder New()
{
return new Builder();
}
public static Builder New() => new Builder();
public class Builder
{
private const int KEYS_CAPACITY = 4;
@ -149,16 +138,12 @@ namespace DCFApixels.DragonECS
public Builder()
{
_basicLayer = EcsConsts.BASIC_LAYER;
Layers = new LayerList(this, _basicLayer);
Layers.Insert(EcsConsts.BASIC_LAYER, EcsConsts.PRE_BEGIN_LAYER, EcsConsts.BEGIN_LAYER);
Layers.InsertAfter(EcsConsts.BASIC_LAYER, EcsConsts.END_LAYER, EcsConsts.POST_END_LAYER);
_uniqueTypes = new HashSet<Type>();
_systems = new Dictionary<string, List<IEcsSystem>>(KEYS_CAPACITY);
}
public Builder Add(IEcsSystem system, string layerName = null)
{
AddInternal(system, layerName, false);
@ -182,7 +167,7 @@ namespace DCFApixels.DragonECS
List<IEcsSystem> list;
if (!_systems.TryGetValue(layerName, out list))
{
list = new List<IEcsSystem> { new SystemsBlockMarkerSystem(layerName.ToString()) };
list = new List<IEcsSystem> { new SystemsLayerMarkerSystem(layerName.ToString()) };
_systems.Add(layerName, list);
}
if ((_uniqueTypes.Add(system.GetType()) == false && isUnique))
@ -192,20 +177,16 @@ namespace DCFApixels.DragonECS
if (system is IEcsModule module)//если система одновременно явялется и системой и модулем то за один Add будет вызван Add и AddModule
AddModule(module);
}
public Builder AddModule(IEcsModule module)
{
module.ImportSystems(this);
return this;
}
public EcsPipeline Build()
{
Add(new DeleteEmptyEntitesSystem(), EcsConsts.POST_END_LAYER);
List<IEcsSystem> result = new List<IEcsSystem>(32);
List<IEcsSystem> basicBlockList = _systems[_basicLayer];
foreach (var item in _systems)
{
if (!Layers.Has(item.Key))
@ -216,17 +197,14 @@ namespace DCFApixels.DragonECS
if(_systems.TryGetValue(item, out var list))
result.AddRange(list);
}
return new EcsPipeline(result.ToArray());
}
public class LayerList : IEnumerable<string>
{
private const string ADD_LAYER = nameof(ADD_LAYER); // автоматический слой нужный только для метода Add
private Builder _source;
private List<string> _layers;
private string _basicLayerName;
public LayerList(Builder source, string basicLayerName)

View File

@ -1,4 +1,5 @@
using System;
using DCFApixels.DragonECS.RunnersCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@ -9,9 +10,6 @@ using static DCFApixels.DragonECS.EcsDebugUtility;
namespace DCFApixels.DragonECS
{
using RunnersCore;
using System.ComponentModel;
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
sealed class EcsRunnerFilterAttribute : Attribute
{
@ -29,7 +27,6 @@ namespace DCFApixels.DragonECS
namespace RunnersCore
{
[EditorBrowsable(EditorBrowsableState.Never)]
public interface IEcsRunner
{
EcsPipeline Source { get; }
@ -122,8 +119,10 @@ namespace DCFApixels.DragonECS
EcsRunner<TInterface>.Register(runnerType);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class EcsRunner<TInterface> : IEcsSystem, IEcsRunner
#if UNITY_2020_3_OR_NEWER
[UnityEngine.Scripting.RequireDerived, UnityEngine.Scripting.Preserve]
#endif
public abstract class EcsRunner<TInterface> : IEcsSystem, IEcsRunner
where TInterface : IEcsSystem
{
#region Register

View File

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
@ -65,6 +67,7 @@ namespace DCFApixels.DragonECS
return (TSubject)newSubject;
}
#region Include/Exclude/Optional
public sealed override TPool Include<TComponent, TPool>()
{
IncludeImplicit<TComponent>();
@ -79,7 +82,6 @@ namespace DCFApixels.DragonECS
{
return _world.GetPool<TComponent, TPool>();
}
public void IncludeImplicit<TComponent>()
{
int id = _world.GetComponentID<TComponent>();
@ -96,6 +98,7 @@ namespace DCFApixels.DragonECS
#endif
_exc.Add(_world.GetComponentID<TComponent>());
}
#endregion
private void End(out EcsMask mask)
{
@ -106,6 +109,20 @@ namespace DCFApixels.DragonECS
_inc = null;
_exc = null;
}
#region SupportReflectionHack
#if UNITY_2020_3_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
private void SupportReflectionHack<TComponent, TPool>() where TPool : IEcsPoolImplementation<TComponent>, new()
{
Include<TComponent, TPool>();
Exclude<TComponent, TPool>();
Optional<TComponent, TPool>();
IncludeImplicit<TComponent>();
ExcludeImplicit<TComponent>();
}
#endregion
}
#endregion
}
@ -127,13 +144,14 @@ namespace DCFApixels.DragonECS
#region BuilderBase
public abstract class EcsSubjectBuilderBase
{
public abstract TPool Include<TComponent, TPool>() where TComponent : struct where TPool : IEcsPoolImplementation<TComponent>, new();
public abstract TPool Exclude<TComponent, TPool>() where TComponent : struct where TPool : IEcsPoolImplementation<TComponent>, new();
public abstract TPool Optional<TComponent, TPool>() where TComponent : struct where TPool : IEcsPoolImplementation<TComponent>, new();
public abstract TPool Include<TComponent, TPool>() where TPool : IEcsPoolImplementation<TComponent>, new();
public abstract TPool Exclude<TComponent, TPool>() where TPool : IEcsPoolImplementation<TComponent>, new();
public abstract TPool Optional<TComponent, TPool>() where TPool : IEcsPoolImplementation<TComponent>, new();
}
#endregion
#region Mask
[DebuggerTypeProxy(typeof(DebuggerProxy))]
public sealed class EcsMask
{
internal readonly Type _worldType;
@ -145,10 +163,40 @@ namespace DCFApixels.DragonECS
_inc = inc;
_exc = exc;
}
public override string ToString()
public override string ToString() => CreateLogString(_worldType, _inc, _exc);
#region Debug utils
private static string CreateLogString(Type worldType, int[] inc, int[] exc)
{
return $"Inc({string.Join(", ", _inc)}) Exc({string.Join(", ", _exc)})";
#if DEBUG
int worldID = WorldMetaStorage.GetWorldID(worldType);
string converter(int o) => EcsDebugUtility.GetGenericTypeName(WorldMetaStorage.GetComponentType(worldID, o), 1);
return $"Inc({string.Join(", ", inc.Select(converter))}) Exc({string.Join(", ", exc.Select(converter))})";
#else
return $"Inc({string.Join(", ", inc)}) Exc({string.Join(", ", exc)})"; // Release optimization
#endif
}
internal class DebuggerProxy
{
public readonly Type worldType;
public readonly int[] inc;
public readonly int[] exc;
public readonly Type[] incTypes;
public readonly Type[] excTypes;
public DebuggerProxy(EcsMask mask)
{
worldType = mask._worldType;
int worldID = WorldMetaStorage.GetWorldID(worldType);
inc = mask._inc;
exc = mask._exc;
Type converter(int o) => WorldMetaStorage.GetComponentType(worldID, o);
incTypes = inc.Select(converter).ToArray();
excTypes = exc.Select(converter).ToArray();
}
public override string ToString() => CreateLogString(worldType, inc, exc);
}
#endregion
}
#endregion
@ -156,25 +204,25 @@ namespace DCFApixels.DragonECS
public ref struct EcsSubjectIterator<TSubject> where TSubject : EcsSubject
{
public readonly TSubject s;
private EcsReadonlyGroup sourceGroup;
private Enumerator enumerator;
private EcsReadonlyGroup _sourceGroup;
private Enumerator _enumerator;
public EcsSubjectIterator(TSubject s, EcsReadonlyGroup sourceGroup)
{
this.s = s;
this.sourceGroup = sourceGroup;
enumerator = default;
_sourceGroup = sourceGroup;
_enumerator = default;
}
public int Entity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => enumerator.Current;
get => _enumerator.Current;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Begin() => enumerator = GetEnumerator();
public void Begin() => _enumerator = GetEnumerator();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Next() => enumerator.MoveNext();
public bool Next() => _enumerator.MoveNext();
public void CopyTo(EcsGroup group)
{
group.Clear();
@ -183,7 +231,7 @@ namespace DCFApixels.DragonECS
group.AddInternal(enumerator.Current);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Enumerator GetEnumerator() => new Enumerator(sourceGroup, s);
public Enumerator GetEnumerator() => new Enumerator(_sourceGroup, s);
public override string ToString()
{

View File

@ -26,9 +26,6 @@ namespace DCFApixels.DragonECS
private short[] _componentCounts;
private EcsGroup _allEntites;
//буфер удаления откладывает освобождение андишников сущностей.
//Нужен для того чтобы запускать некоторые процесыы связанные с удалением сущности не по одному при каждом удалении, а пачкой
//В теории такой подход частично улучшает ситуацию с переполнением поколений
private int[] _delEntBuffer;
private int _delEntBufferCount;
@ -75,7 +72,7 @@ namespace DCFApixels.DragonECS
Worlds[uniqueID] = this;
}
_worldTypeID = WorldMetaStorage.GetWorldId(Archetype);
_worldTypeID = WorldMetaStorage.GetWorldID(Archetype);
_entityDispenser = new IntDispenser(0);
_nullPool = EcsNullPool.instance;
@ -95,7 +92,6 @@ namespace DCFApixels.DragonECS
_subjects = new EcsSubject[128];
_executors = new EcsQueryExecutor[128];
}
public void Destroy()
{
_entityDispenser = null;
@ -109,10 +105,6 @@ namespace DCFApixels.DragonECS
Worlds[uniqueID] = null;
_worldIdDispenser.Release(uniqueID);
}
public void DestryWithPipeline()
{
Destroy();
}
#endregion
#region GetComponentID
@ -121,26 +113,25 @@ namespace DCFApixels.DragonECS
#endregion
#region GetPool
public TPool GetPool<TComponent, TPool>() where TComponent : struct where TPool : IEcsPoolImplementation<TComponent>, new()
#if UNITY_2020_3_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
public TPool GetPool<TComponent, TPool>() where TPool : IEcsPoolImplementation<TComponent>, new()
{
int uniqueID = WorldMetaStorage.GetComponentId<TComponent>(_worldTypeID);
if (uniqueID >= _pools.Length)
{
int oldCapacity = _pools.Length;
Array.Resize(ref _pools, _pools.Length << 1);
ArrayUtility.Fill(_pools, _nullPool, oldCapacity, oldCapacity - _pools.Length);
}
if (_pools[uniqueID] == _nullPool)
{
var pool = new TPool();
_pools[uniqueID] = pool;
pool.OnInit(this, uniqueID);
_poolsCount++;
//EcsDebug.Print(pool.GetType().FullName);
}
return (TPool)_pools[uniqueID];
}
#endregion
@ -158,39 +149,38 @@ namespace DCFApixels.DragonECS
#endregion
#region Queries
public TExecutor GetExecutor<TExecutor>(Func<EcsWorld, TExecutor> builder) where TExecutor: EcsQueryExecutor
public TExecutor GetExecutor<TExecutor>() where TExecutor : EcsQueryExecutor, new()
{
int id = WorldMetaStorage.GetExecutorId<TExecutor>(_worldTypeID);
if (id >= _executors.Length)
Array.Resize(ref _executors, _executors.Length << 1);
if (_executors[id] == null)
_executors[id] = builder(this);
{
var executor = new TExecutor();
executor.Initialize(this);
_executors[id] = executor;
}
return (TExecutor)_executors[id];
}
private EcsWhereExecutor<TSubject> EcsWhereExecutorBuilder<TSubject>(EcsWorld world) where TSubject : EcsSubject
{
return new EcsWhereExecutor<TSubject>(world.GetSubject<TSubject>());
}
public EcsWhereResult<TSubject> WhereFor<TSubject>(EcsReadonlyGroup sourceGroup, out TSubject subject) where TSubject : EcsSubject
{
var executor = GetExecutor(EcsWhereExecutorBuilder<TSubject>);
var executor = GetExecutor<EcsWhereExecutor<TSubject>>();
subject = executor.Subject;
return executor.ExecuteFor(sourceGroup);
}
public EcsWhereResult<TSubject> WhereFor<TSubject>(EcsReadonlyGroup sourceGroup) where TSubject : EcsSubject
{
return GetExecutor(EcsWhereExecutorBuilder<TSubject>).ExecuteFor(sourceGroup);
return GetExecutor<EcsWhereExecutor<TSubject>>().ExecuteFor(sourceGroup);
}
public EcsWhereResult<TSubject> Where<TSubject>(out TSubject subject) where TSubject : EcsSubject
{
var executor = GetExecutor(EcsWhereExecutorBuilder<TSubject>);
var executor = GetExecutor<EcsWhereExecutor<TSubject>>();
subject = executor.Subject;
return executor.Execute();
}
public EcsWhereResult<TSubject> Where<TSubject>() where TSubject : EcsSubject
{
return GetExecutor(EcsWhereExecutorBuilder<TSubject>).Execute();
return GetExecutor<EcsWhereExecutor<TSubject>>().Execute();
}
#endregion
@ -332,15 +322,16 @@ namespace DCFApixels.DragonECS
}
#endregion
#region Groups
#region Groups Pool
internal void RegisterGroup(EcsGroup group)
{
_groups.Add(new WeakReference<EcsGroup>(group));
}
internal EcsGroup GetGroupFromPool()
{
if (_groupsPool.Count <= 0) return new EcsGroup(this);
return _groupsPool.Pop();
EcsGroup result = _groupsPool.Count <= 0 ? new EcsGroup(this) : _groupsPool.Pop();
result._isReleased = false;
return result;
}
internal void ReleaseGroup(EcsGroup group)
{
@ -348,6 +339,7 @@ namespace DCFApixels.DragonECS
if (group.World != this)
throw new ArgumentException("groupFilter.WorldIndex != this");
#endif
group._isReleased = true;
group.Clear();
_groupsPool.Push(group);
}
@ -369,40 +361,13 @@ namespace DCFApixels.DragonECS
break;
}
}
#endregion
// public int GetComponents(int entity, ref object[] list)
// {
// var entityOffset = GetRawEntityOffset(entity);
// var itemsCount = _entities[entityOffset + RawEntityOffsets.ComponentsCount];
// if (itemsCount == 0) { return 0; }
// if (list == null || list.Length < itemsCount)
// {
// list = new object[_pools.Length];
// }
// var dataOffset = entityOffset + RawEntityOffsets.Components;
// for (var i = 0; i < itemsCount; i++)
// {
// list[i] = _pools[_entities[dataOffset + i]].GetRaw(entity);
// }
// return itemsCount;
// }
// public int GetComponentTypes(int entity, ref Type[] list)
// {
// var entityOffset = GetRawEntityOffset(entity);
// var itemsCount = _entities[entityOffset + RawEntityOffsets.ComponentsCount];
// if (itemsCount == 0) { return 0; }
// if (list == null || list.Length < itemsCount)
// {
// list = new Type[_pools.Length];
// }
// var dataOffset = entityOffset + RawEntityOffsets.Components;
// for (var i = 0; i < itemsCount; i++)
// {
// list[i] = _pools[_entities[dataOffset + i]].GetComponentType();
// }
// return itemsCount;
// }
#region NullWorld
private sealed class EcsNullWorld : EcsWorld<EcsNullWorld>
{
public EcsNullWorld() : base(false) { }
}
#endregion
}
@ -414,31 +379,33 @@ namespace DCFApixels.DragonECS
internal EcsWorld(bool isIndexable) : base(isIndexable) { }
}
#region Utils
#region WorldMetaStorage
public static class WorldMetaStorage
{
private static List<Resizer> _resizer = new List<Resizer>();
private static int _tokenCount = 0;
private static int[] _componentCounts = new int[0];
private static int[] _subjectsCounts = new int[0];
private static WorldTypeMeta[] _metas = new WorldTypeMeta[0];
private static Dictionary<Type, int> _worldIds = new Dictionary<Type, int>();
private static class WorldIndex<TWorldArchetype>
{
public static int id = GetWorldId(typeof(TWorldArchetype));
public static int id = GetWorldID(typeof(TWorldArchetype));
}
private static int GetToken()
{
_tokenCount++;
Array.Resize(ref _componentCounts, _tokenCount);
Array.Resize(ref _subjectsCounts, _tokenCount);
WorldTypeMeta meta = new WorldTypeMeta();
meta.id = _tokenCount;
Array.Resize(ref _metas, ++_tokenCount);
_metas[_tokenCount - 1] = meta;
foreach (var item in _resizer)
item.Resize(_tokenCount);
return _tokenCount - 1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetWorldId(Type archetype)
public static int GetWorldID(Type archetype)
{
if(_worldIds.TryGetValue(archetype, out int id) == false)
if(!_worldIds.TryGetValue(archetype, out int id))
{
id = GetToken();
_worldIds.Add(archetype, id);
@ -453,6 +420,11 @@ namespace DCFApixels.DragonECS
public static int GetSubjectId<T>(int worldID) => Subject<T>.Get(worldID);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int GetExecutorId<T>(int worldID) => Executor<T>.Get(worldID);
public static bool IsComponentTypeDeclared(int worldID, Type type) => _metas[worldID].IsDeclaredType(type);
public static Type GetComponentType(int worldID, int componentID) => _metas[worldID].GetComponentType(componentID);
#region Resizer
private abstract class Resizer
{
public abstract void Resize(int size);
@ -466,6 +438,7 @@ namespace DCFApixels.DragonECS
Array.Resize(ref Executor<T>.ids, size);
}
}
#endregion
private static class Component<T>
{
public static int[] ids;
@ -481,7 +454,11 @@ namespace DCFApixels.DragonECS
{
ref int id = ref ids[token];
if (id < 0)
id = _componentCounts[token]++;
{
var meta = _metas[token];
id = meta.componentCount++;
meta.AddType(id, typeof(T));
}
return id;
}
}
@ -500,7 +477,7 @@ namespace DCFApixels.DragonECS
{
ref int id = ref ids[token];
if (id < 0)
id = _subjectsCounts[token]++;
id = _metas[token].subjectsCount++;
return id;
}
}
@ -519,10 +496,35 @@ namespace DCFApixels.DragonECS
{
ref int id = ref ids[token];
if (id < 0)
id = _subjectsCounts[token]++;
id = _metas[token].executorsCount++;
return id;
}
}
private class WorldTypeMeta
{
public int id;
public int componentCount;
public int subjectsCount;
public int executorsCount;
private Type[] types;
private HashSet<Type> declaredComponentTypes;
public void AddType(int id, Type type)
{
if(types.Length <= id)
Array.Resize(ref types, id + 10);
types[id] = type;
declaredComponentTypes.Add(type);
}
public Type GetComponentType(int componentID) => types[componentID];
public bool IsDeclaredType(Type type) => declaredComponentTypes.Contains(type);
public WorldTypeMeta()
{
types = new Type[10];
declaredComponentTypes = new HashSet<Type>();
}
}
}
#endregion
@ -564,4 +566,12 @@ namespace DCFApixels.DragonECS
}
}
#endregion
#region Extensions
public static class IntExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static entlong ToEntityLong(this int self, EcsWorld world) => world.GetEntityLong(self);
}
#endregion
}

View File

@ -2,6 +2,14 @@
{
public abstract class EcsQueryExecutor
{
private EcsWorld _world;
public EcsWorld World => _world;
internal void Initialize(EcsWorld world)
{
_world = world;
OnInitialize();
}
protected abstract void OnInitialize();
internal void Destroy() => OnDestroy();
protected abstract void OnDestroy();
}

View File

@ -1,26 +1,28 @@
using Unity.Profiling;
namespace DCFApixels.DragonECS
namespace DCFApixels.DragonECS
{
public sealed class EcsWhereExecutor<TSubject> : EcsQueryExecutor where TSubject : EcsSubject
{
private readonly TSubject _subject;
private readonly EcsGroup _filteredGroup;
private TSubject _subject;
private EcsGroup _filteredGroup;
private long _executeVersion;
private ProfilerMarker _executeWhere = new ProfilerMarker("JoinAttachQuery.Where");
private EcsProfilerMarker _executeWhere = new EcsProfilerMarker("Where");
#region Properties
public TSubject Subject => _subject;
internal long ExecuteVersion => _executeVersion;
#endregion
#region Constructors
public EcsWhereExecutor(TSubject subject)
#region OnInitialize/OnDestroy
protected sealed override void OnInitialize()
{
_subject = subject;
_filteredGroup = EcsGroup.New(subject.World);
_subject = World.GetSubject<TSubject>();
_filteredGroup = EcsGroup.New(World);
}
protected sealed override void OnDestroy()
{
_filteredGroup.Release();
}
#endregion
@ -37,10 +39,6 @@ namespace DCFApixels.DragonECS
return new EcsWhereResult<TSubject>(this, _filteredGroup.Readonly);
}
}
protected sealed override void OnDestroy()
{
_filteredGroup.Release();
}
#endregion
}
@ -52,7 +50,6 @@ namespace DCFApixels.DragonECS
public readonly EcsReadonlyGroup group;
private readonly long _version;
public bool IsRelevant => _version == _executer.ExecuteVersion;
public EcsWhereResult(EcsWhereExecutor<TSubject> executer, EcsReadonlyGroup group)
{
_executer = executer;
@ -67,7 +64,6 @@ namespace DCFApixels.DragonECS
#endif
return group.GetEnumerator();
}
public override string ToString()
{
return group.ToString();

View File

@ -31,15 +31,6 @@ namespace DCFApixels.DragonECS
void RemoveListener(IEcsPoolEventListener listener);
#endregion
}
public interface IEcsPoolEventListener
{
/// <summary>Called after adding an entity to the pool, but before changing values.</summary>
void OnAdd(int entityID);
/// <summary>Is called when EcsPool.Write or EcsPool.Add is called, but before changing values.</summary>
void OnWrite(int entityID);
/// <summary>Called after deleting an entity from the pool</summary>
void OnDel(int entityID);
}
public interface IEcsPool<T>
{
ref T Add(int entityID);
@ -47,7 +38,6 @@ namespace DCFApixels.DragonECS
ref T Write(int entityID);
}
/// <summary>Only used to implement a custom pool. In other contexts use IEcsPool or IEcsPool<T>.</summary>
/// <typeparam name="T">Component type</typeparam>
public interface IEcsPoolImplementation : IEcsPool
{
void OnInit(EcsWorld world, int componentID);
@ -98,7 +88,7 @@ namespace DCFApixels.DragonECS
}
}
#region Dummy
#region Dummy EcsNullPool
namespace Internal
{
public struct NullComponent { }
@ -216,7 +206,16 @@ namespace DCFApixels.DragonECS
}
#endregion
#region Extensions
#region Callbacks Interface
public interface IEcsPoolEventListener
{
/// <summary>Called after adding an entity to the pool, but before changing values.</summary>
void OnAdd(int entityID);
/// <summary>Is called when EcsPool.Write or EcsPool.Add is called, but before changing values.</summary>
void OnWrite(int entityID);
/// <summary>Called after deleting an entity from the pool</summary>
void OnDel(int entityID);
}
public static class PoolEventListExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]

View File

@ -1,10 +0,0 @@
namespace DCFApixels.DragonECS
{
public static class IntExtensions
{
public static entlong ToEntityLong(this int self, EcsWorld world)
{
return world.GetEntityLong(self);
}
}
}

View File

@ -1,15 +1,17 @@
#pragma warning disable IDE1006
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using static DCFApixels.DragonECS.entlong.ThrowHalper;
namespace DCFApixels.DragonECS
{
using static entlong.ThrowHalper;
// [ id 32 | gen 16 | world 16 ]
/// <summary>Strong identifier/Permanent entity identifier</summary>
[StructLayout(LayoutKind.Explicit, Pack = 2, Size = 8)]
[DebuggerTypeProxy(typeof(DebuggerProxy))]
public readonly struct entlong : IEquatable<long>, IEquatable<entlong>
{
public static readonly entlong NULL = default;
@ -33,8 +35,6 @@ namespace DCFApixels.DragonECS
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => this == NULL;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public int ID
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@ -46,7 +46,6 @@ namespace DCFApixels.DragonECS
return id;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public short Gen
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@ -69,7 +68,6 @@ namespace DCFApixels.DragonECS
return EcsWorld.Worlds[world];
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public short WorldID
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@ -158,5 +156,33 @@ namespace DCFApixels.DragonECS
}
}
#endregion
#region DebuggerProxy
internal class DebuggerProxy
{
private List<object> _componentsList;
private entlong _value;
public long full => _value.full;
public int id => _value.id;
public int gen => _value.gen;
public int world => _value.world;
public EntState State => _value.IsNull ? EntState.Null : _value.IsAlive ? EntState.Alive : EntState.Dead;
public EcsWorld EcsWorld => _value.World;
public IEnumerable<object> components
{
get
{
_value.World.GetComponents(_value.ID, _componentsList);
return _componentsList;
}
}
public DebuggerProxy(entlong value)
{
_value = value;
_componentsList = new List<object>();
}
public enum EntState { Null, Dead, Alive, }
}
#endregion
}
}