using System; using System.Collections.Generic; namespace MoonTools.ECS { internal class RelationDepot { private Dictionary storages = new Dictionary(); private void Register() where TRelationKind : unmanaged { if (!storages.ContainsKey(typeof(TRelationKind))) { storages.Add(typeof(TRelationKind), new RelationStorage()); } } private RelationStorage Lookup() where TRelationKind : unmanaged { Register(); return (RelationStorage) storages[typeof(TRelationKind)]; } public void Set(Relation relation, TRelationKind relationData) where TRelationKind : unmanaged { Lookup().Set(relation, relationData); } public void Remove(Relation relation) where TRelationKind : unmanaged { Lookup().Remove(relation); } // FIXME: optimize this public void OnEntityDestroy(int entityID) { foreach (var storage in storages.Values) { storage.OnEntityDestroy(entityID); } } public IEnumerable<(Entity, Entity, TRelationKind)> Relations() where TRelationKind : unmanaged { return Lookup().All(); } public bool Related(int idA, int idB) where TRelationKind : unmanaged { return Lookup().Has(new Relation(idA, idB)); } public IEnumerable<(Entity, TRelationKind)> RelatedToA(int entityID) where TRelationKind : unmanaged { return Lookup().RelatedToA(entityID); } public IEnumerable<(Entity, TRelationKind)> RelatedToB(int entityID) where TRelationKind : unmanaged { return Lookup().RelatedToB(entityID); } public void Save(RelationDepotState state) { foreach (var (type, storage) in storages) { if (!state.StorageStates.ContainsKey(type)) { state.StorageStates.Add(type, storage.CreateState()); } storage.Save(state.StorageStates[type]); } } public void Load(RelationDepotState state) { foreach (var (type, storageState) in state.StorageStates) { storages[type].Load(storageState); } } } }