-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasset-crop-probe.ts
More file actions
2058 lines (1973 loc) · 80.6 KB
/
Copy pathasset-crop-probe.ts
File metadata and controls
2058 lines (1973 loc) · 80.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
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { chromium, type Browser, type Page } from 'playwright';
import sharp from 'sharp';
import { startServer, stopServer, type ServerHandle } from './preview-server';
type ProbeStatus = 'pass' | 'warn' | 'fail';
type CropSurface = 'vegetation' | 'npc';
type CandidateSurface = CropSurface | 'npc_close_glb';
type MaterializationProfileSource = 'window.npcMaterializationProfile' | 'renderer-private-fallback';
interface ImageMetrics {
width: number;
height: number;
lumaMean: number;
lumaStdDev: number;
saturationMean: number;
overexposedRatio: number;
greenDominanceRatio: number;
alphaCoverage: number;
}
interface CandidateInfo {
surface: CandidateSurface;
category: string;
combatantId?: string | null;
selectionReason?: string | null;
materialName: string;
materialType: string;
objectName: string;
instanceIndex: number | null;
worldPosition: { x: number; y: number; z: number };
approximateRadius: number;
worldBounds?: {
min: { x: number; y: number; z: number };
max: { x: number; y: number; z: number };
} | null;
}
interface CropResult {
surface: CropSurface;
status: ProbeStatus;
candidate: CandidateInfo | null;
screenshot: string | null;
crop: string | null;
cropRect: { x: number; y: number; width: number; height: number } | null;
metrics: ImageMetrics | null;
findings: string[];
}
interface CloseGlbNpcRow {
id: string;
distance: number;
faction: string;
lod: string;
renderMode: 'close-glb' | 'impostor' | 'culled';
clip: string | null;
hasWeapon: boolean;
closeFallbackReason: string | null;
// Slice 4 (MaterializationProfile v2): exposed via window.npcMaterializationProfile().
reason: string | null;
inActiveCombat: boolean;
}
interface CloseModelRuntimeStats {
closeRadiusMeters?: number;
closeModelActiveCap?: number;
candidatesWithinCloseRadius?: number;
renderedCloseModels?: number;
activeCloseModels?: number;
fallbackCount?: number;
fallbackCounts?: Record<string, number>;
nearestFallbackDistanceMeters?: number | null;
farthestFallbackDistanceMeters?: number | null;
poolLoads?: number;
poolTargets?: Record<string, number>;
poolAvailable?: Record<string, number>;
[key: string]: unknown;
}
interface CloseGlbTelemetry {
lazyLoadAllowed: boolean;
combatantCount: number;
materializationProfileSource: MaterializationProfileSource;
activeCloseModelCount: number;
closeModelPoolLoads: number;
closeModelPoolTargets: Record<string, number>;
closeModelPoolAvailable: Record<string, number>;
closeModelRuntimeStats: CloseModelRuntimeStats | null;
closeModelFallbacks: unknown[];
nearest: CloseGlbNpcRow[];
}
interface CloseGlbReviewPose {
attempted: boolean;
reason: string | null;
targetCombatantId: string | null;
targetFaction: string | null;
targetPosition: { x: number; y: number; z: number } | null;
playerPosition: { x: number; y: number; z: number } | null;
distanceMeters: number | null;
}
interface DirectedZoneWarp {
attempted: boolean;
reason: string | null;
modeName: string | null;
zoneId: string | null;
zoneName: string | null;
zonePosition: { x: number; y: number; z: number } | null;
warpedPlayerPosition: { x: number; y: number; z: number } | null;
liveCombatantsBefore: number;
liveCombatantsAfter: number;
combatantsWithinCloseRadiusAfter: number;
waitMsObserved: number;
}
interface TierEventCapture {
// Slice 8: empirical tier-transition flow captured during the probe.
// `available` reflects whether `__materializationTierEvents` is exposed
// (requires `?diag=1` and diag slice-6 bus subscription).
available: boolean;
totalEvents: number;
byTransition: Record<string, number>;
byReason: Record<string, number>;
inActiveCombatPromotions: number;
firstObservationToCloseGlb: number;
sample: Array<{
combatantId: string;
fromRender: string | null;
toRender: string;
reason: string;
distanceMeters: number;
}>;
}
interface SystemTimingSample {
name: string;
emaMs: number;
budgetMs: number;
}
interface PerfTelemetrySystemTiming {
// Slice 11: per-system breakdown from `window.perf.report().systemBreakdown`.
// This is the PerformanceTelemetry-side timing list which includes nested
// sub-systems like `World.Atmosphere.SkyTexture`, `World.Atmosphere.Clouds`,
// and `World.Atmosphere.LightFog` that the SystemUpdater-level
// `getSystemTimings()` rollup does not expose. Used to split the dominant
// `World.Atmosphere` cost into its actual sub-paths.
name: string;
emaMs: number;
lastMs: number;
peakMs: number;
budgetMs: number;
}
interface SkyRefreshDiagnostic {
// Slice 14: real refresh-loop activity captured during the perf
// window. If `fireCount` is small or `totalMs` is near zero while
// the World.Atmosphere.SkyTexture EMA reports ~5 ms, the EMA is
// measurement-artifactual (singleton state leak, HMR cache, or
// instrumentation-chain bug) and slice 14 (TSL port) is the only
// way to eliminate the timing.
available: boolean;
fireCount: number;
totalMs: number;
lastMs: number;
avgMs: number;
}
interface MaterializationPerfWindow {
// Slice 9: falsifiable perf bar for the materialization review pose.
// The probe drains `window.__metrics` (300-sample ring), waits a fixed
// window with the steady review pose held, then reads
// `getSnapshot()`. Percentiles cover the captured window; activeRender*
// / candidate counts are sampled at end of window.
attempted: boolean;
reason: string | null;
durationMs: number;
frameCount: number;
avgFrameMs: number;
p95FrameMs: number;
p99FrameMs: number;
maxFrameMs: number;
hitch33Count: number;
hitch50Count: number;
hitch100Count: number;
combatantCount: number;
firingCount: number;
engagingCount: number;
activeCloseModels: number;
candidatesWithinCloseRadius: number;
fallbackCount: number;
// Slice 10: per-system EMA timings captured at end of window via
// `engine.systemManager.getSystemTimings()`. Sorted descending so the
// first entries are the largest CPU contributors. Empty array when
// the accessor is unavailable.
systemTimings: SystemTimingSample[];
systemTimingsTotalMs: number;
// Slice 11: per-system breakdown from `window.perf.report().systemBreakdown`,
// which includes sub-system timings (e.g. `World.Atmosphere.SkyTexture`).
// Used to split the dominant `World.Atmosphere` cost into its actual
// sub-paths. Empty array when `window.perf` is unavailable.
perfTelemetryTimings: PerfTelemetrySystemTiming[];
atmosphereSubTimings: PerfTelemetrySystemTiming[];
// combat-sub-attribution: per-step breakdown of the Combat
// bucket (Combat.Influence, Combat.AI, Combat.Billboards, Combat.Effects)
// captured via the same `systemBreakdown` rollup. Used to size R2's
// cover-spatial-grid against the AI sub-step rather than the Combat
// aggregate. Empty array when `window.perf` is unavailable.
combatSubTimings: PerfTelemetrySystemTiming[];
// Slice 14: real refresh-loop activity (counter + total ms in body)
// captured over the same window the EMA is taken from. Distinguishes
// genuine refresh cost from phantom EMA.
skyRefresh: SkyRefreshDiagnostic;
}
interface CloseGlbComparison {
visibleNpcCloseGlbCount: number;
status: ProbeStatus;
finding: string;
cropIsolation: string[];
initialTelemetry: CloseGlbTelemetry;
startupPrewarmMarks: { name: string; sinceStartMs: number }[];
tierEvents: TierEventCapture | null;
directedZoneWarp: DirectedZoneWarp | null;
reviewPose: CloseGlbReviewPose | null;
perfWindow: MaterializationPerfWindow | null;
telemetry: CloseGlbTelemetry;
candidate: CandidateInfo | null;
screenshot: string | null;
crop: string | null;
cropRect: { x: number; y: number; width: number; height: number } | null;
metrics: ImageMetrics | null;
}
interface ModeCropResult {
mode: string;
status: ProbeStatus;
url: string;
resolvedBackend: string | null;
strictWebGPUReady: boolean;
startupTerrainFeatureCompileMarks: { name: string; sinceStartMs: number }[];
crops: CropResult[];
closeGlbComparison: CloseGlbComparison;
consoleErrors: string[];
pageErrors: string[];
requestFailures: string[];
}
interface CropProbeReport {
createdAt: string;
sourceGitSha: string;
sourceGitStatus: string[];
mode: 'asset-crop-probe';
status: ProbeStatus;
options: {
modes: string[];
renderer: string;
headed: boolean;
port: number;
closeModelWaitMs: number;
};
output: {
json: string;
markdown: string;
};
results: ModeCropResult[];
nonClaims: string[];
}
const HOST = '127.0.0.1';
const DEFAULT_PORT = 9271;
const ARTIFACT_ROOT = join(process.cwd(), 'artifacts', 'perf');
const OUTPUT_NAME = 'asset-crop-probe';
const VIEWPORT = { width: 1440, height: 900 };
const CLOSE_MODEL_LAZY_LOAD_FLAG = '__TIJ_ALLOW_NPC_CLOSE_MODEL_LAZY_LOAD__';
const MODE_ALIASES: Record<string, string> = {
combat120: 'ai_sandbox',
tdm: 'team_deathmatch',
};
const RUNTIME_MODE_BY_PROBE_MODE: Record<string, string> = {
team_deathmatch: 'tdm',
};
function nowSlug(): string {
return new Date().toISOString().replace(/[:.]/g, '-');
}
function gitSha(): string {
try {
return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: process.cwd(), encoding: 'utf8' }).trim();
} catch {
return 'unknown';
}
}
function gitStatus(): string[] {
try {
return execFileSync('git', ['status', '--short'], { cwd: process.cwd(), encoding: 'utf8' })
.split(/\r?\n/)
.map(line => line.trimEnd())
.filter(Boolean);
} catch {
return ['unknown'];
}
}
function parseStringFlag(name: string, fallback: string): string {
const eqArg = process.argv.find(arg => arg.startsWith(`--${name}=`));
if (eqArg) return String(eqArg.split('=')[1] ?? fallback);
const idx = process.argv.indexOf(`--${name}`);
if (idx >= 0 && idx + 1 < process.argv.length) return process.argv[idx + 1];
return fallback;
}
function parseNumberFlag(name: string, fallback: number): number {
const parsed = Number(parseStringFlag(name, String(fallback)));
return Number.isFinite(parsed) ? parsed : fallback;
}
function hasFlag(name: string): boolean {
return process.argv.includes(`--${name}`);
}
function normalizeModes(raw: string): string[] {
return raw
.split(',')
.map(mode => mode.trim())
.filter(Boolean)
.map(mode => MODE_ALIASES[mode] ?? mode)
.filter((mode, index, all) => all.indexOf(mode) === index);
}
function runtimeModeForProbeMode(mode: string): string {
return RUNTIME_MODE_BY_PROBE_MODE[mode] ?? mode;
}
async function imageMetrics(path: string): Promise<ImageMetrics> {
const image = sharp(path).ensureAlpha();
const metadata = await image.metadata();
const { data, info } = await image.raw().toBuffer({ resolveWithObject: true });
let lumaSum = 0;
let lumaSqSum = 0;
let saturationSum = 0;
let overexposed = 0;
let greenDominant = 0;
let alphaCovered = 0;
const pixels = Math.max(1, info.width * info.height);
for (let i = 0; i < data.length; i += info.channels) {
const r = data[i] / 255;
const g = data[i + 1] / 255;
const b = data[i + 2] / 255;
const a = data[i + 3] / 255;
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
lumaSum += luma;
lumaSqSum += luma * luma;
saturationSum += max > 1e-6 ? (max - min) / max : 0;
if (luma > 0.92) overexposed++;
if (g > r * 1.08 && g > b * 1.08) greenDominant++;
if (a > 0.05) alphaCovered++;
}
const mean = lumaSum / pixels;
const variance = Math.max(0, lumaSqSum / pixels - mean * mean);
return {
width: metadata.width ?? info.width,
height: metadata.height ?? info.height,
lumaMean: mean,
lumaStdDev: Math.sqrt(variance),
saturationMean: saturationSum / pixels,
overexposedRatio: overexposed / pixels,
greenDominanceRatio: greenDominant / pixels,
alphaCoverage: alphaCovered / pixels,
};
}
async function startMode(page: Page, mode: string): Promise<void> {
await page.waitForFunction(() => Boolean((window as any).__engine?.startGameWithMode), null, { timeout: 90_000 });
await page.evaluate(async (modeName: string) => {
const engine = (window as any).__engine;
await engine.startGameWithMode(modeName);
}, mode);
await page.waitForFunction(() => Boolean((window as any).__engine?.gameStarted), null, { timeout: 90_000 });
}
async function getCapabilities(page: Page): Promise<{ resolvedBackend: string | null; strictWebGPUReady: boolean }> {
return page.evaluate(() => {
const capabilities = (window as any).__rendererBackendCapabilities?.() ?? null;
const resolvedBackend = capabilities?.resolvedBackend ?? null;
return {
resolvedBackend,
strictWebGPUReady: resolvedBackend === 'webgpu' && capabilities?.initStatus === 'ready',
};
});
}
async function selectCandidate(page: Page, surface: CropSurface): Promise<CandidateInfo | null> {
return page.evaluate((targetSurface: CropSurface) => {
const renderer = (window as any).__renderer;
const engine = (window as any).__engine;
const scene = renderer?.scene ?? engine?.renderer?.scene;
const camera = renderer?.camera ?? engine?.renderer?.camera;
if (!scene?.traverse || !camera?.position || !camera?.matrixWorld) return null;
const Matrix4 = camera.matrixWorld.constructor;
const Vector3 = camera.position.constructor;
const Quaternion = camera.quaternion?.constructor;
if (!Matrix4 || !Vector3 || !Quaternion) return null;
const materialArray = (material: any) => Array.isArray(material)
? material
: material
? [material]
: [];
const surfaceFor = (material: any): CropSurface | null => {
const uniforms = material?.uniforms ?? {};
if (Object.prototype.hasOwnProperty.call(uniforms, 'vegetationExposure')) return 'vegetation';
if (Object.prototype.hasOwnProperty.call(uniforms, 'npcExposure')) return 'npc';
return null;
};
const categoryFor = (object: any, material: any): string => {
let current = object;
while (current) {
const category = current.userData?.perfCategory;
if (typeof category === 'string' && category.length > 0) return category;
current = current.parent;
}
const uniforms = material?.uniforms ?? {};
if (Object.prototype.hasOwnProperty.call(uniforms, 'vegetationExposure')) return 'vegetation_imposters';
if (Object.prototype.hasOwnProperty.call(uniforms, 'npcExposure')) return 'npc_imposters';
return 'unattributed';
};
const toPoint = (v: any) => ({ x: Number(v.x), y: Number(v.y), z: Number(v.z) });
const candidates: CandidateInfo[] = [];
const matrix = new Matrix4();
const position = new Vector3();
const scale = new Vector3();
const quaternion = new Quaternion();
scene.traverse((object: any) => {
if (!object?.isMesh || object.visible === false) return;
for (const material of materialArray(object.material)) {
const surface = surfaceFor(material);
if (surface !== targetSurface) continue;
if (object.isInstancedMesh && typeof object.getMatrixAt === 'function') {
const count = Math.min(Number(object.count ?? 0), 128);
for (let i = 0; i < count; i++) {
object.getMatrixAt(i, matrix);
matrix.premultiply(object.matrixWorld);
matrix.decompose(position, quaternion, scale);
if (!Number.isFinite(position.x) || !Number.isFinite(position.y) || !Number.isFinite(position.z)) continue;
candidates.push({
surface,
category: categoryFor(object, material),
materialName: String(material.name ?? '(unnamed)'),
materialType: String(material.type ?? '(unknown)'),
objectName: String(object.name ?? '(unnamed)'),
instanceIndex: i,
worldPosition: toPoint(position),
approximateRadius: Math.max(2, scale.length() * 1.5),
});
}
} else {
const geometry = object.geometry;
const instancePosition = geometry?.attributes?.instancePosition;
const instanceScale = geometry?.attributes?.instanceScale;
if (instancePosition && targetSurface === 'vegetation') {
const count = Math.min(Number(geometry.instanceCount ?? instancePosition.count ?? 0), 256);
for (let i = 0; i < count; i++) {
const x = Number(instancePosition.getX(i));
const y = Number(instancePosition.getY(i));
const z = Number(instancePosition.getZ(i));
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue;
const sx = Number(instanceScale?.getX?.(i) ?? 4);
const sy = Number(instanceScale?.getY?.(i) ?? 4);
candidates.push({
surface,
category: categoryFor(object, material),
materialName: String(material.name ?? '(unnamed)'),
materialType: String(material.type ?? '(unknown)'),
objectName: String(object.name ?? '(unnamed)'),
instanceIndex: i,
worldPosition: { x, y, z },
approximateRadius: Math.max(3, Math.max(Math.abs(sx), Math.abs(sy)) * 3),
});
}
} else {
object.getWorldPosition(position);
candidates.push({
surface,
category: categoryFor(object, material),
materialName: String(material.name ?? '(unnamed)'),
materialType: String(material.type ?? '(unknown)'),
objectName: String(object.name ?? '(unnamed)'),
instanceIndex: null,
worldPosition: toPoint(position),
approximateRadius: 4,
});
}
}
}
});
const cameraPos = camera.position ?? { x: 0, y: 0, z: 0 };
candidates.sort((a, b) => {
const da = Math.hypot(a.worldPosition.x - cameraPos.x, a.worldPosition.z - cameraPos.z);
const db = Math.hypot(b.worldPosition.x - cameraPos.x, b.worldPosition.z - cameraPos.z);
return da - db;
});
return candidates[0] ?? null;
}, surface);
}
async function frameCandidate(page: Page, candidate: CandidateInfo): Promise<{ x: number; y: number; width: number; height: number } | null> {
return page.evaluate((target: CandidateInfo) => {
const engine = (window as any).__engine;
const rendererHost = engine?.renderer ?? (window as any).__renderer;
const camera = rendererHost?.camera ?? (window as any).__renderer?.camera;
const terrain = engine?.systemManager?.terrainSystem;
const atmosphere = engine?.systemManager?.atmosphereSystem;
if (!camera?.clone || !camera?.position || !camera?.matrixWorld) return null;
const Vector3 = camera.position.constructor;
const targetPos = new Vector3(target.worldPosition.x, target.worldPosition.y, target.worldPosition.z);
const radius = Math.max(2, Number(target.approximateRadius ?? 4));
const offset = new Vector3(radius * 3.5, Math.max(4, radius * 1.4), radius * 5.5);
const override = camera.clone();
override.near = 0.1;
override.far = Math.max(3000, camera.far ?? 3000);
override.aspect = 1440 / 900;
override.position.copy(targetPos).add(offset);
override.lookAt(targetPos.x, targetPos.y + radius * 0.4, targetPos.z);
override.updateProjectionMatrix?.();
override.updateMatrixWorld?.(true);
rendererHost?.setOverrideCamera?.(override);
terrain?.setRenderCameraOverride?.(override);
terrain?.updatePlayerPosition?.(override.position);
terrain?.update?.(0.016);
atmosphere?.setTerrainYAtCamera?.(Number(terrain?.getHeightAt?.(override.position.x, override.position.z) ?? override.position.y));
atmosphere?.syncDomePosition?.(override.position);
const right = new Vector3();
const up = new Vector3();
override.matrixWorld.extractBasis(right, up, new Vector3());
const bounds = target.worldBounds;
const points = bounds
? [
new Vector3(bounds.min.x, bounds.min.y, bounds.min.z),
new Vector3(bounds.min.x, bounds.min.y, bounds.max.z),
new Vector3(bounds.min.x, bounds.max.y, bounds.min.z),
new Vector3(bounds.min.x, bounds.max.y, bounds.max.z),
new Vector3(bounds.max.x, bounds.min.y, bounds.min.z),
new Vector3(bounds.max.x, bounds.min.y, bounds.max.z),
new Vector3(bounds.max.x, bounds.max.y, bounds.min.z),
new Vector3(bounds.max.x, bounds.max.y, bounds.max.z),
].map(point => point.project(override))
: [
targetPos.clone().addScaledVector(right, -radius).addScaledVector(up, -radius),
targetPos.clone().addScaledVector(right, radius).addScaledVector(up, -radius),
targetPos.clone().addScaledVector(right, -radius).addScaledVector(up, radius),
targetPos.clone().addScaledVector(right, radius).addScaledVector(up, radius),
targetPos.clone(),
].map(point => point.project(override));
const xs = points.map(point => (point.x * 0.5 + 0.5) * 1440);
const ys = points.map(point => (-point.y * 0.5 + 0.5) * 900);
const minX = Math.min(...xs);
const maxX = Math.max(...xs);
const minY = Math.min(...ys);
const maxY = Math.max(...ys);
if (![minX, maxX, minY, maxY].every(Number.isFinite)) return null;
const pad = Math.max(16, Math.min(80, radius * 6));
return {
x: minX - pad,
y: minY - pad,
width: maxX - minX + pad * 2,
height: maxY - minY + pad * 2,
};
}, candidate);
}
async function clearCameraOverride(page: Page): Promise<void> {
await page.evaluate(() => {
const engine = (window as any).__engine;
const rendererHost = engine?.renderer ?? (window as any).__renderer;
const terrain = engine?.systemManager?.terrainSystem;
rendererHost?.setOverrideCamera?.(null);
terrain?.setRenderCameraOverride?.(null);
});
}
async function setVegetationVisibilityForProbe(page: Page, visible: boolean): Promise<void> {
await page.evaluate((nextVisible: boolean) => {
const renderer = (window as any).__renderer;
const engine = (window as any).__engine;
const scene = renderer?.scene ?? engine?.renderer?.scene;
if (!scene?.traverse) return;
const materialArray = (material: any) => Array.isArray(material)
? material
: material
? [material]
: [];
const isVegetationObject = (object: any): boolean => {
let current = object;
while (current) {
const category = current.userData?.perfCategory;
if (typeof category === 'string' && category.includes('vegetation')) return true;
current = current.parent;
}
return materialArray(object.material).some((material: any) => (
Object.prototype.hasOwnProperty.call(material?.uniforms ?? {}, 'vegetationExposure')
));
};
scene.traverse((object: any) => {
if (!object || !isVegetationObject(object)) return;
if (nextVisible) {
if (Object.prototype.hasOwnProperty.call(object.userData ?? {}, '__assetCropPrevVisible')) {
object.visible = Boolean(object.userData.__assetCropPrevVisible);
delete object.userData.__assetCropPrevVisible;
}
} else if (!Object.prototype.hasOwnProperty.call(object.userData ?? {}, '__assetCropPrevVisible')) {
object.userData = object.userData ?? {};
object.userData.__assetCropPrevVisible = object.visible !== false;
object.visible = false;
}
});
}, visible);
}
async function setTerrainVisibilityForProbe(page: Page, visible: boolean): Promise<void> {
await page.evaluate((nextVisible: boolean) => {
const renderer = (window as any).__renderer;
const engine = (window as any).__engine;
const scene = renderer?.scene ?? engine?.renderer?.scene;
if (!scene?.traverse) return;
const materialArray = (material: any) => Array.isArray(material)
? material
: material
? [material]
: [];
const isTerrainObject = (object: any): boolean => {
let current = object;
while (current) {
const category = String(current.userData?.perfCategory ?? '').toLowerCase();
if (category.includes('terrain')) return true;
if (String(current.name ?? '').toLowerCase().includes('terrain')) return true;
current = current.parent;
}
return materialArray(object.material).some((material: any) => (
Boolean(material?.userData?.terrainUniforms)
));
};
scene.traverse((object: any) => {
if (!object || !isTerrainObject(object)) return;
if (nextVisible) {
if (Object.prototype.hasOwnProperty.call(object.userData ?? {}, '__assetCropPrevTerrainVisible')) {
object.visible = Boolean(object.userData.__assetCropPrevTerrainVisible);
delete object.userData.__assetCropPrevTerrainVisible;
}
} else if (!Object.prototype.hasOwnProperty.call(object.userData ?? {}, '__assetCropPrevTerrainVisible')) {
object.userData = object.userData ?? {};
object.userData.__assetCropPrevTerrainVisible = object.visible !== false;
object.visible = false;
}
});
}, visible);
}
async function pauseRenderLoopForProbe(page: Page): Promise<boolean> {
return page.evaluate(() => {
const engine = (window as any).__engine;
if (!engine) return false;
const wasRunning = Boolean(engine.isLoopRunning);
engine.isLoopRunning = false;
if (engine.animationFrameId !== null && engine.animationFrameId !== undefined) {
cancelAnimationFrame(engine.animationFrameId);
engine.animationFrameId = null;
}
return wasRunning;
});
}
async function resumeRenderLoopForProbe(page: Page, wasRunning: boolean): Promise<void> {
if (!wasRunning) return;
await page.evaluate(() => {
const engine = (window as any).__engine;
engine?.start?.();
});
}
async function renderStaticProbeFrame(page: Page): Promise<void> {
await page.evaluate(() => {
const engine = (window as any).__engine;
if (typeof engine?.renderDiagnosticsFrame === 'function') {
engine.renderDiagnosticsFrame();
return;
}
const rendererHost = engine?.renderer ?? (window as any).__renderer;
const renderer = rendererHost?.renderer;
const scene = rendererHost?.scene;
const camera = rendererHost?.getActiveCamera?.() ?? rendererHost?.camera;
if (renderer?.render && scene && camera) {
renderer.render(scene, camera);
}
});
}
async function selectCloseGlbCandidate(page: Page, preferredCombatantId?: string | null): Promise<CandidateInfo | null> {
return page.evaluate((preferredId: string | null) => {
const renderer = (window as any).__renderer;
const engine = (window as any).__engine;
const combat = engine?.systemManager?.combatantSystem;
const combatantRenderer = combat?.combatantRenderer ?? combat?.getRenderer?.();
const scene = renderer?.scene ?? engine?.renderer?.scene;
const camera = renderer?.camera ?? engine?.renderer?.camera;
if (!scene?.traverse || !camera?.position) return null;
const Vector3 = camera.position.constructor;
const materialArray = (material: any) => Array.isArray(material)
? material
: material
? [material]
: [];
const modelPathFor = (object: any): string => {
let current = object;
while (current) {
const path = current.userData?.modelPath;
if (typeof path === 'string' && path.length > 0) return path.toLowerCase();
current = current.parent;
}
return '';
};
const isCloseGlb = (object: any): boolean => {
let current = object;
while (current) {
if (current.userData?.perfCategory === 'npc_close_glb') return true;
current = current.parent;
}
return modelPathFor(object).includes('npcs/pixel-forge');
};
const toPoint = (v: any) => ({ x: Number(v.x), y: Number(v.y), z: Number(v.z) });
const createBounds = (): NonNullable<CandidateInfo['worldBounds']> => ({
min: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },
max: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },
});
const expandBounds = (
bounds: NonNullable<CandidateInfo['worldBounds']>,
center: { x: number; y: number; z: number },
radius: number,
): void => {
if (![center.x, center.y, center.z, radius].every(Number.isFinite)) return;
bounds.min.x = Math.min(bounds.min.x, center.x - radius);
bounds.min.y = Math.min(bounds.min.y, center.y - radius);
bounds.min.z = Math.min(bounds.min.z, center.z - radius);
bounds.max.x = Math.max(bounds.max.x, center.x + radius);
bounds.max.y = Math.max(bounds.max.y, center.y + radius);
bounds.max.z = Math.max(bounds.max.z, center.z + radius);
};
const usableBounds = (bounds: CandidateInfo['worldBounds']): bounds is NonNullable<CandidateInfo['worldBounds']> => {
if (!bounds) return false;
return [
bounds.min.x, bounds.min.y, bounds.min.z,
bounds.max.x, bounds.max.y, bounds.max.z,
].every(Number.isFinite)
&& bounds.max.x > bounds.min.x
&& bounds.max.y > bounds.min.y
&& bounds.max.z > bounds.min.z;
};
const centerFromBounds = (bounds: NonNullable<CandidateInfo['worldBounds']>) => ({
x: (bounds.min.x + bounds.max.x) * 0.5,
y: (bounds.min.y + bounds.max.y) * 0.5,
z: (bounds.min.z + bounds.max.z) * 0.5,
});
const radiusFromBounds = (bounds: NonNullable<CandidateInfo['worldBounds']>): number => {
const dx = bounds.max.x - bounds.min.x;
const dy = bounds.max.y - bounds.min.y;
const dz = bounds.max.z - bounds.min.z;
return Math.max(2.4, Math.min(9.0, Math.hypot(dx, dy, dz) * 0.55));
};
const meshBoundsFor = (object: any): CandidateInfo['worldBounds'] => {
if (!object) return null;
object.updateMatrixWorld?.(true);
const bounds = createBounds();
const meshCenter = new Vector3();
const sphereCenter = new Vector3();
const meshScale = new Vector3();
const visit = (child: any): void => {
if (!child?.isMesh || child.visible === false || !child.geometry) return;
child.getWorldPosition?.(meshCenter);
child.getWorldScale?.(meshScale);
let sphere = child.geometry.boundingSphere;
if (!sphere && typeof child.geometry.computeBoundingSphere === 'function') {
try {
child.geometry.computeBoundingSphere();
sphere = child.geometry.boundingSphere;
} catch {
sphere = null;
}
}
let radius = 0.45;
if (sphere && Number.isFinite(Number(sphere.radius)) && Number(sphere.radius) > 0) {
sphereCenter.set(
Number(sphere.center?.x ?? 0),
Number(sphere.center?.y ?? 0),
Number(sphere.center?.z ?? 0),
);
child.localToWorld?.(sphereCenter);
meshCenter.copy?.(sphereCenter);
const scaleMax = Math.max(Math.abs(meshScale.x), Math.abs(meshScale.y), Math.abs(meshScale.z), 1);
radius = Math.max(0.25, Number(sphere.radius) * scaleMax);
}
expandBounds(bounds, meshCenter, radius);
};
if (typeof object.traverse === 'function') {
object.traverse(visit);
} else {
visit(object);
}
return usableBounds(bounds) ? bounds : null;
};
const candidates: CandidateInfo[] = [];
let preferredCandidate: CandidateInfo | null = null;
const position = new Vector3();
const addObjectCandidate = (object: any, combatantId: string | null, selectionReason: string): void => {
if (!object || object.visible === false) return;
object.getWorldPosition(position);
let radius = 2.4;
const worldBounds = meshBoundsFor(object);
if (usableBounds(worldBounds)) {
const center = centerFromBounds(worldBounds);
position.set(center.x, center.y, center.z);
radius = radiusFromBounds(worldBounds);
}
let material: any = null;
object.traverse?.((child: any) => {
if (material || !child?.isMesh) return;
material = materialArray(child.material)[0] ?? null;
});
if (!material && object.isMesh) material = materialArray(object.material)[0] ?? null;
const candidate: CandidateInfo = {
surface: 'npc_close_glb',
category: 'npc_close_glb',
combatantId,
selectionReason,
materialName: String(material?.name ?? '(unnamed)'),
materialType: String(material?.type ?? '(unknown)'),
objectName: String(object.name ?? '(unnamed)'),
instanceIndex: null,
worldPosition: toPoint(position),
approximateRadius: radius,
worldBounds,
};
candidates.push(candidate);
if (preferredId && combatantId === preferredId) {
preferredCandidate = candidate;
}
};
if (combatantRenderer?.activeCloseModels instanceof Map) {
combatantRenderer.activeCloseModels.forEach((instance: any, combatantId: unknown) => {
const id = String(combatantId);
addObjectCandidate(
instance?.root,
id,
preferredId && id === preferredId ? 'preferred-active-close-model' : 'active-close-model',
);
});
}
if (preferredCandidate) return preferredCandidate;
scene.traverse((object: any) => {
if (!object?.isMesh || object.visible === false || !isCloseGlb(object)) return;
if (candidates.length > 0) return;
object.getWorldPosition(position);
let radius = 2.4;
const worldBounds = meshBoundsFor(object);
if (usableBounds(worldBounds)) {
const center = centerFromBounds(worldBounds);
position.set(center.x, center.y, center.z);
radius = radiusFromBounds(worldBounds);
}
const materials = materialArray(object.material);
const material = materials[0] ?? null;
candidates.push({
surface: 'npc_close_glb',
category: 'npc_close_glb',
combatantId: null,
selectionReason: 'scene-close-glb-fallback',
materialName: String(material?.name ?? '(unnamed)'),
materialType: String(material?.type ?? '(unknown)'),
objectName: String(object.name ?? '(unnamed)'),
instanceIndex: null,
worldPosition: toPoint(position),
approximateRadius: Math.min(Math.max(radius, 4.5), 9),
worldBounds,
});
});
const cameraPos = camera.position ?? { x: 0, y: 0, z: 0 };
candidates.sort((a, b) => {
const da = Math.hypot(a.worldPosition.x - cameraPos.x, a.worldPosition.z - cameraPos.z);
const db = Math.hypot(b.worldPosition.x - cameraPos.x, b.worldPosition.z - cameraPos.z);
return da - db;
});
return candidates[0] ?? null;
}, preferredCombatantId ?? null);
}
async function closeGlbCount(page: Page): Promise<number> {
return page.evaluate(() => {
const renderer = (window as any).__renderer;
const engine = (window as any).__engine;
const combat = engine?.systemManager?.combatantSystem;
const combatantRenderer = combat?.combatantRenderer ?? combat?.getRenderer?.();
if (combatantRenderer?.activeCloseModels instanceof Map) {
return combatantRenderer.activeCloseModels.size;
}
const scene = renderer?.scene ?? engine?.renderer?.scene;
if (!scene?.traverse) return 0;
const modelPathFor = (object: any): string => {
let current = object;
while (current) {
const path = current.userData?.modelPath;
if (typeof path === 'string' && path.length > 0) return path.toLowerCase();
current = current.parent;
}
return '';
};
const isCloseGlb = (object: any): boolean => {
let current = object;
while (current) {
if (current.userData?.perfCategory === 'npc_close_glb') return true;
current = current.parent;
}
return modelPathFor(object).includes('npcs/pixel-forge');
};
let count = 0;
scene.traverse((object: any) => {
if (!object?.isMesh || object.visible === false) return;
if (isCloseGlb(object)) {
count++;
}
});
return count;
});
}
async function getCloseModelTelemetry(page: Page): Promise<CloseGlbTelemetry> {
return page.evaluate((lazyLoadFlag: string) => {
const engine = (window as any).__engine;
const combat = engine?.systemManager?.combatantSystem;
const renderer = combat?.combatantRenderer ?? combat?.getRenderer?.();
const playerController = engine?.systemManager?.playerController;
const camera = engine?.renderer?.camera ?? (window as any).__renderer?.camera;
const playerPosition = playerController?.getPosition?.()
?? combat?.playerPosition
?? camera?.position
?? { x: 0, y: 0, z: 0 };
let publicProfile: any = null;
try {
publicProfile = typeof (window as any).npcMaterializationProfile === 'function'
? (window as any).npcMaterializationProfile(24)
: null;
} catch {
publicProfile = null;
}
const copyNumericRecord = (value: any): Record<string, number> => {
const output: Record<string, number> = {};
if (!value || typeof value !== 'object') return output;
Object.entries(value).forEach(([key, recordValue]) => {
output[String(key)] = Number(recordValue);
});
return output;
};
const normalizeRenderMode = (value: any): CloseGlbNpcRow['renderMode'] => {
if (value === 'close-glb' || value === 'impostor' || value === 'culled') return value;
return 'culled';
};
const publicRows = Array.isArray(publicProfile?.rows)
? publicProfile.rows.map((row: any) => ({
id: String(row.combatantId ?? row.id ?? ''),
distance: Number(row.distanceMeters ?? row.distance ?? 0),
faction: String(row.faction ?? ''),
lod: String(row.lodLevel ?? row.lod ?? ''),
renderMode: normalizeRenderMode(row.renderMode),
clip: row.clipId == null ? null : String(row.clipId),
hasWeapon: Boolean(row.hasCloseModelWeapon ?? row.hasWeapon),
closeFallbackReason: row.closeFallbackReason == null ? null : String(row.closeFallbackReason),
reason: row.reason == null ? null : String(row.reason),
inActiveCombat: Boolean(row.inActiveCombat),
})).sort((a: CloseGlbNpcRow, b: CloseGlbNpcRow) => a.distance - b.distance)
: null;
const activeCloseModels = renderer?.activeCloseModels instanceof Map