File size: 53,559 Bytes
1a23f33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// v10 real (-DatasetV10Real, needs -DatasetV9): photoreal outdoor biomes built at run time on the scene's walkable ground,
// recorded in exactly the v9 data format (RGB / ids / depth / whitebox / capsule characters, cut grid, centred camera).
//  * the authored set dressing (classes 3-6) is hidden and loses its collision; the authored ground / paving keep their
//    collision (the gameplay walks on it) but are not rendered
//  * a new ground surface: a height field traced from the authored ground (80 cm grid over the area the bot visits), with a
//    little natural relief away from the route; it gets the photo-scanned PBR sets of the current biome variant (M_V10PBR)
//  * v10 real v2 (diversity): every look (= camera variant, only on the v9 cut grid) rolls a new biome variant out of 12
//    (conifer forest, autumn wood, spring meadow, dry savanna, semi desert, rocky coast, snow alpine, rain wetland, rock
//    badlands, mossy old wood, red canyon, sand beach): asset mix, ground / slope / cover PBR sets, foliage season tint,
//    snow / moss / dust / sand cover on the models, wetness, density multipliers and the light presets that suit it
//    (incl. night and storm). The CC0 photo-scanned assets (Poly Haven) are re-scattered as Nanite instances with
//    noise-driven patches; objects that would block the route keep a clearance from the route and the spawns; ground
//    cover (grass, debris) is labelled ground, rocks 4, plants / trees / logs 5, props 6
//  * perspective telephoto camera (FOV 22-40 deg) replacing the orthographic one: same framing (the v9 frame width at the
//    player), camera pulled back along the view axis
//   -DatasetV10Real [-DatasetV10Biome=<variant>|forest|meadow|arid|coast] [-DatasetV10Density=1] [-DatasetV10FovMin=22 -DatasetV10FovMax=40]
#include "PipelineCapture.h"
#include "PipelineWhitebox.h"
#include "GameDemo.h"
#include "Camera/CameraTypes.h"
#include "Components/StaticMeshComponent.h"
#include "Components/InstancedStaticMeshComponent.h"
#include "Components/SceneCaptureComponent2D.h"
#include "Engine/StaticMesh.h"
#include "Engine/Texture.h"
#include "GameFramework/SpringArmComponent.h"
#include "Materials/MaterialInterface.h"
#include "Materials/Material.h"
#include "Components/ExponentialHeightFogComponent.h"
#include "Components/LocalLightComponent.h"
#include "Components/DecalComponent.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "MeshDescription.h"
#include "StaticMeshAttributes.h"
#include "EngineUtils.h"
#include "Misc/CommandLine.h"
#include "HAL/IConsoleManager.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Dom/JsonObject.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"

