File size: 16,741 Bytes
e4ffbe5
 
 
 
 
 
 
 
ea061d3
e4ffbe5
cc005aa
d7a80d5
e4ffbe5
 
cc005aa
f812939
 
e4ffbe5
 
 
 
 
cc005aa
 
f812939
 
cc005aa
565f6e7
cc005aa
 
 
 
 
 
 
 
 
 
 
 
f812939
cc005aa
f812939
cc005aa
f812939
 
 
cc005aa
 
f812939
cc005aa
 
 
 
 
 
 
 
 
f812939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc005aa
 
 
 
 
 
e4ffbe5
 
 
 
cc005aa
 
 
 
 
e4ffbe5
 
cc005aa
 
 
 
 
 
 
565f08b
 
 
 
 
 
 
c18c642
 
 
 
 
 
 
 
e4ffbe5
 
 
 
 
 
 
f812939
 
e4ffbe5
565f6e7
e4ffbe5
 
 
d7a80d5
 
 
 
 
 
 
 
e4ffbe5
f812939
 
 
e4ffbe5
 
cc005aa
 
f812939
 
 
 
 
 
cc005aa
 
 
e4ffbe5
 
 
 
 
 
 
cc005aa
 
 
 
 
 
e4ffbe5
 
 
 
 
 
 
 
 
 
cc005aa
 
 
 
 
 
 
 
 
565f08b
c18c642
 
e4ffbe5
 
 
 
 
 
cc005aa
e4ffbe5
 
 
 
 
 
cc005aa
e4ffbe5
 
 
 
 
 
 
 
 
cc005aa
e4ffbe5
 
 
 
 
 
 
 
ea061d3
 
 
 
e4ffbe5
 
ea061d3
cc005aa
 
 
 
 
 
 
e4ffbe5
 
 
cc005aa
565f6e7
e4ffbe5
 
c18c642
 
 
 
 
 
 
 
565f08b
 
c18c642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565f08b
 
e4ffbe5
 
 
d7a80d5
 
 
 
 
 
 
 
e4ffbe5
 
 
 
cc005aa
e4ffbe5
 
cc005aa
 
 
 
 
 
 
 
 
 
c18c642
 
 
 
 
 
 
565f08b
e4ffbe5
 
 
 
ea061d3
e4ffbe5
 
 
 
 
 
 
 
 
 
ea061d3
 
e4ffbe5
ea061d3
 
cc005aa
 
 
 
 
 
 
e4ffbe5
 
 
d7a80d5
 
 
 
 
 
 
 
e4ffbe5
 
 
 
 
ea061d3
 
e4ffbe5
ea061d3
e4ffbe5
 
 
 
 
 
ea061d3
e4ffbe5
 
 
 
 
 
 
 
cc005aa
 
e4ffbe5
 
 
cc005aa
 
 
 
 
 
 
 
 
e4ffbe5
 
 
 
cc005aa
 
 
e4ffbe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c18c642
 
 
 
565f6e7
c18c642
 
 
 
 
 
 
 
 
 
e4ffbe5
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import * as THREE from "three";
import { Vector3 } from "three";
import { Pilot, Projectile, GroundTarget, WeaponType, AmmoBelt } from "../types";
import { physical, destructible } from "../types/components";
import { WEAPON_SPECS_MAP } from "./aircraftData";
import { AIRCRAFT_DEFINITIONS } from "./content/aircraft/registry";
import { MODIFICATIONS } from "./content/modifications/modificationData";
import { FlightPhysicsEngine } from "./flightModel";
import { generateId, closestPointOnSegment, getPlaneHitRadius, LOCAL_FORWARD } from "./math";
import { getTerrainHeight } from "./terrainModel";
import { getCockpitDef } from "./content/aircraft/cockpitRegistry";
import { solveGunConvergenceLocal } from "./weaponConvergence";

function beltName(belt: AmmoBelt | string): string {
  return String(belt);
}

