Vehicle Engine True Globals
Global variables and functions available in the BeamNG vehicle Lua VM (VE context). These globals provide access to vehicle physics, data, UI communication, and inter-VM bridging to the Game Engine (G
Global variables and functions available in the BeamNG vehicle Lua VM (VE context). These globals provide access to vehicle physics, data, UI communication, and inter-VM bridging to the Game Engine (GE).
See Also
- Obj: C++ Vehicle binding for physics manipulation.
- V: Vehicle JBeam data and configuration.
- Extensions: Plugin system for modular features.
- Guihooks: UI communication bridge.
- InitSequence: Lifecycle and initialization order.
- Communication: Inter-VM (VE/GE/UI) communication patterns.
Core Environment Globals (main.lua)
System Constants
| Global | Type | Description |
|---|---|---|
vmType | string | Always "vehicle" in VE context. Identifies the Lua VM. |
shippingBuild | boolean | Release flag. true in public builds, false in development. |
print | function | Console logger. Outputs to the game console and log files. |
float3 | type | Alias for vec3 (vector3) type. |
Timing & Physics
| Global | Type | Description |
|---|---|---|
lastDt | number | Time delta of the last graphics frame (seconds). |
physicsDt | number | Fixed physics step time (default 0.0005s = 2000Hz). |
profilerPushEvent | function | Push a profiling event marker. |
profilerPopEvent | function | Pop the current profiling event marker. |
Vehicle Identity
| Global | Type | Description |
|---|---|---|
objectId | number | Unique vehicle object ID in the game world. |
vehiclePath | string | Root directory path of the vehicle files. |
Player State
| Global | Type | Description |
|---|---|---|
playerInfo | table | Player seating information. Contains firstPlayerSeated, anyPlayerSeated, seatName. |
setControllingPlayers(players) | function | Sets authority players for networked multiplayer. |
Ghosting Flags
| Global | Type | Description |
|---|---|---|
ghostOnReset | boolean | Enable collision ghosting after vehicle reset. |
ghostOnTp | boolean | Enable collision ghosting after teleport. |
Engine Lifecycle Callbacks
These functions are called by the engine during specific lifecycle events. Override them to add custom logic.
Initialization
function init(path, initData) -- Entry point on vehicle spawn
function initSystems() -- Internal boot, called after init
function onVehicleLoaded() -- Called when physics initialization is completeFrame Update Loop
function updateGFX(dt) -- Called every graphics frame (UI rate)
function onGraphicsStep(dtSim) -- Called every graphics stepPhysics Update Loop (2000Hz)
function onPhysicsStep(dtPhys) -- High-frequency physics step (must enable first)
function enablePhysicsStepHook() -- Enable 2000Hz physics hook
function updateCorePhysicsStepEnabled() -- Check if any module needs physics stepDebug Visualization
function onDebugDraw(x, y, z) -- Called when debug drawing is enabledEvent Handlers
function onCallEvent(name, data) -- Generic event dispatcher hook
function onSettingsChanged() -- Called when game settings changeStructural Events
function onBeamBroke(id, energy) -- Called when a beam breaks
function onBeamDeformed(id, ratio) -- Called when a beam deforms
function onTorsionbarBroken(id) -- Called when a torsion bar breaks
function onDynamicBeamAdded(id) -- Called when a dynamic beam is created
function onDynamicBeamDeleted(id) -- Called when a dynamic beam is removed
function onDynamicBeamBroke(id, energy) -- Called when a dynamic beam breaksCoupling Events
function onCouplerFound(cid, obj2id, coupler2cid) -- Called when a coupler is found
function onCouplerAttached(cid, obj2id, coupler2cid) -- Called when couplers attach
function onCouplerDetached(cid, obj2id, coupler2cid, breakForce) -- Called when couplers detachLifecycle Events
function onVehicleReset() -- Called when vehicle is reset (R key)
function onDespawnObject() -- Called before vehicle is removed
function onNodeCollision(p) -- Called when a node collidesSerialization
function exportPersistentData() -- Return data to persist across resets
function importPersistentData(data) -- Restore data from previous sessionPrimary Global Modules
These modules are loaded into the global scope and provide core vehicle functionality.
State Fields - Physics & State
| Variable | Description |
|---|---|
obj - C++ Vehicle Object` | The obj global is a C++ binding to the Vehicle object. It provides direct access to physics. Key Methods: See: obj.md for complete documentation. |
v - Vehicle Data & JBeam` | The v global contains compiled JBeam data and vehicle configuration. Properties: Methods: See: v.md for complete documentation. |
Usage Example
-- Position & Orientation
obj:getPosition() -- Returns vec3 world position
obj:getPositionXYZ() -- Returns x, y, z numbers
obj:getRotation() -- Returns quat world rotation
obj:getVelocity() -- Returns vec3 world velocity
obj:getVelocityXYZ() -- Returns vx, vy, vz numbers
obj:getAngularVelocity() -- Returns vec3 angular velocity
obj:getDirectionVector() -- Returns forward unit vector
obj:getDirectionVectorUp() -- Returns up unit vector
obj:getRollPitchYaw() -- Returns roll, pitch, yaw angles
obj:getGroundSpeed() -- Returns speed relative to ground (m/s)
obj:getAltitude() -- Returns height above sea level
obj:calcCenterOfGravity() -- Returns COG world position
-- Physics Control
obj:setPhysicsStepEnabled(enabled) -- Toggle 2000Hz physics hook
obj:getPhysicsDt() -- Get physics step duration
obj:applyForce(node1, node2, magnitude) -- Apply force between nodes (N)
obj:applyForceVector(nodeId, vector) -- Apply force vector to node
obj:applyForceTime(n1, n2, mag, dur) -- Apply force for duration
obj:applyTorqueAxisCouple(mag, n1, n2, n3) -- Apply torque via 3 nodes
-- Node Access
obj:getNodePosition(cid) -- Get node position relative to ref
obj:getAbsNodePosition(cid) -- Get node position in world space
obj:getNodeMass(cid) -- Get node mass (kg)
obj:setNodeMass(cid, mass) -- Set node mass dynamically
obj:getNodeVelocityVector(cid) -- Get node velocity vector
obj:getNodeForceVector(cid) -- Get force on node
obj:getNodeCluster(cid) -- Get cluster ID for node
-- Beam State
obj:beamIsBroken(cid) -- Check if beam is broken
obj:getBeamLength(cid) -- Get current beam length
obj:getBeamRefLength(cid) -- Get beam rest length
obj:getBeamStress(cid) -- Get beam stress ratio
obj:setBeam(cid, id1, id2, str, spr, damp, ...) -- Modify beam properties
obj:breakBeam(cid) -- Manually break a beam
-- Environment
obj:getEnvTemperature() -- Get ambient temperature (Kelvin)
obj:getEnvPressure() -- Get ambient pressure
obj:getGroupPressure(groupId) -- Get pressure group pressure
obj:inWater(cid) -- Check if node is submerged
-- Audio
obj:createSFXSource(sample, profile, desc, nodeId, flags) -- Create sound source
obj:playSFX(handle) -- Play persistent sound
obj:stopSFX(handle) -- Stop persistent sound
obj:playSFXOnce(sample, nodeId, vol, pitch) -- Play one-shot sound
-- Inter-VM Communication (GE Bridge)
obj:queueGameEngineLua(cmd) -- Execute code in GE context
obj:queueObjectLuaCommand(targetId, cmd) -- Send command to another vehicle
obj:getId() / obj:getID() -- Get vehicle object ID
-- Management
obj:requestReset(mode) -- Request physics reset
obj:setGhostEnabled(enabled) -- Toggle collision ghosting
obj:setLoadComponent(name, bool) -- Toggle C++ components
obj:finishLoading() -- Finalize JBeam initializationv.data -- Compiled JBeam structure (nodes, beams, triangles)
v.config -- Part configuration and variables
v.data.nodes -- Table of all nodes (indexed by CID)
v.data.beams -- Table of all beams (indexed by CID)
v.data.triangles -- Aerodynamic collision triangles
v.data.refNodes -- Reference nodes for orientation
v.data.variables -- JBeam variables ($fuel, $tirepressure, etc.)
v.data.powertrain -- Powertrain configuration
v.data.energyStorage -- Energy storage configuration
v.data.controller -- Controller definitions
v.data.electrics -- Electrics mappings
v.data.information -- Vehicle metadata (name, brand, author)
v.loadVehicleStage2(initData) -- Internal vehicle loader
v.getPartConfig() -- Returns current part configurationState Fields - Communication & UI
| Variable | Description |
|---|---|
guihooks - UI Communication Bridge` | Communication bridge between vehicle Lua and the HTML/JavaScript UI. Methods: See: guihooks.md for complete documentation. |
extensions - Plugin System` | Infrastructure for managing vehicle extensions, dependency resolution, and event hooking. Methods: Lifecycle Hooks for Extensions: See: extensions.md and extensions/FOLDER_OVERVIEW.md for complete documentation. |
Usage Example
-- Messaging
guihooks.message(msg, ttl, category, icon) -- Display UI notification toast
-- Example: guihooks.message("Alert!", 5, "safety", "warning")
-- Event Triggering
guihooks.trigger(hookName, ...) -- Trigger JavaScript event
-- Example: guihooks.trigger("MyEvent", {value = 1})
-- Data Streaming (High Frequency)
guihooks.queueStream(key, value) -- Queue data for UI sync
guihooks.sendStreams() -- Transmit cached stream data
-- Example: guihooks.queueStream("custom_data", 42)
guihooks.triggerStream(streamName, streamData) -- Immediate stream transmission
-- Graphing
guihooks.graph(a, ...) -- Send data to Generic Graph app
-- Example: guihooks.graph({"RPM", 3000, 1, "rpm"})
-- Reset
guihooks.reset() -- Reset UI state (called on vehicle reset)-- Loading & Unloading
extensions.load(moduleName) -- Load and initialize an extension
extensions.unload(moduleName) -- Disable and unload an extension
extensions.reload(moduleName) -- Hot-reload an extension from disk
extensions.destroy() -- Unload all extensions
-- Hooking (Event Dispatch)
extensions.hook(funcName, ...) -- Call function on all loaded extensions
-- Example: extensions.hook("onReset") -- triggers onReset() in all extensions
-- Querying
extensions.isExtensionLoaded(extName) -- Check if extension is active
extensions.getLoadedExtensionsNames(excludeVirtual) -- Get list of active extensions
-- Module Paths
extensions.addModulePath(directory) -- Add folder to require() search path
-- Serialization
extensions.deserialize(data, filter) -- Restore extension states
-- In your extension file (lua/vehicle/extensions/myExt.lua):
local M = {}
function M.onInit() -- Called when extension loads
function M.onVehicleLoaded() -- Called when vehicle physics ready
function M.updateGFX(dt) -- Called every graphics frame
function M.onPhysicsStep(dt) -- Called every physics step (if enabled)
function M.onReset() -- Called on vehicle reset
function M.onDespawnObject() -- Called before vehicle removal
function M.onBeamBroke(id, energy) -- Called when beam breaks
return MState Fields - Vehicle Systems
| Variable | Description |
|---|---|
electrics - Electrical Data Bus` | Central shared memory for vehicle signals and electrical values. Properties: Standard Value Keys: Methods: See: electrics.md for complete documentation. |
powertrain - Drive System` | Physical torque/velocity simulation for engines, gearboxes, and drivetrain. Methods: See: powertrain.md for complete documentation. |
controller - Logic Hub` | Manager for vehicle controllers defined in JBeam. Methods: See: controller.md for complete documentation. |
beamstate - Damage & Structure` | Core damage tracking, breakgroups, and coupler management. Properties: Methods: See: beamstate.md for complete documentation. |
damageTracker - Component Damage` | Reporting system for tracking damage to specific vehicle components. Methods: See: damageTracker.md for complete documentation. |
wheels - Wheel Physics` | Individual wheel/tire data, thermals, and braking. Properties: Wheel Object Properties: Methods: See: wheels.md for complete documentation. |
input - User Input` | User input smoothing and driving assistants. Properties: Methods: See: input.md for complete documentation. |
Usage Example
electrics.values -- Master table of all electrical values
electrics.disabledState -- Table of disabled/overridden values
-- User Inputs (smoothed)
electrics.values.throttle -- 0 to 1
electrics.values.brake -- 0 to 1
electrics.values.clutch -- 0 to 1
electrics.values.steering -- -1 to 1
electrics.values.parkingbrake -- 0 to 1
-- Engine & Powertrain
electrics.values.rpm -- Engine RPM
electrics.values.maxrpm -- Max RPM
electrics.values.gear -- Gear name ("N", "1", "D", etc.)
electrics.values.gearIndex -- Gear number
electrics.values.wheelspeed -- Wheel speed (m/s)
electrics.values.airspeed -- Air speed (m/s)
-- Vehicle State
electrics.values.ignitionLevel -- 0=Off, 1=Acc, 2=On, 3=Start
electrics.values.engineRunning -- 0 or 1
electrics.values.fuel -- Fuel level 0 to 1
electrics.values.oiltemp -- Oil temperature (°C)
electrics.values.watertemp -- Water temperature (°C)
-- Lights & Signals
electrics.values.signal_L -- Left turn signal
electrics.values.signal_R -- Right turn signal
electrics.values.hazard -- Hazard lights
electrics.values.highbeam -- High beams
electrics.values.lowbeam -- Low beams
electrics.values.lightbar -- Emergency light state
electrics.init() -- Initialize electrics module
electrics.reset() -- Reset to defaults
electrics.updateGFX(dt) -- Update electrics (called by engine)
electrics.setIgnitionLevel(level) -- Set ignition (0-3)
electrics.horn(state) -- Control horn (true/false)
-- Signal controls
electrics.set_left_signal(state, autoCancel)
electrics.set_right_signal(state, autoCancel)
electrics.set_warn_signal(value)
electrics.stop_turn_signal()
-- Light controls
electrics.setLightsState(newval) -- 0=Off, 1=Low, 2=High
electrics.set_fog_lights(state)
electrics.light_flash_highbeams(enabled)
-- Toggles
electrics.toggle_lights()
electrics.toggle_highbeams()
electrics.toggle_left_signal()
electrics.toggle_right_signal()
electrics.toggle_warn_signal()
electrics.toggle_fog_lights()
electrics.toggle_lightbar_signal()powertrain.init() -- Initialize powertrain
powertrain.reset() -- Reset powertrain state
powertrain.update() -- Physics update (2000Hz)
powertrain.updateGFX(dt) -- Graphics update
-- Device Access
powertrain.getDevice(name) -- Get device by name
-- Example: local engine = powertrain.getDevice("mainEngine")
-- Device Tree Traversal
powertrain.getChild(device, port) -- Get child device at output port
powertrain.getParent(device) -- Get parent device
-- Torque Calculation
powertrain.calculateWantedEngineTorque(device, throttle)
-- Device Lists
powertrain.getDevicesByType(type) -- Get devices by type
powertrain.getDevicesByCategory(cat) -- Get devices by category
-- Properties
powertrain.engine -- Reference to main engine device
powertrain.deviceMap -- Map of all devices by name
powertrain.torqueConverter -- Reference to torque converter (if present)State Fields - Additional Modules
| Variable | Description |
|---|---|
sounds - Audio System` | Audio interface for engine, impact, and wind sounds. Methods: See: sounds.md for complete documentation. |
props - Visual Props` | Animated visual props (needles, steering wheels). Methods: See: props.md for complete documentation. |
ai - Vehicle AI` | Automation, pathing, and traffic control. Methods: See: ai.md for complete documentation. |
sensors - Physical Sensors` | Access to G-force, rotation, and physical sensors. Properties: Methods: See: sensors.md for complete documentation. |
fire - Fire Simulation` | Thermal damage and explosion simulation. Methods: See: fire.md for complete documentation. |
hydros - Hydraulic Actuators` | Hydraulic actuators and Force Feedback. Methods: See: hydros.md for complete documentation. |
thrusters - Direct Forces` | Direct physical forces applied to JBeam nodes. Methods: See: thrusters.md for complete documentation. |
recovery - Recovery System` | System for resets, towing, and world teleporting. Methods: See: recovery.md for complete documentation. |
mapmgr - Map Manager` | Navigation data, road analysis, and traffic tracking. Methods: See: mapmgr.md for complete documentation. |
partCondition - Part Wear` | Persistence for mileage and part health. Methods: See: partCondition.md for complete documentation. |
material - Material Effects` | Glowmaps and damaged textures. Methods: See: material.md for complete documentation. |
particles - Particle Effects` | Management of physical particles (dust, smoke, sparks). Methods: See: particles.md for complete documentation. |
streams - Telemetry Streaming` | High-frequency UI data streaming. Methods: See: streams.md for complete documentation. |
protocols - External Telemetry` | External telemetry standards (Outgauge, Outsim, Motion Sim). Methods: See: protocols.md for complete documentation. |
backwardsCompatibility - Legacy Support` | Legacy support layer for older mods. See: backwardsCompatibility.md for complete documentation. |
bdebug / bdebugImpl - Debug Visualization` | Visualization tools for nodes and beams. See: bdebug.md and bdebugImpl.md for complete documentation. |
Usage Example
sounds.init()
sounds.reset()
sounds.updateGFX(dt)
sounds.setSoundParameter(name, value) -- Set sound effect parameterprops.init()
props.reset()
props.updateGFX(dt)
props.setPropValue(propName, value) -- Set prop animation valueUtility Globals (ve_utils.lua)
Utility functions available in the global scope.
HighPerfTimer() -- Create a high-precision timer
-- Usage: local timer = HighPerfTimer(); ...; local ms = timer:stopAndReset()
tableFromHeaderTable(entry) -- Convert JBeam header table to dictionary
-- Converts JBeam's {["header1"]=1, ["header2"]=2} format to standard Lua table
saveCompiledJBeam(data, filename, lvl) -- Write compiled JBeam to file
-- For debugging JBeam compilation
getContrastColor(i, a) -- Generate contrasting colors
-- Returns color table for UI/graphing use
createCurve(points, returnArray) -- Create a spline curve
-- Returns a function that interpolates along the curve
PSItoPascal(psi) -- Convert PSI to Pascals
-- Pressure unit conversion utilitySee: mathUtils.md for unit conversions and constants.
All Registered Modules
Complete list of all core modules registered in the vehicle VM:
| Module | Description |
|---|---|
ai | Vehicle automation and pathing |
backwardsCompatibility | Legacy mod support |
bdebug | Debug visualization proxy |
beamstate | Damage and structural state |
controller | Logic controller manager |
damageTracker | Component damage tracking |
drivetrain | Legacy drivetrain proxy |
electrics | Electrical data bus |
energyStorage | Fuel and battery containers |
extensions | Plugin system |
fire | Fire and thermal simulation |
guihooks | UI communication bridge |
hydros | Hydraulic actuators |
input | User input handling |
mapmgr | Map and navigation data |
material | Material effects |
particlefilter | Particle filtering |
particles | Particle effects |
powertrain | Physical drive system |
props | Animated visual props |
protocols | External telemetry protocols |
recovery | Recovery and teleport |
scriptai | Scripted AI recording/playback |
sensors | Physical sensors |
settings | Vehicle settings |
sounds | Audio system |
streams | Telemetry streaming |
thrusters | Direct force application |
v | Vehicle data and JBeam |
wheels | Wheel and tire physics |
Inter-VM Communication Summary
The vehicle Lua VM can communicate with other contexts:
| From | To | Method | Syntax |
|---|---|---|---|
| VE | GE | C++ Bridge | obj:queueGameEngineLua("code") |
| VE | Other VE | Peer Bridge | obj:queueObjectLuaCommand(id, "code") |
| VE | UI | Event | guihooks.trigger("event", data) |
| VE | UI | Stream | guihooks.queueStream("key", value) |
| VE | Internal | Data Bus | electrics.values.key = value |
See: communication.md for complete inter-VM communication guide.
Quick Reference: Most Used Globals
-- Physics & Position
obj:getPosition() -- vec3 world position
obj:getVelocity() -- vec3 velocity (m/s)
obj:getID() -- Vehicle ID
-- Vehicle Data
v.data.nodes[cid] -- Access node data
v.data.beams[cid] -- Access beam data
-- Signals (Data Bus)
electrics.values.rpm -- Engine RPM
electrics.values.throttle -- Throttle input
electrics.values.wheelspeed -- Speed (m/s)
electrics.values.gear -- Current gear
-- Powertrain
powertrain.getDevice("mainEngine") -- Get engine device
powertrain.getDevice("gearbox") -- Get gearbox device
-- UI Communication
guihooks.message("Text", 5) -- Show toast message
guihooks.trigger("Event", data) -- Trigger UI event
guihooks.queueStream("key", value) -- Stream to UI
-- Extensions
extensions.hook("onReset") -- Call hook on all extensions
extensions.isExtensionLoaded("name") -- Check if extension loaded
-- Debug
print("Debug message") -- Log to consoleFire Module Reference
Module defined in `lua/vehicle/fire.lua`. Physics-based fire and thermal simulation. Fire can be triggered by high temperatures, collisions, or fuel tank ruptures.
Guihooks Module Reference
Communication bridge between vehicle Lua and game UI (JavaScript). This module handles event triggers, high-frequency data streams, and UI notifications.