namespace
{
// kinds: base instances per m2 of the visited zone per base biome (forest / meadow / arid / coast) and patch threshold of the kind's noise
struct FV10KindCfg{const TCHAR* Kind;float Dens[4];float Cut[4];int32 Sem;bool Big;};
const FV10KindCfg V10Kinds[]={
    {TEXT("grass"), {2.f,4.5f,.45f,.3f},   {-.05f,-.3f,.25f,.3f}, 1,false},
    {TEXT("plant"), {.35f,.6f,.25f,.15f},  {0.f,-.15f,.05f,.2f},  5,false},
    {TEXT("debris"),{.12f,.03f,.06f,.02f}, {-.1f,.3f,.1f,.3f},   1,false},
    {TEXT("rock"),  {.06f,.03f,.14f,.14f}, {-.1f,.2f,-.3f,-.4f},  4,false},   // small rocks (< 70 cm); bigger ones use the "rockbig" entry
    {TEXT("rockbig"),{.010f,.005f,.016f,.02f},{-1.f,-1.f,-1.f,-1.f},4,true},
    {TEXT("shrub"), {.08f,.045f,.06f,.02f},{-.2f,-.1f,-.3f,0.f}, 5,true},
    {TEXT("log"),   {.006f,.0025f,.003f,.002f},{-1.f,-1.f,-1.f,-1.f},5,true},
    {TEXT("tree"),  {.05f,.01f,.008f,.004f},{-.4f,-.2f,-1.f,-1.f},5,true},
    {TEXT("prop"),  {.0012f,.0012f,.0012f,.0018f},{-1.f,-1.f,-1.f,-1.f},6,true}};
// biome variants (one per look)
struct FV10Variant
{
    const TCHAR* Name;const TCHAR* Assets;int32 Base;float Mul[9];
    const TCHAR* Ground;const TCHAR* Side;const TCHAR* Cover;float GCov0,GCov1;
    FLinearColor Fol0,Fol1;FLinearColor Cov;float Cov0,Cov1,CovRough;float Wet;const TCHAR* Lights;
};
const TCHAR* GForestG=TEXT("ph_forest_ground_04 ph_forest_leaves_02 ph_forest_leaves_04 ph_forrest_ground_01 ph_brown_mud_leaves_01");
const TCHAR* GMossySide=TEXT("ph_mossy_rock ph_rock_pitted_mossy ph_lichen_rock ph_rock_ground ph_cliff_side");
const TCHAR* GRockSide=TEXT("ph_rock_ground ph_lichen_rock ph_cliff_side ph_gray_rocks");
const TCHAR* GDrySide=TEXT("ph_rock_boulder_dry ph_rock_face_03 ph_cliff_side ph_rock_ground_02");
const TCHAR* GAllDay=TEXT("golden mist overcast noon backlit dusk");
const FV10Variant V10Vars[]={
    {TEXT("conifer_forest"),TEXT("forest"),0,{1,1,1,1,1,1,1,1.2f,1},GForestG,GMossySide,TEXT("ph_forest_leaves_02 ph_forest_leaves_04 ph_brown_mud_leaves_01 ph_moss_wood"),.1f,.4f,
        FLinearColor(.95f,1.02f,.9f),FLinearColor(1.f,1.f,1.f),FLinearColor(.26f,.34f,.13f),0.f,.25f,.9f,0.f,GAllDay},
    {TEXT("autumn_wood"),TEXT("forest meadow"),0,{.7f,.6f,1.6f,1,1,1.2f,1.5f,1,1},TEXT("ph_forest_leaves_02 ph_forest_leaves_04 ph_brown_mud_leaves_01 ph_forrest_ground_01"),GMossySide,
        TEXT("ph_forest_leaves_02 ph_forest_leaves_04 ph_brown_mud_leaves_01"),.3f,.6f,FLinearColor(1.5f,.85f,.32f),FLinearColor(1.3f,.55f,.24f),FLinearColor(.5f,.27f,.1f),0.f,.2f,.85f,0.f,
        TEXT("golden mist overcast backlit dusk")},
    {TEXT("spring_meadow"),TEXT("meadow"),1,{1.2f,1.5f,1,1,1,1,1,1,1},TEXT("ph_leafy_grass ph_grass_path_2 ph_brown_mud_leaves_01 ph_forest_ground_04"),GRockSide,
        TEXT("ph_leafy_grass ph_grass_path_2 ph_brown_mud_leaves_01"),.12f,.4f,FLinearColor(.92f,1.14f,.82f),FLinearColor(1.f,1.06f,.9f),FLinearColor(.3f,.4f,.15f),0.f,.15f,.9f,0.f,GAllDay},
    {TEXT("dry_savanna"),TEXT("meadow arid"),1,{.8f,.5f,.5f,1,1,.8f,.5f,.6f,1},TEXT("ph_brown_mud_dry ph_dry_ground_rocks ph_gravelly_sand ph_red_laterite_soil_stones"),GDrySide,
        TEXT("ph_sand_01 ph_gravelly_sand ph_brown_mud_dry"),.1f,.35f,FLinearColor(1.32f,1.05f,.52f),FLinearColor(1.2f,.95f,.6f),FLinearColor(.62f,.52f,.4f),0.f,.2f,.9f,0.f,
        TEXT("golden noon backlit dusk overcast")},
    {TEXT("semi_desert"),TEXT("arid"),2,{1,1,1,1,1,1,1,1,1},TEXT("ph_dry_ground_rocks ph_brown_mud_dry ph_red_laterite_soil_stones ph_red_mud_stones ph_gravelly_sand ph_rocky_terrain ph_aerial_rocks_02"),
        GDrySide,TEXT("ph_sand_01 ph_gravelly_sand ph_brown_mud_dry"),.12f,.4f,FLinearColor(1.f,1.f,1.f),FLinearColor(1.08f,1.f,.85f),FLinearColor(.66f,.55f,.42f),0.f,.15f,.9f,0.f,
        TEXT("golden noon backlit dusk overcast night")},
    {TEXT("rocky_coast"),TEXT("coast"),3,{1,1,1,1.2f,1.2f,1,1,1,1},TEXT("ph_coast_sand_01 ph_coast_sand_05 ph_coast_sand_rocks_02 ph_coast_land_rocks_01 ph_aerial_beach_01 ph_clean_pebbles ph_gravelly_sand"),
        TEXT("ph_coast_land_rocks_01 ph_cliff_side ph_gray_rocks ph_rock_ground"),TEXT("ph_coast_sand_01 ph_clean_pebbles ph_gravelly_sand"),.12f,.4f,FLinearColor(1.f,1.f,1.f),FLinearColor(.95f,1.02f,.95f),
        FLinearColor(.78f,.72f,.6f),0.f,.2f,.85f,0.f,TEXT("golden mist overcast noon backlit dusk storm")},
    {TEXT("snow_alpine"),TEXT("forest coast"),0,{.12f,.1f,.3f,1.2f,1.3f,.6f,.8f,1.2f,.6f},TEXT("ph_snow_01 ph_snow_02 ph_snow_field_aerial"),TEXT("ph_rock_ground ph_gray_rocks ph_cliff_side"),
        TEXT("ph_snow_01 ph_snow_02"),.35f,.7f,FLinearColor(.8f,.88f,.92f),FLinearColor(.95f,.98f,1.f),FLinearColor(.92f,.94f,.98f),.45f,.85f,.6f,0.f,TEXT("overcast noon golden mist storm night")},
    {TEXT("rain_wetland"),TEXT("meadow forest"),1,{1.1f,1.2f,.8f,.8f,.8f,1.2f,1,.8f,1},TEXT("ph_brown_mud ph_brown_mud_02 ph_brown_mud_03 ph_brown_mud_leaves_01"),GMossySide,
        TEXT("ph_brown_mud_leaves_01 ph_moss_wood"),.15f,.45f,FLinearColor(.82f,1.f,.78f),FLinearColor(.9f,1.05f,.85f),FLinearColor(.14f,.19f,.08f),.08f,.3f,.85f,1.f,TEXT("overcast mist storm")},
    {TEXT("rock_badlands"),TEXT("arid coast"),2,{.2f,.3f,.6f,1.6f,1.5f,.5f,.3f,.3f,.6f},
        TEXT("ph_rock_ground ph_rock_ground_02 ph_rocks_ground_01 ph_rocks_ground_02 ph_rocks_ground_04 ph_rocks_ground_05 ph_rocks_ground_06 ph_aerial_rocks_01 ph_aerial_rocks_02 ph_aerial_rocks_04 ph_gray_rocks"),
        GRockSide,TEXT("ph_gravelly_sand ph_clean_pebbles"),.05f,.25f,FLinearColor(1.15f,1.f,.7f),FLinearColor(1.05f,.95f,.75f),FLinearColor(.5f,.48f,.45f),0.f,.3f,.9f,0.f,
        TEXT("golden mist overcast noon backlit dusk night storm")},
    {TEXT("mossy_oldwood"),TEXT("forest"),0,{.6f,1.2f,1.6f,1.3f,1.2f,1.3f,2.f,1.3f,1},TEXT("ph_forest_ground_04 ph_forrest_ground_01 ph_forest_leaves_04 ph_brown_mud_leaves_01"),GMossySide,
        TEXT("ph_moss_wood ph_mossy_rock ph_forest_leaves_04"),.3f,.6f,FLinearColor(.78f,1.f,.72f),FLinearColor(.9f,1.05f,.85f),FLinearColor(.13f,.19f,.07f),.2f,.45f,.85f,.5f,
        TEXT("mist overcast backlit golden")},
    {TEXT("red_canyon"),TEXT("arid"),2,{.4f,.6f,.6f,1.3f,1.4f,.8f,.5f,.5f,1},TEXT("ph_red_laterite_soil_stones ph_red_mud_stones"),GDrySide,
        TEXT("ph_red_laterite_soil_stones ph_red_mud_stones"),.1f,.35f,FLinearColor(1.2f,1.f,.65f),FLinearColor(1.1f,.95f,.7f),FLinearColor(.62f,.36f,.24f),.15f,.4f,.9f,0.f,TEXT("golden noon backlit dusk")},
    {TEXT("sand_beach"),TEXT("coast"),3,{.5f,.6f,.5f,.6f,.6f,.5f,.5f,0.f,1.5f},TEXT("ph_coast_sand_01 ph_coast_sand_05 ph_aerial_beach_01 ph_gravelly_sand"),
        TEXT("ph_coast_land_rocks_01 ph_gray_rocks"),TEXT("ph_coast_sand_01 ph_coast_sand_05"),.15f,.45f,FLinearColor(1.05f,1.02f,.85f),FLinearColor(1.f,1.f,1.f),FLinearColor(.8f,.72f,.58f),0.f,.3f,.9f,0.f,
        TEXT("golden noon overcast backlit dusk")}};
const int32 V10NumVars=UE_ARRAY_COUNT(V10Vars);
struct FV10Season{const TCHAR* Var;FLinearColor Col;float A0,A1;bool FolCov;};
const FV10Season V10Seasons[]={{TEXT("autumn_wood"),FLinearColor(1.f,.42f,.1f),.55f,.95f,false},{TEXT("dry_savanna"),FLinearColor(.88f,.72f,.32f),.45f,.75f,true},
    {TEXT("snow_alpine"),FLinearColor(.62f,.7f,.66f),.2f,.4f,true},{TEXT("spring_meadow"),FLinearColor(.5f,.95f,.25f),.1f,.3f,false},{TEXT("semi_desert"),FLinearColor(.75f,.78f,.45f),0.f,.3f,true},
    {TEXT("red_canyon"),FLinearColor(.8f,.7f,.35f),.2f,.5f,true},{TEXT("sand_beach"),FLinearColor(.75f,.8f,.5f),0.f,.25f,true},{TEXT("rock_badlands"),FLinearColor(.8f,.7f,.4f),.2f,.5f,true},
    {TEXT("rocky_coast"),FLinearColor(.6f,.8f,.4f),0.f,.2f,true}};
const FV10Season* V10SeasonOf(const TCHAR* Var){for(const FV10Season& S:V10Seasons)if(FCString::Strcmp(S.Var,Var)==0)return &S;return nullptr;}
struct FV10Mesh{UStaticMesh* Mesh=nullptr;FString Id,Kind;FVector Size=FVector::ZeroVector;float MinZ=0;bool Foliage=false;TArray<UMaterialInterface*> Mats;TArray<FString> Biomes;};
TArray<FV10Mesh> GV10All;   // the whole catalog (loaded once, kept by V10RealKeep)
int32 V10SemOf(const AActor* A){int32 Id=-1;if(A)for(const FName& T:A->Tags){FString S=T.ToString();if(S.RemoveFromStart(TEXT("semantic:")))Id=FCString::Atoi(*S);}return Id;}
// FRandomStream is a plain LCG: neighbouring seeds give correlated first draws (the same first biome in every run), so
// per-look seeds go through a splitmix64 finaliser first
int32 V10Mix(int64 A,int64 B){uint64 Z=uint64(A)*0x9E3779B97F4A7C15ull+uint64(B)*0xBF58476D1CE4E5B9ull+0x94D049BB133111EBull;Z=(Z^(Z>>30))*0xBF58476D1CE4E5B9ull;Z=(Z^(Z>>27))*0x94D049BB133111EBull;Z^=Z>>31;return int32(Z&0x7fffffff);}
float V10Fbm(float X,float Y,float S,float O){return FMath::PerlinNoise2D(FVector2D(X/S+O,Y/S-O*.7f))*.65f+FMath::PerlinNoise2D(FVector2D(X/(S*.37f)-O,Y/(S*.37f)+O*1.3f))*.35f;}
bool V10IsFoliageMat(const UMaterialInterface* M){const UMaterial* B=M?M->GetMaterial():nullptr;return B&&B->GetName().Contains(TEXT("Foliage"));}

UStaticMesh* V10BuildGrid(UObject* Outer,const TArray<FVector3f>& P,const TArray<FVector3f>& N,const TArray<int32>& Tri,UMaterialInterface* Mat)
{
    if(Tri.Num()<3)return nullptr;
    FMeshDescription MD;FStaticMeshAttributes Attr(MD);Attr.Register();
    TVertexAttributesRef<FVector3f> Pos=Attr.GetVertexPositions();
    TVertexInstanceAttributesRef<FVector3f> Nrm=Attr.GetVertexInstanceNormals(),Tan=Attr.GetVertexInstanceTangents();
    TVertexInstanceAttributesRef<float> Sgn=Attr.GetVertexInstanceBinormalSigns();
    TVertexInstanceAttributesRef<FVector2f> UVs=Attr.GetVertexInstanceUVs();if(UVs.GetNumChannels()<1)UVs.SetNumChannels(1);
    MD.ReserveNewVertices(P.Num());MD.ReserveNewVertexInstances(P.Num());MD.ReserveNewTriangles(Tri.Num()/3);MD.ReserveNewEdges(Tri.Num());
    const FPolygonGroupID G=MD.CreatePolygonGroup();Attr.GetPolygonGroupMaterialSlotNames()[G]=FName(TEXT("M0"));
    TArray<FVertexInstanceID> VI;VI.SetNum(P.Num());
    for(int32 I=0;I<P.Num();I++)
    {
        const FVertexID V=MD.CreateVertex();Pos[V]=P[I];
        const FVertexInstanceID X=MD.CreateVertexInstance(V);VI[I]=X;
        FVector3f T=FVector3f(1,0,0)-N[I]*N[I].X;T.Normalize();
        Nrm[X]=N[I];Tan[X]=T;Sgn[X]=1.f;UVs.Set(X,0,FVector2f(P[I].X/100.f,P[I].Y/100.f));
    }
    for(int32 I=0;I+2<Tri.Num();I+=3){FVertexInstanceID T3[3]={VI[Tri[I]],VI[Tri[I+1]],VI[Tri[I+2]]};MD.CreateTriangle(G,MakeArrayView(T3,3));}
    UStaticMesh* SM=NewObject<UStaticMesh>(Outer);
    SM->GetStaticMaterials().Add(FStaticMaterial(Mat,FName(TEXT("M0"))));
    UStaticMesh::FBuildMeshDescriptionsParams BP;BP.bFastBuild=true;BP.bMarkPackageDirty=false;BP.bCommitMeshDescription=false;BP.bBuildSimpleCollision=false;
    TArray<const FMeshDescription*> L;L.Add(&MD);
    return SM->BuildFromMeshDescriptions(L,BP)?SM:nullptr;
}
}

