encompass-cs/encompass-cs/Collections/TypedComponentStore.cs

77 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
namespace Encompass
{
internal abstract class TypedComponentStore
{
public abstract int Count { get; }
public abstract IEnumerable<(Entity, Type, IComponent)> AllInterfaceTyped();
public abstract bool Has(Entity entity);
public abstract void Remove(Entity entity);
public abstract void Clear();
}
internal class TypedComponentStore<TComponent> : TypedComponentStore where TComponent : struct, IComponent
{
private readonly Dictionary<Entity, TComponent> store = new Dictionary<Entity, TComponent>(128);
private readonly Dictionary<Entity, int> priorities = new Dictionary<Entity, int>(128);
public override int Count { get => store.Count; }
public TComponent Get(Entity entity)
{
return store[entity];
}
public void Set(Entity entity, TComponent component)
{
store[entity] = component;
}
public bool Set(Entity entity, TComponent component, int priority)
{
if (!priorities.ContainsKey(entity) || priority < priorities[entity]) {
store[entity] = component;
priorities[entity] = priority;
return true;
}
return false;
}
public override bool Has(Entity entity)
{
return store.ContainsKey(entity);
}
public override void Clear()
{
store.Clear();
priorities.Clear();
}
public IEnumerable<(TComponent, Entity)> All()
{
foreach (var kvp in store)
{
yield return (kvp.Value, kvp.Key);
}
}
public override IEnumerable<(Entity, Type, IComponent)> AllInterfaceTyped()
{
foreach (var kvp in store)
{
yield return (kvp.Key, typeof(TComponent), (IComponent)kvp.Value);
}
}
public override void Remove(Entity entity)
{
store.Remove(entity);
priorities.Remove(entity);
}
}
}