-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapture-sun-and-atmosphere-shots.ts
More file actions
2377 lines (2226 loc) · 87.6 KB
/
Copy pathcapture-sun-and-atmosphere-shots.ts
File metadata and controls
2377 lines (2226 loc) · 87.6 KB
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env tsx
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2025-2026 Matthew Kissinger
/**
* Capture Playwright smoke screenshots for cycle #12
* `cycle-sun-and-atmosphere-overhaul` task `sun-and-atmosphere-playtest-evidence`.
*
* Extends the framework from `scripts/capture-hosek-wilkie-shots.ts`. Adds a
* `--tod=<noon|golden|dusk|twilight|dawn|midnight>` flag that pins the active
* scenario's preset to the requested time-of-day via
* `WorldBuilder.forceTimeOfDay` (per `AtmosphereSystem.ts:200-204`); converts
* the target *absolute* hour to the preset-relative fraction the runtime
* expects (`forceTimeOfDay = (targetHour - preset.todCycle.startHour + 24) / 24`).
*
* The full capture matrix per the cycle brief is:
* - 20 visual shots: 5 scenarios x 4 TOD (noon / golden / dusk / twilight,
* plus the brief's optional dawn TOD). The default run captures
* noon/golden/dusk/twilight for all five scenarios (= 20). Pass
* `--tod=dawn` to add the dawn matrix on top.
* - 8 WebGPU vs WebGL2 parity shots: 1 scenario (openfrontier) x 4 TOD x 2
* renderer modes.
* - 5 night-red regression shots: each scenario at absolute midnight; the
* run pixel-samples `renderer.moonLight.color` and asserts
* `r < 0.5 * max(g, b)` (red-not-dominant assertion lives inside the
* script and writes a JSON summary alongside the captures).
*
* Total when invoked with the cycle's default matrix: 20 + 8 + 5 = 33 shots.
*
* Cycle `cycle-skylut-resolution-bump` task `skylut-playtest-evidence`
* (2026-05-19) adds a `--lut-bump-check` flag that takes a focused pair only:
* Open Frontier noon + A Shau midday-flyover. Used with `--prefix=pre|post`
* to produce the before/after baseline pair. The artifact root flips to
* `artifacts/cycle-skylut-resolution-bump/playtest-evidence/`. The flag also
* computes a horizon-row gradient monotonicity check (delta-per-pixel
* ≤ 4/255 across the visible band) and a fog-vs-sky horizon parity check
* (±5%) and writes them to `bump-summary.json` alongside the PNGs.
*
* Usage:
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts # full 33-shot matrix
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --tod=noon # single TOD, all scenarios
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --scenario=ashau # single scenario, all TOD
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --skip-parity # skip the WebGPU/WebGL2 pair set
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --skip-night # skip the night-red regression set
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --lut-bump-check --prefix=pre # pre-bump baseline pair
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --lut-bump-check --prefix=post # post-bump pair + analysis
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --ridge-occlusion-check --scenario=ashau --tod=dusk
* npx tsx scripts/capture-sun-and-atmosphere-shots.ts --ridge-occlusion-check --scenario=ashau --tod=dusk --renderer-modes=webgpu-strict,webgpu-force-webgl --angle=d3d11
*
* Notes:
* - `combat120` (ai_sandbox) has no `todCycle` and ignores `forceTimeOfDay`.
* The script detects the absent cycle and falls back to direct
* `sunDirection` manipulation (matches the pattern in
* `scripts/capture-sky-sun-disc-restore.ts:forceSunBelowHorizon`).
* - Captures are best-effort. If a scenario fails to load (e.g. the perf-harness
* bundle is stale), the script logs the failure and continues to the next
* shot rather than throwing — autonomous-loop posture treats this as
* evidence-capture, not a merge gate.
* - Artifacts are written under `artifacts/cycle-sun-and-atmosphere-overhaul/playtest-evidence/`
* (gitignored by default; commit via `git add -f`).
*/
import { chromium, type Page, type ConsoleMessage } from 'playwright';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import sharp from 'sharp';
import { startServer, stopServer, type ServerHandle } from './preview-server';
type ScenarioKey = 'ashau' | 'openfrontier' | 'tdm' | 'zc' | 'combat120';
type TodLabel = 'noon' | 'golden' | 'dusk' | 'twilight' | 'dawn' | 'midnight';
type RendererMode = 'webgpu' | 'webgpu-strict' | 'webgpu-force-webgl' | 'webgl';
type CaptureView = 'sun' | 'ridge';
type BrowserAngleBackend = 'swiftshader' | 'd3d11' | 'vulkan' | 'default';
interface ScenarioPreset {
key: ScenarioKey;
mode: string; // engine.startGameWithMode argument
startHour: number; // matches ScenarioAtmospherePresets.ts todCycle.startHour
hasTodCycle: boolean;
sunAzimuthRad: number;
sunElevationRad: number;
cameraHeight: number; // sky-dominant clearance above local terrain
settleSec: number;
label: string;
}
interface Pose {
position: [number, number, number];
yawDeg: number;
pitchDeg: number;
lookAt?: [number, number, number];
}
interface RidgeOcclusionDiagnostics {
target: [number, number, number];
cameraGround: [number, number, number];
sunHorizontal: [number, number];
ridgeRiseMeters: number;
score: number;
samplesChecked: number;
}
interface SunOcclusionDiagnostics {
terrainOccluded: boolean;
terrainHitDistance: number | null;
terrainClearanceAtCamera: number | null;
samplesChecked: number;
cameraPosition: [number, number, number] | null;
sunDirection: [number, number, number] | null;
reason: string;
}
// ----- Configuration tables -----
const SCENARIO_PRESETS: ScenarioPreset[] = [
{
key: 'ashau',
mode: 'a_shau_valley',
startHour: 6,
hasTodCycle: true,
sunAzimuthRad: Math.PI * 0.15,
sunElevationRad: Math.PI * 0.055,
cameraHeight: 300,
settleSec: 8,
label: 'A Shau Valley',
},
{
key: 'openfrontier',
mode: 'open_frontier',
startHour: 12,
hasTodCycle: true,
sunAzimuthRad: Math.PI * 0.25,
sunElevationRad: Math.PI * 0.42,
cameraHeight: 120,
settleSec: 6,
label: 'Open Frontier',
},
{
key: 'tdm',
mode: 'tdm',
startHour: 18,
hasTodCycle: true,
sunAzimuthRad: Math.PI * 1.1,
sunElevationRad: Math.PI * 0.035,
cameraHeight: 80,
settleSec: 6,
label: 'TDM',
},
{
key: 'zc',
mode: 'zone_control',
startHour: 16,
hasTodCycle: true,
sunAzimuthRad: Math.PI * 0.78,
sunElevationRad: Math.PI * 0.12,
cameraHeight: 100,
settleSec: 6,
label: 'Zone Control',
},
{
key: 'combat120',
mode: 'ai_sandbox',
startHour: 12, // mirrors preset.sunElevationRad ~ noon, but no animation
hasTodCycle: false,
sunAzimuthRad: Math.PI * 0.25,
sunElevationRad: Math.PI * 0.42,
cameraHeight: 80,
settleSec: 6,
label: 'combat120',
},
];
/**
* Absolute clock hour each TOD targets. Mirrors spike Section 4 visual
* targets and lines up with `clockElevationAtHour` in
* ScenarioAtmospherePresets.ts (which uses a sin curve with maxElev=70deg and
* minElev=-10deg, so the available elevation range is dawn→noon→dusk→midnight
* = -10°→+70°→-10°→-10°). The TOD hours below were back-solved from those
* elevations to land at the spike Section 4 targets per TOD bucket.
*/
const TOD_HOURS: Record<TodLabel, number> = {
noon: 12, // peak elevation +70 deg (max in the model)
golden: 16, // descending branch; sin gives ~+22 deg elevation
dusk: 17.6, // sin gives ~+6 deg elevation
twilight: 20, // descending past horizon; sin gives ~-5 deg elevation
dawn: 4, // mirror of dusk, pre-sunrise; sin gives ~+6 deg
midnight: 0, // absolute midnight; elevation pinned to -10 deg
};
const DEFAULT_VISUAL_TODS: TodLabel[] = ['noon', 'golden', 'dusk', 'twilight'];
const PARITY_SCENARIO: ScenarioKey = 'openfrontier';
const PARITY_TODS: TodLabel[] = DEFAULT_VISUAL_TODS;
const NIGHT_TOD: TodLabel = 'midnight';
const PORT = 9182;
const VIEWPORT = { width: 1920, height: 1080 };
const STARTUP_TIMEOUT_MS = 90_000;
const OUT_DIR = join(
process.cwd(),
'artifacts',
'cycle-sun-and-atmosphere-overhaul',
'playtest-evidence'
);
/**
* Cycle `cycle-skylut-resolution-bump`: focused pre/post artifact root used
* only when `--lut-bump-check` is passed. Distinct from `OUT_DIR` so the
* cycle's evidence lives in its own folder under `artifacts/`.
*/
const LUT_BUMP_OUT_DIR = join(
process.cwd(),
'artifacts',
'cycle-skylut-resolution-bump',
'playtest-evidence'
);
/**
* Cycle `cycle-skylut-resolution-bump` focused capture pair: Open Frontier
* noon (the canonical "midday dark spots" report) + A Shau midday flyover
* (the "skybox edge through terrain" report). Both use the existing preset's
* `cameraHeight` so the framing matches the user's reported viewpoint.
*/
const LUT_BUMP_PAIR: Array<{ scenario: ScenarioKey; tod: TodLabel }> = [
{ scenario: 'openfrontier', tod: 'noon' },
{ scenario: 'ashau', tod: 'noon' },
];
// ----- CLI -----
function readFlagValue(name: string): string | null {
const flagged = process.argv.find((a) => a.startsWith(`--${name}=`));
if (flagged) return flagged.split('=')[1] ?? null;
const idx = process.argv.indexOf(`--${name}`);
if (idx >= 0 && idx + 1 < process.argv.length) return process.argv[idx + 1];
return null;
}
function hasFlag(name: string): boolean {
return process.argv.includes(`--${name}`);
}
function logStep(msg: string): void {
console.log(`[${new Date().toISOString()}] ${msg}`);
}
function parseRendererModes(defaultModes: RendererMode[]): RendererMode[] {
const raw = readFlagValue('renderer-modes');
if (!raw) return defaultModes;
const parsed = raw
.split(',')
.map((part) => part.trim())
.filter(Boolean);
const allowed = new Set<RendererMode>(['webgpu', 'webgpu-strict', 'webgpu-force-webgl', 'webgl']);
const modes = parsed.map((mode) => {
if (!allowed.has(mode as RendererMode)) {
throw new Error(`Invalid --renderer-modes entry "${mode}". Expected webgpu, webgpu-strict, webgpu-force-webgl, or webgl.`);
}
return mode as RendererMode;
});
return modes.length > 0 ? modes : defaultModes;
}
function parseBrowserAngle(): BrowserAngleBackend {
const raw = readFlagValue('angle') ?? 'swiftshader';
if (
raw !== 'swiftshader'
&& raw !== 'd3d11'
&& raw !== 'vulkan'
&& raw !== 'default'
) {
throw new Error(`Invalid --angle=${raw}. Expected swiftshader, d3d11, vulkan, or default.`);
}
return raw;
}
function buildBrowserLaunchOptions(): {
headless: boolean;
channel?: string;
args: string[];
angle: BrowserAngleBackend;
} {
const angle = parseBrowserAngle();
const channel = readFlagValue('browser-channel') ?? undefined;
const args = [
...(angle === 'default' ? [] : [`--use-angle=${angle}`]),
'--enable-webgl',
'--enable-unsafe-webgpu',
];
return {
headless: !hasFlag('headed'),
channel,
args,
angle,
};
}
// ----- TOD math -----
/**
* Convert an absolute target hour to the preset-relative fraction
* `WorldBuilder.forceTimeOfDay` expects. Matches the AtmosphereSystem wiring at
* `AtmosphereSystem.ts:200-204`:
*
* simulationTimeSeconds = forceTimeOfDay * dayLengthSeconds
*
* and `computeSunDirectionAtTime` reads
*
* currentHour = startHour + (simulationTimeSeconds / dayLengthSeconds) * 24
*
* so to land at `targetHour`, set `forceTimeOfDay = (targetHour - startHour + 24) % 24 / 24`.
*/
function targetHourToForceTod(targetHour: number, startHour: number): number {
const wrapped = ((targetHour - startHour) % 24 + 24) % 24;
return wrapped / 24;
}
// ----- Engine driving -----
async function waitForEngine(page: Page): Promise<void> {
try {
await page.waitForFunction(
() => Boolean((window as { __engine?: unknown }).__engine),
undefined,
{ timeout: STARTUP_TIMEOUT_MS }
);
} catch (error) {
const fatal = await readFatalOverlayText(page);
const message = error instanceof Error ? error.message : String(error);
throw new Error(fatal ? `${message}; fatalOverlay=${fatal}` : message);
}
}
async function readFatalOverlayText(page: Page): Promise<string | null> {
try {
return await page.evaluate(() => {
const text = document.body?.innerText?.trim() ?? '';
if (!text.includes('Failed to initialize')) return null;
return text.replace(/\s+/g, ' ').slice(0, 500);
});
} catch {
return null;
}
}
async function startMode(page: Page, mode: string): Promise<void> {
logStep(`Starting mode ${mode}`);
await page.evaluate(async (m: string) => {
const engine = (window as { __engine?: { startGameWithMode?: (mode: string) => Promise<void> } }).__engine;
if (!engine?.startGameWithMode) throw new Error('engine.startGameWithMode unavailable');
await engine.startGameWithMode(m);
}, mode);
const deadline = Date.now() + 60_000;
while (Date.now() < deadline) {
const state = await page.evaluate(() => {
const e = (window as { __engine?: { gameStarted?: boolean; startupFlow?: { getState?: () => { phase?: string } } } }).__engine;
return {
gameStarted: Boolean(e?.gameStarted),
phase: String(e?.startupFlow?.getState?.()?.phase ?? ''),
};
});
if (state.gameStarted || state.phase === 'live') return;
await page.waitForTimeout(250);
}
throw new Error(`Mode ${mode} did not enter live phase`);
}
async function dismissBriefingIfPresent(page: Page): Promise<void> {
const beginBtn = page.locator('[data-ref="beginBtn"]');
try {
if (await beginBtn.isVisible({ timeout: 1500 })) {
await beginBtn.click();
await page.waitForTimeout(500);
}
} catch {
/* not present */
}
}
/**
* Pin the active scenario's preset to the requested TOD.
*
* The runtime `forceTimeOfDay` path is gated on `import.meta.env.DEV` (see
* `AtmosphereSystem.ts:200`), so in the perf-harness vite-build bundle the
* `window.__worldBuilder` override is dead-coded out. To keep the evidence
* fully reproducible against the production build target, we ALSO directly
* mutate the `AtmosphereSystem` internals: `simulationTimeSeconds`
* (matches `forceTimeOfDay * dayLength`) and `sunDirection` (matches what
* `computeSunDirectionAtTime` would have produced). For presets without a
* `todCycle` (combat120) we only set `sunDirection` directly.
*
* We additionally publish to `window.__worldBuilder` so a dev-mode rerun of
* the script produces the same pinned sun-direction via the WorldBuilder
* channel.
*
* After the override lands we burn down the sky-LUT refresh timer + tick a
* couple of frames so the dome re-bakes against the new sun direction before
* the snap.
*/
async function applyTod(
page: Page,
preset: ScenarioPreset,
tod: TodLabel
): Promise<{ forceTod: number; appliedVia: 'worldBuilder' | 'directSunRotation' }> {
const targetHour = TOD_HOURS[tod];
const forceTod = targetHourToForceTod(targetHour, preset.startHour);
// Always publish the WorldBuilder override; harmless in retail because the
// runtime gate is `import.meta.env.DEV`, but a dev-mode rerun benefits.
await page.evaluate((tod: number) => {
const w = window as unknown as Record<string, unknown>;
const existing = (w['__worldBuilder'] as Record<string, unknown> | undefined) ?? {};
w['__worldBuilder'] = { ...existing, forceTimeOfDay: tod, active: true };
}, forceTod);
// Build the target sun direction unit vector for this TOD; this is what we
// want the LUT bake + moonLight to read against. The model's clamped
// computeSunDirectionAtTime may NOT produce this exact vector (e.g. ashau's
// sunElevationRad=10° + clamp envelope means the model never returns
// elevation < -10°), so we override the sunDirection AFTER the update() tick
// inside forceSkyRefresh so the night-red blend's `sunElevationRad < -8°`
// gate actually fires for the night-red regression test.
const todElevationRad = todToAbsoluteElevationRad(tod);
const cosE = Math.cos(todElevationRad);
const targetSunDir = {
x: cosE * Math.cos(preset.sunAzimuthRad),
y: Math.sin(todElevationRad),
z: cosE * Math.sin(preset.sunAzimuthRad),
};
if (preset.hasTodCycle) {
// Directly mutate AtmosphereSystem internals so the override fires in the
// perf-harness build target too. Mirror computeSunDirectionAtTime by
// setting simulationTimeSeconds to `forceTod * dayLength`; the next
// update() call will recompute sunDirection from that sim time.
const dayLengthSeconds = 600; // matches all 4 todCycle dayLengthSeconds entries
await page.evaluate(
({ simSeconds, tgt }: { simSeconds: number; tgt: { x: number; y: number; z: number } }) => {
const engine = (window as { __engine?: { systemManager?: { atmosphereSystem?: unknown } } }).__engine;
const atm = engine?.systemManager?.atmosphereSystem as unknown as {
simulationTimeSeconds?: number;
sunDirection?: { set: (x: number, y: number, z: number) => unknown };
};
if (!atm) return;
atm.simulationTimeSeconds = simSeconds;
// Belt-and-suspenders: also set sunDirection directly. The update() in
// forceSkyRefresh below will overwrite this with the clamped model
// direction, then forceSkyRefresh re-applies our target after the
// tick so the FINAL bake uses our direction.
if (atm.sunDirection?.set) {
atm.sunDirection.set(tgt.x, tgt.y, tgt.z);
}
},
{ simSeconds: forceTod * dayLengthSeconds, tgt: targetSunDir }
);
await forceSkyRefresh(page, targetSunDir);
return { forceTod, appliedVia: 'worldBuilder' };
}
// combat120 / any preset without a todCycle: rotate sunDirection directly.
// Build a unit vector from the preset azimuth + a TOD-keyed elevation;
// matches the math `computeSunDirectionAtTime` would have used.
await page.evaluate(
({ tgt }: { tgt: { x: number; y: number; z: number } }) => {
const engine = (window as { __engine?: { systemManager?: { atmosphereSystem?: unknown } } }).__engine;
const atm = engine?.systemManager?.atmosphereSystem as unknown as {
sunDirection?: { set: (x: number, y: number, z: number) => unknown };
};
if (!atm?.sunDirection?.set) return;
atm.sunDirection.set(tgt.x, tgt.y, tgt.z);
},
{ tgt: targetSunDir }
);
await forceSkyRefresh(page, targetSunDir);
return { forceTod, appliedVia: 'directSunRotation' };
}
/**
* Approximate sun elevation per absolute TOD slot. Mirrors the visual targets
* the spike memo Section 4 calls out per TOD bucket (noon ~75 deg, golden
* ~22 deg, dusk ~6 deg, twilight ~-5 deg, dawn mirror of dusk, midnight deep).
*/
function todToAbsoluteElevationRad(tod: TodLabel): number {
switch (tod) {
case 'noon': return (75 * Math.PI) / 180;
case 'golden': return (22 * Math.PI) / 180;
case 'dusk': return (6 * Math.PI) / 180;
case 'twilight': return (-5 * Math.PI) / 180;
case 'dawn': return (6 * Math.PI) / 180;
case 'midnight': return (-25 * Math.PI) / 180;
}
}
/**
* Burn down the sky-LUT refresh timer + force the bake against the target
* sun direction. Without this, the cached 2-second-old texture would smear
* the previous TOD's gradient onto the snap.
*
* AtmosphereSystem.update calls `backend.update(dt, this.sunDirection)` where
* `this.sunDirection` was JUST overwritten by `computeSunDirectionAtTime` if
* the active preset has a `todCycle`. For presets whose elevation clamp
* envelope doesn't dip past -8° (e.g. `ashau`), the night-red blend
* `sunElevation < -8°` gate never fires through the normal update path.
*
* To force the bake against our target direction:
* 1) burn the refresh timer + content-changed flag
* 2) directly call `backend.update(dt, targetSunDir)` with our chosen vector
* — bypassing AtmosphereSystem.update entirely so computeSunDirectionAtTime
* cannot clobber it.
* 3) also call `atm.applyToRenderer()` so moonLight.color is repopulated
* from the freshly-baked sunColor.
*
* Pass `targetSunDir = undefined` for the simpler ramp path (use the current
* AtmosphereSystem.sunDirection, whatever update() set it to). Pass an
* explicit target to force-bake at a direction outside the preset envelope.
*/
async function forceSkyRefresh(
page: Page,
targetSunDir?: { x: number; y: number; z: number }
): Promise<void> {
await page.evaluate(
({ tgt }: { tgt?: { x: number; y: number; z: number } }) => {
const engine = (window as { __engine?: { systemManager?: { atmosphereSystem?: unknown } } }).__engine;
const atm = engine?.systemManager?.atmosphereSystem as unknown as {
hosekBackend?: {
skyTextureRefreshTimer?: number;
skyContentChanged?: boolean;
update?: (dt: number, sunDir: { x: number; y: number; z: number }) => void;
};
update?: (dt: number) => void;
sunDirection?: { set: (x: number, y: number, z: number) => unknown; x: number; y: number; z: number };
applyToRenderer?: () => void;
getLightingSnapshot?: (out: unknown) => unknown;
lightingSnapshot?: unknown;
};
const terrain = engine?.systemManager?.terrainSystem as unknown as
| { setAtmosphereLighting?: (lighting: unknown) => void }
| undefined;
if (!atm) return;
if (atm.hosekBackend) {
atm.hosekBackend.skyTextureRefreshTimer = 9999;
atm.hosekBackend.skyContentChanged = true;
}
if (typeof atm.update === 'function') {
atm.update(0.016);
atm.update(3.0);
}
// Force the bake against the target direction AFTER updates. This
// bypasses computeSunDirectionAtTime's clamp envelope so deep-night
// captures fire the night-red blend regardless of preset bounds.
if (tgt && atm.hosekBackend?.update && atm.sunDirection?.set) {
atm.sunDirection.set(tgt.x, tgt.y, tgt.z);
atm.hosekBackend.skyTextureRefreshTimer = 9999;
atm.hosekBackend.skyContentChanged = true;
atm.hosekBackend.update(3.0, tgt);
// Push the newly-baked sunColor onto moonLight.color etc.
if (typeof atm.applyToRenderer === 'function') {
atm.applyToRenderer();
}
}
if (atm.getLightingSnapshot && atm.lightingSnapshot && terrain?.setAtmosphereLighting) {
const lighting = atm.getLightingSnapshot(atm.lightingSnapshot);
terrain.setAtmosphereLighting(lighting);
}
},
{ tgt: targetSunDir }
);
}
// ----- Pose + render -----
/**
* Camera pose pointing toward the sun azimuth + just above horizon so the
* dome dominates the frame. Mirrors `capture-hosek-wilkie-shots.poseTowardSun`.
*/
function poseTowardSun(azimuthRad: number, height: number, pitchDeg: number): Pose {
const sx = Math.cos(azimuthRad);
const sz = Math.sin(azimuthRad);
const yawRad = Math.atan2(sx, -sz);
return {
position: [0, height, 0],
yawDeg: (yawRad * 180) / Math.PI,
pitchDeg,
};
}
/**
* Build the sky-dominant sun pose using terrain-relative height. A Shau's DEM
* can sit hundreds of metres above world zero, so a fixed world-Y capture can
* end up below terrain and produce misleading sun/lighting evidence.
*/
async function buildSunPose(page: Page, preset: ScenarioPreset, pitchDeg: number): Promise<Pose> {
const basePose = poseTowardSun(preset.sunAzimuthRad, preset.cameraHeight, pitchDeg);
let sample: {
terrainY: number | null;
sunDirection: [number, number, number] | null;
} | null = null;
try {
sample = await page.evaluate(() => {
const engine = (window as { __engine?: { systemManager?: { atmosphereSystem?: unknown; terrainSystem?: unknown } } }).__engine;
const terrain = engine?.systemManager?.terrainSystem as
| { getHeightAt?: (x: number, z: number) => number }
| undefined;
const atmosphere = engine?.systemManager?.atmosphereSystem as
| { sunDirection?: { x: number; y: number; z: number } }
| undefined;
const y = terrain?.getHeightAt?.(0, 0);
const sun = atmosphere?.sunDirection;
return {
terrainY: Number.isFinite(y) ? Number(y) : null,
sunDirection: sun
&& Number.isFinite(sun.x)
&& Number.isFinite(sun.y)
&& Number.isFinite(sun.z)
? [Number(sun.x), Number(sun.y), Number(sun.z)] as [number, number, number]
: null,
};
});
} catch {
sample = null;
}
if (sample?.terrainY === null || sample === null) {
return basePose;
}
const position = [
basePose.position[0],
sample.terrainY + preset.cameraHeight,
basePose.position[2],
] as [number, number, number];
const sun = sample.sunDirection;
if (sun) {
const len = Math.hypot(sun[0], sun[1], sun[2]) || 1;
const target = [
position[0] + (sun[0] / len) * 1000,
position[1] + (sun[1] / len) * 1000,
position[2] + (sun[2] / len) * 1000,
] as [number, number, number];
return {
...basePose,
position,
lookAt: target,
};
}
return {
...basePose,
position,
};
}
/**
* Build a terrain-dominant "sun behind ridge" pose. The camera sits on the
* anti-sun side of the strongest sampled rise, then looks along the horizontal
* sun vector at the ridge. This shot class is what exposes hill/ridge light
* bleed; sky-dominant sun shots cannot prove that failure mode.
*/
async function buildRidgeOcclusionPose(page: Page, preset: ScenarioPreset): Promise<{
pose: Pose;
diagnostics: RidgeOcclusionDiagnostics;
}> {
const fallbackSunHorizontal: [number, number] = [
Math.cos(preset.sunAzimuthRad),
Math.sin(preset.sunAzimuthRad),
];
return await page.evaluate(
({ fallback, scenarioKey }: { fallback: [number, number]; scenarioKey: ScenarioKey }) => {
const engine = (window as { __engine?: { systemManager?: { atmosphereSystem?: unknown; terrainSystem?: unknown } } }).__engine;
const terrain = engine?.systemManager?.terrainSystem as
| {
getHeightAt?: (x: number, z: number) => number;
getSlopeAt?: (x: number, z: number) => number;
}
| undefined;
const atmosphere = engine?.systemManager?.atmosphereSystem as
| { sunDirection?: { x: number; y: number; z: number } }
| undefined;
if (!terrain?.getHeightAt) {
const target: [number, number, number] = [0, 0, 0];
return {
pose: {
position: [-fallback[0] * 180, 34, -fallback[1] * 180] as [number, number, number],
yawDeg: (Math.atan2(fallback[0], -fallback[1]) * 180) / Math.PI,
pitchDeg: -4,
lookAt: target,
},
diagnostics: {
target,
cameraGround: [-fallback[0] * 180, 0, -fallback[1] * 180] as [number, number, number],
sunHorizontal: fallback,
ridgeRiseMeters: 0,
score: 0,
samplesChecked: 0,
},
};
}
let sx = atmosphere?.sunDirection?.x ?? fallback[0];
let sy = atmosphere?.sunDirection?.y ?? 0.1;
let sz = atmosphere?.sunDirection?.z ?? fallback[1];
const sunLen3d = Math.hypot(sx, sy, sz);
if (sunLen3d > 0.001) {
sx /= sunLen3d;
sy /= sunLen3d;
sz /= sunLen3d;
} else {
sx = fallback[0];
sy = 0.1;
sz = fallback[1];
}
const sunHorizontalLen = Math.hypot(sx, sz) || 1;
const hx = sx / sunHorizontalLen;
const hz = sz / sunHorizontalLen;
const isAshaU = scenarioKey === 'ashau';
const extent = isAshaU ? 1800 : 720;
const step = isAshaU ? 150 : 60;
const distances = isAshaU ? [180, 300, 480, 660] : [90, 150, 240, 330];
let samplesChecked = 0;
let best = {
x: 0,
z: 0,
y: terrain.getHeightAt(0, 0),
cameraX: -hx * distances[0],
cameraZ: -hz * distances[0],
cameraGroundY: terrain.getHeightAt(-hx * distances[0], -hz * distances[0]),
rise: 0,
score: Number.NEGATIVE_INFINITY,
};
for (let x = -extent; x <= extent; x += step) {
for (let z = -extent; z <= extent; z += step) {
const y = terrain.getHeightAt(x, z);
if (!Number.isFinite(y)) continue;
for (const distance of distances) {
samplesChecked++;
const cameraX = x - hx * distance;
const cameraZ = z - hz * distance;
const cameraGroundY = terrain.getHeightAt(cameraX, cameraZ);
if (!Number.isFinite(cameraGroundY)) continue;
const rise = y - cameraGroundY;
const slope = terrain.getSlopeAt?.(x, z) ?? 0;
const score = rise * 1.8 + Math.max(0, y) * 0.04 + slope * 28 - distance * 0.015;
if (score > best.score && rise > (isAshaU ? 20 : 5)) {
best = { x, z, y, cameraX, cameraZ, cameraGroundY, rise, score };
}
}
}
}
if (!Number.isFinite(best.score)) {
const y = terrain.getHeightAt(0, 0);
const distance = distances[0];
best = {
x: 0,
z: 0,
y,
cameraX: -hx * distance,
cameraZ: -hz * distance,
cameraGroundY: terrain.getHeightAt(-hx * distance, -hz * distance),
rise: 0,
score: 0,
};
}
const cameraClearance = 18;
const cameraY = best.cameraGroundY + cameraClearance;
const target: [number, number, number] = [
best.cameraX + sx * 1000,
cameraY + sy * 1000,
best.cameraZ + sz * 1000,
];
const cameraGround: [number, number, number] = [best.cameraX, best.cameraGroundY, best.cameraZ];
const yawDeg = (Math.atan2(sx, -sz) * 180) / Math.PI;
const pose: Pose = {
position: [best.cameraX, cameraY, best.cameraZ],
yawDeg,
pitchDeg: -5,
lookAt: target,
};
return {
pose,
diagnostics: {
target,
cameraGround,
sunHorizontal: [sx, sz] as [number, number],
ridgeRiseMeters: best.rise,
score: best.score,
samplesChecked,
},
};
},
{ fallback: fallbackSunHorizontal, scenarioKey: preset.key }
);
}
async function poseAndRender(page: Page, pose: Pose): Promise<void> {
await page.evaluate(
({ p, vp }: { p: Pose; vp: { width: number; height: number } }) => {
const engine = (window as { __engine?: unknown }).__engine as unknown as {
isLoopRunning?: boolean;
animationFrameId?: number | null;
renderer?: {
camera?: {
position: { x: number; y: number; z: number; set: (x: number, y: number, z: number) => unknown };
rotation: { order: string; set: (x: number, y: number, z: number) => unknown };
lookAt?: (x: number, y: number, z: number) => unknown;
updateMatrixWorld: (force: boolean) => void;
aspect?: number;
updateProjectionMatrix?: () => void;
};
renderer?: {
setSize: (w: number, h: number, updateStyle?: boolean) => void;
render: (scene: unknown, camera: unknown) => void;
shadowMap?: { needsUpdate?: boolean };
};
scene?: unknown;
setOverrideCamera?: (camera: unknown | null) => void;
postProcessing?: { setSize?: (w: number, h: number) => void; beginFrame?: () => void; endFrame?: () => void };
};
systemManager?: {
atmosphereSystem?: {
syncDomePosition?: (pos: unknown) => void;
setTerrainYAtCamera?: (height: number) => void;
applyToRenderer?: () => void;
getLightingSnapshot?: (out: unknown) => unknown;
lightingSnapshot?: unknown;
};
skybox?: { updatePosition?: (pos: unknown) => void };
waterSystem?: { update?: (dt: number) => void };
terrainSystem?: {
getHeightAt?: (x: number, z: number) => number;
updatePlayerPosition?: (position: { x: number; y: number; z: number }) => void;
update?: (dt: number) => void;
setAtmosphereLighting?: (lighting: unknown) => void;
setRenderCameraOverride?: (camera: unknown | null) => void;
};
};
};
const renderer = engine?.renderer;
const camera = renderer?.camera;
const threeRenderer = renderer?.renderer;
const scene = renderer?.scene;
const pp = renderer?.postProcessing;
if (!engine || !camera || !threeRenderer || !scene) {
throw new Error('engine/camera/renderer/scene unavailable');
}
// Stop the engine RAF so per-frame systems do not overwrite our pose.
engine.isLoopRunning = false;
if (engine.animationFrameId !== null && engine.animationFrameId !== undefined) {
cancelAnimationFrame(engine.animationFrameId);
engine.animationFrameId = null;
}
threeRenderer.setSize(vp.width, vp.height, true);
if (pp && typeof pp.setSize === 'function') pp.setSize(vp.width, vp.height);
if (typeof camera.aspect === 'number') {
camera.aspect = vp.width / vp.height;
camera.updateProjectionMatrix?.();
}
camera.position.set(p.position[0], p.position[1], p.position[2]);
const yawRad = (p.yawDeg * Math.PI) / 180;
const pitchRad = (p.pitchDeg * Math.PI) / 180;
camera.rotation.order = 'YXZ';
if (p.lookAt && typeof camera.lookAt === 'function') {
camera.rotation.set(0, yawRad, 0);
camera.lookAt(p.lookAt[0], p.lookAt[1], p.lookAt[2]);
} else {
camera.rotation.set(pitchRad, yawRad, 0);
}
camera.updateMatrixWorld(true);
const terrain = engine.systemManager?.terrainSystem;
const cameraGroundY = terrain?.getHeightAt?.(p.position[0], p.position[2]);
terrain?.updatePlayerPosition?.({
x: p.position[0],
y: Number.isFinite(cameraGroundY) ? Number(cameraGroundY) : p.position[1],
z: p.position[2],
});
renderer.setOverrideCamera?.(camera);
terrain?.setRenderCameraOverride?.(camera);
for (let i = 0; i < 10; i++) {
terrain?.update?.(1 / 30);
}
// Glue both the legacy Skybox (if still mounted) and the analytic
// dome to the new camera position.
const skybox = engine.systemManager?.skybox;
if (skybox?.updatePosition) skybox.updatePosition(camera.position);
const atm = engine.systemManager?.atmosphereSystem;
if (atm?.syncDomePosition) atm.syncDomePosition(camera.position);
if (atm?.setTerrainYAtCamera && Number.isFinite(cameraGroundY)) atm.setTerrainYAtCamera(Number(cameraGroundY));
atm?.applyToRenderer?.();
if (atm?.getLightingSnapshot && atm.lightingSnapshot && terrain?.setAtmosphereLighting) {
const lighting = atm.getLightingSnapshot(atm.lightingSnapshot);
terrain.setAtmosphereLighting(lighting);
}
engine.systemManager?.waterSystem?.update?.(0.016);
if (threeRenderer.shadowMap) threeRenderer.shadowMap.needsUpdate = true;
for (let i = 0; i < 2; i++) {
pp?.beginFrame?.();
threeRenderer.render(scene, camera);
pp?.endFrame?.();
}
},
{ p: pose, vp: VIEWPORT }
);
}
async function sampleSunOcclusion(page: Page): Promise<SunOcclusionDiagnostics> {
try {
return await page.evaluate(() => {
const engine = (window as { __engine?: unknown }).__engine as
| {
renderer?: {
camera?: {
position?: {
x: number;
y: number;
z: number;
clone?: () => unknown;
};
};
};
systemManager?: {
atmosphereSystem?: {
sunDirection?: {
x: number;
y: number;
z: number;
clone?: () => unknown;
};
};
terrainSystem?: {
getHeightAt?: (x: number, z: number) => number;
raycastTerrain?: (origin: unknown, direction: unknown, maxDistance: number) => { hit: boolean; distance?: number };
};
};
}
| undefined;
const cameraPosition = engine?.renderer?.camera?.position;
const sun = engine?.systemManager?.atmosphereSystem?.sunDirection;
const terrain = engine?.systemManager?.terrainSystem;
if (!cameraPosition || !sun || !terrain?.getHeightAt) {
return {
terrainOccluded: false,
terrainHitDistance: null,
terrainClearanceAtCamera: null,
samplesChecked: 0,
cameraPosition: cameraPosition
? [Number(cameraPosition.x), Number(cameraPosition.y), Number(cameraPosition.z)] as [number, number, number]
: null,
sunDirection: sun
? [Number(sun.x), Number(sun.y), Number(sun.z)] as [number, number, number]
: null,
reason: 'camera, sunDirection, or terrain height unavailable',
};
}
const cx = Number(cameraPosition.x);
const cy = Number(cameraPosition.y);
const cz = Number(cameraPosition.z);
let sx = Number(sun.x);
let sy = Number(sun.y);
let sz = Number(sun.z);
const len = Math.hypot(sx, sy, sz);
if (!Number.isFinite(cx) || !Number.isFinite(cy) || !Number.isFinite(cz) || !Number.isFinite(len) || len < 1e-4) {
return {
terrainOccluded: false,
terrainHitDistance: null,
terrainClearanceAtCamera: null,
samplesChecked: 0,
cameraPosition: [cx, cy, cz] as [number, number, number],
sunDirection: [sx, sy, sz] as [number, number, number],
reason: 'invalid camera or sun vector',
};
}
sx /= len;
sy /= len;
sz /= len;
const terrainAtCamera = terrain.getHeightAt(cx, cz);
const terrainClearanceAtCamera = Number.isFinite(terrainAtCamera)
? cy - Number(terrainAtCamera)
: null;
const maxDistance = 1500;
if (terrain.raycastTerrain && typeof cameraPosition.clone === 'function' && typeof sun.clone === 'function') {
try {
const origin = cameraPosition.clone();