Refactor project management and enhance architecture

Added a new static class `AssetsPath` for asset management.
Added a new icon file (`icon-256.ico`) for UI representation.
Added new package references to enhance functionality.
Added internals visibility attributes for better testing.
Added a new `EngineEditorViewModel` class for MVVM support.
Added a new `GameObject` class for component management.
Added a new `BitSet` class for efficient bit manipulation.
Added various utility classes to support the new entity system.

Changed the `ID` property in `ProjectInfo` to internal.
Changed the `AddProjectAsync` method to return the created `ProjectInfo`.
Changed the connection string retrieval method to use the new `Command` constant.
Changed the `DataPath` class to use `readonly` fields for folder paths.
Changed the `ActivationHandler` class to use new `DataPath` constants.
Changed the `OpenProjectPage` layout and interaction for better UI.

Updated the target framework to a newer version for compatibility.
Updated the `ProjectService` to use new constants from `DataPath`.
Updated the `World` class to improve entity management.

Refactored the `ProjectRepository` class to encapsulate SQL commands.
Refactored the `Transform` class to use properties for better encapsulation.
This commit is contained in:
2025-04-05 16:07:53 +09:00
parent 62fe30ff2b
commit 7cd881b7d4
44 changed files with 1672 additions and 247 deletions

View File

@@ -0,0 +1,5 @@
namespace Ghost.Entities;
public struct Archetype
{
}

View File

@@ -1,4 +1,7 @@
global using EntityID = System.UInt32;
global using GenerationID = System.UInt16;
global using WorldID = System.UInt16;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Ghost.Engine")]

213
Ghost.Entities/Chunk.cs Normal file
View File

