-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixedWingModel.ts
More file actions
1194 lines (1063 loc) · 42.5 KB
/
Copy pathFixedWingModel.ts
File metadata and controls
1194 lines (1063 loc) · 42.5 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
import * as THREE from 'three';
import type { GameSystem } from '../../types';
import type { ITerrainRuntime, IHUDSystem, IPlayerController } from '../../types/SystemInterfaces';
import type { VehicleManager } from './VehicleManager';
import { Airframe } from './airframe/Airframe';
import type { AirframeIntent, AirframeTerrainProbe } from './airframe/types';
import { createFlatTerrainProbe, createRuntimeTerrainProbe } from './airframe/terrainProbe';
import {
airframeConfigFromLegacy,
airframeStateToFixedWingSnapshot,
fixedWingFlightStateFromSnapshot,
} from './FixedWingTypes';
import type {
FixedWingCommand,
FixedWingFlightPhase,
FixedWingFlightSnapshot,
FixedWingFlightState,
} from './FixedWingTypes';
import { FixedWingAnimation } from './FixedWingAnimation';
import { FixedWingInteraction } from './FixedWingInteraction';
import { FixedWingVehicleAdapter } from './FixedWingVehicleAdapter';
import { shouldRenderAirVehicle, shouldSimulateAirVehicle } from './AirVehicleVisibility';
import {
buildFixedWingPilotCommand,
createIdleFixedWingPilotIntent,
deriveFixedWingControlPhase,
} from './FixedWingControlLaw';
import type { FixedWingControlPhase, FixedWingPilotIntent } from './FixedWingControlLaw';
import { NPCFixedWingPilot } from './NPCFixedWingPilot';
import type { Mission as NPCPilotMission, TerrainProbe as NPCTerrainProbe } from './NPCFixedWingPilot';
import {
deriveFixedWingOperationState,
getFixedWingExitStatus,
} from './FixedWingOperations';
import type {
FixedWingOperationState,
FixedWingSpawnMetadata,
} from './FixedWingOperations';
import {
FIXED_WING_CONFIGS,
getFixedWingConfigKeyForModelPath,
getFixedWingDisplayInfo,
} from './FixedWingConfigs';
import type { FixedWingDisplayInfo } from './FixedWingConfigs';
import type { VehicleExitOptions, VehicleExitPlan, VehicleExitResult } from './PlayerVehicleAdapter';
import { modelLoader } from '../assets/ModelLoader';
import { Faction } from '../combat/types';
import type { CombatantSystem } from '../combat/CombatantSystem';
import { TracerPool } from '../effects/TracerPool';
import { Logger } from '../../utils/Logger';
import { computeFixedWingShot, getFixedWingWeaponConfig } from './FixedWingArmament';
import type { FixedWingWeaponConfig } from './FixedWingArmament';
import { optimizeFixedWingStaticDrawCalls } from './FixedWingRenderOptimization';
const FIXED_WING_GUN_TRACER_RANGE = 500;
interface FixedWingWeaponState {
/** Per-airframe armament config (geometry, spread, cadence, magazine). */
config: FixedWingWeaponConfig;
ammo: number;
cooldownRemaining: number;
roundsSinceTracer: number;
/** Round-robin barrel cursor (paired wing cannons / broadside battery). */
barrelIndex: number;
isFiring: boolean;
faction: Faction;
}
const _gunMuzzle = new THREE.Vector3();
const _gunForward = new THREE.Vector3();
const _gunTracerEnd = new THREE.Vector3();
const _gunRay = new THREE.Ray();
const _gunSpreadRight = new THREE.Vector3();
const _gunSpreadUp = new THREE.Vector3();
interface AircraftRuntime {
airframe: Airframe;
/**
* Pending command fed to the Airframe each update. Latest gameplay-side
* command, translated to an `AirframeIntent` at step time.
*/
command: FixedWingCommand;
worldHalfExtent: number;
}
type VehicleExitRequester = {
requestVehicleExit?: (options?: VehicleExitOptions) => VehicleExitResult;
};
interface FixedWingFlightData {
airspeed: number;
heading: number;
verticalSpeed: number;
altitude: number;
altitudeAGL: number;
controlPhase: FixedWingControlPhase;
operationState: FixedWingOperationState;
phase: FixedWingFlightPhase;
aoaDeg: number;
sideslipDeg: number;
throttle: number;
brake: number;
weightOnWheels: boolean;
isStalled: boolean;
flightState: FixedWingFlightState;
stallSpeed: number;
pitch: number;
roll: number;
orbitHoldEnabled: boolean;
configKey: string | null;
}
function createIdleCommand(): FixedWingCommand {
return {
throttleTarget: 0,
pitchCommand: 0,
rollCommand: 0,
yawCommand: 0,
brake: 0,
freeLook: false,
stabilityAssist: false,
};
}
/**
* Translate a gameplay-side `FixedWingCommand` into an `AirframeIntent`.
* `stabilityAssist` maps to `tier: 'assist' | 'raw'` (the `feel` config scales
* are neutralized in `airframeConfigFromLegacy` so command values flow through
* unchanged); `brake` is clamped at ground-tier by the Airframe command builder.
*/
function commandToAirframeIntent(cmd: FixedWingCommand): AirframeIntent {
return {
pitch: cmd.pitchCommand,
roll: cmd.rollCommand,
yaw: cmd.yawCommand,
throttle: cmd.throttleTarget,
brake: cmd.brake,
tier: cmd.stabilityAssist ? 'assist' : 'raw',
};
}
function sanitizeCommand(command: Partial<FixedWingCommand>, base: FixedWingCommand): FixedWingCommand {
const next: FixedWingCommand = { ...base };
if (command.throttleTarget !== undefined) {
next.throttleTarget = THREE.MathUtils.clamp(command.throttleTarget, 0, 1);
}
if (command.pitchCommand !== undefined) {
next.pitchCommand = THREE.MathUtils.clamp(command.pitchCommand, -1, 1);
}
if (command.rollCommand !== undefined) {
next.rollCommand = THREE.MathUtils.clamp(command.rollCommand, -1, 1);
}
if (command.yawCommand !== undefined) {
next.yawCommand = THREE.MathUtils.clamp(command.yawCommand, -1, 1);
}
if (command.brake !== undefined) {
next.brake = THREE.MathUtils.clamp(command.brake, 0, 1);
}
if (command.freeLook !== undefined) {
next.freeLook = command.freeLook;
}
if (command.stabilityAssist !== undefined) {
next.stabilityAssist = command.stabilityAssist;
}
return next;
}
/**
* Optional airborne-hint sink on the concrete HUD. Accessed structurally (the
* same way the adapter reaches `updateFixedWingAmmo`) so the model does not
* have to widen the fenced `IHUDSystem` for a UI-only nicety — a HUD that lacks
* the method simply shows no hint.
*/
interface FixedWingAirborneHintSink {
flashFixedWingAirborneHint?(): void;
}
/**
* Orchestrates all fixed-wing aircraft instances.
* Parallel to HelicopterModel; each airframe carries its own gun from the
* armament table (A-1 wing cannons, F-4 nose rotary, AC-47 broadside; no door
* gunners).
*/
export class FixedWingModel implements GameSystem {
private static readonly IDLE_SIMULATION_SPEED = 0.5;
private scene: THREE.Scene;
private animation = new FixedWingAnimation();
private interaction: FixedWingInteraction;
// Per-aircraft state
private groups = new Map<string, THREE.Group>();
private runtimes = new Map<string, AircraftRuntime>();
private configKeys = new Map<string, string>();
private displayNames = new Map<string, string>();
private collisionRegistered = new Set<string>();
private spawnMetadata = new Map<string, FixedWingSpawnMetadata>();
private lineupAircraft = new Set<string>();
/**
* Per-aircraft latched sim-cull state. `true` means we simulated last frame,
* `false` means we were culled. Drives the hysteresis band in
* `shouldSimulateAirVehicle`. Aircraft default to `true` (simulate) until we
* have evidence they should be culled.
*/
private simulating = new Map<string, boolean>();
private pilotedAircraftId: string | null = null;
/** NPC pilots attached to aircraft in our catalog. See `attachNPCPilot()`. */
private npcPilots = new Map<string, NPCFixedWingPilot>();
// Dependencies
private terrainManager?: ITerrainRuntime;
private terrainProbe: AirframeTerrainProbe = createFlatTerrainProbe(0);
private playerController?: IPlayerController;
private hudSystem?: IHUDSystem;
private vehicleManager?: VehicleManager;
private combatantSystem?: CombatantSystem;
// Forward armament: per-aircraft weapon state + a small shared tracer pool.
private weapons = new Map<string, FixedWingWeaponState>();
private tracerPool?: TracerPool;
// Airborne-gate feedback: set when the player holds the trigger while the
// aircraft is still grounded (the gun silently no-ops there). The HUD reads
// and clears this each frame to surface a transient "Airborne to fire" hint
// instead of nothing. Internal signal only — not a fired round, not a gate
// change.
private groundedFireBlocked = false;
// Controls from player input
private currentPilotIntent: FixedWingPilotIntent = createIdleFixedWingPilotIntent();
private currentCommand: FixedWingCommand = createIdleCommand();
private pilotIntentActive = false;
constructor(scene: THREE.Scene) {
this.scene = scene;
this.interaction = new FixedWingInteraction(this.groups, this.displayNames, this.configKeys);
}
// -- Dependency setters --
setTerrainManager(terrainManager: ITerrainRuntime): void {
this.terrainManager = terrainManager;
this.terrainProbe = createRuntimeTerrainProbe(terrainManager);
this.interaction.setTerrainManager(terrainManager);
}
setPlayerController(playerController: IPlayerController): void {
this.playerController = playerController;
this.interaction.setPlayerController(playerController);
}
setHUDSystem(hudSystem: IHUDSystem): void {
this.hudSystem = hudSystem;
this.interaction.setHUDSystem(hudSystem);
}
setVehicleManager(vehicleManager: VehicleManager): void {
this.vehicleManager = vehicleManager;
}
setCombatantSystem(combatantSystem: CombatantSystem): void {
this.combatantSystem = combatantSystem;
}
// -- GameSystem lifecycle --
async init(): Promise<void> {
Logger.info('fixedwing', 'FixedWingModel initialized');
}
update(deltaTime: number): void {
// Update interaction prompts
this.interaction.checkPlayerProximity();
const camera = this.playerController && typeof this.playerController.getCamera === 'function'
? this.playerController.getCamera()
: null;
for (const [aircraftId, runtime] of this.runtimes) {
const group = this.groups.get(aircraftId);
if (!group) {
continue;
}
const isPiloted = aircraftId === this.pilotedAircraftId;
const npcPilot = !isPiloted ? this.npcPilots.get(aircraftId) : undefined;
const snapshot = this.buildSnapshot(runtime);
const flightState = fixedWingFlightStateFromSnapshot(snapshot);
const needsStep = isPiloted
|| npcPilot !== undefined
|| flightState !== 'grounded'
|| snapshot.airspeed > FixedWingModel.IDLE_SIMULATION_SPEED;
// Distance cull gate: parked / idle unpiloted aircraft beyond the render
// cull distance (plus hysteresis) are removed from the physics path
// entirely. Airborne NPC aircraft stay simulated regardless of distance.
const wasSimulating = this.simulating.get(aircraftId) ?? true;
const withinSimRange = shouldSimulateAirVehicle({
camera,
scene: this.scene,
vehiclePosition: group.position,
isAirborne: flightState !== 'grounded',
isPiloted,
hasActiveNPCPilot: npcPilot !== undefined,
currentlySimulating: wasSimulating,
});
const shouldSimulate = needsStep && withinSimRange;
if (shouldSimulate !== wasSimulating) {
this.simulating.set(aircraftId, shouldSimulate);
if (!shouldSimulate) {
// Freeze residual velocity so when sim resumes the airframe does not
// jump on the first step. Position and quaternion are already the
// last-simulated values; skipping step() leaves them untouched.
runtime.airframe.getVelocity().set(0, 0, 0);
Logger.debug('fixedwing', `simulation culled: ${aircraftId} (distance gate)`);
} else {
Logger.debug('fixedwing', `simulation resumed: ${aircraftId}`);
}
}
if (isPiloted) {
const configKey = this.configKeys.get(aircraftId);
const config = configKey ? FIXED_WING_CONFIGS[configKey] : null;
if (config && this.pilotIntentActive) {
const position = runtime.airframe.getPosition();
runtime.command = sanitizeCommand(
buildFixedWingPilotCommand(
snapshot,
config.physics,
config.pilotProfile,
this.currentPilotIntent,
{ positionX: position.x, positionZ: position.z },
),
runtime.command,
);
} else {
runtime.command = sanitizeCommand(this.currentCommand, runtime.command);
}
} else if (npcPilot && shouldSimulate) {
const configKey = this.configKeys.get(aircraftId);
const config = configKey ? FIXED_WING_CONFIGS[configKey] : null;
const airframeState = runtime.airframe.getState();
const pilotIntent = npcPilot.update(deltaTime, airframeState);
if (pilotIntent && config) {
const position = runtime.airframe.getPosition();
runtime.command = sanitizeCommand(
buildFixedWingPilotCommand(
snapshot,
config.physics,
config.pilotProfile,
pilotIntent,
{ positionX: position.x, positionZ: position.z },
),
runtime.command,
);
} else {
runtime.command = sanitizeCommand({
throttleTarget: 0,
pitchCommand: 0,
rollCommand: 0,
yawCommand: 0,
brake: 1,
}, runtime.command);
}
} else if (shouldSimulate) {
runtime.command = sanitizeCommand({
throttleTarget: 0,
pitchCommand: 0,
rollCommand: 0,
yawCommand: 0,
brake: runtime.command.brake > 0 ? runtime.command.brake : 0,
}, runtime.command);
}
if (shouldSimulate) {
runtime.airframe.step(
commandToAirframeIntent(runtime.command),
this.terrainProbe,
deltaTime,
);
const postSnapshot = this.buildSnapshot(runtime);
const configKey = this.configKeys.get(aircraftId);
const config = configKey ? FIXED_WING_CONFIGS[configKey] : null;
if (config && (postSnapshot.airspeed > config.operation.taxiSpeedMax || !postSnapshot.weightOnWheels)) {
this.lineupAircraft.delete(aircraftId);
}
const visualState = runtime.airframe.getInterpolatedState();
group.position.copy(visualState.position);
group.quaternion.copy(visualState.quaternion);
}
const currentSnapshot = shouldSimulate ? this.buildSnapshot(runtime) : snapshot;
const currentFlightState = fixedWingFlightStateFromSnapshot(currentSnapshot);
// Forward cannon: only the player-piloted aircraft can pull the trigger.
// Gated to airborne flight so a parked aircraft can't strafe the apron.
if (isPiloted) {
this.updateForwardGun(
aircraftId,
group,
currentFlightState !== 'grounded',
deltaTime,
);
// Surface the airborne-gate feedback: if the player held the trigger
// while grounded this frame, flash a transient HUD hint so the silent
// no-op reads as "not yet" instead of a broken gun.
if (this.consumeGroundedFireBlocked()) {
(this.hudSystem as FixedWingAirborneHintSink | undefined)
?.flashFixedWingAirborneHint?.();
}
}
const shouldRender = shouldRenderAirVehicle({
camera,
scene: this.scene,
vehiclePosition: group.position,
isAirborne: currentFlightState !== 'grounded',
isPiloted,
currentlyVisible: group.visible,
});
group.visible = shouldRender;
if (shouldRender) {
// Parked unpiloted aircraft (no pilot, grounded, near-zero airspeed) freeze
// their propellers so flying past idle aircraft on the airfield doesn't show
// them spinning.
const isAircraftActive = isPiloted
|| npcPilot !== undefined
|| currentFlightState !== 'grounded'
|| currentSnapshot.airspeed > FixedWingModel.IDLE_SIMULATION_SPEED;
this.animation.update(aircraftId, currentSnapshot.throttle, deltaTime, isAircraftActive);
}
if (isPiloted && this.playerController) {
// Feed the interpolated visual pose (`group.position`), not raw physics,
// so the camera, HUD readouts, and downstream consumers share one time
// base — raw physics aliased the fixed-step sawtooth at high refresh.
this.playerController.updatePlayerPosition(group.position);
}
}
// Sweep expired tracers (no-op until the cannon has actually fired).
this.tracerPool?.update();
}
dispose(): void {
for (const [id, group] of this.groups) {
if (this.collisionRegistered.has(id)) {
this.terrainManager?.unregisterCollisionObject(id);
}
this.scene.remove(group);
group.traverse((node) => {
if (!(node instanceof THREE.Mesh)) {
return;
}
if (node.userData.generatedMergedGeometry === true) {
node.geometry.dispose();
if (Array.isArray(node.material)) {
node.material.forEach((material) => material.dispose());
} else {
node.material.dispose();
}
}
});
this.animation.dispose(id);
}
this.groups.clear();
this.runtimes.clear();
this.configKeys.clear();
this.displayNames.clear();
this.collisionRegistered.clear();
this.spawnMetadata.clear();
this.lineupAircraft.clear();
this.simulating.clear();
this.weapons.clear();
this.tracerPool?.dispose();
this.tracerPool = undefined;
for (const pilot of this.npcPilots.values()) pilot.clearMission();
this.npcPilots.clear();
}
// -- Aircraft creation --
/**
* Create an interactive fixed-wing aircraft at a parking spot.
* Called by the airfield layout system instead of placing a static model.
*/
async createAircraftAtSpot(
id: string,
modelPath: string,
worldPosition: THREE.Vector3,
heading: number,
metadata?: FixedWingSpawnMetadata,
): Promise<boolean> {
const configKey = getFixedWingConfigKeyForModelPath(modelPath);
if (!configKey) {
Logger.warn('fixedwing', `No config for model path: ${modelPath}`);
return false;
}
const config = FIXED_WING_CONFIGS[configKey];
if (!config) {
Logger.warn('fixedwing', `No physics config for key: ${configKey}`);
return false;
}
const display = getFixedWingDisplayInfo(configKey);
if (!display) return false;
try {
const { scene: innerModel, animations } = await modelLoader.loadAnimatedModel(modelPath);
// Most GLBs face +Z but physics forward is -Z, so default to a 180° Y flip.
// Per-aircraft override (`modelYawOffset` on FixedWingDisplayInfo) handles
// GLBs authored facing -Z (e.g. A-1 Skyraider) — they override to 0.
innerModel.rotation.y = display.modelYawOffset ?? Math.PI;
this.optimizeLoadedAircraft(innerModel, configKey);
// Outer group is driven by physics quaternion (position + attitude).
// Inner model handles the visual-to-physics rotation offset.
const group = new THREE.Group();
group.add(innerModel);
group.position.copy(worldPosition);
// Ensure Y is on terrain (use physics gearClearance instead of hardcoded offset)
if (this.terrainManager) {
const h = this.terrainManager.getHeightAt(worldPosition.x, worldPosition.z);
group.position.y = h + config.physics.gearClearance;
worldPosition.y = h + config.physics.gearClearance;
}
this.scene.add(group);
this.groups.set(id, group);
this.configKeys.set(id, configKey);
this.displayNames.set(id, display.displayName);
if (metadata) {
this.spawnMetadata.set(id, {
standId: metadata.standId,
taxiRoute: metadata.taxiRoute.map((point) => point.clone()),
runwayStart: metadata.runwayStart
? {
id: metadata.runwayStart.id,
position: metadata.runwayStart.position.clone(),
heading: metadata.runwayStart.heading,
holdShortPosition: metadata.runwayStart.holdShortPosition?.clone(),
shortFinalDistance: metadata.runwayStart.shortFinalDistance,
shortFinalAltitude: metadata.runwayStart.shortFinalAltitude,
}
: undefined,
});
}
if (this.terrainManager) {
this.terrainManager.registerCollisionObject(id, group, { dynamic: true });
this.collisionRegistered.add(id);
}
// Build the airframe instance (starts parked on the ground).
const airframe = new Airframe(worldPosition.clone(), airframeConfigFromLegacy(config.physics));
// Set initial heading on the airframe quaternion.
const q = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), heading);
airframe.getQuaternion().copy(q);
// Sync group to initial physics state so parked aircraft face the right way.
group.quaternion.copy(q);
let worldHalfExtent = 0;
if (this.terrainManager) {
worldHalfExtent = this.terrainManager.getPlayableWorldSize() / 2;
airframe.setWorldHalfExtent(worldHalfExtent);
}
this.runtimes.set(id, {
airframe,
command: createIdleCommand(),
worldHalfExtent,
});
// Forward armament: each airframe pulls its own weapon config from the
// armament table (A-1 wing cannons, F-4 nose rotary, AC-47 broadside).
// US-owned (matching the adapter faction) so friend-or-foe filtering
// spares allies.
const weaponConfig = getFixedWingWeaponConfig(configKey);
this.weapons.set(id, {
config: weaponConfig,
ammo: weaponConfig.ammoCapacity,
cooldownRemaining: 0,
roundsSinceTracer: 0,
barrelIndex: 0,
isFiring: false,
faction: Faction.US,
});
// Wire animation on the inner model (where propeller nodes live)
this.animation.initialize(id, configKey, innerModel, animations);
// Register with VehicleManager
if (this.vehicleManager) {
const adapter = new FixedWingVehicleAdapter(id, configKey, Faction.US, this);
this.vehicleManager.register(adapter);
}
Logger.info('fixedwing', `Created ${display.displayName} at (${worldPosition.x.toFixed(0)}, ${worldPosition.z.toFixed(0)})`);
return true;
} catch (err) {
Logger.warn('fixedwing', `Failed to load model ${modelPath}: ${err}`);
return false;
}
}
private optimizeLoadedAircraft(innerModel: THREE.Group, configKey: string): void {
const display = getFixedWingDisplayInfo(configKey);
const propellerNames = new Set(
(display?.propellerNodes ?? []).map((name) => name.toLowerCase()),
);
const result = optimizeFixedWingStaticDrawCalls(innerModel, configKey, propellerNames);
if (result.sourceMeshCount > 0) {
Logger.info(
'fixedwing',
`Optimized ${configKey} draw calls: ${result.sourceMeshCount} leaf meshes -> ${result.mergedMeshCount} batches`,
);
}
}
// -- Player interaction --
tryEnterAircraft(): boolean {
return this.interaction.tryEnterAircraft();
}
getPlayerExitPlan(aircraftId: string | null, options: VehicleExitOptions = {}): VehicleExitPlan | null {
if (!aircraftId) {
return { canExit: false, message: 'Cannot find aircraft for exit.' };
}
const group = this.groups.get(aircraftId);
if (!group) {
return { canExit: false, message: 'Cannot find aircraft for exit.' };
}
const normalPosition = this.buildAircraftExitPosition(group, false);
if (options.force) {
return { canExit: true, mode: 'force_cleanup', position: normalPosition };
}
const flightData = this.getFlightData(aircraftId);
const configKey = this.configKeys.get(aircraftId);
const config = configKey ? FIXED_WING_CONFIGS[configKey] : null;
if (!flightData || !config) {
return { canExit: true, mode: 'normal', position: normalPosition };
}
const exitStatus = getFixedWingExitStatus({
weightOnWheels: flightData.weightOnWheels,
airspeed: flightData.airspeed,
altitudeAGL: flightData.altitudeAGL,
}, config);
if (exitStatus.canExit) {
return { canExit: true, mode: 'normal', position: normalPosition };
}
if (options.allowEject) {
return {
canExit: true,
mode: 'emergency_eject',
position: this.buildAircraftEjectionPosition(group),
message: 'Emergency bailout.',
};
}
return {
canExit: false,
message: exitStatus.message ?? 'Cannot exit aircraft yet.',
position: normalPosition,
};
}
exitAircraft(): void {
const exitRequester = this.playerController as (IPlayerController & VehicleExitRequester) | undefined;
if (typeof exitRequester?.requestVehicleExit === 'function') {
const result = exitRequester.requestVehicleExit({ allowEject: false, reason: 'fixed-wing-model' });
if (result.exited || result.reason === 'blocked') {
return;
}
}
if (this.pilotedAircraftId) {
const flightData = this.getFlightData(this.pilotedAircraftId);
const configKey = this.configKeys.get(this.pilotedAircraftId);
const config = configKey ? FIXED_WING_CONFIGS[configKey] : null;
if (flightData && config) {
const exitStatus = getFixedWingExitStatus({
weightOnWheels: flightData.weightOnWheels,
airspeed: flightData.airspeed,
altitudeAGL: flightData.altitudeAGL,
}, config);
if (!exitStatus.canExit) {
this.hudSystem?.showMessage(exitStatus.message ?? 'Cannot exit aircraft yet.', 2000);
return;
}
}
}
this.pilotedAircraftId = null;
this.currentCommand = createIdleCommand();
this.currentPilotIntent = createIdleFixedWingPilotIntent();
this.pilotIntentActive = false;
this.interaction.exitAircraft();
}
private buildAircraftExitPosition(group: THREE.Group, projectToGround: boolean): THREE.Vector3 {
const exitPosition = group.position.clone();
const rightVector = new THREE.Vector3(1, 0, 0).applyQuaternion(group.quaternion);
const aftVector = new THREE.Vector3(0, 0, 1).applyQuaternion(group.quaternion);
exitPosition.addScaledVector(rightVector, projectToGround ? 7 : 4);
if (projectToGround) {
exitPosition.addScaledVector(aftVector, 6);
}
if (this.terrainManager) {
const terrainHeight = this.terrainManager.getEffectiveHeightAt(exitPosition.x, exitPosition.z);
exitPosition.y = projectToGround
? terrainHeight + 1.5
: Math.max(exitPosition.y, terrainHeight + 1.5);
}
return exitPosition;
}
private buildAircraftEjectionPosition(group: THREE.Group): THREE.Vector3 {
const exitPosition = group.position.clone();
const rightVector = new THREE.Vector3(1, 0, 0).applyQuaternion(group.quaternion);
const aftVector = new THREE.Vector3(0, 0, 1).applyQuaternion(group.quaternion);
exitPosition.addScaledVector(rightVector, 7);
exitPosition.addScaledVector(aftVector, 6);
if (this.terrainManager) {
const terrainHeight = this.terrainManager.getEffectiveHeightAt(exitPosition.x, exitPosition.z);
exitPosition.y = Math.max(exitPosition.y, terrainHeight + 1.5);
}
return exitPosition;
}
setPilotedAircraft(aircraftId: string | null): void {
this.pilotedAircraftId = aircraftId;
this.currentCommand = createIdleCommand();
this.currentPilotIntent = createIdleFixedWingPilotIntent();
this.pilotIntentActive = false;
// Reset physics for parked aircraft to prevent stale micro-drift
if (aircraftId) {
const runtime = this.runtimes.get(aircraftId);
if (runtime) {
const snapshot = this.buildSnapshot(runtime);
if (snapshot.phase === 'parked') {
runtime.airframe.resetToGround(runtime.airframe.getPosition());
runtime.command = createIdleCommand();
if (runtime.worldHalfExtent > 0) {
runtime.airframe.setWorldHalfExtent(runtime.worldHalfExtent);
}
// Restore heading from the group quaternion
const group = this.groups.get(aircraftId);
if (group) {
runtime.airframe.getQuaternion().copy(group.quaternion);
}
}
}
}
}
setFixedWingCommand(command: FixedWingCommand): void {
this.pilotIntentActive = false;
this.currentCommand = { ...command };
}
setFixedWingControls(controls: { throttle: number; pitch: number; roll: number; yaw: number }): void {
this.pilotIntentActive = false;
this.currentCommand = {
throttleTarget: controls.throttle,
pitchCommand: controls.pitch,
rollCommand: controls.roll,
yawCommand: controls.yaw,
brake: 0,
freeLook: false,
stabilityAssist: false,
};
}
setFixedWingPilotIntent(intent: FixedWingPilotIntent): void {
this.currentPilotIntent = { ...intent };
this.pilotIntentActive = true;
}
// -- Forward armament --
/**
* Begin firing the airframe's gun for the given aircraft. Held trigger: the
* gun keeps firing each update while `isFiring` is set and ammo remains.
*/
startFiring(aircraftId: string): void {
const weapon = this.weapons.get(aircraftId);
if (weapon) weapon.isFiring = true;
}
stopFiring(aircraftId: string): void {
const weapon = this.weapons.get(aircraftId);
if (weapon) weapon.isFiring = false;
}
/**
* Number of armament installations the player fires as a unit. The fleet
* fires its barrels as one trigger group (round-robin), so this is 1 when an
* aircraft is armed — the multi-barrel detail is the table's, not the count's.
*/
getWeaponCount(aircraftId: string): number {
return this.weapons.has(aircraftId) ? 1 : 0;
}
/** Forward / broadside gun ammo remaining for this airframe. */
getWeaponAmmo(aircraftId: string): number {
return this.weapons.get(aircraftId)?.ammo ?? 0;
}
/** Gun magazine capacity (full load) for this airframe's armament. */
getWeaponAmmoCapacity(aircraftId: string): number {
return this.weapons.get(aircraftId)?.config.ammoCapacity ?? 0;
}
/** HUD-facing weapon name for this airframe's armament. */
getWeaponName(aircraftId: string): string {
return this.weapons.get(aircraftId)?.config.name ?? '';
}
/**
* Reads and clears the airborne-gate feedback flag: returns `true` once for
* each frame in which the player pulled the trigger while grounded (the gun
* fired nothing). The HUD polls this to flash a transient "Airborne to fire"
* hint so the silence is explained rather than mysterious. Consume-on-read so
* the hint naturally fades when the player stops trying or lifts off.
*/
consumeGroundedFireBlocked(): boolean {
const blocked = this.groundedFireBlocked;
this.groundedFireBlocked = false;
return blocked;
}
/**
* Advance the airframe's gun for one frame. Fires as many rounds as the
* fire-rate budget allows while the trigger is held, routing each shot
* through the shared combatant fire path so friend-or-foe filtering and
* damage resolution match the helicopter and player weapons. Fire geometry
* (origin / direction / spread / cadence / magazine) comes from the airframe
* armament table: A-1 and F-4 fire forward; the AC-47 fires its broadside
* battery 90° to the left of the nose. Only fires for airborne / moving
* aircraft (no ground strafing of the parking apron).
*/
private updateForwardGun(
aircraftId: string,
group: THREE.Group,
isAirborne: boolean,
deltaTime: number,
): void {
const weapon = this.weapons.get(aircraftId);
if (!weapon) return;
if (weapon.cooldownRemaining > 0) {
weapon.cooldownRemaining -= deltaTime;
}
// Holding the trigger on the ground produces no rounds (the gate below).
// Record it so the HUD can explain the silence with an "Airborne to fire"
// hint instead of leaving the player guessing whether the gun is broken.
if (weapon.isFiring && !isAirborne && weapon.ammo > 0) {
this.groundedFireBlocked = true;
}
if (!weapon.isFiring || !isAirborne || weapon.ammo <= 0) {
return;
}
if (!this.combatantSystem) {
return;
}
const gun = weapon.config;
const interval = 1 / gun.fireRate;
let rounds = 0;
// Fire as many rounds as the dt budget allows, capped against a runaway loop.
while (weapon.cooldownRemaining <= 0 && weapon.ammo > 0 && rounds < 32) {
weapon.cooldownRemaining += interval;
weapon.ammo--;
weapon.roundsSinceTracer++;
rounds++;
// Resolve muzzle origin + fire direction from the airframe armament table.
// Round-robins across the barrels (paired wing cannons / broadside trio).
computeFixedWingShot(
gun,
group.position,
group.quaternion,
weapon.barrelIndex,
_gunMuzzle,
_gunForward,
);
weapon.barrelIndex++;
this.applyGunSpread(_gunForward, gun.spreadDeg);
_gunRay.origin.copy(_gunMuzzle);
_gunRay.direction.copy(_gunForward);
const result = this.combatantSystem.handlePlayerShot(
_gunRay,
() => gun.damage,
'fixedwing_gun',
weapon.faction,
);
if (result.hit) {
this.combatantSystem.impactEffectsPool?.spawn(result.point, _gunForward);
}
if (weapon.roundsSinceTracer >= gun.tracerInterval) {
weapon.roundsSinceTracer = 0;
if (result.hit) {
_gunTracerEnd.copy(result.point);
} else {
_gunTracerEnd.copy(_gunMuzzle).addScaledVector(_gunForward, FIXED_WING_GUN_TRACER_RANGE);
}
this.ensureTracerPool().spawn(_gunMuzzle, _gunTracerEnd, 120);
}
}
}
/** Lazily create the shared tracer pool (only when something actually fires). */
private ensureTracerPool(): TracerPool {
if (!this.tracerPool) {
this.tracerPool = new TracerPool(this.scene, 24);
}
return this.tracerPool;
}
/** Apply a random cone spread to a normalized forward direction in place. */
private applyGunSpread(direction: THREE.Vector3, spreadDeg: number): void {
if (spreadDeg <= 0) return;
const spreadRad = (spreadDeg * Math.PI) / 180;
const angle = Math.random() * spreadRad;
const rotation = Math.random() * Math.PI * 2;
const up = _gunSpreadUp.set(0, 1, 0);
const right = _gunSpreadRight.crossVectors(direction, up);
if (right.lengthSq() < 0.001) {
up.set(1, 0, 0);
right.crossVectors(direction, up);
}
right.normalize();
up.crossVectors(right, direction).normalize();
direction
.addScaledVector(right, Math.sin(angle) * Math.cos(rotation))
.addScaledVector(up, Math.sin(angle) * Math.sin(rotation))
.normalize();
}
// -- NPC pilot hooks --
/**
* Attach an NPC pilot to an aircraft in this catalog. The pilot owns the
* aircraft's runtime command whenever the aircraft is not player-piloted.
* Returns false if the aircraftId is unknown.
*/
attachNPCPilot(aircraftId: string, mission: NPCPilotMission): boolean {
if (!this.runtimes.has(aircraftId)) {
return false;
}
const terrainProbe: NPCTerrainProbe | null = this.terrainManager
? { getHeightAt: (x: number, z: number) => this.terrainManager!.getHeightAt(x, z) }
: null;
const existing = this.npcPilots.get(aircraftId);
const pilot = existing ?? new NPCFixedWingPilot(undefined, terrainProbe);
pilot.setMission(mission);
this.npcPilots.set(aircraftId, pilot);
Logger.info('fixedwing', `NPC pilot attached to ${aircraftId} (mission.kind=${mission.kind})`);
return true;
}
detachNPCPilot(aircraftId: string): void {
const pilot = this.npcPilots.get(aircraftId);
if (!pilot) return;
pilot.clearMission();
this.npcPilots.delete(aircraftId);
}
getNPCPilot(aircraftId: string): NPCFixedWingPilot | null {
return this.npcPilots.get(aircraftId) ?? null;
}
// -- Queries --