Skip to content

Game.Simulation.TrafficSpawnerAISystem

Assembly: Assembly-CSharp
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
TrafficSpawnerAISystem is responsible for generating "dummy" random traffic from TrafficSpawner buildings. It schedules a Burst-compiled IJobChunk (TrafficSpawnerTickJob) that iterates TrafficSpawner entities, issues RandomTrafficRequest entities, and spawns vehicles (personal cars, delivery trucks, public/transport vehicles, aircraft, ships, trains) and their passengers. The system integrates with SimulationSystem, ClimateSystem, CityConfigurationSystem and VehicleCapacitySystem, and uses an EndFrameBarrier EntityCommandBuffer for safe entity creation and modifications inside jobs. It also coordinates vehicle selection via helper types PersonalCarSelectData and TransportVehicleSelectData.


Fields

  • private EntityQuery m_BuildingQuery
    Query selecting TrafficSpawner entities with ServiceDispatch buffers; used to schedule the Tick job.

  • private EntityQuery m_PersonalCarQuery
    Query used by PersonalCarSelectData to find available personal car prefabs.

  • private EntityQuery m_TransportVehicleQuery
    Query used by TransportVehicleSelectData to find available transport vehicle prefabs.

  • private EntityQuery m_CreaturePrefabQuery
    Query selecting creature/resident prefab chunks used when creating passengers.

  • private SimulationSystem m_SimulationSystem
    Reference to the SimulationSystem (used for loadingProgress and timing-related decisions).

  • private ClimateSystem m_ClimateSystem
    Reference to the ClimateSystem (present but not heavily referenced in this file; available for climate-dependent logic).

  • private CityConfigurationSystem m_CityConfigurationSystem
    Used to read city configuration such as left-hand traffic setting.

  • private VehicleCapacitySystem m_VehicleCapacitySystem
    Used to get vehicle selection data (delivery truck capacities, etc).

  • private EndFrameBarrier m_EndFrameBarrier
    Barrier system used to obtain an EntityCommandBuffer. The job writes entity creation/modification through this barrier.

  • private EntityArchetype m_TrafficRequestArchetype
    Archetype used to create RandomTrafficRequest / ServiceRequest / RequestGroup entities.

  • private EntityArchetype m_HandleRequestArchetype
    Archetype used to create HandleRequest entities representing completed request handling.

  • private ComponentTypeSet m_CurrentLaneTypesRelative
    Temporary ComponentTypeSet used when removing lane-relative types from created passenger objects.

  • private PersonalCarSelectData m_PersonalCarSelectData
    Helper instance that encapsulates logic for selecting and creating personal car prefabs.

  • private TransportVehicleSelectData m_TransportVehicleSelectData
    Helper instance that encapsulates logic for selecting and creating transport vehicle prefabs.

  • private TypeHandle __TypeHandle
    Internal cached collection of type handles used when scheduling the job (see nested TypeHandle struct).

  • private struct TypeHandle
    Nested struct that caches EntityTypeHandle, ComponentTypeHandles, ComponentLookup and BufferLookup instances required for the job. It has an __AssignHandles method that initializes those handles from a SystemState.


Properties

  • None (the system exposes no public properties)

