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.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
beamngpy.procedural module
- class beamngpy.procedural.ProceduralBump(pos, width, length, height, upper_length, upper_width, name, rot_quat=None, material=None)
Bases:
ProceduralMesh
- place(bng)
- class beamngpy.procedural.ProceduralCone(pos, radius, height, name, rot_quat=None, material=None)
Bases:
ProceduralMesh
- place(bng)
- class beamngpy.procedural.ProceduralCube(pos, size, name, rot_quat=None, material=None)
Bases:
ProceduralMesh
- place(bng)
- class beamngpy.procedural.ProceduralCylinder(pos, radius, height, name, rot_quat=None, material=None)
Bases:
ProceduralMesh
- place(bng)
- class beamngpy.procedural.ProceduralMesh(pos, name, material, rot_quat=None)
Bases:
ScenarioObject
- place(bng)
- class beamngpy.procedural.ProceduralRing(pos, radius, thickness, name, rot_quat=None, material=None)
Bases:
ProceduralMesh
- place(bng)
beamngpy.road module
- class beamngpy.road.DecalRoad(options)
Bases:
SceneObject
- class beamngpy.road.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.road.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.
beamngpy.scenario module
- 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_quat=(0, 0, 0, 1), cling=True)
Adds a vehicle to this scenario at the given position with the given orientation.
- Parameters
pos (tuple) – (x,y,z) tuple specifying the position of the vehicle.
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, connect_existing=True)
Connects this scenario to the simulator, hooking up any cameras to their counterpart in the simulator.
- Parameters
bng (
BeamNGpy
) – The BeamNGpy instance to generate the scenario for.connect_existing (bool) – Whether vehicles spawned already in the scenario should be connected to this (:class:
.Scenario
) instance.
- 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.- Raises
BNGError – If the scenario already has set its info .json file included.
- 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 thescene
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, 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, 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.Accelerometer(name, bng, vehicle, requested_update_time=0.1, pos=(0, 0, 1.7), dir=(0, -1, 0), up=(0, 0, 1), is_using_gravity=False, is_visualised=True, is_snapping_desired=False, is_force_inside_triangle=False)
Bases:
object
- collect_ad_hoc_poll_request(request_id)
Collects a previously-issued ad-hoc polling request, if it has been processed.
- Parameters
request_id (int) – The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request.
- Returns
The readings data.
- Return type
(dict)
- get_direction()
Gets the current direction vector of this sensor.
- Returns
The sensor direction.
- Return type
(list)
- get_position()
Gets the current world-space position of this sensor.
- Returns
The sensor position.
- Return type
(list)
- is_ad_hoc_poll_request_ready(request_id)
Checks if a previously-issued ad-hoc polling request has been processed and is ready to collect.
- Parameters
request_id (int) – The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request.
- Returns
A flag which indicates if the ad-hoc polling request is complete.
- Return type
(bool)
- poll()
Gets the most-recent readings for this sensor. Note: if this sensor was created with a negative update rate, then there may have been no readings taken.
- Returns
A dictionary containing the acceleration in each dimension of the local coordinate system of the accelerometer sensor.
- Return type
(dict)
- remove()
Removes this sensor from the simulation.
- send_ad_hoc_poll_request()
Sends an ad-hoc polling request to the simulator. This will be executed by the simulator immediately, but will take time to process, so the result can be queried after some time has passed. To check if it has been processed, we first call the is_ad_hoc_poll_request_ready() function, then call the collect_ad_hoc_poll_request() function to retrieve the sensor reading.
- Returns
A unique Id number for the ad-hoc request.
- Return type
(int)
- set_is_using_gravity(is_using_gravity)
Sets whether this accelerometer sensor is to include gravity in the computation or not.
- Parameters
is_visualised (bool) – A flag which indicates if this accelerometer sensor is to use gravity in the computation or not.
- set_is_visualised(is_visualised)
Sets whether this accelerometer sensor is to be visualised or not.
- Parameters
is_visualised (bool) – A flag which indicates if this accelerometer sensor is to be visualised or not.
- set_requested_update_time(requested_update_time)
Sets the current ‘requested update time’ value for this sensor.
- Parameters
requested_update_time (float) – The new requested update time.
- class beamngpy.sensors.Camera(name, bng, vehicle=None, requested_update_time=0.1, update_priority=0.0, pos=(0, 0, 3), dir=(0, -1, 0), up=(0, 0, 1), resolution=(512, 512), field_of_view_y=70, near_far_planes=(0.05, 100.0), is_using_shared_memory=True, is_render_colours=True, is_render_annotations=True, is_render_instance=False, is_render_depth=True, is_depth_inverted=False, is_visualised=True, is_static=False, is_snapping_desired=False, is_force_inside_triangle=False)
Bases:
object
- collect_ad_hoc_poll_request(request_id)
Collects a previously-issued ad-hoc polling request, if it has been processed.
- Parameters
request_id (int) – The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request.
- Returns
The readings data.
- Return type
(dict)
- static draw_bounding_boxes(bounding_boxes, colour, width=3, font='arial.ttf', font_size=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. NOTE: The given image is not directly modified and the boxes are drawn onto a copy.
- Parameters
bounding_boxes (list) – List of bounding boxes to draw.
colour (
Image
) – The image to draw the bounding boxes on.width (int) – The width of bounding box outlines in pixels.
font (str) – A string specifying the font which bounding box labels will have.
fontsize (int) – The font size used when drawing labels.
- Returns
A :class:.Image` that is a copy of the given image with bounding boxes drawn onto it.
- static export_bounding_boxes_xml(bounding_boxes, folder=None, filename=None, path=None, database=None, size=None)
Exports the given list of bounding boxes to the Pascal-VOC XML standard. Additional properties to this function correspond to tags in the Pascal-VOC standard.
- Parameters
bounding_boxes (list) – The list of bounding boxes to export.
folder (str) – Contents of the ‘folder’ tag.
filename (str) – Contents of the ‘filename’ tag.
path (str) – Contents of the ‘path’ tag.
database (str) – Contents of the ‘database’ tag.
size (tuple) – Contents of the ‘size tag. It’s expected to be a tuple of the image width, height, and depth.
- Returns
XML string encoding of the given list of bounding boxes according to Pascal-VOC.
- static extract_bounding_boxes(semantic_data, instance_data, 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 colour in the semantic annotations and the given class mapping, and the colour of the object in the instance annotation.
- Parameters
semantic_data (
Image
) – The image containing semantic annotation information.instance_data (
Image
) – The image containing instance annotation information.classes (dict) – A mapping of colours to their class names to identify object types based on the semantic annotation information. The keys in this dictionary are the respective colours expressed as a 24-bit integer, i.e. [r * 256^2 + g * 256 + b].
- Returns
‘bbox’: [min_x, min_y, max_x, max_y], ‘color’: [233, 11, 15], ‘class’: [‘CAR’], where min_x, min_y, max_x, max_y mark the corners of the bounding box, colour contains the RGB colour of the object in the instance annotations, and class the object type identified through the given class mapping.
- Return type
A list of bounding boxes specified as dictionaries. Example
- get_direction()
Gets the current forward direction vector of this sensor.
- Returns
The sensor direction.
- Return type
(list)
- get_full_poll_request()
Gets a full camera request (semantic annotation and instance annotation data included). NOTE: this function blocks the simulation until the data request is completed.
- Returns
The camera data, as images
- Return type
(dict)
- get_max_pending_requests()
Gets the current ‘max pending requests’ value for this sensor. This is the maximum number of polling requests which can be issued at one time.
- Returns
The max pending requests value.
- Return type
(int)
- get_position()
Gets the current world-space position of this sensor.
- Returns
The sensor position.
- Return type
(list)
- get_requested_update_time()
Gets the current ‘requested update time’ value for this sensor.
- Returns
The requested update time.
- Return type
(float)
- get_up()
Gets the current up direction vector of this sensor.
- Returns
The sensor direction.
- Return type
(list)
- get_update_priority()
Gets the current ‘update priority’ value for this sensor, in range [0, 1], with priority going 0 –> 1, highest to lowest.
- Returns
The update priority value.
- Return type
(float)
- is_ad_hoc_poll_request_ready(request_id)
Checks if a previously-issued ad-hoc polling request has been processed and is ready to collect.
- Parameters
request_id (int) – The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request.
- Returns
A flag which indicates if the ad-hoc polling request is complete.
- Return type
(bool)
- poll()
Gets the most-recent readings for this sensor. Note: if this sensor was created with a negative update rate, then there may have been no readings taken.
- Returns
The processed images.
- Return type
(dict)
- remove()
Removes this sensor from the simulation.
- send_ad_hoc_poll_request()
Sends an ad-hoc polling request to the simulator. This will be executed by the simulator immediately, but will take time to process, so the result can be queried after some time has passed. To check if it has been processed, we first call the is_ad_hoc_poll_request_ready() function, then call the collect_ad_hoc_poll_request() function to retrieve the sensor reading.
- Returns
A unique Id number for the ad-hoc request.
- Return type
(int)
- set_direction(dir)
Sets the current forward direction vector of this sensor.
- Parameters
pos (tuple) – The new forward direction vector.
- set_max_pending_requests(max_pending_requests)
Sets the current ‘max pending requests’ value for this sensor. This is the maximum number of polling requests which can be issued at one time.
- Parameters
max_pending_requests (int) – The new max pending requests value.
- set_position(pos)
Sets the current world-space position for this sensor.
- Parameters
pos (tuple) – The new position.
- set_requested_update_time(requested_update_time)
Sets the current ‘requested update time’ value for this sensor.
- Parameters
requested_update_time (float) – The new requested update time.
- set_up(up)
Sets the current up vector of this sensor.
- Parameters
pos (tuple) – The new up vector.
- set_update_priority(update_priority)
Sets the current ‘update priority’ value for this sensor, in range [0, 1], with priority going 0 –> 1, , highest to lowest.
- Parameters
update_priority (float) – The new update priority value.
- world_point_to_pixel(point)
Converts a 3D point in world space to the 2D pixel coordinate at which it is represented on this camera. NOTE: The pixel does not have to actually be visible on the camera image itself in order to retrieve a value; it can be obscured by geometry which is closer, or it can be run without respect to the near and far plane values of the camera.
- Parameters
point (tuple) – The given 3D point, in world space coordinates.
- Returns
The 2D pixel value which represents the given 3D point, on this camera.
- Return type
(list)
- 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(name, bng, vehicle=None, requested_update_time=0.1, update_priority=0.0, pos=(0, 0, 1.7), dir=(0, -1, 0), up=(0, 0, 1), vertical_resolution=64, vertical_angle=26.9, rays_per_second=2200000, frequency=20, horizontal_angle=360, max_distance=120, is_using_shared_memory=True, is_visualised=True, is_annotated=False, is_static=False, is_snapping_desired=False, is_force_inside_triangle=False)
Bases:
object
- collect_ad_hoc_poll_request(request_id)
Collects a previously-issued ad-hoc polling request, if it has been processed.
- Parameters
request_id (int) – The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request.
- Returns
A dictionary containing the LiDAR point cloud and colour data.
- Return type
(dict)
- get_direction()
Gets the current direction vector of this sensor.
- Returns
The sensor direction.
- Return type
(list)
- get_is_annotated()
Gets a flag which indicates if this LiDAR sensor is annotated or not.
- Returns
A flag which indicates if this LiDAR sensor is annotated or not.
- Return type
(bool)
- get_is_visualised()
Gets a flag which indicates if this LiDAR sensor is visualised or not.
- Returns
A flag which indicates if this LiDAR sensor is visualised or not.
- Return type
(bool)
- get_max_pending_requests()
Gets the current ‘max pending requests’ value for this sensor. This is the maximum number of polling requests which can be issued at one time.
- Returns
The max pending requests value.
- Return type
(int)
- get_position()
Gets the current world-space position of this sensor.
- Returns
The sensor position.
- Return type
(list)
- get_requested_update_time()
Gets the current ‘requested update time’ value for this sensor.
- Returns
The requested update time.
- Return type
(float)
- get_update_priority()
Gets the current ‘update priority’ value for this sensor, in range [0, 1], with priority going 0 –> 1, highest to lowest.
- Returns
The update priority value.
- Return type
(float)
- is_ad_hoc_poll_request_ready(request_id)
Checks if a previously-issued ad-hoc polling request has been processed and is ready to collect.
- Parameters
request_id (int) – The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request.
- Returns
A flag which indicates if the ad-hoc polling request is complete.
- Return type
(bool)
- poll()
Gets the most-recent readings for this sensor. Note: if this sensor was created with a negative update rate, then there may have been no readings taken.
- Returns
The LiDAR point cloud and colour data.
- Return type
(np.array x 2)
- remove()
Removes this sensor from the simulation.
- send_ad_hoc_poll_request()
Sends an ad-hoc polling request to the simulator. This will be executed by the simulator immediately, but will take time to process, so the result can be queried after some time has passed. To check if it has been processed, we first call the is_ad_hoc_poll_request_ready() function, then call the collect_ad_hoc_poll_request() function to retrieve the sensor reading.
- Returns
A unique Id number for the ad-hoc request.
- Return type
(int)
- set_is_annotated(is_annotated)
Sets whether this LiDAR sensor is to be annotated or not. This means it will return annotation data instead of distances.
- Parameters
is_visualised (bool) – A flag which indicates if this LiDAR sensor is to be annotated or not.
- set_is_visualised(is_visualised)
Sets whether this LiDAR sensor is to be visualised or not.
- Parameters
is_visualised (bool) – A flag which indicates if this LiDAR sensor is to be visualised or not.
- set_max_pending_requests(max_pending_requests)
Sets the current ‘max pending requests’ value for this sensor. This is the maximum number of polling requests which can be issued at one time.
- Parameters
update_priority (int) – The new max pending requests value.
- set_requested_update_time(requested_update_time)
Sets the current ‘requested update time’ value for this sensor.
- Parameters
update_priority (float) – The new requested update time.
- set_update_priority(update_priority)
Sets the current ‘update priority’ value for this sensor, in range [0, 1], with priority going 0 –> 1, , highest to lowest.
- Parameters
update_priority (float) – The new update priority value.
- 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(name, bng, vehicle=None, requested_update_time=0.1, update_priority=0.0, pos=(0, 0, 1.7), dir=(0, -1, 0), up=(0, 0, 1), resolution=(200, 200), field_of_view_y=5.7, near_far_planes=(0.1, 5.1), range_roundess=-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, is_visualised=True, is_static=False, is_snapping_desired=False, is_force_inside_triangle=False)
Bases:
object
- collect_ad_hoc_poll_request(request_id)
Collects a previously-issued ad-hoc polling request, if it has been processed. :param request_id: The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request. :type request_id: int
- Returns
The readings data.
- Return type
(dict)
- get_direction()
Gets the current direction vector of this sensor. :returns: The sensor direction. :rtype: (list)
- get_is_visualised()
Gets a flag which indicates if this ultrasonic sensor is visualised or not. :returns: A flag which indicates if this ultrasonic sensor is visualised or not. :rtype: (bool)
- get_max_pending_requests()
Gets the current ‘max pending requests’ value for this sensor. This is the maximum number of polling requests which can be issued at one time. :returns: The max pending requests value. :rtype: (int)
- get_position()
Gets the current world-space position of this sensor. :returns: The sensor position. :rtype: (list)
- get_requested_update_time()
Gets the current ‘requested update time’ value for this sensor. :returns: The requested update time. :rtype: (float)
- get_update_priority()
Gets the current ‘update priority’ value for this sensor, in range [0, 1], with priority going 0 –> 1, highest to lowest. :returns: The update priority value. :rtype: (float)
- is_ad_hoc_poll_request_ready(request_id)
Checks if a previously-issued ad-hoc polling request has been processed and is ready to collect. :param request_id: The unique Id number of the ad-hoc request. This was returned from the simulator upon sending the ad-hoc polling request. :type request_id: int
- Returns
A flag which indicates if the ad-hoc polling request is complete.
- Return type
(bool)
- poll()
Gets the most-recent readings for this sensor. Note: if this sensor was created with a negative update rate, then there may have been no readings taken. :returns: A dictionary containing the distance measurement and the window (min and mix values) in which it was computed. :rtype: (dict)
- remove()
Removes this sensor from the simulation.
- send_ad_hoc_poll_request()
Sends an ad-hoc polling request to the simulator. This will be executed by the simulator immediately, but will take time to process, so the result can be queried after some time has passed. To check if it has been processed, we first call the is_ad_hoc_poll_request_ready() function, then call the collect_ad_hoc_poll_request() function to retrieve the sensor reading. :returns: A unique Id number for the ad-hoc request. :rtype: (int)
- set_is_visualised(is_visualised)
Sets whether this ultrasonic sensor is to be visualised or not. :param is_visualised: A flag which indicates if this ultrasonic sensor is to be visualised or not. :type is_visualised: bool
- set_max_pending_requests(max_pending_requests)
Sets the current ‘max pending requests’ value for this sensor. This is the maximum number of polling requests which can be issued at one time. :param max_pending_requests: The new max pending requests value. :type max_pending_requests: int
- set_requested_update_time(requested_update_time)
Sets the current ‘requested update time’ value for this sensor. :param requested_update_time: The new requested update time. :type requested_update_time: float
- set_update_priority(update_priority)
Sets the current ‘update priority’ value for this sensor, in range [0, 1], with priority going 0 –> 1, , highest to lowest. :param update_priority: The new update priority :type update_priority: float
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 mapspan
: Drive along the entire road network of the mapmanual
: Drive to a specific waypoint, target set separatelychase
: Chase a target vehicle, target set separatelyflee
: Flee from a vehicle, target set separatelystopping
: Make the vehicle come to a halt (AI disables itselfonce 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 AIsees 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.
- property bng
- close()
Closes this vehicle’s and its sensors’ connection and detaches all sensors.
- connect(bng)
Opens socket communication with the corresponding vehicle.
- 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.
- is_connected()
- poll_sensors()
Updates the vehicle’s sensor readings.
- Parameters
requests (None) – This function parameter is not used and will be removed in future versions.
- Returns
Dict with sensor data to support compatibility with previous versions. Use vehicle.sensors[<sensor_id>].data[<data_access_id>] to access the polled sensor data.
- queue_lua_command(chunk)
Executes lua chunk in the vehicle engine VM.
- Parameters
chunk (str) – lua chunk as a string
- 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.
- 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 theuser, including engaging the clutch.
realistic_manual_auto_clutch
: Gears have to be shifted manuallyby the user, without having to use the clutch.
arcade
: Gears shift up and down automatically. If the brake isheld, the vehicle automatically shifts into reverse and accelerates backward until brake is released or throttle is engaged.
realistic_automatic
: Gears shift up automatically, but reverseand 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>/<outputDir>
- 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) tripletdir
: The vehicle’s direction vector as an (x,y,z) tripletup
: The vehicle’s up vector as an (x,y,z) tripletvel
: 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 toVehicle.poll_sensors()
also updates the vehicle state along with retrieving sensor data.
- stop_in_game_logging()
Stops in game logging.
- teleport(pos, rot_quat=None, reset=True)
Teleports the vehicle to the given position with the given rotation.
- Parameters
pos (tuple) – The target position as an (x,y,z) tuple containing world-space coordinates.
rot_quat (tuple) – Optional tuple (x, y, z, w) specifying vehicle rotation as quaternion
reset (bool) – Specifies if the vehicle will be reset to its initial state during teleport (including its velocity).
Notes
The
reset=False
option is incompatible with setting rotation of the vehicle. With the current implementation, it is not possible to set the rotation of the vehicle and to keep its velocity during teleport.
- 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