void APipelineCapture::ParseV10Real(const TCHAR* Cmd)
{
    V10Real=FParse::Param(Cmd,TEXT("DatasetV10Real"));
    if(!V10Real)return;
    V10Photo=true;DynamicEvents=false;   // the v4 dynamic events spawn authored props during the run
    FString B;
    if(FParse::Value(Cmd,TEXT("DatasetV10Biome="),B))
    {
        static const TCHAR* Old[4][2]={{TEXT("forest"),TEXT("conifer_forest")},{TEXT("meadow"),TEXT("spring_meadow")},{TEXT("arid"),TEXT("semi_desert")},{TEXT("coast"),TEXT("rocky_coast")}};
        for(int32 I=0;I<4;I++)if(B.Equals(Old[I][0],ESearchCase::IgnoreCase))B=Old[I][1];
        for(int32 I=0;I<V10NumVars;I++)if(B.Equals(V10Vars[I].Name,ESearchCase::IgnoreCase))V10VarForced=I;
    }
    {float E=0;if(FParse::Value(Cmd,TEXT("DatasetV10NaniteEdge="),E)&&E>0)if(IConsoleVariable* Cv=IConsoleManager::Get().FindConsoleVariable(TEXT("r.Nanite.MaxPixelsPerEdge")))Cv->Set(E,ECVF_SetByCode);}   // tests
    FParse::Value(Cmd,TEXT("DatasetV10AOFix="),V10AOFix);FParse::Value(Cmd,TEXT("DatasetV10GrassShadow="),V10GrassShadow);FParse::Value(Cmd,TEXT("DatasetV10Light="),V10LightForced);
    FParse::Value(Cmd,TEXT("DatasetV10Density="),V10Density);FParse::Value(Cmd,TEXT("DatasetV10FovMin="),V10FovMin);FParse::Value(Cmd,TEXT("DatasetV10FovMax="),V10FovMax);
    int32 Seed=0;FParse::Value(Cmd,TEXT("DatasetSeed="),Seed);V10RealSeed=Seed*7307+101;
    V10Fov=.5f*(V10FovMin+V10FovMax);
    UE_LOG(LogTemp,Display,TEXT("DATASET_V10 real v2: %d biome variants, forced '%s' density %.2f fov %.0f-%.0f"),V10NumVars,V10VarForced>=0?V10Vars[V10VarForced].Name:TEXT("-"),V10Density,V10FovMin,V10FovMax);
}

bool APipelineCapture::V10HfAt(float X,float Y,float& Z,int32& Cls) const
{
    if(V10HfNX<2||V10HfNY<2)return false;
    const float FX=(X-V10HfOrigin.X)/V10HfStep,FY=(Y-V10HfOrigin.Y)/V10HfStep;
    const int32 IX=FMath::FloorToInt(FX),IY=FMath::FloorToInt(FY);
    if(IX<0||IY<0||IX>=V10HfNX-1||IY>=V10HfNY-1)return false;
    const float AX=FX-IX,AY=FY-IY;
    const int32 I00=IY*V10HfNX+IX,I10=I00+1,I01=I00+V10HfNX,I11=I01+1;
    if(!V10HfCls[I00]||!V10HfCls[I10]||!V10HfCls[I01]||!V10HfCls[I11])return false;
    Z=FMath::Lerp(FMath::Lerp(V10HfZ[I00],V10HfZ[I10],AX),FMath::Lerp(V10HfZ[I01],V10HfZ[I11],AX),AY);
    Cls=V10HfCls[(AY<.5f?(AX<.5f?I00:I10):(AX<.5f?I01:I11))];
    return true;
}

