Skip to content

Game.Simulation.MaintenanceVehicleDispatchSystem

Assembly: Game (Game.dll)
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
MaintenanceVehicleDispatchSystem is the ECS system that drives maintenance vehicle dispatching in the simulation. It processes MaintenanceRequest entities, validates requests and targets, sets up pathfinding for requests (origin -> destination or reverse), and enqueues actual vehicle dispatches. The system uses Burst-compiled jobs (MaintenanceVehicleDispatchJob and DispatchVehiclesJob), schedules pathfinding via PathfindSetupSystem, reads area data from the AreaSearchSystem, and defers structural changes through an EndFrameBarrier command buffer. It runs at a coarse interval (every 16 simulation frames) and uses parallel job scheduling and native queues for scalability. This system contains the bulk of logic for finding suitable vehicle sources, validating targets/handlers, resetting failed requests, and ultimately creating service dispatch entries.


Fields

  • private EndFrameBarrier m_EndFrameBarrier
    Used to obtain a command buffer (parallel writer) for structural changes (add/remove components, destroy entities). Changes are applied at end-of-frame to keep job safety.

  • private SimulationSystem m_SimulationSystem
    Reference to the main simulation system; used to read the global frameIndex and compute update-frame indices.

  • private PathfindSetupSystem m_PathfindSetupSystem
    Used to enqueue pathfind setup requests (SetupQueueItem) when a maintenance request needs pathfinding (either to find a vehicle or to send a vehicle to a target).

  • private Game.Areas.SearchSystem m_AreaSearchSystem
    Provides a read-only area search tree used to resolve district/area entities from world positions when searching vehicle sources.

  • private EntityQuery m_RequestQuery
    Query used to select entities that have MaintenanceRequest and UpdateFrame so this system only runs/update when such requests exist.

  • private TypeHandle __TypeHandle
    Internal container for EntityType/ComponentType/ComponentLookup/BufferLookup handles. Assigned on creation to speed access in OnUpdate.

  • private struct VehicleDispatch (private nested struct)
    Small pair struct { Entity m_Request; Entity m_Source; } used to enqueue dispatches from the chunk job to the DispatchVehiclesJob via a NativeQueue.

  • private struct MaintenanceVehicleDispatchJob (private nested, [BurstCompile], implements IJobChunk)
    Chunk job that iterates request entities and:

  • Ticks ServiceRequest timing.
  • Validates targets (ValidateTarget) and reversed-mode sources (ValidateReversed).
  • Enqueues pathfinding setup requests (FindVehicleSource / FindVehicleTarget).
  • Adds PathInformation / PathElement buffers/components when needed.
  • Converts completed path results to vehicle dispatches (DispatchVehicle/ResetReverseRequest/ResetFailedRequest).
  • Enqueues VehicleDispatchs into a NativeQueue for final dispatch.

Note: This job contains many internal helper functions (ValidateReversed, ValidateHandler, ValidateTarget, ResetReverseRequest, ResetFailedRequest, DispatchVehicle, FindVehicleSource, FindVehicleTarget) that operate on ComponentLookups / BufferLookups inside the job.

  • private struct DispatchVehiclesJob (private nested, [BurstCompile], implements IJob)
    Single-threaded job that dequeues VehicleDispatch from a NativeQueue and either:
  • Adds a ServiceDispatch buffer entry on the source entity (if it already has a buffer), or
  • Flips the source's ServiceRequest to skip cooldown so the source will be processed (if no buffer exists yet).

  • private struct TypeHandle (private nested struct)
    Aggregates many EntityTypeHandle / ComponentTypeHandle / ComponentLookup / BufferLookup instances used by the jobs. Assigned via __AssignHandles to the current SystemState.

Properties

  • No public properties on this system.
    All job and internal handles are private; interaction with this system is via creating MaintenanceRequest / ServiceRequest entities or by reading simulation state.

Constructors

  • public MaintenanceVehicleDispatchSystem()
    Default constructor (empty). The system is set up by the world during creation; important initialization happens in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns 16. The system is scheduled to run at a coarse frequency (every 16 simulation frames) to reduce cost; the implementation computes update-frame indices and operates only on requests whose UpdateFrame shared component matches the job frame index logic.

{{ The system uses (m_SimulationSystem.frameIndex >> 4) & 0x1F to compute the current update index and schedules work for requests with a nextUpdateFrameIndex. This reduces how frequently individual requests are processed. }}

  • [Preserve] protected override void OnCreate()
    Initializes system references and query:
  • Acquires EndFrameBarrier, SimulationSystem, PathfindSetupSystem, Game.Areas.SearchSystem from World.
  • Builds m_RequestQuery for entities with MaintenanceRequest and UpdateFrame.
  • Calls RequireForUpdate(m_RequestQuery) so the system only runs when relevant entities exist.

