BeamNGpy Reference

Submodules

beamngpy.beamng module

beamngpy.beamngcommon module

exception beamngpy.beamngcommon.BNGDisconnectedError

Bases: ValueError

Exception class for BeamNGpy being disconnected when it shouldn’t.

exception beamngpy.beamngcommon.BNGError

Bases: Exception

Generic BeamNG error

exception beamngpy.beamngcommon.BNGValueError

Bases: ValueError

Value error specific to BeamNGpy.

class beamngpy.beamngcommon.Config

Bases: dict

Configuration class which mainly wraps around a dictionary to offer access to keys as members. Instead of spam[“eggs”], it”s possible to simply go spam.eggs.

load(cfg_file)

Loads every key-value pair in the given json file into the config.

load_values(dic)

Loads every key-value pair from the given dictionary into the config.

save(cfg_file)

Saves every key-value pair of this config into the given json file.

beamngpy.beamngcommon.ack(ack_type)
beamngpy.beamngcommon.angle_to_quat(angle)

Converts an euler angle to a quaternion.

Parameters

angle (tuple) – Euler angle (degrees)

Returns

Quaterion with the order (x, y, z, w) with w representing the real component

beamngpy.beamngcommon.compute_rotation_matrix(quat)

Calculates the rotation matrix for the given quaternion to be used in a scenario prefab.

Parameters

quat (tuple) – Quaterion with the order (x, y, z, w) with w representing the real component

Returns

The rotation matrix as np array.

beamngpy.beamngcommon.config_logging(handlers, replace=True, level=10, redirect_warnings=True, log_communication=False)

Function to configure logging. :param handlers: list of already configured logging.Handler objects :type handlers: list :param replace: whether to replace existing list of handlers with new ones or whether to add them, optional :type replace: bool :param level: log level of the beamngpy logger object, optional :type level: int :param redirect_warnings: whether to redirect warnings to the logger. Beware that this modifies the warnings settings. :type redirect_warnings: bool :param log_communication: whether to log the BeamNGpy protocol messages between BeamNGpy and BeamNG.tech, optional :type log_communication: bool

beamngpy.beamngcommon.create_warning(msg, category=None)

Helper function for BeamNGpy modules to create warnings.

Parameters
  • msg (string) – message to be displayed

  • category (exception, optional) – Category of warning to be issued. See warnings documentation for more details. Defaults to None.

beamngpy.beamngcommon.ensure_config(cfg_file)

Tests if the given cfg_file path points to a configuration file. If not, a default configuration will be written to that file. The file is then loaded into the CFG field.

beamngpy.beamngcommon.get_default()

Creates and returns an instance of the Config class with the default value for each option.

beamngpy.beamngcommon.quat_as_rotation_mat_str(quat)

For a given quaternion, the function computes the corresponding rotation matrix and converts it into a string.

Parameters
  • quat (tuple) – Quaterion with the order (x, y, z, w) with w

  • component (representing the real) –

Returns

Rotation matrix as string

beamngpy.beamngcommon.recv_msg(skt)

Reads a messagepack-encoded message from the given socket, decodes it, and returns it. Before the raw message bytes are read, this function expects the amount of bytes to read being sent as a zero-padded 16-character string.

Parameters

skt (socket) – The socket to read from

Returns

The decoded message.

beamngpy.beamngcommon.send_msg(skt, data)

Encodes the given data via messagepack and sends the bytes over the given socket. Before the raw message bytes are sent, the amount of bytes the message is long is sent as a zero-padded 16-character string.

Parameters
  • skt (socket) – The socket to write to

  • data (dict) – The data to encode and send

beamngpy.beamngcommon.set_up_simple_logging(log_file=None, redirect_warnings=None, level=20, log_communication=False)

Helper function that provides high-level control over beamng logging. For low-level control over the logging system use beamngcommon.config_logging. Sets up logging to sys.stderr and optionally to a given file. Existing log files are moved to <log_file>.1. By default beamngpy logs warnings and errors to sys.stderr, so this function is only of use, if the log output should additionaly be written to a file, or if the log level needs to be adjusted.

Parameters
  • log_file (str) – log filename, optional

  • redirect_warnings (bool) – Whether to redirect warnings to the logger. Beware that this modifies the warnings settings.

  • level (int) – log level of handler that is created for the log file

  • log_communication (bool) – whether to log the BeamNGpy protocol messages between BeamNGpy and BeamNG.tech, optional

beamngpy.level module

class beamngpy.level.Level(name, size, path, **props)

Bases: object

Represents a level in the simulator, listing various properties like the level’s name, size, and available scenarios.

static from_dict(d)

beamngpy.noise module

beamngpy.scenario module

class beamngpy.scenario.DecalRoad(options)

Bases: SceneObject

class beamngpy.scenario.MeshRoad(top_material, bottom_material=None, side_material=None, rid=None, default_width=10.0, default_depth=5.0, **options)

Bases: object

This class represents a MeshRoad in the environment. It contains information about the road’s materials, direction-ness of lanes, and geometry of the edges that make up the road.

add_nodes(*nodes)

Adds a list of nodes to this decal road.

Parameters

nodes (list) – List of (x, y, z), (x, y, z, width) or (x, y, z, width, depth) tuples of the road’s nodes.

class beamngpy.scenario.ProceduralBump(pos, rot, width, length, height, upper_length, upper_width, name, rot_quat=None, material=None)

Bases: ProceduralMesh

place(bng)
class beamngpy.scenario.ProceduralCone(pos, rot, radius, height, name, rot_quat=None, material=None)

Bases: ProceduralMesh

place(bng)
class beamngpy.scenario.ProceduralCube(pos, rot, size, name, rot_quat=None, material=None)

Bases: ProceduralMesh

place(bng)
class beamngpy.scenario.ProceduralCylinder(pos, rot, radius, height, name, rot_quat=None, material=None)

