-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperf-active-driver.cjs
More file actions
5258 lines (4991 loc) · 233 KB
/
Copy pathperf-active-driver.cjs
File metadata and controls
5258 lines (4991 loc) · 233 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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2025-2026 Matthew Kissinger
/**
* Performance harness driver.
*
* This script is injected into the running page by the perf-capture harness.
* It instantiates a `PlayerBot` (ground-combat state-machine bot) on each
* active scenario and ticks it against the engine's own combat/navigation
* primitives — terrain raycast for LOS, navmesh for movement, the live
* combatant list for target search. The bot never reinvents those
* primitives; it consumes them.
*
* The bot and its controller live in `src/dev/harness/playerBot/*.ts` as the
* source-of-truth implementation (with Vitest coverage). This driver is a
* pure-JS mirror of that state machine, because Vite's injected script tag
* cannot import TypeScript modules. When changing bot behavior, change the
* TypeScript source AND this file together (same discipline
* `chooseHeadingByGradient`, `pointAlongPath`, etc. have followed since
* perf-harness-redesign).
*/
(function (root) {
const globalWindow = typeof window !== 'undefined' ? window : null;
// ── Pure helpers kept for Node-side regression tests (scripts/perf-harness).
// These are the same primitives that perf-harness-redesign, perf-harness-killbot
// and perf-harness-verticality-and-sizing exercised; do not remove without
// updating scripts/perf-harness/perf-active-driver.test.js in lockstep.
function evaluateFireDecision(opts) {
const forward = opts && opts.cameraForward;
const toTarget = opts && opts.toTarget;
const aimDotThreshold = Number(opts && opts.aimDotThreshold);
const verticalThreshold = Number(opts && opts.verticalThreshold);
const closeRange = !!(opts && opts.closeRange);
const allowSteepGroundFire = !!(opts && opts.allowSteepGroundFire);
if (!forward || !toTarget) {
return { shouldFire: false, reason: 'missing_vectors', aimDot: 0, verticalComponent: 0 };
}
const fx = Number(forward.x || 0);
const fy = Number(forward.y || 0);
const fz = Number(forward.z || 0);
const tx = Number(toTarget.x || 0);
const ty = Number(toTarget.y || 0);
const tz = Number(toTarget.z || 0);
const fLen = Math.hypot(fx, fy, fz);
const tLen = Math.hypot(tx, ty, tz);
if (!Number.isFinite(fLen) || !Number.isFinite(tLen) || fLen < 1e-6 || tLen < 1e-6) {
return { shouldFire: false, reason: 'degenerate_vectors', aimDot: 0, verticalComponent: 0 };
}
const fnx = fx / fLen;
const fny = fy / fLen;
const fnz = fz / fLen;
const tnx = tx / tLen;
const tny = ty / tLen;
const tnz = tz / tLen;
const aimDot = fnx * tnx + fny * tny + fnz * tnz;
const verticalComponent = Math.abs(tny);
const upwardVerticalComponent = Math.max(0, tny);
const dotThreshold = Number.isFinite(aimDotThreshold) ? aimDotThreshold : 0.8;
const vThreshold = Number.isFinite(verticalThreshold) ? verticalThreshold : 0.45;
const steepGroundFireAllowed = allowSteepGroundFire
&& upwardVerticalComponent <= FIRE_VERTICAL_COMPONENT_THRESHOLD;
if (aimDot < dotThreshold) {
return { shouldFire: false, reason: 'aim_dot_too_low', aimDot: aimDot, verticalComponent: verticalComponent };
}
if (upwardVerticalComponent > vThreshold && !closeRange && !steepGroundFireAllowed) {
return { shouldFire: false, reason: 'vertical_angle_rejected', aimDot: aimDot, verticalComponent: verticalComponent };
}
return { shouldFire: true, reason: 'ok', aimDot: aimDot, verticalComponent: verticalComponent };
}
function chooseHeadingByGradient(opts) {
const sampleHeight = opts && opts.sampleHeight;
const from = opts && opts.from;
const bearingRad = Number(opts && opts.bearingRad);
const maxGradient = Number(opts && opts.maxGradient);
const lookAhead = Number(opts && opts.lookAhead);
if (typeof sampleHeight !== 'function' || !from || !Number.isFinite(bearingRad)) {
return null;
}
const grad = Number.isFinite(maxGradient) && maxGradient > 0 ? maxGradient : 0.45;
const la = Number.isFinite(lookAhead) && lookAhead > 0 ? lookAhead : 8;
const hHere = Number(sampleHeight(Number(from.x), Number(from.z)));
if (!Number.isFinite(hHere)) return null;
const offsets = [0, Math.PI / 4, -Math.PI / 4, Math.PI / 2, -Math.PI / 2];
let best = null;
let bestAbsGrad = Number.POSITIVE_INFINITY;
for (let i = 0; i < offsets.length; i++) {
const yaw = bearingRad + offsets[i];
const dx = Math.sin(yaw);
const dz = -Math.cos(yaw);
const bdx = Math.sin(bearingRad);
const bdz = -Math.cos(bearingRad);
const dot = dx * bdx + dz * bdz;
if (dot <= 0) continue;
const probeX = Number(from.x) + dx * la;
const probeZ = Number(from.z) + dz * la;
const hThere = Number(sampleHeight(probeX, probeZ));
if (!Number.isFinite(hThere)) continue;
const gradient = (hThere - hHere) / la;
const absGradient = Math.abs(gradient);
if (absGradient > grad) continue;
if (absGradient < bestAbsGrad) {
bestAbsGrad = absGradient;
best = { yaw: yaw, gradient: gradient, offsetRad: offsets[i] };
}
}
return best;
}
// Actor-height mirrors. PlayerController.getPosition() and combatant.position
// are already eye-level actor anchors, matching PlayerMovement.PLAYER_EYE_HEIGHT
// and CombatantConfig.NPC_Y_OFFSET. Only ground/objective points need a
// positive look height; combatant targets need a center-mass offset below
// their actor anchor.
const PLAYER_EYE_HEIGHT = 2.2;
// Mirrors the visual chest proxy center from CombatantConfig and
// CombatantBodyMetrics. Keep this formula aligned with
// src/dev/harness/playerBot/states.ts.
const NPC_PIXEL_FORGE_VISUAL_HEIGHT = 2.95 * 1.0;
const COMBATANT_HIT_PROXY_VISUAL_HEIGHT_MULTIPLIER = 1.16;
const COMBATANT_HIT_PROXY_CHEST_START_RATIO = 0.46;
const COMBATANT_HIT_PROXY_CHEST_END_RATIO = 0.72;
const COMBATANT_HIT_PROXY_CHEST_CENTER_RATIO =
(COMBATANT_HIT_PROXY_CHEST_START_RATIO + COMBATANT_HIT_PROXY_CHEST_END_RATIO) / 2;
const COMBATANT_HIT_PROXY_CHEST_RADIUS_RATIO = 0.18;
const TARGET_ACTOR_AIM_Y_OFFSET =
NPC_PIXEL_FORGE_VISUAL_HEIGHT
* COMBATANT_HIT_PROXY_VISUAL_HEIGHT_MULTIPLIER
* COMBATANT_HIT_PROXY_CHEST_CENTER_RATIO
- PLAYER_EYE_HEIGHT;
const TARGET_CHEST_HEIGHT = PLAYER_EYE_HEIGHT + TARGET_ACTOR_AIM_Y_OFFSET;
const TARGET_LOS_HEIGHT = TARGET_CHEST_HEIGHT;
const DEFAULT_BULLET_SPEED = 400;
const FIRE_VERTICAL_COMPONENT_THRESHOLD = 0.9;
function targetActorAimYOffset(scaleY) {
const scale = Number.isFinite(Number(scaleY)) ? Number(scaleY) : 1;
return NPC_PIXEL_FORGE_VISUAL_HEIGHT
* COMBATANT_HIT_PROXY_VISUAL_HEIGHT_MULTIPLIER
* scale
* COMBATANT_HIT_PROXY_CHEST_CENTER_RATIO
- PLAYER_EYE_HEIGHT;
}
function targetChestProxyRadius(scaleY) {
const scale = Number.isFinite(Number(scaleY)) ? Number(scaleY) : 1;
return NPC_PIXEL_FORGE_VISUAL_HEIGHT
* COMBATANT_HIT_PROXY_VISUAL_HEIGHT_MULTIPLIER
* scale
* COMBATANT_HIT_PROXY_CHEST_RADIUS_RATIO;
}
function computeRayAimMetrics(origin, direction, aimPoint, proxyRadius) {
if (!origin || !direction || !aimPoint) return null;
const tx = Number(aimPoint.x) - Number(origin.x);
const ty = Number(aimPoint.y) - Number(origin.y);
const tz = Number(aimPoint.z) - Number(origin.z);
const targetDistance = Math.hypot(tx, ty, tz);
const dirLen = Math.hypot(Number(direction.x), Number(direction.y), Number(direction.z));
if (!Number.isFinite(targetDistance) || targetDistance <= 1e-6 || !Number.isFinite(dirLen) || dirLen <= 1e-6) {
return null;
}
const fx = Number(direction.x) / dirLen;
const fy = Number(direction.y) / dirLen;
const fz = Number(direction.z) / dirLen;
const aimDot = (fx * tx + fy * ty + fz * tz) / targetDistance;
const clampedDot = Math.max(-1, Math.min(1, Number.isFinite(aimDot) ? aimDot : -1));
const closestDistance = Math.max(0, fx * tx + fy * ty + fz * tz);
const closestX = Number(origin.x) + fx * closestDistance;
const closestY = Number(origin.y) + fy * closestDistance;
const closestZ = Number(origin.z) + fz * closestDistance;
const missDistance = Math.hypot(
Number(aimPoint.x) - closestX,
Number(aimPoint.y) - closestY,
Number(aimPoint.z) - closestZ,
);
const radius = Number.isFinite(Number(proxyRadius)) && Number(proxyRadius) > 0
? Number(proxyRadius)
: null;
return {
aimDot: clampedDot,
aimAngleDeg: Math.acos(clampedDot) * 180 / Math.PI,
aimMissDistance: missDistance,
aimMissRadiusRatio: radius !== null ? missDistance / radius : null,
aimDistance: targetDistance,
rayDistanceToClosestAim: closestDistance,
};
}
// Player's maximum walkable slope, derived from SlopePhysics.PLAYER_CLIMB_SLOPE_DOT.
const PLAYER_CLIMB_SLOPE_DOT = 0.7;
const PLAYER_MAX_CLIMB_ANGLE_RAD = Math.acos(PLAYER_CLIMB_SLOPE_DOT);
const PLAYER_MAX_CLIMB_GRADIENT = Math.tan(PLAYER_MAX_CLIMB_ANGLE_RAD);
// Path-trust invariant (perf-harness-verticality-and-sizing).
const PATH_TRUST_TTL_MS = 5000;
const ROUTE_MICRO_TARGET_DISTANCE = 3;
const ROUTE_MICRO_TARGET_ANCHOR_DISTANCE = 12;
const ROUTE_TARGET_REPLAN_DISTANCE = 24;
const ROUTE_PROGRESS_MIN_IMPROVEMENT = 8;
const ROUTE_PROGRESS_MIN_CLOSURE_RATIO = 0.15;
const ROUTE_PROGRESS_TIMEOUT_MS = 6000;
const ROUTE_PROGRESS_MIN_TRAVEL = 60;
const ROUTE_NO_PROGRESS_TARGET_COOLDOWN_MS = 8000;
const ROUTE_FAILED_OBJECTIVE_COOLDOWN_MS = 12000;
const ROUTE_OVERLAY_WALK_RECOVERY_STUCK_MS = 600;
const RUNTIME_TERRAIN_BLOCK_TARGET_COOLDOWN_MS = 3000;
const SHOT_EPOCH_HISTORY_LIMIT = 32;
const ROUTE_SNAP_EPOCH_HISTORY_LIMIT = 32;
const FIRING_RETARGET_EPOCH_HISTORY_LIMIT = 32;
const NAVMESH_START_SNAP_RADIUS = 80;
const NAVMESH_TARGET_SNAP_RADIUS = 80;
const NAVMESH_TRUSTED_ROUTE_SNAP_DISTANCE = 24;
const COMBAT_APPROACH_MIN_HOLD_DISTANCE = 45;
const COMBAT_APPROACH_MAX_HOLD_DISTANCE = 170;
const COMBAT_APPROACH_CLOSE_STANDOFF_DISTANCE = 85;
const COMBAT_APPROACH_LATERAL_MIN = 24;
const COMBAT_APPROACH_LATERAL_MAX = 90;
// Humanized synthetic-camera slew cap. The driver used to allow 24 deg yaw /
// 8 deg pitch in one tick, which made route-to-fire handoffs look unlike a
// player mouse sweep and could perturb terrain/CDLOD presentation.
const DRIVER_VIEW_MAX_YAW_STEP_RAD = (12 * Math.PI) / 180;
const DRIVER_VIEW_MAX_PITCH_STEP_RAD = (4 * Math.PI) / 180;
function normalizeDriverSeed(raw) {
const seed = Number(raw);
if (!Number.isFinite(seed) || seed < 0) return null;
return Math.floor(seed) >>> 0;
}
function createSeededRandom(seed) {
let state = normalizeDriverSeed(seed);
if (state === null) return Math.random;
return function seededRandom() {
state = (state + 0x6D2B79F5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function isPathTrusted(opts) {
const path = opts && opts.path;
const index = Number(opts && opts.waypointIdx);
const ageMs = Number(opts && opts.pathAgeMs);
if (!Array.isArray(path) || path.length < 2) return false;
if (!Number.isFinite(index) || index < 0 || index >= path.length) return false;
if (!Number.isFinite(ageMs) || ageMs < 0) return false;
return ageMs < PATH_TRUST_TTL_MS;
}
const AIM_PITCH_LIMIT_RAD = (80 * Math.PI) / 180;
function clampAimYByPitch(playerY, desiredY, horizontalDist) {
const py = Number(playerY || 0);
const dy = Number(desiredY);
if (!Number.isFinite(dy)) return py;
const hz = Number(horizontalDist || 0);
if (!Number.isFinite(hz) || hz <= 0.01) return dy;
const vLimit = hz * Math.tan(AIM_PITCH_LIMIT_RAD);
return Math.max(py - vLimit, Math.min(py + vLimit, dy));
}
function computeUtilityScore(opts) {
const distance = Number(opts && opts.distance);
const hasLOS = !!(opts && opts.hasLOS);
const isEngagingUs = !!(opts && opts.isEngagingUs);
if (!Number.isFinite(distance) || distance < 0) return 0;
const visibility = hasLOS ? 1 : 0.3;
const threat = isEngagingUs ? 2 : 1;
return visibility * (1 / (distance + 1)) * threat;
}
function shouldSwitchTarget(currentScore, candidateScore, ratio) {
const r = Number.isFinite(ratio) && ratio > 1 ? ratio : 1.3;
const cur = Number.isFinite(currentScore) ? currentScore : 0;
const cand = Number.isFinite(candidateScore) ? candidateScore : 0;
if (cur <= 0) return cand > 0;
return cand > cur * r;
}
function computeAimSolution(opts) {
const eyeX = Number(opts && opts.eyeX);
const eyeY = Number(opts && opts.eyeY);
const eyeZ = Number(opts && opts.eyeZ);
const targetX = Number(opts && opts.targetX);
const targetY = Number(opts && opts.targetY);
const targetZ = Number(opts && opts.targetZ);
const vx = Number(opts && opts.targetVx) || 0;
const vy = Number(opts && opts.targetVy) || 0;
const vz = Number(opts && opts.targetVz) || 0;
const bulletSpeed = Number(opts && opts.bulletSpeed) > 0 ? Number(opts.bulletSpeed) : DEFAULT_BULLET_SPEED;
const horizontalDist = Math.hypot(targetX - eyeX, targetZ - eyeZ);
const tFlight = horizontalDist / bulletSpeed;
const aimX = targetX + vx * tFlight;
const aimY = targetY + vy * tFlight;
const aimZ = targetZ + vz * tFlight;
const horizontalAim = Math.hypot(aimX - eyeX, aimZ - eyeZ) || 1e-6;
const yaw = Math.atan2(aimX - eyeX, -(aimZ - eyeZ));
const pitch = Math.atan2(aimY - eyeY, horizontalAim);
return { yaw: yaw, pitch: pitch, aimPoint: { x: aimX, y: aimY, z: aimZ }, horizontalDist: horizontalDist };
}
function computeAdaptiveLookahead(speed) {
const s = Number.isFinite(speed) && speed >= 0 ? Number(speed) : 0;
return Math.max(5, Math.min(20, 8 + 0.05 * s));
}
function pointAlongPath(path, fromIdx, fromPos, lookaheadDist) {
if (!Array.isArray(path) || path.length === 0) return null;
const idx = Math.max(0, Math.min(path.length - 1, Number(fromIdx) || 0));
if (path.length === 1 || idx >= path.length - 1) {
const last = path[path.length - 1];
return last ? { x: Number(last.x || 0), y: Number(last.y || 0), z: Number(last.z || 0) } : null;
}
const pos = fromPos || path[idx];
const px = Number(pos && pos.x || 0);
const pz = Number(pos && pos.z || 0);
const lookahead = Number.isFinite(lookaheadDist) && lookaheadDist > 0 ? Number(lookaheadDist) : 8;
const cumulative = new Array(path.length).fill(0);
for (let i = 1; i < path.length; i++) {
const a = path[i - 1] || {};
const b = path[i] || {};
cumulative[i] = cumulative[i - 1] + Math.hypot(
Number(b.x || 0) - Number(a.x || 0),
Number(b.z || 0) - Number(a.z || 0),
);
}
let best = null;
let bestDistanceSq = Number.POSITIVE_INFINITY;
for (let i = idx; i < path.length - 1; i++) {
const a = path[i] || {};
const b = path[i + 1] || {};
const ax = Number(a.x || 0);
const az = Number(a.z || 0);
const bx = Number(b.x || 0);
const bz = Number(b.z || 0);
const vx = bx - ax;
const vz = bz - az;
const segSq = vx * vx + vz * vz;
if (segSq <= 1e-8) continue;
const t = Math.max(0, Math.min(1, ((px - ax) * vx + (pz - az) * vz) / segSq));
const qx = ax + vx * t;
const qz = az + vz * t;
const dx = qx - px;
const dz = qz - pz;
const dSq = dx * dx + dz * dz;
if (dSq < bestDistanceSq) {
bestDistanceSq = dSq;
best = {
distance: cumulative[i] + Math.sqrt(segSq) * t,
};
}
}
if (!best) {
const wp = path[idx];
best = { distance: cumulative[idx], x: Number(wp.x || 0), z: Number(wp.z || 0) };
}
const targetDistance = Math.min(cumulative[cumulative.length - 1], best.distance + lookahead);
for (let i = idx; i < path.length - 1; i++) {
const a = path[i] || {};
const b = path[i + 1] || {};
const segStart = cumulative[i];
const segEnd = cumulative[i + 1];
const segLen = segEnd - segStart;
if (segLen <= 1e-8) continue;
if (targetDistance <= segEnd || i === path.length - 2) {
const t = Math.max(0, Math.min(1, (targetDistance - segStart) / segLen));
const ax = Number(a.x || 0);
const ay = Number(a.y || 0);
const az = Number(a.z || 0);
const bx = Number(b.x || 0);
const by = Number(b.y || 0);
const bz = Number(b.z || 0);
return {
x: ax + (bx - ax) * t,
y: ay + (by - ay) * t,
z: az + (bz - az) * t,
};
}
}
const last = path[path.length - 1];
return last ? { x: Number(last.x || 0), y: Number(last.y || 0), z: Number(last.z || 0) } : null;
}
// ── Waypoint advance + replan + pit-trap heuristics (bot-pathing-pit-and-steep-uphill). ──
//
// The driver's old advance-rule used horizontal-only distance to decide a
// waypoint had been "passed". On steep uphill that fired before the bot
// had actually climbed to the waypoint's height, which exhausted the path
// mid-climb and triggered a 750ms-cadence re-plan. The bot then zigzagged.
//
// These helpers fence both decisions behind explicit horizontal AND vertical
// tolerances, and surface the steep-climb case as a separate predicate so
// the fast-replan path can defer while the bot is still climbing.
//
// Defaults:
// - horizontalTolerance 4m: same as the prior live-driver value.
// - verticalTolerance 2.5m: roughly one player-eye-height (2.2m) plus a
// small margin so a waypoint at ground-level still counts as reached.
// - steepClimbVerticalDelta 3m: heuristic for "still climbing"; matches
// the brief.
function shouldAdvanceWaypoint(opts) {
const player = opts && opts.playerPos;
const wp = opts && opts.waypoint;
if (!player || !wp) return false;
const hTol = Number.isFinite(opts && opts.horizontalTolerance) && opts.horizontalTolerance > 0
? Number(opts.horizontalTolerance) : 4;
const vTol = Number.isFinite(opts && opts.verticalTolerance) && opts.verticalTolerance > 0
? Number(opts.verticalTolerance) : 2.5;
const dx = Number(wp.x || 0) - Number(player.x || 0);
const dz = Number(wp.z || 0) - Number(player.z || 0);
const horizontal = Math.hypot(dx, dz);
if (horizontal > hTol) return false;
// Some navmesh waypoints carry a y; if absent (or non-finite) we treat
// the waypoint as planar and accept the advance on horizontal proximity.
const wy = Number(wp.y);
const py = Number(player.y);
if (!Number.isFinite(wy) || !Number.isFinite(py)) return true;
return Math.abs(wy - py) <= vTol;
}
function isSteepClimbWaypoint(opts) {
const player = opts && opts.playerPos;
const wp = opts && opts.waypoint;
if (!player || !wp) return false;
const climbDelta = Number.isFinite(opts && opts.climbDelta) && opts.climbDelta > 0
? Number(opts.climbDelta) : 3;
const dx = Number(wp.x || 0) - Number(player.x || 0);
const dz = Number(wp.z || 0) - Number(player.z || 0);
const horizontal = Math.hypot(dx, dz);
// Only "steep" if the waypoint is meaningfully above us AND still nearby
// (within ~12m horizontally — beyond that the slope is averaged out).
if (horizontal > 12) return false;
const wy = Number(wp.y);
const py = Number(player.y);
if (!Number.isFinite(wy) || !Number.isFinite(py)) return false;
return (wy - py) > climbDelta;
}
function shouldFastReplan(opts) {
const pathExhausted = !!(opts && opts.pathExhausted);
const sinceReplanMs = Number(opts && opts.sinceReplanMs);
const fastReplanMs = Number.isFinite(opts && opts.fastReplanMs) && opts.fastReplanMs > 0
? Number(opts.fastReplanMs) : 750;
if (!pathExhausted) return false;
if (!Number.isFinite(sinceReplanMs) || sinceReplanMs <= fastReplanMs) return false;
// Suppress the fast re-plan while the bot is mid-climb to a waypoint that
// is still above it. The path is still trustworthy; we just need time to
// climb. The full TTL re-plan still fires (handled outside this helper).
if (opts && opts.steepClimbActive) return false;
return true;
}
function detectPitTrap(opts) {
const stuckMs = Number(opts && opts.stuckMs);
const stuckThresholdMs = Number.isFinite(opts && opts.stuckThresholdMs) && opts.stuckThresholdMs > 0
? Number(opts.stuckThresholdMs) : 4000;
if (!Number.isFinite(stuckMs) || stuckMs < stuckThresholdMs) return false;
const player = opts && opts.playerPos;
const wp = opts && opts.currentWaypoint;
const pitDelta = Number.isFinite(opts && opts.pitVerticalDelta) && opts.pitVerticalDelta > 0
? Number(opts.pitVerticalDelta) : 3;
if (!player || !wp) {
// No active waypoint context — still surface as a pit-trap when stuck.
// The caller decides whether to escape; this predicate is purely
// observational so the test can pin "stuck for long enough" alone.
return true;
}
const wy = Number(wp.y);
const py = Number(player.y);
if (!Number.isFinite(wy) || !Number.isFinite(py)) return true;
// True pit signature: the next waypoint is meaningfully above us. If
// the waypoint is at or below us, the bot is stuck for some other
// reason (terrain wall, geometry pinch); the caller can still react
// but a pit-escape teleport is the wrong fix. Return false here so
// the escape path is reserved for the up-and-out case.
return (wy - py) > pitDelta;
}
function evaluateFireGate(opts) {
const aimErrorRad = Number(opts && opts.aimErrorRad);
const maxAimErrorRad = Number(opts && opts.maxAimErrorRad);
const losClear = !!(opts && opts.losClear);
const pitchRad = Number(opts && opts.pitchRad);
const distance = Number(opts && opts.distance);
const ammoReady = !!(opts && opts.ammoReady);
const errLimit = Number.isFinite(maxAimErrorRad) && maxAimErrorRad > 0 ? maxAimErrorRad : (3 * Math.PI) / 180;
if (!ammoReady) return { fire: false, reason: 'ammo_not_ready' };
if (!Number.isFinite(aimErrorRad) || aimErrorRad > errLimit) return { fire: false, reason: 'aim_error_too_high' };
if (!losClear) return { fire: false, reason: 'los_blocked' };
const MIN_SAFE_PITCH = -25 * Math.PI / 180;
if (Number.isFinite(pitchRad) && pitchRad < MIN_SAFE_PITCH && (!Number.isFinite(distance) || distance > 10)) {
return { fire: false, reason: 'fire_pitch_unsafe' };
}
return { fire: true, reason: 'ok' };
}
function sampleTerrainLineHeight(terrain, x, z) {
if (!terrain) return null;
const sample = typeof terrain.getEffectiveHeightAt === 'function'
? terrain.getEffectiveHeightAt(x, z)
: typeof terrain.getHeightAt === 'function'
? terrain.getHeightAt(x, z)
: null;
const height = Number(sample);
return Number.isFinite(height) ? height : null;
}
function findHeightProfileTerrainBlock(terrain, from, dir, distance, clearance) {
if (!terrain || (typeof terrain.getEffectiveHeightAt !== 'function' && typeof terrain.getHeightAt !== 'function')) {
return null;
}
if (!Number.isFinite(distance) || distance <= 0) return null;
const targetClearance = Number.isFinite(Number(clearance)) ? Math.max(0, Number(clearance)) : 0.75;
const endpointPadding = Math.min(8, Math.max(targetClearance, distance * 0.05));
// Terrain raycasts can miss when the camera is very close to, or already
// partly inside, a hillside. Do not blind the driver to the first few
// meters of terrain; this LOS result gates both target acquisition and
// firing in the perf harness.
const startDistance = Math.max(targetClearance, Math.min(2, endpointPadding));
const stopDistance = distance - endpointPadding;
if (stopDistance <= startDistance) return null;
const step = Math.max(2, Math.min(4, distance / 96));
const occlusionMargin = -0.25;
for (let d = startDistance; d < stopDistance; d += step) {
const x = from.x + dir.x * d;
const y = from.y + dir.y * d;
const z = from.z + dir.z * d;
const terrainY = sampleTerrainLineHeight(terrain, x, z);
if (terrainY === null) continue;
if (terrainY - y >= occlusionMargin) {
return d;
}
}
return null;
}
function queryTerrainLineOfSight(terrain, fromPos, toPos, clearance) {
if (!terrain || typeof terrain.raycastTerrain !== 'function') {
return { status: 'unknown', clear: false, reason: 'missing_terrain_raycast' };
}
const from = {
x: Number(fromPos && fromPos.x),
y: Number((fromPos && fromPos.y) || 0),
z: Number(fromPos && fromPos.z),
};
const to = {
x: Number(toPos && toPos.x),
y: Number((toPos && toPos.y) || 0),
z: Number(toPos && toPos.z),
};
const dx = to.x - from.x;
const dy = to.y - from.y;
const dz = to.z - from.z;
const distance = Math.hypot(dx, dy, dz);
if (!Number.isFinite(distance)) {
return { status: 'unknown', clear: false, reason: 'invalid_query' };
}
if (distance < 0.001) {
return { status: 'clear', clear: true, reason: 'degenerate_distance' };
}
const dir = { x: dx / distance, y: dy / distance, z: dz / distance };
let hit;
try {
hit = terrain.raycastTerrain(from, dir, distance);
} catch (_error) {
return { status: 'unknown', clear: false, reason: 'raycast_error' };
}
const targetClearance = Number.isFinite(Number(clearance)) ? Math.max(0, Number(clearance)) : 0.75;
if (!hit || !hit.hit) {
const profileBlockDistance = findHeightProfileTerrainBlock(terrain, from, dir, distance, targetClearance);
if (profileBlockDistance !== null) {
return {
status: 'blocked',
clear: false,
reason: 'height_profile_blocked',
distance: profileBlockDistance,
};
}
return { status: 'clear', clear: true, reason: 'raycast_miss' };
}
if (!Number.isFinite(Number(hit.distance))) {
return { status: 'unknown', clear: false, reason: 'invalid_hit_distance' };
}
if (Number(hit.distance) < distance - targetClearance) {
return { status: 'blocked', clear: false, reason: 'terrain_hit_before_target' };
}
return { status: 'clear', clear: true, reason: 'hit_within_target_clearance' };
}
function hasClearTerrainLineOfSight(terrain, fromPos, toPos, clearance) {
return queryTerrainLineOfSight(terrain, fromPos, toPos, clearance).clear;
}
function angularDistance(yaw1, pitch1, yaw2, pitch2) {
let dy = Number(yaw2) - Number(yaw1);
while (dy > Math.PI) dy -= Math.PI * 2;
while (dy < -Math.PI) dy += Math.PI * 2;
const dp = Number(pitch2) - Number(pitch1);
return Math.hypot(dy, dp);
}
function signedYawDelta(fromYaw, toYaw) {
let delta = Number(toYaw) - Number(fromYaw);
if (!Number.isFinite(delta)) return 0;
while (delta > Math.PI) delta -= Math.PI * 2;
while (delta < -Math.PI) delta += Math.PI * 2;
return delta;
}
function clampSigned(value, maxAbs) {
const v = Number(value);
const limit = Math.max(0, Number(maxAbs) || 0);
if (!Number.isFinite(v)) return 0;
if (v > limit) return limit;
if (v < -limit) return -limit;
return v;
}
function clampDriverPitch(p) {
if (!Number.isFinite(p)) return 0;
return Math.max(-AIM_PITCH_LIMIT_RAD, Math.min(AIM_PITCH_LIMIT_RAD, p));
}
function applyViewSlewLimit(currentYaw, currentPitch, targetYaw, targetPitch, limits) {
const yawLimit = Number.isFinite(Number(limits && limits.yaw))
? Math.max(0, Number(limits.yaw))
: DRIVER_VIEW_MAX_YAW_STEP_RAD;
const pitchLimit = Number.isFinite(Number(limits && limits.pitch))
? Math.max(0, Number(limits.pitch))
: DRIVER_VIEW_MAX_PITCH_STEP_RAD;
const yawDelta = signedYawDelta(currentYaw, targetYaw);
const pitchDelta = Number(targetPitch) - Number(currentPitch);
const clampedYawDelta = clampSigned(yawDelta, yawLimit);
const clampedPitchDelta = clampSigned(pitchDelta, pitchLimit);
const yaw = Number(currentYaw) + clampedYawDelta;
const pitch = clampDriverPitch(Number(currentPitch) + clampedPitchDelta);
return {
yaw,
pitch,
yawDelta,
pitchDelta,
remainingYawDelta: signedYawDelta(yaw, targetYaw),
remainingPitchDelta: Number(targetPitch) - pitch,
yawClamped: Math.abs(clampedYawDelta - yawDelta) > 1e-9,
pitchClamped: Math.abs(clampedPitchDelta - pitchDelta) > 1e-9,
};
}
function syncViewAnchorToActual(anchorYaw, anchorPitch, actualYaw, actualPitch, epsilonRad) {
const yawFallback = Number.isFinite(Number(anchorYaw)) ? Number(anchorYaw) : 0;
const pitchFallback = clampDriverPitch(Number.isFinite(Number(anchorPitch)) ? Number(anchorPitch) : 0);
const yaw = Number.isFinite(Number(actualYaw)) ? Number(actualYaw) : yawFallback;
const pitch = Number.isFinite(Number(actualPitch)) ? clampDriverPitch(Number(actualPitch)) : pitchFallback;
const yawDelta = signedYawDelta(yawFallback, yaw);
const pitchDelta = pitch - pitchFallback;
const epsilon = Number.isFinite(Number(epsilonRad)) ? Math.max(0, Number(epsilonRad)) : 1e-4;
return {
yaw,
pitch,
yawDelta,
pitchDelta,
changed: Math.abs(yawDelta) > epsilon || Math.abs(pitchDelta) > epsilon,
};
}
// ── Objective zone selector (pure, exported for Node-side regression tests). ──
//
// Picks the next capture zone the harness bot should march on.
//
// Rules (mode-agnostic; callers pass in the friendly-faction predicate):
// - Skip home-base zones — the bot never targets its own or the enemy
// spawn as an objective.
// - Skip zones that are friendly-owned AND not contested. This is the
// cycling-fix invariant: once a zone is ours and uncontested, it is
// NOT a valid objective. On wide maps (e.g. A Shau) the previous
// "prefer distant unowned zones" scoring still picked a nearby owned
// zone because `priority * 500_000` was swamped by distSq across 10+
// km. Hard-skipping the owned-uncontested class prevents the loop.
// - Among the remaining candidates, prefer contested (someone is taking
// it from us right now), then unowned/enemy-held, breaking ties by
// squared distance. Returns null when no actionable zone remains.
//
// `isFriendly(owner)` is passed in so the selector stays faction-agnostic
// and unit-testable without the BLUFOR/OPFOR constants.
function pickObjectiveZone(opts) {
const zones = opts && Array.isArray(opts.zones) ? opts.zones : null;
if (!zones || zones.length === 0) return null;
const playerPos = opts && opts.playerPos;
if (!playerPos) return null;
const isFriendly = (opts && typeof opts.isFriendly === 'function')
? opts.isFriendly
: () => false;
const px = Number(playerPos.x);
const pz = Number(playerPos.z);
if (!Number.isFinite(px) || !Number.isFinite(pz)) return null;
// Lexicographic sort: priority class first (contested > unowned/enemy),
// then distance. Explicit lex order is safer than a composite score on
// wide maps (e.g. A Shau's ~20 km diagonal) where distSq would swamp any
// fixed priority weight.
let best = null;
let bestPriority = Number.POSITIVE_INFINITY;
let bestDistSq = Number.POSITIVE_INFINITY;
for (let i = 0; i < zones.length; i++) {
const z = zones[i];
if (!z || z.isHomeBase || !z.position) continue;
const isContested = z.state === 'contested';
const ownedByUs = isFriendly(z.owner);
// Cycling-fix: friendly-owned non-contested zones are NOT actionable.
if (ownedByUs && !isContested) continue;
const dx = Number(z.position.x) - px;
const dz = Number(z.position.z) - pz;
if (!Number.isFinite(dx) || !Number.isFinite(dz)) continue;
const distSq = dx * dx + dz * dz;
// Priority 0 = contested (defend / retake now), 1 = unowned / enemy.
const priority = isContested ? 0 : 1;
if (priority < bestPriority || (priority === bestPriority && distSq < bestDistSq)) {
best = z;
bestPriority = priority;
bestDistSq = distSq;
}
}
return best;
}
function selectPatrolObjective(opts) {
const aggressive = !!(opts && opts.aggressiveMode);
const combatObjective = opts && opts.combatObjective && opts.combatObjective.position
? opts.combatObjective
: null;
const zoneObjective = opts && opts.zoneObjective && opts.zoneObjective.position
? opts.zoneObjective
: null;
const fallbackObjective = opts && opts.fallbackObjective && opts.fallbackObjective.position
? opts.fallbackObjective
: null;
const maxCombatDistance = Number(opts && opts.combatObjectiveMaxDistance);
const combatDistance = Number(combatObjective && combatObjective.distance);
const combatInDetourRange =
combatObjective &&
Number.isFinite(combatDistance) &&
(!Number.isFinite(maxCombatDistance) || combatDistance <= maxCombatDistance);
if (aggressive && combatInDetourRange) return combatObjective;
if (zoneObjective) return zoneObjective;
if (combatInDetourRange) return combatObjective;
return fallbackObjective;
}
function objectiveTelemetryKey(objective, zoneId) {
if (!objective || !objective.position) return null;
const kind = String(objective.kind || 'unknown');
if (kind === 'zone' && zoneId) return `zone:${String(zoneId)}`;
if (objective.id !== null && objective.id !== undefined && String(objective.id) !== '') {
return `${kind}:${String(objective.id)}`;
}
return kind;
}
function objectiveBlockKey(kind, id) {
if (kind === null || kind === undefined || id === null || id === undefined || String(id) === '') return null;
return `${String(kind)}:${String(id)}`;
}
function routeTargetIdentityKey(kind, objective, zoneId) {
const normalizedKind = kind ? String(kind) : 'unknown';
const routeObjective = objective && objective.position
? objective
: objective
? { kind: normalizedKind, position: objective }
: null;
return objectiveTelemetryKey(routeObjective, zoneId) ?? normalizedKind;
}
// ── Combat stat helpers (pure, exported for Node-side regression tests). ──
//
// The driver polls the engine's PlayerStatsTracker each tick. These
// helpers turn a (baseline, current) pair of polled snapshots into a
// monotonically-increasing run total, ignoring snapshots that look
// corrupt (negative, NaN). They also gracefully handle the
// PlayerStatsTracker being reset mid-run (e.g. on respawn) by
// re-baselining when the polled value drops below the baseline.
function deltaSinceBaseline(currentValue, baselineValue) {
const cur = Number(currentValue);
const base = Number(baselineValue);
if (!Number.isFinite(cur)) return 0;
if (!Number.isFinite(base)) return Math.max(0, cur);
return Math.max(0, cur - base);
}
function rebasedTotal(prevTotal, currentValue, baselineValue) {
const prev = Number.isFinite(prevTotal) ? Number(prevTotal) : 0;
const cur = Number(currentValue);
const base = Number(baselineValue);
if (!Number.isFinite(cur)) return { total: prev, newBaseline: base };
// PlayerStatsTracker reset (cur dropped below baseline). Fold the
// last segment into prev and rebase to current.
if (Number.isFinite(base) && cur < base) {
return { total: prev, newBaseline: cur };
}
return { total: prev + deltaSinceBaseline(cur, base), newBaseline: cur };
}
function damageTakenDelta(prevHealth, currentHealth) {
const prev = Number(prevHealth);
const cur = Number(currentHealth);
if (!Number.isFinite(prev) || !Number.isFinite(cur)) return 0;
// Health going up = regen / respawn. Only count strict drops.
if (cur >= prev) return 0;
return prev - cur;
}
function computeAccuracy(shotsFired, shotsHit) {
const f = Number(shotsFired);
const h = Number(shotsHit);
if (!Number.isFinite(f) || f <= 0) return 0;
if (!Number.isFinite(h) || h <= 0) return 0;
return Math.max(0, Math.min(1, h / f));
}
// ── PlayerBot state machine (JS mirror of src/dev/harness/playerBot/states.ts). ──
//
// `stepBotState(state, ctx)` is pure: returns { intent, nextState, resetTimeInState }.
// The TypeScript version is unit-tested under src/dev/harness/*.test.ts;
// changes here MUST be ported to the TS source in the same PR.
const OPFOR_FACTIONS = new Set(['NVA', 'VC']);
const BLUFOR_FACTIONS = new Set(['US', 'ARVN']);
function isOpforFaction(faction) { return OPFOR_FACTIONS.has(faction); }
function isBluforFaction(faction) { return BLUFOR_FACTIONS.has(faction); }
// ── Match-end detection (harness-lifecycle-halt-on-match-end). ──
//
// The harness bot plays for BLUFOR; the live engine signals victory through
// TicketSystem.getGameState() which exposes { phase: 'ENDED', winner: Faction }.
// GameModeManager itself does not expose a match-end query — TicketSystem is
// the canonical owner of that lifecycle bit. Pure helper so the Node test
// can assert the outcome mapping without spinning up the engine.
// Modes without a faction win condition (harness-match-end-skip-ai-sandbox).
// TicketSystem reports phase='ENDED' from the start in ai_sandbox — no
// tickets, no objective — which would otherwise latch match-end on the
// first sample tick and truncate the capture. Keep the list small and
// explicit so zone_control / team_deathmatch / open_frontier still exit
// normally when their real win condition fires.
const MODES_WITHOUT_WIN_CONDITION = new Set(['ai_sandbox']);
function detectMatchEnded(gameState, mode) {
if (mode && MODES_WITHOUT_WIN_CONDITION.has(String(mode).toLowerCase())) return false;
if (!gameState) return false;
if (gameState.phase === 'ENDED') return true;
return gameState.gameActive === false;
}
function detectMatchOutcome(gameState, mode) {
if (!detectMatchEnded(gameState, mode)) return null;
const winner = gameState && gameState.winner;
if (isBluforFaction(winner)) return 'victory';
if (isOpforFaction(winner)) return 'defeat';
return 'draw';
}
// How long perf-capture.ts keeps sampling after the harness reports match-end
// before tearing down — gives tail frames a chance to flush. The brief
// specifies 2s; tuneable but kept as a constant so the regression test can
// assert against the same value.
const MATCH_END_TAIL_MS = 2000;
/**
* Pure decision used by scripts/perf-capture.ts: should the capture loop
* break out of its `while (Date.now() - startMs < durationSeconds * 1000)`
* because the harness already observed match-end at least MATCH_END_TAIL_MS
* ago? Returns false when no match-end has been observed yet (capture runs
* to its configured duration).
*/
function shouldFinalizeAfterMatchEnd(matchEndedAtMs, nowMs, tailMs) {
if (matchEndedAtMs === null || matchEndedAtMs === undefined) return false;
if (!Number.isFinite(matchEndedAtMs) || !Number.isFinite(nowMs)) return false;
const tail = Number.isFinite(tailMs) && tailMs >= 0 ? tailMs : MATCH_END_TAIL_MS;
return nowMs - matchEndedAtMs >= tail;
}
function appendBoundedEvent(buffer, event, limit) {
if (!Array.isArray(buffer)) return [];
const max = Math.max(1, Number.isFinite(Number(limit)) ? Math.floor(Number(limit)) : SHOT_EPOCH_HISTORY_LIMIT);
if (buffer.length < max) {
buffer.push(event);
return buffer;
}
if (buffer.length > max) {
const retainStart = buffer.length - max;
for (let i = 0; i < max; i++) {
buffer[i] = buffer[i + retainStart];
}
buffer.length = max;
}
buffer.copyWithin(0, 1, max);
buffer[max - 1] = event;
return buffer;
}
function finiteOrNull(value) {
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric : null;
}
function sanitizeVector3Like(value) {
if (!value || typeof value !== 'object') return null;
return {
x: finiteOrNull(value.x),
y: finiteOrNull(value.y),
z: finiteOrNull(value.z),
};
}
function sanitizeRotationDegLike(value) {
if (!value || typeof value !== 'object') return null;
return {
yaw: finiteOrNull(value.yaw),
pitch: finiteOrNull(value.pitch),
roll: finiteOrNull(value.roll),
};
}
function sanitizeQuaternionLike(value) {
if (!value || typeof value !== 'object') return null;
return {
x: finiteOrNull(value.x),
y: finiteOrNull(value.y),
z: finiteOrNull(value.z),
w: finiteOrNull(value.w),
};
}
function sanitizeCameraDeltaLike(value) {
if (!value || typeof value !== 'object') return null;
return {
positionMeters: finiteOrNull(value.positionMeters),
yawDeg: finiteOrNull(value.yawDeg),
pitchDeg: finiteOrNull(value.pitchDeg),
rollDeg: finiteOrNull(value.rollDeg),
};
}
function sanitizePresentationCameraEpoch(value) {
if (!value || typeof value !== 'object') return null;
return {
stage: typeof value.stage === 'string' ? value.stage : 'unknown',
frameCount: finiteOrNull(value.frameCount),
atMs: finiteOrNull(value.atMs),
cameraSource: typeof value.cameraSource === 'string' ? value.cameraSource : 'unknown',
position: sanitizeVector3Like(value.position),
rotationDeg: sanitizeRotationDegLike(value.rotationDeg),
quaternion: sanitizeQuaternionLike(value.quaternion),
deltaFromPrevious: sanitizeCameraDeltaLike(value.deltaFromPrevious),
};
}
function sanitizePresentationTerrainSample(value) {
if (!value || typeof value !== 'object') return null;
return {
terrainHeightAtCamera: finiteOrNull(value.terrainHeightAtCamera),
effectiveHeightAtCamera: finiteOrNull(value.effectiveHeightAtCamera),
clearanceMeters: finiteOrNull(value.clearanceMeters),
effectiveClearanceMeters: finiteOrNull(value.effectiveClearanceMeters),
hasTerrain: typeof value.hasTerrain === 'boolean' ? value.hasTerrain : null,
areaReady: typeof value.areaReady === 'boolean' ? value.areaReady : null,
};
}
function sanitizeStringNumberRecord(value) {
if (!value || typeof value !== 'object') return {};
const output = {};
for (const key in value) {
if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
const numeric = finiteOrNull(value[key]);
if (numeric !== null) output[String(key)] = numeric;
}
return output;
}
function sanitizePresentationTerrainEpoch(value) {
if (!value || typeof value !== 'object') return null;
return {
tileCount: finiteOrNull(value.tileCount),
tileSelectionSaturated: typeof value.tileSelectionSaturated === 'boolean'
? value.tileSelectionSaturated
: null,
tileHash: typeof value.tileHash === 'string' ? value.tileHash : null,