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

camera_world_point_to_pixel(name, point)
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_accelerometer(name, vid)
close_camera(name)
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_ultrasonic(name)
collect_ad_hoc_poll_request_accelerometer(request_id)
collect_ad_hoc_poll_request_camera(request_id)
collect_ad_hoc_poll_request_lidar(request_id)
collect_ad_hoc_poll_request_ultrasonic(request_id)
create_bump(name, width, length, height, upper_length, upper_width, pos, 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_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_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_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_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_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_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_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_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_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_userpath()

Tries to find the userpath based on the beamng installation if the user did not provide a custom userpath.

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_accelerometer_sensor_direction(name)
get_accelerometer_sensor_position(name)
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_camera_max_pending_gpu_requests(name)
get_camera_requested_update_time(name)
get_camera_sensor_direction(name)
get_camera_sensor_position(name)
get_camera_sensor_up(name)
get_camera_update_priority(name)
get_current_scenario(levels=None)

Queries the currently loaded scenario from the simulator.

Parameters

levels (dict) – A mapping of level names to Level instances

Returns

A Scenario instance of the currently-loaded scenario. If the levels parameter contains the level the scenario is taking place in, the scenario’s parent level field will be filled in accordingly.

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_full_camera_request(name)
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 loaded

  • menu otherwise

If a scenario is loaded, the resulting dictionary also contains a scenario_state entry whose value is pre-running if the scenario is currently at the start screen or running 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.

Parameters

level – The level to get scenarios for. Can either be the name of the level as a string or an instance of Level

Returns

A mapping of scenario paths to their corresponding Scenario instance.

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_levels(), get_scenarios())

get_lidar_frequency(name)
get_lidar_is_annotated(name)
get_lidar_is_visualised(name)
get_lidar_max_distance(name)
get_lidar_max_pending_gpu_requests(name)
get_lidar_rays_per_second(name)
get_lidar_requested_update_time(name)
get_lidar_sensor_direction(name)
get_lidar_sensor_position(name)
get_lidar_update_priority(name)
get_lidar_vertical_resolution(name)
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.

Parameters

levels (dict) – A dictionary of level names to Level instances to fill in the parent level of returned scenarios.

Returns

A mapping of scenario paths to their corresponding Scenario instance.

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 the SimGroup 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 using get_scene_object_data().

get_ultrasonic_is_visualised(name)
get_ultrasonic_max_pending_gpu_requests(name)
get_ultrasonic_requested_update_time(name)
get_ultrasonic_sensor_direction(name)
get_ultrasonic_sensor_position(name)
get_ultrasonic_update_priority(name)
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

hide_hud()

Hides the HUD in the simulator.

is_ad_hoc_poll_request_ready_accelerometer(request_id)
is_ad_hoc_poll_request_ready_camera(request_id)
is_ad_hoc_poll_request_ready_lidar(request_id)
is_ad_hoc_poll_request_ready_ultrasonic(request_id)
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.

load_trackbuilder_track(path)

Spawns a TrackBuilder track provided by the given path to a TrackBuilder .json file.

Parameters

path (str) – Path to a .json file created by TrackBuilder.

