CARLA
Loading...
Searching...
No Matches
CarlaEngine.cpp
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
8#include "Carla.h"
23#include "Carla/Sensor/Sensor.h"
24
26#include <carla/Logging.h>
27#include <carla/MsgPack.h>
33#include <carla/ros2/ROS2.h>
40
41#include <util/ue-header-guard-begin.h>
42#include "Engine/Engine.h"
43#include "Engine/GameViewportClient.h"
44#include "EngineUtils.h"
45#include "GameFramework/WorldSettings.h"
46#include "HAL/FileManager.h"
47#include "HAL/IConsoleManager.h"
48#include "HAL/PlatformProcess.h"
49#include "HAL/ThreadHeartBeat.h"
50#include "UObject/UObjectGlobals.h"
51#include "HAL/PlatformTime.h"
52#include "Misc/App.h"
53#include "Misc/FileHelper.h"
54#include "Misc/Paths.h"
55#include "PhysicsEngine/PhysicsSettings.h"
56#include "SceneInterface.h"
57#include "Engine/Engine.h"
58#include "Engine/GameViewportClient.h"
59#include <util/ue-header-guard-end.h>
60
61#include <cstdlib>
62#include <cstring>
63#include <optional>
64#include <thread>
65
66// =============================================================================
67// -- Static local methods -----------------------------------------------------
68// =============================================================================
69
70// init static variables
72
74{
75 return std::max(std::thread::hardware_concurrency(), 4u) - 2u;
76}
77
78#if !UE_BUILD_SHIPPING
79static TAutoConsoleVariable<int32> CVarCarlaMultiGpuVerifyFrames(
80 TEXT("carla.MultiGpu.VerifyFrames"),
81 1,
82 TEXT("Multi-GPU primary: read every frame sent to the secondaries back and log an error when it ")
83 TEXT("does not parse completely with this build (1 = on, 0 = off)."),
84 ECVF_Default);
85#endif // !UE_BUILD_SHIPPING
86
87static TOptional<double> FCarlaEngine_GetFixedDeltaSeconds()
88{
89 return FApp::IsBenchmarking() ? FApp::GetFixedDeltaTime() : TOptional<double>{};
90}
91
92static void FCarlaEngine_SetFixedDeltaSeconds(TOptional<double> FixedDeltaSeconds)
93{
94 FApp::SetBenchmarking(FixedDeltaSeconds.IsSet());
95 FApp::SetFixedDeltaTime(FixedDeltaSeconds.Get(0.0));
96}
97
98/// Whether a travel to another map is scheduled for @a World: load_world()
99/// only schedules it, and the engine performs it at the start of the next
100/// engine frame, before ticking any world.
101static bool FCarlaEngine_IsWorldTravelPending(const UWorld *World)
102{
103 const FWorldContext *Context = (GEngine && World) ? GEngine->GetWorldContextFromWorld(World) : nullptr;
104 return (Context != nullptr) && !Context->TravelURL.IsEmpty();
105}
106
123
124/// Multi-GPU secondary: the world the primary generated from OpenDRIVE, where
125/// this server's OpenDriveMap reads it and with the same parameters, before
126/// the map opens; for any other map, no generated world of an earlier load.
128{
129 const FString XODRPath = UOpenDrive::GetSavedXODRPath(TEXT("OpenDriveMap"));
130 IFileManager::Get().Delete(*XODRPath, false, true, true);
131 if (!Extras.opendrive)
132 {
133 return;
134 }
135 TArray<uint8> OpenDrive;
136 OpenDrive.Append(reinterpret_cast<const uint8 *>(Extras.opendrive->data()),
137 static_cast<int32>(Extras.opendrive->size()));
138 if (!FFileHelper::SaveArrayToFile(OpenDrive, *XODRPath))
139 {
140 UE_LOG(LogCarla, Error, TEXT("Multi-GPU: cannot write the primary's OpenDRIVE world to %s"), *XODRPath);
141 return;
142 }
144 if ((GameInstance == nullptr) || !Extras.generation_parameters)
145 {
146 return;
147 }
148 try
149 {
152 reinterpret_cast<const unsigned char *>(Extras.generation_parameters->data()),
153 Extras.generation_parameters->size()));
154 }
155 catch (const std::exception &e)
156 {
157 UE_LOG(LogCarla, Error, TEXT("Multi-GPU: the primary's OpenDRIVE generation parameters do not read: %s"),
158 UTF8_TO_TCHAR(e.what()));
159 }
160}
161
162// =============================================================================
163// -- FCarlaEngine -------------------------------------------------------------
164// =============================================================================
165
167{
168 // The command callback captures this engine and outlives it otherwise
169 // (Secondary is kept alive by its own commander).
170 if (Secondary)
171 {
172 Secondary->Stop();
173 // OnBeginFrame took over the process-wide time step; give it back (the
174 // editor keeps running after a PIE secondary ends).
175 FApp::SetUseFixedTimeStep(false);
176 // The generated worlds the primary sent are of no use to anyone else.
177 IFileManager::Get().DeleteDirectory(
178 *FPaths::GetPath(UOpenDrive::GetSavedXODRPath(TEXT("OpenDriveMap"))), false, true);
180 }
181 if (bIsRunning)
182 {
183 #if defined(WITH_ROS2)
184 auto ROS2 = carla::ros2::ROS2::GetInstance();
185 if (ROS2->IsEnabled())
186 ROS2->Shutdown();
187 #endif
188 FWorldDelegates::OnWorldTickStart.Remove(OnPreTickHandle);
189 FWorldDelegates::OnWorldPostActorTick.Remove(OnPostTickHandle);
191 FCoreDelegates::OnBeginFrame.Remove(OnBeginFrameHandle);
192 if (GEngine)
193 {
194 GEngine->OnTravelFailure().Remove(OnTravelFailureHandle);
195 }
196 FWorldDelegates::OnPreWorldInitialization.Remove(OnPreWorldInitializationHandle);
197 FCoreUObjectDelegates::PreLoadMap.Remove(OnPreLoadMapHandle);
198 FCoreUObjectDelegates::PostLoadMapWithWorld.Remove(OnPostLoadMapHandle);
200 }
201}
202
204{
205 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
206 if (!bIsRunning)
207 {
208 // Content packs are discovered when the engine subsystem initializes;
209 // this is the no-op safety net that guarantees they are mounted before
210 // the RPC server answers its first get_available_maps.
212 {
213 ContentPacks->Discover();
214 }
215 // A previous run's generated OpenDRIVE files must not shadow the cooked
216 // OpenDriveMap stub in this one. A Multi-GPU secondary keeps the worlds
217 // the primary sends in a folder of its own and leaves the shared files
218 // alone: the primary may run from the same installation.
219 if (Settings.PrimaryIP.empty())
220 {
222 }
223 else
224 {
225 // Unique to this process even across PID namespaces (containers that
226 // share an installation).
227 UOpenDrive::SetSavedXODRDirectory(FPaths::ProjectSavedDir() / FString::Printf(
228 TEXT("OpenDrive/MultiGpuSecondary-%s"), *FApp::GetInstanceId().ToString()));
229 }
230
231 const auto StreamingPort = Settings.StreamingPort;
232 const auto SecondaryPort = Settings.SecondaryPort;
233 const auto PrimaryIP = Settings.PrimaryIP;
234 const auto PrimaryPort = Settings.PrimaryPort;
235
236 // rpclib's asio acceptor throws (std::system_error, "address already
237 // in use") when the RPC port is taken -- typically another CARLA
238 // instance still running. Unhandled it aborts the whole editor with
239 // SIGABRT and a core dump; fail with a readable message instead.
240 try
241 {
242 auto BroadcastStream = Server.Start(Settings.RPCPort, StreamingPort, SecondaryPort);
244 WorldObserver.SetStream(BroadcastStream);
245 }
246 catch (const std::exception &e)
247 {
248 UE_LOG(LogCarla, Error,
249 TEXT("CARLA server failed to start on RPC port %d: %s. "
250 "Another CARLA server is probably running on this port -- "
251 "close it or launch with a different -carla-rpc-port. "
252 "Shutting down."),
253 Settings.RPCPort, UTF8_TO_TCHAR(e.what()));
254 // Immediate exit: a deferred RequestExit lets the engine keep
255 // initializing this half-built game instance and it segfaults in
256 // teardown before ever reaching the main loop. The UE log mirror
257 // may not flush before _exit, so also print straight to stderr.
258 fprintf(stderr,
259 "ERROR: CARLA server failed to start on RPC port %d: %s. "
260 "Another CARLA server is probably running on this port -- "
261 "close it or launch with a different -carla-rpc-port.\n",
262 static_cast<int>(Settings.RPCPort), e.what());
263 fflush(stderr);
264 GLog->Flush();
265 FPlatformMisc::RequestExit(true);
266 return;
267 }
268
269 OnPreTickHandle = FWorldDelegates::OnWorldTickStart.AddRaw(
270 this,
272 OnPostTickHandle = FWorldDelegates::OnWorldPostActorTick.AddRaw(
273 this,
276 this,
278 OnPreWorldInitializationHandle = FWorldDelegates::OnPreWorldInitialization.AddRaw(
279 this,
281 OnPreLoadMapHandle = FCoreUObjectDelegates::PreLoadMap.AddLambda(
282 [this](const FString &) { SuspendHeartBeatForLoad(); });
283 OnPostLoadMapHandle = FCoreUObjectDelegates::PostLoadMapWithWorld.AddLambda(
284 [this](UWorld *) { ResumeHeartBeatAfterLoad(); });
285
286 bIsRunning = true;
287
288 // check to convert this as secondary server
289 if (!PrimaryIP.empty())
290 {
291 // we are secondary server, connecting to primary server
292 bIsPrimaryServer = false;
294
295 // Clients subscribe with the primary's stream ids only (see GET_TOKEN).
297 // Except for this server's own world snapshots, which direct clients of
298 // this server read; the primary never routes its stream 1 here.
299 {
300 const auto BroadcastStreamId =
302 Server.GetStreamingServer().SetStreamAlias(BroadcastStreamId, BroadcastStreamId);
303 }
304
305 // ROS commands address the sensor by the primary's stream id.
306 auto FindAliasedStream = [this](const carla::Buffer &Data)
307 -> std::optional<carla::streaming::detail::stream_id_type>
308 {
309 carla::streaming::detail::stream_id_type PrimaryStreamId = 0u;
310 if (Data.size() < sizeof(PrimaryStreamId))
311 {
312 return std::nullopt;
313 }
314 std::memcpy(&PrimaryStreamId, Data.data(), sizeof(PrimaryStreamId));
315 return Server.GetStreamingServer().FindStreamAlias(PrimaryStreamId);
316 };
317
318 // define the commands executor (when a command comes from the primary server)
319 auto CommandExecutor = [=, this](carla::multigpu::MultiGPUCommand Id, carla::Buffer Data) {
320 switch (Id) {
322 {
323 TRACE_CPUPROFILER_EVENT_SCOPE_STR("MultiGPUCommand::SEND_FRAME");
324 // Parsed outside the lock, so a large frame does not hold up the
325 // game thread. Only a complete frame is queued: a frame is never
326 // played in part.
327 FFrameData Frame;
328 const carla::multigpu::FrameDataReadResult Result = Frame.Read(Data.data(), Data.size());
329 const uint64_t FrameNumber = Frame.GetFrameNumber();
330 bool bReportDrop = false;
331 bool bReportFormat = false;
332 {
333 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
334 if (CurrentEpisode && !Result.IsComplete())
335 {
336 bReportDrop = (DroppedFrames++ == 0u);
337 // This server missed the primary's state: get all of it again.
338 bResyncRequested = true;
339 }
340 else if (CurrentEpisode)
341 {
342 bReportFormat = ((Result.skipped > 0u) || (Result.grown > 0u)) && !bWarnedFrameFormat;
343 bWarnedFrameFormat = bWarnedFrameFormat || bReportFormat;
344 {
345 TRACE_CPUPROFILER_EVENT_SCOPE_STR("FramesToProcess.emplace_back");
346 FramesToProcess.emplace_back(std::move(Frame));
348 }
349 // SEND_FRAME has no acknowledgement or backpressure, so a growing
350 // backlog means this secondary is falling behind; surface it.
351 // Logged only on state change, with separate warn/recovery
352 // thresholds (hysteresis) so a backlog oscillating near one
353 // value can't flip the log every tick.
354 static constexpr int32 BacklogWarningThreshold = 5;
355 static constexpr int32 BacklogRecoveryThreshold = 2;
356 const int32 BacklogSize = static_cast<int32>(FramesToProcess.size());
357 if (BacklogSize > BacklogWarningThreshold && !bFramesToProcessBacklogged)
358 {
359 UE_LOG(LogCarla, Warning,
360 TEXT("Secondary server is falling behind the primary: %d frames queued"),
361 BacklogSize);
363 }
364 else if (BacklogSize <= BacklogRecoveryThreshold && bFramesToProcessBacklogged)
365 {
366 UE_LOG(LogCarla, Log, TEXT("Secondary server has caught up with the primary"));
368 }
369 }
370 }
371 // carla::log_* rather than UE_LOG, so that Shipping logs show them too.
372 if (bReportDrop)
373 {
374 carla::log_error("multigpu: dropping a frame from the primary:",
375 carla::multigpu::FrameDataStatusName(Result.status), "at packet",
376 static_cast<uint32_t>(Result.packet_id), "(offset", Result.offset, "declaring",
377 Result.packet_size, "bytes) of a", Data.size(),
378 "byte frame. Every server must run the same CARLA build.");
379 }
380 if (bReportFormat)
381 {
382 carla::log_warning("multigpu: frame", FrameNumber, "from the primary carries",
383 Result.skipped, "packets this build does not know (first id",
384 static_cast<uint32_t>(Result.first_skipped_id), ") and", Result.grown,
385 "packets longer than it reads. Every server must run the same CARLA build.");
386 }
387 break;
388 }
390 {
392 std::string_view(reinterpret_cast<const char *>(Data.data()), Data.size()));
393 {
394 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
395 PendingLoadMap = UTF8_TO_TCHAR(Request.map.c_str());
397 PendingLoadMapId = Request.load_id;
399 bLoadMapPending = true;
400 }
401 break;
402 }
404 {
405 // Resolved by actor id: local stream ids follow this secondary's own creation order.
407 std::optional<carla::streaming::detail::token_type> Token;
408 if (Data.size() >= sizeof(Request))
409 {
410 std::memcpy(&Request, Data.data(), sizeof(Request));
412 }
413 if (!Token)
414 {
415 carla::log_warning("multigpu: cannot provide a token for sensor actor ", Request.actor_id,
416 " (", Data.size(), "-byte request); replying not ready");
417 carla::Buffer Reply(
418 reinterpret_cast<const unsigned char *>(carla::multigpu::kTokenNotReadyMarker.data()),
420 Secondary->Write(std::move(Reply));
421 break;
422 }
423 carla::Buffer Reply(reinterpret_cast<const unsigned char *>(&*Token), sizeof(*Token));
424 carla::log_info("responding with a token for port ", Token->get_port());
425 Secondary->Write(std::move(Reply));
426 break;
427 }
429 {
430 std::string msg("Yes, I'm alive");
431 carla::Buffer buf((unsigned char *) msg.c_str(), (size_t) msg.size());
432 carla::log_info("responding is alive command");
433 Secondary->Write(std::move(buf));
434 break;
435 }
437 {
438 const auto sensor_id = FindAliasedStream(Data);
439 if (sensor_id)
440 {
442 }
443 const bool res = sensor_id.has_value();
444 carla::Buffer buf(reinterpret_cast<const unsigned char *>(&res), sizeof(res));
445 carla::log_info("responding ENABLE_ROS with: ", res);
446 Secondary->Write(std::move(buf));
447 break;
448 }
450 {
451 const auto sensor_id = FindAliasedStream(Data);
452 if (sensor_id)
453 {
455 }
456 const bool res = sensor_id.has_value();
457 carla::Buffer buf(reinterpret_cast<const unsigned char *>(&res), sizeof(res));
458 carla::log_info("responding DISABLE_ROS with: ", res);
459 Secondary->Write(std::move(buf));
460 break;
461 }
463 {
464 const auto sensor_id = FindAliasedStream(Data);
465 const bool res = sensor_id && Server.GetStreamingServer().IsEnabledForROS(*sensor_id);
466 carla::Buffer buf(reinterpret_cast<const unsigned char *>(&res), sizeof(res));
467 carla::log_info("responding IS_ENABLED_ROS with: ", res);
468 Secondary->Write(std::move(buf));
469 break;
470 }
471 }
472 };
473
474 Secondary = std::make_shared<carla::multigpu::Secondary>(PrimaryIP, PrimaryPort, CommandExecutor);
475 Secondary->Connect();
476 // set this server in synchronous mode
477 bSynchronousMode = true;
478 // From here on, OnBeginFrame sets this server's time step from every
479 // primary frame; the benchmarking switch must not override it.
480 FApp::SetBenchmarking(false);
481 OnBeginFrameHandle = FCoreDelegates::OnBeginFrame.AddRaw(this, &FCarlaEngine::OnBeginFrame);
482 if (GEngine)
483 {
484 OnTravelFailureHandle = GEngine->OnTravelFailure().AddLambda(
485 [this](UWorld *, ETravelFailure::Type, const FString &Error)
486 {
487 bTravelFailed = true;
488 carla::log_error("multigpu: failed to load the map the primary loaded:", TCHAR_TO_UTF8(*Error));
489 });
490 }
491 if (!FApp::CanEverRender())
492 {
493 UE_LOG(LogCarla, Warning,
494 TEXT("Multi-GPU secondary started without rendering (-nullrhi): camera sensors routed here will produce no data"));
495 }
496 }
497 else
498 {
499 // we are primary server, starting server
500 bIsPrimaryServer = true;
502 SecondaryServer->SetNewConnectionCallback([this]()
503 {
504 this->bNewConnection = true;
505 UE_LOG(LogCarla, Log, TEXT("New secondary connection detected"));
506 });
507 if (!FApp::CanEverRender())
508 {
509 UE_LOG(LogCarla, Log,
510 TEXT("Rendering disabled (-nullrhi): running as a non-rendering, authority-only primary. Camera sensors need a connected rendering secondary server to produce data."));
511 }
512 }
513 }
514
515 // create ROS2 manager
516 #if defined(WITH_ROS2)
517 if (Settings.ROS2)
518 {
519 UE_LOG(LogCarla, Log, TEXT("ROS2: Creating ROS2 Instance..."));
520 auto ROS2 = carla::ros2::ROS2::GetInstance();
521 const std::string Rmw = TCHAR_TO_UTF8(*Settings.RmwName);
522 const auto Parsed = carla::ros2::MiddlewareFromString(Rmw);
523 if (!Parsed.valid)
524 {
525 UE_LOG(LogCarla, Error,
526 TEXT("ROS2: unrecognized --rmw value '%s'. Available: %s. ROS2 is DISABLED for this session."),
527 *Settings.RmwName,
528 UTF8_TO_TCHAR(carla::ros2::GetAvailableMiddleware().c_str()));
529 }
530 else
531 {
532 int32 DomainId = Settings.ROS2DomainId;
533 if (DomainId != carla::ros2::kUnsetDomainId && !carla::ros2::IsValidDomainId(DomainId))
534 {
535 UE_LOG(LogCarla, Error,
536 TEXT("ROS2: --ros-domain-id=%d is out of range [%d, %d]; using the default domain."),
539 }
540 if (!ROS2->Enable(true, Parsed.middleware, DomainId))
541 {
542 // Either the middleware is not compiled in, or it failed to start
543 // (e.g. an invalid DDS profile); ROS2::Enable logged which one.
544 UE_LOG(LogCarla, Error,
545 TEXT("ROS2: middleware '%s' could not be enabled (compiled in: %s); see the ROS2 errors above. ROS2 is DISABLED for this session."),
546 *Settings.RmwName,
547 UTF8_TO_TCHAR(carla::ros2::GetAvailableMiddleware().c_str()));
548 }
549 else
550 {
551 UE_LOG(LogCarla, Log, TEXT("ROS2: enabled with middleware '%s'."), *Settings.RmwName);
552 if (Settings.RmwName == TEXT("fastdds"))
553 {
554 // Mirrors the transport default applied in FastDDSSharedParticipant:
555 // UDPv4-only unless FASTDDS_BUILTIN_TRANSPORTS is set (Fast-DDS
556 // shared memory silently drops data across container/uid/version
557 // boundaries, so it is opt-in).
558 const char *TransportsEnv = std::getenv("FASTDDS_BUILTIN_TRANSPORTS");
559 if (TransportsEnv != nullptr)
560 {
561 UE_LOG(LogCarla, Log,
562 TEXT("ROS2: Fast-DDS builtin transports set from FASTDDS_BUILTIN_TRANSPORTS='%s'."),
563 UTF8_TO_TCHAR(TransportsEnv));
564 }
565 else
566 {
567 UE_LOG(LogCarla, Log,
568 TEXT("ROS2: Fast-DDS transport: UDPv4 only (default; set FASTDDS_BUILTIN_TRANSPORTS=DEFAULT to re-enable shared memory)."));
569 }
570 }
571 // Apply the configured default topic visibility before any sensor stream is
572 // created. Gated on Settings.ROS2 so non-ROS2 runs never force every stream
573 // active (which would make every sensor produce data each tick).
574 Server.GetStreamingServer().SetROS2TopicVisibilityDefaultEnabled(Settings.ROS2TopicVisibility);
575 }
576 }
577 } else {
578 UE_LOG(LogCarla, Log, TEXT("ROS2: ROS2 enabled..."));
579 }
580 #else
581 UE_LOG(LogCarla, Log, TEXT("ROS2: ROS2 extension not build..."));
582 #endif
583
584 bMapChanged = true;
585}
586
588{
589 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
591 {
592 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
593 CurrentEpisode = &Episode;
594 // The new episode has a new actor registry.
595 MappedId.clear();
597 DroppedFrames = 0u;
598 bWarnedFrameFormat = false;
599 }
600
601 // Reset map settings
602 UWorld* World = CurrentEpisode->GetWorld();
603 ALargeMapManager* LargeMapManager = UCarlaStatics::GetLargeMapManager(World);
604 if (LargeMapManager)
605 {
608 }
609
610 // The settings survive load_world(reset_settings=False) but the traffic
611 // light manager is new with every map, and a map can enable sign snapping
612 // on its own. Enable it on whichever side lacks it so that they agree.
614 if (ATrafficLightManager* TrafficLightManager =
615 GameMode ? GameMode->GetTrafficLightManager() : nullptr)
616 {
618 {
619 TrafficLightManager->SetAdjustSignsHeightToGround(true);
620 }
621 else
622 {
624 TrafficLightManager->GetAdjustSignsHeightToGround();
625 }
626 }
627
628 if (!bIsPrimaryServer)
629 {
630 // set this secondary server with no-rendering mode
632 // and synchronous, as it plays the primary's frames: its own clients (read-only
633 // queries) then never wait for a tick that only the primary triggers
635 }
636
638
639 ResetFrameCounter(GFrameNumber);
640
641 // make connection between Episode and Recorder
642 if (Recorder)
643 {
644 Recorder->SetEpisode(&Episode);
645 Episode.SetRecorder(Recorder);
647 }
648
649 Server.NotifyBeginEpisode(Episode);
650
652
654 {
655 PreparedFrame.reset();
656 LastPlayedFrame.reset();
657 bWarnedUntimedFrame = false;
658 bWarnedUnpairedFrame = false;
659 bWarnedNoSensorTicks = false;
660 RestoredPoses = 0u;
661 RestoredPoseClasses.Reset();
662 // Map actors that simulate physics (movable props) would fall or drift on
663 // their own here; the primary's frames move them instead.
664 for (auto &It : Episode.GetActorRegistry())
665 {
666 FCarlaActor *CarlaActor = It.Value.Get();
667 if ((CarlaActor != nullptr) && (CarlaActor->GetActorType() == FCarlaActor::ActorType::Other) &&
668 !CarlaActor->IsDormant() && (CarlaActor->GetActor() != nullptr))
669 {
670 if (auto *Root = Cast<UPrimitiveComponent>(CarlaActor->GetActor()->GetRootComponent()))
671 {
672 if (Root->IsSimulatingPhysics())
673 {
674 Root->SetSimulatePhysics(false);
675 }
676 }
677 }
678 }
679 if (bTravelFailed)
680 {
681 // The engine fell back to another map: playing the primary's frames here
682 // would mirror them onto the wrong world.
683 bTravelFailed = false;
684 DetachFromPrimary("could not load the primary's map; all servers must run the same build with the same content");
685 return;
686 }
687 if (!LoadingMap.IsEmpty() &&
688 !FPaths::GetBaseFilename(LoadingMap).Equals(Episode.GetMapName(), ESearchCase::IgnoreCase))
689 {
690 UE_LOG(LogCarla, Warning, TEXT("Multi-GPU: the primary loaded %s and this secondary is on %s"),
691 *LoadingMap, *Episode.GetMapName());
692 }
693
696
697 // Re-arms the primary's full-resync flag (see Router::HandleResponse),
698 // since connect-time arming predates this secondary's own level load.
700 EpisodeReadyPendingSince = FPlatformTime::Seconds();
702 }
703}
704
706{
707 if (!bEpisodeReadyPending || CurrentEpisode == nullptr)
708 {
709 return;
710 }
711 // The primary mirrors frames only after EPISODE_READY, so its first frame finds the furniture spawned.
712 for (TActorIterator<AOpenDriveGenerator> It(CurrentEpisode->GetWorld()); It; ++It)
713 {
714 if (It->IsStreetFurnitureGenerating())
715 {
716 return;
717 }
718 }
719 bEpisodeReadyPending = false;
720 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: episode content ready after %.2f s, sending EPISODE_READY"),
721 FPlatformTime::Seconds() - EpisodeReadyPendingSince);
723}
724
726{
728 Secondary->Write(carla::Buffer(reinterpret_cast<const unsigned char *>(Ready.data()), Ready.size()));
729}
730
731void FCarlaEngine::DetachFromPrimary(const char *Reason)
732{
733 carla::log_error("multigpu:", Reason, "- this secondary stops mirroring the primary until it is restarted");
734 if (Secondary)
735 {
736 // Joins the command threads; nothing they run waits on this thread.
737 Secondary->Stop();
738 }
739 {
740 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
741 FramesToProcess.clear();
742 QueuedFrames = 0u;
743 }
744 PreparedFrame.reset();
745 LastPlayedFrame.reset();
746 FApp::SetUseFixedTimeStep(false);
747}
748
750{
753 uint64_t Dropped = 0u;
754 {
755 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
756 CurrentEpisode = nullptr;
757 FramesToProcess.clear();
758 QueuedFrames = 0u;
760 Dropped = DroppedFrames;
761 DroppedFrames = 0u;
762 }
763 if (Dropped > 1u)
764 {
765 carla::log_error("multigpu: dropped", Dropped, "incomplete frames from the primary in this episode");
766 }
767 if (DeltaMismatches > 0u)
768 {
769 carla::log_warning("multigpu:", DeltaMismatches, "frames of this episode ran with another time step than the primary's");
770 DeltaMismatches = 0u;
771 }
772 if (RestoredPoses > 0u)
773 {
774 carla::log_warning("multigpu:", RestoredPoses, "mirror poses had moved before their capture in this episode and were restored");
775 RestoredPoses = 0u;
776 }
777 PreparedFrame.reset();
778 LastPlayedFrame.reset();
779}
780
781void FCarlaEngine::BindReplayedSensor(uint32_t PrimaryActorId, uint32_t LocalActorId, bool bCreated)
782{
783 FCarlaActor *CarlaActor = CurrentEpisode->FindCarlaActor(LocalActorId);
784 if ((CarlaActor == nullptr) || (CarlaActor->GetActorType() != FCarlaActor::ActorType::Sensor))
785 {
786 return;
787 }
788
790 {
792 {
793 UE_LOG(LogCarla, Warning,
794 TEXT("Multi-GPU: ignoring replayed sensor %u (primary actor %u): the episode of the latest map load is not open here (did the level load fail?); its clients get no data until it is"),
795 LocalActorId, PrimaryActorId);
797 }
798 return;
799 }
800
801 ASensor *Sensor = Cast<ASensor>(CarlaActor->GetActor());
802 const bool bSensorHasStream = (Sensor != nullptr) && Sensor->IsStreamReady();
803 std::optional<carla::streaming::detail::stream_id_type> OwnStreamId;
804 if (bSensorHasStream)
805 {
807 }
808 else if (FActorSensorData *DormantData = CarlaActor->GetActorData<FActorSensorData>())
809 {
810 if (DormantData->Stream.IsStreamReady())
811 {
812 OwnStreamId = carla::streaming::detail::token_type(DormantData->Stream.GetToken()).get_stream_id();
813 }
814 }
815 if (!OwnStreamId)
816 {
817 UE_LOG(LogCarla, Warning,
818 TEXT("Multi-GPU: replayed sensor %u (primary actor %u) has no stream; its clients get no data"),
819 LocalActorId, PrimaryActorId);
820 return;
821 }
822
823 // Only a sensor created by this replay step has never ticked; a live
824 // sensor's stream must not be replaced (its capture reads it concurrently).
825 const bool bCanAdopt = bCreated && bSensorHasStream;
826 auto ReservedStream = SensorStreams.Bind(Server.GetStreamingServer(), PrimaryActorId, *OwnStreamId, bCanAdopt);
827 if (!ReservedStream)
828 {
829 return;
830 }
831 Sensor->SetDataStream(FDataStream(std::move(*ReservedStream)));
832 Server.GetStreamingServer().CloseStream(*OwnStreamId);
833}
834
836{
837 if (!SecondaryServer || !SecondaryServer->IsAnySecondaryLoading())
838 {
839 return;
840 }
841 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
842 static constexpr double TimeoutSeconds = 30.0;
843 const double Start = FPlatformTime::Seconds();
844 const double Deadline = Start + TimeoutSeconds;
845 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: waiting for secondary servers to load the new episode"));
846 while (SecondaryServer->IsAnySecondaryLoading())
847 {
849 {
850 // This frame belongs to a world being left: the new one waits instead.
851 return;
852 }
853 if (FPlatformTime::Seconds() >= Deadline)
854 {
855 UE_LOG(LogCarla, Warning,
856 TEXT("Multi-GPU: secondary servers did not load the new episode within %.0f s (waited %.0f ms); ticking without waiting"),
857 TimeoutSeconds, (FPlatformTime::Seconds() - Start) * 1000.0);
858 SecondaryServer->StopWaitingForSecondaryLoads();
859 return;
860 }
861 Server.RunSome(1u);
862 }
863 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: all secondary servers loaded the new episode after %.0f ms"),
864 (FPlatformTime::Seconds() - Start) * 1000.0);
865}
866
867void FCarlaEngine::OnPreTick(UWorld *World, ELevelTick TickType, float DeltaSeconds)
868{
869 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
870 if (TickType != ELevelTick::LEVELTICK_All)
871 {
872 return;
873 }
874
875 if (!bIsPrimaryServer)
876 {
879 CurrentEpisode != nullptr,
880 PreparedFrame.has_value(),
881 (CurrentEpisode != nullptr) && (World == CurrentEpisode->GetWorld()));
883 {
884 FString MapToLoad;
886 {
887 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
888 MapToLoad = std::move(PendingLoadMap);
889 PendingLoadMap.Reset();
890 Extras = std::move(PendingLoadMapExtras);
894 bLoadMapPending = false;
895 }
896 PreparedFrame.reset();
897 LoadingMap = MapToLoad;
898 // A map this package lacks would make the engine fall back to another
899 // one, and frames of the primary's world would then be played there.
900 if (UCarlaStatics::FindMapPath(FPaths::GetBaseFilename(MapToLoad)).IsEmpty())
901 {
902 DetachFromPrimary(TCHAR_TO_UTF8(*FString::Printf(
903 TEXT("the primary loaded %s, which this server does not have"), *MapToLoad)));
904 return;
905 }
907 UGameplayStatics::OpenLevel(CurrentEpisode->GetWorld(), *MapToLoad, true);
908 // Frames still queued belong to the world being left; NotifyEndEpisode drops them.
909 return;
910 }
911
913 {
914 // An engine frame on this server's own clock: no primary frame, so no
915 // simulation time passes either.
916 return;
917 }
918
919 std::optional<FFrameData> Frame;
920 {
921 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
922 if (!FramesToProcess.empty() && (FramesToProcess.front().GetFrameNumber() == *PreparedFrame))
923 {
924 Frame.emplace(std::move(FramesToProcess.front()));
925 FramesToProcess.erase(FramesToProcess.begin());
927 }
928 }
929 if (Frame)
930 {
931 // Played outside the lock, so the command thread is never held up by
932 // a large resync.
933 PlayPrimaryFrame(*World, DeltaSeconds, *Frame);
934 }
935 else if (!bWarnedUnpairedFrame)
936 {
938 UE_LOG(LogCarla, Warning, TEXT("Multi-GPU: primary frame %llu, prepared for this engine frame, is gone"),
939 static_cast<uint64>(*PreparedFrame));
940 }
941 PreparedFrame.reset();
942 return;
943 }
944
945 PendingFrameTime.reset();
946 if (CurrentEpisode && !bSynchronousMode && SecondaryServer->HasClientsConnected())
947 {
948 // set synchronous mode
954 }
955
956 // process RPC commands. Waiting here for a client's tick is not a hang:
957 // keep the game thread's heartbeat going so Unreal's hang detector only
958 // reports a game thread that is stuck somewhere else (#10233).
959 do
960 {
961 Server.RunSome(1u);
962 FThreadHeartBeat::Get().HeartBeat();
963 }
965
966 // load_world() only schedules the travel, for the next engine frame: this
967 // frame still belongs to the world being left, and is never sent.
968 bool bLeavingWorld = FCarlaEngine_IsWorldTravelPending(World);
969
970 // Frames sent while a secondary is still loading are dropped there.
971 if (bSynchronousMode && !bLeavingWorld)
972 {
974 // Another client's load_world can be served while waiting.
975 bLeavingWorld = FCarlaEngine_IsWorldTravelPending(World);
976 }
977
978 if (CurrentEpisode && (World == CurrentEpisode->GetWorld()) && !bLeavingWorld)
979 {
980 // The world's clocks before UWorld::Tick adds this frame's delta to them.
981 const AWorldSettings *WorldSettings = World->GetWorldSettings();
983 Time.DeltaSeconds = DeltaSeconds;
984 Time.TimeSeconds = World->TimeSeconds;
985 Time.UnpausedTimeSeconds = World->UnpausedTimeSeconds;
986 Time.RealTimeSeconds = World->RealTimeSeconds;
987 Time.AudioTimeSeconds = World->AudioTimeSeconds;
988 Time.TimeDilation = WorldSettings ? WorldSettings->GetEffectiveTimeDilation() : 1.0f;
989 PendingFrameTime = Time;
990 }
991
992 // update frame counter
994
995 if (CurrentEpisode)
996 {
997 CurrentEpisode->TickTimers(DeltaSeconds);
998 }
999}
1000
1002{
1003 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
1004 bFramePlayedThisTick = false;
1005 PreparedFrame.reset();
1006 if (!Secondary)
1007 {
1008 return;
1009 }
1010
1011 const bool bConnected = Secondary->IsConnected();
1012 if (bWasConnectedToPrimary && !bConnected)
1013 {
1014 carla::log_warning("multigpu: lost the connection to the primary; this secondary stops mirroring "
1015 "it and runs on its own clock until it is restarted");
1016 }
1017 bWasConnectedToPrimary = bConnected;
1018
1020 {
1021 const double Now = FPlatformTime::Seconds();
1022 if (Now - LastResyncRequestSeconds >= 1.0)
1023 {
1025 bResyncRequested = false;
1026 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: missed state of the primary; asking it for a resync"));
1028 }
1029 }
1030
1032
1034 State.connected = bConnected;
1035 State.has_episode = (CurrentEpisode != nullptr);
1036 State.travel_pending = State.has_episode && FCarlaEngine_IsWorldTravelPending(CurrentEpisode->GetWorld());
1037 // While EPISODE_READY is held back, frames run on this server's own clock so the content can finish.
1038 State.load_map_pending = bLoadMapPending || bEpisodeReadyPending;
1039 State.exit_requested = IsEngineExitRequested();
1041
1043 {
1044 // Not mirroring anything: serve RPCs on this server's own clock, without
1045 // spinning (RunSome returns at once when there is no work).
1046 Server.RunSome(1u);
1047 static constexpr double MinFrameSeconds = 1.0 / 50.0;
1048 const double Elapsed = FPlatformTime::Seconds() - LastOwnClockFrameSeconds;
1049 if (Elapsed < MinFrameSeconds)
1050 {
1051 FPlatformProcess::Sleep(static_cast<float>(MinFrameSeconds - Elapsed));
1052 }
1053 LastOwnClockFrameSeconds = FPlatformTime::Seconds();
1054 FApp::SetUseFixedTimeStep(false);
1055 return;
1056 }
1057
1058 // Never wait without an episode or while a map load is pending or a travel
1059 // is scheduled: the primary waits for this server's EPISODE_READY, which is
1060 // only sent from NotifyBeginEpisode, inside the travel.
1061 const bool bCanWait = (Action == carla::multigpu::BeginFrameAction::Wait);
1062 std::optional<uint64_t> Frame;
1063 std::optional<float> Delta;
1064 do
1065 {
1066 Server.RunSome(1u);
1067 // An idle primary (synchronous mode, no client ticking) is not a hang here.
1068 FThreadHeartBeat::Get().HeartBeat();
1069 if (!bCanWait || bLoadMapPending || IsEngineExitRequested() || !Secondary->IsConnected())
1070 {
1071 break;
1072 }
1073 if (QueuedFrames.load() == 0u)
1074 {
1075 // RunSome returns at once when it has nothing to do: without this the
1076 // loop spins a core until the command thread queues a frame. A sleep on
1077 // the monotonic clock, unlike a timed condition wait with this libc++.
1078 FPlatformProcess::SleepNoStats(0.0005f);
1079 continue;
1080 }
1081 std::scoped_lock<std::mutex> Lock(FrameToProcessMutex);
1082 if (!FramesToProcess.empty())
1083 {
1084 Frame = FramesToProcess.front().GetFrameNumber();
1085 if (const carla::multigpu::FrameTime *Time = FramesToProcess.front().GetFrameTime())
1086 {
1087 Delta = Time->delta_seconds;
1088 }
1089 }
1090 }
1091 while (!Frame);
1092
1093 // This engine frame's time step: UEngine::UpdateTimeAndHandleMaxTickRate,
1094 // which runs right after this delegate, turns it back into this very float,
1095 // so the world ticks with exactly the primary's delta.
1096 const bool bTimed = Delta && carla::multigpu::IsUsableDelta(*Delta);
1097 FApp::SetUseFixedTimeStep(bTimed);
1098 if (bTimed)
1099 {
1100 FApp::SetFixedDeltaTime(static_cast<double>(*Delta));
1101 }
1102 PreparedFrame = Frame;
1103}
1104
1105void FCarlaEngine::PlayPrimaryFrame(UWorld &World, float DeltaSeconds, FFrameData &Frame)
1106{
1107 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
1108 const uint64_t FrameNumber = Frame.GetFrameNumber();
1109 const carla::multigpu::FrameTime *Time = Frame.GetFrameTime();
1110 if (Time)
1111 {
1112 if (DeltaSeconds != Time->delta_seconds)
1113 {
1114 if (DeltaMismatches++ == 0u)
1115 {
1116 carla::log_warning("multigpu: frame", FrameNumber, "ran with a", DeltaSeconds,
1117 "s time step instead of the primary's", Time->delta_seconds, "s");
1118 }
1119 }
1120
1121 // The primary's world clocks before this frame's accumulation: UWorld::Tick
1122 // then adds the same float to the same doubles, so the world time materials,
1123 // animations and tick intervals see is the primary's, bit for bit.
1124 World.TimeSeconds = Time->world_time_seconds;
1125 World.UnpausedTimeSeconds = Time->world_unpaused_time_seconds;
1126 World.RealTimeSeconds = Time->world_real_time_seconds;
1127 World.AudioTimeSeconds = Time->world_audio_time_seconds;
1128 if (AWorldSettings *WorldSettings = World.GetWorldSettings())
1129 {
1130 if (WorldSettings->TimeDilation != Time->time_dilation)
1131 {
1132 WorldSettings->TimeDilation = Time->time_dilation;
1133 }
1134 }
1135
1136 const bool bConsecutive = carla::multigpu::IsConsecutive(LastPlayedFrame, FrameNumber);
1138 {
1139 // A frame went missing: this server lacks whatever it carried.
1140 bResyncRequested = true;
1141 }
1142 if (!bConsecutive)
1143 {
1144 // What the primary's clocks read while it served the RPCs this frame
1145 // replays (spawns, attachments): before its TickTimers of this frame.
1147 Time->elapsed_game_time - Time->delta_seconds,
1148 Time->visual_game_time - Time->delta_seconds);
1149 FCarlaEngine::ResetFrameCounter(FrameNumber - 1u);
1150 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: following the primary's clock from frame %llu (elapsed %.6f s)"),
1151 static_cast<uint64>(FrameNumber), Time->elapsed_game_time);
1152 }
1153 MirrorPrimarySettings(*Time);
1154 if (!Frame.HasSensorTicks() && !bWarnedNoSensorTicks)
1155 {
1156 bWarnedNoSensorTicks = true;
1157 carla::log_warning("multigpu: the primary does not say which sensors tick; no sensor of this "
1158 "secondary will produce data. Every server must run the same CARLA build.");
1159 }
1160 }
1161
1162 {
1163 TRACE_CPUPROFILER_EVENT_SCOPE_STR("FramesToProcess.PlayFrameData");
1164 // Ends with the frame counter set to the primary's frame number.
1165 Frame.PlayFrameData(
1167 MappedId,
1169 [this](uint32_t PrimaryActorId, uint32_t LocalActorId, bool bCreated)
1170 {
1171 BindReplayedSensor(PrimaryActorId, LocalActorId, bCreated);
1172 },
1173 [this](uint32_t PrimaryActorId)
1174 {
1175 SensorStreams.Unbind(Server.GetStreamingServer(), PrimaryActorId);
1176 });
1177 }
1178
1179 if (Time)
1180 {
1182 LastPlayedFrame = FrameNumber;
1183 }
1184 else
1185 {
1187 {
1188 bWarnedUntimedFrame = true;
1189 carla::log_warning("multigpu: the primary sends frames without its clock (an older build?); "
1190 "this secondary stamps them with its own. Every server must run the same CARLA build.");
1191 }
1192 CurrentEpisode->TickTimers(DeltaSeconds);
1193 LastPlayedFrame.reset();
1194 }
1195 bFramePlayedThisTick = true;
1196}
1197
1199{
1200 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
1201 for (const auto &Played : MirrorState.PlayedPoses)
1202 {
1203 FCarlaActor *CarlaActor = CurrentEpisode->FindCarlaActor(Played.first);
1204 if ((CarlaActor == nullptr) || CarlaActor->IsDormant() || (CarlaActor->GetActor() == nullptr))
1205 {
1206 continue;
1207 }
1208 const FTransform Current = CarlaActor->GetActorGlobalTransform();
1209 const FTransform &Pose = Played.second;
1210 // 1e-3 cm and about 1e-4 degrees
1211 const bool bMoved =
1212 !Current.GetLocation().Equals(Pose.GetLocation(), 1e-3) ||
1213 (Current.GetRotation().AngularDistance(Pose.GetRotation()) > FMath::DegreesToRadians(1e-4));
1214 if (!bMoved)
1215 {
1216 continue;
1217 }
1218 AActor *Actor = CarlaActor->GetActor();
1219 FTransform Restored = Pose;
1220 Restored.SetScale3D(Actor->GetActorScale3D());
1221 CarlaActor->SetActorGlobalTransform(Restored, ETeleportType::None);
1222 ++RestoredPoses;
1223 const FName ClassName = Actor->GetClass()->GetFName();
1224 if (!RestoredPoseClasses.Contains(ClassName))
1225 {
1226 RestoredPoseClasses.Add(ClassName);
1227 UE_LOG(LogCarla, Warning,
1228 TEXT("Multi-GPU: a %s mirror moved on its own between playing frame %llu and its capture; restored the primary's pose"),
1229 *ClassName.ToString(), static_cast<uint64>(FCarlaEngine::GetFrameCounter()));
1230 }
1231 }
1232}
1233
1235{
1237 SettingsFromFrameTime(Time, Settings);
1238 // A secondary plays the primary's frames, so it is synchronous whatever the
1239 // primary runs, and never renders its own viewport.
1240 Settings.bSynchronousMode = true;
1241 Settings.bNoRenderingMode = true;
1243 {
1244 return;
1245 }
1246 CurrentEpisode->ApplySettings(Settings);
1247 // set_episode_settings applies these two itself; do the same here.
1249 {
1250 if (ALargeMapManager *LargeMap = GameMode->GetLMManager())
1251 {
1252 LargeMap->ConsiderSpectatorAsEgo(Settings.SpectatorAsEgo);
1253 }
1254 if (ATrafficLightManager *TrafficLightManager = GameMode->GetTrafficLightManager())
1255 {
1256 TrafficLightManager->SetAdjustSignsHeightToGround(Settings.bAdjustSignsHeightToGround);
1257 }
1258 }
1259 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: mirroring the primary's settings (fixed delta %s, substepping %s)"),
1260 Settings.FixedDeltaSeconds.IsSet() ? *FString::SanitizeFloat(Settings.FixedDeltaSeconds.GetValue()) : TEXT("none"),
1261 Settings.bSubstepping ? TEXT("on") : TEXT("off"));
1262}
1263
1264
1265void FCarlaEngine::OnPostTick(UWorld *World, ELevelTick TickType, float DeltaSeconds)
1266{
1267 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
1268 // With -RenderOffScreen nobody can see the main viewport, but its world
1269 // render still costs a full scene pass (Lumen, shadows, clouds) every frame
1270 // next to the sensors' own captures. Keep it disabled in that mode; sensors
1271 // are independent scene captures and are unaffected.
1272 static const bool bRenderOffScreen =
1273 FParse::Param(FCommandLine::Get(), TEXT("RenderOffScreen"));
1274 if (bRenderOffScreen && GEngine && GEngine->GameViewport &&
1275 !GEngine->GameViewport->bDisableWorldRendering)
1276 {
1277 GEngine->GameViewport->bDisableWorldRendering = true;
1278 }
1279 // FScene::SceneFrameNumber normally advances once per main-viewport world
1280 // render (FRendererModule::BeginRenderingViewFamilies). With the viewport's
1281 // world render disabled it freezes, every scene capture gets
1282 // ViewFamily.FrameNumber == 0, and all frame-keyed renderer caches (global
1283 // distance field, virtual shadow maps, Lumen temporal state) treat every
1284 // capture as "never rendered" and rebuild from scratch. Advance it manually
1285 // so sensors keep the normal per-frame cache behavior.
1286 if (World && World->Scene && GEngine && GEngine->GameViewport &&
1287 GEngine->GameViewport->bDisableWorldRendering)
1288 {
1289 World->Scene->IncrementFrameNumber();
1290 }
1291 // tick the recorder/replayer system
1292 if (GetCurrentEpisode())
1293 {
1294 // First, so that the frame sent below carries what a replay just set
1295 // (actor poses, visual time), as the primary's own snapshot does.
1296 auto* EpisodeRecorder = GetCurrentEpisode()->GetRecorder();
1297 if (EpisodeRecorder)
1298 {
1299 EpisodeRecorder->Ticking(DeltaSeconds);
1300 }
1301
1302 // Only frames whose start OnPreTick recorded, of the episode's world, and
1303 // never the frame that leaves it.
1304 if (bIsPrimaryServer && PendingFrameTime && SecondaryServer->HasClientsConnected() &&
1305 (World == GetCurrentEpisode()->GetWorld()) && !FCarlaEngine_IsWorldTravelPending(World))
1306 {
1307 const bool bWasNewConnection = bNewConnection.exchange(false);
1308 FFrameData &FrameData = GetCurrentEpisode()->GetFrameData();
1309 FrameData.GetFrameData(GetCurrentEpisode(), true, bWasNewConnection);
1310
1313 Time.delta_seconds = PendingFrameTime->DeltaSeconds;
1316 Time.world_time_seconds = PendingFrameTime->TimeSeconds;
1317 Time.world_unpaused_time_seconds = PendingFrameTime->UnpausedTimeSeconds;
1318 Time.world_real_time_seconds = PendingFrameTime->RealTimeSeconds;
1319 Time.world_audio_time_seconds = PendingFrameTime->AudioTimeSeconds;
1320 Time.time_dilation = PendingFrameTime->TimeDilation;
1321 Time.full_resync = bWasNewConnection;
1322 FrameTimeFromSettings(GetCurrentEpisode()->GetSettings(), Time);
1323 FrameData.SetFrameTime(Time);
1324
1325 std::ostringstream OutStream;
1326 FrameData.Write(OutStream);
1327
1328 // send frame data to secondary
1329 std::string Tmp(OutStream.str());
1330 SecondaryServer->GetCommander().SendFrameData(carla::Buffer(std::move((unsigned char *) Tmp.c_str()), (size_t) Tmp.size()));
1331
1332#if !UE_BUILD_SHIPPING
1333 if (CVarCarlaMultiGpuVerifyFrames.GetValueOnGameThread() != 0)
1334 {
1335 FFrameData Check;
1337 Check.Read(reinterpret_cast<const uint8_t *>(Tmp.data()), Tmp.size());
1338 if (!Result.IsComplete() || (Result.skipped > 0u) || (Result.grown > 0u))
1339 {
1340 UE_LOG(LogCarla, Error,
1341 TEXT("Multi-GPU: the frame sent to the secondaries does not read back: %s at packet %u (offset %llu), %u unknown and %u longer packets"),
1342 UTF8_TO_TCHAR(carla::multigpu::FrameDataStatusName(Result.status)),
1343 static_cast<uint32>(Result.packet_id), static_cast<uint64>(Result.offset),
1344 Result.skipped, Result.grown);
1345 }
1346 }
1347#endif // !UE_BUILD_SHIPPING
1348
1349 // Game thread, like the get_sensor_token RPC: it must not run inside a
1350 // Router callback, and the secondary answers GET_TOKEN on its command
1351 // thread, so this cannot wait on either game thread.
1352 if (bWasNewConnection)
1353 {
1354 const std::size_t Rerouted = SecondaryServer->GetCommander().RerouteLostSensors();
1355 if (Rerouted > 0u)
1356 {
1357 UE_LOG(LogCarla, Log, TEXT("Multi-GPU: routed %d sensors of a lost secondary to a new one"),
1358 static_cast<int32>(Rerouted));
1359 }
1360 }
1361 }
1362
1363 // Every server records its own events here, with or without secondaries
1364 // (a secondary never sends them), so they never pile up.
1366 }
1367 PendingFrameTime.reset();
1368
1369 // A secondary only captures and broadcasts frames that carry the primary's
1370 // state, on the world it was played on.
1371 const bool bCaptureThisFrame = bIsPrimaryServer ||
1372 (bFramePlayedThisTick && CurrentEpisode && (World == CurrentEpisode->GetWorld()));
1373 if ((TickType == ELevelTick::LEVELTICK_All) && (CurrentEpisode != nullptr) && bCaptureThisFrame)
1374 {
1375 if (!bIsPrimaryServer)
1376 {
1378 }
1379
1380 // Look for lightsubsystem
1381 bool LightUpdatePending = false;
1382 if (World)
1383 {
1384 UCarlaLightSubsystem* CarlaLightSubsystem = World->GetSubsystem<UCarlaLightSubsystem>();
1385 if (CarlaLightSubsystem)
1386 {
1387 LightUpdatePending = CarlaLightSubsystem->IsUpdatePending();
1388 }
1389 }
1390
1391 // send the worldsnapshot
1392 WorldObserver.BroadcastTick(*CurrentEpisode, DeltaSeconds, bMapChanged, LightUpdatePending);
1393 CurrentEpisode->GetSensorManager().PostPhysTick(World, TickType, DeltaSeconds);
1395 }
1396 bFramePlayedThisTick = false;
1397}
1398
1400{
1402 {
1404 FThreadHeartBeat::Get().SuspendHeartBeat();
1405 }
1406}
1407
1409{
1411 {
1413 FThreadHeartBeat::Get().ResumeHeartBeat();
1414 }
1415}
1416
1417void FCarlaEngine::OnPreWorldInitialization(UWorld *World, const UWorld::InitializationValues IVS)
1418{
1419 // Chaos rebuilds its dynamic BVH tree in an async task and swaps it in only
1420 // when that task has finished, so the frame a contact is first detected
1421 // depends on wall-clock timing. Its grid has no such history. Chaos reads
1422 // this cvar when it builds a world's acceleration structures, and changing
1423 // it while they exist breaks the swap (a check in
1424 // CopyUnBuiltDynamicAccelerationStructures), hence here and not on
1425 // apply_settings.
1426 static const TCHAR *CVarName = TEXT("p.Chaos.AccelerationStructureUseDynamicTree");
1427 IConsoleVariable *CVar = IConsoleManager::Get().FindConsoleVariable(CVarName);
1428 if (CVar == nullptr)
1429 {
1431 {
1432 UE_LOG(LogCarla, Warning, TEXT("%s not found: collisions are not deterministic"), CVarName);
1433 }
1434 return;
1435 }
1437 {
1439 {
1441 }
1442 CVar->Set(0, ECVF_SetByCode);
1443 }
1445 {
1446 CVar->Set(DynamicTreeBeforeDeterministicCollisions.GetValue(), ECVF_SetByCode);
1448 }
1449}
1450
1452{
1454
1455 // A secondary plays the primary's frames: it is synchronous whatever it is told.
1456 const bool bWasSynchronous = bSynchronousMode;
1458
1459 // Tick cues sent while asynchronous were never consumed: entering synchronous
1460 // mode with them banked would run that many frames without any client
1461 // ticking, which breaks determinism. Start synchronous mode from zero, as a
1462 // fresh server does.
1463 if (bIsPrimaryServer && !bWasSynchronous && bSynchronousMode)
1464 {
1466 }
1467
1468#if WITH_EDITOR
1469 if (GEngine && GEngine->GameViewport)
1470 {
1471 // -RenderOffScreen keeps the invisible main viewport's world render off
1472 // regardless of the episode's no-rendering setting (see OnPostTick).
1473 GEngine->GameViewport->bDisableWorldRendering = Settings.bNoRenderingMode ||
1474 FParse::Param(FCommandLine::Get(), TEXT("RenderOffScreen"));
1475 }
1476#endif
1477 if (bIsPrimaryServer)
1478 {
1480 }
1481 else
1482 {
1483 // OnBeginFrame sets this server's time step from every primary frame. Its
1484 // sensor streams wait for slow clients instead of dropping their data.
1486 }
1487
1488 // Setting parameters for physics substepping
1489 UPhysicsSettings* PhysSett = UPhysicsSettings::Get();
1490 PhysSett->bSubstepping = Settings.bSubstepping;
1491 PhysSett->MaxSubstepDeltaTime = Settings.MaxSubstepDeltaTime;
1492 PhysSett->MaxSubsteps = Settings.MaxSubsteps;
1493
1494 UWorld* World = CurrentEpisode->GetWorld();
1495 ALargeMapManager* LargeMapManager = UCarlaStatics::GetLargeMapManager(World);
1496 if (LargeMapManager)
1497 {
1498 LargeMapManager->SetLayerStreamingDistance(Settings.TileStreamingDistance);
1499 LargeMapManager->SetActorStreamingDistance(Settings.ActorActiveDistance);
1500 }
1501}
1502
1504{
1505 bMapChanged = false;
1506}
static void FCarlaEngine_SetFixedDeltaSeconds(TOptional< double > FixedDeltaSeconds)
static bool FCarlaEngine_IsWorldTravelPending(const UWorld *World)
Whether a travel to another map is scheduled for World: load_world() only schedules it,...
static void FCarlaEngine_PrepareGeneratedWorld(UWorld *World, const carla::multigpu::LoadMapExtras &Extras)
Multi-GPU secondary: the world the primary generated from OpenDRIVE, where this server's OpenDriveMap...
static TAutoConsoleVariable< int32 > CVarCarlaMultiGpuVerifyFrames(TEXT("carla.MultiGpu.VerifyFrames"), 1, TEXT("does not parse completely with this build (1 = on, 0 = off)."), ECVF_Default)
static uint32 FCarlaEngine_GetNumberOfThreadsForRPCServer()
static bool FCarlaEngine_SameSettings(const FEpisodeSettings &A, const FEpisodeSettings &B)
static TOptional< double > FCarlaEngine_GetFixedDeltaSeconds()
FDataStreamTmpl< carla::streaming::Stream > FDataStream
Definition DataStream.h:80
void FrameTimeFromSettings(const FEpisodeSettings &Settings, carla::multigpu::FrameTime &Time)
Copies the episode settings into a FrameTime and back.
void SettingsFromFrameTime(const carla::multigpu::FrameTime &Time, FEpisodeSettings &Settings)
Base class for the CARLA Game Mode.
ATrafficLightManager * GetTrafficLightManager()
CarlaReplayer * GetReplayer(void)
void SetEpisode(UCarlaEpisode *ThisEpisode)
float GetLayerStreamingDistance() const
void SetActorStreamingDistance(float Distance)
void SetLayerStreamingDistance(float Distance)
float GetActorStreamingDistance() const
auto GetToken() const
Return the token that allows subscribing to this sensor's stream.
void SetDataStream(FDataStream InStream)
Replace the FDataStream associated with this sensor.
Class In charge of creating and assigning traffic light groups, controllers and components.
void CheckPlayAfterMapLoaded(void)
A view over an actor and its properties.
Definition CarlaActor.h:25
ActorType GetActorType() const
Definition CarlaActor.h:86
bool IsDormant() const
Definition CarlaActor.h:71
AActor * GetActor()
Definition CarlaActor.h:91
FTransform GetActorGlobalTransform() const
void SetActorGlobalTransform(const FTransform &Transform, ETeleportType Teleport=ETeleportType::TeleportPhysics)
FActorData * GetActorData()
Definition CarlaActor.h:205
void SendEpisodeReadyWhenContentReady()
Sends EPISODE_READY once the world's generated content has finished spawning.
void OnEpisodeSettingsChanged(const FEpisodeSettings &Settings)
uint64_t RestoredPoses
FDelegateHandle OnEpisodeSettingsChangeHandle
std::shared_ptr< carla::multigpu::Router > SecondaryServer
FDelegateHandle OnPostLoadMapHandle
uint64_t DeltaMismatches
FString LoadingMap
std::atomic< size_t > QueuedFrames
std::mutex FrameToProcessMutex
void OnPreTick(UWorld *World, ELevelTick TickType, float DeltaSeconds)
TSet< FName > RestoredPoseClasses
bool bWarnedSensorBindRefused
static uint64_t FrameCounter
Definition CarlaEngine.h:43
carla::multigpu::SensorStreamRegistry::epoch_type PendingLoadEpoch
static uint64_t GetFrameCounter()
Definition CarlaEngine.h:73
FDelegateHandle OnPreLoadMapHandle
void ResetSimulationState()
void MirrorPrimarySettings(const carla::multigpu::FrameTime &Time)
FWorldObserver WorldObserver
uint64_t DroppedFrames
FCarlaServer Server
FDelegateHandle OnBeginFrameHandle
static void ResetFrameCounter(uint64_t Value=0)
Definition CarlaEngine.h:89
bool bWarnedNoSensorTicks
void OnBeginFrame()
Secondary only (FCoreDelegates::OnBeginFrame, before the engine computes this frame's delta): waits f...
void NotifyEndEpisode()
std::atomic< bool > bResyncRequested
double LastOwnClockFrameSeconds
bool bFramesToProcessBacklogged
std::unordered_map< uint32_t, uint32_t > MappedId
double EpisodeReadyPendingSince
bool bWarnedFrameFormat
FEpisodeSettings CurrentSettings
void SuspendHeartBeatForLoad()
carla::multigpu::SensorStreamRegistry::epoch_type LoadingEpoch
bool bEpisodeReadyPending
bool bHeartBeatSuspendedForLoad
static uint64_t UpdateFrameCounter()
Definition CarlaEngine.h:78
void SendEpisodeReady()
Secondary only: tells the primary this episode is ready, which also makes it send a full resync.
std::atomic< bool > bLoadMapPending
UCarlaEpisode * CurrentEpisode
FMirrorState MirrorState
FDelegateHandle OnPreWorldInitializationHandle
std::vector< FFrameData > FramesToProcess
void DetachFromPrimary(const char *Reason)
Secondary only: stops mirroring the primary for good (it is gone, or this server cannot load its map)...
void BindReplayedSensor(uint32_t PrimaryActorId, uint32_t LocalActorId, bool bCreated)
Secondary only: binds a sensor replayed from the primary to the stream its clients were given (see ca...
void ResumeHeartBeatAfterLoad()
carla::multigpu::LoadMapExtras PendingLoadMapExtras
std::atomic< bool > bNewConnection
std::optional< uint64_t > PreparedFrame
void NotifyBeginEpisode(UCarlaEpisode &Episode)
void NotifyInitGame(const UCarlaSettings &Settings)
TOptional< int32 > DynamicTreeBeforeDeterministicCollisions
Value of p.Chaos.AccelerationStructureUseDynamicTree before deterministic collisions changed it; unse...
carla::multigpu::load_map_id_type LoadingLoadMapId
std::optional< FPendingFrameTime > PendingFrameTime
ACarlaRecorder * Recorder
void PlayPrimaryFrame(UWorld &World, float DeltaSeconds, FFrameData &Frame)
Secondary only: plays the primary's frame on the frame OnBeginFrame prepared, with the primary's cloc...
bool bIsPrimaryServer
bool bWarnedUntimedFrame
bool bWarnedUnpairedFrame
bool bFramePlayedThisTick
double LastResyncRequestSeconds
FString PendingLoadMap
bool bSynchronousMode
void WaitForSecondaryEpisodes()
Primary only: keeps processing RPC until every secondary sent LOAD_MAP reports its episode ready (bou...
FDelegateHandle OnPreTickHandle
std::optional< uint64_t > LastPlayedFrame
void RestorePlayedPoses()
Secondary only: puts back any mirror that moved since its frame was played (a local mover the mirror ...
carla::multigpu::SensorStreamRegistry SensorStreams
bool bWasConnectedToPrimary
FDelegateHandle OnTravelFailureHandle
FDelegateHandle OnPostTickHandle
std::shared_ptr< carla::multigpu::Secondary > Secondary
UCarlaEpisode * GetCurrentEpisode()
Definition CarlaEngine.h:63
void OnPreWorldInitialization(UWorld *World, const UWorld::InitializationValues IVS)
Applies FEpisodeSettings::bDeterministicCollisions to the world about to be created.
carla::multigpu::load_map_id_type PendingLoadMapId
void OnPostTick(UWorld *World, ELevelTick TickType, float DeltaSeconds)
bool TickCueReceived()
std::shared_ptr< carla::multigpu::Router > GetSecondaryServer()
void RunSome(uint32 Milliseconds)
void ResetTickCues()
Drops the tick cues banked so far.
carla::streaming::Server & GetStreamingServer()
void NotifyEndEpisode()
void NotifyBeginEpisode(UCarlaEpisode &Episode)
void SetIsSecondaryServer(bool bIsSecondary)
A Multi-GPU secondary refuses every call that would change its world.
FDataMultiStream Start(uint16_t RPCPort, uint16_t StreamingPort, uint16_t SecondaryPort)
void AsyncRun(uint32 NumberOfWorkerThreads)
static FOnEpisodeSettingsChange OnEpisodeSettingsChange
void GetFrameData(UCarlaEpisode *ThisEpisode, bool bAdditionalData=false, bool bIncludeActorsAgain=false)
Definition FrameData.cpp:33
void Write(std::ostream &OutStream)
void SetFrameTime(const carla::multigpu::FrameTime &Time)
Definition FrameData.h:190
bool HasSensorTicks() const
Whether the frame says which sensors tick (only older builds do not).
Definition FrameData.h:188
uint64_t GetFrameNumber() const
Definition FrameData.h:185
carla::multigpu::FrameDataReadResult Read(const uint8_t *Data, size_t Size)
Parses one SEND_FRAME payload.
const carla::multigpu::FrameTime * GetFrameTime() const
The primary's clocks and settings of this frame; null for a frame from an older primary.
Definition FrameData.h:194
void Clear()
void PlayFrameData(UCarlaEpisode *ThisEpisode, std::unordered_map< uint32_t, uint32_t > &MappedId, FMirrorState &MirrorState, TFunctionRef< void(uint32_t, uint32_t, bool)> OnActorAdded, TFunctionRef< void(uint32_t)> OnActorRemoved)
OnActorAdded receives (primary actor id, local actor id, whether it was just created rather than reus...
void PostPhysTick(UWorld *World, ELevelTick TickType, float DeltaSeconds)
auto GetToken() const
Return the token that allows subscribing to this sensor's stream.
void SetStream(FDataMultiStream InStream)
Replace the Stream associated with this sensor.
void BroadcastTick(const UCarlaEpisode &Episode, float DeltaSeconds, bool MapChange, bool PendingLightUpdate)
Send a message to every connected client with the info about the given Episode.
Mounts CARLA content packs (content-only Unreal plugins cooked as DLC against a base release,...
static UCarlaContentPackManager * Get()
A simulation episode.
FFrameData & GetFrameData()
double GetVisualGameTime() const
Visual game seconds.
FEpisodeSettings EpisodeSettings
static void ClearGeneratedWorldFiles()
Delete Saved/OpenDrive|Nav/OpenDriveMap.
FCarlaActor * FindCarlaActor(FCarlaActor::IdType ActorId)
Find a Carla actor by id.
const FString & GetMapName() const
void ApplySettings(const FEpisodeSettings &Settings)
double GetElapsedGameTime() const
Game seconds since the start of this episode.
const FEpisodeSettings & GetSettings() const
void SetRecorder(ACarlaRecorder *Rec)
void SetTimers(double InElapsedGameTime, double InVisualGameTime)
Multi-GPU secondary: adopt the primary's clocks for the frame being played.
void TickTimers(float DeltaSeconds)
const FActorRegistry & GetActorRegistry() const
ACarlaRecorder * GetRecorder() const
FSensorManager & GetSensorManager()
The game instance contains elements that must be kept alive in between levels.
void SetOpendriveGenerationParameters(const carla::rpc::OpendriveGenerationParameters &Parameters)
Global settings for CARLA.
uint32 StreamingPort
setting for the streaming port.
std::string PrimaryIP
setting for the IP and Port of the primary server to connect.
uint32 RPCPort
World port to listen for client connections.
uint32 SecondaryPort
setting for the secondary servers port.
static FString FindMapPath(const FString &MapName)
static UCarlaGameInstance * GetGameInstance(const UObject *WorldContextObject)
static ALargeMapManager * GetLargeMapManager(const UObject *WorldContextObject)
static ACarlaGameModeBase * GetGameMode(const UObject *WorldContextObject)
static FString GetSavedXODRPath(const FString &MapName)
Where a generated OpenDRIVE world stores its xodr: <ProjectSavedDir>/OpenDrive/<MapName>....
static void SetSavedXODRDirectory(const FString &Directory)
Multi-GPU secondary: a folder of this process for the generated worlds the primary sends,...
A piece of raw data.
static T UnPack(const Buffer &buffer)
Definition MsgPack.h:27
std::optional< token_type > Resolve(carla::streaming::Server &server, actor_id_type actor_id, stream_id_type primary_stream_id)
Token that serves primary actor actor_id under primary_stream_id, reserving a local stream if the sen...
epoch_type BeginEpisodeChange(carla::streaming::Server &server)
The primary switched episode: forgets every actor and returns the epoch the secondary must pass to Op...
bool IsEpisodeOpen()
Whether Bind()/Unbind() are accepted, i.e.
void OpenEpisode(epoch_type epoch)
Accepts binding if epoch is the latest one BeginEpisodeChange() issued.
std::optional< carla::streaming::Stream > Bind(carla::streaming::Server &server, actor_id_type actor_id, stream_id_type sensor_stream_id, bool can_adopt)
Returns the stream reserved for actor_id if can_adopt (the sensor has never ticked) and the sensor mu...
void Unbind(carla::streaming::Server &server, actor_id_type actor_id)
Forgets actor_id, closing its reserved stream if no sensor adopted it.
static std::shared_ptr< ROS2 > GetInstance()
Definition ROS2.h:61
std::optional< stream_id > FindStreamAlias(stream_id alias)
bool IsEnabledForROS(stream_id sensor_id)
void CloseStream(carla::streaming::detail::stream_id_type id)
void EnableForROS(stream_id sensor_id)
void SetStreamAlias(stream_id alias, stream_id target)
void SetROS2TopicVisibilityDefaultEnabled(bool enabled)
void DisableForROS(stream_id sensor_id)
void SetSynchronousMode(bool is_synchro)
void SetSessionsUseStreamAliases(bool enabled)
Serializes a stream endpoint.
bool IsConsecutive(std::optional< uint64_t > last_played, uint64_t frame)
Whether frame directly follows the last frame this secondary played.
Definition frameGate.h:69
bool IsUsableDelta(float delta_seconds)
Whether a primary's delta can be this engine frame's time step.
Definition frameGate.h:80
BeginFrameAction DecideBeginFrame(const BeginFrameState &state)
Definition frameGate.h:34
const char * FrameDataStatusName(FrameDataStatus status)
LoadMapRequest ParseLoadMapPayload(std::string_view payload)
Definition commands.h:90
PreTickAction DecidePreTick(bool load_map_pending, bool has_episode, bool frame_prepared, bool episode_world)
Definition frameGate.h:54
BeginFrameAction
What a secondary does at the start of an engine frame, before the engine computes the frame's time st...
Definition frameGate.h:16
@ OwnClock
Not connected to a primary: run on this server's own clock.
Definition frameGate.h:18
@ Wait
Wait for the primary's next frame and take its time step.
Definition frameGate.h:23
bool NeedsResync(std::optional< uint64_t > last_played, uint64_t frame, bool full_resync)
Whether playing frame shows that this secondary missed primary state (a frame went missing) that only...
Definition frameGate.h:75
PreTickAction
What a secondary does when its world starts ticking.
Definition frameGate.h:45
@ Skip
No primary frame: let the frame pass without simulation time.
Definition frameGate.h:51
@ OpenLevel
Open the map the primary loaded; nothing else this frame.
Definition frameGate.h:47
constexpr std::string_view kTokenNotReadyMarker
GET_TOKEN reply when the secondary cannot resolve the sensor to a stream (or the request is malformed...
Definition commands.h:159
std::string MakeEpisodeReadyMessage(load_map_id_type load_id)
Episode-ready message: the marker followed by the load id of the LOAD_MAP that started the episode,...
Definition commands.h:124
std::string GetAvailableMiddleware()
bool IsValidDomainId(int id)
constexpr int kMinDomainId
Lowest valid ROS 2 domain id.
constexpr int kMaxDomainId
Highest valid ROS 2 domain id (RTPS maximum).
constexpr int kUnsetDomainId
Sentinel domain id meaning "no domain id was configured on the command line"; each middleware falls b...
MiddlewareParseResult MiddlewareFromString(const std::string &name)
Parse a middleware name string (lowercase).
Definition Middleware.h:42
std::vector< std::pair< uint32_t, FTransform > > PlayedPoses
The poses the last frame played set, by local id, to check before the capture that nothing moved a mi...
Definition FrameData.h:70
void Reset()
Definition FrameData.h:79
bool IsComplete() const
Only a complete frame may be played.
uint32_t skipped
Packets whose id this build does not know.
uint32_t grown
Known packets with trailing bytes this build does not read (written by a newer build).
uint8_t packet_id
Id, offset and declared size of the last packet looked at.
Frame data packet 25: the primary's clocks and episode settings for one frame.
Definition frameTime.h:20
double elapsed_game_time
UCarlaEpisode clocks at the end of frame N.
Definition frameTime.h:37
float delta_seconds
The raw DeltaSeconds that UWorld::Tick(N) received, before time dilation and clamping.
Definition frameTime.h:34
uint64_t frame
Frame counter of frame N; equal to the frame's FrameCounter packet.
Definition frameTime.h:30
bool full_resync
Set on the frame that rebuilds a secondary from scratch (a new or reconnected secondary,...
Definition frameTime.h:67
float time_dilation
AWorldSettings::GetEffectiveTimeDilation() of frame N.
Definition frameTime.h:63
double world_time_seconds
UWorld clocks at the start of frame N, before UWorld::Tick adds the delta to them.
Definition frameTime.h:42
GET_TOKEN request payload.
Definition commands.h:151
What a LOAD_MAP carries besides the map: for a world the primary generated from OpenDRIVE (generate_o...
Definition commands.h:51
std::optional< std::string > generation_parameters
Definition commands.h:53
std::optional< std::string > opendrive
Definition commands.h:52