Merge branch 'dev' into patch-2

This commit is contained in:
matejm42 2024-04-23 22:14:54 +02:00 committed by GitHub
commit b8418279ff
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
140 changed files with 3242 additions and 1095 deletions

View File

@ -1,3 +1,20 @@
## Latest Changes
* Prevent from segfault on failing SignalReference identification when loading OpenDrive files
* Added vehicle doors to the recorder
* Added functions to get actor' components transform
* Added posibility to Digital Twins to work with local files (osm and xodr)
* Enable proper material merging for Building in Digital Twins
* Added functions to get actor' bones transforms
* Added functions to get actor' bones and components names
* Added functions to get actor' sockets transforms
* make PythonAPI Windows: Fixed incompatibility issue with Anaconda due `py` command.
* Added function to get actor' sockets names
* Fixed bug in python agents when vehicle list was empty causing a check on all vehicles (BasicAgent.py) and detected pedestrians as vehicles if no pedestrains are present (BehaviourAgent.py)
* Extended debug drawing functions to allow drawing primitives on HUD layer
* Added possibility to change gravity variable in imui sensor for the accelerometer
* Fixed ROS2 native extension build error when ROS2 is installed in the system.
* ROS2Native: Force fast-dds dependencies download to avoid build crash when boost_asio and tinyxml2 are not installed in Linux.
## CARLA 0.9.15
* Added Digital Twins feature version 0.1. Now you can create your own map based on OpenStreetMaps
@ -25,6 +42,8 @@
* Fixed bug causing the `FPixelReader::SavePixelsToDisk(PixelData, FilePath)` function to crash due to pixel array not set correctly.
* Fixed segfaults in Python API due to incorrect GIL locking under Python 3.10.
* Fixed the import script, where could use any other TilesInfo.txt if the destination folder has many
* Fixed PythonAPI not installing on Debian due to deprecated function of distro in setup.py. Less ambiguous error for other posix platforms.
## CARLA 0.9.14

View File

@ -301,7 +301,7 @@ def _get_sumo_net(cfg_file):
net_file = os.path.join(os.path.dirname(cfg_file), tag.get('value'))
logging.debug('Reading net file: %s', net_file)
sumo_net = traci.sumolib.net.readNet(net_file)
sumo_net = sumolib.net.readNet(net_file)
return sumo_net
class SumoSimulation(object):

View File