export function getProjectileReleaseState(
  pilot: Pilot,
  type: WeaponType,
  hardpointIndex?: number
): { position: Vector3; velocity: Vector3 } {
  const rotation = new THREE.Quaternion(pilot.qx, pilot.qy, pilot.qz, pilot.qw);
  const spec = WEAPON_SPECS_MAP[type];
  const aircraftDef = AIRCRAFT_DEFINITIONS.find(
    definition => definition.specs.id === pilot.aircraftId
  );
  const currentAmmo = pilot.ammo[type] ?? spec.ammoCapacity;
  const releasedCount = Math.max(0, spec.ammoCapacity - currentAmmo);
  const hardpointList =
    type === WeaponType.BOMB
      ? aircraftDef?.hardpoints.bombPositions
      : type === WeaponType.ROCKET
        ? aircraftDef?.hardpoints.rocketPositions
        : aircraftDef?.hardpoints.positions;
  const selectedHardpointIndex = hardpointIndex ?? releasedCount;
  const hardpoint = hardpointList?.length
    ? hardpointList[selectedHardpointIndex % hardpointList.length]
    : null;
  const hardpointLocal = hardpoint
    ? new Vector3(hardpoint.x, hardpoint.y, hardpoint.z)
    : LOCAL_FORWARD.clone().multiplyScalar(12);

  const position = new Vector3(pilot.x, pilot.y, pilot.z);
  position.add(hardpointLocal.clone().applyQuaternion(rotation));

  const velocity = new Vector3(pilot.vx, pilot.vy, pilot.vz);
  if (type === WeaponType.BOMB) {
    velocity.add(
      new Vector3(0, -1, 0)
        .applyQuaternion(rotation)
        .multiplyScalar(3.5)
    );
  } else {
    let directionLocal = LOCAL_FORWARD.clone();
    const convergenceM = aircraftDef?.hardpoints.gunConvergenceM;
    const cockpitDef = aircraftDef ? getCockpitDef(aircraftDef.specs.id) : undefined;
    if (
      type !== WeaponType.ROCKET &&
      hardpoint &&
      convergenceM !== undefined &&
      cockpitDef
    ) {
      directionLocal = solveGunConvergenceLocal(
        hardpointLocal,
        cockpitDef,
        convergenceM
      ).directionLocal;
    }
    const direction = directionLocal.applyQuaternion(rotation).normalize();
    velocity.addScaledVector(direction, spec.muzzleVelocity);
  }

  return { position, velocity };
}

export interface EngineCallbacks {
  registerKill: (killerId: string, victimId: string, weapon: string) => void;
  registerGroundTargetKill: (killerId: string, target: GroundTarget) => void;
  onProjectileSpawn?: (type: WeaponType) => void;
  onProjectileImpact?: (
    type: WeaponType,
    position: Vector3,
    ownerId: string
  ) => void;
  onGroundTargetDamage?: (targetId: string, hp: number, isDead: boolean) => void;
  onHitEnemy?: (killerId: string, targetId: string, isGround: boolean) => void;
  onPlayerDamage?: (
    shooterId: string,
    targetId: string,
    damage: number,
    bulletType: string,
    hitSpotLocal: Vector3
  ) => void;
  // Fires with the actual local-space impact offset in metres (not normalised)
  // so the voxel deformation system can destroy voxels in the right place.
  onVoxelHit?: (
    targetId: string,
    localOffsetMeters: Vector3,
    blastMeters: number
  ) => void;
  // Returns the centre of the first voxel struck by the segment in local aircraft
  // space, null if the aircraft uses voxels but the segment misses all of them,
  // or undefined if the aircraft has no voxel definition (use closest-point fallback).
  getVoxelImpact?: (
    targetId: string,
    segStartLocal: Vector3,
    segEndLocal: Vector3
  ) => THREE.Vector3 | null | undefined;
}

