Game.Simulation.PathfindSetupSystem
Assembly: Assembly-CSharp (most game systems live in the main game assembly)
Namespace: Game.Simulation
Type: class
Base: GameSystemBase, IPreDeserialize
Summary:
PathfindSetupSystem is responsible for preparing pathfinding "setup" data (start/end targets) for a wide variety of in-game services and agents (transport, emergency services, citizens, resources, garbage, post, etc.). It collects setup requests placed into queues, groups and sorts them by target type, schedules specific setup jobs (via a set of per-service setup helper objects), collects targets discovered by those jobs into per-request buffers, and finally enqueues completed PathfindAction requests into the global PathfindQueueSystem. The system is job-aware and uses Unity.Jobs and native containers; it tracks job dependencies to avoid race conditions and disposes native resources in OnDestroy and PreDeserialize.
Key responsibilities & notes:
- Accepts incoming SetupQueueItem requests via NativeQueue
Fields
-
private PathfindTargetSeekerData m_TargetSeekerData
Holds seeker metadata used to construct PathfindTargetSeeker instances for target searches. Created in OnCreate and used across FindTargets calls. -
private CommonPathfindSetup m_CommonPathfindSetup
Helper for common target setups such as current location, safety, accidents. -
private PostServicePathfindSetup m_PostServicePathfindSetup
Helper for post-related setups (post vans, mail transfer, mailboxes, requests). -
private GarbagePathfindSetup m_GarbagePathfindSetup
Helper for garbage-related setups (collectors, transfers, requests). -
private TransportPathfindSetup m_TransportPathfindSetup
Helper for transport-target setups (taxis, transport vehicles, route waypoints, requests). -
private PolicePathfindSetup m_PolicePathfindSetup
Helper for police-related setups (patrols, prisoner transport, requests). -
private FirePathfindSetup m_FirePathfindSetup
Helper for fire-related setups (engines, shelters, evacuation requests). -
private HealthcarePathfindSetup m_HealthcarePathfindSetup
Helper for healthcare-related setups (hospitals, ambulances, hearses, requests). -
private AreaPathfindSetup m_AreaPathfindSetup
Helper for area-based setups (area locations, wood resources). -
private RoadPathfindSetup m_RoadPathfindSetup
Helper for road and maintenance setups (maintenance, random traffic, outside connections, maintenance requests). -
private CitizenPathfindSetup m_CitizenPathfindSetup
Helper for citizen-target setups (tourist, leisure, school/job seekers, attractions, homeless shelters, find home). -
private ResourcePathfindSetup m_ResourcePathfindSetup
Helper for resource-related setups (sellers, exports, storage transfers). -
private SimulationSystem m_SimulationSystem
Reference to the global simulation system for accessing frame index and smoothSpeed. -
private PathfindQueueSystem m_PathfindQueueSystem
Reference to the PathfindQueueSystem for enqueuing completed PathfindAction requests. -
private AirwaySystem m_AirwaySystem
Reference used when target distribution depends on airway data. -
private NativeList<SetupListItem> m_SetupList
Accumulated list of all setup sub-requests for the current update. Each real request produces two SetupListItem entries (start and end) and stores results in UnsafeListbuffers. -
private List<SetupQueue> m_ActiveQueues
Active setup queues currently being serviced. Each SetupQueue contains a NativeQueueand timing metadata. -
private List<SetupQueue> m_FreeQueues
Pool of recycled SetupQueue objects (their NativeQueue is disposed when system destroyed or PreDeserialize, but queues can be reused between frames while alive). -
private List<ActionListItem> m_ActionList
Parallel list of PathfindAction wrappers corresponding to queued setup requests. Used to assign discovered start/end buffers back to actions. -
private JobHandle m_QueueDependencies
Combined job dependency for writers that enqueue into queue(s). AddQueueWriter merges external writer handles here to ensure correct ordering. -
private JobHandle m_SetupDependencies
Combined job dependency for internal setup jobs (the DequePathTargetsJob and other setup jobs). The system completes this handle in CompleteSetup before forwarding PathfindAction data. -
private uint m_QueueSimulationFrameIndex
Earliest result frame among active queues — used to provide pendingSimulationFrame. -
private uint m_SetupSimulationFrameIndex
Frame index used to track when setup work should be considered done; used for pendingSimulationFrame and resetting state. -
private int m_PendingRequestCount
Count of pending PathfindAction requests waiting for setup completion. Exposed via pendingRequestCount.
Properties
-
public uint pendingSimulationFrame { get; }
Returns the minimum of m_QueueSimulationFrameIndex and m_SetupSimulationFrameIndex. Use to know the earliest simulation frame where pending pathfind setups will complete. Useful for scheduling or debugging. -
public int pendingRequestCount { get; }
Number of requests currently pending setup completion. Useful for metrics/debug or gating logic.
Constructors
public PathfindSetupSystem()
Default constructor. The main initialization happens in OnCreate (system component creation pattern).
Methods
protected override void OnCreate()
Initialize all helper setup objects, fetch references to other systems (SimulationSystem, PathfindQueueSystem, AirwaySystem) via World, and create native containers (m_SetupList, lists for queues/actions). Called by framework when the system is instantiated.
Important: Allocates NativeList
-
protected override void OnDestroy()
Cleans up job dependencies, disposes all NativeQueue instances in active/free lists, completes setup job dependencies, disposes each SetupListItem unsafe buffer (m_Buffer), and disposes PathfindAction objects stored in action list. Clears managed lists and then calls base.OnDestroy(). Always ensure OnDestroy completes outstanding jobs and disposes native memory to avoid leaks. -
public void PreDeserialize(Context context)
Called before deserialization to tear down and reset native state safely. Completes dependencies m_QueueDependencies and m_SetupDependencies, disposes all active/free queues and buffers and clears lists, and resets indices and counters. Important during save/load to avoid carrying transient runtime state across serialization boundaries. -
protected override void OnUpdate()
Main per-frame logic: - If there are no active queues, returns early.
- Calls CompleteSetup() to finalize any previous setup work if needed.
- Updates target seeker data with airway information.
- Ensures queue writer job dependencies are completed.
- Iterates active queues, calculates how many items to dequeue per frame (supports spreading work over frames using spreadFrame and smoothSpeed), and moves dequeued SetupQueueItem objects into m_SetupList and m_ActionList.
- If queue becomes empty, moves it to m_FreeQueues; otherwise keeps it in m_ActiveQueues.
- Sorts m_SetupList by target type so targets are grouped and calls FindTargets on contiguous ranges of same SetupTargetType.
-
Sets m_PendingRequestCount and frame indices used for pendingSimulationFrame.
-
public void CompleteSetup()
Completes setup-phase of the system: - Resets m_SetupSimulationFrameIndex and m_PendingRequestCount.
- Completes m_SetupDependencies (waits for setup jobs).
- Iterates m_SetupList and assigns each SetupListItem's discovered buffer to the corresponding PathfindAction (start or end).
- Enqueues each PathfindAction into m_PathfindQueueSystem with original owner/system/resultFrame.
-
Clears m_SetupList and m_ActionList. Call this if you need to force completion of pending setups early (e.g., before a save).
-
public NativeQueue<SetupQueueItem> GetQueue(object system, int maxDelayFrames, int spreadFrames = 0)
Public accessor to create or reuse a SetupQueue, returning the NativeQueuewhere external systems should enqueue setup requests. - maxDelayFrames controls when results should be produced (m_ResultFrame = current frame + maxDelayFrames).
- spreadFrames is used to spread dequeuing work across frames.
- The returned NativeQueue is allocated with Allocator.Persistent and will be disposed by the PathfindSetupSystem in OnDestroy or PreDeserialize. Do not dispose it yourself.
-
The system updates its internal m_QueueSimulationFrameIndex to reflect the earliest result frame.
-
public void AddQueueWriter(JobHandle handle)
When user code schedules a job that writes into any SetupQueue returned by GetQueue, call AddQueueWriter to combine the writer's JobHandle with m_QueueDependencies. This ensures PathfindSetupSystem will wait for those writers before dequeuing. -
public EntityQuery GetSetupQuery(params EntityQueryDesc[] entityQueryDesc)
Convenience wrapper to call GetEntityQuery with EntityQueryDesc[] from other setup helpers. Returns an EntityQuery for target selection. -
public EntityQuery GetSetupQuery(params ComponentType[] componentTypes)
Convenience wrapper to call GetEntityQuery with ComponentType[]. -
private unsafe void FindTargets(int startIndex, int endIndex)
Internal: for a contiguous block of m_SetupList entries with the same SetupTargetType, prepares a temporary NativeQueue(Allocator.TempJob), constructs a SetupData object that references the subrange and the target queue's parallel writer, schedules a DequePathTargetsJob that drains that queue into the SetupListItem buffers, calls the type-specific FindTargets(targetType, setupData) to schedule the target-discovery job(s) for the block, combines dependencies and ensures the targetQueue is disposed after the dequeuing job completes. This is the central orchestration that connects per-type target finders with the per-request buffers. -
private JobHandle FindTargets(SetupTargetType targetType, in SetupData setupData)
Dispatches to the appropriate setup helper method based on targetType (huge switch). Each case returns a JobHandle that represents the scheduled target-discovery work. If the targetType is unknown, logs a warning and returns default JobHandle. This is where all service-specific setup code is invoked (CommonPathfindSetup, PostServicePathfindSetup, etc.). -
DequePathTargetsJob (private struct implementing IJob)
Dequeues PathfindSetupTarget items from a NativeQueueand writes them into the corresponding SetupListItem.m_Buffer entries. It: - Uses an unsafe pointer to an array of SetupListItem (m_SetupItems).
- For each dequeued PathfindSetupTarget, determines the SetupListItem by m_SetupIndex and either appends the PathTarget to the buffer or, if SkipPathfind is set in parameters, keeps only the lowest-cost PathTarget (special-case skip pathfinding behavior).
- Runs as a job scheduled after the main target-discovery jobs, then its completion is combined into m_SetupDependencies.
Notes about job safety and memory:
- SetupListItem contains an UnsafeList
Usage Example
// Example from another game system that wants to request pathfind setup work:
protected override void OnCreate()
{
base.OnCreate();
// Acquire the PathfindSetupSystem reference
var pathfindSetup = World.GetExistingSystemManaged<PathfindSetupSystem>();
// Request a queue where our system will enqueue SetupQueueItem requests.
// maxDelayFrames: how many frames before results are expected.
// spreadFrames: number of frames to spread processing across (optional).
var queue = pathfindSetup.GetQueue(this, maxDelayFrames: 2, spreadFrames: 1);
// If you will write to 'queue' from a Job, capture the JobHandle and call:
// pathfindSetup.AddQueueWriter(jobHandle);
}
// Enqueuing a SetupQueueItem is done by filling the struct and calling queue.Enqueue(...)
// (SetupQueueItem is defined elsewhere in the game's codebase). Example (conceptual):
// var item = new SetupQueueItem { m_Origin = originTarget, m_Destination = destTarget, m_Parameters = parameters, m_Owner = ownerEntity };
// queue.Enqueue(item);
// If enqueuing from a job, ensure that job's handle is passed to pathfindSetup.AddQueueWriter(...)