Skip to content

Game.Simulation.TransportTrainAISystem

Assembly:
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
TransportTrainAISystem is the simulation system responsible for running AI logic for trains (both cargo and public transport) each relevant simulation update. Internally it schedules a Burst-compiled IJobChunk (TransportTrainTickJob) that iterates matching train vehicle entities and handles pathfinding, boarding/unboarding, dispatch selection, parking, maintenance/refueling logic, carriage prefab changes, pantograph handling, and related state transitions. The system integrates with the pathfinding setup system, boarding helpers, depot/station data, and the end-frame barrier to produce command buffer changes safely.


Fields

  • private EndFrameBarrier m_EndFrameBarrier
    Reference to the EndFrameBarrier system used to obtain a parallel command buffer for issuing structural changes at end of frame.

  • private SimulationSystem m_SimulationSystem
    Reference to the SimulationSystem (provides frame index and other simulation-wide data).

  • private PathfindSetupSystem m_PathfindSetupSystem
    Reference used to enqueue pathfind setup requests produced by the transport tick job.

  • private CityStatisticsSystem m_CityStatisticsSystem
    Used when scheduling boarding-related jobs that update city statistics.

  • private AchievementTriggerSystem m_AchievementTriggerSystem
    Used by boarding/dispatch logic to trigger achievements where relevant.

  • private CityConfigurationSystem m_CityConfigurationSystem
    Used by helper data to configure carriage selection and other transport settings.

  • private EntityQuery m_VehicleQuery
    Query used to select train vehicles that this system should update (requires TrainCurrentLane, Owner, PrefabRef, PathOwner, Target and at least one of CargoTransport/PublicTransport).

  • private EntityQuery m_CarriagePrefabQuery
    Query used by the carriage selection helper to find carriage prefabs.

  • private EntityArchetype m_TransportVehicleRequestArchetype
    Archetype used when the system creates transport vehicle request entities to ask for dispatches.

  • private EntityArchetype m_HandleRequestArchetype
    Archetype used for handle-request events created by this system.

  • private ComponentTypeSet m_MovingToParkedTrainRemoveTypes
    Component type set listing components to remove when moving a vehicle into a parked state (used when parking a train).

  • private ComponentTypeSet m_MovingToParkedTrainAddTypes
    Component type set listing components to add when a vehicle becomes parked (ParkedTrain, Stopped, Updated).

  • private TransportTrainCarriageSelectData m_TransportTrainCarriageSelectData
    Helper data / utility used to select carriage prefabs during loading/dispatch.

  • private TransportBoardingHelpers.BoardingLookupData m_BoardingLookupData
    Precomputed lookup data used by boarding helpers to speed boarding operations.

  • private TypeHandle __TypeHandle
    Generated/per-instance struct that caches ComponentTypeHandle, BufferTypeHandle and ComponentLookup handles used by the inner job to access ECS data efficiently.

Properties

  • None (no public properties exposed by the system).

