Skip to content

Game.Simulation.GarbageFacilityAISystem

Assembly: Assembly-CSharp.dll
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
GarbageFacilityAISystem is the simulation system responsible for driving the in-game behavior of garbage facilities (processing of garbage, creating and dispatching garbage trucks and delivery trucks, handling transfer/collection requests, updating facility priorities and notification icons). It uses Unity DOTS-style jobs to iterate facility entities (GarbageFacility components + ServiceDispatch buffers) and performs per-facility logic in a Burst-compiled IJobChunk (GarbageFacilityTickJob). A small follow-up IJob (GarbageFacilityActionJob) consumes queued actions (e.g. enable/disable garbage trucks). The system also manages archetypes/queries and communicates with other systems (vehicle selection, icon commands, simulation system, end-frame barrier).


Fields

  • private VehicleCapacitySystem m_VehicleCapacitySystem
    Reference to the system that provides delivery truck selection/capacity info used when spawning delivery trucks.

  • private EndFrameBarrier m_EndFrameBarrier
    Barrier used to produce EntityCommandBuffer operations that are executed at end of frame. The tick job writes commands via the parallel writer returned by this barrier.

  • private SimulationSystem m_SimulationSystem
    Used to get the current simulation frame index and other simulation-wide information.

  • private IconCommandSystem m_IconCommandSystem
    Used to add/remove building notification icons (e.g. "facility full" notification).

  • private CityConfigurationSystem m_CityConfigurationSystem
    Reference used when preparing vehicle selection (through GarbageTruckSelectData).

  • private GarbageTruckSelectData m_GarbageTruckSelectData
    Utility that encapsulates logic to pick/create garbage trucks for spawning. Pre/Post-update hooks are used to set up selection data.

  • private EntityQuery m_BuildingQuery
    Query matching garbage facility entities (GarbageFacility + ServiceDispatch etc.) that this system updates.

  • private EntityQuery m_GarbageTruckPrefabQuery
    Query used by the GarbageTruckSelectData to prepare available truck prefabs.

  • private EntityQuery m_GarbageSettingsQuery
    Query to fetch singleton GarbageParameterData (game-wide garbage parameters).

  • private EntityArchetype m_GarbageTransferRequestArchetype
    Archetype used to create GarbageTransferRequest entities.

  • private EntityArchetype m_GarbageCollectionRequestArchetype
    Archetype used to create GarbageCollectionRequest (service request) entities.

  • private EntityArchetype m_HandleRequestArchetype
    Archetype used to create HandleRequest entities (to mark request handling).

  • private ComponentTypeSet m_ParkedToMovingRemoveTypes
    Component set that is removed from parked cars when converting to moving vehicles.

  • private ComponentTypeSet m_ParkedToMovingCarAddTypes
    Component set that is added to a car when converting from parked to moving (moving, lane data, path ownership, etc.).

  • private TypeHandle __TypeHandle
    Internal structure collecting cached Component/Buffer/Lookup type handles used by the job. Populated in OnCreateForCompiler / __AssignHandles.

  • Nested/Related private data types (described below): GarbageFacilityAction, GarbageFacilityTickJob, GarbageFacilityActionJob, TypeHandle.


Properties

  • (No public properties exposed by this system.)