void APipelineCapture::V10RealBuild()
{
    if(!V10Real||!Player)return;
    UWorld* World=GetWorld();const double T0=FPlatformTime::Seconds();
    V10LoadSets();
    FRandomStream R(V10Mix(V10RealSeed,17));
    // ---- 1. hide the authored scene ------------------------------------------------------------------------------
    int32 HidA=0,HidG=0;
    for(TActorIterator<AActor> I(World);I;++I)
    {
        AActor* A=*I;
        if(A==this||Cast<AGameDemoFighter>(A)||A->ActorHasTag(TEXT("whitebox"))||A->ActorHasTag(TEXT("v10_real")))continue;
        const int32 S=V10SemOf(A);if(S<1||S>6)continue;
        if(S>=3){A->SetActorHiddenInGame(true);A->SetActorEnableCollision(false);HidA++;continue;}
        TArray<UPrimitiveComponent*> Cs;A->GetComponents(Cs);
        for(UPrimitiveComponent* C:Cs){C->SetVisibility(false,true);V10RealHiddenGround.Add(C);HidG++;}
    }
    // the host scenes' own lamps / neon / glow (local lights lit the volumetric fog into white halos), decals, water planes,
    // particle systems and other unlabelled meshes do not belong in a natural biome either
    int32 HidL=0,HidD=0,HidU=0;TMap<FString,int32> UCls;
    for(TActorIterator<AActor> I(World);I;++I)
    {
        AActor* A=*I;if(A==this||A->ActorHasTag(TEXT("whitebox"))||A->ActorHasTag(TEXT("v10_real"))||A->ActorHasTag(TEXT("v4_event")))continue;
        bool Fighter=false;for(AActor* P=A;P&&!Fighter;P=P->GetAttachParentActor())Fighter|=Cast<AGameDemoFighter>(P)!=nullptr||Cast<AGameDemoFighter>(P->GetOwner())!=nullptr;
        if(Fighter)continue;
        TArray<UActorComponent*> Cs;A->GetComponents(Cs);const int32 S=V10SemOf(A);const bool Unlab=S<1||S>6;
        for(UActorComponent* C:Cs)
        {
            if(auto* Lc=Cast<ULocalLightComponent>(C)){if(Lc->IsVisible()){Lc->SetVisibility(false);HidL++;}continue;}
            if(auto* Dc=Cast<UDecalComponent>(C)){if(Dc->IsVisible()){Dc->SetVisibility(false);HidD++;}continue;}
            auto* Pc=Cast<UPrimitiveComponent>(C);
            if(!Unlab||!Pc||!Pc->IsVisible()||Pc->bHiddenInGame||Pc->ComponentHasTag(TEXT("v8fx")))continue;
            Pc->SetVisibility(false);HidU++;UCls.FindOrAdd(Pc->GetClass()->GetName())++;
        }
    }
    {FString L;for(const auto& P:UCls)L+=FString::Printf(TEXT("%s:%d "),*P.Key,P.Value);
     UE_LOG(LogTemp,Display,TEXT("DATASET_V10 real: lights off %d, decals off %d, unlabelled primitives off %d (%s)"),HidL,HidD,HidU,*L);}
    // ---- 2. height field ground ------------------------------------------------------------------------------------
    V10S0=Player->GetAuthoredSpawnPosition();const float RefZ=Player->GetActorLocation().Z;
    V10Anchors.Reset();V10Anchors.Add(V10S0);
    V10SB=V10S0;if(AGameDemoFighter* B=Player->Opponent.Get()){V10SB=B->GetAuthoredSpawnPosition();V10Anchors.Add(V10SB);}
    for(const FVector& P:Player->ExplorationWaypoints)if(FVector::Dist2D(P,V10S0)<7000.f)V10Anchors.Add(P);
    for(const FVector& P:Player->ExplorationPlaces)if(FVector::Dist2D(P,V10S0)<7000.f)V10Anchors.Add(P);
    FBox2D Box(ForceInit);for(const FVector& P:V10Anchors)Box+=FVector2D(P.X,P.Y);
    Box=Box.ExpandBy(4800.f);
    const FVector2D Ctr=Box.GetCenter();FVector2D Ext=Box.GetExtent();Ext.X=FMath::Min(Ext.X,13000.f);Ext.Y=FMath::Min(Ext.Y,13000.f);
    V10HfNX=FMath::CeilToInt(2*Ext.X/V10HfStep)+1;V10HfNY=FMath::CeilToInt(2*Ext.Y/V10HfStep)+1;
    V10HfOrigin=FVector(Ctr.X-Ext.X,Ctr.Y-Ext.Y,RefZ);
    V10HfZ.SetNumZeroed(V10HfNX*V10HfNY);V10HfCls.SetNumZeroed(V10HfNX*V10HfNY);
    FCollisionQueryParams Q(SCENE_QUERY_STAT(V10Ground),true);
    for(TActorIterator<AGameDemoFighter> F(World);F;++F)Q.AddIgnoredActor(*F);
    int32 Valid=0;
    // distance to the places the gameplay uses: no relief there (the characters stand on the authored collision)
    const FVector S0=V10S0,SB=V10SB;
    auto Busy=[&](const FVector2D& P){float D=RouteDist2D(P);D=FMath::Min(D,FVector2D::Distance(P,FVector2D(S0)));D=FMath::Min(D,FVector2D::Distance(P,FVector2D(SB))-600.f);return D;};
    const float Amp=R.FRandRange(8.f,26.f);
    for(int32 Y=0;Y<V10HfNY;Y++)for(int32 X=0;X<V10HfNX;X++)
    {
        const float WX=V10HfOrigin.X+X*V10HfStep,WY=V10HfOrigin.Y+Y*V10HfStep;
        FCollisionQueryParams Q2=Q;
        for(int32 Pass=0;Pass<4;Pass++)
        {
            FHitResult H;
            if(!World->LineTraceSingleByChannel(H,FVector(WX,WY,RefZ+6000),FVector(WX,WY,RefZ-6000),ECC_Visibility,Q2))break;
            const int32 S=V10SemOf(H.GetActor());
            if(S!=1&&S!=2){if(H.GetActor())Q2.AddIgnoredActor(H.GetActor());continue;}
            const int32 K=Y*V10HfNX+X;
            float Z=H.ImpactPoint.Z;
            if(S==1)Z+=Amp*FMath::SmoothStep(350.f,1100.f,Busy(FVector2D(WX,WY)))*V10Fbm(WX,WY,900.f,3.1f);
            V10HfZ[K]=Z;V10HfCls[K]=(uint8)S;Valid++;break;   // class 2 = former paving: rendered / labelled as ground, scattered sparser
        }
    }
    // holes (water, building footprints, gaps between ground pieces) take the nearest valid height; then the steps between
    // ground pieces of different levels (platform edges: vertical walls with stretched texture) relax into slopes of at most
    // ~30 deg. Cells near the route / spawns keep their traced height (the characters walk on the authored collision there).
    int32 Filled=0;
    {
        TArray<int32> Fq;Fq.Reserve(V10HfNX*V10HfNY);for(int32 K=0;K<V10HfNX*V10HfNY;K++)if(V10HfCls[K])Fq.Add(K);
        for(int32 H=0;H<Fq.Num();H++)
        {
            const int32 K=Fq[H],X=K%V10HfNX,Y=K/V10HfNX;
            const int32 Nb[4][2]={{X-1,Y},{X+1,Y},{X,Y-1},{X,Y+1}};
            for(const auto& B:Nb)if(B[0]>=0&&B[1]>=0&&B[0]<V10HfNX&&B[1]<V10HfNY)
            {const int32 J=B[1]*V10HfNX+B[0];if(!V10HfCls[J]){V10HfCls[J]=1;V10HfZ[J]=V10HfZ[K];Fq.Add(J);Filled++;}}
        }
    }
    {
        TArray<float> Wt;Wt.SetNumUninitialized(V10HfNX*V10HfNY);
        for(int32 K=0;K<V10HfNX*V10HfNY;K++)Wt[K]=FMath::SmoothStep(150.f,600.f,Busy(FVector2D(V10HfOrigin.X+(K%V10HfNX)*V10HfStep,V10HfOrigin.Y+(K/V10HfNX)*V10HfStep)));
        const float MaxStep=.55f*V10HfStep;TArray<float> Z2=V10HfZ;
        for(int32 It=0;It<120;It++)
        {
            for(int32 Y=0;Y<V10HfNY;Y++)for(int32 X=0;X<V10HfNX;X++)
            {
                const int32 K=Y*V10HfNX+X;if(Wt[K]<=0.f)continue;
                float Lo=-1e9f,Hi=1e9f;
                for(int32 DY=-1;DY<=1;DY++)for(int32 DX=-1;DX<=1;DX++)
                {
                    if(!DX&&!DY)continue;const int32 XX=X+DX,YY=Y+DY;if(XX<0||YY<0||XX>=V10HfNX||YY>=V10HfNY)continue;
                    const float Zn=V10HfZ[YY*V10HfNX+XX],M=MaxStep*((DX&&DY)?1.414f:1.f);Lo=FMath::Max(Lo,Zn-M);Hi=FMath::Min(Hi,Zn+M);
                }
                const float T=Lo<=Hi?FMath::Clamp(V10HfZ[K],Lo,Hi):.5f*(Lo+Hi);
                Z2[K]=FMath::Lerp(V10HfZ[K],T,Wt[K]);
            }
            V10HfZ=Z2;
        }
    }
    {   // one ground surface (the authored paving becomes a natural clearing, class 1); vertices relative to the holder at the grid origin
        TArray<int32> Map;Map.Init(-1,V10HfNX*V10HfNY);TArray<FVector3f> P,N;TArray<int32> Tri;
        auto Vtx=[&](int32 X,int32 Y)->int32
        {
            const int32 K=Y*V10HfNX+X;if(Map[K]>=0)return Map[K];
            auto Hz=[&](int32 XX,int32 YY){XX=FMath::Clamp(XX,0,V10HfNX-1);YY=FMath::Clamp(YY,0,V10HfNY-1);const int32 Q3=YY*V10HfNX+XX;return V10HfCls[Q3]?V10HfZ[Q3]:V10HfZ[K];};
            const float DX=(Hz(X+1,Y)-Hz(X-1,Y))/(2*V10HfStep),DY=(Hz(X,Y+1)-Hz(X,Y-1))/(2*V10HfStep);
            FVector3f Nn(-DX,-DY,1.f);Nn.Normalize();
            Map[K]=P.Add(FVector3f(X*V10HfStep,Y*V10HfStep,V10HfZ[K]-RefZ));N.Add(Nn);return Map[K];
        };
        for(int32 Y=0;Y+1<V10HfNY;Y++)for(int32 X=0;X+1<V10HfNX;X++)
        {
            const int32 K=Y*V10HfNX+X;const uint8 C[4]={V10HfCls[K],V10HfCls[K+1],V10HfCls[K+V10HfNX],V10HfCls[K+V10HfNX+1]};
            if(!C[0]||!C[1]||!C[2]||!C[3])continue;
            const int32 A0=Vtx(X,Y),A1=Vtx(X+1,Y),A2=Vtx(X,Y+1),A3=Vtx(X+1,Y+1);
            // front faces: UE triangle normal is (C-A)x(B-A) -> (v00, v01, v10) and (v10, v01, v11) face +Z
            Tri.Append({A0,A2,A1,A1,A2,A3});
        }
        AActor* H=World->SpawnActor<AActor>(AActor::StaticClass(),FTransform(V10HfOrigin));
        if(H)
        {
            USceneComponent* HR=NewObject<USceneComponent>(H);H->SetRootComponent(HR);HR->RegisterComponent();HR->SetWorldLocation(V10HfOrigin);
            H->Tags.Add(FName(TEXT("semantic:1")));H->Tags.Add(TEXT("v4_event"));H->Tags.Add(TEXT("v10_real"));
            if(UStaticMesh* M=V10BuildGrid(H,P,N,Tri,V10Mat?V10Mat.Get():nullptr))
            {
                V10RealKeep.Add(M);
                auto* C=NewObject<UStaticMeshComponent>(H);C->SetupAttachment(HR);C->SetMobility(EComponentMobility::Movable);C->SetStaticMesh(M);
                C->SetCollisionEnabled(ECollisionEnabled::NoCollision);C->SetCastShadow(true);C->ComponentTags.Add(TEXT("v10_ground"));C->SetTextureForceResidentFlag(true);
                C->RegisterComponent();C->SetRelativeTransform(FTransform::Identity);H->AddInstanceComponent(C);V10RealGround.Add(C);
                V10RealCounts.Add(TEXT("ground_tris"),Tri.Num()/3);
            }
        }
    }
    // ---- 3. the whole asset catalog, textures forced resident (every look re-scatters another biome) -----------------
    GV10All.Reset();int32 NTex=0;TSet<UTexture*> SeenTex;
    {
        FString S;
        if(FFileHelper::LoadFileToString(S,*(FPaths::ProjectContentDir()/TEXT("Xfer/V10/v10_models.json"))))
        {
            TSharedPtr<FJsonObject> O;const TSharedRef<TJsonReader<>> Rd=TJsonReaderFactory<>::Create(S);
            const TArray<TSharedPtr<FJsonValue>>* A;
            if(FJsonSerializer::Deserialize(Rd,O)&&O.IsValid()&&O->TryGetArrayField(TEXT("meshes"),A))for(const auto& V:*A)
            {
                const TSharedPtr<FJsonObject> T=V->AsObject();if(!T)continue;
                FV10Mesh M;M.Id=T->GetStringField(TEXT("id"));M.Kind=T->GetStringField(TEXT("kind"));M.Foliage=T->GetBoolField(TEXT("foliage"));
                {bool Skip=false;for(const TCHAR* X:{TEXT("mountainside"),TEXT("rock_face_"),TEXT("coastal_cliff_"),TEXT("coast_line_"),TEXT("coast_land_rocks_"),TEXT("namaqualand_cliff_"),TEXT("grass_medium_01"),TEXT("celandine_01")})Skip|=M.Id.StartsWith(X);
                 static TArray<FString> Excl;static bool ExclInit=false;if(!ExclInit){ExclInit=true;FString E;if(FParse::Value(FCommandLine::Get(),TEXT("DatasetV10Exclude="),E))E.ParseIntoArray(Excl,TEXT("+"));}
                 for(const FString& X:Excl)Skip|=M.Id.StartsWith(X);if(Skip)continue;}
                // scanned cliff faces are open shells; grass_medium_01 / celandine_01 ship dirty opacity maps (grey padding blocks around the blades render as dark patches)
                const TArray<TSharedPtr<FJsonValue>>* Bs;if(T->TryGetArrayField(TEXT("biomes"),Bs))for(const auto& B:*Bs)M.Biomes.Add(B->AsString());
                const TArray<TSharedPtr<FJsonValue>>* Sz;if(T->TryGetArrayField(TEXT("size"),Sz)&&Sz->Num()==3)M.Size=FVector((*Sz)[0]->AsNumber(),(*Sz)[1]->AsNumber(),(*Sz)[2]->AsNumber());
                M.MinZ=T->GetNumberField(TEXT("min_z"));
                if(M.Kind==TEXT("debris")&&FMath::Max(M.Size.X,M.Size.Y)>120.f)M.Kind=TEXT("log");
                if(M.Kind==TEXT("rock")&&FMath::Max(M.Size.X,M.Size.Y)>=70.f)M.Kind=TEXT("rockbig");
                if(M.Kind==TEXT("rockbig")&&FMath::Max(M.Size.X,M.Size.Y)>1400.f)continue;   // cliffs / shore shelves: larger than the play spaces
                if(M.Kind==TEXT("shrub")&&FMath::Max3(M.Size.X,M.Size.Y,M.Size.Z)<70.f)M.Kind=TEXT("plant");
                M.Mesh=LoadObject<UStaticMesh>(nullptr,*T->GetStringField(TEXT("mesh")));if(!M.Mesh)continue;
                const TArray<TSharedPtr<FJsonValue>>* Ms;
                if(T->TryGetArrayField(TEXT("materials"),Ms))for(const auto& X:*Ms)
                {
                    UMaterialInterface* Mi=X->AsString().IsEmpty()?nullptr:LoadObject<UMaterialInterface>(nullptr,*X->AsString());M.Mats.Add(Mi);
                    if(!Mi)continue;
                    V10RealKeep.Add(Mi);
                    for(const TCHAR* Pn:{TEXT("BC"),TEXT("NM"),TEXT("RT"),TEXT("OP")})
                    {
                        UTexture* Tx=nullptr;
                        if(Mi->GetTextureParameterValue(FHashedMaterialParameterInfo(FName(Pn)),Tx)&&Tx&&!SeenTex.Contains(Tx)){SeenTex.Add(Tx);V10RealKeep.Add(Tx);Tx->SetForceMipLevelsToBeResident(1e6f);NTex++;}
                    }
                }
                V10RealKeep.Add(M.Mesh);GV10All.Add(M);
            }
        }
    }
    // zone of the visible play space (within ~26 m of the route / anchors) and its area
    const FVector2D Lo(V10HfOrigin.X,V10HfOrigin.Y),Hi(V10HfOrigin.X+(V10HfNX-1)*V10HfStep,V10HfOrigin.Y+(V10HfNY-1)*V10HfStep);
    int32 ZoneHit=0,ZoneTry=0;
    for(int32 I=0;I<4000;I++)
    {
        ZoneTry++;const FVector2D P(R.FRandRange(Lo.X,Hi.X),R.FRandRange(Lo.Y,Hi.Y));
        bool In=RouteDist2D(P)<2600.f;for(const FVector& A:V10Anchors)In|=FVector2D::Distance(P,FVector2D(A.X,A.Y))<3000.f;ZoneHit+=In;
    }
    V10AreaM2=(Hi.X-Lo.X)*(Hi.Y-Lo.Y)/1e4f*ZoneHit/FMath::Max(1,ZoneTry);
    V10RealCounts.Add(TEXT("hidden_actors"),HidA);V10RealCounts.Add(TEXT("hidden_ground_components"),HidG);V10RealCounts.Add(TEXT("catalog_meshes"),GV10All.Num());
    V10RealCounts.Add(TEXT("resident_textures"),NTex);V10RealCounts.Add(TEXT("zone_m2"),FMath::RoundToInt(V10AreaM2));V10RealCounts.Add(TEXT("relief_cm"),FMath::RoundToInt(Amp));V10RealCounts.Add(TEXT("holes_filled"),Filled);V10RealCounts.Add(TEXT("lights_off"),HidL);V10RealCounts.Add(TEXT("unlabelled_off"),HidU);
    UE_LOG(LogTemp,Display,TEXT("DATASET_V10 real: hidden %d actors / %d ground comps, height field %dx%d (%d valid, relief %.0f cm), catalog %d meshes, %d textures resident, zone %.0f m2, %.1fs"),
        HidA,HidG,V10HfNX,V10HfNY,Valid,Amp,GV10All.Num(),NTex,V10AreaM2,FPlatformTime::Seconds()-T0);
}