Constructors

  • public TransportTrainAISystem()
    Default constructor. The system is created by the DOTS World. Initialization of queries and helper data happens in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval used by the system (16). Controls how often the system runs relative to simulation ticks.

  • public override int GetUpdateOffset(SystemUpdatePhase phase)
    Returns the update offset used by the system (3). Combined with interval determines scheduling phase.

  • protected override void OnCreate()
    Initializes the system: obtains references to required systems (EndFrameBarrier, SimulationSystem, PathfindSetupSystem, etc.), constructs entity queries and archetypes, prepares ComponentTypeSet sets, and creates helper objects (carriage selector, boarding lookup). Also calls RequireForUpdate with the vehicle query.

  • protected override void OnUpdate()
    Main update method. Prepares TransportBoardingHelpers.BoardingData, updates carriage-selection helper data, updates boarding lookup data, schedules the Burst-compiled TransportTrainTickJob (IJobChunk) in parallel for all matching vehicle entities, schedules boarding follow-up jobs, posts pathfind queue writers, adds the job handle to the end-frame barrier, and sets the system dependency to the boarding job handle. This method wires together pathfinding, boarding, carriage swaps, and command buffer production.

  • protected override void OnCreateForCompiler()
    Internal helper used by generated/compiled code to assign queries and type handles for the ECS compiler. Calls __AssignQueries and assigns TypeHandle handles.

  • private void __AssignQueries(ref SystemState state)
    Generated helper for assigning queries. Present to satisfy internal compiler/runtime requirements (minimal in this implementation).

  • (Nested) TransportTrainTickJob : IJobChunk (BurstCompiled)

  • Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
    Iterates the chunk's vehicle entities and gathers component buffers/data, then calls Tick for each entity.
  • Tick(...)
    Core per-vehicle logic: handles resetting/creating paths, checking and extending path buffers, reversing trains, updating pantograph flags, checking and setting maintenance flags, checking dispatch queues, requesting targets, handling stuck vehicles and blockers, selecting next dispatchs, parking trains, boarding start/stop logic, path appending, pathfinding setup (FindNewPath), parking-space checks, updating batches and issuing command buffer changes as needed. Implements most of the train AI behavior.
  • Many helper methods implemented inside the job, for example:
    • CheckParkingSpace(...) — syncs TrainFlags.IgnoreParkedVehicle with spawn location parked-vehicle flags.
    • TryParkTrain(...) — convert a moving train into parked state, update components and spawn-location fixes.
    • UpdatePantograph(...) — sets per-car pantograph flags based on prefab train data (MultiUnit / Pantograph).
    • UpdateStop(...) — mark boarding side (left/right) based on relative positions and controller flags.
    • FindNewPath(...) — prepare PathfindParameters and enqueue a pathfind setup item.
    • CheckNavigationLanes(...) — check end-of-path navigation lanes and optionally skip waypoints or mark arriving.
    • SetNextWaypointTarget(...) — set target to next waypoint on route waypoints buffer.
    • CheckServiceDispatches(...) — choose best dispatch request when many exist and limit service dispatch list.
    • RequestTargetIfNeeded(...) — create a TransportVehicleRequest entity if none exists and timing allows.
    • SelectNextDispatch(...) — attempt to pick the next service dispatch / request and attach routes, append path elements from a request, mark route flags, and handle target setting.
    • UpdateBatches(...) — issue BatchesUpdated components to update rendering/instance batching for vehicle/rail layout.
    • ReturnToDepot(...) — clear dispatches and set vehicle to return-to-depot state.
    • StartBoarding(...) / StopBoarding(...) — begin and end boarding sequences using TransportBoardingHelpers.BoardingData, handle refueling/maintenance decisions, and apply loading resource changes.
    • TryChangeCarriagePrefab(...) / CheckLoadingResources(...) — attempt to change carriage prefab types based on loading resources (used for cargo trains) and apply Updated component so prefab changes take effect.
    • QuantityUpdated(...) — add Updated component to vehicles when load/quantity changes.
    • CountPassengers(...) / ArePassengersReady(...) — helpers for boarding logic and determining whether to depart.
    • GetTransportStationFromStop(...) / GetStorageCompanyFromStop(...) / GetNextStorageCompany(...) — helpers to walk ownership hierarchy from stops to find owning station/company entities.

Note: most job methods read/write many component types and buffers using ComponentLookup/BufferLookup and produce structural changes via a parallel EntityCommandBuffer from m_EndFrameBarrier.

Usage Example

// The system is usually managed by the ECS World. Example: get or create the system and ensure it runs.
// This is a minimal usage snippet for a mod that needs to access the system instance.

var world = Unity.Entities.World.DefaultGameObjectInjectionWorld;
var trainAISystem = world.GetOrCreateSystemManaged<Game.Simulation.TransportTrainAISystem>();

// You typically don't call OnUpdate manually — the DOTS scheduler runs it according to its interval.
// But you can ensure dependent systems are created and inspect its queries if needed (read-only via reflection):
// Example: check if system has vehicles matching its query (mostly for diagnostics).
// Note: the m_VehicleQuery field is private; direct access requires reflection or extending the system.

If you want additional details (full list of all Component types used by the inner job, descriptions of specific flags and component structs like CargoTransport/PublicTransport/Train, or examples of hooking into boarding events), tell me which area to expand and I will add it.