using System; using Cysharp.Threading.Tasks; namespace DanieleMarotta.RiversongCodeShowcase { [GameSystemGroup(typeof(EarlyGameSystemGroup))] [InitializeAfter(typeof(PreLoadAssetsSystem))] public class EntityCacheSystem : GameSystem, IInitializable, IDisposable { [InjectService] private IEntityCollection _entityCollection; [InjectService] private IEntityCache _entityCache; [InjectService] private GameConfig _config; public EntityCacheSystem(IServiceLocator serviceLocator) : base(serviceLocator) { } public UniTask InitializeAsync() { CreateCaches(); foreach (var entity in _entityCollection.GetInternalEntityList(typeof(Entity))) _entityCache.OnAdded(entity); var callbacks = _entityCollection.On(); callbacks.Added += _entityCache.OnAdded; callbacks.Removed += _entityCache.OnRemoved; return UniTask.CompletedTask; } private void CreateCaches() { _entityCache.CreateCache((int)EntityCacheKeys.HarvesterBuildings, b => b.Definition.HarvestedResource); _entityCache.CreateCache((int)EntityCacheKeys.HunterBuildings, b => b.Definition.TargetCritter); _entityCache.CreateCache((int)EntityCacheKeys.FarmBuildings, b => b.Definition.IsFarm); _entityCache.CreateCache((int)EntityCacheKeys.ProducerBuildings, b => b.Definition.Recipe); _entityCache.CreateCache((int)EntityCacheKeys.ProviderBuildings, b => b.Definition.ProvidedProducts.Count > 0); _entityCache.CreateCache((int)EntityCacheKeys.BuildingsWithWorkers, b => b.Definition.WorkerCount > 0); _entityCache.CreateCache((int)EntityCacheKeys.HouseBuildings, b => b.Definition.IsHouse); _entityCache.CreateCache((int)EntityCacheKeys.StorageBuildings, b => b.Definition.IsStorage); _entityCache.CreateCache((int)EntityCacheKeys.StorageRequestBuildings, b => b.Definition.IsStorage); _entityCache.CreateCache((int)EntityCacheKeys.TentBuildings, b => b.Definition == _config.Population.TentBuilding.Asset); _entityCache.CreateCache( (int)EntityCacheKeys.HunterAgents, a => { ref var jobState = ref a.GetJobStateRW(); return jobState.Job == AgentJob.Hunter; }); _entityCache.CreateCache( (int)EntityCacheKeys.CritterAgents, a => { ref var critterState = ref a.GetCritterStateRW(); return critterState.IsCritter; }); } public void Dispose() { var callbacks = _entityCollection.On(); callbacks.Added -= _entityCache.OnAdded; callbacks.Removed -= _entityCache.OnRemoved; } } }