sergi-e/api-snipets (#3409)

* First iteration with snipets, copy button and snippet button for all methods

* New iteration with snipets implemented and test snipets

* New iteration without yaml intervention, with auxiliary doc deleted and responsive buttons to window width

* New iteration with snipets copied from recipes, images added, and invisible button for small window

* Fixed some marging issues & code formatting

* Removed recipe reference and its instances. Snipets are now scalable to window width. Added button to close snipet. doc_gen_snipets.py is now imported in doc_gen.py. Cleaned css inside .py and added to extra.css

* New iteration with two functionalities for snipet buttons. Pop up for small windows.

* Fixed bp_library.md

Co-authored-by: Marc Garcia Puig <marcgpuig@gmail.com>
This commit is contained in:
sergi.e 2020-10-15 16:48:48 +02:00 committed by GitHub
parent c54aa11653
commit 31fff28bc6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 1111 additions and 453 deletions

View File

@ -281,7 +281,7 @@ ai_controller.stop()
```
When a walker reaches the target location, they will automatically walk to another random point. If the target point is not reachable, walkers will go to the closest point from their current location.
[This recipe](ref_code_recipes.md#walker-batch-recipe) uses batches to spawn a lot of walkers and make them wander around.
A snipet in [carla.Client](python_api.md#carla.Client.apply_batch_sync) uses batches to spawn a lot of walkers and make them wander around.
!!! Important
__To destroy AI pedestrians__, stop the AI controller and destroy both, the actor, and the controller.

View File

@ -2,7 +2,7 @@
This page introduces the main features and modules in CARLA. Detailed explanations of the different subjects can be found in their corresponding page.
In order to learn about the different classes and methods in the API, take a look at the [Python API reference](python_api.md). Besides, the [Code recipes](ref_code_recipes.md) reference contains some common code chunks, specially useful during these first steps.
In order to learn about the different classes and methods in the API, take a look at the [Python API reference](python_api.md).
* [__First steps__](#first-steps)
* [1st- World and client](#1st-world-and-client)

View File

@ -28,7 +28,7 @@ Take a look at [__carla.Client__](python_api.md#carla.Client) in the Python API
### Client creation
Two things are needed. The __IP__ address identifying it, and __two TCP ports__ to communicate with the server. An optional third parameter sets the amount of working threads. By default this is set to all (`0`). [This code recipe](ref_code_recipes.md#parse-client-creation-arguments) shows how to parse these as arguments when running the script.
Two things are needed. The __IP__ address identifying it, and __two TCP ports__ to communicate with the server. An optional third parameter sets the amount of working threads. By default this is set to all (`0`). The [carla.Client](python_api.md#carla.Client.__init__) in the Python API reference contains a snipet that shows how to parse these as arguments when running the script.
```py
client = carla.Client('localhost', 2000)
@ -224,7 +224,7 @@ debug = world.debug
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)
```
This example is extended in a [code recipe](ref_code_recipes.md#debug-bounding-box-recipe) to draw boxes for every actor in a world snapshot.
This example is extended in a snipet in [carla.DebugHelper](python_api.md#carla.DebugHelper.draw_box) that shows how to draw boxes for every actor in a world snapshot.
### World snapshots

View File

@ -23,7 +23,7 @@ table.defTable {
}
table.defTable thead {
background: #ffffff;
background: #ffffff;
border-bottom: 1px solid #444444;
}
@ -39,6 +39,13 @@ table.defTable tbody td{
padding: 7px 13px;
}
/************************* INHERITED PYTHON API LINE **************************/
.Inherited {
padding-left:30px;
margin-top:-20px
}
/************************* TOWN SLIDER **************************/
* {box-sizing:border-box}
@ -53,7 +60,7 @@ table.defTable tbody td{
/* Hide the images by default */
.townslide {
display: none;
text-align: center;
text-align: center;
}
@ -130,3 +137,110 @@ table.defTable tbody td{
background-color: #717171;
}
/************************* COPY SCRIPT BUTTON **************************/
.CopyScript {
box-shadow:inset 0px 1px 0px 0px #ffffff;
background:linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
background-color:#ffffff;
border-radius:6px;
border:1px solid #dcdcdc;
display:inline-block;
cursor:pointer;
color:#666666;
font-family:Arial;
font-size:15px;
font-weight:bold;
padding:6px 6px;
text-decoration:none;
text-shadow:0px 1px 0px #ffffff;
margin-left: 2px;
}
.CopyScript:hover {
background:linear-gradient(to bottom, #f6f6f6 5%, #ffffff 100%);
background-color:#f6f6f6;
}
.CopyScript:active {
position:relative;
top:1px;
}
/************************* CLOSE SNIPET BUTTON **************************/
.CloseSnipet {
box-shadow:inset 0px 1px 0px 0px #ffffff;
background:linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
background-color:#ffffff;
border-radius:6px;
border:1px solid #dcdcdc;
display:inline-block;
cursor:pointer;
color:#666666;
font-family:Arial;
font-size:15px;
font-weight:bold;
padding:6px 6px;
text-decoration:none;
text-shadow:0px 1px 0px #ffffff;
margin-left: 2px;
}
.CloseSnipet:hover {
background:linear-gradient(to bottom, #ffe6e6 5%, #ffffff 100%);
background-color:#ffffff;
}
.CloseSnipet:active {
position:relative;
top:1px;
}
/************************* SNIPET TITLE **************************/
.SnipetFont {
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
letter-spacing: 0.4px;
margin-left: 10px;
margin-bottom: 0px;
word-spacing: -2.2px;
color: #4675B1;
font-weight: 700;
text-decoration: rgb(68, 68, 68);
font-style: normal;
font-variant: normal;
text-transform: none;
}
/************************* SNIPET BUTTON **************************/
.SnipetButton {
background-color: #476e9e;
border-radius:42px;
border:0px;
display:inline-block;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:12px;
padding:2px 3px;
text-decoration:none;
text-shadow:0px 1px 0px #2f6627;
}
/************************* SNIPET CONTENT **************************/
.SnipetContent {
width: calc(100vw - 1150px);
margin-left: 10px;
}
/************************* SNIPET CONTAINER **************************/
.Container {
position: fixed;
margin-left: 0px;
overflow-y: auto;
padding-left: 10px;
height: 95%;
top: 70px;
left: 1100px;
}

View File

Before

Width:  |  Height:  |  Size: 512 KiB

After

Width:  |  Height:  |  Size: 512 KiB

View File

Before

Width:  |  Height:  |  Size: 948 KiB

After

Width:  |  Height:  |  Size: 948 KiB

View File

Before

Width:  |  Height:  |  Size: 531 KiB

After

Width:  |  Height:  |  Size: 531 KiB

View File

Before

Width:  |  Height:  |  Size: 11 MiB

After

Width:  |  Height:  |  Size: 11 MiB

View File

@ -81,8 +81,6 @@ CARLA forum</a>
<p style="padding-left:30px;line-height:1.8">
[__Python API reference__](python_api.md)
— Classes and methods in the Python API.
[__Code recipes__](ref_code_recipes.md)
— Some code fragments commonly used.
[__Blueprint library__](bp_library.md)
— Blueprints provided to spawn actors.
[__C++ reference__](ref_cpp.md)
@ -91,12 +89,14 @@ CARLA forum</a>
— Detailed explanation of the recorder file format.
[__Sensors reference__](ref_sensors.md)
— Everything about sensors and the data they retrieve.
</p>
## Plugins
<p style="padding-left:30px;line-height:1.8">
[__carlaviz — web visualizer__](plugins_carlaviz.md)
— Plugin that listens the simulation and shows the scene and some simulation data in a web browser.
</p>
## ROS bridge
<p style="padding-left:30px;line-height:1.8">
[__ROS bridge installation__](ros_installation.md)
@ -139,11 +139,11 @@ CARLA forum</a>
## Tutorials — Developers
<p style="padding-left:30px;line-height:1.8">
[__Contribute with new assets__](tuto_D_contribute_assets.md)
[__Contribute new assets__](tuto_D_contribute_assets.md)
— Add new content to CARLA.
[__Create a sensor__](tuto_D_create_sensor.md)
— Develop a new sensor to be used in CARLA.
[__Create semantic tags_](tuto_D_create_semantic_tags.md)
[__Create semantic tags__](tuto_D_create_semantic_tags.md)
— Define new semantic tags for semantic segmentation.
[__Customize vehicle suspension__](tuto_D_customize_vehicle_suspension.md)
— Modify the suspension system of a vehicle.

View File

@ -193,7 +193,7 @@ Returns the actor's attribute with `id` as identifier if existing.
- **Setter:** _[carla.ActorBlueprint.set_attribute](#carla.ActorBlueprint.set_attribute)_
<h5 style="margin-top: -20px">Setters</h5>
<div style="padding-left:30px;margin-top:-25px"></div>- <a name="carla.ActorBlueprint.set_attribute"></a>**<font color="#7fb800">set_attribute</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**id**</font>, <font color="#00a6ed">**value**</font>)
<div style="padding-left:30px;margin-top:-25px"></div>- <a name="carla.ActorBlueprint.set_attribute"></a>**<font color="#7fb800">set_attribute</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**id**</font>, <font color="#00a6ed">**value**</font>)<button class="SnipetButton" id="carla.ActorBlueprint.set_attribute-snipet_button">snipet &rarr;</button>
If the `id` attribute is modifiable, changes its value to `value`.
- **Parameters:**
- `id` (_str_) The identifier for the attribute that is intended to be changed.
@ -265,13 +265,13 @@ Returns the velocity vector registered for an actor in that tick.
---
## carla.AttachmentType<a name="carla.AttachmentType"></a>
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. [Here](ref_code_recipes.md#attach-sensors-recipe) is a brief recipe in which we can see how sensors can be attached to a car when spawned. Note that the attachment type is declared as an enum within the class.
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](#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.
<h3>Instance Variables</h3>
- <a name="carla.AttachmentType.Rigid"></a>**<font color="#f8805a">Rigid</font>**
With this fixed attatchment the object follow its parent position strictly. This is the recommended attachment to retrieve precise data from the simulation.
- <a name="carla.AttachmentType.SpringArm"></a>**<font color="#f8805a">SpringArm</font>**
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 this out](ref_code_recipes.md#attach-sensors-recipe) to learn some more about them. <br><b style="color:red;">Warning:</b> The <b>SpringArm</b> attachment presents weird behaviors when an actor is spawned with a relative translation in the Z-axis (e.g. <code>child_location = Location(0,0,2)</code>).
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](https://docs.unrealengine.com/en-US/Gameplay/HowTo/UsingCameras/SpringArmComponents/index.html) to learn more about them. <br><b style="color:red;">Warning:</b> The <b>SpringArm</b> attachment presents weird behaviors when an actor is spawned with a relative translation in the Z-axis (e.g. <code>child_location = Location(0,0,2)</code>).
---
@ -308,7 +308,7 @@ Parses the identifiers for every blueprint to string.
---
## carla.BoundingBox<a name="carla.BoundingBox"></a>
Bounding boxes contain the geometry of an actor or an element in the scene. They can be used by [carla.DebugHelper](#carla.DebugHelper) or a [carla.Client](#carla.Client) to draw their shapes for debugging. Check out this [recipe](ref_code_recipes.md#debug-bounding-box-recipe) where the user takes a snapshot of the world and then proceeds to draw bounding boxes for traffic lights.
Bounding boxes contain the geometry of an actor or an element in the scene. They can be used by [carla.DebugHelper](#carla.DebugHelper) or a [carla.Client](#carla.Client) to draw their shapes for debugging. Check out the snipet in [carla.DebugHelper.draw_box](#carla.DebugHelper.draw_box) where a snapshot of the world is used to draw bounding boxes for traffic lights.
<h3>Instance Variables</h3>
- <a name="carla.BoundingBox.extent"></a>**<font color="#f8805a">extent</font>** (_[carla.Vector3D](#carla.Vector3D)<small> meters</small>_)
@ -390,7 +390,7 @@ The Client connects CARLA to the server which runs the simulation. Both server a
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](adv_recorder.md) is some information about how to use this recorder.
<h3>Methods</h3>
- <a name="carla.Client.__init__"></a>**<font color="#7fb800">\__init__</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**host**=127.0.0.1</font>, <font color="#00a6ed">**port**=2000</font>, <font color="#00a6ed">**worker_threads**=0</font>)
- <a name="carla.Client.__init__"></a>**<font color="#7fb800">\__init__</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**host**=127.0.0.1</font>, <font color="#00a6ed">**port**=2000</font>, <font color="#00a6ed">**worker_threads**=0</font>)<button class="SnipetButton" id="carla.Client.__init__-snipet_button">snipet &rarr;</button>
Client constructor.
- **Parameters:**
- `host` (_str_) IP address where a CARLA Simulator instance is running. Default is localhost (127.0.0.1).
@ -400,7 +400,7 @@ Client constructor.
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 __<font color="#7fb800">apply_batch_sync()</font>__ method. [Here](https://github.com/carla-simulator/carla/blob/10c5f6a482a21abfd00220c68c7f12b4110b7f63/PythonAPI/examples/spawn_npc.py#L126) is an example on how to delete the actors that appear in [carla.ActorList](#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.
- <a name="carla.Client.apply_batch_sync"></a>**<font color="#7fb800">apply_batch_sync</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**commands**</font>, <font color="#00a6ed">**due_tick_cue**=False</font>)
- <a name="carla.Client.apply_batch_sync"></a>**<font color="#7fb800">apply_batch_sync</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**commands**</font>, <font color="#00a6ed">**due_tick_cue**=False</font>)<button class="SnipetButton" id="carla.Client.apply_batch_sync-snipet_button">snipet &rarr;</button>
Executes a list of commands on a single simulation step, blocks until the commands are linked, and returns a list of <b>command.Response</b> that can be used to determine whether a single command succeeded or not. [Here](https://github.com/carla-simulator/carla/blob/10c5f6a482a21abfd00220c68c7f12b4110b7f63/PythonAPI/examples/spawn_npc.py#L112-L116) 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 **<font color="#7fb800">apply_batch()</font>**.
@ -503,7 +503,7 @@ Sets the maxixum time a network call is allowed before blocking it and raising a
---
## carla.CollisionEvent<a name="carla.CollisionEvent"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines a collision data for <b>sensor.other.collision</b>. The sensor creates one of this for every collision detected which may be many for one simulation step. Learn more about this [here](ref_sensors.md#collision-detector).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines a collision data for <b>sensor.other.collision</b>. The sensor creates one of this for every collision detected which may be many for one simulation step. Learn more about this [here](ref_sensors.md#collision-detector).
<h3>Instance Variables</h3>
- <a name="carla.CollisionEvent.actor"></a>**<font color="#f8805a">actor</font>** (_[carla.Actor](#carla.Actor)_)
@ -545,7 +545,7 @@ Initializes a color, black by default.
---
## carla.ColorConverter<a name="carla.ColorConverter"></a>
Class that defines conversion patterns that can be applied to a [carla.Image](#carla.Image) in order to show information provided by [carla.Sensor](#carla.Sensor). Depth conversions cause a loss of accuracy, as sensors detect depth as <b>float</b> that is then converted to a grayscale value between 0 and 255. Take a look a this [recipe](ref_code_recipes.md#converted-image-recipe) to see an example of how to create and save image data for <b>sensor.camera.semantic_segmentation</b>.
Class that defines conversion patterns that can be applied to a [carla.Image](#carla.Image) in order to show information provided by [carla.Sensor](#carla.Sensor). Depth conversions cause a loss of accuracy, as sensors detect depth as <b>float</b> that is then converted to a grayscale value between 0 and 255. Take a look at the snipet in [carla.Sensor.listen](#carla.Sensor.listen) to see an example of how to create and save image data for <b>sensor.camera.semantic_segmentation</b>.
<h3>Instance Variables</h3>
- <a name="carla.ColorConverter.CityScapesPalette"></a>**<font color="#f8805a">CityScapesPalette</font>**
@ -616,7 +616,7 @@ Iterate over the [carla.DVSEvent](#carla.DVSEvent) retrieved as data.
---
## carla.DebugHelper<a name="carla.DebugHelper"></a>
Helper class part of [carla.World](#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. Check out this [recipe](ref_code_recipes.md#debug-bounding-box-recipe) where the user takes a snapshot of the world and then proceeds to draw bounding boxes for traffic lights.
Helper class part of [carla.World](#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.
<h3>Methods</h3>
- <a name="carla.DebugHelper.draw_arrow"></a>**<font color="#7fb800">draw_arrow</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**begin**</font>, <font color="#00a6ed">**end**</font>, <font color="#00a6ed">**thickness**=0.1</font>, <font color="#00a6ed">**arrow_size**=0.1</font>, <font color="#00a6ed">**color**=(255,0,0)</font>, <font color="#00a6ed">**life_time**=-1.0</font>)
@ -628,7 +628,7 @@ Draws an arrow from `begin` to `end` pointing in that direction.
- `arrow_size` (_float<small> meters</small>_) Size of the tip of the arrow.
- `color` (_[carla.Color](#carla.Color)_) RGB code to color the object. Red by default.
- `life_time` (_float<small> seconds</small>_) Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
- <a name="carla.DebugHelper.draw_box"></a>**<font color="#7fb800">draw_box</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**box**</font>, <font color="#00a6ed">**rotation**</font>, <font color="#00a6ed">**thickness**=0.1</font>, <font color="#00a6ed">**color**=(255,0,0)</font>, <font color="#00a6ed">**life_time**=-1.0</font>)
- <a name="carla.DebugHelper.draw_box"></a>**<font color="#7fb800">draw_box</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**box**</font>, <font color="#00a6ed">**rotation**</font>, <font color="#00a6ed">**thickness**=0.1</font>, <font color="#00a6ed">**color**=(255,0,0)</font>, <font color="#00a6ed">**life_time**=-1.0</font>)<button class="SnipetButton" id="carla.DebugHelper.draw_box-snipet_button">snipet &rarr;</button>
Draws a box, ussually to act for object colliders.
- **Parameters:**
- `box` (_[carla.BoundingBox](#carla.BoundingBox)_) Object containing a location and the length of a box for every axis.
@ -636,7 +636,7 @@ Draws a box, ussually to act for object colliders.
- `thickness` (_float<small> meters</small>_) Density of the lines that define the box.
- `color` (_[carla.Color](#carla.Color)_) RGB code to color the object. Red by default.
- `life_time` (_float<small> seconds</small>_) Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
- <a name="carla.DebugHelper.draw_line"></a>**<font color="#7fb800">draw_line</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**begin**</font>, <font color="#00a6ed">**end**</font>, <font color="#00a6ed">**thickness**=0.1</font>, <font color="#00a6ed">**color**=(255,0,0)</font>, <font color="#00a6ed">**life_time**=-1.0</font>)
- <a name="carla.DebugHelper.draw_line"></a>**<font color="#7fb800">draw_line</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**begin**</font>, <font color="#00a6ed">**end**</font>, <font color="#00a6ed">**thickness**=0.1</font>, <font color="#00a6ed">**color**=(255,0,0)</font>, <font color="#00a6ed">**life_time**=-1.0</font>)<button class="SnipetButton" id="carla.DebugHelper.draw_line-snipet_button">snipet &rarr;</button>
Draws a line in between `begin` and `end`.
- **Parameters:**
- `begin` (_[carla.Location](#carla.Location)<small> meters</small>_) Point in the coordinate system where the line starts.
@ -713,7 +713,7 @@ Height regarding ground level.
---
## carla.GnssMeasurement<a name="carla.GnssMeasurement"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the Gnss data registered by a <b>sensor.other.gnss</b>. It essentially reports its position with the position of the sensor and an OpenDRIVE geo-reference.
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the Gnss data registered by a <b>sensor.other.gnss</b>. It essentially reports its position with the position of the sensor and an OpenDRIVE geo-reference.
<h3>Instance Variables</h3>
- <a name="carla.GnssMeasurement.altitude"></a>**<font color="#f8805a">altitude</font>** (_float<small> meters</small>_)
@ -731,7 +731,7 @@ West/East value of a point on the map.
---
## carla.IMUMeasurement<a name="carla.IMUMeasurement"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the data registered by a <b>sensor.other.imu</b>, regarding the sensor's transformation according to the current [carla.World](#carla.World). It essentially acts as accelerometer, gyroscope and compass.
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the data registered by a <b>sensor.other.imu</b>, regarding the sensor's transformation according to the current [carla.World](#carla.World). It essentially acts as accelerometer, gyroscope and compass.
<h3>Instance Variables</h3>
- <a name="carla.IMUMeasurement.accelerometer"></a>**<font color="#f8805a">accelerometer</font>** (_[carla.Vector3D](#carla.Vector3D)<small> m/s<sup>2</sup></small>_)
@ -749,7 +749,7 @@ Angular velocity.
---
## carla.Image<a name="carla.Image"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines an image of 32-bit BGRA colors that will be used as initial data retrieved by camera sensors. There are different camera sensors (currently three, RGB, depth and semantic segmentation) and each of these makes different use for the images. Learn more about them [here](ref_sensors.md).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines an image of 32-bit BGRA colors that will be used as initial data retrieved by camera sensors. There are different camera sensors (currently three, RGB, depth and semantic segmentation) and each of these makes different use for the images. Learn more about them [here](ref_sensors.md).
<h3>Instance Variables</h3>
- <a name="carla.Image.fov"></a>**<font color="#f8805a">fov</font>** (_float<small> degrees</small>_)
@ -952,7 +952,7 @@ Type 381.
---
## carla.LaneChange<a name="carla.LaneChange"></a>
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](#carla.Waypoint) according to the OpenDRIVE file. In this [recipe](ref_code_recipes.md#lanes-recipe) the user creates a waypoint for a current vehicle position and learns which turns are permitted.
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](#carla.Waypoint) according to the OpenDRIVE file. The snipet in [carla.Map.get_waypoint](#carla.Map.get_waypoint) shows how a waypoint can be used to learn which turns are permitted.
<h3>Instance Variables</h3>
- <a name="carla.LaneChange.NONE"></a>**<font color="#f8805a">NONE</font>**
@ -967,7 +967,7 @@ Traffic rules allow turning either right or left.
---
## carla.LaneInvasionEvent<a name="carla.LaneInvasionEvent"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines lanes invasion for <b>sensor.other.lane_invasion</b>. It works only client-side and is dependant on OpenDRIVE to provide reliable information. The sensor creates one of this every time there is a lane invasion, which may be more than once per simulation step. Learn more about this [here](ref_sensors.md#lane-invasion-detector).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines lanes invasion for <b>sensor.other.lane_invasion</b>. It works only client-side and is dependant on OpenDRIVE to provide reliable information. The sensor creates one of this every time there is a lane invasion, which may be more than once per simulation step. Learn more about this [here](ref_sensors.md#lane-invasion-detector).
<h3>Instance Variables</h3>
- <a name="carla.LaneInvasionEvent.actor"></a>**<font color="#f8805a">actor</font>** (_[carla.Actor](#carla.Actor)_)
@ -1013,8 +1013,7 @@ White by default.
---
## carla.LaneMarkingType<a name="carla.LaneMarkingType"></a>
Class that defines the lane marking types accepted by OpenDRIVE 1.4. Take a look at this [recipe](ref_code_recipes.md#lanes-recipe) where the user creates a [carla.Waypoint](#carla.Waypoint) for a vehicle location and retrieves from it 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.
Class that defines the lane marking types accepted by OpenDRIVE 1.4. The snipet in [carla.Map.get_waypoint](#carla.Map.get_waypoint) shows how a waypoint can be used to retrieve the information about adjacent lane markings. <br><br> __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.
<h3>Instance Variables</h3>
- <a name="carla.LaneMarkingType.NONE"></a>**<font color="#f8805a">NONE</font>**
@ -1032,7 +1031,7 @@ __Note on double types:__ Lane markings are defined under the OpenDRIVE standard
---
## carla.LaneType<a name="carla.LaneType"></a>
Class that defines the possible lane types accepted by OpenDRIVE 1.4. This standards define the road information. For instance in this [recipe](ref_code_recipes.md#lanes-recipe) the user creates a [carla.Waypoint](#carla.Waypoint) for the current location of a vehicle and uses it to get the current and adjacent lane types.
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](#carla.Map.get_waypoint) makes use of a waypoint to get the current and adjacent lane types.
<h3>Instance Variables</h3>
- <a name="carla.LaneType.NONE"></a>**<font color="#f8805a">NONE</font>**
@ -1078,7 +1077,7 @@ Computed intensity for this point as a scalar value between [0.0 , 1.0].
---
## carla.LidarMeasurement<a name="carla.LidarMeasurement"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the LIDAR data retrieved by a <b>sensor.lidar.ray_cast</b>. This essentially simulates a rotating LIDAR using ray-casting. Learn more about this [here](ref_sensors.md#lidar-raycast-sensor).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the LIDAR data retrieved by a <b>sensor.lidar.ray_cast</b>. This essentially simulates a rotating LIDAR using ray-casting. Learn more about this [here](ref_sensors.md#lidar-raycast-sensor).
<h3>Instance Variables</h3>
- <a name="carla.LidarMeasurement.channels"></a>**<font color="#f8805a">channels</font>** (_int_)
@ -1309,7 +1308,7 @@ Switch of a light. It is __True__ when the light is on.
---
## carla.Location<a name="carla.Location"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Vector3D](#carla.Vector3D)_</b></small></div></p><p>Represents a spot in the world.
<div class="Inherited"><small><b>Inherited from _[carla.Vector3D](#carla.Vector3D)_</b></small></div></p><p>Represents a spot in the world.
<h3>Instance Variables</h3>
- <a name="carla.Location.x"></a>**<font color="#f8805a">x</font>** (_float<small> meters</small>_)
@ -1401,7 +1400,7 @@ Returns a list of recommendations made by the creators of the map to be used as
- <a name="carla.Map.get_topology"></a>**<font color="#7fb800">get_topology</font>**(<font color="#00a6ed">**self**</font>)
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](https://networkx.github.io/) to work with. Output could look like this: <b>[(w0, w1), (w0, w2), (w1, w3), (w2, w3), (w0, w4)]</b>.
- **Return:** _list(tuple([carla.Waypoint](#carla.Waypoint), [carla.Waypoint](#carla.Waypoint)))_
- <a name="carla.Map.get_waypoint"></a>**<font color="#7fb800">get_waypoint</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**location**</font>, <font color="#00a6ed">**project_to_road**=True</font>, <font color="#00a6ed">**lane_type**=[carla.LaneType.Driving](#carla.LaneType.Driving)</font>)
- <a name="carla.Map.get_waypoint"></a>**<font color="#7fb800">get_waypoint</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**location**</font>, <font color="#00a6ed">**project_to_road**=True</font>, <font color="#00a6ed">**lane_type**=[carla.LaneType.Driving](#carla.LaneType.Driving)</font>)<button class="SnipetButton" id="carla.Map.get_waypoint-snipet_button">snipet &rarr;</button>
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 as `LaneType.Driving & LaneType.Shoulder`.
The method will return <b>None</b> 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:**
@ -1423,7 +1422,7 @@ Returns a waypoint if all the parameters passed are correct. Otherwise, returns
---
## carla.ObstacleDetectionEvent<a name="carla.ObstacleDetectionEvent"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the obstacle data for <b>sensor.other.obstacle</b>. Learn more about this [here](ref_sensors.md#obstacle-detector).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the obstacle data for <b>sensor.other.obstacle</b>. Learn more about this [here](ref_sensors.md#obstacle-detector).
<h3>Instance Variables</h3>
- <a name="carla.ObstacleDetectionEvent.actor"></a>**<font color="#f8805a">actor</font>** (_[carla.Actor](#carla.Actor)_)
@ -1512,7 +1511,7 @@ The velocity of the detected object towards the sensor.
---
## carla.RadarMeasurement<a name="carla.RadarMeasurement"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines and gathers the measures registered by a <b>sensor.other.radar</b>, representing a wall of points in front of the sensor with a distance, angle and velocity in relation to it. The data consists of a [carla.RadarDetection](#carla.RadarDetection) array. Learn more about this [here](ref_sensors.md#radar-sensor).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines and gathers the measures registered by a <b>sensor.other.radar</b>, representing a wall of points in front of the sensor with a distance, angle and velocity in relation to it. The data consists of a [carla.RadarDetection](#carla.RadarDetection) array. Learn more about this [here](ref_sensors.md#radar-sensor).
<h3>Instance Variables</h3>
- <a name="carla.RadarMeasurement.raw_data"></a>**<font color="#f8805a">raw_data</font>** (_bytes_)
@ -1678,7 +1677,7 @@ Enum declaration used in [carla.RssSensor](#carla.RssSensor) to set the log leve
---
## carla.RssResponse<a name="carla.RssResponse"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that contains the output of a [carla.RssSensor](#carla.RssSensor). This is the result of the RSS calculations performed for the parent vehicle of the sensor.
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that contains the output of a [carla.RssSensor](#carla.RssSensor). This is the result of the RSS calculations performed for the parent vehicle of the sensor.
A [carla.RssRestrictor](#carla.RssRestrictor) will use the data to modify the [carla.VehicleControl](#carla.VehicleControl) of the vehicle.
@ -1730,7 +1729,7 @@ Disables the _stay on road_ feature.
---
## carla.RssSensor<a name="carla.RssSensor"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Sensor](#carla.Sensor)_</b></small></div></p><p>This sensor works a bit differently than the rest. Take look at the [specific documentation](adv_rss.md), and the [rss sensor reference](ref_sensors.md#rss-sensor) to gain full understanding of it.
<div class="Inherited"><small><b>Inherited from _[carla.Sensor](#carla.Sensor)_</b></small></div></p><p>This sensor works a bit differently than the rest. Take look at the [specific documentation](adv_rss.md), and the [rss sensor reference](ref_sensors.md#rss-sensor) to gain full understanding of it.
The RSS sensor uses world information, and a [RSS library](https://github.com/intel/ad-rss-lib) to make safety checks on a vehicle. The output retrieved by the sensor is a [carla.RssResponse](#carla.RssResponse). This will be used by a [carla.RssRestrictor](#carla.RssRestrictor) to modify a [carla.VehicleControl](#carla.VehicleControl) before applying it to a vehicle.
@ -1796,7 +1795,7 @@ ID of the actor hit by the ray.
---
## carla.SemanticLidarMeasurement<a name="carla.SemanticLidarMeasurement"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the semantic LIDAR data retrieved by a <b>sensor.lidar.ray_cast_semantic</b>. This essentially simulates a rotating LIDAR using ray-casting. Learn more about this [here](ref_sensors.md#semanticlidar-raycast-sensor).
<div class="Inherited"><small><b>Inherited from _[carla.SensorData](#carla.SensorData)_</b></small></div></p><p>Class that defines the semantic LIDAR data retrieved by a <b>sensor.lidar.ray_cast_semantic</b>. This essentially simulates a rotating LIDAR using ray-casting. Learn more about this [here](ref_sensors.md#semanticlidar-raycast-sensor).
<h3>Instance Variables</h3>
- <a name="carla.SemanticLidarMeasurement.channels"></a>**<font color="#f8805a">channels</font>** (_int_)
@ -1829,7 +1828,7 @@ Iterate over the [carla.SemanticLidarDetection](#carla.SemanticLidarDetection) r
---
## carla.Sensor<a name="carla.Sensor"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>Sensors compound a specific family of actors quite diverse and unique. They are normally spawned as attachment/sons of a vehicle (take a look at [carla.World](#carla.World) to learn about actor spawning). Sensors are thoroughly designed to retrieve different types of data that they are listening to. The data they receive is shaped as different subclasses inherited from [carla.SensorData](#carla.SensorData) (depending on the sensor).
<div class="Inherited"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>Sensors compound a specific family of actors quite diverse and unique. They are normally spawned as attachment/sons of a vehicle (take a look at [carla.World](#carla.World) to learn about actor spawning). Sensors are thoroughly designed to retrieve different types of data that they are listening to. The data they receive is shaped as different subclasses inherited from [carla.SensorData](#carla.SensorData) (depending on the 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](#carla.BlueprintLibrary). All the information on their preferences and settlement can be found [here](ref_sensors.md), but the list of those available in CARLA so far goes as follow.
<br><b>Receive data on every tick.</b>
@ -1852,7 +1851,7 @@ Iterate over the [carla.SemanticLidarDetection](#carla.SemanticLidarDetection) r
When <b>True</b> the sensor will be waiting for data.
<h3>Methods</h3>
- <a name="carla.Sensor.listen"></a>**<font color="#7fb800">listen</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**callback**</font>)
- <a name="carla.Sensor.listen"></a>**<font color="#7fb800">listen</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**callback**</font>)<button class="SnipetButton" id="carla.Sensor.listen-snipet_button">snipet &rarr;</button>
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](#carla.SensorData) to work with.
- **Parameters:**
- `callback` (_function_) The called function with one argument containing the sensor data.
@ -1916,9 +1915,9 @@ Time register of the frame at which this measurement was taken given by the OS i
---
## carla.TrafficLight<a name="carla.TrafficLight"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.TrafficSign](#carla.TrafficSign)_</b></small></div></p><p>A traffic light actor, considered a specific type of traffic sign. As traffic lights will mostly appear at junctions, they belong to a group which contains the different traffic lights in it. Inside the group, traffic lights are differenciated by their pole index.
<div class="Inherited"><small><b>Inherited from _[carla.TrafficSign](#carla.TrafficSign)_</b></small></div></p><p>A traffic light actor, considered a specific type of traffic sign. As traffic lights will mostly appear at junctions, they belong to a group which contains the different traffic lights in it. Inside the group, traffic lights are differenciated by their pole index.
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. Take a look at this [recipe](ref_code_recipes.md#traffic-lights-recipe) to learn how to do so.
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.
<h3>Instance Variables</h3>
- <a name="carla.TrafficLight.state"></a>**<font color="#f8805a">state</font>** (_[carla.TrafficLightState](#carla.TrafficLightState)_)
@ -1967,7 +1966,7 @@ The client returns the time set for the traffic light to be yellow, according to
- **Setter:** _[carla.TrafficLight.set_yellow_time](#carla.TrafficLight.set_yellow_time)_
<h5 style="margin-top: -20px">Setters</h5>
<div style="padding-left:30px;margin-top:-25px"></div>- <a name="carla.TrafficLight.set_state"></a>**<font color="#7fb800">set_state</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**state**</font>)
<div style="padding-left:30px;margin-top:-25px"></div>- <a name="carla.TrafficLight.set_state"></a>**<font color="#7fb800">set_state</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**state**</font>)<button class="SnipetButton" id="carla.TrafficLight.set_state-snipet_button">snipet &rarr;</button>
Sets a given state to a traffic light actor.
- **Parameters:**
- `state` (_[carla.TrafficLightState](#carla.TrafficLightState)_)
@ -1993,7 +1992,7 @@ Sets a given time for the yellow light to be active.
---
## carla.TrafficLightState<a name="carla.TrafficLightState"></a>
All possible states for traffic lights. These can either change at a specific time step or be changed manually. Take a look at this [recipe](ref_code_recipes.md#traffic-lights-recipe) to see an example.
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](#carla.TrafficLight.set_state) changes the state of a traffic light on the fly.
<h3>Instance Variables</h3>
- <a name="carla.TrafficLightState.Red"></a>**<font color="#f8805a">Red</font>**
@ -2085,7 +2084,7 @@ Enables or disables the OSM mode. This mode allows the user to run TM in a map c
---
## carla.TrafficSign<a name="carla.TrafficSign"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>Traffic signs appearing in the simulation except for traffic lights. These have their own class inherited from this in [carla.TrafficLight](#carla.TrafficLight). Right now, speed signs, stops and yields are mainly the ones implemented, but many others are borne in mind.
<div class="Inherited"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>Traffic signs appearing in the simulation except for traffic lights. These have their own class inherited from this in [carla.TrafficLight](#carla.TrafficLight). Right now, speed signs, stops and yields are mainly the ones implemented, but many others are borne in mind.
<h3>Instance Variables</h3>
- <a name="carla.TrafficSign.trigger_volume"></a>**<font color="#f8805a">trigger_volume</font>**
@ -2210,7 +2209,7 @@ Returns the axis values for the vector parsed as string.
---
## carla.Vehicle<a name="carla.Vehicle"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>One of the most important group of actors in CARLA. These include any type of vehicle from cars to trucks, motorbikes, vans, bycicles and also official vehicles such as police cars. A wide set of these actors is provided in [carla.BlueprintLibrary](#carla.BlueprintLibrary) to facilitate differente requirements. Vehicles can be either manually controlled or set to an autopilot mode that will be conducted client-side by the <b>traffic manager</b>.
<div class="Inherited"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>One of the most important group of actors in CARLA. These include any type of vehicle from cars to trucks, motorbikes, vans, bycicles and also official vehicles such as police cars. A wide set of these actors is provided in [carla.BlueprintLibrary](#carla.BlueprintLibrary) to facilitate differente requirements. Vehicles can be either manually controlled or set to an autopilot mode that will be conducted client-side by the <b>traffic manager</b>.
<h3>Instance Variables</h3>
- <a name="carla.Vehicle.bounding_box"></a>**<font color="#f8805a">bounding_box</font>** (_[carla.BoundingBox](#carla.BoundingBox)_)
@ -2394,7 +2393,7 @@ VehiclePhysicsControl constructor.
---
## carla.Walker<a name="carla.Walker"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>This class inherits from the [carla.Actor](#carla.Actor) and defines pedestrians in the simulation. Walkers are a special type of actor that can be controlled either by an AI ([carla.WalkerAIController](#carla.WalkerAIController)) or manually via script, using a series of [carla.WalkerControl](#carla.WalkerControl) to move these and their skeletons.
<div class="Inherited"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>This class inherits from the [carla.Actor](#carla.Actor) and defines pedestrians in the simulation. Walkers are a special type of actor that can be controlled either by an AI ([carla.WalkerAIController](#carla.WalkerAIController)) or manually via script, using a series of [carla.WalkerControl](#carla.WalkerControl) to move these and their skeletons.
<h3>Instance Variables</h3>
- <a name="carla.Walker.bounding_box"></a>**<font color="#f8805a">bounding_box</font>** (_[carla.BoundingBox](#carla.BoundingBox)_)
@ -2421,7 +2420,7 @@ The client returns the control applied to this walker during last tick. The meth
---
## carla.WalkerAIController<a name="carla.WalkerAIController"></a>
<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>Class that conducts AI control for a walker. The controllers are defined as actors, but they are quite different from the rest. They need to be attached to a parent actor during their creation, which is the walker they will be controlling (take a look at [carla.World](#carla.World) if you are yet to learn on how to spawn actors). They also need for a special blueprint (already defined in [carla.BlueprintLibrary](#carla.BlueprintLibrary) as "controller.ai.walker"). This is an empty blueprint, as the AI controller will be invisible in the simulation but will follow its parent around to dictate every step of the way.
<div class="Inherited"><small><b>Inherited from _[carla.Actor](#carla.Actor)_</b></small></div></p><p>Class that conducts AI control for a walker. The controllers are defined as actors, but they are quite different from the rest. They need to be attached to a parent actor during their creation, which is the walker they will be controlling (take a look at [carla.World](#carla.World) if you are yet to learn on how to spawn actors). They also need for a special blueprint (already defined in [carla.BlueprintLibrary](#carla.BlueprintLibrary) as "controller.ai.walker"). This is an empty blueprint, as the AI controller will be invisible in the simulation but will follow its parent around to dictate every step of the way.
<h3>Methods</h3>
- <a name="carla.WalkerAIController.go_to_location"></a>**<font color="#7fb800">go_to_location</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**destination**</font>)
@ -2430,7 +2429,7 @@ Sets the destination that the pedestrian will reach.
- `destination` (_[carla.Location](#carla.Location)<small> meters</small>_)
- <a name="carla.WalkerAIController.start"></a>**<font color="#7fb800">start</font>**(<font color="#00a6ed">**self**</font>)
Enables AI control for its parent walker.
- <a name="carla.WalkerAIController.stop"></a>**<font color="#7fb800">stop</font>**(<font color="#00a6ed">**self**</font>)
- <a name="carla.WalkerAIController.stop"></a>**<font color="#7fb800">stop</font>**(<font color="#00a6ed">**self**</font>)<button class="SnipetButton" id="carla.WalkerAIController.stop-snipet_button">snipet &rarr;</button>
Disables AI control for its parent walker.
<h5 style="margin-top: -20px">Setters</h5>
@ -2702,7 +2701,7 @@ This method is used in [__asynchronous__ mode](https://[carla.readthedocs.io](#c
- **Parameters:**
- `seconds` (_float<small> seconds</small>_) Maximum time the server should wait for a tick. It is set to <code>10.0</code> by default.
- **Return:** _[carla.WorldSnapshot](#carla.WorldSnapshot)_
- <a name="carla.World.spawn_actor"></a>**<font color="#7fb800">spawn_actor</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**blueprint**</font>, <font color="#00a6ed">**transform**</font>, <font color="#00a6ed">**attach_to**=None</font>, <font color="#00a6ed">**attachment**=Rigid</font>)
- <a name="carla.World.spawn_actor"></a>**<font color="#7fb800">spawn_actor</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**blueprint**</font>, <font color="#00a6ed">**transform**</font>, <font color="#00a6ed">**attach_to**=None</font>, <font color="#00a6ed">**attachment**=Rigid</font>)<button class="SnipetButton" id="carla.World.spawn_actor-snipet_button">snipet &rarr;</button>
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](#carla.ActorBlueprint)_) The reference from which the actor will be created.
@ -2774,7 +2773,7 @@ Returns an object containing some data about the simulation such as synchrony be
- <a name="carla.World.get_snapshot"></a>**<font color="#7fb800">get_snapshot</font>**(<font color="#00a6ed">**self**</font>)
Returns a snapshot of the world at a certain moment comprising all the information about the actors.
- **Return:** _[carla.WorldSnapshot](#carla.WorldSnapshot)_
- <a name="carla.World.get_spectator"></a>**<font color="#7fb800">get_spectator</font>**(<font color="#00a6ed">**self**</font>)
- <a name="carla.World.get_spectator"></a>**<font color="#7fb800">get_spectator</font>**(<font color="#00a6ed">**self**</font>)<button class="SnipetButton" id="carla.World.get_spectator-snipet_button">snipet &rarr;</button>
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](#carla.Actor)_
- <a name="carla.World.get_weather"></a>**<font color="#7fb800">get_weather</font>**(<font color="#00a6ed">**self**</font>)
@ -3148,4 +3147,480 @@ Links another command to be executed right after. It allows to ease very common
- **Parameters:**
- `command` (_any carla Command_) a Carla command.
---
---
[comment]: <> (=========================)
[comment]: <> (PYTHON API SCRIPT SNIPETS)
[comment]: <> (=========================)
<div id="snipets-container" class="Container" onmouseover='this.style["overflowX"]="scroll";' onmouseout='this.style["overflowX"]="visible";'></div>
<script>
function CopyToClipboard(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
}
}
</script>
<script>
function CloseSnipet() {
document.getElementById("snipets-container").innerHTML = null;
}
</script>
<div id ="carla.Map.get_waypoint-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.Map.get_waypoint
</p>
<div id="carla.Map.get_waypoint-code" class="SnipetContent">
```py
# 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))
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.Map.get_waypoint-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
<img src="/img/snipets_images/carla.Map.get_waypoint.jpg">
</div>
<div id ="carla.Sensor.listen-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.Sensor.listen
</p>
<div id="carla.Sensor.listen-code" class="SnipetContent">
```py
# 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))
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.Sensor.listen-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
<div id ="carla.World.spawn_actor-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.World.spawn_actor
</p>
<div id="carla.World.spawn_actor-code" class="SnipetContent">
```py
# 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)
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.spawn_actor-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
<div id ="carla.ActorBlueprint.set_attribute-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.ActorBlueprint.set_attribute
</p>
<div id="carla.ActorBlueprint.set_attribute-code" class="SnipetContent">
```py
# 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)
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.ActorBlueprint.set_attribute-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
<div id ="carla.World.get_spectator-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.World.get_spectator
</p>
<div id="carla.World.get_spectator-code" class="SnipetContent">
```py
# 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())
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.get_spectator-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
<div id ="carla.DebugHelper.draw_line-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.DebugHelper.draw_line
</p>
<div id="carla.DebugHelper.draw_line-code" class="SnipetContent">
```py
# 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)
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.DebugHelper.draw_line-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
<img src="/img/snipets_images/carla.DebugHelper.draw_line.jpg">
</div>
<div id ="carla.DebugHelper.draw_box-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.DebugHelper.draw_box
</p>
<div id="carla.DebugHelper.draw_box-code" class="SnipetContent">
```py
# 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)
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.DebugHelper.draw_box-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
<img src="/img/snipets_images/carla.DebugHelper.draw_box.jpg">
</div>
<div id ="carla.TrafficLight.set_state-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.TrafficLight.set_state
</p>
<div id="carla.TrafficLight.set_state-code" class="SnipetContent">
```py
# 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)
# ...
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.TrafficLight.set_state-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
<img src="/img/snipets_images/carla.TrafficLight.set_state.gif">
</div>
<div id ="carla.Client.apply_batch_sync-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.Client.apply_batch_sync
</p>
<div id="carla.Client.apply_batch_sync-code" class="SnipetContent">
```py
# 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)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.Client.apply_batch_sync-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
<div id ="carla.WalkerAIController.stop-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.WalkerAIController.stop
</p>
<div id="carla.WalkerAIController.stop-code" class="SnipetContent">
```py
#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])
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.WalkerAIController.stop-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
<div id ="carla.Client.__init__-snipet" style="display: none;">
<p class="SnipetFont">
Snipet for carla.Client.__init__
</p>
<div id="carla.Client.__init__-code" class="SnipetContent">
```py
# 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)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.Client.__init__-code')">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snipet</button><br><br>
</div>
</div>
<script>
function ButtonAction(container_name){
if(window_big){
snipet_name = container_name.replace('-snipet_button','-snipet');
document.getElementById("snipets-container").innerHTML = document.getElementById(snipet_name).innerHTML;
}
else{
document.getElementById("snipets-container").innerHTML = null;code_name = container_name.replace('-snipet_button','-code');
var range = document.createRange();
range.selectNode(document.getElementById(code_name));
alert(range);
}
}
function WindowResize(){
if(window.innerWidth > 1200){
window_big = true;
}
else{
window_big = false;
}
}
var window_big;
if(window.innerWidth > 1200){
window_big = true;
}
else{
window_big = false;
}
buttons = document.getElementsByClassName('SnipetButton')
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click",function(){ButtonAction(buttons[i].id);},true);
}
window.onresize = WindowResize;
</script>

