using System.Runtime.CompilerServices;
namespace OECS;
///
/// Registry of all component sparse sets, keyed by component type.
/// Provides typed generic accessors that delegate to the underlying
/// instances.
///
internal class ComponentStore
{
private readonly Dictionary _sets = new();
///
/// Gets or creates the sparse set for component type .
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private SparseSet GetSet() where T : struct
{
var type = typeof(T);
if (!_sets.TryGetValue(type, out var set))
{
var newSet = new SparseSet();
_sets[type] = newSet;
return newSet;
}
return (SparseSet)set;
}
///
/// Gets the sparse set for component type if it exists.
///
private SparseSet? GetSetIfExists() where T : struct
{
if (_sets.TryGetValue(typeof(T), out var set))
return (SparseSet)set;
return null;
}
///
/// Returns all registered component types.
///
public IEnumerable ComponentTypes => _sets.Keys;
public void Add(Entity entity, T component) where T : struct
{
GetSet().Add(entity, component);
}
public void Remove(Entity entity) where T : struct
{
GetSetIfExists()?.Remove(entity);
}
public ref T Get(Entity entity) where T : struct
{
return ref GetSet().Get(entity);
}
public bool Has(Entity entity) where T : struct
{
return GetSetIfExists()?.Contains(entity) ?? false;
}
///
/// Removes all components for the given entity across all component types.
///
public void RemoveAll(Entity entity)
{
foreach (var set in _sets.Values)
{
set.Remove(entity);
}
}
///
/// Returns the sparse set for a given type, or null if not registered.
/// Used by query execution to probe sets by Type.
///
public ISparseSet? GetSet(Type componentType)
{
_sets.TryGetValue(componentType, out var set);
return set;
}
///
/// Returns the count of entities in the sparse set for type .
/// Returns 0 if the set does not exist.
///
public int Count() where T : struct
{
return GetSetIfExists()?.Count ?? 0;
}
///
/// Returns the count of entities in the sparse set for the given type.
/// Returns 0 if the set does not exist.
///
public int Count(Type componentType)
{
return GetSet(componentType)?.Count ?? 0;
}
}