CARLA
Loading...
Searching...
No Matches
World.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma
2// de Barcelona (UAB).
3//
4// This work is licensed under the terms of the MIT license.
5// For a copy, see <https://opensource.org/licenses/MIT>.
6
8
9#include "carla/Logging.h"
10#include "carla/client/Actor.h"
13#include "carla/client/Map.h"
15#include "carla/StringUtil.h"
18#include "carla/road/Junction.h"
20
21#include <exception>
22
23namespace carla {
24namespace client {
25
27 return _episode.Lock()->GetCurrentMap();
28 }
29
30 void World::LoadLevelLayer(rpc::MapLayer map_layers) const {
31 _episode.Lock()->LoadLevelLayer(map_layers);
32 }
33
34 void World::UnloadLevelLayer(rpc::MapLayer map_layers) const {
35 _episode.Lock()->UnloadLevelLayer(map_layers);
36 }
37
39 return _episode.Lock()->GetBlueprintLibrary();
40 }
41
43 return _episode.Lock()->GetVehiclesLightStates();
44 }
45
46 std::optional<geom::Location> World::GetRandomLocationFromNavigation() const {
47 return _episode.Lock()->GetRandomLocationFromNavigation();
48 }
49
51 return _episode.Lock()->GetSpectator();
52 }
53
55 return _episode.Lock()->GetEpisodeSettings();
56 }
57
58 uint64_t World::ApplySettings(const rpc::EpisodeSettings &settings, time_duration timeout) {
59 rpc::EpisodeSettings new_settings = settings;
60 uint64_t id = _episode.Lock()->SetEpisodeSettings(settings);
61
62 time_duration local_timeout = timeout.milliseconds() == 0 ?
63 _episode.Lock()->GetNetworkingTimeout() : timeout;
64
65 if (settings.fixed_delta_seconds.has_value()) {
66 using namespace std::literals::chrono_literals;
67
68 const auto number_of_attemps = 30u;
69 uint64_t tics_correct = 0;
70 for (auto i = 0u; i < number_of_attemps; i++) {
71 const auto curr_snapshot = GetSnapshot();
72
73 const double error = abs(new_settings.fixed_delta_seconds.value() - curr_snapshot.GetTimestamp().delta_seconds);
74 if (error < std::numeric_limits<float>::epsilon())
75 tics_correct++;
76
77 if (tics_correct >= 2)
78 return id;
79
80 if (settings.synchronous_mode) {
81 // only drive the simulation forward in synchronous mode; in
82 // asynchronous mode wait for the server to advance on its own
83 Tick(local_timeout);
84 } else {
85 WaitForTick(local_timeout);
86 }
87 }
88
89 log_warning("World::ApplySettings: After", number_of_attemps, " attemps, the settings were not correctly set. Please check that everything is consistent.");
90 }
91 return id;
92 }
93
95 return _episode.Lock()->GetWeatherParameters();
96 }
97
99 _episode.Lock()->SetWeatherParameters(weather);
100 }
101
103 return _episode.Lock()->GetIMUSensorGravity();
104 }
105
106 void World::SetIMUSensorGravity(float gravity) {
107 _episode.Lock()->SetIMUSensorGravity(gravity);
108 }
109
111 return _episode.Lock()->IsWeatherEnabled();
112 }
113
115 return _episode.Lock()->GetWorldSnapshot();
116 }
117
119 auto simulator = _episode.Lock();
120 auto description = simulator->GetActorById(id);
121 return description.has_value() ?
122 simulator->MakeActor(std::move(*description)) :
123 nullptr;
124 }
125
128 _episode,
129 _episode.Lock()->GetAllTheActorsInTheEpisode()}};
130 }
131
132 SharedPtr<ActorList> World::GetActors(const std::vector<ActorId> &actor_ids) const {
134 _episode,
135 _episode.Lock()->GetActorsById(actor_ids)}};
136 }
137
139 const ActorBlueprint &blueprint,
140 const geom::Transform &transform,
141 Actor *parent_actor,
142 rpc::AttachmentType attachment_type) {
143 return _episode.Lock()->SpawnActor(blueprint, transform, parent_actor, attachment_type);
144 }
145
147 const ActorBlueprint &blueprint,
148 const geom::Transform &transform,
149 Actor *parent_actor,
150 rpc::AttachmentType attachment_type) noexcept {
151 try {
152 return SpawnActor(blueprint, transform, parent_actor, attachment_type);
153 } catch (const std::exception &) {
154 return nullptr;
155 }
156 }
157
159 time_duration local_timeout = timeout.milliseconds() == 0 ?
160 _episode.Lock()->GetNetworkingTimeout() : timeout;
161
162 return _episode.Lock()->WaitForTick(local_timeout);
163 }
164
165 size_t World::OnTick(std::function<void(WorldSnapshot)> callback) {
166 return _episode.Lock()->RegisterOnTickEvent(std::move(callback));
167 }
168
169 void World::RemoveOnTick(size_t callback_id) {
170 _episode.Lock()->RemoveOnTickEvent(callback_id);
171 }
172
173 uint64_t World::Tick(time_duration timeout) {
174 time_duration local_timeout = timeout.milliseconds() == 0 ?
175 _episode.Lock()->GetNetworkingTimeout() : timeout;
176 return _episode.Lock()->Tick(local_timeout);
177 }
178
179 void World::SetPedestriansCrossFactor(float percentage) {
180 _episode.Lock()->SetPedestriansCrossFactor(percentage);
181 }
182
183 void World::SetPedestriansSeed(unsigned int seed) {
184 _episode.Lock()->SetPedestriansSeed(seed);
185 }
186
190 std::string landmark_id = landmark.GetId();
191 for (size_t i = 0; i < actors->size(); i++) {
192 SharedPtr<Actor> actor = actors->at(i);
193 if (StringUtil::Match(actor->GetTypeId(), "*traffic.*")) {
194 TrafficSign* sign = static_cast<TrafficSign*>(actor.get());
195 if(sign && (sign->GetSignId() == landmark_id)) {
196 return actor;
197 }
198 }
199 }
200 return nullptr;
201 }
202
206 std::string landmark_id = landmark.GetId();
207 for (size_t i = 0; i < actors->size(); i++) {
208 SharedPtr<Actor> actor = actors->at(i);
209 if (StringUtil::Match(actor->GetTypeId(), "*traffic_light*")) {
210 TrafficLight* tl = static_cast<TrafficLight*>(actor.get());
211 if(tl && (tl->GetSignId() == landmark_id)) {
212 return actor;
213 }
214 }
215 }
216 return nullptr;
217 }
218
222 for (size_t i = 0; i < actors->size(); i++) {
223 SharedPtr<Actor> actor = actors->at(i);
224 if (StringUtil::Match(actor->GetTypeId(), "*traffic_light*")) {
225 TrafficLight* tl = static_cast<TrafficLight*>(actor.get());
226 if(tl && (tl->GetSignId() == sign_id)) {
227 return actor;
228 }
229 }
230 }
231 return nullptr;
232 }
233
235 _episode.Lock()->ResetAllTrafficLights();
236 }
237
239 const std::vector<float> &vertices,
240 const std::vector<uint32_t> &triangles,
241 const std::string &material) {
242 _episode.Lock()->SpawnCustomMesh(vertices, triangles, material);
243 }
244
246 return _episode.Lock()->GetLightManager();
247 }
248
250 _episode.Lock()->FreezeAllTrafficLights(frozen);
251 }
252
253 std::vector<geom::BoundingBox> World::GetLevelBBs(uint8_t queried_tag) const {
254 return _episode.Lock()->GetLevelBBs(queried_tag);
255 }
256
257 std::vector<rpc::EnvironmentObject> World::GetEnvironmentObjects(uint8_t queried_tag) const {
258 return _episode.Lock()->GetEnvironmentObjects(queried_tag);
259 }
260
262 std::vector<uint64_t> env_objects_ids,
263 bool enable) const {
264 _episode.Lock()->EnableEnvironmentObjects(env_objects_ids, enable);
265 }
266
267 std::optional<rpc::LabelledPoint> World::ProjectPoint(
268 geom::Location location, geom::Vector3D direction, float search_distance) const {
269 auto result = _episode.Lock()->ProjectPoint(location, direction, search_distance);
270 if (result.first) {
271 return result.second;
272 }
273 return {};
274 }
275
276 std::optional<rpc::LabelledPoint> World::GroundProjection(
277 geom::Location location, float search_distance) const {
278 const geom::Vector3D DownVector(0,0,-1);
279 return ProjectPoint(location, DownVector, search_distance);
280 }
281
282 std::vector<rpc::LabelledPoint> World::CastRay(
283 geom::Location start_location, geom::Location end_location) const {
284 return _episode.Lock()->CastRay(start_location, end_location);
285 }
286
287 std::vector<SharedPtr<Actor>> World::GetTrafficLightsFromWaypoint(
288 const Waypoint& waypoint, double distance) const {
289 std::vector<SharedPtr<Actor>> Result;
290 std::vector<SharedPtr<Landmark>> landmarks =
292 std::set<std::string> added_signals;
293 for (auto& landmark : landmarks) {
294 if (road::SignalType::IsTrafficLight(landmark->GetType())) {
295 SharedPtr<Actor> traffic_light = GetTrafficLight(*(landmark.get()));
296 if (traffic_light) {
297 if(added_signals.count(landmark->GetId()) == 0) {
298 Result.emplace_back(traffic_light);
299 added_signals.insert(landmark->GetId());
300 }
301 }
302 }
303 }
304 return Result;
305 }
306
307 std::vector<SharedPtr<Actor>> World::GetTrafficLightsInJunction(
308 const road::JuncId junc_id) const {
309 std::vector<SharedPtr<Actor>> Result;
310 SharedPtr<Map> map = GetMap();
311 const road::Junction* junction = map->GetMap().GetJunction(junc_id);
312 for (const road::ContId& cont_id : junction->GetControllers()) {
313 const std::unique_ptr<road::Controller>& controller =
314 map->GetMap().GetControllers().at(cont_id);
315 for (road::SignId sign_id : controller->GetSignals()) {
316 SharedPtr<Actor> traffic_light = GetTrafficLightFromOpenDRIVE(sign_id);
317 if (traffic_light) {
318 Result.emplace_back(traffic_light);
319 }
320 }
321 }
322 return Result;
323 }
324
326 const std::string &object_name,
327 const rpc::MaterialParameter& parameter,
328 const rpc::TextureColor& Texture) {
329 _episode.Lock()->ApplyColorTextureToObjects({object_name}, parameter, Texture);
330 }
331
333 const std::vector<std::string> &objects_name,
334 const rpc::MaterialParameter& parameter,
335 const rpc::TextureColor& Texture) {
336 _episode.Lock()->ApplyColorTextureToObjects(objects_name, parameter, Texture);
337 }
338
340 const std::string &object_name,
341 const rpc::MaterialParameter& parameter,
342 const rpc::TextureFloatColor& Texture) {
343 _episode.Lock()->ApplyColorTextureToObjects({object_name}, parameter, Texture);
344 }
345
347 const std::vector<std::string> &objects_name,
348 const rpc::MaterialParameter& parameter,
349 const rpc::TextureFloatColor& Texture) {
350 _episode.Lock()->ApplyColorTextureToObjects(objects_name, parameter, Texture);
351 }
352
354 const rpc::TextureFloatColor& panorama,
355 float intensity,
356 int32_t face_size) {
357 _episode.Lock()->SetSkyLightMap(panorama, intensity, face_size);
358 }
359
361 _episode.Lock()->ClearSkyLightMap();
362 }
363
365 return _episode.Lock()->HasSkyLightMap();
366 }
367
368 std::vector<std::string> World::GetNamesOfAllObjects() const {
369 return _episode.Lock()->GetNamesOfAllObjects();
370 }
371
372 void World::SetPublishTF(bool publish_tf) {
373 _episode.Lock()->SetPublishTF(publish_tf);
374 }
375
376 bool World::GetPublishTF() const {
377 return _episode.Lock()->GetPublishTF();
378 }
379
380 std::vector<geom::Transform> World::GetEgoSpawnPoints() const {
381 return _episode.Lock()->GetEgoSpawnPoints();
382 }
383
385 const std::string &object_name,
386 const rpc::TextureColor& diffuse_texture,
387 const rpc::TextureFloatColor& emissive_texture,
388 const rpc::TextureFloatColor& normal_texture,
389 const rpc::TextureFloatColor& ao_roughness_metallic_emissive_texture)
390 {
391 if (diffuse_texture.GetWidth() && diffuse_texture.GetHeight()) {
393 object_name, rpc::MaterialParameter::Tex_Diffuse, diffuse_texture);
394 }
395 if (normal_texture.GetWidth() && normal_texture.GetHeight()) {
397 object_name, rpc::MaterialParameter::Tex_Normal, normal_texture);
398 }
399 if (ao_roughness_metallic_emissive_texture.GetWidth() &&
400 ao_roughness_metallic_emissive_texture.GetHeight()) {
402 object_name,
404 ao_roughness_metallic_emissive_texture);
405 }
406 if (emissive_texture.GetWidth() && emissive_texture.GetHeight()) {
408 object_name, rpc::MaterialParameter::Tex_Emissive, emissive_texture);
409 }
410 }
411
413 const std::vector<std::string> &objects_names,
414 const rpc::TextureColor& diffuse_texture,
415 const rpc::TextureFloatColor& emissive_texture,
416 const rpc::TextureFloatColor& normal_texture,
417 const rpc::TextureFloatColor& ao_roughness_metallic_emissive_texture)
418 {
419 if (diffuse_texture.GetWidth() && diffuse_texture.GetHeight()) {
421 objects_names, rpc::MaterialParameter::Tex_Diffuse, diffuse_texture);
422 }
423 if (normal_texture.GetWidth() && normal_texture.GetHeight()) {
425 objects_names, rpc::MaterialParameter::Tex_Normal, normal_texture);
426 }
427 if (ao_roughness_metallic_emissive_texture.GetWidth() &&
428 ao_roughness_metallic_emissive_texture.GetHeight()) {
430 objects_names,
432 ao_roughness_metallic_emissive_texture);
433 }
434 if (emissive_texture.GetWidth() && emissive_texture.GetHeight()) {
436 objects_names, rpc::MaterialParameter::Tex_Emissive, emissive_texture);
437 }
438 }
439
440} // namespace client
441} // namespace carla
float distance
float intensity
std::map< std::string, unsigned int > junction
static bool Match(const char *str, const char *wildcard_pattern)
Match str with the Unix shell-style wildcard_pattern.
Contains all the necessary information for spawning an Actor.
Represents an actor in the simulation.
Class containing a reference to RoadInfoSignal.
Definition Landmark.h:22
std::string GetId() const
Definition Landmark.h:49
carla::road::SignId GetSignId() const
std::vector< SharedPtr< Landmark > > GetAllLandmarksInDistance(double distance, bool stop_at_junction=false) const
Returns a list of landmarks from the current position to a certain distance.
void ClearSkyLightMap()
Definition World.cpp:360
float GetIMUSensorGravity() const
Get gravity value used for the IMU sensor accelerometer calculation.
Definition World.cpp:102
SharedPtr< ActorList > GetActors() const
Return a list with all the actors currently present in the world.
Definition World.cpp:126
void ApplyColorTextureToObject(const std::string &actor_name, const rpc::MaterialParameter &parameter, const rpc::TextureColor &Texture)
Definition World.cpp:325
std::vector< geom::BoundingBox > GetLevelBBs(uint8_t queried_tag) const
Returns all the BBs of all the elements of the level.
Definition World.cpp:253
void LoadLevelLayer(rpc::MapLayer map_layers) const
Definition World.cpp:30
SharedPtr< BlueprintLibrary > GetBlueprintLibrary() const
Return the list of blueprints available in this world.
Definition World.cpp:38
void EnableEnvironmentObjects(std::vector< uint64_t > env_objects_ids, bool enable) const
Definition World.cpp:261
void FreezeAllTrafficLights(bool frozen)
Definition World.cpp:249
std::vector< geom::Transform > GetEgoSpawnPoints() const
Get all ego spawn points available in the level.
Definition World.cpp:380
WorldSnapshot GetSnapshot() const
Return a snapshot of the world at this moment.
Definition World.cpp:114
void ResetAllTrafficLights()
Definition World.cpp:234
bool HasSkyLightMap() const
Definition World.cpp:364
void SetPublishTF(bool publish_tf)
Set whether to publish ROS2 TF information.
Definition World.cpp:372
rpc::WeatherParameters GetWeather() const
Retrieve the weather parameters currently active in the world.
Definition World.cpp:94
SharedPtr< Actor > GetSpectator() const
Return the spectator actor.
Definition World.cpp:50
rpc::VehicleLightStateList GetVehiclesLightStates() const
Returns a list of pairs where the firts element is the vehicle ID and the second one is the light sta...
Definition World.cpp:42
SharedPtr< Actor > GetActor(ActorId id) const
Find actor by id, return nullptr if not found.
Definition World.cpp:118
SharedPtr< Actor > GetTrafficLight(const Landmark &landmark) const
Definition World.cpp:203
SharedPtr< Actor > TrySpawnActor(const ActorBlueprint &blueprint, const geom::Transform &transform, Actor *parent=nullptr, rpc::AttachmentType attachment_type=rpc::AttachmentType::Rigid) noexcept
Same as SpawnActor but return nullptr on failure instead of throwing an exception.
Definition World.cpp:146
void SetPedestriansCrossFactor(float percentage)
set the probability that an agent could cross the roads in its path following percentage of 0....
Definition World.cpp:179
uint64_t Tick(time_duration timeout)
Signal the simulator to continue to next tick (only has effect on synchronous mode).
Definition World.cpp:173
detail::EpisodeProxy _episode
Definition World.h:279
std::optional< rpc::LabelledPoint > GroundProjection(geom::Location location, float search_distance=10000.0) const
Definition World.cpp:276
std::optional< rpc::LabelledPoint > ProjectPoint(geom::Location location, geom::Vector3D direction, float search_distance=10000.f) const
Definition World.cpp:267
bool IsWeatherEnabled() const
Query if the Weather is enabled or not.
Definition World.cpp:110
WorldSnapshot WaitForTick(time_duration timeout) const
Block calling thread until a world tick is received.
Definition World.cpp:158
std::vector< SharedPtr< Actor > > GetTrafficLightsInJunction(const road::JuncId junc_id) const
Definition World.cpp:307
void ApplyTexturesToObject(const std::string &actor_name, const rpc::TextureColor &diffuse_texture, const rpc::TextureFloatColor &emissive_texture, const rpc::TextureFloatColor &normal_texture, const rpc::TextureFloatColor &ao_roughness_metallic_emissive_texture)
Definition World.cpp:384
std::vector< std::string > GetNamesOfAllObjects() const
Definition World.cpp:368
uint64_t ApplySettings(const rpc::EpisodeSettings &settings, time_duration timeout)
Definition World.cpp:58
void SetSkyLightMap(const rpc::TextureFloatColor &panorama, float intensity=1.0f, int32_t face_size=512)
Light the scene with an environment map: an equirectangular linear RGB(A) float panorama in the CARLA...
Definition World.cpp:353
std::vector< rpc::EnvironmentObject > GetEnvironmentObjects(uint8_t queried_tag) const
Definition World.cpp:257
SharedPtr< Map > GetMap() const
Return the map that describes this world.
Definition World.cpp:26
std::vector< rpc::LabelledPoint > CastRay(geom::Location start_location, geom::Location end_location) const
Definition World.cpp:282
std::vector< SharedPtr< Actor > > GetTrafficLightsFromWaypoint(const Waypoint &waypoint, double distance) const
Definition World.cpp:287
void SetIMUSensorGravity(float gravity)
Set gravity value used for the IMU sensor accelerometer calculation.
Definition World.cpp:106
void SpawnCustomMesh(const std::vector< float > &vertices, const std::vector< uint32_t > &triangles, const std::string &material)
Spawns a static procedural mesh with collision.
Definition World.cpp:238
bool GetPublishTF() const
Get whether ROS2 TF information is being published.
Definition World.cpp:376
void ApplyColorTextureToObjects(const std::vector< std::string > &objects_names, const rpc::MaterialParameter &parameter, const rpc::TextureColor &Texture)
Definition World.cpp:332
void ApplyFloatColorTextureToObjects(const std::vector< std::string > &objects_names, const rpc::MaterialParameter &parameter, const rpc::TextureFloatColor &Texture)
Definition World.cpp:346
SharedPtr< Actor > SpawnActor(const ActorBlueprint &blueprint, const geom::Transform &transform, Actor *parent=nullptr, rpc::AttachmentType attachment_type=rpc::AttachmentType::Rigid)
Spawn an actor into the world based on the blueprint provided at transform.
Definition World.cpp:138
void SetPedestriansSeed(unsigned int seed)
set the seed to use with random numbers in the pedestrians module
Definition World.cpp:183
void ApplyTexturesToObjects(const std::vector< std::string > &objects_names, const rpc::TextureColor &diffuse_texture, const rpc::TextureFloatColor &emissive_texture, const rpc::TextureFloatColor &normal_texture, const rpc::TextureFloatColor &ao_roughness_metallic_emissive_texture)
Definition World.cpp:412
SharedPtr< LightManager > GetLightManager() const
Definition World.cpp:245
std::optional< geom::Location > GetRandomLocationFromNavigation() const
Get a random location from the pedestrians navigation mesh.
Definition World.cpp:46
SharedPtr< Actor > GetTrafficSign(const Landmark &landmark) const
Definition World.cpp:187
void ApplyFloatColorTextureToObject(const std::string &actor_name, const rpc::MaterialParameter &parameter, const rpc::TextureFloatColor &Texture)
Definition World.cpp:339
void RemoveOnTick(size_t callback_id)
Remove a callback registered with OnTick.
Definition World.cpp:169
SharedPtr< Actor > GetTrafficLightFromOpenDRIVE(const road::SignId &sign_id) const
Definition World.cpp:219
size_t OnTick(std::function< void(WorldSnapshot)> callback)
Register a callback to be called every time a world tick is received.
Definition World.cpp:165
void SetWeather(const rpc::WeatherParameters &weather)
Change the weather in the simulation.
Definition World.cpp:98
rpc::EpisodeSettings GetSettings() const
Definition World.cpp:54
void UnloadLevelLayer(rpc::MapLayer map_layers) const
Definition World.cpp:34
SharedPtrType Lock() const
Same as TryLock but never return nullptr.
A rigid transform in CARLA's / Unreal's left-handed frame: x forward, y right, z up,...
const std::set< ContId > & GetControllers() const
static bool IsTrafficLight(const std::string &type)
uint32_t GetWidth() const
Definition Texture.h:29
uint32_t GetHeight() const
Definition Texture.h:33
Positive time duration up to milliseconds resolution.
Definition Time.h:20
static time_duration milliseconds(size_t timeout)
Definition Time.h:27
int32_t JuncId
Definition RoadTypes.h:17
std::string ContId
Definition RoadTypes.h:31
std::string SignId
Definition RoadTypes.h:25
std::vector< std::pair< ActorId, VehicleLightState::flag_type > > VehicleLightStateList
This file contains definitions of common data structures used in traffic manager.
std::shared_ptr< T > SharedPtr
Definition Memory.h:15
static void log_warning(Args &&... args)
Definition Logging.h:96