Bases: ProceduralMesh

place(bng)
class beamngpy.scenario.ProceduralMesh(pos, rot, name, material, rot_quat=None)

Bases: ScenarioObject

place(bng)
class beamngpy.scenario.ProceduralRing(pos, rot, radius, thickness, name, rot_quat=None, material=None)

Bases: ProceduralMesh

place(bng)
class beamngpy.scenario.Road(material, rid=None, interpolate=True, default_width=10.0, **options)

Bases: object

This class represents a DecalRoad in the environment. It contains information about the road’s material, direction-ness of lanes, and geometry of the edges that make up the road.

add_nodes(*nodes)

Adds a list of nodes to this decal road.

Parameters

nodes (list) – List of (x, y, z) or (x, y, z, width) tuples of the road’s nodes.

class beamngpy.scenario.Scenario(level, name, path=None, **options)

Bases: object

The scenario class contains information for setting up and executing simulation scenarios along with methods to extract data during their execution.

add_camera(camera, name)

Adds a beamngpy.sensors.Camera to this scenario which can be used to obtain rendered frames from a location in the world (e.g. something like a surveillance camera.)

Parameters
  • camera (beamngpy.sensors.Camera) – The camera to add.

  • name (str) – The name the camera should be identified with.

add_checkpoints(positions, scales, ids=None)

Adds checkpoints to the scenario.

Parameters
  • positions (list) – positions (tuple of length 3) of individual points

  • scales (list) – scale (tuple of length 3) of individual points

  • ids (list) – optional, names of the individual points

add_mesh_road(road)

Adds a mesh road to this scenario.

Parameters

road (beamngpy.MeshRoad) – mesh road to be added to the scenario.

add_object(obj)

Adds an extra object to be placed in the prefab. Objects are expected to be ScenarioObject instances with additional, type- specific properties in that class’s opts dictionary.

add_procedural_mesh(mesh)

Adds a ProceduralMesh to be placed in world to the scenario.

Parameters

mesh (ProceduralMesh) – The mesh to place.

add_road(road)

Adds a road to this scenario.

Parameters

road (beamngpy.Road) – road to be added to the scenario.

add_vehicle(vehicle, pos=(0, 0, 0), rot=None, rot_quat=(0, 0, 0, 1), cling=True)

Adds a vehicle to this scenario at the given position with the given orientation. This method has to be called before a scenario is started.

Parameters
  • pos (tuple) – (x,y,z) tuple specifying the position of the vehicle.

  • rot (tuple) – (x,y,z) tuple expressing the rotation of the vehicle in Euler angles around each axis. Deprecated.

  • rot_quat (tuple, optional) – (x, y, z, w) tuple specifying the rotation as quaternion

close()

Closes open connections and allocations of the scenario.

connect(bng)

Connects this scenario to the simulator, hooking up any cameras to their counterpart in the simulator.

decode_frames(camera_data)

Decodes raw camera sensor data as a Image

delete(bng)

Deletes files created by this scenario from the given BeamNGpy’s home/user path.

encode_requests()

Encodes the sensor requests of cameras placed in this scenario for the simulator.

Returns

Dictionary of camera names to their corresponding sensor requests.

find(bng)

Looks for the files of an existing scenario and returns the path to the info file of this scenario, iff one is found.

Parameters

bng (BeamNGpy) – The BeamNGpy instance to look for the scenario in.

Returns

The path to the information file of his scenario found in the simulator as a string, None if it could not be found.

find_procedural_meshes()

Finds procedural meshes placed in the world right now.

Returns

A list of ScenarioObject containing procedural meshes found in the world.

Raises

BNGError – If the scenario is not currently loaded.

find_static_objects()

Finds static objects placed in the world right now.

Returns

A list of ScenarioObject containing statically placed objects found in the world.

Raises

BNGError – If the scenario is not currently loaded.

find_waypoints()

Finds waypoints placed in the world right now.

Returns

A list of ScenarioObject containing waypoints found in the world.

Raises

BNGError – If the scenario is not currently loaded.

static from_dict(d)
game_classes = {'DecalRoad': <function Scenario.<lambda>>, 'MissionGroup': <function Scenario.<lambda>>}
get_engine_flags()

Gathers engine flags to set for cameras in this scenario to work.

Returns

Dictionary of flag names to their state.

get_vehicle(vehicle_id)

Retrieves the vehicle with the given ID from this scenario.

Parameters

vehicle_id (str) – The ID of the vehicle to find.

Returns

The Vehicle with the given ID. None if it wasn’t found.

make(bng)

Generates necessary files to describe the scenario in the simulation and outputs them to the simulator.

Parameters

bng (BeamNGpy) – The BeamNGpy instance to generate the scenario for.

Returns

The path to the information file of this scenario in the simulator.

remove_vehicle(vehicle)

Removes the given Vehicle: from this scenario. If the scenario is currently loaded, the vehicle will be despawned.

Parameters

vehicle (Vehicle) – The vehicle to remove.

render_cameras()

Renders images for each of the cameras place in this scenario.

Returns

A dictionary mapping camera names to color, annotation, or depth images, depending on how each camera is set up.

Raises
  • BNGError – If the scenario is currently not loaded.

  • DeprecationWarning – Always, return type will be None in future versions, we recommend to access sensor data through the Camera object instead of relying on the return value of this function.

restart()

Restarts this scenario. Requires the scenario to be loaded into a running BeamNGpy instance first.

Notes

If any vehicles have been added during the scenario after it has been started, they will be removed as the scenario is reset to its original state.

Raises

BNGError – If the scenario has not been loaded.

set_initial_focus(vehicle_id)

defines which vehicle has the initial focus

Parameters

vehicle_id (string) – vehicle id of focussed vehicle

start()

Starts this scenario. Requires the scenario to be loaded into a running BeamNGpy instance first.

Raises