open(extensions=None, *args, launch=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.

open_accelerometer(name, vid, requested_update_time, pos, dir, up, is_using_gravity, is_visualised, is_snapping_desired, is_force_inside_triangle)
open_camera(name, vehicle, requested_update_time, update_priority, size, field_of_view_y, near_far_planes, pos, dir, up, is_using_shared_memory, colour_shmem_handle, colour_shmem_size, annotation_shmem_handle, annotation_shmem_size, depth_shmem_handle, depth_shmem_size, is_render_colours, is_render_annotations, is_render_instance, is_render_depth, is_visualised, is_static, is_snapping_desired, is_force_inside_triangle)
open_lidar(name, vehicle, is_using_shared_memory, point_cloud_shmem_handle, point_cloud_shmem_size, colour_shmem_handle, colour_shmem_size, requested_update_time, update_priority, pos, dir, up, vertical_resolution, vertical_angle, rays_per_second, frequency, horizontal_angle, max_distance, is_visualised, is_annotated, is_static, is_snapping_desired, is_force_inside_triangle)
open_ultrasonic(name, vehicle, requested_update_time, update_priority, pos, dir, up, size, field_of_view_y, near_far_planes, range_roundness, range_cutoff_sensitivity, range_shape, range_focus, range_min_cutoff, range_direct_max_cutoff, sensitivity, fixed_window_size, is_visualised, is_static, is_snapping_desired, is_force_inside_triangle)
pause()

Sends a pause request to BeamNG.*, blocking until the simulation is paused.

poll_accelerometer(name)
poll_camera(name, is_using_shared_memory)
poll_lidar(name, is_using_shared_memory)
poll_ultrasonic(name)
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()
remove_debug_cylinder(cylinder_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_ad_hoc_request_accelerometer(name, vid)
send_ad_hoc_request_camera(name)
send_ad_hoc_request_lidar(name)
send_ad_hoc_request_ultrasonic(name)
set_accelerometer_is_using_gravity(name, vid, is_using_gravity)
set_accelerometer_is_visualised(name, vid, is_visualised)
set_accelerometer_requested_update_time(name, vid, requested_update_time)
set_camera_max_pending_gpu_requests(name, max_pending_gpu_requests)
set_camera_requested_update_time(name, requested_update_time)
set_camera_sensor_direction(name, dir)
set_camera_sensor_position(name, pos)
set_camera_sensor_up(name, up)
set_camera_update_priority(name, update_priority)
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_lidar_frequency(name, frequency)
set_lidar_is_annotated(name, is_annotated)
set_lidar_is_visualised(name, is_visualised)
set_lidar_max_distance(name, max_distance)
set_lidar_max_pending_gpu_requests(name, max_pending_gpu_requests)
set_lidar_rays_per_second(name, rays_per_second)
set_lidar_requested_update_time(name, requested_update_time)
set_lidar_update_priority(name, update_priority)
set_lidar_vertical_resolution(name, vertical_resolution)
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 of

  • 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_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, custom_data=None)

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.

  • custom_data (dict) – Custom data used by the specific camera mode. Defaults to None.

set_relative_camera(pos, 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_ultrasonic_is_visualised(name, is_visualised)
set_ultrasonic_max_pending_gpu_requests(name, max_pending_gpu_requests)
set_ultrasonic_requested_update_time(name, requested_update_time)
set_ultrasonic_update_priority(name, update_priority)
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.

show_hud()

Shows the HUD in the simulator.

spawn_vehicle(vehicle, pos, 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_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(restrict_actions=False)

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.

Parameters

restrict_actions (bool) – Whether to keep scenario restrictions, such as limited menu options and controls. Defaults to False.

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.

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_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_quat (tuple) – Optional tuple specifying object rotation as a quaternion

teleport_vehicle(vehicle_id, pos, 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_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.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

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

Bases: object

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

static from_dict(d)

beamngpy.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 the scene field of this class.

update()

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

Raises

BNGError – If the scenario is currently not loaded.

class beamngpy.scenario.ScenarioObject(oid, name, otype, pos, 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 map

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

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

  • chase: Chase a target vehicle, target set separately

  • flee: Flee from a vehicle, target set separately

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

    once the vehicle stopped.)

Note

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

Parameters

mode (str) – The AI mode to set.

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

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

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

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

Notes

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

Raises

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

ai_set_speed(speed, mode='limit')

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

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

    sees fit.

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

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

  • mode (str) – The speed mode.

ai_set_target(target, mode='chase')

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

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

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

ai_set_waypoint(waypoint)

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

Parameters

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

annotate_parts()

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

attach_sensor(name, sensor)

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

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

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

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 the

    user, including engaging the clutch.

  • realistic_manual_auto_clutch: Gears have to be shifted manually

    by the user, without having to use the clutch.

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

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

  • realistic_automatic: Gears shift up automatically, but reverse

    and parking need to be shifted to manually.

Parameters

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

Raises

BNGValueError – If an invalid mode is given.

set_velocity(velocity, dt=1.0)

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

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

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

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

start_in_game_logging(outputDir)

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

Parameters

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

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

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

  • vel: The vehicle’s velocity along each axis in metres per second as an (x,y,z) triplet

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

stop_in_game_logging()

Stops in game logging.

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

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)