Skip to content

Game.Simulation.RandomTrafficDispatchSystem

Assembly: Assembly-CSharp (game runtime)
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
System responsible for processing RandomTrafficRequest entities: it validates targets, starts pathfinding to find vehicle sources, marks entities as dispatched, and enqueues vehicle dispatches to be recorded on source spawners. The system uses chunked jobs (IJobChunk) for parallel processing, sets up pathfinding requests via PathfindSetupSystem, and posts final service dispatches at end-of-frame through an EndFrameBarrier. It also implements cooldown/failure reset logic for service requests and respects UpdateFrame shared-component scheduling to spread work across frames.


Fields

  • private EndFrameBarrier m_EndFrameBarrier
    Holds the EndFrameBarrier system used to create a parallel EntityCommandBuffer and to add job producer dependencies. Ensures entity command buffer changes are applied at the proper point in the frame.

  • private SimulationSystem m_SimulationSystem
    Reference to the main simulation system; used to read frameIndex and loadingProgress to determine scheduling/spacing of updates.

  • private PathfindSetupSystem m_PathfindSetupSystem
    Reference to the pathfinding setup system used to enqueue new pathfinding setup requests (SetupQueueItem) for RandomTrafficRequest entities.

  • private EntityQuery m_RequestQuery
    EntityQuery that selects entities containing RandomTrafficRequest and UpdateFrame (read-only). Used to drive the system's execution (RequireForUpdate).

  • private TypeHandle __TypeHandle
    Internal struct bundling Entity/Component/Buffer/Shared component handles and lookups used by jobs. Populated on creation for efficient access in jobs.

Properties

  • None (this system exposes no public properties).

Constructors

  • public RandomTrafficDispatchSystem()
    Default parameterless constructor. The system performs initialization in OnCreate where it grabs references to other systems and establishes the required EntityQuery.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval in frames for different phases. In LoadSimulation phase returns 1 (every frame). In other phases returns 16. This determines how frequently the system is considered for update scheduling by the game's system manager.

  • [Preserve] protected override void OnCreate()
    Initializes system references: obtains EndFrameBarrier, SimulationSystem, PathfindSetupSystem and creates the EntityQuery for RandomTrafficRequest + UpdateFrame. Calls RequireForUpdate(m_RequestQuery) so the system runs only when there are matching requests.

  • [Preserve] protected override void OnUpdate()
    Main scheduling method. Builds and schedules two jobs:

  • RandomTrafficDispatchJob (IJobChunk, Burst compiled): iterates request chunks, validates targets/spawners, ticks ServiceRequest cooldowns, sets up pathfinding (enqueues SetupQueueItem), handles dispatched/path-information results, and enqueues VehicleDispatch items into a NativeQueue for later recording.
  • DispatchVehiclesJob (IJob, Burst compiled): dequeues VehicleDispatch items and appends ServiceDispatch entries to source spawners' buffers. The method calculates update-frame indices (m_UpdateFrameIndex and m_NextUpdateFrameIndex) based on SimulationSystem.frameIndex and loadingProgress to stagger processing across frames. It wires job dependencies, disposes the NativeQueue with the correct dependency, registers the pathfind queue writer, and registers the producer job handle with the EndFrameBarrier command buffer.

  • protected override void OnCreateForCompiler()
    Internal helper used at compile-time by the generated code path: assigns queries and component type handles via __AssignQueries and TypeHandle.__AssignHandles. Not normally invoked by user code.

  • [MethodImpl(MethodImplOptions.AggressiveInlining)] private void __AssignQueries(ref SystemState state)
    Internal method used by the compiler-generated scaffolding to create/assign any EntityQuery builders. In this implementation it creates & disposes a temporary EntityQueryBuilder to ensure proper internal setup.

  • private struct TypeHandle
    Nested helper struct that stores EntityTypeHandle, ComponentTypeHandle, SharedComponentTypeHandle, ComponentLookup and BufferLookup instances. Method __AssignHandles(ref SystemState) initializes all handles from the given SystemState. Used to pass handles into burst jobs.

  • private struct RandomTrafficDispatchJob : IJobChunk (nested)
    Burst-compiled IJobChunk that performs the bulk of the logic for RandomTrafficRequest processing:

  • Reads chunk UpdateFrame shared component and only processes requests for decorated update indices.
  • Validates TrafficSpawner targets and assigns the spawner's m_TrafficRequest to the request entity if not already set.
  • Ticks ServiceRequest (SimulationUtils.TickServiceRequest) and, when it's time, selects a vehicle source by enqueuing a pathfind SetupQueueItem (via PathfindSetupSystem queue) and adding PathInformation and PathElement buffer components to the request entity.
  • When PathInformation is present with a valid origin, enqueues a VehicleDispatch (request entity + origin spawner) into an output NativeQueue and adds Dispatched component to the request entity.
  • When dispatched/pathfinding fails, resets the ServiceRequest failure/cooldown state and removes PathInformation/PathElement/Dispatched as appropriate.
  • Uses a RandomSeed per job to randomly pick search strategies (swap start/target) and configures PathfindParameters based on RoadTypes, TrackTypes, size class, and energy type flags.

  • private struct DispatchVehiclesJob : IJob (nested)
    Burst-compiled job that consumes the NativeQueue produced by RandomTrafficDispatchJob and appends ServiceDispatch entries to the TrafficSpawner (source) entity's buffer. This is the final step that registers the dispatched request with the spawner so that a vehicle can be spawned later.

  • Several small helper methods inside RandomTrafficDispatchJob (private):

  • ValidateHandler(Entity, Entity) : checks if a handler spawner's ServiceDispatch buffer contains the request (used when processing Dispatched components).
  • ValidateTarget(Entity, Entity) : verifies and registers that the TrafficSpawner target is valid and associates the request with the spawner.
  • ResetFailedRequest(int, Entity, bool dispatched, ref ServiceRequest) : resets a failed request (cooldown etc.) and removes PathInformation/PathElement and possibly Dispatched components via the parallel ECB.
  • DispatchVehicle(int, Entity, PathInformation) : enqueues a VehicleDispatch and adds Dispatched component to the request entity.
  • FindVehicleSource(int, ref Random, Entity, RandomTrafficRequest) : sets up PathfindParameters and SetupQueueTargets based on the request (road/track types, size, flags), randomly orders source/target selection, enqueues a SetupQueueItem to start pathfinding, and adds empty PathInformation and PathElement buffer components to the request entity.