// a new biome variant for a new look: material parameters + re-scatter (called from V10PhotoLook, i.e. only on the cut grid)
void APipelineCapture::V10RealNewVariant(FV9Look& L)
{
    if(!V10Real)return;
    FRandomStream R(V10Mix(V10RealSeed,++V10LookN));
    int32 Var=V10VarForced;
    if(Var<0){Var=R.RandRange(0,V10NumVars-1);if(Var==V10Var&&V10NumVars>1)Var=(Var+1+R.RandRange(0,V10NumVars-2))%V10NumVars;}
    V10Var=Var;const FV10Variant& V=V10Vars[Var];
    V10VarName=V.Name;V10VarLights=V.Lights;V10VarGround=V.Ground;V10VarSide=V.Side;V10VarCover=V.Cover;V10VarGCov0=V.GCov0;V10VarGCov1=V.GCov1;V10VarWet=V.Wet;
    L.Biome=V.Name;V10VarLog.AddUnique(V.Name);
    V10RealScatterNow(Var,R.RandRange(1,1<<30));
}

void APipelineCapture::V10RealScatterNow(int32 Var,int32 Seed)
{
    UWorld* World=GetWorld();const double T0=FPlatformTime::Seconds();
    const FV10Variant& V=V10Vars[FMath::Clamp(Var,0,V10NumVars-1)];const int32 Bi=V.Base;
    FRandomStream R(Seed);
    // ---- remove the previous look's instances and whitebox twins ----------------------------------------------------
    for(const TWeakObjectPtr<UPrimitiveComponent>& W:V10RealTwins)if(UPrimitiveComponent* C=W.Get()){WhiteboxComponents.Remove(C);if(Whitebox)Whitebox->RemoveShowOnlyComponent(C);C->DestroyComponent();}
    V10RealTwins.Reset();
    for(const TWeakObjectPtr<UInstancedStaticMeshComponent>& W:V10RealScatter)if(UInstancedStaticMeshComponent* C=W.Get())C->DestroyComponent();
    V10RealScatter.Reset();V10RealMIDs.Reset();V10LookCounts.Reset();
    // ---- per-look material variants (season tint, cover, wetness) ----------------------------------------------------
    const FLinearColor Fol=FLinearColor::LerpUsingHSV(V.Fol0,V.Fol1,R.FRand());const float CovAmt=R.FRandRange(V.Cov0,V.Cov1);const FV10Season* Sea=V10SeasonOf(V.Name);
    TMap<UMaterialInterface*,UMaterialInterface*> MidOf;
    auto Mat=[&](UMaterialInterface* Mi)->UMaterialInterface*
    {
        if(!Mi)return nullptr;if(UMaterialInterface** F=MidOf.Find(Mi))return *F;
        UMaterialInstanceDynamic* D=UMaterialInstanceDynamic::Create(Mi,this);
        const bool Fo=V10IsFoliageMat(Mi);
        // per material a little hue / value jitter around the season tint (not every plant turns at once)
        const FLinearColor J(R.FRandRange(.94f,1.06f),R.FRandRange(.94f,1.06f),R.FRandRange(.92f,1.08f));
        if(Fo)D->SetVectorParameterValue(TEXT("Tint"),FLinearColor::LerpUsingHSV(FLinearColor::White,Fol,R.FRandRange(.6f,1.f))*J*(1.f-.22f*V.Wet));
        else if(V.Wet>0)D->SetVectorParameterValue(TEXT("Tint"),FLinearColor(1,1,1)*(1.f-.25f*V.Wet));
        if(Fo){D->SetScalarParameterValue(TEXT("Bright"),R.FRandRange(.96f,1.08f));D->SetScalarParameterValue(TEXT("AOScale"),.3f);D->SetScalarParameterValue(TEXT("SSSAmt"),.3f);}
        if(Fo&&Sea)   // a quarter of the plants lag behind (greener)
        {
            D->SetVectorParameterValue(TEXT("SeasonCol"),Sea->Col*FLinearColor(R.FRandRange(.9f,1.1f),R.FRandRange(.85f,1.15f),R.FRandRange(.8f,1.2f)));
            D->SetScalarParameterValue(TEXT("SeasonAmt"),R.FRandRange(Sea->A0,Sea->A1)*(R.FRand()<.25f?.4f:1.f));
        }
        D->SetVectorParameterValue(TEXT("CovColor"),V.Cov*R.FRandRange(.9f,1.1f));D->SetScalarParameterValue(TEXT("CovAmt"),CovAmt*(Fo?(Sea&&Sea->FolCov?.6f:0.f):1.f));D->SetScalarParameterValue(TEXT("CovRough"),V.CovRough);D->SetScalarParameterValue(TEXT("CovDetail"),V.Cov.GetLuminance()>.5f?.35f:.85f);
        if(V.Wet>0)D->SetScalarParameterValue(TEXT("RMul"),FMath::Lerp(1.f,.6f,V.Wet));   // wet, not mirror: a top-down sun glint flooded whole frames
        V10RealMIDs.Add(D);MidOf.Add(Mi,D);return D;
    };
    // ---- scatter ---------------------------------------------------------------------------------------------------
    TArray<FString> AssetTags;FString(V.Assets).ParseIntoArray(AssetTags,TEXT(" "));
    TArray<const FV10Mesh*> Pool;for(const FV10Mesh& M:GV10All){bool In=false;for(const FString& T:AssetTags)In|=M.Biomes.Contains(T);if(In)Pool.Add(&M);}
    TMap<UStaticMesh*,TArray<FTransform>> Inst;TMap<UStaticMesh*,int32> MeshSem;TMap<UStaticMesh*,bool> MeshBig;TMap<UStaticMesh*,const FV10Mesh*> MeshInfo;
    TMap<FIntPoint,TArray<FVector4f>> BigGrid;   // x, y, radius for big object spacing (5 m cells)
    auto BigFree=[&](const FVector2D& P,float Rad)
    {
        const FIntPoint C0(FMath::FloorToInt(P.X/500.f),FMath::FloorToInt(P.Y/500.f));const int32 Rr=FMath::CeilToInt((Rad+700.f)/500.f);
        for(int32 Y=-Rr;Y<=Rr;Y++)for(int32 X=-Rr;X<=Rr;X++)if(const TArray<FVector4f>* L=BigGrid.Find(C0+FIntPoint(X,Y)))
            for(const FVector4f& B:*L)if(FVector2D::Distance(P,FVector2D(B.X,B.Y))<(Rad+B.Z)*.85f)return false;
        return true;
    };
    const FVector2D Lo(V10HfOrigin.X,V10HfOrigin.Y),Hi(V10HfOrigin.X+(V10HfNX-1)*V10HfStep,V10HfOrigin.Y+(V10HfNY-1)*V10HfStep);
    auto Zone=[&](const FVector2D& P){if(RouteDist2D(P)<2600.f)return true;for(const FVector& A:V10Anchors)if(FVector2D::Distance(P,FVector2D(A.X,A.Y))<3000.f)return true;return false;};
    const FVector S0=V10S0,SB=V10SB;
    const float Global=V10Density*R.FRandRange(.6f,1.4f);   // per look: sparser / denser
    const bool OpenClearing=R.FRand()<.25f;                 // the former paving: an open clearing or overgrown
    const float NoiseShift=R.FRandRange(0.f,100.f);
    int32 Rej[4]={0,0,0,0};
    for(int32 KI=0;KI<UE_ARRAY_COUNT(V10Kinds);KI++)
    {
        const FV10KindCfg& K=V10Kinds[KI];
        TArray<const FV10Mesh*> Ms;for(const FV10Mesh* M:Pool)if(M->Kind==K.Kind)Ms.Add(M);
        if(!Ms.Num()){V10LookCounts.Add(K.Kind,0);continue;}
        const int32 Want=FMath::Min(FMath::RoundToInt(K.Dens[Bi]*V.Mul[KI]*Global*V10AreaM2),K.Big?4000:160000);
        int32 Placed=0;const float NoiseOff=KI*13.7f+NoiseShift;
        // small kinds come in clusters (a few clumps of one or two species around a centre, gaussian spread) with bare ground in
        // between, the way ground cover grows; big objects are placed one by one with clearances
        const float MeanN=K.Big?1.f:KI==0?18.f:KI==1?6.f:KI==2?4.f:5.f;
        const float CR0=KI==0?60.f:KI==1?40.f:KI==2?50.f:40.f,CR1=KI==0?220.f:KI==1?150.f:KI==2?200.f:150.f;
        auto PlaceAt=[&](const FVector2D& P,const FV10Mesh& M,float Sc)->bool
        {
            float Z;int32 Cls;if(!V10HfAt(P.X,P.Y,Z,Cls)){Rej[2]++;return false;}
            if(Cls==2&&OpenClearing&&R.FRand()>(K.Big?.35f:.5f))return false;
            const bool Rock=K.Sem==4,Tree=M.Kind==TEXT("tree"),Grass=M.Kind==TEXT("grass")||M.Kind==TEXT("debris");
            const float Rad=.5f*FMath::Max(M.Size.X,M.Size.Y)*Sc;
            if(K.Big)
            {
                // trees: the trunk keeps clear of the route, the canopy may reach over its edge (depth / shade in the frame)
                const float RR=Tree?.35f*Rad:Rad,Clear=Tree?160.f:M.Kind==TEXT("prop")?140.f:170.f;
                if(RouteDist2D(P)<RR+Clear||FVector2D::Distance(P,FVector2D(S0))<RR+550.f||FVector2D::Distance(P,FVector2D(SB))<RR+850.f){Rej[3]++;return false;}
                const float SpR=Tree?.6f*Rad:Rad;
                if(!BigFree(P,SpR)){Rej[3]++;return false;}
                BigGrid.FindOrAdd(FIntPoint(FMath::FloorToInt(P.X/500.f),FMath::FloorToInt(P.Y/500.f))).Add(FVector4f(P.X,P.Y,SpR,0));
            }
            else if(Rock&&RouteDist2D(P)<60.f+Rad){Rej[3]++;return false;}
            const float Tilt=Rock?12.f:Tree?3.f:M.Kind==TEXT("log")||Grass?4.f:6.f;
            const FRotator Rot(R.FRandRange(-Tilt,Tilt),R.FRandRange(0.f,360.f),R.FRandRange(-Tilt,Tilt));
            const float Sink=M.Size.Z*Sc*(Rock?R.FRandRange(.1f,.3f):Tree?.04f:M.Kind==TEXT("log")?.12f:.03f)+M.MinZ*Sc;
            const FVector S3=FVector(Sc)*FVector(R.FRandRange(.92f,1.08f),R.FRandRange(.92f,1.08f),R.FRandRange(.9f,1.1f));
            Inst.FindOrAdd(M.Mesh).Add(FTransform(Rot,FVector(P.X,P.Y,Z-Sink),S3));MeshSem.Add(M.Mesh,K.Sem);MeshBig.Add(M.Mesh,K.Big||Rock);MeshInfo.Add(M.Mesh,&M);
            return true;
        };
        auto PickMesh=[&]()->const FV10Mesh*
        {
            const FV10Mesh* Pk=Ms[R.RandRange(0,Ms.Num()-1)];
            if(KI==0)for(int32 Tr=0;Tr<3&&FMath::Max(Pk->Size.X,Pk->Size.Y)<20.f;Tr++)Pk=Ms[R.RandRange(0,Ms.Num()-1)];
            return Pk;
        };
        for(int32 Try=0;Try<Want*6&&Placed<Want;Try++)
        {
            const FVector2D P0(R.FRandRange(Lo.X,Hi.X),R.FRandRange(Lo.Y,Hi.Y));
            if(!Zone(P0)){Rej[0]++;continue;}
            if(K.Cut[Bi]>-1.f&&V10Fbm(P0.X,P0.Y,K.Big?2500.f:1300.f,NoiseOff)<K.Cut[Bi]){Rej[1]++;continue;}
            const FV10Mesh* MA=PickMesh();const FV10Mesh* MB=R.FRand()<.4f?PickMesh():MA;
            const bool Rock=K.Sem==4,Tree=MA->Kind==TEXT("tree");
            auto Scale=[&](const FV10Mesh& M){return Rock?R.FRandRange(K.Big?.7f:.6f,K.Big?1.35f:1.6f):Tree?R.FRandRange(.8f,1.2f):M.Kind==TEXT("prop")?R.FRandRange(.95f,1.05f):KI==0?R.FRandRange(1.f,1.6f):R.FRandRange(.8f,1.3f);};
            if(K.Big){if(PlaceAt(P0,*MA,Scale(*MA)))Placed++;continue;}
            const int32 N=FMath::Max(1,FMath::RoundToInt(MeanN*R.FRandRange(.3f,1.7f)));const float Rc=R.FRandRange(CR0,CR1);
            for(int32 J=0;J<N&&Placed<Want;J++)
            {
                const float U=FMath::Max(1e-4f,R.FRand()),Rr=FMath::Min(Rc*.5f*FMath::Sqrt(-2.f*FMath::Loge(U)),Rc*1.6f),An=R.FRandRange(0.f,2*UE_PI);
                const FV10Mesh& M=*(J%3==2?MB:MA);
                if(PlaceAt(P0+FVector2D(FMath::Cos(An),FMath::Sin(An))*Rr,M,Scale(M)))Placed++;
            }
        }
        V10LookCounts.Add(K.Kind,Placed);
    }
    // ---- components (stencil set here: the label set-up pass ran before the first look) -------------------------------
    int32 NComp=0,NInst=0;
    for(auto& E:Inst)
    {
        const int32 S=FMath::Clamp(MeshSem.FindRef(E.Key),0,6);
        AActor* H=V10Holder[S].Get();
        if(!H)
        {
            H=World->SpawnActor<AActor>(AActor::StaticClass(),FTransform(V10HfOrigin));if(!H)continue;
            USceneComponent* HR=NewObject<USceneComponent>(H);H->SetRootComponent(HR);HR->RegisterComponent();
            H->Tags.Add(FName(*FString::Printf(TEXT("semantic:%d"),S)));H->Tags.Add(TEXT("v4_event"));H->Tags.Add(TEXT("v10_real"));V10Holder[S]=H;
        }
        auto* C=NewObject<UInstancedStaticMeshComponent>(H);C->SetupAttachment(H->GetRootComponent());C->SetMobility(EComponentMobility::Movable);
        C->SetStaticMesh(E.Key);C->SetCollisionEnabled(ECollisionEnabled::NoCollision);C->SetCastShadow(true);C->ComponentTags.Add(TEXT("v10_scatter"));
        if(const FV10Mesh* Info=MeshInfo.FindRef(E.Key))if(Info->Kind==TEXT("grass")||Info->Kind==TEXT("plant")||Info->Kind==TEXT("debris"))
        {   // ground cover shadows: 1 full, 2 no contact shadows (the screen-space ones blacken dense tufts), 0 none
            if(V10GrassShadow==0)C->SetCastShadow(false);else if(V10GrassShadow==2)C->bCastContactShadow=false;
            // masked cards become solid blobs in the mesh distance fields / Lumen scene: every clump then occludes the sky light
            // and leaves a dark halo on the ground. Ground cover stays out of the indirect / distance field lighting.
            C->bAffectDistanceFieldLighting=false;C->bAffectDynamicIndirectLighting=false;
        }
        if(MeshBig.FindRef(E.Key))C->ComponentTags.Add(TEXT("v10_big"));
        if(const FV10Mesh* Info=MeshInfo.FindRef(E.Key))for(int32 Sl=0;Sl<Info->Mats.Num();Sl++)if(UMaterialInterface* Mi=Mat(Info->Mats[Sl]))C->SetMaterial(Sl,Mi);
        C->SetRenderCustomDepth(true);C->SetCustomDepthStencilValue(S);C->SetTextureForceResidentFlag(true);
        C->RegisterComponent();H->AddInstanceComponent(C);C->AddInstances(E.Value,false,true);
        V10RealScatter.Add(C);NComp++;NInst+=E.Value.Num();
    }
    // ---- whitebox twins of the structural objects (rocks, shrubs, trees, logs, props) ----------------------------------
    if(Whitebox&&V10WhiteHolder.IsValid())
    {
        UMaterialInterface* White=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Xfer/V10/Materials/M_V10White.M_V10White"));if(!White)White=WhiteMaterialRef;
        AActor* H=V10WhiteHolder.Get();
        for(const TWeakObjectPtr<UInstancedStaticMeshComponent>& Sw:V10RealScatter)if(UInstancedStaticMeshComponent* C=Sw.Get())
        {
            if(!C->ComponentHasTag(TEXT("v10_big")))continue;
            auto* W=NewObject<UInstancedStaticMeshComponent>(H);W->SetupAttachment(H->GetRootComponent());W->SetMobility(EComponentMobility::Movable);W->SetStaticMesh(C->GetStaticMesh());
            for(int32 K=0;K<C->GetNumMaterials();K++)W->SetMaterial(K,White);
            W->SetCollisionEnabled(ECollisionEnabled::NoCollision);W->SetCastShadow(false);W->RegisterComponent();H->AddInstanceComponent(W);
            TArray<FTransform> T;T.Reserve(C->GetInstanceCount());
            for(int32 K=0;K<C->GetInstanceCount();K++){FTransform X;C->GetInstanceTransform(K,X,true);T.Add(X);}
            W->AddInstances(T,false,true);
            WhiteboxComponents.Add(W);Whitebox->ShowOnlyComponent(W);V10RealTwins.Add(W);
        }
    }
    V10LookCounts.Add(TEXT("instances"),NInst);V10LookCounts.Add(TEXT("components"),NComp);V10LookCounts.Add(TEXT("pool_meshes"),Pool.Num());
    V10LookCounts.Add(TEXT("density_x100"),FMath::RoundToInt(Global*100));V10LookCounts.Add(TEXT("open_clearing"),OpenClearing);V10LookCounts.Add(TEXT("whitebox_twins"),V10RealTwins.Num());
    UE_LOG(LogTemp,Display,TEXT("DATASET_V10 real look %d: %s pool %d, %d instances in %d components (density %.2f, cover %.2f, wet %.1f, rejects %d/%d/%d/%d) %.1fs"),
        V10LookN,V.Name,Pool.Num(),NInst,NComp,Global,CovAmt,V.Wet,Rej[0],Rej[1],Rej[2],Rej[3],FPlatformTime::Seconds()-T0);
}