View File

@ -1,372 +0,0 @@
# Code recipes
This section contains a list of recipes that complement the [first steps](core_concepts.md) section and are used to illustrate the use of Python API methods.
Each recipe has a list of [python API classes](python_api.md),
which is divided into those in which the recipe is centered, and those that need to be used.
There are more recipes to come!
* [__Actor Spectator Recipe__](#actor-spectator-recipe)
* [__Attach Sensors Recipe__](#attach-sensors-recipe)
* [__Actor Attribute Recipe__](#actor-attribute-recipe)
* [__Converted Image Recipe__](#converted-image-recipe)
* [__Lanes Recipe__](#lanes-recipe)
* [__Debug Bounding Box Recipe__](#debug-bounding-box-recipe)
* [__Debug Vehicle Trail Recipe__](#debug-vehicle-trail-recipe)
* [__Parsing Client Arguments Recipe__](#parsing-client-arguments-recipe)
* [__Traffic Light Recipe__](#traffic-light-recipe)
* [__Walker Batch Recipe__](#walker-batch-recipe)
---
## Actor Spectator Recipe
This recipe spawns an actor and the spectator camera at the actor's location.
Focused on:<br>
[`carla.World`](python_api.md#carla.World)<br>
[`carla.Actor`](python_api.md#carla.Actor)
Used:<br>
[`carla.WorldSnapshot`](python_api.md#carla.WorldSnapshot)<br>
[`carla.ActorSnapshot`](python_api.md#carla.ActorSnapshot)
```py
# ...
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())
# ...
```
---
## Attach Sensors Recipe
This recipe attaches different camera / sensors to a vehicle with different attachments.
Focused on:<br>
[`carla.Sensor`](python_api.md#carla.Sensor)<br>
[`carla.AttachmentType`](python_api.md#carla.AttachmentType)<br>
Used:<br>
[`carla.World`](python_api.md#carla.World)
```py
# ...
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)
# ...
```
---
## Actor Attribute Recipe
This recipe changes attributes of different type of blueprint actors.
Focused on:<br>
[`carla.ActorAttribute`](python_api.md#carla.ActorAttribute)<br>
[`carla.ActorBlueprint`](python_api.md#carla.ActorBlueprint)<br>
Used:<br>
[`carla.World`](python_api.md#carla.World)<br>
[`carla.BlueprintLibrary`](python_api.md#carla.BlueprintLibrary)<br>
```py
# ...
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)
# ...
```
---
## Converted Image Recipe
This recipe applies a color conversion to the image taken by a camera sensor,
so it is converted to a semantic segmentation image.
Focused on:<br>
[`carla.ColorConverter`](python_api.md#carla.ColorConverter)<br>
[`carla.Sensor`](python_api.md#carla.Sensor)
```py
# ...
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))
# ...
```
---
## Lanes Recipe
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.
Focused on:<br>
[`carla.LaneMarking`](python_api.md#carla.LaneMarking)<br>
[`carla.LaneMarkingType`](python_api.md#carla.LaneMarkingType)<br>
[`carla.LaneChange`](python_api.md#carla.LaneChange)<br>
[`carla.LaneType`](python_api.md#carla.LaneType)<br>
Used:<br>
[`carla.Waypoint`](python_api.md#carla.Waypoint)<br>
[`carla.World`](python_api.md#carla.World)
```py
# ...
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))
# ...
```
![lane_marking_recipe](img/recipe_lane_marking.jpg)
---
## Debug Bounding Box Recipe
This recipe shows how to draw traffic light actor bounding boxes from a world snapshot.
Focused on:<br>
[`carla.DebugHelper`](python_api.md#carla.DebugHelper)<br>
[`carla.BoundingBox`](python_api.md#carla.BoundingBox)
Used:<br>
[`carla.ActorSnapshot`](python_api.md#carla.ActorSnapshot)<br>
[`carla.Actor`](python_api.md#carla.Actor)<br>
[`carla.Vector3D`](python_api.md#carla.Vector3D)<br>
[`carla.Color`](python_api.md#carla.Color)
```py
# ....
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)
# ...
```
![debug_bb_recipe](img/recipe_debug_bb.jpg)
---
## Debug Vehicle Trail Recipe
This recipe is a modification of
[`lane_explorer.py`](https://github.com/carla-simulator/carla/blob/master/PythonAPI/util/lane_explorer.py) example.
It draws the path of an actor through the world, printing information at each waypoint.
Focused on:<br>
[`carla.DebugHelper`](python_api.md#carla.DebugHelper)<br>
[`carla.Waypoint`](python_api.md#carla.Waypoint)<br>
[`carla.Actor`](python_api.md#carla.Actor)
Used:<br>
[`carla.ActorSnapshot`](python_api.md#carla.ActorSnapshot)<br>
[`carla.Vector3D`](python_api.md#carla.Vector3D)<br>
[`carla.LaneType`](python_api.md#carla.LaneType)<br>
[`carla.Color`](python_api.md#carla.Color)<br>
[`carla.Map`](python_api.md#carla.Map)
```py
# ...
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)
# ...
```
The image below shows how a vehicle loses control and drives on a sidewalk. The trail shows the
path it was following and the speed at each waypoint.
![debug_trail_recipe](img/recipe_debug_trail.jpg)
---
## Parsing Client Arguments Recipe
This recipe shows in every script provided in `PythonAPI/Examples` and it is used to parse the client creation arguments when running the script.
Focused on:<br>
[`carla.Client`](python_api.md#carla.Client)<br>
Used:<br>
[`carla.Client`](python_api.md#carla.Client)
```py
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)
```
---
## Traffic Light Recipe
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.
Focused on:<br>
[`carla.TrafficLight`](python_api.md#carla.TrafficLight)<br>
[`carla.TrafficLightState`](python_api.md#carla.TrafficLightState)
Used:<br>
[`carla.Vehicle`](python_api.md#carla.Vehicle)
```py
# ...
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)
# ...
```
![tl_recipe](img/tl_recipe.gif)
---
## Walker Batch Recipe
```py
# 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)
```
To **destroy the pedestrians**, stop them from the navigation, and then destroy the objects (actor and controller):
```py
# 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])
```

View File

@ -387,7 +387,7 @@
- class_name: TrafficLightState
# - DESCRIPTION ------------------------
doc: >
All possible states for traffic lights. These can either change at a specific time step or be changed manually. Take a look at this [recipe](ref_code_recipes.md#traffic-lights-recipe) to see an example.
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.
# - PROPERTIES -------------------------
instance_variables:
- var_name: Red
@ -403,7 +403,7 @@
doc: >
A traffic light actor, considered a specific type of traffic sign. As traffic lights will mostly appear at junctions, they belong to a group which contains the different traffic lights in it. Inside the group, traffic lights are differenciated by their pole index.
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. Take a look at this [recipe](ref_code_recipes.md#traffic-lights-recipe) to learn how to do so.
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.
# - PROPERTIES -------------------------
instance_variables:
- var_name: state

View File

@ -10,6 +10,7 @@
import os
import yaml
import re
import doc_gen_snipets
COLOR_METHOD = '#7fb800'
COLOR_PARAM = '#00a6ed'
@ -35,7 +36,7 @@ class MarkdownFile:
self._data = ""
self._list_depth = 0
self.endl = ' \n'
def data(self):
return self._data
@ -77,9 +78,7 @@ class MarkdownFile:
self._data, '#Python API reference\n'])
def button_apis(self):
self._data = join([
self._data,
''])
self._data = join([self._data, ''])
def title(self, strongness, buf):
self._data = join([
@ -95,7 +94,7 @@ class MarkdownFile:
def inherit_join(self, inh):
self._data = join([
self._data,'<div style="padding-left:30px;margin-top:-20px"><small><b>Inherited from ',inh,'</b></small></div></p><p>'])
self._data,'<div class="Inherited"><small><b>Inherited from ',inh,'</b></small></div></p><p>'])
def note(self, buf):
self._data = join([self._data, buf])
@ -117,6 +116,9 @@ def italic(buf):
def bold(buf):
return join(['**', buf, '**'])
def snipet(name,class_key):
return join(["<button class=\"SnipetButton\" id=\"",class_key,".",name,"-snipet_button\">", "snipet &rarr;", '</button>'])
def code(buf):
return join(['`', buf, '`'])
@ -221,6 +223,52 @@ class YamlFile:
def get_modules(self):
return [module for module in self.data]
def append_snipet_button_script(md):
md.textn("\n\n<script>\n"+
"function ButtonAction(container_name){\n"+
"if(window_big){\n"+
"snipet_name = container_name.replace('-snipet_button','-snipet');\n"+
"document.getElementById(\"snipets-container\").innerHTML = document.getElementById(snipet_name).innerHTML;\n"+
"}\n"+
"else{\n"+
"document.getElementById(\"snipets-container\").innerHTML = null;"+
"code_name = container_name.replace('-snipet_button','-code');\n"+
"var range = document.createRange();\n"+
"range.selectNode(document.getElementById(code_name));\n"+
"alert(range);\n"+
"}\n"+
"}\n"+
"function WindowResize(){\n"+
"if(window.innerWidth > 1200){\n"+
"window_big = true;\n"+
"}\n"+
"else{\n"+
"window_big = false;\n"+
"}\n"+
"}\n"+
"var window_big;\n"+
"if(window.innerWidth > 1200){\n"+
"window_big = true;\n"+
"}\n"+
"else{\n"+
"window_big = false;\n"+
"}\n"+
"buttons = document.getElementsByClassName('SnipetButton')\n"+
"for (let i = 0; i < buttons.length; i++) {\n"+
"buttons[i].addEventListener(\"click\",function(){ButtonAction(buttons[i].id);},true);\n"+
"}\n"+
"window.onresize = WindowResize;\n"+
"</script>\n")
def append_code_snipets(md):
current_folder = os.path.dirname(os.path.abspath(__file__))
snipets_path = os.path.join(current_folder, '../../Docs/python_api_snipets.md')
snipets = open(snipets_path, 'r')
md.text(snipets.read())
os.remove(snipets_path)
def gen_stub_method_def(method):
"""Return python def as it should be written in stub files"""
@ -235,14 +283,16 @@ def gen_stub_method_def(method):
return join([method_name, parentheses(param), return_type])
def gen_doc_method_def(method, is_indx=False, with_self=True):
def gen_doc_method_def(method, class_key, is_indx=False, with_self=True):
"""Return python def as it should be written in docs"""
param = ''
snipet_link = ''
method_name = method['def_name']
full_method_name = method_name
if valid_dic_val(method, 'static'):
with_self = False
# to correclty render methods like __init__ in md
# to correctly render methods like __init__ in md
if method_name[0] == '_':
method_name = '\\' + method_name
if is_indx:
@ -269,7 +319,15 @@ def gen_doc_method_def(method, is_indx=False, with_self=True):
del method['params']
param = param[:-2] # delete the last ', '
return join([method_name, parentheses(param)])
# Add snipet
current_folder = os.path.dirname(os.path.abspath(__file__))
snipets_path = os.path.join(current_folder, '../../Docs/python_api_snipets.md')
snipets = open(snipets_path, 'r')
if class_key+'.'+full_method_name+'-snipet' in snipets.read():
snipet_link = snipet(full_method_name, class_key)
return join([method_name, parentheses(param),snipet_link])
def gen_doc_dunder_def(dunder, is_indx=False, with_self=True):
"""Return python def as it should be written in docs"""
@ -278,7 +336,7 @@ def gen_doc_dunder_def(dunder, is_indx=False, with_self=True):
if valid_dic_val(dunder, 'static'):
with_self = False
# to correclty render methods like __init__ in md
# to correctly render methods like __init__ in md
if dunder_name[0] == '_':
dunder_name = '\\' + dunder_name
if is_indx:
@ -320,7 +378,7 @@ def gen_inst_var_indx(inst_var, class_key):
def gen_method_indx(method, class_key):
method_name = method['def_name']
method_key = join([class_key, method_name], '.')
method_def = gen_doc_method_def(method, True)
method_def = gen_doc_method_def(method, class_key, True)
return join([
brackets(method_def),
parentheses(method_key), ' ',
@ -352,7 +410,7 @@ def add_doc_method_param(md, param):
def add_doc_method(md, method, class_key):
method_name = method['def_name']
method_key = join([class_key, method_name], '.')
method_def = gen_doc_method_def(method, False)
method_def = gen_doc_method_def(method, class_key, False)
md.list_pushn(join([html_key(method_key), method_def]))
# Method doc
@ -403,10 +461,10 @@ def add_doc_method(md, method, class_key):
md.list_pop()
def add_doc_getter_setter(md, method,class_key,is_getter,other_list):
def add_doc_getter_setter(md, method, class_key, is_getter, other_list):
method_name = method['def_name']
method_key = join([class_key, method_name], '.')
method_def = gen_doc_method_def(method, False)
method_def = gen_doc_method_def(method, class_key, False)
md.list_pushn(join([html_key(method_key), method_def]))
# Method doc
@ -535,7 +593,6 @@ def add_doc_inst_var(md, inst_var, class_key):
md.list_pop()
class Documentation:
"""Main documentation class"""
@ -644,16 +701,18 @@ class Documentation:
if len(get_list)>0:
md.title_html(5, 'Getters')
for method in get_list:
add_doc_getter_setter(md, method,class_key,True,set_list)
add_doc_getter_setter(md, method, class_key, True, set_list)
if len(set_list)>0:
md.title_html(5, 'Setters')
for method in set_list:
add_doc_getter_setter(md, method,class_key,False,get_list)
add_doc_getter_setter(md, method, class_key, False, get_list)
if len(dunder_list)>0:
md.title_html(5, 'Dunder methods')
for method in dunder_list:
add_doc_dunder(md, method, class_key)
md.separator()
append_code_snipets(md)
append_snipet_button_script(md)
return md.data().strip()
def gen_markdown(self):
@ -665,6 +724,7 @@ def main():
"""Main function"""
print("Generating PythonAPI documentation...")
script_path = os.path.dirname(os.path.abspath(__file__))
doc_gen_snipets.main()
docs = Documentation(script_path)
with open(os.path.join(script_path, '../../Docs/python_api.md'), 'w') as md_file:
md_file.write(docs.gen_markdown())

146
PythonAPI/docs/doc_gen_snipets.py Executable file
View File

@ -0,0 +1,146 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import os
import yaml
import re
COLOR_METHOD = '#7fb800'
COLOR_PARAM = '#00a6ed'
COLOR_INSTANCE_VAR = '#f8805a'
COLOR_NOTE = '#8E8E8E'
COLOR_WARNING = '#ED2F2F'
QUERY = re.compile(r'([cC]arla(\.[a-zA-Z0-9_]+)+)')
def create_hyperlinks(text):
return re.sub(QUERY, r'[\1](#\1)', text)
def create_getter_setter_hyperlinks(text):
return re.sub(QUERY, r'[\1](#\1)', text)
def join(elem, separator=''):
return separator.join(elem)
class MarkdownFile:
def __init__(self):
self._data = ""
self._list_depth = 0
self.endl = ' \n'
def data(self):
return self._data
def list_depth(self):
if self._data.strip()[-1:] != '\n' or self._list_depth == 0:
return ''
return join([' ' * self._list_depth])
def textn(self, buf):
self._data = join([self._data, self.list_depth(), buf, self.endl])
class Documentation:
"""Main documentation class"""
def __init__(self, path, images_path):
self._snipets_path = os.path.join(os.path.dirname(path), 'snipets')
self._files = [f for f in os.listdir(self._snipets_path) if f.endswith('.py')]
self._snipets = list()
for snipet_file in self._files:
current_snipet_path = os.path.join(self._snipets_path, snipet_file)
self._snipets.append(current_snipet_path)
# Gather snipet images
self._snipets_images_path = images_path
self._files_images = [f for f in os.listdir(self._snipets_images_path)]
self._snipets_images = list()
for snipet_image in self._files_images:
current_image_path = os.path.join(self._snipets_images_path, snipet_image)
self._snipets_images.append(current_image_path)
def gen_body(self):
"""Generates the documentation body"""
md = MarkdownFile()
# Create header for snipets (div container and script to copy)
md.textn(
"[comment]: <> (=========================)\n"+
"[comment]: <> (PYTHON API SCRIPT SNIPETS)\n"+
"[comment]: <> (=========================)\n"+
"<div id=\"snipets-container\" class=\"Container\" onmouseover='this.style[\"overflowX\"]=\"scroll\";' onmouseout='this.style[\"overflowX\"]=\"visible\";'></div>\n"+
"<script>\n"+
"function CopyToClipboard(containerid) {\n"+
"if (document.selection) {\n"+
"var range = document.body.createTextRange();\n"+
"range.moveToElementText(document.getElementById(containerid));\n"+
"range.select().createTextRange();\n"+
"document.execCommand(\"copy\");\n"+
"} \n"+
"else if (window.getSelection) {\n"+
"var range = document.createRange();\n"+
"range.selectNode(document.getElementById(containerid));\n"+
"window.getSelection().addRange(range);\n"+
"document.execCommand(\"copy\");\n"+
"}\n"+
"}\n</script>\n"+
"<script>\n"+
"function CloseSnipet() {\n"+
"document.getElementById(\"snipets-container\").innerHTML = null;\n"+
"}\n"+
"</script>\n")
# Create content for every snipet
for snipet_path in self._snipets:
current_snipet = open(snipet_path, 'r')
snipet_name = os.path.basename(current_snipet.name) # Remove path
snipet_name = os.path.splitext(snipet_name)[0] # Remove extension
# Header for a snipet
md.textn("<div id =\""+snipet_name+"-snipet\" style=\"display: none;\">\n"+
"<p class=\"SnipetFont\">\n"+
"Snipet for "+snipet_name+"\n"+
"</p>\n"+
"<div id=\""+snipet_name+"-code\" class=\"SnipetContent\">\n\n```py\n")
# The snipet code
md.textn(current_snipet.read())
# Closing for a snipet
md.textn("\n```\n<button id=\"button1\" class=\"CopyScript\" onclick=\"CopyToClipboard('"+snipet_name+"-code')\">Copy snipet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id=\"button1\" class=\"CloseSnipet\" onclick=\"CloseSnipet()\">Close snipet</button><br><br>\n")
# Check if snipet image exists, and add it
for snipet_path_to_image in self._snipets_images:
snipet_image_name = os.path.splitext(os.path.basename(snipet_path_to_image))[0]
if snipet_name == snipet_image_name:
md.textn("\n<img src=\"/img/snipets_images/"+os.path.basename(snipet_path_to_image)+"\">\n")
md.textn("</div>\n")
# Closing div
md.textn("\n</div>\n")
return md.data().strip()
def gen_markdown(self):
"""Generates the whole markdown file"""
return join([self.gen_body()], '\n').strip()
def main():
"""Main function"""
print("Generating PythonAPI snipets...")
script_path = os.path.dirname(os.path.abspath(__file__)+'/snipets')
snipets_images_path = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))) + '/Docs/img/snipets_images'
docs = Documentation(script_path, snipets_images_path)
snipets_md_path = os.path.join(os.path.dirname(os.path.dirname(
os.path.dirname(script_path))), 'Docs/python_api_snipets.md')
with open(snipets_md_path, 'w') as md_file:
md_file.write(docs.gen_markdown())
print("Done snipets!")
if __name__ == "__main__":
main()

View File

@ -383,7 +383,7 @@
- class_name: BoundingBox
# - DESCRIPTION ------------------------
doc: >
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 this [recipe](ref_code_recipes.md#debug-bounding-box-recipe) where the user takes a snapshot of the world and then proceeds to draw bounding boxes for traffic lights.
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.
# - PROPERTIES -------------------------
instance_variables:
- var_name: extent

View File

@ -5,7 +5,7 @@
- class_name: LaneType
# - DESCRIPTION ------------------------
doc: >
Class that defines the possible lane types accepted by OpenDRIVE 1.4. This standards define the road information. For instance in this [recipe](ref_code_recipes.md#lanes-recipe) the user creates a carla.Waypoint for the current location of a vehicle and uses it to get the current and adjacent lane types.
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.
# - PROPERTIES -------------------------
instance_variables:
- var_name: NONE
@ -57,7 +57,7 @@
- class_name: LaneChange
# - DESCRIPTION ------------------------
doc: >
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. In this [recipe](ref_code_recipes.md#lanes-recipe) the user creates a waypoint for a current vehicle position and learns which turns are permitted.
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.
# - PROPERTIES -------------------------
instance_variables:
- var_name: NONE
@ -98,8 +98,8 @@
- class_name: LaneMarkingType
# - DESCRIPTION ------------------------
doc: >
Class that defines the lane marking types accepted by OpenDRIVE 1.4. Take a look at this [recipe](ref_code_recipes.md#lanes-recipe) where the user creates a carla.Waypoint for a vehicle location and retrieves from it the information about adjacent lane markings.
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.
<br><br>
__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.
# - PROPERTIES -------------------------
instance_variables:

View File

@ -36,7 +36,7 @@
- class_name: ColorConverter
# - DESCRIPTION ------------------------
doc: >
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 <b>float</b> that is then converted to a grayscale value between 0 and 255. Take a look a this [recipe](ref_code_recipes.md#converted-image-recipe) to see an example of how to create and save image data for <b>sensor.camera.semantic_segmentation</b>.
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 <b>float</b> 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 <b>sensor.camera.semantic_segmentation</b>.
# - PROPERTIES -------------------------
instance_variables:
- var_name: CityScapesPalette

View File

@ -0,0 +1,19 @@
# 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)
# ...

View File

@ -0,0 +1,30 @@
# 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)

View File

@ -0,0 +1,58 @@
# 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)

View File

@ -0,0 +1,13 @@
# 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)
# ...

View File

@ -0,0 +1,24 @@
# 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)
# ...

View File

@ -0,0 +1,15 @@
# 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))
# ...

View File

@ -0,0 +1,10 @@
# 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))
# ...

View File

@ -0,0 +1,28 @@
# 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)
# ...

View File

@ -0,0 +1,9 @@
#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])

View File

@ -0,0 +1,20 @@
# 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())
# ...

View File

@ -0,0 +1,10 @@
# 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)
# ...

View File

@ -174,7 +174,7 @@
- class_name: AttachmentType
# - DESCRIPTION ------------------------
doc: >
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. [Here](ref_code_recipes.md#attach-sensors-recipe) is a brief recipe in which we can see how sensors can be attached to a car when spawned. Note that the attachment type is declared as an enum within the class.
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.
# - PROPERTIES -------------------------
instance_variables:
@ -183,7 +183,7 @@
With this fixed attatchment the object follow its parent position strictly. This is the recommended attachment to retrieve precise data from the simulation.
- var_name: SpringArm
doc: >
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 this out](ref_code_recipes.md#attach-sensors-recipe) to learn some more about them. <br><b style="color:red;">Warning:</b> The <b>SpringArm</b> attachment presents weird behaviors when an actor is spawned with a relative translation in the Z-axis (e.g. <code>child_location = Location(0,0,2)</code>).
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](https://docs.unrealengine.com/en-US/Gameplay/HowTo/UsingCameras/SpringArmComponents/index.html) to learn more about them. <br><b style="color:red;">Warning:</b> The <b>SpringArm</b> attachment presents weird behaviors when an actor is spawned with a relative translation in the Z-axis (e.g. <code>child_location = Location(0,0,2)</code>).
# --------------------------------------
- class_name: World
@ -430,7 +430,7 @@
- class_name: DebugHelper
# - DESCRIPTION ------------------------
doc: >
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. Check out this [recipe](ref_code_recipes.md#debug-bounding-box-recipe) where the user takes a snapshot of the world and then proceeds to draw bounding boxes for traffic lights.
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 ----------------------------
methods:
- def_name: draw_arrow

View File

@ -34,7 +34,6 @@ nav:
- 'Traffic Manager': 'adv_traffic_manager.md'
- References:
- 'Python API reference': 'python_api.md'
- 'Code recipes': 'ref_code_recipes.md'
- 'Blueprint Library': 'bp_library.md'
- 'C++ reference' : 'ref_cpp.md'
- 'Recorder binary file format': 'ref_recorder_binary_file_format.md'
@ -60,7 +59,7 @@ nav:
- "Material customization": 'tuto_A_material_customization.md'
- 'Vehicle modelling': 'tuto_A_vehicle_modelling.md'
- Tutorials (developers):
- 'Contribute with assets': 'tuto_D_contribute_assets.md'
- 'Contribute assets': 'tuto_D_contribute_assets.md'
- 'Create a sensor': 'tuto_D_create_sensor.md'
- 'Create semantic tags': 'tuto_D_create_semantic_tags.md'
- 'Customize vehicle suspension': 'tuto_D_customize_vehicle_suspension.md'