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 
164  SharedPtr<ActorList> actors = GetActors();
165  SharedPtr<TrafficSign> result;
166  std::string landmark_id = landmark.GetId();
167  for (size_t i = 0; i < actors->size(); i++) {
168  SharedPtr<Actor> actor = actors->at(i);
169  if (StringUtil::Match(actor->GetTypeId(), "*traffic.*")) {
170  TrafficSign* sign = static_cast<TrafficSign*>(actor.get());
171  if(sign && (sign->GetSignId() == landmark_id)) {
172  return actor;
173  }
174  }
175  }
176  return nullptr;
177  }
178 
180  SharedPtr<ActorList> actors = GetActors();
182  std::string landmark_id = landmark.GetId();
183  for (size_t i = 0; i < actors->size(); i++) {
184  SharedPtr<Actor> actor = actors->at(i);
185  if (StringUtil::Match(actor->GetTypeId(), "*traffic_light*")) {
186  TrafficLight* tl = static_cast<TrafficLight*>(actor.get());
187  if(tl && (tl->GetSignId() == landmark_id)) {
188  return actor;
189  }
190  }
191  }
192  return nullptr;
193  }
194 
196  SharedPtr<ActorList> actors = GetActors();
198  for (size_t i = 0; i < actors->size(); i++) {
199  SharedPtr<Actor> actor = actors->at(i);
200  if (StringUtil::Match(actor->GetTypeId(), "*traffic_light*")) {
201  TrafficLight* tl = static_cast<TrafficLight*>(actor.get());
202  if(tl && (tl->GetSignId() == sign_id)) {
203  return actor;
204  }
205  }
206  }
207  return nullptr;
208  }
209 
211  _episode.Lock()->ResetAllTrafficLights();
212  }
213 
215  return _episode.Lock()->GetLightManager();
216  }
217 
218  void World::FreezeAllTrafficLights(bool frozen) {
219  _episode.Lock()->FreezeAllTrafficLights(frozen);
220  }
221 
222  std::vector<geom::BoundingBox> World::GetLevelBBs(uint8_t queried_tag) const {
223  return _episode.Lock()->GetLevelBBs(queried_tag);
224  }
225 
226  std::vector<rpc::EnvironmentObject> World::GetEnvironmentObjects(uint8_t queried_tag) const {
227  return _episode.Lock()->GetEnvironmentObjects(queried_tag);
228  }
229 
231  std::vector<uint64_t> env_objects_ids,
232  bool enable) const {
233  _episode.Lock()->EnableEnvironmentObjects(env_objects_ids, enable);
234  }
235 
236  boost::optional<rpc::LabelledPoint> World::ProjectPoint(
237  geom::Location location, geom::Vector3D direction, float search_distance) const {
238  auto result = _episode.Lock()->ProjectPoint(location, direction, search_distance);
239  if (result.first) {
240  return result.second;
241  }
242  return {};
243  }
244 
245  boost::optional<rpc::LabelledPoint> World::GroundProjection(
246  geom::Location location, float search_distance) const {
247  const geom::Vector3D DownVector(0,0,-1);
248  return ProjectPoint(location, DownVector, search_distance);
249  }
250 
251  std::vector<rpc::LabelledPoint> World::CastRay(
252  geom::Location start_location, geom::Location end_location) const {
253  return _episode.Lock()->CastRay(start_location, end_location);
254  }
255 
256  std::vector<SharedPtr<Actor>> World::GetTrafficLightsFromWaypoint(
257  const Waypoint& waypoint, double distance) const {
258  std::vector<SharedPtr<Actor>> Result;
259  std::vector<SharedPtr<Landmark>> landmarks =
260  waypoint.GetAllLandmarksInDistance(distance);
261  std::set<std::string> added_signals;
262  for (auto& landmark : landmarks) {
263  if (road::SignalType::IsTrafficLight(landmark->GetType())) {
264  SharedPtr<Actor> traffic_light = GetTrafficLight(*(landmark.get()));
265  if (traffic_light) {
266  if(added_signals.count(landmark->GetId()) == 0) {
267  Result.emplace_back(traffic_light);
268  added_signals.insert(landmark->GetId());
269  }
270  }
271  }
272  }
273  return Result;
274  }
275 
276  std::vector<SharedPtr<Actor>> World::GetTrafficLightsInJunction(
277  const road::JuncId junc_id) const {
278  std::vector<SharedPtr<Actor>> Result;
279  SharedPtr<Map> map = GetMap();
280  const road::Junction* junction = map->GetMap().GetJunction(junc_id);
281  for (const road::ContId& cont_id : junction->GetControllers()) {
282  const std::unique_ptr<road::Controller>& controller =
283  map->GetMap().GetControllers().at(cont_id);
284  for (road::SignId sign_id : controller->GetSignals()) {
285  SharedPtr<Actor> traffic_light = GetTrafficLightFromOpenDRIVE(sign_id);
286  if (traffic_light) {
287  Result.emplace_back(traffic_light);
288  }
289  }
290  }
291  return Result;
292  }
293 
294 } // namespace client
295 } // namespace carla
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:276
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:236
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:214
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:251
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
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:192
std::string GetId() const
Definition: Landmark.h:49
SharedPtr< Actor > GetTrafficLightFromOpenDRIVE(const road::SignId &sign_id) const
Definition: World.cpp:195
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:163
void ResetAllTrafficLights()
Definition: World.cpp:210
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
boost::optional< rpc::LabelledPoint > GroundProjection(geom::Location location, float search_distance=10000.0) const
Definition: World.cpp:245
rpc::WeatherParameters GetWeather() const
Retrieve the weather parameters currently active in the world.
Definition: World.cpp:86
void FreezeAllTrafficLights(bool frozen)
Definition: World.cpp:218
void EnableEnvironmentObjects(std::vector< uint64_t > env_objects_ids, bool enable) const
Definition: World.cpp:230
std::vector< SharedPtr< Actor > > GetTrafficLightsFromWaypoint(const Waypoint &waypoint, double distance) const
Definition: World.cpp:256
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:222
Positive time duration up to milliseconds resolution.
Definition: Time.h:19
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
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:226
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:179
WorldSnapshot WaitForTick(time_duration timeout) const
Block calling thread until a world tick is received.
Definition: World.cpp:138