Game.Pathfind.PathUtils
Assembly: Assembly-CSharp (game runtime)
Namespace: Game.Pathfind
Type: public static class
Base: System.Object
Summary:
Utility helpers used by the pathfinding subsystem. Provides functions to compute path costs and speeds, build and combine path element buffers, trim/extend paths, derive PathSpecification/LocationSpecification objects for different lane and route types (cars, tracks, pedestrians, taxis, transport stops, spawn locations, etc.), and helper utilities for appending paths to ongoing navigation buffers for many vehicle types. The class is designed for use with the game's ECS data (DynamicBuffer, ComponentLookup, BufferLookup, Native collections) and contains many overloads tailored to different vehicle types and lane data structures. Most methods are pure helpers and operate on low-level PathElement/PathOwner structures and PathSpecification data used by the pathfinder.
Fields
private struct AppendPathValue
A small POD struct used internally by TryAppendPath implementations. Contains:- m_TargetDelta (float): the curve position or delta value to use when matching/patching a path.
-
m_Index (int): an index encoding where the matched lane/element was found (0 = current lane, 1..n = navigation lanes, num+ = path elements).
-
public const float MIN_DENSITY = 0.01f
A public constant used as a minimum density threshold for some density-based computations (e.g., lane availability/density calculations).
Properties
- (This is a static utility class — there are no public properties.)
Constructors
- (No public constructors — PathUtils is a static class. All members are static.)
Methods
-
public static float CalculateCost(ref Random random, in PathSpecification pathSpecification, in PathfindParameters pathfindParameters)
Calculates a stochastic or stable cost for a path edge combining speed, predefined cost components, length, and parameter weights. If the Stable flag is set in pathfindParameters, the result is deterministic; otherwise a random factor in [0.5,1] is applied. -
public static float CalculateCost(in PathSpecification pathSpecification, in CoverageParameters coverageParameters, float2 delta)
Returns a coverage-style cost: length * density * abs(delta.y - delta.x). Delta typically encodes start/end curve positions. -
public static float CalculateCost(in PathSpecification pathSpecification, in AvailabilityParameters availabilityParameters, float2 delta)
Calculates a cost that accounts for availability weighting, scaling by density and max speed. -
public static float CalculateLength(in PathSpecification pathSpecification, float2 delta)
Returns the effective length (pathSpecification.m_Length * abs(delta.y - delta.x)). -
public static float CalculateSpeed(in PathSpecification pathSpecification, in PathfindParameters pathfindParameters)
Computes travel speed for the edge given the path specification and requested path methods (pedestrian vs vehicle, secondary flags, max/walk speeds, flow offset). Takes into account IgnoreFlow flag and flow offset scaling. -
public static void CombinePaths(DynamicBuffer<PathElement> sourceElements1, DynamicBuffer<PathElement> sourceElements2, DynamicBuffer<PathElement> targetElements)
Concatenate two PathElement buffers into targetElements. -
public static PathInformation CombinePaths(PathInformation pathInformation1, PathInformation pathInformation2)
Combine two PathInformation structs (e.g., distance, duration, cost and destination) into a merged PathInformation. -
public static void CopyPath(DynamicBuffer<PathElement> sourceElements, PathOwner sourceOwner, int skipCount, DynamicBuffer<PathElement> targetElements)
Overload: copies a portion of sourceElements into targetElements starting from sourceOwner.m_ElementIndex + skipCount to end. -
public static void CopyPath(DynamicBuffer<PathElement> sourceElements, PathOwner sourceOwner, int skipCount, int endIndex, DynamicBuffer<PathElement> targetElements)
Copies a subrange from sourceElements into targetElements. endIndex is clamped to sourceElements.Length. -
public static void TrimPath(DynamicBuffer<PathElement> pathElements, ref PathOwner pathOwner)
Trim the path by removing elements before pathOwner.m_ElementIndex and reset pathOwner.m_ElementIndex to 0. -
public static void TrimPath(DynamicBuffer<PathElement> pathElements, ref PathOwner pathOwner, int startIndex)
Trim the path by removing the first startIndex elements and set pathOwner.m_ElementIndex = 0. -
public static int FindFirstLane(DynamicBuffer<PathElement> pathElements, PathOwner pathOwner, int skipCount, ComponentLookup<Game.Net.ParkingLane> parkingLaneData)
Search forward from pathOwner.m_ElementIndex + skipCount and return the index of the first element whose target has a ParkingLane component. Returns pathElements.Length if none. -
public static bool GetStartDirection(DynamicBuffer<PathElement> path, PathOwner pathOwner, ref ComponentLookup<Curve> curveData, out int startOffset, out bool forward)
Find the first curve-based element in the path starting at the pathOwner's element index and establish whether the motion on that curve is forward. Returns false if no curve found. -
public static bool GetEndDirection(DynamicBuffer<PathElement> path, PathOwner pathOwner, ref ComponentLookup<Curve> curveData, out int endOffset, out bool forward)
Find the last curve-based element and determine the forward direction for it. Mirrors GetStartDirection but for path end. -
public static void ExtendPath(DynamicBuffer<PathElement> path, PathOwner pathOwner, ref float distance, ref ComponentLookup<Curve> curveData, ref ComponentLookup<Lane> laneData, ref ComponentLookup<EdgeLane> edgeLaneData, ref ComponentLookup<Owner> ownerData, ref ComponentLookup<Game.Net.Edge> edgeData, ref BufferLookup<ConnectedEdge> connectedEdges, ref BufferLookup<Game.Net.SubLane> subLanes)
Extends the path at the end by inserting intermediate curve segments up to a requested distance. Uses NetUtils.FindConnectedLane to advance to connected lanes. Adjusts path elements' target deltas accordingly and accumulates how much distance was consumed. -
public static void ExtendReverseLocations(PathElement prevElement, DynamicBuffer<PathElement> path, PathOwner pathOwner, float distance, ComponentLookup<Curve> curveData, ComponentLookup<Lane> laneData, ComponentLookup<EdgeLane> edgeLaneData, ComponentLookup<Owner> ownerData, ComponentLookup<Game.Net.Edge> edgeData, BufferLookup<ConnectedEdge> connectedEdges, BufferLookup<Game.Net.SubLane> subLanes)
Attempts to insert reverse (return) segments where vehicle route geometry indicates a reverse approach is preferable (compares tangents and owner entities to detect matching lanes). -
public static void InitializeSpawnPath(DynamicBuffer<PathElement> path, NativeList<PathElement> laneBuffer, Entity parkingLocation, ref PathOwner pathOwner, float length, ref ComponentLookup<Curve> curveData, ref ComponentLookup<Lane> laneData, ref ComponentLookup<EdgeLane> edgeLaneData, ref ComponentLookup<Owner> ownerData, ref ComponentLookup<Game.Net.Edge> edgeData, ref ComponentLookup<Game.Objects.SpawnLocation> spawnLocationData, ref BufferLookup<ConnectedEdge> connectedEdges, ref BufferLookup<Game.Net.SubLane> subLanes)
Constructs a spawn path centered around either an existing path start or a spawn location entity. Builds laneBuffer with elements spanning half the requested length in both directions, used by vehicle spawn logic. -
public static void ResetPath(ref CarCurrentLane currentLane, DynamicBuffer<PathElement> path, ComponentLookup<SlaveLane> slaveLaneData, ComponentLookup<Owner> ownerData, BufferLookup<Game.Net.SubLane> subLanes)
(No-op in provided code — placeholder potentially for resetting current lane state given a new path.) -
public static void ResetPath(ref WatercraftCurrentLane currentLane, DynamicBuffer<PathElement> path, ComponentLookup<SlaveLane> slaveLaneData, ComponentLookup<Owner> ownerData, BufferLookup<Game.Net.SubLane> subLanes)
Resets the currentCurvePosition.z to the first path element's start delta if it matches the master lane; otherwise uses stored curvePosition.y fallback. -
public static void ResetPath(ref AircraftCurrentLane currentLane, DynamicBuffer<PathElement> path)
Resets aircraft current lane positions similarly and sets SkipLane flag for airway/flying lanes when appropriate. -
public static bool TryAppendPath(ref CarCurrentLane currentLane, DynamicBuffer<CarNavigationLane> navigationLanes, DynamicBuffer<PathElement> path, DynamicBuffer<PathElement> appendPath, ComponentLookup<SlaveLane> slaveLaneData, ComponentLookup<Owner> ownerData, BufferLookup<Game.Net.SubLane> subLanes)
Overload that appends appendPath to path adjusting navigation lanes/current lane as necessary. Internally constructs a NativeParallelHashMap of master-lane -> AppendPathValue then searches appendPath for a match. Returns true if appended; sets appended count via out overload. -
public static bool TryAppendPath(... out int appendedCount)
(Car)
Same as above but returns appendedCount indicating how many elements were appended. -
public static bool TryAppendPath(ref WatercraftCurrentLane currentLane, DynamicBuffer<WatercraftNavigationLane> navigationLanes, DynamicBuffer<PathElement> path, DynamicBuffer<PathElement> appendPath, ComponentLookup<SlaveLane> slaveLaneData, ComponentLookup<Owner> ownerData, BufferLookup<Game.Net.SubLane> subLanes)
and... out int appendedCount
Watercraft-specialized versions of TryAppendPath (same pattern as Car but for watercraft lane structures). -
public static bool TryAppendPath(ref AircraftCurrentLane currentLane, DynamicBuffer<AircraftNavigationLane> navigationLanes, DynamicBuffer<PathElement> path, DynamicBuffer<PathElement> appendPath)
Aircraft version (no slave lane/sub-lane mapping). -
public static bool TryAppendPath(ref TrainCurrentLane currentLane, DynamicBuffer<TrainNavigationLane> navigationLanes, DynamicBuffer<PathElement> path, DynamicBuffer<PathElement> appendPath)
Train version (uses front lane curve position w component for reset). -
public static Entity GetMasterLane(Entity lane, ComponentLookup<SlaveLane> slaveLaneData, ComponentLookup<Owner> ownerData, BufferLookup<Game.Net.SubLane> subLanes)
If the lane is a slave lane and an owner with sub-lanes exists, returns the corresponding master sub-lane entity; otherwise returns the lane unchanged. -
public static void TryAddCosts(ref PathfindCosts costs, PathfindCosts add)
Accumulates add.m_Value into costs.m_Value. -
public static void TryAddCosts(ref PathfindCosts costs, PathfindCosts add, float distance)
Accumulates add scaled by distance into costs. -
public static void TryAddCosts(ref PathfindCosts costs, PathfindCosts add, Bezier4x3 curve)
If start and end tangents exist and normalize correctly, compute the angle between tangents and add costs scaled by that angle. -
public static void TryAddCosts(ref PathfindCosts costs, PathfindCosts add, bool doIt)
Conditional cost addition based on boolean. -
public static void TryAddCosts(ref PathfindCosts costs, PathfindCosts add, float distance, bool doIt)
Conditional scaled-add. -
public static PathSpecification GetCarDriveSpecification(Curve curve, Game.Net.CarLane carLane, CarLaneData carLaneData, PathfindCarData carPathfindData, float density)
Create a PathSpecification representing a drivable car lane. Calculates flags, methods, speeds, densities, access, and aggregates many cost components (driving cost, curve cost, lane cross cost, forbidden/turning/UTurn costs) based on lane flags. Also sets rules for blockages and restrictions. -
public static PathSpecification GetCarDriveSpecification(Curve curve, Game.Net.CarLane carLane, Game.Net.TrackLane trackLaneData, CarLaneData carLaneData, PathfindCarData carPathfindData, float density)
Variant that includes track compatibility (adds PathMethod.Track) and merges track-specific flags for AllowMiddle/Twoway. -
public static PathSpecification GetTaxiDriveSpecification(Curve curveData, Game.Net.CarLane carLaneData, PathfindCarData carPathfindData, PathfindTransportData transportPathfindData, float density)
Taxi-specific drive specification. Uses transport-specific travel/ordering/starting costs adjusted for taxi semantics. -
public static PathSpecification GetTrackDriveSpecification(Curve curveData, Game.Net.TrackLane trackLaneData, PathfindTrackData trackPathfindData)
Create PathSpecification for track lanes (trains/trams). Adds costs for two-way, switches, diamond crossings, and track driving cost. -
public static PathSpecification GetParkingSpaceSpecification(Game.Net.ParkingLane parkingLane, ParkingLaneData parkingLaneData, PathfindCarData carPathfindData)
Create PathSpecification for parking spaces: parking lane speeds and density, boarding method, parking special flags, parking cost (fee/comfort), and entry/exit allowances. -
public static float GetTaxiAvailabilityDelay(Game.Net.ParkingLane parkingLaneData)
Returns an availability delay used in taxi ordering calculation. -
public static PathSpecification GetTaxiAccessSpecification(Game.Net.ParkingLane parkingLaneData, PathfindCarData carPathfindData, PathfindTransportData transportPathfindData)
Create a PathSpecification for taxi access to parking/taxi stand with ordering/starting costs and flags like SecondaryStart/FreeForward. -
public static PathSpecification GetSpecification(Curve curveData, Game.Net.PedestrianLane pedestrianLaneData, PathfindPedestrianData pedestrianPathfindData)
Create PathSpecification for pedestrian lanes (walking speed, pedestrian costs including crosswalks/unsafe crosswalks, allow enter/exit/middle flags, on-water handling). -
public static PathSpecification GetSpecification(Curve curveData, Game.Net.ConnectionLane connectionLaneData, GarageLane garageLane, Game.Net.OutsideConnection outsideConnection, PathfindConnectionData connectionPathfindData)
Create a generic ConnectionLane PathSpecification (used for outside connections, garages, parking, airway, inside/area/pedestrian connections). Handles many flags (parking/airway/area/outside/allow enter/exit) and applies various connection costs. -
public static PathSpecification GetSecondarySpecification(Curve curveData, Game.Net.ConnectionLane connectionLaneData, Game.Net.OutsideConnection outsideConnection, PathfindConnectionData connectionPathfindData)
Create a "secondary" connection spec used for secondary edges (e.g., taxi lanes, secondary start/end) with special handling of taxi starts or normal border/distance costs. -
public static PathSpecification GetTransportStopSpecification(Game.Routes.TransportStop transportStop, TransportLine transportLine, WaitingPassengers waitingPassengers, TransportLineData transportLineData, PathfindTransportData transportPathfindData, bool isWaypoint)
Create specification for transport route stops (buses/trains/metros). Takes into account active flag, allow enter/exit, whether it is a waypoint, passenger vs cargo transport, stop durations and waiting time adjustments, ticket price and comfort. -
public static PathSpecification GetTaxiStopSpecification(Game.Routes.TransportStop transportStop, TaxiStand taxiStand, WaitingPassengers waitingPassengers, PathfindTransportData transportPathfindData)
Taxi-specific transport stop specification. Adjusts starting costs for waiting times and taxi fees. -
public static PathSpecification GetSpawnLocationSpecification(PathfindPedestrianData pedestrianPathfindData, float distance, Entity accessRestriction, bool requireAuthorization, bool allowEnter, bool allowExit)
Create a spawn location specification for pedestrian spawns. Optional authorization, enter/exit flags and spawn costs. -
public static PathSpecification GetSpawnLocationSpecification(RouteConnectionType connectionType, PathfindCarData carPathfindData, Game.Net.CarLane carLane, float distance, int laneCrossCount, Entity accessRestriction, bool requireAuthorization, bool allowEnter, bool allowExit)
Create a spawn location specification for cars depending on connection type (Cargo/Road/Parking). Adds spawn/driving/lane cross costs. -
public static PathSpecification GetSpawnLocationSpecification(PathfindTrackData trackPathfindData, Entity accessRestriction)
Track spawn location spec. -
public static PathSpecification GetSpawnLocationSpecification(RouteConnectionType connectionType, PathfindConnectionData connectionPathfindData, RoadTypes roadType, float distance, Entity accessRestriction, bool requireAuthorization, bool allowEnter, bool allowExit)
Generic connection spawn spec handling pedestrian, road, track, and air (helicopter/airplane) options and associated costs. -
public static PathSpecification GetTransportLineSpecification(TransportLineData transportLineData, PathfindTransportData transportPathfindData, RouteInfo routeInfo)
Creates a PathSpecification for whole transport line segments using route distance/duration and transport line characteristics (passenger/cargo). -
public static LocationSpecification GetLocationSpecification(Curve curveData)
Returns a LocationSpecification containing a Line3.Segment from the curve's start to end (for placement/line queries). -
public static LocationSpecification GetLocationSpecification(Curve curveData, Game.Net.ParkingLane parkingLaneData)
Returns a LocationSpecification centered at the curve midpoint (used for parking spawn positions). -
public static LocationSpecification GetLocationSpecification(float3 position)
Return a LocationSpecification with zero-length segment at the position. -
public static LocationSpecification GetLocationSpecification(float3 position1, float3 position2)
Return a LocationSpecification representing the segment between two positions. -
public static void UpdateOwnedVehicleMethods(Entity householdEntity, ref BufferLookup<OwnedVehicle> ownedVehicleBuffs, ref PathfindParameters parameters, ref SetupQueueTarget origin, ref SetupQueueTarget destination)
If the household owns vehicles, update pathfinding parameters and setup targets to include vehicle (road+parking) methods, set parking size and ignored rules for combustion/heavy/slow traffic. -
public static bool IsPathfindingPurpose(Purpose purpose)
Utility to determine if a Purpose enum value is one of the pathfinding-relevant purposes (GoingHome, Hospital, Safety, EmergencyShelter, Crime, Escape, Sightseeing, VisitAttractions). Returns true for those, false otherwise.
Usage Example
// Example: build a PathSpecification for a car lane and compute its travel cost
Curve curve = ...; // obtained from curve component
Game.Net.CarLane carLane = ...; // from lane component
CarLaneData carLaneData = ...; // lane metadata
PathfindCarData carPathfindData = ...;
float density = 0.5f;
PathSpecification spec = PathUtils.GetCarDriveSpecification(curve, carLane, carLaneData, carPathfindData, density);
// compute deterministic cost using provided PathfindParameters
PathfindParameters parameters = default;
parameters.m_Methods = spec.m_Methods;
parameters.m_MaxSpeed = new float2(spec.m_MaxSpeed, 5.555556f);
parameters.m_Weights = new PathfindWeights { m_Value = new float4(1,1,1,1) };
parameters.m_PathfindFlags = PathfindFlags.Stable;
Random rng = new Random(12345);
float cost = PathUtils.CalculateCost(ref rng, spec, parameters);
If you want, I can produce a shorter reference listing only the most commonly used methods or generate example snippets for TryAppendPath and InitializeSpawnPath usage in a job/ECS context.