Files
riversong-code-showcase/Source/Riversong/Game/CommonServices/Entities/EntityCache/EntityCacheSystem.cs
2026-05-21 16:04:49 +02:00

71 lines
3.0 KiB
C#

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<Entity>();
callbacks.Added += _entityCache.OnAdded;
callbacks.Removed += _entityCache.OnRemoved;
return UniTask.CompletedTask;
}
private void CreateCaches()
{
_entityCache.CreateCache<Building>((int)EntityCacheKeys.HarvesterBuildings, b => b.Definition.HarvestedResource);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.HunterBuildings, b => b.Definition.TargetCritter);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.FarmBuildings, b => b.Definition.IsFarm);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.ProducerBuildings, b => b.Definition.Recipe);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.ProviderBuildings, b => b.Definition.ProvidedProducts.Count > 0);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.BuildingsWithWorkers, b => b.Definition.WorkerCount > 0);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.HouseBuildings, b => b.Definition.IsHouse);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.StorageBuildings, b => b.Definition.IsStorage);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.StorageRequestBuildings, b => b.Definition.IsStorage);
_entityCache.CreateCache<Building>((int)EntityCacheKeys.TentBuildings, b => b.Definition == _config.Population.TentBuilding.Asset);
_entityCache.CreateCache<Agent>(
(int)EntityCacheKeys.HunterAgents,
a =>
{
ref var jobState = ref a.GetJobStateRW();
return jobState.Job == AgentJob.Hunter;
});
_entityCache.CreateCache<Agent>(
(int)EntityCacheKeys.CritterAgents,
a =>
{
ref var critterState = ref a.GetCritterStateRW();
return critterState.IsCritter;
});
}
public void Dispose()
{
var callbacks = _entityCollection.On<Entity>();
callbacks.Added -= _entityCache.OnAdded;
callbacks.Removed -= _entityCache.OnRemoved;
}
}
}