CARLA
World.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017 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 
7 #include "carla/client/World.h"
8 
9 #include "carla/Logging.h"
10 #include "carla/client/Actor.h"
12 #include "carla/client/ActorList.h"
14 #include "carla/StringUtil.h"
15 #include "carla/road/SignalType.h"
16 #include "carla/road/Junction.h"
18 
19 #include <exception>
20 
21 namespace carla {
22 namespace client {
23 
25  return _episode.Lock()->GetCurrentMap();
26  }
27 
28  void World::LoadLevelLayer(rpc::MapLayer map_layers) const {
29  _episode.Lock()->LoadLevelLayer(map_layers);
30  }
31 
32  void World::UnloadLevelLayer(rpc::MapLayer map_layers) const {
33  _episode.Lock()->UnloadLevelLayer(map_layers);
34  }
35 
37  return _episode.Lock()->GetBlueprintLibrary();
38  }
39 
41  return _episode.Lock()->GetVehiclesLightStates();
42  }
43 
44  boost::optional<geom::Location> World::GetRandomLocationFromNavigation() const {
45  return _episode.Lock()->GetRandomLocationFromNavigation();
46  }
47 
49  return _episode.Lock()->GetSpectator();
50  }
51 
53  return _episode.Lock()->GetEpisodeSettings();
54  }
55 
56  uint64_t World::ApplySettings(const rpc::EpisodeSettings &settings, time_duration timeout) {
57  rpc::EpisodeSettings new_settings = settings;
58  uint64_t id = _episode.Lock()->SetEpisodeSettings(settings);
59 
60  time_duration local_timeout = timeout.milliseconds() == 0 ?
61  _episode.Lock()->GetNetworkingTimeout() : timeout;
62 
63  if (settings.fixed_delta_seconds.has_value()) {
64  using namespace std::literals::chrono_literals;
65 
66  const auto number_of_attemps = 30u;
67  uint64_t tics_correct = 0;
68  for (auto i = 0u; i < number_of_attemps; i++) {
69  const auto curr_snapshot = GetSnapshot();
70 
71  const double error = abs(new_settings.fixed_delta_seconds.get() - curr_snapshot.GetTimestamp().delta_seconds);
72  if (error < std::numeric_limits<float>::epsilon())
73  tics_correct++;
74 
75  if (tics_correct >= 2)
76  return id;
77 
78  Tick(local_timeout);
79  }
80 
81  log_warning("World::ApplySettings: After", number_of_attemps, " attemps, the settings were not correctly set. Please check that everything is consistent.");
82  }
83  return id;
84  }
85 
87  return _episode.Lock()->GetWeatherParameters();
88  }
89 
91  _episode.Lock()->SetWeatherParameters(weather);
92  }
93 
95  return _episode.Lock()->GetWorldSnapshot();
96  }
97 
99  auto simulator = _episode.Lock();
100  auto description = simulator->GetActorById(id);
101  return description.has_value() ?
102  simulator->MakeActor(std::move(*description)) :
103  nullptr;
104  }
105 
107  return SharedPtr<ActorList>{new ActorList{
108  _episode,
109  _episode.Lock()->GetAllTheActorsInTheEpisode()}};
110  }
111 
112  SharedPtr<ActorList> World::GetActors(const std::vector<ActorId> &actor_ids) const {
113  return SharedPtr<ActorList>{new ActorList{
114  _episode,
115  _episode.Lock()->GetActorsById(actor_ids)}};
116  }
117 
119  const ActorBlueprint &blueprint,
120  const geom::Transform &transform,
121  Actor *parent_actor,
122  rpc::AttachmentType attachment_type) {
123  return _episode.Lock()->SpawnActor(blueprint, transform, parent_actor, attachment_type);
124  }
125 
127  const ActorBlueprint &blueprint,
128  const geom::Transform &transform,
129  Actor *parent_actor,
130  rpc::AttachmentType attachment_type) noexcept {
131  try {
132  return SpawnActor(blueprint, transform, parent_actor, attachment_type);
133  } catch (const std::exception &) {
134  return nullptr;
135  }
136  }
137 
139  time_duration local_timeout = timeout.milliseconds() == 0 ?
140  _episode.Lock()->GetNetworkingTimeout() : timeout;
141 
142  return _episode.Lock()->WaitForTick(local_timeout);
143  }
144 
145  size_t World::OnTick(std::function<void(WorldSnapshot)> callback) {
146  return _episode.Lock()->RegisterOnTickEvent(std::move(callback));
147  }
148 
149  void World::RemoveOnTick(size_t callback_id) {
150  _episode.Lock()->RemoveOnTickEvent(callback_id);
151  }
152 
153  uint64_t World::Tick(time_duration timeout) {
154  time_duration local_timeout = timeout.milliseconds() == 0 ?
155  _episode.Lock()->GetNetworkingTimeout() : timeout;
156  return _episode.Lock()->Tick(local_timeout);
157  }
158 
159  void World::SetPedestriansCrossFactor(float percentage) {
160  _episode.Lock()->SetPedestriansCrossFactor(percentage);
161  }
162 
163  void World::SetPedestriansSeed(unsigned int seed) {
164  _episode.Lock()->SetPedestriansSeed(seed);
165  }
166 
168  SharedPtr<ActorList> actors = GetActors();
169  SharedPtr<TrafficSign> result;
170  std::string landmark_id = landmark.GetId();
171  for (size_t i = 0; i < actors->size(); i++) {
172  SharedPtr<Actor> actor = actors->at(i);
173  if (StringUtil::Match(actor->GetTypeId(), "*traffic.*")) {
174  TrafficSign* sign = static_cast<TrafficSign*>(actor.get());
175  if(sign && (sign->GetSignId() == landmark_id)) {
176  return actor;
177  }
178  }
179  }
180  return nullptr;
181  }
182 
184  SharedPtr<ActorList> actors = GetActors();
186  std::string landmark_id = landmark.GetId();
187  for (size_t i = 0; i < actors->size(); i++) {
188  SharedPtr<Actor> actor = actors->at(i);
189  if (StringUtil::Match(actor->GetTypeId(), "*traffic_light*")) {
190  TrafficLight* tl = static_cast<TrafficLight*>(actor.get());
191  if(tl && (tl->GetSignId() == landmark_id)) {
192  return actor;
193  }
194  }
195  }
196  return nullptr;
197  }
198 
200  SharedPtr<ActorList> actors = GetActors();
202  for (size_t i = 0; i < actors->size(); i++) {
203  SharedPtr<Actor> actor = actors->at(i);
204  if (StringUtil::Match(actor->GetTypeId(), "*traffic_light*")) {
205  TrafficLight* tl = static_cast<TrafficLight*>(actor.get());
206  if(tl && (tl->GetSignId() == sign_id)) {
207  return actor;
208  }
209  }
210  }
211  return nullptr;
212  }
213 
215  _episode.Lock()->ResetAllTrafficLights();
216  }
217 
219  return _episode.Lock()->GetLightManager();
220  }
221 
222  void World::FreezeAllTrafficLights(bool frozen) {
223  _episode.Lock()->FreezeAllTrafficLights(frozen);
224  }
225 
226  std::vector<geom::BoundingBox> World::GetLevelBBs(uint8_t queried_tag) const {
227  return _episode.Lock()->GetLevelBBs(queried_tag);
228  }
229 
230  std::vector<rpc::EnvironmentObject> World::GetEnvironmentObjects(uint8_t queried_tag) const {
231  return _episode.Lock()->GetEnvironmentObjects(queried_tag);
232  }
233 
235  std::vector<uint64_t> env_objects_ids,
236  bool enable) const {
237  _episode.Lock()->EnableEnvironmentObjects(env_objects_ids, enable);
238  }
239 
240  boost::optional<rpc::LabelledPoint> World::ProjectPoint(
241  geom::Location location, geom::Vector3D direction, float search_distance) const {
242  auto result = _episode.Lock()->ProjectPoint(location, direction, search_distance);
243  if (result.first) {
244  return result.second;
245  }
246  return {};
247  }
248 
249  boost::optional<rpc::LabelledPoint> World::GroundProjection(
250  geom::Location location, float search_distance) const {
251  const geom::Vector3D DownVector(0,0,-1);
252  return ProjectPoint(location, DownVector, search_distance);
253  }
254 
255  std::vector<rpc::LabelledPoint> World::CastRay(
256  geom::Location start_location, geom::Location end_location) const {
257  return _episode.Lock()->CastRay(start_location, end_location);
258  }
259 
260  std::vector<SharedPtr<Actor>> World::GetTrafficLightsFromWaypoint(
261  const Waypoint& waypoint, double distance) const {
262  std::vector<SharedPtr<Actor>> Result;
263  std::vector<SharedPtr<Landmark>> landmarks =
264  waypoint.GetAllLandmarksInDistance(distance);
265  std::set<std::string> added_signals;
266  for (auto& landmark : landmarks) {
267  if (road::SignalType::IsTrafficLight(landmark->GetType())) {
268  SharedPtr<Actor> traffic_light = GetTrafficLight(*(landmark.get()));
269  if (traffic_light) {
270  if(added_signals.count(landmark->GetId()) == 0) {
271  Result.emplace_back(traffic_light);
272  added_signals.insert(landmark->GetId());
273  }
274  }
275  }
276  }
277  return Result;
278  }
279 
280  std::vector<SharedPtr<Actor>> World::GetTrafficLightsInJunction(
281  const road::JuncId junc_id) const {
282  std::vector<SharedPtr<Actor>> Result;
283  SharedPtr<Map> map = GetMap();
284  const road::Junction* junction = map->GetMap().GetJunction(junc_id);
285  for (const road::ContId& cont_id : junction->GetControllers()) {
286  const std::unique_ptr<road::Controller>& controller =
287  map->GetMap().GetControllers().at(cont_id);
288  for (road::SignId sign_id : controller->GetSignals()) {
289  SharedPtr<Actor> traffic_light = GetTrafficLightFromOpenDRIVE(sign_id);
290  if (traffic_light) {
291  Result.emplace_back(traffic_light);
292  }
293  }
294  }
295  return Result;
296  }
297 
299  const std::string &object_name,
300  const rpc::MaterialParameter& parameter,
301  const rpc::TextureColor& Texture) {
302  _episode.Lock()->ApplyColorTextureToObjects({object_name}, parameter, Texture);
303  }
304 
306  const std::vector<std::string> &objects_name,
307  const rpc::MaterialParameter& parameter,
308  const rpc::TextureColor& Texture) {
309  _episode.Lock()->ApplyColorTextureToObjects(objects_name, parameter, Texture);
310  }
311 
313  const std::string &object_name,
314  const rpc::MaterialParameter& parameter,
315  const rpc::TextureFloatColor& Texture) {
316  _episode.Lock()->ApplyColorTextureToObjects({object_name}, parameter, Texture);
317  }
318 
320  const std::vector<std::string> &objects_name,
321  const rpc::MaterialParameter& parameter,
322  const rpc::TextureFloatColor& Texture) {
323  _episode.Lock()->ApplyColorTextureToObjects(objects_name, parameter, Texture);
324  }
325 
326  std::vector<std::string> World::GetNamesOfAllObjects() const {
327  return _episode.Lock()->GetNamesOfAllObjects();
328  }
329 
331  const std::string &object_name,
332  const rpc::TextureColor& diffuse_texture,
333  const rpc::TextureFloatColor& emissive_texture,
334  const rpc::TextureFloatColor& normal_texture,
335  const rpc::TextureFloatColor& ao_roughness_metallic_emissive_texture)
336  {
337  if (diffuse_texture.GetWidth() && diffuse_texture.GetHeight()) {
339  object_name, rpc::MaterialParameter::Tex_Diffuse, diffuse_texture);
340  }
341  if (normal_texture.GetWidth() && normal_texture.GetHeight()) {
343  object_name, rpc::MaterialParameter::Tex_Normal, normal_texture);
344  }
345  if (ao_roughness_metallic_emissive_texture.GetWidth() &&
346  ao_roughness_metallic_emissive_texture.GetHeight()) {
348  object_name,
350  ao_roughness_metallic_emissive_texture);
351  }
352  if (emissive_texture.GetWidth() && emissive_texture.GetHeight()) {
354  object_name, rpc::MaterialParameter::Tex_Emissive, emissive_texture);
355  }
356  }
357 
359  const std::vector<std::string> &objects_names,
360  const rpc::TextureColor& diffuse_texture,
361  const rpc::TextureFloatColor& emissive_texture,
362  const rpc::TextureFloatColor& normal_texture,
363  const rpc::TextureFloatColor& ao_roughness_metallic_emissive_texture)
364  {
365  if (diffuse_texture.GetWidth() && diffuse_texture.GetHeight()) {
367  objects_names, rpc::MaterialParameter::Tex_Diffuse, diffuse_texture);
368  }
369  if (normal_texture.GetWidth() && normal_texture.GetHeight()) {
371  objects_names, rpc::MaterialParameter::Tex_Normal, normal_texture);
372  }
373  if (ao_roughness_metallic_emissive_texture.GetWidth() &&
374  ao_roughness_metallic_emissive_texture.GetHeight()) {
376  objects_names,
378  ao_roughness_metallic_emissive_texture);
379  }
380  if (emissive_texture.GetWidth() && emissive_texture.GetHeight()) {
382  objects_names, rpc::MaterialParameter::Tex_Emissive, emissive_texture);
383  }
384  }
385 
386 } // namespace client
387 } // namespace carla
std::vector< std::string > GetNamesOfAllObjects() const
Definition: World.cpp:326
SharedPtr< BlueprintLibrary > GetBlueprintLibrary() const
Return the list of blueprints available in this world.
Definition: World.cpp:36
std::vector< SharedPtr< Actor > > GetTrafficLightsInJunction(const road::JuncId junc_id) const
Definition: World.cpp:280
void RemoveOnTick(size_t callback_id)
Remove a callback registered with OnTick.
Definition: World.cpp:149
std::string SignId
Definition: RoadTypes.h:25
static time_duration milliseconds(size_t timeout)
Definition: Time.h:26
void SetWeather(const rpc::WeatherParameters &weather)
Change the weather in the simulation.
Definition: World.cpp:90
SharedPtr< ActorList > GetActors() const
Return a list with all the actors currently present in the world.
Definition: World.cpp:106
void SetPedestriansCrossFactor(float percentage)
set the probability that an agent could cross the roads in its path following percentage of 0...
Definition: World.cpp:159
size_t OnTick(std::function< void(WorldSnapshot)> callback)
Register a callback to be called every time a world tick is received.
Definition: World.cpp:145
boost::optional< rpc::LabelledPoint > ProjectPoint(geom::Location location, geom::Vector3D direction, float search_distance=10000.f) const
Definition: World.cpp:240
const std::set< ContId > & GetControllers() const
Definition: road/Junction.h:85
void UnloadLevelLayer(rpc::MapLayer map_layers) const
Definition: World.cpp:32
SharedPtr< Actor > GetSpectator() const
Return the spectator actor.
Definition: World.cpp:48
SharedPtr< LightManager > GetLightManager() const
Definition: World.cpp:218
boost::shared_ptr< T > SharedPtr
Use this SharedPtr (boost::shared_ptr) to keep compatibility with boost::python, but it would be nice...
Definition: Memory.h:20
std::vector< std::pair< ActorId, VehicleLightState::flag_type > > VehicleLightStateList
std::vector< rpc::LabelledPoint > CastRay(geom::Location start_location, geom::Location end_location) const
Definition: World.cpp:255
This file contains definitions of common data structures used in traffic manager. ...
Definition: Carla.cpp:133
SharedPtr< Map > GetMap() const
Return the map that describes this world.
Definition: World.cpp:24
void ApplyColorTextureToObject(const std::string &actor_name, const rpc::MaterialParameter &parameter, const rpc::TextureColor &Texture)
Definition: World.cpp:298
Class containing a reference to RoadInfoSignal.
Definition: Landmark.h:22
int32_t JuncId
Definition: RoadTypes.h:17
uint64_t Tick(time_duration timeout)
Signal the simulator to continue to next tick (only has effect on synchronous mode).
Definition: World.cpp:153
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:40
detail::EpisodeProxy _episode
Definition: World.h:235
std::string GetId() const
Definition: Landmark.h:49
SharedPtr< Actor > GetTrafficLightFromOpenDRIVE(const road::SignId &sign_id) const
Definition: World.cpp:199
void ApplyColorTextureToObjects(const std::vector< std::string > &objects_names, const rpc::MaterialParameter &parameter, const rpc::TextureColor &Texture)
Definition: World.cpp:305
static bool Match(const char *str, const char *wildcard_pattern)
Match str with the Unix shell-style wildcard_pattern.
Definition: StringUtil.cpp:17
carla::ActorId ActorId
SharedPtr< Actor > GetTrafficSign(const Landmark &landmark) const
Definition: World.cpp:167
void ResetAllTrafficLights()
Definition: World.cpp:214
void LoadLevelLayer(rpc::MapLayer map_layers) const
Definition: World.cpp:28
SharedPtr< Actor > GetActor(ActorId id) const
Find actor by id, return nullptr if not found.
Definition: World.cpp:98
carla::road::SignId GetSignId() const
Definition: TrafficSign.cpp:14
static void log_warning(Args &&... args)
Definition: Logging.h:96
void SetPedestriansSeed(unsigned int seed)
set the seed to use with random numbers in the pedestrians module
Definition: World.cpp:163
void ApplyFloatColorTextureToObject(const std::string &actor_name, const rpc::MaterialParameter &parameter, const rpc::TextureFloatColor &Texture)
Definition: World.cpp:312
boost::optional< rpc::LabelledPoint > GroundProjection(geom::Location location, float search_distance=10000.0) const
Definition: World.cpp:249
rpc::WeatherParameters GetWeather() const
Retrieve the weather parameters currently active in the world.
Definition: World.cpp:86
void FreezeAllTrafficLights(bool frozen)
Definition: World.cpp:222
void EnableEnvironmentObjects(std::vector< uint64_t > env_objects_ids, bool enable) const
Definition: World.cpp:234
std::vector< SharedPtr< Actor > > GetTrafficLightsFromWaypoint(const Waypoint &waypoint, double distance) const
Definition: World.cpp:260
Represents an actor in the simulation.
Definition: client/Actor.h:18
uint64_t ApplySettings(const rpc::EpisodeSettings &settings, time_duration timeout)
Definition: World.cpp:56
std::vector< geom::BoundingBox > GetLevelBBs(uint8_t queried_tag) const
Returns all the BBs of all the elements of the level.
Definition: World.cpp:226
Positive time duration up to milliseconds resolution.
Definition: Time.h:19
uint32_t GetHeight() const
Definition: Texture.h:33
static bool IsTrafficLight(const std::string &type)
Definition: SignalType.cpp:121
Contains all the necessary information for spawning an Actor.
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:126
SharedPtrType Lock() const
Same as TryLock but never return nullptr.
rpc::EpisodeSettings GetSettings() const
Definition: World.cpp:52
std::string ContId
Definition: RoadTypes.h:29
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.
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:118
void ApplyFloatColorTextureToObjects(const std::vector< std::string > &objects_names, const rpc::MaterialParameter &parameter, const rpc::TextureFloatColor &Texture)
Definition: World.cpp:319
WorldSnapshot GetSnapshot() const
Return a snapshot of the world at this moment.
Definition: World.cpp:94
std::vector< rpc::EnvironmentObject > GetEnvironmentObjects(uint8_t queried_tag) const
Definition: World.cpp:230
boost::optional< geom::Location > GetRandomLocationFromNavigation() const
Get a random location from the pedestrians navigation mesh.
Definition: World.cpp:44
SharedPtr< Actor > GetTrafficLight(const Landmark &landmark) const
Definition: World.cpp:183
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:330
uint32_t GetWidth() const
Definition: Texture.h:29
WorldSnapshot WaitForTick(time_duration timeout) const
Block calling thread until a world tick is received.
Definition: World.cpp:138
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:358