export class ProjectileSystem {
  public static spawnProjectile(
    pilot: Pilot,
    type: WeaponType,
    projectiles: Projectile[],
    onProjectileSpawn?: (type: WeaponType) => void,
    random: () => number = Math.random
  ) {
    const rot = new THREE.Quaternion(pilot.qx, pilot.qy, pilot.qz, pilot.qw);

    const spec = WEAPON_SPECS_MAP[type];

    let dispersionAmount = spec.dispersion;
    pilot.modifications?.forEach(modId => {
      const mod = MODIFICATIONS.find(m => m.id === modId);
      if (mod?.effects.dispersion !== undefined) {
        dispersionAmount *= (1 + mod.effects.dispersion);
      }
    });

    const spread = new THREE.Vector3(
      (random() - 0.5) * dispersionAmount,
      (random() - 0.5) * dispersionAmount,
      (random() - 0.5) * dispersionAmount
    ).applyQuaternion(rot);

    const release = getProjectileReleaseState(pilot, type);
    if (type !== WeaponType.BOMB) {
      const dir = release.velocity
        .clone()
        .sub(new Vector3(pilot.vx, pilot.vy, pilot.vz))
        .normalize()
        .add(spread)
        .normalize();
      release.velocity.set(pilot.vx, pilot.vy, pilot.vz)
        .addScaledVector(dir, spec.muzzleVelocity);
    }

    const projectile: Projectile = {
      id: generateId(),
      ownerId: pilot.id,
      ownerTeam: pilot.team,
      type,
      belt: pilot.ammoBelt,
      x: release.position.x,
      y: release.position.y,
      z: release.position.z,
      vx: release.velocity.x,
      vy: release.velocity.y,
      vz: release.velocity.z,
      life: type === WeaponType.ROCKET ? 4.5 : type === WeaponType.BOMB ? 7.0 : 1.8,
      isRocket: type === WeaponType.ROCKET || type === WeaponType.BOMB
    };

    if (pilot.id === "player" && onProjectileSpawn) {
      onProjectileSpawn(type);
    }

    projectiles.push(projectile);
  }
  
  private static lastPosTmp = new Vector3();
  private static currentPosTmp = new Vector3();
  private static targetPosTmp = new Vector3();
  private static closestTmp = new Vector3();
  private static localImpactWorldTmp = new Vector3();
  private static rotInvTmp = new THREE.Quaternion();
  private static eulerTmp = new THREE.Euler();
  private static relativeOffsetLocalTmp = new Vector3();
  private static localOffsetMetersTmp = new Vector3();
  private static localSegStartTmp = new Vector3();
  private static localSegEndTmp = new Vector3();

