RLS Studios
ProjectsPatreonCommunityDocsAbout
Join Patreon
BeamNG Modding Docs

Guides

Reference

Server CommandsGE UtilitiesGame Engine MainNavigation GraphScreenshot CaptureServerServer ConnectionSpawnpoint ManagerSimulation TimeVehicle SpawningSuspension Frequency Tester
Bus DriverDamage GoalDemolition DerbyDistance GoalDrift GoalFinish Race GoalNo-Move GoalPosition GoalQuick RaceQuick Race LoaderRace MarkersRace DebugRace Goals ManagerRace UIScenario HelperScenario EngineScenarios LoaderSpeed GoalTime Limit GoalWaypoint ActionScenario Waypoints

UI

Resources

BeamNG Game Engine Lua Cheat SheetGE Developer RecipesMCP Server Setup

// RLS.STUDIOS=true

Premium Mods for BeamNG.drive. Career systems, custom vehicles, and immersive gameplay experiences.

Index

HomeProjectsPatreon

Socials

DiscordPatreon (RLS)Patreon (Vehicles)

© 2026 RLS Studios. All rights reserved.

Modding since 2024

API ReferenceGE Extensionsscenario

Scenario Engine

The main scenario engine. Manages the entire scenario lifecycle: loading, state transitions, countdown, racing, finishing, multiseat, vehicle processing, waypoint processing, and UI coordination. This

The main scenario engine. Manages the entire scenario lifecycle: loading, state transitions, countdown, racing, finishing, multiseat, vehicle processing, waypoint processing, and UI coordination. This is the largest and most central scenario file.


Internal State

FieldTypeDescription
M.onRaceWaypointReachedvariesAssigned as onRaceWaypointReached

Key Public API (Exports)

FunctionSignatureDescription
M.executeScenario(sc)Starts executing a scenario (loads level, extensions)
M.restartScenario()Restarts the current scenario from scratch
M.stop()Stops and unloads the scenario completely
M.endRace(countDownTime?)Triggers race end with optional countdown
M.endScenario(countDownTime?)Finishes scenario, hooks goals, applies slow-motion
M.finish(result)Pools a result (pass/fail) and triggers finish flow
M.getScenario()Returns the current scenario table
M.changeState(newState)Transitions scenario to a new state
M.freezeAll(state)Freezes/unfreezes all scenario vehicles
M.pauseScenario / M.continueScenario()Pauses/resumes simulation time
M.stopRaceTimer()Stops the race timer
M.getRaceDistance(scenario)Calculates total race distance from lapConfig
M.uiEventRetry()Restarts scenario (called from UI button)
M.uiEventFreeRoam()Transitions to free-roam mode
M.getVehicleName(vehicleID)Returns vehicle name from ID
M.rollingStartTriggered()Handles rolling start checkpoint crossing
M.spawnPrefab(val, objName, objFileName, objPos, objRotation, objScale)-
M.onClientEndMission()-
M.onClientStartMission()Hook called when a mission starts
M.onScenarioUIReady(state)-
M.onResetGameplay(playerID)-
M.prepareStartUI()-
M.onCameraModeChanged(modeName)-
M.trackVehicleMovementAfterDamage(vehicleName, trackingOptions)-
M.onPreRender(dt, dtSim)-
M.onVehicleStoppedMoving(vehicleID)-
M.onPhysicsUnpaused()-
M.onPhysicsPaused()-
M.onFilteredInputChanged(devName, action, value)-
M.onSerialize()-
M.onDeserialized(data)-
M.onExtensionUnloaded()-
M.displayStartUI()-
M.displayEndUI()-
M.updateVehicleAiState(vehicleName, data)-
M.onExtensionLoaded()-
M.onVehicleSelected(vehicleData)-
M.onBeamNGTrigger(data)-
M.getscenarioName()-

Scenario States

StateDescription
pre-startLevel loaded, prefabs spawned, vehicles frozen, extensions loading
pre-runningUI shown, markers initialized, goals set up, vehicles frozen
runningActive gameplay - sub-states: countdown, racing
finishedRace ended, results being gathered
postFinal UI shown, stats calculated
restartRestarting (clears and re-enters pre-start)

Race Sub-States (within running)

Sub-StateDescription
countdown3.5s countdown (or 1.5s if showCountdown is false)
racingActive race - timer running, goals checking
doneRace complete, transitioning to post

How It Works

Loading Flow

  1. executeScenario(sc) stores scenario, loads extensions, starts level via core_levels.startLevel
  2. onClientStartMission fires when level loads - creates ScenarioObjectsGroup, spawns prefabs, spawns user vehicle
  3. completeStartUp processes vehicles, waypoints, level state changes, input filters, camera setup

Race Flow

  1. pre-running → freezes vehicles, initializes markers, goals, waypoints
  2. running + countdown → shows countdown, unfreezes on completion
  3. running + racing → timer active, goals ticking, waypoints tracking
  4. endRace() → transitions to finished, hooks gather stats
  5. post → displays end UI with stats, medals, retry/freeRoam buttons

Vehicle Processing

  • Iterates BeamNGVehicle objects in scene
  • Maps vehicleNameToId and vehicleIdToName
  • Sets playerUsable and startFocus flags from scenario JSON
  • Applies vehicle extensions from config

AI Initialization

  • Reads driver config from scenario.vehicles[name].driver
  • Supports: ModeAI, AiAggression, targetAI, frozen, command, fleeTarget, roadDrivability

Key Subsystems

  • Multiseat: Supports multiple human players with device-to-vehicle assignment
  • Attempts: Configurable retry system with attemptsInfo for multiple attempts per scenario
  • Level State: Can modify scene objects (time of day, etc.) and restore on exit
  • Stats: Gathers end-of-race statistics via statistics_statistics
  • Camera Path: Supports intro camera paths via democam SimPath objects

Usage Example

-- Usually launched by scenariosLoader:
local sc = scenario_scenariosLoader.loadScenario(path)
scenario_scenarios.executeScenario(sc)

-- End race from goal code:
scenario_scenarios.finish({failed = "You crashed!"})
-- or
scenario_scenarios.finish({msg = "You won!"})

-- Get current scenario:
local scenario = scenario_scenarios.getScenario()
if scenario and scenario.state == 'running' then
  -- do something
end

Key Notes

  • File is ~2200 lines - the backbone of the scenario system
  • Uses simTimeAuthority for bullet time (1/8 speed during end screen)
  • inputActionFilter manages hotkey blacklists/whitelists per scenario
  • Camera blacklist prevents free cam during scenarios
  • onDrawDebug visualizes waypoint nodes in editor mode
  • Backward compatibility metatable warns about deprecated field names

Additional Exports

  • M.onDrawDebug - (undocumented)

See Also

  • Scenario Bus Driver - Bus Route Scenario Logic - Related reference
  • Scenario Damage Goal - Damage-Based Win/Fail Condition - Related reference
  • Scenario Demolition Derby - Last Vehicle Moving Wins - Related reference
  • Scenario System Guide - Guide

Scenario Helper

Utility library for scenario scripting. Provides helper functions to queue Lua commands on vehicles, configure AI behavior, flash UI messages, and measure distances between scene objects.

Scenarios Loader

M.dependencies = {'core_levels'}

On this page

Internal StateKey Public API (Exports)Scenario StatesRace Sub-States (within running)How It WorksLoading FlowRace FlowVehicle ProcessingAI InitializationKey SubsystemsUsage ExampleKey NotesAdditional ExportsSee Also