void APipelineCapture::V10RealWhitebox()
{
    if(!V10Real||!Whitebox)return;
    UMaterialInterface* White=LoadObject<UMaterialInterface>(nullptr,TEXT("/Game/Xfer/V10/Materials/M_V10White.M_V10White"));
    if(!White)White=WhiteMaterialRef;
    // the authored structural whitebox describes the hidden scene: out of the whitebox pass
    int32 Removed=0;
    for(TActorIterator<AActor> I(GetWorld());I;++I)if(I->ActorHasTag(TEXT("whitebox"))&&!Cast<APipelineWhitebox>(*I))
    {
        TArray<UPrimitiveComponent*> Cs;I->GetComponents(Cs);
        for(UPrimitiveComponent* C:Cs){Whitebox->RemoveShowOnlyComponent(C);WhiteboxComponents.Remove(C);C->SetVisibility(false);Removed++;}
    }
    AActor* H=GetWorld()->SpawnActor<AActor>(AActor::StaticClass(),FTransform(V10HfOrigin));if(!H)return;
    USceneComponent* HR=NewObject<USceneComponent>(H);H->SetRootComponent(HR);HR->RegisterComponent();H->Tags.Add(TEXT("whitebox_v10"));V10WhiteHolder=H;
    for(const TWeakObjectPtr<UStaticMeshComponent>& G:V10RealGround)if(UStaticMeshComponent* C=G.Get())
    {
        auto* W=NewObject<UStaticMeshComponent>(H);W->SetupAttachment(HR);W->SetMobility(EComponentMobility::Movable);W->SetStaticMesh(C->GetStaticMesh());W->SetMaterial(0,White);
        W->SetCollisionEnabled(ECollisionEnabled::NoCollision);W->SetCastShadow(false);W->RegisterComponent();W->SetWorldTransform(C->GetComponentTransform());H->AddInstanceComponent(W);
        WhiteboxComponents.Add(W);Whitebox->ShowOnlyComponent(W);
    }
    V10RealCounts.Add(TEXT("whitebox_removed"),Removed);
    UE_LOG(LogTemp,Display,TEXT("DATASET_V10 real whitebox: %d authored components out, ground twin in (object twins follow every look)"),Removed);
}

