UnboundRun-data / code /ue_capture /ParkourCapture.cpp
teawhite's picture
Update dataset card, summaries, previews, thumbnails and code
2258c8d verified
Raw History Blame Contribute Delete
65.9 kB
#include "ParkourCapture.h"
#include "GameDemo.h"
#include "Animation/AnimInstanceProxy.h"
#include "Animation/AnimNodeBase.h"
#include "Animation/AnimSequence.h"
#include "Animation/AnimationPoseData.h"
#include "Camera/CameraActor.h"
#include "Camera/CameraComponent.h"
#include "Components/SceneCaptureComponent2D.h"
#include "Components/SkeletalMeshComponent.h"
#include "Components/StaticMeshComponent.h"
#include "Components/InstancedStaticMeshComponent.h"
#include "Components/DirectionalLightComponent.h"
#include "Components/SkyLightComponent.h"
#include "Components/ExponentialHeightFogComponent.h"
#include "Components/VolumetricCloudComponent.h"
#include "Components/SkyAtmosphereComponent.h"
#include "Components/LocalLightComponent.h"
#include "Components/DecalComponent.h"
#include "Engine/TextureRenderTarget2D.h"
#include "Engine/StaticMesh.h"
#include "Engine/SkeletalMesh.h"
#include "Engine/World.h"
#include "EngineUtils.h"
#include "GameFramework/PlayerController.h"
#include "Materials/MaterialInterface.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "Engine/Texture.h"
#include "Misc/App.h"
#include "Async/ParallelFor.h"
#include "Misc/CommandLine.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "HAL/PlatformTime.h"
#include "HAL/IConsoleManager.h"
#include "HAL/FileManager.h"
#include "Serialization/JsonSerializer.h"
#include "Serialization/JsonWriter.h"
#include "TextureResource.h"
#include "Math/InverseRotationMatrix.h"
#include "ImageUtils.h"
#include "ImageCore.h"
#include "Async/Async.h"
#include "Modules/ModuleManager.h"
#include "ShaderCompiler.h"
#if WITH_EDITOR
#include "AssetCompilingManager.h"
#endif
namespace
{
using JOPK=TSharedPtr<FJsonObject>;
TSharedPtr<FJsonValue> PkNum(double V){return MakeShared<FJsonValueNumber>(V);}
TArray<TSharedPtr<FJsonValue>> PkVec(const FVector& V){return {PkNum(V.X),PkNum(V.Y),PkNum(V.Z)};}
TArray<TSharedPtr<FJsonValue>> PkMat(const FMatrix& M){TArray<TSharedPtr<FJsonValue>> A;for(int I=0;I<4;I++)for(int J=0;J<4;J++)A.Add(PkNum(M.M[I][J]));return A;}
bool PkSaveJSON(JOPK J,const FString& Path){FString S;auto W=TJsonWriterFactory<>::Create(&S);FJsonSerializer::Serialize(J.ToSharedRef(),W);return FFileHelper::SaveStringToFile(S,*Path,FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);}
bool PkLoadJSON(const FString& Path,JOPK& Out){FString Text;if(!FFileHelper::LoadFileToString(Text,*Path))return false;auto R=TJsonReaderFactory<>::Create(Text);return FJsonSerializer::Deserialize(R,Out)&&Out.IsValid();}
void PkFloats(const JOPK& O,const TCHAR* Field,TArray<float>& Out)
{
Out.Reset();const TArray<TSharedPtr<FJsonValue>>* A=nullptr;
if(O->TryGetArrayField(FString(Field),A)){Out.Reserve(A->Num());for(const TSharedPtr<FJsonValue>& V:*A)Out.Add(float(V->AsNumber()));}
}
void PkCV(const TCHAR* Name,int Value){if(auto* C=IConsoleManager::Get().FindConsoleVariable(Name))C->Set(Value,ECVF_SetByCode);}
bool PkIsFinger(const FString& N){for(const TCHAR* K:{TEXT("thumb"),TEXT("index"),TEXT("middle"),TEXT("ring"),TEXT("pinky")})if(N.Contains(K))return true;return false;}
// bone, child whose position defines the bone direction, pk joint that child must reach
const TCHAR* const GPkAim[12][3]={
{TEXT("upperarm_l"),TEXT("lowerarm_l"),TEXT("elbow_l")},{TEXT("lowerarm_l"),TEXT("hand_l"),TEXT("wrist_l")},{TEXT("hand_l"),TEXT("middle_01_l"),TEXT("knuckle_l")},
{TEXT("upperarm_r"),TEXT("lowerarm_r"),TEXT("elbow_r")},{TEXT("lowerarm_r"),TEXT("hand_r"),TEXT("wrist_r")},{TEXT("hand_r"),TEXT("middle_01_r"),TEXT("knuckle_r")},
{TEXT("thigh_l"),TEXT("calf_l"),TEXT("knee_l")},{TEXT("calf_l"),TEXT("foot_l"),TEXT("ankle_l")},{TEXT("foot_l"),TEXT("ball_l"),TEXT("ball_l")},
{TEXT("thigh_r"),TEXT("calf_r"),TEXT("knee_r")},{TEXT("calf_r"),TEXT("foot_r"),TEXT("ankle_r")},{TEXT("foot_r"),TEXT("ball_r"),TEXT("ball_r")}};
const TCHAR* PkMeshPath(const FString& Model)
{
return Model==TEXT("quinn")?TEXT("/Game/Characters/Mannequins/Meshes/SKM_Quinn_Simple.SKM_Quinn_Simple"):TEXT("/Game/Characters/Mannequins/Meshes/SKM_Manny_Simple.SKM_Manny_Simple");
}
}
// =============================================================================================
// Body animation: reference pose (fingers from a clip), limbs aimed onto the pk joints, hidden head.
// =============================================================================================
struct FParkourAnimProxy : FAnimInstanceProxy
{
FPkPose P;
FParkourAnimProxy(UAnimInstance* I):FAnimInstanceProxy(I){}
virtual void PreUpdate(UAnimInstance* I,float Dt) override
{
FAnimInstanceProxy::PreUpdate(I,Dt);
if(const UParkourAnim* A=Cast<UParkourAnim>(I))P=A->Pose;
}
virtual bool Evaluate(FPoseContext& Output) override
{
Output.ResetToRefPose();
const FBoneContainer& Bones=Output.Pose.GetBoneContainer();
const FReferenceSkeleton& RefSkel=Bones.GetReferenceSkeleton();
if(P.Fingers)
{
FPoseContext Clip(this);Clip.ResetToRefPose();
FAnimationPoseData D(Clip);
P.Fingers->GetAnimationPose(D,FAnimExtractContext(double(FMath::Clamp(P.FingerT,0.f,FMath::Max(.001f,P.Fingers->GetPlayLength()-.0001f))),false));
for(FCompactPoseBoneIndex I:Output.Pose.ForEachBoneIndex())
if(PkIsFinger(RefSkel.GetBoneName(Bones.MakeMeshPoseIndex(I).GetInt()).ToString()))Output.Pose[I]=Clip.Pose[I];
}
auto Find=[&](const TCHAR* N)->int32
{
const int32 Mesh=RefSkel.FindBoneIndex(FName(N));
if(Mesh==INDEX_NONE)return INDEX_NONE;
return Bones.MakeCompactPoseIndex(FMeshPoseBoneIndex(Mesh)).GetInt();
};
const int32 Count=Output.Pose.GetNumBones();
TArray<FTransform> CS;CS.SetNum(Count);
auto Rebuild=[&]()
{
for(FCompactPoseBoneIndex I:Output.Pose.ForEachBoneIndex())
{
const int32 Pa=Bones.GetParentBoneIndex(I).GetInt();
CS[I.GetInt()]=Pa==INDEX_NONE?Output.Pose[I]:Output.Pose[I]*CS[Pa];
}
};
Rebuild();
if(P.Valid&&P.Targets.Num()==12)
{
for(int32 K=0;K<12;K++)
{
const int32 Bone=Find(GPkAim[K][0]),Child=Find(GPkAim[K][1]);
if(Bone<0||Child<0)continue;
const FVector CurDir=(CS[Child].GetLocation()-CS[Bone].GetLocation()).GetSafeNormal();
const FVector Tgt=(P.Targets[K]-CS[Bone].GetLocation()).GetSafeNormal();
if(CurDir.IsNearlyZero()||Tgt.IsNearlyZero())continue;
const FQuat Q=FQuat::FindBetweenNormals(CurDir,Tgt);
FTransform N=CS[Bone];N.SetRotation((Q*N.GetRotation()).GetNormalized());
const int32 Pa=Bones.GetParentBoneIndex(FCompactPoseBoneIndex(Bone)).GetInt();
const FTransform L=Pa==INDEX_NONE?N:N.GetRelativeTransform(CS[Pa]);
Output.Pose[FCompactPoseBoneIndex(Bone)].SetRotation(L.GetRotation().GetNormalized());
Rebuild();
}
}
const int32 Head=Find(TEXT("head"));
if(Head!=INDEX_NONE)Output.Pose[FCompactPoseBoneIndex(Head)].SetScale3D(FVector(P.HeadScale));
Output.Pose.NormalizeRotations();
return true;
}
};
UParkourAnim::UParkourAnim(){bUseMultiThreadedAnimationUpdate=false;}
FAnimInstanceProxy* UParkourAnim::CreateAnimInstanceProxy(){return new FParkourAnimProxy(this);}
void UParkourAnim::DestroyAnimInstanceProxy(FAnimInstanceProxy* P){delete P;}
AParkourDriver::AParkourDriver(){PrimaryActorTick.bCanEverTick=true;PrimaryActorTick.TickGroup=TG_PrePhysics;}
void AParkourDriver::Tick(float Dt){Super::Tick(Dt);if(CaptureOwner)CaptureOwner->PreStep(Dt);}
// =============================================================================================
AParkourCapture::AParkourCapture()
{
PrimaryActorTick.bCanEverTick=true;PrimaryActorTick.TickGroup=TG_PostUpdateWork;
RootComponent=CreateDefaultSubobject<USceneComponent>(TEXT("ParkourRoot"));
RGB=CreateDefaultSubobject<USceneCaptureComponent2D>(TEXT("PkRGB"));
Labels=CreateDefaultSubobject<USceneCaptureComponent2D>(TEXT("PkLabels"));
Whitebox=CreateDefaultSubobject<USceneCaptureComponent2D>(TEXT("PkWhitebox"));
for(auto* C:{RGB.Get(),Labels.Get(),Whitebox.Get()})
{
C->SetupAttachment(RootComponent);C->bCaptureEveryFrame=false;C->bCaptureOnMovement=false;C->bAlwaysPersistRenderingState=true;
C->ShowFlags.SetTemporalAA(false);C->ShowFlags.SetAntiAliasing(false);C->ShowFlags.SetMotionBlur(false);C->ShowFlags.SetDepthOfField(false);
C->ShowFlags.SetScreenPercentage(false);C->ShowFlags.SetPostProcessing(true);C->ShowFlags.SetPostProcessMaterial(true);C->ShowFlags.SetTonemapper(true);
}
}
void AParkourCapture::Fail(const FString& Reason)
{
Finished=true;JOPK J=MakeShared<FJsonObject>();J->SetBoolField(TEXT("ok"),false);J->SetStringField(TEXT("error"),Reason);
if(!Directory.IsEmpty()&&!FPaths::FileExists(Directory/TEXT("capture_result.json")))PkSaveJSON(J,Directory/TEXT("capture_result.json"));
UE_LOG(LogTemp,Error,TEXT("PARKOUR FAILURE: %s"),*Reason);
FPlatformMisc::RequestExit(false);
}
void AParkourCapture::DumpSkeleton(const FString& Path)
{
// Reference pose, component space rotated into body space (X forward, Y right, Z up; feet at the origin), scale 1.
JOPK Root=MakeShared<FJsonObject>();const FTransform Rel(FRotator(0,-90,0));
for(const FString Model:{FString(TEXT("manny")),FString(TEXT("quinn"))})
{
USkeletalMesh* Mesh=LoadObject<USkeletalMesh>(nullptr,PkMeshPath(Model));
if(!Mesh){Fail(TEXT("Missing mannequin mesh for skeleton dump"));return;}
const FReferenceSkeleton& R=Mesh->GetRefSkeleton();
TArray<FTransform> CS;CS.SetNum(R.GetNum());JOPK M=MakeShared<FJsonObject>();JOPK Par=MakeShared<FJsonObject>();
for(int32 I=0;I<R.GetNum();I++)
{
const int32 Pa=R.GetParentIndex(I);CS[I]=Pa==INDEX_NONE?R.GetRefBonePose()[I]:R.GetRefBonePose()[I]*CS[Pa];
M->SetArrayField(R.GetBoneName(I).ToString(),PkVec(Rel.TransformPosition(CS[I].GetLocation())));
Par->SetStringField(R.GetBoneName(I).ToString(),Pa==INDEX_NONE?FString():R.GetBoneName(Pa).ToString());
}
JOPK O=MakeShared<FJsonObject>();O->SetObjectField(TEXT("bones"),M);O->SetObjectField(TEXT("parents"),Par);Root->SetObjectField(Model,O);
}
PkSaveJSON(Root,Path);
UE_LOG(LogTemp,Display,TEXT("PARKOUR skeleton written to %s"),*Path);
Finished=true;FPlatformMisc::RequestExit(false);
}
void AParkourCapture::BeginPlay()
{
Super::BeginPlay();
const TCHAR* Cmd=FCommandLine::Get();
FString SkeletonPath;
if(FParse::Value(Cmd,TEXT("ParkourDumpSkeleton="),SkeletonPath)){DumpSkeleton(SkeletonPath);return;}
FParse::Value(Cmd,TEXT("DatasetOutput="),Directory);FParse::Value(Cmd,TEXT("ParkourEpisodes="),EpisodeDir);
FParse::Value(Cmd,TEXT("DatasetWidth="),Width);FParse::Value(Cmd,TEXT("DatasetHeight="),Height);
FParse::Value(Cmd,TEXT("DatasetFrames="),Frames);FParse::Value(Cmd,TEXT("DatasetWarmup="),Warmup);FParse::Value(Cmd,TEXT("DatasetSimHz="),SimHz);
FParse::Value(Cmd,TEXT("DatasetStride="),Stride);FParse::Value(Cmd,TEXT("DatasetWarmupWallSeconds="),WarmupWallSeconds);FParse::Value(Cmd,TEXT("DatasetSeed="),Seed);
FParse::Value(Cmd,TEXT("DatasetJpegQuality="),JpegQuality);FParse::Value(Cmd,TEXT("DatasetWhiteboxJpegQuality="),WhiteboxQuality);
FParse::Value(Cmd,TEXT("DatasetMainViewPercent="),MainViewPercent);FParse::Value(Cmd,TEXT("DatasetAppearance="),AppearanceName);
FParse::Value(Cmd,TEXT("DatasetAppearanceSeed="),AppearanceSeed);FParse::Value(Cmd,TEXT("ParkourSettleSteps="),Settle);
FParse::Value(Cmd,TEXT("ParkourSunYawJitter="),SunYawJitter);FParse::Value(Cmd,TEXT("DatasetWhiteboxExposureBias="),WhiteboxExposureBias);
UEWhitebox=FParse::Param(Cmd,TEXT("ParkourUEWhitebox"));
FParse::Value(Cmd,TEXT("ParkourSSAA="),SS);SS=FMath::Clamp(SS,1,3);FParse::Value(Cmd,TEXT("ParkourSharpen="),Sharpen);Sharpen=FMath::Clamp(Sharpen,0.f,1.5f);LookV3=!FParse::Param(Cmd,TEXT("ParkourLookV2"));
AppRng.Initialize(AppearanceSeed*7+3);
if(SimHz<16||SimHz>240||Stride<1||Stride>30){Fail(TEXT("Invalid simulation rate or stride"));return;}
SimStep=1.0/SimHz;
if(Directory.IsEmpty()||EpisodeDir.IsEmpty()||Width<64||Height<64||Frames<1){Fail(TEXT("Invalid dataset arguments (need DatasetOutput and ParkourEpisodes)"));return;}
if(FPaths::FileExists(Directory/TEXT("capture_result.json"))){Fail(TEXT("Refuse to overwrite an existing capture"));return;}
IFileManager::Get().MakeDirectory(*(Directory/TEXT("raw")),true);
FModuleManager::Get().LoadModule(TEXT("ImageWrapper"));
{TArray<FColor> Probe;Probe.Init(FColor::Black,16);TArray<uint8> ProbeG;ProbeG.Init(0,16);TArray64<uint8> Out;
FImageUtils::CompressImage(Out,TEXT("jpg"),FImageView(Probe.GetData(),4,4,EGammaSpace::sRGB),90);
FImageUtils::CompressImage(Out,TEXT("png"),FImageView(ProbeG.GetData(),4,4,1,ERawImageFormat::G8,EGammaSpace::Linear),0);}
FApp::SetUseFixedTimeStep(true);FApp::SetFixedDeltaTime(SimStep);
PkCV(TEXT("r.CustomDepth"),3);PkCV(TEXT("r.AntiAliasingMethod"),0);PkCV(TEXT("r.MotionBlurQuality"),0);PkCV(TEXT("r.DepthOfFieldQuality"),0);
PkCV(TEXT("r.ScreenPercentage.Mode"),0);PkCV(TEXT("r.ScreenPercentage"),FMath::Clamp(MainViewPercent,10,100));PkCV(TEXT("r.DynamicRes.OperationMode"),0);
Driver=GetWorld()->SpawnActor<AParkourDriver>();Driver->CaptureOwner=this;
}
void AParkourCapture::LoadAssets()
{
Cube=LoadObject<UStaticMesh>(nullptr,TEXT("/Engine/BasicShapes/Cube.Cube"));Cylinder=LoadObject<UStaticMesh>(nullptr,TEXT("/Engine/BasicShapes/Cylinder.Cylinder"));
Sphere=LoadObject<UStaticMesh>(nullptr,TEXT("/Engine/BasicShapes/Sphere.Sphere"));
WhiteMat=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Generated/Parkour/M_PK_Whitebox.M_PK_Whitebox"));
if(!WhiteMat)WhiteMat=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Generated/Data/M_Whitebox.M_Whitebox"));
FingerClip=LoadObject<UAnimSequence>(nullptr,TEXT("/Game/Characters/Mannequins/Anims/Unarmed/MM_Idle.MM_Idle"));
if(!Cube||!Cylinder||!Sphere||!WhiteMat){Fail(TEXT("Missing engine shapes or whitebox material"));return;}
FString Text;
if(!FFileHelper::LoadFileToString(Text,*(FPaths::ProjectContentDir()/TEXT("Generated/Parkour/parkour_materials.json")))){Fail(TEXT("Missing parkour material manifest"));return;}
TSharedPtr<FJsonObject> Root;auto Reader=TJsonReaderFactory<>::Create(Text);
if(!FJsonSerializer::Deserialize(Reader,Root)||!Root.IsValid()){Fail(TEXT("Bad parkour material manifest"));return;}
for(const TSharedPtr<FJsonValue>& V:Root->GetArrayField(TEXT("materials")))
{
const TSharedPtr<FJsonObject> O=V->AsObject();const FString Name=O->GetStringField(TEXT("name")).ToLower();
UMaterialInterface* M=LoadObject<UMaterialInterface>(nullptr,*O->GetStringField(TEXT("mic")));if(!M)continue;
static const TCHAR* Exclude[]={TEXT("water"),TEXT("ice"),TEXT("fern"),TEXT("periwinkle"),TEXT("scan_"),TEXT("bark"),TEXT("root"),TEXT("rope"),TEXT("pages"),TEXT("marking"),TEXT("_wear"),TEXT("stream"),TEXT("moss_set"),TEXT("plant")};
bool Skip=false;for(const TCHAR* E:Exclude)if(Name.Contains(E))Skip=true;
if(Skip)continue;
const int32 Idx=Mats.Num();Mats.Add({Name,M});KeepAlive.Add(M);
double Tile=0;O->TryGetNumberField(FString(TEXT("tile_cm")),Tile);MatTile.Add(float(Tile));
FString Src;O->TryGetStringField(FString(TEXT("source")),Src);MatCC0.Add(Src==TEXT("cc0"));
if(Name.Contains(TEXT("rock"))||Name.Contains(TEXT("boulder"))||Name.Contains(TEXT("cliff")))RockIdx.Add(Idx); // falling rocks (cc0 rock sets included)
if(Src==TEXT("cc0"))continue; // CC0 sets are only used through the style role pools
auto Has=[&](std::initializer_list<const TCHAR*> Keys){for(const TCHAR* K:Keys)if(Name.Contains(K))return true;return false;};
if(Name.StartsWith(TEXT("ad_"))){AdIdx.Add(Idx);continue;}
if(Has({TEXT("glass"),TEXT("shutter"),TEXT("recess"),TEXT("door"),TEXT("window")}))DarkIdx.Add(Idx);
if(Has({TEXT("timber"),TEXT("wood"),TEXT("deck"),TEXT("plank")}))WoodIdx.Add(Idx);
if(Has({TEXT("iron"),TEXT("steel"),TEXT("bronze"),TEXT("brass"),TEXT("copper"),TEXT("metal"),TEXT("hull"),TEXT("fittings"),TEXT("structure"),TEXT("frame")}))MetalIdx.Add(Idx);
if(Has({TEXT("timber"),TEXT("trim"),TEXT("coping"),TEXT("frame"),TEXT("border"),TEXT("iron"),TEXT("steel"),TEXT("bronze")}))TrimIdx.Add(Idx);
if(Has({TEXT("paving"),TEXT("gravel"),TEXT("soil"),TEXT("earth"),TEXT("ground"),TEXT("sand"),TEXT("asphalt"),TEXT("setts"),TEXT("cobble"),TEXT("pavers"),TEXT("court"),TEXT("meadow"),TEXT("seabed"),TEXT("packed_snow"),TEXT("terrain"),TEXT("walk"),TEXT("route"),TEXT("yard")})&&!Has({TEXT("roof")}))GroundIdx.Add(Idx);
if(Has({TEXT("roof"),TEXT("tile"),TEXT("slate"),TEXT("deck"),TEXT("paving"),TEXT("concrete"),TEXT("pavers"),TEXT("inlay"),TEXT("plank"),TEXT("course")}))RoofIdx.Add(Idx);
if(Has({TEXT("plaster"),TEXT("wall"),TEXT("facade"),TEXT("brick"),TEXT("stone"),TEXT("limestone"),TEXT("sandstone"),TEXT("render"),TEXT("concrete"),TEXT("blocks"),TEXT("hull"),TEXT("basalt"),TEXT("storefront"),TEXT("masonry"),TEXT("adobe"),TEXT("foundation"),TEXT("raised"),TEXT("kiln")})&&!Has({TEXT("paving"),TEXT("soil"),TEXT("gravel")}))WallIdx.Add(Idx);
}
if(Mats.Num()==0){Fail(TEXT("No usable tiling materials in this scene"));return;}
// style role pools + palettes (manifest v2)
Root->TryGetStringField(FString(TEXT("style")),StyleName);
static const TCHAR* RoleNames[]={TEXT("wall"),TEXT("roof"),TEXT("tiles"),TEXT("trim"),TEXT("wood"),TEXT("shutter"),TEXT("frame"),TEXT("metal"),TEXT("concrete"),TEXT("ground")};
const TSharedPtr<FJsonObject>* RolesJ=nullptr;
if(Root->TryGetObjectField(FString(TEXT("roles")),RolesJ))
for(const TCHAR* RN:RoleNames)
{
const TArray<TSharedPtr<FJsonValue>>* Arr=nullptr;
if(!(*RolesJ)->TryGetArrayField(FString(RN),Arr))continue;
TArray<int32> Pool;
for(const TSharedPtr<FJsonValue>& V:*Arr){const FString N=V->AsString().ToLower();for(int32 I=0;I<Mats.Num();I++)if(Mats[I].Key==N)Pool.Add(I);}
RolePools.Add(FString(RN),Pool);
}
const TSharedPtr<FJsonObject>* PalJ=nullptr;
if(Root->TryGetObjectField(FString(TEXT("palettes")),PalJ))
for(const TCHAR* RN:RoleNames)
{
const TArray<TSharedPtr<FJsonValue>>* Arr=nullptr;
if(!(*PalJ)->TryGetArrayField(FString(RN),Arr))continue;
TArray<FLinearColor> P;
for(const TSharedPtr<FJsonValue>& V:*Arr){const TArray<TSharedPtr<FJsonValue>>& C=V->AsArray();if(C.Num()>=3)P.Add(FLinearColor(C[0]->AsNumber(),C[1]->AsNumber(),C[2]->AsNumber()));}
Palettes.Add(FString(RN),P);
}
BoxMat=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Generated/Parkour/M_ParkourBox.M_ParkourBox"));
WhiteTex=LoadObject<UTexture>(nullptr,TEXT("/Engine/EngineResources/WhiteSquareTexture.WhiteSquareTexture"));
{FString Pools;for(const auto& KV:RolePools)Pools+=FString::Printf(TEXT("%s=%d "),*KV.Key,KV.Value.Num());UE_LOG(LogTemp,Display,TEXT("PARKOUR style=%s pools: %s"),*StyleName,*Pools);}
TArray<int32> All;for(int32 I=0;I<Mats.Num();I++)if(!MatCC0[I])All.Add(I);
for(TArray<int32>* Pool:{&WallIdx,&RoofIdx,&GroundIdx,&TrimIdx,&WoodIdx,&MetalIdx})if(Pool->Num()==0)*Pool=All;
UE_LOG(LogTemp,Display,TEXT("PARKOUR materials=%d wall=%d roof=%d ground=%d trim=%d dark=%d ad=%d metal=%d wood=%d"),Mats.Num(),WallIdx.Num(),RoofIdx.Num(),GroundIdx.Num(),TrimIdx.Num(),DarkIdx.Num(),AdIdx.Num(),MetalIdx.Num(),WoodIdx.Num());
}
void AParkourCapture::HideScene()
{
for(TActorIterator<AActor> I(GetWorld());I;++I)
{
AActor* A=*I;if(A==this||A==Driver.Get()||A==ViewCam.Get())continue;
bool HasMesh=false,IsSky=false,HasLocal=false,HasDecal=false;
TArray<UActorComponent*> Comps;A->GetComponents(Comps);
for(UActorComponent* C:Comps)
{
if(auto* SM=Cast<UStaticMeshComponent>(C))
{
HasMesh=true;const FString N=GetNameSafe(SM->GetStaticMesh()).ToLower();
if(N.Contains(TEXT("sky"))||SM->Bounds.SphereRadius>200000.f)IsSky=true;
for(int32 K=0;K<SM->GetNumMaterials();K++)if(GetNameSafe(SM->GetMaterial(K)).ToLower().Contains(TEXT("sky")))IsSky=true;
}
else if(C->IsA<USkeletalMeshComponent>()||C->GetClass()->GetName().Contains(TEXT("Landscape")))HasMesh=true;
else if(C->IsA<ULocalLightComponent>())HasLocal=true;
else if(C->IsA<UDecalComponent>())HasDecal=true;
}
if((HasMesh&&!IsSky)||HasLocal||HasDecal)
{
A->SetActorHiddenInGame(true);A->SetActorEnableCollision(false);A->SetActorTickEnabled(false);
for(UActorComponent* C:Comps)
{
if(auto* L=Cast<ULocalLightComponent>(C))L->SetVisibility(false);
if(C->IsA<USkeletalMeshComponent>()||C->GetClass()->GetName().Contains(TEXT("Movement")))C->SetComponentTickEnabled(false);
}
}
}
}
bool AParkourCapture::SetupBody(const FString& Model,float Scale,int32 Skin)
{
ModelName=Model==TEXT("quinn")?TEXT("quinn"):TEXT("manny");const bool Quinn=ModelName==TEXT("quinn");
USkeletalMesh* Mesh=LoadObject<USkeletalMesh>(nullptr,PkMeshPath(ModelName));
if(!Mesh){Fail(TEXT("Missing mannequin mesh"));return false;}
KeepAlive.Add(Mesh);
TArray<UMaterialInterface*> Skins;
for(const TCHAR* P:Quinn?TArray<const TCHAR*>{TEXT("/Game/Characters/Mannequins/Materials/Quinn/MI_Quinn_01.MI_Quinn_01"),TEXT("/Game/Characters/Mannequins/Materials/Quinn/MI_Quinn_02.MI_Quinn_02")}
:TArray<const TCHAR*>{TEXT("/Game/Characters/Mannequins/Materials/Manny/MI_Manny_01_New.MI_Manny_01_New"),TEXT("/Game/Characters/Mannequins/Materials/Manny/MI_Manny_02_New.MI_Manny_02_New")})
if(UMaterialInterface* M=LoadObject<UMaterialInterface>(nullptr,P)){Skins.Add(M);KeepAlive.Add(M);}
BodyScale=Scale;
BodyRoot=NewObject<USceneComponent>(this,TEXT("PkBodyRoot"));BodyRoot->SetupAttachment(RootComponent);BodyRoot->SetUsingAbsoluteLocation(true);BodyRoot->SetUsingAbsoluteRotation(true);BodyRoot->RegisterComponent();
auto Make=[&](const TCHAR* Name)->USkeletalMeshComponent*
{
auto* C=NewObject<USkeletalMeshComponent>(this,Name);C->SetupAttachment(BodyRoot);C->SetSkeletalMeshAsset(Mesh);
C->SetRelativeRotation(FRotator(0,-90,0));C->SetRelativeScale3D(FVector(BodyScale));
C->VisibilityBasedAnimTickOption=EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones;C->bEnableUpdateRateOptimizations=false;
C->SetCollisionEnabled(ECollisionEnabled::NoCollision);C->SetGenerateOverlapEvents(false);return C;
};
Body=Make(TEXT("PkBody"));
Body->SetAnimationMode(EAnimationMode::AnimationBlueprint);Body->SetAnimInstanceClass(UParkourAnim::StaticClass());
const int32 SkinMode=FMath::Clamp(Skin,0,3);SkinName=FString::Printf(TEXT("mat%d"),SkinMode);
if(Skins.Num()>=2)
{
if(SkinMode==1&&Mesh->GetMaterials().Num()>=2){Body->SetMaterial(0,Skins[1]);Body->SetMaterial(1,Skins[0]);}
else if(SkinMode>=2)for(int32 S=0;S<Mesh->GetMaterials().Num();S++)Body->SetMaterial(S,Skins[SkinMode-2]);
}
Body->SetRenderCustomDepth(true);Body->SetCustomDepthStencilValue(10);
Body->RegisterComponent();
Body->PrimaryComponentTick.AddPrerequisite(Driver,Driver->PrimaryActorTick);
if(UEWhitebox)
{
BodyWB=Make(TEXT("PkBodyWhitebox"));
for(int32 S=0;S<Mesh->GetMaterials().Num();S++)BodyWB->SetMaterial(S,WhiteMat);
BodyWB->SetVisibleInSceneCaptureOnly(true);BodyWB->SetAffectDistanceFieldLighting(false);BodyWB->SetAffectDynamicIndirectLighting(false);
BodyWB->RegisterComponent();BodyWB->SetLeaderPoseComponent(Body);
}
return true;
}
void AParkourCapture::SetupCaptures()
{
auto* LabelMaterial=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Generated/Data/M_Semantic.M_Semantic"));
if(!LabelMaterial){Fail(TEXT("Missing semantic material"));return;}
int32 Index=0;
for(auto* C:{RGB.Get(),Labels.Get(),Whitebox.Get()})
{
const bool Tiny=Index==2&&!UEWhitebox;
UTextureRenderTarget2D* RT=NewObject<UTextureRenderTarget2D>(this);Targets.Add(RT);
RT->ClearColor=FLinearColor::Black;RT->bAutoGenerateMips=false;
const int32 F=Index==0?SS:1;RT->InitCustomFormat(Tiny?16:Width*F,Tiny?16:Height*F,PF_B8G8R8A8,Index==1);
if(Index==0){RT->bForceLinearGamma=true;RT->TargetGamma=2.2f;}
RT->UpdateResourceImmediate(true);C->TextureTarget=RT;C->CaptureSource=ESceneCaptureSource::SCS_FinalColorLDR;C->PostProcessBlendWeight=1;
auto& PP=C->PostProcessSettings;
PP.bOverride_MotionBlurAmount=true;PP.MotionBlurAmount=0;PP.bOverride_VignetteIntensity=true;PP.VignetteIntensity=0;
PP.bOverride_SceneFringeIntensity=true;PP.SceneFringeIntensity=0;PP.bOverride_FilmGrainIntensity=true;PP.FilmGrainIntensity=0;
if(Index==0)
{
PP.bOverride_DynamicGlobalIlluminationMethod=true;PP.DynamicGlobalIlluminationMethod=EDynamicGlobalIlluminationMethod::Lumen;
PP.bOverride_ReflectionMethod=true;PP.ReflectionMethod=EReflectionMethod::Lumen;
if(LookV3)
{
// v3 look: higher Lumen quality, local exposure (keeps dark corners and bright skies readable instead of a flat
// global exposure), a little contrast, softer bloom
PP.bOverride_LumenSceneLightingQuality=true;PP.LumenSceneLightingQuality=2.f;
PP.bOverride_LumenFinalGatherQuality=true;PP.LumenFinalGatherQuality=2.f;
PP.bOverride_LumenReflectionQuality=true;PP.LumenReflectionQuality=2.f;
PP.bOverride_LocalExposureHighlightContrastScale=true;PP.LocalExposureHighlightContrastScale=.72f;
PP.bOverride_LocalExposureShadowContrastScale=true;PP.LocalExposureShadowContrastScale=.78f;
PP.bOverride_ColorContrast=true;PP.ColorContrast=FVector4(1.07f,1.07f,1.07f,1.f);
PP.bOverride_BloomIntensity=true;PP.BloomIntensity=.45f;
}
}
if(Index==1)
{
PP.WeightedBlendables.Array.Add(FWeightedBlendable(1,LabelMaterial));C->ShowFlags.SetAtmosphere(false);C->ShowFlags.SetFog(false);
C->ShowFlags.SetLighting(false);C->ShowFlags.SetDynamicShadows(false);C->ShowFlags.SetGlobalIllumination(false);C->ShowFlags.SetLumenGlobalIllumination(false);
C->ShowFlags.SetLumenReflections(false);C->ShowFlags.SetReflectionEnvironment(false);C->ShowFlags.SetScreenSpaceReflections(false);C->ShowFlags.SetAmbientOcclusion(false);
C->ShowFlags.SetBloom(false);C->ShowFlags.SetVolumetricFog(false);
PP.bOverride_DynamicGlobalIlluminationMethod=true;PP.DynamicGlobalIlluminationMethod=EDynamicGlobalIlluminationMethod::None;
PP.bOverride_ReflectionMethod=true;PP.ReflectionMethod=EReflectionMethod::None;
}
if(Index==2)
{
C->ShowFlags.SetAtmosphere(false);C->ShowFlags.SetFog(false);
PP.bOverride_DynamicGlobalIlluminationMethod=true;PP.DynamicGlobalIlluminationMethod=EDynamicGlobalIlluminationMethod::None;
PP.bOverride_ReflectionMethod=true;PP.ReflectionMethod=EReflectionMethod::None;
PP.bOverride_AutoExposureMethod=true;PP.AutoExposureMethod=EAutoExposureMethod::AEM_Manual;
PP.bOverride_AutoExposureApplyPhysicalCameraExposure=true;PP.AutoExposureApplyPhysicalCameraExposure=false;
PP.bOverride_AutoExposureBias=true;PP.AutoExposureBias=WhiteboxExposureBias;PP.bOverride_BloomIntensity=true;PP.BloomIntensity=0;
C->PrimitiveRenderMode=ESceneCapturePrimitiveRenderMode::PRM_UseShowOnlyList;
}
Index++;
}
}
void AParkourCapture::SetupAppearance()
{
if(UMaterialInterface* Base=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Generated/Data/M_Appearance.M_Appearance")))
{AppearanceMID=UMaterialInstanceDynamic::Create(Base,this);RGB->PostProcessSettings.WeightedBlendables.Array.Add(FWeightedBlendable(1,AppearanceMID));}
AppearanceJSON=MakeShared<FJsonObject>();AppearanceJSON->SetStringField(TEXT("name"),AppearanceName);AppearanceJSON->SetNumberField(TEXT("seed"),AppearanceSeed);
UExponentialHeightFogComponent* Fog=nullptr;bool HasAtmosphere=false,HasClouds=false;
for(TActorIterator<AActor> I(GetWorld());I;++I)
{
TArray<UActorComponent*> Comps;I->GetComponents(Comps);
for(UActorComponent* C:Comps)
{
if(auto* D=Cast<UDirectionalLightComponent>(C)){if(!Sun||D->Intensity>Sun->Intensity)Sun=D;}
else if(auto* S=Cast<USkyLightComponent>(C))SkyLight=S;
else if(auto* F=Cast<UExponentialHeightFogComponent>(C))Fog=F;
else if(C->IsA<USkyAtmosphereComponent>())HasAtmosphere=true;
else if(C->IsA<UVolumetricCloudComponent>())HasClouds=true;
}
}
FRandomStream& R=AppRng;auto& PP=RGB->PostProcessSettings;
const float BaseExposureBias=PP.AutoExposureBias;
auto SetClass=[&](int32 C,const FLinearColor& Tint,float Hue,float Sat,float Bright)
{if(AppearanceMID){AppearanceMID->SetVectorParameterValue(*FString::Printf(TEXT("T%d"),C),Tint);AppearanceMID->SetVectorParameterValue(*FString::Printf(TEXT("A%d"),C),FLinearColor(Hue,Sat,Bright));}};
auto SunSet=[&](float Pitch,float YawDelta,float Mul,const FLinearColor& Color)
{
if(!Sun)return;Sun->SetMobility(EComponentMobility::Movable);const FRotator Old=Sun->GetComponentRotation();
Sun->SetWorldRotation(FRotator(Pitch,Old.Yaw+YawDelta,0));Sun->SetIntensity(Sun->Intensity*Mul);Sun->SetLightColor(Color);
AppearanceJSON->SetNumberField(TEXT("sun_pitch"),Pitch);AppearanceJSON->SetNumberField(TEXT("sun_intensity_mul"),Mul);
};
auto SkySet=[&](float Mul){if(SkyLight){SkyLight->SetIntensity(SkyLight->Intensity*Mul);AppearanceJSON->SetNumberField(TEXT("sky_intensity_mul"),Mul);}};
auto FogSet=[&](float DensityMul,const FLinearColor& Color){if(Fog){Fog->SetFogDensity(Fog->FogDensity*DensityMul);Fog->SetFogInscatteringColor(Color);AppearanceJSON->SetNumberField(TEXT("fog_density_mul"),DensityMul);}};
auto Grade=[&](float Temp,float Sat,float Exposure)
{
PP.bOverride_WhiteTemp=true;PP.WhiteTemp=Temp;PP.bOverride_ColorSaturation=true;PP.ColorSaturation=FVector4(Sat,Sat,Sat,1);
if(Exposure!=0){PP.bOverride_AutoExposureBias=true;PP.AutoExposureBias=BaseExposureBias+Exposure;}
AppearanceJSON->SetNumberField(TEXT("white_temp"),Temp);AppearanceJSON->SetNumberField(TEXT("saturation"),Sat);AppearanceJSON->SetNumberField(TEXT("exposure_bias_add"),Exposure);
};
const FString N=AppearanceName.ToLower();
GlassLit=N==TEXT("night")?4.5f:N==TEXT("golden")?1.5f:N==TEXT("overcast")?.45f:N==TEXT("snow")?.35f:.06f;
AppearanceJSON->SetNumberField(TEXT("window_light"),GlassLit);
if(Sun)Sun->SetMobility(EComponentMobility::Movable);
if(N==TEXT("golden")){SunSet(-R.FRandRange(9.f,18.f),R.FRandRange(-180.f,180.f),R.FRandRange(.9f,1.2f),FLinearColor(1.f,R.FRandRange(.62f,.75f),R.FRandRange(.38f,.5f)));
SkySet(R.FRandRange(.65f,.9f));FogSet(R.FRandRange(1.f,1.6f),FLinearColor(.9f,.62f,.42f));Grade(R.FRandRange(7400.f,8300.f),1.08f,0);}
else if(N==TEXT("night")){SunSet(-R.FRandRange(30.f,55.f),R.FRandRange(-180.f,180.f),R.FRandRange(.18f,.3f),FLinearColor(.55f,.66f,1.f));
SkySet(R.FRandRange(.5f,.8f));FogSet(R.FRandRange(.8f,1.3f),FLinearColor(.04f,.06f,.12f));Grade(R.FRandRange(4500.f,5300.f),.72f,0);}
else if(N==TEXT("overcast")){SunSet(-R.FRandRange(35.f,65.f),R.FRandRange(-60.f,60.f),R.FRandRange(.15f,.32f),FLinearColor(.92f,.95f,1.f));
SkySet(R.FRandRange(1.2f,1.6f));FogSet(R.FRandRange(1.8f,3.5f),FLinearColor(.55f,.6f,.66f));Grade(R.FRandRange(6000.f,6500.f),.8f,0);}
else if(N==TEXT("snow")){SunSet(-R.FRandRange(25.f,50.f),R.FRandRange(-90.f,90.f),R.FRandRange(.4f,.7f),FLinearColor(.95f,.97f,1.f));
SkySet(R.FRandRange(1.f,1.25f));FogSet(R.FRandRange(1.3f,2.5f),FLinearColor(.7f,.75f,.82f));Grade(R.FRandRange(5700.f,6300.f),.85f,0);
if(AppearanceMID){AppearanceMID->SetVectorParameterValue(TEXT("SA"),FLinearColor(R.FRandRange(.8f,1.f),R.FRandRange(.7f,.95f),R.FRandRange(.2f,.5f)));
AppearanceMID->SetVectorParameterValue(TEXT("SB"),FLinearColor(R.FRandRange(.7f,.95f),R.FRandRange(.4f,.7f),R.FRandRange(.5f,.8f)));
AppearanceMID->SetVectorParameterValue(TEXT("G"),FLinearColor(R.FRandRange(.4f,.62f),.76f,4.f));}
SetClass(5,FLinearColor(.85f,.9f,.92f),0,.6f,1.f);}
else if(N==TEXT("autumn")){SunSet(-R.FRandRange(22.f,45.f),R.FRandRange(-120.f,120.f),R.FRandRange(.95f,1.15f),FLinearColor(1.f,.86f,.68f));
SkySet(1.f);Grade(R.FRandRange(6900.f,7600.f),1.05f,0);
SetClass(5,FLinearColor(1.f,R.FRandRange(.85f,.95f),R.FRandRange(.7f,.85f)),-R.FRandRange(.16f,.28f),R.FRandRange(1.05f,1.3f),R.FRandRange(.85f,1.f));
SetClass(1,FLinearColor(1.f,.92f,.78f),-.03f,.9f,.95f);}
else if(N==TEXT("default")&&LookV3)
{ // v3 look: the GameCrafter scenes are lit for a top-down camera (high sun); in first person a lower sun gives long
// shadows, modelled facades and a warmer key / cooler fill instead of flat noon light
SunSet(-R.FRandRange(20.f,46.f),R.FRandRange(-180.f,180.f),R.FRandRange(1.f,1.15f),FLinearColor(1.f,R.FRandRange(.9f,.96f),R.FRandRange(.8f,.9f)));
SkySet(R.FRandRange(.85f,1.05f));Grade(R.FRandRange(6300.f,6800.f),1.04f,0);
}
else if(N==TEXT("palette")){for(int32 C:{1,2,3,4,6})SetClass(C,FLinearColor(R.FRandRange(.85f,1.15f),R.FRandRange(.85f,1.15f),R.FRandRange(.85f,1.15f)),R.FRandRange(-.5f,.5f),R.FRandRange(.45f,1.35f),R.FRandRange(.7f,1.3f));
SetClass(5,FLinearColor(1,1,1),R.FRandRange(-.12f,.12f),R.FRandRange(.6f,1.3f),R.FRandRange(.8f,1.15f));
if(R.FRand()<.5f)SunSet(-R.FRandRange(20.f,60.f),R.FRandRange(-180.f,180.f),R.FRandRange(.7f,1.1f),FLinearColor(1,1,1));}
// v3 look: volumetric clouds (the scenes have a sky atmosphere but an empty sky); own random stream so the other
// appearance draws stay unchanged
if(LookV3&&HasAtmosphere&&!HasClouds&&!FParse::Param(FCommandLine::Get(),TEXT("ParkourNoClouds")))
{
FRandomStream CR(AppearanceSeed*7919+Seed*13+5);
// no clouds over the underwater habitat (its "sky" is the water surface)
const float P=(N==TEXT("night")||StyleName==TEXT("habitat"))?0.f:N==TEXT("overcast")?1.f:N==TEXT("golden")?.9f:N==TEXT("snow")?.6f:.8f;
UMaterialInterface* CM=LoadObject<UMaterialInterface>(nullptr,TEXT("/Engine/EngineSky/VolumetricClouds/m_SimpleVolumetricCloud_Inst.m_SimpleVolumetricCloud_Inst"));
bool Added=false;
if(CM&&CR.FRand()<P)
{
UVolumetricCloudComponent* VC=NewObject<UVolumetricCloudComponent>(this,TEXT("PkClouds"));
VC->SetMaterial(CM);
const float CloudBottom=N==TEXT("overcast")?CR.FRandRange(.8f,1.6f):CR.FRandRange(1.4f,3.2f),CloudHeight=CR.FRandRange(3.5f,8.f);
VC->SetLayerBottomAltitude(CloudBottom);VC->SetLayerHeight(CloudHeight);VC->RegisterComponent();Added=true;
AppearanceJSON->SetNumberField(TEXT("clouds_bottom_km"),CloudBottom);AppearanceJSON->SetNumberField(TEXT("clouds_height_km"),CloudHeight);
}
AppearanceJSON->SetBoolField(TEXT("clouds"),Added);
}
float CalibratedEv=0;
if(FParse::Value(FCommandLine::Get(),TEXT("DatasetExposureAdd="),CalibratedEv))
{PP.bOverride_AutoExposureBias=true;PP.AutoExposureBias=BaseExposureBias+CalibratedEv;AppearanceJSON->SetNumberField(TEXT("exposure_bias_add"),CalibratedEv);AppearanceJSON->SetBoolField(TEXT("exposure_calibrated"),true);}
FRandomStream CR(Seed*31+11);
if(CR.FRand()>.3f)SetClass(10,FLinearColor(CR.FRandRange(.8f,1.2f),CR.FRandRange(.8f,1.2f),CR.FRandRange(.8f,1.2f)),CR.FRandRange(-.5f,.5f),CR.FRandRange(.35f,1.5f),CR.FRandRange(.6f,1.3f));
if(Sun){SunBaseYaw=Sun->GetComponentRotation().Yaw;HaveSun=true;}
if(SkyLight)SkyLight->RecaptureSky();
}
void AParkourCapture::EpisodeSun(FRandomStream& R)
{
if(!HaveSun||!Sun||SunYawJitter<=0)return;
const FRotator Old=Sun->GetComponentRotation();
Sun->SetWorldRotation(FRotator(Old.Pitch,SunBaseYaw+R.FRandRange(-SunYawJitter,SunYawJitter),Old.Roll));
if(SkyLight)SkyLight->RecaptureSky();
}
UMaterialInterface* AParkourCapture::MatFor(const TArray<int32>& Pool,FRandomStream& R,float TexScale,float TintVar,float Rough,float Emissive)
{
const int32 Idx=Pool[R.RandRange(0,Pool.Num()-1)];
UMaterialInstanceDynamic* M=UMaterialInstanceDynamic::Create(Mats[Idx].Value,this);
const float B=1.f+R.FRandRange(-TintVar,TintVar);
M->SetVectorParameterValue(TEXT("Tint"),FLinearColor(B*(1+R.FRandRange(-.05f,.05f)),B*(1+R.FRandRange(-.05f,.05f)),B*(1+R.FRandRange(-.05f,.05f))));
M->SetScalarParameterValue(TEXT("TexScale"),TexScale);M->SetScalarParameterValue(TEXT("TexOffset"),R.FRandRange(0.f,7.f));
M->SetScalarParameterValue(TEXT("Roughness"),Rough);M->SetScalarParameterValue(TEXT("Emissive"),Emissive);
EpisodeMIDs.Add(M);
return M;
}
UMaterialInterface* AParkourCapture::RoleMat(const FString& RoleName,FRandomStream& R)
{
// Glass: dark glossy panes; lit panes glow with an appearance-dependent strength.
if((RoleName==TEXT("glass")||RoleName==TEXT("glass_lit"))&&BoxMat)
{
UMaterialInstanceDynamic* M=UMaterialInstanceDynamic::Create(BoxMat,this);EpisodeMIDs.Add(M);
if(WhiteTex)M->SetTextureParameterValue(TEXT("BaseTex"),WhiteTex);
const float K=R.FRandRange(.025f,.06f);M->SetVectorParameterValue(TEXT("Tint"),FLinearColor(K,K*R.FRandRange(1.f,1.15f),K*R.FRandRange(1.05f,1.35f)));
M->SetScalarParameterValue(TEXT("Roughness"),R.FRandRange(.04f,.12f));M->SetScalarParameterValue(TEXT("Metallic"),.15f);
for(const TCHAR* P:{TEXT("EdgeAO"),TEXT("BottomGrime"),TEXT("StreakAmt"),TEXT("GrimeRough")})M->SetScalarParameterValue(P,0.f);
M->SetScalarParameterValue(TEXT("MacroVar"),.05f);
if(RoleName==TEXT("glass_lit"))
{
const bool Cool=R.FRand()<.25f;
M->SetVectorParameterValue(TEXT("EmissiveColor"),Cool?FLinearColor(.8f,.9f,1.f):FLinearColor(1.f,R.FRandRange(.62f,.8f),R.FRandRange(.35f,.55f)));
M->SetScalarParameterValue(TEXT("EmissiveLit"),GlassLit*R.FRandRange(.7f,1.3f));
}
return M;
}
const TArray<int32>* Pool=RolePools.Find(RoleName);
if(Pool&&Pool->Num()>0)
{
const int32 Idx=(*Pool)[R.RandRange(0,Pool->Num()-1)];
UMaterialInstanceDynamic* M=UMaterialInstanceDynamic::Create(Mats[Idx].Value,this);EpisodeMIDs.Add(M);
const float Tile=MatTile[Idx]>1?MatTile[Idx]:(RoleName==TEXT("wall")?300.f:RoleName==TEXT("roof")||RoleName==TEXT("ground")?380.f:180.f);
M->SetScalarParameterValue(TEXT("TexScale"),Tile*R.FRandRange(.85f,1.2f));M->SetScalarParameterValue(TEXT("TexOffset"),R.FRandRange(0.f,7.f));
const float B=1.f+R.FRandRange(-.08f,.08f);M->SetVectorParameterValue(TEXT("Tint"),FLinearColor(B,B,B));
if(const TArray<FLinearColor>* Pal=Palettes.Find(RoleName))
if(Pal->Num()>0){M->SetVectorParameterValue(TEXT("PalA"),(*Pal)[R.RandRange(0,Pal->Num()-1)]);M->SetVectorParameterValue(TEXT("PalB"),(*Pal)[R.RandRange(0,Pal->Num()-1)]);}
const bool Flat=RoleName==TEXT("roof")||RoleName==TEXT("ground")||RoleName==TEXT("tiles");
M->SetScalarParameterValue(TEXT("BottomGrime"),RoleName==TEXT("wall")?R.FRandRange(.12f,.3f):0.f);
M->SetScalarParameterValue(TEXT("StreakAmt"),Flat?0.f:R.FRandRange(.08f,.25f));
M->SetScalarParameterValue(TEXT("EdgeAO"),R.FRandRange(.12f,.28f));
M->SetScalarParameterValue(TEXT("MacroVar"),R.FRandRange(.06f,.16f));
if(!MatCC0[Idx])M->SetScalarParameterValue(TEXT("Roughness"),RoleName==TEXT("metal")?.45f:.8f);
if(RoleName==TEXT("metal")&&MatCC0[Idx])M->SetScalarParameterValue(TEXT("Metallic"),R.FRandRange(.3f,.8f));
return M;
}
return nullptr;
}
void AParkourCapture::ClearCourse()
{
if(Course){Course->Destroy();Course=nullptr;}
WBComps.Reset();EpisodeMIDs.Reset();
}
// =============================================================================================
// Episode = course primitives + 48 Hz state table, both generated by pk (Python).
// =============================================================================================
bool AParkourCapture::LoadEpisode(int32 Index)
{
const FString Path=EpisodeDir/FString::Printf(TEXT("ep_%03d.json"),Index);
JOPK J;if(!PkLoadJSON(Path,J)){Fail(FString(TEXT("Missing or bad episode file "))+Path);return false;}
ClearCourse();
FPkEpisode E;E.Index=Index;E.Seed=int32(J->GetNumberField(TEXT("seed")));E.Steps=int32(J->GetNumberField(TEXT("steps")));E.Duration=J->GetNumberField(TEXT("duration_s"));
PkFloats(J,TEXT("feet"),E.Feet);PkFloats(J,TEXT("rot"),E.Rot);PkFloats(J,TEXT("cam"),E.Cam);PkFloats(J,TEXT("joints"),E.Joints);PkFloats(J,TEXT("phase"),E.Phase);
{TArray<float> M;PkFloats(J,TEXT("move"),M);for(float V:M)E.Move.Add(FMath::RoundToInt(V));}
if(J->HasField(TEXT("lane")))PkFloats(J,TEXT("lane"),E.Lane);
if(J->HasField(TEXT("score"))){TArray<float> Sc;PkFloats(J,TEXT("score"),Sc);for(float V:Sc)E.Score.Add(FMath::RoundToInt(V));}
for(const TSharedPtr<FJsonValue>& V:J->GetArrayField(TEXT("move_names")))E.MoveNames.Add(V->AsString());
TArray<FString> JointNames;for(const TSharedPtr<FJsonValue>& V:J->GetArrayField(TEXT("joint_names")))JointNames.Add(V->AsString());
E.NumJoints=JointNames.Num();
for(int32 K=0;K<12;K++){const int32 Q=JointNames.IndexOfByKey(FString(GPkAim[K][2]));if(Q==INDEX_NONE){Fail(FString(TEXT("Episode lacks joint "))+GPkAim[K][2]);return false;}E.AimJoint.Add(Q);}
if(E.Steps<2||E.Feet.Num()!=E.Steps*3||E.Rot.Num()!=E.Steps*3||E.Cam.Num()!=E.Steps*7||E.Joints.Num()!=E.Steps*E.NumJoints*3||E.Move.Num()!=E.Steps)
{Fail(FString::Printf(TEXT("Episode %d table sizes inconsistent"),Index));return false;}
Ep=MoveTemp(E);
// dress the primitives
FRandomStream R(Ep.Seed^0x2545F491);
EpisodeSun(R);
Course=GetWorld()->SpawnActor<AActor>(AActor::StaticClass(),FTransform::Identity);
USceneComponent* CRoot=NewObject<USceneComponent>(Course,TEXT("CourseRoot"));Course->SetRootComponent(CRoot);CRoot->RegisterComponent();
TArray<UMaterialInterface*> MatOf;
for(const TSharedPtr<FJsonValue>& V:J->GetArrayField(TEXT("mats")))
{
const FString N=V->AsString();UMaterialInterface* M=nullptr;
FString RoleName=N;while(RoleName.Len()>1&&FChar::IsDigit(RoleName[RoleName.Len()-1]))RoleName.LeftChopInline(1);
if(RoleName==TEXT("gold"))M=GoldMat();
else if(RoleName==TEXT("rock"))M=RockMat(R);
else if(RoleName!=TEXT("ad")&&RoleName!=TEXT("dark"))M=RoleMat(RoleName,R);
if(!M)
{
if(RoleName==TEXT("wall")||RoleName==TEXT("concrete")||RoleName==TEXT("shutter"))M=MatFor(WallIdx,R,R.FRandRange(220.f,380.f),.15f,.85f);
else if(RoleName==TEXT("roof")||RoleName==TEXT("tiles"))M=MatFor(RoofIdx,R,R.FRandRange(180.f,320.f),.12f,.8f);
else if(RoleName==TEXT("ground"))M=MatFor(GroundIdx,R,R.FRandRange(300.f,500.f),.1f,.85f);
else if(RoleName==TEXT("trim")||RoleName==TEXT("frame"))M=MatFor(TrimIdx,R,R.FRandRange(120.f,220.f),.1f,.6f);
else if(RoleName==TEXT("wood"))M=MatFor(WoodIdx,R,R.FRandRange(100.f,200.f),.12f,.75f);
else if(RoleName==TEXT("metal"))M=MatFor(MetalIdx,R,R.FRandRange(100.f,200.f),.12f,.45f);
else if(RoleName==TEXT("ad")&&AdIdx.Num())M=MatFor(AdIdx,R,250.f,.1f,.4f,R.FRandRange(1.f,4.f));
else if(RoleName==TEXT("dark")&&DarkIdx.Num()&&R.FRand()<.7f)M=MatFor(DarkIdx,R,150.f,.1f,.35f);
else{UMaterialInstanceDynamic* D=Cast<UMaterialInstanceDynamic>(MatFor(RoleName==TEXT("ad")?TrimIdx:WallIdx,R,200.f,0,.3f));const float K=R.FRandRange(.06f,.18f);D->SetVectorParameterValue(TEXT("Tint"),FLinearColor(K,K*1.02f,K*1.06f));M=D;}
}
MatOf.Add(M);
}
// dynamic primitives (v3): prim index -> slot
TMap<int32,int32> DynSlot;DynComps.Reset();DynKeys.Reset();DynSpin.Reset();DynVis.Reset();
const TArray<TSharedPtr<FJsonValue>>* DynArr=nullptr;
if(J->TryGetArrayField(FString(TEXT("dyn")),DynArr))
for(const TSharedPtr<FJsonValue>& V:*DynArr)
{
const TSharedPtr<FJsonObject> O=V->AsObject();if(!O.IsValid())continue;
TArray<float> Keys;
for(const TSharedPtr<FJsonValue>& KV:O->GetArrayField(TEXT("k"))){const TArray<TSharedPtr<FJsonValue>>& KA=KV->AsArray();if(KA.Num()<10)continue;for(int32 Q=0;Q<10;Q++)Keys.Add(float(KA[Q]->AsNumber()));}
const TArray<TSharedPtr<FJsonValue>>& Vis=O->GetArrayField(TEXT("v"));
DynSlot.Add(int32(O->GetNumberField(TEXT("i"))),DynKeys.Num());
DynKeys.Add(MoveTemp(Keys));DynSpin.Add(float(O->GetNumberField(TEXT("spin"))));
DynVis.Add(FIntPoint(Vis.Num()>0?int32(Vis[0]->AsNumber()):0,Vis.Num()>1?int32(Vis[1]->AsNumber()):-1));
DynComps.Add(nullptr);
}
TMap<int64,TPair<UInstancedStaticMeshComponent*,UInstancedStaticMeshComponent*>> Groups;int32 Count=0,PrimIndex=-1;
for(const TSharedPtr<FJsonValue>& V:J->GetArrayField(TEXT("prims")))
{
PrimIndex++;
const TArray<TSharedPtr<FJsonValue>>& A=V->AsArray();if(A.Num()<12)continue;
const int32 Shape=int32(A[0]->AsNumber()),Cls=int32(A[10]->AsNumber()),Mi=FMath::Clamp(int32(A[11]->AsNumber()),0,FMath::Max(0,MatOf.Num()-1));
const FVector C(A[1]->AsNumber(),A[2]->AsNumber(),A[3]->AsNumber()),S(A[4]->AsNumber(),A[5]->AsNumber(),A[6]->AsNumber());
const FRotator Rt(A[7]->AsNumber(),A[8]->AsNumber(),A[9]->AsNumber());
UStaticMesh* PrimMesh=Shape==1?Cylinder.Get():Shape==2?Sphere.Get():Cube.Get();
if(const int32* Slot=DynSlot.Find(PrimIndex))
{
auto* SM=NewObject<UStaticMeshComponent>(Course);SM->SetStaticMesh(PrimMesh);SM->SetMobility(EComponentMobility::Movable);
SM->SetCollisionEnabled(ECollisionEnabled::NoCollision);SM->SetGenerateOverlapEvents(false);
for(int32 K=0;K<FMath::Max(1,PrimMesh->GetStaticMaterials().Num());K++)SM->SetMaterial(K,MatOf.Num()?MatOf[Mi]:WhiteMat.Get());
SM->SetRenderCustomDepth(true);SM->SetCustomDepthStencilValue(Cls);
SM->SetupAttachment(Course->GetRootComponent());SM->RegisterComponent();SM->SetWorldTransform(FTransform(Rt,C,S/100.f));
DynComps[*Slot]=SM;Count++;continue;
}
const int64 Key=int64(Shape)*1000000+int64(Mi)*1000+Cls;
TPair<UInstancedStaticMeshComponent*,UInstancedStaticMeshComponent*>* G=Groups.Find(Key);
if(!G)
{
UStaticMesh* Mesh=PrimMesh;
auto Make=[&](bool White)->UInstancedStaticMeshComponent*
{
auto* Ism=NewObject<UInstancedStaticMeshComponent>(Course);Ism->SetStaticMesh(Mesh);Ism->SetMobility(EComponentMobility::Movable);
Ism->SetCollisionEnabled(ECollisionEnabled::NoCollision);Ism->SetGenerateOverlapEvents(false);
for(int32 K=0;K<FMath::Max(1,Mesh->GetStaticMaterials().Num());K++)Ism->SetMaterial(K,White?WhiteMat.Get():(MatOf.Num()?MatOf[Mi]:WhiteMat.Get()));
if(White){Ism->SetVisibleInSceneCaptureOnly(true);Ism->SetAffectDistanceFieldLighting(false);Ism->SetAffectDynamicIndirectLighting(false);}
else{Ism->SetRenderCustomDepth(true);Ism->SetCustomDepthStencilValue(Cls);}
Ism->SetupAttachment(Course->GetRootComponent());Ism->RegisterComponent();Ism->SetWorldTransform(FTransform::Identity);
return Ism;
};
UInstancedStaticMeshComponent* W=nullptr;if(UEWhitebox){W=Make(true);WBComps.Add(W);}
G=&Groups.Add(Key,TPair<UInstancedStaticMeshComponent*,UInstancedStaticMeshComponent*>(Make(false),W));
}
const FTransform T(Rt,C,S/100.f);
G->Key->AddInstance(T,true);if(G->Value)G->Value->AddInstance(T,true);Count++;
}
for(auto* C:{RGB.Get(),Labels.Get()}){C->HiddenComponents.Reset();for(UPrimitiveComponent* P:WBComps)C->HideComponent(P);if(BodyWB)C->HideComponent(BodyWB);}
Whitebox->ShowOnlyComponents.Reset();
if(UEWhitebox){for(UPrimitiveComponent* P:WBComps)Whitebox->ShowOnlyComponent(P);if(BodyWB)Whitebox->ShowOnlyComponent(BodyWB);}
UE_LOG(LogTemp,Display,TEXT("PARKOUR episode %d steps=%d duration=%.1fs primitives=%d groups=%d dynamic=%d"),Index,Ep.Steps,Ep.Duration,Count,Groups.Num(),DynComps.Num());
return true;
}
void AParkourCapture::ApplyStep(int32 S)
{
S=FMath::Clamp(S,0,Ep.Steps-1);
const float* F=&Ep.Feet[S*3];const float* Rr=&Ep.Rot[S*3];const float* C=&Ep.Cam[S*7];
BodyRoot->SetWorldLocationAndRotation(FVector(F[0],F[1],F[2]),FRotator(Rr[0],Rr[1],Rr[2]));
CamLoc=FVector(C[0],C[1],C[2]);CamRot=FRotator(C[3],C[4],C[5]);Fov=C[6];
if(UParkourAnim* A=Cast<UParkourAnim>(Body->GetAnimInstance()))
{
FPkPose& P=A->Pose;P.Valid=true;P.Targets.SetNum(12);
const FTransform Rel=Body->GetRelativeTransform();
for(int32 K=0;K<12;K++)
{
const float* Jt=&Ep.Joints[(S*Ep.NumJoints+Ep.AimJoint[K])*3];
P.Targets[K]=Rel.InverseTransformPosition(FVector(Jt[0],Jt[1],Jt[2]));
}
P.Fingers=FingerClip;P.FingerT=float(FMath::Fmod(S*SimStep,FingerClip?double(FingerClip->GetPlayLength()):1.0));
}
if(ViewCam){ViewCam->SetActorLocationAndRotation(CamLoc,CamRot);ViewCam->GetCameraComponent()->SetFieldOfView(Fov);}
ApplyDyn(S);
}
// Same evaluation as pk/dynamics.py eval_dyn: linear interpolation between key frames [step, c xyz, pitch yaw roll, size xyz],
// end keys hold, spin (deg / step) added to yaw, visible in [v0, v1) (v1 < 0: forever).
void AParkourCapture::ApplyDyn(int32 S)
{
for(int32 I=0;I<DynComps.Num();I++)
{
UStaticMeshComponent* C=DynComps[I];if(!C)continue;
const FIntPoint V=DynVis[I];
if(S<V.X||(V.Y>=0&&S>=V.Y)){if(C->IsVisible())C->SetVisibility(false);continue;}
const TArray<float>& K=DynKeys[I];const int32 N=K.Num()/10;if(N==0)continue;
const float* A=&K[0];const float* B=A;float U=0.f;
if(S>=K[(N-1)*10]){A=B=&K[(N-1)*10];}
else if(S>K[0]){int32 Q=1;while(Q<N-1&&K[Q*10]<S)Q++;A=&K[(Q-1)*10];B=&K[Q*10];U=(float(S)-A[0])/FMath::Max(1.f,B[0]-A[0]);}
float X[9];for(int32 Q=0;Q<9;Q++)X[Q]=A[Q+1]+(B[Q+1]-A[Q+1])*U;
C->SetWorldTransform(FTransform(FRotator(X[3],X[4]+DynSpin[I]*S,X[5]),FVector(X[0],X[1],X[2]),FVector(X[6],X[7],X[8])/100.f));
if(!C->IsVisible())C->SetVisibility(true);
}
}
UMaterialInterface* AParkourCapture::GoldMat()
{
// the same polished gold in every scene / appearance (a little self-lit so it still reads at dusk and night)
// v3: dedicated coin material (relief rim / boss / reeded edge, metallic gold, slight glow)
if(LookV3)if(UMaterialInterface* G=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Generated/Parkour/M_PK_Gold.M_PK_Gold"))){KeepAlive.Add(G);return G;}
if(!BoxMat)return WhiteMat.Get();
UMaterialInstanceDynamic* M=UMaterialInstanceDynamic::Create(BoxMat,this);EpisodeMIDs.Add(M);
if(WhiteTex)M->SetTextureParameterValue(TEXT("BaseTex"),WhiteTex);
M->SetVectorParameterValue(TEXT("Tint"),FLinearColor(1.f,.62f,.13f));
M->SetScalarParameterValue(TEXT("Metallic"),1.f);M->SetScalarParameterValue(TEXT("Roughness"),.24f);M->SetScalarParameterValue(TEXT("FlatMinRough"),0.f);
for(const TCHAR* P:{TEXT("EdgeAO"),TEXT("BottomGrime"),TEXT("StreakAmt"),TEXT("GrimeRough"),TEXT("MacroVar")})M->SetScalarParameterValue(P,0.f);
M->SetScalarParameterValue(TEXT("Emissive"),.35f);M->SetScalarParameterValue(TEXT("EmissiveLit"),0.f);
return M;
}
UMaterialInterface* AParkourCapture::RockMat(FRandomStream& R)
{
// prefer the neutral grey CC0 rock sets (same stone look in every scene); scene rock materials (often mossy) only as fallback
TArray<int32> Grey;for(int32 I:RockIdx)if(Mats[I].Key.StartsWith(TEXT("cc0_rock")))Grey.Add(I);
const TArray<int32>& Pool=Grey.Num()?Grey:(RockIdx.Num()?RockIdx:WallIdx);
UMaterialInstanceDynamic* M=Cast<UMaterialInstanceDynamic>(MatFor(Pool,R,R.FRandRange(110.f,190.f),.1f,.88f));
if(M)
{
// the CC0 rock sets are yellow / olive: mostly desaturate them to a warm grey stone (else they read as melons)
const float B=R.FRandRange(1.1f,1.35f);M->SetVectorParameterValue(TEXT("Tint"),FLinearColor(B,B*.97f,B*.93f));
M->SetScalarParameterValue(TEXT("Desat"),R.FRandRange(.72f,.88f));
M->SetScalarParameterValue(TEXT("EdgeAO"),0.f);M->SetScalarParameterValue(TEXT("BottomGrime"),0.f);M->SetScalarParameterValue(TEXT("StreakAmt"),0.f);
M->SetScalarParameterValue(TEXT("MacroVar"),.2f);
}
return M;
}
void AParkourCapture::PreStep(float Dt)
{
if(!Ready||Finished)return;
CaptureThisStep=false;
const bool Started=CaptureStart>=0&&Steps>=CaptureStart;
if(!Started){ApplyStep(0);return;}
if(SettleLeft>0){SettleLeft--;ApplyStep(0);return;}
if(EpStep>=Ep.Steps)
{
if(!LoadEpisode(Ep.Index+1))return;
EpStep=0;SettleLeft=Settle;EpisodeStart=true;ApplyStep(0);return;
}
ApplyStep(EpStep);
CaptureThisStep=(EpStep%Stride)==0;
EpStep++;
}
// =============================================================================================
void AParkourCapture::Initialize()
{
LoadAssets();if(Finished)return;
JOPK First;
if(!PkLoadJSON(EpisodeDir/TEXT("ep_000.json"),First)){Fail(TEXT("Missing ep_000.json in ParkourEpisodes"));return;}
const TSharedPtr<FJsonObject>* BodyJ=nullptr;FString Model=TEXT("manny");double Scale=1;double Skin=0;
if(First->TryGetObjectField(FString(TEXT("body")),BodyJ)){(*BodyJ)->TryGetStringField(FString(TEXT("model")),Model);(*BodyJ)->TryGetNumberField(FString(TEXT("scale")),Scale);(*BodyJ)->TryGetNumberField(FString(TEXT("skin")),Skin);}
First.Reset();
ViewCam=GetWorld()->SpawnActor<ACameraActor>();
HideScene();
if(!SetupBody(Model,float(Scale),int32(Skin)))return;
SetupCaptures();if(Finished)return;
SetupAppearance();
for(TActorIterator<AGameDemoFighter> I(GetWorld());I;++I){I->SetActorTickEnabled(false);I->SetActorHiddenInGame(true);I->SetActorEnableCollision(false);}
if(APlayerController* PC=GetWorld()->GetFirstPlayerController())PC->SetViewTarget(ViewCam.Get());
if(!LoadEpisode(0))return;
EpStep=0;EpisodeStart=true;ApplyStep(0);
InitWallTime=FPlatformTime::Seconds();Ready=true;
}
void AParkourCapture::Tick(float Dt)
{
Super::Tick(Dt);if(Finished)return;
if(!Ready){Initialize();return;}
Steps++;
if(APlayerController* PC=GetWorld()->GetFirstPlayerController())if(PC->GetViewTarget()!=ViewCam.Get())PC->SetViewTarget(ViewCam.Get());
if(CaptureStart<0)
{
int32 Pending=GShaderCompilingManager?GShaderCompilingManager->GetNumRemainingJobs():0;
#if WITH_EDITOR
Pending+=FAssetCompilingManager::Get().GetNumRemainingAssets();
#endif
const double Now=FPlatformTime::Seconds();
if(Pending>0)CompileIdleSince=-1;else if(CompileIdleSince<0)CompileIdleSince=Now;
if(Now-LastWarmupLog>2){LastWarmupLog=Now;UE_LOG(LogTemp,Display,TEXT("PARKOUR_WARMUP steps=%d pending_compiles=%d wall=%.1f"),Steps,Pending,Now-InitWallTime);}
if(Steps>=Warmup&&Now-InitWallTime>=WarmupWallSeconds&&CompileIdleSince>=0&&Now-CompileIdleSince>=5)
{CaptureStart=Steps+Settle;UE_LOG(LogTemp,Display,TEXT("PARKOUR_CAPTURE_START step=%d"),CaptureStart);}
if(Steps>16)Capture(false);
return;
}
if(!CaptureThisStep){Capture(false);return;}
Capture(true);
}
void AParkourCapture::Capture(bool Write)
{
FMinimalViewInfo View;View.Location=CamLoc;View.Rotation=CamRot;View.FOV=Fov;View.AspectRatio=float(Width)/Height;View.bConstrainAspectRatio=false;
View.ProjectionMode=ECameraProjectionMode::Perspective;
const FMatrix Projection=View.CalculateProjectionMatrix();
const FMatrix ViewMatrix=FTranslationMatrix(-View.Location)*FInverseRotationMatrix(View.Rotation)*FMatrix(FPlane(0,0,1,0),FPlane(1,0,0,0),FPlane(0,1,0,0),FPlane(0,0,0,1));
const FMatrix VP=ViewMatrix*Projection;
for(auto* C:{RGB.Get(),Labels.Get(),Whitebox.Get()})
{
if(C==Whitebox.Get()&&!UEWhitebox)continue;
// only the RGB view needs every step (Lumen / exposure history); labels / whitebox also render every 8th warm-up step so
// their shaders are compiled before frame 0 (otherwise frame 0 had an all-invalid label map)
if(!Write&&C!=RGB.Get()&&!(CaptureStart<0&&Steps%8==0))continue;
C->SetWorldLocationAndRotation(View.Location,View.Rotation);C->ProjectionType=ECameraProjectionMode::Perspective;C->FOVAngle=Fov;
C->bUseCustomProjectionMatrix=true;C->CustomProjectionMatrix=Projection;
C->CaptureScene();
}
if(!Write)return;
TArray<FColor> Color,Semantic,White;FReadSurfaceDataFlags Flags(RCM_UNorm);Flags.SetLinearToGamma(false);
if(!Targets[0]->GameThread_GetRenderTargetResource()->ReadPixels(Color,Flags)||!Targets[1]->GameThread_GetRenderTargetResource()->ReadPixels(Semantic,Flags)||
(UEWhitebox&&!Targets[2]->GameThread_GetRenderTargetResource()->ReadPixels(White,Flags))){Fail(TEXT("GPU readback failed"));return;}
if(SS>1)Downsample(Color);
if(Color.Num()!=Width*Height||Semantic.Num()!=Color.Num()||(UEWhitebox&&White.Num()!=Color.Num())){Fail(TEXT("Pass extent mismatch"));return;}
TArray<uint8> IDs;IDs.Reserve(Semantic.Num());int32 Invalid=0;
for(const FColor& S:Semantic){const uint8 V=S.R;IDs.Add(V);if(!(V<=8||V==10))Invalid++;}
const int32 St=FMath::Clamp(EpStep-1,0,Ep.Steps-1);const FString MoveName=Ep.MoveNames.IsValidIndex(Ep.Move[St])?Ep.MoveNames[Ep.Move[St]]:FString(TEXT("?"));
const FString Prefix=Directory/TEXT("raw")/FString::Printf(TEXT("%06d"),Frame);
JOPK J=MakeShared<FJsonObject>();
J->SetNumberField(TEXT("frame_id"),Frame);J->SetNumberField(TEXT("episode"),Ep.Index);J->SetNumberField(TEXT("step"),St);J->SetBoolField(TEXT("episode_start"),EpisodeStart);
J->SetNumberField(TEXT("episode_time_s"),St*SimStep);J->SetStringField(TEXT("move"),MoveName);J->SetNumberField(TEXT("move_phase"),Ep.Phase.IsValidIndex(St)?Ep.Phase[St]:0);
J->SetArrayField(TEXT("feet_world_cm"),PkVec(BodyRoot->GetComponentLocation()));
J->SetArrayField(TEXT("camera_world_cm"),PkVec(View.Location));J->SetArrayField(TEXT("camera_pitch_yaw_roll"),{PkNum(View.Rotation.Pitch),PkNum(View.Rotation.Yaw),PkNum(View.Rotation.Roll)});
J->SetNumberField(TEXT("fov_x_deg"),Fov);J->SetArrayField(TEXT("world_to_view"),PkMat(ViewMatrix));J->SetArrayField(TEXT("projection"),PkMat(Projection));J->SetArrayField(TEXT("world_to_clip"),PkMat(VP));
if(Ep.Lane.IsValidIndex(St))J->SetNumberField(TEXT("lane"),Ep.Lane[St]);
if(Ep.Score.IsValidIndex(St))J->SetNumberField(TEXT("coins"),Ep.Score[St]);
J->SetStringField(TEXT("appearance"),AppearanceName);J->SetNumberField(TEXT("label_invalid_pixels"),Invalid);J->SetNumberField(TEXT("frame_fps"),double(SimHz)/Stride);
EpisodeStart=false;MoveFrames.FindOrAdd(MoveName)++;
if(Frame==0)CaptureWallStart=FPlatformTime::Seconds();
else if(Frame%160==0)UE_LOG(LogTemp,Display,TEXT("PARKOUR_PROGRESS frame=%d/%d fps=%.2f pending=%d"),Frame,Frames,Frame/FMath::Max(1e-3,FPlatformTime::Seconds()-CaptureWallStart),PendingWrites.GetValue());
while(PendingWrites.GetValue()>48)FPlatformProcess::Sleep(.002f);
FString JsonText;{auto Writer=TJsonWriterFactory<>::Create(&JsonText);FJsonSerializer::Serialize(J.ToSharedRef(),Writer);}
PendingWrites.Increment();
const int32 IW=Width,IH=Height,Q=JpegQuality,WQ=WhiteboxQuality;FThreadSafeCounter* Counter=&PendingWrites;const bool HasWhite=UEWhitebox;
Async(EAsyncExecution::ThreadPool,[Counter,Rgb=MoveTemp(Color),Ids=MoveTemp(IDs),Wb=MoveTemp(White),Js=MoveTemp(JsonText),Prefix,IW,IH,Q,WQ,HasWhite]() mutable
{
TArray64<uint8> RF,IF,WF;
bool Ok=FImageUtils::CompressImage(RF,TEXT("jpg"),FImageView(Rgb.GetData(),IW,IH,EGammaSpace::sRGB),Q)
&&FImageUtils::CompressImage(IF,TEXT("png"),FImageView(Ids.GetData(),IW,IH,1,ERawImageFormat::G8,EGammaSpace::Linear),0)
&&FFileHelper::SaveArrayToFile(RF,*(Prefix+TEXT(".jpg")))&&FFileHelper::SaveArrayToFile(IF,*(Prefix+TEXT(".ids.png")))
&&FFileHelper::SaveStringToFile(Js,*(Prefix+TEXT(".json")),FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
if(Ok&&HasWhite)Ok=FImageUtils::CompressImage(WF,TEXT("jpg"),FImageView(Wb.GetData(),IW,IH,EGammaSpace::sRGB),WQ)&&FFileHelper::SaveArrayToFile(WF,*(Prefix+TEXT(".uewhitebox.jpg")));
if(!Ok)UE_LOG(LogTemp,Error,TEXT("PARKOUR_ASYNC_WRITE_FAILED %s"),*Prefix);
Counter->Decrement();
});
Frame++;
if(Frame>=Frames)
{
while(PendingWrites.GetValue()>0)FPlatformProcess::Sleep(.01f);
JOPK Res=MakeShared<FJsonObject>();Res->SetBoolField(TEXT("ok"),true);Res->SetStringField(TEXT("mode"),TEXT("parkour_first_person_pk"));
Res->SetNumberField(TEXT("frames"),Frame);Res->SetNumberField(TEXT("episodes"),Ep.Index+1);Res->SetNumberField(TEXT("width"),Width);Res->SetNumberField(TEXT("height"),Height);
Res->SetNumberField(TEXT("simulation_fps"),SimHz);Res->SetNumberField(TEXT("frame_fps"),double(SimHz)/Stride);Res->SetNumberField(TEXT("frame_stride"),Stride);
Res->SetNumberField(TEXT("capture_wall_seconds"),FPlatformTime::Seconds()-CaptureWallStart);Res->SetNumberField(TEXT("seed"),Seed);
Res->SetStringField(TEXT("episodes_dir"),EpisodeDir);Res->SetBoolField(TEXT("ue_whitebox"),UEWhitebox);
Res->SetObjectField(TEXT("appearance"),AppearanceJSON);
JOPK RCh=MakeShared<FJsonObject>();RCh->SetStringField(TEXT("model"),ModelName);RCh->SetStringField(TEXT("material_variant"),SkinName);RCh->SetNumberField(TEXT("scale"),BodyScale);Res->SetObjectField(TEXT("character"),RCh);
JOPK MF=MakeShared<FJsonObject>();for(auto& KV:MoveFrames)MF->SetNumberField(KV.Key,KV.Value);Res->SetObjectField(TEXT("move_frames"),MF);
TArray<TSharedPtr<FJsonValue>> MatNames;for(auto& M:Mats)MatNames.Add(MakeShared<FJsonValueString>(M.Key));Res->SetArrayField(TEXT("scene_materials"),MatNames);
Res->SetStringField(TEXT("files_per_frame"),TEXT("%06d.jpg RGB; %06d.ids.png semantic ids; %06d.json metadata (whitebox is rendered by pk from the episode files)"));
Res->SetStringField(TEXT("semantic_classes"),TEXT("0 sky, 1 ground, 2 roof surface, 3 building/facade/window, 6 obstacle/prop, 7 coin, 8 falling rock/debris, 10 player body"));
Res->SetStringField(TEXT("matrix_convention"),TEXT("row-major matrices, world row vectors; view axes right/up/forward, UE world cm"));
PkSaveJSON(Res,Directory/TEXT("capture_result.json"));
UE_LOG(LogTemp,Display,TEXT("PARKOUR_DONE frames=%d episodes=%d"),Frame,Ep.Index+1);
Finished=true;FPlatformMisc::RequestExit(false);
}
}
void AParkourCapture::Downsample(TArray<FColor>& Px)
{
const int32 S=SS,W=Width,H=Height,SW=W*S;
if(S<=1||Px.Num()!=SW*H*S)return;
static float Lin[256];static uint8 Enc[4096];static bool Init=false;
if(!Init)
{
for(int32 I=0;I<256;I++){const float V=I/255.f;Lin[I]=V<=.04045f?V/12.92f:FMath::Pow((V+.055f)/1.055f,2.4f);}
for(int32 I=0;I<4096;I++){const float L=I/4095.f;const float V=L<=.0031308f?L*12.92f:1.055f*FMath::Pow(L,1.f/2.4f)-.055f;Enc[I]=(uint8)FMath::Clamp(FMath::RoundToInt(V*255.f),0,255);}
Init=true;
}
TArray<FColor> Out;Out.SetNumUninitialized(W*H);
const float K=4095.f/(S*S);const FColor* In=Px.GetData();FColor* O=Out.GetData();
ParallelFor(H,[In,O,S,W,SW,K](int32 Y)
{
for(int32 X=0;X<W;X++)
{
float R=0,G=0,B=0;
for(int32 DY=0;DY<S;DY++){const FColor* Row=In+(Y*S+DY)*SW+X*S;for(int32 DX=0;DX<S;DX++){R+=Lin[Row[DX].R];G+=Lin[Row[DX].G];B+=Lin[Row[DX].B];}}
O[Y*W+X]=FColor(Enc[FMath::Min(4095,(int32)(R*K+.5f))],Enc[FMath::Min(4095,(int32)(G*K+.5f))],Enc[FMath::Min(4095,(int32)(B*K+.5f))],255);
}
});
if(Sharpen>0)
{
// mild unsharp mask (3x3 cross) on the box-filtered result: the 2x2 average is a little soft at 1280 px
TArray<FColor> Src=Out;const FColor* I2=Src.GetData();const float A=Sharpen;
ParallelFor(H,[I2,O,W,H,A](int32 Y)
{
const int32 Y0=FMath::Max(Y-1,0),Y1=FMath::Min(Y+1,H-1);
for(int32 X=0;X<W;X++)
{
const int32 X0=FMath::Max(X-1,0),X1=FMath::Min(X+1,W-1);
const FColor C=I2[Y*W+X],L=I2[Y*W+X0],Rt=I2[Y*W+X1],U=I2[Y0*W+X],D=I2[Y1*W+X];
auto F=[A](int32 c,int32 l,int32 r,int32 u,int32 d){return (uint8)FMath::Clamp(FMath::RoundToInt(c+A*(c-(l+r+u+d)*.25f)),0,255);};
O[Y*W+X]=FColor(F(C.R,L.R,Rt.R,U.R,D.R),F(C.G,L.G,Rt.G,U.G,D.G),F(C.B,L.B,Rt.B,U.B,D.B),255);
}
});
}
Px=MoveTemp(Out);
}