Traffic System
Reference for `gameplay_traffic`, the master traffic system that spawns, manages, respawns, and pools AI traffic vehicles. This is the central orchestrator for all traffic behavior.
Reference for gameplay_traffic, the master traffic system that spawns, manages, respawns, and pools AI traffic vehicles. This is the central orchestrator for all traffic behavior.
Module Exports (M)
Setup & Lifecycle
| Function | Signature | Description |
|---|---|---|
setupTraffic | (amount?, policeRatio?, options?) → bool | Prepares vehicle groups and spawns traffic |
setupTrafficWaitForUi | (usePolice?) | Setup from radial menu with loading screen |
setupCustomTraffic | (amount?, params?) | Spawns traffic with custom multiSpawn params |
spawnTraffic | (amount?, groupData?, options?) | Low-level spawn via core_multiSpawn |
activate | (vehList?, ignoreFilter?) | Activates traffic mode for given vehicle IDs |
deactivate | (stopAi?) | Deactivates traffic for all vehicles |
toggle | (keepInMemory?) | Toggles traffic on/off in freeroam |
deleteVehicles | () | Deletes all traffic vehicles |
Vehicle Management
| Function | Signature | Description |
|---|---|---|
insertTraffic | (id, ignoreAi?, ignoreVehPool?) | Inserts vehicle into traffic table |
removeTraffic | (id, stopAi?) | Removes vehicle from traffic table |
refreshVehicles | () | Resets core data on all traffic vehicles |
Focus & Teleporting
| Function | Signature | Description |
|---|---|---|
setFocus | (mode?, data?) | Sets focus point ("camera", "vehicle", or "custom") |
getFocus | () → table | Returns current focus point data |
forceTeleport | (id, pos?, dir?, minDist?, maxDist?, targetDist?) | Force-teleports a traffic vehicle |
scatterTraffic | (vehIds?, minDist?, maxDist?) | Teleports a group of vehicles away |
State & Config
| Function | Signature | Description |
|---|---|---|
getState | () → string | Returns "off", "loading", "spawning", or "on" |
getTrafficVars | () → table | Returns current traffic variables |
setTrafficVars | (data, reset?) | Sets variables like aiMode, speedLimit, activeAmount |
setActiveAmount | (amount?) | Sets max visible vehicles |
setDebugMode | (value) | Toggles debug visualization |
Queries
| Function | Signature | Description |
|---|---|---|
getTrafficData | () → table | Returns the full traffic table (id → vehicle object) |
getTraffic | () → table | Alias for getTrafficData |
getTrafficList | () → table | Returns list of AI traffic vehicle IDs |
getTrafficAiVehIds | () → table | Alias for getTrafficList |
getTrafficAmount | (activeOnly?) → number | Returns traffic vehicle count |
getNumOfTraffic | (activeOnly?) → number | Alias for getTrafficAmount |
getTrafficPool | () → pool | Returns the vehicle active pooling object |
getIdealSpawnAmount | (amount?, ignoreAdjust?) → number | Calculates how many vehicles to spawn |
freezeState | () → trafficData, policeData, parkingData | Serializes traffic + police + parking state |
unfreezeState | (trafficData, policeData, parkingData) | Restores traffic + police + parking state |
Aliases
| Function | Signature | Description |
|---|---|---|
forceTeleportAll | (vehIds?, minDist?, maxDist?) | Alias for scatterTraffic |
trackAIAllVeh | (mode?) | Sets AI mode for all traffic vehicles (called from radial menu) |
Hooks / Lifecycle
| Function | Description |
|---|---|
onUpdate | Main per-frame loop: focus updates, pool management, traffic logic |
onPreRender | Debug visualization (lines, text) when debugMode is on |
onVehicleMapmgrUpdate | Completes spawn process when last vehicle processes mapmgr |
onVehicleSpawned | Updates traffic role/properties on vehicle replace |
onVehicleSwitched | Checks if new player vehicle should join traffic table |
onVehicleResetted | Re-checks player vehicle data |
onVehicleDestroyed | Removes vehicle from traffic |
onVehicleActiveChanged | Handles teleport flags when vehicles activate/deactivate in pool |
onVehicleGroupSpawned | Activates traffic after multiSpawn completes |
onTrafficStarted | Internal: initializes pool, focus, variables |
onTrafficStopped | Internal: cleans up pool and tables |
onClientStartMission | Sets worldLoaded flag |
onClientEndMission | Full reset of traffic system |
onUiWaitingState | Callback for loading UI - triggers parking + traffic setup |
onSerialize | Serializes traffic state for hot-reload |
onDeserialized | Restores traffic state after hot-reload |
Module Fields
| Field | Type | Default | Description |
|---|---|---|---|
debugMode | bool | false | Visual and logging debug mode |
showMessages | bool | true | Whether UI messages can be automatically shown |
forceFocus | bool | nil | Forces focus updates even when traffic is off |
M.activate | (vehList, ignoreFilter) | - | activate handler |
M.deactivate | (stopAi) | - | deactivate handler |
M.debugMode | value | - | visual and logging debug mode |
M.deleteVehicles | () | - | deleteVehicles handler |
M.dependencies | value | - | Returns list of extension dependencies |
M.forceTeleport | (id, pos, dir, minDist, maxDist, targetDist) | - | forceTeleport handler |
M.forceTeleportAll | (vehIds, minDist, maxDist) | - | forceTeleportAll handler |
M.freezeState | () | - | freezeState handler |
M.getFocus | () | - | Returns Focus |
M.getIdealSpawnAmount | (amount, ignoreAdjust) | - | Returns IdealSpawnAmount |
M.getNumOfTraffic | (activeOnly) | - | Returns NumOfTraffic |
M.getState | () | - | Returns State |
M.getTraffic | () | - | Returns Traffic |
M.getTrafficAiVehIds | () | - | Returns TrafficAiVehIds |
M.getTrafficAmount | (activeOnly) | - | Returns TrafficAmount |
M.getTrafficData | () | - | Returns TrafficData |
M.getTrafficList | () | - | Returns TrafficList |
M.getTrafficPool | () | - | Returns TrafficPool |
M.getTrafficVars | () | - | Returns TrafficVars |
M.insertTraffic | (id, ignoreAi, ignoreVehPool) | - | insertTraffic handler |
M.onClientEndMission | () | - | Callback for ClientEndMission event |
M.onClientStartMission | () | - | Callback for ClientStartMission event |
M.onDeserialized | (data) | - | Callback for Deserialized event |
M.onPreRender | (dt) | - | Callback for PreRender event |
M.onSerialize | () | - | Callback for Serialize event |
M.onTrafficStarted | () | - | Callback for TrafficStarted event |
M.onTrafficStopped | () | - | Callback for TrafficStopped event |
M.onUiWaitingState | () | - | Callback for UiWaitingState event |
M.onUpdate | (dtReal, dtSim) | - | Callback for Update event |
M.onVehicleActiveChanged | (vehId, active) | - | Callback for VehicleActiveChanged event |
M.onVehicleDestroyed | (id) | - | Callback for VehicleDestroyed event |
M.onVehicleGroupSpawned | (vehList, groupId, groupName) | - | Callback for VehicleGroupSpawned event |
M.onVehicleMapmgrUpdate | (id) | - | Callback for VehicleMapmgrUpdate event |
M.onVehicleResetted | (id) | - | Callback for VehicleResetted event |
M.onVehicleSpawned | (id) | - | Callback for VehicleSpawned event |
M.onVehicleSwitched | (oldId, newId) | - | Callback for VehicleSwitched event |
M.refreshVehicles | () | - | refreshVehicles handler |
M.removeTraffic | (id, stopAi) | - | removeTraffic handler |
M.scatterTraffic | (vehIds, minDist, maxDist) | - | scatterTraffic handler |
M.setActiveAmount | (amount) | - | Sets ActiveAmount |
M.setDebugMode | (value) | - | Sets DebugMode |
M.setFocus | (mode, data) | - | Sets Focus |
M.setTrafficVars | (data, reset) | - | Sets TrafficVars |
M.setupCustomTraffic | (amount, params) | - | Sets upCustomTraffic |
M.setupTraffic | (amount, policeRatio, options) | - | Sets upTraffic |
M.setupTrafficWaitForUi | (usePolice) | - | Sets upTrafficWaitForUi |
M.showMessages | value | - | if enabled, UI messages can be automatically shown |
M.spawnTraffic | (amount, groupData, options) | - | public interface |
M.toggle | (keepInMemory) | - | keepInMemory allows instantenous reactivation at the expense of RAM consumption when traffic is disabled |
M.trackAIAllVeh | (mode) | - | trackAIAllVeh handler |
M.unfreezeState | (trafficData, policeData, parkingData) | - | unfreezeState handler |
Internals
Traffic Variables (vars)
{
spawnValue = 1, -- respawn frequency (0 = disabled, 3 = rapid)
spawnDirBias = 0.2, -- direction bias (-1 away, 1 towards player)
activeAmount = huge, -- max active vehicles
baseAggression = 0.35, -- AI aggression
speedLimit = -1, -- global speed limit override (-1 = use road limits)
aiMode = "traffic", -- default AI mode
aiAware = "auto", -- car avoidance mode
aiDebug = "off", -- debug rendering
enableRandomEvents = false
}Vehicle Pooling
Traffic uses core_vehicleActivePooling to manage a pool of active/inactive vehicles. When the active count exceeds activeAmount, vehicles are deactivated (mesh hidden, physics stopped). Deactivated vehicles get _teleport flag and are repositioned when reactivated.
Spawning Theory
Vehicles respawn along a route ahead of the focus point. The system considers:
- Road density: Branch node count in 200m radius affects spawn distance
- Drivability: Roads below threshold are skipped; narrow roads get reduced drivability
- Direction scattering: Adjusts bias based on ratio of outbound vs inbound traffic
- Dynamic sampling: Every 5 seconds, samples local conditions to tune spawn parameters
Focus System
The focus point determines where traffic is centered:
"camera"(default): Game camera position and forward"vehicle": Player vehicle position and velocity vector"custom": Arbitrary position/direction- Auto mode switches between camera and vehicle based on context
How It Works
setupTraffic()creates vehicle groups (optionally with police), callsspawnTraffic()onVehicleGroupSpawned→activate()inserts vehicles into traffic tableonTrafficStartedinitializes the pool, focus, and variablesonUpdateruns the main loop: updates focus, processes vehicle pool, callsdoTraffic()doTrafficiterates all vehicles, calling theironUpdateand processing one respawn per frame- When a vehicle goes out of range, it fades out and re-queues for respawn ahead
Usage Example
-- Start traffic with 10 vehicles, 25% police
gameplay_traffic.setupTraffic(10, 0.25)
-- Adjust traffic speed limit
gameplay_traffic.setTrafficVars({speedLimit = 13.89}) -- 50 km/h
-- Get all traffic data
local data = gameplay_traffic.getTrafficData()
for id, veh in pairs(data) do
log("I", "", string.format("Vehicle %d: %s at %0.1f m/s", id, veh.modelName, veh.speed))
end
-- Toggle traffic off/on
gameplay_traffic.toggle()See Also
- Gameplay Achievement - Related reference
- Gameplay City - Related reference
- discover - Discover / Experience System - Related reference
- Gameplay Systems Guide - Guide
Taxi Ride System
Reference for `gameplay_taxi`, which manages the full taxi ride experience - finding nearby taxis, hailing, entering, choosing a destination via the big map, AI-driven travel, idle camera, skip/telepo
Vehicle Performance
Reference for `gameplay_vehiclePerformance`, which calculates a Performance Index (PI) from drag test data and assigns vehicles to performance classes (D through X).