BNGError – If the scenario is not loaded.

sync_scene()

Retrieves the current scene tree of the scenario from the simulator, converting them into the most appropriate known (sub)class of SceneObject. The result is not returned but rather stored in the scene field of this class.

update()

Synchronizes object states of this scenario with the simulator. For example, this is used to update the Vehicle.state fields of each vehicle in the scenario.

Raises

BNGError – If the scenario is currently not loaded.

class beamngpy.scenario.ScenarioObject(oid, name, otype, pos, rot, scale, rot_quat=None, **options)

Bases: object

This class is used to represent objects in the simulator’s environment. It contains basic information like the object type, position, rotation, and scale.

static from_game_dict(d)
class beamngpy.scenario.SceneObject(options)

Bases: object

class beamngpy.scenario.StaticObject(name, pos, rot, scale, shape, rot_quat=None)

Bases: ScenarioObject

beamngpy.sensors module

This module implements various sensors that can be attached to vehicles to extract data from simulations.

class beamngpy.sensors.AbstractSensor

Bases: ABC

Abstract Sensor class declaring properties common to the ordinary and noise sensors.

abstract property data
class beamngpy.sensors.Camera(pos, direction, fov, resolution, near_far=(0.01, 1000), colour=False, depth=False, depth_distance=(0.01, 1000), depth_inverse=False, annotation=False, instance=False, shmem=True)

Bases: Sensor

A camera sensor provides several types of image data from a user-defined perspective relative to the vehicle. It can provide the following types of data:

  • Colour images

  • Pixel-wise depth

  • Pixel-wise object annotation

  • Pixel-wise instance annotation to separate overlapping objects of the same type

A single camera sensor can be configured to provide any or all of these data at once, ensuring they all align to the same perspective.

attach(vehicle, name)

This method is called when the camera is attached and allocates shared memory space to house the sensor data the camera is supposed to provide.

Parameters
  • vehicle (Vehicle) – The vehicle the camera is being attached to.

  • name (str) – The name of the camera.

connect(bng, vehicle)

This method is called when the vehicle is set up in the simulation. It’s used to inform the simulation about the shared memory used to exchange sensor data for this camera.

Parameters
  • bng (BeamNGpy) – Running instance of BeamNGpy.

  • vehicle (Vehicle) – The vehicle being connected.

decode_b64_response(resp)
decode_image(buffer, width, height, channels, dtype=numpy.uint8)
decode_response(resp)

Called to do post-processing on sensor data obtained from the simulation. This method is called after raw simulation data is received and the resulting processed data is considered the result of a sensor request.

Example

Consult the implementation of the Camera sensor for a good example of decoding sensor data.

decode_shmem_response(resp)

This method obtains sensor data written to shared memory and decodes them as images. The resulting data is returned as a dictionary. This dictionary contains an entry for each requested image type that is mapped to a PIL.Image instance.

Parameters

resp (dict) – The raw sensor data as a dictionary that was returned by the simulation.

Returns

The decoded response as a dictionary.

detach(vehicle, name)

This method is called when the camera is detached from the vehicle. It de-allocates the shared memory space obtained for sensor data.

Parameters
  • vehicle (Vehicle) – The vehicle the camera is being detached from.

  • name (str) – The name of the camera.

disconnect(bng, vehicle)

This method is called when the vehicle is disconnected from the simulation. It’s used to tell the simulation to close the shared memory used to exchange sensor data for this camera.

Parameters
  • bng (BeamNGpy) – Running instance of BeamNGpy.

  • vehicle (Vehicle) – The vehicle being disconnected.

static draw_bboxes(bboxes, color, width=3, font='arial.ttf', fontsize=14)

Draws the given list of bounding boxes onto the given image. The boxes are drawn with the given width of outlines in pixels and the given font and size configuration. The given image is not directly modified and the boxes are drawn onto a copy. The bboxes are expected to be in the format returned by extract_bboxes.

Parameters
  • bboxes (list) – List of bounding boxes to draw. Consult the documentation of extract_bboxes for information on the structure of this list.

  • color (Image) – The image to draw bounding boxes on. Will be copied and not modified in place.

  • width (int) – The width of bounding box outlines in pixels.

  • font (str) – A string specifying the font bounding box labels are supposed to have.

  • fontsize (int) – The font size to draw labels with.

Returns