{{ This is where TypeHandles are not yet assigned; the full handle assignment happens in OnCreateForCompiler / __AssignHandles. }}

  • [Preserve] protected override void OnUpdate()
    Main scheduling method. Key responsibilities:
  • Computes current and next update-frame indices from SimulationSystem.frameIndex.
  • Creates a NativeQueue to transfer dispatches from parallel chunk job to a single-threaded finalization job.
  • Builds and schedules MaintenanceVehicleDispatchJob (IJobChunk, Burst) with many component lookups and buffer lookups; the job:
    • Validates and ticks ServiceRequest, MaintenanceRequest.
    • Enqueues pathfinding (via PathfindSetupSystem queue writer) when needed.
    • Adds PathInformation and PathElement buffers/components and sets up Pathfind requests.
    • Adds Dispatched components and enqueues VehicleDispatch items.
  • Builds and schedules DispatchVehiclesJob which consumes VehicleDispatch queue to write ServiceDispatch buffers or set ServiceRequest flags on source entities.
  • Connects job dependencies to PathfindSetupSystem, AreaSearchSystem, and EndFrameBarrier, and disposes the queue when safe.

{{ Important notes for modders: - The heavy work is executed inside Burst jobs and uses ComponentLookup/BufferLookup — do not attempt to access managed objects or UnityEngine APIs in those jobs. - Pathfinding setup is enqueued via PathfindSetupSystem; the actual pathfinding is handled elsewhere. - Structural changes are done through EndFrameBarrier's parallel command buffer to preserve job safety. - This method is where maintenance request lifecycle transitions happen (request -> pathfinding -> dispatched -> eventual handler). }}

  • private void __AssignQueries(ref SystemState state)
    Internal helper used for compiler-generated code; currently a no-op placeholder that constructs an EntityQueryBuilder and disposes it. Used during OnCreateForCompiler.

  • protected override void OnCreateForCompiler()
    Internal setup invoked by generated code / compiler-time helpers. Calls __AssignQueries and assigns TypeHandle handles via __TypeHandle.__AssignHandles(ref state). Modders typically do not need to call or modify this.

  • (Nested job methods) MaintenanceVehicleDispatchJob.Execute / DispatchVehiclesJob.Execute

  • Execute() in MaintenanceVehicleDispatchJob: operates per-chunk, handles both "next frame index" pre-pathfind ticking and the "current frame index" post-pathfind processing, including ValidateTarget/ValidateReversed, ResetFailedRequest, ResetReverseRequest, DispatchVehicle, FindVehicleSource, FindVehicleTarget.
  • Execute() in DispatchVehiclesJob: dequeues enqueued VehicleDispatch structs and applies the final dispatch (ServiceDispatch buffer or ServiceRequest flag change) on the main thread.

{{ The nested job functions implement the bulk of selection/validation logic, including: - ValidateTarget: ensure the target can accept maintenance (checks MaintenanceConsumer, Park maintenance priority, Net condition priority) and reserves the request as the consumer's m_Request. - ValidateReversed: ensure a depot or vehicle source can accept a reversed (source-driven) request and reserves the request on the source. - FindVehicleSource / FindVehicleTarget: prepare PathfindParameters and SetupQueueTargets and enqueue SetupQueueItem into PathfindSetupSystem's queue. - ResetFailedRequest: increments dispatch index and clears PathInformation/PathElement and Dispatched components where appropriate. }}

Usage Example

// The system itself is a world system and is created/managed by the World.
// Typical modding interaction is to create a MaintenanceRequest + ServiceRequest entity,
// then let this system handle pathfinding and dispatching.
// Example: show standard OnCreate override used in the system to acquire required systems.

[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    m_EndFrameBarrier = base.World.GetOrCreateSystemManaged<EndFrameBarrier>();
    m_SimulationSystem = base.World.GetOrCreateSystemManaged<SimulationSystem>();
    m_PathfindSetupSystem = base.World.GetOrCreateSystemManaged<PathfindSetupSystem>();
    m_AreaSearchSystem = base.World.GetOrCreateSystemManaged<Game.Areas.SearchSystem>();
    m_RequestQuery = GetEntityQuery(ComponentType.ReadOnly<MaintenanceRequest>(), ComponentType.ReadOnly<UpdateFrame>());
    RequireForUpdate(m_RequestQuery);
}

Additional notes for modders: - To request maintenance, create a MaintenanceRequest entity together with a ServiceRequest component and an UpdateFrame shared component (so the system picks it up). The system will handle ticking ServiceRequest.m_Cooldown, pathfinding setup, and dispatching vehicles or resetting failed requests. - Because most work is done in Burst jobs, follow the same restrictions as Jobs: avoid managed references in data passed to jobs and use ComponentLookup / BufferLookup where appropriate. - If you need to observe when a dispatch occurs, monitor the ServiceDispatch buffer on vehicle/depot entities or inspect Dispatched/PathInformation components on request entities. - The system is tuned to treat parks, net deterioration, and different maintenance types (via prefab maintenance data) differently when calculating targets and available sources.