Compare commits

...

3 Commits

Author SHA1 Message Date
cosmonaut 94c195e920 sparse set 2023-12-19 15:31:10 -08:00
cosmonaut cbdcca5bbf start rewriting component storage 2023-12-18 17:58:08 -08:00
cosmonaut 2adecf771a rewrite storage getters to avoid dictionaries 2023-12-18 11:33:29 -08:00
10 changed files with 319 additions and 257 deletions

View File

@ -7,8 +7,8 @@ namespace MoonTools.ECS.Collections;
public unsafe class NativeArray<T> : IDisposable where T : unmanaged public unsafe class NativeArray<T> : IDisposable where T : unmanaged
{ {
private T* Elements; private T* Elements;
public int Count { get; private set;} public int Count { get; private set; }
private int Capacity; public int Capacity { get; private set; }
private int ElementSize; private int ElementSize;
public Span<T> ToSpan() => new Span<T>(Elements, Count); public Span<T> ToSpan() => new Span<T>(Elements, Count);
@ -61,7 +61,7 @@ public unsafe class NativeArray<T> : IDisposable where T : unmanaged
Count = 0; Count = 0;
} }
private void ResizeTo(int size) public void ResizeTo(int size)
{ {
Capacity = size; Capacity = size;
Elements = (T*) NativeMemory.Realloc((void*) Elements, (nuint) (ElementSize * Capacity)); Elements = (T*) NativeMemory.Realloc((void*) Elements, (nuint) (ElementSize * Capacity));

View File

@ -7,8 +7,8 @@ namespace MoonTools.ECS.Collections;
internal unsafe class NativeArray : IDisposable internal unsafe class NativeArray : IDisposable
{ {
private nint Elements; private nint Elements;
public int Count { get; private set;} public int Count { get; private set; }
private int Capacity; public int Capacity { get; private set; }
public readonly int ElementSize; public readonly int ElementSize;
private bool IsDisposed; private bool IsDisposed;
@ -44,7 +44,7 @@ internal unsafe class NativeArray : IDisposable
Elements = (nint) NativeMemory.Realloc((void*) Elements, (nuint) (ElementSize * Capacity)); Elements = (nint) NativeMemory.Realloc((void*) Elements, (nuint) (ElementSize * Capacity));
} }
private void ResizeTo(int capacity) public void ResizeTo(int capacity)
{ {
Capacity = capacity; Capacity = capacity;
Elements = (nint) NativeMemory.Realloc((void*) Elements, (nuint) (ElementSize * Capacity)); Elements = (nint) NativeMemory.Realloc((void*) Elements, (nuint) (ElementSize * Capacity));
@ -65,6 +65,11 @@ internal unsafe class NativeArray : IDisposable
Count -= 1; Count -= 1;
} }
public void RemoveLastElement()
{
Count -= 1;
}
public void Append<T>(T component) where T : unmanaged public void Append<T>(T component) where T : unmanaged
{ {
if (Count >= Capacity) if (Count >= Capacity)

View File

@ -1,87 +1,104 @@
using System; using System;
using System.Collections.Generic; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using MoonTools.ECS.Collections; using MoonTools.ECS.Collections;
namespace MoonTools.ECS; namespace MoonTools.ECS;
internal class ComponentStorage : IDisposable public class ComponentStorage : IDisposable
{ {
internal readonly Dictionary<Entity, int> EntityIDToStorageIndex = new Dictionary<Entity, int>(16); internal readonly NativeArray<Entity> DenseArray = new NativeArray<Entity>();
internal readonly NativeArray Components; internal readonly NativeArray<int> SparseArray = new NativeArray<int>();
internal readonly NativeArray<Entity> EntityIDs; internal nint ElementArray;
internal readonly TypeId TypeId; internal int ElementArrayCapacity;
private bool IsDisposed; private bool IsDisposed;
public ComponentStorage(TypeId typeId, int elementSize) public int ElementSize { get; private set; }
public int Count => DenseArray.Count;
public unsafe ComponentStorage(int elementSize)
{ {
Components = new NativeArray(elementSize); for (var i = 0; i < 16; i += 1)
EntityIDs = new NativeArray<Entity>(); {
TypeId = typeId; SparseArray.Append(Entity.Null.ID); // sentinel value
}
ElementArrayCapacity = 16;
ElementArray = (nint) NativeMemory.Alloc((nuint) (elementSize * ElementArrayCapacity));
ElementSize = elementSize;
} }
public bool Any() public bool Any() => DenseArray.Count > 0;
public unsafe ref T Get<T>(Entity entity) where T : unmanaged
{ {
return Components.Count > 0; return ref ((T*) ElementArray)[SparseArray[entity.ID]];
} }
public bool Has(Entity entity) public unsafe ref T GetFirst<T>() where T : unmanaged
{
return EntityIDToStorageIndex.ContainsKey(entity);
}
public ref T Get<T>(in Entity entity) where T : unmanaged
{
return ref Components.Get<T>(EntityIDToStorageIndex[entity]);
}
public ref T GetFirst<T>() where T : unmanaged
{ {
#if DEBUG #if DEBUG
if (Components.Count == 0) if (DenseArray.Count == 0)
{ {
throw new IndexOutOfRangeException("Component storage is empty!"); throw new IndexOutOfRangeException("Component storage is empty!");
} }
#endif #endif
return ref Components.Get<T>(0); return ref ((T*) ElementArray)[0];
} }
// Returns true if the entity had this component. public unsafe bool Set<T>(Entity entity, T component) where T : unmanaged
public bool Set<T>(in Entity entity, in T component) where T : unmanaged
{ {
if (EntityIDToStorageIndex.TryGetValue(entity, out var index)) var newEntity = entity.ID >= SparseArray.Count || SparseArray[entity.ID] == Entity.Null.ID;
if (newEntity)
{ {
Components.Set(index, component); // the entity is being added! let's do some record keeping
return true; var index = DenseArray.Count;
} DenseArray.Append(entity);
else if (entity.ID >= SparseArray.Count)
{
EntityIDToStorageIndex[entity] = Components.Count;
EntityIDs.Append(entity);
Components.Append(component);
return false;
}
}
// Returns true if the entity had this component.
public bool Remove(in Entity entity)
{
if (EntityIDToStorageIndex.TryGetValue(entity, out int index))
{
var lastElementIndex = Components.Count - 1;
var lastEntity = EntityIDs[lastElementIndex];
// move a component into the hole to maintain contiguous memory
Components.Delete(index);
EntityIDs.Delete(index);
EntityIDToStorageIndex.Remove(entity);
// update the index if it changed
if (lastElementIndex != index)
{ {
EntityIDToStorageIndex[lastEntity] = index; var oldCount = SparseArray.Count;
SparseArray.ResizeTo(entity.ID + 1);
for (var i = oldCount; i < SparseArray.Capacity; i += 1)
{
SparseArray.Append(Entity.Null.ID); // sentinel value
}
} }
SparseArray[entity.ID] = index;
if (entity.ID >= ElementArrayCapacity)
{
ElementArrayCapacity = entity.ID + 1;
ElementArray = (nint) NativeMemory.Realloc((void*) ElementArray, (nuint) (ElementArrayCapacity * ElementSize));
}
}
Unsafe.Write((void*) (ElementArray + ElementSize * SparseArray[entity.ID]), component);
return !newEntity;
}
public bool Has(Entity entity)
{
return entity.ID < SparseArray.Count && SparseArray[entity.ID] != Entity.Null.ID;
}
public unsafe bool Remove(Entity entity)
{
if (Has(entity))
{
var denseIndex = SparseArray[entity.ID];
var lastItem = DenseArray[DenseArray.Count - 1];
DenseArray[denseIndex] = lastItem;
SparseArray[lastItem.ID] = denseIndex;
SparseArray[entity.ID] = Entity.Null.ID; // sentinel value
if (denseIndex != DenseArray.Count - 1)
{
NativeMemory.Copy((void*) (ElementArray + ElementSize * (DenseArray.Count - 1)), (void*) (ElementArray + ElementSize * denseIndex), (nuint) ElementSize);
}
DenseArray.RemoveLastElement();
return true; return true;
} }
@ -91,46 +108,47 @@ internal class ComponentStorage : IDisposable
public void Clear() public void Clear()
{ {
Components.Clear(); DenseArray.Clear();
EntityIDs.Clear(); for (var i = 0; i < SparseArray.Capacity; i += 1)
EntityIDToStorageIndex.Clear(); {
SparseArray[i] = Entity.Null.ID;
}
} }
public Entity FirstEntity() public Entity FirstEntity()
{ {
#if DEBUG #if DEBUG
if (EntityIDs.Count == 0) if (DenseArray.Count == 0)
{ {
throw new IndexOutOfRangeException("Component storage is empty!"); throw new IndexOutOfRangeException("Component storage is empty!");
} }
#endif #endif
return EntityIDs[0]; return DenseArray[0];
} }
#if DEBUG #if DEBUG
internal IEnumerable<Entity> Debug_GetEntities() internal Span<Entity> Debug_GetEntities()
{ {
return EntityIDToStorageIndex.Keys; return DenseArray.ToSpan();
} }
#endif #endif
protected virtual void Dispose(bool disposing) protected unsafe virtual void Dispose(bool disposing)
{ {
if (!IsDisposed) if (!IsDisposed)
{ {
Components.Dispose(); if (disposing)
EntityIDs.Dispose(); {
DenseArray.Dispose();
SparseArray.Dispose();
}
NativeMemory.Free((void*) ElementArray);
IsDisposed = true; IsDisposed = true;
} }
} }
// ~ComponentStorage()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose() public void Dispose()
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method

View File

@ -11,7 +11,7 @@ public abstract class DebugSystem : System
protected DebugSystem(World world) : base(world) { } protected DebugSystem(World world) : base(world) { }
protected World.ComponentTypeEnumerator Debug_GetAllComponentTypes(Entity entity) => World.Debug_GetAllComponentTypes(entity); protected World.ComponentTypeEnumerator Debug_GetAllComponentTypes(Entity entity) => World.Debug_GetAllComponentTypes(entity);
protected IEnumerable<Entity> Debug_GetEntities(Type componentType) => World.Debug_GetEntities(componentType); protected Span<Entity> Debug_GetEntities(Type componentType) => World.Debug_GetEntities(componentType);
protected IEnumerable<Type> Debug_SearchComponentType(string typeString) => World.Debug_SearchComponentType(typeString); protected IEnumerable<Type> Debug_SearchComponentType(string typeString) => World.Debug_SearchComponentType(typeString);
} }
#endif #endif

View File

@ -1,3 +1,6 @@
namespace MoonTools.ECS; namespace MoonTools.ECS;
public readonly record struct Entity(uint ID); public readonly record struct Entity(int ID)
{
public static readonly Entity Null = new Entity(int.MaxValue);
}

View File

@ -5,12 +5,12 @@ namespace MoonTools.ECS;
internal class IdAssigner : IDisposable internal class IdAssigner : IDisposable
{ {
uint Next; int Next = 0;
NativeArray<uint> AvailableIds = new NativeArray<uint>(); NativeArray<int> AvailableIds = new NativeArray<int>();
private bool IsDisposed; private bool IsDisposed;
public uint Assign() public int Assign()
{ {
if (AvailableIds.TryPop(out var id)) if (AvailableIds.TryPop(out var id))
{ {
@ -22,7 +22,7 @@ internal class IdAssigner : IDisposable
return id; return id;
} }
public void Unassign(uint id) public void Unassign(int id)
{ {
AvailableIds.Append(id); AvailableIds.Append(id);
} }
@ -46,13 +46,6 @@ internal class IdAssigner : IDisposable
} }
} }
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~IdAssigner()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose() public void Dispose()
{ {
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method

View File

@ -10,6 +10,7 @@ internal class RelationStorage
{ {
internal NativeArray Relations; internal NativeArray Relations;
internal NativeArray RelationDatas; internal NativeArray RelationDatas;
internal int ElementSize;
internal Dictionary<(Entity, Entity), int> Indices = new Dictionary<(Entity, Entity), int>(16); internal Dictionary<(Entity, Entity), int> Indices = new Dictionary<(Entity, Entity), int>(16);
internal Dictionary<Entity, IndexableSet<Entity>> OutRelationSets = new Dictionary<Entity, IndexableSet<Entity>>(16); internal Dictionary<Entity, IndexableSet<Entity>> OutRelationSets = new Dictionary<Entity, IndexableSet<Entity>>(16);
internal Dictionary<Entity, IndexableSet<Entity>> InRelationSets = new Dictionary<Entity, IndexableSet<Entity>>(16); internal Dictionary<Entity, IndexableSet<Entity>> InRelationSets = new Dictionary<Entity, IndexableSet<Entity>>(16);
@ -19,6 +20,7 @@ internal class RelationStorage
public RelationStorage(int relationDataSize) public RelationStorage(int relationDataSize)
{ {
ElementSize = relationDataSize;
Relations = new NativeArray(Unsafe.SizeOf<(Entity, Entity)>()); Relations = new NativeArray(Unsafe.SizeOf<(Entity, Entity)>());
RelationDatas = new NativeArray(relationDataSize); RelationDatas = new NativeArray(relationDataSize);
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using MoonTools.ECS.Collections; using MoonTools.ECS.Collections;
namespace MoonTools.ECS; namespace MoonTools.ECS;
@ -8,12 +9,12 @@ namespace MoonTools.ECS;
// TODO: we should implement a NativeDictionary that can be memcopied // TODO: we should implement a NativeDictionary that can be memcopied
public class Snapshot : IDisposable public class Snapshot : IDisposable
{ {
private Dictionary<TypeId, ComponentSnapshot> ComponentSnapshots = new Dictionary<TypeId, ComponentSnapshot>(); private List<ComponentSnapshot> ComponentSnapshots = new List<ComponentSnapshot>();
// FIXME: we could just have a filter ID
private Dictionary<FilterSignature, List<Entity>> Filters = new Dictionary<FilterSignature, List<Entity>>(); private Dictionary<FilterSignature, List<Entity>> Filters = new Dictionary<FilterSignature, List<Entity>>();
private Dictionary<TypeId, RelationSnapshot> RelationSnapshots = private List<RelationSnapshot> RelationSnapshots = new List<RelationSnapshot>();
new Dictionary<TypeId, RelationSnapshot>();
private Dictionary<Entity, IndexableSet<TypeId>> EntityRelationIndex = private Dictionary<Entity, IndexableSet<TypeId>> EntityRelationIndex =
new Dictionary<Entity, IndexableSet<TypeId>>(); new Dictionary<Entity, IndexableSet<TypeId>>();
@ -21,7 +22,7 @@ public class Snapshot : IDisposable
private Dictionary<Entity, IndexableSet<TypeId>> EntityComponentIndex = private Dictionary<Entity, IndexableSet<TypeId>> EntityComponentIndex =
new Dictionary<Entity, IndexableSet<TypeId>>(); new Dictionary<Entity, IndexableSet<TypeId>>();
private Dictionary<Entity, string> EntityTags = new Dictionary<Entity, string>(); private List<string> EntityTags = new List<string>();
private IdAssigner EntityIdAssigner = new IdAssigner(); private IdAssigner EntityIdAssigner = new IdAssigner();
@ -48,30 +49,29 @@ public class Snapshot : IDisposable
// clear all component storages in case any were created after snapshot // clear all component storages in case any were created after snapshot
// FIXME: this can be eliminated via component discovery // FIXME: this can be eliminated via component discovery
foreach (var (typeId, componentStorage) in world.ComponentIndex) foreach (var componentStorage in world.ComponentIndex)
{ {
componentStorage.Clear(); componentStorage.Clear();
} }
// clear all relation storages in case any were created after snapshot // clear all relation storages in case any were created after snapshot
// FIXME: this can be eliminated via component discovery // FIXME: this can be eliminated via component discovery
foreach (var (typeId, relationStorage) in world.RelationIndex) foreach (var relationStorage in world.RelationIndex)
{ {
relationStorage.Clear(); relationStorage.Clear();
} }
// restore components for (var i = 0; i < world.ComponentIndex.Count; i += 1)
foreach (var (typeId, componentSnapshot) in ComponentSnapshots)
{ {
var componentStorage = world.ComponentIndex[typeId]; var componentStorage = world.ComponentIndex[i];
componentSnapshot.Restore(componentStorage); ComponentSnapshots[i].Restore(componentStorage);
} }
// restore relation state // restore relation state
foreach (var (typeId, relationSnapshot) in RelationSnapshots) for (var i = 0; i < RelationSnapshots.Count; i += 1)
{ {
var relationStorage = world.RelationIndex[typeId]; var relationStorage = world.RelationIndex[i];
relationSnapshot.Restore(relationStorage); RelationSnapshots[i].Restore(relationStorage);
} }
// restore entity relation index state // restore entity relation index state
@ -107,9 +107,10 @@ public class Snapshot : IDisposable
} }
// restore entity tags // restore entity tags
foreach (var (id, s) in EntityTags) world.EntityTags.Clear();
foreach (var s in EntityTags)
{ {
world.EntityTags[id] = s; world.EntityTags.Add(s);
} }
} }
@ -125,15 +126,25 @@ public class Snapshot : IDisposable
} }
// copy components // copy components
foreach (var (typeId, componentStorage) in world.ComponentIndex) for (var i = ComponentSnapshots.Count; i < world.ComponentIndex.Count; i += 1)
{ {
TakeComponentSnapshot(typeId, componentStorage); ComponentSnapshots.Add(new ComponentSnapshot(world.ComponentIndex[i].ElementSize));
}
for (var i = 0; i < world.ComponentIndex.Count; i += 1)
{
ComponentSnapshots[i].Take(world.ComponentIndex[i]);
} }
// copy relations // copy relations
foreach (var (typeId, relationStorage) in world.RelationIndex) for (var i = RelationSnapshots.Count; i < world.RelationIndex.Count; i += 1)
{ {
TakeRelationSnapshot(typeId, relationStorage); RelationSnapshots.Add(new RelationSnapshot(world.RelationIndex[i].ElementSize));
}
for (var i = 0; i < world.RelationIndex.Count; i += 1)
{
RelationSnapshots[i].Take(world.RelationIndex[i]);
} }
// copy entity relation index // copy entity relation index
@ -171,9 +182,10 @@ public class Snapshot : IDisposable
} }
// copy entity tags // copy entity tags
foreach (var (id, s) in world.EntityTags) EntityTags.Clear();
foreach (var s in world.EntityTags)
{ {
EntityTags[id] = s; EntityTags.Add(s);
} }
} }
@ -193,70 +205,53 @@ public class Snapshot : IDisposable
} }
} }
private void TakeComponentSnapshot(TypeId typeId, ComponentStorage componentStorage)
{
if (!ComponentSnapshots.TryGetValue(typeId, out var componentSnapshot))
{
componentSnapshot = new ComponentSnapshot(componentStorage.Components.ElementSize);
ComponentSnapshots.Add(typeId, componentSnapshot);
}
componentSnapshot.Take(componentStorage);
}
private void TakeRelationSnapshot(TypeId typeId, RelationStorage relationStorage)
{
if (!RelationSnapshots.TryGetValue(typeId, out var snapshot))
{
snapshot = new RelationSnapshot(relationStorage.RelationDatas.ElementSize);
RelationSnapshots.Add(typeId, snapshot);
}
snapshot.Take(relationStorage);
}
private class ComponentSnapshot : IDisposable private class ComponentSnapshot : IDisposable
{ {
private readonly NativeArray Components; private readonly NativeArray<Entity> DenseArray;
private readonly NativeArray<Entity> EntityIDs; private readonly NativeArray<int> SparseArray;
private nint ElementArray;
private int ElementArrayCapacity;
private bool IsDisposed; private bool IsDisposed;
public ComponentSnapshot(int elementSize) public unsafe ComponentSnapshot(int elementSize)
{ {
Components = new NativeArray(elementSize); ElementArray = (nint) NativeMemory.Alloc((nuint) (16 * elementSize));
EntityIDs = new NativeArray<Entity>(); DenseArray = new NativeArray<Entity>(elementSize);
SparseArray = new NativeArray<int>(elementSize);
} }
public void Take(ComponentStorage componentStorage) public unsafe void Take(ComponentStorage componentStorage)
{ {
componentStorage.Components.CopyAllTo(Components); componentStorage.DenseArray.CopyTo(DenseArray);
componentStorage.EntityIDs.CopyTo(EntityIDs); componentStorage.SparseArray.CopyTo(SparseArray);
} if (componentStorage.ElementArrayCapacity > ElementArrayCapacity)
public void Restore(ComponentStorage componentStorage)
{
Components.CopyAllTo(componentStorage.Components);
EntityIDs.CopyTo(componentStorage.EntityIDs);
componentStorage.EntityIDToStorageIndex.Clear();
for (int i = 0; i < EntityIDs.Count; i += 1)
{ {
var entityID = EntityIDs[i]; ElementArrayCapacity = componentStorage.ElementArrayCapacity;
componentStorage.EntityIDToStorageIndex[entityID] = i; NativeMemory.Realloc((void*) ElementArray, (nuint) (componentStorage.ElementSize * ElementArrayCapacity));
} }
NativeMemory.Copy((void*) componentStorage.ElementArray, (void*) ElementArray, (nuint) (ElementArrayCapacity * componentStorage.ElementSize));
} }
protected virtual void Dispose(bool disposing) public unsafe void Restore(ComponentStorage componentStorage)
{
DenseArray.CopyTo(componentStorage.DenseArray);
SparseArray.CopyTo(componentStorage.SparseArray);
NativeMemory.Copy((void*) ElementArray, (void*) componentStorage.ElementArray, (nuint) (ElementArrayCapacity * componentStorage.ElementSize));
}
protected unsafe virtual void Dispose(bool disposing)
{ {
if (!IsDisposed) if (!IsDisposed)
{ {
if (disposing) if (disposing)
{ {
Components.Dispose(); DenseArray.Dispose();
EntityIDs.Dispose(); SparseArray.Dispose();
} }
NativeMemory.Free((void*) ElementArray);
IsDisposed = true; IsDisposed = true;
} }
} }
@ -348,12 +343,12 @@ public class Snapshot : IDisposable
{ {
if (disposing) if (disposing)
{ {
foreach (var componentSnapshot in ComponentSnapshots.Values) foreach (var componentSnapshot in ComponentSnapshots)
{ {
componentSnapshot.Dispose(); componentSnapshot.Dispose();
} }
foreach (var relationSnapshot in RelationSnapshots.Values) foreach (var relationSnapshot in RelationSnapshots)
{ {
relationSnapshot.Dispose(); relationSnapshot.Dispose();
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Runtime.CompilerServices;
namespace MoonTools.ECS; namespace MoonTools.ECS;
@ -8,4 +9,74 @@ public readonly record struct TypeId(uint Value) : IComparable<TypeId>
{ {
return Value.CompareTo(other.Value); return Value.CompareTo(other.Value);
} }
public static implicit operator int(TypeId typeId)
{
return (int) typeId.Value;
}
}
public class ComponentTypeIdAssigner
{
protected static ushort Counter;
}
public class ComponentTypeIdAssigner<T> : ComponentTypeIdAssigner
{
public static readonly ushort Id;
public static readonly int Size;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static ComponentTypeIdAssigner()
{
Id = Counter++;
Size = Unsafe.SizeOf<T>();
World.ComponentTypeElementSizes.Add(Size);
#if DEBUG
World.ComponentTypeToId[typeof(T)] = new TypeId(Id);
World.ComponentTypeIdToType.Add(typeof(T));
#endif
}
}
public class RelationTypeIdAssigner
{
protected static ushort Counter;
}
public class RelationTypeIdAssigner<T> : RelationTypeIdAssigner
{
public static readonly ushort Id;
public static readonly int Size;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static RelationTypeIdAssigner()
{
Id = Counter++;
Size = Unsafe.SizeOf<T>();
World.RelationTypeElementSizes.Add(Size);
}
}
public class MessageTypeIdAssigner
{
protected static ushort Counter;
}
public class MessageTypeIdAssigner<T> : MessageTypeIdAssigner
{
public static readonly ushort Id;
public static readonly int Size;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static MessageTypeIdAssigner()
{
Id = Counter++;
Size = Unsafe.SizeOf<T>();
World.MessageTypeElementSizes.Add(Size);
}
} }

View File

@ -7,85 +7,63 @@ namespace MoonTools.ECS;
public class World : IDisposable public class World : IDisposable
{ {
// Get TypeId from a Type
private readonly Dictionary<Type, TypeId> TypeToId = new Dictionary<Type, TypeId>();
#if DEBUG #if DEBUG
private Dictionary<TypeId, Type> IdToType = new Dictionary<TypeId, Type>(); // TODO: is there a smarter way to do this?
internal static Dictionary<Type, TypeId> ComponentTypeToId = new Dictionary<Type, TypeId>();
internal static List<Type> ComponentTypeIdToType = new List<Type>();
#endif #endif
// Get element size from a TypeId internal static List<int> ComponentTypeElementSizes = new List<int>();
private readonly Dictionary<TypeId, int> ElementSizes = new Dictionary<TypeId, int>(); internal static List<int> RelationTypeElementSizes = new List<int>();
internal static List<int> MessageTypeElementSizes = new List<int>();
// Filters // Filters
internal readonly Dictionary<FilterSignature, Filter> FilterIndex = new Dictionary<FilterSignature, Filter>(); internal readonly Dictionary<FilterSignature, Filter> FilterIndex = new Dictionary<FilterSignature, Filter>();
private readonly Dictionary<TypeId, List<Filter>> TypeToFilter = new Dictionary<TypeId, List<Filter>>(); private readonly List<List<Filter>> ComponentTypeToFilter = new List<List<Filter>>();
// TODO: can we make the tag an native array of chars at some point? // TODO: can we make the tag an native array of chars at some point?
internal Dictionary<Entity, string> EntityTags = new Dictionary<Entity, string>(); internal List<string> EntityTags = new List<string>();
// Relation Storages // Relation Storages
internal Dictionary<TypeId, RelationStorage> RelationIndex = new Dictionary<TypeId, RelationStorage>(); internal List<RelationStorage> RelationIndex = new List<RelationStorage>();
internal Dictionary<Entity, IndexableSet<TypeId>> EntityRelationIndex = new Dictionary<Entity, IndexableSet<TypeId>>(); internal Dictionary<Entity, IndexableSet<TypeId>> EntityRelationIndex = new Dictionary<Entity, IndexableSet<TypeId>>();
// Message Storages // Message Storages
private Dictionary<TypeId, MessageStorage> MessageIndex = new Dictionary<TypeId, MessageStorage>(); private List<MessageStorage> MessageIndex = new List<MessageStorage>();
public FilterBuilder FilterBuilder => new FilterBuilder(this); public FilterBuilder FilterBuilder => new FilterBuilder(this);
internal readonly Dictionary<TypeId, ComponentStorage> ComponentIndex = new Dictionary<TypeId, ComponentStorage>(); internal readonly List<ComponentStorage> ComponentIndex = new List<ComponentStorage>();
internal Dictionary<Entity, IndexableSet<TypeId>> EntityComponentIndex = new Dictionary<Entity, IndexableSet<TypeId>>(); internal Dictionary<Entity, IndexableSet<TypeId>> EntityComponentIndex = new Dictionary<Entity, IndexableSet<TypeId>>();
internal IdAssigner EntityIdAssigner = new IdAssigner(); internal IdAssigner EntityIdAssigner = new IdAssigner();
private IdAssigner TypeIdAssigner = new IdAssigner();
private bool IsDisposed; private bool IsDisposed;
internal TypeId GetTypeId<T>() where T : unmanaged
{
if (TypeToId.ContainsKey(typeof(T)))
{
return TypeToId[typeof(T)];
}
var typeId = new TypeId(TypeIdAssigner.Assign());
TypeToId.Add(typeof(T), typeId);
ElementSizes.Add(typeId, Unsafe.SizeOf<T>());
#if DEBUG
IdToType.Add(typeId, typeof(T));
#endif
return typeId;
}
internal TypeId GetComponentTypeId<T>() where T : unmanaged internal TypeId GetComponentTypeId<T>() where T : unmanaged
{ {
var typeId = GetTypeId<T>(); var typeId = new TypeId(ComponentTypeIdAssigner<T>.Id);
if (ComponentIndex.TryGetValue(typeId, out var componentStorage)) if (typeId < ComponentIndex.Count)
{ {
return typeId; return typeId;
} }
componentStorage = new ComponentStorage(typeId, ElementSizes[typeId]); // add missing storages, it's possible for there to be multiples in multi-world scenarios
ComponentIndex.Add(typeId, componentStorage); for (var i = ComponentIndex.Count; i <= typeId; i += 1)
TypeToFilter.Add(typeId, new List<Filter>()); {
var componentStorage = new ComponentStorage(ComponentTypeElementSizes[i]);
ComponentIndex.Add(componentStorage);
ComponentTypeToFilter.Add(new List<Filter>());
}
return typeId; return typeId;
} }
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private ComponentStorage GetComponentStorage<T>() where T : unmanaged private ComponentStorage GetComponentStorage<T>() where T : unmanaged
{ {
var typeId = GetTypeId<T>(); var typeId = GetComponentTypeId<T>();
if (ComponentIndex.TryGetValue(typeId, out var componentStorage)) return ComponentIndex[typeId];
{
return componentStorage;
}
componentStorage = new ComponentStorage(typeId, ElementSizes[typeId]);
ComponentIndex.Add(typeId, componentStorage);
TypeToFilter.Add(typeId, new List<Filter>());
return componentStorage;
} }
// FILTERS // FILTERS
@ -98,12 +76,12 @@ public class World : IDisposable
foreach (var typeId in signature.Included) foreach (var typeId in signature.Included)
{ {
TypeToFilter[typeId].Add(filter); ComponentTypeToFilter[(int) typeId.Value].Add(filter);
} }
foreach (var typeId in signature.Excluded) foreach (var typeId in signature.Excluded)
{ {
TypeToFilter[typeId].Add(filter); ComponentTypeToFilter[(int) typeId.Value].Add(filter);
} }
FilterIndex.Add(signature, filter); FilterIndex.Add(signature, filter);
@ -122,21 +100,20 @@ public class World : IDisposable
{ {
EntityRelationIndex.Add(entity, new IndexableSet<TypeId>()); EntityRelationIndex.Add(entity, new IndexableSet<TypeId>());
EntityComponentIndex.Add(entity, new IndexableSet<TypeId>()); EntityComponentIndex.Add(entity, new IndexableSet<TypeId>());
EntityTags.Add(tag);
} }
EntityTags[entity] = tag;
return entity; return entity;
} }
public void Tag(Entity entity, string tag) public void Tag(Entity entity, string tag)
{ {
EntityTags[entity] = tag; EntityTags[(int) entity.ID] = tag;
} }
public string GetTag(Entity entity) public string GetTag(Entity entity)
{ {
return EntityTags[entity]; return EntityTags[(int) entity.ID];
} }
public void Destroy(in Entity entity) public void Destroy(in Entity entity)
@ -147,7 +124,7 @@ public class World : IDisposable
var componentStorage = ComponentIndex[componentTypeIndex]; var componentStorage = ComponentIndex[componentTypeIndex];
componentStorage.Remove(entity); componentStorage.Remove(entity);
foreach (var filter in TypeToFilter[componentTypeIndex]) foreach (var filter in ComponentTypeToFilter[componentTypeIndex])
{ {
filter.RemoveEntity(entity); filter.RemoveEntity(entity);
} }
@ -171,13 +148,12 @@ public class World : IDisposable
public bool Has<T>(in Entity entity) where T : unmanaged public bool Has<T>(in Entity entity) where T : unmanaged
{ {
var storage = GetComponentStorage<T>(); return GetComponentStorage<T>().Has(entity);
return storage.Has(entity);
} }
internal bool Has(in Entity entity, in TypeId typeId) internal bool Has(in Entity entity, in TypeId typeId)
{ {
return EntityComponentIndex[entity].Contains(typeId); return ComponentIndex[(int) typeId.Value].Has(entity);
} }
public bool Some<T>() where T : unmanaged public bool Some<T>() where T : unmanaged
@ -207,12 +183,13 @@ public class World : IDisposable
public void Set<T>(in Entity entity, in T component) where T : unmanaged public void Set<T>(in Entity entity, in T component) where T : unmanaged
{ {
var componentStorage = GetComponentStorage<T>(); var componentStorage = GetComponentStorage<T>();
var typeId = new TypeId(ComponentTypeIdAssigner<T>.Id);
if (!componentStorage.Set(entity, component)) if (!componentStorage.Set(entity, component))
{ {
EntityComponentIndex[entity].Add(componentStorage.TypeId); EntityComponentIndex[entity].Add(typeId);
foreach (var filter in TypeToFilter[componentStorage.TypeId]) foreach (var filter in ComponentTypeToFilter[typeId])
{ {
filter.Check(entity); filter.Check(entity);
} }
@ -222,12 +199,13 @@ public class World : IDisposable
public void Remove<T>(in Entity entity) where T : unmanaged public void Remove<T>(in Entity entity) where T : unmanaged
{ {
var componentStorage = GetComponentStorage<T>(); var componentStorage = GetComponentStorage<T>();
var typeId = new TypeId(ComponentTypeIdAssigner<T>.Id);
if (componentStorage.Remove(entity)) if (componentStorage.Remove(entity))
{ {
EntityComponentIndex[entity].Remove(componentStorage.TypeId); EntityComponentIndex[entity].Remove(typeId);
foreach (var filter in TypeToFilter[componentStorage.TypeId]) foreach (var filter in ComponentTypeToFilter[typeId])
{ {
filter.Check(entity); filter.Check(entity);
} }
@ -236,31 +214,29 @@ public class World : IDisposable
// RELATIONS // RELATIONS
private RelationStorage RegisterRelationType(TypeId typeId)
{
var relationStorage = new RelationStorage(ElementSizes[typeId]);
RelationIndex.Add(typeId, relationStorage);
return relationStorage;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] [MethodImpl(MethodImplOptions.AggressiveInlining)]
private RelationStorage GetRelationStorage<T>() where T : unmanaged private RelationStorage GetRelationStorage<T>() where T : unmanaged
{ {
var typeId = GetTypeId<T>(); var typeId = new TypeId(RelationTypeIdAssigner<T>.Id);
if (RelationIndex.TryGetValue(typeId, out var relationStorage)) if (typeId.Value < RelationIndex.Count)
{ {
return relationStorage; return RelationIndex[typeId];
} }
return RegisterRelationType(typeId); for (var i = RelationIndex.Count; i <= typeId; i += 1)
{
RelationIndex.Add(new RelationStorage(RelationTypeElementSizes[i]));
}
return RelationIndex[typeId];
} }
public void Relate<T>(in Entity entityA, in Entity entityB, in T relation) where T : unmanaged public void Relate<T>(in Entity entityA, in Entity entityB, in T relation) where T : unmanaged
{ {
var relationStorage = GetRelationStorage<T>(); var relationStorage = GetRelationStorage<T>();
relationStorage.Set(entityA, entityB, relation); relationStorage.Set(entityA, entityB, relation);
EntityRelationIndex[entityA].Add(TypeToId[typeof(T)]); EntityRelationIndex[entityA].Add(new TypeId(RelationTypeIdAssigner<T>.Id));
EntityRelationIndex[entityB].Add(TypeToId[typeof(T)]); EntityRelationIndex[entityB].Add(new TypeId(RelationTypeIdAssigner<T>.Id));
} }
public void Unrelate<T>(in Entity entityA, in Entity entityB) where T : unmanaged public void Unrelate<T>(in Entity entityA, in Entity entityB) where T : unmanaged
@ -355,52 +331,52 @@ public class World : IDisposable
// MESSAGES // MESSAGES
private TypeId GetMessageTypeId<T>() where T : unmanaged private MessageStorage GetMessageStorage<T>() where T : unmanaged
{ {
var typeId = GetTypeId<T>(); var typeId = new TypeId(MessageTypeIdAssigner<T>.Id);
if (!MessageIndex.ContainsKey(typeId)) if (typeId < MessageIndex.Count)
{ {
MessageIndex.Add(typeId, new MessageStorage(Unsafe.SizeOf<T>())); return MessageIndex[typeId];
} }
return typeId; for (var i = MessageIndex.Count; i <= typeId; i += 1)
{
MessageIndex.Add(new MessageStorage(MessageTypeElementSizes[i]));
}
return MessageIndex[typeId];
} }
public void Send<T>(in T message) where T : unmanaged public void Send<T>(in T message) where T : unmanaged
{ {
var typeId = GetMessageTypeId<T>(); GetMessageStorage<T>().Add(message);
MessageIndex[typeId].Add(message);
} }
public bool SomeMessage<T>() where T : unmanaged public bool SomeMessage<T>() where T : unmanaged
{ {
var typeId = GetMessageTypeId<T>(); return GetMessageStorage<T>().Some();
return MessageIndex[typeId].Some();
} }
public ReadOnlySpan<T> ReadMessages<T>() where T : unmanaged public ReadOnlySpan<T> ReadMessages<T>() where T : unmanaged
{ {
var typeId = GetMessageTypeId<T>(); return GetMessageStorage<T>().All<T>();
return MessageIndex[typeId].All<T>();
} }
public T ReadMessage<T>() where T : unmanaged public T ReadMessage<T>() where T : unmanaged
{ {
var typeId = GetMessageTypeId<T>(); return GetMessageStorage<T>().First<T>();
return MessageIndex[typeId].First<T>();
} }
public void ClearMessages<T>() where T : unmanaged public void ClearMessages<T>() where T : unmanaged
{ {
var typeId = GetMessageTypeId<T>(); GetMessageStorage<T>().Clear();
MessageIndex[typeId].Clear();
} }
// TODO: temporary component storage? // TODO: temporary component storage?
public void FinishUpdate() public void FinishUpdate()
{ {
foreach (var (_, messageStorage) in MessageIndex) foreach (var messageStorage in MessageIndex)
{ {
messageStorage.Clear(); messageStorage.Clear();
} }
@ -415,15 +391,15 @@ public class World : IDisposable
return new ComponentTypeEnumerator(this, EntityComponentIndex[entity]); return new ComponentTypeEnumerator(this, EntityComponentIndex[entity]);
} }
public IEnumerable<Entity> Debug_GetEntities(Type componentType) public Span<Entity> Debug_GetEntities(Type componentType)
{ {
var storage = ComponentIndex[TypeToId[componentType]]; var storage = ComponentIndex[ComponentTypeToId[componentType]];
return storage.Debug_GetEntities(); return storage.Debug_GetEntities();
} }
public IEnumerable<Type> Debug_SearchComponentType(string typeString) public IEnumerable<Type> Debug_SearchComponentType(string typeString)
{ {
foreach (var type in TypeToId.Keys) foreach (var type in ComponentTypeToId.Keys)
{ {
if (type.ToString().ToLower().Contains(typeString.ToLower())) if (type.ToString().ToLower().Contains(typeString.ToLower()))
{ {
@ -456,7 +432,7 @@ public class World : IDisposable
return ComponentIndex < Types.Count; return ComponentIndex < Types.Count;
} }
public Type Current => World.IdToType[Types[ComponentIndex]]; public Type Current => ComponentTypeIdToType[Types[ComponentIndex]];
} }
#endif #endif
@ -466,17 +442,17 @@ public class World : IDisposable
{ {
if (disposing) if (disposing)
{ {
foreach (var componentStorage in ComponentIndex.Values) foreach (var componentStorage in ComponentIndex)
{ {
componentStorage.Dispose(); componentStorage.Dispose();
} }
foreach (var relationStorage in RelationIndex.Values) foreach (var relationStorage in RelationIndex)
{ {
relationStorage.Dispose(); relationStorage.Dispose();
} }
foreach (var messageStorage in MessageIndex.Values) foreach (var messageStorage in MessageIndex)
{ {
messageStorage.Dispose(); messageStorage.Dispose();
} }
@ -497,7 +473,6 @@ public class World : IDisposable
} }
EntityIdAssigner.Dispose(); EntityIdAssigner.Dispose();
TypeIdAssigner.Dispose();
} }
IsDisposed = true; IsDisposed = true;