Skip to content

Game.Tools.TrafficRoutesSystem

Assembly: Game
Namespace: Game.Tools

Type: class

Base: GameSystemBase

Summary:
TrafficRoutesSystem is an ECS system responsible for gathering path sources and updating / visualizing live route lines (traffic routes) in the game. It collects relevant entities (buildings, nets, transport stops, etc.) into a target map, finds path sources whose path elements reference those targets, and then updates "LivePath" route entities and their route segments. The system uses several Burst-compiled jobs (FillTargetMapJob, FindPathSourcesJob, UpdateLivePathsJob) to perform this work in parallel and issues entity commands via a ModificationBarrier2 command buffer. It is used by the in-game tool that toggles route visualization and is optimized to limit update frequency and the number of sources processed.


Fields

  • private ModificationBarrier2 m_ModificationBarrier
    Provides an EntityCommandBuffer for safely creating/updating/deleting entities and components from jobs; used to add/remove route and segment entities.

  • private ToolSystem m_ToolSystem
    Reference to the ToolSystem used to get the currently selected entity/index when routes visualization is driven by the selection.

  • private EntityQuery m_LivePathQuery
    Query matching LivePath + Route entities (excluding Deleted). Used to enumerate existing live route entities and their segments to update/remove them as needed.

  • private EntityQuery m_PathSourceQuery
    Query for potential path source entities. Filtered by UpdateFrame shared component and presence of PathOwner/TrainCurrentLane and excludes Deleted/Temp.

  • private EntityQuery m_RouteConfigQuery
    Query used to fetch the RouteConfigurationData singleton (route visualization prefabs, colors, etc).

  • private int m_UpdateFrameIndex
    Cyclic index used to stagger expensive per-frame work across frames (used with UpdateFrame shared component filtering).

  • private TypeHandle __TypeHandle
    Internal container that stores Component/Buffer/Type handles used to read component lookups and buffer lookups inside jobs (assigned in OnCreateForCompiler).

Properties

  • public bool routesVisible { get; set; }
    Flag that controls whether route visualization is driven by the tool selection. When true, the system will build a target map based on the currently selected entity and update live paths accordingly. When false the selection-driven target-map path discovery is skipped.

Constructors

  • public TrafficRoutesSystem()
    Default constructor. The system initializes internal data in OnCreate and OnCreateForCompiler; the ctor only sets up the instance.

Methods

  • protected override void OnCreate()
    Initializes system-level state: gets/creates the ModificationBarrier2 and ToolSystem, builds the entity queries (live path, path sources, route config), sets m_UpdateFrameIndex = -1 and routesVisible = false. Also used to prepare queries used later in OnUpdate.

  • protected override void OnUpdate()
    Main update routine. Behavior:

  • Determines selection-driven entity (tool selection) when routesVisible is true.
  • Gathers current live path archetype chunks asynchronously.
  • If a supported selection entity type is selected (building, aggregate, network node/edge, transport stop, outside connection etc.) it:
    • Builds a target map (FillTargetMapJob) of entities and sub-entities (sub-lanes, sub-nets, sub-areas, spawn locations, renters, connected routes, sub-objects).
    • Schedules FindPathSourcesJob in parallel to scan PathSource-capable entities and enqueue actual path source entities that reference the target map.
    • Uses an UpdateLivePathsJob to create/update route visualization entities and segments or remove stale segments, using a command buffer from m_ModificationBarrier. It also respects a per-frame source count limit and the UpdateFrame index filter.
  • Disposes temporary containers and manages job dependencies and producer job handles correctly.

  • protected override void OnCreateForCompiler()
    Internal setup used by generated code to assign query handles and type handles (calls __AssignQueries and __TypeHandle.__AssignHandles). Required for proper job handle/component handle initialization in compiled ECS systems.

  • private void __AssignQueries(ref SystemState state)
    Helper used during compilation-time setup to initialize internal queries (placeholder in this decompiled view).

  • Nested job structs (private):

  • FillTargetMapJob : IJob (BurstCompile)
    Traverses a selected entity and its sub-entities (sub-objects, sub-lanes, sub-nets, sub-areas, spawn locations, renters, aggregate elements, connected routes, outside connections, attached parents) to build a NativeHashSet of target entities that are used to find path sources. This job populates the m_TargetMap used by FindPathSourcesJob.
  • FindPathSourcesJob : IJobChunk (BurstCompile)
    Scans archetype chunks for entities that can be path source providers. It inspects component buffers (PathElement), current lane components for different vehicle types, navigation lanes, controllers, and other components. It enqueues entities that are true path sources (those whose PathElements or current lanes reference targets in the target map) into a NativeQueue for processing by UpdateLivePathsJob. It uses the UpdateFrame filter to limit scanned entities.
  • UpdateLivePathsJob : IJob (BurstCompile)
    Consumes the queued path sources and existing live path chunks to:
    • Build a map of route visualization prefabs to current live path entity data.
    • Ensure each found path source translates into a route segment entity owned by an appropriate route visualization entity (prefab).
    • Remove route segments whose PathSource no longer exists or wasn't updated this frame (deleted) and mark route entities as Deleted when they become empty.
    • Create new visualization route entities when new source types are discovered (using prefab route and segment archetypes from RouteConfigurationData). Uses an EntityCommandBuffer (m_CommandBuffer) from m_ModificationBarrier to enqueue entity creation/deletion/updates.

Notes / Implementation details: - The system uses a per-frame rotated UpdateFrame shared component to split workload across frames (m_UpdateFrameIndex). - The UpdateLivePathsJob enforces a source count limit (m_SourceCountLimit = 200) to avoid creating arbitrarily many segments in a single update. - The system is designed for safe parallel execution and memory safety: it uses NativeHashMap/NativeQueue, BufferLookup/ComponentLookup and schedules jobs with combined dependencies; it also disposes temporary containers with job dependencies respected.

Usage Example

// Toggle route visualization from a mod or tool.
// Requires using Unity.Entities;
var world = Unity.Entities.World.DefaultGameObjectInjectionWorld;
if (world != null)
{
    var routesSystem = world.GetExistingSystemManaged<Game.Tools.TrafficRoutesSystem>();
    if (routesSystem != null)
    {
        // Turn on tool-driven route visualization (system will use the tool selection)
        routesSystem.routesVisible = true;

        // Or turn off selection-driven updates (routes stay until created entities are removed)
        // routesSystem.routesVisible = false;
    }
}

Additional tips for modders: - To customize visualization appearance or behavior, inspect/override RouteConfigurationData or provide your own route prefabs that the system will instantiate as LivePath and RouteSegment entities. - Be careful when interacting with the same entities the system expects (LivePath / Route / RouteSegment / PathSource) — using the ModificationBarrier2 or scheduling jobs with proper dependencies prevents race conditions. - For performance, limit toggling routesVisible and avoid selecting extremely large aggregates frequently; the system already staggers work with UpdateFrame but very large maps may still be costly.