CARLA
Loading...
Searching...
No Matches
CarlaEpisode.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
18
22#if WITH_ROS2
23 #include <carla/ros2/ROS2.h>
24#endif
25#include <carla/rpc/Actor.h>
30
31#include <util/ue-header-guard-begin.h>
32#include "GameFramework/Pawn.h"
33#include "Materials/MaterialParameterCollectionInstance.h"
34#include <util/ue-header-guard-end.h>
35
36#include "CarlaEpisode.generated.h"
37
38class AWalkerBase;
39
40/// A simulation episode.
41///
42/// Each time the level is restarted a new episode is created.
43UCLASS(BlueprintType, Blueprintable)
44class CARLA_API UCarlaEpisode : public UObject
45{
46 GENERATED_BODY()
47
48 // ===========================================================================
49 // -- Constructor ------------------------------------------------------------
50 // ===========================================================================
51
52public:
53
54 UCarlaEpisode(const FObjectInitializer &ObjectInitializer);
55
56 // ===========================================================================
57 // -- Load a new episode -----------------------------------------------------
58 // ===========================================================================
59
60 /// Load a new map and start a new episode.
61 ///
62 /// If @a MapString is empty, the current map is reloaded.
63 UFUNCTION(BlueprintCallable)
64 bool LoadNewEpisode(const FString &MapString, bool ResetSettings = true);
65
66 /// Load a new map generating the mesh from OpenDRIVE data and
67 /// start a new episode.
68 ///
69 /// If @a MapString is empty, it fails.
71 const FString &OpenDriveString,
73
74 // ===========================================================================
75 // -- Episode settings -------------------------------------------------------
76 // ===========================================================================
77
78 UFUNCTION(BlueprintCallable)
80 {
81 return EpisodeSettings;
82 }
83
84 UFUNCTION(BlueprintCallable)
85 void ApplySettings(const FEpisodeSettings &Settings);
86
87 // ===========================================================================
88 // -- Retrieve info about this episode ---------------------------------------
89 // ===========================================================================
90
91 /// Return the unique id of this episode.
92 auto GetId() const
93 {
94 return Id;
95 }
96
97 /// Return the name of the map loaded in this episode.
98 UFUNCTION(BlueprintCallable)
99 /// Block (game thread, bounded) until the RecastBuilder run started by the
100 /// last generate_opendrive_world has finished. Returns whether the navmesh
101 /// was built (true when no build is pending).
102 static bool WaitForPendingNavigationBuild(double TimeoutSeconds);
103
104 /// Delete Saved/OpenDrive|Nav/OpenDriveMap.* left by a previous generated
105 /// world (server startup and before each generation).
106 static void ClearGeneratedWorldFiles();
107
108 const FString &GetMapName() const
109 {
110 return MapName;
111 }
112
113 /// Game seconds since the start of this episode.
114 double GetElapsedGameTime() const
115 {
116 return ElapsedGameTime;
117 }
118
119 /// Visual game seconds
120 double GetVisualGameTime() const
121 {
122 return VisualGameTime;
123 }
124
125 void SetVisualGameTime(double Time)
126 {
127 VisualGameTime = Time;
128
129 // update time in material parameters also
131 {
132 MaterialParameters->SetScalarParameterValue(FName("VisualTime"), VisualGameTime);
133 }
134 }
135
136 /// Return the list of actor definitions that are available to be spawned this
137 /// episode.
138 UFUNCTION(BlueprintCallable)
140 {
141 return ActorDispatcher->GetActorDefinitions();
142 }
143
144 /// Return the list of recommended spawn points for vehicles.
145 UFUNCTION(BlueprintCallable)
146 TArray<FTransform> GetRecommendedSpawnPoints() const;
147
148 /// Return the geo projection of the map loaded
150 {
151 return MapGeoProjection;
152 }
153
154 // ===========================================================================
155 // -- Retrieve special actors ------------------------------------------------
156 // ===========================================================================
157
158 UFUNCTION(BlueprintCallable)
160 {
161 return Spectator;
162 }
163
164 UFUNCTION(BlueprintCallable)
166 {
167 return Weather;
168 }
169
171 {
172 return ActorDispatcher->GetActorRegistry();
173 }
174
176 {
177 return ActorDispatcher->GetActorRegistry();
178 }
179
180 // ===========================================================================
181 // -- Actor look up methods --------------------------------------------------
182 // ===========================================================================
183
184 /// Find a Carla actor by id.
185 ///
186 /// If the actor is not found or is pending kill, the returned view is
187 /// invalid.
189 {
190 return ActorDispatcher->GetActorRegistry().FindCarlaActor(ActorId);
191 }
192
193 /// Find the actor view of @a Actor.
194 ///
195 /// If the actor is not found or is pending kill, the returned view is
196 /// invalid.
198 {
199 return ActorDispatcher->GetActorRegistry().FindCarlaActor(Actor);
200 }
201
202 /// Get the description of the Carla actor (sensor) using specific stream id.
203 ///
204 /// If the actor is not found returns an empty string
206 {
207 return ActorDispatcher->GetActorRegistry().GetDescriptionFromStream(StreamId);
208 }
209
210 /// Find the Carla actor (sensor) that owns the stream @a StreamId, or nullptr.
212 {
213 return ActorDispatcher->GetActorRegistry().FindCarlaActorFromStream(StreamId);
214 }
215
216 // ===========================================================================
217 // -- Actor handling methods -------------------------------------------------
218 // ===========================================================================
219
220 /// Spawns an actor based on @a ActorDescription at @a Transform. To properly
221 /// despawn an actor created with this function call DestroyActor.
222 ///
223 /// @return A pair containing the result of the spawn function and a view over
224 /// the actor and its properties. If the status is different of Success the
225 /// view is invalid.
226 TPair<EActorSpawnResultStatus, FCarlaActor*> SpawnActorWithInfo(
227 const FTransform &Transform,
228 FActorDescription thisActorDescription,
229 FCarlaActor::IdType DesiredId = 0);
230
231 /// Spawns an actor based on @a ActorDescription at @a Transform.
232 ///
233 /// @return the actor to be spawned
235 const FTransform &Transform,
236 FActorDescription thisActorDescription)
237 {
238 FTransform NewTransform = Transform;
239 auto result = ActorDispatcher->ReSpawnActor(NewTransform, thisActorDescription);
240 if (Recorder->IsEnabled())
241 {
242 // do something?
243 }
244
245 return result;
246 }
247
248 /// Spawns an actor based on @a ActorDescription at @a Transform. To properly
249 /// despawn an actor created with this function call DestroyActor.
250 ///
251 /// @return nullptr on failure.
252 ///
253 /// @note Special overload for blueprints.
254 UFUNCTION(BlueprintCallable)
256 const FTransform &Transform,
257 FActorDescription ActorDescription)
258 {
259 return SpawnActorWithInfo(Transform, std::move(ActorDescription)).Value->GetActor();
260 }
261
262 /// Attach @a Child to @a Parent.
263 ///
264 /// @pre Actors cannot be null.
265 UFUNCTION(BlueprintCallable)
266 void AttachActors(
267 AActor *Child,
268 AActor *Parent,
269 EAttachmentType InAttachmentType = EAttachmentType::Rigid);
270
271 /// @copydoc FActorDispatcher::DestroyActor(AActor*)
272 UFUNCTION(BlueprintCallable)
273 bool DestroyActor(AActor *Actor)
274 {
275 FCarlaActor* CarlaActor = FindCarlaActor(Actor);
276 if (CarlaActor)
277 {
278 carla::rpc::ActorId ActorId = CarlaActor->GetActorId();
279 return DestroyActor(ActorId);
280 }
281 return false;
282 }
283
285 {
287 {
288 GetFrameData().AddEvent(
289 CarlaRecorderEventDel{ActorId});
290 }
291 if (Recorder->IsEnabled())
292 {
293 // recorder event
294 CarlaRecorderEventDel RecEvent{ActorId};
295 Recorder->AddEvent(std::move(RecEvent));
296 }
297
298 return ActorDispatcher->DestroyActor(ActorId);
299 }
300
301 /// SerializeActor, with the ids the primary's clients know on a Multi-GPU
302 /// secondary (for data a sensor streams to them).
303 carla::rpc::Actor SerializeActorWithPrimaryIds(AActor *Actor) const;
304
305 /// ROS 2: registers the ros_name of each of @a Child's ancestors as one of
306 /// its parent frames.
307 void AddRosParentNames(FCarlaActor &Child);
308
310 {
311 ActorDispatcher->PutActorToSleep(ActorId, this);
312 }
313
315 {
316 ActorDispatcher->WakeActorUp(ActorId, this);
317 }
318
319 // ===========================================================================
320 // -- Other methods ----------------------------------------------------------
321 // ===========================================================================
322
323 /// Create a serializable object describing the actor.
324 carla::rpc::Actor SerializeActor(FCarlaActor* CarlaActor) const;
325
326 /// Create a serializable object describing the actor.
327 /// Can be used to serialized actors that are not in the registry
328 carla::rpc::Actor SerializeActor(AActor* Actor) const;
329
330 // ===========================================================================
331 // -- Private methods and members --------------------------------------------
332 // ===========================================================================
333
335 {
336 return Recorder;
337 }
338
340 {
341 Recorder = Rec;
342 }
343
345 {
346 return Recorder->GetReplayer();
347 }
348
349 std::string StartRecorder(std::string name, bool AdditionalData, bool StopReplayer);
350
351 FIntVector GetCurrentMapOrigin() const { return CurrentMapOrigin; }
352
353 void SetCurrentMapOrigin(const FIntVector& NewOrigin) { CurrentMapOrigin = NewOrigin; }
354
356
357 /// Multi-GPU primary: the world state the frames sent so far carried.
359
360 /// A scene light changed: Multi-GPU secondaries get its new state.
361 void MarkSceneLightChanged(int32 LightId)
362 {
364 {
365 MultiGpuWorldState.ChangedLights.Add(LightId);
366 }
367 }
368
370
371 // ===========================================================================
372 // -- Pedestrian navigation state (server-side walker navigation) -------------
373 // ===========================================================================
374
375 /// Probability that a walker whose navigation starts after this call is a
376 /// "crosser" (may traverse crosswalk/road nav areas). Legacy semantics of
377 /// carla.World.set_pedestrians_cross_factor.
378 void SetPedestriansCrossFactor(float InCrossFactor)
379 {
380 PedestriansCrossFactor = FMath::Clamp(InCrossFactor, 0.0f, 1.0f);
381 }
382
383 /// Seed the RNG behind the crosser draw (and any future navigation
384 /// randomness). Deterministic given the same seed and start order.
385 void SetPedestriansSeed(uint32 InSeed)
386 {
387 PedestriansNavRNG.Initialize(static_cast<int32>(InSeed));
388 }
389
390 /// Draw once per walker at navigation start: crosser or not.
392 {
394 }
395
396 bool bIsPrimaryServer = true;
397
398private:
399
400 friend class ACarlaGameModeBase;
402 friend class FCarlaEngine;
403
405
406 void EndPlay();
407
408 /// True if the centre of @a Walker's capsule is inside the collision of a
409 /// building or wall, where physics would push the walker out through the
410 /// terrain (#10212).
411 bool IsWalkerInsideBuilding(const AWalkerBase &Walker) const;
412
414 {
415 ActorDispatcher->Bind(ActorFactory);
416 }
417
418 std::pair<int, FCarlaActor&> TryToCreateReplayerActor(
419 FVector &Location,
420 FVector &Rotation,
421 FActorDescription &ActorDesc,
422 unsigned int desiredId);
423
424 bool SetActorSimulatePhysics(FCarlaActor &CarlaActor, bool bEnabled);
425
426 bool SetActorCollisions(FCarlaActor &CarlaActor, bool bEnabled);
427
428 bool SetActorDead(FCarlaActor &CarlaActor);
429
430 void TickTimers(float DeltaSeconds)
431 {
432 ElapsedGameTime += DeltaSeconds;
433 SetVisualGameTime(VisualGameTime + DeltaSeconds);
434 #if defined(WITH_ROS2)
435 auto ROS2 = carla::ros2::ROS2::GetInstance();
436 if (ROS2->IsEnabled())
437 ROS2->SetTimestamp(GetElapsedGameTime());
438 #endif
439
440 }
441
442 /// Multi-GPU secondary: adopt the primary's clocks for the frame being
443 /// played. Absolute, not accumulated, so frames a secondary never played
444 /// (while it was loading) cause no drift.
445 void SetTimers(double InElapsedGameTime, double InVisualGameTime)
446 {
447 ElapsedGameTime = InElapsedGameTime;
448 SetVisualGameTime(InVisualGameTime);
449 #if defined(WITH_ROS2)
450 auto ROS2 = carla::ros2::ROS2::GetInstance();
451 if (ROS2->IsEnabled())
452 ROS2->SetTimestamp(GetElapsedGameTime());
453 #endif
454 }
455
456 const uint64 Id = 0u;
457
458 // simulation time
459 double ElapsedGameTime = 0.0;
460
461 // visual time (used by clounds and other FX that need to be deterministic)
462 double VisualGameTime = 0.0;
463
464 UPROPERTY(VisibleAnywhere)
465 FString MapName;
466
467 UPROPERTY(VisibleAnywhere)
469
470 UPROPERTY(VisibleAnywhere)
472
473 UPROPERTY(VisibleAnywhere)
474 APawn *Spectator = nullptr;
475
476 UPROPERTY(VisibleAnywhere)
477 AWeather *Weather = nullptr;
478
479 UPROPERTY(VisibleAnywhere)
480 UMaterialParameterCollectionInstance *MaterialParameters = nullptr;
481
483
485
487
489
490 FRandomStream PedestriansNavRNG = FRandomStream(0);
491
493
495
497};
498
500 const TSet<carla::rpc::CityObjectLabel> &SemanticTags);
EAttachmentType
FString CarlaGetRelevantTagAsString(const TSet< crp::CityObjectLabel > &SemanticTags)
Base class for Carla actor factories.
Recorder for the simulation.
A registry of all the Carla actors.
A view over an actor and its properties.
Definition CarlaActor.h:25
uint32 IdType
Definition CarlaActor.h:28
IdType GetActorId() const
Definition CarlaActor.h:81
Euler angles of a rotation in CARLA's / Unreal's left-handed frame: x forward, y right,...
Definition Rotation.h:45
A rigid transform in CARLA's / Unreal's left-handed frame: x forward, y right, z up,...
Object in charge of binding ActorDefinitions to spawn functions, as well as keeping the registry of a...
AWeather * Weather
FIntVector GetCurrentMapOrigin() const
auto GetId() const
Return the unique id of this episode.
FFrameData & GetFrameData()
FPrimaryWorldState & GetMultiGpuWorldState()
Multi-GPU primary: the world state the frames sent so far carried.
double GetVisualGameTime() const
Visual game seconds.
FEpisodeSettings EpisodeSettings
bool SetActorSimulatePhysics(FCarlaActor &CarlaActor, bool bEnabled)
CarlaReplayer * GetReplayer() const
void PutActorToSleep(carla::rpc::ActorId ActorId)
void SetCurrentMapOrigin(const FIntVector &NewOrigin)
AActor * SpawnActor(const FTransform &Transform, FActorDescription ActorDescription)
Spawns an actor based on ActorDescription at Transform.
UCarlaEpisode(const FObjectInitializer &ObjectInitializer)
void SetPedestriansCrossFactor(float InCrossFactor)
Probability that a walker whose navigation starts after this call is a "crosser" (may traverse crossw...
FIntVector CurrentMapOrigin
bool LoadNewOpendriveEpisode(const FString &OpenDriveString, const carla::rpc::OpendriveGenerationParameters &Params)
Load a new map generating the mesh from OpenDRIVE data and start a new episode.
const TArray< FActorDefinition > & GetActorDefinitions() const
Return the list of actor definitions that are available to be spawned this episode.
FRandomStream PedestriansNavRNG
FCarlaActor * FindCarlaActor(FCarlaActor::IdType ActorId)
Find a Carla actor by id.
FCarlaActor * FindCarlaActor(AActor *Actor) const
Find the actor view of Actor.
UActorDispatcher * ActorDispatcher
const FString & GetMapName() const
AWeather * GetWeather() const
void SetPedestriansSeed(uint32 InSeed)
Seed the RNG behind the crosser draw (and any future navigation randomness).
const uint64 Id
FPrimaryWorldState MultiGpuWorldState
float PedestriansCrossFactor
void RegisterActorFactory(ACarlaActorFactory &ActorFactory)
double GetElapsedGameTime() const
Game seconds since the start of this episode.
FSensorManager SensorManager
FString GetActorDescriptionFromStream(carla::streaming::detail::stream_id_type StreamId)
Get the description of the Carla actor (sensor) using specific stream id.
bool DestroyActor(carla::rpc::ActorId ActorId)
TPair< EActorSpawnResultStatus, FCarlaActor * > SpawnActorWithInfo(const FTransform &Transform, FActorDescription thisActorDescription, FCarlaActor::IdType DesiredId=0)
Spawns an actor based on ActorDescription at Transform.
UMaterialParameterCollectionInstance * MaterialParameters
APawn * Spectator
bool IsWalkerInsideBuilding(const AWalkerBase &Walker) const
True if the centre of Walker's capsule is inside the collision of a building or wall,...
friend class ACarlaGameModeBase
ACarlaRecorder * Recorder
const FEpisodeSettings & GetSettings() const
void SetRecorder(ACarlaRecorder *Rec)
void InitializeAtBeginPlay()
AActor * ReSpawnActorWithInfo(const FTransform &Transform, FActorDescription thisActorDescription)
Spawns an actor based on ActorDescription at Transform.
void SetTimers(double InElapsedGameTime, double InVisualGameTime)
Multi-GPU secondary: adopt the primary's clocks for the frame being played.
std::pair< int, FCarlaActor & > TryToCreateReplayerActor(FVector &Location, FVector &Rotation, FActorDescription &ActorDesc, unsigned int desiredId)
void MarkSceneLightChanged(int32 LightId)
A scene light changed: Multi-GPU secondaries get its new state.
void TickTimers(float DeltaSeconds)
bool SetActorCollisions(FCarlaActor &CarlaActor, bool bEnabled)
carla::geom::GeoProjection MapGeoProjection
bool SetActorDead(FCarlaActor &CarlaActor)
FCarlaActor * FindCarlaActorFromStream(carla::streaming::detail::stream_id_type StreamId)
Find the Carla actor (sensor) that owns the stream StreamId, or nullptr.
APawn * GetSpectatorPawn() const
void SetVisualGameTime(double Time)
const FActorRegistry & GetActorRegistry() const
ACarlaRecorder * GetRecorder() const
FSensorManager & GetSensorManager()
bool DrawWalkerIsCrosser()
Draw once per walker at navigation start: crosser or not.
FFrameData FrameData
double VisualGameTime
FActorRegistry & GetActorRegistry()
bool LoadNewEpisode(const FString &MapString, bool ResetSettings=true)
Load a new map and start a new episode.
const carla::geom::GeoProjection & GetGeoProjection() const
Return the geo projection of the map loaded.
double ElapsedGameTime
friend class AAutowareGameModeBase
friend class FCarlaEngine
bool DestroyActor(AActor *Actor)
void WakeActorUp(carla::rpc::ActorId ActorId)
static std::shared_ptr< ROS2 > GetInstance()
Definition ROS2.h:61
uint32_t ActorId
Definition ActorId.h:14
This file contains definitions of common data structures used in traffic manager.
A definition of a Carla Actor with all the variation and attributes.
A description of a Carla Actor with all its variation.
What a Multi-GPU primary remembers between the frames it sends, to send the world state only when it ...
Definition FrameData.h:106
Seting for map generation from opendrive without additional geometry.