301 KiB
#Python API reference
This reference contains all the details the Python API. To consult a previous reference for a specific CARLA release, change the documentation version using the panel in the bottom right corner.
This will change the whole documentation to a previous state. Remember that the latest version is the dev
branch and may show features not available in any packaged versions of CARLA.
carla.Actor
CARLA defines actors as anything that plays a role in the simulation or can be moved around. That includes: pedestrians, vehicles, sensors and traffic signs (considering traffic lights as part of these). Actors are spawned in the simulation by carla.World and they need for a carla.ActorBlueprint to be created. These blueprints belong into a library provided by CARLA, find more about them here.
Instance Variables
- attributes (dict)
A dictionary containing the attributes of the blueprint this actor was based on. - id (int)
Identifier for this actor. Unique during a given episode. - is_alive (bool)
Returns whether this object was destroyed using this actor handle. - parent (carla.Actor)
Actors may be attached to a parent actor that they will follow around. This is said actor. - semantic_tags (list(int))
A list of semantic tags provided by the blueprint listing components for this actor. E.g. a traffic light could be tagged withPole
andTrafficLight
. These tags are used by the semantic segmentation sensor. Find more about this and other sensors here. - type_id (str)
The identifier of the blueprint this actor was based on, e.g.vehicle.ford.mustang
.
Methods
- add_angular_impulse(self, angular_impulse)
Applies an angular impulse at the center of mass of the actor. This method should be used for instantaneous torques, usually applied once. Use add_torque() to apply rotation forces over a period of time.- Parameters:
angular_impulse
(carla.Vector3D – degrees*s) – Angular impulse vector in global coordinates.
- Parameters:
- add_force(self, force)
Applies a force at the center of mass of the actor. This method should be used for forces that are applied over a certain period of time. Use add_impulse() to apply an impulse that only lasts an instant.- Parameters:
force
(carla.Vector3D – N) – Force vector in global coordinates.
- Parameters:
- add_impulse(self, impulse)
Applies an impulse at the center of mass of the actor. This method should be used for instantaneous forces, usually applied once. Use add_force() to apply forces over a period of time.- Parameters:
impulse
(carla.Vector3D – N*s) – Impulse vector in global coordinates.
- Parameters:
- add_torque(self, torque)
Applies a torque at the center of mass of the actor. This method should be used for torques that are applied over a certain period of time. Use add_angular_impulse() to apply a torque that only lasts an instant.- Parameters:
torque
(carla.Vector3D – degrees) – Torque vector in global coordinates.
- Parameters:
- destroy(self)
Tells the simulator to destroy this actor and returns True if it was successful. It has no effect if it was already destroyed.- Return: bool
- Warning: _This method blocks the script until the destruction is completed by the simulator. _
- disable_constant_velocity(self)
Disables any constant velocity previously set for a carla.Vehicle actor. - enable_constant_velocity(self, velocity)
Sets a vehicle's velocity vector to a constant value over time. The resulting velocity will be approximately thevelocity
being set, as with set_target_velocity().- Parameters:
velocity
(carla.Vector3D – m/s) – Velocity vector in local space.
- Warning: _Enabling a constant velocity for a vehicle managed by the Traffic Manager may cause conflicts. This method overrides any changes in velocity by the TM.
_
- Parameters:
Getters
- get_acceleration(self)
Returns the actor's 3D acceleration vector the client recieved during last tick. The method does not call the simulator.- Return: carla.Vector3D – m/s2
- get_angular_velocity(self)
Returns the actor's angular velocity vector the client recieved during last tick. The method does not call the simulator.- Return: carla.Vector3D – deg/s
- get_location(self)
Returns the actor's location the client recieved during last tick. The method does not call the simulator.- Return: carla.Location – meters
- Setter: carla.Actor.set_location
- get_transform(self)
Returns the actor's transform (location and rotation) the client recieved during last tick. The method does not call the simulator.- Return: carla.Transform
- Setter: carla.Actor.set_transform
- get_velocity(self)
Returns the actor's velocity vector the client recieved during last tick. The method does not call the simulator.- Return: carla.Vector3D – m/s
- get_world(self)
Returns the world this actor belongs to.- Return: carla.World
Setters
- set_location(self, location)
Teleports the actor to a given location.- Parameters:
location
(carla.Location – meters)
- Getter: carla.Actor.get_location
- Parameters:
- set_simulate_physics(self, enabled=True)
Enables or disables the simulation of physics on this actor.- Parameters:
enabled
(bool)
- Parameters:
- set_target_angular_velocity(self, angular_velocity)
Sets the actor's angular velocity vector. The modification will be effective two frames after the setting. Also, this is applied before the physics step so the resulting angular velocity will be affected by external forces at this frame such as friction.- Parameters:
angular_velocity
(carla.Vector3D – deg/s)
- Note: _The update will not be effective until two frames after it is set.
_
- Parameters:
- set_target_velocity(self, velocity)
Sets the actor's velocity vector. The modification will be effective two frames after the setting. Also, this is applied before the physics step so the resulting velocity will be affected by external forces at this frame such as friction.- Parameters:
velocity
(carla.Vector3D)
- Note: _The update will not be effective until two frames after it is set.
_
- Parameters:
- set_transform(self, transform)
Teleports the actor to a given transform (location and rotation).- Parameters:
transform
(carla.Transform)
- Getter: carla.Actor.get_transform
- Parameters:
Dunder methods
carla.ActorAttribute
CARLA provides a library of blueprints for actors that can be accessed as carla.BlueprintLibrary. Each of these blueprints has a series of attributes defined internally. Some of these are modifiable, others are not. A list of recommended values is provided for those that can be set.
Instance Variables
- id (str)
The attribute's name and identifier in the library. - is_modifiable (bool)
It is True if the attribute's value can be modified. - recommended_values (list(str))
A list of values suggested by those who designed the blueprint. - type (carla.ActorAttributeType)
The attribute's parameter type.
Methods
- as_bool(self)
Reads the attribute as boolean value. - as_color(self)
Reads the attribute as carla.Color. - as_float(self)
Reads the attribute as float. - as_int(self)
Reads the attribute as int. - as_str(self)
Reads the attribute as string.
Dunder methods
- _bool_(self)
- _eq_(self, other=bool / int / float / str / carla.Color / carla.ActorAttribute)
Returns true if this actor's attribute andother
are the same.- Return: bool
- _float_(self)
- _int_(self)
- _ne_(self, other=bool / int / float / str / carla.Color / carla.ActorAttribute)
Returns true if this actor's attribute andother
are different.- Return: bool
- _nonzero_(self)
Returns true if this actor's attribute is not zero or null.- Return: bool
- _str_(self)
carla.ActorAttributeType
CARLA provides a library of blueprints for actors in carla.BlueprintLibrary with different attributes each. This class defines the types those at carla.ActorAttribute can be as a series of enum. All this information is managed internally and listed here for a better comprehension of how CARLA works.
Instance Variables
carla.ActorBlueprint
CARLA provides a blueprint library for actors that can be consulted through carla.BlueprintLibrary. Each of these consists of an identifier for the blueprint and a series of attributes that may be modifiable or not. This class is the intermediate step between the library and the actor creation. Actors need an actor blueprint to be spawned. These store the information for said blueprint in an object with its attributes and some tags to categorize them. The user can then customize some attributes and eventually spawn the actors through carla.World.
Instance Variables
- id (str)
The identifier of said blueprint inside the library. E.g.walker.pedestrian.0001
. - tags (list(str))
A list of tags each blueprint has that helps describing them. E.g.['0001', 'pedestrian', 'walker']
.
Methods
- has_attribute(self, id)
Returns True if the blueprint contains the attributeid
.- Parameters:
id
(str) – e.g.gender
would return True for pedestrians' blueprints.
- Return: bool
- Parameters:
- has_tag(self, tag)
Returns True if the blueprint has the specifiedtag
listed.- Parameters:
tag
(str) – e.g. 'walker'.
- Return: bool
- Parameters:
- match_tags(self, wildcard_pattern)
Returns True if any of the tags listed for this blueprint matcheswildcard_pattern
. Matching follows fnmatch standard.- Parameters:
wildcard_pattern
(str)
- Return: bool
- Parameters:
Getters
- get_attribute(self, id)
Returns the actor's attribute withid
as identifier if existing.- Parameters:
id
(str)
- Return: carla.ActorAttribute
- Setter: carla.ActorBlueprint.set_attribute
- Parameters:
Setters
- set_attribute(self, id, value)snippet →
If theid
attribute is modifiable, changes its value tovalue
.- Parameters:
id
(str) – The identifier for the attribute that is intended to be changed.value
(str) – The new value for said attribute.
- Getter: carla.ActorBlueprint.get_attribute
- Parameters:
Dunder methods
- _iter_(self)
Iterate over the carla.ActorAttribute that this blueprint has. - _len_(self)
Returns the amount of attributes for this blueprint. - _str_(self)
carla.ActorList
A class that contains every actor present on the scene and provides access to them. The list is automatically created and updated by the server and it can be returned using carla.World.
Methods
- filter(self, wildcard_pattern)
Filters a list of Actors matchingwildcard_pattern
against their variable type_id (which identifies the blueprint used to spawn them). Matching follows fnmatch standard.- Parameters:
wildcard_pattern
(str)
- Return: list
- Parameters:
- find(self, actor_id)
Finds an actor using its identifier and returns it or None if it is not present.- Parameters:
actor_id
(int)
- Return: carla.Actor
- Parameters:
Dunder methods
- _getitem_(self, pos=int)
Returns the actor corresponding topos
position in the list.- Return: carla.Actor
- _iter_(self)
Iterate over the carla.Actor contained in the list. - _len_(self)
Returns the amount of actors listed.- Return: int
- _str_(self)
Parses to the ID for every actor listed.- Return: str
carla.ActorSnapshot
A class that comprises all the information for an actor at a certain moment in time. These objects are contained in a carla.WorldSnapshot and sent to the client once every tick.
Instance Variables
Methods
Getters
- get_acceleration(self)
Returns the acceleration vector registered for an actor in that tick.- Return: carla.Vector3D – m/s2
- get_angular_velocity(self)
Returns the angular velocity vector registered for an actor in that tick.- Return: carla.Vector3D – rad/s
- get_transform(self)
Returns the actor's transform (location and rotation) for an actor in that tick.- Return: carla.Transform
- get_velocity(self)
Returns the velocity vector registered for an actor in that tick.- Return: carla.Vector3D – m/s
carla.AttachmentType
Class that defines attachment options between an actor and its parent. When spawning actors, these can be attached to another actor so their position changes accordingly. This is specially useful for sensors. The snipet in carla.World.spawn_actor shows some sensors being attached to a car when spawned. Note that the attachment type is declared as an enum within the class.
Instance Variables
- Rigid
With this fixed attatchment the object follow its parent position strictly. This is the recommended attachment to retrieve precise data from the simulation. - SpringArm
An attachment that expands or retracts the position of the actor, depending on its parent. This attachment is only recommended to record videos from the simulation where a smooth movement is needed. SpringArms are an Unreal Engine component so check the UE docs to learn more about them.
Warning: The SpringArm attachment presents weird behaviors when an actor is spawned with a relative translation in the Z-axis (e.g.child_location = Location(0,0,2)
).
carla.BlueprintLibrary
A class that contains the blueprints provided for actor spawning. Its main application is to return carla.ActorBlueprint objects needed to spawn actors. Each blueprint has an identifier and attributes that may or may not be modifiable. The library is automatically created by the server and can be accessed through carla.World.
Here is a reference containing every available blueprint and its specifics.
Methods
- filter(self, wildcard_pattern)
Filters a list of blueprints matching thewildcard_pattern
against the id and tags of every blueprint contained in this library and returns the result as a new one. Matching follows fnmatch standard.- Parameters:
wildcard_pattern
(str)
- Return: carla.BlueprintLibrary
- Parameters:
- find(self, id)
Returns the blueprint corresponding to that identifier.- Parameters:
id
(str)
- Return: carla.ActorBlueprint
- Parameters:
Dunder methods
- _getitem_(self, pos=int)
Returns the blueprint stored inpos
position inside the data structure containing them.- Return: carla.ActorBlueprint
- _iter_(self)
Iterate over the carla.ActorBlueprint stored in the library. - _len_(self)
Returns the amount of blueprints comprising the library.- Return: int
- _str_(self)
Parses the identifiers for every blueprint to string.- Return: string
carla.BoundingBox
Bounding boxes contain the geometry of an actor or an element in the scene. They can be used by carla.DebugHelper or a carla.Client to draw their shapes for debugging. Check out the snipet in carla.DebugHelper.draw_box where a snapshot of the world is used to draw bounding boxes for traffic lights.
Instance Variables
- extent (carla.Vector3D – meters)
Vector from the center of the box to one vertex. The value in each axis equals half the size of the box for that axis.extent.x * 2
would return the size of the box in the X-axis. - location (carla.Location – meters)
The center of the bounding box. - rotation (carla.Rotation)
The orientation of the bounding box.
Methods
- _init_(self, location, extent)
- Parameters:
location
(carla.Location) – Center of the box, relative to its parent.extent
(carla.Vector3D – meters) – Vector containing half the size of the box for every axis.
- Parameters:
- contains(self, world_point, transform)
Returns True if a point passed in world space is inside this bounding box.- Parameters:
world_point
(carla.Location – meters) – The point in world space to be checked.transform
(carla.Transform) – Contains location and rotation needed to convert this object's local space to world space.
- Return: bool
- Parameters:
Getters
- get_local_vertices(self)
Returns a list containing the locations of this object's vertices in local space.- Return: list(carla.Location)
- get_world_vertices(self, transform)
Returns a list containing the locations of this object's vertices in world space.- Parameters:
transform
(carla.Transform) – Contains location and rotation needed to convert this object's local space to world space.
- Return: list(carla.Location)
- Parameters:
Dunder methods
- _eq_(self, other=carla.BoundingBox)
Returns true if both location and extent are equal for this andother
.- Return: bool
- _ne_(self, other=carla.BoundingBox)
Returns true if either location or extent are different for this andother
.- Return: bool
- _str_(self)
Parses the location and extent of the bounding box to string.- Return: str
carla.CityObjectLabel
Enum declaration that contains the different tags available to filter the bounding boxes returned by carla.World.get_level_bbs(). These values correspond to the semantic tag that the elements in the scene have.
Instance Variables
- None
- Buildings
- Fences
- Other
- Pedestrians
- Poles
- RoadLines
- Roads
- Sidewalks
- TrafficSigns
- Vegetation
- Vehicles
- Walls
- Sky
- Ground
- Bridge
- RailTrack
- GuardRail
- TrafficLight
- Static
- Dynamic
- Water
- Terrain
- Any
carla.Client
The Client connects CARLA to the server which runs the simulation. Both server and client contain a CARLA library (libcarla) with some differences that allow communication between them. Many clients can be created and each of these will connect to the RPC server inside the simulation to send commands. The simulation runs server-side. Once the connection is established, the client will only receive data retrieved from the simulation. Walkers are the exception. The client is in charge of managing pedestrians so, if you are running a simulation with multiple clients, some issues may arise. For example, if you spawn walkers through different clients, collisions may happen, as each client is only aware of the ones it is in charge of.
The client also has a recording feature that saves all the information of a simulation while running it. This allows the server to replay it at will to obtain information and experiment with it. Here is some information about how to use this recorder.
Methods
- _init_(self, host=127.0.0.1, port=2000, worker_threads=0)snippet →
Client constructor.- Parameters:
host
(str) – IP address where a CARLA Simulator instance is running. Default is localhost (127.0.0.1).port
(int) – TCP port where the CARLA Simulator instance is running. Default are 2000 and the subsequent 2001.worker_threads
(int) – Number of working threads used for background updates. If 0, use all available concurrency.
- Parameters:
- apply_batch(self, commands)
Executes a list of commands on a single simulation step and retrieves no information. If you need information about the response of each command, use the apply_batch_sync() method. Here is an example on how to delete the actors that appear in carla.ActorList all at once.- Parameters:
commands
(list) – A list of commands to execute in batch. Each command is different and has its own parameters. They appear listed at the bottom of this page.
- Parameters:
- apply_batch_sync(self, commands, due_tick_cue=False)snippet →
Executes a list of commands on a single simulation step, blocks until the commands are linked, and returns a list of command.Response that can be used to determine whether a single command succeeded or not. Here is an example of it being used to spawn actors.- Parameters:
commands
(list) – A list of commands to execute in batch. The commands available are listed right above, in the method apply_batch().due_tick_cue
(bool) – A boolean parameter to specify whether or not to perform a carla.World.tick after applying the batch in synchronous mode. It is False by default.
- Return: list(command.Response)
- Parameters:
- generate_opendrive_world(self, opendrive, parameters=(2.0, 50.0, 1.0, 0.6, true, true), reset_settings=True)
Loads a new world with a basic 3D topology generated from the content of an OpenDRIVE file. This content is passed as astring
parameter. It is similar toclient.load_world(map_name)
but allows for custom OpenDRIVE maps in server side. Cars can drive around the map, but there are no graphics besides the road and sidewalks.- Parameters:
opendrive
(str) – Content of an OpenDRIVE file asstring
, not the path to the.xodr
.parameters
(carla.OpendriveGenerationParameters) – Additional settings for the mesh generation. If none are provided, default values will be used.reset_settings
(bool) – Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- Parameters:
- load_world(self, map_name, reset_settings=True, map_layers=carla.MapLayer.All)
Creates a new world with default settings usingmap_name
map. All actors in the current world will be destroyed.- Parameters:
map_name
(str) – Name of the map to be used in this world. Accepts both full paths and map names, e.g. '/Game/Carla/Maps/Town01' or 'Town01'. Remember that these paths are dynamic.reset_settings
(bool) – Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.map_layers
(carla.MapLayer) – Layers of the map that will be loaded. By default all layers are loaded. This parameter works like a flag mask.
- Warning: _
map_layers
are only available for "Opt" maps _
- Parameters:
- reload_world(self, reset_settings=True)
Reload the current world, note that a new world is created with default settings using the same map. All actors present in the world will be destroyed, but traffic manager instances will stay alive.- Parameters:
reset_settings
(bool) – Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- Raises: RuntimeError when corresponding.
- Parameters:
- replay_file(self, name, start, duration, follow_id, replay_sensors)
Load a new world with default settings usingmap_name
map. All actors present in the current world will be destroyed, but traffic manager instances will stay alive.- Parameters:
name
(str) – Name of the file containing the information of the simulation.start
(float – seconds) – Time where to start playing the simulation. Negative is read as beginning from the end, being -10 just 10 seconds before the recording finished.duration
(float – seconds) – Time that will be reenacted using the informationname
file. If the end is reached, the simulation will continue.follow_id
(int) – ID of the actor to follow. If this is 0 then camera is disabled.replay_sensors
(bool) – Flag to enable or disable the spawn of sensors during playback.
- Parameters:
- show_recorder_actors_blocked(self, filename, min_time, min_distance)
The terminal will show the information registered for actors considered blocked. An actor is considered blocked when it does not move a minimum distance in a period of time, being thesemin_distance
andmin_time
.- Parameters:
filename
(str) – Name of the recorded file to load.min_time
(float – seconds) – Minimum time the actor has to move a minimum distance before being considered blocked. Default is 60 seconds.min_distance
(float – centimeters) – Minimum distance the actor has to move to not be considered blocked. Default is 100 centimeters.
- Return: string
- Parameters:
- show_recorder_collisions(self, filename, category1, category2)
The terminal will show the collisions registered by the recorder. These can be filtered by specifying the type of actor involved. The categories will be specified incategory1
andcategory2
as follows: 'h' = Hero, the one vehicle that can be controlled manually or managed by the user. 'v' = Vehicle 'w' = Walker 't' = Traffic light 'o' = Other 'a' = Any If you want to see only collisions between a vehicles and a walkers, use forcategory1
as 'v' andcategory2
as 'w' or vice versa. If you want to see all the collisions (filter off) you can use 'a' for both parameters.- Parameters:
filename
(str) – Name or absolute path of the file recorded, depending on your previous choice.category1
(single char) – Character variable specifying a first type of actor involved in the collision.category2
(single char) – Character variable specifying the second type of actor involved in the collision.
- Return: string
- Parameters:
- show_recorder_file_info(self, filename, show_all)
The information saved by the recorder will be parsed and shown in your terminal as text (frames, times, events, state, positions...). The information shown can be specified by using theshow_all
parameter. Here is some more information about how to read the recorder file.- Parameters:
filename
(str) – Name or absolute path of the file recorded, depending on your previous choice.show_all
(bool) – If True, returns all the information stored for every frame (traffic light states, positions of all actors, orientation and animation data...). If False, returns a summary of key events and frames.
- Return: string
- Parameters:
- start_recorder(self, filename, additional_data=False)
Enables the recording feature, which will start saving every information possible needed by the server to replay the simulation.- Parameters:
filename
(str) – Name of the file to write the recorded data. A simple name will save the recording in 'CarlaUE4/Saved/recording.log'. Otherwise, if some folder appears in the name, it will be considered an absolute path.additional_data
(bool) – Enables or disable recording non-essential data for reproducing the simulation (bounding box location, physics control parameters, etc).
- Parameters:
- stop_recorder(self)
Stops the recording in progress. If you specified a path infilename
, the recording will be there. If not, look insideCarlaUE4/Saved/
. - stop_replayer(self, keep_actors)
Stop current replayer.- Parameters:
keep_actors
(bool) – True if you want autoremove all actors from the replayer, or False to keep them.
- Parameters:
Getters
- get_available_maps(self)
Returns a list of strings containing the paths of the maps available on server. These paths are dynamic, they will be created during the simulation and so you will not find them when looking up in your files. One of the possible returns for this method would be: ['/Game/Carla/Maps/Town01', '/Game/Carla/Maps/Town02', '/Game/Carla/Maps/Town03', '/Game/Carla/Maps/Town04', '/Game/Carla/Maps/Town05', '/Game/Carla/Maps/Town06', '/Game/Carla/Maps/Town07'].- Return: list(str)
- get_client_version(self)
Returns the client libcarla version by consulting it in the "Version.h" file. Both client and server can use different libcarla versions but some issues may arise regarding unexpected incompatibilities.- Return: str
- get_server_version(self)
Returns the server libcarla version by consulting it in the "Version.h" file. Both client and server should use the same libcarla version.- Return: str
- get_trafficmanager(self, client_connection=8000)
Returns an instance of the traffic manager related to the specified port. If it does not exist, this will be created.- Parameters:
client_connection
(int) – Port that will be used by the traffic manager. Default is8000
.
- Return: carla.TrafficManager
- Parameters:
- get_world(self)
Returns the world object currently active in the simulation. This world will be later used for example to load maps.- Return: carla.World
Setters
- set_replayer_time_factor(self, time_factor=1.0)
When used, the time speed of the reenacted simulation is modified at will. It can be used several times while a playback is in curse.- Parameters:
time_factor
(float) – 1.0 means normal time speed. Greater than 1.0 means fast motion (2.0 would be double speed) and lesser means slow motion (0.5 would be half speed).
- Parameters:
- set_timeout(self, seconds)
Sets the maxixum time a network call is allowed before blocking it and raising a timeout exceeded error.- Parameters:
seconds
(float – seconds) – New timeout value. Default is 5 seconds.
- Parameters:
carla.CollisionEvent
Instance Variables
- actor (carla.Actor)
The actor the sensor is attached to, the one that measured the collision. - other_actor (carla.Actor)
The second actor involved in the collision. - normal_impulse (carla.Vector3D – N*s)
Normal impulse resulting of the collision.
carla.Color
Class that defines a 32-bit RGBA color.
Instance Variables
- r (int)
Red color (0-255). - g (int)
Green color (0-255). - b (int)
Blue color (0-255). - a (int)
Alpha channel (0-255).
Methods
- _init_(self, r=0, g=0, b=0, a=255)
Initializes a color, black by default.- Parameters:
r
(int)g
(int)b
(int)a
(int)
- Parameters:
Dunder methods
- _eq_(self, other=carla.Color)
- _ne_(self, other=carla.Color)
- _str_(self)
carla.ColorConverter
Class that defines conversion patterns that can be applied to a carla.Image in order to show information provided by carla.Sensor. Depth conversions cause a loss of accuracy, as sensors detect depth as float that is then converted to a grayscale value between 0 and 255. Take a look at the snipet in carla.Sensor.listen to see an example of how to create and save image data for sensor.camera.semantic_segmentation.
Instance Variables
- CityScapesPalette
Converts the image to a segmentated map using tags provided by the blueprint library. Used by the semantic segmentation camera. - Depth
Converts the image to a linear depth map. Used by the depth camera. - LogarithmicDepth
Converts the image to a depth map using a logarithmic scale, leading to better precision for small distances at the expense of losing it when further away. - Raw
No changes applied to the image. Used by the RGB camera.
carla.DVSEvent
Class that defines a DVS event. An event is a quadruple, so a tuple of 4 elements, with x
, y
pixel coordinate location, timestamp t
and polarity pol
of the event. Learn more about them here.
Instance Variables
- x (int)
X pixel coordinate. - y (int)
Y pixel coordinate. - t (int)
Timestamp of the moment the event happened. - pol (bool)
Polarity of the event. True for positive and False for negative.
Methods
Dunder methods
carla.DVSEventArray
Class that defines a stream of events in carla.DVSEvent. Such stream is an array of arbitrary size depending on the number of events. This class also stores the field of view, the height and width of the image and the timestamp from convenience. Learn more about them here.
Instance Variables
- fov (float – degrees)
Horizontal field of view of the image. - height (int)
Image height in pixels. - width (int)
Image width in pixels. - raw_data (bytes)
Methods
- to_array(self)
Converts the stream of events to an array of int values in the following order[x, y, t, pol]
. - to_array_pol(self)
Returns an array with the polarity of all the events in the stream. - to_array_t(self)
Returns an array with the timestamp of all the events in the stream. - to_array_x(self)
Returns an array with X pixel coordinate of all the events in the stream. - to_array_y(self)
Returns an array with Y pixel coordinate of all the events in the stream. - to_image(self)
Converts the image following this pattern: blue indicates positive events, red indicates negative events.
Dunder methods
- _getitem_(self, pos=int)
- _iter_(self)
Iterate over the carla.DVSEvent retrieved as data. - _len_(self)
- _setitem_(self, pos=int, color=carla.Color)
- _str_(self)
carla.DebugHelper
Helper class part of carla.World that defines methods for creating debug shapes. By default, shapes last one second. They can be permanent, but take into account the resources needed to do so. Take a look at the snipets available for this class to learn how to debug easily in CARLA.
Methods
- draw_arrow(self, begin, end, thickness=0.1, arrow_size=0.1, color=(255,0,0), life_time=-1.0)
Draws an arrow frombegin
toend
pointing in that direction.- Parameters:
begin
(carla.Location – meters) – Point in the coordinate system where the arrow starts.end
(carla.Location – meters) – Point in the coordinate system where the arrow ends and points towards to.thickness
(float – meters) – Density of the line.arrow_size
(float – meters) – Size of the tip of the arrow.color
(carla.Color) – RGB code to color the object. Red by default.life_time
(float – seconds) – Shape's lifespan. By default it only lasts one frame. Set this to0
for permanent shapes.
- Parameters:
- draw_box(self, box, rotation, thickness=0.1, color=(255,0,0), life_time=-1.0)snippet →
Draws a box, ussually to act for object colliders.- Parameters:
box
(carla.BoundingBox) – Object containing a location and the length of a box for every axis.rotation
(carla.Rotation – degrees (pitch,yaw,roll)) – Orientation of the box according to Unreal Engine's axis system.thickness
(float – meters) – Density of the lines that define the box.color
(carla.Color) – RGB code to color the object. Red by default.life_time
(float – seconds) – Shape's lifespan. By default it only lasts one frame. Set this to0
for permanent shapes.
- Parameters:
- draw_line(self, begin, end, thickness=0.1, color=(255,0,0), life_time=-1.0)
Draws a line in betweenbegin
andend
.- Parameters:
begin
(carla.Location – meters) – Point in the coordinate system where the line starts.end
(carla.Location – meters) – Spot in the coordinate system where the line ends.thickness
(float – meters) – Density of the line.color
(carla.Color) – RGB code to color the object. Red by default.life_time
(float – seconds) – Shape's lifespan. By default it only lasts one frame. Set this to0
for permanent shapes.
- Parameters:
- draw_point(self, location, size=0.1, color=(255,0,0), life_time=-1.0)
Draws a pointlocation
.- Parameters:
location
(carla.Location – meters) – Spot in the coordinate system to center the object.size
(float – meters) – Density of the point.color
(carla.Color) – RGB code to color the object. Red by default.life_time
(float – seconds) – Shape's lifespan. By default it only lasts one frame. Set this to0
for permanent shapes.
- Parameters:
- draw_string(self, location, text, draw_shadow=False, color=(255,0,0), life_time=-1.0)snippet →
Draws a string in a given location of the simulation which can only be seen server-side.- Parameters:
location
(carla.Location – meters) – Spot in the simulation where the text will be centered.text
(str) – Text intended to be shown in the world.draw_shadow
(bool) – Casts a shadow for the string that could help in visualization. It is disabled by default.color
(carla.Color) – RGB code to color the string. Red by default.life_time
(float – seconds) – Shape's lifespan. By default it only lasts one frame. Set this to0
for permanent shapes.
- Parameters:
carla.EnvironmentObject
Class that represents a geometry in the level, this geometry could be part of an actor formed with other EnvironmentObjects (ie: buildings).
Instance Variables
- transform (carla.Transform)
Contains the location and orientation of the EnvironmentObject in world space. - bounding_box (carla.BoundingBox)
Object containing a location, rotation and the length of a box for every axis in world space. - id (int)
Unique ID to identify the object in the level. - name (string)
Name of the EnvironmentObject. - type (carla.CityObjectLabel)
Semantic tag.
Methods
Dunder methods
carla.GearPhysicsControl
Class that provides access to vehicle transmission details by defining a gear and when to run on it. This will be later used by carla.VehiclePhysicsControl to help simulate physics.
Instance Variables
- ratio (float)
The transmission ratio of the gear. - down_ratio (float)
Quotient between current RPM and MaxRPM where the autonomous gear box should shift down. - up_ratio (float)
Quotient between current RPM and MaxRPM where the autonomous gear box should shift up.
Methods
- _init_(self, ratio=1.0, down_ratio=0.5, up_ratio=0.65)
- Parameters:
ratio
(float)down_ratio
(float)up_ratio
(float)
- Parameters:
Dunder methods
- _eq_(self, other=carla.GearPhysicsControl)
- _ne_(self, other=carla.GearPhysicsControl)
- _str_(self)
carla.GeoLocation
Class that contains geographical coordinates simulated data. The carla.Map can convert simulation locations by using the tag in the OpenDRIVE file.
Instance Variables
- latitude (float – degrees)
North/South value of a point on the map. - longitude (float – degrees)
West/East value of a point on the map. - altitude (float – meters)
Height regarding ground level.
Methods
- _init_(self, latitude=0.0, longitude=0.0, altitude=0.0)
- Parameters:
latitude
(float – degrees)longitude
(float – degrees)altitude
(float – meters)
- Parameters:
Dunder methods
- _eq_(self, other=carla.GeoLocation)
- _ne_(self, other=carla.GeoLocation)
- _str_(self)
carla.GnssMeasurement
Instance Variables
- altitude (float – meters)
Height regarding ground level. - latitude (float – degrees)
North/South value of a point on the map. - longitude (float – degrees)
West/East value of a point on the map.
Methods
Dunder methods
carla.IMUMeasurement
Instance Variables
- accelerometer (carla.Vector3D – m/s2)
Linear acceleration. - compass (float – radians)
Orientation with regard to the North ([0.0, -1.0, 0.0] in Unreal Engine). - gyroscope (carla.Vector3D – rad/s)
Angular velocity.
Methods
Dunder methods
carla.Image
Instance Variables
- fov (float – degrees)
Horizontal field of view of the image. - height (int)
Image height in pixels. - width (int)
Image width in pixels. - raw_data (bytes)
Methods
- convert(self, color_converter)
Converts the image following thecolor_converter
pattern.- Parameters:
color_converter
(carla.ColorConverter)
- Parameters:
- save_to_disk(self, path, color_converter=Raw)
Saves the image to disk using a converter pattern stated ascolor_converter
. The default conversion pattern is Raw that will make no changes to the image.- Parameters:
path
(str) – Path that will contain the image.color_converter
(carla.ColorConverter) – Default Raw will make no changes.
- Parameters:
Dunder methods
- _getitem_(self, pos=int)
- _iter_(self)
Iterate over the carla.Color that form the image. - _len_(self)
- _setitem_(self, pos=int, color=carla.Color)
- _str_(self)
carla.Junction
Class that embodies the intersections on the road described in the OpenDRIVE file according to OpenDRIVE 1.4 standards.
Instance Variables
- id (int)
Identificator found in the OpenDRIVE file. - bounding_box (carla.BoundingBox)
Bounding box encapsulating the junction lanes.
Methods
Getters
- get_waypoints(self, lane_type)
Returns a list of pairs of waypoints. Every tuple on the list contains first an initial and then a final waypoint within the intersection boundaries that describe the beginning and the end of said lane along the junction. Lanes follow their OpenDRIVE definitions so there may be many different tuples with the same starting waypoint due to possible deviations, as this are considered different lanes.- Parameters:
lane_type
(carla.LaneType) – Type of lanes to get the waypoints.
- Return: list(tuple(carla.Waypoint))
- Parameters:
carla.LabelledPoint
Class that represent a position in space with a semantic label.
Instance Variables
carla.Landmark
Class that defines any type of traffic landmark or sign affecting a road. These class mediates between the OpenDRIVE 1.4 standard definition of the landmarks and their representation in the simulation. This class retrieves all the information defining a landmark in OpenDRIVE and facilitates information about which lanes does it affect and when. Landmarks will be accessed by carla.Waypoint objects trying to retrieve the regulation of their lane. Therefore some attributes depend on the waypoint that is consulting the landmark and so, creating the object.
Instance Variables
- road_id (int)
The OpenDRIVE ID of the road where this landmark is defined. Due to OpenDRIVE road definitions, this road may be different from the road the landmark is currently affecting. It is mostly the case in junctions where the road diverges in different routes. Example: a traffic light is defined in one of the divergent roads in a junction, but it affects all the possible routes. - distance (float – meters)
Distance between the landmark and the waypoint creating the object (queryingget_landmarks
orget_landmarks_of_type
). - s (float – meters)
Distance where the landmark is positioned along the geometry of the roadroad_id
. - t (float – meters)
Lateral distance where the landmark is positioned from the edge of the roadroad_id
. - id (str)
Unique ID of the landmark in the OpenDRIVE file. - name (str)
Name of the landmark in the in the OpenDRIVE file. - is_dynamic (bool)
Indicates if the landmark has state changes over time such as traffic lights. - orientation (carla.LandmarkOrientation – degrees)
Indicates which lanes the landmark is facing towards to. - z_offset (float – meters)
Height where the landmark is placed. - country (str)
Country code where the landmark is defined (default to OpenDRIVE is Germany 2017). - type (str)
Type identificator of the landmark according to the country code. - sub_type (str)
Subtype identificator of the landmark according to the country code. - value (float)
Value printed in the signal (e.g. speed limit, maximum weight, etc). - unit (str)
Units of measurement for the attributevalue
. - height (float – meters)
Total height of the signal. - width (float – meters)
Total width of the signal. - text (str)
Additional text in the signal. - h_offset (float – meters)
Orientation offset of the signal relative to the the definition ofroad_id
ats
in OpenDRIVE. - pitch (float – meters)
Pitch rotation of the signal (Y-axis in UE coordinates system). - roll (float)
Roll rotation of the signal (X-axis in UE coordinates system). - waypoint (carla.Waypoint)
A waypoint placed in the lane of the one that made the query and at thes
of the landmark. It is the first waypoint for which the landmark will be effective. - transform (carla.Transform)
The location and orientation of the landmark in the simulation.
Methods
Getters
- get_lane_validities(self)
Returns which lanes the landmark is affecting to. As there may be specific lanes where the landmark is not effective, the return is a list of pairs containing ranges of the lane_id affected: Example: In a road with 5 lanes, being 3 not affected: [(from_lane1,to_lane2),(from_lane4,to_lane5)].- Return: list(tuple(int))
carla.LandmarkOrientation
Helper class to define the orientation of a landmark in the road. The definition is not directly translated from OpenDRIVE but converted for the sake of understanding.
Instance Variables
- Positive
The landmark faces towards vehicles going on the same direction as the road's geometry definition (lanes 0 and negative in OpenDRIVE). - Negative
The landmark faces towards vehicles going on the opposite direction to the road's geometry definition (positive lanes in OpenDRIVE). - Both
Affects vehicles going in both directions of the road.
carla.LandmarkType
Helper class containing a set of commonly used landmark types as defined by the default country code in the OpenDRIVE standard (Germany 2017). carla.Landmark does not reference this class. The landmark type is a string that varies greatly depending on the country code being used. This class only makes it easier to manage some of the most commonly used in the default set by describing them as an enum.
Instance Variables
- Danger
Type 101. - LanesMerging
Type 121. - CautionPedestrian
Type 133. - CautionBicycle
Type 138. - LevelCrossing
Type 150. - StopSign
Type 206. - YieldSign
Type 205. - MandatoryTurnDirection
Type 209. - MandatoryLeftRightDirection
Type 211. - TwoChoiceTurnDirection
Type 214. - Roundabout
Type 215. - PassRightLeft
Type 222. - AccessForbidden
Type 250. - AccessForbiddenMotorvehicles
Type 251. - AccessForbiddenTrucks
Type 253. - AccessForbiddenBicycle
Type 254. - AccessForbiddenWeight
Type 263. - AccessForbiddenWidth
Type 264. - AccessForbiddenHeight
Type 265. - AccessForbiddenWrongDirection
Type 267. - ForbiddenUTurn
Type 272. - MaximumSpeed
Type 274. - ForbiddenOvertakingMotorvehicles
Type 276. - ForbiddenOvertakingTrucks
Type 277. - AbsoluteNoStop
Type 283. - RestrictedStop
Type 286. - HasWayNextIntersection
Type 301. - PriorityWay
Type 306. - PriorityWayEnd
Type 307. - CityBegin
Type 310. - CityEnd
Type 311. - Highway
Type 330. - RecomendedSpeed
Type 380. - RecomendedSpeedEnd
Type 381.
carla.LaneChange
Class that defines the permission to turn either left, right, both or none (meaning only going straight is allowed). This information is stored for every carla.Waypoint according to the OpenDRIVE file. The snipet in carla.Map.get_waypoint shows how a waypoint can be used to learn which turns are permitted.
Instance Variables
- NONE
Traffic rules do not allow turning right or left, only going straight. - Right
Traffic rules allow turning right. - Left
Traffic rules allow turning left. - Both
Traffic rules allow turning either right or left.
carla.LaneInvasionEvent
Instance Variables
- actor (carla.Actor)
Gets the actor the sensor is attached to, the one that invaded another lane. - crossed_lane_markings (list(carla.LaneMarking))
List of lane markings that have been crossed and detected by the sensor.
Methods
Dunder methods
carla.LaneMarking
Class that gathers all the information regarding a lane marking according to OpenDRIVE 1.4 standard standard.
Instance Variables
- color (carla.LaneMarkingColor)
Actual color of the marking. - lane_change (carla.LaneChange)
Permissions for said lane marking to be crossed. - type (carla.LaneMarkingType)
Lane marking type. - width (float)
Horizontal lane marking thickness.
carla.LaneMarkingColor
Class that defines the lane marking colors according to OpenDRIVE 1.4.
Instance Variables
carla.LaneMarkingType
Class that defines the lane marking types accepted by OpenDRIVE 1.4. The snipet in carla.Map.get_waypoint shows how a waypoint can be used to retrieve the information about adjacent lane markings.
Note on double types: Lane markings are defined under the OpenDRIVE standard that determines whereas a line will be considered "BrokenSolid" or "SolidBroken". For each road there is a center lane marking, defined from left to right regarding the lane's directions. The rest of the lane markings are defined in order from the center lane to the closest outside of the road.
Instance Variables
carla.LaneType
Class that defines the possible lane types accepted by OpenDRIVE 1.4. This standards define the road information. The snipet in carla.Map.get_waypoint makes use of a waypoint to get the current and adjacent lane types.
Instance Variables
- NONE
- Driving
- Stop
- Shoulder
- Biking
- Sidewalk
- Border
- Restricted
- Parking
- Bidirectional
- Median
- Special1
- Special2
- Special3
- RoadWorks
- Tram
- Rail
- Entry
- Exit
- OffRamp
- OnRamp
- Any
Every type except for NONE.
carla.LidarDetection
Data contained inside a carla.LidarMeasurement. Each of these represents one of the points in the cloud with its location and its asociated intensity.
Instance Variables
- point (carla.Location – meters)
Point in xyz coordinates. - intensity (float)
Computed intensity for this point as a scalar value between [0.0 , 1.0].
Methods
Dunder methods
carla.LidarMeasurement
Instance Variables
- channels (int)
Number of lasers shot. - horizontal_angle (float – radians)
Horizontal angle the LIDAR is rotated at the time of the measurement. - raw_data (bytes)
Received list of 4D points. Each point consists of [x,y,z] coordiantes plus the intensity computed for that point.
Methods
- save_to_disk(self, path)
Saves the point cloud to disk as a .ply file describing data from 3D scanners. The files generated are ready to be used within MeshLab, an open source system for processing said files. Just take into account that axis may differ from Unreal Engine and so, need to be reallocated.- Parameters:
path
(str)
- Parameters:
Getters
- get_point_count(self, channel)
Retrieves the number of points sorted by channel that are generated by this measure. Sorting by channel allows to identify the original channel for every point.- Parameters:
channel
(int)
- Parameters:
Dunder methods
- _getitem_(self, pos=int)
- _iter_(self)
Iterate over the carla.LidarDetection retrieved as data. - _len_(self)
- _setitem_(self, pos=int, detection=carla.LidarDetection)
- _str_(self)
carla.Light
This class exposes the lights that exist in the scene, except for vehicle lights. The properties of a light can be queried and changed at will. Lights are automatically turned on when the simulator enters night mode (sun altitude is below zero).
Instance Variables
- color (carla.Color)
Color of the light. - id (int)
Identifier of the light. - intensity (float – lumens)
Intensity of the light. - is_on (bool)
Switch of the light. It is True when the light is on. When the night mode starts, this is set to True. - location (carla.Location – meters)
Position of the light. - light_group (carla.LightGroup)
Group the light belongs to. - light_state (carla.LightState)
State of the light. Summarizes its attributes, group, and if it is on/off.
Methods
Setters
- set_color(self, color)
Changes the color of the light tocolor
.- Parameters:
color
(carla.Color)
- Parameters:
- set_intensity(self, intensity)
Changes the intensity of the light tointensity
.- Parameters:
intensity
(float – lumens)
- Parameters:
- set_light_group(self, light_group)
Changes the light to the grouplight_group
.- Parameters:
light_group
(carla.LightGroup)
- Parameters:
- set_light_state(self, light_state)
Changes the state of the light tolight_state
. This may change attributes, group and turn the light on/off all at once.- Parameters:
light_state
(carla.LightState)
- Parameters:
carla.LightGroup
This class categorizes the lights on scene into different groups. These groups available are provided as a enum values that can be used as flags.
Note. So far, though there is a vehicle
group, vehicle lights are not available as carla.Light objects. These have to be managed using carla.Vehicle and carla.VehicleLightState.
Instance Variables
carla.LightManager
This class handles the lights in the scene. Its main use is to get and set the state of groups or lists of lights in one call. An instance of this class can be retrieved by the carla.World.get_lightmanager().
Note. So far, though there is a vehicle
group, vehicle lights are not available as carla.Light objects. These have to be managed using carla.Vehicle and carla.VehicleLightState.
Methods
- is_active(self, lights)
Returns a list with booleans stating if the elements inlights
are switched on/off.- Parameters:
lights
(list(carla.Light)) – List of lights to be queried.
- Return: list(bool)
- Parameters:
- turn_off(self, lights)
Switches off all the lights inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be switched off.
- Parameters:
- turn_on(self, lights)
Switches on all the lights inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be switched on.
- Parameters:
Getters
- get_all_lights(self, light_group=carla.LightGroup.None)
Returns a list containing the lights in a certain group. By default, the group isNone
.- Parameters:
light_group
(carla.LightGroup) – Group to filter the lights returned. Default isNone
.
- Return: list(carla.Light)
- Parameters:
- get_color(self, lights)
Returns a list with the colors of every element inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be queried.
- Return: list(carla.Color)
- Setter: carla.LightManager.set_color
- Parameters:
- get_intensity(self, lights)
Returns a list with the intensity of every element inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be queried.
- Return: list(float) – lumens
- Setter: carla.LightManager.set_intensity
- Parameters:
- get_light_group(self, lights)
Returns a list with the group of every element inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be queried.
- Return: list(carla.LightGroup)
- Setter: carla.LightManager.set_light_group
- Parameters:
- get_light_state(self, lights)
Returns a list with the state of all the attributes of every element inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be queried.
- Return: list(carla.LightState)
- Setter: carla.LightManager.set_light_state
- Parameters:
- get_turned_off_lights(self, light_group)
Returns a list containing lights switched off in the scene, filtered by group.- Parameters:
light_group
(carla.LightGroup) – List of lights to be queried.
- Return: list(carla.Light)
- Parameters:
- get_turned_on_lights(self, light_group)
Returns a list containing lights switched on in the scene, filtered by group.- Parameters:
light_group
(carla.LightGroup) – List of lights to be queried.
- Return: list(carla.Light)
- Parameters:
Setters
- set_active(self, lights, active)
Switches on/off the elements inlights
.- Parameters:
lights
(list(carla.Light)) – List of lights to be switched on/off.active
(list(bool)) – List of booleans to be applied.
- Parameters:
- set_color(self, lights, color)
Changes the color of the elements inlights
tocolor
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.color
(carla.Color) – Color to be applied.
- Getter: carla.LightManager.get_color
- Parameters:
- set_colors(self, lights, colors)
Changes the color of each element inlights
to the corresponding incolors
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.colors
(list(carla.Color)) – List of colors to be applied.
- Parameters:
- set_intensities(self, lights, intensities)
Changes the intensity of each element inlights
to the corresponding inintensities
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.intensities
(list(float) – lumens) – List of intensities to be applied.
- Parameters:
- set_intensity(self, lights, intensity)
Changes the intensity of every element inlights
tointensity
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.intensity
(float – lumens) – Intensity to be applied.
- Getter: carla.LightManager.get_intensity
- Parameters:
- set_light_group(self, lights, light_group)
Changes the group of every element inlights
tolight_group
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.light_group
(carla.LightGroup) – Group to be applied.
- Getter: carla.LightManager.get_light_group
- Parameters:
- set_light_groups(self, lights, light_groups)
Changes the group of each element inlights
to the corresponding inlight_groups
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.light_groups
(list(carla.LightGroup)) – List of groups to be applied.
- Parameters:
- set_light_state(self, lights, light_state)
Changes the state of the attributes of every element inlights
tolight_state
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.light_state
(carla.LightState) – State of the attributes to be applied.
- Getter: carla.LightManager.get_light_state
- Parameters:
- set_light_states(self, lights, light_states)
Changes the state of the attributes of each element inlights
to the corresponding inlight_states
.- Parameters:
lights
(list(carla.Light)) – List of lights to be changed.light_states
(list(carla.LightState)) – List of state of the attributes to be applied.
- Parameters:
carla.LightState
This class represents all the light variables except the identifier and the location, which are should to be static. Using this class allows to manage all the parametrization of the light in one call.
Instance Variables
- intensity (float – lumens)
Intensity of a light. - color (carla.Color)
Color of a light. - group (carla.LightGroup)
Group a light belongs to. - active (bool)
Switch of a light. It is True when the light is on.
Methods
- _init_(self, intensity=0.0, color=carla.Color(), group=carla.LightGroup.None, active=False)
- Parameters:
intensity
(float – lumens) – Intensity of the light. Default is0.0
.color
(carla.Color) – Color of the light. Default is black.group
(carla.LightGroup) – Group the light belongs to. Default is the generic groupNone
.active
(bool) – Swith of the light. Default isFalse
, light is off.
- Parameters:
carla.Location
Instance Variables
- x (float – meters)
Distance from origin to spot on X axis. - y (float – meters)
Distance from origin to spot on Y axis. - z (float – meters)
Distance from origin to spot on Z axis.
Methods
- _init_(self, x=0.0, y=0.0, z=0.0)
- Parameters:
x
(float)y
(float)z
(float)
- Parameters:
- distance(self, location)
Returns Euclidean distance from this location to another one.- Parameters:
location
(carla.Location) – The other point to compute the distance with.
- Return: float – meters
- Parameters:
Dunder methods
- _eq_(self, other=carla.Location)
Returns True if both locations are the same point in space.- Return: bool
- _ne_(self, other=carla.Location)
Returns True if both locations are different points in space.- Return: bool
- _str_(self)
Parses the axis' values to string.- Return: str
carla.Map
Class containing the road information and waypoint managing. Data is retrieved from an OpenDRIVE file that describes the road. A query system is defined which works hand in hand with carla.Waypoint to translate geometrical information from the .xodr to natural world points. CARLA is currently working with OpenDRIVE 1.4 standard.
Instance Variables
- name (str)
The name of the map. It corresponds to the .umap from Unreal Engine that is loaded from a CARLA server, which then references to the .xodr road description.
Methods
- _init_(self, name, xodr_content)
Constructor for this class. Though a map is automatically generated when initializing the world, using this method in no-rendering mode facilitates working with an .xodr without any CARLA server running.- Parameters:
name
(str) – Name of the current map.xodr_content
(str) – .xodr content in string format.
- Return: list(carla.Transform)
- Parameters:
- generate_waypoints(self, distance)
Returns a list of waypoints with a certain distance between them for every lane and centered inside of it. Waypoints are not listed in any particular order. Remember that waypoints closer than 2cm within the same road, section and lane will have the same identificator.- Parameters:
distance
(float – meters) – Approximate distance between waypoints.
- Return: list(carla.Waypoint)
- Parameters:
- save_to_disk(self, path)
Saves the .xodr OpenDRIVE file of the current map to disk.- Parameters:
path
– Path where the file will be saved.
- Parameters:
- to_opendrive(self)
Returns the .xodr OpenDRIVe file of the current map as string.- Return: str
- transform_to_geolocation(self, location)
Converts a givenlocation
, a point in the simulation, to a carla.GeoLocation, which represents world coordinates. The geographical location of the map is defined inside OpenDRIVE within the tag .- Parameters:
location
(carla.Location)
- Return: carla.GeoLocation
- Parameters:
Getters
- get_all_landmarks(self)
Returns all the landmarks in the map. Landmarks retrieved using this method have a null waypoint.- Return: list(carla.Landmark)
- get_all_landmarks_from_id(self, opendrive_id)
Returns the landmarks with a certain OpenDRIVE ID. Landmarks retrieved using this method have a null waypoint.- Parameters:
opendrive_id
(string) – The OpenDRIVE ID of the landmarks.
- Return: list(carla.Landmark)
- Parameters:
- get_all_landmarks_of_type(self, type)
Returns the landmarks of a specific type. Landmarks retrieved using this method have a null waypoint.- Parameters:
type
(string) – The type of the landmarks.
- Return: list(carla.Landmark)
- Parameters:
- get_landmark_group(self, landmark)
Returns the landmarks in the same group as the specified landmark (including itself). Returns an empty list if the landmark does not belong to any group.- Parameters:
landmark
(carla.Landmark) – A landmark that belongs to the group.
- Return: list(carla.Landmark)
- Parameters:
- get_spawn_points(self)
Returns a list of recommendations made by the creators of the map to be used as spawning points for the vehicles. The list includes carla.Transform objects with certain location and orientation. Said locations are slightly on-air in order to avoid Z-collisions, so vehicles fall for a bit before starting their way.- Return: list(carla.Transform)
- get_topology(self)
Returns a list of tuples describing a minimal graph of the topology of the OpenDRIVE file. The tuples contain pairs of waypoints located either at the point a road begins or ends. The first one is the origin and the second one represents another road end that can be reached. This graph can be loaded into NetworkX to work with. Output could look like this: [(w0, w1), (w0, w2), (w1, w3), (w2, w3), (w0, w4)].- Return: list(tuple(carla.Waypoint, carla.Waypoint))
- get_waypoint(self, location, project_to_road=True, lane_type=carla.LaneType.Driving)snippet →
Returns a waypoint that can be located in an exact location or translated to the center of the nearest lane. Said lane type can be defined using flags such asLaneType.Driving & LaneType.Shoulder
. The method will return None if the waypoint is not found, which may happen only when trying to retrieve a waypoint for an exact location. That eases checking if a point is inside a certain road, as otherwise, it will return the corresponding waypoint.- Parameters:
location
(carla.Location – meters) – Location used as reference for the carla.Waypoint.project_to_road
(bool) – If True, the waypoint will be at the center of the closest lane. This is the default setting. If False, the waypoint will be exactly inlocation
. None means said location does not belong to a road.lane_type
(carla.LaneType) – Limits the search for nearest lane to one or various lane types that can be flagged.
- Return: carla.Waypoint
- Parameters:
- get_waypoint_xodr(self, road_id, lane_id, s)
Returns a waypoint if all the parameters passed are correct. Otherwise, returns None.- Parameters:
road_id
(int) – ID of the road to get the waypoint.lane_id
(int) – ID of the lane to get the waypoint.s
(float – meters) – Specify the length from the road start.
- Return: carla.Waypoint
- Parameters:
Dunder methods
carla.MapLayer
Class that represents each manageable layer of the map. Can be used as flags. WARNING: Only "Opt" maps are able to work with map layers..
Instance Variables
- NONE
No layers selected. - Buildings
- Decals
- Foliage
- Ground
- ParkedVehicles
- Particles
- Props
- StreetLights
- Walls
- All
All layers selected.
carla.ObstacleDetectionEvent
Instance Variables
- actor (carla.Actor)
The actor the sensor is attached to. - other_actor (carla.Actor)
The actor or object considered to be an obstacle. - distance (float – meters)
Distance betweenactor
andother
.
Methods
Dunder methods
carla.OpendriveGenerationParameters
This class defines the parameters used when generating a world using an OpenDRIVE file.
Instance Variables
- vertex_distance (float)
Distance between vertices of the mesh generated. Default is2.0
. - max_road_length (float)
Max road length for a single mesh portion. The mesh of the map is divided into portions, in order to avoid propagating issues. Default is50.0
. - wall_height (float)
Height of walls created on the boundaries of the road. These prevent vehicles from falling off the road. Default is1.0
. - additional_width (float)
Additional with applied junction lanes. Complex situations tend to occur at junctions, and a little increase can prevent vehicles from falling off the road. Default is0.6
. - smooth_junctions (bool)
If True, the mesh at junctions will be smoothed to prevent issues where roads blocked other roads. Default isTrue
. - enable_mesh_visibility (bool)
If True, the road mesh will be rendered. Setting this to False should reduce the rendering overhead. Default isTrue
. - enable_pedestrian_navigation (bool)
If True, Pedestrian navigation will be enabled using Recast tool. For very large maps it is recomended to disable this option. Default isTrue
.
carla.Osm2Odr
Class that converts an OpenStreetMap map to OpenDRIVE format, so that it can be loaded in CARLA. Find out more about this feature in the docs.
Methods
- convert(osm_file, settings)
Takes the content of an.osm
file (OpenStreetMap format) and returns the content of the.xodr
(OpenDRIVE format) describing said map. Some parameterization is passed to do the conversion.- Parameters:
osm_file
(str) – The content of the input OpenStreetMap file parsed as string.settings
(carla.OSM2ODRSettings) – Parameterization for the conversion.
- Return: str
- Parameters:
carla.Osm2OdrSettings
Helper class that contains the parameterization that will be used by carla.Osm2Odr to convert an OpenStreetMap map to OpenDRIVE format. Find out more about this feature in the docs.
Instance Variables
- use_offsets (bool)
Enables the use of offset for the conversion. The offset will move the origin position of the map. Default value is False. - offset_x (float – meters)
Offset in the X axis. Default value is 0.0. - offset_y (float – meters)
Offset in the Y axis. Default value is 0.0. - default_lane_width (float – meters)
Width of the lanes described in the resulting XODR map. Default value is 4.0. - elevation_layer_height (float – meters)
Defines the height separating two different OpenStreetMap layers. Default value is 0.0.
carla.RadarDetection
Data contained inside a carla.RadarMeasurement. Each of these represents one of the points in the cloud that a sensor.other.radar registers and contains the distance, angle and velocity in relation to the radar.
Instance Variables
- altitude (float – radians)
Altitude angle of the detection. - azimuth (float – radians)
Azimuth angle of the detection. - depth (float – meters)
Distance from the sensor to the detection position. - velocity (float – m/s)
The velocity of the detected object towards the sensor.
Methods
Dunder methods
carla.RadarMeasurement
Instance Variables
- raw_data (bytes)
The complete information of the carla.RadarDetection the radar has registered.
Methods
Getters
Dunder methods
- _getitem_(self, pos=int)
- _iter_(self)
Iterate over the carla.RadarDetection retrieved as data. - _len_(self)
- _setitem_(self, pos=int, detection=carla.RadarDetection)
- _str_(self)
carla.Rotation
Class that represents a 3D rotation and therefore, an orientation in space. CARLA uses the Unreal Engine coordinates system. This is a Z-up left-handed system.
The constructor method follows a specific order of declaration: (pitch, yaw, roll)
, which corresponds to (Y-rotation,Z-rotation,X-rotation)
.
Unreal Engine's coordinates system.
Instance Variables
- pitch (float – degrees)
Y-axis rotation angle. - yaw (float – degrees)
Z-axis rotation angle. - roll (float – degrees)
X-axis rotation angle.
Methods
- _init_(self, pitch=0.0, yaw=0.0, roll=0.0)
- Parameters:
pitch
(float – degrees) – Y-axis rotation angle.yaw
(float – degrees) – Z-axis rotation angle.roll
(float – degrees) – X-axis rotation angle.
- Warning: The declaration order is different in CARLA
(pitch,yaw,roll)
, and in the Unreal Engine Editor(roll,pitch,yaw)
. When working in a build from source, don't mix up the axes' rotations.
- Parameters:
Getters
- get_forward_vector(self)
Computes the vector pointing forward according to the rotation of the object.- Return: carla.Vector3D
- get_right_vector(self)
Computes the vector pointing to the right according to the rotation of the object.- Return: carla.Vector3D
- get_up_vector(self)
Computes the vector pointing upwards according to the rotation of the object.- Return: carla.Vector3D
Dunder methods
- _eq_(self, other=carla.Rotation)
Returns True if both rotations represent the same orientation for every axis.- Return: bool
- _ne_(self, other=carla.Rotation)
Returns True if both rotations represent the same orientation for every axis.- Return: bool
- _str_(self)
Parses the axis' orientations to string.
carla.RssActorConstellationData
Data structure that is provided within the callback registered by RssSensor.register_actor_constellation_callback().
Instance Variables
- ego_match_object (ad.map.match.Object)
The ego map matched information. - ego_route (ad.map.route.FullRoute)
The ego route. - ego_dynamics_on_route (carla.RssEgoDynamicsOnRoute)
Current ego vehicle dynamics regarding the route. - other_match_object (ad.map.match.Object)
The other object's map matched information. This is only valid if 'other_actor' is not 'None'. - other_actor (carla.Actor)
The other actor. This is 'None' in case of query of default parameters or articial objects of kind ad.rss.world.ObjectType.ArtificialObject with no dedicated 'carla.Actor' (as e.g. for the road boundaries at the moment).
Methods
Dunder methods
carla.RssActorConstellationResult
Data structure that should be returned by the callback registered by RssSensor.register_actor_constellation_callback().
Instance Variables
- rss_calculation_mode (ad.rss.map.RssMode)
The calculation mode to be applied with the actor. - restrict_speed_limit_mode (ad.rss.map.RestrictSpeedLimitMode)
The mode for restricting speed limit. - ego_vehicle_dynamics (ad.rss.world.RssDynamics)
The RSS dynamics to be applied for the ego vehicle. - actor_object_type (ad.rss.world.ObjectType)
The RSS object type to be used for the actor. - actor_dynamics (ad.rss.world.RssDynamics)
The RSS dynamics to be applied for the actor.
Methods
Dunder methods
carla.RssEgoDynamicsOnRoute
Part of the data contained inside a carla.RssResponse describing the state of the vehicle. The parameters include its current dynamics, and how it is heading regarding the target route.
Instance Variables
- ego_speed (ad.physics.Speed)
The ego vehicle's speed. - min_stopping_distance (ad.physics.Distance)
The current minimum stopping distance. - ego_center (ad.map.point.ENUPoint)
The considered enu position of the ego vehicle. - ego_heading (ad.map.point.ENUHeading)
The considered heading of the ego vehicle. - ego_center_within_route (bool)
States if the ego vehicle's center is within the route. - crossing_border (bool)
States if the vehicle is already crossing one of the lane borders. - route_heading (ad.map.point.ENUHeading)
The considered heading of the route. - route_nominal_center (ad.map.point.ENUPoint)
The considered nominal center of the current route. - heading_diff (ad.map.point.ENUHeading)
The considered heading diff towards the route. - route_speed_lat (ad.physics.Speed)
The ego vehicle's speed component lat regarding the route. - route_speed_lon (ad.physics.Speed)
The ego vehicle's speed component lon regarding the route. - route_accel_lat (ad.physics.Acceleration)
The ego vehicle's acceleration component lat regarding the route. - route_accel_lon (ad.physics.Acceleration)
The ego vehicle's acceleration component lon regarding the route. - avg_route_accel_lat (ad.physics.Acceleration)
The ego vehicle's acceleration component lat regarding the route smoothened by an average filter. - avg_route_accel_lon (ad.physics.Acceleration)
The ego acceleration component lon regarding the route smoothened by an average filter.
Methods
Dunder methods
carla.RssLogLevel
Enum declaration used in carla.RssSensor to set the log level.
Instance Variables
carla.RssResponse
A carla.RssRestrictor will use the data to modify the carla.VehicleControl of the vehicle.
Instance Variables
- response_valid (bool)
States if the response is valid. It is False if calculations failed or an exception occured. - proper_response (ad.rss.state.ProperResponse)
The proper response that the RSS calculated for the vehicle. - rss_state_snapshot (ad.rss.state.RssStateSnapshot)
Detailed RSS states at the current moment in time. - ego_dynamics_on_route (carla.RssEgoDynamicsOnRoute)
Current ego vehicle dynamics regarding the route. - world_model (ad.rss.world.WorldModel)
World model used for calculations. - situation_snapshot (ad.rss.situation.SituationSnapshot)
Detailed RSS situations extracted from the world model.
Methods
Dunder methods
carla.RssRestrictor
These objects apply restrictions to a carla.VehicleControl. It is part of the CARLA implementation of the C++ Library for Responsibility Sensitive Safety. This class works hand in hand with a rss sensor, which provides the data of the restrictions to be applied.
Methods
- restrict_vehicle_control(self, vehicle_control, proper_response, ego_dynamics_on_route, vehicle_physics)
Applies the safety restrictions given by a carla.RssSensor to a carla.VehicleControl.- Parameters:
vehicle_control
(carla.VehicleControl) – The input vehicle control to be restricted.proper_response
(ad.rss.state.ProperResponse) – Part of the response generated by the sensor. Contains restrictions to be applied to the acceleration of the vehicle.ego_dynamics_on_route
(carla.RssEgoDynamicsOnRoute) – Part of the response generated by the sensor. Contains dynamics and heading of the vehicle regarding its route.vehicle_physics
(carla.VehiclePhysicsControl) – The current physics of the vehicle. Used to apply the restrictions properly.
- Return: carla.VehicleControl
- Parameters:
carla.RssRoadBoundariesMode
Enum declaration used in carla.RssSensor to enable or disable the stay on road feature. In summary, this feature considers the road boundaries as virtual objects. The minimum safety distance check is applied to these virtual walls, in order to make sure the vehicle does not drive off the road.
Instance Variables
carla.RssSensor
The RSS sensor uses world information, and a RSS library to make safety checks on a vehicle. The output retrieved by the sensor is a carla.RssResponse. This will be used by a carla.RssRestrictor to modify a carla.VehicleControl before applying it to a vehicle.
Instance Variables
- ego_vehicle_dynamics (ad.rss.world.RssDynamics)
States the RSS parameters that the sensor will consider for the ego vehicle if no actor constellation callback is registered. - other_vehicle_dynamics (ad.rss.world.RssDynamics)
States the RSS parameters that the sensor will consider for the rest of vehicles if no actor constellation callback is registered. - pedestrian_dynamics (ad.rss.world.RssDynamics)
States the RSS parameters that the sensor will consider for pedestrians if no actor constellation callback is registered. - road_boundaries_mode (carla.RssRoadBoundariesMode)
Switches the stay on road feature. By default is Off. - routing_targets (vector<carla.Transform>)
The current list of targets considered to route the vehicle. If no routing targets are defined, a route is generated at random.
Methods
- append_routing_target(self, routing_target)
Appends a new target position to the current route of the vehicle.- Parameters:
routing_target
(carla.Transform) – New target point for the route. Choose these after the intersections to force the route to take the desired turn.
- Parameters:
- drop_route(self)
Discards the current route. If there are targets remaining in routing_targets, creates a new route using those. Otherwise, a new route is created at random. - register_actor_constellation_callback(self, callback)
Register a callback to customize a carla.RssActorConstellationResult. By this callback the settings of RSS parameters are done per actor constellation and the settings (ego_vehicle_dynamics, other_vehicle_dynamics and pedestrian_dynamics) have no effect.- Parameters:
callback
– The function to be called whenever a RSS situation is about to be calculated.
- Parameters:
- reset_routing_targets(self)
Erases the targets that have been appended to the route.
Setters
- set_log_level(self, log_level)
Sets the log level.- Parameters:
log_level
(carla.RssLogLevel) – New log level.
- Parameters:
- set_map_log_level(self, log_level)
Sets the map log level.- Parameters:
log_level
(carla.RssLogLevel) – New map log level.
- Parameters:
Dunder methods
carla.SemanticLidarDetection
Data contained inside a carla.SemanticLidarMeasurement. Each of these represents one of the points in the cloud with its location, the cosine of the incident angle, index of the object hit, and its semantic tag.
Instance Variables
- point (carla.Location – meters)
[x,y,z] coordinates of the point. - cos_inc_angle (float)
Cosine of the incident angle between the ray, and the normal of the hit object. - object_idx (uint)
ID of the actor hit by the ray. - object_tag (uint)
Semantic tag of the component hit by the ray.
Methods
Dunder methods
carla.SemanticLidarMeasurement
Instance Variables
- channels (int)
Number of lasers shot. - horizontal_angle (float – radians)
Horizontal angle the LIDAR is rotated at the time of the measurement. - raw_data (bytes)
Received list of raw detection points. Each point consists of [x,y,z] coordinates plus the cosine of the incident angle, the index of the hit actor, and its semantic tag.
Methods
- save_to_disk(self, path)
Saves the point cloud to disk as a .ply file describing data from 3D scanners. The files generated are ready to be used within MeshLab, an open-source system for processing said files. Just take into account that axis may differ from Unreal Engine and so, need to be reallocated.- Parameters:
path
(str)
- Parameters:
Getters
- get_point_count(self, channel)
Retrieves the number of points sorted by channel that are generated by this measure. Sorting by channel allows to identify the original channel for every point.- Parameters:
channel
(int)
- Parameters:
Dunder methods
- _getitem_(self, pos=int)
- _iter_(self)
Iterate over the carla.SemanticLidarDetection retrieved as data. - _len_(self)
- _setitem_(self, pos=int, detection=carla.SemanticLidarDetection)
- _str_(self)
carla.Sensor
Most sensors can be divided in two groups: those receiving data on every tick (cameras, point clouds and some specific sensors) and those who only receive under certain circumstances (trigger detectors). CARLA provides a specific set of sensors and their blueprint can be found in carla.BlueprintLibrary. All the information on their preferences and settlement can be found here, but the list of those available in CARLA so far goes as follow.
Receive data on every tick.
- Depth camera.
- Gnss sensor.
- IMU sensor.
- Lidar raycast.
- SemanticLidar raycast.
- Radar.
- RGB camera.
- RSS sensor.
- Semantic Segmentation camera.
Only receive data when triggered. - Collision detector.
- Lane invasion detector.
- Obstacle detector.
Instance Variables
Methods
- listen(self, callback)snippet →
The function the sensor will be calling to every time a new measurement is received. This function needs for an argument containing an object type carla.SensorData to work with.- Parameters:
callback
(function) – The called function with one argument containing the sensor data.
- Parameters:
- stop(self)
Commands the sensor to stop listening for data.
Dunder methods
carla.SensorData
Base class for all the objects containing data generated by a carla.Sensor. This objects should be the argument of the function said sensor is listening to, in order to work with them. Each of these sensors needs for a specific type of sensor data. Hereunder is a list of the sensors and their corresponding data.
- Cameras (RGB, depth and semantic segmentation): carla.Image.
- Collision detector: carla.CollisionEvent.
- GNSS sensor: carla.GnssMeasurement.
- IMU sensor: carla.IMUMeasurement.
- Lane invasion detector: carla.LaneInvasionEvent.
- LIDAR sensor: carla.LidarMeasurement.
- Obstacle detector: carla.ObstacleDetectionEvent.
- Radar sensor: carla.RadarMeasurement.
- RSS sensor: carla.RssResponse.
- Semantic LIDAR sensor: carla.SemanticLidarMeasurement.
Instance Variables
- frame (int)
Frame count when the data was generated. - timestamp (float – seconds)
Simulation-time when the data was generated. - transform (carla.Transform)
Sensor's transform when the data was generated.
carla.Timestamp
Class that contains time information for simulated data. This information is automatically retrieved as part of the carla.WorldSnapshot the client gets on every frame, but might also be used in many other situations such as a carla.Sensor retrieveing data.
Instance Variables
- frame (int)
The number of frames elapsed since the simulator was launched. - elapsed_seconds (float – seconds)
Simulated seconds elapsed since the beginning of the current episode. - delta_seconds (float – seconds)
Simulated seconds elapsed since the previous frame. - platform_timestamp (float – seconds)
Time register of the frame at which this measurement was taken given by the OS in seconds.
Methods
- _init_(self, frame, elapsed_seconds, delta_seconds, platform_timestamp)
- Parameters:
frame
(int)elapsed_seconds
(float – seconds)delta_seconds
(float – seconds)platform_timestamp
(float – seconds)
- Parameters:
Dunder methods
- _eq_(self, other=carla.Timestamp)
- _ne_(self, other=carla.Timestamp)
- _str_(self)
carla.TrafficLight
Within a group the state of traffic lights is changed in a cyclic pattern: one index is chosen and it spends a few seconds in green, yellow and eventually red. The rest of the traffic lights remain frozen in red this whole time, meaning that there is a gap in the last seconds of the cycle where all the traffic lights are red. However, the state of a traffic light can be changed manually.
Instance Variables
- state (carla.TrafficLightState)
Current state of the traffic light.
Methods
- freeze(self, freeze)
Stops all the traffic lights in the scene at their current state.- Parameters:
freeze
(bool)
- Parameters:
- is_frozen(self)
The client returns True if a traffic light is frozen according to last tick. The method does not call the simulator.- Return: bool
- reset_group(self)
Resets the state of the traffic lights of the group to the initial state at the start of the simulation.- Note: _This method calls the simulator. _
Getters
- get_elapsed_time(self)
The client returns the time in seconds since current light state started according to last tick. The method does not call the simulator.- Return: float – seconds
- get_green_time(self)
The client returns the time set for the traffic light to be green, according to last tick. The method does not call the simulator.- Return: float – seconds
- Setter: carla.TrafficLight.set_green_time
- get_group_traffic_lights(self)
Returns all traffic lights in the group this one belongs to.- Return: list(carla.TrafficLight)
- Note: _This method calls the simulator. _
- get_pole_index(self)
Returns the index of the pole that identifies it as part of the traffic light group of a junction.- Return: int
- get_red_time(self)
The client returns the time set for the traffic light to be red, according to last tick. The method does not call the simulator.- Return: float – seconds
- Setter: carla.TrafficLight.set_red_time
- get_state(self)
The client returns the state of the traffic light according to last tick. The method does not call the simulator.- Return: carla.TrafficLightState
- Setter: carla.TrafficLight.set_state
- get_yellow_time(self)
The client returns the time set for the traffic light to be yellow, according to last tick. The method does not call the simulator.- Return: float – seconds
- Setter: carla.TrafficLight.set_yellow_time
Setters
- set_green_time(self, green_time)
- Parameters:
green_time
(float – seconds) – Sets a given time for the green light to be active.
- Getter: carla.TrafficLight.get_green_time
- Parameters:
- set_red_time(self, red_time)
Sets a given time for the red state to be active.- Parameters:
red_time
(float – seconds)
- Getter: carla.TrafficLight.get_red_time
- Parameters:
- set_state(self, state)snippet →
Sets a given state to a traffic light actor.- Parameters:
state
(carla.TrafficLightState)
- Getter: carla.TrafficLight.get_state
- Parameters:
- set_yellow_time(self, yellow_time)
Sets a given time for the yellow light to be active.- Parameters:
yellow_time
(float – seconds)
- Getter: carla.TrafficLight.get_yellow_time
- Parameters:
Dunder methods
carla.TrafficLightState
All possible states for traffic lights. These can either change at a specific time step or be changed manually. The snipet in carla.TrafficLight.set_state changes the state of a traffic light on the fly.
Instance Variables
carla.TrafficManager
The traffic manager is a module built on top of the CARLA API in C++. It handles any group of vehicles set to autopilot mode to populate the simulation with realistic urban traffic conditions and give the chance to user to customize some behaviours. The architecture of the traffic manager is divided in five different goal-oriented stages and a PID controller where the information flows until eventually, a carla.VehicleControl is applied to every vehicle registered in a traffic manager. In order to learn more, visit the documentation regarding this module.
Methods
- auto_lane_change(self, actor, enable)
Turns on or off lane changing behaviour for a vehicle.- Parameters:
actor
(carla.Actor) – The vehicle whose settings are changed.enable
(bool) – True is default and enables lane changes. False will disable them.
- Parameters:
- collision_detection(self, reference_actor, other_actor, detect_collision)
Tunes on/off collisions between a vehicle and another specific actor. In order to ignore all other vehicles, traffic lights or walkers, use the specific ignore methods described in this same section.- Parameters:
reference_actor
(carla.Actor) – Vehicle that is going to ignore collisions.other_actor
(carla.Actor) – The actor thatreference_actor
is going to ignore collisions with.detect_collision
(bool) – True is default and enables collisions. False will disable them.
- Parameters:
- distance_to_leading_vehicle(self, actor, distance)
Sets the minimum distance in meters that a vehicle has to keep with the others. The distance is in meters and will affect the minimum moving distance. It is computed from front to back of the vehicle objects.- Parameters:
actor
(carla.Actor) – Vehicle whose minimum distance is being changed.distance
(float – meters) – Meters between both vehicles.
- Parameters:
- force_lane_change(self, actor, direction)
Forces a vehicle to change either to the lane on its left or right, if existing, as indicated indirection
. This method applies the lane change no matter what, disregarding possible collisions.- Parameters:
actor
(carla.Actor) – Vehicle being forced to change lanes.direction
(bool) – Destination lane. True is the one on the right and False is the left one.
- Parameters:
- global_percentage_speed_difference(self, percentage)
Sets the difference the vehicle's intended speed and its current speed limit. Speed limits can be exceeded by setting theperc
to a negative value. Default is 30. Exceeding a speed limit can be done using negative percentages.- Parameters:
percentage
(float) – Percentage difference between intended speed and the current limit.
- Parameters:
- ignore_lights_percentage(self, actor, perc)
During the traffic light stage, which runs every frame, this method sets the percent chance that traffic lights will be ignored for a vehicle.- Parameters:
actor
(carla.Actor) – The actor that is going to ignore traffic lights.perc
(float) – Between 0 and 100. Amount of times traffic lights will be ignored.
- Parameters:
- ignore_signs_percentage(self, actor, perc)
During the traffic light stage, which runs every frame, this method sets the percent chance that stop signs will be ignored for a vehicle.- Parameters:
actor
(carla.Actor) – The actor that is going to ignore stop signs.perc
(float) – Between 0 and 100. Amount of times stop signs will be ignored.
- Parameters:
- ignore_vehicles_percentage(self, actor, perc)
During the collision detection stage, which runs every frame, this method sets a percent chance that collisions with another vehicle will be ignored for a vehicle.- Parameters:
actor
(carla.Actor) – The vehicle that is going to ignore other vehicles.perc
(float) – Between 0 and 100. Amount of times collisions will be ignored.
- Parameters:
- ignore_walkers_percentage(self, actor, perc)
During the collision detection stage, which runs every frame, this method sets a percent chance that collisions with walkers will be ignored for a vehicle.- Parameters:
actor
(carla.Actor) – The vehicle that is going to ignore walkers on scene.perc
(float) – Between 0 and 100. Amount of times collisions will be ignored.
- Parameters:
- vehicle_percentage_speed_difference(self, actor, percentage)
Sets the difference the vehicle's intended speed and its current speed limit. Speed limits can be exceeded by setting theperc
to a negative value. Default is 30. Exceeding a speed limit can be done using negative percentages.- Parameters:
actor
(carla.Actor) – Vehicle whose speed behaviour is being changed.percentage
(float) – Percentage difference between intended speed and the current limit.
- Parameters:
Getters
- get_port(self)
Returns the port where the Traffic Manager is connected. If the object is a TM-Client, it will return the port of its TM-Server. Read the documentation to learn the difference.- Return: uint16
Setters
- set_global_distance_to_leading_vehicle(self, distance)
Sets the minimum distance in meters that vehicles have to keep with the rest. The distance is in meters and will affect the minimum moving distance. It is computed from center to center of the vehicle objects.- Parameters:
distance
(float – meters) – Meters between vehicles.
- Parameters:
- set_hybrid_physics_mode(self, enabled=False)
Enables or disables the hybrid physics mode. In this mode, vehicle's farther than a certain radius from the ego vehicle will have their physics disabled. Computation cost will be reduced by not calculating vehicle dynamics. Vehicles will be teleported.- Parameters:
enabled
(bool) – If True, enables the hybrid physics.
- Parameters:
- set_hybrid_physics_radius(self, r=50.0)
With hybrid physics on, changes the radius of the area of influence where physics are enabled.- Parameters:
r
(float – meters) – New radius where physics are enabled.
- Parameters:
- set_osm_mode(self, mode_switch=True)
Enables or disables the OSM mode. This mode allows the user to run TM in a map created with the OSM feature. These maps allow having dead-end streets. Normally, if vehicles cannot find the next waypoint, TM crashes. If OSM mode is enabled, it will show a warning, and destroy vehicles when necessary.- Parameters:
mode_switch
(bool) – If True, the OSM mode is enabled.
- Parameters:
- set_percentage_keep_right_rule(self, actor, perc)
During the localization stage, this method sets a percent chance that vehicle will follow the keep right rule, and stay in the right lane.- Parameters:
actor
(carla.Actor) – Vehicle whose behaviour is being changed.perc
(float) – Between 0 and 100. Amount of times the vehicle will follow the keep right rule.
- Parameters:
- set_random_device_seed(self, value)
Sets a specific random seed for the Traffic Manager, thereby setting it to be deterministic.- Parameters:
value
(int) – Seed value for the random number generation of the Traffic Manager.
- Parameters:
- set_synchronous_mode(self, mode_switch=True)
Sets the Traffic Manager to synchronous mode. In a multiclient situation, only the TM-Server can tick. Similarly, in a multiTM situation, only one TM-Server must tick. Use this method in the client that does the world tick, and right after setting the world to synchronous mode, to set which TM will be the master while in sync.- Parameters:
mode_switch
(bool) – If True, the TM synchronous mode is enabled.
- Warning: _If the server is set to synchronous mode, the TM must be set to synchronous mode too in the same client that does the tick. _
- Parameters:
carla.TrafficSign
Instance Variables
- trigger_volume
A carla.BoundingBox situated near a traffic sign where the carla.Actor who is inside can know about it.
carla.Transform
Class that defines a transformation, a combination of location and rotation, without scaling.
Instance Variables
- location (carla.Location)
Describes a point in the coordinate system. - rotation (carla.Rotation – degrees (pitch, yaw, roll))
Describes a rotation for an object according to Unreal Engine's axis system.
Methods
- _init_(self, location, rotation)
- Parameters:
location
(carla.Location)rotation
(carla.Rotation – degrees (pitch, yaw, roll))
- Parameters:
- transform(self, in_point)
Translates a 3D point from local to global coordinates using the current transformation as frame of reference.- Parameters:
in_point
(carla.Location) – Location in the space to which the transformation will be applied.
- Parameters:
Getters
- get_forward_vector(self)
Computes a forward vector using the rotation of the object.- Return: carla.Vector3D
- get_inverse_matrix(self)
Computes the 4-matrix representation of the inverse transformation.- Return: list(list(float))
- get_matrix(self)
Computes the 4-matrix representation of the transformation.- Return: list(list(float))
- get_right_vector(self)
Computes a right vector using the rotatio of the object.- Return: carla.Vector3D
- get_up_vector(self)
Computes an up vector using the rotation of the object.- Return: carla.Vector3D
Dunder methods
- _eq_(self, other=carla.Transform)
Returns True if both location and rotation are equal for this andother
.- Return: bool
- _ne_(self, other=carla.Transform)
Returns True if any location and rotation are not equal for this andother
.- Return: bool
- _str_(self)
Parses both location and rotation to string.- Return: str
carla.Vector2D
Helper class to perform 2D operations.
Instance Variables
Methods
Dunder methods
- _add_(self, other=carla.Vector2D)
- _eq_(self, other=carla.Vector2D)
Returns True if values for every axis are equal.- Return: bool
- _mul_(self, other=carla.Vector2D)
- _ne_(self, bool=carla.Vector2D)
Returns True if the value for any axis is different.- Return: bool
- _str_(self)
Returns the axis values for the vector parsed as string.- Return: str
- _sub_(self, other=carla.Vector2D)
- _truediv_(self, other=carla.Vector2D)
carla.Vector3D
Helper class to perform 3D operations.
Instance Variables
Methods
Dunder methods
- _add_(self, other=carla.Vector3D)
- _eq_(self, other=carla.Vector3D)
Returns True if values for every axis are equal.- Return: bool
- _mul_(self, other=carla.Vector3D)
- _ne_(self, other=carla.Vector3D)
Returns True if the value for any axis is different.- Return: bool
- _str_(self)
Returns the axis values for the vector parsed as string.- Return: str
- _sub_(self, other=carla.Vector3D)
- _truediv_(self, other=carla.Vector3D)
carla.Vehicle
Instance Variables
- bounding_box (carla.BoundingBox)
Bounding box containing the geometry of the vehicle. Its location and rotation are relative to the vehicle it is attached to.
Methods
- apply_control(self, control)
Applies a control object on the next tick, containing driving parameters such as throttle, steering or gear shifting.- Parameters:
control
(carla.VehicleControl)
- Parameters:
- apply_physics_control(self, physics_control)
Applies a physics control object in the next tick containing the parameters that define the vehicle as a corporeal body. E.g.: moment of inertia, mass, drag coefficient and many more.- Parameters:
physics_control
(carla.VehiclePhysicsControl)
- Parameters:
- enable_carsim(self, simfile_path)
Enables the CarSim physics solver for this particular vehicle. In order for this function to work, there needs to be a valid license manager running on the server side. The control inputs are redirected to CarSim which will provide the position and orientation of the vehicle for every frame.- Parameters:
simfile_path
(str) – Path to the.simfile
file with the parameters of the simulation.
- Parameters:
- is_at_traffic_light(self)
Vehicles will be affected by a traffic light when the light is red and the vehicle is inside its bounding box. The client returns whether a traffic light is affecting this vehicle according to last tick (it does not call the simulator).- Return: bool
- use_carsim_road(self, enabled)
Enables or disables the usage of CarSim vs terrain file specified in the.simfile
. By default this option is disabled and CarSim uses unreal engine methods to process the geometry of the scene.- Parameters:
enabled
(bool)
- Parameters:
Getters
- get_control(self)
The client returns the control applied in the last tick. The method does not call the simulator.- Return: carla.VehicleControl
- get_light_state(self)
Returns a flag representing the vehicle light state, this represents which lights are active or not.- Return: carla.VehicleLightState
- Setter: carla.Vehicle.set_light_state
- get_physics_control(self)
The simulator returns the last physics control applied to this vehicle.- Return: carla.VehiclePhysicsControl
- Warning: This method does call the simulator to retrieve the value.
- get_speed_limit(self)
The client returns the speed limit affecting this vehicle according to last tick (it does not call the simulator). The speed limit is updated when passing by a speed limit signal, so a vehicle might have none right after spawning.- Return: float – m/s
- get_traffic_light(self)
Retrieves the traffic light actor affecting this vehicle (if any) according to last tick. The method does not call the simulator.- Return: carla.TrafficLight
- get_traffic_light_state(self)
The client returns the state of the traffic light affecting this vehicle according to last tick. The method does not call the simulator. If no traffic light is currently affecting the vehicle, returns green.- Return: carla.TrafficLightState
- get_wheel_steer_angle(self, wheel_location)
Returns the physics angle in degrees of a vehicle's wheel.- Parameters:
wheel_location
(carla.VehicleWheelLocation)
- Return: float
- Note: _Returns the angle based on the physics of the wheel, not the visual angle. _
- Parameters:
Setters
- set_autopilot(self, enabled=True, port=8000)
Registers or deletes the vehicle from a Traffic Manager's list. When True, the Traffic Manager passed as parameter will move the vehicle around. The autopilot takes place client-side.- Parameters:
enabled
(bool)port
(uint16) – The port of the TM-Server where the vehicle is to be registered or unlisted. If None is passed, it will consider a TM at default port8000
.
- Parameters:
- set_light_state(self, light_state)
Sets the light state of a vehicle using a flag that represents the lights that are on and off.- Parameters:
light_state
(carla.VehicleLightState)
- Getter: carla.Vehicle.get_light_state
- Parameters:
- set_wheel_steer_direction(self, wheel_location, angle_in_deg)snippet →
Sets the angle of a vehicle's wheel visually.- Parameters:
wheel_location
(carla.VehicleWheelLocation)angle_in_deg
(float)
- Warning: _Does not affect the physics of the vehicle. _
- Parameters:
Dunder methods
carla.VehicleControl
Manages the basic movement of a vehicle using typical driving controls.
Instance Variables
- throttle (float)
A scalar value to control the vehicle throttle [0.0, 1.0]. Default is 0.0. - steer (float)
A scalar value to control the vehicle steering [-1.0, 1.0]. Default is 0.0. - brake (float)
A scalar value to control the vehicle brake [0.0, 1.0]. Default is 0.0. - hand_brake (bool)
Determines whether hand brake will be used. Default is False. - reverse (bool)
Determines whether the vehicle will move backwards. Default is False. - manual_gear_shift (bool)
Determines whether the vehicle will be controlled by changing gears manually. Default is False. - gear (int)
States which gear is the vehicle running on.
Methods
- _init_(self, throttle=0.0, steer=0.0, brake=0.0, hand_brake=False, reverse=False, manual_gear_shift=False, gear=0)
- Parameters:
throttle
(float) – Scalar value between [0.0,1.0].steer
(float) – Scalar value between [0.0,1.0].brake
(float) – Scalar value between [0.0,1.0].hand_brake
(bool)reverse
(bool)manual_gear_shift
(bool)gear
(int)
- Parameters:
Dunder methods
- _eq_(self, other=carla.VehicleControl)
- _ne_(self, other=carla.VehicleControl)
- _str_(self)
carla.VehicleLightState
Class that recaps the state of the lights of a vehicle, these can be used as a flags. E.g: VehicleLightState.HighBeam & VehicleLightState.Brake
will return True
when both are active. Lights are off by default in any situation and should be managed by the user via script. The blinkers blink automatically. Warning: Right now, not all vehicles have been prepared to work with this functionality, this will be added to all of them in later updates.
Instance Variables
- NONE
All lights off. - Position
- LowBeam
- HighBeam
- Brake
- RightBlinker
- LeftBlinker
- Reverse
- Fog
- Interior
- Special1
This is reserved for certain vehicles that can have special lights, like a siren. - Special2
This is reserved for certain vehicles that can have special lights, like a siren. - All
All lights on.
carla.VehiclePhysicsControl
Summarizes the parameters that will be used to simulate a carla.Vehicle as a physical object. The specific settings for the wheels though are stipulated using carla.WheelPhysicsControl.
Instance Variables
- torque_curve (list(carla.Vector2D))
Curve that indicates the torque measured in Nm for a specific RPM of the vehicle's engine. - max_rpm (float)
The maximum RPM of the vehicle's engine. - moi (float – kg*m2)
The moment of inertia of the vehicle's engine. - damping_rate_full_throttle (float)
Damping ratio when the throttle is maximum. - damping_rate_zero_throttle_clutch_engaged (float)
Damping ratio when the throttle is zero with clutch engaged. - damping_rate_zero_throttle_clutch_disengaged (float)
Damping ratio when the throttle is zero with clutch disengaged. - use_gear_autobox (bool)
If True, the vehicle will have an automatic transmission. - gear_switch_time (float – seconds)
Switching time between gears. - clutch_strength (float – kg*m2/s)
Clutch strength of the vehicle. - final_ratio (float)
Fixed ratio from transmission to wheels. - forward_gears (list(carla.GearPhysicsControl))
List of objects defining the vehicle's gears. - mass (float – kilograms)
Mass of the vehicle. - drag_coefficient (float)
Drag coefficient of the vehicle's chassis. - center_of_mass (carla.Vector3D – meters)
Center of mass of the vehicle. - steering_curve (list(carla.Vector2D))
Curve that indicates the maximum steering for a specific forward speed. - use_sweep_wheel_collision (bool)
Enable the use of sweep for wheel collision. By default, it is disabled and it uses a simple raycast from the axis to the floor for each wheel. This option provides a better collision model in which the full volume of the wheel is checked against collisions. - wheels (list(carla.WheelPhysicsControl))
List of wheel physics objects. This list should have 4 elements, where index 0 corresponds to the front left wheel, index 1 corresponds to the front right wheel, index 2 corresponds to the back left wheel and index 3 corresponds to the back right wheel. For 2 wheeled vehicles, set the same values for both front and back wheels.
Methods
- _init_(self, torque_curve=0.0, 500.0], [5000.0, 500.0, max_rpm=5000.0, moi=1.0, damping_rate_full_throttle=0.15, damping_rate_zero_throttle_clutch_engaged=2.0, damping_rate_zero_throttle_clutch_disengaged=0.35, use_gear_autobox=True, gear_switch_time=0.5, clutch_strength=10.0, final_ratio=4.0, forward_gears=list(), mass=1000.0, drag_coefficient=0.3, center_of_mass=[0.0, 0.0, 0.0], steering_curve=0.0, 1.0], [10.0, 0.5, wheels=list())
VehiclePhysicsControl constructor.- Parameters:
torque_curve
(list(carla.Vector2D))max_rpm
(float)moi
(float – kg*m2)damping_rate_full_throttle
(float)damping_rate_zero_throttle_clutch_engaged
(float)damping_rate_zero_throttle_clutch_disengaged
(float)use_gear_autobox
(bool)gear_switch_time
(float – seconds)clutch_strength
(float – kg*m2/s)final_ratio
(float)forward_gears
(list(carla.GearPhysicsControl))drag_coefficient
(float)center_of_mass
(carla.Vector3D)steering_curve
(carla.Vector2D)wheels
(list(carla.WheelPhysicsControl))
- Parameters:
Dunder methods
- _eq_(self, other=carla.VehiclePhysicsControl)
- _ne_(self, other=carla.VehiclePhysicsControl)
- _str_(self)
carla.VehicleWheelLocation
enum
representing the position of each wheel on a vehicle. Used to identify the target wheel when setting an angle in carla.Vehicle.set_wheel_steer_direction or carla.Vehicle.get_wheel_steer_angle.
Instance Variables
- FL_Wheel
Front left wheel of a 4 wheeled vehicle. - FR_Wheel
Front right wheel of a 4 wheeled vehicle. - BL_Wheel
Back left wheel of a 4 wheeled vehicle. - BR_Wheel
Back right wheel of a 4 wheeled vehicle. - Front_Wheel
Front wheel of a 2 wheeled vehicle. - Back_Wheel
Back wheel of a 2 wheeled vehicle.
carla.Walker
Instance Variables
- bounding_box (carla.BoundingBox)
Bounding box containing the geometry of the walker. Its location and rotation are relative to the walker it is attached to.
Methods
- apply_control(self, control)
On the next tick, the control will move the walker in a certain direction with a certain speed. Jumps can be commanded too.- Parameters:
control
(carla.WalkerControl)
- Parameters:
- apply_control(self, control)
On the next tick, the control defines a list of bone transformations that will be applied to the walker's skeleton.- Parameters:
control
(carla.WalkerBoneControl)
- Parameters:
Getters
- get_control(self)
The client returns the control applied to this walker during last tick. The method does not call the simulator.- Return: carla.WalkerControl
Dunder methods
carla.WalkerAIController
Methods
- go_to_location(self, destination)
Sets the destination that the pedestrian will reach.- Parameters:
destination
(carla.Location – meters)
- Parameters:
- start(self)
Enables AI control for its parent walker. - stop(self)snippet →
Disables AI control for its parent walker.
Setters
- set_max_speed(self, speed=1.4)
Sets a speed for the walker in meters per second.- Parameters:
speed
(float – m/s) – An easy walking speed is set by default.
- Parameters:
Dunder methods
carla.WalkerBoneControl
This class grants bone specific manipulation for walker. The skeletons of walkers have been unified for clarity and the transform applied to each bone are always relative to its parent. Take a look here to learn more on how to create a walker and define its movement.
Instance Variables
- bone_transforms (list([name,transform]))
List of tuples where the first value is the bone's name and the second value stores the transformation (changes in location and rotation) that will be applied to it.
Methods
- _init_(self, list(name,transform))
Initializes an object containing moves to be applied on tick. These are listed with the name of the bone and the transform that will be applied to it.- Parameters:
list(name,transform)
(tuple)
- Parameters:
Dunder methods
carla.WalkerControl
This class defines specific directions that can be commanded to a carla.Walker to control it via script. The walker's animations will blend automatically with the parameters defined in this class when applied, though specific skeleton moves can be obtained through class.WalkerBoneControl.
AI control can be settled for walkers, but the control used to do so is carla.WalkerAIController.
Instance Variables
- direction (carla.Vector3D)
Vector using global coordinates that will correspond to the direction of the walker. - speed (float – m/s)
A scalar value to control the walker's speed. - jump (bool)
If True, the walker will perform a jump.
Methods
- _init_(self, direction=[1.0, 0.0, 0.0], speed=0.0, jump=False)
- Parameters:
direction
(carla.Vector3D)speed
(float – m/s)jump
(bool)
- Parameters:
Dunder methods
- _eq_(self, other=carla.WalkerControl)
Compares every variable withother
and returns True if these are all the same. - _ne_(self, other=carla.WalkerControl)
Compares every variable withother
and returns True if any of these differ. - _str_(self)
carla.Waypoint
Waypoints in CARLA are described as 3D directed points. They have a carla.Transform which locates the waypoint in a road and orientates it according to the lane. They also store the road information belonging to said point regarding its lane and lane markings.
All the information regarding waypoints and the waypoint API is retrieved as provided by the OpenDRIVE file. Once the client asks for the map object to the server, no longer communication will be needed.
Instance Variables
- id (int)
The identificator is generated using a hash combination of the road, section, lane and s values that correspond to said point in the OpenDRIVE geometry. The s precision is set to 2 centimeters, so 2 waypoints closer than 2 centimeters in the same road, section and lane, will have the same identificator. - transform (carla.Transform)
Position and orientation of the waypoint according to the current lane information. This data is computed the first time it is accessed. It is not created right away in order to ease computing costs when lots of waypoints are created but their specific transform is not needed. - road_id (int)
OpenDRIVE road's id. - section_id (int)
OpenDRIVE section's id, based on the order that they are originally defined. - lane_id (int)
OpenDRIVE lane's id, this value can be positive or negative which represents the direction of the current lane with respect to the road. For more information refer to OpenDRIVE documentation. - s (float)
OpenDRIVE s value of the current position. - is_junction (bool)
True if the current Waypoint is on a junction as defined by OpenDRIVE. - lane_width (float)
Horizontal size of the road at current s. - lane_change (carla.LaneChange)
Lane change definition of the current Waypoint's location, based on the traffic rules defined in the OpenDRIVE file. It states if a lane change can be done and in which direction. - lane_type (carla.LaneType)
The lane type of the current Waypoint, based on OpenDRIVE 1.4 standard. - right_lane_marking (carla.LaneMarking)
The right lane marking information based on the direction of the Waypoint. - left_lane_marking (carla.LaneMarking)
The left lane marking information based on the direction of the Waypoint.
Methods
- next(self, distance)
Returns a list of waypoints at a certain approximatedistance
from the current one. It takes into account the road and its possible deviations without performing any lane change and returns one waypoint per option. The list may be empty if the lane is not connected to any other at the specified distance.- Parameters:
distance
(float – meters) – The approximate distance where to get the next waypoints.
- Return: list(carla.Waypoint)
- Parameters:
- next_until_lane_end(self, distance)
Returns a list of waypoints from this to the end of the lane separated by a certaindistance
.- Parameters:
distance
(float – meters) – The approximate distance between waypoints.
- Return: list(carla.Waypoint)
- Parameters:
- previous(self, distance)
This method does not return the waypoint previously visited by an actor, but a list of waypoints at an approximatedistance
but in the opposite direction of the lane. Similarly to next(), it takes into account the road and its possible deviations without performing any lane change and returns one waypoint per option. The list may be empty if the lane is not connected to any other at the specified distance.- Parameters:
distance
(float – meters) – The approximate distance where to get the previous waypoints.
- Return: list(carla.Waypoint)
- Parameters:
- previous_until_lane_start(self, distance)
Returns a list of waypoints from this to the start of the lane separated by a certaindistance
.- Parameters:
distance
(float – meters) – The approximate distance between waypoints.
- Return: list(carla.Waypoint)
- Parameters:
Getters
- get_junction(self)
If the waypoint belongs to a junction this method returns the asociated junction object. Otherwise returns null.- Return: carla.Junction
- get_landmarks(self, distance, stop_at_junction=False)
Returns a list of landmarks in the road from the current waypoint until the specified distance.- Parameters:
distance
(float – meters) – The maximum distance to search for landmarks from the current waypoint.stop_at_junction
(bool) – Enables or disables the landmark search through junctions.
- Return: list(carla.Landmark)
- Parameters:
- get_landmarks_of_type(self, distance, type, stop_at_junction=False)
Returns a list of landmarks in the road of a specified type from the current waypoint until the specified distance.- Parameters:
distance
(float – meters) – The maximum distance to search for landmarks from the current waypoint.type
(str) – The type of landmarks to search.stop_at_junction
(bool) – Enables or disables the landmark search through junctions.
- Return: list(carla.Landmark)
- Parameters:
- get_left_lane(self)
Generates a Waypoint at the center of the left lane based on the direction of the current Waypoint, taking into account if the lane change is allowed in this location. Will return None if the lane does not exist.- Return: carla.Waypoint
- get_right_lane(self)
Generates a waypoint at the center of the right lane based on the direction of the current waypoint, taking into account if the lane change is allowed in this location. Will return None if the lane does not exist.- Return: carla.Waypoint
Dunder methods
carla.WeatherParameters
This class defines objects containing lighting and weather specifications that can later be applied in carla.World. So far, these conditions only intervene with sensor.camera.rgb. They neither affect the actor's physics nor other sensors.
Each of these parameters acts indepently from the rest. Increasing the rainfall will not automatically create puddles nor change the road's humidity. That makes for a better customization but means that realistic conditions need to be scripted. However an example of dynamic weather conditions working realistically can be found here.
Instance Variables
- cloudiness (float)
Values range from 0 to 100, being 0 a clear sky and 100 one completely covered with clouds. - precipitation (float)
Rain intensity values range from 0 to 100, being 0 none at all and 100 a heavy rain. - precipitation_deposits (float)
Determines the creation of puddles. Values range from 0 to 100, being 0 none at all and 100 a road completely capped with water. Puddles are created with static noise, meaning that they will always appear at the same locations. - wind_intensity (float)
Controls the strenght of the wind with values from 0, no wind at all, to 100, a strong wind. The wind does affect rain direction and leaves from trees, so this value is restricted to avoid animation issues. - sun_azimuth_angle (float – degrees)
The azimuth angle of the sun. Values range from 0 to 360. Zero is an origin point in a sphere determined by Unreal Engine. - sun_altitude_angle (float – degrees)
Altitude angle of the sun. Values range from -90 to 90 corresponding to midnight and midday each. - fog_density (float)
Fog concentration or thickness. It only affects the RGB camera sensor. Values range from 0 to 100. - fog_distance (float – meters)
Fog start distance. Values range from 0 to infinite. - wetness (float)
Wetness intensity. It only affects the RGB camera sensor. Values range from 0 to 100. - fog_falloff (float)
Density of the fog (as in specific mass) from 0 to infinity. The bigger the value, the more dense and heavy it will be, and the fog will reach smaller heights. Corresponds to Fog Height Falloff in the UE docs.
If the value is 0, the fog will be lighter than air, and will cover the whole scene.
A value of 1 is approximately as dense as the air, and reaches normal-sized buildings.
For values greater than 5, the air will be so dense that it will be compressed on ground level.
Methods
- _init_(self, cloudiness=0.0, precipitation=0.0, precipitation_deposits=0.0, wind_intensity=0.0, sun_azimuth_angle=0.0, sun_altitude_angle=0.0, fog_density=0.0, fog_distance=0.0, wetness=0.0, fog_falloff=0.2)
Method to initialize an object defining weather conditions. This class has some presets for different noon and sunset conditions listed in a note below.- Parameters:
cloudiness
(float) – 0 is a clear sky, 100 complete overcast.precipitation
(float) – 0 is no rain at all, 100 a heavy rain.precipitation_deposits
(float) – 0 means no puddles on the road, 100 means roads completely capped by rain.wind_intensity
(float) – 0 is calm, 100 a strong wind.sun_azimuth_angle
(float – degrees) – 0 is an arbitrary North, 180 its corresponding South.sun_altitude_angle
(float – degrees) – 90 is midday, -90 is midnight.fog_density
(float) – Concentration or thickness of the fog, from 0 to 100.fog_distance
(float – meters) – Distance where the fog starts in meters.wetness
(float) – Humidity percentages of the road, from 0 to 100.fog_falloff
(float) – Density (specific mass) of the fog, from 0 to infinity.
- Note: _ClearNoon, CloudyNoon, WetNoon, WetCloudyNoon, SoftRainNoon, MidRainyNoon, HardRainNoon, ClearSunset, CloudySunset, WetSunset, WetCloudySunset, SoftRainSunset, MidRainSunset, HardRainSunset. _
- Parameters:
Dunder methods
- _eq_(self, other)
Returns True if both objects' variables are the same.- Return: bool
- _ne_(self, other)
Returns True if both objects' variables are different.- Return: bool
- _str_(self)
carla.WheelPhysicsControl
Class that defines specific physical parameters for wheel objects that will be part of a carla.VehiclePhysicsControl to simulate vehicle it as a material object.
Instance Variables
- tire_friction (float)
A scalar value that indicates the friction of the wheel. - damping_rate (float)
Damping rate of the wheel. - max_steer_angle (float – degrees)
Maximum angle that the wheel can steer. - radius (float – centimeters)
Radius of the wheel. - max_brake_torque (float – N*m)
Maximum brake torque. - max_handbrake_torque (float – N*m)
Maximum handbrake torque. - position (carla.Vector3D)
World position of the wheel. This is a read-only parameter.
Methods
- _init_(self, tire_friction=2.0, damping_rate=0.25, max_steer_angle=70.0, radius=30.0, max_brake_torque=1500.0, max_handbrake_torque=3000.0, position=(0.0,0.0,0.0))
- Parameters:
tire_friction
(float)damping_rate
(float)max_steer_angle
(float – degrees)radius
(float – centimerers)max_brake_torque
(float – N*m)max_handbrake_torque
(float – N*m)position
(carla.Vector3D – meters)
- Parameters:
Dunder methods
- _eq_(self, other=carla.WheelPhysicsControl)
- _ne_(self, other=carla.WheelPhysicsControl)
- _str_(self)
carla.World
World objects are created by the client to have a place for the simulation to happen. The world contains the map we can see, meaning the asset, not the navigation map. Navigation maps are part of the carla.Map class. It also manages the weather and actors present in it. There can only be one world per simulation, but it can be changed anytime.
Instance Variables
- id (int)
The ID of the episode associated with this world. Episodes are different sessions of a simulation. These change everytime a world is disabled or reloaded. Keeping track is useful to avoid possible issues. - debug (carla.DebugHelper)
Responsible for creating different shapes for debugging. Take a look at its class to learn more about it.
Methods
- apply_settings(self, world_settings)
This method applies settings contained in an object to the simulation running and returns the ID of the frame they were implemented.- Parameters:
world_settings
(carla.WorldSettings)
- Return: int
- Warning: _If synchronous mode is enabled, and there is a Traffic Manager running, this must be set to sync mode too. Read this to learn how to do it. _
- Parameters:
- cast_ray(self, initial_location, final_location)
Casts a ray from the specified initial_location to final_location. The function then detects all geometries intersecting the ray and returns a list of carla.LabelledPoint in order.- Parameters:
initial_location
(carla.Location) – The initial position of the ray.final_location
(carla.Location) – The final position of the ray.
- Return: list(carla.LabelledPoint)
- Parameters:
- enable_environment_objects(self, env_objects_ids, enable)snippet →
Enable or disable a set of EnvironmentObject identified by their id. These objects will appear or disappear from the level.- Parameters:
env_objects_ids
(set(int)) – Set of EnvironmentObject ids to change.enable
(bool) – State to be applied to all the EnvironmentObject of the set.
- Parameters:
- freeze_all_traffic_lights(self, frozen)
Freezes or unfreezes all traffic lights in the scene. Frozen traffic lights can be modified by the user but the time will not update them until unfrozen.- Parameters:
frozen
(bool)
- Parameters:
- ground_projection(self, location, search_distance)
Projects the specified point downwards in the scene. The functions casts a ray from location in the direction (0,0,-1) (downwards) and returns a carla.Labelled object with the first geometry this ray intersects (usually the ground). If no geometry is found in the search_distance range the function returnsNone
.- Parameters:
location
(carla.Location) – The point to be projected.search_distance
(float) – The maximum distance to perform the projection.
- Return: carla.LabelledPoint
- Parameters:
- load_map_layer(self, map_layers)snippet →
Loads the selected layers to the level. If the layer is already loaded the call has no effect.- Parameters:
map_layers
(carla.MapLayer) – Mask of level layers to be loaded.
- Warning: This only affects "Opt" maps. The minimum layout includes roads, sidewalks, traffic lights and traffic signs.
- Parameters:
- on_tick(self, callback)
This method is used in asynchronous mode. It starts callbacks from the client for the function defined ascallback
, and returns the ID of the callback. The function will be called everytime the server ticks. It requires a carla.WorldSnapshot as argument, which can be retrieved from wait_for_tick(). Use remove_on_tick() to stop the callbacks.- Parameters:
callback
(carla.WorldSnapshot) – Function with a snapshot as compulsory parameter that will be called when the client receives a tick.
- Return: int
- Parameters:
- project_point(self, location, direction, search_distance)
Projects the specified point to the desired direction in the scene. The functions casts a ray from location in a direction and returns a carla.Labelled object with the first geometry this ray intersects. If no geometry is found in the search_distance range the function returnsNone
.- Parameters:
location
(carla.Location) – The point to be projected.direction
(carla.Vector3D) – The direction of projection.search_distance
(float) – The maximum distance to perform the projection.
- Return: carla.LabelledPoint
- Parameters:
- remove_on_tick(self, callback_id)
Stops the callback forcallback_id
started with on_tick().- Parameters:
callback_id
(callback) – The callback to be removed. The ID is returned when creating the callback.
- Parameters:
- reset_all_traffic_lights(self)
Resets the cycle of all traffic lights in the map to the initial state. - spawn_actor(self, blueprint, transform, attach_to=None, attachment=Rigid)snippet →
The method will create, return and spawn an actor into the world. The actor will need an available blueprint to be created and a transform (location and rotation). It can also be attached to a parent with a certain attachment type.- Parameters:
blueprint
(carla.ActorBlueprint) – The reference from which the actor will be created.transform
(carla.Transform) – Contains the location and orientation the actor will be spawned with.attach_to
(carla.Actor) – The parent object that the spawned actor will follow around.attachment
(carla.AttachmentType) – Determines how fixed and rigorous should be the changes in position according to its parent object.
- Return: carla.Actor
- Parameters:
- tick(self, seconds=10.0)
This method is used in synchronous mode, when the server waits for a client tick before computing the next frame. This method will send the tick, and give way to the server. It returns the ID of the new frame computed by the server.- Parameters:
seconds
(float – seconds) – Maximum time the server should wait for a tick. It is set to10.0
by default.
- Return: int
- Note: _If no tick is received in synchronous mode, the simulation will freeze. Also, if many ticks are received from different clients, there may be synchronization issues. Please read the docs about synchronous mode to learn more.
_
- Parameters:
- try_spawn_actor(self, blueprint, transform, attach_to=None, attachment=Rigid)
Same as spawn_actor() but returns None on failure instead of throwing an exception.- Parameters:
blueprint
(carla.ActorBlueprint) – The reference from which the actor will be created.transform
(carla.Transform) – Contains the location and orientation the actor will be spawned with.attach_to
(carla.Actor) – The parent object that the spawned actor will follow around.attachment
(carla.AttachmentType) – Determines how fixed and rigorous should be the changes in position according to its parent object.
- Return: carla.Actor
- Parameters:
- unload_map_layer(self, map_layers)snippet →
Unloads the selected layers to the level. If the layer is already unloaded the call has no effect.- Parameters:
map_layers
(carla.MapLayer) – Mask of level layers to be unloaded.
- Warning: This only affects "Opt" maps. The minimum layout includes roads, sidewalks, traffic lights and traffic signs.
- Parameters:
- wait_for_tick(self, seconds=10.0)
This method is used in asynchronous mode. It makes the client wait for a server tick. When the next frame is computed, the server will tick and return a snapshot describing the new state of the world.- Parameters:
seconds
(float – seconds) – Maximum time the server should wait for a tick. It is set to10.0
by default.
- Return: carla.WorldSnapshot
- Parameters:
Getters
- get_actor(self, actor_id)
Looks up for an actor by ID and returns None if not found.- Parameters:
actor_id
(int)
- Return: carla.Actor
- Parameters:
- get_actors(self, actor_ids=None)
Retrieves a list of carla.Actor elements, either using a list of IDs provided or just listing everyone on stage. If an ID does not correspond with any actor, it will be excluded from the list returned, meaning that both the list of IDs and the list of actors may have different lengths.- Parameters:
actor_ids
(list) – The IDs of the actors being searched. By default it is set to None and returns every actor on scene.
- Return: carla.ActorList
- Parameters:
- get_blueprint_library(self)
Returns a list of actor blueprints available to ease the spawn of these into the world.- Return: carla.BlueprintLibrary
- get_environment_objects(self, object_type=Any)
Returns a list of EnvironmentObject with the requested semantic tag. The method returns all the EnvironmentObjects in the level by default, but the query can be filtered by semantic tags with the argumentobject_type
.- Parameters:
object_type
(carla.CityObjectLabel) – Semantic tag of the EnvironmentObjects that are returned.
- Return: array(carla.EnvironmentObject)
- Parameters:
- get_level_bbs(self, actor_type=Any)
Returns an array of bounding boxes with location and rotation in world space. The method returns all the bounding boxes in the level by default, but the query can be filtered by semantic tags with the argumentactor_type
.- Parameters:
actor_type
(carla.CityObjectLabel) – Semantic tag of the elements contained in the bounding boxes that are returned.
- Return: array(carla.BoundingBox)
- Parameters:
- get_lightmanager(self)
Returns an instance of carla.LightManager that can be used to handle the lights in the scene.- Return: carla.LightManager
- get_map(self)
Asks the server for the XODR containing the map file, and returns this parsed as a carla.Map.- Return: carla.Map
- Warning: _This method does call the simulation. It is expensive, and should only be called once.
_
- get_random_location_from_navigation(self)
This can only be used with walkers. It retrieves a random location to be used as a destination using the go_to_location() method in carla.WalkerAIController. This location will be part of a sidewalk. Roads, crosswalks and grass zones are excluded. The method does not take into consideration locations of existing actors so if a collision happens when trying to spawn an actor, it will return an error. Take a look atspawn_npc.py
for an example.- Return: carla.Location
- get_settings(self)
Returns an object containing some data about the simulation such as synchrony between client and server or rendering mode.- Return: carla.WorldSettings
- get_snapshot(self)
Returns a snapshot of the world at a certain moment comprising all the information about the actors.- Return: carla.WorldSnapshot
- get_spectator(self)snippet →
Returns the spectator actor. The spectator is a special type of actor created by Unreal Engine, usually with ID=0, that acts as a camera and controls the view in the simulator window.- Return: carla.Actor
- get_traffic_light(self, landmark)
Provided a landmark, returns the traffic light object it describes.- Parameters:
landmark
(carla.Landmark) – The landmark object describing a traffic light.
- Return: carla.TrafficLight
- Parameters:
- get_traffic_sign(self, landmark)
Provided a landmark, returns the traffic sign object it describes.- Parameters:
landmark
(carla.Landmark) – The landmark object describing a traffic sign.
- Return: carla.TrafficSign
- Parameters:
- get_vehicles_light_states(self)
Returns a dict where the keys are carla.Actor IDs and the values are carla.VehicleLightState of that vehicle.- Return: dict
- get_weather(self)
Retrieves an object containing weather parameters currently active in the simulation, mainly cloudiness, precipitation, wind and sun position.- Return: carla.WeatherParameters
- Setter: carla.World.set_weather
Setters
- set_weather(self, weather)
Changes the weather parameteres ruling the simulation to another ones defined in an object.- Parameters:
weather
(carla.WeatherParameters) – New conditions to be applied.
- Getter: carla.World.get_weather
- Parameters:
Dunder methods
- _str_(self)
The content of the world is parsed and printed as a brief report of its current state.- Return: string
carla.WorldSettings
The simulation has some advanced configuration options that are contained in this class and can be managed using carla.World and its methods. These allow the user to choose between client-server synchrony/asynchrony, activation of "no rendering mode" and either if the simulation should run with a fixed or variable time-step. Check this out if you want to learn about it.
Instance Variables
- synchronous_mode (bool)
States the synchrony between client and server. When set to true, the server will wait for a client tick in order to move forward. It is false by default. - no_rendering_mode (bool)
When enabled, the simulation will run no rendering at all. This is mainly used to avoid overhead during heavy traffic simulations. It is false by default. - fixed_delta_seconds (float)
Ensures that the time elapsed between two steps of the simulation is fixed. Set this to 0.0 to work with a variable time-step, as happens by default. - substepping (bool)
Enable the physics substepping. This option allows computing some physics substeps between two render frames. If synchronous mode is set, the number of substeps and its time interval are fixed and computed are so they fulfilled the requirements of carla.WorldSettings.max_substep and carla.WorldSettings.max_substep_delta_time. These last two parameters need to be compatible with carla.WorldSettings.fixed_delta_seconds. Enabled by default. - max_substep_delta_time (float)
Maximum delta time of the substeps. If the carla.WorldSettingsmax_substep is high enough, the substep delta time would be always below or equal to this value. By default, the value is set to 0.01. - max_substeps (int)
The maximum number of physics substepping that are allowed. By default, the value is set to 10. - max_culling_distance (float)
Configure the max draw distance for each mesh of the level. - deterministic_ragdolls (bool)
Defines wether to use deterministic physics for pedestrian death animations or physical ragdoll simulation. When enabled, pedestrians have less realistic death animation but ensures determinism. When disabled, pedestrians are simulated as ragdolls with more realistic simulation and collision but no determinsm can be ensured.
Methods
- _init_(self, synchronous_mode=False, no_rendering_mode=False, fixed_delta_seconds=0.0)
Creates an object containing desired settings that could later be applied through carla.World and its method apply_settings().- Parameters:
synchronous_mode
(bool) – Set this to true to enable client-server synchrony.no_rendering_mode
(bool) – Set this to true to completely disable rendering in the simulation.fixed_delta_seconds
(float – seconds) – Set a fixed time-step in between frames.0.0
means variable time-step and it is the default mode.
- Parameters:
Dunder methods
- _eq_(self, other=carla.WorldSettings)
Returns True if both objects' variables are the same.- Return: bool
- _ne_(self, other=carla.WorldSettings)
Returns True if both objects' variables are different.- Return: bool
- _str_(self)
Parses the established settings to a string and shows them in command line.- Return: str
carla.WorldSnapshot
This snapshot comprises all the information for every actor on scene at a certain moment of time. It creates and gives acces to a data structure containing a series of carla.ActorSnapshot. The client recieves a new snapshot on every tick that cannot be stored.
Instance Variables
- id (int)
A value unique for every snapshot to differenciate them. - frame (int)
Simulation frame in which the snapshot was taken. - timestamp (carla.Timestamp – seconds)
Precise moment in time when snapshot was taken. This class works in seconds as given by the operative system.
Methods
- find(self, actor_id)
Given a certain actor ID, returns its corresponding snapshot or None if it is not found.- Parameters:
actor_id
(int)
- Return: carla.ActorSnapshot
- Parameters:
- has_actor(self, actor_id)
Given a certain actor ID, checks if there is a snapshot corresponding it and so, if the actor was present at that moment.- Parameters:
actor_id
(int)
- Return: bool
- Parameters:
Dunder methods
- _eq_(self, other=carla.WorldSnapshot)
Returns True if both timestamp are the same.- Return: bool
- _iter_(self)
Iterate over the carla.ActorSnapshot stored in the snapshot. - _len_(self)
Returns the amount of carla.ActorSnapshot present in this snapshot.- Return: int
- _ne_(self, other=carla.WorldSnapshot)
Returns True if both timestamp are different.- Return: bool
command.ApplyAngularImpulse
Command adaptation of add_angular_impulse() in carla.Actor. Applies an angular impulse to an actor.
Instance Variables
- actor_id (int)
Actor affected by the command. - impulse (carla.Vector3D – degrees*s)
Angular impulse applied to the actor.
Methods
- _init_(self, actor, impulse)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.impulse
(carla.Vector3D – degrees*s)
- Parameters:
command.ApplyForce
Command adaptation of add_force() in carla.Actor. Applies a force to an actor.
Instance Variables
- actor_id (int)
Actor affected by the command. - force (carla.Vector3D – N)
Force applied to the actor over time.
Methods
- _init_(self, actor, force)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.force
(carla.Vector3D – N)
- Parameters:
command.ApplyImpulse
Command adaptation of add_impulse() in carla.Actor. Applies an impulse to an actor.
Instance Variables
- actor_id (int)
Actor affected by the command. - impulse (carla.Vector3D – N*s)
Impulse applied to the actor.
Methods
- _init_(self, actor, impulse)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.impulse
(carla.Vector3D – N*s)
- Parameters:
command.ApplyTargetAngularVelocity
Command adaptation of set_target_angular_velocity() in carla.Actor. Sets the actor's angular velocity vector.
Instance Variables
- actor_id (int)
Actor affected by the command. - angular_velocity (carla.Vector3D – deg/s)
The 3D angular velocity that will be applied to the actor.
Methods
- _init_(self, actor, angular_velocity)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.angular_velocity
(carla.Vector3D – deg/s) – Angular velocity vector applied to the actor.
- Parameters:
command.ApplyTargetVelocity
Command adaptation of set_target_velocity() in carla.Actor.
Instance Variables
- actor_id (int)
Actor affected by the command. - velocity (carla.Vector3D – m/s)
The 3D velocity applied to the actor.
Methods
- _init_(self, actor, velocity)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.velocity
(carla.Vector3D – m/s) – Velocity vector applied to the actor.
- Parameters:
command.ApplyTorque
Command adaptation of add_torque() in carla.Actor. Applies a torque to an actor.
Instance Variables
- actor_id (int)
Actor affected by the command. - torque (carla.Vector3D – degrees)
Torque applied to the actor over time.
Methods
- _init_(self, actor, torque)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.torque
(carla.Vector3D – degrees)
- Parameters:
command.ApplyTransform
Command adaptation of set_transform() in carla.Actor. Sets a new transform to an actor.
Instance Variables
- actor_id (int)
Actor affected by the command. - transform (carla.Transform)
Transformation to be applied.
Methods
- _init_(self, actor, transform)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.transform
(carla.Transform)
- Parameters:
command.ApplyVehicleControl
Command adaptation of apply_control() in carla.Vehicle. Applies a certain control to a vehicle.
Instance Variables
- actor_id (int)
Vehicle actor affected by the command. - control (carla.VehicleControl)
Vehicle control to be applied.
Methods
- _init_(self, actor, control)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.control
(carla.VehicleControl)
- Parameters:
command.ApplyWalkerControl
Command adaptation of apply_control() in carla.Walker. Applies a control to a walker.
Instance Variables
- actor_id (int)
Walker actor affected by the command. - control (carla.WalkerControl)
Walker control to be applied.
Methods
- _init_(self, actor, control)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.control
(carla.WalkerControl)
- Parameters:
command.ApplyWalkerState
Apply a state to the walker actor. Specially useful to initialize an actor them with a specific location, orientation and speed.
Instance Variables
- actor_id (int)
Walker actor affected by the command. - transform (carla.Transform)
Transform to be applied. - speed (float – m/s)
Speed to be applied.
Methods
- _init_(self, actor, transform, speed)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.transform
(carla.Transform)speed
(float – m/s)
- Parameters:
command.DestroyActor
Command adaptation of destroy() in carla.Actor that tells the simulator to destroy this actor. It has no effect if the actor was already destroyed. When executed with apply_batch_sync() in carla.Client there will be a command.Response that will return a boolean stating whether the actor was successfully destroyed.
Instance Variables
Methods
- _init_(self, actor)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.
- Parameters:
command.Response
States the result of executing a command as either the ID of the actor to whom the command was applied to (when succeeded) or an error string (when failed). actor ID, depending on whether or not the command succeeded. The method apply_batch_sync() in carla.Client returns a list of these to summarize the execution of a batch.
Instance Variables
- actor_id (int)
Actor to whom the command was applied to. States that the command was successful. - error (str)
A string stating the command has failed.
Methods
- has_error(self)
Returns True if the command execution fails, and False if it was successful.- Return: bool
command.SetAutopilot
Command adaptation of set_autopilot() in carla.Vehicle. Turns on/off the vehicle's autopilot mode.
Instance Variables
- actor_id (int)
Actor that is affected by the command. - enabled (bool)
If autopilot should be activated or not. - port (uint16)
Port of the Traffic Manager where the vehicle is to be registered or unlisted.
Methods
- _init_(self, actor, enabled, port=8000)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.enabled
(bool)port
(uint16) – The Traffic Manager port where the vehicle is to be registered or unlisted. If None is passed, it will consider a TM at default port8000
.
- Parameters:
command.SetSimulatePhysics
Command adaptation of set_simulate_physics() in carla.Actor. Determines whether an actor will be affected by physics or not.
Instance Variables
Methods
- _init_(self, actor, enabled)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.enabled
(bool)
- Parameters:
command.SetVehicleLightState
Command adaptation of set_light_state() in carla.Vehicle. Sets the light state of a vehicle.
Instance Variables
- actor_id (int)
Actor that is affected by the command. - light_state (carla.VehicleLightState)
Defines the light state of a vehicle.
Methods
- _init_(self, actor, light_state)
- Parameters:
actor
(carla.Actor or int) – Actor or its ID to whom the command will be applied to.light_state
(carla.VehicleLightState) – Recaps the state of the lights of a vehicle, these can be used as a flags.
- Parameters:
command.SpawnActor
Command adaptation of spawn_actor() in carla.World. Spawns an actor into the world based on the blueprint provided and the transform. If a parent is provided, the actor is attached to it.
Instance Variables
- transform (carla.Transform)
Transform to be applied. - parent_id (int)
Identificator of the parent actor.
Methods
- _init_(self)
- _init_(self, blueprint, transform)
- Parameters:
blueprint
(carla.ActorBlueprint)transform
(carla.Transform)
- Parameters:
- _init_(self, blueprint, transform, parent)
- Parameters:
blueprint
(carla.ActorBlueprint)transform
(carla.Transform)parent
(carla.Actor or int)
- Parameters:
- then(self, command)
Links another command to be executed right after. It allows to ease very common flows such as spawning a set of vehicles by command and then using this method to set them to autopilot automatically.- Parameters:
command
(any carla Command) – a Carla command.
- Parameters:
Snippet for carla.World.load_map_layer
# This recipe toggles on several layers in our "_Opt" maps
# Load town one with only minimum layout (roads, sidewalks, traffic lights and traffic signs)
world = client.load_world('Town01_Opt', carla.MapLayer.None)
# Toggle all buildings on
world.load_map_layer(carla.MapLayer.Buildings)
# Toggle all foliage on
world.load_map_layer(carla.MapLayer.Foliage)
# Toggle all parked vehicles on
world.load_map_layer(carla.MapLayer.ParkedVehicles)
Copy snippet Close snippet
Snippet for carla.World.unload_map_layer
# This recipe toggles off several layers in our "_Opt" maps
# Load town one with minimum layout (roads, sidewalks, traffic lights and traffic signs)
# as well as buildings and parked vehicles
world = client.load_world('Town01_Opt', carla.MapLayer.Buildings | carla.MapLayer.ParkedVehicles)
# Toggle all buildings off
world.unload_map_layer(carla.MapLayer.Buildings)
# Toggle all parked vehicles off
world.unload_map_layer(carla.MapLayer.ParkedVehicles)
Copy snippet Close snippet
Snippet for carla.Map.get_waypoint
# This recipe shows the current traffic rules affecting the vehicle.
# Shows the current lane type and if a lane change can be done in the actual lane or the surrounding ones.
# ...
waypoint = world.get_map().get_waypoint(vehicle.get_location(),project_to_road=True, lane_type=(carla.LaneType.Driving | carla.LaneType.Shoulder | carla.LaneType.Sidewalk))
print("Current lane type: " + str(waypoint.lane_type))
# Check current lane change allowed
print("Current Lane change: " + str(waypoint.lane_change))
# Left and Right lane markings
print("L lane marking type: " + str(waypoint.left_lane_marking.type))
print("L lane marking change: " + str(waypoint.left_lane_marking.lane_change))
print("R lane marking type: " + str(waypoint.right_lane_marking.type))
print("R lane marking change: " + str(waypoint.right_lane_marking.lane_change))
# ...
Copy snippet Close snippet
Snippet for carla.World.get_spectator
# This recipe spawns an actor and the spectator camera at the actor's location.
# ...
world = client.get_world()
spectator = world.get_spectator()
vehicle_bp = random.choice(world.get_blueprint_library().filter('vehicle.bmw.*'))
transform = random.choice(world.get_map().get_spawn_points())
vehicle = world.try_spawn_actor(vehicle_bp, transform)
# Wait for world to get the vehicle actor
world.tick()
world_snapshot = world.wait_for_tick()
actor_snapshot = world_snapshot.find(vehicle.id)
# Set spectator at given transform (vehicle transform)
spectator.set_transform(actor_snapshot.get_transform())
# ...
Copy snippet Close snippet
Snippet for carla.WalkerAIController.stop
#To destroy the pedestrians, stop them from the navigation, and then destroy the objects (actor and controller).
# stop pedestrians (list is [controller, actor, controller, actor ...])
for i in range(0, len(all_id), 2):
all_actors[i].stop()
# destroy pedestrian (actor and controller)
client.apply_batch([carla.command.DestroyActor(x) for x in all_id])
Copy snippet Close snippet
Snippet for carla.World.spawn_actor
# This recipe attaches different camera / sensors to a vehicle with different attachments.
# ...
camera = world.spawn_actor(rgb_camera_bp, transform, attach_to=vehicle, attachment_type=Attachment.Rigid)
# Default attachment: Attachment.Rigid
gnss_sensor = world.spawn_actor(sensor_gnss_bp, transform, attach_to=vehicle)
collision_sensor = world.spawn_actor(sensor_collision_bp, transform, attach_to=vehicle)
lane_invasion_sensor = world.spawn_actor(sensor_lane_invasion_bp, transform, attach_to=vehicle)
# ...
Copy snippet Close snippet
Snippet for carla.Client.apply_batch_sync
# 0. Choose a blueprint fo the walkers
world = client.get_world()
blueprintsWalkers = world.get_blueprint_library().filter("walker.pedestrian.*")
walker_bp = random.choice(blueprintsWalkers)
# 1. Take all the random locations to spawn
spawn_points = []
for i in range(50):
spawn_point = carla.Transform()
spawn_point.location = world.get_random_location_from_navigation()
if (spawn_point.location != None):
spawn_points.append(spawn_point)
# 2. Build the batch of commands to spawn the pedestrians
batch = []
for spawn_point in spawn_points:
walker_bp = random.choice(blueprintsWalkers)
batch.append(carla.command.SpawnActor(walker_bp, spawn_point))
# 2.1 apply the batch
results = client.apply_batch_sync(batch, True)
for i in range(len(results)):
if results[i].error:
logging.error(results[i].error)
else:
walkers_list.append({"id": results[i].actor_id})
# 3. Spawn walker AI controllers for each walker
batch = []
walker_controller_bp = world.get_blueprint_library().find('controller.ai.walker')
for i in range(len(walkers_list)):
batch.append(carla.command.SpawnActor(walker_controller_bp, carla.Transform(), walkers_list[i]["id"]))
# 3.1 apply the batch
results = client.apply_batch_sync(batch, True)
for i in range(len(results)):
if results[i].error:
logging.error(results[i].error)
else:
walkers_list[i]["con"] = results[i].actor_id
# 4. Put altogether the walker and controller ids
for i in range(len(walkers_list)):
all_id.append(walkers_list[i]["con"])
all_id.append(walkers_list[i]["id"])
all_actors = world.get_actors(all_id)
# wait for a tick to ensure client receives the last transform of the walkers we have just created
world.wait_for_tick()
# 5. initialize each controller and set target to walk to (list is [controller, actor, controller, actor ...])
for i in range(0, len(all_actors), 2):
# start walker
all_actors[i].start()
# set walk to random point
all_actors[i].go_to_location(world.get_random_location_from_navigation())
# random max speed
all_actors[i].set_max_speed(1 + random.random()) # max speed between 1 and 2 (default is 1.4 m/s)
Copy snippet Close snippet
Snippet for carla.ActorBlueprint.set_attribute
# This recipe changes attributes of different type of blueprint actors.
# ...
walker_bp = world.get_blueprint_library().filter('walker.pedestrian.0002')
walker_bp.set_attribute('is_invincible', True)
# ...
# Changes attribute randomly by the recommended value
vehicle_bp = wolrd.get_blueprint_library().filter('vehicle.bmw.*')
color = random.choice(vehicle_bp.get_attribute('color').recommended_values)
vehicle_bp.set_attribute('color', color)
# ...
camera_bp = world.get_blueprint_library().filter('sensor.camera.rgb')
camera_bp.set_attribute('image_size_x', 600)
camera_bp.set_attribute('image_size_y', 600)
# ...
Copy snippet Close snippet
Snippet for carla.DebugHelper.draw_box
# This recipe shows how to draw traffic light actor bounding boxes from a world snapshot.
# ....
debug = world.debug
world_snapshot = world.get_snapshot()
for actor_snapshot in world_snapshot:
actual_actor = world.get_actor(actor_snapshot.id)
if actual_actor.type_id == 'traffic.traffic_light':
debug.draw_box(carla.BoundingBox(actor_snapshot.get_transform().location,carla.Vector3D(0.5,0.5,2)),actor_snapshot.get_transform().rotation, 0.05, carla.Color(255,0,0,0),0)
# ...
Copy snippet Close snippet
Snippet for carla.Sensor.listen
# This recipe applies a color conversion to the image taken by a camera sensor,
# so it is converted to a semantic segmentation image.
# ...
camera_bp = world.get_blueprint_library().filter('sensor.camera.semantic_segmentation')
# ...
cc = carla.ColorConverter.CityScapesPalette
camera.listen(lambda image: image.save_to_disk('output/%06d.png' % image.frame, cc))
# ...
Copy snippet Close snippet
Snippet for carla.Vehicle.set_wheel_steer_direction
# Sets the appearance of the vehicles front wheels to 40°. Vehicle physics will not be affected.
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FR_Wheel, 40.0)
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FL_Wheel, 40.0)
Copy snippet Close snippet
Snippet for carla.DebugHelper.draw_string
# This recipe is a modification of lane_explorer.py example.
# It draws the path of an actor through the world, printing information at each waypoint.
# ...
current_w = map.get_waypoint(vehicle.get_location())
while True:
next_w = map.get_waypoint(vehicle.get_location(), lane_type=carla.LaneType.Driving | carla.LaneType.Shoulder | carla.LaneType.Sidewalk )
# Check if the vehicle is moving
if next_w.id != current_w.id:
vector = vehicle.get_velocity()
# Check if the vehicle is on a sidewalk
if current_w.lane_type == carla.LaneType.Sidewalk:
draw_waypoint_union(debug, current_w, next_w, cyan if current_w.is_junction else red, 60)
else:
draw_waypoint_union(debug, current_w, next_w, cyan if current_w.is_junction else green, 60)
debug.draw_string(current_w.transform.location, str('%15.0f km/h' % (3.6 * math.sqrt(vector.x**2 + vector.y**2 + vector.z**2))), False, orange, 60)
draw_transform(debug, current_w.transform, white, 60)
# Update the current waypoint and sleep for some time
current_w = next_w
time.sleep(args.tick_time)
# ...
Copy snippet Close snippet
Snippet for carla.World.enable_environment_objects
# This recipe turn visibility off and on for two specifc buildings on the map
# Get the buildings in the world
world = client.get_world()
env_objs = world.get_environment_objects(carla.CityObjectLabel.Buildings)
# Access individual building IDs and save in a set
building_01 = env_objs[0]
building_02 = env_objs[1]
objects_to_toggle = {building_01.id, building_02.id}
# Toggle buildings off
world.enable_environment_objects(objects_to_toggle, False)
# Toggle buildings on
world.enable_environment_objects(objects_to_toggle, True)
Copy snippet Close snippet
Snippet for carla.Client.__init__
# This recipe shows in every script provided in PythonAPI/Examples
# and it is used to parse the client creation arguments when running the script.
argparser = argparse.ArgumentParser(
description=__doc__)
argparser.add_argument(
'--host',
metavar='H',
default='127.0.0.1',
help='IP of the host server (default: 127.0.0.1)')
argparser.add_argument(
'-p', '--port',
metavar='P',
default=2000,
type=int,
help='TCP port to listen to (default: 2000)')
argparser.add_argument(
'-s', '--speed',
metavar='FACTOR',
default=1.0,
type=float,
help='rate at which the weather changes (default: 1.0)')
args = argparser.parse_args()
speed_factor = args.speed
update_freq = 0.1 / speed_factor
client = carla.Client(args.host, args.port)
Copy snippet Close snippet
Snippet for carla.TrafficLight.set_state
# This recipe changes from red to green the traffic light that affects the vehicle.
# This is done by detecting if the vehicle actor is at a traffic light.
# ...
world = client.get_world()
spectator = world.get_spectator()
vehicle_bp = random.choice(world.get_blueprint_library().filter('vehicle.bmw.*'))
transform = random.choice(world.get_map().get_spawn_points())
vehicle = world.try_spawn_actor(vehicle_bp, transform)
# Wait for world to get the vehicle actor
world.tick()
world_snapshot = world.wait_for_tick()
actor_snapshot = world_snapshot.find(vehicle.id)
# Set spectator at given transform (vehicle transform)
spectator.set_transform(actor_snapshot.get_transform())
# ...# ...
if vehicle_actor.is_at_traffic_light():
traffic_light = vehicle_actor.get_traffic_light()
if traffic_light.get_state() == carla.TrafficLightState.Red:
# world.hud.notification("Traffic light changed! Good to go!")
traffic_light.set_state(carla.TrafficLightState.Green)
# ...
Copy snippet Close snippet