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"
21
30
36
37namespace carla {
38namespace traffic_manager {
39
40namespace chr = std::chrono;
41
42using namespace std::chrono_literals;
43
44using TimePoint = chr::time_point<chr::system_clock, chr::nanoseconds>;
45using TLGroup = std::vector<carla::SharedPtr<carla::client::TrafficLight>>;
46using LocalMapPtr = std::shared_ptr<InMemoryMap>;
47using constants::HybridMode::HYBRID_MODE_DT;
48
49/// The function of this class is to integrate all the various stages of
50/// the traffic manager appropriately using messengers.
52
53private:
54 /// PID controller parameters.
55 std::vector<float> longitudinal_PID_parameters;
57 std::vector<float> lateral_PID_parameters;
59 /// CARLA client connection object.
61 /// CARLA client and object.
62 cc::World world;
63 /// Set of all actors registered with traffic manager.
65 // Set containing the ids of the registered large vehicles
66 std::unordered_map<ActorId, std::pair<float, bool>> large_vehicles;
67 /// State counter to track changes in registered actors.
69 /// List of vehicles registered with the traffic manager in
70 /// current update cycle.
71 std::vector<ActorId> vehicle_id_list;
72 /// Pointer to local map cache.
74 /// Structures to hold waypoint buffers for all vehicles.
76 /// Object for tracking paths of the traffic vehicles.
78 /// Type containing the current state of all actors involved in the simulation.
80 /// Time instance used to calculate dt in asynchronous mode.
82 /// Parameterization object.
84 /// Array to hold output data of localization stage.
86 /// Array to hold output data of collision avoidance.
88 /// Array to hold output data of traffic light response.
90 /// Array to hold output data of motion planning.
92 /// Variable to keep track of currently reserved array space for frames.
94 /// Various stages representing core operations of traffic manager.
101 /// Traffic manager server instance.
103 /// Switch to turn on / turn off traffic manager.
104 std::atomic<bool> run_traffic_manger{true};
105 /// Single worker thread for sequential execution of sub-components.
106 std::unique_ptr<std::thread> worker_thread;
107 /// Last processed frame
108 size_t last_frame{0};
109 /// Starts at the limit so the first batch of an episode is waited for.
111 constants::WorldInfoRefresh::MAX_UNWAITED_CONTROL_BATCHES};
112 /// Randomization seed.
113 uint64_t seed {static_cast<uint64_t>(time(NULL))};
114 /// Structure holding random devices per vehicle.
116 std::vector<ActorId> marked_for_removal;
117 /// Mutex to prevent vehicle registration during frame array re-allocation.
119
120 /// Method to check if all traffic lights are frozen in a group.
121 bool CheckAllFrozen(TLGroup tl_to_freeze);
122
123public:
124 /// Private constructor for singleton lifecycle management.
126 std::vector<float> longitudinal_highway_PID_parameters,
127 std::vector<float> lateral_PID_parameters,
128 std::vector<float> lateral_highway_PID_parameters,
129 float perc_decrease_from_limit,
130 cc::detail::EpisodeProxy &episode_proxy,
131 uint16_t &RPCportTM);
132
133 /// Destructor.
134 virtual ~TrafficManagerLocal();
135
136 /// Method to setup InMemoryMap.
137 void SetupLocalMap();
138
139 /// To start the TrafficManager.
140 void Start();
141
142 /// To do one step of the TrafficManager.
143 void Step();
144
145 /// Initiates thread to run the TrafficManager sequentially.
146 void Run();
147
148 /// To stop the TrafficManager.
149 void Stop();
150
151 /// To release the traffic manager.
152 void Release();
153
154 /// To reset the traffic manager for the episode @a episode_id.
155 void Reset(uint64_t episode_id);
156
157 std::vector<ActorPtr> TakeReleasedActors() {
159 }
160
161 /// This method registers a vehicle with the traffic manager.
162 void RegisterVehicles(const std::vector<ActorPtr> &actor_list);
163
164 /// This method unregisters a vehicle from traffic manager.
165 void UnregisterVehicles(const std::vector<ActorPtr> &actor_list);
166
167 /// Method to set a vehicle's % decrease in velocity with respect to the speed limit.
168 /// If less than 0, it's a % increase.
169 void SetPercentageSpeedDifference(const ActorPtr &actor, const float percentage);
170
171 /// Set a vehicle's exact desired velocity.
172 void SetDesiredSpeed(const ActorPtr &actor, const float value);
173
174 /// Method to set a global % decrease in velocity with respect to the speed limit.
175 /// If less than 0, it's a % increase.
176 void SetGlobalPercentageSpeedDifference(float const percentage);
177
178 /// Method to set a lane offset displacement from the center line.
179 /// Positive values imply a right offset while negative ones mean a left one.
180 void SetLaneOffset(const ActorPtr &actor, const float offset);
181
182 /// Method to set a global lane offset displacement from the center line.
183 /// Positive values imply a right offset while negative ones mean a left one.
184 void SetGlobalLaneOffset(float const offset);
185
186 /// Method to enable/disable the wide-turn manoeuvre for a single large vehicle.
187 void SetLargeVehicleWideTurn(const ActorPtr &actor, const bool enable);
188
189 /// Method to enable/disable the wide-turn manoeuvre globally for large vehicles.
190 void SetGlobalLargeVehicleWideTurn(const bool enable);
191
192 /// Method to set the automatic management of the vehicle lights
193 void SetUpdateVehicleLights(const ActorPtr &actor, const bool do_update);
194
195 /// Method to set collision detection rules between vehicles.
196 void SetCollisionDetection(const ActorPtr &reference_actor, const ActorPtr &other_actor, const bool detect_collision);
197
198 /// Method to force lane change on a vehicle.
199 /// Direction flag can be set to true for left and false for right.
200 void SetForceLaneChange(const ActorPtr &actor, const bool direction);
201
202 /// Enable/disable automatic lane change on a vehicle.
203 void SetAutoLaneChange(const ActorPtr &actor, const bool enable);
204
205 /// Method to specify how much distance a vehicle should maintain to
206 /// the leading vehicle.
207 void SetDistanceToLeadingVehicle(const ActorPtr &actor, const float distance);
208
209 /// Method to specify the % chance of ignoring collisions with any walker.
210 void SetPercentageIgnoreWalkers(const ActorPtr &actor, const float perc);
211
212 /// Method to specify the % chance of ignoring collisions with any vehicle.
213 void SetPercentageIgnoreVehicles(const ActorPtr &actor, const float perc);
214
215 /// Method to specify the % chance of running any traffic light.
216 void SetPercentageRunningLight(const ActorPtr &actor, const float perc);
217
218 /// Method to specify the % chance of running any traffic sign.
219 void SetPercentageRunningSign(const ActorPtr &actor, const float perc);
220
221 /// Method to switch traffic manager into synchronous execution.
222 void SetSynchronousMode(bool mode);
223
224 /// Method to set Tick timeout for synchronous execution.
226
227 /// Method to provide synchronous tick.
228 bool SynchronousTick();
229
230 /// Get CARLA episode information.
232
233 /// Get list of all registered vehicles.
234 std::vector<ActorId> GetRegisteredVehiclesIDs();
235
236 /// Method to specify how much distance a vehicle should maintain to
237 /// the Global leading vehicle.
238 void SetGlobalDistanceToLeadingVehicle(const float distance);
239
240 /// Method to set % to keep on the slow lane.
241 void SetKeepSlowLanePercentage(const ActorPtr &actor, const float percentage);
242
243 /// Method to set % to randomly do a left lane change.
244 void SetRandomLeftLaneChangePercentage(const ActorPtr &actor, const float percentage);
245
246 /// Method to set % to randomly do a right lane change.
247 void SetRandomRightLaneChangePercentage(const ActorPtr &actor, const float percentage);
248
249 /// Method to set hybrid physics mode.
250 void SetHybridPhysicsMode(const bool mode_switch);
251
252 /// Method to set hybrid physics radius.
253 void SetHybridPhysicsRadius(const float radius);
254
255 /// Method to set randomization seed.
256 void SetRandomDeviceSeed(const uint64_t _seed);
257
258 /// Method to set Open Street Map mode.
259 void SetOSMMode(const bool mode_switch);
260
261 /// Method to set our own imported path.
262 void SetCustomPath(const ActorPtr &actor, const Path path, const bool empty_buffer);
263
264 /// Method to remove a list of points.
265 void RemoveUploadPath(const ActorId &actor_id, const bool remove_path);
266
267 /// Method to update an already set list of points.
268 void UpdateUploadPath(const ActorId &actor_id, const Path path);
269
270 /// Method to set our own imported route.
271 void SetImportedRoute(const ActorPtr &actor, const Route route, const bool empty_buffer);
272
273 /// Method to remove a route.
274 void RemoveImportedRoute(const ActorId &actor_id, const bool remove_path);
275
276 /// Method to update an already set route.
277 void UpdateImportedRoute(const ActorId &actor_id, const Route route);
278
279 /// Method to get the vehicle's next action.
280 Action GetNextAction(const ActorId &actor_id);
281
282 /// Method to get the vehicle's action buffer.
283 ActionBuffer GetActionBuffer(const ActorId &actor_id);
284
285 void ShutDown() {};
286};
287
288} // namespace traffic_manager
289} // namespace carla
ALSM: Agent Lifecycle and State Managerment This class has functionality to update the local cache of...
Definition ALSM.h:43
std::vector< ActorPtr > TakeReleased()
Actors removed since the last call; drop them with no lock held.
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 ...
TrafficManagerBase()
Protected constructor for singleton lifecycle management.
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.
std::vector< ActorPtr > TakeReleasedActors()
Vehicles released since the last call; the caller drops them with no TM lock held.
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 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.
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.
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.
TrafficManagerLocal(std::vector< float > longitudinal_PID_parameters, std::vector< float > longitudinal_highway_PID_parameters, std::vector< float > lateral_PID_parameters, std::vector< float > lateral_highway_PID_parameters, float perc_decrease_from_limit, cc::detail::EpisodeProxy &episode_proxy, uint16_t &RPCportTM)
Private constructor for singleton lifecycle management.
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 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.
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...
EpisodeProxyImpl< EpisodeProxyPointerType::Strong > EpisodeProxy
carla::SharedPtr< cc::Actor > ActorPtr
std::vector< uint8_t > Route
std::vector< cg::Location > Path
std::vector< carla::rpc::Command > ControlFrame
std::vector< bool > TLFrame
std::vector< Action > ActionBuffer
std::vector< CollisionHazardData > CollisionFrame
std::shared_ptr< InMemoryMap > LocalMapPtr
Definition ALSM.h:38
std::pair< RoadOption, WaypointPtr > Action
chr::time_point< chr::system_clock, chr::nanoseconds > TimePoint
std::vector< LocalizationData > LocalizationFrame
std::unordered_map< carla::ActorId, Buffer > BufferMap
std::vector< carla::SharedPtr< carla::client::TrafficLight > > TLGroup
This file contains definitions of common data structures used in traffic manager.