Compare commits

..

1 Commits
main ... x64

Author SHA1 Message Date
cosmonaut 4538c0f3c9 specify x64 2 years ago
  1. 6
      .drone.yml
  2. 7
      TODO
  3. 46
      encompass-cs.sln
  4. 16
      encompass-cs/Attributes/Adds.cs
  5. 11
      encompass-cs/Attributes/Receives.cs
  6. 11
      encompass-cs/Attributes/Sends.cs
  7. 156
      encompass-cs/Collections/BitSet512.cs
  8. 1
      encompass-cs/Collections/ComponentBitSet.cs
  9. 1
      encompass-cs/Collections/ComponentStore.cs
  10. 22
      encompass-cs/Collections/MessageStore.cs
  11. 3
      encompass-cs/Collections/TypedComponentStore.cs
  12. 2
      encompass-cs/Collections/TypedMessageStore.cs
  13. 13
      encompass-cs/ComponentManager.cs
  14. 132
      encompass-cs/DrawLayerManager.cs
  15. 69
      encompass-cs/Engine.cs
  16. 2
      encompass-cs/Engines/Spawner.cs
  17. 4
      encompass-cs/EntitySetQuery.cs
  18. 12
      encompass-cs/Exceptions/IllegalSendTypeException.cs
  19. 390
      encompass-cs/Graph/DirectedGraph.cs
  20. 18
      encompass-cs/Graph/SimpleCycleComparer.cs
  21. 7
      encompass-cs/IMessage.cs
  22. 4
      encompass-cs/Interfaces/IComponent.cs
  23. 7
      encompass-cs/Interfaces/IDrawableComponent.cs
  24. 18
      encompass-cs/MessageManager.cs
  25. 40
      encompass-cs/RenderManager.cs
  26. 20
      encompass-cs/Renderer.cs
  27. 11
      encompass-cs/Renderers/GeneralRenderer.cs
  28. 18
      encompass-cs/Renderers/OrderedRenderer.cs
  29. 7
      encompass-cs/UberEngine.cs
  30. 4
      encompass-cs/UberRenderer.cs
  31. 4
      encompass-cs/World.cs
  32. 193
      encompass-cs/WorldBuilder.cs
  33. 5
      encompass-cs/encompass-cs.csproj
  34. 16
      test/ComponentTest.cs
  35. 22
      test/EngineTest.cs
  36. 18
      test/GeneralRendererTest.cs
  37. 109
      test/OrderedRendererTest.cs
  38. 4
      test/SpawnerTest.cs
  39. 112
      test/WorldBuilderTest.cs
  40. 81
      test/WorldTest.cs
  41. 3
      test/test.csproj

6
.drone.yml