  public static updateProjectiles(
    dt: number,
    projectiles: Projectile[],
    pilots: Pilot[],
    groundTargets: GroundTarget[],
    mapId: string,
    callbacks: EngineCallbacks
  ) {
    for (let i = projectiles.length - 1; i >= 0; i--) {
      const p = projectiles[i];
      p.life -= dt;

      ProjectileSystem.lastPosTmp.set(p.x, p.y, p.z);

      if (p.type === WeaponType.BOMB) {
        p.vy -= 9.8 * dt;
      }

      p.x += p.vx * dt;
      p.y += p.vy * dt;
      p.z += p.vz * dt;

      ProjectileSystem.currentPosTmp.set(p.x, p.y, p.z);
      let hasHit = false;

      // Pilot check
      for (const target of pilots) {
        const epTarget = target as any;

        if (target.id === p.ownerId) continue;
        if (target.team === p.ownerTeam) continue;
        const tPhys = physical(target.entity);
        const tDestr = destructible(target.entity);
        const tDm = tDestr.damageModel!;
        if (tDm.fuselage <= 0) continue;
        if ((epTarget.invulnerableTimer ?? 0) > 0) continue;

        ProjectileSystem.targetPosTmp.set(tPhys.x, tPhys.y, tPhys.z);
        closestPointOnSegment(
          ProjectileSystem.lastPosTmp,
          ProjectileSystem.currentPosTmp,
          ProjectileSystem.targetPosTmp,
          ProjectileSystem.closestTmp
        );
        const distToPlaneCenter = ProjectileSystem.closestTmp.distanceTo(ProjectileSystem.targetPosTmp);
        const hitRadius = getPlaneHitRadius(target.specs);

        if (distToPlaneCenter < hitRadius) {
          ProjectileSystem.rotInvTmp
            .set(tPhys.qx, tPhys.qy, tPhys.qz, tPhys.qw)
            .invert();

          // Transform projectile segment endpoints into local aircraft space
          ProjectileSystem.localSegStartTmp
            .copy(ProjectileSystem.lastPosTmp)
            .sub(ProjectileSystem.targetPosTmp)
            .applyQuaternion(ProjectileSystem.rotInvTmp);
          ProjectileSystem.localSegEndTmp
            .copy(ProjectileSystem.currentPosTmp)
            .sub(ProjectileSystem.targetPosTmp)
            .applyQuaternion(ProjectileSystem.rotInvTmp);

          // Precise voxel traversal when the target aircraft has a voxel def.
          // getVoxelImpact returns:
          //   Vector3  → voxel aircraft, cell struck — use as impact centre
          //   null     → voxel aircraft, segment misses all cells — skip hit
          //   undefined→ no voxel def — fall back to closest-point method
          const voxResult = callbacks.getVoxelImpact?.(
            target.id,
            ProjectileSystem.localSegStartTmp,
            ProjectileSystem.localSegEndTmp
          );
          if (voxResult === null) break; // voxel aircraft, true miss

          if (voxResult !== undefined) {
            ProjectileSystem.localOffsetMetersTmp.copy(voxResult);
          } else {
            // Closest-point fallback for aircraft without voxel definitions
            ProjectileSystem.localImpactWorldTmp
              .copy(ProjectileSystem.closestTmp)
              .sub(ProjectileSystem.targetPosTmp);
            ProjectileSystem.localOffsetMetersTmp
              .copy(ProjectileSystem.localImpactWorldTmp)
              .applyQuaternion(ProjectileSystem.rotInvTmp);
          }

          ProjectileSystem.relativeOffsetLocalTmp
            .copy(ProjectileSystem.localOffsetMetersTmp)
            .divideScalar(hitRadius);

          let finalDmg = WEAPON_SPECS_MAP[p.type].damage;
          const owner = pilots.find(pl => pl.id === p.ownerId);
          owner?.modifications?.forEach(modId => {
            const mod = MODIFICATIONS.find(m => m.id === modId);
            if (mod?.effects.damage !== undefined) {
              finalDmg *= (1 + mod.effects.damage);
            }
          });

          const belt = beltName(p.belt);
          if (belt === "Armor-Piercing") finalDmg *= 1.3;
          if (belt === "Incendiary") finalDmg *= 0.85;

          FlightPhysicsEngine.applyDamage(target, finalDmg, String(p.type), ProjectileSystem.relativeOffsetLocalTmp);
          hasHit = true;

          if (callbacks.onPlayerDamage) {
            callbacks.onPlayerDamage(
              p.ownerId,
              target.id,
              finalDmg,
              String(p.type),
              ProjectileSystem.relativeOffsetLocalTmp
            );
          }

          // Voxel deformation — only fired when a specific cell was struck.
          // Blast radii are explicit per weapon type, not derived from damage values.
          if (voxResult !== undefined && callbacks.onVoxelHit) {
            const blastM =
              p.type === WeaponType.BOMB   ? 2.50 :
              p.type === WeaponType.ROCKET ? 0.75 : 0;
            callbacks.onVoxelHit(target.id, ProjectileSystem.localOffsetMetersTmp, blastM);
          }
          if (callbacks.onHitEnemy) {
            callbacks.onHitEnemy(p.ownerId, target.id, false);
          }

          if (tDm.fuselage <= 0) {
            callbacks.registerKill(p.ownerId, target.id, String(p.type));
          }

          break;
        }
      }

      // Ground target check
      if (!hasHit) {
        for (const target of groundTargets) {
          const gtDestr = destructible(target.entity);
          if (gtDestr.isDead || target.team === p.ownerTeam) continue;

          const gtPhys = physical(target.entity);
          ProjectileSystem.targetPosTmp.set(gtPhys.x, gtPhys.y, gtPhys.z);
          closestPointOnSegment(
            ProjectileSystem.lastPosTmp,
            ProjectileSystem.currentPosTmp,
            ProjectileSystem.targetPosTmp,
            ProjectileSystem.closestTmp
          );
          const distToTgt = ProjectileSystem.closestTmp.distanceTo(ProjectileSystem.targetPosTmp);

          if (distToTgt < 24) {
            let dmg = WEAPON_SPECS_MAP[p.type].damage;
            const owner = pilots.find(pl => pl.id === p.ownerId);
            owner?.modifications?.forEach(modId => {
              const mod = MODIFICATIONS.find(m => m.id === modId);
              if (mod?.effects.damage !== undefined) {
                dmg *= (1 + mod.effects.damage);
              }
            });

            const belt = beltName(p.belt);

            if (belt === "Armor-Piercing") dmg *= 1.8;
            if (p.type === WeaponType.BOMB) dmg *= 2.5;

            gtDestr.hp = Math.max(0, gtDestr.hp - dmg);
            if (gtDestr.hp <= 0) gtDestr.isDead = true;
            if (callbacks.onGroundTargetDamage) {
              callbacks.onGroundTargetDamage(target.id, gtDestr.hp, gtDestr.isDead);
            }
            if (callbacks.onHitEnemy) {
              callbacks.onHitEnemy(p.ownerId, target.id, true);
            }
            hasHit = true;

            if (gtDestr.isDead) {
              callbacks.registerGroundTargetKill(p.ownerId, target);
            }

            break;
          }
        }
      }

      const terrainHeight = getTerrainHeight(p.x, p.z, mapId).height;
      if (!hasHit && p.y <= Math.max(12, terrainHeight)) {
        hasHit = true;

        if (p.isRocket) {
          this.triggerSplashDamage(
            ProjectileSystem.currentPosTmp,
            p.ownerId,
            p.ownerTeam,
            p.type,
            groundTargets,
            pilots,
            callbacks
          );
        }
      }

      if (hasHit || p.life <= 0) {
        if (hasHit && callbacks.onProjectileImpact) {
          callbacks.onProjectileImpact(p.type, ProjectileSystem.currentPosTmp, p.ownerId);
        }
        projectiles.splice(i, 1);
      }
    }
  }

