BeamNGpy Reference
Submodules
beamngpy.beamng module
- class beamngpy.beamng.BeamNGpy(host, port, home=None, user=None, remote=False)
Bases:
object
The BeamNGpy class is the backbone of communication with the BeamNG simulation and offers methods of starting, stopping, connecting to, and controlling the state of the simulator.
- add_debug_cylinder(circle_positions, radius, rgba_color)
- add_debug_line(points, point_colors, spheres=None, sphere_colors=None, cling=False, offset=0)
The function is deprecated, use ‘add_debug_polyline’ instead! Adds a visual line to be rendered by BeamNG. This is mainly used for debugging purposes, but can also be used to add visual indicators to the user. A line is given as a series of points encoded as (x, y, z) triplets and also a list of colors given as (r, g, b, a) quartets. Additionally, it’s possible to give a list of spheres to be rendered alongside the line; spheres are specified similar to the line: a list of (x, y, z, r) points, where r is the radius of the sphere. A list of colors that the respective spheres should have is also given as a list of (r, g, b, a) quartets.
- Parameters
points (list) – List of points in the line given as (x, y, z) coordinate triplets.
point_colors (list) – List of colors as (r, g, b, a) quartets, each value expressing red, green, blue, and alpha intensity from 0 to 1. Only the first entry is used.
spheres (list) – Optional list of points where spheres should be rendered, given as (x, y, z, r) tuples where x,y,z are coordinates and r the radius of the sphere.
sphere_colors (list) – Optional list of sphere colors that contains the desired color of spheres in the sphere list as a (r, g, b, a) quartet for each sphere.
cling (bool) – Whether or not to align the given coordinates to the ground, e.g. set all z-coords to the ground height below the given x, y coords.
offset (float) – A height offset that is used alongside the cling flag. This is value is added to computed z-coords and can be used to make the line float above the ground by, for example, adding 10cm to the z value.
- Returns
The ID of the added debug line that can be used to remove the line
- add_debug_polyline(coordinates, rgba_color, cling=False, offset=0)
- add_debug_rectangle(vertices, rgba_color, cling=False, offset=0)
- add_debug_spheres(coordinates, radii, rgba_colors, cling=False, offset=0)
- add_debug_square_prism(end_points, end_point_dims, rgba_color)
- add_debug_text(origin, content, rgba_color, cling=False, offset=0)
- add_debug_triangle(vertices, rgba_color, cling=False, offset=0)
- annotate_parts(vehicle)
Triggers per-part annotation for the given
Vehicle
.- Parameters
vehicle (
Vehicle
) – The vehicle to annotate.
- apply_graphics_setting()
Makes the game apply a graphics setting that has been changed since startup or the last time settings were applied. A call to this is required after changing settings like whether or not the game is in fullscreen or the resolution, otherwise those settings will only take effect after the next launch.
- await_vehicle_spawn(vid)
Waits for the vehicle with the given name to spawn and returns once it has.
- Parameters
vid (str) – The name of the vehicle to wait for.
- change_setting(key, value)
Changes a setting in the game. Examples of the key and value pairs given to this method can be found in your game’s settings ini files. These are usually in <userpath>/settings/game-settings.ini or <userpath>/settings/cloud/game-settings-cloud.ini.
- Parameters
key (str) – The key of the setting that is to be changed
value (str) – The desired value.
- close()
Kills the BeamNG.* process.
- close_lidar(name)
Closes the Lidar instance of the given name in the simulator.
- Parameters
name (str) – The name of the Lidar instance to close.
- close_shmem(name)
Tells the simulator to close a previously-opened shared memory handle.
- Parameters
name (str) – The name of the shared memory space to close.
- close_ultrasonic(name)
Closes the ultrasonic sensor instance of the given name in the simulator.
- Parameters
name (str) – The name of the ultrasonic sensor instance to close.
- connect(tries=25)
Tries connecting to the running simulator over the host and port configuration set in this class. Upon failure, connections are re-attempted a limited amount of times.
- Parameters
tries (int) – The amount of attempts to connect before giving up.
- create_bump(name, width, length, height, upper_length, upper_width, pos, rot, rot_quat=None, material=None)
Creates a procedurally generated bump with the given properties at the given position and rotation. The material can optionally be specified and a name can be assigned for later identification.
- Parameters
name (str) – Name for the mesh. Should be unique.
width (float) – The width of the bump, i.e. its size between left and right edges.
length (float) – The length of the bump, i.e. the distances from up and downward slopes.
height (float) – The height of the tip.
upper_length (float) – The length of the tip.
upper_width (float) – The width of the tip.
pos (tuple) – (X, Y, Z) coordinate triplet specifying the cylinder’s position.
rot (tuple) – Triplet of Euler angles specifying rotations around the (X, Y, Z) axes. Deprecated.
rot_quat (tuple) – Quaternion specifying the bump’s rotation
material (str) – Optional material name to use as a texture for the mesh.
- create_cone(name, radius, height, pos, rot, rot_quat=None, material=None)
Creates a procedurally generated cone with the given properties at the given position and rotation. The material can optionally be specified and a name can be assigned for later identification.
- Parameters
name (str) – Name for the mesh. Should be unique.
radius (float) – Radius of the base circle.
height (float) – Distance of the tip to the base circle.
pos (tuple) – (X, Y, Z) coordinate triplet specifying the cylinder’s position.
rot (tuple) – Triplet of Euler angles specifying rotations around the (X, Y, Z) axes. Deprecated.
rot_quat (tuple) – Quaternion specifying the cone’s rotation
material (str) – Optional material name to use as a texture for the mesh.
- create_cube(name, size, pos, rot, rot_quat=None, material=None)
Creates a procedurally generated cube with the given properties at the given position and rotation. The material can optionally be specified and a name can be assigned for later identification.
- Parameters
name (str) – Name for the mesh. Should be unique.
size (tuple) – A triplet specifying the (length, width, height) of the cuboid.
pos (tuple) – (X, Y, Z) coordinate triplet specifying the cylinder’s position.
rot (tuple) – Triplet of Euler angles specifying rotations around the (X, Y, Z) axes. Deprecated.
rot_quat (tuple) – Quaternion specifying the cube’s rotation
material (str) – Optional material name to use as a texture for the mesh.
- create_cylinder(name, radius, height, pos, rot, rot_quat=None, material=None)
Creates a procedurally generated cylinder mesh with the given radius and height at the given position and rotation. The material can optionally be specified and a name can be assigned for later identification.
- Parameters
name (str) – Name for the mesh. Should be unique.
radius (float) – The radius of the cylinder’s base circle.
height (float) – The between top and bottom circles of the cylinder.
pos (tuple) – (X, Y, Z) coordinate triplet specifying the cylinder’s position.
rot (tuple) – Triplet of Euler angles specifying rotations around the (X, Y, Z) axes. Deprecated.
rot_quat (tuple) – Quaternion specifying the cylinder’s rotation
material (str) – Optional material name to use as a texture for the mesh.
- create_ring(name, radius, thickness, pos, rot, rot_quat=None, material=None)
Creates a procedurally generated ring with the given properties at the given position and rotation. The material can optionally be specified and a name can be assigned for later identification.
- Parameters
name (str) – Name for the mesh. Should be unique.
radius (float) – Radius of the circle encompassing the ring.
thickness (float) – Thickness of the rim.
pos (tuple) – (X, Y, Z) coordinate triplet specifying the cylinder’s position.
rot (tuple) – Triplet of Euler angles specifying rotations around the (X, Y, Z) axes. Deprecated.
rot_quat (tuple) – Quaternion specifying the ring’s rotation
material (str) – Optional material name to use as a texture for the mesh.
- create_scenario(level, name, prefab, info)
Prompts the simulator to create files required for a scenario. Namely, the “info.json” containing scenario information and the contents of the scenario prefab containing objects in the scene.
- Parameters
level (str) – The name of the level the new scenario is in
name (str) – The name of the scenario
prefab (str) – Contents of the scenario’s prefab file
info (dict) – Contents of the scenario’s info.json
- delete_scenario(path)
Prompts the simulator to delete files of the scenario at the given path.
- Parameters
path (str) – The path to the scenario relative to the
directory. (user) –
- despawn_vehicle(vehicle)
Despawns the given
Vehicle
from the simulation.- Parameters
vehicle (
Vehicle
) – The vehicle to despawn.
- determine_binary()
Tries to find one of the common BeamNG-binaries in the specified home path and returns the discovered path as a string.
- Returns
Path to the binary as a string.
- Raises
BNGError – If no binary could be determined.
- determine_effective_userpath()
- determine_userpath()
Tries to find the userpath based on the beamng installation if the user did not provide a custom userpath.
- disconnect()
Closes socket communication with the corresponding BeamNG instance.
- display_gui_message(msg)
Displays a toast message in the user interface of the simulator.
- Parameters
msg (str) – The message to display.
- find_objects_class(clazz)
Scans the current environment in the simulator for objects of a certain class and returns them as a list of
ScenarioObject
.What kind of classes correspond to what kind of objects is described in the BeamNG.drive documentation.
- Parameters
clazz (str) – The class name of objects to find.
- Returns
Found objects as a list.
- get_annotation_classes(annotations)
Method to convert the annotation configuration of the simulator into a mapping of colors to the corresponding object classes.
- Parameters
annotations (dict) – The annotation configuration of the simulator. Expected to be in the format get_annotations() returns.
- Returns
A mapping of colors encoded as 24bit integers to object classes according to the simulator.
- get_annotations()
Method to obtain the annotation configuration of the simulator.
- Returns
A mapping of object classes to lists containing the [R, G, B] values of the colors objects of that class are rendered with.
- get_available_vehicles()
Retrieves a dictionary of vehicles known to the simulator that map to various properties of the vehicle and a list of pre-configured vehicle configurations.
- Returns
A mapping of model names to vehicle properties & configs.
- Raises
BNGError – If the game is not running to accept a request.
- get_current_scenario(levels=None)
Queries the currently loaded scenario from the simulator.
- get_current_vehicles()
- get_current_vehicles_info()
Queries the currently active vehicles in the simulator.
- Returns
A mapping of vehicle IDs to instances of the
Vehicle
class for each active vehicle. These vehicles are not connected to by this function.
- get_gamestate()
Retrieves the current game state of the simulator. The game state is returned as a dictionary containing a
state
entry that is either:scenario
when a scenario is loadedmenu
otherwise
If a scenario is loaded, the resulting dictionary also contains a
scenario_state
entry whose value ispre-running
if the scenario is currently at the start screen orrunning
otherwise.- Returns
The game state as a dictionary as described above.
- get_level_scenarios(level)
Queries the simulator for all scenarios available in the given level.
- get_levels()
Queries the available levels in the simulator and returns them as a mapping of level name to
Level
instances.- Returns
A dictionary of available level names to a corresponding instance of the
Level
class.
- get_levels_and_scenarios()
Utility method that retrieves all levels and scenarios and returns them as a tuple of (levels, scenarios).
- Returns
- get_part_annotation(part)
- get_part_annotations(vehicle)
- get_part_config(vehicle)
Retrieves the current part configuration of the given vehicle. The configuration contains both the current values of adjustable vehicle parameters and a mapping of part types to their currently-selected part.
- Parameters
vehicle (
Vehicle
) – The vehicle to get part config of- Returns
The current vehicle configuration as a dictionary.
- get_part_options(vehicle)
Retrieves a mapping of part slots for the given vehicle and their possible parts.
- Parameters
vehicle (
Vehicle
) – The vehicle to get part options of- Returns
A mapping of part configuration options for the given.
- get_player_camera_modes(vid)
Retrieves information about the camera modes configured for the vehicle identified by the given ID.
- Parameters
vid (str) – Vehicle ID of the vehicle to get camera mode information of.
- Returns
A dictionary mapping camera mode names to configuration options.
- get_road_edges(road)
Retrieves the edges of the road with the given name and returns them as a list of point triplets. Roads are defined by a series of lines that specify the leftmost, center, and rightmost point in the road. These lines go horizontally across the road and the series of leftmost points make up the left edge of the road, the series of rightmost points make up the right edge of the road, and the series of center points the middle line of the road.
- Parameters
road (str) – Name of the road to get edges from.
- Returns
The road edges as a list of (left, center, right) point triplets. Each point is an (X, Y, Z) coordinate triplet.
- get_roads()
Retrieves the vertex data of all DecalRoads in the current scenario. The vertex data of a DecalRoad is formatted as point triples, where each triplet represents the left, centre, and right points of the edges that make up a DecalRoad.
- Returns
A dict mapping DecalRoad IDs to lists of point triples.
- get_scenario_name()
Retrieves the name of the currently-loaded scenario in the simulator.
- Returns
The name of the loaded scenario as a string.
- get_scenarios(levels=None)
Queries the available scenarios and returns them as a mapping of paths to
Scenario
instances. The scenarios are constructed to point to their parent levels, so to avoid extra queries to the simulator about existing levels, a cache of available levels can be passed to this method.
- get_scene_object_data(obj_id)
Retrieves all available key/value pairs the simulation offers for the given object as a dictionary.
- Returns
A dictionary of key/values the simulator offers for the object of the given ID.
- get_scenetree()
Queries the scene tree of the current scenario/level. The scene tree is returned as a tree of
SceneObject
instances the root of which is of theSimGroup
class.- Returns
A tree of
SceneObject
objects that contains all objects in the current scene. The respective objects do not contain type-specific information. This information can be obtained on a per-object basis usingget_scene_object_data()
.
- get_vehicle_bbox(vehicle)
Retrieves the current bounding box of the vehicle. The bounding box corresponds to the vehicle’s location/rotation in world space, i.e. if the vehicle moves/turns, the bounding box moves acoordingly. Note that the bounding box contains the min/max coordinates of the entire vehicle. This means that the vehicle losing a part like a mirror will cause the bounding box to “expand” while the vehicle moves as the mirror is left behind, but still counts as part of the box containing the vehicle.
- Parameters
vehicle (
Vehicle
) – The vehicle to get the bounding box of- 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
- hello()
First function called after connections. Exchanges the protocol version with the connected simulator and raises an error upon mismatch.
- hide_hud()
Hides the HUD in the simulator.
- kill_beamng()
Kills the running BeamNG.* process.
- load_scenario(scenario)
Loads the given scenario in the simulation and returns once loading is finished.
- Parameters
scenario (
Scenario
) – The scenario to load.
- message(req, **kwargs)
Generic message function which is parameterized with the type of message to send and all parameters that are to be embedded in the request. Responses are expected to have the same type as the request. If this is not the case, an error is raised.
- Parameters
req (str) – The request type.
- Raises
BNGValueError – If the response type does not match the request type
- Returns
The response received from the simulator as a dictionary.
- open(extensions=None, *args, launch=True, deploy=True, **opts)
Starts a BeamNG.* process, opens a server socket, and waits for the spawned BeamNG.* process to connect. This method blocks until the process started and is ready.
- Parameters
launch (bool) – Whether to launch a new process or connect to a running one on the configured host/port. Defaults to True.
deploy (bool) – Whether to deploy the required Lua extensions as a mod zip to the configured userpath. If false, it is assumed that the Lua extensions are already installed. Deprecated.
- open_lidar(name, vehicle, useSharedMemory=False, shmem='', shmemSize=0, 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)
Opens a Lidar sensor instance in the simulator with the given parameters writing its data to the given shared memory space. The Lidar instance has to be assigned a unique name that is later used for closing.
- Parameters
name (str) – The name of the LiDAR instance to open. Must be unique (relative to other LiDARS currently opened).
vehicle (
Vehicle
) – The vehicle this Lidar is attached to.shmem (str) – The handle of the shared memory space used to exchange data, if required.
shmemSize (int) – Size of the shared memory space that has been allocated for exchange.
pos (tuple) – (X, Y, Z) the sensor position in vehicle space.
dir (tuple) – (X, Y, Z) the sensor direction.
vres (int) – Vertical resolution, i.e. how many lines are sampled vertically.
vAngle (float) – The vertical LiDAR sensor angle, in degrees.
rps (int) – The rays per second emmited by the LiDAR sensor.
hz (int) – The refresh rate of the LiDAR sensor, in Hz.
hAngle (float) – The horizontal degrees covered, i.e. 360 degrees covers the entire surroundings of the vehicle.
maxDist (float) – Maximum distance of points. Any dot farther away will not show up in the sample.
isVisualised (bool) – Whether or not to render the LiDAR sensor points in the simulator.
isAnnotated (bool) – Whether or not to use LiDAR annotations in the visualisation.
isStatic (bool) – Whether or not the LiDAR sensor should be static (fixed position) or attached to a vehicle.
isSnappingDesired (bool) – Whether or not to snap the LiDAR sensor to the nearest vehicle triangle.
isForceInsideTriangle (bool) – Whether or not to force the LiDAR sensor to be inside the nearest vehicle triangle.
- open_shmem(name, size)
Tells the simulator to open a shared memory handle with the given amount of bytes.
- Parameters
name (str) – The name of the shared memory to open.
size (int) – The size to map in bytes.
- open_ultrasonic(name, vehicle, pos=(0.0, -1.0, 0.0), dir=(0.0, 1.0, 0.0), size=(200, 200), fov=0.3, 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=10.6, sensitivity=3.0, fixed_window_size=10.0, isVisualised=True, isStatic=False, isSnappingDesired=False, isForceInsideTriangle=False)
Opens an ultrasonic sensor instance in the simulator with the given parameters. The ultrasonic instance has to be assigned a unique name that is later used for closing.
- Parameters
name (str) – The name of the ultrasonic sensor instance to open. Has to be unique relative to other ultrasonic sensors currently opened.
vehicle (
Vehicle
) – The vehicle this ultrasonic sensor is attached to.pos (tuple) – (X, Y, Z) coordinate triplet specifying the position of the sensor, in world space.
dir (tuple) – (X, Y, Z) coordinate triplet specifying the direction of the ultrasonic sensor.
size (tuple) – (X, Y) the resolution of the ultrasonic sensor.
fov (float) – (X, Y) the ultrasonic sensor field of view parameters.
near_far_planes (tuple) – (X, Y) the ultrasonic sensor near and far plane distances.
range_roundness (float) – the general roudness of the ultrasonic sensor range-shape. Can be negative.
range_cutoff_sensitivity (float) – a cutoff sensitivity parameter for the ultrasonic sensor range-shape.
range_shape (float) – the shape of the ultrasonic sensor range-shape in [0, 1], from conical to circular.
range_focus (float) – the focus parameter for the ultrasonic sensor range-shape.
range_min_cutoff (float) – the minimum cut-off distance for the ultrasonic sensor range-shape. Nothing closer than this will be detected.
range_direct_max_cutoff (float) – the maximum cut-off distance for the ultrasonic sensor range-shape. This parameter is a hard cutoff - nothing further than this will be detected, although other parameters can also control the max distance.
sensitivity (float) – an ultrasonic sensor sensitivity parameter.
fixed_window_size (float) – an ultrasonic sensor sensitivity parameter.
isVisualised (bool) – Whether or not to render the ultrasonic sensor points in the simulator.
isStatic (bool) – Whether or not the ultrasonic sensor should be static (fixed position) or attached to a vehicle.
isSnappingDesired (bool) – Whether or not to snap the ultrasonic sensor to the nearest vehicle triangle.
isForceInsideTriangle (bool) – Whether or not to force the ultrasonic sensor to be inside the nearest vehicle triangle.
- pause()
Sends a pause request to BeamNG.*, blocking until the simulation is paused.
- poll_sensors(vehicle)
This member function is deprecated and will be removed in future versions. Use ‘Vehicle.poll_sensors’ instead.
Retrieves sensor values for the sensors attached to the given vehicle. This method correctly splits requests meant for the game engine and requests meant for the vehicle, sending them to their supposed destinations and waiting for results from them. Results from either are merged into one dictionary for ease of use. The received data is decoded by each sensor and returned, but also stored in the vehicle’s sensor cache to avoid repeated requests.
- Parameters
vehicle (
Vehicle
) – The vehicle whose sensors are polled.- Returns
The decoded sensor data from both engine and vehicle as one dictionary having a key-value pair for each sensor’s name and the data received for it.
- prepare_call(extensions, *args, **usr_opts)
Prepares the command line call to execute to start BeamNG.*. according to this class’ and the global configuration.
- Returns
List of shell components ready to be called in the
subprocess
module.
- queue_lua_command(chunk)
Executes one lua chunk in the game engine VM.
- Parameters
chunk (str) – lua chunk as a string
- quit_beamng()
- static read_effective_userpath(userpath)
- recv()
Helper method for receiving data over this instance’s socket.
- Returns
The data received.
- remove_debug_cylinder(cylinder_id)
- remove_debug_line(line_id)
- remove_debug_polyline(line_id)
- remove_debug_rectangle(rectangle_id)
- remove_debug_spheres(sphere_ids)
- remove_debug_square_prism(prism_id)
- remove_debug_text(text_id)
- remove_debug_triangle(triangle_id)
- remove_step_limit()
Removes the steps-per-second setting, making the simulation run at undefined time slices.
- render_cameras()
Renders all cameras associated with the loaded scenario. These cameras work exactly like the ones attached to vehicles as sensors, except scenario cameras do not follow the vehicle they are attached to and can be used to get a view from the perspective of something like a surveillance camera, for example.
A scenario needs to be loaded for this method to work.
- Returns
The rendered data for all cameras in the loaded scenario as a dict mapping camera name to render results.
- restart_scenario()
Restarts a running scenario.
- resume()
Sends a resume request to BeamNG.*, blocking until the simulation is resumed.
- revert_annotations(vehicle)
Reverts the given vehicle’s annotations back to the object-based mode, removing the per-part annotations.
- Parameters
vehicle (
Vehicle
) – The vehicle to annotate.
- send(data)
Helper method for sending data over this instance’s socket.
- Parameters
data (dict) – The data to send.
- set_deterministic()
Sets the simulator to run in deterministic mode. For this to function properly, an amount of steps per second needs to have been specified in the simulator’s settings, or through
set_steps_per_second()
.
- set_engine_flags(flags)
Sets flags in the simulation engine. Flags are given as key/value pairs of strings and booleans, where each string specifies a flag and the boolean the state to set. Possible flags are:
annotations
: Whether pixel-wise annotation should be enabled.
- set_free_camera(pos, direction)
Sets the position and direction of the free camera. The free camera is one that does not follow any particular vehicle, but can instead be put at any spot and any position on the map.
- Parameters
pos (tuple) – The position of the camera as a (x, y, z) triplet.
direction (tuple) – The directional vector of the camera as a (x, y, z) triplet.
- set_gravity(gravity=-9.807)
Sets the strength of gravity in the simulator.
- Parameters
gravity (float) – The gravity value to set. The default one is that of earth (-9.807)
- set_nondeterministic()
Disables the deterministic mode of the simulator. Any steps per second setting is retained.
- set_part_config(vehicle, cfg)
Sets the current part configuration of the given vehicle. The configuration is given as a dictionary containing both adjustable vehicle parameters and a mapping of part types to their selected parts.
- Parameters
vehicle (
Vehicle
) – The vehicle to change the config ofcfg (dict) – The new vehicle configuration as a dictionary.
Notes
Changing parts causes the vehicle to respawn, which repairs it as a side-effect.
- set_particles_enabled(enabled)
En-/disabled visual particle emmission.
- Parameters
enabled (bool) – Whether or not to en- or disabled effects.
- set_player_camera_mode(vid, mode, config)
Sets the camera mode of the vehicle identified by the given vehicle ID. The mode is given as a string that identifies one of the valid modes offered by the simulator. These modes can be queried using the (
get_player_camera_mode()
) method.The camera can be further configured with some common parameters, but it is not guaranteed the camera mode will respect all of them. These parameters include:
rotation: The rotation of the camera as a triplet of Euler angles
fov: The field of view angle
offset: The (x, y, z) vector to offset the camera’s position by
distance: The distance of the camera to the vehicle
Since each camera mode is implemented as a custom Lua extension, it is not possible to automatically query the exact features of the mode. Further information can be found in the lua/ge/extensions/core/cameraModes files which contain the implementations of each camera mode.
- Parameters
vid (str) – Vehicle ID of the vehice to change the mode of.
mode (str) – Camera mode to set
config (dict) – Dictionary of further properties to set in the mode
- set_relative_camera(pos, rot=None, rot_quat=None)
Switches the camera mode for the currently-entered vehicle to the ‘relative’ mode in which the camera can be placed at an arbitrary point relative to the vehicle, moving along with it as it drives around.
- Parameters
pos (tuple) – (x, y, z) tuple of the camera’s position relative to the vehicle.
rot (tuple) – Euler angles expressing the rotation of the camera.
rot_quat (tuple) – The camera’s rotation but written as a quat.
- set_steps_per_second(sps)
Specifies the temporal resolution of the simulation. The setting can be understood to determine into how many steps the simulation divides one second of simulation. A setting of two, for example, would mean one second is simulated in two steps. Conversely, to simulate one second, one needs to advance the simulation two steps.
- Parameters
sps (int) – The steps per second to set.
- set_tod(tod)
Sets the current time of day. The time of day value is given as a float between 0 and 1. How this value affects the lighting of the scene is dependant on the map’s TimeOfDay object.
- Parameters
tod (float) – Time of day beteen 0 and 1.
- set_weather_preset(preset, time=1)
Triggers a change to a different weather preset. Weather presets affect multiple settings at once (time of day, wind speed, cloud coverage, etc.) and need to have been defined first. Example json objects defining weather presets can be found in BeamNG.tech’s
art/weather/defaults.json
file.- Parameters
preset (str) – The name of the preset to switch to. Needs to be defined already within the simulation.
time (float) – Time in seconds the transition from the current settings to the preset’s should take.
- setup_workspace()
- show_hud()
Shows the HUD in the simulator.
- spawn_vehicle(vehicle, pos, rot, rot_quat=(0, 0, 0, 1), cling=True)
Spawns the given
Vehicle
instance in the simulator. This method is meant for spawning vehicles during the simulation. Vehicles that are known to be required before running the simulation should be added during scenario creation instead. Cannot spawn two vehicles with the same id/name.- Parameters
vehicle (
Vehicle
) – The vehicle to be spawned.pos (tuple) – Where to spawn the vehicle as a (x, y, z) triplet.
rot (tuple) – The rotation of the vehicle as a triplet of Euler angles. Deprecated.
rot_quat (tuple) – Vehicle rotation in form of a quaternion
cling (bool) – If set, the z-coordinate of the vehicle’s position will be set to the ground level at the given position to avoid spawning the vehicle below ground or in the air.
- Returns
bool indicating whether the spawn was successful or not
- start_beamng(extensions, *args, **opts)
Spawns a BeamNG.* process and retains a reference to it for later termination.
- start_scenario()
Starts the scenario; equivalent to clicking the “Start” button in the game after loading a scenario. This method blocks until the countdown to the scenario’s start has finished.
- start_traffic(participants)
Enables traffic simulation for the given list of vehicles.
- Parameters
participants (list) – List of vehicles that will be part of the simulation. These vehicles need to be spawned beforehand and the simulation will take control of them.
- start_vehicle_connection(vehicle)
Prompts the simulator to initiate a new connection for the given vehicle, opening a server socket BeamNGpy can connect to. The port of this new server socket is returned.
- Parameters
vehicle (
Vehicle
) – The vehicle instance to be connected.- Returns
The port connections to the given vehicle are available on.
- step(count, wait=True)
Advances the simulation the given amount of steps, assuming it is currently paused. If the wait flag is set, this method blocks until the simulator has finished simulating the desired amount of steps. If not, this method resumes immediately. This can be used to queue commands that should be executed right after the steps have been simulated.
- Parameters
count (int) – The amount of steps to simulate.
wait (bool) – Optional. Whether to wait for the steps to be simulated. Defaults to True.
- Raises
BNGError – If the wait flag is set but the simulator doesn’t respond appropriately.
- stop_scenario()
Stops a running scenario and returns to the main menu.
- stop_traffic(stop=False)
Stops the traffic simulation.
- Parameters
stop (bool) – Whether or not to stop the vehicles participating in traffic. If True, vehicles will come to a halt, if False, the AI will simply stop controlling the vehicle.
- switch_vehicle(vehicle)
Switches to the given
Vehicle
. This means that the simulator’s main camera, inputs by the user, and so on will all focus on that vehicle from now on.- Parameters
vehicle (
Vehicle
) – The target vehicle.
- teleport_scenario_object(scenario_object, pos, rot=None, rot_quat=None)
Teleports the given scenario object to the given position with the given rotation.
- Parameters
scenario_object (
ScenarioObject
) – The vehicle to teleport.pos (tuple) – The target position as an (x,y,z) tuple containing world-space coordinates.
rot (tuple) – Optional tuple specifying rotations around the (x,y,z) axes in degrees. Deprecated.
rot_quat (tuple) – Optional tuple specifying object rotation as a quaternion
- teleport_vehicle(vehicle_id, pos, rot=None, rot_quat=None, reset=True)
Teleports the given vehicle to the given position with the given rotation.
- Parameters
vehicle_id (string) – The id/name of the vehicle to teleport.
pos (tuple) – The target position as an (x,y,z) tuple containing world-space coordinates.
rot (tuple) – Optional tuple specifying rotations around the (x,y,z) axes in degrees. Deprecated.
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.
- update_scenario()
Updates the
Vehicle.state
field of each vehicle in the currently running scenario.
- beamngpy.beamng.log_exception(extype, value, trace)
Hook to log uncaught exceptions to the logging framework. Register this as the excepthook with sys.excepthook = log_exception.
- beamngpy.beamng.setup_logging(log_file=None, activateWarnings=True, level=20)
Sets up the logging framework to log to the given log_file and to STDOUT. If the path to the log_file does not exist, directories for it will be created.
- Parameters
log_file (str) – filename for log
activateWarnings (bool) – whether to redirect warnings to the logger. Beware that this modifies the warnings settings. Optional.
level (int) – log level of handler that is created for the log file, optional
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 todata (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
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
- 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 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, 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.
- 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.
- 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 informationinstance (
Image
) – The image containing instance annotation informationclasses (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 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.
- 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 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>/<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) 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 persecond 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.
- 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
- class beamngpy.visualiser.LidarVisualiser(points_ceiling)
Bases:
object
- init_gl(width, height)
- on_drag(x, y)
- on_key(name, *args)
- open(width, height)
- render()
- update_points(points, vehicle_state)
- beamngpy.visualiser.lidar_resize(width, height)
Module contents
BeamNGPy API module.
- beamngpy.read(fil)