encompass-cs/encompass-cs/ComponentBitSet.cs

76 lines
2.2 KiB
C#
Raw Normal View History

using System;
using System.Collections;
using System.Collections.Generic;
namespace Encompass
{
internal class ComponentBitSet
{
2019-12-20 19:28:56 +00:00
BitArrayPool bitArrayPool = new BitArrayPool(32768); // todo: set entity cap
Dictionary<Entity, BitArray> entities = new Dictionary<Entity, BitArray>();
2019-12-22 09:15:58 +00:00
Dictionary<Type, int> TypeToIndex { get; set; }
BitArray withQueryArray;
BitArray withoutQueryArray;
BitArray emptyArray;
2019-12-22 09:15:58 +00:00
public ComponentBitSet(Dictionary<Type, int> typeToIndex)
{
2019-12-22 09:15:58 +00:00
TypeToIndex = typeToIndex;
}
public void FinishRegistering()
{
2019-12-22 09:15:58 +00:00
withQueryArray = new BitArray(TypeToIndex.Count);
withoutQueryArray = new BitArray(TypeToIndex.Count);
emptyArray = new BitArray(TypeToIndex.Count);
foreach (var kvp in entities)
{
kvp.Value.Length = TypeToIndex.Count;
}
}
public void Clear()
{
2019-12-20 19:28:56 +00:00
foreach (var kvp in entities)
{
bitArrayPool.Free(kvp.Value);
}
entities.Clear();
}
public void AddEntity(Entity entity)
{
2019-12-22 09:15:58 +00:00
var bitArray = bitArrayPool.Obtain(TypeToIndex.Count);
2019-12-20 19:28:56 +00:00
entities.Add(entity, bitArray);
}
public void Set<TComponent>(Entity entity) where TComponent : struct, IComponent
{
if (!entities.ContainsKey(entity)) { AddEntity(entity); }
2019-12-22 09:15:58 +00:00
entities[entity].Set(TypeToIndex[typeof(TComponent)], true);
}
public void RemoveComponent<TComponent>(Entity entity) where TComponent : struct, IComponent
{
if (entities.ContainsKey(entity))
{
entities[entity].Set(TypeToIndex[typeof(TComponent)], false);
}
}
2019-12-20 19:28:56 +00:00
public void RemoveEntity(Entity entity)
{
2019-12-20 19:28:56 +00:00
if (entities.ContainsKey(entity))
{
bitArrayPool.Free(entities[entity]);
entities.Remove(entity);
}
}
2019-12-22 09:15:58 +00:00
public BitArray EntityBitArray(Entity entity)
{
2019-12-22 09:15:58 +00:00
return entities.ContainsKey(entity) ? entities[entity] : emptyArray;
}
}
}