Constructors

  • public GarbageFacilityAISystem()
    Default constructor. The system overrides OnCreate to initialize queries, archetypes, and references to other systems.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval (in frames) for the system. This system returns 256 (kUpdatesPerDay / 4 in this code, used by scheduling logic).

  • public override int GetUpdateOffset(SystemUpdatePhase phase)
    Returns the update frame offset. This system uses an offset of 80 to stagger updates.

  • [Preserve] protected override void OnCreate()
    Initialize references to supporting systems (VehicleCapacitySystem, EndFrameBarrier, IconCommandSystem, SimulationSystem, CityConfigurationSystem). Create queries (garbage facilities, settings, truck prefabs) and create the request/handle archetypes. Prepare ComponentTypeSet lists used to transition parked vehicles to moving. Calls RequireForUpdate for essential queries. Also prepares m_GarbageTruckSelectData.

  • [Preserve] protected override void OnUpdate()
    Main scheduling method. It:

  • Calls PreUpdate on GarbageTruckSelectData (prepares truck selection state).
  • Allocates a NativeQueue to collect actions produced by the per-facility job.
  • Constructs a GarbageFacilityTickJob (IJobChunk) and schedules it in parallel over the building query.
  • Schedules a GarbageFacilityActionJob (IJob) to consume the action queue and toggle garbage truck disabled state.
  • Registers produced JobHandles with IconCommandSystem and EndFrameBarrier and updates base.Dependency appropriately. The tick job performs the per-facility logic (processing rates, spawning vehicles, creating requests, updating priorities, icons and flags).

  • private static float CalculateProcessingRate(float maxProcessingRate, float efficiency, int garbageAmount, int garbageCapacity)
    Computes the actual processing rate of the facility based on efficiency and a factor derived from how full the facility is. Uses CalculateGarbageAmountFactor internally.

  • private static float CalculateGarbageAmountFactor(int garbageAmount, int garbageCapacity)
    Returns a factor in [0,1] that scales with garbage fill level: saturate(0.1 + 1.8 * garbageAmount / max(1, garbageCapacity)). Used to bias processing towards fuller facilities.

  • protected override void OnCreateForCompiler()
    Internal initialization used by generated code paths: assigns query handles and caches component handles via TypeHandle.__AssignHandles.

  • private void __AssignQueries(ref SystemState state)
    Internal helper invoked by OnCreateForCompiler. (Generated code stub in this build.)

  • Additional private helper methods (inside the GarbageFacilityTickJob) — these are part of the job and not directly callable from outside but are important to the system's behavior:

  • QuantityUpdated(...) — recursively marks quantity/batches updates for subobjects (updates subobject state when amounts change).
  • AddResourceProductionData(...) / CombineResourceProductionData(...) — combine resource production buffers from the facility prefab and installed upgrades.
  • ProcessAreas(...) — moves garbage between facility and linked storage areas (subareas), respecting area storage capacity, processing speed and facility parameters.
  • Tick(...) — core per-facility logic executed for each facility chunk/instance: handles outside-connection fill, processing rate calculation, updating resource production outputs, managing owned and guest vehicles, trying to spawn garbage or delivery trucks for dispatch requests, adjusting priorities, creating transfer or collection requests, toggling facility flags, and adding/removing notification icons.
  • RequestTargetIfNeeded(...) — ensures a periodic GarbageCollectionRequest is created if the facility needs target gathering and has available vehicles.
  • TrySpawnGarbageTruck(...) — attempts to spawn or wake a parked garbage truck in response to a GarbageCollectionRequest. Handles parked->moving transitions, truck creation, ownership and path handoff.
  • TrySpawnDeliveryTruck(...) — attempts to spawn delivery trucks to ferry garbage between facilities according to GarbageTransferRequest; sets up loaded/buying flags, adjusts available counts and paths.

Nested types (brief):

  • GarbageFacilityAction (nested struct)
    Small POD describing an action to set a garbage truck disabled/enabled; enqueued by the tick job to be executed later by GarbageFacilityActionJob.

  • GarbageFacilityTickJob (nested struct, BurstCompile, implements IJobChunk)
    The Burst-compiled IJobChunk that iterates facility chunks, reads/writes many component types and buffers and performs the per-facility tick logic described above. It writes entity commands via m_CommandBuffer and icon commands via m_IconCommandBuffer. It uses a RandomSeed and the SimulationSystem frame index for deterministic/randomized behavior.

  • GarbageFacilityActionJob (nested struct, BurstCompile, implements IJob)
    Reads the queued GarbageFacilityAction items and updates the GarbageTruck component (toggles the Disabled bit).

  • TypeHandle (nested struct)
    Internal structure for caching ComponentTypeHandle, BufferTypeHandle and ComponentLookup handles used by the job(s). Assigned from SystemState in OnCreateForCompiler.


Usage Example

Example: from a mod/system that wants to update a GarbageFacility component on a building entity (toggle a flag or read processing rate counters). Typical pattern is to get the EntityManager and read/write component data. Note: most internal fields and helper methods are private; interaction is normally done by creating requests (GarbageTransferRequest/GarbageCollectionRequest) or by modifying component data on entities.

// Example snippet: toggling a flag on a garbage facility component of an entity
var em = World.DefaultGameObjectInjectionWorld.EntityManager;
if (em.HasComponent<Game.Buildings.GarbageFacility>(facilityEntity))
{
    var gf = em.GetComponentData<Game.Buildings.GarbageFacility>(facilityEntity);
    // Set or clear a custom flag (example uses HasAvailableSpace as a demo; in-game flags are managed by the system)
    gf.m_Flags |= Game.Buildings.GarbageFacilityFlags.HasAvailableSpace;
    em.SetComponentData(facilityEntity, gf);
}

// Example snippet: creating a GarbageTransferRequest entity (useful to request deliveries)
var archetype = em.CreateArchetype(
    typeof(ServiceRequest),
    typeof(Game.Simulation.GarbageTransferRequest),
    typeof(RequestGroup)
);
var req = em.CreateEntity(archetype);
em.SetComponentData(req, new RequestGroup { m_Group = 8u });
em.SetComponentData(req, new Game.Simulation.GarbageTransferRequest(
    source: facilityEntity,
    flags: Game.Simulation.GarbageTransferRequestFlags.Deliver,
    priority: 0.5f,
    amount: 200
));

(When modding, prefer using the available public request types and archetypes to interact with the garbage system instead of directly manipulating private internals.)