@ -8,7 +8,7 @@ CARLA has been developed to integrate with several 3rd party applications in ord
- [__Scenic__](tuto_G_scenic.md)
- [__CarSIM__](tuto_G_carsim_integration.md)
- [__Chrono__](tuto_G_chrono.md)
- [__OpenDRIVE__](adv_opendrive.md)
- [__ASAM OpenDRIVE__](adv_opendrive.md)
- [__PTV Vissim__](adv_ptv.md)
- [__RSS__](adv_rss.md)
- [__AWS and RLlib__](tuto_G_rllib_integration.md)
@ -59,9 +59,9 @@ CARLA's integration with CarSim allows vehicle controls in CARLA to be forwarded
Learn how to use CARLA alongside CarSIM [here](tuto_G_carsim_integration.md).
## OpenDRIVE
## ASAM OpenDRIVE
[__OpenDRIVE__](https://www.asam.net/standards/detail/opendrive/) is an open format specification used to describe the logic of a road network intended to standardise the discription of road networks in digital format and allow different applications to exchange data on road networks. Please refer to the full documentation [__here__](adv_opendrive.md)
[__ASAM OpenDRIVE__](https://www.asam.net/standards/detail/opendrive/) is an open format specification used to describe the logic of a road network intended to standardise the discription of road networks in digital format and allow different applications to exchange data on road networks. Please refer to the full documentation [__here__](adv_opendrive.md)
## RSS - Responsibility Sensitive Safety

View File

@ -17,7 +17,26 @@ The __Digital Twin Tool__ enables procedural generation of unique 3D environment
## Building the OSM renderer
If you are using Linux, you have the option of using the OSM renderer in the CARLA interface to navigate a large OSM map region that you have downloaded. You first need to build the OSM renderer. Run `make osmrenderer` inside the CARLA root directory. You may need to upgrade your version of CMake to v3.2 or above in order for this to work. This will create two folders in your build directory called `libosmcout-source` and `libosmcout-build`. Windows users do not have the option of using the OSM renderer and must use directly a URL.
If you are using Linux, you have the option of using the OSM renderer in the CARLA interface to navigate a large OSM map region that you have downloaded. You first need to build the OSM renderer before proceeding to build CARLA. Run `make osmrenderer` inside the CARLA root directory. You may need to upgrade your version of CMake to v3.2 or above in order for this to work. This will create two folders in your build directory called `libosmcout-source` and `libosmcout-build`. Before proceeding to build CARLA, you need to then edit the `Build.sh` file in the directory `$CARLA_ROOT/Build/libosmcout-source/maps` like so, to ensure the executable is found:
```bash
if [[ -x ../Import/src/Import ]]; then
importExe=../Import/src/Import
elif [[ -x ../debug/Import/Import ]]; then
importExe=../debug/Import/Import
elif [[ -x ../build/Import/Import ]]; then
importExe=../build/Import/Import
################### Add this line ####################
elif [ -x ../../libosmscout-build/Import/Import ]; then
importExe=../../libosmscout-build/Import/Import
#######################################################
else
echo "Cannot find Import executable!"
exit 1
fi
```
Then continue to build CARLA in the normal way. Windows users do not have the option of using the OSM renderer and must directly the URL.
## Downloading and preparing OSM map data

View File

@ -1,52 +1,49 @@
# Carla Multi-GPU feature
Multi-GPU in carla means that the user can start several servers (called secondary servers) that will do render work for the main server (called primary server) for different sensors.
Multi-GPU in carla means that the user can start several servers (called secondary servers) that will do render work for the main server (called primary server) using a dedicated GPU from the system. The primary server will distribute the sensors, that are created by the user, to the different secondary servers available.
![Multi-GPU example with 2 secondary servers](img/multigpu-example.png)
We need to start the primary server (usually with a flag to avoid using any GPU). This server will process all physics and synchronize the scene data to the others secondary servers. Then we can start any secondary server as we want (usually one per dedicated GPU in the system), using the parameters we will describe further. After this, the client can connect (always to the primary server) and proceed as usual.
All the system is transparent to the user, who don't need to know from which server comes the sensor data, he just receives the data directly from a secondary server.
## Primary server
The steps are: first, start the primary server without any render capability. The parameters we can use are:
The steps are, first, start the primary server without any render capability.
The parameters we can use are:
* `-nullrhi`: disables any render capabilities (GPU free)
* `-carla-primary-port`: TCP port used to listen for secondary servers (default 2002)
* `-nullrhi`
* `-carla-primary-port`
For example
Run the following from the command line:
**./CarlaUE4.sh -nullrhi**
```sh
./CarlaUE4.sh -nullrhi
```
The primary server will use by default the port 2002 to listen for secondary servers. If you need to listen on another port, then you can change it with the flag
The primary server will use, by default, the port 2002 to listen for secondary servers. If you need to listen on another port, then you can change it with the port flag:
```sh
./CarlaUE4.sh -nullrhi -carla-primary-port=3002
```
**./CarlaUE4.sh -nullrhi -carla-primary-port=3002**
## Secondary servers
We may then start as many servers as we need, but the ideal is to have as many secondary servers as the number of GPUs installed in the computer. Through parameters we need to specify the GPU we want the server use and also the host/port where the primary server is listening, with the flags:
Then we need to start as many servers as we want, but the ideal is to have as many secondary servers as GPU. Through parameters we need to specify the GPU we want the server use and also the host/port where the primary server is listenning, with the flags:
* `-carla-rpc-port`: TCP port to accept client connections (for secondary servers it is not needed, but the port needs to be free)
* `-carla-primary-host`: IP of the primary server to connect
* `-carla-primary-port`: TCP port of the primary server to connect
* `-ini:[/Script/Engine.RendererSettings]:r.GraphicsAdapter`: tells which GPU device to use for this secondary server
* `-carla-rpc-port`
* `-carla-primary-host`
* `-carla-primary-port`
* `-ini:[/Script/Engine.RendererSettings]:r.GraphicsAdapter`
For example, if the primary server is executing in the same computer than the secondary servers and with the default port, we can use this:
For example, if the primary server is executing in the same computer than the secondary servers and with the default port, we can use this command:
```sh
./CarlaUE4.sh -carla-rpc-port=3000 -carla-primary-host=127.0.0.1 -ini:[/Script/Engine.RendererSettings]:r.GraphicsAdapter=0
```
**./CarlaUE4.sh -carla-rpc-port=3000 -carla-primary-host=127.0.0.1 -ini:[/Script/Engine.RendererSettings]:r.GraphicsAdapter=0**
Here, the secondary server will use port 3000 as the RPC server to avoid conflicts with other ports (but it will never be used), and will connect to the primary server located at IP 127.0.0.1 (localhost) in the default port (2002), and also this server will use the GPU device 0.
If we want to start another secondary server using another GPU, we could use the following command:
If we want to start another secondary server in the same machine using another GPU, we could use this command:
```sh
./CarlaUE4.sh -carla-rpc-port=4000 -carla-primary-host=127.0.0.1 -carla-primary-port=2002 -ini:[/Script/Engine.RendererSettings]:r.GraphicsAdapter=1
```
**./CarlaUE4.sh -carla-rpc-port=4000 -carla-primary-host=127.0.0.1 -carla-primary-port=2002 -ini:[/Script/Engine.RendererSettings]:r.GraphicsAdapter=1**
This secondary server will use port 4000 as the RPC server to avoid conflicts with other ports and will connect to the primary server located at IP 127.0.0.1 in port 2002, and also this server will use the GPU device 1.
This secondary server will use port 4000 as the RPC server to avoid conflicts with other ports and will connect to the primary server located at IP 127.0.0.1 in the port 2002, and also this server will use the GPU device 1.
## Pipeline
## Synchronous mode
After the first secondary server connects to the primary server, the system is setup to synchronous mode automatically, with the default values of 1/20 delta seconds.
After the first secondary server connects to the primary server, it will set up the synchronous mode automatically, with the default values of 1/20 delta seconds.

View File

@ -1,6 +1,6 @@
# OpenDRIVE standalone mode
# ASAM OpenDRIVE standalone mode
This feature allows users to ingest any OpenDRIVE file as a CARLA map out-of-the-box. In order to do so, the simulator will automatically generate a road mesh for actors to navigate through.
This feature allows users to ingest any ASAM OpenDRIVE file as a CARLA map out-of-the-box. In order to do so, the simulator will automatically generate a road mesh for actors to navigate through.
* [__Overview__](#overview)
* [__Run a standalone map__](#run-a-standalone-map)
@ -26,9 +26,9 @@ Traffic lights, stops and yields will be generated on the fly. Pedestrians will
---
## Run a standalone map
Open an OpenDRIVE file is just a matter of calling [`client.generate_opendrive_world()`](python_api.md#carla.Client.generate_opendrive_world) through the API. This will generate the new map, and block the simulation until it is ready. The method needs for two parameters.
Open an ASAM OpenDRIVE file is just a matter of calling [`client.generate_opendrive_world()`](python_api.md#carla.Client.generate_opendrive_world) through the API. This will generate the new map, and block the simulation until it is ready. The method needs for two parameters.
* __`opendrive`__ is the content of the OpenDRIVE file parsed as a string.
* __`opendrive`__ is the content of the ASAM OpenDRIVE file parsed as a string.
* __`parameters`__ is a [carla.OpendriveGenerationParameters](python_api.md#carla.OpendriveGenerationParameters) containing settings for the generation of the mesh. __This argument is optional__.
* __`vertex_distance`__ *(default 2.0 meters)* — Distance between the vertices of the mesh. The bigger, the distance, the more inaccurate the mesh will be. However, if the distance is too small, the resulting mesh will be too heavy to work with.

View File

@ -59,7 +59,7 @@ As a reminder, the feature is only available for the Linux build so far.
### Dependencies
There are additional prerequisites required for building RSS and its dependencies. Take a look at the [official documentation](https://intel.github.io/ad-rss-lib/BUILDING)) to know more about this.
There are additional prerequisites required for building RSS and its dependencies. Take a look at the [official documentation](https://intel.github.io/ad-rss-lib/BUILDING) to know more about this.
Dependencies provided by Ubunutu (>= 16.04).
```sh

View File

@ -76,7 +76,7 @@ CARLA forum</a>
> CARLA is a performance demanding software. At the very minimum it requires a 6GB GPU or, even better, a dedicated GPU capable of running Unreal Engine.
>
> Take a look at [Unreal Engine's recommended hardware](https://www.ue4community.wiki/recommended-hardware-x1p9qyg0).
> Take a look at [Unreal Engine's recommended hardware](https://dev.epicgames.com/documentation/en-us/unreal-engine/hardware-and-software-specifications-for-unreal-engine).
---
@ -365,7 +365,7 @@ CARLA forum</a>
>In Windows it will be the default Python version for:
> py -3 --version
> python --version
>Make sure you are running your scripts with the version of Python that corresponds to your `.egg` file.
>In Linux, you may also need to set your Python path to point to the CARLA `.egg`. To do this, run the following command:

View File

@ -48,6 +48,16 @@ wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key|sudo apt-key add
To avoid compatibility issues between Unreal Engine and the CARLA dependencies, use the same compiler version and C++ runtime library to compile everything. The CARLA team uses clang-8 (or clang-10 in Ubuntu 20.04) and LLVM's libc++. Change the default clang version to compile Unreal Engine and the CARLA dependencies.
__Ubuntu 22.04__.
```sh
sudo apt-add-repository "deb http://archive.ubuntu.com/ubuntu focal main universe"
sudo apt-get update
sudo apt-get install build-essential clang-10 lld-10 g++-7 cmake ninja-build libvulkan1 python python3 python3-dev python3-pip libpng-dev libtiff5-dev libjpeg-dev tzdata sed curl unzip autoconf libtool rsync libxml2-dev git git-lfs
sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/lib/llvm-10/bin/clang++ 180 &&
sudo update-alternatives --install /usr/bin/clang clang /usr/lib/llvm-10/bin/clang 180 &&
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-7 180
```
__Ubuntu 20.04__.
```sh
sudo apt-add-repository "deb http://apt.llvm.org/focal/ llvm-toolchain-focal main"

View File

@ -1,13 +1,13 @@
# Update CARLA
* [__Update commands summary__](#update-commands-summary)
* [__Get the lastest binary release__](#get-latest-binary-release)
* [__Update Linux and Windows build__](#update-linux-and-windows-build)
* [Clean the build](#clean-the-build)
* [Pull from origin](#pull-from-origin)
* [Download the assets](#download-the-assets)
* [Launch the server](#launch-the-server)
* [__Get development assets__](#get-development-assets)
* [__Update commands summary__](#update-commands-summary)
* [__Get the lastest binary release__](#get-latest-binary-release)
* [__Update Linux and Windows build__](#update-linux-and-windows-build)
* [Clean the build](#clean-the-build)
* [Pull from origin](#pull-from-origin)
* [Download the assets](#download-the-assets)
* [Launch the server](#launch-the-server)
* [__Get development assets__](#get-development-assets)
To post unexpected issues, doubts or suggestions, feel free to login in the CARLA forum.
@ -25,30 +25,30 @@ CARLA forum</a>
<summary> Show command lines to update CARLA</summary>
```sh
# Update a CARLA packaged release.
# 1. Delete the current one.
# 2. Follow the Quick start installation to get the one desired.
# Update a CARLA packaged release.
# 1. Delete the current one.
# 2. Follow the Quick start installation to get the one desired.
# Update Linux build.
# Update Linux build.
git checkout master
make clean
git pull origin master
./Update.sh
# Update Windows build.
# Update Windows build.
git checkout master
make clean
git pull origin master
# Erase the content in `Unreal\CarlaUE4\Content\Carla`.
# Go to `\Util\ContentVersions.txt`.
# Download the latest content.
# Extract the new content in `Unreal\CarlaUE4\Content\Carla`.
# Extract the new content in `Unreal\CarlaUE4\Content\Carla`.
# Get development assets.
# Delete the `/Carla` folder containing previous assets.
# Get development assets.
# Delete the `/Carla` folder containing previous assets.
# Go to the main carla folder.
git clone https://bitbucket.org/carla-simulator/carla-content Unreal/CarlaUE4/Content/Carla
@ -56,11 +56,11 @@ git clone https://bitbucket.org/carla-simulator/carla-content Unreal/CarlaUE4/Co
</details>
---
## Get latest binary release
## Get latest binary release
Binary releases are prepackaged and thus, tied to a specific version of CARLA. To get the latest, erase the previous and follow the [quick start installation](start_quickstart.md) to get the one desired.
Binary releases are prepackaged and thus, tied to a specific version of CARLA. To get the latest, erase the previous and follow the [quick start installation](start_quickstart.md) to get the one desired.
Releases are listed in __Development__ in the CARLA repository. There is also a highly experimental __Nightly build__ containing the current state of CARLA up to date.
Releases are listed in __Development__ in the CARLA repository. There is also a highly experimental __Nightly build__ containing the current state of CARLA up to date.
<div class="build-buttons">
<p>
@ -69,22 +69,22 @@ Releases are listed in __Development__ in the CARLA repository. There is also a
</p>
<p>
<a href="http://carla-releases.s3.amazonaws.com/Linux/Dev/CARLA_Latest.tar.gz" target="_blank" class="btn btn-neutral" title="Go to the linux nightly CARLA build">
<a href="https://carla-releases.s3.us-east-005.backblazeb2.com/Linux/Dev/CARLA_Latest.tar.gz" target="_blank" class="btn btn-neutral" title="Go to the linux nightly CARLA build">
<span class="icon fa-cloud-download"></span> Get the linux nightly build</a>
</p>
<p>
<a href="http://carla-releases.s3.amazonaws.com/Linux/Dev/AdditionalMaps_Latest.tar.gz" target="_blank" class="btn btn-neutral" title="Go to the linux nightly AdditionalMaps build">
<a href="https://carla-releases.s3.us-east-005.backblazeb2.com/Linux/Dev/AdditionalMaps_Latest.tar.gz" target="_blank" class="btn btn-neutral" title="Go to the linux nightly AdditionalMaps build">
<span class="icon fa-cloud-download"></span> Get the linux nightly build additional maps</a>
</p>
<p>
<a href="http://carla-releases.s3.amazonaws.com/Windows/Dev/CARLA_Latest.zip" target="_blank" class="btn btn-neutral" title="Go to the windows nightly CARLA build">
<a href="https://carla-releases.s3.us-east-005.backblazeb2.com/Windows/Dev/CARLA_Latest.zip" target="_blank" class="btn btn-neutral" title="Go to the windows nightly CARLA build">
<span class="icon fa-cloud-download"></span> Get the windows nightly build</a>
</p>
<p>
<a href="http://carla-releases.s3.amazonaws.com/Windows/Dev/AdditionalMaps_Latest.zip" target="_blank" class="btn btn-neutral" title="Go to the windows nightly AdditionalMaps build">
<a href="https://carla-releases.s3.us-east-005.backblazeb2.com/Windows/Dev/AdditionalMaps_Latest.zip" target="_blank" class="btn btn-neutral" title="Go to the windows nightly AdditionalMaps build">
<span class="icon fa-cloud-download"></span> Get the windows nightly build additional maps</a>
</p>
@ -93,22 +93,22 @@ Releases are listed in __Development__ in the CARLA repository. There is also a
---
## Update Linux and Windows build
Make sure to be in the local `master` branch before the update. Then, merge or rebase the changes to other branches and solve possible conflicts.
Make sure to be in the local `master` branch before the update. Then, merge or rebase the changes to other branches and solve possible conflicts.
```sh
```sh
git checkout master
```
### Clean the build
Go to the main CARLA folder and delete binaries and temporals generated by the previous build.
```sh
```sh
make clean
```
### Pull from origin
Get the current version from `master` in the CARLA repository.
Get the current version from `master` in the CARLA repository.
```sh
git pull origin master
```
@ -120,19 +120,19 @@ __Linux.__
./Update.sh
```
__Windows.__
__Windows.__
__1.__ Erase the previous content in `Unreal\CarlaUE4\Content\Carla`.
__2.__ Go to `\Util\ContentVersions.txt`.
__3.__ Download the content for `latest`.
__4.__ Extract the new content in `Unreal\CarlaUE4\Content\Carla`.
__1.__ Erase the previous content in `Unreal\CarlaUE4\Content\Carla`.
__2.__ Go to `\Util\ContentVersions.txt`.
__3.__ Download the content for `latest`.
__4.__ Extract the new content in `Unreal\CarlaUE4\Content\Carla`.
!!! Note
In order to work with that the CARLA team is devleoping, go to __get development assets__ below.
In order to work with that the CARLA team is devleoping, go to __get development assets__ below.
### Launch the server
Run the server in spectator view to make sure that everything worked properly.
Run the server in spectator view to make sure that everything worked properly.
```sh
make launch
@ -141,18 +141,18 @@ make launch
---
## Get development assets
The CARLA team works with assets still in development. These models and maps have a [public git repository][contentrepolink] where the CARLA team regularly pushes latest updates. Assets are still unfinished, using them is only recommended for developers.
The CARLA team works with assets still in development. These models and maps have a [public git repository][contentrepolink] where the CARLA team regularly pushes latest updates. Assets are still unfinished, using them is only recommended for developers.
In order to handle this repository it is advisted to install [git-lfs][gitlfslink]. The repository is modified regularly, and git-lfs works faster with large binary files.
In order to handle this repository it is advisted to install [git-lfs][gitlfslink]. The repository is modified regularly, and git-lfs works faster with large binary files.
To clone the repository, __go to the main CARLA directory__ and run the following command.
To clone the repository, __go to the main CARLA directory__ and run the following command.
```sh
git clone https://bitbucket.org/carla-simulator/carla-content Unreal/CarlaUE4/Content/Carla
```
!!! Warning
Delete the `/Carla` folder containing the assets before cloning the repository. Otherwise, an error will show.
Delete the `/Carla` folder containing the assets before cloning the repository. Otherwise, an error will show.
[contentrepolink]: https://bitbucket.org/carla-simulator/carla-content
[gitlfslink]: https://github.com/git-lfs/git-lfs/wiki/Installation

View File

@ -40,7 +40,7 @@ In this section you will find details of system requirements, minor and major so
#### Minor installations
* [__CMake__](https://cmake.org/download/) generates standard build files from simple configuration files.
* [__CMake__](https://cmake.org/download/) generates standard build files from simple configuration files. __We recommend you use version 3.15+__.
* [__Git__](https://git-scm.com/downloads) is a version control system to manage CARLA repositories.
* [__Make__](http://gnuwin32.sourceforge.net/packages/make.htm) generates the executables. It is necessary to use __Make version 3.81__, otherwise the build may fail. If you have multiple versions of Make installed, check that you are using version 3.81 in your PATH when building CARLA. You can check your default version of Make by running `make --version`.
* [__7Zip__](https://www.7-zip.org/) is a file compression software. This is required for automatic decompression of asset files and prevents errors during build time due to large files being extracted incorrectly or partially.

View File

@ -37,7 +37,7 @@ __Blueprints__ are already-made actor layouts necessary to spawn an actor. Basic
### 3rd- Maps and navigation
__The map__ is the object representing the simulated world, the town mostly. There are eight maps available. All of them use OpenDRIVE 1.4 standard to describe the roads.
__The map__ is the object representing the simulated world, the town mostly. There are eight maps available. All of them use ASAM OpenDRIVE 1.4 standard to describe the roads.
__Roads, lanes and junctions__ are managed by the [Python API](python_api.md) to be accessed from the client. These are used along with the __waypoint__ class to provide vehicles with a navigation path.

View File

@ -23,6 +23,7 @@ After discussing about the world and its actors, it is time to put everything in
- [Add map package](tuto_M_add_map_package.md)
- [Add map source](tuto_M_add_map_source.md)
- [Alternative methods](tuto_M_add_map_alternative.md)
- [__Additional maps__](#additional-maps)
---
@ -257,6 +258,9 @@ Non-layered maps are shown in the table below (click the town name to see an ove
| [__Town11__](map_town11.md) | A Large Map that is undecorated. Serves as a proof of concept for the Large Maps feature. |
| [__Town12__](map_town12.md) | A Large Map with numerous different regions, including high-rise, residential and rural environments.|
!!! note
Town06 and Town07 are additional content which does not come with the standard CARLA package. Please see the [additional maps section](#additional-maps) for details on how to import these.
### Layered maps
The layout of layered maps is the same as non-layered maps but it is possible to toggle off and on the layers of the map. There is a minimum layout that cannot be toggled off and consists of roads, sidewalks, traffic lights and traffic signs. Layered maps can be identified by the suffix `_Opt`, for example, `Town01_Opt`. With these maps it is possible to [load][load_layer] and [unload][unload_layer] layers via the Python API:
@ -291,3 +295,27 @@ CARLA is designed to be extensible and highly customisable for specialist applic
* [__Add map package__](tuto_M_add_map_package.md)
* [__Add map source__](tuto_M_add_map_source.md)
* [__Alternative methods__](tuto_M_add_map_alternative.md)
## Additional maps
Each release has it's own additional package of extra assets and maps. This additional package includes the maps __Town06__ and __Town07__. These are stored separately to reduce the size of the build, so they can only be imported after the main package has been installed.
__1.__ [Download](https://github.com/carla-simulator/carla/blob/master/Docs/download.md) the appropriate package for your desired version of CARLA.
__2.__ Extract the package:
- __On Linux__:
- move the package to the _Import_ folder and run the following script to extract the contents:
```sh
cd path/to/carla/root
./ImportAssets.sh
```
- __On Windows__:
- Extract the contents directly in the root folder.
---

View File

@ -10,10 +10,10 @@
> branch. It contains the very latest fixes and features that will be part of the
> next release, but also some experimental changes. Use at your own risk!
- [CARLA Nightly Build (Linux)](https://carla-releases.s3.eu-west-3.amazonaws.com/Linux/Dev/CARLA_Latest.tar.gz)
- [AdditionalMaps Nightly Build (Linux)](https://carla-releases.s3.eu-west-3.amazonaws.com/Linux/Dev/AdditionalMaps_Latest.tar.gz)
- [CARLA Nightly Build (Windows)](https://carla-releases.s3.eu-west-3.amazonaws.com/Windows/Dev/CARLA_Latest.zip)
- [AdditionalMaps Nightly Build (Windows)](https://carla-releases.s3.eu-west-3.amazonaws.com/Windows/Dev/AdditionalMaps_Latest.zip)
- [CARLA Nightly Build (Linux)](https://carla-releases.s3.us-east-005.backblazeb2.com/Linux/Dev/CARLA_Latest.tar.gz)
- [AdditionalMaps Nightly Build (Linux)](https://carla-releases.s3.us-east-005.backblazeb2.com/Linux/Dev/AdditionalMaps_Latest.tar.gz)
- [CARLA Nightly Build (Windows)](https://carla-releases.s3.us-east-005.backblazeb2.com/Windows/Dev/CARLA_Latest.zip)
- [AdditionalMaps Nightly Build (Windows)](https://carla-releases.s3.us-east-005.backblazeb2.com/Windows/Dev/AdditionalMaps_Latest.zip)
### Versions 0.9.x

66
Docs/ecosys_simready.md Normal file
View File

@ -0,0 +1,66 @@
# SimReady content with NVIDIA Omniverse
NVIDIA's [__SimReady__](https://developer.nvidia.com/omniverse/simready-assets) specification supports the preparation of __3D content that is purpose-built for simulation__ to help streamline content creation pipelines for simulating 3D virtual environments for machine learning purposes in robotics and autonomous driving. Through the Omniverse Unreal Engine plugin now integrated into CARLA users can import, in just a few clicks, SimReady content such as vehicles already configured with working lights, doors and wheels and props ready for use instantaneously to decorate CARLA maps. CARLA's Omniverse integration boasts to significantly accelerate your environment building pipeline and opens the door to a whole world of applications in the [__Omniverse ecosystem__](https://www.nvidia.com/en-us/omniverse/ecosystem/).
!!! note
The Omniverse Unreal Engine Connector is currently only available in Windows.
Follow these steps to start using Omniverse and using SimReady content in CARLA:
Before anything else, you should first [install NVIDIA Omniverse](https://docs.omniverse.nvidia.com/install-guide/latest/index.html)
### 1. Installing the Unreal Engine Omniverse Connector
1. Launch the NVIDIA Omniverse Launcher
2. Navigate to the **Exchange** tab
3. Locate the __Epic Games Unreal Engine 4.26 Omniverse Connector__
4. Ensure the install version is **Release 105.1.578**
5. Click *Install*
6. Omniverse will not be able to find Unreal Engine, click **OK**.
7. It will prompt you to find your Unreal Engine installation, select this path: {UE4_ROOT}\Engine\Plugins\Marketplace\NVIDIA
8. Press *Install*.
### 2. Set Up Local Omniverse Server
1. Open NVIDIA Omniverse with the launcher
2. Navigate to the *Nucleus* tab
3. Click on *Create Local Server*
4. Create administrator details
5. Select the folder icon next to *Local Nucleus Service*, this should open your localhost server in your web browser
### 3. Connecting to CARLA Simulator
1. Launch CARLA using `make launch` from the command line the CARLA root folder
2. If an existing server is active and you want to restart the setup, click on *Clean Local Assets* (optional)
3. Select the *Omniverse* icon and click on *Add Server*
4. Name the server and click *Add to Content Browser*
5. A login form should launch in your browser, click *Create Account*
6. Create administrator details
7. Omniverse folders should now be visible in your Content/Omniverse folder in the Unreal Engine content browser
8. Go to your web browser again
9. Click on *Connect to a Server*
10. Authenticate using the server name you set for the CARLA server
11. Use the administrator details that you set for the CARLA server
12. The server folders should now show up in your browser
### 4. Importing a SimReady asset
1. Navigate to the Projects folder within the browser navigator
2. Right click, and select *Upload Folder*
3. Select your SimReady folders
4. Upload the files
### 5. Using the Omniverse Connector to Load the Vehicle to CARLA
1. Open the CARLA project in Unreal Engine
2. Navigate to `CarlaTools/Content/USDImporter`
3. Right click on *UW_USDVehicleImporterEditorWidget*
4. Select *Run Editor Utility Widget*
5. Find the Vehicle within your Omniverse browser navigator
6. Copy the path (should look something like: omniverse://localhost/Projects/SimReadyUSD.../vehicle.usd)
7. Paste it inside the Omiverse URL tab within the Widget
8. Select *Import Asset*
9. You should see the vehicle show up in the engine within the folder that you specified in the *Import destination* field
10. Open another map scene (it may have opened a new scene with the imported data) a *Save Content* prompt should appear. Uncheck the *Untitled* scene, and click on *Save selected* to save new content
11. The vehicle is now usable within CARLA and will be available through the Python API

56
Docs/ecosys_synkrotron.md Normal file
View File

@ -0,0 +1,56 @@
<img src="../img/synkrotron.jpg" alt= “synkrotron_logo” style="display: block; margin-left: auto; margin-right: auto; width: 70%;">
# Synkrotron simulation solutions
Synkrotron provides advanced solutions for autonomous driving simulation built on top of CARLA. Synkrotron's product suite OASIS supports a broad range of applications including scenario generation, sensor modelling, traffic simulation and data management. Based on a flexible architecture OASIS can be deployed on the cloud at scale, or in a developer's local environment for prototyping.
---
<img src="../img/oasis_logo.png" alt= “synkrotron_logo” style="display: block; margin-left: auto; margin-right: auto; width: 70%;">
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; height: auto;">
<iframe src="https://www.youtube.com/embed/YRI67aar3S0" frameborder="0" allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe>
</div>
<br>
## [__OASIS simulation platform__](https://www.synkrotron.ai/sim.html)
OASIS Sim is a fully-fledged, scalable simulation platform with CARLA at its core. It supports the complete life-cycle of AD simulation:
- scenario import & editing with a graphical user interface
- sensor configuration
- distributed task management
- diagnosis through rich simulation data and logs
Both cloud and local deployment are available through containerized packaging. Comprehensive APIs are exposed for integration with DevOps too. You can [request a trial](https://synkrotron.ai/contact.html) from Synkrotron.
## [__OASIS data platform__](https://www.synkrotron.ai/data.html)
OASIS Data is a platform for managing the high volume of data flowing through the autonomous driving R&D pipeline. Data-driven development of AD systems are made possible with OASIS Data via the following functionalities:
* data acquisition and anonymization
* multi-stage filtering based on structured data (CAN bus signals, active-safety triggering, etc.) and unstructured data (sensor readings)
* information mapping and environment reconstruction with LIDAR and/or vision-only strategy
* auto-labeling of data with pre-trained perception models
* scenario tagging and reconstruction with OpenX format output
The processed data from the platform supports downstream applications such as scenario re-simulation with Oasis Sim, retraining of perception models with new labeled data and operational fleet management.
## __Synkrotron Tools and Services__
In addition to the complete solutions introduced above, Synkrotron also offers the following developer tools and services to facilitate AD simulation development.
| Product/service | Description |
| -----------| ------ |
| __Sensor model__: fish-eye camera | Fisheye camera with configurable distortion parameters |
| __Sensor model__: LIDAR | Advanced lidar model with configurable shutter mode and material reflections |
| __SOTIF__ scenario generation tool | Given the ODD description from user, identify important scenario elements and generate critical scenarios to help uncover unknown unsafe domains of the autonomous driving systems, achieved by using an ontology-based method combined with iterative optimizations against evaluations in Carla |
| __Map creation__ | Given lidar scan data (can also provide road-test data collection equipments & service), create HD maps for the user and output OpenDrive files which can be loaded in Carla for PnC tests or logsim |
| __Sensor model__: physics models for camera | Supports CMOS simulations and outputs 12bit raw sensor data, for customers who develop ISP algorithms or who has ECUs that need raw data from camera instead of RGBs |
| __Static scene creation__ | Combined HD mapping, 3D asset development and procedural modeling to create 3D static scenes/digital twins for users |
| __Dynamic scenario reconstruction__ | On top of static scenes, also detect and track various traffic participants from user's road-test data; the recovered trajectories/behaviors are turned into OpenScenario 1.0 files and can be re-simulated in CARLA |

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
Docs/img/oasis_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

BIN
Docs/img/synkrotron.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -5,7 +5,7 @@
Town 13 is a Large Map with dimensions of 10x10 km<sup>2</sup>. It is divided into 36 tiles, most with dimensions of 2x2 km<sup>2</sup> (some edge tiles are smaller). There are numerous contrasting regions to the city including urban, residential and rural areas, along with a large highway system surrounding the city with a ringroad. The architectural styles reflect those of many medium to large cities across North America.
!!! note
Town 13 has been designed as an adjunct to Town 13, such that they can serve as a __train-test pair__. The towns share many common features, but also many differences in the styles of buildings, road textures, pavement textures and also vegetation. Using one of the pair to produce training data and then using the other for testing is ideal for exposing overfitting issues that might be arising while developing an AD stack.
Town 13 has been designed as an adjunct to Town 12, such that they can serve as a __train-test pair__. The towns share many common features, but also many differences in the styles of buildings, road textures, pavement textures and also vegetation. Using one of the pair to produce training data and then using the other for testing is ideal for exposing overfitting issues that might be arising while developing an AD stack.
## Navigator

View File

@ -434,7 +434,13 @@ Enum declaration that contains the different tags available to filter the boundi
- <a name="carla.CityObjectLabel.Sidewalks"></a>**<font color="#f8805a">Sidewalks</font>**
- <a name="carla.CityObjectLabel.TrafficSigns"></a>**<font color="#f8805a">TrafficSigns</font>**
- <a name="carla.CityObjectLabel.Vegetation"></a>**<font color="#f8805a">Vegetation</font>**
- <a name="carla.CityObjectLabel.Vehicles"></a>**<font color="#f8805a">Vehicles</font>**
- <a name="carla.CityObjectLabel.Car"></a>**<font color="#f8805a">Car</font>**
- <a name="carla.CityObjectLabel.Bus"></a>**<font color="#f8805a">Bus</font>**
- <a name="carla.CityObjectLabel.Truck"></a>**<font color="#f8805a">Truck</font>**
- <a name="carla.CityObjectLabel.Motorcycle"></a>**<font color="#f8805a">Motorcycle</font>**
- <a name="carla.CityObjectLabel.Bicycle"></a>**<font color="#f8805a">Bicycle</font>**
- <a name="carla.CityObjectLabel.Rider"></a>**<font color="#f8805a">Rider</font>**
- <a name="carla.CityObjectLabel.Train"></a>**<font color="#f8805a">Train</font>**
- <a name="carla.CityObjectLabel.Walls"></a>**<font color="#f8805a">Walls</font>**
- <a name="carla.CityObjectLabel.Sky"></a>**<font color="#f8805a">Sky</font>**
- <a name="carla.CityObjectLabel.Ground"></a>**<font color="#f8805a">Ground</font>**
@ -475,7 +481,7 @@ Executes a list of commands on a single simulation step, blocks until the comman
- <a name="carla.Client.generate_opendrive_world"></a>**<font color="#7fb800">generate_opendrive_world</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**opendrive**</font>, <font color="#00a6ed">**parameters**=(2.0, 50.0, 1.0, 0.6, true, true)</font>, <font color="#00a6ed">**reset_settings**=True</font>)
Loads a new world with a basic 3D topology generated from the content of an OpenDRIVE file. This content is passed as a `string` parameter. It is similar to `client.load_world(map_name)` but allows for custom OpenDRIVE maps in server side. Cars can drive around the map, but there are no graphics besides the road and sidewalks.
- **Parameters:**
- `opendrive` (_str_) - Content of an OpenDRIVE file as `string`, __not the path to the `.xodr`__.
- `opendrive` (_str_) - Content of an ASAM OpenDRIVE file as `string`, __not the path to the `.xodr`__.
- `parameters` (_[carla.OpendriveGenerationParameters](#carla.OpendriveGenerationParameters)_) - Additional settings for the mesh generation. If none are provided, default values will be used.
- `reset_settings` (_bool_) - Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- <a name="carla.Client.load_world"></a>**<font color="#7fb800">load_world</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**map_name**</font>, <font color="#00a6ed">**reset_settings**=True</font>, <font color="#00a6ed">**map_layers**=[carla.MapLayer.All](#carla.MapLayer.All)</font>)
@ -484,12 +490,23 @@ Creates a new world with default settings using `map_name` map. All actors in th
- `map_name` (_str_) - Name of the map to be used in this world. Accepts both full paths and map names, e.g. '/Game/Carla/Maps/Town01' or 'Town01'. Remember that these paths are dynamic.
- `reset_settings` (_bool_) - Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- `map_layers` (_[carla.MapLayer](#carla.MapLayer)_) - Layers of the map that will be loaded. By default all layers are loaded. This parameter works like a flag mask.
- **Return:** _[carla.World](#carla.World)_
- **Warning:** <font color="#ED2F2F">_`map_layers` are only available for "Opt" maps
_</font>
- <a name="carla.Client.load_world_if_different"></a>**<font color="#7fb800">load_world_if_different</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**map_name**</font>, <font color="#00a6ed">**reset_settings**=True</font>, <font color="#00a6ed">**map_layers**=[carla.MapLayer.All](#carla.MapLayer.All)</font>)
Creates a new world with default settings using `map_name` map only if it is a different map from the currently loaded map. Otherwise this function returns `None`. All actors in the current world will be destroyed.
- **Parameters:**
- `map_name` (_str_) - Name of the map to be used in this world. Accepts both full paths and map names, e.g. '/Game/Carla/Maps/Town01' or 'Town01'. Remember that these paths are dynamic.
- `reset_settings` (_bool_) - Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- `map_layers` (_[carla.MapLayer](#carla.MapLayer)_) - Layers of the map that will be loaded. By default all layers are loaded. This parameter works like a flag mask.
- **Return:** _[carla.World](#carla.World)_
- **Warning:** <font color="#ED2F2F">_`map_layers` are only available for "Opt" maps
_</font>
- <a name="carla.Client.reload_world"></a>**<font color="#7fb800">reload_world</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**reset_settings**=True</font>)
Reload the current world, note that a new world is created with default settings using the same map. All actors present in the world will be destroyed, __but__ traffic manager instances will stay alive.
- **Parameters:**
- `reset_settings` (_bool_) - Option to reset the episode setting to default values, set to false to keep the current settings. This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- **Return:** _[carla.World](#carla.World)_
- **Raises:** RuntimeError when corresponding.
- <a name="carla.Client.replay_file"></a>**<font color="#7fb800">replay_file</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**name**</font>, <font color="#00a6ed">**start**</font>, <font color="#00a6ed">**duration**</font>, <font color="#00a6ed">**follow_id**</font>, <font color="#00a6ed">**replay_sensors**</font>)
Load a new world with default settings using `map_name` map. All actors present in the current world will be destroyed, __but__ traffic manager instances will stay alive.
@ -722,13 +739,45 @@ Draws an arrow from `begin` to `end` pointing in that direction.
- `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>)<button class="SnipetButton" id="carla.DebugHelper.draw_box-snipet_button">snippet &rarr;</button>
Draws a box, ussually to act for object colliders.
Draws a box, usually to act for object colliders.
- **Parameters:**
- `box` (_[carla.BoundingBox](#carla.BoundingBox)_) - Object containing a location and the length of a box for every axis.
- `rotation` (_[carla.Rotation](#carla.Rotation)<small> - degrees (pitch,yaw,roll)</small>_) - Orientation of the box according to Unreal Engine's axis system.
- `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_hud_arrow"></a>**<font color="#7fb800">draw_hud_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>)
Draws an arrow on the HUD from `begin` to `end` which can only be seen server-side.
- **Parameters:**
- `begin` (_[carla.Location](#carla.Location)<small> - meters</small>_) - Point in the coordinate system where the arrow starts.
- `end` (_[carla.Location](#carla.Location)<small> - meters</small>_) - Point in the coordinate system where the arrow ends and points towards to.
- `thickness` (_float<small> - meters</small>_) - Density of the line.
- `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_hud_box"></a>**<font color="#7fb800">draw_hud_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>)
Draws a box on the HUD, usually to act for object colliders. The box can only be seen server-side.
- **Parameters:**
- `box` (_[carla.BoundingBox](#carla.BoundingBox)_) - Object containing a location and the length of a box for every axis.
- `rotation` (_[carla.Rotation](#carla.Rotation)<small> - degrees (pitch,yaw,roll)</small>_) - Orientation of the box according to Unreal Engine's axis system.
- `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_hud_line"></a>**<font color="#7fb800">draw_hud_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>)
Draws a line on the HUD in between `begin` and `end`. The line can only be seen server-side.
- **Parameters:**
- `begin` (_[carla.Location](#carla.Location)<small> - meters</small>_) - Point in the coordinate system where the line starts.
- `end` (_[carla.Location](#carla.Location)<small> - meters</small>_) - Spot in the coordinate system where the line ends.
- `thickness` (_float<small> - meters</small>_) - Density of the line.
- `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_hud_point"></a>**<font color="#7fb800">draw_hud_point</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**location**</font>, <font color="#00a6ed">**size**=0.1</font>, <font color="#00a6ed">**color**=(255,0,0)</font>, <font color="#00a6ed">**life_time**=-1.0</font>)
Draws a point on the HUD at `location`. The point can only be seen server-side.
- **Parameters:**
- `location` (_[carla.Location](#carla.Location)<small> - meters</small>_) - Spot in the coordinate system to center the object.
- `size` (_float<small> - meters</small>_) - Density of the point.
- `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>)
Draws a line in between `begin` and `end`.
- **Parameters:**
@ -1706,7 +1755,7 @@ Distance between `actor` and `other`.
---
## carla.OpendriveGenerationParameters<a name="carla.OpendriveGenerationParameters"></a>
This class defines the parameters used when generating a world using an OpenDRIVE file.
This class defines the parameters used when generating a world using an ASAM OpenDRIVE file.
### Instance Variables
- <a name="carla.OpendriveGenerationParameters.vertex_distance"></a>**<font color="#f8805a">vertex_distance</font>** (_float_)
@ -2202,6 +2251,12 @@ Sensors compound a specific family of actors quite diverse and unique. They are
When <b>True</b> the sensor will be waiting for data.
### Methods
- <a name="carla.Sensor.disable_for_ros"></a>**<font color="#7fb800">disable_for_ros</font>**(<font color="#00a6ed">**self**</font>)
Commands the sensor to not be processed for publishing in ROS2 if there is no any listen to it.
- <a name="carla.Sensor.enable_for_ros"></a>**<font color="#7fb800">enable_for_ros</font>**(<font color="#00a6ed">**self**</font>)
Commands the sensor to be processed to be able to publish in ROS2 without any listen to it.
- <a name="carla.Sensor.is_enabled_for_ros"></a>**<font color="#7fb800">is_enabled_for_ros</font>**(<font color="#00a6ed">**self**</font>)
Returns if the sensor is enabled or not to publish in ROS2 if there is no any listen to it.
- <a name="carla.Sensor.is_listening"></a>**<font color="#7fb800">is_listening</font>**(<font color="#00a6ed">**self**</font>)
Returns whether the sensor is in a listening state.
- <a name="carla.Sensor.is_listening_gbuffer"></a>**<font color="#7fb800">is_listening_gbuffer</font>**(<font color="#00a6ed">**self**</font>, <font color="#00a6ed">**gbuffer_id**</font>)
@ -3733,9 +3788,9 @@ When enabled, the simulation will run no rendering at all. This is mainly used t
- <a name="carla.WorldSettings.fixed_delta_seconds"></a>**<font color="#f8805a">fixed_delta_seconds</font>** (_float_)
Ensures that the time elapsed between two steps of the simulation is fixed. Set this to <b>0.0</b> to work with a variable time-step, as happens by default.
- <a name="carla.WorldSettings.substepping"></a>**<font color="#f8805a">substepping</font>** (_bool_)
Enable the physics substepping. This option allows computing some physics substeps between two render frames. If synchronous mode is set, the number of substeps and its time interval are fixed and computed are so they fulfilled the requirements of [carla.WorldSettings.max_substep](#carla.WorldSettings.max_substep) and [carla.WorldSettings.max_substep_delta_time](#carla.WorldSettings.max_substep_delta_time). These last two parameters need to be compatible with [carla.WorldSettings.fixed_delta_seconds](#carla.WorldSettings.fixed_delta_seconds). Enabled by default.
Enable the physics substepping. This option allows computing some physics substeps between two render frames. If synchronous mode is set, the number of substeps and its time interval are fixed and computed are so they fulfilled the requirements of [carla.WorldSettings.max_substeps](#carla.WorldSettings.max_substeps) and [carla.WorldSettings.max_substep_delta_time](#carla.WorldSettings.max_substep_delta_time). These last two parameters need to be compatible with [carla.WorldSettings.fixed_delta_seconds](#carla.WorldSettings.fixed_delta_seconds). Enabled by default.
- <a name="carla.WorldSettings.max_substep_delta_time"></a>**<font color="#f8805a">max_substep_delta_time</font>** (_float_)
Maximum delta time of the substeps. If the [carla.WorldSettingsmax_substep](#carla.WorldSettingsmax_substep) is high enough, the substep delta time would be always below or equal to this value. By default, the value is set to 0.01.
Maximum delta time of the substeps. If the [carla.WorldSettings.max_substeps](#carla.WorldSettings.max_substeps) is high enough, the substep delta time would be always below or equal to this value. By default, the value is set to 0.01.
- <a name="carla.WorldSettings.max_substeps"></a>**<font color="#f8805a">max_substeps</font>** (_int_)
The maximum number of physics substepping that are allowed. By default, the value is set to 10.
- <a name="carla.WorldSettings.max_culling_distance"></a>**<font color="#f8805a">max_culling_distance</font>** (_float_)
@ -4034,6 +4089,11 @@ Actor affected by the command.
---
## command.FutureActor<a name="command.FutureActor"></a>
A utility object used to reference an actor that will be created in the command in the previous step, it has no parameters or methods.
---
## command.Response<a name="command.Response"></a>
States the result of executing a command as either the ID of the actor to whom the command was applied to (when succeeded) or an error string (when failed). actor ID, depending on whether or not the command succeeded. The method __<font color="#7fb800">apply_batch_sync()</font>__ in [carla.Client](#carla.Client) returns a list of these to summarize the execution of a batch.
@ -4188,33 +4248,29 @@ document.getElementById("snipets-container").innerHTML = null;
}
</script>
<div id ="carla.World.enable_environment_objects-snipet" style="display: none;">
<div id ="carla.World.unload_map_layer-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.World.enable_environment_objects
Snippet for carla.World.unload_map_layer
</p>
<div id="carla.World.enable_environment_objects-code" class="SnipetContent">
<div id="carla.World.unload_map_layer-code" class="SnipetContent">
```py
# This recipe turn visibility off and on for two specifc buildings on the map
# This recipe toggles off several layers in our "_Opt" maps
# Get the buildings in the world
world = client.get_world()
env_objs = world.get_environment_objects(carla.CityObjectLabel.Buildings)
# Load town one with minimum layout (roads, sidewalks, traffic lights and traffic signs)
# as well as buildings and parked vehicles
world = client.load_world('Town01_Opt', carla.MapLayer.Buildings | carla.MapLayer.ParkedVehicles)
# Access individual building IDs and save in a set
building_01 = env_objs[0]
building_02 = env_objs[1]
objects_to_toggle = {building_01.id, building_02.id}
# Toggle all buildings off
world.unload_map_layer(carla.MapLayer.Buildings)
# Toggle buildings off
world.enable_environment_objects(objects_to_toggle, False)
# Toggle buildings on
world.enable_environment_objects(objects_to_toggle, True)
# Toggle all parked vehicles off
world.unload_map_layer(carla.MapLayer.ParkedVehicles)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.enable_environment_objects-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.unload_map_layer-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
@ -4257,206 +4313,37 @@ while True:
</div>
<div id ="carla.World.unload_map_layer-snipet" style="display: none;">
<div id ="carla.ActorBlueprint.set_attribute-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.World.unload_map_layer
Snippet for carla.ActorBlueprint.set_attribute
</p>
<div id="carla.World.unload_map_layer-code" class="SnipetContent">
```py
# This recipe toggles off several layers in our "_Opt" maps
# Load town one with minimum layout (roads, sidewalks, traffic lights and traffic signs)
# as well as buildings and parked vehicles
world = client.load_world('Town01_Opt', carla.MapLayer.Buildings | carla.MapLayer.ParkedVehicles)
# Toggle all buildings off
world.unload_map_layer(carla.MapLayer.Buildings)
# Toggle all parked vehicles off
world.unload_map_layer(carla.MapLayer.ParkedVehicles)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.unload_map_layer-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.Vehicle.set_wheel_steer_direction-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.Vehicle.set_wheel_steer_direction
</p>
<div id="carla.Vehicle.set_wheel_steer_direction-code" class="SnipetContent">
```py
# Sets the appearance of the vehicles front wheels to 40°. Vehicle physics will not be affected.
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FR_Wheel, 40.0)
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FL_Wheel, 40.0)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.Vehicle.set_wheel_steer_direction-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.Client.__init__-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.Client.__init__
</p>
<div id="carla.Client.__init__-code" class="SnipetContent">
<div id="carla.ActorBlueprint.set_attribute-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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.Map.get_waypoint-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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.
# This recipe changes attributes of different type of blueprint actors.
# ...
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))
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.Map.get_waypoint-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<img src="/img/snipets_images/carla.Map.get_waypoint.jpg">
</div>
<div id ="carla.World.spawn_actor-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.WalkerAIController.stop-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.DebugHelper.draw_box-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<img src="/img/snipets_images/carla.DebugHelper.draw_box.jpg">
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.ActorBlueprint.set_attribute-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
@ -4520,6 +4407,67 @@ camera.listen(lambda image: image.save_to_disk('output/%06d.png' % image.frame,
</div>
<div id ="carla.World.load_map_layer-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.World.load_map_layer
</p>
<div id="carla.World.load_map_layer-code" class="SnipetContent">
```py
# This recipe toggles on several layers in our "_Opt" maps
# Load town one with only minimum layout (roads, sidewalks, traffic lights and traffic signs)
world = client.load_world('Town01_Opt', carla.MapLayer.None)
# Toggle all buildings on
world.load_map_layer(carla.MapLayer.Buildings)
# Toggle all foliage on
world.load_map_layer(carla.MapLayer.Foliage)
# Toggle all parked vehicles on
world.load_map_layer(carla.MapLayer.ParkedVehicles)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.load_map_layer-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.Map.get_waypoint-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<img src="/img/snipets_images/carla.Map.get_waypoint.jpg">
</div>
<div id ="carla.TrafficLight.set_state-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.TrafficLight.set_state
@ -4566,37 +4514,77 @@ if vehicle_actor.is_at_traffic_light():
</div>
<div id ="carla.ActorBlueprint.set_attribute-snipet" style="display: none;">
<div id ="carla.Vehicle.set_wheel_steer_direction-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.ActorBlueprint.set_attribute
Snippet for carla.Vehicle.set_wheel_steer_direction
</p>
<div id="carla.ActorBlueprint.set_attribute-code" class="SnipetContent">
<div id="carla.Vehicle.set_wheel_steer_direction-code" class="SnipetContent">
```py
# Sets the appearance of the vehicles front wheels to 40°. Vehicle physics will not be affected.
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FR_Wheel, 40.0)
vehicle.set_wheel_steer_direction(carla.VehicleWheelLocation.FL_Wheel, 40.0)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.Vehicle.set_wheel_steer_direction-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.DebugHelper.draw_box-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.DebugHelper.draw_box
</p>
<div id="carla.DebugHelper.draw_box-code" class="SnipetContent">
```py
# This recipe changes attributes of different type of blueprint actors.
# This recipe shows how to draw traffic light actor bounding boxes from a world snapshot.
# ...
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)
# ....
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)
# ...
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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.DebugHelper.draw_box-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<img src="/img/snipets_images/carla.DebugHelper.draw_box.jpg">
</div>
<div id ="carla.WalkerAIController.stop-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
@ -4673,31 +4661,103 @@ for i in range(0, len(all_actors), 2):
</div>
<div id ="carla.World.load_map_layer-snipet" style="display: none;">
<div id ="carla.World.enable_environment_objects-snipet" style="display: none;">
<p class="SnipetFont">
Snippet for carla.World.load_map_layer
Snippet for carla.World.enable_environment_objects
</p>
<div id="carla.World.load_map_layer-code" class="SnipetContent">
<div id="carla.World.enable_environment_objects-code" class="SnipetContent">
```py
# This recipe toggles on several layers in our "_Opt" maps
# This recipe turn visibility off and on for two specifc buildings on the map
# Load town one with only minimum layout (roads, sidewalks, traffic lights and traffic signs)
world = client.load_world('Town01_Opt', carla.MapLayer.None)
# Get the buildings in the world
world = client.get_world()
env_objs = world.get_environment_objects(carla.CityObjectLabel.Buildings)
# Toggle all buildings on
world.load_map_layer(carla.MapLayer.Buildings)
# Access individual building IDs and save in a set
building_01 = env_objs[0]
building_02 = env_objs[1]
objects_to_toggle = {building_01.id, building_02.id}
# Toggle all foliage on
world.load_map_layer(carla.MapLayer.Foliage)
# Toggle all parked vehicles on
world.load_map_layer(carla.MapLayer.ParkedVehicles)
# Toggle buildings off
world.enable_environment_objects(objects_to_toggle, False)
# Toggle buildings on
world.enable_environment_objects(objects_to_toggle, True)
```
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.load_map_layer-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
<button id="button1" class="CopyScript" onclick="CopyToClipboard('carla.World.enable_environment_objects-code')">Copy snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.Client.__init__-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
<div id ="carla.World.spawn_actor-snipet" style="display: none;">
<p class="SnipetFont">
Snippet 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 snippet</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button id="button1" class="CloseSnipet" onclick="CloseSnipet()">Close snippet</button><br><br>
</div>
@ -4737,4 +4797,4 @@ for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click",function(){ButtonAction(buttons[i].id);},true);
}
window.onresize = WindowResize;
</script>
</script>

View File

@ -711,34 +711,39 @@ This raw [carla.Image](python_api.md#carla.Image) can be stored and converted it
raw_image.save_to_disk("path/to/save/converted/image",carla.ColorConverter.cityScapesPalette)
```
The following tags are currently available:
The following tags are currently available (Note, tags changed from version 0.9.13 to 0.9.14):
| Value | Tag | Converted color | Description |
| ----------------------------------- | ----------------------------------- | ----------------------------------- | ----------------------------------- |
| `0` | Unlabeled | `(0, 0, 0)` | Elements that have not been categorized are considered `Unlabeled`. This category is meant to be empty or at least contain elements with no collisions. |
| `1` | Building | `(70, 70, 70)` | Buildings like houses, skyscrapers,... and the elements attached to them. <br> E.g. air conditioners, scaffolding, awning or ladders and much more. |
| `2` | Fence | `(100, 40, 40)` | Barriers, railing, or other upright structures. Basically wood or wire assemblies that enclose an area of ground. |
| `3` | Other | `(55, 90, 80)` | Everything that does not belong to any other category. |
| `4` | Pedestrian | `(220, 20, 60)` | Humans that walk or ride/drive any kind of vehicle or mobility system. <br> E.g. bicycles or scooters, skateboards, horses, roller-blades, wheel-chairs, etc. |
| `5` | Pole | `(153, 153, 153)` | Small mainly vertically oriented pole. If the pole has a horizontal part (often for traffic light poles) this is also considered pole. <br> E.g. sign pole, traffic light poles. |
| `6` | RoadLine | `(157, 234, 50)` | The markings on the road. |
| `7` | Road | `(128, 64, 128)` | Part of ground on which cars usually drive. <br> E.g. lanes in any directions, and streets. |
| `8` | SideWalk | `(244, 35, 232)` | Part of ground designated for pedestrians or cyclists. Delimited from the road by some obstacle (such as curbs or poles), not only by markings. This label includes a possibly delimiting curb, traffic islands (the walkable part), and pedestrian zones. |
| `9` | Vegetation | `(107, 142, 35)` | Trees, hedges, all kinds of vertical vegetation. Ground-level vegetation is considered `Terrain`. |
| `10` | Vehicles | `(0, 0, 142)` | Cars, vans, trucks, motorcycles, bikes, buses, trains. |
| `11` | Wall | `(102, 102, 156)` | Individual standing walls. Not part of a building. |
| `12` | TrafficSign | `(220, 220, 0)` | Signs installed by the state/city authority, usually for traffic regulation. This category does not include the poles where signs are attached to. <br> E.g. traffic- signs, parking signs, direction signs... |
| `13` | Sky | `(70, 130, 180)` | Open sky. Includes clouds and the sun. |
| `14` | Ground | `(81, 0, 81)` | Any horizontal ground-level structures that does not match any other category. For example areas shared by vehicles and pedestrians, or flat roundabouts delimited from the road by a curb. |
| `15` | Bridge | `(150, 100, 100)` | Only the structure of the bridge. Fences, people, vehicles, an other elements on top of it are labeled separately. |
| `16` | RailTrack | `(230, 150, 140)` | All kind of rail tracks that are non-drivable by cars. <br> E.g. subway and train rail tracks. |
| `17` | GuardRail | `(180, 165, 180)` | All types of guard rails/crash barriers. |
| `18` | TrafficLight | `(250, 170, 30)` | Traffic light boxes without their poles. |
| `19` | Static | `(110, 190, 160)` | Elements in the scene and props that are immovable. <br> E.g. fire hydrants, fixed benches, fountains, bus stops, etc. |
| `20` | Dynamic | `(170, 120, 50)` | Elements whose position is susceptible to change over time. <br> E.g. Movable trash bins, buggies, bags, wheelchairs, animals, etc. |
| `21` | Water | `(45, 60, 150)` | Horizontal water surfaces. <br> E.g. Lakes, sea, rivers. |
| `22` | Terrain | `(145, 170, 100)` | Grass, ground-level vegetation, soil or sand. These areas are not meant to be driven on. This label includes a possibly delimiting curb. |
| `1` | Roads | `(128, 64, 128)` | Part of ground on which cars usually drive. <br> E.g. lanes in any directions, and streets. |
| `2` | SideWalks | `(244, 35, 232)` | Part of ground designated for pedestrians or cyclists. Delimited from the road by some obstacle (such as curbs or poles), not only by markings. This label includes a possibly delimiting curb, traffic islands (the walkable part), and pedestrian zones. |
| `3` | Building | `(70, 70, 70)` | Buildings like houses, skyscrapers,... and the elements attached to them. <br> E.g. air conditioners, scaffolding, awning or ladders and much more. |
| `4` | Wall | `(102, 102, 156)` | Individual standing walls. Not part of a building. |
| `5` | Fence | `(190, 153, 153)` | Barriers, railing, or other upright structures. Basically wood or wire assemblies that enclose an area of ground. |
| `6` | Pole | `(153, 153, 153)` | Small mainly vertically oriented pole. If the pole has a horizontal part (often for traffic light poles) this is also considered pole. <br> E.g. sign pole, traffic light poles. |
| `7` | TrafficLight | `(250, 170, 30)` | Traffic light boxes without their poles. |
| `8` | TrafficSign | `(220, 220, 0)` | Signs installed by the state/city authority, usually for traffic regulation. This category does not include the poles where signs are attached to. <br> E.g. traffic- signs, parking signs, direction signs... |
| `9` | Vegetation | `(107, 142, 35)` | Trees, hedges, all kinds of vertical vegetation. Ground-level vegetation is considered `Terrain`. |
| `10` | Terrain | `(152, 251, 152)` | Grass, ground-level vegetation, soil or sand. These areas are not meant to be driven on. This label includes a possibly delimiting curb. |
| `11` | Sky | `(70, 130, 180)` | Open sky. Includes clouds and the sun. |
| `12` | Pedestrian | `(220, 20, 60)` | Humans that walk |
| `13` | Rider | `(255, 0, 0)` | Humans that ride/drive any kind of vehicle or mobility system <br> E.g. bicycles or scooters, skateboards, horses, roller-blades, wheel-chairs, etc. . |
| `14` | Car | `(0, 0, 142)` | Cars, vans |
| `15` | Truck | `(0, 0, 70)` | Trucks |
| `16` | Bus | `(0, 60, 100)` | Busses |
| `17` | Train | `(0, 60, 100)` | Trains |
| `18` | Motorcycle | `(0, 0, 230)` | Motorcycle, Motorbike |
| `19` | Bicycle | `(119, 11, 32)` | Bicylces |
| `20` | Static | `(110, 190, 160)` | Elements in the scene and props that are immovable. <br> E.g. fire hydrants, fixed benches, fountains, bus stops, etc. |
| `21` | Dynamic | `(170, 120, 50)` | Elements whose position is susceptible to change over time. <br> E.g. Movable trash bins, buggies, bags, wheelchairs, animals, etc. |
| `22` | Other | `(55, 90, 80)` | Everything that does not belong to any other category. |
| `23` | Water | `(45, 60, 150)` | Horizontal water surfaces. <br> E.g. Lakes, sea, rivers. |
| `24` | RoadLine | `(157, 234, 50)` | The markings on the road. |
| `25` | Ground | `(81, 0, 81)` | Any horizontal ground-level structures that does not match any other category. For example areas shared by vehicles and pedestrians, or flat roundabouts delimited from the road by a curb. |
| `26` | Bridge | `(150, 100, 100)` | Only the structure of the bridge. Fences, people, vehicles, an other elements on top of it are labeled separately. |
| `27` | RailTrack | `(230, 150, 140)` | All kind of rail tracks that are non-drivable by cars. <br> E.g. subway and train rail tracks. |
| `28` | GuardRail | `(180, 165, 180)` | All types of guard rails/crash barriers. |
<br>
!!! Note

View File

@ -6,7 +6,7 @@
This document refers to the latest version of CARLA. For documentation of previous versions, select the required version in the bottom right hand corner where you see this button: ![docs_version_panel](img/docs_version_panel.jpg)
CARLA is an open-source autonomous driving simulator. It was built from scratch to serve as a modular and flexible API to address a range of tasks involved in the problem of autonomous driving. One of the main goals of CARLA is to help democratize autonomous driving R&D, serving as a tool that can be easily accessed and customized by users. To do so, the simulator has to meet the requirements of different use cases within the general problem of driving (e.g. learning driving policies, training perception algorithms, etc.). CARLA is grounded on Unreal Engine to run the simulation and uses the OpenDRIVE standard (1.4 as today) to define roads and urban settings. Control over the simulation is granted through an API handled in Python and C++ that is constantly growing as the project does.
CARLA is an open-source autonomous driving simulator. It was built from scratch to serve as a modular and flexible API to address a range of tasks involved in the problem of autonomous driving. One of the main goals of CARLA is to help democratize autonomous driving R&D, serving as a tool that can be easily accessed and customized by users. To do so, the simulator has to meet the requirements of different use cases within the general problem of driving (e.g. learning driving policies, training perception algorithms, etc.). CARLA is grounded on Unreal Engine to run the simulation and uses the ASAM OpenDRIVE standard (1.4 as today) to define roads and urban settings. Control over the simulation is granted through an API handled in Python and C++ that is constantly growing as the project does.
In order to smooth the process of developing, training and validating driving systems, CARLA evolved to become an ecosystem of projects, built around the main platform by the community. In this context, it is important to understand some things about how does CARLA work, so as to fully comprehend its capabilities.

View File

@ -106,7 +106,7 @@ The package is a compressed file named __CARLA_version.number__. Download and ex
---
## Import additional assets
Each release has it's own additional package of extra assets and maps. This additional package includes the maps __Town06__, __Town07__, and __Town10__. These are stored separately to reduce the size of the build, so they can only be imported after the main package has been installed.
Each release has it's own additional package of extra assets and maps. This additional package includes the maps __Town06__ and __Town07__. These are stored separately to reduce the size of the build, so they can only be imported after the main package has been installed.
__1.__ [Download](https://github.com/carla-simulator/carla/blob/master/Docs/download.md) the appropriate package for your desired version of CARLA.

View File

@ -13,7 +13,7 @@ This tutorial details how to add a new vehicle to CARLA. There are two sections,
---
## Add a 4 wheeled vehicle
Vehicles added to CARLA need to use a __common base skeleton__ which is found [__here__](https://carla-assets.s3.eu-west-3.amazonaws.com/fbx/VehicleSkeleton.rar). This link will download a folder called `VehicleSkeleton.rar` which contains the base skeleton in two different `.fbx` formats, one in ASCII and the other in binary. The format you use will depend on your 3D modeling software requirements.
Vehicles added to CARLA need to use a __common base skeleton__ which is found [__here__](https://carla-assets.s3.us-east-005.backblazeb2.com/fbx/VehicleSkeleton.rar). This link will download a folder called `VehicleSkeleton.rar` which contains the base skeleton in two different `.fbx` formats, one in ASCII and the other in binary. The format you use will depend on your 3D modeling software requirements.
__The positions of the skeleton bones can be changed but any other manipulation such as rotation, addition of new bones, or changing the current hierarchy will lead to errors. __
@ -52,7 +52,7 @@ We recommend that you divide the vehicle into the following materials:
- __Lights__: Headlights, indicator lights, etc.
- __LightGlass_Ext__: A layer of glass that allows visibility from the outside to the inside of the light.
- __LightGlass_Int__: A layer of glass that allows visibility from the inside to the outside of the light.
- __LicensePlate__: A rectangular plane of 29x12 cm. You can use the CARLA provided `.fbx` for best results, download it [here](https://carla-assets.s3.eu-west-3.amazonaws.com/fbx/LicensePlate.rar). The texture will be assigned automatically in Unreal Engine.
- __LicensePlate__: A rectangular plane of 29x12 cm. You can use the CARLA provided `.fbx` for best results, download it [here](https://carla-assets.s3.us-east-005.backblazeb2.com/fbx/LicensePlate.rar). The texture will be assigned automatically in Unreal Engine.
- __Interior__: Any other details that don't fit in the above sections can go into _Interior_.
Materials should be named using the format `M_CarPart_CarName`, e.g., `M_Bodywork_Mustang`.
@ -278,7 +278,7 @@ All other parameters such as engine, transmission, steering curve, are the same
---
## Add a 2 wheeled vehicle
Adding 2 wheeled vehicles is similar to adding a 4 wheeled one but due to the complexity of the animation you'll need to set up aditional bones to guide the driver's animation. [Here](https://carla-assets.s3.eu-west-3.amazonaws.com/fbx/BikeSkeleton.rar) is the link to the reference skeleton for 2 wheeled vehicles.
Adding 2 wheeled vehicles is similar to adding a 4 wheeled one but due to the complexity of the animation you'll need to set up aditional bones to guide the driver's animation. [Here](https://carla-assets.s3.us-east-005.backblazeb2.com/fbx/BikeSkeleton.rar) is the link to the reference skeleton for 2 wheeled vehicles.
As with the 4 wheeled vehicles, orient the model towards positive "x" and every bone axis towards
positive x and with the z axis facing upwards.

View File

@ -23,9 +23,9 @@ In CARLA, there is a set of master materials that are used as templates for the
* __M_CarInterior_Master__ — Material applied to the inside of the car.
* __M_CarLightsGlass_Master__ — Material applied to the glass covering car lights.
* __M_CarWindows_Master__ — Material applied to the windows.
* __M_CarLicensePlate_Master__ — Material applied to the license plate.
* __M_CarVehicleLights_Master__ — Material applied to the car lights as an emissive texure.
* __M_CarVehicleLigthsSirens_Master__ — Material applied to the sirens, if applicable.
* __M_LicensePlate_Master__ — Material applied to the license plate.
* __M_VehicleLights_Master__ — Material applied to the car lights as an emissive texure.
* __M_VehicleLights_Sirens_Master__ — Material applied to the sirens, if applicable.
---
## Customize car materials
@ -142,7 +142,7 @@ Similarly to car materials, a building material can be greatly changed if desire
* `Color` — Tint to be applied based on the white area on the __Diffuse__ `Alpha` texture.
* `Emissive Texture` — Enable the usage of an __Emissive__ texture.
* `EmissiveColor` — Tint to be applied based on the white area on the __ORME__ `Emissive mask` texture.
* `Emissive atenuance` — Factor that divides the intensity stated in __BP_Lights__ to obtain proper emissive values.
* `Emissive attenuance` — Factor that divides the intensity stated in __BP_Lights__ to obtain proper emissive values.
* `RoughnessCorrection` — Changes the intensity of the roughness map.
* `MetallicCorrection` — Changes the intensity of the metallic map.
* `NormalFlatness` — Changes the intensity of the normal map.

View File

@ -67,7 +67,7 @@ __4.3__ Press `Compile` in the toolbar above and save the changes.
## Physics colliders
!!! Important
This tutorial is based on a [contribution](https://bitbucket.org/yankagan/carla-content/wiki/Home) made by __[yankagan](https://github.com/yankagan)__! The contributor also wants to aknowledge __Francisco E__ for the tutorial on [how to import custom collisions in UE](https://www.youtube.com/watch?v=SEH4f0HrCDM).
This tutorial is based on a [contribution](https://bitbucket.org/yankagan/carla-content/wiki/Home) made by __[yankagan](https://github.com/yankagan)__! The contributor also wants to acknowledge __Francisco E__ for the tutorial on [how to import custom collisions in UE](https://www.youtube.com/watch?v=SEH4f0HrCDM).
[This video](https://www.youtube.com/watch?v=CXK2M2cNQ4Y) shows the results achieved after following this tutorial.

View File

@ -50,10 +50,15 @@ camera.listen(image_queue.put)
We want to take 3D points from the simulation and project them into the 2D plane of the camera. Firstly, we need to construct the camera projection matrix:
```py
def build_projection_matrix(w, h, fov):
def build_projection_matrix(w, h, fov, is_behind_camera=False):
focal = w / (2.0 * np.tan(fov * np.pi / 360.0))
K = np.identity(3)
K[0, 0] = K[1, 1] = focal
if is_behind_camera:
K[0, 0] = K[1, 1] = -focal
else:
K[0, 0] = K[1, 1] = focal
K[0, 2] = w / 2.0
K[1, 2] = h / 2.0
return K
@ -99,6 +104,7 @@ fov = camera_bp.get_attribute("fov").as_float()
# Calculate the camera projection matrix to project from 3D -> 2D
K = build_projection_matrix(image_w, image_h, fov)
K_b = build_projection_matrix(image_w, image_h, fov, is_behind_camera=True)
```
## Bounding boxes
@ -191,7 +197,7 @@ while True:
forward_vec = vehicle.get_transform().get_forward_vector()
ray = bb.location - vehicle.get_transform().location
if forward_vec.dot(ray) > 1:
if forward_vec.dot(ray) > 0:
# Cycle through the vertices
verts = [v for v in bb.get_world_vertices(carla.Transform())]
for edge in edges:
@ -249,6 +255,11 @@ cv2.waitKey(1)
Now we use a modified game loop to draw the vehicle bounding boxes:
```py
def point_in_canvas(pos, img_h, img_w):
"""Return true if point is in canvas"""
if (pos[0] >= 0) and (pos[0] < img_w) and (pos[1] >= 0) and (pos[1] < img_h):
return True
return False
while True:
# Retrieve and reshape the image
@ -279,12 +290,28 @@ while True:
forward_vec = vehicle.get_transform().get_forward_vector()
ray = npc.get_transform().location - vehicle.get_transform().location
if forward_vec.dot(ray) > 1:
p1 = get_image_point(bb.location, K, world_2_camera)
if forward_vec.dot(ray) > 0:
verts = [v for v in bb.get_world_vertices(npc.get_transform())]
for edge in edges:
p1 = get_image_point(verts[edge[0]], K, world_2_camera)
p2 = get_image_point(verts[edge[1]], K, world_2_camera)
p1_in_canvas = point_in_canvas(p1, image_h, image_w)
p2_in_canvas = point_in_canvas(p2, image_h, image_w)
if not p1_in_canvas and not p2_in_canvas:
continue
ray0 = verts[edge[0]] - camera.get_transform().location
ray1 = verts[edge[1]] - camera.get_transform().location
cam_forward_vec = camera.get_transform().get_forward_vector()
# One of the vertex is behind the camera
if not (cam_forward_vec.dot(ray0) > 0):
p1 = get_image_point(verts[edge[0]], K_b, world_2_camera)
if not (cam_forward_vec.dot(ray1) > 0):
p2 = get_image_point(verts[edge[1]], K_b, world_2_camera)
cv2.line(img, (int(p1[0]),int(p1[1])), (int(p2[0]),int(p2[1])), (255,0,0, 255), 1)
cv2.imshow('ImageWindowName',img)
@ -330,7 +357,7 @@ while True:
forward_vec = vehicle.get_transform().get_forward_vector()
ray = npc.get_transform().location - vehicle.get_transform().location
if forward_vec.dot(ray) > 1:
if forward_vec.dot(ray) > 0:
p1 = get_image_point(bb.location, K, world_2_camera)http://host.robots.ox.ac.uk/pascal/VOC/
verts = [v for v in bb.get_world_vertices(npc.get_transform())]
x_max = -10000
@ -408,7 +435,7 @@ while True:
if dist < 50:
forward_vec = vehicle.get_transform().get_forward_vector()
ray = npc.get_transform().location - vehicle.get_transform().location
if forward_vec.dot(ray) > 1:
if forward_vec.dot(ray) > 0:
p1 = get_image_point(bb.location, K, world_2_camera)
verts = [v for v in bb.get_world_vertices(npc.get_transform())]
x_max = -10000

View File

@ -25,7 +25,7 @@ This page shows you how to generate a `.sim` file, explains how vehicle dimensio
__For Ubuntu__:
1. Download the plugin [here](https://www.carsim.com/users/unreal_plugin/unreal_plugin_2020_0.php).
2. Replace the file `CarSim.Build.cs` with the file found [here](https://carla-releases.s3.eu-west-3.amazonaws.com/Backup/CarSim.Build.cs) in order to use the correct solver for Ubuntu.
2. Replace the file `CarSim.Build.cs` with the file found [here](https://carla-assets.s3.us-east-005.backblazeb2.com/Backup/CarSim.Build.cs) in order to use the correct solver for Ubuntu.
3. This step can be skipped if you are using the packaged version of CARLA. The packaged version has already been compiled using this flag but if you are building CARLA from source then you will need to compile the server with the `--carsim` flag.

View File

@ -147,7 +147,7 @@ def build_projection_matrix(w, h, fov):
## Build the skeleton
Now we can put the moving parts together. First, gather the bone coordinates from the simulation using `pedestrian.get_bones()` and then put together the skeleton and project it onto the 2D imaging plane of the camera sensor. The bones are joined into the complete skeleton using the pairs defined in __skeleton.txt__ that can be downloaded [__here__](https://carla-assets.s3.eu-west-3.amazonaws.com/fbx/skeleton.txt).
Now we can put the moving parts together. First, gather the bone coordinates from the simulation using `pedestrian.get_bones()` and then put together the skeleton and project it onto the 2D imaging plane of the camera sensor. The bones are joined into the complete skeleton using the pairs defined in __skeleton.txt__ that can be downloaded [__here__](https://carla-assets.s3.us-east-005.backblazeb2.com/fbx/skeleton.txt).
We need a function to iterate through the bone pairs defined in __skeleton.txt__ and join the bone coordinates into lines that can be overlayed onto a camera sensor image.

View File

@ -568,7 +568,7 @@ The script places the sensor on the hood of the car, and rotated a bit upwards.
The callback is a bit more complex this time, showing more of its capabilities. It will draw the points captured by the radar on the fly. The points will be colored depending on their velocity regarding the ego vehicle.
* __Blue__ for points approaching the vehicle.
* __Read__ for points moving away from it.
* __Red__ for points moving away from it.
* __White__ for points static regarding the ego vehicle.
```py

View File

@ -8,7 +8,7 @@ Firstly, we need to load the Unreal Editor and load a CARLA map, follow the inst
![select_building](../img/tuto_G_texture_streaming/building_selected.png)
We have selected __BP_Apartment04_v5_Opt__ for texture manipulation, the name can be seen in the World Outliner panel. __Make sure to hover over the name in the World Outliner and use the name defined in the tooltip__. The the internal name may differ from the title displayed in the list. In this case, the internal name is actually __BP_Apartment04_v5_Opt_2__.
We have selected __BP_Apartment04_v05_Opt__ for texture manipulation, the name can be seen in the World Outliner panel. __Make sure to hover over the name in the World Outliner and use the name defined in the tooltip__. The the internal name may differ from the title displayed in the list. In this case, the internal name is actually __BP_Apartment04_v05_Opt_2__.
![tooltip](../img/tuto_G_texture_streaming/tooltip.png)

View File

@ -32,7 +32,7 @@ You will need to install RoadRunner. You can follow the [installation guide][rr_
## Build a map in RoadRunner
The specifics of how to build a map in RoadRunner go beyond the scope of this guide, however, there are video tutorials available in the [RoadRunner documentation][rr_tutorials].
The specifics of how to build a map in RoadRunner go beyond the scope of this guide, however, there is an introductory tutorial series available on the [MathWorks website][rr_intro_tutorials] and there are video tutorials for specific actions available in the [RoadRunner documentation][rr_tutorials].
__Keep in mind that a map heavy with props can slow the import process significantly.__ This is because Unreal Engine needs to convert every mesh to an Unreal asset. If you plan to import your map into a source build version of CARLA, we highly recommend that you only create the road layout in RoadRunner and leave any customization until after the map has been imported into Unreal Engine. CARLA provides several tools that you can use in the Unreal Engine editor to simplify the customization process.
@ -41,6 +41,7 @@ __Keep in mind that a map heavy with props can slow the import process significa
## Export a map in RoadRunner
[rr_tutorials]: https://www.mathworks.com/support/search.html?fq=asset_type_name:video%20category:roadrunner/index&page=1&s_tid=CRUX_topnav
[rr_intro_tutorials]: https://www.mathworks.com/solutions/automated-driving/roadrunner-tutorial.html
Below is a basic guideline to export your custom map from RoadRunner. You can find more detailed information about how to export to CARLA in [MathWorks' documentation][exportlink].
@ -104,4 +105,4 @@ If you have any questions about the process, then you can ask in the [forum](htt
<a href="https://github.com/carla-simulator/carla/discussions" target="_blank" class="btn btn-neutral" title="Go to the CARLA forum">
CARLA forum</a>
</p>
</div>
</div>

View File

@ -78,6 +78,10 @@ __6.__ A `<mapName>.bin` file will be created. This file contains the informatio
__7.__ Test the pedestrian navigation by starting a simulation and running the example script `generate_traffic.py` in `PythonAPI/examples`.
!!! note
**If you need to rebuild the pedestrian navigation** after updating the map, ensure to delete the CARLA cache. This is normally found in the home directory in Ubuntu (i.e. `cd ~`), or in the user directory in Windows (the directory assigned to the environment variable `USERPROFILE`), remove the folder named `carlaCache` and all of its contents, it is likely to be large in size.
---
If you have any questions about the process, then you can ask in the [forum](https://github.com/carla-simulator/carla/discussions).

View File

@ -22,6 +22,9 @@ In this tutorial we will cover the process of creating a simple map for use with
* [Next steps](#next-steps)
* __[Trees and vegetation](#trees-and-vegetation)__
* [Foliage tool](#foliage-tool)
* __[Exporting a map](#exporting-a-map)__
* [Exporting a map as a separate package](#exporting-a-map-as-a-separate-package)
* [Exporting a map as part of a complete CARLA package](#exporting-a-map-as-part-of-a-complete-carla-package)
@ -403,12 +406,56 @@ Navigate to the vegetation folder in the CARLA content library: `Carla > Static
A useful tool for trees and vegetation is the [__Unreal Engine foliage tool__](https://docs.unrealengine.com/4.27/en-US/BuildingWorlds/Foliage/). Activate the tool by selecting the `mode` from the mode dropdown in the toolbar.
![foliage_tool](img/tuto_content_authoring_maps/select_foliage_tool.png)
![foliage_tool](img/tuto_content_authoring_maps/select_foliage_tool.gif)
Drag your desired foliage item into the box labeled `+ Drop Foliage Here`. Set an appropriate density in the density field, then paint into the map with your foliage item.
![foliage_paint](img/tuto_content_authoring_maps/foliage_paint.gif)
---
## Exporting a map
### Exporting a map as a separate package
To export a map as a map package that can be ingested into a standalone CARLA package installation, use the `make package` command as follows:
```sh
make package ARGS="--packages=<mapName>"
```
The `<mapName>` must point to a json file located in `CARLA_ROOT/Unreal/CarlaUE4/Content/Carla/Config` named *mapName.Package.json* which has the following structure:
```json
{
"maps": [
{
"path": "/Game/Carla/Maps/",
"name": "MyMap",
"use_carla_materials": true
}
],
"props": []
}
```
Your map should have been saved as `MyMap.umap` file in the `CARLA_ROOT/Unreal/CarlaUE4/Content/Carla/Maps` directory.
The exported map archive will be saved in the `Dist` folder on Linux and the `/Build/UE4Carla/` folder on Windows.
### Exporting a map as part of a complete CARLA package
To export the map as part of a complete CARLA package, such that the map is available on launch of the package, include the following line in the `DefaultGame.ini` file in `CARLA_ROOT/Unreal/CarlaUE4/Config/`:
```
+MapsToCook=(FilePath="/Game/Carla/Maps/MyMap")
```
This line should be added in the `[/Script/UnrealEd.ProjectPackagingSettings]` section, preferably next to the other `MapsToCook(...)` entries. Then run `make package` command to build a package containing your map. The exported CARLA package with your map will be saved in the `Dist` folder on Linux and the `/Build/UE4Carla/` folder on Windows.
---
## Next steps
Continue customizing your map using the tools and guides below:

View File

@ -1,36 +1,36 @@
# Content authoring - vehicles
CARLA provides a comprehensive set of vehicles out of the box in the blueprint library. CARLA allows the user to expand upon this with custom vehicles for maximum extensibility.
CARLA provides a comprehensive set of vehicles out of the box in the blueprint library. CARLA allows the user to expand upon this with custom vehicles for maximum extensibility.
3D modelling of detailed vehicles is highly complex and requires a significant degree of skill. We therefore refer the reader to alternative sources of documentation on 3D modelling, since this is beyond the scope of this guide. There are, however, numerous sources of vehicle models in both free and proprietary online repositories. Hence the user has many options to turn to for creating custom vehicles for use in CARLA.
The key factors in preparing a custom vehicle for CARLA lie in rigging the vehicle armature and then importing into the Unreal Engine. After rigging and importing, blueprints need to be set for the car and the wheels. Then apply materials and add the glass parts of the vehicle. We will cover these steps in the following guide.
* __[Modeling](#modeling)__
* [Naming conventions](#naming-conventions)
* __[Rigging](#rigging-the-vehicle-using-an-armature)__
* [Import](#import)
* __[Modeling](#modeling)__
* [Naming conventions](#naming-conventions)
* __[Rigging](#rigging-the-vehicle-using-an-armature)__
* [Import](#import)
* [Armature](#add-an-armature)
* [Parenting](#parenting)
* [Assignment](#assigning-car-parts-to-bones)
* [Assignment](#assigning-car-parts-to-bones)
* [Blender add-on](#blender-ue4-vehicle-rigging-add-on)
* [Export](#export)
* __[Import into Unreal Engine](#importing-into-unreal-engine)__
* [Physics asset](#setting-the-physics-asset)
* [Export](#export)
* __[Import into Unreal Engine](#importing-into-unreal-engine)__
* [Physics asset](#setting-the-physics-asset)
* [Animation](#creating-the-animation)
* [Blueprint](#creating-the-blueprint)
* __[Materials](#materials)__
* __[Materials](#materials)__
* [Applying materials](#applying-a-material-to-your-vehicle)
* [Color](#color)
* [Clear coat](#clear-coat)
* [Orange peel](#orange-peel)
* [Flakes](#flakes)
* [Dust](#dust)
* __[Glass](#glass)__
* __[Glass](#glass)__
* [Glass meshes](#glass-meshes)
* [Glass material](#glass-material)
* [Single layer glass](#single-layer-glass)
* __[Wheels](#wheels)__
* __[Wheels](#wheels)__
* [Wheel blueprint](#wheel-blueprint)
* [Collision mesh](#collision-mesh)
* [Tire configuration](#tire-configuration)
@ -41,7 +41,7 @@ The key factors in preparing a custom vehicle for CARLA lie in rigging the vehic
## Modeling
Vehicles should have between 50,000 and 100,000 faces. We recommend triangulating the model prior to export as best practice. CARLA vehicles are modeled using the size and scale of actual cars as reference. Please ensure you pay careful attention to the units of your 3D application. Some work in centimeters while others work in meters.
Vehicles should have between 50,000 and 100,000 faces. We recommend triangulating the model prior to export as best practice. CARLA vehicles are modeled using the size and scale of actual cars as reference. Please ensure you pay careful attention to the units of your 3D application. Some work in centimeters while others work in meters.
### Naming conventions
@ -53,7 +53,7 @@ For ease and consistency we recommend that you divide the vehicle into the follo
- __Lights__: Headlights, indicator lights, etc.
- __LightGlass_Ext__: A layer of glass that allows visibility from the outside to the inside of the light.
- __LightGlass_Int__: A layer of glass that allows visibility from the inside to the outside of the light.
- __LicensePlate__: A rectangular plane of 29x12 cm. You can use the CARLA provided `.fbx` for best results, download it [here](https://carla-assets.s3.eu-west-3.amazonaws.com/fbx/LicensePlate.rar). The texture will be assigned automatically in Unreal Engine.
- __LicensePlate__: A rectangular plane of 29x12 cm. You can use the CARLA provided `.fbx` for best results, download it [here](https://carla-assets.s3.us-east-005.backblazeb2.com/fbx/LicensePlate.rar). The texture will be assigned automatically in Unreal Engine.
- __Interior__: Any other details that don't fit in the above sections can go into _Interior_.
Materials should be named using the format `M_CarPart_CarName`, e.g, `M_Bodywork_Mustang`.
@ -62,11 +62,11 @@ Textures should be named using the format `T_CarPart_CarName`, e.g, `T_Bodywork_
## Rigging the vehicle using an armature
To look realistic within the simulation, the car needs to have rotating and wheels, the front pair of which can turn with steering inputs. Therefore to prepare a vehicle for CARLA, an armature needs to be rigged to the car to identify the wheels and allow their movement.
To look realistic within the simulation, the car needs to have rotating and wheels, the front pair of which can turn with steering inputs. Therefore to prepare a vehicle for CARLA, an armature needs to be rigged to the car to identify the wheels and allow their movement.
### Import
### Import
Import or model the vehicle model mesh in your 3D modelling application. In this guide we will use Blender 3D. Ensure that the wheels are separable from the main body. Each wheel must be accessible as a distinct object.
Import or model the vehicle model mesh in your 3D modelling application. In this guide we will use Blender 3D. Ensure that the wheels are separable from the main body. Each wheel must be accessible as a distinct object.
![model_in_blender](img/tuto_content_authoring_vehicles/import_model_blender.png)
@ -74,23 +74,23 @@ It is important to ensure that the vehicle faces in the positive X direction, so
### Add an armature
Now add an armature to the center of the vehicle, ensure the object is properly centered, the root of the armature bone should be set at the origin. Switch to edit mode and rotate the armature 90 around the x axis.
Now add an armature to the center of the vehicle, ensure the object is properly centered, the root of the armature bone should be set at the origin. Switch to edit mode and rotate the armature 90 around the x axis.
![armature_init](img/tuto_content_authoring_vehicles/vehicle_base_bone.png)
Now select the armature and add 4 more bones. Each of these bones needs to be located such that the root of the bone coincides with the centre of the each wheel. This can be achieved by locating the 3D cursor at the center of each wheel in edit mode. Select one of the wheels in object mode, select a vertex, press A to select all vertices then `Shift+S` and select `Cursor to selected`. This will locate the cursor in the center of the wheel. Then, in object mode, select the armature, switch to edit mode, select a bone and choose `Selection to cursor`. Your bone will now coincide with the wheel. Rotate each bone such that it lines up with the base of the armature.
Now select the armature and add 4 more bones. Each of these bones needs to be located such that the root of the bone coincides with the centre of the each wheel. This can be achieved by locating the 3D cursor at the center of each wheel in edit mode. Select one of the wheels in object mode, select a vertex, press A to select all vertices then `Shift+S` and select `Cursor to selected`. This will locate the cursor in the center of the wheel. Then, in object mode, select the armature, switch to edit mode, select a bone and choose `Selection to cursor`. Your bone will now coincide with the wheel. Rotate each bone such that it lines up with the base of the armature.
For each wheel, it is recommended to name the bone according to the wheel it needs to be coupled to, this will help in identification later when you need to assign vertex groups to each bone.
For each wheel, it is recommended to name the bone according to the wheel it needs to be coupled to, this will help in identification later when you need to assign vertex groups to each bone.
![armature_full](img/tuto_content_authoring_vehicles/all_vehicle_bones.png)
### Parenting
### Parenting
Now select all the parts of the body and all 4 wheels using shift or control in the project outliner, then control select the armature you have created (this order is important, it won't work if you select these in reverse order). Press `Ctrl+p` and select `With empty groups` to bind the mesh to the armature.
Now select all the parts of the body and all 4 wheels using shift or control in the project outliner, then control select the armature you have created (this order is important, it won't work if you select these in reverse order). Press `Ctrl+p` and select `With empty groups` to bind the mesh to the armature.
![bind_armature](img/tuto_content_authoring_vehicles/bind_armature.gif)
Now you have parented the mesh to the armature, you now need to assign each wheel to its respective bone. Select a wheel either in the outliner or the editor. Switch to edit mode, and select all the vertices of the wheel (shortcut - `a`).
Now you have parented the mesh to the armature, you now need to assign each wheel to its respective bone. Select a wheel either in the outliner or the editor. Switch to edit mode, and select all the vertices of the wheel (shortcut - `a`).
### Assigning car parts to bones
@ -108,9 +108,9 @@ There is a very useful add on for blender for rigging a vehicle for import into
### Export
Now we will export our rigged model into FBX format for import into Unreal Engine. Select `Export > FBX (.fbx)` from the File menu. In the `Object Types` section of the `Include` panel, shift select the `Armature` and `Mesh` options.
Now we will export our rigged model into FBX format for import into Unreal Engine. Select `Export > FBX (.fbx)` from the File menu. In the `Object Types` section of the `Include` panel, shift select the `Armature` and `Mesh` options.
In the `Transform` panel. Change `Forward` to `X Forward` and change `Up` to `Z Up`. This is important to ensure the vehicle is oriented correctly in the Unreal Engine.
In the `Transform` panel. Change `Forward` to `X Forward` and change `Up` to `Z Up`. This is important to ensure the vehicle is oriented correctly in the Unreal Engine.
In the `Armature` section uncheck `Add Leaf Bones` and uncheck `Bake Animation`.
@ -118,7 +118,7 @@ In the `Armature` section uncheck `Add Leaf Bones` and uncheck `Bake Animation`.
## Importing into unreal engine
Launch the Unreal Editor with the `make launch` command from the CARLA root directory (the one where you have built CARLA from source). Open a content browser, set up an appropriate directory and right click and select `Import to ....`. Choose the FBX file that you previously exported from Blender (or another 3D modelling application). Import with default settings.
Launch the Unreal Editor with the `make launch` command from the CARLA root directory (the one where you have built CARLA from source). Open a content browser, set up an appropriate directory and right click and select `Import to ....`. Choose the FBX file that you previously exported from Blender (or another 3D modelling application). Import with default settings.
### Setting the physics asset
@ -130,7 +130,7 @@ First, select the main body, in the `Details` menu on the right, change the `Lin
![physics_details](img/tuto_content_authoring_vehicles/physics_details.png)
Now select all the wheels (in the `Skeleton Tree` section on the left).
Now select all the wheels (in the `Skeleton Tree` section on the left).
![regenerate_wheels](img/tuto_content_authoring_vehicles/wheels_asset.png)
@ -170,7 +170,7 @@ Select the `Vehicles` node and expand the `Vehicles` item in the `Default value`
![vehicle_factory](img/tuto_content_authoring_vehicles/vehicle_factory_page.png)
Press the plus icon to add your new vehicle. Scroll down to the last entry and expand it, it should be empty. Name the make and model of your vehicle and under the class section find your blueprint class that you created in the previous section. Leave the number of wheels as 4 and put the generation as 2. Compile and save. Do a global save for safety and you are now..ready to run your vehicle in a simulation.
Press the plus icon to add your new vehicle. Scroll down to the last entry and expand it, it should be empty. Name the make and model of your vehicle and under the class section find your blueprint class that you created in the previous section. Leave the number of wheels as 4 and put the generation as 2. Compile and save. Do a global save for safety and you are now..ready to run your vehicle in a simulation.
Press play in the unreal toolbar to run the simulation. Once it is running, open a terminal and run the `manual_control.py` script with the filter option to specify your new vehicle model:
@ -185,13 +185,13 @@ As it is, the vehicle currently has no textures or colors applied. The next step
Once you have your vehicle imported as a basic asset with the mesh and blueprints laid out, you now want to add materials to your vehicle to facilitate photorealistic rendering in the Unreal Engine, for maximum fidelity in your machine learning training data.
The Unreal Editor boasts a comprehensive materials workflow that facilitates the creation of highly realistic materials. This does, however, add a significant degree of complexity to the process. For this reason, CARLA is provided with a large library of material prototypes for you to use without having to start from scratch.
The Unreal Editor boasts a comprehensive materials workflow that facilitates the creation of highly realistic materials. This does, however, add a significant degree of complexity to the process. For this reason, CARLA is provided with a large library of material prototypes for you to use without having to start from scratch.
### Applying a material to your vehicle
CARLA provides a prototype material for replicating the glossy finish of vehicles that can mimic numerous different types of vehicle paint jobs and features. Open Unreal editor and in the content browser, locate the material in `Content > Carla > Static > GenericMaterials > 00_MastersOpt`. The basic material is called `M_CarPaint_Master`. Right click on this material and choose `Create Material Instance` from the context material. Name it and move it into the folder where your new vehicle content is stored.
In the Unreal Editor, move the spectator to a point near the floor and drag the skeletal mesh of the vehicle from the content browser into the scene, the body of your vehicle will now appear there.
In the Unreal Editor, move the spectator to a point near the floor and drag the skeletal mesh of the vehicle from the content browser into the scene, the body of your vehicle will now appear there.
![add_model](img/tuto_content_authoring_vehicles/add_model.gif)
@ -207,7 +207,7 @@ The color settings govern the overall color of the car. The base color is simply
![change_base_color](img/tuto_content_authoring_vehicles/change_base_color.gif)
#### __Clear coat__
#### __Clear coat__
The clear coat settings govern the appearance of the finish and how it reacts to light. The roughness uses a texture to apply imperfections to the vehicle surface, scattering light more with higher values to create a matte look. Subtle adjustments and low values are recommended for a realistic look. Generally, car paint jobs are smooth and reflective, however, this effect might be used more generously to model specialist matte finishes of custom paint jobs.
@ -215,7 +215,7 @@ The clear coat settings govern the appearance of the finish and how it reacts to
An important parameter to govern the "shininess" or "glossiness" of your car is the `Clear Coat Intensity`. High values close to 1 will make the coat shiny and glossy.
#### __Orange peel__
#### __Orange peel__
Finishes on real cars (particularly on mass produced cars for the general market) tend to have imperfections that appear as slight ripples in the paint. The orange peel effect mimics this and makes cars look more realistic.
@ -223,13 +223,13 @@ Finishes on real cars (particularly on mass produced cars for the general market
#### __Flakes__
Some cars have paint jobs that include flakes of other material, such as metals or ceramics, to give the car a `metallic` or `pearlescant` appearance, adding extra glints and reflections that react in an attractive way to light. The flakes parameters allows CARLA to mimic this. To mimic metallic finishes, it would be
Some cars have paint jobs that include flakes of other material, such as metals or ceramics, to give the car a `metallic` or `pearlescant` appearance, adding extra glints and reflections that react in an attractive way to light. The flakes parameters allows CARLA to mimic this. To mimic metallic finishes, it would be
![flakes](img/tuto_content_authoring_vehicles/flakes.gif)
#### __Dust__
Cars often accumulate grease and dust on the body that adds additional texture to the paint, affecting the way it reflects the light. The dust parameters allow you to add patches of disruption to the coat to mimic foreign materials sticking to the paint.
Cars often accumulate grease and dust on the body that adds additional texture to the paint, affecting the way it reflects the light. The dust parameters allow you to add patches of disruption to the coat to mimic foreign materials sticking to the paint.
![dust](img/tuto_content_authoring_vehicles/change_dust.gif)
@ -245,15 +245,15 @@ Here we see the glass parts attached to the main bodywork (not the doors or othe
![main_glass](img/tuto_content_authoring_vehicles/glass.png)
If we separate the constituent mesh parts, we can see that the glass profile is separated into 4 different layers.
If we separate the constituent mesh parts, we can see that the glass profile is separated into 4 different layers.
![main_glass_expanded](img/tuto_content_authoring_vehicles/glass_expanded.png)
The 4 layers are separated into 2 groups, the exterior layers, with normals facing out of the vehicle and the interior layers, with mesh normals facing into the vehicle interior. The following diagram demonstrates
The 4 layers are separated into 2 groups, the exterior layers, with normals facing out of the vehicle and the interior layers, with mesh normals facing into the vehicle interior. The following diagram demonstrates
![glass_layers](img/tuto_content_authoring_vehicles/glass_layers.png)
Once you have created your mesh layers, import them in the content browser into the Unreal Editor in the folder where you have stored your vehicle.
Once you have created your mesh layers, import them in the content browser into the Unreal Editor in the folder where you have stored your vehicle.
Shift select the 4 glass layers and drag them into the map so you can see them.
@ -288,7 +288,7 @@ For the wheels of CARLA vehicles, we need to set up a blueprint class for each w
### Wheel blueprint
Inside the folder where you have your new vehicle, right click and choose to create a new blueprint class. Search for
Inside the folder where you have your new vehicle, right click and choose to create a new blueprint class. Search for
![wheel_blueprint](img/tuto_content_authoring_vehicles/wheel_blueprint.png)
@ -298,12 +298,12 @@ Double click on the blueprint to adjust it:
### Collision mesh
Firstly, the default cylinder used for the collision mesh has a high polygon count, so we should replace this with a low polygon version. In the content browser locate the `CollisionWheel` mesh inside `Content > Carla > Blueprints > Vehicles`. Drag it onto the
Firstly, the default cylinder used for the collision mesh has a high polygon count, so we should replace this with a low polygon version. In the content browser locate the `CollisionWheel` mesh inside `Content > Carla > Blueprints > Vehicles`. Drag it onto the
`Collision Mesh` slot in the details panel of the blueprint. This will improve performance without any noticeable deficit to physics simulation.
### Tire configuration
Next, we set the tire configuration. Inside `Content > Carla > Blueprints > Vehicles` locate the `CommonTireConfig` configuration and drag it onto the `Tire Config` section of the blueprint. If you double click on the Tire Config in the blueprint, you can adjust the Friction Scale, you can modify the behavior of the vehicle's road handling. By default it is set at 3.5, a value suitable for most vehicle use cases. However, if you wish to model for example a racing vehicle with slick tires, this would be the appropriate parameter to adjust.
Next, we set the tire configuration. Inside `Content > Carla > Blueprints > Vehicles` locate the `CommonTireConfig` configuration and drag it onto the `Tire Config` section of the blueprint. If you double click on the Tire Config in the blueprint, you can adjust the Friction Scale, you can modify the behavior of the vehicle's road handling. By default it is set at 3.5, a value suitable for most vehicle use cases. However, if you wish to model for example a racing vehicle with slick tires, this would be the appropriate parameter to adjust.
### Wheel dimensions
@ -316,24 +316,24 @@ Now plug these numbers into the `Wheel` section of the blueprint.Take care to re
![bp_wheel_dimensions](img/tuto_content_authoring_vehicles/bp_wheel_dimensions.png)
`Affected by handbrake` should be checked for both rear wheels.
`Affected by handbrake` should be checked for both rear wheels.
`Steer angle` should be set to the maximum intended steer angle for both front wheels and set to zero for both rear wheels.
### __Suspension characteristics__
The default values here provide a reasonable starting point. View [__this guide__](tuto_D_customize_vehicle_suspension.md) to set suspension characteristics appropriate to your vehicle type.
The default values here provide a reasonable starting point. View [__this guide__](tuto_D_customize_vehicle_suspension.md) to set suspension characteristics appropriate to your vehicle type.
## Lights
The last element to complete a realistic vehicle for CARLA is the lights, headlights, brake lights, blinkers etc. In your 3D modelling application, you should model some shapes that resemble the lights of the vehicle you are replicating. This would be flat discs or flat cuboid structures for most headlights. Some vehicles may also have strips of LEDs.
The last element to complete a realistic vehicle for CARLA is the lights, headlights, brake lights, blinkers etc. In your 3D modelling application, you should model some shapes that resemble the lights of the vehicle you are replicating. This would be flat discs or flat cuboid structures for most headlights. Some vehicles may also have strips of LEDs.
![lights_blender](img/tuto_content_authoring_vehicles/lights_blender.png)
### UV map
The different types of lights (headlights, blinkers, brake lights, etc.) are distinguished using a texture. You need to create a UV map in your 3D modelling application and position the lights to match up with the relevant region of the texture.
The different types of lights (headlights, blinkers, brake lights, etc.) are distinguished using a texture. You need to create a UV map in your 3D modelling application and position the lights to match up with the relevant region of the texture.
![lights_uv](img/tuto_content_authoring_vehicles/lights_uv_map.png)

View File

@ -1,45 +1,45 @@
# Tutorials
Here you will find the multitude of tutorials available to help you understand how to use CARLA's many features.
Here you will find the multitude of tutorials available to help you understand how to use CARLA's many features.
## General
### CARLA features
[__Retrieve simulation data__](tuto_G_retrieve_data.md) — A step by step guide to properly gather data using the recorder.
[__Traffic manager__](tuto_G_traffic_manager.md) — How to use traffic manager to guide traffic around your town.
[__Texture streaming__](tuto_G_texture_streaming.md) — Modify textures of map objects in real time to add variation.
[__Instance segmentation camera__](tuto_G_instance_segmentation_sensor.md) — Use an instance segmentation camera to distinguish objects of the same class.
[__Bounding boxes__](tuto_G_bounding_boxes.md) — Project bounding boxes from CARLA objects into the camera.
[__Pedestrian bones__](tuto_G_pedestrian_bones.md) — Project pedestrian skeleton into camera plane.
[__Control walker skeletons__](tuto_G_control_walker_skeletons.md) — Animate walkers using skeletons.
* [__Retrieve simulation data__](tuto_G_retrieve_data.md) — A step by step guide to properly gather data using the recorder.
* [__Traffic manager__](tuto_G_traffic_manager.md) — How to use traffic manager to guide traffic around your town.
* [__Texture streaming__](tuto_G_texture_streaming.md) — Modify textures of map objects in real time to add variation.
* [__Instance segmentation camera__](tuto_G_instance_segmentation_sensor.md) — Use an instance segmentation camera to distinguish objects of the same class.
* [__Bounding boxes__](tuto_G_bounding_boxes.md) — Project bounding boxes from CARLA objects into the camera.
* [__Pedestrian bones__](tuto_G_pedestrian_bones.md) — Project pedestrian skeleton into camera plane.
* [__Control walker skeletons__](tuto_G_control_walker_skeletons.md) — Animate walkers using skeletons.
### Building and integration
[__Build Unreal Engine and CARLA in Docker__](build_docker_unreal.md) — Build Unreal Engine and CARLA in Docker.
[__CarSim Integration__](tuto_G_carsim_integration.md) — Tutorial on how to run a simulation using the CarSim vehicle dynamics engine.
[__RLlib Integration__](tuto_G_rllib_integration.md) — Find out how to run your own experiment using the RLlib library.
[__Chrono Integration__](tuto_G_chrono.md) — Use the Chrono integration to simulation physics.
[__PyGame control__](tuto_G_pygame.md) — Use PyGame to display the output of camera sensors.
* [__Build Unreal Engine and CARLA in Docker__](build_docker_unreal.md) — Build Unreal Engine and CARLA in Docker.
* [__CarSim Integration__](tuto_G_carsim_integration.md) — Tutorial on how to run a simulation using the CarSim vehicle dynamics engine.
* [__RLlib Integration__](tuto_G_rllib_integration.md) — Find out how to run your own experiment using the RLlib library.
* [__Chrono Integration__](tuto_G_chrono.md) — Use the Chrono integration to simulation physics.
* [__PyGame control__](tuto_G_pygame.md) — Use PyGame to display the output of camera sensors.
## Assets and maps
[__Generate maps with OpenStreetMap__](tuto_G_openstreetmap.md) — Use OpenStreetMap to generate maps for use in simulations.
[__Add a new vehicle__](tuto_A_add_vehicle.md) — Prepare a vehicle to be used in CARLA.
[__Add new props__](tuto_A_add_props.md) — Import additional props into CARLA.
[__Create standalone packages__](tuto_A_create_standalone.md) — Generate and handle standalone packages for assets.
[__Material customization__](tuto_A_material_customization.md) — Edit vehicle and building materials.
* [__Generate maps with OpenStreetMap__](tuto_G_openstreetmap.md) — Use OpenStreetMap to generate maps for use in simulations.
* [__Add a new vehicle__](tuto_A_add_vehicle.md) — Prepare a vehicle to be used in CARLA.
* [__Add new props__](tuto_A_add_props.md) — Import additional props into CARLA.
* [__Create standalone packages__](tuto_A_create_standalone.md) — Generate and handle standalone packages for assets.
* [__Material customization__](tuto_A_material_customization.md) — Edit vehicle and building materials.
## Developers
[__How to upgrade content__](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) — Define customized tags for semantic segmentation.
[__Customize vehicle suspension__](tuto_D_customize_vehicle_suspension.md) — Modify the suspension system of a vehicle.
[__Generate detailed colliders__](tuto_D_generate_colliders.md) — Create detailed colliders for vehicles.
[__Make a release__](tuto_D_make_release.md) — How to make a release of CARLA
* [__How to upgrade content__](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) — Define customized tags for semantic segmentation.
* [__Customize vehicle suspension__](tuto_D_customize_vehicle_suspension.md) — Modify the suspension system of a vehicle.
* [__Generate detailed colliders__](tuto_D_generate_colliders.md) — Create detailed colliders for vehicles.
* [__Make a release__](tuto_D_make_release.md) — How to make a release of CARLA
## Video tutorials
[__Fundamentals__](https://www.youtube.com/watch?v=pONr1R1dy88) — Learn the fundamental concepts of CARLA and start your first script. [__CODE__](https://carla-releases.s3.eu-west-3.amazonaws.com/Docs/Fundamentals.ipynb)
[__An in depth look at CARLA's sensors__](https://www.youtube.com/watch?v=om8klsBj4rc) — An in depth look at CARLA's sensors and how to use them. [__CODE__](https://carla-releases.s3.eu-west-3.amazonaws.com/Docs/Sensors_code.zip)
* [__Fundamentals__](https://www.youtube.com/watch?v=pONr1R1dy88) — Learn the fundamental concepts of CARLA and start your first script. [__CODE__](https://carla-releases.s3.us-east-005.backblazeb2.com/Docs/Fundamentals.ipynb)
* [__An in depth look at CARLA's sensors__](https://www.youtube.com/watch?v=om8klsBj4rc) — An in depth look at CARLA's sensors and how to use them. [__CODE__](https://carla-releases.s3.us-east-005.backblazeb2.com/Docs/Sensors_code.zip)

489
Jenkinsfile vendored
View File

@ -11,91 +11,177 @@ pipeline
stages
{
stage('Creating nodes')
{
agent { label "master" }
steps
{
script
{
JOB_ID = "${env.BUILD_TAG}"
jenkinsLib = load("/home/jenkins/jenkins_426.groovy")
jenkinsLib.CreateUbuntuBuildNode(JOB_ID)
jenkinsLib.CreateWindowsBuildNode(JOB_ID)
}
}
}
stage('Building CARLA')
{
parallel
{
//stage('Building CARLA')
//{
//parallel
//{
stage('ubuntu')
{
agent { label "ubuntu && build && ${JOB_ID}" }
agent { label "gpu" }
environment
{
UE4_ROOT = '/home/jenkins/UnrealEngine_4.26'
}
stages
{
stage('ubuntu setup')
stage('stash dependencies')
{
agent{ label 'cache' }
options{skipDefaultCheckout()}
steps
{
sh 'git update-index --skip-worktree Unreal/CarlaUE4/CarlaUE4.uproject'
sh 'make setup ARGS="--python-version=3.7,2 --target-wheel-platform=manylinux_2_27_x86_64 --chrono"'
sh "echo ${BRANCH_NAME}"
sh "set"
sh "cp ../../Build_Linux.tar.gz ."
stash includes: 'Build_Linux.tar.gz', name: 'build_cache'
}
}
stage('ubuntu build')
stage('prepare environment')
{
steps
parallel
{
sh 'make LibCarla'
sh 'make PythonAPI ARGS="--python-version=3.7,2 --target-wheel-platform=manylinux_2_27_x86_64"'
sh 'make CarlaUE4Editor ARGS="--chrono"'
sh 'make plugins'
sh 'make examples'
}
post
{
always
stage('generate libs')
{
archiveArtifacts 'PythonAPI/carla/dist/*.egg'
archiveArtifacts 'PythonAPI/carla/dist/*.whl'
stash includes: 'PythonAPI/carla/dist/*.egg', name: 'ubuntu_eggs'
stash includes: 'PythonAPI/carla/dist/*.whl', name: 'ubuntu_wheels'
stages
{
stage('ubuntu setup')
{
steps
{
unstash name: 'build_cache'
sh 'tar -xvzf Build_Linux.tar.gz'
sh 'git update-index --skip-worktree Unreal/CarlaUE4/CarlaUE4.uproject'
sh 'make setup ARGS="--python-version=3.8,2 --target-wheel-platform=manylinux_2_27_x86_64 --chrono"'
}
}
stage('ubuntu build')
{
steps
{
sh 'make LibCarla'
sh 'make PythonAPI ARGS="--python-version=3.8,2 --target-wheel-platform=manylinux_2_27_x86_64"'
sh 'make CarlaUE4Editor ARGS="--chrono"'
sh 'make plugins'
sh 'make examples'
}
post
{
always
{
archiveArtifacts 'PythonAPI/carla/dist/*.egg'
archiveArtifacts 'PythonAPI/carla/dist/*.whl'
stash includes: 'PythonAPI/carla/dist/*.egg', name: 'ubuntu_eggs'
stash includes: 'PythonAPI/carla/dist/*.whl', name: 'ubuntu_wheels'
}
}
}
stage('ubuntu unit tests')
{
steps
{
sh 'make check ARGS="--all --xml --python-version=3.8,2 --target-wheel-platform=manylinux_2_27_x86_64"'
}
post
{
always
{
junit 'Build/test-results/*.xml'
archiveArtifacts 'profiler.csv'
}
}
}
}
}
}
}
stage('ubuntu unit tests')
{
steps
{
sh 'make check ARGS="--all --xml --python-version=3.7,2 --target-wheel-platform=manylinux_2_27_x86_64"'
}
post
{
always
stage('Download additional resources')
{
junit 'Build/test-results/*.xml'
archiveArtifacts 'profiler.csv'
stages
{
stage('TEST: Checkout Doxygen repo')
{
when { branch "ruben/jenkins_migration"; }
steps
{
dir('doc_repo')
{
checkout scmGit(
branches: [[name: '*/ruben/jenkins_migration']],
extensions: [
cleanBeforeCheckout(),
checkoutOption(120),
localBranch("**"),
cloneOption(noTags:false, reference:'', shallow: false, timeout:120)
],
userRemoteConfigs: [
[
credentialsId: 'github_token_as_pwd_2',
url: 'https://github.com/carla-simulator/carla-simulator.github.io.git'
]
]
)
}
}
}
stage('Checkout Doxygen repo')
{
when { anyOf { branch "master"; branch "dev"; buildingTag() } }
steps
{
dir('doc_repo')
{
checkout scmGit(
branches: [[name: '*/master']],
extensions: [
cleanBeforeCheckout(),
checkoutOption(120),
localBranch("**"),
cloneOption(noTags:false, reference:'', shallow: false, timeout:120)
],
userRemoteConfigs: [
[
credentialsId: 'github_token_as_pwd_2',
url: 'https://github.com/carla-simulator/carla-simulator.github.io.git'
]
]
)
}
}
}
stage('ubuntu retrieve content')
{
steps
{
sh './Update.sh'
}
}
}
}
}
}
stage('ubuntu retrieve content')
{
steps
{
sh './Update.sh'
}
}
stage('ubuntu package')
{
steps
{
sh 'make package ARGS="--python-version=3.7,2 --target-wheel-platform=manylinux_2_27_x86_64 --chrono"'
sh 'make package ARGS="--packages=AdditionalMaps,Town06_Opt,Town07_Opt,Town11,Town12,Town13,Town15 --target-archive=AdditionalMaps --clean-intermediate --python-version=3.7,2 --target-wheel-platform=manylinux_2_27_x86_64"'
sh 'make package ARGS="--python-version=3.8,2 --target-wheel-platform=manylinux_2_27_x86_64 --chrono"'
sh '''
prefix="PR-"
case "$BRANCH_NAME" in
("$prefix"*)
echo "This is a pull request, skipping complete package"
;;
(*)
echo "Generating complete package"
make package ARGS="--packages=AdditionalMaps,Town06_Opt,Town07_Opt,Town11,Town12,Town13,Town15 --target-archive=AdditionalMaps --clean-intermediate --python-version=3.8,2 --target-wheel-platform=manylinux_2_27_x86_64"
tar -czf CarlaUE4_logs.tar.gz Unreal/CarlaUE4/Saved/Logs/
;;
esac
'''
sh 'make examples ARGS="localhost 3654"'
}
post
@ -103,105 +189,161 @@ pipeline
always
{
archiveArtifacts 'Dist/*.tar.gz'
archiveArtifacts artifacts:'CarlaUE4_logs.tar.gz',
allowEmptyArchive: true
stash includes: 'Dist/CARLA*.tar.gz', name: 'ubuntu_package'
// stash includes: 'Dist/AdditionalMaps*.tar.gz', name: 'ubuntu_package2'
stash includes: 'Examples/', name: 'ubuntu_examples'
}
success
{
node('master')
{
script
{
JOB_ID = "${env.BUILD_TAG}"
jenkinsLib = load("/home/jenkins/jenkins_426.groovy")
}
}
jenkinsLib.CreateUbuntuTestNode(JOB_ID)
stage('Testing and documentation')
{
parallel
{
stage('Testing')
{
stages
{
stage('ubuntu smoke tests')
{
steps
{
unstash name: 'ubuntu_eggs'
unstash name: 'ubuntu_wheels'
unstash name: 'ubuntu_package'
unstash name: 'ubuntu_examples'
sh 'tar -xvzf Dist/CARLA*.tar.gz -C Dist/'
sh 'DISPLAY= ./Dist/CarlaUE4.sh -nullrhi -RenderOffScreen --carla-rpc-port=3654 --carla-streaming-port=0 -nosound > CarlaUE4.log &'
sh 'make smoke_tests ARGS="--xml --python-version=3.8 --target-wheel-platform=manylinux_2_27_x86_64"'
sh 'make run-examples ARGS="localhost 3654"'
}
post
{
always
{
archiveArtifacts 'CarlaUE4.log'
junit 'Build/test-results/smoke-tests-*.xml'
}
}
}
}
}
stage('Generate documentation')
{
stages
{
stage('ubuntu Doxygen generation')
{
when { anyOf { branch "master"; branch "dev"; buildingTag() } }
steps
{
sh 'make docs'
sh 'tar -czf carla_doc.tar.gz ./Doxygen'
stash includes: 'carla_doc.tar.gz', name: 'carla_docs'
}
}
stage('TEST: ubuntu Doxygen generation')
{
when { branch "ruben/jenkins_migration"; }
steps
{
sh 'make docs'
sh 'tar -czf carla_doc.tar.gz ./Doxygen'
stash includes: 'carla_doc.tar.gz', name: 'carla_docs'
}
}
}
}
}
}
stage('ubuntu smoke tests')
{
agent { label "ubuntu && gpu && ${JOB_ID}" }
steps
{
unstash name: 'ubuntu_eggs'
unstash name: 'ubuntu_wheels'
unstash name: 'ubuntu_package'
// unstash name: 'ubuntu_package2'
unstash name: 'ubuntu_examples'
sh 'tar -xvzf Dist/CARLA*.tar.gz -C Dist/'
// sh 'tar -xvzf Dist/AdditionalMaps*.tar.gz -C Dist/'
sh 'DISPLAY= ./Dist/CarlaUE4.sh -nullrhi -RenderOffScreen --carla-rpc-port=3654 --carla-streaming-port=0 -nosound > CarlaUE4.log &'
sh 'make smoke_tests ARGS="--xml --python-version=3.7 --target-wheel-platform=manylinux_2_27_x86_64"'
sh 'make run-examples ARGS="localhost 3654"'
}
post
{
always
{
archiveArtifacts 'CarlaUE4.log'
junit 'Build/test-results/smoke-tests-*.xml'
deleteDir()
node('master')
{
script
{
JOB_ID = "${env.BUILD_TAG}"
jenkinsLib = load("/home/jenkins/jenkins_426.groovy")
jenkinsLib.DeleteUbuntuTestNode(JOB_ID)
stage('Deployment and documentation publishing')
{
parallel
{
stage('Release Deployment')
{
stages
{
stage('TEST: ubuntu deploy sim')
{
when { branch "ruben/jenkins_migration"; }
steps
{
sh 'git checkout .'
sh 'make deploy ARGS="--test"'
}
}
stage('ubuntu deploy dev')
{
when { branch "dev"; }
steps
{
sh 'git checkout .'
sh 'make deploy ARGS="--replace-latest"'
}
}
stage('ubuntu deploy master')
{
when { anyOf { branch "master"; buildingTag() } }
steps
{
sh 'git checkout .'
sh 'make deploy ARGS="--replace-latest --docker-push"'
}
}
}
}
}
}
stage('ubuntu deploy dev')
{
when { branch "dev"; }
steps
{
sh 'git checkout .'
sh 'make deploy ARGS="--replace-latest"'
}
}
stage('ubuntu deploy master')
{
when { anyOf { branch "master"; buildingTag() } }
steps
{
sh 'git checkout .'
sh 'make deploy ARGS="--replace-latest --docker-push"'
}
}
stage('ubuntu Doxygen')
{
when { anyOf { branch "master"; branch "dev"; buildingTag() } }
steps
{
sh 'rm -rf ~/carla-simulator.github.io/Doxygen'
sh '''
cd ~/carla-simulator.github.io
git remote set-url origin git@docs:carla-simulator/carla-simulator.github.io.git
git fetch
git checkout -B master origin/master
'''
sh 'make docs'
sh 'cp -rf ./Doxygen ~/carla-simulator.github.io/'
sh '''
cd ~/carla-simulator.github.io
git add Doxygen
git commit -m "Updated c++ docs" || true
git push
'''
}
post
{
always
stage('Publish documentation')
{
deleteDir()
stages
{
stage('ubuntu Doxygen upload')
{
when { anyOf { branch "master"; branch "dev"; buildingTag() } }
steps
{
dir('doc_repo')
{
unstash name: 'carla_docs'
withCredentials([gitUsernamePassword(credentialsId: 'github_token_as_pwd_2', gitToolName: 'git-tool')]) {
sh '''
tar -xvzf carla_doc.tar.gz
git add Doxygen
git commit -m "Updated c++ docs" || true
git push --set-upstream origin ruben/jenkins_migration
'''
}
}
}
}
stage('TEST: ubuntu Doxygen upload')
{
when { branch "ruben/jenkins_migration"; }
steps
{
dir('doc_repo')
{
unstash name: 'carla_docs'
withCredentials([gitUsernamePassword(credentialsId: 'github_token_as_pwd_2', gitToolName: 'git-tool')]) {
sh '''
tar -xvzf carla_doc.tar.gz
git add Doxygen
git commit -m "Updated c++ docs" || true
git push --set-upstream origin ruben/jenkins_migration
'''
}
}
}
}
}
}
}
}
@ -211,23 +353,14 @@ pipeline
always
{
deleteDir()
node('master')
{
script
{
JOB_ID = "${env.BUILD_TAG}"
jenkinsLib = load("/home/jenkins/jenkins_426.groovy")
jenkinsLib.DeleteUbuntuBuildNode(JOB_ID)
}
}
}
}
}
/*
stage('windows')
{
agent { label "windows && build && ${JOB_ID}" }
agent { label "windows" }
environment
{
UE4_ROOT = 'C:\\UE_4.26'
@ -239,11 +372,11 @@ pipeline
steps
{
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
git update-index --skip-worktree Unreal/CarlaUE4/CarlaUE4.uproject
"""
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make setup ARGS="--chrono"
"""
}
@ -253,19 +386,19 @@ pipeline
steps
{
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make LibCarla
"""
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make PythonAPI
"""
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make CarlaUE4Editor ARGS="--chrono"
"""
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make plugins
"""
}
@ -283,7 +416,7 @@ pipeline
steps
{
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
call Update.bat
"""
}
@ -293,11 +426,11 @@ pipeline
steps
{
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make package ARGS="--chrono"
"""
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
make package ARGS="--packages=AdditionalMaps,Town06_Opt,Town07_Opt,Town11,Town12,Town13,Town15 --target-archive=AdditionalMaps --clean-intermediate"
"""
}
@ -307,38 +440,30 @@ pipeline
}
}
}
stage('windows deploy')
{
when { anyOf { branch "master"; branch "dev"; buildingTag() } }
steps {
bat """
call ../setEnv64.bat
call C:\\Users\\jenkins\\setEnv64.bat
git checkout .
make deploy ARGS="--replace-latest"
REM make deploy ARGS="--replace-latest"
"""
}
}
}
post
{
always
{
deleteDir()
node('master')
{
script
{
JOB_ID = "${env.BUILD_TAG}"
jenkinsLib = load("/home/jenkins/jenkins_426.groovy")
jenkinsLib.DeleteWindowsBuildNode(JOB_ID)
}
}
}
}
}
}
}
}*/
//}
//}
}
}

View File

@ -21,6 +21,18 @@ if (BUILD_RSS_VARIANT)
install(FILES ${spdlog_file} DESTINATION lib)
list(APPEND ADRSS_LIBS ${spdlog_file})
set(proj_include_dir ${ADRSS_INSTALL_DIR}/../../proj-install/include)
set(proj_lib ${ADRSS_INSTALL_DIR}/../../proj-install/lib/libproj.a)
install(DIRECTORY ${proj_include_dir} DESTINATION include/system)
list(APPEND ADRSS_INCLUDE_DIRS ${proj_include_dir})
install(FILES ${proj_lib} DESTINATION lib)
list(APPEND ADRSS_LIBS ${proj_lib})
# as long as the libosm2odr uses the same odrSprial interface it is enough to copy the built static library
set(odr_lib ${ADRSS_INSTALL_DIR}/../src/ad-rss-lib/dependencies/map/dependencies/odrSpiral/lib/libodrSpiral.a)
install(FILES ${odr_lib} DESTINATION lib)
list(APPEND ADRSS_LIBS ${odr_lib})
foreach(ad_lib ad_physics ad_rss ad_map_access ad_map_opendrive_reader ad_rss_map_integration)
set(${ad_lib}_file ${ADRSS_INSTALL_DIR}/${ad_lib}/lib/lib${ad_lib}.a)
install(FILES ${${ad_lib}_file} DESTINATION lib)

View File

@ -32,6 +32,42 @@ namespace client {
return GetEpisode().Lock()->GetActorAcceleration(*this);
}
geom::Transform Actor::GetComponentWorldTransform(const std::string componentName) const {
return GetEpisode().Lock()->GetActorComponentWorldTransform(*this, componentName);
}
geom::Transform Actor::GetComponentRelativeTransform(const std::string componentName) const {
return GetEpisode().Lock()->GetActorComponentRelativeTransform(*this, componentName);
}
std::vector<geom::Transform> Actor::GetBoneWorldTransforms() const {
return GetEpisode().Lock()->GetActorBoneWorldTransforms(*this);
}
std::vector<geom::Transform> Actor::GetBoneRelativeTransforms() const {
return GetEpisode().Lock()->GetActorBoneRelativeTransforms(*this);
}
std::vector<std::string> Actor::GetComponentNames() const {
return GetEpisode().Lock()->GetActorComponentNames(*this);
}
std::vector<std::string> Actor::GetBoneNames() const {
return GetEpisode().Lock()->GetActorBoneNames(*this);
}
std::vector<geom::Transform> Actor::GetSocketWorldTransforms() const {
return GetEpisode().Lock()->GetActorSocketWorldTransforms(*this);
}
std::vector<geom::Transform> Actor::GetSocketRelativeTransforms() const {
return GetEpisode().Lock()->GetActorSocketRelativeTransforms(*this);
}
std::vector<std::string> Actor::GetSocketNames() const {
return GetEpisode().Lock()->GetActorSocketNames(*this);
}
void Actor::SetLocation(const geom::Location &location) {
GetEpisode().Lock()->SetActorLocation(*this, location);
}

View File

@ -60,6 +60,24 @@ namespace client {
/// acceleration calculated after the actor's velocity.
geom::Vector3D GetAcceleration() const;
geom::Transform GetComponentWorldTransform(const std::string componentName) const;
geom::Transform GetComponentRelativeTransform(const std::string componentName) const;
std::vector<geom::Transform> GetBoneWorldTransforms() const;
std::vector<geom::Transform> GetBoneRelativeTransforms() const;
std::vector<std::string> GetComponentNames() const;
std::vector<std::string> GetBoneNames() const;
std::vector<geom::Transform> GetSocketWorldTransforms() const;
std::vector<geom::Transform> GetSocketRelativeTransforms() const;
std::vector<std::string> GetSocketNames() const;
/// Teleport the actor to @a location.
void SetLocation(const geom::Location &location);

View File

@ -35,6 +35,16 @@ namespace client {
DrawShape(_episode, point, color, life_time, persistent_lines);
}
void DebugHelper::DrawHUDPoint(
const geom::Location &location,
float size,
sensor::data::Color color,
float life_time,
bool persistent_lines) {
Shape::HUDPoint point{location, size};
DrawShape(_episode, point, color, life_time, persistent_lines);
}
void DebugHelper::DrawLine(
const geom::Location &begin,
const geom::Location &end,
@ -46,6 +56,17 @@ namespace client {
DrawShape(_episode, line, color, life_time, persistent_lines);
}
void DebugHelper::DrawHUDLine(
const geom::Location &begin,
const geom::Location &end,
float thickness,
Color color,
float life_time,
bool persistent_lines) {
Shape::HUDLine line{begin, end, thickness};
DrawShape(_episode, line, color, life_time, persistent_lines);
}
void DebugHelper::DrawArrow(
const geom::Location &begin,
const geom::Location &end,
@ -59,6 +80,19 @@ namespace client {
DrawShape(_episode, arrow, color, life_time, persistent_lines);
}
void DebugHelper::DrawHUDArrow(
const geom::Location &begin,
const geom::Location &end,
float thickness,
float arrow_size,
sensor::data::Color color,
float life_time,
bool persistent_lines) {
Shape::HUDLine line{begin, end, thickness};
Shape::HUDArrow arrow{line, arrow_size};
DrawShape(_episode, arrow, color, life_time, persistent_lines);
}
void DebugHelper::DrawBox(
const geom::BoundingBox &box,
const geom::Rotation &rotation,
@ -70,6 +104,17 @@ namespace client {
DrawShape(_episode, the_box, color, life_time, persistent_lines);
}
void DebugHelper::DrawHUDBox(
const geom::BoundingBox &box,
const geom::Rotation &rotation,
float thickness,
sensor::data::Color color,
float life_time,
bool persistent_lines) {
Shape::HUDBox the_box{box, rotation, thickness};
DrawShape(_episode, the_box, color, life_time, persistent_lines);
}
void DebugHelper::DrawString(
const geom::Location &location,
const std::string &text,

View File

@ -30,6 +30,13 @@ namespace client {
float life_time = -1.0f,
bool persistent_lines = true);
void DrawHUDPoint(
const geom::Location &location,
float size = 0.1f,
Color color = Color{255u, 0u, 0u},
float life_time = -1.0f,
bool persistent_lines = true);
void DrawLine(
const geom::Location &begin,
const geom::Location &end,
@ -38,6 +45,14 @@ namespace client {
float life_time = -1.0f,
bool persistent_lines = true);
void DrawHUDLine(
const geom::Location &begin,
const geom::Location &end,
float thickness = 1.0f,
Color color = Color{225u, 0u, 0u},
float life_time = -1.0f,
bool presistent_lines = true);
void DrawArrow(
const geom::Location &begin,
const geom::Location &end,
@ -47,6 +62,15 @@ namespace client {
float life_time = -1.0f,
bool persistent_lines = true);
void DrawHUDArrow(
const geom::Location &begin,
const geom::Location &end,
float thickness = 0.1f,
float arrow_size = 0.1f,
Color color = Color{255u, 0u, 0u},
float life_time = -1.0f,
bool persistent_lines = true);
void DrawBox(
const geom::BoundingBox &box,
const geom::Rotation &rotation,
@ -55,6 +79,14 @@ namespace client {
float life_time = -1.0f,
bool persistent_lines = true);
void DrawHUDBox(
const geom::BoundingBox &box,
const geom::Rotation &rotation,
float thickness = 0.1f,
Color color = Color{255u, 0u, 0u},
float life_time = -1.0f,
bool persistent_lines = true);
void DrawString(
const geom::Location &location,
const std::string &text,

View File

@ -12,6 +12,7 @@
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <cstdint>
namespace carla {
namespace client {

View File

@ -144,6 +144,10 @@ namespace client {
BaseJSONPath);
}
void Vehicle::RestorePhysXPhysics() {
GetEpisode().Lock()->RestorePhysXPhysics(*this);
}
rpc::VehicleFailureState Vehicle::GetFailureState() const {
return GetEpisode().Lock()->GetActorSnapshot(*this).state.vehicle_data.failure_state;
}

View File

@ -137,6 +137,8 @@ namespace client {
std::string TireJSON = "",
std::string BaseJSONPath = "");
void RestorePhysXPhysics();
/// Returns the failure state of the vehicle
rpc::VehicleFailureState GetFailureState() const;

View File

@ -90,6 +90,15 @@ namespace client {
void World::SetWeather(const rpc::WeatherParameters &weather) {
_episode.Lock()->SetWeatherParameters(weather);
}
float World::GetIMUISensorGravity() const {
return _episode.Lock()->GetIMUISensorGravity();
}
void World::SetIMUISensorGravity(float NewIMUISensorGravity) {
_episode.Lock()->SetIMUISensorGravity(NewIMUISensorGravity);
}
WorldSnapshot World::GetSnapshot() const {
return _episode.Lock()->GetWorldSnapshot();
@ -119,17 +128,19 @@ namespace client {
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent_actor,
rpc::AttachmentType attachment_type) {
return _episode.Lock()->SpawnActor(blueprint, transform, parent_actor, attachment_type);
rpc::AttachmentType attachment_type,
const std::string& socket_name) {
return _episode.Lock()->SpawnActor(blueprint, transform, parent_actor, attachment_type, GarbageCollectionPolicy::Inherit, socket_name);
}
SharedPtr<Actor> World::TrySpawnActor(
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent_actor,
rpc::AttachmentType attachment_type) noexcept {
rpc::AttachmentType attachment_type,
const std::string& socket_name) noexcept {
try {
return SpawnActor(blueprint, transform, parent_actor, attachment_type);
return SpawnActor(blueprint, transform, parent_actor, attachment_type, socket_name);
} catch (const std::exception &) {
return nullptr;
}

View File

@ -29,6 +29,7 @@
#include "carla/rpc/Texture.h"
#include "carla/rpc/MaterialParameter.h"
#include <string>
#include <boost/optional.hpp>
namespace carla {
@ -93,6 +94,12 @@ namespace client {
/// Change the weather in the simulation.
void SetWeather(const rpc::WeatherParameters &weather);
/// Get Gravity value used for IMUI Sensor accelerometer calculation
float GetIMUISensorGravity() const;
/// Set Gravity value used for IMUI Sensor accelerometer calculation
void SetIMUISensorGravity(float NewIMUISensorGravity);
/// Return a snapshot of the world at this moment.
WorldSnapshot GetSnapshot() const;
@ -112,7 +119,8 @@ namespace client {
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent = nullptr,
rpc::AttachmentType attachment_type = rpc::AttachmentType::Rigid);
rpc::AttachmentType attachment_type = rpc::AttachmentType::Rigid,
const std::string& socket_name = "");
/// Same as SpawnActor but return nullptr on failure instead of throwing an
/// exception.
@ -120,7 +128,8 @@ namespace client {
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent = nullptr,
rpc::AttachmentType attachment_type = rpc::AttachmentType::Rigid) noexcept;
rpc::AttachmentType attachment_type = rpc::AttachmentType::Rigid,
const std::string& socket_name = "") noexcept;
/// Block calling thread until a world tick is received.
WorldSnapshot WaitForTick(time_duration timeout) const;

View File

@ -267,6 +267,14 @@ namespace detail {
_pimpl->AsyncCall("set_weather_parameters", weather);
}
float Client::GetIMUISensorGravity() const {
return _pimpl->CallAndWait<float>("get_imui_gravity");
}
void Client::SetIMUISensorGravity(float NewIMUISensorGravity) {
_pimpl->AsyncCall("set_imui_gravity", NewIMUISensorGravity);
}
std::vector<rpc::Actor> Client::GetActorsById(
const std::vector<ActorId> &ids) {
using return_t = std::vector<rpc::Actor>;
@ -326,11 +334,12 @@ namespace detail {
return _pimpl->CallAndWait<rpc::Actor>("spawn_actor", description, transform);
}
rpc::Actor Client::SpawnActorWithParent(
rpc::Actor Client::SpawnActorWithParent(
const rpc::ActorDescription &description,
const geom::Transform &transform,
rpc::ActorId parent,
rpc::AttachmentType attachment_type) {
rpc::AttachmentType attachment_type,
const std::string& socket_name) {
if (attachment_type == rpc::AttachmentType::SpringArm ||
attachment_type == rpc::AttachmentType::SpringArmGhost)
@ -348,7 +357,8 @@ namespace detail {
description,
transform,
parent,
attachment_type);
attachment_type,
socket_name);
}
bool Client::DestroyActor(rpc::ActorId actor) {
@ -408,6 +418,49 @@ namespace detail {
_pimpl->AsyncCall("add_actor_torque", actor, vector);
}
geom::Transform Client::GetActorComponentWorldTransform(rpc::ActorId actor, const std::string componentName) {
return _pimpl->CallAndWait<geom::Transform>("get_actor_component_world_transform", actor, componentName);
}
geom::Transform Client::GetActorComponentRelativeTransform(rpc::ActorId actor, const std::string componentName) {
return _pimpl->CallAndWait<geom::Transform>("get_actor_component_relative_transform", actor, componentName);
}
std::vector<geom::Transform> Client::GetActorBoneWorldTransforms(rpc::ActorId actor) {
using return_t = std::vector<geom::Transform>;
return _pimpl->CallAndWait<return_t>("get_actor_bone_world_transforms", actor);
}
std::vector<geom::Transform> Client::GetActorBoneRelativeTransforms(rpc::ActorId actor) {
using return_t = std::vector<geom::Transform>;
return _pimpl->CallAndWait<return_t>("get_actor_bone_relative_transforms", actor);
}
std::vector<std::string> Client::GetActorComponentNames(rpc::ActorId actor) {
using return_t = std::vector<std::string>;
return _pimpl->CallAndWait<return_t>("get_actor_component_names", actor);
}
std::vector<std::string> Client::GetActorBoneNames(rpc::ActorId actor) {
using return_t = std::vector<std::string>;
return _pimpl->CallAndWait<return_t>("get_actor_bone_names", actor);
}
std::vector<geom::Transform> Client::GetActorSocketWorldTransforms(rpc::ActorId actor) {
using return_t = std::vector<geom::Transform>;
return _pimpl->CallAndWait<return_t>("get_actor_socket_world_transforms", actor);
}
std::vector<geom::Transform> Client::GetActorSocketRelativeTransforms(rpc::ActorId actor) {
using return_t = std::vector<geom::Transform>;
return _pimpl->CallAndWait<return_t>("get_actor_socket_relative_transforms", actor);
}
std::vector<std::string> Client::GetActorSocketNames(rpc::ActorId actor) {
using return_t = std::vector<std::string>;
return _pimpl->CallAndWait<return_t>("get_actor_socket_names", actor);
}
void Client::SetActorSimulatePhysics(rpc::ActorId actor, const bool enabled) {
_pimpl->CallAndWait<void>("set_actor_simulate_physics", actor, enabled);
}
@ -475,6 +528,10 @@ namespace detail {
BaseJSONPath);
}
void Client::RestorePhysXPhysics(rpc::ActorId vehicle) {
_pimpl->AsyncCall("restore_physx_physics", vehicle);
}
void Client::ApplyControlToWalker(rpc::ActorId walker, const rpc::WalkerControl &control) {
_pimpl->AsyncCall("apply_control_to_walker", walker, control);
}

View File

@ -149,6 +149,10 @@ namespace detail {
void SetWeatherParameters(const rpc::WeatherParameters &weather);
float GetIMUISensorGravity() const;
void SetIMUISensorGravity( float NewIMUISensorGravity );
std::vector<rpc::Actor> GetActorsById(const std::vector<ActorId> &ids);
rpc::VehiclePhysicsControl GetVehiclePhysicsControl(rpc::ActorId vehicle) const;
@ -179,7 +183,8 @@ namespace detail {
const rpc::ActorDescription &description,
const geom::Transform &transform,
rpc::ActorId parent,
rpc::AttachmentType attachment_type);
rpc::AttachmentType attachment_type,
const std::string& socket_name = "");
bool DestroyActor(rpc::ActorId actor);
@ -232,6 +237,35 @@ namespace detail {
rpc::ActorId actor,
const geom::Vector3D &vector);
geom::Transform GetActorComponentWorldTransform(
rpc::ActorId actor,
const std::string componentName);
geom::Transform GetActorComponentRelativeTransform(
rpc::ActorId actor,
const std::string componentName);
std::vector<geom::Transform> GetActorBoneWorldTransforms(
rpc::ActorId actor);
std::vector<geom::Transform> GetActorBoneRelativeTransforms(
rpc::ActorId actor);
std::vector<std::string> GetActorComponentNames(
rpc::ActorId actor);
std::vector<std::string> GetActorBoneNames(
rpc::ActorId actor);
std::vector<geom::Transform> GetActorSocketWorldTransforms(
rpc::ActorId actor);
std::vector<geom::Transform> GetActorSocketRelativeTransforms(
rpc::ActorId actor);
std::vector<std::string> GetActorSocketNames(
rpc::ActorId actor);
void SetActorSimulatePhysics(
rpc::ActorId actor,
bool enabled);
@ -297,6 +331,8 @@ namespace detail {
std::string TireJSON,
std::string BaseJSONPath);
void RestorePhysXPhysics(rpc::ActorId vehicle);
void ApplyControlToWalker(
rpc::ActorId walker,
const rpc::WalkerControl &control);

View File

@ -342,19 +342,21 @@ EpisodeProxy Simulator::GetCurrentEpisode() {
// -- General operations with actors -----------------------------------------
// ===========================================================================
SharedPtr<Actor> Simulator::SpawnActor(
SharedPtr<Actor> Simulator::SpawnActor(
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent,
rpc::AttachmentType attachment_type,
GarbageCollectionPolicy gc) {
GarbageCollectionPolicy gc,
const std::string& socket_name) {
rpc::Actor actor;
if (parent != nullptr) {
actor = _client.SpawnActorWithParent(
blueprint.MakeActorDescription(),
transform,
parent->GetId(),
attachment_type);
attachment_type,
socket_name);
} else {
actor = _client.SpawnActor(
blueprint.MakeActorDescription(),

View File

@ -259,6 +259,14 @@ namespace detail {
_client.SetWeatherParameters(weather);
}
float GetIMUISensorGravity() const {
return _client.GetIMUISensorGravity();
}
void SetIMUISensorGravity(float NewIMUISensorGravity) {
_client.SetIMUISensorGravity(NewIMUISensorGravity);
}
rpc::VehiclePhysicsControl GetVehiclePhysicsControl(const Vehicle &vehicle) const {
return _client.GetVehiclePhysicsControl(vehicle.GetId());
}
@ -357,7 +365,8 @@ namespace detail {
const geom::Transform &transform,
Actor *parent = nullptr,
rpc::AttachmentType attachment_type = rpc::AttachmentType::Rigid,
GarbageCollectionPolicy gc = GarbageCollectionPolicy::Inherit);
GarbageCollectionPolicy gc = GarbageCollectionPolicy::Inherit,
const std::string& socket_name = "");
bool DestroyActor(Actor &actor);
@ -438,6 +447,42 @@ namespace detail {
return GetActorSnapshot(actor).acceleration;
}
geom::Transform GetActorComponentWorldTransform(const Actor &actor, const std::string componentName) {
return _client.GetActorComponentWorldTransform(actor.GetId(), componentName);
}
geom::Transform GetActorComponentRelativeTransform(const Actor &actor, std::string componentName) {
return _client.GetActorComponentRelativeTransform(actor.GetId(), componentName);
}
std::vector<geom::Transform> GetActorBoneWorldTransforms(const Actor &actor) {
return _client.GetActorBoneWorldTransforms(actor.GetId());
}
std::vector<geom::Transform> GetActorBoneRelativeTransforms(const Actor &actor) {
return _client.GetActorBoneRelativeTransforms(actor.GetId());
}
std::vector<std::string> GetActorComponentNames(const Actor &actor) {
return _client.GetActorComponentNames(actor.GetId());
}
std::vector<std::string> GetActorBoneNames(const Actor &actor) {
return _client.GetActorBoneNames(actor.GetId());
}
std::vector<geom::Transform> GetActorSocketWorldTransforms(const Actor &actor) {
return _client.GetActorSocketWorldTransforms(actor.GetId());
}
std::vector<geom::Transform> GetActorSocketRelativeTransforms(const Actor &actor) {
return _client.GetActorSocketRelativeTransforms(actor.GetId());
}
std::vector<std::string> GetActorSocketNames(const Actor &actor) {
return _client.GetActorSocketNames(actor.GetId());
}
void SetActorLocation(Actor &actor, const geom::Location &location) {
_client.SetActorLocation(actor.GetId(), location);
}
@ -572,6 +617,10 @@ namespace detail {
BaseJSONPath);
}
void RestorePhysXPhysics(Vehicle &vehicle) {
_client.RestorePhysXPhysics(vehicle.GetId());
}
/// @}
// =========================================================================
/// @name Operations with the recorder

View File

@ -1232,12 +1232,17 @@ namespace road {
while(s_current < s_end){
if(lane->GetWidth(s_current) != 0.0f){
const auto edges = lane->GetCornerPositions(s_current, 0);
if (edges.first == edges.second) continue;
geom::Vector3D director = edges.second - edges.first;
geom::Vector3D treeposition = edges.first - director.MakeUnitVector() * distancefromdrivinglineborder;
geom::Transform lanetransform = lane->ComputeTransform(s_current);
geom::Transform treeTransform(treeposition, lanetransform.rotation);
const carla::road::element::RoadInfoSpeed* roadinfo = lane->GetInfo<carla::road::element::RoadInfoSpeed>(s_current);
transforms.push_back(std::make_pair(treeTransform,roadinfo->GetType()));
if(roadinfo){
transforms.push_back(std::make_pair(treeTransform, roadinfo->GetType()));
}else{
transforms.push_back(std::make_pair(treeTransform, "urban"));
}
}
s_current += distancebetweentrees;
}

View File

@ -761,14 +761,11 @@ std::map<road::Lane::LaneType , std::vector<std::unique_ptr<Mesh>>> MeshFactory:
case carla::road::element::LaneMarking::Type::Solid: {
size_t currentIndex = out_mesh.GetVertices().size() + 1;
std::pair<geom::Vector3D, geom::Vector3D> edges = lane.GetCornerPositions(s_current, 0);
geom::Vector3D director = edges.second - edges.first;
director /= director.Length();
geom::Vector3D endmarking = edges.first + director * lane_mark_info.width;
std::pair<geom::Vector3D, geom::Vector3D> edges =
ComputeEdgesForLanemark(lane_section, lane, s_current, lane_mark_info.width);
out_mesh.AddVertex(edges.first);
out_mesh.AddVertex(endmarking);
out_mesh.AddVertex(edges.second);
out_mesh.AddIndex(currentIndex);
out_mesh.AddIndex(currentIndex + 1);
@ -784,30 +781,23 @@ std::map<road::Lane::LaneType , std::vector<std::unique_ptr<Mesh>>> MeshFactory:
case carla::road::element::LaneMarking::Type::Broken: {
size_t currentIndex = out_mesh.GetVertices().size() + 1;
std::pair<geom::Vector3D, geom::Vector3D> edges =
lane.GetCornerPositions(s_current, road_param.extra_lane_width);
geom::Vector3D director = edges.second - edges.first;
director /= director.Length();
geom::Vector3D endmarking = edges.first + director * lane_mark_info.width;
std::pair<geom::Vector3D, geom::Vector3D> edges =
ComputeEdgesForLanemark(lane_section, lane, s_current, lane_mark_info.width);
out_mesh.AddVertex(edges.first);
out_mesh.AddVertex(endmarking);
out_mesh.AddVertex(edges.second);
s_current += road_param.resolution * 3;
if (s_current > s_end)
{
s_current = s_end;
}
edges = lane.GetCornerPositions(s_current, road_param.extra_lane_width);
director = edges.second - edges.first;
director /= director.Length();
endmarking = edges.first + director * lane_mark_info.width;
edges = ComputeEdgesForLanemark(lane_section, lane, s_current, lane_mark_info.width);
out_mesh.AddVertex(edges.first);
out_mesh.AddVertex(endmarking);
out_mesh.AddVertex(edges.second);
out_mesh.AddIndex(currentIndex);
out_mesh.AddIndex(currentIndex + 1);
out_mesh.AddIndex(currentIndex + 2);
@ -864,13 +854,12 @@ std::map<road::Lane::LaneType , std::vector<std::unique_ptr<Mesh>>> MeshFactory:
const carla::road::element::RoadInfoMarkRecord* road_info_mark = lane.GetInfo<carla::road::element::RoadInfoMarkRecord>(s_current);
if (road_info_mark != nullptr) {
carla::road::element::LaneMarking lane_mark_info(*road_info_mark);
std::pair<geom::Vector3D, geom::Vector3D> edges = lane.GetCornerPositions(s_end, 0);
geom::Vector3D director = edges.second - edges.first;
director /= director.Length();
geom::Vector3D endmarking = edges.first + director * lane_mark_info.width;
std::pair<geom::Vector3D, geom::Vector3D> edges =
ComputeEdgesForLanemark(lane_section, lane, s_end, lane_mark_info.width);
out_mesh.AddVertex(edges.first);
out_mesh.AddVertex(endmarking);
out_mesh.AddVertex(edges.second);
}
inout.push_back(std::make_unique<Mesh>(out_mesh));
}
@ -927,29 +916,21 @@ std::map<road::Lane::LaneType , std::vector<std::unique_ptr<Mesh>>> MeshFactory:
case carla::road::element::LaneMarking::Type::Broken: {
size_t currentIndex = out_mesh.GetVertices().size() + 1;
std::pair<geom::Vector3D, geom::Vector3D> edges =
lane.GetCornerPositions(s_current, road_param.extra_lane_width);
geom::Vector3D director = edges.second - edges.first;
director /= director.Length();
geom::Vector3D endmarking = edges.first + director * lane_mark_info.width;
std::pair<geom::Vector3D, geom::Vector3D> edges =
ComputeEdgesForLanemark(lane_section, lane, s_current, lane_mark_info.width);
out_mesh.AddVertex(edges.first);
out_mesh.AddVertex(endmarking);
out_mesh.AddVertex(edges.second);
s_current += road_param.resolution * 3;
if (s_current > s_end) {
s_current = s_end;
}
edges = lane.GetCornerPositions(s_current, road_param.extra_lane_width);
director = edges.second - edges.first;
director /= director.Length();
endmarking = edges.first + director * lane_mark_info.width;
edges = ComputeEdgesForLanemark(lane_section, lane, s_current, lane_mark_info.width);
out_mesh.AddVertex(edges.first);
out_mesh.AddVertex(endmarking);
out_mesh.AddVertex(edges.second);
out_mesh.AddIndex(currentIndex);
out_mesh.AddIndex(currentIndex + 1);
@ -1150,6 +1131,33 @@ std::map<road::Lane::LaneType , std::vector<std::unique_ptr<Mesh>>> MeshFactory:
return std::make_unique<Mesh>(out_mesh);
}
std::pair<geom::Vector3D, geom::Vector3D> MeshFactory::ComputeEdgesForLanemark(
const road::LaneSection& lane_section,
const road::Lane& lane,
const double s_current,
const double lanemark_width) const {
std::pair<geom::Vector3D, geom::Vector3D> edges =
lane.GetCornerPositions(s_current, road_param.extra_lane_width);
geom::Vector3D director;
if (edges.first != edges.second) {
director = edges.second - edges.first;
director /= director.Length();
} else {
const std::map<road::LaneId, road::Lane> & lanes = lane_section.GetLanes();
for (const auto& lane_pair : lanes) {
std::pair<geom::Vector3D, geom::Vector3D> another_edge =
lane_pair.second.GetCornerPositions(s_current, road_param.extra_lane_width);
if (another_edge.first != another_edge.second) {
director = another_edge.second - another_edge.first;
director /= director.Length();
break;
}
}
}
geom::Vector3D endmarking = edges.first + director * lanemark_width;
return std::make_pair(edges.first, endmarking);
}
} // namespace geom
} // namespace carla

View File

@ -148,6 +148,15 @@ namespace geom {
RoadParameters road_param;
private:
// Calculate the points on both sides of the lane mark for the specified s_current
std::pair<geom::Vector3D, geom::Vector3D> ComputeEdgesForLanemark(
const road::LaneSection& lane_section,
const road::Lane& lane,
const double s_current,
const double lanemark_width) const;
};
} // namespace geom

View File

@ -10,6 +10,7 @@
#include "carla/MsgPackAdaptors.h"
#include "carla/geom/Transform.h"
#include "carla/rpc/ActorDescription.h"
#include "carla/rpc/AttachmentType.h"
#include "carla/rpc/ActorId.h"
#include "carla/rpc/TrafficLightState.h"
#include "carla/rpc/VehicleAckermannControl.h"
@ -18,6 +19,8 @@
#include "carla/rpc/VehicleLightState.h"
#include "carla/rpc/WalkerControl.h"
#include <string>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4583)
@ -59,11 +62,19 @@ namespace rpc {
: description(std::move(description)),
transform(transform),
parent(parent) {}
SpawnActor(ActorDescription description, const geom::Transform &transform, ActorId parent, AttachmentType attachment_type, const std::string& bone)
: description(std::move(description)),
transform(transform),
parent(parent),
attachment_type(attachment_type),
socket_name(bone) {}
ActorDescription description;
geom::Transform transform;
boost::optional<ActorId> parent;
AttachmentType attachment_type;
std::string socket_name;
std::vector<Command> do_after;
MSGPACK_DEFINE_ARRAY(description, transform, parent, do_after);
MSGPACK_DEFINE_ARRAY(description, transform, parent, attachment_type, socket_name, do_after);
};
struct DestroyActor : CommandBase<DestroyActor> {

View File

@ -35,6 +35,12 @@ namespace rpc {
MSGPACK_DEFINE_ARRAY(location, size);
};
struct HUDPoint {
geom::Location location;
float size;
MSGPACK_DEFINE_ARRAY(location, size);
};
struct Line {
geom::Location begin;
geom::Location end;
@ -42,12 +48,25 @@ namespace rpc {
MSGPACK_DEFINE_ARRAY(begin, end, thickness);
};
struct HUDLine {
geom::Location begin;
geom::Location end;
float thickness;
MSGPACK_DEFINE_ARRAY(begin, end, thickness);
};
struct Arrow {
Line line;
float arrow_size;
MSGPACK_DEFINE_ARRAY(line, arrow_size);
};
struct HUDArrow {
HUDLine line;
float arrow_size;
MSGPACK_DEFINE_ARRAY(line, arrow_size);
};
struct Box {
geom::BoundingBox box;
geom::Rotation rotation;
@ -55,6 +74,13 @@ namespace rpc {
MSGPACK_DEFINE_ARRAY(box, rotation, thickness);
};
struct HUDBox {
geom::BoundingBox box;
geom::Rotation rotation;
float thickness;
MSGPACK_DEFINE_ARRAY(box, rotation, thickness);
};
struct String {
geom::Location location;
std::string text;
@ -62,7 +88,7 @@ namespace rpc {
MSGPACK_DEFINE_ARRAY(location, text, draw_shadow);
};
boost::variant2::variant<Point, Line, Arrow, Box, String> primitive;
boost::variant2::variant<Point, Line, Arrow, Box, String, HUDPoint, HUDLine, HUDArrow, HUDBox> primitive;
Color color = {255u, 0u, 0u};

View File

@ -309,17 +309,17 @@ void RssSensor::TickRssSensor(const client::Timestamp &timestamp, CallbackFuncti
auto const settings = GetWorld().GetSettings();
if ( settings.synchronous_mode ) {
_rss_check->GetLogger()->trace("RssSensor[{}] sync-tick", timestamp.frame);
_rss_check->GetLogger()->info("RssSensor[{}] sync-tick", timestamp.frame);
TickRssSensorThreadLocked(timestamp, actors, callback);
}
else {
// store the future to prevent the destructor of the future from blocked waiting
_rss_check->GetLogger()->trace("RssSensor[{}] async-tick", timestamp.frame);
_rss_check->GetLogger()->info("RssSensor[{}] async-tick", timestamp.frame);
_tick_future = std::async(&RssSensor::TickRssSensorThreadLocked, this, timestamp, actors, callback);
}
} else {
if (bool(_rss_check)){
_rss_check->GetLogger()->debug("RssSensor[{}] tick dropped", timestamp.frame);
_rss_check->GetLogger()->info("RssSensor[{}] tick dropped", timestamp.frame);
}
}
}

View File

@ -345,12 +345,14 @@ class BasicAgent(object):
return None
return Polygon(route_bb)
if self._ignore_vehicles:
return (False, None, -1)
if not vehicle_list:
if vehicle_list is None:
vehicle_list = self._world.get_actors().filter("*vehicle*")
if len(vehicle_list) == 0:
return (False, None, -1)
if not max_distance:
max_distance = self._base_vehicle_threshold

View File

@ -33,9 +33,10 @@ def get_libcarla_extensions():
if os.name == "posix":
import distro
linux_distro = distro.linux_distribution()[0]
if linux_distro.lower() in ["ubuntu", "debian", "deepin"]:
supported_dists = ["ubuntu", "debian", "deepin"]
linux_distro = distro.id().lower()
if linux_distro in supported_dists:
pwd = os.path.dirname(os.path.realpath(__file__))
pylib = "libboost_python%d%d.a" % (sys.version_info.major,
sys.version_info.minor)
@ -55,7 +56,7 @@ def get_libcarla_extensions():
os.path.join(pwd, 'dependencies/lib/libxerces-c.a')]
extra_link_args += ['-lz']
extra_compile_args = [
'-isystem', 'dependencies/include/system', '-fPIC', '-std=c++14',
'-isystem', os.path.join(pwd, 'dependencies/include/system'), '-fPIC', '-std=c++14',
'-Werror', '-Wall', '-Wextra', '-Wpedantic', '-Wno-self-assign-overloaded',
'-Wdeprecated', '-Wno-shadow', '-Wuninitialized', '-Wunreachable-code',
'-Wpessimizing-move', '-Wold-style-cast', '-Wnull-dereference',
@ -77,6 +78,7 @@ def get_libcarla_extensions():
extra_link_args += [os.path.join(pwd, 'dependencies/lib/libad_physics.a')]
extra_link_args += [os.path.join(pwd, 'dependencies/lib/libad_map_opendrive_reader.a')]
extra_link_args += [os.path.join(pwd, 'dependencies/lib/libboost_program_options.a')]
extra_link_args += [os.path.join(pwd, 'dependencies/lib/libodrSpiral.a')]
extra_link_args += [os.path.join(pwd, 'dependencies/lib/libspdlog.a')]
extra_link_args += ['-lrt']
extra_link_args += ['-ltbb']
@ -100,7 +102,7 @@ def get_libcarla_extensions():
# extra_link_args += ['/usr/lib/gcc/x86_64-linux-gnu/7/libstdc++.a']
extra_link_args += ['-lstdc++']
else:
raise NotImplementedError
raise NotImplementedError(linux_distro + " not in supported posix platforms: " + str(supported_dists))
elif os.name == "nt":
pwd = os.path.dirname(os.path.realpath(__file__))
pylib = 'libboost_python%d%d' % (

View File

@ -113,6 +113,15 @@ void export_actor() {
.def("get_velocity", &cc::Actor::GetVelocity)
.def("get_angular_velocity", &cc::Actor::GetAngularVelocity)
.def("get_acceleration", &cc::Actor::GetAcceleration)
.def("get_component_world_transform", &cc::Actor::GetComponentWorldTransform, (arg("component_name")))
.def("get_component_relative_transform", &cc::Actor::GetComponentRelativeTransform, (arg("component_name")))
.def("get_bone_world_transforms", CALL_RETURNING_LIST(cc::Actor,GetBoneWorldTransforms))
.def("get_bone_relative_transforms", CALL_RETURNING_LIST(cc::Actor,GetBoneRelativeTransforms))
.def("get_component_names", CALL_RETURNING_LIST(cc::Actor,GetComponentNames))
.def("get_bone_names", CALL_RETURNING_LIST(cc::Actor,GetBoneNames))
.def("get_socket_world_transforms", CALL_RETURNING_LIST(cc::Actor,GetSocketWorldTransforms))
.def("get_socket_relative_transforms", CALL_RETURNING_LIST(cc::Actor,GetSocketRelativeTransforms))
.def("get_socket_names", CALL_RETURNING_LIST(cc::Actor,GetSocketNames))
.def("set_location", &cc::Actor::SetLocation, (arg("location")))
.def("set_transform", &cc::Actor::SetTransform, (arg("transform")))
.def("set_target_velocity", &cc::Actor::SetTargetVelocity, (arg("velocity")))
@ -194,6 +203,7 @@ void export_actor() {
.def("enable_carsim", &cc::Vehicle::EnableCarSim, (arg("simfile_path") = ""))
.def("use_carsim_road", &cc::Vehicle::UseCarSimRoad, (arg("enabled")))
.def("enable_chrono_physics", &cc::Vehicle::EnableChronoPhysics, (arg("max_substeps")=30, arg("max_substep_delta_time")=0.002, arg("vehicle_json")="", arg("powetrain_json")="", arg("tire_json")="", arg("base_json_path")=""))
.def("restore_physx_physics", &cc::Vehicle::RestorePhysXPhysics)
.def("get_failure_state", &cc::Vehicle::GetFailureState)
.def(self_ns::str(self_ns::self))
;

View File

@ -82,9 +82,15 @@ void export_commands() {
"__init__",
&command_impl::CustomSpawnActorInit<cc::ActorBlueprint, cg::Transform, ActorPtr>,
(arg("blueprint"), arg("transform"), arg("parent")))
.def(
"__init__",
&command_impl::CustomSpawnActorInit<cc::ActorBlueprint, cg::Transform, ActorPtr, cr::AttachmentType, std::string>,
(arg("blueprint"), arg("transform"), arg("parent"), arg("attachment_type"), arg("socket_name")))
.def(init<cr::Command::SpawnActor>())
.def_readwrite("transform", &cr::Command::SpawnActor::transform)
.def_readwrite("parent_id", &cr::Command::SpawnActor::parent)
.def_readwrite("attachment_type", &cr::Command::SpawnActor::attachment_type)
.def_readwrite("socket_name", &cr::Command::SpawnActor::socket_name)
.def("then", &command_impl::Then, (arg("command")))
;

View File

@ -11,6 +11,8 @@
#include <carla/rpc/EnvironmentObject.h>
#include <carla/rpc/ObjectLabel.h>
#include <string>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
namespace carla {
@ -293,15 +295,17 @@ void export_world() {
const cc::ActorBlueprint &blueprint, \
const cg::Transform &transform, \
cc::Actor *parent, \
cr::AttachmentType attachment_type) { \
cr::AttachmentType attachment_type, \
const std::string& bone) { \
carla::PythonUtil::ReleaseGIL unlock; \
return self.fn(blueprint, transform, parent, attachment_type); \
return self.fn(blueprint, transform, parent, attachment_type, bone); \
}, \
( \
arg("blueprint"), \
arg("transform"), \
arg("attach_to")=carla::SharedPtr<cc::Actor>(), \
arg("attachment_type")=cr::AttachmentType::Rigid)
arg("attachment_type")=cr::AttachmentType::Rigid, \
arg("bone")=std::string())
class_<cc::World>("World", no_init)
.add_property("id", &cc::World::GetId)
@ -317,6 +321,8 @@ void export_world() {
.def("apply_settings", &ApplySettings, (arg("settings"), arg("seconds")=0.0))
.def("get_weather", CONST_CALL_WITHOUT_GIL(cc::World, GetWeather))
.def("set_weather", &cc::World::SetWeather)
.def("get_imui_sensor_gravity", CONST_CALL_WITHOUT_GIL(cc::World, GetIMUISensorGravity))
.def("set_imui_sensor_gravity", &cc::World::SetIMUISensorGravity, (arg("NewIMUISensorGravity")) )
.def("get_snapshot", &cc::World::GetSnapshot)
.def("get_actor", CONST_CALL_WITHOUT_GIL_1(cc::World, GetActor, carla::ActorId), (arg("actor_id")))
.def("get_actors", CONST_CALL_WITHOUT_GIL(cc::World, GetActors))
@ -368,6 +374,12 @@ void export_world() {
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_hud_point", &cc::DebugHelper::DrawHUDPoint,
(arg("location"),
arg("size")=0.1f,
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_line", &cc::DebugHelper::DrawLine,
(arg("begin"),
arg("end"),
@ -375,6 +387,13 @@ void export_world() {
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_hud_line", &cc::DebugHelper::DrawHUDLine,
(arg("begin"),
arg("end"),
arg("thickness")=0.1f,
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_arrow", &cc::DebugHelper::DrawArrow,
(arg("begin"),
arg("end"),
@ -383,6 +402,14 @@ void export_world() {
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_hud_arrow", &cc::DebugHelper::DrawHUDArrow,
(arg("begin"),
arg("end"),
arg("thickness")=0.1f,
arg("arrow_size")=0.1f,
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_box", &cc::DebugHelper::DrawBox,
(arg("box"),
arg("rotation"),
@ -390,6 +417,13 @@ void export_world() {
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_hud_box", &cc::DebugHelper::DrawHUDBox,
(arg("box"),
arg("rotation"),
arg("thickness")=0.1f,
arg("color")=cc::DebugHelper::Color(255u, 0u, 0u),
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
.def("draw_string", &cc::DebugHelper::DrawString,
(arg("location"),
arg("text"),
@ -398,4 +432,6 @@ void export_world() {
arg("life_time")=-1.0f,
arg("persistent_lines")=true))
;
// scope HUD = class_<cc::DebugHelper>(
}

View File

@ -65,7 +65,7 @@
- param_name: opendrive
type: str
doc: >
Content of an OpenDRIVE file as `string`, __not the path to the `.xodr`__.
Content of an ASAM OpenDRIVE file as `string`, __not the path to the `.xodr`__.
- param_name: parameters
type: carla.OpendriveGenerationParameters
default: (2.0, 50.0, 1.0, 0.6, true, true)
@ -101,6 +101,7 @@
doc: >
Layers of the map that will be loaded. By default all layers are loaded.
This parameter works like a flag mask.
return: carla.World
warning: >
`map_layers` are only available for "Opt" maps
doc: >
@ -114,11 +115,37 @@
doc: >
Option to reset the episode setting to default values, set to false to keep the current settings.
This is useful to keep sync mode when changing map and to keep deterministic scenarios.
return: carla.World
raises: RuntimeError when corresponding.
doc: >
Reload the current world, note that a new world is created with default
settings using the same map. All actors present in the world will be
destroyed, __but__ traffic manager instances will stay alive.
# --------------------------------------
- def_name: load_world_if_different
params:
- param_name: map_name
type: str
doc: >
Name of the map to be used in this world. Accepts both full paths and map names, e.g.
'/Game/Carla/Maps/Town01' or 'Town01'. Remember that these paths are dynamic.
- param_name: reset_settings
type: bool
default: true
doc: >
Option to reset the episode setting to default values, set to false to keep the current settings.
This is useful to keep sync mode when changing map and to keep deterministic scenarios.
- param_name: map_layers
type: carla.MapLayer
default: carla.MapLayer.All
doc: >
Layers of the map that will be loaded. By default all layers are loaded.
This parameter works like a flag mask.
return: carla.World
warning: >
`map_layers` are only available for "Opt" maps
doc: >
Creates a new world with default settings using `map_name` map only if it is a different map from the currently loaded map. Otherwise this function returns `None`. All actors in the current world will be destroyed.
# --------------------------------------
- def_name: replay_file
params:
@ -732,7 +759,7 @@
- class_name: OpendriveGenerationParameters
# - DESCRIPTION ------------------------
doc: >
This class defines the parameters used when generating a world using an OpenDRIVE file.
This class defines the parameters used when generating a world using an ASAM OpenDRIVE file.
# - PROPERTIES -------------------------
instance_variables:
- var_name: vertex_distance

View File

@ -69,7 +69,11 @@
doc: >
Links another command to be executed right after. It allows to ease very common flows such as spawning a set of vehicles by command and then using this method to set them to autopilot automatically.
# --------------------------------------
- class_name: FutureActor
# - DESCRIPTION ------------------------
doc: >
A utility object used to reference an actor that will be created in the command in the previous step, it has no parameters or methods.
# --------------------------------------
- class_name: DestroyActor
# - DESCRIPTION ------------------------
doc: >

View File

@ -70,7 +70,13 @@
- var_name: Sidewalks
- var_name: TrafficSigns
- var_name: Vegetation
- var_name: Vehicles
- var_name: Car
- var_name: Bus
- var_name: Truck
- var_name: Motorcycle
- var_name: Bicycle
- var_name: Rider
- var_name: Train
- var_name: Walls
- var_name: Sky
- var_name: Ground

View File

@ -125,11 +125,11 @@
- var_name: substepping
type: bool
doc: >
Enable the physics substepping. This option allows computing some physics substeps between two render frames. If synchronous mode is set, the number of substeps and its time interval are fixed and computed are so they fulfilled the requirements of carla.WorldSettings.max_substep and carla.WorldSettings.max_substep_delta_time. These last two parameters need to be compatible with carla.WorldSettings.fixed_delta_seconds. Enabled by default.
Enable the physics substepping. This option allows computing some physics substeps between two render frames. If synchronous mode is set, the number of substeps and its time interval are fixed and computed are so they fulfilled the requirements of carla.WorldSettings.max_substeps and carla.WorldSettings.max_substep_delta_time. These last two parameters need to be compatible with carla.WorldSettings.fixed_delta_seconds. Enabled by default.
- var_name: max_substep_delta_time
type: float
doc: >
Maximum delta time of the substeps. If the carla.WorldSettingsmax_substep is high enough, the substep delta time would be always below or equal to this value. By default, the value is set to 0.01.
Maximum delta time of the substeps. If the carla.WorldSettings.max_substeps is high enough, the substep delta time would be always below or equal to this value. By default, the value is set to 0.01.
- var_name: max_substeps
type: int
doc: >
@ -993,8 +993,140 @@
doc: >
Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
doc: >
Draws a box, ussually to act for object colliders.
Draws a box, usually to act for object colliders.
# --------------------------------------
- def_name: draw_hud_arrow
params:
- param_name: begin
type: carla.Location
param_units: meters
doc: >
Point in the coordinate system where the arrow starts.
- param_name: end
type: carla.Location
param_units: meters
doc: >
Point in the coordinate system where the arrow ends and points towards to.
- param_name: thickness
type: float
default: 0.1
param_units: meters
doc: >
Density of the line.
- param_name: arrow_size
type: float
default: 0.1
param_units: meters
doc: >
Size of the tip of the arrow.
- param_name: color
type: carla.Color
default: (255,0,0)
doc: >
RGB code to color the object. Red by default.
- param_name: life_time
type: float
default: -1.0
param_units: seconds
doc: >
Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
doc: >
Draws an arrow on the HUD from `begin` to `end` which can only be seen server-side.
# --------------------------------------
- def_name: draw_hud_box
params:
- param_name: box
type: carla.BoundingBox
doc: >
Object containing a location and the length of a box for every axis.
- param_name: rotation
type: carla.Rotation
param_units: degrees (pitch,yaw,roll)
doc: >
Orientation of the box according to Unreal Engine's axis system.
- param_name: thickness
type: float
default: 0.1
param_units: meters
doc: >
Density of the lines that define the box.
- param_name: color
type: carla.Color
default: (255,0,0)
doc: >
RGB code to color the object. Red by default.
- param_name: life_time
type: float
default: -1.0
param_units: seconds
doc: >
Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
doc: >
Draws a box on the HUD, usually to act for object colliders. The box can only be seen server-side.
# --------------------------------------
- def_name: draw_hud_line
params:
- param_name: begin
type: carla.Location
param_units: meters
doc: >
Point in the coordinate system where the line starts.
- param_name: end
type: carla.Location
param_units: meters
doc: >
Spot in the coordinate system where the line ends.
- param_name: thickness
type: float
default: 0.1
param_units: meters
doc: >
Density of the line.
- param_name: color
type: carla.Color
default: (255,0,0)
doc: >
RGB code to color the object. Red by default.
- param_name: life_time
type: float
default: -1.0
param_units: seconds
doc: >
Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
doc: >
Draws a line on the HUD in between `begin` and `end`. The line can only be seen server-side.
# --------------------------------------
- def_name: draw_hud_point
params:
- param_name: location
type: carla.Location
param_units: meters
doc: >
Spot in the coordinate system to center the object.
- param_name: size
type: float
default: 0.1
param_units: meters
doc: >
Density of the point.
- param_name: color
type: carla.Color
default: (255,0,0)
doc: >
RGB code to color the object. Red by default.
- param_name: life_time
type: float
default: -1.0
param_units: seconds
doc: >
Shape's lifespan. By default it only lasts one frame. Set this to <code>0</code> for permanent shapes.
doc: >
Draws a point on the HUD at `location`. The point can only be seen server-side.
# --------------------------------------
- def_name: draw_line
params:

View File

@ -0,0 +1,34 @@
import glob
import os
import sys
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
# ==============================================================================
# -- imports -------------------------------------------------------------------
# ==============================================================================
import carla
client = carla.Client('localhost', 2000)
world = client.get_world()
location = carla.Location(200.0, 200.0, 200.0)
rotation = carla.Rotation(0.0, 0.0, 0.0)
transform = carla.Transform(location, rotation)
bp_library = world.get_blueprint_library()
bp_audi = bp_library.find('vehicle.audi.tt')
audi = world.spawn_actor(bp_audi, transform)
component_transform = audi.get_component_world_transform('front-blinker-r-1')
print(component_transform)

View File

@ -324,6 +324,7 @@ class KeyboardControl(object):
def __init__(self, world, start_in_autopilot):
self._carsim_enabled = False
self._carsim_road = False
self._chrono_enabled = False
self._autopilot_enabled = start_in_autopilot
if isinstance(world.player, carla.Vehicle):
self._control = carla.VehicleControl()
@ -417,14 +418,24 @@ class KeyboardControl(object):
world.camera_manager.set_sensor(current_index)
elif event.key == K_k and (pygame.key.get_mods() & KMOD_CTRL):
print("k pressed")
world.player.enable_carsim()
if not self._carsim_enabled:
self._carsim_enabled = True
world.player.enable_carsim()
else:
self._carsim_enabled = False
world.player.restore_physx_physics()
elif event.key == K_o and (pygame.key.get_mods() & KMOD_CTRL):
print("o pressed")
vehicle_json = "sedan/vehicle/Sedan_Vehicle.json"
powertrain_json = "sedan/powertrain/Sedan_SimpleMapPowertrain.json"
tire_json = "sedan/tire/Sedan_TMeasyTire.json"
base_path = "~/carla/Build/chrono-install/share/chrono/data/vehicle/"
world.player.enable_chrono_physics(5000, 0.002, vehicle_json, powertrain_json, tire_json, base_path)
if not self._chrono_enabled:
self._chrono_enabled = True
vehicle_json = "sedan/vehicle/Sedan_Vehicle.json"
powertrain_json = "sedan/powertrain/Sedan_SimpleMapPowertrain.json"
tire_json = "sedan/tire/Sedan_TMeasyTire.json"
base_path = "/home/adas/carla/Build/chrono-install/share/chrono/data/vehicle/"
world.player.enable_chrono_physics(5000, 0.002, vehicle_json, powertrain_json, tire_json, base_path)
else:
self._chrono_enabled = False
world.player.restore_physx_physics()
elif event.key == K_j and (pygame.key.get_mods() & KMOD_CTRL):
self._carsim_road = not self._carsim_road
world.player.use_carsim_road(self._carsim_road)

View File

@ -135,6 +135,7 @@ class World(object):
def __init__(self, carla_world, args):
self.world = carla_world
self.sync = args.sync
self.actor_role_name = args.rolename
self.dim = (args.width, args.height)
try:
@ -161,10 +162,7 @@ class World(object):
sys.exit(1)
self.restart()
self.world_tick_id = self.world.on_tick(self.on_world_tick)
def on_world_tick(self, world_snapshot):
self.hud.on_world_tick(world_snapshot)
self.world_tick_id = self.world.on_tick(self.hud.on_world_tick)
def toggle_pause(self):
settings = self.world.get_settings()
@ -235,6 +233,11 @@ class World(object):
self.rss_sensor = RssSensor(self.player, self.world,
self.rss_unstructured_scene_visualizer, self.rss_bounding_box_visualizer, self.hud.rss_state_visualizer)
if self.sync:
self.world.tick()
else:
self.world.wait_for_tick()
def tick(self, clock):
self.hud.tick(self.player, clock)
@ -384,7 +387,7 @@ class VehicleControl(object):
print('\nReceived signal {}. Trigger stopping...'.format(signum))
VehicleControl.signal_received = True
def parse_events(self, world, clock):
def parse_events(self, world, clock, sync_mode):
if VehicleControl.signal_received:
print('\nAccepted signal. Stopping loop...')
return True
@ -806,13 +809,27 @@ def game_loop(args):
(args.width, args.height),
pygame.HWSURFACE | pygame.DOUBLEBUF)
world = World(client.get_world(), args)
sim_world = client.get_world()
original_settings = sim_world.get_settings()
settings = sim_world.get_settings()
if args.sync != settings.synchronous_mode:
args.sync = True
settings.synchronous_mode = True
settings.fixed_delta_seconds = 0.05
sim_world.apply_settings(settings)
traffic_manager = client.get_trafficmanager()
traffic_manager.set_synchronous_mode(True)
world = World(sim_world, args)
controller = VehicleControl(world, args.autopilot)
clock = pygame.time.Clock()
while True:
if args.sync:
sim_world.tick()
clock.tick_busy_loop(60)
if controller.parse_events(world, clock):
if controller.parse_events(world, clock, args.sync):
return
world.tick(clock)
world.render(display)
@ -875,6 +892,10 @@ def main():
'--externalActor',
action='store_true',
help='attaches to externally created actor by role name')
argparser.add_argument(
'--sync',
action='store_true',
help='Activate synchronous mode execution')
args = argparser.parse_args()
args.width, args.height = [int(x) for x in args.res.split('x')]

View File

@ -334,6 +334,9 @@ class RssSensor(object):
self.map_log_level = self.map_log_level-1
self.sensor.set_map_log_level(self.map_log_level)
def drop_route(self):
self.sensor.drop_route()
@staticmethod
def get_default_parameters():
ego_dynamics = ad.rss.world.RssDynamics()

View File

@ -1,7 +1,6 @@
CARLA Simulator
===============
[![Build Status](https://travis-ci.org/carla-simulator/carla.svg?branch=master)](https://travis-ci.org/carla-simulator/carla)
[![Documentation](https://readthedocs.org/projects/carla/badge/?version=latest)](http://carla.readthedocs.io)
[![carla.org](Docs/img/btn/web.png)](http://carla.org)
@ -15,29 +14,38 @@ validation of autonomous driving systems. In addition to open-source code and pr
vehicles) that were created for this purpose and can be used freely. The simulation platform supports flexible specification of sensor suites and
environmental conditions.
[![CARLA Video](Docs/img/video_thumbnail_0910.jpg)](https://www.youtube.com/watch?v=7jej46ALVRE)
[![CARLA Video](Docs/img/0_9_15_thumbnail.webp)](https://www.youtube.com/watch?v=q4V9GYjA1pE )
If you want to benchmark your model in the same conditions as in our CoRL17
paper, check out
[Benchmarking](https://github.com/carla-simulator/driving-benchmarks).
### Download CARLA
Linux:
* [**Get CARLA overnight build**](http://carla-releases.s3.amazonaws.com/Linux/Dev/CARLA_Latest.tar.gz)
* [**Get AdditionalMaps overnight build**](http://carla-releases.s3.amazonaws.com/Linux/Dev/AdditionalMaps_Latest.tar.gz)
* [**Get CARLA overnight build**](https://carla-releases.s3.us-east-005.backblazeb2.com/Linux/Dev/CARLA_Latest.tar.gz)
* [**Get AdditionalMaps overnight build**](https://carla-releases.s3.us-east-005.backblazeb2.com/Linux/Dev/AdditionalMaps_Latest.tar.gz)
Windows:
* [**Get CARLA overnight build**](http://carla-releases.s3.amazonaws.com/Windows/Dev/CARLA_Latest.zip)
* [**Get AdditionalMaps overnight build**](http://carla-releases.s3.amazonaws.com/Windows/Dev/AdditionalMaps_Latest.zip)
* [**Get CARLA overnight build**](https://carla-releases.s3.us-east-005.backblazeb2.com/Windows/Dev/CARLA_Latest.zip)
* [**Get AdditionalMaps overnight build**](https://carla-releases.s3.us-east-005.backblazeb2.com/Windows/Dev/AdditionalMaps_Latest.zip)
### Recommended system
* Intel i7 gen 9th - 11th / Intel i9 gen 9th - 11th / AMD ryzen 7 / AMD ryzen 9
* +16 GB RAM memory
* NVIDIA RTX 2070 / NVIDIA RTX 2080 / NVIDIA RTX 3070, NVIDIA RTX 3080
* Ubuntu 18.04
* +32 GB RAM memory
* NVIDIA RTX 3070 / NVIDIA RTX 3080 / NVIDIA RTX 4090
* Ubuntu 20.04
## Documentation
The [CARLA documentation](https://carla.readthedocs.io/en/latest/) is hosted on ReadTheDocs. Please see the following key links:
- [Building on Linux](https://carla.readthedocs.io/en/latest/build_linux/)
- [Building on Windows](https://carla.readthedocs.io/en/latest/build_windows/)
- [First steps](https://carla.readthedocs.io/en/latest/tuto_first_steps/)
- [CARLA asset catalogue](https://carla.readthedocs.io/en/latest/catalogue/)
- [Python API reference](https://carla.readthedocs.io/en/latest/python_api/)
- [Blueprint library](https://carla.readthedocs.io/en/latest/bp_library/)
## CARLA Ecosystem
Repositories associated to the CARLA simulation platform:
Repositories associated with the CARLA simulation platform:
* [**CARLA Autonomous Driving leaderboard**](https://leaderboard.carla.org/): Automatic platform to validate Autonomous Driving stacks
* [**Scenario_Runner**](https://github.com/carla-simulator/scenario_runner): Engine to execute traffic scenarios in CARLA 0.9.X
@ -46,8 +54,10 @@ Repositories associated to the CARLA simulation platform:
* [**Conditional Imitation-Learning**](https://github.com/felipecode/coiltraine): Training and testing Conditional Imitation Learning models in CARLA
* [**AutoWare AV stack**](https://github.com/carla-simulator/carla-autoware): Bridge to connect AutoWare AV stack to CARLA
* [**Reinforcement-Learning**](https://github.com/carla-simulator/reinforcement-learning): Code for running Conditional Reinforcement Learning models in CARLA
* [**RoadRunner**](https://www.mathworks.com/products/roadrunner.html): MATLAB GUI based application to create road networks in the ASAM OpenDRIVE format
* [**Map Editor**](https://github.com/carla-simulator/carla-map-editor): Standalone GUI application to enhance RoadRunner maps with traffic lights and traffic signs information
**Like what you see? Star us on GitHub to support the project!**
Paper
@ -74,24 +84,22 @@ Felipe Codevilla, Antonio Lopez, Vladlen Koltun; PMLR 78:1-16
Building CARLA
--------------
Use `git clone` or download the project from this page. Note that the master branch contains the most recent release of CARLA with the latest fixes and features.
Clone this repository locally from GitHub:
Then follow the instruction at [How to build on Linux][buildlinuxlink] or [How to build on Windows][buildwindowslink].
The Linux build needs for an UE patch to solve some visualization issues regarding Vulkan. Those already working with a Linux build should install the patch and make the UE build again using the following commands.
```sh
# Download and install the UE patch
cd ~/UnrealEngine_4.24
wget https://carla-releases.s3.eu-west-3.amazonaws.com/Linux/UE_Patch/430667-13636743-patch.txt ~/430667-13636743-patch.txt
patch --strip=4 < ~/430667-13636743-patch.txt
# Build UE
./Setup.sh && ./GenerateProjectFiles.sh && make
git clone https://github.com/carla-simulator/carla.git .
```
Unfortunately we don't have official instructions to build on Mac yet, please check the progress at [issue #150][issue150].
Also, clone the [CARLA fork of the Unreal Engine](https://github.com/CarlaUnreal/UnrealEngine) into an appropriate location:
```sh
git clone --depth 1 -b carla https://github.com/CarlaUnreal/UnrealEngine.git .
```
Once you have cloned the repositories, follow the instructions for [building in Linux][buildlinuxlink] or [building in Windows][buildwindowslink].
[buildlinuxlink]: https://carla.readthedocs.io/en/latest/build_linux/
[buildwindowslink]: https://carla.readthedocs.io/en/latest/build_windows/
[issue150]: https://github.com/carla-simulator/carla/issues/150
Contributing
------------
@ -106,29 +114,6 @@ F.A.Q.
If you run into problems, check our
[FAQ](https://carla.readthedocs.io/en/latest/build_faq/).
CARLA Talks
------
The team creates some additional content for users, besides the docs. This is a great way to cover different subjects such as detailed explanations for a specific module, latest improvements in a feature, future work and much more.
__CARLA Talks 2020 (May):__
* __General__
* Art improvements: environment and rendering — [video](https://youtu.be/ZZaHevsz8W8) | [slides](https://drive.google.com/file/d/1l9Ztaq0Q8fNN5YPU4-5vL13eZUwsQl5P/view?usp=sharing)
* Core implementations: synchrony, snapshots and landmarks — [video](https://youtu.be/nyyTLmphqY4) | [slides](https://drive.google.com/file/d/1yaOwf1419qWZqE1gTSrrknsWOhawEWh_/view?usp=sharing)
* Data ingestion — [video](https://youtu.be/mHiUUZ4xC9o) | [slides](https://drive.google.com/file/d/10uNBAMreKajYimIhwCqSYXjhfVs2bX31/view?usp=sharing)
* Pedestrians and their implementation — [video](https://youtu.be/Uoz2ihDwaWA) | [slides](https://drive.google.com/file/d/1Tsosin7BLP1k558shtbzUdo2ZXVKy5CB/view?usp=sharing)
* Sensors in CARLA — [video](https://youtu.be/T8qCSet8WK0) | [slides](https://drive.google.com/file/d/1UO8ZAIOp-1xaBzcFMfn_IoipycVkUo4q/view?usp=sharing)
* __Modules__
* Improvements in the Traffic Manager — [video](https://youtu.be/n9cufaJ17eA) | [slides](https://drive.google.com/file/d/1R9uNZ6pYHSZoEBxs2vYK7swiriKbbuxo/view?usp=sharing)
* Integration of autoware and ROS — [video](https://youtu.be/ChIgcC2scwU) | [slides](https://drive.google.com/file/d/1uO6nBaFirrllb08OeqGAMVLApQ6EbgAt/view?usp=sharing)
* Introducing ScenarioRunner — [video](https://youtu.be/dcnnNJowqzM) | [slides](https://drive.google.com/file/d/1zgoH_kLOfIw117FJGm2IVZZAIRw9U2Q0/view?usp=sharing)
* OpenSCENARIO support — [slides](https://drive.google.com/file/d/1g6ATxZRTWEdstiZwfBN1_T_x_WwZs0zE/view?usp=sharing)
* __Features__
* Co-Simulations with SUMO and PTV-Vissim — [video](https://youtu.be/PuFSbj1PU94) | [slides](https://drive.google.com/file/d/10DgMNUBqKqWBrdiwBiAIT4DdR9ObCquI/view?usp=sharing)
* Integration of RSS-lib — [slides](https://drive.google.com/file/d/1whREmrCv67fOMipgCk6kkiW4VPODig0A/view?usp=sharing)
* The External Sensor Interface (ESI) — [video](https://youtu.be/5hXHPV9FIeY) | [slides](https://drive.google.com/file/d/1VWFaEoS12siW6NtQDUkm44BVO7tveRbJ/view?usp=sharing)
* The OpenDRIVE Standalone Mode — [video](https://youtu.be/U25GhofVV1Q) | [slides](https://drive.google.com/file/d/1D5VsgfX7dmgPWn7UtDDid3-OdS1HI4pY/view?usp=sharing)
Licenses
-------

View File

@ -1055,6 +1055,28 @@ ECarlaServerResponse FVehicleActor::EnableChronoPhysics(
return ECarlaServerResponse::Success;
}
ECarlaServerResponse FVehicleActor::RestorePhysXPhysics()
{
if (IsDormant())
{
}
else
{
auto Vehicle = Cast<ACarlaWheeledVehicle>(GetActor());
if (Vehicle == nullptr)
{
return ECarlaServerResponse::NotAVehicle;
}
UBaseCarlaMovementComponent* MovementComponent =
Vehicle->GetCarlaMovementComponent<UBaseCarlaMovementComponent>();
if(MovementComponent)
{
MovementComponent->DisableSpecialPhysics();
}
}
return ECarlaServerResponse::Success;
}
// FSensorActor functions ---------------------
// FtrafficSignActor functions ---------------------

View File

@ -343,6 +343,11 @@ public:
return ECarlaServerResponse::ActorTypeMismatch;
}
virtual ECarlaServerResponse RestorePhysXPhysics()
{
return ECarlaServerResponse::ActorTypeMismatch;
}
// Traffic light functions
virtual ECarlaServerResponse SetTrafficLightState(const ETrafficLightState&)
@ -532,6 +537,8 @@ public:
uint64_t MaxSubsteps, float MaxSubstepDeltaTime,
const FString& VehicleJSON, const FString& PowertrainJSON,
const FString& TireJSON, const FString& BaseJSONPath) final;
virtual ECarlaServerResponse RestorePhysXPhysics();
};
class FSensorActor : public FCarlaActor

View File

@ -34,6 +34,9 @@ static bool ValidateStaticMesh(UStaticMesh *Mesh)
for (int i = 0; i < Mesh->StaticMaterials.Num(); i++)
{
UMaterialInterface *Material = Mesh->GetMaterial(i);
if (!Material) {
Material = UMaterial::GetDefaultMaterial(MD_Surface);
}
const FString MaterialName = Material->GetName();
if (MaterialName.Contains(TEXT("light"), ESearchCase::IgnoreCase) ||

View File

@ -105,7 +105,7 @@ bool UCarlaEpisode::LoadNewEpisode(const FString &MapString, bool ResetSettings)
UGameplayStatics::OpenLevel(GetWorld(), *FinalPath, true);
if (ResetSettings)
ApplySettings(FEpisodeSettings{});
// send 'LOAD_MAP' command to all secondary servers (if any)
if (bIsPrimaryServer)
{
@ -114,7 +114,7 @@ bool UCarlaEpisode::LoadNewEpisode(const FString &MapString, bool ResetSettings)
{
FCarlaEngine *CarlaEngine = GameInstance->GetCarlaEngine();
auto SecondaryServer = CarlaEngine->GetSecondaryServer();
if (SecondaryServer->HasClientsConnected())
if (SecondaryServer->HasClientsConnected())
{
SecondaryServer->GetCommander().SendLoadMap(std::string(TCHAR_TO_UTF8(*FinalPath)));
}
@ -294,11 +294,12 @@ carla::rpc::Actor UCarlaEpisode::SerializeActor(AActor* Actor) const
void UCarlaEpisode::AttachActors(
AActor *Child,
AActor *Parent,
EAttachmentType InAttachmentType)
EAttachmentType InAttachmentType,
const FString& SocketName)
{
Child->AddActorWorldOffset(FVector(CurrentMapOrigin));
UActorAttacher::AttachActors(Child, Parent, InAttachmentType);
UActorAttacher::AttachActors(Child, Parent, InAttachmentType, SocketName);
if (bIsPrimaryServer)
{

View File

@ -245,7 +245,8 @@ public:
void AttachActors(
AActor *Child,
AActor *Parent,
EAttachmentType InAttachmentType = EAttachmentType::Rigid);
EAttachmentType InAttachmentType = EAttachmentType::Rigid,
const FString& SocketName = "");
/// @copydoc FActorDispatcher::DestroyActor(AActor*)
UFUNCTION(BlueprintCallable)

View File

@ -112,6 +112,10 @@ public:
TArray<FString> GetNamesOfAllActors();
// Gravitational acceleration. Default is earth one, which is approximately 9.81 m/s^2
UPROPERTY(BlueprintReadOnly, EditAnywhere, Category="Sensor Gravity")
float IMUISensorGravity = 9.81f;
protected:
void InitGame(const FString &MapName, const FString &Options, FString &ErrorMessage) override;
@ -176,6 +180,7 @@ private:
UPROPERTY()
ATrafficLightManager* TrafficLightManager = nullptr;
UPROPERTY()
ALargeMapManager* LMManager = nullptr;
FDelegateHandle OnEpisodeSettingsChangeHandle;

View File

@ -33,7 +33,6 @@ void ACarlaHUD::DrawHUD()
FVector2D Screen;
if (Player->ProjectWorldLocationToScreen(StringList[i].Location, Screen, true))
{
// draw text
DrawText(StringList[i].Str, StringList[i].Color, Screen.X, Screen.Y);
}
@ -45,6 +44,25 @@ void ACarlaHUD::DrawHUD()
else
++i;
}
while (i < LineList.Num())
{
// project position from camera
FVector2D Begin, End;
if (Player->ProjectWorldLocationToScreen(LineList[i].Begin, Begin, true) &&
Player->ProjectWorldLocationToScreen(LineList[i].End, End, true))
{
DrawLine(Begin.X, Begin.Y, End.X, End.Y, LineList[i].Color, LineList[i].Thickness);
}
// check to remove the string
if (Now >= LineList[i].TimeToDie)
{
LineList.RemoveAt(i);
}
else
++i;
}
}
void ACarlaHUD::AddHUDString(const FString Str, const FVector Location, const FColor Color, double LifeTime)
@ -53,3 +71,10 @@ void ACarlaHUD::AddHUDString(const FString Str, const FVector Location, const FC
HUDString Obj { Str, Location, Color, Now + LifeTime };
StringList.Add(std::move(Obj));
}
void ACarlaHUD::AddHUDLine(const FVector Begin, const FVector End, const float Thickness, const FColor Color, double LifeTime)
{
double Now = FPlatformTime::Seconds();
HUDLine Obj { Begin, End, Thickness, Color, Now + LifeTime };
LineList.Add(std::move(Obj));
}

View File

@ -35,6 +35,15 @@ struct HUDString
double TimeToDie;
};
struct HUDLine
{
FVector Begin;
FVector End;
float Thickness;
FColor Color;
double TimeToDie;
};
/// Class to draw on HUD
UCLASS()
class CARLA_API ACarlaHUD : public AHUD
@ -55,7 +64,9 @@ public:
void AddDebugVehicleForTelemetry(UWheeledVehicleMovementComponent* Veh) { DebugVehicle = Veh; }
void AddHUDString(const FString Str, const FVector Location, const FColor Color, double LifeTime);
void AddHUDLine(const FVector Begin, const FVector End, const float Thickness, const FColor Color, double LifeTime);
private:
TArray<HUDString> StringList;
TArray<HUDLine> LineList;
};

View File

@ -304,6 +304,15 @@ void ACarlaRecorder::AddVehicleLight(FCarlaActor *CarlaActor)
AddLightVehicle(LightVehicle);
}
void ACarlaRecorder::AddVehicleDoor(const ACarlaWheeledVehicle &Vehicle, const EVehicleDoor SDoors, bool bIsOpen)
{
CarlaRecorderDoorVehicle DoorVehicle;
DoorVehicle.DatabaseId = Episode->GetActorRegistry().FindCarlaActor(&Vehicle)->GetActorId();
DoorVehicle.Doors = static_cast<CarlaRecorderDoorVehicle::VehicleDoorType>(SDoors);
DoorVehicle.bIsOpen = bIsOpen;
AddDoorVehicle(DoorVehicle);
}
void ACarlaRecorder::AddActorKinematics(FCarlaActor *CarlaActor)
{
check(CarlaActor != nullptr);
@ -478,6 +487,7 @@ void ACarlaRecorder::Clear(void)
PhysicsControls.Clear();
TrafficLightTimes.Clear();
WalkersBones.Clear();
DoorVehicles.Clear();
Wheels.Clear();
Bikers.Clear();
}
@ -496,6 +506,7 @@ void ACarlaRecorder::Write(double DeltaSeconds)
EventsDel.Write(File);
EventsParent.Write(File);
Collisions.Write(File);
DoorVehicles.Write(File);
// positions and states
Positions.Write(File);
@ -652,6 +663,14 @@ void ACarlaRecorder::AddLightVehicle(const CarlaRecorderLightVehicle &LightVehic
}
}
void ACarlaRecorder::AddDoorVehicle(const CarlaRecorderDoorVehicle &DoorVehicle)
{
if (Enabled)
{
DoorVehicles.Add(DoorVehicle);
}
}
void ACarlaRecorder::AddEventLightSceneChanged(const UCarlaLight* Light)
{
if (Enabled)

View File

@ -33,7 +33,9 @@
#include "CarlaRecorderState.h"
#include "CarlaRecorderVisualTime.h"
#include "CarlaRecorderWalkerBones.h"
#include "CarlaRecorderDoorVehicle.h"
#include "CarlaReplayer.h"
#include "Carla/Vehicle/CarlaWheeledVehicle.h"
#include "CarlaRecorder.generated.h"
@ -67,6 +69,7 @@ enum class CarlaRecorderPacketId : uint8_t
FrameCounter,
WalkerBones,
VisualTime,
VehicleDoor,
AnimVehicleWheels,
AnimBiker
};
@ -137,6 +140,10 @@ public:
void AddActorBones(FCarlaActor *CarlaActor);
void AddVehicleDoor(const ACarlaWheeledVehicle& Vehicle, const EVehicleDoor SDoors, bool bIsOpen);
void AddDoorVehicle(const CarlaRecorderDoorVehicle &DoorVehicle);
// set episode
void SetEpisode(UCarlaEpisode *ThisEpisode)
{
@ -208,6 +215,7 @@ private:
CarlaRecorderTrafficLightTimes TrafficLightTimes;
CarlaRecorderWalkersBones WalkersBones;
CarlaRecorderVisualTime VisualTime;
CarlaRecorderDoorVehicles DoorVehicles;
// replayer
CarlaReplayer Replayer;

View File

@ -0,0 +1,75 @@
// Copyright (c) 2023 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>.
#include "CarlaRecorderDoorVehicle.h"
#include "CarlaRecorder.h"
#include "CarlaRecorderHelpers.h"
void CarlaRecorderDoorVehicle::Write(std::ostream &OutFile)
{
// database id
WriteValue<uint32_t>(OutFile, this->DatabaseId);
WriteValue<VehicleDoorType>(OutFile, this->Doors);
WriteValue<bool>(OutFile, this->bIsOpen);
}
void CarlaRecorderDoorVehicle::Read(std::istream &InFile)
{
// database id
ReadValue<uint32_t>(InFile, this->DatabaseId);
ReadValue<VehicleDoorType>(InFile, this->Doors);
ReadValue<bool>(InFile, this->bIsOpen);
}
// ---------------------------------------------
void CarlaRecorderDoorVehicles::Clear(void)
{
Vehicles.clear();
}
void CarlaRecorderDoorVehicles::Add(const CarlaRecorderDoorVehicle &Vehicle)
{
Vehicles.push_back(Vehicle);
}
void CarlaRecorderDoorVehicles::Write(std::ostream &OutFile)
{
// write the packet id
WriteValue<char>(OutFile, static_cast<char>(CarlaRecorderPacketId::VehicleDoor));
// write a dummy packet size
uint32_t Total = 2 + Vehicles.size() * sizeof(CarlaRecorderDoorVehicle);
WriteValue<uint32_t>(OutFile, Total);
// write total records
Total = Vehicles.size();
WriteValue<uint16_t>(OutFile, Total);
for (auto& Vehicle : Vehicles)
{
Vehicle.Write(OutFile);
}
}
void CarlaRecorderDoorVehicles::Read(std::istream &InFile)
{
uint16_t Total;
CarlaRecorderDoorVehicle DoorVehicle;
// read Total walkers
ReadValue<uint16_t>(InFile, Total);
for (uint16_t i = 0; i < Total; ++i)
{
DoorVehicle.Read(InFile);
Add(DoorVehicle);
}
}
const std::vector<CarlaRecorderDoorVehicle>& CarlaRecorderDoorVehicles::GetDoorVehicles()
{
return Vehicles;
}

View File

@ -0,0 +1,45 @@
// Copyright (c) 2023 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>.
#pragma once
#include <sstream>
#include <vector>
#include <type_traits>
#pragma pack(push, 1)
struct CarlaRecorderDoorVehicle
{
// Use same type as carla::vehicle::CarlaWheeledVehicle::EVehicleDoor
using VehicleDoorType = uint8_t;
uint32_t DatabaseId;
VehicleDoorType Doors;
bool bIsOpen;
void Read(std::istream &InFile);
void Write(std::ostream &OutFile);
};
#pragma pack(pop)
struct CarlaRecorderDoorVehicles
{
public:
void Add(const CarlaRecorderDoorVehicle &InObj);
void Clear(void);
void Write(std::ostream &OutFile);
void Read(std::istream &InFile);
const std::vector<CarlaRecorderDoorVehicle>& GetDoorVehicles();
private:
std::vector<CarlaRecorderDoorVehicle> Vehicles;
};

View File

@ -19,6 +19,8 @@
#include <carla/rpc/VehiclePhysicsControl.h>
#include <compiler/enable-ue4-macros.h>
#include <Carla/Vehicle/CarlaWheeledVehicle.h>
inline bool CarlaRecorderQuery::ReadHeader(void)
{
if (File.eof())
@ -271,6 +273,49 @@ std::string CarlaRecorderQuery::QueryInfo(std::string Filename, bool bShowAll)
SkipPacket();
break;
// vehicle door animations
case static_cast<char>(CarlaRecorderPacketId::VehicleDoor):
if (bShowAll)
{
ReadValue<uint16_t>(File, Total);
if (Total > 0 && !bFramePrinted)
{
PrintFrame(Info);
bFramePrinted = true;
}
Info << " Vehicle door animations: " << Total << std::endl;
for (i = 0; i < Total; ++i)
{
DoorVehicle.Read(File);
CarlaRecorderDoorVehicle::VehicleDoorType doorVehicle;
doorVehicle = DoorVehicle.Doors;
EVehicleDoor eDoorVehicle = static_cast<EVehicleDoor>(doorVehicle);
std::string opened_doors_list;
Info << " Id: " << DoorVehicle.DatabaseId << std::endl;
Info << " Doors opened: ";
if (eDoorVehicle == EVehicleDoor::FL)
Info << " Front Left " << std::endl;
if (eDoorVehicle == EVehicleDoor::FR)
Info << " Front Right " << std::endl;
if (eDoorVehicle == EVehicleDoor::RL)
Info << " Rear Left " << std::endl;
if (eDoorVehicle == EVehicleDoor::RR)
Info << " Rear Right " << std::endl;
if (eDoorVehicle == EVehicleDoor::Hood)
Info << " Hood " << std::endl;
if (eDoorVehicle == EVehicleDoor::Trunk)
Info << " Trunk " << std::endl;
if (eDoorVehicle == EVehicleDoor::All)
Info << " All " << std::endl;
}
}
else
SkipPacket();
break;
// vehicle light animations
case static_cast<char>(CarlaRecorderPacketId::VehicleLight):
if (bShowAll)

View File

@ -26,6 +26,7 @@
#include "CarlaRecorderPosition.h"
#include "CarlaRecorderState.h"
#include "CarlaRecorderWalkerBones.h"
#include "CarlaRecorderDoorVehicle.h"
class CarlaRecorderQuery
{
@ -69,6 +70,7 @@ private:
CarlaRecorderPhysicsControl PhysicsControl;
CarlaRecorderTrafficLightTime TrafficLightTime;
CarlaRecorderWalkerBones WalkerBones;
CarlaRecorderDoorVehicle DoorVehicle;
// read next header packet
bool ReadHeader(void);

View File

@ -378,6 +378,14 @@ void CarlaReplayer::ProcessToTime(double Time, bool IsFirstTime)
SkipPacket();
break;
// vehicle door animation
case static_cast<char>(CarlaRecorderPacketId::VehicleDoor):
if (bFrameFound)
ProcessDoorVehicle();
else
SkipPacket();
break;
// scene lights animation
case static_cast<char>(CarlaRecorderPacketId::SceneLight):
if (bFrameFound)
@ -649,6 +657,25 @@ void CarlaReplayer::ProcessLightVehicle(void)
}
}
void CarlaReplayer::ProcessDoorVehicle(void)
{
uint16_t Total;
CarlaRecorderDoorVehicle DoorVehicle;
// read Total walkers
ReadValue<uint16_t>(File, Total);
for (uint16_t i = 0; i < Total; ++i)
{
DoorVehicle.Read(File);
DoorVehicle.DatabaseId = MappedId[DoorVehicle.DatabaseId];
// check if ignore this actor
if (!(IgnoreHero && IsHeroMap[DoorVehicle.DatabaseId]))
{
Helper.ProcessReplayerDoorVehicle(DoorVehicle);
}
}
}
void CarlaReplayer::ProcessLightScene(void)
{
uint16_t Total;

View File

@ -158,6 +158,8 @@ private:
void ProcessLightVehicle(void);
void ProcessLightScene(void);
void ProcessDoorVehicle(void);
void ProcessWalkerBones(void);
// positions

View File

@ -416,6 +416,24 @@ void CarlaReplayerHelper::ProcessReplayerAnimVehicle(CarlaRecorderAnimVehicle Ve
}
}
// set the openings and closings of vehicle doors
void CarlaReplayerHelper::ProcessReplayerDoorVehicle(CarlaRecorderDoorVehicle DoorVehicle)
{
check(Episode != nullptr);
FCarlaActor * CarlaActor = Episode->FindCarlaActor(DoorVehicle.DatabaseId);
if (CarlaActor)
{
ACarlaWheeledVehicle * Vehicle = Cast<ACarlaWheeledVehicle>(CarlaActor->GetActor());
if (Vehicle) {
if(DoorVehicle.bIsOpen){
Vehicle->OpenDoor(static_cast<EVehicleDoor>(DoorVehicle.Doors));
}else{
Vehicle->CloseDoor(static_cast<EVehicleDoor>(DoorVehicle.Doors));
}
}
}
}
// set the lights for vehicles
void CarlaReplayerHelper::ProcessReplayerLightVehicle(CarlaRecorderLightVehicle LightVehicle)
{

View File

@ -15,6 +15,7 @@
#include "CarlaRecorderAnimVehicleWheels.h"
#include "CarlaRecorderLightVehicle.h"
#include "CarlaRecorderLightScene.h"
#include "CarlaRecorderDoorVehicle.h"
#include "CarlaRecorderWalkerBones.h"
#include <unordered_map>
@ -65,6 +66,9 @@ public:
// set the animation for walkers
void ProcessReplayerAnimWalker(CarlaRecorderAnimWalker Walker);
// set the openings and closing of vehicle doors
void ProcessReplayerDoorVehicle(CarlaRecorderDoorVehicle DoorVehicle);
// set the animation for bikers
void ProcessReplayerAnimBiker(CarlaRecorderAnimBiker Biker);

View File

@ -1,11 +1,12 @@
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// Copyright (c) 2024 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>.
#include "Carla.h"
#include "Carla/Sensor/CollisionSensor.h"
#include "Carla.h"
#include "CoreMinimal.h"
#include "Carla/Actor/ActorBlueprintFunctionLibrary.h"
#include "Carla/Actor/ActorRegistry.h"
@ -13,11 +14,13 @@
#include "Carla/Game/CarlaEngine.h"
#include "Carla/Game/CarlaGameInstance.h"
#include "Carla/Game/CarlaGameModeBase.h"
#include "Carla/Vehicle/CarlaWheeledVehicle.h"
#include "Carla/Walker/WalkerBase.h"
ACollisionSensor::ACollisionSensor(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
PrimaryActorTick.bCanEverTick = false;
PrimaryActorTick.bCanEverTick = true;
}
FActorDefinition ACollisionSensor::GetSensorDefinition()
@ -32,27 +35,37 @@ void ACollisionSensor::SetOwner(AActor *NewOwner)
Super::SetOwner(NewOwner);
/// @todo Deregister previous owner if there was one.
if (NewOwner != nullptr)
if (IsValid(NewOwner))
{
NewOwner->OnActorHit.AddDynamic(this, &ACollisionSensor::OnCollisionEvent);
ACarlaWheeledVehicle* Vehicle = Cast<ACarlaWheeledVehicle>(NewOwner);
if(IsValid(Vehicle))
{
Vehicle->GetMesh()->OnComponentHit.AddDynamic(this, &ACollisionSensor::OnComponentCollisionEvent);
}
else
{
AWalkerBase* Walker = Cast<AWalkerBase>(NewOwner);
if(IsValid(Walker))
{
Walker->GetMesh()->OnComponentHit.AddDynamic(this, &ACollisionSensor::OnComponentCollisionEvent);
}
else
{
OnActorHit.AddDynamic(this, &ACollisionSensor::OnActorCollisionEvent);
}
}
}
else
{
UE_LOG(LogCarla, Log, TEXT("ACollisionSensor::SetOwner New owner is not valid or you are destroying collision sensor") );
}
}
void ACollisionSensor::OnCollisionEvent(
AActor *Actor,
AActor *OtherActor,
FVector NormalImpulse,
const FHitResult &Hit)
{
if (Actor == nullptr || OtherActor == nullptr)
{
return;
}
uint64_t CurrentFrame = FCarlaEngine::GetFrameCounter();
void ACollisionSensor::PrePhysTick(float DeltaSeconds) {
Super::PrePhysTick(DeltaSeconds);
// remove all items from previous frames
uint64_t CurrentFrame = FCarlaEngine::GetFrameCounter();
CollisionRegistry.erase(
std::remove_if(
CollisionRegistry.begin(),
@ -62,6 +75,29 @@ void ACollisionSensor::OnCollisionEvent(
return std::get<0>(Item) < CurrentFrame;
}),
CollisionRegistry.end());
}
void ACollisionSensor::OnCollisionEvent(
AActor *Actor,
AActor *OtherActor,
FVector NormalImpulse,
const FHitResult &Hit)
{
if (!IsValid(OtherActor))
{
UE_LOG(LogCarla, Error, TEXT("ACollisionSensor::OnActorCollisionEvent Error with collided actor; Not valid.\n Collider actor %s"),
*(Actor->GetName()) );
return;
}
if (!IsValid(Actor))
{
UE_LOG(LogCarla, Error, TEXT("ACollisionSensor::OnActorCollisionEvent Error with collider actor; Not valid.\n Collided actor %s"),
*(OtherActor->GetName()) );
return;
}
uint64_t CurrentFrame = FCarlaEngine::GetFrameCounter();
// check if this collision has been procesed already in this frame
for (auto& Collision: CollisionRegistry)
@ -74,23 +110,27 @@ void ACollisionSensor::OnCollisionEvent(
}
}
const auto &Episode = GetEpisode();
const auto& CurrentEpisode = GetEpisode();
constexpr float TO_METERS = 1e-2;
NormalImpulse *= TO_METERS;
GetDataStream(*this).SerializeAndSend(
*this,
Episode.SerializeActor(Actor),
Episode.SerializeActor(OtherActor),
carla::geom::Vector3D{NormalImpulse.X, NormalImpulse.Y, NormalImpulse.Z});
CurrentEpisode.SerializeActor(Actor),
CurrentEpisode.SerializeActor(OtherActor),
carla::geom::Vector3D(
(float)NormalImpulse.X,
(float)NormalImpulse.Y,
(float)NormalImpulse.Z));
// record the collision event
if (Episode.GetRecorder()->IsEnabled()){
Episode.GetRecorder()->AddCollision(Actor, OtherActor);
if (CurrentEpisode.GetRecorder()->IsEnabled()){
CurrentEpisode.GetRecorder()->AddCollision(Actor, OtherActor);
}
CollisionRegistry.emplace_back(CurrentFrame, Actor, OtherActor);
// ROS2
#if defined(WITH_ROS2)
#if defined(WITH_ROS2)
auto ROS2 = carla::ros2::ROS2::GetInstance();
if (ROS2->IsEnabled())
{
@ -107,5 +147,25 @@ void ACollisionSensor::OnCollisionEvent(
ROS2->ProcessDataFromCollisionSensor(0, StreamId, GetActorTransform(), OtherActor->GetUniqueID(), carla::geom::Vector3D{NormalImpulse.X, NormalImpulse.Y, NormalImpulse.Z}, this);
}
}
#endif
#endif
}
void ACollisionSensor::OnActorCollisionEvent(
AActor *Actor,
AActor *OtherActor,
FVector NormalImpulse,
const FHitResult &Hit)
{
OnCollisionEvent(Actor, OtherActor, NormalImpulse, Hit);
}
void ACollisionSensor::OnComponentCollisionEvent(
UPrimitiveComponent* HitComp,
AActor* OtherActor,
UPrimitiveComponent* OtherComp,
FVector NormalImpulse,
const FHitResult& Hit)
{
AActor* Actor = HitComp->GetOwner();
OnCollisionEvent(Actor, OtherActor, NormalImpulse, Hit);
}

View File

@ -1,4 +1,4 @@
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// Copyright (c) 2024 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
@ -26,10 +26,9 @@ public:
ACollisionSensor(const FObjectInitializer& ObjectInitializer);
virtual void PrePhysTick(float DeltaSeconds) override;
void SetOwner(AActor *NewOwner) override;
private:
UFUNCTION()
void OnCollisionEvent(
AActor *Actor,
@ -37,6 +36,22 @@ private:
FVector NormalImpulse,
const FHitResult &Hit);
UFUNCTION(BlueprintCallable, Category="Collision")
void OnActorCollisionEvent(
AActor *Actor,
AActor *OtherActor,
FVector NormalImpulse,
const FHitResult &Hit);
UFUNCTION()
void OnComponentCollisionEvent(
UPrimitiveComponent* HitComp,
AActor* OtherActor,
UPrimitiveComponent* OtherComp,
FVector NormalImpulse,
const FHitResult& Hit);
private:
/// Registry that saves all collisions. Used to avoid sending the same collision more than once per frame,
/// as the collision sensor uses the PhysX substepping tick. Helps with sensor usage and stream overload.
std::vector<std::tuple<uint64_t, AActor*, AActor*>> CollisionRegistry;

View File

@ -104,8 +104,8 @@ carla::geom::Vector3D AInertialMeasurementUnit::ComputeAccelerometer(
{
// Used to convert from UE4's cm to meters
constexpr float TO_METERS = 1e-2;
// Earth's gravitational acceleration is approximately 9.81 m/s^2
constexpr float GRAVITY = 9.81f;
// Gravity set by gamemode
const float GRAVITY = UCarlaStatics::GetGameMode(GetWorld())->IMUISensorGravity;
// 2nd derivative of the polynomic (quadratic) interpolation
// using the point in current time and two previous steps:

View File

@ -9,6 +9,11 @@
#include "Carla/Server/CarlaServerResponse.h"
#include "Carla/Traffic/TrafficLightGroup.h"
#include "EngineUtils.h"
#include "Components/SkeletalMeshComponent.h"
#include "Components/SkinnedMeshComponent.h"
#include "Components/SceneComponent.h"
#include "Engine/SkeletalMesh.h"
#include "Engine/SkeletalMeshSocket.h"
#include "Carla/OpenDrive/OpenDrive.h"
#include "Carla/Util/DebugShapeDrawer.h"
@ -659,6 +664,31 @@ void FCarlaServer::FPimpl::BindActions()
Weather->ApplyWeather(weather);
return R<void>::Success();
};
// -- IMUI Gravity ---------------------------------------------------------
BIND_SYNC(get_imui_gravity) << [this]() -> R<float>
{
REQUIRE_CARLA_EPISODE();
ACarlaGameModeBase* GameMode = UCarlaStatics::GetGameMode(Episode->GetWorld());
if (GameMode == nullptr)
{
RESPOND_ERROR("get_imui_gravity error: unable to get carla gamemode");
}
return GameMode->IMUISensorGravity;
};
BIND_SYNC(set_imui_gravity) << [this](float newimuigravity) -> R<void>
{
REQUIRE_CARLA_EPISODE();
ACarlaGameModeBase* GameMode = UCarlaStatics::GetGameMode(Episode->GetWorld());
if (GameMode == nullptr)
{
RESPOND_ERROR("get_imui_gravity error: unable to get carla gamemode");
}
GameMode->IMUISensorGravity = newimuigravity;
return R<void>::Success();
};
// ~~ Actor operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -706,7 +736,8 @@ void FCarlaServer::FPimpl::BindActions()
cr::ActorDescription Description,
const cr::Transform &Transform,
cr::ActorId ParentId,
cr::AttachmentType InAttachmentType) -> R<cr::Actor>
cr::AttachmentType InAttachmentType,
const std::string& socket_name) -> R<cr::Actor>
{
REQUIRE_CARLA_EPISODE();
@ -760,7 +791,8 @@ void FCarlaServer::FPimpl::BindActions()
Episode->AttachActors(
CarlaActor->GetActor(),
ParentCarlaActor->GetActor(),
static_cast<EAttachmentType>(InAttachmentType));
static_cast<EAttachmentType>(InAttachmentType),
FString(socket_name.c_str()));
}
else
{
@ -1274,6 +1306,340 @@ BIND_SYNC(is_sensor_enabled_for_ros) << [this](carla::streaming::detail::stream_
return R<void>::Success();
};
BIND_SYNC(get_actor_component_world_transform) << [this](
cr::ActorId ActorId,
const std::string componentName) -> R<cr::Transform>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_component_world_transform",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<UActorComponent*> Components;
CarlaActor->GetActor()->GetComponents(Components);
USceneComponent* Component = nullptr;
for(auto Cmp : Components)
{
if(USceneComponent* SCMP = Cast<USceneComponent>(Cmp))
{
if(SCMP->GetName() == componentName.c_str())
{
Component = SCMP;
break;
}
}
}
if(!Component)
{
return RespondError(
"get_actor_component_world_transform",
ECarlaServerResponse::ComponentNotFound,
" Component Name: " + FString(componentName.c_str()));
}
FTransform ComponentWorldTransform = Component->GetComponentTransform();
return cr::Transform(ComponentWorldTransform);
}
};
BIND_SYNC(get_actor_component_relative_transform) << [this](
cr::ActorId ActorId,
const std::string componentName) -> R<cr::Transform>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_component_relative_transform",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<UActorComponent*> Components;
CarlaActor->GetActor()->GetComponents(Components);
USceneComponent* Component = nullptr;
for(auto Cmp : Components)
{
if(USceneComponent* SCMP = Cast<USceneComponent>(Cmp))
{
if(SCMP->GetName() == componentName.c_str())
{
Component = SCMP;
break;
}
}
}
if(!Component)
{
return RespondError(
"get_actor_component_world_transform",
ECarlaServerResponse::ComponentNotFound,
" Component Name: " + FString(componentName.c_str()));
}
FTransform ComponentRelativeTransform = Component->GetRelativeTransform();
return cr::Transform(ComponentRelativeTransform);
}
};
BIND_SYNC(get_actor_bone_world_transforms) << [this](
cr::ActorId ActorId) -> R<std::vector<cr::Transform>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_bone_world_transforms",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<FTransform> BoneWorldTransforms;
TArray<USkinnedMeshComponent*> SkinnedMeshComponents;
CarlaActor->GetActor()->GetComponents<USkinnedMeshComponent>(SkinnedMeshComponents);
if(!SkinnedMeshComponents[0])
{
return RespondError(
"get_actor_bone_world_transforms",
ECarlaServerResponse::ComponentNotFound,
" Component Name: SkinnedMeshComponent ");
}
else
{
for(USkinnedMeshComponent* SkinnedMeshComponent : SkinnedMeshComponents)
{
const int32 NumBones = SkinnedMeshComponent->GetNumBones();
for (int32 BoneIndex = 0; BoneIndex < NumBones; ++BoneIndex)
{
FTransform WorldTransform = SkinnedMeshComponent->GetComponentTransform();
FTransform BoneTransform = SkinnedMeshComponent->GetBoneTransform(BoneIndex, WorldTransform);
BoneWorldTransforms.Add(BoneTransform);
}
}
return MakeVectorFromTArray<cr::Transform>(BoneWorldTransforms);
}
}
};
BIND_SYNC(get_actor_bone_relative_transforms) << [this](
cr::ActorId ActorId) -> R<std::vector<cr::Transform>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_bone_relative_transforms",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<FTransform> BoneRelativeTransforms;
TArray<USkinnedMeshComponent*> SkinnedMeshComponents;
CarlaActor->GetActor()->GetComponents<USkinnedMeshComponent>(SkinnedMeshComponents);
if(!SkinnedMeshComponents[0])
{
return RespondError(
"get_actor_bone_relative_transforms",
ECarlaServerResponse::ComponentNotFound,
" Component Name: SkinnedMeshComponent ");
}
else
{
for(USkinnedMeshComponent* SkinnedMeshComponent : SkinnedMeshComponents)
{
const int32 NumBones = SkinnedMeshComponent->GetNumBones();
for (int32 BoneIndex = 0; BoneIndex < NumBones; ++BoneIndex)
{
FTransform BoneTransform = SkinnedMeshComponent->GetBoneTransform(BoneIndex, FTransform::Identity);
BoneRelativeTransforms.Add(BoneTransform);
}
}
return MakeVectorFromTArray<cr::Transform>(BoneRelativeTransforms);
}
}
};
BIND_SYNC(get_actor_component_names) << [this](
cr::ActorId ActorId) -> R<std::vector<std::string>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_component_names",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<UActorComponent*> Components;
CarlaActor->GetActor()->GetComponents(Components);
std::vector<std::string> ComponentNames;
for(auto Cmp : Components)
{
FString ComponentName = Cmp->GetName();
ComponentNames.push_back(TCHAR_TO_UTF8(*ComponentName));
}
return ComponentNames;
}
};
BIND_SYNC(get_actor_bone_names) << [this](
cr::ActorId ActorId) -> R<std::vector<std::string>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_bone_names",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
USkinnedMeshComponent* SkinnedMeshComponent = CarlaActor->GetActor()->FindComponentByClass<USkinnedMeshComponent>();
if(!SkinnedMeshComponent)
{
return RespondError(
"get_actor_bone_names",
ECarlaServerResponse::ComponentNotFound,
" Component Name: SkinnedMeshComponent ");
}
else
{
TArray<FName> BoneNames;
SkinnedMeshComponent->GetBoneNames(BoneNames);
TArray<std::string> StringBoneNames;
for (const FName& Name : BoneNames)
{
FString FBoneName = Name.ToString();
std::string StringBoneName = TCHAR_TO_UTF8(*FBoneName);
StringBoneNames.Add(StringBoneName);
}
return MakeVectorFromTArray<std::string>(StringBoneNames);
}
}
};
BIND_SYNC(get_actor_socket_world_transforms) << [this](
cr::ActorId ActorId) -> R<std::vector<cr::Transform>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_socket_world_transforms",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<FTransform> SocketWorldTransforms;
TArray<UActorComponent*> Components;
CarlaActor->GetActor()->GetComponents(Components);
for(UActorComponent* ActorComponent : Components)
{
if(USceneComponent* SceneComponent = Cast<USceneComponent>(ActorComponent))
{
const TArray<FName>& SocketNames = SceneComponent->GetAllSocketNames();
for (const FName& SocketName : SocketNames)
{
FTransform SocketTransform = SceneComponent->GetSocketTransform(SocketName);
SocketWorldTransforms.Add(SocketTransform);
}
}
}
return MakeVectorFromTArray<cr::Transform>(SocketWorldTransforms);
}
};
BIND_SYNC(get_actor_socket_relative_transforms) << [this](
cr::ActorId ActorId) -> R<std::vector<cr::Transform>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_socket_relative_transforms",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<FTransform> SocketRelativeTransforms;
TArray<UActorComponent*> Components;
CarlaActor->GetActor()->GetComponents(Components);
for(UActorComponent* ActorComponent : Components)
{
if(USceneComponent* SceneComponent = Cast<USceneComponent>(ActorComponent))
{
const TArray<FName>& SocketNames = SceneComponent->GetAllSocketNames();
for (const FName& SocketName : SocketNames)
{
FTransform SocketTransform = SceneComponent->GetSocketTransform(SocketName, ERelativeTransformSpace::RTS_Actor);
SocketRelativeTransforms.Add(SocketTransform);
}
}
}
return MakeVectorFromTArray<cr::Transform>(SocketRelativeTransforms);
}
};
BIND_SYNC(get_actor_socket_names) << [this](
cr::ActorId ActorId) -> R<std::vector<std::string>>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"get_actor_socket_names",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
else
{
TArray<FName> SocketNames;
std::vector<std::string> StringSocketNames;
TArray<UActorComponent*> Components;
CarlaActor->GetActor()->GetComponents(Components);
for(UActorComponent* ActorComponent : Components)
{
if(USceneComponent* SceneComponent = Cast<USceneComponent>(ActorComponent))
{
SocketNames = SceneComponent->GetAllSocketNames();
for (const FName& Name : SocketNames)
{
FString FSocketName = Name.ToString();
std::string StringSocketName = TCHAR_TO_UTF8(*FSocketName);
StringSocketNames.push_back(StringSocketName);
}
}
}
return StringSocketNames;
}
};
BIND_SYNC(get_physics_control) << [this](
cr::ActorId ActorId) -> R<cr::VehiclePhysicsControl>
{
@ -1953,6 +2319,30 @@ BIND_SYNC(is_sensor_enabled_for_ros) << [this](carla::streaming::detail::stream_
return R<void>::Success();
};
BIND_SYNC(restore_physx_physics) << [this](
cr::ActorId ActorId) -> R<void>
{
REQUIRE_CARLA_EPISODE();
FCarlaActor* CarlaActor = Episode->FindCarlaActor(ActorId);
if (!CarlaActor)
{
return RespondError(
"restore_physx_physics",
ECarlaServerResponse::ActorNotFound,
" Actor Id: " + FString::FromInt(ActorId));
}
ECarlaServerResponse Response =
CarlaActor->RestorePhysXPhysics();
if (Response != ECarlaServerResponse::Success)
{
return RespondError(
"restore_physx_physics",
Response,
" Actor Id: " + FString::FromInt(ActorId));
}
return R<void>::Success();
};
// ~~ Traffic lights ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BIND_SYNC(set_traffic_light_state) << [this](
@ -2457,7 +2847,8 @@ BIND_SYNC(is_sensor_enabled_for_ros) << [this](carla::streaming::detail::stream_
c.description,
c.transform,
*c.parent,
cr::AttachmentType::Rigid) :
cr::AttachmentType::Rigid,
c.socket_name) :
spawn_actor(c.description, c.transform);
if (!result.HasError())
{

View File

@ -14,6 +14,8 @@ FString CarlaGetStringError(ECarlaServerResponse Response)
return "Sucess";
case ECarlaServerResponse::ActorNotFound:
return "Actor could not be found in the registry";
case ECarlaServerResponse::ComponentNotFound:
return "Component could not be found in this actor";
case ECarlaServerResponse::ActorTypeMismatch:
return "Actor does not match the expected type";
case ECarlaServerResponse::MissingActor:

View File

@ -10,6 +10,7 @@ enum class ECarlaServerResponse
{
Success,
ActorNotFound,
ComponentNotFound,
ActorTypeMismatch,
FunctionNotSupported,
NullActor,

View File

@ -4,7 +4,7 @@
#include "Carla/Game/CarlaGameInstance.h"
#include "Carla/Settings/CarlaSettings.h"
#include "Carla/Game/CarlaGameInstance.h"
#include "Async.h"
#include "Components/StaticMeshComponent.h"
#include "Engine/DirectionalLight.h"

View File

@ -36,11 +36,15 @@ void UYieldSignComponent::InitializeSign(const carla::road::Map &Map)
if(lane == 0)
continue;
auto signal_waypoint = Map.GetWaypoint(
RoadId, lane, SignalReference->GetS()).get();
if(Map.GetLane(signal_waypoint).GetType() != cr::Lane::LaneType::Driving)
auto signal_waypoint_optional = Map.GetWaypoint(RoadId, lane, SignalReference->GetS());
if (!signal_waypoint_optional) {
carla::log_warning("YieldSignComponent::InitializeSignsignal() waypoint seems to be invalid, ignoring. RoadId:", RoadId, " LaneId:", lane, " s:", SignalReference->GetS());
continue;
}
auto signal_waypoint = signal_waypoint_optional.value();
if(Map.GetLane(signal_waypoint).GetType() != cr::Lane::LaneType::Driving) {
continue;
}
auto box_waypoint = signal_waypoint;
// Prevent adding the bounding box inside the intersection

View File

@ -96,7 +96,8 @@ static void UActorAttacher_AttachActorsWithSpringArmGhost(
void UActorAttacher::AttachActors(
AActor *Child,
AActor *Parent,
const EAttachmentType AttachmentType)
const EAttachmentType AttachmentType,
const FString& SocketName)
{
check(Child != nullptr);
check(Parent != nullptr);
@ -104,7 +105,7 @@ void UActorAttacher::AttachActors(
switch (AttachmentType)
{
case EAttachmentType::Rigid:
Child->AttachToActor(Parent, FAttachmentTransformRules::KeepRelativeTransform);
Child->AttachToActor(Parent, FAttachmentTransformRules::KeepRelativeTransform, FName(*SocketName));
break;
case EAttachmentType::SpringArm:
UActorAttacher_AttachActorsWithSpringArm(Child, Parent);

Some files were not shown because too many files have changed in this diff Show More