void APipelineCapture::V10RealCamera(FMinimalViewInfo& View)
{
    if(!V10Real||!Player)return;
    // same framing as the orthographic view (frame width W at the pivot = the player), seen through a telephoto lens
    const float W=FMath::Max(View.OrthoWidth,300.f);const FVector Fwd=View.Rotation.Vector();
    const FVector Pivot=View.Location+Fwd*Player->CameraBoom->TargetArmLength;
    const float Fov=FMath::Clamp(V10Fov,10.f,90.f);
    V10CamDist=.5f*W/FMath::Tan(FMath::DegreesToRadians(.5f*Fov));
    View.ProjectionMode=ECameraProjectionMode::Perspective;View.FOV=Fov;View.Location=Pivot-Fwd*V10CamDist;
    // the telephoto camera sits 30-80 m above the ground: height fog over that whole path laid a milky veil over the frame.
    // Fog starts near the ground (aerial haze stays for mist / storm looks)
    if(UExponentialHeightFogComponent* F=V10Fog.Get())
    {
        const float St=V10CamDist*(V9Cur.Light==1||V9Cur.Light==7?.6f:.9f);
        if(FMath::Abs(F->StartDistance-St)>100.f){F->SetStartDistance(St);F->SetVolumetricFogStartDistance(St);}
    }
}

void APipelineCapture::V10RealLookJson(TSharedPtr<FJsonObject> J)
{
    if(!V10Real)return;
    J->SetStringField(TEXT("v10_variant"),V10VarName);
    TSharedPtr<FJsonObject> C=MakeShared<FJsonObject>();for(const auto& P:V10LookCounts)C->SetNumberField(P.Key,P.Value);J->SetObjectField(TEXT("v10_scatter"),C);
}