Constructors

  • public TrafficSpawnerAISystem()
    Default constructor. Class is annotated with [Preserve] for runtime linking. Initialization of queries and cached objects happens in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval for this system. Uses smaller interval during LoadSimulation phase (returns 16), otherwise returns 256. Controls how often the system schedules work.

  • public override int GetUpdateOffset(SystemUpdatePhase phase)
    Returns an update offset to distribute work among frames. Returns 2 for LoadSimulation phase, otherwise 32.

  • [Preserve] protected override void OnCreate()
    Initializes the system: gets references to dependent systems (SimulationSystem, ClimateSystem, EndFrameBarrier, CityConfigurationSystem, VehicleCapacitySystem), initializes PersonalCarSelectData and TransportVehicleSelectData, creates several EntityQueries, creates archetypes for traffic requests and handle requests, sets up the m_CurrentLaneTypesRelative ComponentTypeSet, and calls RequireForUpdate for the building query so the system runs only when there are spawners. It also contains an Assert for sanity checks.

  • [Preserve] protected override void OnUpdate()
    Main scheduling method. Prepares select-data helpers (PreUpdate), gets creature prefab chunks asynchronously, configures and schedules the Burst-compiled TrafficSpawnerTickJob in parallel (passing in component handles, lookups, buffers, configuration flags, random seed, archetypes, select-data references, creature prefab chunks, and a parallel EntityCommandBuffer writer from m_EndFrameBarrier). After scheduling it wires up dependencies, calls PostUpdate on select-data helpers, registers the job with the EndFrameBarrier, disposes temporary native data, and sets base.Dependency to the scheduled job handle.

  • private void __AssignQueries(ref SystemState state)
    Internal method called in OnCreateForCompiler. Currently just constructs (and disposes) an EntityQueryBuilder; used for compiler-time requirements.

  • protected override void OnCreateForCompiler()
    Compiler helper method that calls __AssignQueries and __TypeHandle.__AssignHandles to ensure handles are assigned for code generation scenarios.

  • private void __AssignHandles(ref SystemState state) (inside TypeHandle)
    Populates the cached EntityTypeHandle, ComponentTypeHandles, ComponentLookup and BufferLookup references from the provided SystemState.

  • private struct TrafficSpawnerTickJob : IJobChunk (nested job type)
    Burst-compiled job that performs the per-chunk processing of TrafficSpawner entities. Responsibilities and notable behavior:

  • Iterates chunks of TrafficSpawner entities and their PrefabRef and ServiceDispatch buffers.
  • Decides whether to request new random traffic (RequestVehicle) based on prefab spawn rates and a RandomSeed.
  • Processes ServiceDispatch buffers: when it finds RandomTrafficRequest entries, it spawns vehicles using SpawnVehicle and removes handled dispatch entries.
  • RequestVehicle(jobIndex, ref Random, Entity, TrafficSpawnerData): creates a RandomTrafficRequest entity via the command buffer with appropriate flags (DeliveryTruck, TransportVehicle, NoSlowVehicles, size class) and a RequestGroup component.
  • SpawnVehicle(jobIndex, ref Random, Entity spawnerEntity, Entity requestEntity, TrafficSpawnerData): validates the request and path information, computes a spawn transform (may spawn immediately when loadingProgress < 0.9), and creates vehicles of different categories:
    • Delivery trucks: selects resource, capacity, may create a single delivery truck and optionally passengers.
    • Transport vehicles (bus/airplane/ship/train): configures transport type, resource vs passenger cargo, sets PublicTransport or CargoTransport flags, and populates LoadingResources when applicable.
    • Personal cars: uses PersonalCarSelectData to create vehicles and optionally trailers, then creates passengers (driver + others) from resident prefab pools.
  • CreatePassengers(jobIndex, Entity vehicleEntity, Entity vehiclePrefab, Transform spawnTransform, bool driver, ref int maxCount, ref Random random): spawns resident objects as passengers using activity location elements from the vehicle prefab. It selects appropriate activity locations (taking left/right-hand traffic into account), creates Resident + CurrentVehicle + Relative transform components, sets Citizen pseudo-random state and age, and uses ObjectEmergeSystem.SelectResidentPrefab to pick resident prefab chunk/entity. Removes lane-relative components from passenger entities and adds them to the created object archetype via the command buffer.
  • GetRandomResource(ref Random): helper mapping a random integer to a Resource enum value.

The job uses multiple ComponentLookup/BufferLookup instances, reads city configuration flags (left-hand traffic), the simulation loading progress to vary spawning behavior, and writes entity creations through a parallel EntityCommandBuffer writer.

  • void IJobChunk.Execute(...) (explicit interface implementation in TrafficSpawnerTickJob)
    Forwards to the job's Execute method.

Usage Example

[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    // Typical initialization performed by the system:
    m_SimulationSystem = World.GetOrCreateSystemManaged<SimulationSystem>();
    m_ClimateSystem = World.GetOrCreateSystemManaged<ClimateSystem>();
    m_EndFrameBarrier = World.GetOrCreateSystemManaged<EndFrameBarrier>();
    // Build queries and require update only when spawners exist:
    m_BuildingQuery = GetEntityQuery(ComponentType.ReadOnly<Game.Buildings.TrafficSpawner>(),
                                     ComponentType.ReadOnly<ServiceDispatch>(),
                                     ComponentType.Exclude<Temp>(),
                                     ComponentType.Exclude<Destroyed>(),
                                     ComponentType.Exclude<Deleted>());
    RequireForUpdate(m_BuildingQuery);
}

Notes for modders: - The core spawn logic runs inside a Burst IJobChunk (TrafficSpawnerTickJob). To modify spawn behavior safely, consider: - Changing prefab spawn rates via TrafficSpawnerData assets. - Hooking or replacing the vehicle selection helpers (PersonalCarSelectData / TransportVehicleSelectData / VehicleCapacitySystem) carefully. - Avoid directly mutating Game data structures from the main thread while the job expects specific Archetypes / buffers. Use ECS APIs or create your own system that runs at an appropriate SystemUpdatePhase and coordinates with EndFrameBarrier. - The job creates many entities via an EntityCommandBuffer.AsParallelWriter produced by EndFrameBarrier; if you need to post-process created vehicles, add a system that runs after EndFrameBarrier or use the same barrier dependency model.