@@ -0,0 +1,213 @@
using Misaki.HighPerformance.Unsafe.Collections;
using Misaki.HighPerformance.Unsafe.Helpers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Ghost.Entities;
internal struct Chunks : IDisposable
{
private UnsafeArray<Chunk> _chunks;
private int _count;
private int _capacity;
public readonly int Count => _count;
public readonly int Capacity => _capacity;
public ref Chunk this[int index] => ref _chunks[index];
public Chunks(int capacity)
{
_chunks = new(capacity, Allocator.Persistent);
_count = 0;
_capacity = capacity;
}
public void Add(Chunk chunk)
{
_chunks[_count] = chunk;
_count++;
}
public void EnsureCapacity(int newCapacity)
{
if (newCapacity <= _capacity)
{
return;
}
_chunks.Resize(newCapacity);
}
public void TrimExcess()
{
if (_count == _capacity)
{
return;
}
_chunks.Resize(_count);
}
public void Clear()
{
for (var i = 0; i < _count; i++)
{
_chunks[i].Clear();
}
_count = 0;
_capacity = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Span<Chunk> AsSpan()
{
return _chunks.AsSpan();
}
public void Dispose()
{
for (var i = 0; i < _count; i++)
{
_chunks[i].Dispose();
}
_chunks.Dispose();
_count = 0;
_capacity = 0;
}
}
internal struct Chunk : IDisposable
{
public UnsafeArray<Entity> entities;
public UnsafeArray<UnsafeArray<byte>> components;
// The component lookup array is used to quickly find the index of a component in the components array.
// Mapping component ID to component index in the components array.
private UnsafeArray<int> _componentLookup;
private int _count;
private readonly int _capacity;
private bool _isDisposed;
public readonly int Count => _count;
public readonly int Capacity => _capacity;
public Chunk(int capacity, Span<ComponentData> data) : this(capacity, data, Component.ToLookupArray(data, Allocator.Persistent))
{
}
public Chunk(int capacity, Span<ComponentData> data, UnsafeArray<int> lookup)
{
_count = 0;
_capacity = capacity;
entities = new(capacity, Allocator.Persistent);
components = new(data.Length, Allocator.Persistent);
_componentLookup = lookup;
for (var i = 0; i < data.Length; i++)
{
var component = data[i];
components[component.id] = new UnsafeArray<byte>(capacity * component.sizeInByte, Allocator.Persistent);
}
}
public int Add(Entity entity)
{
var index = _count;
entities[index] = entity;
_count++;
return index;
}
public unsafe bool Remove(int index)
{
if (index < 0 || index >= _count)
{
return false;
}
var lastIndex = _count--;
entities[index] = entities[lastIndex];
for (var i = 0; i < components.Count; i++)
{
var componentArray = UnsafeUtilities.ReadArrayElementUnsafe<UnsafeArray<byte>>(components.GetUnsafePtr(), i);
var componentSize = componentArray->Count / _capacity;
var removedComponent = UnsafeUtilities.ReadArrayElementUnsafe<byte>(componentArray->GetUnsafePtr(), index * componentSize);
var lastComponent = UnsafeUtilities.ReadArrayElementUnsafe<byte>(componentArray->GetUnsafePtr(), lastIndex * componentSize);
MemoryUtilities.MemCpy(removedComponent, lastComponent, (nuint)componentSize);
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private readonly int IndexOf<T>()
where T : unmanaged, IComponent
{
var id = Component<T>.data.id;
Debug.Assert(id != -1 && id < _componentLookup.Count, $"Index is out of bounds, component {typeof(T)} with id {id} does not exist in this chunk.");
return _componentLookup[id];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Has<T>()
where T : unmanaged, IComponent
{
var id = Component<T>.data.id;
return id < _componentLookup.Count && _componentLookup[id] != -1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly unsafe UnsafeArray<T> GetArrayOf<T>()
where T : unmanaged, IComponent
{
var index = IndexOf<T>();
var componentArray = components[index];
return UnsafeUtilities.CastArray<byte, T>(componentArray);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly unsafe ref T GetComponent<T>(int index)
where T : unmanaged, IComponent
{
var componentArray = GetArrayOf<T>();
return ref componentArray[index];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Entity GetEntity(int index)
{
return entities[index];
}
public void Clear()
{
_count = 0;
}
public void Dispose()
{
if (_isDisposed)
{
return;
}
entities.Dispose();
_componentLookup.Dispose();
for (var i = 0; i < components.Count; i++)
{
components[i].Dispose();
}
components.Dispose();
_isDisposed = true;
}
}

103
Ghost.Entities/Component.cs Normal file
View File

@@ -0,0 +1,103 @@
using Ghost.Entities.Helpers;
using Ghost.Entities.Registries;
using Misaki.HighPerformance.Unsafe.Collections;
using Misaki.HighPerformance.Unsafe.Helpers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Ghost.Entities;
public interface IComponent
{
}
[SkipLocalsInit]
internal readonly record struct ComponentData
{
public readonly int id;
public readonly int sizeInByte;
public ComponentData(int id, int sizeInByte)
{
this.id = id;
this.sizeInByte = sizeInByte;
}
}
internal static class Component
{
public static unsafe UnsafeArray<int> ToLookupArray(Span<ComponentData> datas, Allocator allocator)
{
var max = 0;
foreach (var data in datas)
{
var componentId = data.id;
if (componentId >= max)
{
max = componentId;
}
}
// Create lookup table where the component ID points to the component index.
var array = new UnsafeArray<int>(max + 1, allocator);
array.AsSpan().Fill(-1);
for (var index = 0; index < datas.Length; index++)
{
ref var type = ref datas[index];
var componentId = type.id;
array[componentId] = index;
}
return array;
}
public static int GetHashCode(Span<ComponentData> components)
{
// Search for the highest id to determine how much uints we need for the stack.
var highestId = 0;
foreach (ref var cmp in components)
{
if (cmp.id > highestId)
{
highestId = cmp.id;
}
}
// Allocate the stack and set bits to replicate a bitset
var length = BitSet.RequiredLength(highestId + 1);
Span<uint> stack = stackalloc uint[length];
var spanBitSet = new SpanBitSet(stack);
foreach (ref var type in components)
{
var x = type.id;
spanBitSet.SetBit(x);
}
return GetHashCode(stack);
}
public static int GetHashCode(Span<uint> span)
{
var hashCode = new HashCode();
hashCode.AddBytes(MemoryMarshal.AsBytes(span));
return hashCode.ToHashCode();
}
}
internal static class Component<T>
where T : unmanaged, IComponent
{
public static readonly ComponentData data;
public static readonly Signature signature;
static Component()
{
data = ComponentRegistry.GetOrAdd<T>();
signature = new Signature(data);
}
}

View File

@@ -1,5 +0,0 @@
namespace Ghost.Entities.Core;
public readonly struct EntityInfo
{
}

View File

@@ -1,141 +0,0 @@
using Ghost.Entities.Helpers;
using Misaki.HighPerformance.Unsafe.Collections;
namespace Ghost.Entities.Core;
public partial struct World
{
public static UnsafeArray<World> Worlds
{
get;
private set;
} = new(4, AllocationType.UnInitialized);
public static UnsafeQueue<WorldID> FreeIndices
{
get;
private set;
} = new(4, AllocationType.UnInitialized);
public static ushort Count
{
get;
private set;
}
public static World Create(int chunkSizeInBytes = 16384, int minimumAmountOfEntitiesPerChunk = 100, int archetypeCapacity = 2, int entityCapacity = 64)
{
lock (ThreadLocker.WorldLock)
{
var recycle = FreeIndices.TryDequeue(out var id);
var recycledId = recycle ? id : Count;
var world = new World(recycledId, chunkSizeInBytes, minimumAmountOfEntitiesPerChunk, archetypeCapacity, entityCapacity);
if (recycledId >= Worlds.Size)
{
var newCapacity = Worlds.Size * 2;
Worlds.ReAlloc(newCapacity);
}
Worlds[recycledId] = world;
Count++;
return world;
}
}
}
public partial struct World
{
/// <summary>
/// The unique <see cref="World"/> ID.
/// </summary>
public int Id
{
get;
}
/// <summary>
/// The amount of <see cref="Entity"/>s currently stored by this <see cref="World"/>.
/// </summary>
public int Size
{
get; internal set;
}
/// <summary>
/// The available <see cref="Entity"/> capacity of this <see cref="World"/>.
/// </summary>
public int Capacity
{
get; internal set;
}
///// <summary>
///// All <see cref="Archetype"/>s that exist in this <see cref="World"/>.
///// </summary>
//public Archetypes Archetypes
//{
// get;
//}
///// <summary>
///// Maps an <see cref="Entity"/> to its <see cref="EntityInfo"/> for quick lookup.
///// </summary>
//internal EntityInfoStorage EntityInfo
//{
// get;
//}
///// <summary>
///// Stores recycled <see cref="Entity"/> IDs and their last version.
///// </summary>
//internal PooledQueue<RecycledEntity> RecycledIds
//{
// get; set;
//}
///// <summary>
///// A cache to map <see cref="QueryDescription"/> to their <see cref="Core.Query"/>, to avoid allocs.
///// </summary>
//internal PooledDictionary<QueryDescription, Query> QueryCache
//{
// get; set;
//}
/// <summary>
/// The <see cref="Chunk"/> size of each <see cref="Archetype"/> in bytes.
/// <remarks>For the best cache optimisation use values that are divisible by 16Kb.</remarks>
/// </summary>
public int BaseChunkSize { get; private set; } = 16_384;
/// <summary>
/// The minimum number of <see cref="Arch.Core.Entity"/>'s that should fit into a <see cref="Chunk"/> within all <see cref="Archetype"/>s.
/// On the basis of this, the <see cref="Archetypes"/>s chunk size may increase.
/// </summary>
public int BaseChunkEntityCount { get; private set; } = 100;
private World(int id, int baseChunkSize, int baseChunkEntityCount, int archetypeCapacity, int entityCapacity)
{
Id = id;
// Mapping.
//GroupToArchetype = new PooledDictionary<int, Archetype>(archetypeCapacity);
// Entity stuff.
//Archetypes = new Archetypes(archetypeCapacity);
//EntityInfo = new EntityInfoStorage(baseChunkSize, entityCapacity);
//RecycledIds = new PooledQueue<RecycledEntity>(entityCapacity);
// Query.
//QueryCache = new PooledDictionary<QueryDescription, Query>(archetypeCapacity);
// Multithreading/Jobs.
//JobHandles = new PooledList<JobHandle>(Environment.ProcessorCount);
//JobsCache = new List<IJob>(Environment.ProcessorCount);
// Config
BaseChunkSize = baseChunkSize;
BaseChunkEntityCount = baseChunkEntityCount;
}
}

View File

@@ -1,6 +1,6 @@
using System.Runtime.CompilerServices;
namespace Ghost.Entities.Core;
namespace Ghost.Entities;
[SkipLocalsInit]
public struct Entity : IEquatable<Entity>, IComparable<Entity>
@@ -14,7 +14,7 @@ public struct Entity : IEquatable<Entity>, IComparable<Entity>
private const EntityID _INDEX_MASK = (1u << (int)_INDEX_BITS) - 1;
private const EntityID _ID_MASK = EntityID.MaxValue;
private uint _id;
private EntityID _id;
public readonly bool IsValid
{
@@ -31,13 +31,13 @@ public struct Entity : IEquatable<Entity>, IComparable<Entity>
public readonly GenerationID Generation
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (GenerationID)((_id >> (int)_INDEX_BITS) & _GENERATION_MASK);
get => (GenerationID)(_id >> (int)_INDEX_BITS & _GENERATION_MASK);
}
public readonly WorldID WorldIndex
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (WorldID)((_id >> (int)(_INDEX_BITS + _GENERATION_BITS)) & _WORLD_INDEX_MASK);
get => (WorldID)(_id >> (int)(_INDEX_BITS + _GENERATION_BITS) & _WORLD_INDEX_MASK);
}
public void IncrementGeneration()
@@ -48,12 +48,12 @@ public struct Entity : IEquatable<Entity>, IComparable<Entity>
throw new InvalidOperationException("Generation overflow");
}
_id = (_id & ~(_GENERATION_MASK << (int)_INDEX_BITS)) | (generation << (int)_INDEX_BITS);
_id = _id & ~(_GENERATION_MASK << (int)_INDEX_BITS) | generation << (int)_INDEX_BITS;
}
internal Entity(EntityID index, EntityID generation, EntityID worldIndex)
{
_id = (worldIndex << (int)(_INDEX_BITS + _GENERATION_BITS)) | (generation << (int)_INDEX_BITS) | index;
_id = worldIndex << (int)(_INDEX_BITS + _GENERATION_BITS) | generation << (int)_INDEX_BITS | index;
}
public readonly bool Equals(Entity other)
@@ -85,4 +85,9 @@ public struct Entity : IEquatable<Entity>, IComparable<Entity>
{
return !(left == right);
}
public override readonly string ToString()
{
return $"Entity {{ Index: {Index}, Generation: {Generation}, WorldIndex: {WorldIndex} }}";
}
}

View File

@@ -0,0 +1,608 @@
// Code from https://github.com/genaray/Arch/blob/master/src/Arch/Core/Utils/BitSet.cs
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
namespace Ghost.Entities.Helpers;
// NOTE: Can this be replaced with `System.Collections.BitArray`?
// NOTE: If not, can it at least mirror that type's API?
/// <summary>
/// The <see cref="BitSet"/> class
/// represents a resizable collection of bits.
/// </summary>
public sealed class BitSet
{
private const int _BIT_SIZE = (sizeof(uint) * 8) - 1; // 31
private const int _INDEX_SIZE = 5; // log_2(BitSize + 1)
private static readonly int _padding = Vector<uint>.Count; // The padding used for vectorisation, the amount of uints required for being vectorized basically
/// <summary>
/// Determines the required length of an <see cref="BitSet"/> to hold the passed id or bit.
/// </summary>
/// <param name="id">The id or bit.</param>
/// <returns>A size of required <see cref="uint"/>s for the bitset.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int RequiredLength(int id)
{
return (id >> 5) + int.Sign(id & _BIT_SIZE);
}
/// <summary>
/// The bits from the bitset.
/// </summary>
private uint[] _bits;
/// TODO: Update on ClearBit, however clearbit is only used in tests so its fine for now.
/// <summary>
/// The highest bit set.
/// </summary>
private int _highestBit;
/// TODO: Update on ClearBit, probably remove <see cref="_highestBit"/> in favor?
/// <summary>
/// The maximum <see cref="_bits"/>-index current in use.
/// </summary>
private int _max;
/// <summary>
/// Initializes a new instance of the <see cref="BitSet" /> class.
/// </summary>
public BitSet()
{
_bits = new uint[_padding];
}
/// <summary>
/// Initializes a new instance of the <see cref="BitSet" /> class.
/// </summary>
public BitSet(params uint[] bits)
{
_bits = bits;
}
/// <summary>
/// The highest uint index in use inside the <see cref="_bits"/>-array.
/// </summary>
public int HighestIndex
{
get => _max;
}
/// <summary>
/// The highest bit set.
/// </summary>
public int HighestBit
{
get => _highestBit;
}
/// <summary>
/// Returns the length of the bitset, how many ints it consists of.
/// </summary>
public int Length
{
get => _bits.Length;
}
/// <summary>
/// Checks whether a bit is set at the index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>True if it is, otherwise false</returns>
public bool IsSet(int index)
{
var b = index >> _INDEX_SIZE;
if (b >= _bits.Length)
{
return false;
}
return (_bits[b] & (1 << (index & _BIT_SIZE))) != 0;
}
/// <summary>
/// Sets a bit at the given index.
/// Resizes its internal array if necessary.
/// </summary>
/// <param name="index">The index.</param>
public void SetBit(int index)
{
var b = index >> _INDEX_SIZE;
if (b >= _bits.Length)
{
Array.Resize(ref _bits, (b + _padding) / _padding * _padding); // Round up to a multiply of Padding
}
// Track highest set bit
_highestBit = Math.Max(_highestBit, index);
_max = (_highestBit / (_BIT_SIZE + 1)) + 1;
_bits[b] |= 1u << (index & _BIT_SIZE);
}
/// <summary>
/// Clears the bit at the given index.
/// </summary>
/// <param name="index">The index.</param>
public void ClearBit(int index)
{
var b = index >> _INDEX_SIZE;
if (b >= _bits.Length)
{
return;
}
_bits[b] &= ~(1u << (index & _BIT_SIZE));
}
/// <summary>
/// Sets all bits.
/// </summary>
public void SetAll()
{
var count = _bits.Length;
for (var i = 0; i < count; i++)
{
_bits[i] = 0xffffffff;
}
_highestBit = (_bits.Length * (_BIT_SIZE + 1)) - 1;
_max = (_highestBit / (_BIT_SIZE + 1)) + 1;
}
/// <summary>
/// Clears all set bits.
/// </summary>
public void ClearAll()
{
Array.Clear(_bits, 0, _bits.Length);
}
/// <summary>
/// Checks if all bits from this instance match those of the other instance.
/// </summary>
/// <param name="other">The other <see cref="BitSet"/>.</param>
/// <returns>True if they match, false if not.</returns>
[SkipLocalsInit]
public bool All(BitSet other)
{
var min = Math.Min(Math.Min(Length, other.Length), _max);
if (!Vector.IsHardwareAccelerated || min < _padding)
{
var bits = _bits.AsSpan();
var otherBits = other._bits.AsSpan();
// Bitwise and
for (var i = 0; i < min; i++)
{
var bit = bits[i];
if ((bit & otherBits[i]) != bit)
{
return false;
}
}
// Handle extra bits on our side that might just be all zero.
for (var i = min; i < _max; i++)
{
if (bits[i] != 0)
{
return false;
}
}
}
else
{
// Vectorized bitwise and
for (var i = 0; i < min; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
var otherVector = new Vector<uint>(other._bits, i);
var resultVector = Vector.BitwiseAnd(vector, otherVector);
if (!Vector.EqualsAll(resultVector, vector))
{
return false;
}
}
// Handle extra bits on our side that might just be all zero.
for (var i = min; i < _max; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
if (!Vector.EqualsAll(vector, Vector<uint>.Zero)) // Vectors are not zero bits[0] != 0 basically
{
return false;
}
}
}
return true;
}
/// <summary>
/// Checks if any bits from this instance match those of the other instance.
/// </summary>
/// <param name="other">The other <see cref="BitSet"/>.</param>
/// <returns>True if they match, false if not.</returns>
public bool Any(BitSet other)
{
var min = Math.Min(Math.Min(Length, other.Length), _max);
if (!Vector.IsHardwareAccelerated || min < _padding)
{
var bits = _bits.AsSpan();
var otherBits = other._bits.AsSpan();
// Bitwise and, return true since any is met
for (var i = 0; i < min; i++)
{
var bit = bits[i];
if ((bit & otherBits[i]) > 0)
{
return true;
}
}
// Handle extra bits on our side that might just be all zero.
for (var i = min; i < _max; i++)
{
if (bits[i] > 0)
{
return false;
}
}
}
else
{
// Vectorized bitwise and, return true since any is met
for (var i = 0; i < min; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
var otherVector = new Vector<uint>(other._bits, i);
var resultVector = Vector.BitwiseAnd(vector, otherVector);
if (!Vector.EqualsAll(resultVector, Vector<uint>.Zero))
{
return true;
}
}
// Handle extra bits on our side that might just be all zero.
for (var i = min; i < _max; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
if (!Vector.EqualsAll(vector, Vector<uint>.Zero)) // Vectors are not zero bits[0] != 0 basically
{
return false;
}
}
}
return _highestBit <= 0;
}
/// <summary>
/// Checks if none bits from this instance match those of the other instance.
/// </summary>
/// <param name="other">The other <see cref="BitSet"/>.</param>
/// <returns>True if none match, false if not.</returns>
public bool None(BitSet other)
{
var min = Math.Min(Math.Min(Length, other.Length), _max);
if (!Vector.IsHardwareAccelerated || min < _padding)
{
var bits = _bits.AsSpan();
var otherBits = other._bits.AsSpan();
// Bitwise and, return true since any is met
for (var i = 0; i < min; i++)
{
var bit = bits[i];
if ((bit & otherBits[i]) != 0)
{
return false;
}
}
}
else
{
// Vectorized bitwise and, return true since any is met
for (var i = 0; i < min; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
var otherVector = new Vector<uint>(other._bits, i);
var resultVector = Vector.BitwiseAnd(vector, otherVector);
if (!Vector.EqualsAll(resultVector, Vector<uint>.Zero))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Checks if exactly all bits from this instance match those of the other instance.
/// </summary>
/// <param name="other">The other <see cref="BitSet"/>.</param>
/// <returns>True if they match, false if not.</returns>
public bool Exclusive(BitSet other)
{
var min = Math.Min(Math.Min(Length, other.Length), _max);
if (!Vector.IsHardwareAccelerated || min < _padding)
{
var bits = _bits.AsSpan();
var otherBits = other._bits.AsSpan();
// Bitwise xor, if both are not totally equal, return false
for (var i = 0; i < min; i++)
{
var bit = bits[i];
if ((bit ^ otherBits[i]) != 0)
{
return false;
}
}
// handle extra bits on our side that might just be all zero
for (var i = min; i < _max; i++)
{
if (bits[i] != 0)
{
return false;
}
}
}
else
{
// Vectorized bitwise xor, return true since any is met
for (var i = 0; i < min; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
var otherVector = new Vector<uint>(other._bits, i);
var resultVector = Vector.Xor(vector, otherVector);
if (!Vector.EqualsAll(resultVector, Vector<uint>.Zero))
{
return false;
}
}
// Handle extra bits on our side that might just be all zero.
for (var i = min; i < _max; i += _padding)
{
var vector = new Vector<uint>(_bits, i);
if (!Vector.EqualsAll(vector, Vector<uint>.Zero)) // Vectors are not zero bits[0] != 0 basically
{
return false;
}
}
}
return true;
}
/// <summary>
/// Creates a <see cref="Span{T}"/> to access the <see cref="_bits"/>.
/// </summary>
/// <returns>The hash.</returns>
public Span<uint> AsSpan()
{
var max = (_highestBit / (_BIT_SIZE + 1)) + 1;
return _bits.AsSpan()[0..max];
}
/// <summary>
/// Copies the bits into a <see cref="Span{T}"/> and returns a slice containing the copied <see cref="_bits"/>.
/// </summary>
/// <param name="span">The <see cref="Span{T}"/> to copy into.</param>
/// <param name="zero">If true, it will zero the unused space from the <see cref="span"/>.</param>
/// <returns>The <see cref="Span{T}"/>.</returns>
public Span<uint> AsSpan(Span<uint> span, bool zero = true)
{
// Copy everything thats possible from one to another
var length = Math.Min(Length, span.Length);
for (var index = 0; index < length; index++)
{
span[index] = _bits[index];
}
// Zero the rest space which was not overriden due to the copy.
for (var index = length; zero && index < span.Length; index++)
{
span[index] = 0;
}
return span[0..length];
}
/// <summary>
/// Calculates the hash, this is unique for the set bits. Two <see cref="BitSet"/> with the same set bits, result in the same hash.
/// </summary>
/// <returns>The hash.</returns>
public override int GetHashCode()
{
return Component.GetHashCode(AsSpan());
}
/// <summary>
/// Prints the content of this instance.
/// </summary>
/// <returns>The string.</returns>
public override string ToString()
{
// Convert uint to binary form for pretty printing
var binaryBuilder = new StringBuilder();
foreach (var bit in _bits)
{
binaryBuilder.Append(Convert.ToString((uint)bit, 2).PadLeft(32, '0')).Append(',');
}
binaryBuilder.Length--;
return $"{nameof(_bits)}: {binaryBuilder}, {nameof(Length)}: {Length}";
}
}
/// <summary>
/// The <see cref="SpanBitSet"/> struct
/// represents a non resizable collection of bits.
/// Used to set, check and clear bits on a allocated <see cref="BitSet"/> or on the stack.
/// </summary>
public readonly ref struct SpanBitSet
{
private const int BitSize = (sizeof(uint) * 8) - 1; // 31
// NOTE: Is a byte not 8 bits?
private const int ByteSize = 5; // log_2(BitSize + 1)
/// <summary>
/// The bits from the bitset.
/// </summary>
private readonly Span<uint> _bits;
/// <summary>
/// Initializes a new instance of the <see cref="BitSet" /> class.
/// </summary>
public SpanBitSet(Span<uint> bits)
{
_bits = bits;
}
/// <summary>
/// Checks whether a bit is set at the index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>True if it is, otherwise false</returns>
public bool IsSet(int index)
{
var b = index >> ByteSize;
if (b >= _bits.Length)
{
return false;
}
return (_bits[b] & (1 << (index & BitSize))) != 0;
}
/// <summary>
/// Sets a bit at the given index.
/// Resizes its internal array if necessary.
/// </summary>
/// <param name="index">The index.</param>
public void SetBit(int index)
{
var b = index >> ByteSize;
if (b >= _bits.Length)
{
return;
}
_bits[b] |= 1u << (index & BitSize);
}
/// <summary>
/// Clears the bit at the given index.
/// </summary>
/// <param name="index">The index.</param>
public void ClearBit(int index)
{
var b = index >> ByteSize;
if (b >= _bits.Length)
{
return;
}
_bits[b] &= ~(1u << (index & BitSize));
}
/// <summary>
///
/// </summary>
public void SetAll()
{
var count = _bits.Length;
for (var i = 0; i < count; i++)
{
_bits[i] = 0xffffffff;
}
}
/// <summary>
/// Clears all set bits.
/// </summary>
public void ClearAll()
{
_bits.Clear();
}
/// <summary>
/// Creates a <see cref="Span{T}"/> to access the <see cref="_bits"/>.
/// </summary>
/// <returns>The hash.</returns>
public Span<uint> AsSpan()
{
return _bits;
}
/// <summary>
/// Copies the bits into a <see cref="Span{T}"/> and returns a slice containing the copied <see cref="_bits"/>.
/// </summary>
/// <param name=""></param>
/// <returns>The hash.</returns>
public Span<uint> AsSpan(Span<uint> span, bool zero = true)
{
// Prevent exception because target array is to small for copy operation
var length = Math.Min(this._bits.Length, span.Length);
for (var index = 0; index < length; index++)
{
span[index] = _bits[index];
}
// Zero the rest space which was not overriden due to the copy.
for (var index = length; zero && index < span.Length; index++)
{
span[index] = 0;
}
return span[.._bits.Length];
}
/// <summary>
/// Calculates the hash, this is unique for the set bits. Two <see cref="BitSet"/> with the same set bits, result in the same hash.
/// </summary>
/// <returns>The hash.</returns>
public override int GetHashCode()
{
return Component.GetHashCode(AsSpan());
}
/// <summary>
/// Prints the content of this instance.
/// </summary>
/// <returns>The string.</returns>
public override string ToString()
{
// Convert uint to binary form for pretty printing
var binaryBuilder = new StringBuilder();
foreach (var bit in _bits)
{
binaryBuilder.Append(Convert.ToString((uint)bit, 2).PadLeft(32, '0')).Append(',');
}
binaryBuilder.Length--;
return $"{nameof(_bits)}: {string.Join(",", binaryBuilder)}";
}
}

View File

@@ -0,0 +1,22 @@
namespace Ghost.Entities.Registries;
internal static class ComponentRegistry
{
private static readonly Dictionary<Type, ComponentData> _hashCodeToComponentMap = new(64);
public static unsafe ComponentData GetOrAdd<T>()
where T : unmanaged, IComponent
{
var type = typeof(T);
if (_hashCodeToComponentMap.TryGetValue(type, out var data))
{
return data;
}
var id = (ushort)_hashCodeToComponentMap.Count;
data = new ComponentData(id, sizeof(T));
_hashCodeToComponentMap.Add(type, data);
return data;
}
}

View File

@@ -0,0 +1,6 @@
namespace Ghost.Entities.Services;
internal class EntityChangeQueue
{
// TODO: This class is not implemented yet.
}

View File

@@ -0,0 +1,38 @@
using Misaki.HighPerformance.Unsafe.Collections;
using Misaki.HighPerformance.Unsafe.Helpers;
namespace Ghost.Entities;
internal struct Signature : IDisposable
{
internal UnsafeArray<ComponentData> _componentDatas;
private int _hashCode;
public Signature(params Span<ComponentData> components)
{
_componentDatas = new UnsafeArray<ComponentData>(components.Length, Allocator.Persistent);
_componentDatas.CopyFrom(components);
_hashCode = -1;
_hashCode = GetHashCode();
}
public override int GetHashCode()
{
if (_hashCode != -1)
{
return _hashCode;
}
unchecked
{
_hashCode = Component.GetHashCode(_componentDatas.AsSpan());
return _hashCode;
}
}
public void Dispose()
{
_componentDatas.Dispose();
}
}