void APipelineCapture::WriteV10Real(TSharedPtr<FJsonObject> O)
{
    if(!V10Real)return;
    TSharedPtr<FJsonObject> J=MakeShared<FJsonObject>();
    TArray<TSharedPtr<FJsonValue>> Vs;for(const FString& S:V10VarLog)Vs.Add(MakeShared<FJsonValueString>(S));J->SetArrayField(TEXT("variants_used"),Vs);
    J->SetStringField(TEXT("forced_variant"),V10VarForced>=0?V10Vars[V10VarForced].Name:TEXT(""));J->SetNumberField(TEXT("variant_count"),V10NumVars);J->SetNumberField(TEXT("density"),V10Density);
    J->SetArrayField(TEXT("fov_range_deg"),{MakeShared<FJsonValueNumber>(V10FovMin),MakeShared<FJsonValueNumber>(V10FovMax)});
    J->SetNumberField(TEXT("height_field_step_cm"),V10HfStep);J->SetNumberField(TEXT("height_field_nx"),V10HfNX);J->SetNumberField(TEXT("height_field_ny"),V10HfNY);
    TSharedPtr<FJsonObject> C=MakeShared<FJsonObject>();for(const auto& P:V10RealCounts)C->SetNumberField(P.Key,P.Value);J->SetObjectField(TEXT("counts"),C);
    J->SetStringField(TEXT("assets"),TEXT("Poly Haven CC0 1.0 photo-scanned models and PBR sets (see Content/Xfer/V10/v10_models.json, v10_pbr.json)"));
    O->SetObjectField(TEXT("v10_real"),J);
}

// ---- promo cinematic cameras (-DatasetCine=orbit|hero|crane|drone|fight|dolly) ------------------------------------------
// Free camera for showcase footage; every pass (RGB, whitebox, labels, depth) uses the same view, so the structural
// whitebox stays aligned with the render. Off unless -DatasetCine is given.
void V10CineCamera(AGameDemoFighter* Player,FMinimalViewInfo& View,float Time,int32 Frame,USceneCaptureComponent2D* RGBC)
{
    static float Fps=30.f;
    static int32 Mode=-1;static float Seed=30.f,Speed=1.f,FStop=2.2f,T0=-1.f,LastT=0.f,A0=0.f,DistSm=0.f;
    static FVector TSm,CamSm,DirSm,Ctr;static float Rad=0.f;
    const TCHAR* Cmd=FCommandLine::Get();
    if(Mode<0)
    {
        FString M;FParse::Value(Cmd,TEXT("DatasetCine="),M);
        Mode=M==TEXT("orbit")?1:M==TEXT("hero")?2:M==TEXT("crane")?3:M==TEXT("drone")?4:M==TEXT("fight")?5:M==TEXT("dolly")?6:0;
        FParse::Value(Cmd,TEXT("DatasetCineSeed="),Seed);FParse::Value(Cmd,TEXT("DatasetCineSpeed="),Speed);FParse::Value(Cmd,TEXT("DatasetCineFStop="),FStop);{int32 Hz=60,St=2;FParse::Value(Cmd,TEXT("DatasetSimHz="),Hz);FParse::Value(Cmd,TEXT("DatasetStride="),St);Fps=float(Hz)/FMath::Max(1,St);}
        if(Mode)UE_LOG(LogTemp,Display,TEXT("DATASET_CINE mode %s seed %.0f speed %.2f fstop %.1f"),*M,Seed,Speed,FStop);
    }
    if(Mode==0||!Player)return;
    UWorld* World=Player->GetWorld();if(!World)return;
    AGameDemoFighter* Boss=Player->Opponent.Get();
    const FVector P=Player->GetActorLocation();
    FVector T=P+FVector(0,0,25);float Sep=0.f;
    float FightW=0.f;
    if(Mode==5&&Boss){const FVector B=Boss->GetActorLocation();Sep=FVector::Dist2D(P,B);FightW=FMath::Clamp((1000.f-Sep)/450.f,0.f,1.f);T=FMath::Lerp(P,B,.42f*FightW)+FVector(0,0,25.f+20.f*FightW);}
    if(T0<0.f)
    {
        T0=Time;LastT=Time;TSm=T;A0=Player->GetActorRotation().Yaw+180.f+Seed;DirSm=Player->GetActorForwardVector();
        FBox B(ForceInit);B+=P;if(Boss)B+=Boss->GetActorLocation();for(const FVector& W:Player->ExplorationWaypoints)B+=W;for(const FVector& W:Player->ExplorationPlaces)B+=W;
        Ctr=B.GetCenter();Ctr.Z=P.Z-90.f;Rad=FMath::Max(1500.f,.5f*FVector::Dist2D(B.Min,B.Max));
        DistSm=0.f;CamSm=FVector::ZeroVector;
    }
    static FVector PrevP=P;
    const float t=Frame/Fps,Dt=FMath::Clamp(Time-LastT,0.f,.1f);LastT=Time;   // shot time runs from the first written frame (warm-up holds the start pose)
    auto Ease=[](float U){U=FMath::Clamp(U,0.f,1.f);return U*U*(3.f-2.f*U);};
    auto Smooth=[&](float Tau){return Dt<=0.f?0.f:1.f-FMath::Exp(-Dt/Tau);};
    TSm=FMath::Lerp(TSm,T,Smooth(Mode==4?2.f:.35f));
    float Dist=430.f,Hgt=70.f,Ang=A0,Fov=40.f;FVector Look=TSm;bool Trace=true;
    switch(Mode)
    {
    case 1: Ang=A0+14.f*Speed*t;Dist=520.f;Hgt=125.f;break;
    case 2:   // chase: low camera behind and beside the player, following the smoothed travel direction
    {
        const FVector V=Dt>0.f?(P-PrevP)/Dt:FVector::ZeroVector;
        if(V.Size2D()>60.f)DirSm=FMath::Lerp(DirSm,V.GetSafeNormal2D(),Smooth(1.1f)).GetSafeNormal2D();
        const FVector R=FVector::CrossProduct(FVector::UpVector,DirSm);
        const FVector Cam=TSm-DirSm*430.f+R*(85.f*(Seed>=0?1:-1))+FVector(0,0,65);
        CamSm=CamSm.IsZero()?Cam:FMath::Lerp(CamSm,Cam,Smooth(.45f));
        Dist=-1.f;Fov=40.f;Look=TSm+DirSm*160.f+FVector(0,0,10);break;
    }
    case 3:{const float U=Ease(t/(12.f/Speed));Dist=FMath::Lerp(280.f,1150.f,U);Hgt=FMath::Lerp(-10.f,980.f,U);Ang=A0+6.f*Speed*t;Fov=45.f;break;}
    case 4:{Dist=Rad*1.05f+700.f;Hgt=Rad*.62f+550.f;Ang=A0+4.5f*Speed*t;Fov=50.f;Look=Ctr;Trace=false;break;}
    case 5:{Dist=FMath::Lerp(500.f,FMath::Clamp(1.1f*Sep+380.f,480.f,950.f),FightW);Hgt=130.f;Ang=A0+10.f*Speed*t;Fov=42.f;break;}
    case 6:{const float U=Ease(t/(10.f/Speed));Dist=FMath::Lerp(950.f,330.f,U);Hgt=FMath::Lerp(260.f,55.f,U);Ang=A0+3.f*Speed*t;Fov=36.f;break;}
    }
    FVector Cam;
    if(Dist>0.f)
    {
        DistSm=DistSm<=0.f?Dist:FMath::Lerp(DistSm,Dist,Smooth(.6f));
        const float Rd=FMath::DegreesToRadians(Ang);
        Cam=Look+FVector(FMath::Cos(Rd)*DistSm,FMath::Sin(Rd)*DistSm,Hgt);
    }
    else Cam=CamSm;
    if(Trace)
    {
        FCollisionQueryParams Q(SCENE_QUERY_STAT(V10Cine),false);Q.AddIgnoredActor(Player);if(Boss)Q.AddIgnoredActor(Boss);
        FHitResult H;
        // pull in only for real occluders (walls, buildings); shrubs, grass and small props are ignored and passed through
        for(int32 It=0;It<8;It++)
        {
            if(!World->LineTraceSingleByChannel(H,Look,Cam,ECC_Camera,Q))break;
            const UPrimitiveComponent* Hc=H.GetComponent();const FVector Ext=Hc?Hc->Bounds.BoxExtent:FVector(1e4);
            if(Hc&&Ext.Z<140.f&&FMath::Max(Ext.X,Ext.Y)<400.f){Q.AddIgnoredComponent(Hc);continue;}
            Cam=H.Location+(Look-Cam).GetSafeNormal()*30.f;break;
        }
        if(World->LineTraceSingleByChannel(H,Cam+FVector(0,0,200),Cam-FVector(0,0,400),ECC_Visibility,Q)&&Cam.Z<H.Location.Z+35.f)Cam.Z=H.Location.Z+35.f;
    }
    if(Mode!=4){const FVector D=Cam-(P+FVector(0,0,40));if(D.Size()<240.f)Cam=P+FVector(0,0,40)+D.GetSafeNormal()*240.f;}
    if(Dt>0.f)PrevP=P;
    View.ProjectionMode=ECameraProjectionMode::Perspective;View.FOV=Fov;View.Location=Cam;View.Rotation=(Look-Cam).Rotation();
    if(RGBC)
    {
        auto& PP=RGBC->PostProcessSettings;RGBC->ShowFlags.SetDepthOfField(Mode!=4);
        PP.bOverride_DepthOfFieldFocalDistance=true;PP.DepthOfFieldFocalDistance=FVector::Dist(Cam,Look);
        PP.bOverride_DepthOfFieldFstop=true;PP.DepthOfFieldFstop=Mode==4?16.f:FStop;
        PP.bOverride_DepthOfFieldSensorWidth=true;PP.DepthOfFieldSensorWidth=36.f;
    }
}