RLS Studios
ProjectsPatreonCommunityDocsAbout
Join Patreon
BeamNG Modding Docs

Guides

Reference

AI Module ReferenceBackwards Compatibility Module ReferenceBdebug Module ReferenceBdebugImpl Module ReferenceBeamstate Module ReferenceBullettime Module ReferenceController Module ReferenceDamageTracker Module ReferenceDrivetrain Module ReferenceElectrics Module ReferenceElectrics Custom Value ParserEnergyStorage Module ReferenceExtensions Module ReferenceFire Module ReferenceVehicle Engine True GlobalsGuihooks Module ReferenceGUI Streams Module ReferenceHTML Texture Module ReferenceHydros Module ReferenceInput Module ReferenceJBeam-Lua Integration GuideMapmgr Module ReferenceMaterial Module ReferenceBeamNG Math & Unit Conversions Referenceobj (Vehicle C++ Object)PartCondition Module ReferenceParticlefilter Module ReferenceParticles Module ReferencePowertrain Module ReferenceVehicle Property & Module TreeProps Module ReferenceProtocols Module ReferenceRecovery Module ReferenceScriptAI Module ReferenceSensors Module ReferenceSounds Module ReferenceStreams Module ReferenceThrusters Module Reference`v` (Vehicle Data & JBeam)Wheels Module Reference

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 Referenceve

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

GlobalTypeDescription
vmTypestringAlways "vehicle" in VE context. Identifies the Lua VM.
shippingBuildbooleanRelease flag. true in public builds, false in development.
printfunctionConsole logger. Outputs to the game console and log files.
float3typeAlias for vec3 (vector3) type.

Timing & Physics

GlobalTypeDescription
lastDtnumberTime delta of the last graphics frame (seconds).
physicsDtnumberFixed physics step time (default 0.0005s = 2000Hz).
profilerPushEventfunctionPush a profiling event marker.
profilerPopEventfunctionPop the current profiling event marker.

Vehicle Identity

GlobalTypeDescription
objectIdnumberUnique vehicle object ID in the game world.
vehiclePathstringRoot directory path of the vehicle files.

Player State

GlobalTypeDescription
playerInfotablePlayer seating information. Contains firstPlayerSeated, anyPlayerSeated, seatName.
setControllingPlayers(players)functionSets authority players for networked multiplayer.

Ghosting Flags

GlobalTypeDescription
ghostOnResetbooleanEnable collision ghosting after vehicle reset.
ghostOnTpbooleanEnable 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 complete

Frame Update Loop

function updateGFX(dt)                  -- Called every graphics frame (UI rate)
function onGraphicsStep(dtSim)          -- Called every graphics step

Physics 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 step

Debug Visualization

function onDebugDraw(x, y, z)           -- Called when debug drawing is enabled

Event Handlers

function onCallEvent(name, data)        -- Generic event dispatcher hook
function onSettingsChanged()            -- Called when game settings change

Structural 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 breaks

Coupling 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 detach

Lifecycle Events

function onVehicleReset()               -- Called when vehicle is reset (R key)
function onDespawnObject()              -- Called before vehicle is removed
function onNodeCollision(p)             -- Called when a node collides

Serialization

function exportPersistentData()         -- Return data to persist across resets
function importPersistentData(data)     -- Restore data from previous session

Primary Global Modules

These modules are loaded into the global scope and provide core vehicle functionality.

State Fields - Physics & State

VariableDescription
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 initialization
v.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 configuration

State Fields - Communication & UI

VariableDescription
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 M

State Fields - Vehicle Systems

VariableDescription
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

VariableDescription
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 parameter
props.init()
props.reset()
props.updateGFX(dt)
props.setPropValue(propName, value)     -- Set prop animation value

Utility 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 utility

See: mathUtils.md for unit conversions and constants.


All Registered Modules

Complete list of all core modules registered in the vehicle VM:

ModuleDescription
aiVehicle automation and pathing
backwardsCompatibilityLegacy mod support
bdebugDebug visualization proxy
beamstateDamage and structural state
controllerLogic controller manager
damageTrackerComponent damage tracking
drivetrainLegacy drivetrain proxy
electricsElectrical data bus
energyStorageFuel and battery containers
extensionsPlugin system
fireFire and thermal simulation
guihooksUI communication bridge
hydrosHydraulic actuators
inputUser input handling
mapmgrMap and navigation data
materialMaterial effects
particlefilterParticle filtering
particlesParticle effects
powertrainPhysical drive system
propsAnimated visual props
protocolsExternal telemetry protocols
recoveryRecovery and teleport
scriptaiScripted AI recording/playback
sensorsPhysical sensors
settingsVehicle settings
soundsAudio system
streamsTelemetry streaming
thrustersDirect force application
vVehicle data and JBeam
wheelsWheel and tire physics

Inter-VM Communication Summary

The vehicle Lua VM can communicate with other contexts:

FromToMethodSyntax
VEGEC++ Bridgeobj:queueGameEngineLua("code")
VEOther VEPeer Bridgeobj:queueObjectLuaCommand(id, "code")
VEUIEventguihooks.trigger("event", data)
VEUIStreamguihooks.queueStream("key", value)
VEInternalData Buselectrics.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 console

Fire 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.

On this page

See AlsoCore Environment Globals (main.lua)System ConstantsTiming & PhysicsVehicle IdentityPlayer StateGhosting FlagsEngine Lifecycle CallbacksInitializationFrame Update LoopPhysics Update Loop (2000Hz)Debug VisualizationEvent HandlersStructural EventsCoupling EventsLifecycle EventsSerializationPrimary Global ModulesState Fields - Physics & StateUsage ExampleState Fields - Communication & UIUsage ExampleState Fields - Vehicle SystemsUsage ExampleState Fields - Additional ModulesUsage ExampleUtility Globals (ve_utils.lua)All Registered ModulesInter-VM Communication SummaryQuick Reference: Most Used Globals