CARLA
Loading...
Searching...
No Matches
TrafficManagerLocal.h
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
7#pragma once
8
9#include <atomic>
10#include <chrono>
11#include <limits>
12#include <mutex>
13#include <thread>
14#include <vector>
15
18#include "carla/client/World.h"
19#include "carla/Memory.h"
20#include "carla/rpc/Command.h"
22
31
37
38namespace carla {
39namespace traffic_manager {
40
41namespace chr = std::chrono;
42
43using namespace std::chrono_literals;
44
45using TimePoint = chr::time_point<chr::system_clock, chr::nanoseconds>;
46using TLGroup = std::vector<carla::SharedPtr<carla::client::TrafficLight>>;
47using LocalMapPtr = std::shared_ptr<InMemoryMap>;
49
50/// The function of this class is to integrate all the various stages of
51/// the traffic manager appropriately using messengers.
53
54private:
55 /// PID controller parameters.
56 std::vector<float> longitudinal_PID_parameters;
58 std::vector<float> lateral_PID_parameters;
60 /// CARLA client connection object.
62 /// CARLA client and object.
64 /// Set of all actors registered with traffic manager.
66 // Set containing the ids of the registered large vehicles
67 std::unordered_map<ActorId, std::pair<float, bool>> large_vehicles;
68 /// State counter to track changes in registered actors.
70 /// List of vehicles registered with the traffic manager in
71 /// current update cycle.
72 std::vector<ActorId> vehicle_id_list;
73 /// Pointer to local map cache.
75 /// Structures to hold waypoint buffers for all vehicles.
77 /// Object for tracking paths of the traffic vehicles.
79 /// Type containing the current state of all actors involved in the simulation.
81 /// Time instance used to calculate dt in asynchronous mode.
83 /// Parameterization object.
85 /// Array to hold output data of localization stage.
87 /// Array to hold output data of collision avoidance.
89 /// Array to hold output data of traffic light response.
91 /// Array to hold output data of motion planning.
93 /// Variable to keep track of currently reserved array space for frames.
95 /// Various stages representing core operations of traffic manager.
102 /// Traffic manager server instance.
104 /// Switch to turn on / turn off traffic manager.
105 std::atomic<bool> run_traffic_manger{true};
106 /// Single worker thread for sequential execution of sub-components.
107 std::unique_ptr<std::thread> worker_thread;
108 /// Last processed frame
109 size_t last_frame{0};
110 /// Cached episode settings; they only change through world.apply_settings.
112 /// Simulation time of the last episode settings refresh.
113 double last_settings_update {-std::numeric_limits<double>::infinity()};
114 /// Starts at the limit so the first batch of an episode is waited for.
117 /// Randomization seed.
118 uint64_t seed {static_cast<uint64_t>(time(NULL))};
119 /// Structure holding random devices per vehicle.
121 std::vector<ActorId> marked_for_removal;
122 /// Mutex to prevent vehicle registration during frame array re-allocation.
124
125 /// Method to check if all traffic lights are frozen in a group.
126 bool CheckAllFrozen(TLGroup tl_to_freeze);
127
128public:
129 /// Private constructor for singleton lifecycle management.
131 std::vector<float> longitudinal_highway_PID_parameters,
132 std::vector<float> lateral_PID_parameters,
133 std::vector<float> lateral_highway_PID_parameters,
134 float perc_decrease_from_limit,
135 cc::detail::EpisodeProxy &episode_proxy,
136 uint16_t &RPCportTM);
137
138 /// Destructor.
139 virtual ~TrafficManagerLocal();
140
141 /// Method to setup InMemoryMap.
142 void SetupLocalMap();
143
144 /// To start the TrafficManager.
145 void Start();
146
147 /// To do one step of the TrafficManager.
148 void Step();
149
150 /// Initiates thread to run the TrafficManager sequentially.
151 void Run();
152
153 /// To stop the TrafficManager.
154 void Stop();
155
156 /// To release the traffic manager.
157 void Release();
158
159 /// To reset the traffic manager for the episode @a episode_id.
160 void Reset(uint64_t episode_id);
161
162 /// This method registers a vehicle with the traffic manager.
163 void RegisterVehicles(const std::vector<ActorPtr> &actor_list);
164
165 /// This method unregisters a vehicle from traffic manager.
166 void UnregisterVehicles(const std::vector<ActorPtr> &actor_list);
167
168 /// Method to set a vehicle's % decrease in velocity with respect to the speed limit.
169 /// If less than 0, it's a % increase.
170 void SetPercentageSpeedDifference(const ActorPtr &actor, const float percentage);
171
172 /// Set a vehicle's exact desired velocity.
173 void SetDesiredSpeed(const ActorPtr &actor, const float value);
174
175 /// Method to set a global % decrease in velocity with respect to the speed limit.
176 /// If less than 0, it's a % increase.
177 void SetGlobalPercentageSpeedDifference(float const percentage);
178
179 /// Method to set a lane offset displacement from the center line.
180 /// Positive values imply a right offset while negative ones mean a left one.
181 void SetLaneOffset(const ActorPtr &actor, const float offset);
182
183 /// Method to set a global lane offset displacement from the center line.
184 /// Positive values imply a right offset while negative ones mean a left one.
185 void SetGlobalLaneOffset(float const offset);
186
187 /// Method to enable/disable the wide-turn manoeuvre for a single large vehicle.
188 void SetLargeVehicleWideTurn(const ActorPtr &actor, const bool enable);
189
190 /// Method to enable/disable the wide-turn manoeuvre globally for large vehicles.
191 void SetGlobalLargeVehicleWideTurn(const bool enable);
192
193 /// Method to set the automatic management of the vehicle lights
194 void SetUpdateVehicleLights(const ActorPtr &actor, const bool do_update);
195
196 /// Method to set collision detection rules between vehicles.
197 void SetCollisionDetection(const ActorPtr &reference_actor, const ActorPtr &other_actor, const bool detect_collision);
198
199 /// Method to force lane change on a vehicle.
200 /// Direction flag can be set to true for left and false for right.
201 void SetForceLaneChange(const ActorPtr &actor, const bool direction);
202
203 /// Enable/disable automatic lane change on a vehicle.
204 void SetAutoLaneChange(const ActorPtr &actor, const bool enable);
205
206 /// Method to specify how much distance a vehicle should maintain to
207 /// the leading vehicle.
208 void SetDistanceToLeadingVehicle(const ActorPtr &actor, const float distance);
209
210 /// Method to specify the % chance of ignoring collisions with any walker.
211 void SetPercentageIgnoreWalkers(const ActorPtr &actor, const float perc);
212
213 /// Method to specify the % chance of ignoring collisions with any vehicle.
214 void SetPercentageIgnoreVehicles(const ActorPtr &actor, const float perc);
215
216 /// Method to specify the % chance of running any traffic light.
217 void SetPercentageRunningLight(const ActorPtr &actor, const float perc);
218
219 /// Method to specify the % chance of running any traffic sign.
220 void SetPercentageRunningSign(const ActorPtr &actor, const float perc);
221
222 /// Method to switch traffic manager into synchronous execution.
223 void SetSynchronousMode(bool mode);
224
225 /// Method to set Tick timeout for synchronous execution.
227
228 /// Method to provide synchronous tick.
229 bool SynchronousTick();
230
231 /// Get CARLA episode information.
233
234 /// Get list of all registered vehicles.
235 std::vector<ActorId> GetRegisteredVehiclesIDs();
236
237 /// Method to specify how much distance a vehicle should maintain to
238 /// the Global leading vehicle.
240
241 /// Method to set % to keep on the slow lane.
242 void SetKeepSlowLanePercentage(const ActorPtr &actor, const float percentage);
243
244 /// Method to set % to randomly do a left lane change.
245 void SetRandomLeftLaneChangePercentage(const ActorPtr &actor, const float percentage);
246
247 /// Method to set % to randomly do a right lane change.
248 void SetRandomRightLaneChangePercentage(const ActorPtr &actor, const float percentage);
249
250 /// Method to set hybrid physics mode.
251 void SetHybridPhysicsMode(const bool mode_switch);
252
253 /// Method to set hybrid physics radius.
254 void SetHybridPhysicsRadius(const float radius);
255
256 /// Method to set randomization seed.
257 void SetRandomDeviceSeed(const uint64_t _seed);
258
259 /// Method to set Open Street Map mode.
260 void SetOSMMode(const bool mode_switch);
261
262 /// Method to set our own imported path.
263 void SetCustomPath(const ActorPtr &actor, const Path path, const bool empty_buffer);
264
265 /// Method to remove a list of points.
266 void RemoveUploadPath(const ActorId &actor_id, const bool remove_path);
267
268 /// Method to update an already set list of points.
269 void UpdateUploadPath(const ActorId &actor_id, const Path path);
270
271 /// Method to set our own imported route.
272 void SetImportedRoute(const ActorPtr &actor, const Route route, const bool empty_buffer);
273
274 /// Method to remove a route.
275 void RemoveImportedRoute(const ActorId &actor_id, const bool remove_path);
276
277 /// Method to update an already set route.
278 void UpdateImportedRoute(const ActorId &actor_id, const Route route);
279
280 /// Method to set automatic respawn of dormant vehicles.
281 void SetRespawnDormantVehicles(const bool mode_switch);
282
283 /// Method to set boundaries to respawn of dormant vehicles.
284 void SetBoundariesRespawnDormantVehicles(const float lower_bound, const float upper_bound);
285
286 /// Method to set limits for boundaries when respawning dormant vehicles.
287 void SetMaxBoundaries(const float lower, const float upper);
288
289 /// Method to get the vehicle's next action.
290 Action GetNextAction(const ActorId &actor_id);
291
292 /// Method to get the vehicle's action buffer.
293 ActionBuffer GetActionBuffer(const ActorId &actor_id);
294
295 void ShutDown() {};
296};
297
298} // namespace traffic_manager
299} // namespace carla
float distance
ALSM: Agent Lifecycle and State Managerment This class has functionality to update the local cache of...
Definition ALSM.h:43
This class has functionality to detect potential collision with a nearby actor.
This class has functionality to maintain a horizon of waypoints ahead of the vehicle for it to follow...
This class holds the state of all the vehicles in the simlation.
This class has functionality for responding to traffic lights and managing entry into non-signalized ...
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
The function of this class is to integrate all the various stages of the traffic manager appropriatel...
void Reset(uint64_t episode_id)
To reset the traffic manager for the episode episode_id.
int registered_vehicles_state
State counter to track changes in registered actors.
LocalizationStage localization_stage
Various stages representing core operations of traffic manager.
TimePoint previous_update_instance
Time instance used to calculate dt in asynchronous mode.
void SetDistanceToLeadingVehicle(const ActorPtr &actor, const float distance)
Method to specify how much distance a vehicle should maintain to the leading vehicle.
void SetLaneOffset(const ActorPtr &actor, const float offset)
Method to set a lane offset displacement from the center line.
AtomicActorSet registered_vehicles
Set of all actors registered with traffic manager.
std::unique_ptr< std::thread > worker_thread
Single worker thread for sequential execution of sub-components.
void SetRespawnDormantVehicles(const bool mode_switch)
Method to set automatic respawn of dormant vehicles.
void SetRandomLeftLaneChangePercentage(const ActorPtr &actor, const float percentage)
Method to set % to randomly do a left lane change.
void SetGlobalPercentageSpeedDifference(float const percentage)
Method to set a global % decrease in velocity with respect to the speed limit.
void SetupLocalMap()
Method to setup InMemoryMap.
carla::client::detail::EpisodeProxy & GetEpisodeProxy()
Get CARLA episode information.
ControlFrame control_frame
Array to hold output data of motion planning.
Parameters parameters
Parameterization object.
std::vector< ActorId > vehicle_id_list
List of vehicles registered with the traffic manager in current update cycle.
bool CheckAllFrozen(TLGroup tl_to_freeze)
Method to check if all traffic lights are frozen in a group.
void UpdateImportedRoute(const ActorId &actor_id, const Route route)
Method to update an already set route.
void SetRandomRightLaneChangePercentage(const ActorPtr &actor, const float percentage)
Method to set % to randomly do a right lane change.
void SetPercentageIgnoreVehicles(const ActorPtr &actor, const float perc)
Method to specify the % chance of ignoring collisions with any vehicle.
BufferMap buffer_map
Structures to hold waypoint buffers for all vehicles.
void SetForceLaneChange(const ActorPtr &actor, const bool direction)
Method to force lane change on a vehicle.
void RemoveImportedRoute(const ActorId &actor_id, const bool remove_path)
Method to remove a route.
void SetKeepSlowLanePercentage(const ActorPtr &actor, const float percentage)
Method to set % to keep on the slow lane.
void SetBoundariesRespawnDormantVehicles(const float lower_bound, const float upper_bound)
Method to set boundaries to respawn of dormant vehicles.
TrackTraffic track_traffic
Object for tracking paths of the traffic vehicles.
TrafficManagerServer server
Traffic manager server instance.
Action GetNextAction(const ActorId &actor_id)
Method to get the vehicle's next action.
void UpdateUploadPath(const ActorId &actor_id, const Path path)
Method to update an already set list of points.
CollisionFrame collision_frame
Array to hold output data of collision avoidance.
rpc::EpisodeSettings episode_settings
Cached episode settings; they only change through world.apply_settings.
void SetHybridPhysicsMode(const bool mode_switch)
Method to set hybrid physics mode.
void SetCustomPath(const ActorPtr &actor, const Path path, const bool empty_buffer)
Method to set our own imported path.
void Run()
Initiates thread to run the TrafficManager sequentially.
TLFrame tl_frame
Array to hold output data of traffic light response.
void SetPercentageRunningLight(const ActorPtr &actor, const float perc)
Method to specify the % chance of running any traffic light.
uint64_t current_reserved_capacity
Variable to keep track of currently reserved array space for frames.
LocalizationFrame localization_frame
Array to hold output data of localization stage.
void SetPercentageRunningSign(const ActorPtr &actor, const float perc)
Method to specify the % chance of running any traffic sign.
void SetCollisionDetection(const ActorPtr &reference_actor, const ActorPtr &other_actor, const bool detect_collision)
Method to set collision detection rules between vehicles.
void SetOSMMode(const bool mode_switch)
Method to set Open Street Map mode.
ActionBuffer GetActionBuffer(const ActorId &actor_id)
Method to get the vehicle's action buffer.
cc::World world
CARLA client and object.
bool SynchronousTick()
Method to provide synchronous tick.
std::vector< ActorId > GetRegisteredVehiclesIDs()
Get list of all registered vehicles.
void SetImportedRoute(const ActorPtr &actor, const Route route, const bool empty_buffer)
Method to set our own imported route.
LocalMapPtr local_map
Pointer to local map cache.
void SetMaxBoundaries(const float lower, const float upper)
Method to set limits for boundaries when respawning dormant vehicles.
void SetPercentageSpeedDifference(const ActorPtr &actor, const float percentage)
Method to set a vehicle's % decrease in velocity with respect to the speed limit.
void SetGlobalLaneOffset(float const offset)
Method to set a global lane offset displacement from the center line.
void SetDesiredSpeed(const ActorPtr &actor, const float value)
Set a vehicle's exact desired velocity.
void SetAutoLaneChange(const ActorPtr &actor, const bool enable)
Enable/disable automatic lane change on a vehicle.
carla::client::detail::EpisodeProxy episode_proxy
CARLA client connection object.
void SetLargeVehicleWideTurn(const ActorPtr &actor, const bool enable)
Method to enable/disable the wide-turn manoeuvre for a single large vehicle.
void SetGlobalDistanceToLeadingVehicle(const float distance)
Method to specify how much distance a vehicle should maintain to the Global leading vehicle.
std::atomic< bool > run_traffic_manger
Switch to turn on / turn off traffic manager.
std::unordered_map< ActorId, std::pair< float, bool > > large_vehicles
RandomGenerator random_device
Structure holding random devices per vehicle.
SimulationState simulation_state
Type containing the current state of all actors involved in the simulation.
void RemoveUploadPath(const ActorId &actor_id, const bool remove_path)
Method to remove a list of points.
uint64_t unwaited_control_batches
Starts at the limit so the first batch of an episode is waited for.
void SetPercentageIgnoreWalkers(const ActorPtr &actor, const float perc)
Method to specify the % chance of ignoring collisions with any walker.
std::vector< float > longitudinal_PID_parameters
PID controller parameters.
void SetUpdateVehicleLights(const ActorPtr &actor, const bool do_update)
Method to set the automatic management of the vehicle lights.
double last_settings_update
Simulation time of the last episode settings refresh.
void RegisterVehicles(const std::vector< ActorPtr > &actor_list)
This method registers a vehicle with the traffic manager.
void UnregisterVehicles(const std::vector< ActorPtr > &actor_list)
This method unregisters a vehicle from traffic manager.
void SetGlobalLargeVehicleWideTurn(const bool enable)
Method to enable/disable the wide-turn manoeuvre globally for large vehicles.
void SetSynchronousMode(bool mode)
Method to switch traffic manager into synchronous execution.
void SetHybridPhysicsRadius(const float radius)
Method to set hybrid physics radius.
void Release()
To release the traffic manager.
void SetRandomDeviceSeed(const uint64_t _seed)
Method to set randomization seed.
void Step()
To do one step of the TrafficManager.
std::mutex registration_mutex
Mutex to prevent vehicle registration during frame array re-allocation.
void SetSynchronousModeTimeOutInMiliSecond(double time)
Method to set Tick timeout for synchronous execution.
This class has functionality for turning on/off the vehicle lights according to the current vehicle s...
std::shared_ptr< InMemoryMap > LocalMapPtr
Definition ALSM.h:38
std::vector< carla::SharedPtr< carla::client::TrafficLight > > TLGroup
std::vector< uint8_t > Route
std::unordered_map< carla::ActorId, Buffer > BufferMap
std::vector< cg::Location > Path
std::vector< CollisionHazardData > CollisionFrame
std::vector< bool > TLFrame
std::pair< RoadOption, WaypointPtr > Action
std::vector< carla::rpc::Command > ControlFrame
chr::time_point< chr::system_clock, chr::nanoseconds > TimePoint
carla::SharedPtr< cc::Actor > ActorPtr
std::vector< Action > ActionBuffer
std::vector< LocalizationData > LocalizationFrame
This file contains definitions of common data structures used in traffic manager.