  public static triggerSplashDamage(
    epicenter: Vector3,
    ownerId: string,
    team: number,
    type: WeaponType,
    groundTargets: GroundTarget[],
    pilots: Pilot[],
    callbacks: EngineCallbacks
  ) {
    const splashRad = type === WeaponType.BOMB ? 180 : 70;
    const baseSplash = type === WeaponType.BOMB ? 350 : 150;

    groundTargets.forEach(t => {
      if (t.isDead || t.team === team) return;

      const d = epicenter.distanceTo(new Vector3(t.x, t.y, t.z));

      if (d < splashRad) {
        const falloff = 1 - d / splashRad;
        t.hp = Math.max(0, t.hp - baseSplash * falloff);

        if (t.hp <= 0) {
          t.isDead = true;
        }

        if (callbacks.onGroundTargetDamage) {
          callbacks.onGroundTargetDamage(t.id, t.hp, t.isDead);
        }

        if (callbacks.onHitEnemy) {
          callbacks.onHitEnemy(ownerId, t.id, true);
        }

        if (t.isDead) {
          callbacks.registerGroundTargetKill(ownerId, t);
        }
      }
    });

    pilots.forEach(p => {
      if (p.team === team) return;
      if (p.damage.fuselage <= 0) return;

      const ep = p as any;
      if ((ep.invulnerableTimer ?? 0) > 0) return;

      const d = epicenter.distanceTo(new Vector3(p.x, p.y, p.z));

      if (d < splashRad) {
        const falloff = 1 - d / splashRad;
        const relativeOffset = new Vector3(0, -0.5, 0);

        FlightPhysicsEngine.applyDamage(p, baseSplash * falloff, String(type), relativeOffset);

        if (callbacks.onVoxelHit) {
          // Blast arrives from the epicenter direction. Transform that vector
          // to local aircraft space and clamp to wing-tip distance so the
          // impact lands on a surface voxel rather than empty space.
          const rotInv = new THREE.Quaternion(p.qx, p.qy, p.qz, p.qw)
            .invert();
          const localDir = new Vector3(
            p.x - epicenter.x, p.y - epicenter.y, p.z - epicenter.z
          ).applyQuaternion(rotInv);
          const localLen = localDir.length();
          if (localLen > 7) localDir.multiplyScalar(7 / localLen);
          // Blast radius at the pilot scales with proximity: 0.3 m at splashRad edge, 2.5 m at centre
          const blastAtImpact = 0.3 + falloff * 2.2;
          callbacks.onVoxelHit(p.id, localDir, blastAtImpact);
        }
        if (callbacks.onHitEnemy) {
          callbacks.onHitEnemy(ownerId, p.id, false);
        }

        if (p.damage.fuselage <= 0) {
          callbacks.registerKill(ownerId, p.id, String(type));
        }
      }
    });
  }
}