29#include <condition_variable>
39using namespace std::string_literals;
50 const auto vc =
client.GetClientVersion();
51 const auto vs =
client.GetServerVersion();
54 "Version mismatch detected: You are trying to connect to a simulator",
55 "that might be incompatible with this API");
56 log_warning(
"Client API version =", vc);
57 log_warning(
"Simulator API version =", vs);
63 auto start = std::chrono::system_clock::now();
64 while (frame > episode.
GetState()->GetTimestamp().frame) {
65 std::this_thread::sleep_for(std::chrono::microseconds(100));
66 auto end = std::chrono::system_clock::now();
67 auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end-start);
85 const std::string &host,
87 const size_t worker_threads,
88 const bool enable_garbage_collection)
90 _client(host, port, worker_threads),
103 class SimulatorReaper {
107 std::unique_lock<std::mutex> lock(_mutex);
108 _queue.push_back(simulator);
110 if (!_running || _owner != CurrentProcess()) {
112 _owner = CurrentProcess();
113 std::thread(&SimulatorReaper::Run,
this).detach();
120 static long CurrentProcess() {
124 return static_cast<long>(::getpid());
129 std::unique_lock<std::mutex> lock(_mutex);
131 _cv.wait(lock, [
this]() {
return !_queue.empty(); });
132 Simulator *simulator = _queue.front();
137 }
catch (
const std::exception &e) {
138 log_error(
"failed to destroy a client:", e.what());
145 std::condition_variable _cv;
146 std::deque<Simulator *> _queue;
147 bool _running =
false;
151 SimulatorReaper &GetSimulatorReaper() {
153 static SimulatorReaper *instance =
new SimulatorReaper();
160 if (simulator ==
nullptr) {
164 GetSimulatorReaper().Post(simulator);
187 for (
auto i = 0u; i < number_of_attempts; ++i) {
188 using namespace std::literals::chrono_literals;
195 if (episode.GetId() !=
id) {
198 while (!
_episode->IsEpisodeChangeHandled()) {
199 if (std::chrono::steady_clock::now() > deadline) {
200 log_warning(
"the Traffic Manager has not finished resetting for the new episode");
203 std::this_thread::sleep_for(10ms);
208 throw_exception(std::runtime_error(
"failed to connect to newly created map"));
217 constexpr auto custom_opendrive_map =
"OpenDriveMap";
219 return LoadEpisode(custom_opendrive_map, reset_settings);
229 _episode = std::make_shared<Episode>(
_client, std::weak_ptr<Simulator>(shared_from_this()));
262 const auto episode_id =
_episode->GetId();
265 std::string map_name;
266 std::string map_base_path;
267 bool fill_base_string =
false;
268 for (
size_t ri = map_info.
name.size(); ri > 0; --ri) {
270 if (fill_base_string ==
false && map_info.
name[i] !=
'/') {
271 map_name += map_info.
name[i];
273 map_base_path += map_info.
name[i];
274 fill_base_string =
true;
277 std::reverse(map_name.begin(), map_name.end());
278 std::reverse(map_base_path.begin(), map_base_path.end());
279 std::string XODRFolder = map_base_path +
"/OpenDrive/" + map_name +
".xodr";
320 auto result =
_episode->WaitForState(timeout);
321 if (!result.has_value()) {
350 return MakeShared<BlueprintLibrary>(std::move(defs));
364 "synchronous mode enabled with variable delta seconds. It is highly "
365 "recommended to set 'fixed_delta_seconds' when running on synchronous mode.");
370 "synchronous mode and substepping are enabled but the number of substeps is not valid. "
371 "Please be aware that this value needs to be in the range [1-16].");
375 if (n_substeps >
static_cast<double>(settings.
max_substeps)) {
377 "synchronous mode and substepping are enabled but the values for the simulation are not valid. "
378 "The values should fulfil fixed_delta_seconds <= max_substep_delta_time * max_substeps. "
379 "Be very careful about that, the time deltas are not guaranteed.");
384 using namespace std::literals::chrono_literals;
409 return _episode->CreateNavigationIfMissing()->IsServerSide();
414 if (walker ==
nullptr) {
420 nav->RegisterWalker(walker->GetId(), controller.
GetId());
425 if (walker ==
nullptr) {
431 nav->UnregisterWalker(walker->GetId(), controller.
GetId());
437 if (
nav->IsServerSide()) {
441 constexpr int attempts = 3;
442 for (
int i = 0; i < attempts; ++i) {
444 if (location.z > -9.0e5f) {
450 return nav->GetRandomLocation();
456 if (
nav->IsServerSide()) {
460 nav->SetPedestriansCrossFactor(percentage);
466 if (
nav->IsServerSide()) {
470 nav->SetPedestriansSeed(seed);
484 if (parent !=
nullptr) {
507 result->GetDisplayId(),
510 "garbage collection");
536 sensor.GetActorDescription().GetStreamToken(),
537 [cb=std::move(callback), ep=
WeakEpisodeProxy{shared_from_this()}](
auto buffer) {
538 auto data = sensor::Deserializer::Deserialize(std::move(buffer));
539 data->_episode = ep.TryLock();
566 [cb=std::move(callback), ep=
WeakEpisodeProxy{shared_from_this()}](
auto buffer) {
567 auto data = sensor::Deserializer::Deserialize(std::move(buffer));
568 data->_episode = ep.TryLock();
590 const std::vector<std::string> &objects_name,
597 const std::vector<std::string> &objects_name,
#define DEBUG_ASSERT(predicate)
#define LIBCARLA_INITIALIZE_LIFETIME_PROFILER(display_name)
static bool IsPoolThread()
Whether the calling thread is a ThreadPool worker (it must not destroy its own pool).
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)
TimeoutException(const std::string &endpoint, time_duration timeout)
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 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...
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)
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
Connects and controls a CARLA Simulator.
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)
static void Delete(Simulator *simulator)
Deleter: on a pool thread, destroy on a background thread (~Simulator joins the pools).
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()
uint64_t spawn_frame
Server frame counter when a spawn call created this actor: snapshots up to and including this frame p...
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::Strong > EpisodeProxy
EpisodeProxyImpl< EpisodeProxyPointerType::Weak > WeakEpisodeProxy
static bool SynchronizeFrame(uint64_t frame, const Episode &episode, time_duration timeout)
Texture< sensor::data::Color > TextureColor
Texture< FloatColor > TextureFloatColor
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...
Seting for map generation from opendrive without additional geometry.