13#include "Engine/DecalActor.h"
14#include "Engine/LevelStreaming.h"
15#include "Engine/LocalPlayer.h"
16#include "Materials/MaterialInstanceDynamic.h"
17#include "Engine/StaticMeshActor.h"
20#include "EngineUtils.h"
30#include "Async/ParallelFor.h"
31#include "DynamicRHI.h"
33#include "DrawDebugHelpers.h"
34#include "Kismet/KismetSystemLibrary.h"
41 : Super(ObjectInitializer)
43 PrimaryActorTick.bCanEverTick =
true;
44 PrimaryActorTick.TickGroup = TG_PrePhysics;
45 bAllowTickBeforeBeginPlay =
false;
47 Episode = CreateDefaultSubobject<UCarlaEpisode>(TEXT(
"Episode"));
49 Recorder = CreateDefaultSubobject<ACarlaRecorder>(TEXT(
"Recorder"));
51 ObjectRegister = CreateDefaultSubobject<UObjectRegister>(TEXT(
"ObjectRegister"));
54 HUDClass = ACarlaHUD::StaticClass();
56 TaggerDelegate = CreateDefaultSubobject<UTaggerDelegate>(TEXT(
"TaggerDelegate"));
57 CarlaSettingsDelegate = CreateDefaultSubobject<UCarlaSettingsDelegate>(TEXT(
"CarlaSettingsDelegate"));
62 UWorld* World = GetWorld();
63 TSoftObjectPtr<UWorld> AssetPtr (World);
64 FString Path = FPaths::GetPath(AssetPtr.GetLongPackageName());
65 Path.RemoveFromStart(
"/Game/");
72 return FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()) + Path;
76 const FString &MapName,
77 const FString &Options,
78 FString &ErrorMessage)
81 Super::InitGame(MapName, Options, ErrorMessage);
83 UWorld* World = GetWorld();
84 check(World !=
nullptr);
85 FString InMapName(MapName);
89 TEXT(
"Missing episode, can't continue without an episode!"));
92 UGameplayStatics::GetActorOfClass(GetWorld(), ALargeMapManager::StaticClass());
93 LMManager = Cast<ALargeMapManager>(LMManagerActor);
106 FString CorrectedMapName = InMapName;
107 constexpr auto PIEPrefix = TEXT(
"UEDPIE_0_");
108 CorrectedMapName.RemoveFromStart(PIEPrefix);
109 UE_LOG(LogCarla, Log, TEXT(
"Corrected map name from %s to %s"), *InMapName, *CorrectedMapName);
116 GameInstance = Cast<UCarlaGameInstance>(GetGameInstance());
119 TEXT(
"GameInstance is not a UCarlaGameInstance, did you forget to set "
120 "it in the project settings?"));
125 UE_LOG(LogCarla, Error, TEXT(
"Missing TaggerDelegate!"));
132 UE_LOG(LogCarla, Error, TEXT(
"Missing CarlaSettingsDelegate!"));
136 UGameplayStatics::GetActorOfClass(GetWorld(), AWeather::StaticClass());
137 if (WeatherActor !=
nullptr) {
138 UE_LOG(LogCarla, Log, TEXT(
"Existing weather actor. Doing nothing then!"));
144 UE_LOG(LogCarla, Error, TEXT(
"Missing weather class!"));
174 Super::RestartPlayer(NewPlayer);
181 UWorld* World = GetWorld();
182 check(World !=
nullptr);
199 World->SpawnActor<ADecalActor>(
200 FVector(0,0,-1000000), FRotator(0,0,0), FActorSpawnParameters());
203 Manager->InitializeTrafficLights();
231 TArray<AActor*> FoundActors;
232 UGameplayStatics::GetAllActorsOfClass(World, AActor::StaticClass(), FoundActors);
233 for(
AActor* Actor : FoundActors)
235 TArray<UCarlaLight*> Lights;
236 Actor->GetComponents(Lights,
false);
237 for(UCarlaLight* Light : Lights)
239 Light->RegisterLight();
247 TArray<FString> Names;
248 TArray<AActor*> Actors;
249 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), Actors);
250 for (
AActor* Actor : Actors)
252 TArray<UStaticMeshComponent*> StaticMeshes;
253 Actor->GetComponents(StaticMeshes);
254 if (StaticMeshes.Num())
256 Names.Add(Actor->GetName());
264 TArray<AActor*> Actors;
265 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), Actors);
266 for (
AActor* Actor : Actors)
268 if(Actor->GetName() == ActorName)
279 FlushRenderingCommands();
280 TArray<FColor> Colors;
281 for (uint32_t y = 0; y < Texture.
GetHeight(); y++)
283 for (uint32_t x = 0; x < Texture.
GetWidth(); x++)
285 auto& Color = Texture.
At(x,y);
286 Colors.Add(FColor(Color.r, Color.g, Color.b, Color.a));
289 UTexture2D* UETexture = UTexture2D::CreateTransient(Texture.
GetWidth(), Texture.
GetHeight(), EPixelFormat::PF_B8G8R8A8);
290 FTexture2DMipMap& Mip = UETexture->PlatformData->Mips[0];
291 void* Data = Mip.BulkData.Lock( LOCK_READ_WRITE );
292 FMemory::Memcpy( Data,
295 Mip.BulkData.Unlock();
296 UETexture->UpdateResource();
302 FlushRenderingCommands();
303 TArray<FFloat16Color> Colors;
304 for (uint32_t y = 0; y < Texture.
GetHeight(); y++)
306 for (uint32_t x = 0; x < Texture.
GetWidth(); x++)
308 auto& Color = Texture.
At(x,y);
309 Colors.Add(FLinearColor(Color.r, Color.g, Color.b, Color.a));
312 UTexture2D* UETexture = UTexture2D::CreateTransient(Texture.
GetWidth(), Texture.
GetHeight(), EPixelFormat::PF_FloatRGBA);
313 FTexture2DMipMap& Mip = UETexture->PlatformData->Mips[0];
314 void* Data = Mip.BulkData.Lock( LOCK_READ_WRITE );
315 FMemory::Memcpy( Data,
318 Mip.BulkData.Unlock();
319 UETexture->UpdateResource();
329 TArray<UStaticMeshComponent*> StaticMeshes;
330 Actor->GetComponents(StaticMeshes);
331 for (UStaticMeshComponent* Mesh : StaticMeshes)
333 for (
int i = 0; i < Mesh->GetNumMaterials(); ++i)
335 UMaterialInterface* OriginalMaterial = Mesh->GetMaterial(i);
336 UMaterialInstanceDynamic* DynamicMaterial = Cast<UMaterialInstanceDynamic>(OriginalMaterial);
339 DynamicMaterial = UMaterialInstanceDynamic::Create(OriginalMaterial, NULL);
340 Mesh->SetMaterial(i, DynamicMaterial);
345 case cr::MaterialParameter::Tex_Diffuse:
346 DynamicMaterial->SetTextureParameterValue(
"BaseColor", Texture);
347 DynamicMaterial->SetTextureParameterValue(
"Difuse", Texture);
348 DynamicMaterial->SetTextureParameterValue(
"Difuse 2", Texture);
349 DynamicMaterial->SetTextureParameterValue(
"Difuse 3", Texture);
350 DynamicMaterial->SetTextureParameterValue(
"Difuse 4", Texture);
352 case cr::MaterialParameter::Tex_Normal:
353 DynamicMaterial->SetTextureParameterValue(
"Normal", Texture);
354 DynamicMaterial->SetTextureParameterValue(
"Normal 2", Texture);
355 DynamicMaterial->SetTextureParameterValue(
"Normal 3", Texture);
356 DynamicMaterial->SetTextureParameterValue(
"Normal 4", Texture);
358 case cr::MaterialParameter::Tex_Emissive:
359 DynamicMaterial->SetTextureParameterValue(
"Emissive", Texture);
361 case cr::MaterialParameter::Tex_Ao_Roughness_Metallic_Emissive:
362 DynamicMaterial->SetTextureParameterValue(
"AO / Roughness / Metallic / Emissive", Texture);
363 DynamicMaterial->SetTextureParameterValue(
"ORMH", Texture);
364 DynamicMaterial->SetTextureParameterValue(
"ORMH 2", Texture);
365 DynamicMaterial->SetTextureParameterValue(
"ORMH 3", Texture);
366 DynamicMaterial->SetTextureParameterValue(
"ORMH 4", Texture);
375 Super::Tick(DeltaSeconds);
391 Super::EndPlay(EndPlayReason);
401 auto *World = GetWorld();
402 check(World !=
nullptr);
406 if (FactoryClass !=
nullptr)
409 if (Factory !=
nullptr)
416 UE_LOG(LogCarla, Error, TEXT(
"Failed to spawn actor spawner"));
424 for (TActorIterator<AVehicleSpawnPoint> It(GetWorld()); It; ++It)
439 UE_LOG(LogCarla, Log, TEXT(
"Generating SpawnPoints ..."));
440 std::vector<std::pair<carla::road::element::Waypoint, carla::road::element::Waypoint>> Topology =
Map->GenerateTopology();
441 UWorld* World = GetWorld();
442 for(
auto& Pair : Topology)
445 FTransform Transform(CarlaTransform);
446 Transform.AddToTranslation(FVector(0.f, 0.f, 50.0f));
455 if (!
Map.has_value()) {
456 UE_LOG(LogCarla, Error, TEXT(
"Invalid Map"));
468 UWorld* World = GetWorld();
469 AActor* TrafficLightManagerActor = UGameplayStatics::GetActorOfClass(World, ATrafficLightManager::StaticClass());
470 if(TrafficLightManagerActor ==
nullptr)
472 FActorSpawnParameters SpawnParams;
486 TArray<AActor*> WorldActors;
487 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStaticMeshActor::StaticClass(), WorldActors);
489 for (
AActor *Actor : WorldActors)
491 AStaticMeshActor *MeshActor = CastChecked<AStaticMeshActor>(Actor);
492 if (MeshActor->GetStaticMeshComponent()->GetStaticMesh() == NULL)
494 UE_LOG(LogTemp, Error, TEXT(
"The object : %s has no mesh"), *MeshActor->GetFullName());
501 TArray<AActor*> WorldActors;
502 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AStaticMeshActor::StaticClass(), WorldActors);
504 for(
AActor *Actor : WorldActors)
506 AStaticMeshActor *MeshActor = CastChecked<AStaticMeshActor>(Actor);
507 if(MeshActor->GetStaticMeshComponent()->GetStaticMesh() != NULL)
511 if (MeshTag != crp::CityObjectLabel::Roads &&
512 MeshTag != crp::CityObjectLabel::Sidewalks &&
513 MeshTag != crp::CityObjectLabel::RoadLines &&
514 MeshTag != crp::CityObjectLabel::Ground &&
515 MeshTag != crp::CityObjectLabel::Terrain &&
516 MeshActor->GetStaticMeshComponent()->GetGenerateOverlapEvents() ==
false)
518 MeshActor->GetStaticMeshComponent()->SetGenerateOverlapEvents(
true);
527 auto World = GetWorld();
528 check(World !=
nullptr);
537 UKismetSystemLibrary::FlushDebugStrings(World);
538 UKismetSystemLibrary::FlushPersistentDebugLines(World);
543 const auto& Signals =
Map->GetSignals();
544 const auto& Controllers =
Map->GetControllers();
546 for(
const auto& Signal : Signals) {
547 const auto& ODSignal = Signal.second;
548 const FTransform Transform = ODSignal->GetTransform();
549 const FVector Location = Transform.GetLocation();
550 const FQuat Rotation = Transform.GetRotation();
562 TArray<const cre::RoadInfoSignal*> References;
563 auto waypoints =
Map->GenerateWaypointsOnRoadEntries();
564 std::unordered_set<cr::RoadId> ExploredRoads;
565 for (
auto & waypoint : waypoints)
568 if (ExploredRoads.count(waypoint.road_id) > 0)
572 ExploredRoads.insert(waypoint.road_id);
575 auto SignalReferences =
Map->GetLane(waypoint).
577 for (
auto *SignalReference : SignalReferences)
579 References.Add(SignalReference);
582 for (
auto& Reference : References)
584 auto RoadId = Reference->GetRoadId();
585 const auto* SignalReference = Reference;
586 const FTransform SignalTransform = SignalReference->GetSignal()->GetTransform();
587 for(
auto &validity : SignalReference->GetValidities())
594 auto signal_waypoint =
Map->GetWaypoint(
595 RoadId, lane, SignalReference->GetS()).get();
597 if(
Map->GetLane(signal_waypoint).GetType() != cr::Lane::LaneType::Driving)
600 FTransform ReferenceTransform =
Map->ComputeTransform(signal_waypoint);
604 ReferenceTransform.GetLocation(),
613 ReferenceTransform.GetLocation(),
614 SignalTransform.GetLocation(),
626 UWorld* World = GetWorld();
629 TArray<AActor*> FoundActors;
630 UGameplayStatics::GetAllActorsOfClass(World, AActor::StaticClass(), FoundActors);
632 TArray<FBoundingBox> BoundingBoxes;
635 return BoundingBoxes;
641 TArray<AActor*> FoundActors;
642 UGameplayStatics::GetAllActorsOfClass(GetWorld(), AActor::StaticClass(), FoundActors);
647 const TSet<uint64>& EnvObjectIds,
655 const UWorld* World = GetWorld();
656 UGameplayStatics::FlushLevelStreaming(World);
658 TArray<FName> LevelsToLoad;
661 FLatentActionInfo LatentInfo;
662 LatentInfo.CallbackTarget =
this;
663 LatentInfo.ExecutionFunction =
"OnLoadStreamLevel";
664 LatentInfo.Linkage = 0;
669 for(FName& LevelName : LevelsToLoad)
672 UGameplayStatics::LoadStreamLevel(World, LevelName,
true,
true, LatentInfo);
674 UGameplayStatics::FlushLevelStreaming(World);
680 const UWorld* World = GetWorld();
682 TArray<FName> LevelsToUnLoad;
685 FLatentActionInfo LatentInfo;
686 LatentInfo.CallbackTarget =
this;
687 LatentInfo.ExecutionFunction =
"OnUnloadStreamLevel";
689 LatentInfo.Linkage = 0;
693 for(FName& LevelName : LevelsToUnLoad)
696 UGameplayStatics::UnloadStreamLevel(World, LevelName, LatentInfo,
false);
698 UGameplayStatics::FlushLevelStreaming(World);
705 UWorld* World = GetWorld();
706 const TArray <ULevelStreaming*> Levels = World->GetStreamingLevels();
707 TArray<FString> LayersToLoad;
716 FString LayerName = UTF8_TO_TCHAR(MapLayerToString(
static_cast<crp::MapLayer>(LayerMask)).c_str());
720 LayersToLoad.Emplace(LayerName);
722 LayerMask = (LayerMask << 1) & AllLayersMask;
726 for(ULevelStreaming* Level : Levels)
728 TArray<FString> StringArray;
729 FString FullSubMapName = Level->GetWorldAssetPackageFName().ToString();
731 FullSubMapName.ParseIntoArray(StringArray, TEXT(
"/"),
false);
732 FString SubMapName = StringArray[StringArray.Num() - 1];
733 for(FString LayerName : LayersToLoad)
735 if(SubMapName.Contains(LayerName))
737 OutLevelNames.Emplace(FName(*SubMapName));
747 ULevel* OutLevel =
nullptr;
748 UWorld* World = GetWorld();
749 const TArray <ULevelStreaming*> Levels = World->GetStreamingLevels();
751 for(ULevelStreaming* Level : Levels)
753 FString FullSubMapName = Level->GetWorldAssetPackageFName().ToString();
754 if(FullSubMapName.Contains(LevelName))
756 OutLevel = Level->GetLoadedLevel();
759 UE_LOG(LogCarla, Warning, TEXT(
"%s has not been loaded"), *LevelName);
Base class for Carla actor factories.
TSubclassOf< AWeather > WeatherClass
The class of Weather to spawn.
void RegisterEnvironmentObjects()
boost::optional< carla::road::Map > Map
void UnLoadMapLayer(int32 MapLayers)
TArray< FTransform > SpawnPointsTransforms
void EnableEnvironmentObjects(const TSet< uint64 > &EnvObjectIds, bool Enable)
TArray< ACarlaActorFactory * > ActorFactoryInstances
void DebugShowSignals(bool enable)
void BeginPlay() override
UCarlaGameInstance * GameInstance
UCarlaSettingsDelegate * CarlaSettingsDelegate
AActor * FindActorByName(const FString &ActorName)
void LoadMapLayer(int32 MapLayers)
void InitGame(const FString &MapName, const FString &Options, FString &ErrorMessage) override
void CheckForEmptyMeshes()
void ApplyTextureToActor(AActor *Actor, UTexture2D *Texture, const carla::rpc::MaterialParameter &TextureParam)
const FString GetFullMapPath() const
ALargeMapManager * LMManager
void RestartPlayer(AController *NewPlayer) override
void SpawnActorFactories()
ACarlaRecorder * Recorder
void EnableOverlapEvents()
void EndPlay(const EEndPlayReason::Type EndPlayReason) override
ULevel * GetULevelFromName(FString LevelName)
FDelegateHandle OnEpisodeSettingsChangeHandle
const FString GetRelativeMapPath() const
void ConvertMapLayerMaskToMapNames(int32 MapLayer, TArray< FName > &OutLevelNames)
void GenerateSpawnPoints()
int PendingLevelsToUnLoad
UTaggerDelegate * TaggerDelegate
ATrafficLightManager * TrafficLightManager
UObjectRegister * ObjectRegister
void OnEpisodeSettingsChanged(const FEpisodeSettings &Settings)
ATrafficLightManager * GetTrafficLightManager()
TArray< FString > GetNamesOfAllActors()
void Tick(float DeltaSeconds) override
TArray< FBoundingBox > GetAllBBsOfLevel(uint8 TagQueried=0xFF) const
ACarlaGameModeBase(const FObjectInitializer &ObjectInitializer)
TSet< TSubclassOf< ACarlaActorFactory > > ActorFactories
List of actor spawners that will be used to define and spawn the actors available in game.
void OnUnloadStreamLevel()
bool ReadyToRegisterObjects
UTexture2D * CreateUETexture(const carla::rpc::TextureColor &Texture)
CarlaReplayer * GetReplayer(void)
void SetEpisode(UCarlaEpisode *ThisEpisode)
void RegisterInitialObjects()
void ConsiderSpectatorAsEgo(bool _SpectatorAsEgo)
static crp::CityObjectLabel GetTagOfTaggedComponent(const UPrimitiveComponent &Component)
Retrieve the tag of an already tagged component.
static void TagActorsInLevel(UWorld &World, bool bTagForSemanticSegmentation)
Set the tag of every actor in level.
Class In charge of creating and assigning traffic light groups, controllers and components.
void ApplyWeather(const FWeatherParameters &WeatherParameters)
Update the weather parameters and notifies it to the blueprint's event
void CheckPlayAfterMapLoaded(void)
static FOnEpisodeSettingsChange OnEpisodeSettingsChange
static TArray< FBoundingBox > GetBoundingBoxOfActors(const TArray< AActor * > &Actors, uint8 InTagQueried=0xFF)
void RegisterActorFactory(ACarlaActorFactory &ActorFactory)
carla::geom::GeoLocation MapGeoReference
const FEpisodeSettings & GetSettings() const
void SetRecorder(ACarlaRecorder *Rec)
void InitializeAtBeginPlay()
void NotifyBeginEpisode(UCarlaEpisode &Episode)
int32 GetCurrentMapLayer() const
void ApplyQualityLevelPreRestart()
Before loading a level, apply the current settings.
void ApplyQualityLevelPostRestart()
After loading a level, apply the current settings.
void Reset()
Reset settings to default.
void SetAllActorsDrawDistance(UWorld *world, float max_draw_distance) const
void RegisterSpawnHandler(UWorld *World)
Create the event trigger handler for all the newly spawned actors to be processed with a custom funct...
void EnableEnvironmentObjects(const TSet< uint64 > &EnvObjectIds, bool Enable)
void RegisterObjects(TArray< AActor * > Actors)
static FString GetXODR(const UWorld *World)
Return the OpenDrive XML associated to MapName, or empty if the file is not found.
void SetSemanticSegmentationEnabled(bool Enable=true)
void RegisterSpawnHandler(UWorld *World)
static std::vector< int > GenerateRange(int a, int b)
Vector3D GetUpVector() const
static boost::optional< road::Map > Load(const std::string &opendrive)
T & At(uint32_t x, uint32_t y)
uint32_t GetWidth() const
uint32_t GetHeight() const
static WeatherParameters Default