A :class:.Image` that is a copy of the given image with bounding boxes drawn onto it.

encode_engine_request()

This method encodes a render request to the simulation engine along with the properties this camera is configured with.

Returns

The request to the engine as a dictionary. This dictionary contains fields for each property of the requested render and which modes (colour, depth, annotation) to render in.

static export_bbox_xml(bboxes, folder=None, filename=None, path=None, database=None, size=None)

Exports the given list of bounding boxes to the Pascal-VOC XML standard. The bounding box list is expected to be in the format that extract_bboxes returns. Additional properties to this function correspond to tags in the Pascal-VOC standard.

Parameters
  • bboxes (list) – The list of bounding boxes the export. Consult the documentation of extract_bboxes for information on its expected structure.

  • folder (str) – Contents of the <folder> tag. Optional.

  • filename (str) – Contents of the <filename> tag. Optional.

  • path (str) – Contents of the <path> tag. Optional.

  • database (str) – Contents of the <database> tag. Optional.

  • size (tuple) – Contents of the <size> tag. It’s expected to be a tuple of the image width, height, and depth. Optional.

Returns

XML string encoding the given list of bounding boxes according to Pascal-VOC.

static extract_bboxes(semantic, instance, classes)

Analyzes the given semantic annotation and instance annotation images for its object bounding boxes. The identified objects are returned as a list of dictionaries containing their bounding box corners, class of object according to the corresponding color in the semantic annotations and the provided class mapping, and the color of the object in the instance annotation.

Parameters
  • semantic (Image) – The image containing semantic annotation information

  • instance (Image) – The image containing instance annotation information

  • classes (dict) – A mapping of colors to their class names to identify object types based on the semantic annotation information. The keys in this dictionary are the respective colors expressed as a 24bit integer, i.e. r * 256^2 + g * 256 + b.

Returns

A list of bounding boxes specified as dictionaries. One example bounding box dictionary contains:

'bbox': [minx, miny, maxx, maxy],
'color': [233, 11, 15],
'class': ['CAR'],

Where minx, miny, maxx, maxy specify the corners of the bounding box, color contains the RGB color of the object in the instance annotations, and class the object type identified through the given class mapping.

get_engine_flags()

Called to retrieve settings for the simulation engine. Depending on the types of data this camera is supposed to provide, this method returns a dictionary enabling certain render modes in the engine.

class beamngpy.sensors.Damage

Bases: Sensor

The damage sensor retrieves information about how damaged the structure of the vehicle is. It’s important to realise that this is a sensor that has no analogue in real life as it returns a perfect knowledge overview of how deformed the vehicle is. It’s therefore more of a ground truth than simulated sensor data.

encode_vehicle_request()

Called to retrieve this sensor’s request to the vehicle as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the attached vehicle.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Electrics sensor for a good example of a vehicle request.

Returns

The request to send to the vehicle as a dictionary.

class beamngpy.sensors.Electrics

Bases: Sensor

This sensor is used to retrieve various values made available by the car’s eletrics systems. These values include:

# TODO: List all the electrics.lua values. - abs (int): ABS state - abs_active (bool): - airspeed (float): Airspeed - airflowspeed (float): - altitude (float): Z axis position - avg_wheel_av (float): - brake (int): Brake value - brake_lights (int): - brake_input (int): Brake input value - check_engine (bool): Check engine light state. - clutch (int): Clutch value - clutch_input (int): Clutch input value - clutch_ratio (int): - driveshaft (float): Driveshaft - engine_load (float): - engine_throttle (int): Engine throttle state - esc (int): ESC state. 0 = not present/inactive, 1 = disabled, Blink = active - esc_active (bool): - exhaust_flow (float): - fog_lights (int): Fog light state - fuel (float): Percentage of fuel remaining. - fuel_capacity (int): Total Fuel Capacity [L]. - fuel_volume (float): - gear (int): - gear_a (int): Gear selected in automatic mode. - gear_index (int): - gear_m (int): Gear selected in manual mode. - hazard (int): Hazard light state - hazard_signal (bool): - headlights (int): - highbeam (int): High beam state - horn (int): - ignition (bool): Engine state - left_signal (bool): - lightbar (int): Lightbar state - lights (int): General light state. 1 = low, 2 = high - lowbeam (int): Low beam state - lowfuel (bool): Low fuel indicator - lowhighbeam (int): Low-high beam state - lowpressure (int): Low fuel pressure indicator - oil (int): - oil_temperature (float): Oil temperature [C]. - parking (int): Parking lights on/off (not implemented yet) - parkingbrake (float): Parking brake state. 0.5 = halfway on - parkingbrake_input (int): Parking brake input state - radiator_fan_spin (int): - reverse (int): Reverse gear state - right_signal (bool): - rpm (float): Engine RPM - rpmspin (float): - rpm_tacho (float): - running (bool): Engine running state - signal_l (int): Left signal state. 0.5 = halfway to full blink - signal_r (int): Right signal state. 0.5 = halfway to full blink - steering (int): Steering state - steering_input (int): Steering input state - tcs (int): TCS state. 0 = not present/inactive, 1 = disabled, Blink = active - tcs_active (bool): - throttle (int): Throttle state - throttle_factor (int): - throttle_input (int): Throttle input state - turnsignal (int): Turn signal value. -1 = Left, 1 = Right, gradually ‘fades’ between values. Use “signal_L” and “signal_R” for flashing indicators. - two_step (bool): - water_temperature (float): Water temperature [C]. - wheelspeed (float): Wheel speed [m/s].

decode_response(resp)

Called to do post-processing on sensor data obtained from the simulation. This method is called after raw simulation data is received and the resulting processed data is considered the result of a sensor request.

Example

Consult the implementation of the Camera sensor for a good example of decoding sensor data.

encode_vehicle_request()

Called to retrieve this sensor’s request to the vehicle as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the attached vehicle.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Electrics sensor for a good example of a vehicle request.

Returns

The request to send to the vehicle as a dictionary.

name_map = {'absActive': 'abs_active', 'avgWheelAV': 'avg_wheel_av', 'brakelights': 'brake_lights', 'checkengine': 'check_engine', 'clutchRatio': 'clutch_ratio', 'engineLoad': 'engine_load', 'engineThrottle': 'engine_throttle', 'escActive': 'esc_active', 'exhaustFlow': 'exhaust_flow', 'fog': 'fog_lights', 'fuelCapacity': 'fuel_capacity', 'fuelVolume': 'fuel_volume', 'gearIndex': 'gear_index', 'gear_A': 'gear_a', 'gear_M': 'gear_m', 'hazard_enabled': 'hazard_signal', 'isShifting': 'is_shifting', 'lights_state': 'headlights', 'oiltemp': 'oil_temperature', 'radiatorFanSpin': 'radiator_fan_spin', 'rpmTacho': 'rpm_tacho', 'signal_L': 'signal_l', 'signal_R': 'signal_r', 'signal_left_input': 'left_signal', 'signal_right_input': 'right_signal', 'tcsActive': 'tcs_active', 'throttleFactor': 'throttle_factor', 'twoStep': 'two_step', 'watertemp': 'water_temperature'}
class beamngpy.sensors.GForces

Bases: Sensor

This sensor is used to obtain the GForces acting on a vehicle.

# TODO: GForce sensor for specific points on/in the vehicle

encode_vehicle_request()

Called to retrieve this sensor’s request to the vehicle as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the attached vehicle.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Electrics sensor for a good example of a vehicle request.

Returns

The request to send to the vehicle as a dictionary.

class beamngpy.sensors.IMU(pos=None, node=None, name=None, debug=False)

Bases: Sensor

An IMU measures forces and rotational acceleration at a certain point on a vehicle. This can be used to analyze forces acting on certain areas of the car (like the driver’s position) or estimate the trajectory of a vehicle from its rotation and acceleration.

connect(bng, vehicle)

Called when the attached vehicle is being initialised in the simulation. This method is used to perform setup code that requires the simulation to be running.

disconnect(bng, vehicle)

Called when the attached vehicle is being removed from simulation. This method is used to perform teardown code after the simulation.

encode_vehicle_request()

Called to retrieve this sensor’s request to the vehicle as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the attached vehicle.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Electrics sensor for a good example of a vehicle request.

Returns

The request to send to the vehicle as a dictionary.

class beamngpy.sensors.Lidar(useSharedMemory=False, pos=(0, 0, 1.7), dir=(0, -1, 0), vres=64, vAngle=26.9, rps=2200000, hz=20, hAngle=360, maxDist=120, isVisualised=True, isAnnotated=False, isStatic=False, isSnappingDesired=False, isForceInsideTriangle=False)

Bases: Sensor

attach(vehicle, name)

Called when the liDAR sensor is attached to a vehicle. This method allocates shared memory space to exchange liDAR data with the engine.

Parameters
  • vehicle (Vehicle) – The vehicle the sensor is being attached to.

  • name (str) – The name of the sensor.

connect(bng, vehicle)

Called when the LiDAR sensor is connected to a vehicle. :param vehicle: The vehicle the sensor is being connected to. :type vehicle: Vehicle

decode_response(resp)

Reads the raw point cloud the simulation wrote to the shared memory and creates a numpy array of points from them. The recoded response is returned as a dictionary with the numpy array in the points entry.

Returns

The decoded response as a dictionary with the point cloud as a numpy array in the points entry. The numpy array is a linear sequence of coordinate triplets in the form of [x0, y0, z0, x1, y1, z1, …, xn, yn, zn].

detach(vehicle, name)

Called when the LiDAR sensor is detached from a vehicle. This method de-allocates the shared memory used to exchange LiDAR data with the engine.

Parameters
  • vehicle (Vehicle) – The vehicle the sensor is being detached from.

  • name (str) – The name of the sensor.

disconnect(bng, vehicle)

Called when the attached vehicle is being removed from simulation. This method is used to perform teardown code after the simulation.

encode_engine_request()

Called to obtain the engine request for this LiDAR sensor. Encodes the properties of this LiDAR to obtain data according to them.

Returns

The engine request containing the settings of this LiDAR sensor as a dictionary.

get_engine_flags()

Returns: a dictionary with the engine flag to enable Lidar.

max_points = 2000000
shmem_size = 24000000
class beamngpy.sensors.Sensor

Bases: AbstractSensor

Sensor meta-class declaring methods common to them.

attach(vehicle, name)

Called when the sensor is attached to a Vehicle instance. Used to perform sensor setup code before the simulation is started. This is called after the sensor has been entered into the vehicle’s map of sensors under the given name.

Parameters
  • vehicle (Vehicle) – The vehicle instance the sensor is being attached to.

  • name (str) – The name the sensor is known under to the vehicle.

connect(bng, vehicle)

Called when the attached vehicle is being initialised in the simulation. This method is used to perform setup code that requires the simulation to be running.

property data

Property used to store sensor readings.

decode_response(resp)

Called to do post-processing on sensor data obtained from the simulation. This method is called after raw simulation data is received and the resulting processed data is considered the result of a sensor request.

Example

Consult the implementation of the Camera sensor for a good example of decoding sensor data.

detach(vehicle, name)

Called when the sensor is detached from a Vehicle instance. Used to perform sensor teardown code after the simulation is finished. This is called after the sensor has been removed from the vehicle’s map of sensors under the given name.

Parameters
  • vehicle (Vehicle) – The vehicle instance the sensor is being detached from.

  • name (str) – The name the sensor was known under to the vehicle.

disconnect(bng, vehicle)

Called when the attached vehicle is being removed from simulation. This method is used to perform teardown code after the simulation.

encode_engine_request()

Called to retrieve this sensor’s data request to the engine as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the game’s engine.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Camera sensor for a good example of an engine request.

Returns

The request to send to the engine as a dictionary.

encode_vehicle_request()

Called to retrieve this sensor’s request to the vehicle as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the attached vehicle.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Electrics sensor for a good example of a vehicle request.

Returns

The request to send to the vehicle as a dictionary.

get_engine_flags()

Called to retrieve a dictionary of settings in the engine this sensor requires.

Returns

A dictionary of flags to set in the engine for this sensor to function.

class beamngpy.sensors.State

Bases: Sensor

The state sensor monitors general stats of the vehicle, such as position, direction, velocity, etc. It is a default sensor every vehicle has and is used to update the vehicle.state attribute.

connect(bng, vehicle)

Called when the attached vehicle is being initialised in the simulation. This method is used to perform setup code that requires the simulation to be running.

decode_response(resp)

Called to do post-processing on sensor data obtained from the simulation. This method is called after raw simulation data is received and the resulting processed data is considered the result of a sensor request.

Example

Consult the implementation of the Camera sensor for a good example of decoding sensor data.

disconnect(bng, vehicle)

Called when the attached vehicle is being removed from simulation. This method is used to perform teardown code after the simulation.

encode_vehicle_request()

Called to retrieve this sensor’s request to the vehicle as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the attached vehicle.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Electrics sensor for a good example of a vehicle request.

Returns

The request to send to the vehicle as a dictionary.

class beamngpy.sensors.Timer

Bases: Sensor

The timer sensor keeps track of the time that has passed since the simulation started. It provides that information in seconds relative to the scenario start and does not represent something like a day time or date. It properly handles pausing the simulation, meaning the value of the timer sensor does not progress while the simulation is paused.

When polled, this sensor provides the time in seconds since the start of the scenario in a dictionary under the ‘time’ key.

encode_engine_request()

Called to retrieve this sensor’s data request to the engine as a dictionary. The dictionary returned by this method will be bundled along the vehicle’s other sensors’ requests as a SensorRequest to the game’s engine.

Note

Sensors require corresponding code in the simulator to handle requests.

Example

Consult the implementation of the Camera sensor for a good example of an engine request.

Returns

The request to send to the engine as a dictionary.

class beamngpy.sensors.Ultrasonic(pos=(0, -3, 0), dir=(0, -1, 0), size=(200, 200), fov=(0.15, 0.15), near_far_planes=(0.05, 10.0), range_roundness=-1.15, range_cutoff_sensitivity=0.0, range_shape=0.3, range_focus=0.376, range_min_cutoff=0.1, range_direct_max_cutoff=5.0, sensitivity=3.0, fixed_window_size=10.0, isVisualised=True, isStatic=False, isSnappingDesired=False, isForceInsideTriangle=False)

Bases: Sensor

An ultrasonic sensor (eg parking sensor).

attach(vehicle, name)

Called when the ultrasonic sensor is attached to a vehicle.

Parameters
  • vehicle (Vehicle) – The vehicle the sensor is being attached to.

  • name (str) – The name of the sensor.

connect(bng, vehicle)

Called when the attached vehicle is being initialised in the simulation. This method is used to perform setup code that requires the simulation to be running.

decode_response(resp)

Reads the raw point cloud the simulation wrote to the shared memory and creates a numpy array of points from them. The recoded response is returned as a dictionary with the numpy array in the points entry.

Returns

The decoded response as a dictionary with the point cloud as a numpy array in the points entry. The numpy array is a linear sequence of coordinate triplets in the form of [x0, y0, z0, x1, y1, z1, …, xn, yn, zn].

detach(vehicle, name)

Called when the ultrasonic sensor is detached from a vehicle.

Parameters
  • vehicle (Vehicle) – The vehicle the sensor is being detached from.

  • name (str) – The name of the sensor.

disconnect(bng, vehicle)

Called when the attached vehicle is being removed from simulation. This method is used to perform teardown code after the simulation.

encode_engine_request()

Called to obtain the engine request for this ultrasonic sensor.

Returns

The engine request containing the settings of this ultrasonic sensor as a dictionary.

beamngpy.test module

beamngpy.vehicle module

class beamngpy.vehicle.Vehicle(vid, model, port=None, **options)

Bases: object

The vehicle class represents a vehicle of the simulation that can be interacted with from BeamNGpy. This class offers methods to both control the vehicle’s state as well as retrieve information about it through sensors the user can attach to the vehicle.

add_imu_node(name, node, debug=False)

Adds an IMU to this vehicle at the given node identified by the given name. The node is specified as a number and can be found by inspecting the vehicle using the ingame vehicle editor.

Parameters
  • name (str) – The name this IMU is identified by. This is mainly used to later remove an IMU.

  • node (int) – The node ID to perform measurements at.

  • debug (bool) – Optional flag which enables debug rendering of the IMU. Useful to verify placement.

add_imu_position(name, pos, debug=False)

Adds an IMU to this vehicle at the given position identified by the given name. The position is relative to the vehicle’s coordinate system, meaning (0, 0, 0) will always refer to the vehicle’s origin regardless of its position in the world. This is to make addition of IMUs independent of the vehicle spawn position. To find an appropriate position relative to the vehicle’s origin, it’s recommended to inspect the vehicle’s nodes in the vehicle editor ingame and retrieve the original relative positions of nodes close to the desired measurement point.

Parameters
  • name (str) – The name this IMU is identified by. This is mainly used to later remove an IMU.

  • pos (list) – The measurement point relative to the vehicle’s origin.

  • debug (bool) – Optional flag which enables debug rendering of the IMU. Useful to verify placement.

ai_drive_in_lane(lane)

Sets the drive in lane flag of the AI. If True, the AI only drives within the lane it can legally drive in.

Parameters

lane (bool) – Lane flag to set.

ai_set_aggression(aggr)
ai_set_line(line, cling=True)

Makes the AI follow a given polyline. The line is specified as a list of dictionaries where each dictionary has a pos entry specifying the supposed position as an (x, y, z) triplet and a speed entry specifying the speed in m/s.

Parameters
  • line (list) – Polyline as list of dicts as described above.

  • cling (bool) – Whether or not to align the z coordinate of

ai_set_mode(mode)

Sets the desired mode of the simulator’s built-in AI for this vehicle. Possible values are:

  • disabled: Turn the AI off (default state)

  • random: Drive from random points to random points on the map

  • span: Drive along the entire road network of the map

  • manual: Drive to a specific waypoint, target set separately

  • chase: Chase a target vehicle, target set separately

  • flee: Flee from a vehicle, target set separately

  • stopping: Make the vehicle come to a halt (AI disables itself

    once the vehicle stopped.)

Note

Some AI methods automatically set appropriate modes, meaning a call to this method might be optional.

Parameters

mode (str) – The AI mode to set.

ai_set_script(script, start_dir=None, up_dir=None, cling=True, teleport=True)

Makes the vehicle follow a given “script” – a script being a list of timestamped positions defining where a vehicle should be at what time. This can be used to make the vehicle drive a long a polyline with speed implicitly expressed in the time between points.

Parameters
  • script (list) – A list of nodes in the script. Each node is expected to be a dict-like that has x, y, and z entries for the supposed position of the vehicle, and a t entry for the time of the node along the path. Time values are in seconds relative to the time when script playback is started.

  • cling (bool) – A flag that makes the simulator cling z-coordinates to the ground. Since computing z-coordinates in advance without knowing the level geometry can be cumbersome, this flag is used to automatically set z-coordinates in the script to the ground height. Defaults to True.

Notes

The AI follows the given script the best it can. It cannot drive along scripts that would be physically impossible, e.g. specifying a script with points A & B one kilometer apart and giving it a a second between those points will make the AI drive from A to B as fast as it can, but unlikely to reach it in the given time. Furthermore, if the AI falls behind schedule, it will start skipping points in the script in an effort to make up for lost time.

Raises

BNGValueError – If the script has fewer than three nodes, the minimum length of a script.

ai_set_speed(speed, mode='limit')

Sets the target speed for the AI in m/s. Speed can be maintained in two modes:

  • limit: Drive speeds between 0 and the limit, as the AI

    sees fit.

  • set: Try to maintain the given speed at all times.

Parameters
  • speed (float) – The target speed in m/s.

  • mode (str) – The speed mode.

ai_set_target(target, mode='chase')

Sets the target to chase or flee. The target should be the ID of another vehicle in the simulation. The AI is automatically set to the given mode.

Parameters
  • target (str) – ID of the target vehicle as a string.

  • mode (str) – How the target should be treated. chase to chase the target, flee to flee from it.

ai_set_waypoint(waypoint)

Sets the waypoint the AI should drive to in manual mode. The AI gets automatically set to manual mode when this method is called.

Parameters

waypoint (str) – ID of the target waypoint as a string.

annotate_parts()

Triggers the process to have individual parts of a vehicle have unique annotation colors.

attach_sensor(name, sensor)

Enters a sensor into this vehicle’s map of known sensors and calls the attach-hook of said sensor. The sensor is identified using the given name, which has to be unique among the other sensors of the vehicle.

Parameters
  • name (str) – The name of the sensor.

  • sensor (beamngpy.Sensor) – The sensor to attach to the vehicle.

close()

Closes this vehicle’s and its sensors’ connection and detaches all sensors.

connect(bng)
control(**options)

Sends a control message to the vehicle, setting vehicle inputs accordingly. Possible values to set are:

  • steering: Rotation of the steering wheel, from -1.0 to 1.0.

  • throttle: Intensity of the throttle, from 0.0 to 1.0.

  • brake: Intensity of the brake, from 0.0 to 1.0.

  • parkingbrake: Intensity of the parkingbrake, from 0.0 to 1.0.

  • clutch: Clutch level, from 0.0 to 1.0.

  • gear: Gear to shift to, -1 eq backwards, 0 eq neutral, 1 to X eq nth gear

Parameters

**kwargs (dict) – The input values to set.

decode_sensor_response(sensor_data)

Goes over the given map of sensor data and decodes each of them iff they have a corresponding sensor to handle the data in this vehicle. The given map of sensor data is expected to have an entries that match up with sensor names in this vehicle.

Parameters

sensor_data (dict) – The sensor data to decode as a dictionary, identifying which sensor to decode data with by the name it is known under in this vehicle.

Returns

The decoded data as a dictionary with entries for each sensor name and corresponding decoded data.

detach_sensor(name)

Detaches a sensor from the vehicle’s map of known sensors and calls the detach-hook of said sensor.

Parameters

name (str) – The name of the sensor to disconnect.

disconnect()

Closes socket communication with the corresponding vehicle.

encode_sensor_requests()

Encodes engine and vehicle requests for this vehicle’s sensors and returns them as a tuple of (engine requests, vehicle requests).

Returns

the engine requests and the vehicle requests to send to the simulation.

Return type

A tuple of two lists

static from_dict(d)
get_bbox()

Returns this vehicle’s current bounding box as a dictionary containing eight points.

Returns

The vehicle’s current bounding box as a dictionary of eight points. Points are named following the convention that the cuboid has a “near” rectangle towards the rear of the vehicle and “far” rectangle towards the front. The points are then named like this:

  • front_bottom_left: Bottom left point of the front rectangle as

    an (x, y ,z) triplet

  • front_bottom_right: Bottom right point of the front rectangle

    as an (x, y, z) triplet

  • front_top_left: Top left point of the front rectangle as an

    (x, y, z) triplet

  • front_top_right: Top right point of the front rectangle as an

    (x, y, z) triplet

  • rear_bottom_left: Bottom left point of the rear rectangle as an

    (x, y, z) triplet

  • rear_bottom_right: Bottom right point of the rear rectangle as

    an (x, y, z) triplet

  • rear_top_left: Top left point of the rear rectangle as an

    (x, y, z) triplet

  • rear_top_right: Top right point of the rear rectangle as an

    (x, y, z) triplet

get_engine_flags()

Gathers the engine flag of every sensor known to this vehicle and returns them as one dictionary.

get_part_config()

Retrieves the current part configuration of this vehicle. The configuration contains both the current values of adjustable vehicle parameters and a mapping of part types to their currently-selected part.

Returns

The current vehicle configuration as a dictionary.

get_part_options()

Retrieves a mapping of part slots in this vehicle and their possible parts.

Returns

A mapping of part configuration options for this vehicle.

hello()
is_connected()
poll_sensors(requests=None)

Updates the vehicle’s sensor readings.

Parameters

requests (None) – This function parameter is not used and will be removed in future versions.

Raises
  • DeprecationWarning – If requests parameter is used.

  • DeprecationWarning – Always, since the return type will change in the future.

Returns

Dict with sensor data to support compatibility with previous versions. The return argument is deprecated and will be removed in future versions. Use vehicle.sensors[<sensor_id>].data[<data_access_id>] instead.

queue_lua_command(chunk)

Executes lua chunk in the vehicle engine VM.

Parameters

chunk (str) – lua chunk as a string

recv()

Reads a message from the corresponding vehicle’s socket and returns it as a dictionary.

Returns

The message received as a dictionary.

remove_imu(name)

Removes the IMU identified by the given name.

Parameters

name (str) – The name of the IMU to be removed.

Raises

BNGValueError – If there is no IMU with the specified name.

revert_annotations()

Reverts per-part annotations of this vehicle such that it will be annotated with the same color for the entire vehicle.

send(data)

Sends the given data as a message to the corresponding vehicle’s socket.

set_color(rgba=(1.0, 1.0, 1.0, 1.0))

Sets the color of this vehicle. Colour can be adjusted on the RGB spectrum and the “shininess” of the paint.

Parameters

rgba (tuple) – The new colour given as a tuple of RGBA floats, where the alpha channel encodes the shininess of the paint.

set_colour(rgba=(1.0, 1.0, 1.0, 1.0))

Sets the color of this vehicle. Colour can be adjusted on the RGB spectrum and the “shininess” of the paint.

Parameters

rgba (tuple) – The new colour given as a tuple of RGBA floats, where the alpha channel encodes the shininess of the paint.

set_in_game_logging_options_from_json(fileName)

Updates the in game logging with the settings specified in the given file/json. The file is expected to be in the following location: <userpath>/<version_number>/<fileName>

Parameters

fileName

set_lights(**kwargs)

Sets the vehicle’s lights to given intensity values. The lighting system features lights that are simply binary on/off, but also ones where the intensity can be varied. Binary lights include:

  • left_signal

  • right_signal

  • hazard_signal

Non-binary lights vary between 0 for off, 1 for on, 2 for higher intensity. For example, headlights can be turned on with 1 and set to be more intense with 2. Non-binary lights include:

  • headlights

  • fog_lights

  • lightbar

Parameters
  • left_signal (bool) – On/off state of the left signal

  • right_signal (bool) – On/off state of the right signal

  • hazard_signal (bool) – On/off state of the hazard lights

  • headlights (int) – Value from 0 to 2 indicating headlight intensity

  • fog_lights (int) – Value from 0 to 2 indicating fog light intensity

  • lightbar (int) – Value from 0 to 2 indicating lightbar intensity

Note

Not every vehicle has every type of light. For example, the lightbar refers to the kind of lights typically found on top of police cars. Setting values for non-existent lights will not cause an error, but also achieve no effect.

Note also that lights are not independent. For example, turning on the hazard lights will make both signal indicators blink, meaning they will be turned on as well. Opposing indicators also turn each other off, i.e. turning on the left signal turns off the right one, and turning on the left signal during

Raises

BNGValueError – If an invalid light value is given.

Returns

Nothing. To query light states, attach an sensors.Electrics sensor and poll it.

set_part_config(cfg)

Sets the current part configuration of this vehicle. The configuration is given as a dictionary containing both adjustable vehicle parameters and a mapping of part types to their selected parts.

Parameters

cfg (dict) – The new vehicle configuration as a dictionary.

Notes

Changing parts causes the vehicle to respawn, which repairs it as a side-effect.

set_shift_mode(mode)

Sets the shifting mode of the vehicle. This changes whether or not and how the vehicle shifts gears depending on the RPM. Available modes are:

  • realistic_manual: Gears have to be shifted manually by the

    user, including engaging the clutch.

  • realistic_manual_auto_clutch: Gears have to be shifted manually

    by the user, without having to use the clutch.

  • arcade: Gears shift up and down automatically. If the brake is

    held, the vehicle automatically shifts into reverse and accelerates backward until brake is released or throttle is engaged.

  • realistic_automatic: Gears shift up automatically, but reverse

    and parking need to be shifted to manually.

Parameters

mode (str) – The mode to set. Must be a string from the options listed above.

Raises

BNGValueError – If an invalid mode is given.

set_velocity(velocity, dt=1.0)

Sets the velocity of this vehicle. The velocity is not achieved instantly, it is acquired gradually over the time interval set by the dt argument.

As the method of setting velocity uses physical forces, at high velocities it is important to set dt to an appropriately high value. The default dt value of 1.0 is suitable for velocities up to 30 m/s.

Parameters
  • velocity (float) – The target velocity in m/s.

  • dt (float) – The time interval over which the vehicle reaches the target velocity. Defaults to 1.0.

start_in_game_logging(outputDir)

Starts in game logging. Beware that any data from previous logging sessions is overwritten in the process.

Parameters

outputDir (str) – to avoid overwriting logging from other vehicles, specify the output directory, overwrites the outputDir set through the json. The data can be found in: <userpath>/<BeamNG version number>/<outpuDir>

property state

This property contains the vehicle’s current state in the running scenario. It is None if no scenario is running or the state has not been retrieved yet. Otherwise, it contains the following key entries:

  • pos: The vehicle’s position as an (x,y,z) triplet

  • dir: The vehicle’s direction vector as an (x,y,z) triplet

  • up: The vehicle’s up vector as an (x,y,z) triplet

  • vel: The vehicle’s velocity along each axis in metres per

    second as an (x,y,z) triplet

Note that the state variable represents a snapshot of the last state. It has to be updated through Vehicle.update_vehicle(), which is made to retrieve the current state. Alternatively, for convenience, a call to Vehicle.poll_sensors() also updates the vehicle state along with retrieving sensor data.

stop_in_game_logging()

Stops in game logging.

update_vehicle()

Synchronises the Vehicle.state field with the simulation.

write_in_game_logging_options_to_json(fileName='template.json')

Writes all available options from the in-game-logger to a json file. The purpose of this functionality is to facilitate the acquisition of a valid template to adjust the options/settings of the in game logging as needed. Depending on the executable used the file can be found at the following location: <userpath>/<BeamNG version number>/<fileName>

Parameters

fileName (str) – not the absolute file path but the name of the json

beamngpy.visualiser module

Module contents