@ -7,18 +7,18 @@
steps:
- name: test
image: mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim
image: mcr.microsoft.com/dotnet/core/sdk:3.1
commands:
- dotnet build -c Release
- dotnet test -c Release
- name: deploy
image: mcr.microsoft.com/dotnet/sdk:5.0.102-ca-patch-buster-slim
image: mcr.microsoft.com/dotnet/core/sdk:3.1
environment:
API_KEY:
from_secret: API_KEY
commands:
- dotnet nuget push /build/encompass-cs/bin/Release/EncompassECS.Framework.*.nupkg -s https://api.nuget.org/v3/index.json -k $API_KEY
- dotnet nuget push /build/encompass-cs/bin/Release/EncompassECS.Framework.*.nupkg -s https://api.nuget.org/v3/index.json -k $API_KEY
when:
ref:
- refs/tags/*.*.*

7
TODO

@ -0,0 +1,7 @@
- immutable component system?
- method to remove all components of a type without destroying Entities
- method to remove a component of a type without destroying entity
- look at test coverage
- docs

46
encompass-cs.sln

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30717.126
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "encompass-cs", "encompass-cs\encompass-cs.csproj", "{B862FC25-0740-4CEA-BC53-3C5F43DCD985}"
EndProject
@ -9,28 +9,38 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "test", "test\test.csproj",
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x64.ActiveCfg = Debug|x64
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x64.Build.0 = Debug|x64
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x86.ActiveCfg = Debug|x86
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x86.Build.0 = Debug|x86
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x64.ActiveCfg = Release|x64
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x64.Build.0 = Release|x64
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x86.ActiveCfg = Release|x86
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x86.Build.0 = Release|x86
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x64.ActiveCfg = Debug|x64
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x64.Build.0 = Debug|x64
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x86.ActiveCfg = Debug|x86
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x86.Build.0 = Debug|x86
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x64.ActiveCfg = Release|x64
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x64.Build.0 = Release|x64
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x86.ActiveCfg = Release|x86
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x86.Build.0 = Release|x86
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x64.ActiveCfg = Debug|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x64.Build.0 = Debug|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x86.ActiveCfg = Debug|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Debug|x86.Build.0 = Debug|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|Any CPU.Build.0 = Release|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x64.ActiveCfg = Release|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x64.Build.0 = Release|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x86.ActiveCfg = Release|Any CPU
{B862FC25-0740-4CEA-BC53-3C5F43DCD985}.Release|x86.Build.0 = Release|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|Any CPU.Build.0 = Debug|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x64.ActiveCfg = Debug|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x64.Build.0 = Debug|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x86.ActiveCfg = Debug|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Debug|x86.Build.0 = Debug|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|Any CPU.ActiveCfg = Release|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|Any CPU.Build.0 = Release|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x64.ActiveCfg = Release|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x64.Build.0 = Release|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x86.ActiveCfg = Release|Any CPU
{23D6C29C-A310-4D3E-8455-8D0B8CA1FC06}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

16
encompass-cs/Attributes/Adds.cs

@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
namespace Encompass
{
[AttributeUsage(AttributeTargets.Class)]
public class Adds : Attribute
{
public readonly HashSet<Type> addTypes;
public Adds(params Type[] addTypes)
{
this.addTypes = new HashSet<Type>(addTypes);
}
}
}

11
encompass-cs/Attributes/Receives.cs

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Encompass.Exceptions;
namespace Encompass
{
@ -10,6 +12,15 @@ namespace Encompass
public Receives(params Type[] receiveTypes)
{
foreach (var receiveType in receiveTypes)
{
var isMessage = receiveType.GetInterfaces().Contains(typeof(IMessage));
if (!isMessage)
{
throw new IllegalSendTypeException("{0} must be a Message", receiveType.Name);
}
}
ReceiveTypes = new HashSet<Type>(receiveTypes);
}
}

11
encompass-cs/Attributes/Sends.cs

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Encompass.Exceptions;
namespace Encompass
{
@ -10,6 +12,15 @@ namespace Encompass
public Sends(params Type[] sendTypes)
{
foreach (var sendType in sendTypes)
{
var isMessage = sendType.GetInterfaces().Contains(typeof(IMessage));
if (!isMessage)
{
throw new IllegalSendTypeException("{0} must be a Message", sendType.Name);
}
}
this.SendTypes = new HashSet<Type>(sendTypes);
}
}

156
encompass-cs/Collections/BitSet512.cs

@ -1,156 +0,0 @@
using System;
namespace Encompass
{
public static unsafe class MemoryHelper
{
public static void Copy(uint* src, uint* dest, int count)
{
for (; count != 0; count--) *dest++ = *src++;
}
public static void Fill(uint* p, int count, uint value)
{
for (; count != 0; count--) *p++ = value;
}
public static void And(uint* p, uint* q, uint* result, int count)
{
for (; count != 0; count--) *result++ = *p++ & *q++;
}
public static void Or(uint* p, uint* q, uint* result, int count)
{
for (; count != 0; count--) *result++ = *p++ | *q++;
}
public static void Not(uint* p, uint* result, int count)
{
for (; count != 0; count--) *result++ = ~*p++;
}
public static bool Equal(uint* p, uint* q, int count)
{
for (; count != 0; count--) if (*p++ != *q++) { return false; }
return true;
}
}
public unsafe struct BitSet512 : IEquatable<BitSet512>
{
public static BitSet512 Zero { get; } = new BitSet512(0);
public static BitSet512 Ones { get; } = new BitSet512(uint.MaxValue);
private const int _uintLength = 16;
private fixed uint _buffer[_uintLength];
public BitSet512(uint value)
{
fixed (uint* p = _buffer) MemoryHelper.Fill(p, _uintLength, value);
}
public BitSet512(uint* src)
{
fixed (uint* dest = _buffer) MemoryHelper.Copy(src, dest, _uintLength);
}
public static BitSet512 operator &(BitSet512 a, BitSet512 b)
{
var tmp = stackalloc uint[_uintLength];
MemoryHelper.And(a._buffer, b._buffer, tmp, _uintLength);
return new BitSet512(tmp);
}
public static BitSet512 operator |(BitSet512 a, BitSet512 b)
{
var tmp = stackalloc uint[_uintLength];
MemoryHelper.Or(a._buffer, b._buffer, tmp, _uintLength);
return new BitSet512(tmp);
}
public static BitSet512 operator ~(BitSet512 a)
{
var tmp = stackalloc uint[_uintLength];
MemoryHelper.Not(a._buffer, tmp, _uintLength);
return new BitSet512(tmp);
}
public static bool operator ==(BitSet512 left, BitSet512 right)
{
return left.Equals(right);
}
public static bool operator !=(BitSet512 left, BitSet512 right)
{
return !(left == right);
}
public BitSet512 Set(int index)
{
var tmp = stackalloc uint[_uintLength];
fixed (uint* p = _buffer) MemoryHelper.Copy(p, tmp, _uintLength);
tmp[index / 32] |= (uint)(1 << index % 32);
return new BitSet512(tmp);
}
public BitSet512 UnSet(int index)
{
var tmp = stackalloc uint[_uintLength];
fixed (uint* p = _buffer) MemoryHelper.Copy(p, tmp, _uintLength);
tmp[index / 32] &= ~(uint)(1 << index % 32);
return new BitSet512(tmp);
}
public bool Get(int bitIndex)
{
var bitInt = (uint)(1 << bitIndex % 32);
return (_buffer[bitIndex / 32] & bitInt) == bitInt;
}
public bool AllTrue()
{
return this == Ones;
}
public bool AllFalse()
{
return this == Zero;
}
public static BitSet512 BitwiseAnd(BitSet512 left, BitSet512 right)
{
return left & right;
}
public static BitSet512 BitwiseOr(BitSet512 left, BitSet512 right)
{
return left | right;
}
public static BitSet512 OnesComplement(BitSet512 bitSet)
{
return ~bitSet;
}
public override bool Equals(object obj)
{
return obj is BitSet512 set && Equals(set);
}
public bool Equals(BitSet512 other)
{
fixed (uint* p = _buffer) return MemoryHelper.Equal(p, other._buffer, _uintLength);
}
public override int GetHashCode()
{
var hc = 0;
for (var i = 0; i < _uintLength; i++)
{
hc ^= _buffer[i].GetHashCode();
}
return hc;
}
}
}

1
encompass-cs/Collections/ComponentBitSet.cs

@ -1,3 +1,4 @@
using MoonTools.FastCollections;
using System;
using System.Collections.Generic;

1
encompass-cs/Collections/ComponentStore.cs

@ -1,4 +1,5 @@
using Encompass.Exceptions;
using MoonTools.FastCollections;
using System;
using System.Collections.Generic;

22
encompass-cs/Collections/MessageStore.cs

@ -8,60 +8,60 @@ namespace Encompass
{
private readonly Dictionary<Type, TypedMessageStore> _stores = new Dictionary<Type, TypedMessageStore>(512);
private void RegisterMessageType<TMessage>() where TMessage : struct
private void RegisterMessageType<TMessage>() where TMessage : struct, IMessage
{
_stores.Add(typeof(TMessage), new TypedMessageStore<TMessage>());
}
private TypedMessageStore<TMessage> Lookup<TMessage>() where TMessage : struct
private TypedMessageStore<TMessage> Lookup<TMessage>() where TMessage : struct, IMessage
{
if (!_stores.ContainsKey(typeof(TMessage))) { RegisterMessageType<TMessage>(); }
return _stores[typeof(TMessage)] as TypedMessageStore<TMessage>;
}
public void AddMessage<TMessage>(in TMessage message) where TMessage : struct
public void AddMessage<TMessage>(in TMessage message) where TMessage : struct, IMessage
{
Lookup<TMessage>().Add(message);
}
public void AddMessage<TMessage>(in TMessage message, double time) where TMessage : struct
public void AddMessage<TMessage>(in TMessage message, double time) where TMessage : struct, IMessage
{
Lookup<TMessage>().Add(message, time);
}
public void AddMessageIgnoringTimeDilation<TMessage>(in TMessage message, double time) where TMessage : struct
public void AddMessageIgnoringTimeDilation<TMessage>(in TMessage message, double time) where TMessage : struct, IMessage
{
Lookup<TMessage>().AddIgnoringTimeDilation(message, time);
}
public ref readonly TMessage First<TMessage>() where TMessage : struct
public ref readonly TMessage First<TMessage>() where TMessage : struct, IMessage
{
if (!Any<TMessage>()) { throw new NoMessageOfTypeException("No Message of type {0} exists", typeof(TMessage).Name); }
return ref Lookup<TMessage>().First();
}
public ReadOnlySpan<TMessage> All<TMessage>() where TMessage : struct
public ReadOnlySpan<TMessage> All<TMessage>() where TMessage : struct, IMessage
{
return Lookup<TMessage>().All();
}
public bool Any<TMessage>() where TMessage : struct
public bool Any<TMessage>() where TMessage : struct, IMessage
{
return Lookup<TMessage>().Any();
}
public IEnumerable<TMessage> WithEntity<TMessage>(int entityID) where TMessage : struct, IHasEntity
public IEnumerable<TMessage> WithEntity<TMessage>(int entityID) where TMessage : struct, IMessage, IHasEntity
{
return Lookup<TMessage>().WithEntity(entityID);
}
public ref readonly TMessage FirstWithEntity<TMessage>(int entityID) where TMessage : struct
public ref readonly TMessage FirstWithEntity<TMessage>(int entityID) where TMessage : struct, IMessage
{
return ref Lookup<TMessage>().FirstWithEntity(entityID);
}
public bool SomeWithEntity<TMessage>(int entityID) where TMessage : struct, IHasEntity
public bool SomeWithEntity<TMessage>(int entityID) where TMessage : struct, IMessage, IHasEntity
{
return Lookup<TMessage>().SomeWithEntity(entityID);
}

3
encompass-cs/Collections/TypedComponentStore.cs

@ -78,8 +78,8 @@ namespace Encompass
{
if (!_priorities.ContainsKey(entityID) || priority <= _priorities[entityID]) // if priorities are equal that means it's the same engine
{
ForceRemove(entityID);
_priorities[entityID] = priority;
ForceRemove(entityID);
return true;
}
@ -92,6 +92,7 @@ namespace Encompass
{
var storageIndex = _entityIDToStorageIndex[entityID];
_entityIDToStorageIndex.Remove(entityID);
_priorities.Remove(entityID);
// move a component into the hole to maintain contiguous memory
if (_nextID > 1 && storageIndex != _nextID - 1)

2
encompass-cs/Collections/TypedMessageStore.cs

@ -9,7 +9,7 @@ namespace Encompass
public abstract void Clear();
}
internal class TypedMessageStore<TMessage> : TypedMessageStore where TMessage : struct
internal class TypedMessageStore<TMessage> : TypedMessageStore where TMessage : struct, IMessage
{
// messages are placed in a contiguous region
// so we can return the collection as a Span

13
encompass-cs/ComponentManager.cs

@ -5,6 +5,8 @@ namespace Encompass
{
internal class ComponentManager
{
private readonly DrawLayerManager _drawLayerManager;
private readonly ComponentStore _existingComponentStore;
private readonly ComponentStore _immediateComponentStore;
private readonly ComponentDeltaStore _replayStore;
@ -17,8 +19,9 @@ namespace Encompass
internal ComponentBitSet ImmediateBits { get { return _immediateComponentStore.ComponentBitSet; } }
internal ComponentBitSet ExistingBits { get { return _existingComponentStore.ComponentBitSet; } }
public ComponentManager(Dictionary<Type, int> typeToIndex)
public ComponentManager(DrawLayerManager drawLayerManager, Dictionary<Type, int> typeToIndex)
{
this._drawLayerManager = drawLayerManager;
_existingComponentStore = new ComponentStore(typeToIndex);
_immediateComponentStore = new ComponentStore(typeToIndex);
_replayStore = new ComponentDeltaStore(typeToIndex);
@ -44,6 +47,11 @@ namespace Encompass
_upToDateComponentStore.SwapWith(componentStore);
}
internal void RegisterDrawableComponent<TComponent>(int entityID, int layer) where TComponent : struct
{
_drawLayerManager.RegisterComponentWithLayer<TComponent>(entityID, layer);
}
internal void WriteComponents()
{
_existingComponentStore.UpdateUsing(_replayStore);
@ -256,6 +264,7 @@ namespace Encompass
_immediateComponentStore.Remove(entityID);
_replayStore.Remove(entityID);
_upToDateComponentStore.Remove(entityID);
_drawLayerManager.UnRegisterEntityWithLayer(entityID);
}
_entitiesMarkedForRemoval.Clear();
@ -267,6 +276,7 @@ namespace Encompass
{
_replayStore.Remove<TComponent>(entityID, priority);
_upToDateComponentStore.Remove<TComponent>(entityID, priority);
_drawLayerManager.UnRegisterComponentWithLayer<TComponent>(entityID);
return true;
}
return false;
@ -277,6 +287,7 @@ namespace Encompass
if (_upToDateComponentStore.Remove<TComponent>(entityID, priority))
{
_replayStore.Remove<TComponent>(entityID, priority);
_drawLayerManager.UnRegisterComponentWithLayer<TComponent>(entityID);
}
}

132
encompass-cs/DrawLayerManager.cs

@ -0,0 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Encompass.Exceptions;
namespace Encompass
{
internal class DrawLayerManager
{
private readonly SortedList<int, int> _layerOrder = new SortedList<int, int>();
private readonly Dictionary<int, Dictionary<Type, HashSet<int>>> _layerIndexToTypeToID = new Dictionary<int, Dictionary<Type, HashSet<int>>>();
private readonly Dictionary<int, HashSet<GeneralRenderer>> _layerIndexToGeneralRenderers = new Dictionary<int, HashSet<GeneralRenderer>>(512);
private readonly Dictionary<Type, Dictionary<int, int>> _typeToEntityToLayer = new Dictionary<Type, Dictionary<int, int>>(512);
public IEnumerable<int> LayerOrder { get { return _layerOrder.Values; } }
public DrawLayerManager()
{
RegisterDrawLayer(0);
}
public void RegisterDrawLayer(int layer)
{
if (!_layerIndexToTypeToID.ContainsKey(layer))
{
_layerOrder.Add(layer, layer);
_layerIndexToGeneralRenderers.Add(layer, new HashSet<GeneralRenderer>());
_layerIndexToTypeToID.Add(layer, new Dictionary<Type, HashSet<int>>());
}
}
public void RegisterOrderedDrawable<TComponent>() where TComponent : struct
{
if (!_typeToEntityToLayer.ContainsKey(typeof(TComponent)))
{
_typeToEntityToLayer.Add(typeof(TComponent), new Dictionary<int, int>(128));
}
foreach (var pair in _layerIndexToTypeToID)
{
if (!pair.Value.ContainsKey(typeof(TComponent)))
{
pair.Value.Add(typeof(TComponent), new HashSet<int>());
}
}
}
public void RegisterGeneralRendererWithLayer(GeneralRenderer renderer, int layer)
{
RegisterDrawLayer(layer);
var set = _layerIndexToGeneralRenderers[layer];
set.Add(renderer);
}
public void RegisterComponentWithLayer<TComponent>(int entityID, int layer) where TComponent : struct
{
if (!_layerIndexToTypeToID.ContainsKey(layer))
{
throw new UndefinedLayerException("Layer {0} is not defined. Use WorldBuilder.RegisterDrawLayer to register the layer.", layer);
}
if (_typeToEntityToLayer[typeof(TComponent)].ContainsKey(entityID))
{
if (_typeToEntityToLayer[typeof(TComponent)][entityID] != layer)
{
UnRegisterComponentWithLayer<TComponent>(entityID);
var set = _layerIndexToTypeToID[layer][typeof(TComponent)];
set.Add(entityID);
_typeToEntityToLayer[typeof(TComponent)].Add(entityID, layer);
}
}
else
{
var set = _layerIndexToTypeToID[layer][typeof(TComponent)];
set.Add(entityID);
_typeToEntityToLayer[typeof(TComponent)].Add(entityID, layer);
}
}
public void UnRegisterComponentWithLayer<TComponent>(int entityID) where TComponent : struct
{
if (!_typeToEntityToLayer.ContainsKey(typeof(TComponent))) { return; }
if (_typeToEntityToLayer[typeof(TComponent)].ContainsKey(entityID))
{
var layer = _typeToEntityToLayer[typeof(TComponent)][entityID];
_layerIndexToTypeToID[layer][typeof(TComponent)].Remove(entityID);
}
_typeToEntityToLayer[typeof(TComponent)].Remove(entityID);
}
public void UnRegisterEntityWithLayer(int entityID)
{
foreach (var store in _layerIndexToTypeToID.Values)
{
foreach (var typeToSet in store)
{
var type = typeToSet.Key;
var set = typeToSet.Value;
if (set.Contains(entityID))
{
_typeToEntityToLayer[type].Remove(entityID);
set.Remove(entityID);
}
}
}
}
public IEnumerable<GeneralRenderer> GeneralRenderersByLayer(int layer)
{
return _layerIndexToGeneralRenderers.ContainsKey(layer) ?
_layerIndexToGeneralRenderers[layer] :
Enumerable.Empty<GeneralRenderer>();
}
public IEnumerable<(int, Type)> AllInLayer(int layer)
{
foreach (var kvp in _layerIndexToTypeToID[layer])
{
foreach (var id in kvp.Value)
{
yield return (id, kvp.Key);
}
}
}
}
}

69
encompass-cs/Engine.cs

@ -3,6 +3,7 @@ using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Encompass.Exceptions;
using MoonTools.FastCollections;
namespace Encompass
{
@ -23,7 +24,6 @@ namespace Encompass
internal readonly HashSet<Type> WriteImmediateTypes = new HashSet<Type>();
internal readonly HashSet<Type> QueryWithTypes = new HashSet<Type>();
internal readonly HashSet<Type> QueryWithoutTypes = new HashSet<Type>();
internal readonly HashSet<Type> AddTypes = new HashSet<Type>();
internal readonly Dictionary<Type, int> WritePriorities = new Dictionary<Type, int>();
internal readonly int DefaultWritePriority = 0;
@ -59,12 +59,6 @@ namespace Encompass
{
_id = Guid.NewGuid();
var addsAttribute = GetType().GetCustomAttribute<Adds>(false);
if (addsAttribute != null)
{
AddTypes = addsAttribute.addTypes;
}
var sendsAttribute = GetType().GetCustomAttribute<Sends>(false);
if (sendsAttribute != null)
{
@ -176,7 +170,7 @@ namespace Encompass
_trackingManager = trackingManager;
}
internal void CheckMessageRead<TMessage>() where TMessage : struct
internal void CheckMessageRead<TMessage>() where TMessage : struct, IMessage
{
if (!ReceiveTypes.Contains(typeof(TMessage)))
{
@ -229,7 +223,7 @@ namespace Encompass
/// <summary>
/// Returns all Entities containing the specified Component type.
/// </summary>
protected ReadOnlySpan<Entity> ReadEntities<TComponent>() where TComponent : struct
protected ReadOnlySpan<Entity> ReadEntities<TComponent>() where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -254,7 +248,7 @@ namespace Encompass
/// <summary>
/// Returns an Entity containing the specified Component type.
/// </summary>
protected ref readonly Entity ReadEntity<TComponent>() where TComponent : struct
protected ref readonly Entity ReadEntity<TComponent>() where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -279,7 +273,7 @@ namespace Encompass
/// <summary>
/// Returns all of the Components with the specified Component Type.
/// </summary>
protected ReadOnlySpan<TComponent> ReadComponents<TComponent>() where TComponent : struct
protected ReadOnlySpan<TComponent> ReadComponents<TComponent>() where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -304,7 +298,7 @@ namespace Encompass
/// <summary>
/// Returns a Component with the specified Component Type. If multiples exist, an arbitrary Component is returned.
/// </summary>
protected ref readonly TComponent ReadComponent<TComponent>() where TComponent : struct
protected ref readonly TComponent ReadComponent<TComponent>() where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -329,7 +323,7 @@ namespace Encompass
/// <summary>
/// Returns true if any Component with the specified Component Type exists.
/// </summary>
protected bool SomeComponent<TComponent>() where TComponent : struct
protected bool SomeComponent<TComponent>() where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -351,7 +345,7 @@ namespace Encompass
}
}
private ref TComponent GetComponentHelper<TComponent>(int entityID) where TComponent : struct
private ref TComponent GetComponentHelper<TComponent>(int entityID) where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -382,7 +376,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalReadException">
/// Thrown when the Engine does not declare that it reads the given Component Type.
/// </exception>
protected ref readonly TComponent GetComponent<TComponent>(in Entity entity) where TComponent : struct
protected ref readonly TComponent GetComponent<TComponent>(in Entity entity) where TComponent : struct, IComponent
{
return ref GetComponentHelper<TComponent>(entity.ID);
}
@ -393,7 +387,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalReadException">
/// Thrown when the Engine does not declare that is Reads the given Component Type.
/// </exception>
protected bool HasComponent<TComponent>(in Entity entity) where TComponent : struct
protected bool HasComponent<TComponent>(in Entity entity) where TComponent : struct, IComponent
{
var immediateRead = ReadImmediateTypes.Contains(typeof(TComponent));
var existingRead = ReadTypes.Contains(typeof(TComponent));
@ -451,7 +445,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalWriteException">
/// Thrown when the Engine does not declare that it Writes the given Component Type.
/// </exception>
protected void SetComponent<TComponent>(in Entity entity, in TComponent component) where TComponent : struct
protected void SetComponent<TComponent>(in Entity entity, in TComponent component) where TComponent : struct, IComponent
{
var priority = WritePriorities.ContainsKey(typeof(TComponent)) ? WritePriorities[typeof(TComponent)] : DefaultWritePriority;
@ -478,6 +472,11 @@ namespace Encompass
{
_trackingManager.RegisterAddition(entity.ID, typeof(TComponent));
}
if (written && component is IDrawableComponent drawableComponent)
{
_componentManager.RegisterDrawableComponent<TComponent>(entity.ID, drawableComponent.Layer);
}
}
/// <summary>
@ -486,13 +485,8 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalWriteException">
/// Thrown when the Engine does not declare that it Writes the given Component Type.
/// </exception>
protected void AddComponent<TComponent>(in Entity entity, in TComponent component) where TComponent : struct
protected void AddComponent<TComponent>(in Entity entity, in TComponent component) where TComponent : struct, IComponent
{
if (!AddTypes.Contains(typeof(TComponent)))
{
throw new IllegalWriteException("Engine {0} tried to add undeclared Component {1}", GetType().Name, typeof(TComponent).Name);
}
if (!EntityCreatedThisFrame(entity.ID))
{
throw new IllegalWriteException("AddComponent used on Entity that was not created in this context. Use SetComponent instead.");
@ -509,6 +503,11 @@ namespace Encompass
}
_trackingManager.RegisterAddition(entity.ID, typeof(TComponent));
if (component is IDrawableComponent drawableComponent)
{
_componentManager.RegisterDrawableComponent<TComponent>(entity.ID, drawableComponent.Layer);
}
}
/// <summary>
@ -517,7 +516,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalSendException">
/// Thrown when the Engine does not declare that it Sends the Message Type.
/// </exception>
protected void SendMessage<TMessage>(in TMessage message) where TMessage : struct
protected void SendMessage<TMessage>(in TMessage message) where TMessage : struct, IMessage
{
if (!SendTypes.Contains(typeof(TMessage)))
{
@ -531,7 +530,7 @@ namespace Encompass
/// Sends a message after the specified number of seconds, respecting time dilation.
/// </summary>
/// <param name="time">The time in seconds that will elapse before the message is sent.</param>
protected void SendMessage<TMessage>(in TMessage message, double time) where TMessage : struct
protected void SendMessage<TMessage>(in TMessage message, double time) where TMessage : struct, IMessage
{
_messageManager.AddMessage(message, time);
}
@ -540,7 +539,7 @@ namespace Encompass
/// Sends a message after the specified number of seconds, ignoring time dilation.
/// </summary>
/// <param name="time">The time in seconds that will elapse before the message is sent.</param>
protected void SendMessageIgnoringTimeDilation<TMessage>(in TMessage message, double time) where TMessage : struct
protected void SendMessageIgnoringTimeDilation<TMessage>(in TMessage message, double time) where TMessage : struct, IMessage
{
_messageManager.AddMessageIgnoringTimeDilation(message, time);
}
@ -551,7 +550,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalReadException">
/// Thrown when the Engine does not declare that it Receives the specified Message Type.
/// </exception>
protected ReadOnlySpan<TMessage> ReadMessages<TMessage>() where TMessage : struct
protected ReadOnlySpan<TMessage> ReadMessages<TMessage>() where TMessage : struct, IMessage
{
CheckMessageRead<TMessage>();
return _messageManager.GetMessagesByType<TMessage>();
@ -563,7 +562,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalReadException">
/// Thrown when the Engine does not declare that it Receives the specified Message Type.
/// </exception>
protected ref readonly TMessage ReadMessage<TMessage>() where TMessage : struct
protected ref readonly TMessage ReadMessage<TMessage>() where TMessage : struct, IMessage
{
CheckMessageRead<TMessage>();
return ref _messageManager.First<TMessage>();
@ -575,7 +574,7 @@ namespace Encompass
/// <exception cref="Encompass.Exceptions.IllegalReadException">
/// Thrown when the Engine does not declare that it Receives the specified Message Type.
/// </exception>
protected bool SomeMessage<TMessage>() where TMessage : struct
protected bool SomeMessage<TMessage>() where TMessage : struct, IMessage
{
CheckMessageRead<TMessage>();
return _messageManager.Any<TMessage>();
@ -594,7 +593,7 @@ namespace Encompass
/// Destroys an arbitrary Entity containing a Component of the specified Type.
/// Entity destruction takes place after all the Engines have been processed by World Update.
/// </summary>
protected void DestroyWith<TComponent>() where TComponent : struct
protected void DestroyWith<TComponent>() where TComponent : struct, IComponent
{
Destroy(ReadEntity<TComponent>());
}
@ -603,7 +602,7 @@ namespace Encompass
/// Destroys all Entities containing a Component of the specified Type.
/// Entity destruction takes place after all the Engines have been processed by World Update.
/// </summary>
protected void DestroyAllWith<TComponent>() where TComponent : struct
protected void DestroyAllWith<TComponent>() where TComponent : struct, IComponent
{
foreach (var entity in ReadEntities<TComponent>())
{
@ -616,7 +615,7 @@ namespace Encompass
/// Note that the Engine must Read the Component type that is being removed.
/// If a Component with the specified type does not exist on the Entity, returns false and does not mutate the Entity.
/// </summary>
protected void RemoveComponent<TComponent>(in Entity entity) where TComponent : struct
protected void RemoveComponent<TComponent>(in Entity entity) where TComponent : struct, IComponent
{
var priority = WritePriorities.ContainsKey(typeof(TComponent)) ? WritePriorities[typeof(TComponent)] : DefaultWritePriority;
@ -709,7 +708,7 @@ namespace Encompass
/// <typeparam name="TMessage">The Message subtype.</typeparam>
/// <param name="entity">The entity that all messages in the IEnumerable refer to.</param>
/// <returns></returns>
protected IEnumerable<TMessage> ReadMessagesWithEntity<TMessage>(in Entity entity) where TMessage : struct, IHasEntity
protected IEnumerable<TMessage> ReadMessagesWithEntity<TMessage>(in Entity entity) where TMessage : struct, IMessage, IHasEntity
{
CheckMessageRead<TMessage>();
return _messageManager.WithEntity<TMessage>(entity.ID);
@ -719,7 +718,7 @@ namespace Encompass
/// Efficiently reads a single Message of a given type that references a given Entity.
/// It is recommended to use this method in conjunction with SomeMessageWithEntity to prevent errors.
/// </summary>
protected ref readonly TMessage ReadMessageWithEntity<TMessage>(in Entity entity) where TMessage : struct, IHasEntity
protected ref readonly TMessage ReadMessageWithEntity<TMessage>(in Entity entity) where TMessage : struct, IMessage, IHasEntity
{
CheckMessageRead<TMessage>();
return ref _messageManager.WithEntitySingular<TMessage>(entity.ID);
@ -728,7 +727,7 @@ namespace Encompass
/// <summary>
/// Efficiently checks if any Message of a given type referencing a given Entity exists.
/// </summary>
protected bool SomeMessageWithEntity<TMessage>(in Entity entity) where TMessage : struct, IHasEntity
protected bool SomeMessageWithEntity<TMessage>(in Entity entity) where TMessage : struct, IMessage, IHasEntity
{
CheckMessageRead<TMessage>();
return _messageManager.SomeWithEntity<TMessage>(entity.ID);

2
encompass-cs/Engines/Spawner.cs

@ -6,7 +6,7 @@ namespace Encompass
/// A Spawner is a special type of Engine that runs a Spawn method in response to each Message it receives.
/// Spawners are useful for organizing the building of new Entities in your game.
/// </summary>
public abstract class Spawner<TMessage> : Engine where TMessage : struct
public abstract class Spawner<TMessage> : Engine where TMessage : struct, IMessage
{
protected Spawner() : base()
{

4
encompass-cs/EntitySetQuery.cs

@ -1,4 +1,6 @@
namespace Encompass
using MoonTools.FastCollections;
namespace Encompass
{
internal struct EntitySetQuery
{

12
encompass-cs/Exceptions/IllegalSendTypeException.cs

@ -0,0 +1,12 @@
using System;
namespace Encompass.Exceptions
{
public class IllegalSendTypeException : Exception
{
public IllegalSendTypeException(
string format,
params object[] args
) : base(string.Format(format, args)) { }
}
}

390
encompass-cs/Graph/DirectedGraph.cs

@ -1,390 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Encompass
{
internal class DirectedGraph<TNode> where TNode : IEquatable<TNode>
{
protected HashSet<TNode> nodes = new HashSet<TNode>();
protected Dictionary<TNode, HashSet<TNode>> neighbors = new Dictionary<TNode, HashSet<TNode>>();
protected HashSet<(TNode, TNode)> edges = new HashSet<(TNode, TNode)>();
public IEnumerable<TNode> Nodes => nodes;
public IEnumerable<(TNode, TNode)> Edges => edges;
public void AddNode(TNode node)
{
if (!Exists(node))
{
nodes.Add(node);
neighbors.Add(node, new HashSet<TNode>());
}
}
public void AddNodes(params TNode[] nodes)
{
foreach (var node in nodes)
{
AddNode(node);
}
}
public void RemoveNode(TNode node)
{
CheckNodes(node);
var edgesToRemove = new List<(TNode, TNode)>();
foreach (var entry in neighbors)
{
if (entry.Value.Contains(node))
{
edgesToRemove.Add((entry.Key, node));
}
}
foreach (var edge in edgesToRemove)
{
RemoveEdge(edge.Item1, edge.Item2);
}
nodes.Remove(node);
neighbors.Remove(node);
}
public void RemoveEdge(TNode v, TNode u)
{
CheckEdge(v, u);
neighbors[v].Remove(u);
edges.Remove((v, u));
}
public void AddEdge(TNode v, TNode u)
{
CheckNodes(v, u);
if (Exists(v, u)) { throw new ArgumentException($"Edge between {v} and {u} already exists in the graph"); }
if (v.Equals(u)) { throw new ArgumentException("Self-edges are not allowed in a simple graph. Use a multigraph instead"); }
neighbors[v].Add(u);
edges.Add((v, u));
}
public bool Exists(TNode node)
{
return nodes.Contains(node);
}
public bool Exists(TNode v, TNode u)
{
CheckNodes(v, u);
return edges.Contains((v, u));
}
protected void CheckNodes(params TNode[] givenNodes)
{
foreach (var node in givenNodes)
{
if (!Exists(node))
{
throw new System.ArgumentException($"Vertex {node} does not exist in the graph");
}
}
}
protected void CheckEdge(TNode v, TNode u)
{
CheckNodes(v, u);
if (!Exists(v, u)) { throw new ArgumentException($"Edge between vertex {v} and vertex {u} does not exist in the graph"); }
}
public IEnumerable<TNode> Neighbors(TNode node)
{
CheckNodes(node);
return neighbors[node];
}
public DirectedGraph<TNode> Clone()
{
var clone = new DirectedGraph<TNode>();
clone.AddNodes(Nodes.ToArray());
foreach (var v in Nodes)
{
foreach (var n in Neighbors(v))
{
clone.AddEdge(v, n);
}
}
return clone;
}
public DirectedGraph<TNode> SubGraph(params TNode[] subVertices)
{
var subGraph = new DirectedGraph<TNode>();
subGraph.AddNodes(subVertices.ToArray());
foreach (var n in Nodes)
{
if (Nodes.Contains(n))
{
var neighbors = Neighbors(n);
foreach (var u in neighbors)
{
if (subVertices.Contains(u))
{
subGraph.AddEdge(n, u);
}
}
}
}
return subGraph;
}
private IEnumerable<TNode> PostorderNodeDFSHelper(HashSet<TNode> discovered, TNode v)
{
discovered.Add(v);
foreach (var neighbor in Neighbors(v))
{
if (!discovered.Contains(neighbor))
{
foreach (var node in PostorderNodeDFSHelper(discovered, neighbor))
{
yield return node;
}
}
}
yield return v;
}
protected IEnumerable<TNode> PostorderNodeDFS()
{
var dfsDiscovered = new HashSet<TNode>();
foreach (var node in Nodes)
{
if (!dfsDiscovered.Contains(node))
{
foreach (var thing in PostorderNodeDFSHelper(dfsDiscovered, node))
{
yield return thing;
}
}
}
}
public IEnumerable<TNode> TopologicalSort()
{
return PostorderNodeDFS().Reverse();
}
public bool Cyclic()
{
return StronglyConnectedComponents().Any((scc) => scc.Count() > 1);
}
public IEnumerable<IEnumerable<TNode>> SimpleCycles()
{
void unblock(TNode thisnode, HashSet<TNode> blocked, Dictionary<TNode, HashSet<TNode>> B) //refactor to remove closure
{
var stack = new Stack<TNode>();
stack.Push(thisnode);
while (stack.Count > 0)
{
var node = stack.Pop();
if (blocked.Contains(thisnode))
{
blocked.Remove(thisnode);
if (B.ContainsKey(node))
{
foreach (var n in B[node])
{
if (!stack.Contains(n))
{
stack.Push(n);
}
}
B[node].Clear();
}
}
}
}
List<List<TNode>> result = new List<List<TNode>>();
var subGraph = Clone();
var sccs = new Stack<IEnumerable<TNode>>();
foreach (var scc in StronglyConnectedComponents())
{
sccs.Push(scc);
}
while (sccs.Count > 0)
{
var scc = new Stack<TNode>(sccs.Pop());
var startNode = scc.Pop();
var path = new Stack<TNode>();
path.Push(startNode);
var blocked = new HashSet<TNode>
{
startNode
};
var closed = new HashSet<TNode>();
var B = new Dictionary<TNode, HashSet<TNode>>();
var stack = new Stack<(TNode, Stack<TNode>)>();
stack.Push((startNode, new Stack<TNode>(subGraph.Neighbors(startNode))));
while (stack.Count > 0)
{
var entry = stack.Peek();
var thisnode = entry.Item1;
var neighbors = entry.Item2;
if (neighbors.Count > 0)
{
var nextNode = neighbors.Pop();
if (nextNode.Equals(startNode))
{
var resultPath = new List<TNode>();
foreach (var v in path)
{
resultPath.Add(v);
}
result.Add(resultPath);
foreach (var v in path)
{
closed.Add(v);
}
}
else if (!blocked.Contains(nextNode))
{
path.Push(nextNode);
stack.Push((nextNode, new Stack<TNode>(subGraph.Neighbors(nextNode))));
closed.Remove(nextNode);
blocked.Add(nextNode);
continue;
}
}
if (neighbors.Count == 0)
{
if (closed.Contains(thisnode))
{
unblock(thisnode, blocked, B);
}
else
{
foreach (var neighbor in subGraph.Neighbors(thisnode))
{
if (!B.ContainsKey(neighbor))
{
B[neighbor] = new HashSet<TNode>();
}
B[neighbor].Add(thisnode);
}
}
stack.Pop();
path.Pop();
}
}
subGraph.RemoveNode(startNode);
var H = subGraph.SubGraph(scc.ToArray());
var HSccs = H.StronglyConnectedComponents();
foreach (var HScc in HSccs)
{
sccs.Push(HScc);
}