Usage Example

// Example: create a RandomTrafficRequest entity pointing at a spawner and let the system process it.
// (This is illustrative — adapt to the game's entity/component creation helpers.)

Entity request = entityManager.CreateEntity();
entityManager.AddComponentData(request, new RandomTrafficRequest {
    m_Target = spawnerEntity,            // the TrafficSpawner building/entity
    m_RoadType = RoadTypes.Car,          // allowed road types
    m_TrackType = TrackTypes.None,
    m_SizeClass = VehicleSizeClass.Small,
    m_Flags = RandomTrafficRequestFlags.None,
    m_EnergyTypes = EnergyTypes.Any
});
entityManager.AddComponentData(request, new ServiceRequest {
    m_Cooldown = 0,
    // other service request fields...
});
entityManager.AddSharedComponentData(request, new UpdateFrame { m_Index = (byte)(simulationFrameIndex & 0xF) });

// The RandomTrafficDispatchSystem will pick this up, start pathfinding, and eventually
// add a Dispatched/PathInformation and enqueue a ServiceDispatch at the source spawner.

Notes & Modding tips: - This system relies heavily on other game types: RandomTrafficRequest, ServiceRequest, PathInformation, TrafficSpawner, ServiceDispatch, UpdateFrame and the PathfindSetupSystem. Ensure correct component shapes when creating requests. - The system staggers work across UpdateFrame indices to spread load; set UpdateFrame.m_Index appropriately for requests if you want them processed in a particular sub-frame. - PathfindParameters are tuned by the system (max speed, methods, ignored rules) depending on request flags; to influence search you should modify the RandomTrafficRequest flags/fields rather than trying to intercept the job. - When adding or removing components that this system expects, use the game's command buffers or schedule operations to avoid race conditions with the jobs.