28using namespace std::string_literals;
43 "Version mismatch detected: You are trying to connect to a simulator",
44 "that might be incompatible with this API");
52 auto start = std::chrono::system_clock::now();
53 while (frame > episode.
GetState()->GetTimestamp().frame) {
54 std::this_thread::sleep_for(std::chrono::microseconds(100));
55 auto end = std::chrono::system_clock::now();
56 auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end-start);
74 const std::string &host,
76 const size_t worker_threads,
77 const bool enable_garbage_collection)
79 _client(host, port, worker_threads),
81 _gc_policy(enable_garbage_collection ?
106 for (
auto i = 0u; i < number_of_attempts; ++i) {
107 using namespace std::literals::chrono_literals;
114 if (episode.GetId() !=
id) {
117 while (!
_episode->IsEpisodeChangeHandled()) {
118 if (std::chrono::steady_clock::now() > deadline) {
119 log_warning(
"the Traffic Manager has not finished resetting for the new episode");
122 std::this_thread::sleep_for(10ms);
127 throw_exception(std::runtime_error(
"failed to connect to newly created map"));
131 std::string opendrive,
136 constexpr auto custom_opendrive_map =
"OpenDriveMap";
138 return LoadEpisode(custom_opendrive_map, reset_settings);
148 _episode = std::make_shared<Episode>(
_client, std::weak_ptr<Simulator>(shared_from_this()));
181 const auto episode_id =
_episode->GetId();
184 std::string map_name;
185 std::string map_base_path;
186 bool fill_base_string =
false;
187 for (
size_t ri = map_info.
name.size(); ri > 0; --ri) {
189 if (fill_base_string ==
false && map_info.
name[i] !=
'/') {
190 map_name += map_info.
name[i];
192 map_base_path += map_info.
name[i];
193 fill_base_string =
true;
196 std::reverse(map_name.begin(), map_name.end());
197 std::reverse(map_base_path.begin(), map_base_path.end());
198 std::string XODRFolder = map_base_path +
"/OpenDrive/" + map_name +
".xodr";
239 auto result =
_episode->WaitForState(timeout);
240 if (!result.has_value()) {
269 return MakeShared<BlueprintLibrary>(std::move(defs));
283 "synchronous mode enabled with variable delta seconds. It is highly "
284 "recommended to set 'fixed_delta_seconds' when running on synchronous mode.");
289 "synchronous mode and substepping are enabled but the number of substeps is not valid. "
290 "Please be aware that this value needs to be in the range [1-16].");
294 if (n_substeps >
static_cast<double>(settings.
max_substeps)) {
296 "synchronous mode and substepping are enabled but the values for the simulation are not valid. "
297 "The values should fulfil fixed_delta_seconds <= max_substep_delta_time * max_substeps. "
298 "Be very careful about that, the time deltas are not guaranteed.");
303 using namespace std::literals::chrono_literals;
315 auto nav =
_episode->CreateNavigationIfMissing();
322 auto nav =
_episode->CreateNavigationIfMissing();
328 return _episode->CreateNavigationIfMissing()->IsServerSide();
333 if (walker ==
nullptr) {
338 auto nav =
_episode->CreateNavigationIfMissing();
339 nav->RegisterWalker(walker->GetId(), controller.
GetId());
344 if (walker ==
nullptr) {
349 auto nav =
_episode->CreateNavigationIfMissing();
350 nav->UnregisterWalker(walker->GetId(), controller.
GetId());
355 auto nav =
_episode->CreateNavigationIfMissing();
356 if (nav->IsServerSide()) {
360 constexpr int attempts = 3;
361 for (
int i = 0; i < attempts; ++i) {
363 if (location.z > -9.0e5f) {
369 return nav->GetRandomLocation();
374 auto nav =
_episode->CreateNavigationIfMissing();
375 if (nav->IsServerSide()) {
379 nav->SetPedestriansCrossFactor(percentage);
384 auto nav =
_episode->CreateNavigationIfMissing();
385 if (nav->IsServerSide()) {
389 nav->SetPedestriansSeed(seed);
403 if (parent !=
nullptr) {
422 result->GetDisplayId(),
425 "garbage collection");
452 [cb=std::move(callback), ep=
WeakEpisodeProxy{shared_from_this()}](
auto buffer) {
453 auto data = sensor::Deserializer::Deserialize(std::move(buffer));
454 data->_episode = ep.TryLock();
481 [cb=std::move(callback), ep=
WeakEpisodeProxy{shared_from_this()}](
auto buffer) {
482 auto data = sensor::Deserializer::Deserialize(std::move(buffer));
483 data->_episode = ep.TryLock();
505 const std::vector<std::string> &objects_name,
512 const std::vector<std::string> &objects_name,
#define DEBUG_ASSERT(predicate)
#define LIBCARLA_INITIALIZE_LIFETIME_PROFILER(display_name)
Contains all the necessary information for spawning an Actor.
rpc::ActorDescription MakeActorDescription() const
Represents an actor in the simulation.
static bool FileExists(std::string_view file)
static SharedPtr< Actor > MakeActor(EpisodeProxy episode, rpc::Actor actor_description, GarbageCollectionPolicy garbage_collection_policy)
Create an Actor based on the provided actor_description.
Internal state of an Actor.
std::optional< uint64_t > _spawn_frame
EpisodeProxy & GetEpisode()
SharedPtr< Actor > GetParent() const
const rpc::Actor & GetActorDescription() const
const std::string & GetDisplayId() const
Provides communication with the rpc and streaming servers of a CARLA simulator.
bool SetPedestriansSeed(uint32_t seed) const
Seed for the server-side navigation RNG (crosser draw); applies to walkers whose navigation starts af...
std::string GetClientVersion()
const std::string GetEndpoint() const
std::string GetMapData() const
bool IsEnabledForROS(const streaming::Token &token)
void DisableForROS(const streaming::Token &token)
bool SetFilesBaseFolder(const std::string &path)
void Send(rpc::ActorId ActorId, const rpc::CustomV2XBytes &data)
void RequestFile(const std::string &name) const
void UnSubscribeFromGBuffer(rpc::ActorId ActorId, uint32_t GBufferId)
void UnSubscribeFromStream(const streaming::Token &token)
rpc::VehicleLightStateList GetVehiclesLightStates()
Returns a list of pairs where the firts element is the vehicle ID and the second one is the light sta...
std::vector< std::string > GetRequiredFiles(const std::string &folder="", const bool download=true) const
void LoadEpisode(std::string map_name, bool reset_settings=true, rpc::MapLayer map_layer=rpc::MapLayer::All)
uint64_t SetEpisodeSettings(const rpc::EpisodeSettings &settings)
void SubscribeToStream(const streaming::Token &token, std::function< void(Buffer)> callback)
std::vector< std::string > GetNamesOfAllObjects() const
void CopyOpenDriveToServer(std::string opendrive, const rpc::OpendriveGenerationParameters ¶ms)
void StopStreaming()
Join the streaming threads; no stream callback runs afterwards.
void FreezeAllTrafficLights(bool frozen)
bool DestroyActor(rpc::ActorId actor)
bool SetPedestriansCrossFactor(float percentage) const
Probability that a walker whose navigation starts after this call may cross roads (server-side naviga...
std::vector< uint8_t > GetCacheFile(const std::string &name, const bool request_otherwise=true) const
void EnableForROS(const streaming::Token &token)
rpc::Actor GetSpectator()
std::vector< rpc::ActorDefinition > GetActorDefinitions()
void SubscribeToGBuffer(rpc::ActorId ActorId, uint32_t GBufferId, std::function< void(Buffer)> callback)
std::string GetServerVersion()
geom::Location GetRandomLocationFromNavigation() const
Server-side random point on the loaded navmesh.
void ApplyColorTextureToObjects(const std::vector< std::string > &objects_name, const rpc::MaterialParameter ¶meter, const rpc::TextureColor &Texture)
rpc::MapInfo GetMapInfo()
rpc::Actor SpawnActorWithParent(const rpc::ActorDescription &description, const geom::Transform &transform, rpc::ActorId parent, rpc::AttachmentType attachment_type)
rpc::EpisodeSettings GetEpisodeSettings()
time_duration GetTimeout() const
rpc::Actor SpawnActor(const rpc::ActorDescription &description, const geom::Transform &transform)
auto GetId() const noexcept
Holds the current episode, and the current episode state.
std::shared_ptr< const EpisodeState > GetState() const
WorldSnapshot WaitForTick(time_duration timeout)
std::shared_ptr< Episode > _episode
bool ShouldUpdateMap(rpc::MapInfo &map_info)
void DisableForROS(const Sensor &sensor)
void RequestFile(const std::string &name) const
std::string _open_drive_file
void EnableForROS(const Sensor &sensor)
void RegisterAIController(const WalkerAIController &controller)
SharedPtr< LightManager > _light_manager
std::vector< std::string > GetRequiredFiles(const std::string &folder="", const bool download=true) const
SharedPtr< Actor > MakeActor(rpc::Actor actor_description, GarbageCollectionPolicy gc=GarbageCollectionPolicy::Disabled)
Creates an actor instance out of a description of an existing actor.
bool IsEnabledForROS(const Sensor &sensor)
SharedPtr< BlueprintLibrary > GetBlueprintLibrary()
void GetReadyCurrentEpisode()
SharedPtr< Actor > SpawnActor(const ActorBlueprint &blueprint, const geom::Transform &transform, Actor *parent=nullptr, rpc::AttachmentType attachment_type=rpc::AttachmentType::Rigid, GarbageCollectionPolicy gc=GarbageCollectionPolicy::Inherit)
Spawns an actor into the simulation.
uint64_t _cached_map_episode_id
Simulator(const std::string &host, uint16_t port, size_t worker_threads=0u, bool enable_garbage_collection=false)
const GarbageCollectionPolicy _gc_policy
rpc::VehicleLightStateList GetVehiclesLightStates()
Returns a list of pairs where the firts element is the vehicle ID and the second one is the light sta...
void UnSubscribeFromGBuffer(Actor &sensor, uint32_t gbuffer_id)
void SubscribeToSensor(const Sensor &sensor, std::function< void(SharedPtr< sensor::SensorData >)> callback)
void UnregisterAIController(const WalkerAIController &controller)
std::vector< uint8_t > GetCacheFile(const std::string &name, const bool request_otherwise) const
SharedPtr< Map > _cached_map
void ApplyColorTextureToObjects(const std::vector< std::string > &objects_name, const rpc::MaterialParameter ¶meter, const rpc::TextureColor &Texture)
– Texture updating operations
std::shared_ptr< WalkerNavigation > GetNavigation()
bool SetFilesBaseFolder(const std::string &path)
SharedPtr< Actor > GetSpectator()
EpisodeProxy LoadOpenDriveEpisode(std::string opendrive, const rpc::OpendriveGenerationParameters ¶ms, bool reset_settings=true)
void Send(const Sensor &sensor, const rpc::CustomV2XBytes &data)
void SetPedestriansCrossFactor(float percentage)
void FreezeAllTrafficLights(bool frozen)
uint64_t SetEpisodeSettings(const rpc::EpisodeSettings &settings)
void UnSubscribeFromSensor(Actor &sensor)
EpisodeProxy LoadEpisode(std::string map_name, bool reset_settings=true, rpc::MapLayer map_layers=rpc::MapLayer::All)
uint64_t Tick(time_duration timeout)
void SubscribeToGBuffer(Actor &sensor, uint32_t gbuffer_id, std::function< void(SharedPtr< sensor::SensorData >)> callback)
std::vector< std::string > GetNamesOfAllObjects() const
std::mutex _cached_map_mutex
SharedPtr< Map > GetCurrentMap()
std::optional< geom::Location > GetRandomLocationFromNavigation()
rpc::EpisodeSettings GetEpisodeSettings()
bool DestroyActor(Actor &actor)
void SetPedestriansSeed(unsigned int seed)
bool IsNavigationServerSide()
True when the current episode's navigation is hosted by the server (World-Partitioned navmesh); walke...
EpisodeProxy GetCurrentEpisode()
streaming::Token GetStreamToken() const
Fixed-size binary payload carried by the custom V2X sensor (sensor.other.v2x_custom).
std::optional< double > fixed_delta_seconds
double max_substep_delta_time
Positive time duration up to milliseconds resolution.
static time_duration milliseconds(size_t timeout)
constexpr auto to_chrono() const
static void ValidateVersions(Client &client)
EpisodeProxyImpl< EpisodeProxyPointerType::Weak > WeakEpisodeProxy
static bool SynchronizeFrame(uint64_t frame, const Episode &episode, time_duration timeout)
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
void throw_exception(const ExceptionT &e)
Templated on the static type so the thrown object keeps its dynamic type: taking a const std::excepti...
static void log_warning(Args &&... args)
static void log_debug(Args &&... args)
Seting for map generation from opendrive without additional geometry.