Prompt Test

查看源码

下载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>PATROL — Autumn Lake Country Flight Toy</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=JetBrains+Mono:wght@500;700&display=swap" rel="stylesheet">
<style>
  * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    user-select: none;
    -webkit-user-select: none;
    touch-action: none;
  }
  html, body {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: #14101d;
    font-family: 'JetBrains Mono', monospace;
    color: #f4e8d8;
  }
  #stage {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    background: #1a1426;
  }
  canvas {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    image-rendering: -moz-crisp-edges;
    image-rendering: -webkit-crisp-edges;
    image-rendering: pixelated;
    image-rendering: crisp-edges;
    display: block;
  }
  #glCanvas { z-index: 1; }
  #hudCanvas { z-index: 2; pointer-events: none; }

  /* Loading Overlay */
  #loader {
    position: absolute;
    inset: 0;
    z-index: 30;
    background: #161122;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 18px;
    transition: opacity 0.45s steps(6);
  }
  #loader.hidden {
    opacity: 0;
    pointer-events: none;
  }
  .pixel-title {
    font-family: 'Press Start 2P', monospace;
    letter-spacing: 3px;
    text-shadow: 0 4px 0 #120c1c, 0 0 24px rgba(255, 166, 94, 0.35);
  }
  #loader .pixel-title {
    font-size: clamp(24px, 4vw, 42px);
    color: #ffb870;
  }
  #loaderStatus {
    font-size: 12px;
    color: #c8b6d4;
    letter-spacing: 1px;
    text-transform: uppercase;
  }
  .progress-frame {
    width: min(340px, 80vw);
    height: 22px;
    padding: 3px;
    background: #231b35;
    border: 2px solid #7d6896;
    box-shadow: 0 4px 0 #0d0914;
  }
  #progressBar {
    width: 0%;
    height: 100%;
    background: repeating-linear-gradient(
      90deg,
      #ff9f5a 0px,
      #ff9f5a 8px,
      #ffd08a 8px,
      #ffd08a 12px
    );
    transition: width 0.1s steps(12);
  }

  /* Title Card */
  #titleCard {
    position: absolute;
    top: 8%;
    left: 50%;
    transform: translateX(-50%);
    z-index: 15;
    text-align: center;
    pointer-events: none;
    transition: opacity 0.6s steps(6), transform 0.6s steps(6);
    background: rgba(20, 15, 32, 0.68);
    border: 2px solid rgba(255, 196, 138, 0.45);
    padding: 16px 26px 14px;
    box-shadow: 0 6px 0 rgba(10, 7, 18, 0.75);
  }
  #titleCard.faded {
    opacity: 0;
    transform: translateX(-50%) translateY(-10px);
  }
  #titleCard h1 {
    font-size: clamp(22px, 3.6vw, 36px);
    color: #ffc582;
    margin-bottom: 8px;
  }
  #titleCard .subtitle {
    font-size: clamp(10px, 1.3vw, 13px);
    color: #e6d7f0;
    letter-spacing: 1.5px;
    text-transform: uppercase;
    margin-bottom: 8px;
  }
  #titleCard .prompt {
    font-size: 11px;
    color: #9be8b8;
    animation: blinkStep 1.2s steps(2) infinite;
  }
  @keyframes blinkStep {
    0%, 49% { opacity: 1; }
    50%, 100% { opacity: 0.35; }
  }

  /* Bottom Control & Status Strip */
  #bottomBar {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 20;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 10px 14px;
    background: rgba(18, 14, 28, 0.82);
    border: 2px solid #594a70;
    padding: 7px 14px;
    box-shadow: 0 4px 0 rgba(8, 6, 14, 0.85);
    max-width: 96vw;
    font-size: 11px;
  }
  .hint-group {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #d6c8e3;
    white-space: nowrap;
  }
  .key-badge {
    display: inline-block;
    background: #2f2544;
    border: 1px solid #8673a1;
    color: #ffd394;
    padding: 1px 5px;
    font-weight: 700;
    font-size: 10px;
    margin-right: 3px;
  }
  .divider {
    width: 2px;
    height: 14px;
    background: #483b5c;
  }
  .missile-rack {
    display: flex;
    align-items: center;
    gap: 5px;
    color: #ffbe78;
    font-weight: 700;
  }
  .missile-pip {
    width: 8px;
    height: 14px;
    border: 1px solid #ffbe78;
    background: #ff8c42;
    position: relative;
  }
  .missile-pip.reloading {
    background: #282038;
    border-color: #6a5982;
  }
  .ui-btn {
    background: #2b223d;
    border: 2px solid #7d6999;
    color: #f7ead9;
    font-family: 'JetBrains Mono', monospace;
    font-size: 11px;
    font-weight: 700;
    padding: 3px 9px;
    cursor: pointer;
    box-shadow: 0 2px 0 #100c18;
    text-transform: uppercase;
  }
  .ui-btn:hover {
    background: #3b2f52;
    border-color: #ffb870;
    color: #ffd79e;
  }
  .ui-btn:active {
    transform: translateY(2px);
    box-shadow: none;
  }
  .ui-btn.active {
    background: #4e3729;
    border-color: #ff9d4d;
    color: #ffd399;
  }

  /* Touch Controls */
  #touchControls {
    position: absolute;
    inset: 0;
    z-index: 18;
    pointer-events: none;
    display: none;
  }
  #touchControls.visible {
    display: block;
  }
  #touchStickZone {
    position: absolute;
    left: 18px;
    bottom: 62px;
    width: 124px;
    height: 124px;
    border: 2px solid rgba(255, 198, 138, 0.42);
    background: rgba(20, 15, 32, 0.45);
    pointer-events: auto;
  }
  #touchStickKnob {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 34px;
    height: 34px;
    margin-left: -17px;
    margin-top: -17px;
    background: rgba(255, 178, 102, 0.75);
    border: 2px solid #fff0d8;
  }
  #touchButtons {
    position: absolute;
    right: 18px;
    bottom: 62px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    pointer-events: auto;
  }
  .touch-row {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
  }
  .touch-pad-btn {
    min-width: 66px;
    height: 48px;
    background: rgba(28, 21, 42, 0.78);
    border: 2px solid #9681b5;
    color: #ffe8c8;
    font-family: 'JetBrains Mono', monospace;
    font-weight: 700;
    font-size: 11px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 3px 0 rgba(10, 7, 16, 0.85);
  }
  .touch-pad-btn.pressed {
    background: rgba(214, 112, 48, 0.85);
    border-color: #ffe2b0;
    transform: translateY(2px);
  }
  @media (max-width: 780px) {
    .desktop-only { display: none; }
    #bottomBar { bottom: 6px; padding: 5px 10px; font-size: 10px; }
  }
</style>
</head>
<body>
<div id="stage">
  <canvas id="glCanvas"></canvas>
  <canvas id="hudCanvas"></canvas>

  <!-- World Generation Progress Screen -->
  <div id="loader">
    <div class="pixel-title">PATROL</div>
    <div id="loaderStatus">INITIALIZING TERRAIN SURVEY...</div>
    <div class="progress-frame">
      <div id="progressBar"></div>
    </div>
  </div>

  <!-- Title Overlay -->
  <div id="titleCard">
    <h1 class="pixel-title">PATROL</h1>
    <div class="subtitle">Autumn Lake Country &bull; Last Light</div>
    <div class="prompt">MOVE MOUSE OR TOUCH TO TAKE CONTROL</div>
  </div>

  <!-- Touch Overlay -->
  <div id="touchControls">
    <div id="touchStickZone">
      <div id="touchStickKnob"></div>
    </div>
    <div id="touchButtons">
      <div class="touch-row">
        <button class="touch-pad-btn" id="btnTouchView">VIEW</button>
        <button class="touch-pad-btn" id="btnTouchRoll">ROLL</button>
      </div>
      <div class="touch-row">
        <button class="touch-pad-btn" id="btnTouchBurn">BURN</button>
        <button class="touch-pad-btn" id="btnTouchFire">FIRE</button>
      </div>
    </div>
  </div>

  <!-- Quiet Bottom Strip -->
  <div id="bottomBar">
    <div class="hint-group desktop-only">
      <span><span class="key-badge">MOUSE</span>STEER</span>
      <span><span class="key-badge">LMB</span>ROLL / HOLD BURNER</span>
      <span><span class="key-badge">RMB/F</span>MISSILE</span>
      <span><span class="key-badge">SPACE</span>VIEW</span>
    </div>
    <div class="divider desktop-only"></div>
    <div class="missile-rack" title="Wing Rail Missiles">
      <span>MSL</span>
      <div class="missile-pip" id="msl0"></div>
      <div class="missile-pip" id="msl1"></div>
      <div class="missile-pip" id="msl2"></div>
      <div class="missile-pip" id="msl3"></div>
    </div>
    <div class="divider"></div>
    <button class="ui-btn" id="btnView">VIEW: CHASE</button>
    <button class="ui-btn" id="btnSound">SOUND: OFF</button>
  </div>
</div>

<script>
(() => {
  'use strict';

  // ============================================================================
  // 1. CONFIGURATION & PALETTE CONSTANTS
  // ============================================================================
  const MAP_SIZE = 512;          // Seamlessly tiling height/biome/shadow map resolution
  const WORLD_TILE_UNITS = 256.0; // World units per map tile (1 unit ≈ 35 meters)
  const SEA_LEVEL = 0.245;       // Water height threshold in normalized [0..1]
  const TERRAIN_HEIGHT_SCALE = 36.0;
  const CLOUD_BASE_Y = 23.0;
  const CLOUD_TOP_Y = 26.8;
  const BASE_TARGET_H = 340;     // Crisp ~340px internal vertical resolution

  // Fixed warm autumn sunset sun direction (normalized)
  const SUN_AZIMUTH = -0.68;     // WNW warm dusk sun
  const SUN_ELEVATION = 0.215;   // Low golden-hour angle (~12.4 deg)
  const SUN_DIR = normalize3([
    Math.cos(SUN_ELEVATION) * Math.sin(SUN_AZIMUTH),
    Math.sin(SUN_ELEVATION),
    Math.cos(SUN_ELEVATION) * Math.cos(SUN_AZIMUTH)
  ]);

  function normalize3(v) {
    const l = Math.hypot(v[0], v[1], v[2]) || 1;
    return [v[0] / l, v[1] / l, v[2] / l];
  }

  // ============================================================================
  // 2. PROCEDURAL WORLD GENERATION VIA INLINE WEB WORKER
  // ============================================================================
  const workerScript = `
    self.onmessage = function(e) {
      const size = e.data.size;
      const sunDir = e.data.sunDir;
      const heightScale = e.data.heightScale;
      const worldUnits = e.data.worldUnits;
      const seaLevel = e.data.seaLevel;

      const totalPixels = size * size;
      const data = new Uint8Array(totalPixels * 4);
      const heights = new Float32Array(totalPixels);
      const moisture = new Float32Array(totalPixels);

      // Seamless periodic permutation table
      const perm = new Uint8Array(512);
      let seed = 133742;
      function rand() {
        seed = (seed * 1664525 + 1013904223) >>> 0;
        return seed / 4294967296;
      }
      const p = new Uint8Array(256);
      for (let i = 0; i < 256; i++) p[i] = i;
      for (let i = 255; i > 0; i--) {
        const j = Math.floor(rand() * (i + 1));
        const tmp = p[i]; p[i] = p[j]; p[j] = tmp;
      }
      for (let i = 0; i < 512; i++) perm[i] = p[i & 255];

      function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); }
      function lerp(a, b, t) { return a + t * (b - a); }
      function grad(hash, x, y) {
        const h = hash & 7;
        const u = h < 4 ? x : y;
        const v = h < 4 ? y : x;
        return ((h & 1) ? -u : u) + ((h & 2) ? -2.0 * v : 2.0 * v);
      }

      // Tileable 2D Perlin noise with integer period
      function periodicNoise(x, y, period) {
        const xi = Math.floor(x);
        const yi = Math.floor(y);
        const xf = x - xi;
        const yf = y - yi;
        const u = fade(xf);
        const v = fade(yf);

        const x0 = ((xi % period) + period) % period;
        const x1 = (x0 + 1) % period;
        const y0 = ((yi % period) + period) % period;
        const y1 = (y0 + 1) % period;

        const aa = perm[perm[x0 & 255] + (y0 & 255)];
        const ab = perm[perm[x0 & 255] + (y1 & 255)];
        const ba = perm[perm[x1 & 255] + (y0 & 255)];
        const bb = perm[perm[x1 & 255] + (y1 & 255)];

        const x1Interp = lerp(grad(aa, xf, yf), grad(ba, xf - 1, yf), u);
        const x2Interp = lerp(grad(ab, xf, yf - 1), grad(bb, xf - 1, yf - 1), u);
        return lerp(x1Interp, x2Interp, v) * 0.45;
      }

      function fbmTile(u, v, basePeriod, octaves) {
        let sum = 0;
        let amp = 0.5;
        let freq = basePeriod;
        let norm = 0;
        for (let i = 0; i < octaves; i++) {
          sum += amp * periodicNoise(u * freq, v * freq, freq);
          norm += amp;
          amp *= 0.5;
          freq *= 2;
        }
        return (sum / norm) * 0.5 + 0.5;
      }

      function ridgedTile(u, v, basePeriod, octaves) {
        let sum = 0;
        let amp = 0.5;
        let freq = basePeriod;
        let weight = 1.0;
        let norm = 0;
        for (let i = 0; i < octaves; i++) {
          let n = periodicNoise(u * freq, v * freq, freq);
          n = 1.0 - Math.abs(n * 1.8);
          n = Math.max(0, n);
          n = n * n * weight;
          weight = Math.min(1.0, Math.max(0.0, n * 1.9));
          sum += n * amp;
          norm += amp;
          amp *= 0.5;
          freq *= 2;
        }
        return sum / norm;
      }

      // Pass 1: Lake basins, rolling hills, and rugged peaks
      for (let y = 0; y < size; y++) {
        if ((y & 63) === 0) {
          self.postMessage({ type: 'progress', pct: Math.round((y / size) * 45), label: 'SCULPTING LAKE BASINS & RIDGES...' });
        }
        const v = y / size;
        for (let x = 0; x < size; x++) {
          const u = x / size;
          const idx = y * size + x;

          // Broad lake country basins + islands
          const lakes = fbmTile(u + 0.13, v + 0.27, 3, 4);
          const hills = fbmTile(u + 0.61, v + 0.42, 6, 4);
          const ridge = ridgedTile(u + 0.05, v + 0.81, 4, 5);
          const detail = fbmTile(u, v, 16, 3);

          // Combine into an expressive lake-country height profile
          let h = lakes * 0.56 + hills * 0.24 + (detail - 0.5) * 0.06;
          // Carve interconnected lake channels and archipelagos
          const lakeMask = Math.max(0, (lakes - 0.36) / 0.64);
          h = h * 0.55 + lakeMask * 0.45;
          // Push mountain chains up where ridge & macro elevation align
          const mountainFactor = Math.max(0, (lakes - 0.46) * 2.1);
          h += ridge * ridge * mountainFactor * 0.72;

          // Subtle terracing on mid-high slopes for stylized contour character
          if (h > seaLevel + 0.03 && h < 0.75) {
            const steps = 26.0;
            const th = Math.floor(h * steps) / steps;
            h = lerp(h, th, 0.22);
          }

          h = Math.max(0.02, Math.min(0.99, h));
          heights[idx] = h;

          // Foliage patch & autumn biome variation
          const patchA = fbmTile(u + 0.31, v + 0.19, 8, 3);
          const patchB = fbmTile(u + 0.77, v + 0.63, 24, 2);
          moisture[idx] = Math.max(0, Math.min(1, patchA * 0.72 + patchB * 0.28));
        }
      }

      // Pass 2: Precompute long baked sun shadows & ambient occlusion
      const texelWorld = worldUnits / size;
      const stepDist = texelWorld * 1.15;
      const maxSteps = 96;
      const sunStepX = (sunDir[0] * stepDist) / worldUnits;
      const sunStepZ = (sunDir[2] * stepDist) / worldUnits;
      const sunStepH = (sunDir[1] * stepDist) / heightScale;

      for (let y = 0; y < size; y++) {
        if ((y & 63) === 0) {
          self.postMessage({ type: 'progress', pct: 45 + Math.round((y / size) * 52), label: 'BAKING AUTUMN SUN SHADOWS...' });
        }
        const v0 = (y + 0.5) / size;
        for (let x = 0; x < size; x++) {
          const idx = y * size + x;
          const h0 = Math.max(heights[idx], seaLevel);
          const u0 = (x + 0.5) / size;

          let su = u0;
          let sv = v0;
          let sh = h0 + 0.0025;
          let shadow = 1.0;

          for (let s = 1; s <= maxSteps; s++) {
            su += sunStepX;
            sv += sunStepZ;
            sh += sunStepH;
            if (sh >= 1.0) break;

            const sx = (((Math.floor(su * size)) % size) + size) % size;
            const sy = (((Math.floor(sv * size)) % size) + size) % size;
            const sampleH = heights[sy * size + sx];
            if (sampleH > sh) {
              shadow = 0.0;
              break;
            }
          }

          // Local valley AO from 4 neighbors
          const xm = (x - 1 + size) % size;
          const xp = (x + 1) % size;
          const ym = (y - 1 + size) % size;
          const yp = (y + 1) % size;
          const avgN = (heights[y * size + xm] + heights[y * size + xp] + heights[ym * size + x] + heights[yp * size + x]) * 0.25;
          const ao = Math.max(0.25, Math.min(1.0, 0.85 + (heights[idx] - avgN) * 6.5));

          const off = idx * 4;
          data[off]     = Math.round(heights[idx] * 255);
          data[off + 1] = Math.round(moisture[idx] * 255);
          data[off + 2] = Math.round(shadow * 255);
          data[off + 3] = Math.round(ao * 255);
        }
      }

      self.postMessage({ type: 'done', data: data.buffer }, [data.buffer]);
    };
  `;

  function buildWorldTexture() {
    return new Promise((resolve) => {
      const blob = new Blob([workerScript], { type: 'application/javascript' });
      const url = URL.createObjectURL(blob);
      const worker = new Worker(url);
      const progressBar = document.getElementById('progressBar');
      const loaderStatus = document.getElementById('loaderStatus');

      worker.onmessage = (e) => {
        if (e.data.type === 'progress') {
          progressBar.style.width = e.data.pct + '%';
          loaderStatus.textContent = e.data.label;
        } else if (e.data.type === 'done') {
          progressBar.style.width = '100%';
          loaderStatus.textContent = 'LAUNCHING PATROL...';
          const raw = new Uint8Array(e.data.data);
          worker.terminate();
          URL.revokeObjectURL(url);
          resolve(raw);
        }
      };

      worker.postMessage({
        size: MAP_SIZE,
        sunDir: SUN_DIR,
        heightScale: TERRAIN_HEIGHT_SCALE,
        worldUnits: WORLD_TILE_UNITS,
        seaLevel: SEA_LEVEL
      });
    });
  }

  // ============================================================================
  // 3. WEB AUDIO SYNTHESIZER (OFF BY DEFAULT)
  // ============================================================================
  class SoundEngine {
    constructor() {
      this.ctx = null;
      this.enabled = false;
      this.master = null;
      this.jetGain = null;
      this.jetOsc1 = null;
      this.jetOsc2 = null;
      this.burnerGain = null;
      this.burnerFilter = null;
      this.windGain = null;
      this.windFilter = null;
      this.warnCooldown = 0;
    }

    init() {
      if (this.ctx) return;
      const AudioCtx = window.AudioContext || window.webkitAudioContext;
      if (!AudioCtx) return;
      this.ctx = new AudioCtx();

      this.master = this.ctx.createGain();
      this.master.gain.value = 0.0;
      this.master.connect(this.ctx.destination);

      // Shared white/pink noise buffer
      const bufSize = this.ctx.sampleRate * 2;
      const noiseBuf = this.ctx.createBuffer(1, bufSize, this.ctx.sampleRate);
      const out = noiseBuf.getChannelData(0);
      let b0 = 0, b1 = 0, b2 = 0;
      for (let i = 0; i < bufSize; i++) {
        const w = Math.random() * 2 - 1;
        b0 = 0.99765 * b0 + w * 0.099046;
        b1 = 0.96300 * b1 + w * 0.2965164;
        b2 = 0.57000 * b2 + w * 1.0526913;
        out[i] = (b0 + b1 + b2 + w * 0.1848) * 0.15;
      }

      // 1. Twin turbine hum
      this.jetGain = this.ctx.createGain();
      this.jetGain.gain.value = 0.11;
      const jetFilter = this.ctx.createBiquadFilter();
      jetFilter.type = 'lowpass';
      jetFilter.frequency.value = 340;

      this.jetOsc1 = this.ctx.createOscillator();
      this.jetOsc1.type = 'sawtooth';
      this.jetOsc1.frequency.value = 88;
      this.jetOsc2 = this.ctx.createOscillator();
      this.jetOsc2.type = 'triangle';
      this.jetOsc2.frequency.value = 177.5;

      this.jetOsc1.connect(jetFilter);
      this.jetOsc2.connect(jetFilter);
      jetFilter.connect(this.jetGain);
      this.jetGain.connect(this.master);
      this.jetOsc1.start();
      this.jetOsc2.start();

      // 2. Afterburner roar (filtered noise)
      const burnSrc = this.ctx.createBufferSource();
      burnSrc.buffer = noiseBuf;
      burnSrc.loop = true;
      this.burnerFilter = this.ctx.createBiquadFilter();
      this.burnerFilter.type = 'bandpass';
      this.burnerFilter.frequency.value = 140;
      this.burnerFilter.Q.value = 0.7;
      this.burnerGain = this.ctx.createGain();
      this.burnerGain.gain.value = 0.04;
      burnSrc.connect(this.burnerFilter);
      this.burnerFilter.connect(this.burnerGain);
      this.burnerGain.connect(this.master);
      burnSrc.start();

      // 3. Airframe wind rush
      const windSrc = this.ctx.createBufferSource();
      windSrc.buffer = noiseBuf;
      windSrc.loop = true;
      this.windFilter = this.ctx.createBiquadFilter();
      this.windFilter.type = 'bandpass';
      this.windFilter.frequency.value = 520;
      this.windFilter.Q.value = 1.4;
      this.windGain = this.ctx.createGain();
      this.windGain.gain.value = 0.04;
      windSrc.connect(this.windFilter);
      this.windFilter.connect(this.windGain);
      this.windGain.connect(this.master);
      windSrc.start();
    }

    toggle() {
      this.init();
      if (!this.ctx) return false;
      if (this.ctx.state === 'suspended') this.ctx.resume();
      this.enabled = !this.enabled;
      const now = this.ctx.currentTime;
      this.master.gain.setTargetAtTime(this.enabled ? 0.34 : 0.0, now, 0.06);
      if (this.enabled) this.playUiClick();
      return this.enabled;
    }

    update(dt, speedNorm, burnerAmt, isCockpit, pullUpWarn) {
      if (!this.ctx || !this.enabled) return;
      const now = this.ctx.currentTime;
      const muffling = isCockpit ? 0.62 : 1.0;

      const baseFreq = 82 + speedNorm * 42 + burnerAmt * 28;
      this.jetOsc1.frequency.setTargetAtTime(baseFreq, now, 0.08);
      this.jetOsc2.frequency.setTargetAtTime(baseFreq * 2.02, now, 0.08);
      this.jetGain.gain.setTargetAtTime((0.08 + speedNorm * 0.06) * muffling, now, 0.08);

      this.burnerFilter.frequency.setTargetAtTime(130 + burnerAmt * 240, now, 0.06);
      this.burnerGain.gain.setTargetAtTime((0.03 + burnerAmt * 0.28) * muffling, now, 0.06);

      this.windFilter.frequency.setTargetAtTime(420 + speedNorm * 580, now, 0.1);
      this.windGain.gain.setTargetAtTime((0.02 + speedNorm * 0.09) * muffling, now, 0.1);

      if (this.warnCooldown > 0) this.warnCooldown -= dt;
      if (pullUpWarn && this.warnCooldown <= 0) {
        this.warnCooldown = 0.55;
        this.playWarningBeep();
      }
    }

    playUiClick() {
      if (!this.ctx || !this.enabled) return;
      const now = this.ctx.currentTime;
      const osc = this.ctx.createOscillator();
      const g = this.ctx.createGain();
      osc.type = 'square';
      osc.frequency.setValueAtTime(660, now);
      osc.frequency.setValueAtTime(990, now + 0.03);
      g.gain.setValueAtTime(0.08, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.07);
      osc.connect(g);
      g.connect(this.master);
      osc.start(now);
      osc.stop(now + 0.075);
    }

    playWarningBeep() {
      if (!this.ctx || !this.enabled) return;
      const now = this.ctx.currentTime;
      const osc = this.ctx.createOscillator();
      const g = this.ctx.createGain();
      osc.type = 'square';
      osc.frequency.setValueAtTime(880, now);
      osc.frequency.setValueAtTime(620, now + 0.09);
      g.gain.setValueAtTime(0.09, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.18);
      osc.connect(g);
      g.connect(this.master);
      osc.start(now);
      osc.stop(now + 0.19);
    }

    playMissileLaunch() {
      if (!this.ctx || !this.enabled) return;
      const now = this.ctx.currentTime;
      // Sharp ignition pop + descending rocket hiss
      const osc = this.ctx.createOscillator();
      const g = this.ctx.createGain();
      osc.type = 'sawtooth';
      osc.frequency.setValueAtTime(320, now);
      osc.frequency.exponentialRampToValueAtTime(75, now + 0.42);
      g.gain.setValueAtTime(0.22, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.45);
      osc.connect(g);
      g.connect(this.master);
      osc.start(now);
      osc.stop(now + 0.46);
    }

    playExplosion(isWater, dist) {
      if (!this.ctx || !this.enabled) return;
      const atten = Math.max(0.08, Math.min(1.0, 42.0 / (dist + 18.0)));
      const now = this.ctx.currentTime;
      const osc = this.ctx.createOscillator();
      const g = this.ctx.createGain();
      osc.type = isWater ? 'triangle' : 'sawtooth';
      osc.frequency.setValueAtTime(isWater ? 140 : 105, now);
      osc.frequency.exponentialRampToValueAtTime(24, now + 0.75);
      g.gain.setValueAtTime(0.38 * atten, now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.78);
      osc.connect(g);
      g.connect(this.master);
      osc.start(now);
      osc.stop(now + 0.8);
    }
  }

  const sound = new SoundEngine();

  // ============================================================================
  // 4. WEBGL2 SETUP & SHADERS (TERRAIN RAYMARCH + 3D FIGHTER + FX PARTICLES)
  // ============================================================================
  const glCanvas = document.getElementById('glCanvas');
  const gl = glCanvas.getContext('webgl2', {
    antialias: false,
    alpha: false,
    depth: true,
    powerPreference: 'high-performance'
  });

  if (!gl) {
    document.getElementById('loaderStatus').textContent = 'WEBGL2 NOT SUPPORTED IN THIS BROWSER';
    return;
  }

  function compileShader(type, src) {
    const sh = gl.createShader(type);
    gl.shaderSource(sh, src);
    gl.compileShader(sh);
    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
      console.error('Shader compile error:', gl.getShaderInfoLog(sh));
      gl.deleteShader(sh);
      return null;
    }
    return sh;
  }

  function createProgram(vsSrc, fsSrc) {
    const vs = compileShader(gl.VERTEX_SHADER, vsSrc);
    const fs = compileShader(gl.FRAGMENT_SHADER, fsSrc);
    const prog = gl.createProgram();
    gl.attachShader(prog, vs);
    gl.attachShader(prog, fs);
    gl.linkProgram(prog);
    if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
      console.error('Program link error:', gl.getProgramInfoLog(prog));
      return null;
    }
    return prog;
  }

  // --------------------------------------------------------------------------
  // 4A. WORLD RAY-MARCHER SHADER (Autumn Lake Country + Clouds + Sky + Depth)
  // --------------------------------------------------------------------------
  const worldVS = `#version 300 es
    layout(location = 0) in vec2 aPos;
    out vec2 vUv;
    void main() {
      vUv = aPos * 0.5 + 0.5;
      gl_Position = vec4(aPos, 0.9999, 1.0);
    }
  `;

  const worldFS = `#version 300 es
    precision highp float;

    in vec2 vUv;
    out vec4 fragColor;

    uniform sampler2D uWorldMap;
    uniform vec3 uCamPos;
    uniform vec3 uCamRight;
    uniform vec3 uCamUp;
    uniform vec3 uCamFwd;
    uniform float uTanHalfFov;
    uniform float uAspect;
    uniform float uTime;
    uniform vec3 uSunDir;
    uniform vec3 uJetPos;
    uniform float uJetYaw;
    uniform mat4 uViewProj;

    const float WORLD_TILE = ${WORLD_TILE_UNITS.toFixed(1)};
    const float HEIGHT_SCALE = ${TERRAIN_HEIGHT_SCALE.toFixed(1)};
    const float SEA_LEVEL = ${SEA_LEVEL.toFixed(4)};
    const float WATER_Y = SEA_LEVEL * HEIGHT_SCALE;
    const float CLOUD_BOT = ${CLOUD_BASE_Y.toFixed(1)};
    const float CLOUD_TOP = ${CLOUD_TOP_Y.toFixed(1)};

    // 4x4 Bayer ordered dithering matrix
    float bayer4x4(vec2 px) {
      int x = int(mod(px.x, 4.0));
      int y = int(mod(px.y, 4.0));
      int idx = y * 4 + x;
      const float m[16] = float[16](
         0.0/16.0,  8.0/16.0,  2.0/16.0, 10.0/16.0,
        12.0/16.0,  4.0/16.0, 14.0/16.0,  6.0/16.0,
         3.0/16.0, 11.0/16.0,  1.0/16.0,  9.0/16.0,
        15.0/16.0,  7.0/16.0, 13.0/16.0,  5.0/16.0
      );
      return m[idx] - 0.5;
    }

    float hash21(vec2 p) {
      p = fract(p * vec2(123.34, 456.21));
      p += dot(p, p + 45.32);
      return fract(p.x * p.y);
    }

    float vnoise(vec2 p) {
      vec2 i = floor(p);
      vec2 f = fract(p);
      f = f * f * (3.0 - 2.0 * f);
      float a = hash21(i);
      float b = hash21(i + vec2(1.0, 0.0));
      float c = hash21(i + vec2(0.0, 1.0));
      float d = hash21(i + vec2(1.0, 1.0));
      return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
    }

    // Puff cumulus cloud density field (drifting slowly with wind)
    float cloudDensity(vec2 xz) {
      vec2 p = xz * 0.017 + vec2(uTime * 0.0032, uTime * 0.0014);
      float n1 = vnoise(p);
      float n2 = vnoise(p * 2.15 + vec2(3.7, 1.9));
      float n3 = vnoise(p * 4.6 - vec2(1.2, 5.4));
      float c = n1 * 0.58 + n2 * 0.28 + n3 * 0.14;
      return smoothstep(0.55, 0.77, c);
    }

    vec4 sampleMap(vec2 xz) {
      return texture(uWorldMap, xz / WORLD_TILE);
    }

    float terrainHeight(vec2 xz) {
      return sampleMap(xz).r * HEIGHT_SCALE;
    }

    vec3 terrainNormal(vec2 xz) {
      float eps = 0.55;
      float hL = terrainHeight(xz - vec2(eps, 0.0));
      float hR = terrainHeight(xz + vec2(eps, 0.0));
      float hD = terrainHeight(xz - vec2(0.0, eps));
      float hU = terrainHeight(xz + vec2(0.0, eps));
      return normalize(vec3(hL - hR, 2.0 * eps, hD - hU));
    }

    // Autumn dusk sky with sun disc, peach/lilac bands & high cirrus streaks
    vec3 evalSky(vec3 rd, vec2 px) {
      float up = clamp(rd.y, 0.0, 1.0);
      float sunAmt = max(dot(rd, uSunDir), 0.0);

      // Zenith to horizon base colors
      vec3 zenithCol = vec3(0.14, 0.16, 0.34);
      vec3 midSkyCol = vec3(0.38, 0.27, 0.48);
      vec3 horizonAway = vec3(0.68, 0.46, 0.62);  // Lilac away from sun
      vec3 horizonSun  = vec3(0.99, 0.66, 0.34);  // Warm gold toward sun

      float sunSide = smoothstep(-0.3, 0.9, dot(normalize(vec3(rd.x, 0.0, rd.z) + 1e-5), normalize(vec3(uSunDir.x, 0.0, uSunDir.z))));
      vec3 horizonCol = mix(horizonAway, horizonSun, sunSide);

      // Dithered vertical sky bands
      float d = bayer4x4(px) * 0.055;
      float hBand = clamp(pow(1.0 - up, 2.3) + d, 0.0, 1.0);
      float mBand = clamp(smoothstep(0.05, 0.58, up) + d, 0.0, 1.0);

      vec3 col = mix(horizonCol, midSkyCol, smoothstep(0.0, 0.45, up + d * 0.5));
      col = mix(col, zenithCol, mBand);

      // High thin cirrus streaks illuminated peach/gold
      if (rd.y > 0.02) {
        vec2 skyUV = rd.xz / (rd.y + 0.14);
        float streak = vnoise(skyUV * vec2(1.4, 5.2) + vec2(uTime * 0.004, 0.0));
        streak *= vnoise(skyUV * vec2(3.8, 12.0) - vec2(2.1, uTime * 0.002));
        float cirrus = smoothstep(0.34, 0.56, streak + d * 0.35) * smoothstep(0.02, 0.22, rd.y);
        vec3 cirrusCol = mix(vec3(0.84, 0.54, 0.62), vec3(1.0, 0.78, 0.50), sunSide);
        col = mix(col, cirrusCol, cirrus * 0.52);
      }

      // Warm solar glow & crisp pixelated sun disc
      col += vec3(1.0, 0.55, 0.24) * pow(sunAmt, 7.0) * 0.42;
      float sunDisc = step(0.9968, sunAmt);
      float sunInner = step(0.9985, sunAmt);
      col = mix(col, vec3(1.0, 0.74, 0.38), sunDisc);
      col = mix(col, vec3(1.0, 0.95, 0.78), sunInner);

      return col;
    }

    // Jet silhouette shadow projection onto ground or cloud deck
    float jetShadowFactor(vec3 worldPos) {
      vec3 toJet = uJetPos - worldPos;
      if (toJet.y <= 0.1) return 1.0;
      float t = toJet.y / max(uSunDir.y, 0.08);
      vec3 proj = worldPos + uSunDir * t;
      vec2 rel = proj.xz - uJetPos.xz;
      float c = cos(uJetYaw);
      float s = sin(uJetYaw);
      // Rotate into jet local XZ (forward = -Z in local)
      vec2 loc = vec2(rel.x * c - rel.y * s, rel.x * s + rel.y * c);
      // Fuselage + delta wing silhouette test
      float fuse = step(abs(loc.x), 0.24) * step(abs(loc.y), 1.35);
      float wingSpan = mix(1.25, 0.15, clamp((loc.y + 0.9) / 1.9, 0.0, 1.0));
      float wing = step(abs(loc.x), wingSpan) * step(abs(loc.y - 0.15), 0.75);
      return (fuse + wing > 0.0) ? 0.42 : 1.0;
    }

    void main() {
      vec2 px = floor(gl_FragCoord.xy);
      vec2 ndc = vUv * 2.0 - 1.0;
      vec3 rd = normalize(uCamFwd + ndc.x * uAspect * uTanHalfFov * uCamRight + ndc.y * uTanHalfFov * uCamUp);
      vec3 ro = uCamPos;

      float dither = bayer4x4(px);
      vec3 skyCol = evalSky(rd, px);

      // Ray-march parameters
      float maxDist = 340.0;
      float t = 0.2;
      bool hitTerrain = false;
      bool hitWater = false;
      float hitT = maxDist;

      // Cloud layer intersection check (analytic slab between CLOUD_BOT and CLOUD_TOP)
      bool hitCloud = false;
      float cloudT = maxDist;
      float cloudShade = 1.0;
      if (abs(rd.y) > 0.002) {
        float tBot = (CLOUD_BOT - ro.y) / rd.y;
        float tTop = (CLOUD_TOP - ro.y) / rd.y;
        float tEnter = min(tBot, tTop);
        float tExit  = max(tBot, tTop);
        if (tExit > 0.2 && tEnter < maxDist) {
          float tc = max(tEnter, 0.2);
          float cStep = max(0.65, (tExit - tc) / 8.0);
          for (int i = 0; i < 8; i++) {
            vec3 cp = ro + rd * tc;
            float dens = cloudDensity(cp.xz);
            float hFrac = clamp((cp.y - CLOUD_BOT) / (CLOUD_TOP - CLOUD_BOT), 0.0, 1.0);
            float dome = sin(hFrac * 3.14159);
            if (dens * dome > 0.28 + dither * 0.08) {
              hitCloud = true;
              cloudT = tc;
              // Stepped shading: bright peach top, warm salmon mid, violet-slate underside
              float sunLit = smoothstep(0.15, 0.85, hFrac + 0.15 * dot(rd, uSunDir));
              cloudShade = sunLit;
              break;
            }
            tc += cStep;
            if (tc > tExit) break;
          }
        }
      }

      // Terrain & Water ray-march
      if (rd.y < 0.22) {
        float dt = 0.35;
        for (int i = 0; i < 145; i++) {
          vec3 p = ro + rd * t;
          if (p.y > HEIGHT_SCALE + 2.0 && rd.y >= 0.0) break;

          float th = terrainHeight(p.xz);
          if (p.y <= WATER_Y && th < WATER_Y) {
            // Refine water plane hit
            float tWater = (WATER_Y - ro.y) / min(rd.y, -0.0005);
            hitWater = true;
            hitT = max(0.2, tWater);
            break;
          }
          if (p.y <= th) {
            // Binary refinement (4 steps) for crisp ridge silhouettes
            float tLo = t - dt;
            float tHi = t;
            for (int b = 0; b < 4; b++) {
              float tMid = 0.5 * (tLo + tHi);
              vec3 pm = ro + rd * tMid;
              if (pm.y <= terrainHeight(pm.xz)) tHi = tMid;
              else tLo = tMid;
            }
            hitTerrain = true;
            hitT = 0.5 * (tLo + tHi);
            break;
          }
          dt = max(0.32, t * 0.022);
          t += dt;
          if (t > maxDist) break;
        }
      }

      vec3 finalCol = skyCol;
      float sceneT = maxDist;

      if (hitWater || hitTerrain) {
        sceneT = hitT;
        vec3 pos = ro + rd * hitT;
        vec4 mapVal = sampleMap(pos.xz);
        float hNorm = mapVal.r;
        float moist = mapVal.g;
        float sunShadow = mapVal.b;
        float ao = mapVal.a;

        // Cloud shadow projected onto ground/water
        vec2 cloudShadowXZ = pos.xz + uSunDir.xz * ((CLOUD_BOT - pos.y) / max(uSunDir.y, 0.1));
        float underCloud = step(0.34, cloudDensity(cloudShadowXZ));
        float totalShadow = min(sunShadow, 1.0 - underCloud * 0.58);
        totalShadow *= jetShadowFactor(pos);

        if (hitWater) {
          float depth = clamp((SEA_LEVEL - hNorm) / SEA_LEVEL, 0.0, 1.0);
          // Stepped water depth palette: pale turquoise shallows -> teal -> cobalt -> deep navy
          float dStep = depth + dither * 0.09;
          vec3 wCol = vec3(0.06, 0.11, 0.25); // Deep navy
          if (dStep < 0.16) wCol = vec3(0.36, 0.64, 0.64);      // Pale turquoise shallows
          else if (dStep < 0.36) wCol = vec3(0.18, 0.42, 0.52); // Teal shelf
          else if (dStep < 0.64) wCol = vec3(0.10, 0.23, 0.40); // Mid lake blue

          // Animated shoreline foam bands
          float wave = sin(depth * 58.0 - uTime * 2.8 + vnoise(pos.xz * 1.8) * 3.0);
          float shoreFoam = step(depth, 0.095) * step(0.35 + dither * 0.25, wave * 0.5 + 0.5);
          wCol = mix(wCol, vec3(0.95, 0.92, 0.88), shoreFoam * 0.85);

          // Apply shadow tint
          wCol = mix(wCol * vec3(0.55, 0.52, 0.78), wCol, step(0.45, totalShadow + dither * 0.2));

          // Low-angle sky reflection (Fresnel)
          vec3 reflDir = reflect(rd, vec3(0.0, 1.0, 0.0));
          vec3 reflCol = evalSky(reflDir, px);
          float fresnel = pow(1.0 - max(-rd.y, 0.0), 3.4);
          wCol = mix(wCol, reflCol, clamp(fresnel * 0.78 + dither * 0.06, 0.0, 0.85));

          // Sun glitter path & short crisp white water glints
          float ripple = vnoise(pos.xz * vec2(3.5, 9.0) + vec2(uTime * 1.4, -uTime * 0.9));
          float ripple2 = vnoise(pos.xz * vec2(7.0, 14.0) - vec2(uTime * 1.1, uTime * 1.7));
          vec3 wNorm = normalize(vec3((ripple - 0.5) * 0.24, 1.0, (ripple2 - 0.5) * 0.24));
          vec3 halfVec = normalize(uSunDir - rd);
          float spec = pow(max(dot(wNorm, halfVec), 0.0), 42.0);
          float glitter = step(0.24, spec * totalShadow + dither * 0.08);
          float glint = step(0.86, ripple * ripple2 * totalShadow + dither * 0.05);
          wCol = mix(wCol, vec3(1.0, 0.86, 0.58), glitter);
          wCol = mix(wCol, vec3(1.0, 0.98, 0.92), glint * 0.85);

          finalCol = wCol;
        } else {
          // LAND SHADING
          vec3 n = terrainNormal(pos.xz);
          float slope = 1.0 - n.y;
          float elevAboveSea = hNorm - SEA_LEVEL;

          // Tree canopy micro-texture for autumn forest patches
          float canopy = vnoise(pos.xz * 5.5);
          float conifer = step(0.76, vnoise(pos.xz * 8.2 + vec2(4.1, 2.7)));

          vec3 albedo;
          if (elevAboveSea < 0.018 && slope < 0.25) {
            // Warm sandy lakeshore
            albedo = vec3(0.84, 0.72, 0.54);
          } else if (hNorm > 0.76 && slope < 0.36) {
            // Snow on highest peaks
            albedo = vec3(0.95, 0.93, 0.98);
          } else if (slope > 0.30 || hNorm > 0.67) {
            // Grey-violet exposed mountain rock
            albedo = mix(vec3(0.38, 0.34, 0.46), vec3(0.54, 0.49, 0.60), step(0.5, canopy + dither * 0.25));
          } else if (moist < 0.34) {
            // Pale golden-ochre autumn meadows
            albedo = mix(vec3(0.76, 0.67, 0.42), vec3(0.65, 0.58, 0.36), step(0.5, canopy + dither * 0.3));
          } else {
            // Autumn forest: orange, crimson, gold + scattered dark conifers
            float patchSel = fract(moist * 3.7 + canopy * 0.35 + dither * 0.14);
            if (conifer > 0.5) {
              albedo = vec3(0.14, 0.22, 0.22); // Dark pine/spruce
            } else if (patchSel < 0.34) {
              albedo = vec3(0.88, 0.44, 0.18); // Burnt orange maple
            } else if (patchSel < 0.66) {
              albedo = vec3(0.74, 0.20, 0.22); // Deep crimson oak
            } else {
              albedo = vec3(0.92, 0.68, 0.22); // Bright birch gold
            }
          }

          // Stepped 3-band lighting with warm dusk sunlight & cool violet shadows
          float ndotl = max(dot(n, uSunDir), 0.0);
          float lit = ndotl * totalShadow * (0.65 + 0.35 * ao);
          float band = lit + dither * 0.16;

          vec3 shadowTint = vec3(0.24, 0.20, 0.42); // Rich violet dusk shadow
          vec3 midTint    = vec3(0.72, 0.58, 0.64); // Warm lilac midtone
          vec3 sunTint    = vec3(1.16, 0.94, 0.74); // Golden low sun highlight

          vec3 lightCol = shadowTint;
          if (band > 0.44) lightCol = sunTint;
          else if (band > 0.16) lightCol = midTint;

          finalCol = albedo * lightCol;
        }
      }

      // Composite cumulus cloud layer if closer than terrain/water
      if (hitCloud && cloudT < sceneT) {
        sceneT = cloudT;
        float cStep = cloudShade + dither * 0.18;
        vec3 cloudCol = vec3(0.42, 0.34, 0.54);       // Violet-plum cloud base
        if (cStep > 0.56) cloudCol = vec3(1.0, 0.78, 0.62); // Warm peach sunlit top
        else if (cStep > 0.28) cloudCol = vec3(0.86, 0.57, 0.58); // Salmon mid-step
        finalCol = cloudCol;
      }

      // Horizon atmospheric haze: gold toward the sun, lilac away from it
      float fogFrac = clamp(pow(sceneT / maxDist, 1.35), 0.0, 1.0);
      float sunHazeSide = smoothstep(-0.35, 0.85, dot(normalize(vec3(rd.x, 0.0, rd.z) + 1e-5), normalize(vec3(uSunDir.x, 0.0, uSunDir.z))));
      vec3 hazeCol = mix(vec3(0.62, 0.46, 0.66), vec3(0.98, 0.68, 0.38), sunHazeSide);
      float ditherFog = step(0.5, fogFrac + dither * 0.14);
      finalCol = mix(finalCol, hazeCol, clamp(fogFrac * 0.82 + ditherFog * 0.14, 0.0, 1.0));

      // Output accurate hardware depth so 3D jet, missiles & particles occlude behind terrain/clouds
      if (sceneT < maxDist) {
        vec3 hitWorld = ro + rd * sceneT;
        vec4 clipPos = uViewProj * vec4(hitWorld, 1.0);
        float ndcDepth = clipPos.z / clipPos.w;
        gl_FragDepth = clamp(ndcDepth * 0.5 + 0.5, 0.0, 0.9999);
      } else {
        gl_FragDepth = 0.9999;
      }

      fragColor = vec4(finalCol, 1.0);
    }
  `;

  // --------------------------------------------------------------------------
  // 4B. 3D LOW-POLY FIGHTER MESH & INVERTED-HULL PIXEL OUTLINE SHADER
  // --------------------------------------------------------------------------
  const meshVS = `#version 300 es
    layout(location = 0) in vec3 aPos;
    layout(location = 1) in vec3 aNormal;
    layout(location = 2) in vec3 aColor;

    uniform mat4 uViewProj;
    uniform mat4 uModel;
    uniform float uOutlineExpand;

    out vec3 vNormal;
    out vec3 vColor;

    void main() {
      vec3 pos = aPos + aNormal * uOutlineExpand;
      vec4 worldPos = uModel * vec4(pos, 1.0);
      vNormal = mat3(uModel) * aNormal;
      vColor = aColor;
      gl_Position = uViewProj * worldPos;
    }
  `;

  const meshFS = `#version 300 es
    precision highp float;

    in vec3 vNormal;
    in vec3 vColor;
    out vec4 fragColor;

    uniform vec3 uSunDir;
    uniform bool uIsOutline;
    uniform float uBurnerGlow;

    float bayer4x4(vec2 px) {
      int x = int(mod(px.x, 4.0));
      int y = int(mod(px.y, 4.0));
      int idx = y * 4 + x;
      const float m[16] = float[16](
         0.0/16.0,  8.0/16.0,  2.0/16.0, 10.0/16.0,
        12.0/16.0,  4.0/16.0, 14.0/16.0,  6.0/16.0,
         3.0/16.0, 11.0/16.0,  1.0/16.0,  9.0/16.0,
        15.0/16.0,  7.0/16.0, 13.0/16.0,  5.0/16.0
      );
      return m[idx] - 0.5;
    }

    void main() {
      if (uIsOutline) {
        fragColor = vec4(0.08, 0.06, 0.13, 1.0);
        return;
      }

      // Emissive nozzle core detection (flagged via high red > 1.0)
      if (vColor.r > 1.01) {
        vec3 core = mix(vec3(1.0, 0.48, 0.14), vec3(1.0, 0.96, 0.82), uBurnerGlow);
        fragColor = vec4(core, 1.0);
        return;
      }

      vec3 n = normalize(vNormal);
      float ndotl = dot(n, uSunDir);
      float d = bayer4x4(floor(gl_FragCoord.xy)) * 0.12;
      float v = ndotl + d;

      // Crisp 3-tone flat shading with warm sun & violet shadow
      vec3 tone = vec3(0.46, 0.44, 0.62); // Shadow tone
      if (v > 0.25) tone = vec3(1.14, 0.98, 0.84); // Lit tone
      else if (v > -0.18) tone = vec3(0.82, 0.76, 0.86); // Mid tone

      fragColor = vec4(vColor * tone, 1.0);
    }
  `;

  // --------------------------------------------------------------------------
  // 4C. BILLBOARD / RIBBON PARTICLE SHADER (Trails, Plumes, Fireballs, Rings)
  // --------------------------------------------------------------------------
  const fxVS = `#version 300 es
    layout(location = 0) in vec3 aPos;
    layout(location = 1) in vec3 aColor;
    layout(location = 2) in float aAlpha;

    uniform mat4 uViewProj;
    out vec3 vColor;
    out float vAlpha;

    void main() {
      vColor = aColor;
      vAlpha = aAlpha;
      gl_Position = uViewProj * vec4(aPos, 1.0);
    }
  `;

  const fxFS = `#version 300 es
    precision highp float;

    in vec3 vColor;
    in float vAlpha;
    out vec4 fragColor;

    float bayer4x4(vec2 px) {
      int x = int(mod(px.x, 4.0));
      int y = int(mod(px.y, 4.0));
      int idx = y * 4 + x;
      const float m[16] = float[16](
         0.0/16.0,  8.0/16.0,  2.0/16.0, 10.0/16.0,
        12.0/16.0,  4.0/16.0, 14.0/16.0,  6.0/16.0,
         3.0/16.0, 11.0/16.0,  1.0/16.0,  9.0/16.0,
        15.0/16.0,  7.0/16.0, 13.0/16.0,  5.0/16.0
      );
      return m[idx];
    }

    void main() {
      // Ordered Bayer stipple transparency so particles stay crisp pixel-art
      if (vAlpha <= bayer4x4(floor(gl_FragCoord.xy)) + 0.02) discard;
      fragColor = vec4(vColor, 1.0);
    }
  `;

  const worldProg = createProgram(worldVS, worldFS);
  const meshProg  = createProgram(meshVS, meshFS);
  const fxProg    = createProgram(fxVS, fxFS);

  // Fullscreen quad VAO
  const quadVao = gl.createVertexArray();
  gl.bindVertexArray(quadVao);
  const quadBuf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, quadBuf);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
  gl.enableVertexAttribArray(0);
  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);

  // ============================================================================
  // 5. LOW-POLY TWIN-ENGINE, TWIN-TAIL FIGHTER & MISSILE GEOMETRY BUILDER
  // ============================================================================
  function createMeshBuilder() {
    const verts = []; // [x, y, z, nx, ny, nz, r, g, b]
    function addTri(a, b, c, col) {
      const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2];
      const vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
      const nx = uy * vz - uz * vy;
      const ny = uz * vx - ux * vz;
      const nz = ux * vy - uy * vx;
      const l = Math.hypot(nx, ny, nz) || 1;
      const n = [nx / l, ny / l, nz / l];
      for (const p of [a, b, c]) {
        verts.push(p[0], p[1], p[2], n[0], n[1], n[2], col[0], col[1], col[2]);
      }
    }
    function addQuad(a, b, c, d, col) {
      addTri(a, b, c, col);
      addTri(a, c, d, col);
    }
    function addMirrorTri(a, b, c, col) {
      addTri(a, b, c, col);
      addTri([-a[0], a[1], a[2]], [-c[0], c[1], c[2]], [-b[0], b[1], b[2]], col);
    }
    function addMirrorQuad(a, b, c, d, col) {
      addQuad(a, b, c, d, col);
      addQuad([-a[0], a[1], a[2]], [-d[0], d[1], d[2]], [-c[0], c[1], c[2]], [-b[0], b[1], b[2]], col);
    }
    return {
      verts,
      addTri,
      addQuad,
      addMirrorTri,
      addMirrorQuad,
      upload() {
        const vao = gl.createVertexArray();
        gl.bindVertexArray(vao);
        const buf = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, buf);
        const arr = new Float32Array(verts);
        gl.bufferData(gl.ARRAY_BUFFER, arr, gl.STATIC_DRAW);
        const stride = 9 * 4;
        gl.enableVertexAttribArray(0);
        gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, 0);
        gl.enableVertexAttribArray(1);
        gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, 3 * 4);
        gl.enableVertexAttribArray(2);
        gl.vertexAttribPointer(2, 3, gl.FLOAT, false, stride, 6 * 4);
        return { vao, count: verts.length / 9 };
      }
    };
  }

  function buildJetMesh() {
    const m = createMeshBuilder();
    // Palette: Splinter grey, slate blue-grey, dark radome, gold canopy, red fin caps, emissive nozzles
    const cLightGrey = [0.68, 0.72, 0.78];
    const cSlate     = [0.38, 0.44, 0.54];
    const cBelly     = [0.56, 0.62, 0.70];
    const cRadome    = [0.18, 0.20, 0.26];
    const cCanopy    = [0.96, 0.74, 0.26];
    const cRedCap    = [0.88, 0.22, 0.20];
    const cNozzle    = [0.22, 0.22, 0.28];
    const cGlow      = [1.50, 0.65, 0.20]; // > 1.0 triggers emissive shader branch

    // Forward nose is -Z (z = -1.65), tail nozzles at +Z (z = +1.35)
    const noseTip = [0, -0.02, -1.68];
    const rTop = [0, 0.11, -1.05], rSide = [0.14, 0.0, -1.05], rBot = [0, -0.09, -1.05];
    m.addMirrorTri(noseTip, rSide, rTop, cRadome);
    m.addMirrorTri(noseTip, rBot, rSide, cRadome);

    // Forward fuselage + intakes
    const fTop = [0, 0.17, -0.35], fSide = [0.25, 0.03, -0.35], fBot = [0.16, -0.12, -0.35];
    m.addMirrorQuad(rTop, rSide, fSide, fTop, cLightGrey);
    m.addMirrorQuad(rSide, rBot, fBot, fSide, cBelly);
    m.addTri(rBot, [-fBot[0], fBot[1], fBot[2]], fBot, cBelly);

    // Gold-tinted bubble canopy
    const cFront = [0, 0.16, -0.78];
    const cPeak  = [0, 0.30, -0.42];
    const cSide  = [0.12, 0.17, -0.45];
    const cRear  = [0, 0.19, -0.05];
    m.addMirrorTri(cFront, cSide, cPeak, cCanopy);
    m.addMirrorTri(cPeak, cSide, cRear, cCanopy);

    // Twin-engine wide spine & rear fuselage
    const aTop = [0.18, 0.16, 1.15], aSide = [0.29, 0.02, 1.15], aBot = [0.22, -0.11, 1.15];
    m.addMirrorQuad(fTop, fSide, aSide, aTop, cSlate);
    m.addQuad(fTop, [-fTop[0], fTop[1], fTop[2]], [-aTop[0], aTop[1], aTop[2]], aTop, cLightGrey);
    m.addMirrorQuad(fSide, fBot, aBot, aSide, cBelly);
    m.addQuad(fBot, [-fBot[0], fBot[1], fBot[2]], [-aBot[0], aBot[1], aBot[2]], aBot, cBelly);

    // Cropped delta wings (with splinter camo upper panels)
    const wRootF = [0.23, 0.04, -0.35];
    const wRootA = [0.27, 0.03,  0.88];
    const wMidF  = [0.82, 0.01,  0.22];
    const wMidA  = [0.82, 0.01,  0.85];
    const wTipF  = [1.42, -0.02, 0.56];
    const wTipA  = [1.42, -0.02, 0.88];
    const wBotOffset = -0.045;

    // Upper wing surfaces
    m.addMirrorQuad(wRootF, wMidF, wMidA, wRootA, cLightGrey);
    m.addMirrorQuad(wMidF, wTipF, wTipA, wMidA, cSlate);
    // Lower wing surfaces
    m.addMirrorQuad(
      [wRootF[0], wRootF[1] + wBotOffset, wRootF[2]],
      [wRootA[0], wRootA[1] + wBotOffset, wRootA[2]],
      [wMidA[0],  wMidA[1]  + wBotOffset, wMidA[2]],
      [wMidF[0],  wMidF[1]  + wBotOffset, wMidF[2]],
      cBelly
    );
    m.addMirrorQuad(
      [wMidF[0], wMidF[1] + wBotOffset, wMidF[2]],
      [wMidA[0], wMidA[1] + wBotOffset, wMidA[2]],
      [wTipA[0], wTipA[1] + wBotOffset, wTipA[2]],
      [wTipF[0], wTipF[1] + wBotOffset, wTipF[2]],
      cBelly
    );
    // Wing leading/trailing/tip edges
    m.addMirrorQuad(wRootF, [wRootF[0], wRootF[1]+wBotOffset, wRootF[2]], [wTipF[0], wTipF[1]+wBotOffset, wTipF[2]], wTipF, cSlate);
    m.addMirrorQuad(wTipF, [wTipF[0], wTipF[1]+wBotOffset, wTipF[2]], [wTipA[0], wTipA[1]+wBotOffset, wTipA[2]], wTipA, cRedCap);
    m.addMirrorQuad(wTipA, [wTipA[0], wTipA[1]+wBotOffset, wTipA[2]], [wRootA[0], wRootA[1]+wBotOffset, wRootA[2]], wRootA, cSlate);

    // Horizontal stabilators
    const hRootF = [0.26, 0.01, 0.90];
    const hRootA = [0.25, 0.01, 1.24];
    const hTipF  = [0.68, -0.02, 1.08];
    const hTipA  = [0.68, -0.02, 1.28];
    m.addMirrorQuad(hRootF, hTipF, hTipA, hRootA, cSlate);
    m.addMirrorQuad(
      [hRootF[0], -0.02, hRootF[2]],
      [hRootA[0], -0.02, hRootA[2]],
      [hTipA[0],  -0.05, hTipA[2]],
      [hTipF[0],  -0.05, hTipF[2]],
      cBelly
    );

    // Canted twin vertical fins with red tips
    const vBaseF = [0.21, 0.14, 0.62];
    const vBaseA = [0.21, 0.14, 1.18];
    const vMidF  = [0.34, 0.45, 0.92];
    const vMidA  = [0.34, 0.45, 1.24];
    const vTopF  = [0.38, 0.56, 1.02];
    const vTopA  = [0.38, 0.56, 1.26];
    m.addMirrorQuad(vBaseF, vMidF, vMidA, vBaseA, cLightGrey);
    m.addMirrorQuad(vBaseA, vMidA, vMidF, vBaseF, cSlate);
    m.addMirrorQuad(vMidF, vTopF, vTopA, vMidA, cRedCap);
    m.addMirrorQuad(vMidA, vTopA, vTopF, vMidF, cRedCap);

    // Twin engine nozzles + glowing exhaust cores
    for (const side of [-1, 1]) {
      const cx = side * 0.14;
      const cy = 0.02;
      const z0 = 1.15, z1 = 1.34;
      const r0 = 0.105, r1 = 0.088;
      const segs = 6;
      for (let i = 0; i < segs; i++) {
        const a0 = (i / segs) * Math.PI * 2;
        const a1 = ((i + 1) / segs) * Math.PI * 2;
        const p00 = [cx + Math.cos(a0) * r0, cy + Math.sin(a0) * r0, z0];
        const p10 = [cx + Math.cos(a1) * r0, cy + Math.sin(a1) * r0, z0];
        const p01 = [cx + Math.cos(a0) * r1, cy + Math.sin(a0) * r1, z1];
        const p11 = [cx + Math.cos(a1) * r1, cy + Math.sin(a1) * r1, z1];
        m.addQuad(p00, p01, p11, p10, cNozzle);
        m.addTri([cx, cy, z1 - 0.02], p11, p01, cGlow);
      }
    }

    return m.upload();
  }

  function buildMissileMesh() {
    const m = createMeshBuilder();
    const cBody = [0.90, 0.90, 0.92];
    const cTip  = [0.22, 0.24, 0.30];
    const cFin  = [0.85, 0.25, 0.20];
    const r = 0.032;
    m.addMirrorTri([0, 0, -0.48], [r, 0, -0.34], [0, r, -0.34], cTip);
    m.addMirrorTri([0, 0, -0.48], [0, -r, -0.34], [r, 0, -0.34], cTip);
    m.addMirrorQuad([0, r, -0.34], [r, 0, -0.34], [r, 0, 0.36], [0, r, 0.36], cBody);
    m.addMirrorQuad([r, 0, -0.34], [0, -r, -0.34], [0, -r, 0.36], [r, 0, 0.36], cBody);
    // Tail fins
    m.addMirrorTri([0, 0, 0.20], [0.09, 0.06, 0.36], [0.09, -0.06, 0.36], cFin);
    return m.upload();
  }

  const jetMesh = buildJetMesh();
  const missileMesh = buildMissileMesh();

  // Dynamic FX buffer
  const fxVao = gl.createVertexArray();
  gl.bindVertexArray(fxVao);
  const fxBuf = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, fxBuf);
  const MAX_FX_VERTS = 16000;
  const fxData = new Float32Array(MAX_FX_VERTS * 7); // x, y, z, r, g, b, alpha
  gl.bufferData(gl.ARRAY_BUFFER, fxData.byteLength, gl.DYNAMIC_DRAW);
  gl.enableVertexAttribArray(0);
  gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 7 * 4, 0);
  gl.enableVertexAttribArray(1);
  gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 7 * 4, 3 * 4);
  gl.enableVertexAttribArray(2);
  gl.vertexAttribPointer(2, 1, gl.FLOAT, false, 7 * 4, 6 * 4);

  // ============================================================================
  // 6. MATRIX & MATH UTILITIES
  // ============================================================================
  function mat4Perspective(fovY, aspect, near, far) {
    const f = 1.0 / Math.tan(fovY * 0.5);
    const nf = 1 / (near - far);
    return new Float32Array([
      f / aspect, 0, 0, 0,
      0, f, 0, 0,
      0, 0, (far + near) * nf, -1,
      0, 0, 2 * far * near * nf, 0
    ]);
  }

  function mat4LookAt(eye, target, up) {
    let zx = eye[0] - target[0], zy = eye[1] - target[1], zz = eye[2] - target[2];
    let len = Math.hypot(zx, zy, zz) || 1;
    zx /= len; zy /= len; zz /= len;

    let xx = up[1] * zz - up[2] * zy;
    let xy = up[2] * zx - up[0] * zz;
    let xz = up[0] * zy - up[1] * zx;
    len = Math.hypot(xx, xy, xz) || 1;
    xx /= len; xy /= len; xz /= len;

    const yx = zy * xz - zz * xy;
    const yy = zz * xx - zx * xz;
    const yz = zx * xy - zy * xx;

    return new Float32Array([
      xx, yx, zx, 0,
      xy, yy, zy, 0,
      xz, yz, zz, 0,
      -(xx * eye[0] + xy * eye[1] + xz * eye[2]),
      -(yx * eye[0] + yy * eye[1] + yz * eye[2]),
      -(zx * eye[0] + zy * eye[1] + zz * eye[2]),
      1
    ]);
  }

  function mat4Multiply(a, b) {
    const out = new Float32Array(16);
    for (let c = 0; c < 4; c++) {
      for (let r = 0; r < 4; r++) {
        out[c * 4 + r] =
          a[0 * 4 + r] * b[c * 4 + 0] +
          a[1 * 4 + r] * b[c * 4 + 1] +
          a[2 * 4 + r] * b[c * 4 + 2] +
          a[3 * 4 + r] * b[c * 4 + 3];
      }
    }
    return out;
  }

  // Build aircraft world matrix from position & basis vectors (right, up, forward)
  function mat4FromBasis(pos, right, up, fwd, scale = 1.0) {
    // Local -Z is forward, +X is right, +Y is up
    return new Float32Array([
      right[0] * scale, right[1] * scale, right[2] * scale, 0,
      up[0] * scale,    up[1] * scale,    up[2] * scale,    0,
      -fwd[0] * scale,  -fwd[1] * scale,  -fwd[2] * scale,  0,
      pos[0],           pos[1],           pos[2],           1
    ]);
  }

  function worldToScreen(pt, viewProj, width, height) {
    const x = pt[0], y = pt[1], z = pt[2];
    const cx = viewProj[0] * x + viewProj[4] * y + viewProj[8] * z + viewProj[12];
    const cy = viewProj[1] * x + viewProj[5] * y + viewProj[9] * z + viewProj[13];
    const cw = viewProj[3] * x + viewProj[7] * y + viewProj[11] * z + viewProj[15];
    if (cw <= 0.01) return null;
    const ndcX = cx / cw;
    const ndcY = cy / cw;
    return [
      (ndcX * 0.5 + 0.5) * width,
      (1.0 - (ndcY * 0.5 + 0.5)) * height
    ];
  }

  // ============================================================================
  // 7. SIMULATION STATE (FLIGHT DYNAMICS, CAMERAS, MISSILES, FX, CPU TERRAIN)
  // ============================================================================
  let worldBytes = null; // Uint8Array(512*512*4) for CPU terrain lookup, collision & radar

  function sampleTerrainHeightCPU(x, z) {
    if (!worldBytes) return SEA_LEVEL * TERRAIN_HEIGHT_SCALE;
    const u = (((x / WORLD_TILE_UNITS) % 1) + 1) % 1;
    const v = (((z / WORLD_TILE_UNITS) % 1) + 1) % 1;
    const fx = u * MAP_SIZE - 0.5;
    const fz = v * MAP_SIZE - 0.5;
    const x0 = ((Math.floor(fx) % MAP_SIZE) + MAP_SIZE) % MAP_SIZE;
    const z0 = ((Math.floor(fz) % MAP_SIZE) + MAP_SIZE) % MAP_SIZE;
    const x1 = (x0 + 1) % MAP_SIZE;
    const z1 = (z0 + 1) % MAP_SIZE;
    const tx = fx - Math.floor(fx);
    const tz = fz - Math.floor(fz);

    const h00 = worldBytes[(z0 * MAP_SIZE + x0) * 4] / 255;
    const h10 = worldBytes[(z0 * MAP_SIZE + x1) * 4] / 255;
    const h01 = worldBytes[(z1 * MAP_SIZE + x0) * 4] / 255;
    const h11 = worldBytes[(z1 * MAP_SIZE + x1) * 4] / 255;
    const h = (h00 * (1 - tx) + h10 * tx) * (1 - tz) + (h01 * (1 - tx) + h11 * tx) * tz;
    return Math.max(h, SEA_LEVEL) * TERRAIN_HEIGHT_SCALE;
  }

  function sampleRawNormCPU(x, z) {
    if (!worldBytes) return SEA_LEVEL;
    const u = (((x / WORLD_TILE_UNITS) % 1) + 1) % 1;
    const v = (((z / WORLD_TILE_UNITS) % 1) + 1) % 1;
    const ix = Math.floor(u * MAP_SIZE) & (MAP_SIZE - 1);
    const iz = Math.floor(v * MAP_SIZE) & (MAP_SIZE - 1);
    return worldBytes[(iz * MAP_SIZE + ix) * 4] / 255;
  }

  // Camera modes: 0 = TOP-DOWN, 1 = CHASE, 2 = COCKPIT
  const VIEW_NAMES = ['TOP-DOWN', 'CHASE', 'COCKPIT'];
  const state = {
    time: 0,
    hasUserInput: false,
    // Aircraft state (1 world unit ≈ 35m; cruise altitude ~ 34 units ≈ 1200m / 3900ft)
    pos: [128.0, 34.5, 128.0],
    yaw: 0.45,          // Radians (0 = -Z North, +PI/2 = +X East)
    pitch: 0.0,         // Radians
    roll: 0.0,          // Bank angle
    barrelRollTimer: 0, // > 0 when executing 360 barrel roll
    barrelRollDir: 1,
    speed: 14.5,        // World units/sec (~480 knots base, ~780 knots on afterburner)
    burner: 0.0,        // [0..1]
    gLoad: 1.0,
    pullUpActive: false,
    lowAltActive: false,
    overspeedActive: false,
    missileWarnTimer: 0,

    // Camera transition blending
    viewMode: 1,        // Start in Chase view
    prevViewMode: 1,
    viewBlend: 1.0,     // 0 -> 1 over ~1.0s
    camPos: [128.0, 36.2, 134.0],
    camFwd: [0, -0.1, -1],
    camUp: [0, 1, 0],
    camRight: [1, 0, 0],
    camFov: 62 * Math.PI / 180,

    // Inputs
    mouseNormX: 0,      // [-1..1]
    mouseNormY: 0,      // [-1..1]
    mouseActive: false,
    lmbDown: false,
    lmbHoldTime: 0,
    rmbDown: false,
    touchStickX: 0,
    touchStickY: 0,
    touchBurn: false,

    // 4 Wing-mounted missiles (local wing rail offsets)
    missiles: [
      { ready: true, cooldown: 0, offset: [-0.96, -0.05, 0.34] },
      { ready: true, cooldown: 0, offset: [ 0.96, -0.05, 0.34] },
      { ready: true, cooldown: 0, offset: [-0.58, -0.05, 0.16] },
      { ready: true, cooldown: 0, offset: [ 0.58, -0.05, 0.16] }
    ],
    nextRail: 0,
    activeMissiles: [],
    explosions: [],
    scorchMarks: [],
    waterRings: [],
    wingTrailsL: [],
    wingTrailsR: [],
    particles: [],
    trailAccum: 0
  };

  function markUserEngaged() {
    if (!state.hasUserInput) {
      state.hasUserInput = true;
      document.getElementById('titleCard').classList.add('faded');
    }
  }

  function cycleViewMode() {
    markUserEngaged();
    state.prevViewMode = state.viewMode;
    state.viewMode = (state.viewMode + 1) % 3;
    state.viewBlend = 0.0;
    document.getElementById('btnView').textContent = 'VIEW: ' + VIEW_NAMES[state.viewMode];
    sound.playUiClick();
  }

  function triggerBarrelRoll() {
    markUserEngaged();
    if (state.barrelRollTimer <= 0.05) {
      state.barrelRollTimer = 0.72;
      state.barrelRollDir = state.mouseNormX >= 0 ? 1 : -1;
    }
  }

  function getJetBasis(yaw, pitch, roll) {
    // Forward vector (yaw=0 -> -Z, yaw=+PI/2 -> +X)
    const cp = Math.cos(pitch), sp = Math.sin(pitch);
    const sy = Math.sin(yaw), cy = Math.cos(yaw);
    const fwd = [sy * cp, sp, -cy * cp];
    const worldUp = [0, 1, 0];
    // Flat right = normalize(cross(fwd, worldUp))
    let rx = fwd[1] * worldUp[2] - fwd[2] * worldUp[1];
    let ry = fwd[2] * worldUp[0] - fwd[0] * worldUp[2];
    let rz = fwd[0] * worldUp[1] - fwd[1] * worldUp[0];
    const rl = Math.hypot(rx, ry, rz) || 1;
    rx /= rl; ry /= rl; rz /= rl;

    // Flat up = cross(right, fwd)
    const ux = ry * fwd[2] - rz * fwd[1];
    const uy = rz * fwd[0] - rx * fwd[2];
    const uz = rx * fwd[1] - ry * fwd[0];

    // Rotate right and up around fwd by roll angle
    const cr = Math.cos(roll), sr = Math.sin(roll);
    const right = [
      rx * cr - ux * sr,
      ry * cr - uy * sr,
      rz * cr - uz * sr
    ];
    const up = [
      ux * cr + rx * sr,
      uy * cr + ry * sr,
      uz * cr + rz * sr
    ];
    return { fwd, right, up };
  }

  function fireMissile() {
    markUserEngaged();
    // Find next ready rail
    let chosen = -1;
    for (let i = 0; i < 4; i++) {
      const idx = (state.nextRail + i) % 4;
      if (state.missiles[idx].ready) {
        chosen = idx;
        state.nextRail = (idx + 1) % 4;
        break;
      }
    }
    if (chosen === -1) return;

    const rail = state.missiles[chosen];
    rail.ready = false;
    rail.cooldown = 4.2;
    state.missileWarnTimer = 0.7;
    updateMissileUI();
    sound.playMissileLaunch();

    const totalRoll = state.roll + (state.barrelRollTimer > 0 ? (1 - state.barrelRollTimer / 0.72) * Math.PI * 2 * state.barrelRollDir : 0);
    const { fwd, right, up } = getJetBasis(state.yaw, state.pitch, totalRoll);

    const launchPos = [
      state.pos[0] + right[0] * rail.offset[0] + up[0] * rail.offset[1] - fwd[0] * rail.offset[2],
      state.pos[1] + right[1] * rail.offset[0] + up[1] * rail.offset[1] - fwd[1] * rail.offset[2],
      state.pos[2] + right[2] * rail.offset[0] + up[2] * rail.offset[1] - fwd[2] * rail.offset[2]
    ];

    // Aim direction: along nose, or dipped slightly toward ground ahead when flying level
    let aimDir = [fwd[0], fwd[1], fwd[2]];
    if (aimDir[1] > -0.06) {
      // Gently depress toward ground/water ~110 units ahead
      const groundAhead = sampleTerrainHeightCPU(
        state.pos[0] + fwd[0] * 115,
        state.pos[2] + fwd[2] * 115
      );
      const dy = (groundAhead - launchPos[1]) / 115;
      aimDir[1] = Math.max(-0.42, Math.min(aimDir[1], dy));
      aimDir = normalize3(aimDir);
    }

    state.activeMissiles.push({
      pos: launchPos,
      dir: aimDir,
      speed: state.speed + 26.0,
      life: 4.5,
      smokeAccum: 0
    });
  }

  function updateMissileUI() {
    for (let i = 0; i < 4; i++) {
      const el = document.getElementById('msl' + i);
      if (state.missiles[i].ready) el.classList.remove('reloading');
      else el.classList.add('reloading');
    }
  }

  function spawnExplosion(pos, isWater) {
    const dist = Math.hypot(pos[0] - state.pos[0], pos[1] - state.pos[1], pos[2] - state.pos[2]);
    sound.playExplosion(isWater, dist);

    state.explosions.push({
      pos: [pos[0], pos[1], pos[2]],
      age: 0,
      maxAge: isWater ? 1.5 : 1.8,
      isWater
    });

    if (isWater) {
      state.waterRings.push({ pos: [pos[0], pos[1] + 0.04, pos[2]], age: 0, maxAge: 2.6 });
      for (let i = 0; i < 26; i++) {
        const ang = Math.random() * Math.PI * 2;
        const spd = 1.5 + Math.random() * 5.5;
        state.particles.push({
          pos: [pos[0], pos[1] + 0.1, pos[2]],
          vel: [Math.cos(ang) * spd * 0.45, 4.5 + Math.random() * 7.5, Math.sin(ang) * spd * 0.45],
          size: 0.28 + Math.random() * 0.35,
          age: 0,
          maxAge: 0.9 + Math.random() * 0.6,
          col: [0.95, 0.97, 1.0],
          gravity: 11.0
        });
      }
    } else {
      state.scorchMarks.push({ pos: [pos[0], pos[1] + 0.06, pos[2]], age: 0, maxAge: 16.0 });
      if (state.scorchMarks.length > 18) state.scorchMarks.shift();
      // Fireball + rising smoke + glowing embers
      for (let i = 0; i < 30; i++) {
        const ang = Math.random() * Math.PI * 2;
        const spd = 1.0 + Math.random() * 6.5;
        const isEmber = i > 18;
        state.particles.push({
          pos: [pos[0], pos[1] + 0.25, pos[2]],
          vel: [Math.cos(ang) * spd, (isEmber ? 4.0 : 2.2) + Math.random() * 5.5, Math.sin(ang) * spd],
          size: isEmber ? 0.14 : (0.45 + Math.random() * 0.55),
          age: 0,
          maxAge: isEmber ? 2.2 : (1.1 + Math.random() * 0.8),
          col: isEmber ? [1.0, 0.55, 0.14] : [1.0, 0.78, 0.28],
          fadeSmoke: !isEmber,
          gravity: isEmber ? 4.5 : -0.8
        });
      }
    }
  }

  // ============================================================================
  // 8. INPUT HANDLERS (MOUSE, KEYBOARD, TOUCH)
  // ============================================================================
  window.addEventListener('mousemove', (e) => {
    const nx = (e.clientX / window.innerWidth) * 2 - 1;
    const ny = (e.clientY / window.innerHeight) * 2 - 1;
    state.mouseNormX = Math.max(-1, Math.min(1, nx));
    state.mouseNormY = Math.max(-1, Math.min(1, ny));
    state.mouseActive = true;
    markUserEngaged();
  });

  window.addEventListener('mousedown', (e) => {
    if (e.target.closest('#bottomBar') || e.target.closest('#touchControls')) return;
    if (e.button === 0) {
      state.lmbDown = true;
      state.lmbHoldTime = 0;
      triggerBarrelRoll();
    } else if (e.button === 2) {
      state.rmbDown = true;
      fireMissile();
    }
  });

  window.addEventListener('mouseup', (e) => {
    if (e.button === 0) {
      state.lmbDown = false;
      state.lmbHoldTime = 0;
    } else if (e.button === 2) {
      state.rmbDown = false;
    }
  });

  window.addEventListener('blur', () => {
    state.lmbDown = false;
    state.rmbDown = false;
    state.touchBurn = false;
  });

  window.addEventListener('contextmenu', (e) => e.preventDefault());

  window.addEventListener('keydown', (e) => {
    if (e.code === 'Space') {
      e.preventDefault();
      cycleViewMode();
    } else if (e.code === 'KeyF') {
      fireMissile();
    } else if (e.code === 'KeyR') {
      triggerBarrelRoll();
    } else if (e.code === 'ShiftLeft' || e.code === 'ShiftRight') {
      state.lmbDown = true;
      markUserEngaged();
    }
  });

  window.addEventListener('keyup', (e) => {
    if (e.code === 'ShiftLeft' || e.code === 'ShiftRight') {
      state.lmbDown = false;
    }
  });

  document.getElementById('btnView').addEventListener('click', cycleViewMode);
  document.getElementById('btnSound').addEventListener('click', () => {
    const on = sound.toggle();
    const btn = document.getElementById('btnSound');
    btn.textContent = on ? 'SOUND: ON' : 'SOUND: OFF';
    btn.classList.toggle('active', on);
  });

  // Touch support
  const touchControls = document.getElementById('touchControls');
  const stickZone = document.getElementById('touchStickZone');
  const stickKnob = document.getElementById('touchStickKnob');
  let stickTouchId = null;

  function enableTouchUI() {
    touchControls.classList.add('visible');
  }
  window.addEventListener('touchstart', enableTouchUI, { once: true, passive: true });

  stickZone.addEventListener('touchstart', (e) => {
    e.preventDefault();
    markUserEngaged();
    const t = e.changedTouches[0];
    stickTouchId = t.identifier;
    updateTouchStick(t.clientX, t.clientY);
  }, { passive: false });

  stickZone.addEventListener('touchmove', (e) => {
    e.preventDefault();
    for (const t of e.changedTouches) {
      if (t.identifier === stickTouchId) {
        updateTouchStick(t.clientX, t.clientY);
      }
    }
  }, { passive: false });

  function resetTouchStick(e) {
    for (const t of e.changedTouches) {
      if (t.identifier === stickTouchId) {
        stickTouchId = null;
        state.touchStickX = 0;
        state.touchStickY = 0;
        stickKnob.style.transform = 'translate(0px, 0px)';
      }
    }
  }
  stickZone.addEventListener('touchend', resetTouchStick);
  stickZone.addEventListener('touchcancel', resetTouchStick);

  function updateTouchStick(cx, cy) {
    const rect = stickZone.getBoundingClientRect();
    const dx = (cx - (rect.left + rect.width / 2)) / (rect.width * 0.42);
    const dy = (cy - (rect.top + rect.height / 2)) / (rect.height * 0.42);
    const len = Math.hypot(dx, dy);
    const cl = len > 1 ? 1 / len : 1;
    state.touchStickX = dx * cl;
    state.touchStickY = dy * cl;
    stickKnob.style.transform = `translate(${state.touchStickX * 36}px, ${state.touchStickY * 36}px)`;
  }

  function bindTouchBtn(id, onDown, onUp) {
    const el = document.getElementById(id);
    el.addEventListener('touchstart', (e) => {
      e.preventDefault();
      el.classList.add('pressed');
      onDown();
    }, { passive: false });
    const end = (e) => {
      e.preventDefault();
      el.classList.remove('pressed');
      if (onUp) onUp();
    };
    el.addEventListener('touchend', end);
    el.addEventListener('touchcancel', end);
  }
  bindTouchBtn('btnTouchView', cycleViewMode);
  bindTouchBtn('btnTouchRoll', triggerBarrelRoll);
  bindTouchBtn('btnTouchBurn', () => { markUserEngaged(); state.touchBurn = true; }, () => { state.touchBurn = false; });
  bindTouchBtn('btnTouchFire', fireMissile);

  // ============================================================================
  // 9. FLIGHT STEP, CAMERA BLENDING & PARTICLE SIMULATION
  // ============================================================================
  function getCameraPose(mode) {
    const totalRoll = state.roll + (state.barrelRollTimer > 0 ? (1 - state.barrelRollTimer / 0.72) * Math.PI * 2 * state.barrelRollDir : 0);
    const { fwd, right, up } = getJetBasis(state.yaw, state.pitch, totalRoll);

    if (mode === 0) {
      // TOP-DOWN (North Up: -Z is up on screen, +X is right)
      const camHeight = 46.0;
      const pos = [state.pos[0], state.pos[1] + camHeight, state.pos[2] + 3.0];
      return {
        pos,
        fwd: normalize3([0, -1, -0.065]),
        up: normalize3([0, 0.065, -1]),
        right: [1, 0, 0],
        fov: 58 * Math.PI / 180
      };
    } else if (mode === 1) {
      // CHASE CAMERA (smoothly trailing behind and slightly above)
      const flatFwd = normalize3([Math.sin(state.yaw), 0, -Math.cos(state.yaw)]);
      const pos = [
        state.pos[0] - flatFwd[0] * 5.2 - fwd[0] * 1.4,
        state.pos[1] + 1.55 - fwd[1] * 1.6,
        state.pos[2] - flatFwd[2] * 5.2 - fwd[2] * 1.4
      ];
      const lookTarget = [
        state.pos[0] + fwd[0] * 9.0,
        state.pos[1] + fwd[1] * 9.0 + 0.35,
        state.pos[2] + fwd[2] * 9.0
      ];
      const cf = normalize3([lookTarget[0] - pos[0], lookTarget[1] - pos[1], lookTarget[2] - pos[2]]);
      // Mild horizon-stabilized roll in chase cam so maneuvers feel dramatic yet readable
      const camBank = totalRoll * 0.28;
      const worldUp = [0, 1, 0];
      let cr = normalize3([
        cf[1] * worldUp[2] - cf[2] * worldUp[1],
        cf[2] * worldUp[0] - cf[0] * worldUp[2],
        cf[0] * worldUp[1] - cf[1] * worldUp[0]
      ]);
      let cu = [
        cr[1] * cf[2] - cr[2] * cf[1],
        cr[2] * cf[0] - cr[0] * cf[2],
        cr[0] * cf[1] - cr[1] * cf[0]
      ];
      const c = Math.cos(camBank), s = Math.sin(camBank);
      return {
        pos,
        fwd: cf,
        right: [cr[0] * c - cu[0] * s, cr[1] * c - cu[1] * s, cr[2] * c - cu[2] * s],
        up: [cu[0] * c + cr[0] * s, cu[1] * c + cr[1] * s, cu[2] * c + cr[2] * s],
        fov: (62 + state.burner * 7) * Math.PI / 180
      };
    } else {
      // COCKPIT VIEW (positioned in bubble canopy looking forward, upper ~58% open sky/HUD)
      const pos = [
        state.pos[0] + fwd[0] * 0.42 + up[0] * 0.24,
        state.pos[1] + fwd[1] * 0.42 + up[1] * 0.24,
        state.pos[2] + fwd[2] * 0.42 + up[2] * 0.24
      ];
      // Pitch camera slightly down so the instrument panel occupies bottom ~38% cleanly
      const pitchBias = -0.13;
      const cf = normalize3([
        fwd[0] * Math.cos(pitchBias) + up[0] * Math.sin(pitchBias),
        fwd[1] * Math.cos(pitchBias) + up[1] * Math.sin(pitchBias),
        fwd[2] * Math.cos(pitchBias) + up[2] * Math.sin(pitchBias)
      ]);
      const cu = normalize3([
        up[0] * Math.cos(pitchBias) - fwd[0] * Math.sin(pitchBias),
        up[1] * Math.cos(pitchBias) - fwd[1] * Math.sin(pitchBias),
        up[2] * Math.cos(pitchBias) - fwd[2] * Math.sin(pitchBias)
      ]);
      return {
        pos,
        fwd: cf,
        right,
        up: cu,
        fov: (65 + state.burner * 5) * Math.PI / 180
      };
    }
  }

  function stepSimulation(dt) {
    state.time += dt;

    // 1. Afterburner & missile re-arm timers
    if (state.lmbDown) state.lmbHoldTime += dt;
    const burnerTarget = (state.touchBurn || (state.lmbDown && state.lmbHoldTime > 0.14)) ? 1.0 : 0.0;
    state.burner += (burnerTarget - state.burner) * Math.min(1, dt * 5.5);

    if (state.missileWarnTimer > 0) state.missileWarnTimer -= dt;
    let railChanged = false;
    for (let i = 0; i < 4; i++) {
      if (!state.missiles[i].ready) {
        state.missiles[i].cooldown -= dt;
        if (state.missiles[i].cooldown <= 0) {
          state.missiles[i].ready = true;
          state.missiles[i].cooldown = 0;
          railChanged = true;
        }
      }
    }
    if (railChanged) updateMissileUI();

    // 2. Steering control (Lazy S-turns autopilot until player moves mouse/touch)
    let turnInput = 0;
    let pitchInput = 0;

    if (!state.hasUserInput) {
      turnInput = Math.sin(state.time * 0.42) * 0.38;
      pitchInput = Math.cos(state.time * 0.31) * 0.08;
    } else if (stickTouchId !== null) {
      turnInput = state.touchStickX;
      pitchInput = -state.touchStickY;
    } else if (state.viewMode === 0) {
      // Top-down north-up: steer smoothly toward cursor direction from screen center
      const curLen = Math.hypot(state.mouseNormX, state.mouseNormY);
      if (curLen > 0.06) {
        const targetYaw = Math.atan2(state.mouseNormX, -state.mouseNormY);
        let diff = targetYaw - state.yaw;
        while (diff > Math.PI) diff -= Math.PI * 2;
        while (diff < -Math.PI) diff += Math.PI * 2;
        turnInput = Math.max(-1, Math.min(1, diff * 1.45));
      }
      pitchInput = 0;
    } else {
      // Chase & Cockpit: cursor offset from screen center sets turn & climb/dive
      const deadzone = 0.04;
      const mx = Math.abs(state.mouseNormX) < deadzone ? 0 : state.mouseNormX;
      const my = Math.abs(state.mouseNormY) < deadzone ? 0 : state.mouseNormY;
      turnInput = mx;
      pitchInput = -my; // Mouse up -> climb (+pitch), mouse down -> dive (-pitch)
    }

    // 3. Arcade flight dynamics & terrain avoidance auto-pull-up
    const targetSpeed = 14.5 + state.burner * 8.5 - Math.sin(state.pitch) * 2.5;
    state.speed += (targetSpeed - state.speed) * Math.min(1, dt * 2.8);

    const yawRate = turnInput * 1.38;
    state.yaw += yawRate * dt;

    const targetRoll = -turnInput * 1.08;
    state.roll += (targetRoll - state.roll) * Math.min(1, dt * 5.2);

    if (state.barrelRollTimer > 0) {
      state.barrelRollTimer = Math.max(0, state.barrelRollTimer - dt);
    }

    // Look-ahead terrain height check for automatic collision avoidance
    const lookX = state.pos[0] + Math.sin(state.yaw) * 24.0;
    const lookZ = state.pos[2] - Math.cos(state.yaw) * 24.0;
    const groundHere = sampleTerrainHeightCPU(state.pos[0], state.pos[2]);
    const groundAhead = sampleTerrainHeightCPU(lookX, lookZ);
    const minSafeAlt = Math.max(groundHere, groundAhead) + 2.6;
    const agl = state.pos[1] - groundHere;

    state.lowAltActive = agl < 4.5;
    state.overspeedActive = state.speed > 21.8;

    let targetPitch = pitchInput * 0.78;
    // Soft ceiling at 72 units
    if (state.pos[1] > 66.0 && targetPitch > 0) {
      targetPitch *= Math.max(0, (74.0 - state.pos[1]) / 8.0);
    }

    if (state.pos[1] < minSafeAlt + 2.2) {
      state.pullUpActive = true;
      const urgency = Math.min(1.0, (minSafeAlt + 2.2 - state.pos[1]) / 3.5);
      targetPitch = Math.max(targetPitch, 0.25 + urgency * 0.55);
    } else {
      state.pullUpActive = false;
    }

    const prevPitch = state.pitch;
    state.pitch += (targetPitch - state.pitch) * Math.min(1, dt * (state.pullUpActive ? 6.5 : 3.8));
    state.pitch = Math.max(-0.85, Math.min(0.85, state.pitch));

    // Compute instantaneous G-load for HUD & gauges
    const pitchAccel = (state.pitch - prevPitch) / Math.max(dt, 0.001);
    const turnG = 1.0 / Math.max(0.35, Math.cos(state.roll));
    state.gLoad += ((turnG + pitchAccel * 2.8) - state.gLoad) * Math.min(1, dt * 8.0);

    // Advance aircraft position
    const { fwd, right, up } = getJetBasis(state.yaw, state.pitch, state.roll);
    state.pos[0] += fwd[0] * state.speed * dt;
    state.pos[1] += fwd[1] * state.speed * dt;
    state.pos[2] += fwd[2] * state.speed * dt;

    // Hard safety floor above terrain/water
    const hardFloor = sampleTerrainHeightCPU(state.pos[0], state.pos[2]) + 0.85;
    if (state.pos[1] < hardFloor) {
      state.pos[1] = hardFloor;
      if (state.pitch < 0.08) state.pitch = 0.08;
    }

    // 4. Smoothly blend camera across the ~1.0s transition
    if (state.viewBlend < 1.0) {
      state.viewBlend = Math.min(1.0, state.viewBlend + dt * 1.05);
    }
    const ease = state.viewBlend * state.viewBlend * (3 - 2 * state.viewBlend);
    const poseA = getCameraPose(state.prevViewMode);
    const poseB = getCameraPose(state.viewMode);

    state.camPos = [
      poseA.pos[0] + (poseB.pos[0] - poseA.pos[0]) * ease,
      poseA.pos[1] + (poseB.pos[1] - poseA.pos[1]) * ease,
      poseA.pos[2] + (poseB.pos[2] - poseA.pos[2]) * ease
    ];
    state.camFwd = normalize3([
      poseA.fwd[0] + (poseB.fwd[0] - poseA.fwd[0]) * ease,
      poseA.fwd[1] + (poseB.fwd[1] - poseA.fwd[1]) * ease,
      poseA.fwd[2] + (poseB.fwd[2] - poseA.fwd[2]) * ease
    ]);
    state.camRight = normalize3([
      poseA.right[0] + (poseB.right[0] - poseA.right[0]) * ease,
      poseA.right[1] + (poseB.right[1] - poseA.right[1]) * ease,
      poseA.right[2] + (poseB.right[2] - poseA.right[2]) * ease
    ]);
    state.camUp = normalize3([
      state.camRight[1] * state.camFwd[2] - state.camRight[2] * state.camFwd[1],
      state.camRight[2] * state.camFwd[0] - state.camRight[0] * state.camFwd[2],
      state.camRight[0] * state.camFwd[1] - state.camRight[1] * state.camFwd[0]
    ]);
    state.camFov = poseA.fov + (poseB.fov - poseA.fov) * ease;

    // 5. Wingtip vapour trails & water-skimming spray/wake
    const totalRoll = state.roll + (state.barrelRollTimer > 0 ? (1 - state.barrelRollTimer / 0.72) * Math.PI * 2 * state.barrelRollDir : 0);
    const jetBasis = getJetBasis(state.yaw, state.pitch, totalRoll);
    state.trailAccum += dt;
    if (state.trailAccum >= 0.025) {
      state.trailAccum = 0;
      const tipL = [
        state.pos[0] - jetBasis.right[0] * 1.40 - jetBasis.fwd[0] * 0.75,
        state.pos[1] - jetBasis.right[1] * 1.40 - jetBasis.fwd[1] * 0.75,
        state.pos[2] - jetBasis.right[2] * 1.40 - jetBasis.fwd[2] * 0.75
      ];
      const tipR = [
        state.pos[0] + jetBasis.right[0] * 1.40 - jetBasis.fwd[0] * 0.75,
        state.pos[1] + jetBasis.right[1] * 1.40 - jetBasis.fwd[1] * 0.75,
        state.pos[2] + jetBasis.right[2] * 1.40 - jetBasis.fwd[2] * 0.75
      ];
      state.wingTrailsL.push({ pos: tipL, age: 0 });
      state.wingTrailsR.push({ pos: tipR, age: 0 });
      if (state.wingTrailsL.length > 44) state.wingTrailsL.shift();
      if (state.wingTrailsR.length > 44) state.wingTrailsR.shift();

      // Skimming water spray & wake when flying low over lakes
      const rawNorm = sampleRawNormCPU(state.pos[0], state.pos[2]);
      const waterSurface = SEA_LEVEL * TERRAIN_HEIGHT_SCALE;
      if (rawNorm < SEA_LEVEL && (state.pos[1] - waterSurface) < 2.3) {
        state.waterRings.push({
          pos: [state.pos[0], waterSurface + 0.03, state.pos[2]],
          age: 0,
          maxAge: 1.5
        });
        for (const s of [-1, 1]) {
          state.particles.push({
            pos: [state.pos[0] + jetBasis.right[0] * s * 0.6, waterSurface + 0.08, state.pos[2] + jetBasis.right[2] * s * 0.6],
            vel: [jetBasis.right[0] * s * 2.2 + (Math.random() - 0.5), 1.8 + Math.random() * 1.8, jetBasis.right[2] * s * 2.2],
            size: 0.22,
            age: 0,
            maxAge: 0.55,
            col: [0.96, 0.98, 1.0],
            gravity: 6.5
          });
        }
      }
    }

    for (const tr of state.wingTrailsL) tr.age += dt;
    for (const tr of state.wingTrailsR) tr.age += dt;
    while (state.wingTrailsL.length && state.wingTrailsL[0].age > 1.1) state.wingTrailsL.shift();
    while (state.wingTrailsR.length && state.wingTrailsR[0].age > 1.1) state.wingTrailsR.shift();

    // 6. Update active missiles
    for (let i = state.activeMissiles.length - 1; i >= 0; i--) {
      const m = state.activeMissiles[i];
      m.life -= dt;
      m.pos[0] += m.dir[0] * m.speed * dt;
      m.pos[1] += m.dir[1] * m.speed * dt;
      m.pos[2] += m.dir[2] * m.speed * dt;

      m.smokeAccum += dt;
      if (m.smokeAccum >= 0.016) {
        m.smokeAccum = 0;
        state.particles.push({
          pos: [m.pos[0] - m.dir[0] * 0.5, m.pos[1] - m.dir[1] * 0.5, m.pos[2] - m.dir[2] * 0.5],
          vel: [(Math.random() - 0.5) * 0.5, 0.25, (Math.random() - 0.5) * 0.5],
          size: 0.24,
          age: 0,
          maxAge: 1.35,
          col: [0.94, 0.88, 0.84],
          gravity: -0.15
        });
      }

      const groundY = sampleTerrainHeightCPU(m.pos[0], m.pos[2]);
      if (m.pos[1] <= groundY || m.life <= 0) {
        const rawN = sampleRawNormCPU(m.pos[0], m.pos[2]);
        const isWater = rawN < SEA_LEVEL;
        spawnExplosion([m.pos[0], groundY, m.pos[2]], isWater);
        state.activeMissiles.splice(i, 1);
      }
    }

    // 7. Update explosions, rings, scorches, and particles
    for (let i = state.explosions.length - 1; i >= 0; i--) {
      state.explosions[i].age += dt;
      if (state.explosions[i].age >= state.explosions[i].maxAge) state.explosions.splice(i, 1);
    }
    for (let i = state.waterRings.length - 1; i >= 0; i--) {
      state.waterRings[i].age += dt;
      if (state.waterRings[i].age >= state.waterRings[i].maxAge) state.waterRings.splice(i, 1);
    }
    for (let i = state.scorchMarks.length - 1; i >= 0; i--) {
      state.scorchMarks[i].age += dt;
      if (state.scorchMarks[i].age >= state.scorchMarks[i].maxAge) state.scorchMarks.splice(i, 1);
    }
    for (let i = state.particles.length - 1; i >= 0; i--) {
      const p = state.particles[i];
      p.age += dt;
      if (p.age >= p.maxAge) {
        state.particles.splice(i, 1);
        continue;
      }
      p.vel[1] -= p.gravity * dt;
      p.pos[0] += p.vel[0] * dt;
      p.pos[1] += p.vel[1] * dt;
      p.pos[2] += p.vel[2] * dt;
      if (p.fadeSmoke && p.age > p.maxAge * 0.35) {
        p.col[0] += (0.26 - p.col[0]) * dt * 4.0;
        p.col[1] += (0.24 - p.col[1]) * dt * 4.0;
        p.col[2] += (0.32 - p.col[2]) * dt * 4.0;
      }
    }

    // Update Web Audio engine
    const speedNorm = Math.max(0, Math.min(1, (state.speed - 13.0) / 10.5));
    const isCockpit = state.viewMode === 2 && state.viewBlend > 0.5;
    sound.update(dt, speedNorm, state.burner, isCockpit, state.pullUpActive);
  }

  // ============================================================================
  // 10. WEBGL2 RENDERER (WORLD PASS + 3D AIRCRAFT + OUTLINES + FX RIBBONS)
  // ============================================================================
  function renderWebGL(width, height) {
    gl.viewport(0, 0, width, height);
    gl.enable(gl.DEPTH_TEST);
    gl.depthFunc(gl.LESS);

    const aspect = width / Math.max(height, 1);
    const tanHalfFov = Math.tan(state.camFov * 0.5);
    const target = [
      state.camPos[0] + state.camFwd[0],
      state.camPos[1] + state.camFwd[1],
      state.camPos[2] + state.camFwd[2]
    ];
    const view = mat4LookAt(state.camPos, target, state.camUp);
    const proj = mat4Perspective(state.camFov, aspect, 0.15, 420.0);
    const viewProj = mat4Multiply(proj, view);

    // 1. Pass 1: Ray-marched Autumn Lake Country + Clouds + Sky + Depth
    gl.useProgram(worldProg);
    gl.bindVertexArray(quadVao);
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, worldTex);
    gl.uniform1i(gl.getUniformLocation(worldProg, 'uWorldMap'), 0);
    gl.uniform3fv(gl.getUniformLocation(worldProg, 'uCamPos'), state.camPos);
    gl.uniform3fv(gl.getUniformLocation(worldProg, 'uCamRight'), state.camRight);
    gl.uniform3fv(gl.getUniformLocation(worldProg, 'uCamUp'), state.camUp);
    gl.uniform3fv(gl.getUniformLocation(worldProg, 'uCamFwd'), state.camFwd);
    gl.uniform1f(gl.getUniformLocation(worldProg, 'uTanHalfFov'), tanHalfFov);
    gl.uniform1f(gl.getUniformLocation(worldProg, 'uAspect'), aspect);
    gl.uniform1f(gl.getUniformLocation(worldProg, 'uTime'), state.time);
    gl.uniform3fv(gl.getUniformLocation(worldProg, 'uSunDir'), SUN_DIR);
    gl.uniform3fv(gl.getUniformLocation(worldProg, 'uJetPos'), state.pos);
    gl.uniform1f(gl.getUniformLocation(worldProg, 'uJetYaw'), state.yaw);
    gl.uniformMatrix4fv(gl.getUniformLocation(worldProg, 'uViewProj'), false, viewProj);

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

    // 2. Pass 2: 3D Fighter Jet + Wing Missiles (hidden when fully inside cockpit)
    const showExternalJet = !(state.viewMode === 2 && state.viewBlend > 0.72);
    const totalRoll = state.roll + (state.barrelRollTimer > 0 ? (1 - state.barrelRollTimer / 0.72) * Math.PI * 2 * state.barrelRollDir : 0);
    const jetBasis = getJetBasis(state.yaw, state.pitch, totalRoll);
    const jetModel = mat4FromBasis(state.pos, jetBasis.right, jetBasis.up, jetBasis.fwd, 1.0);

    gl.useProgram(meshProg);
    gl.uniformMatrix4fv(gl.getUniformLocation(meshProg, 'uViewProj'), false, viewProj);
    gl.uniform3fv(gl.getUniformLocation(meshProg, 'uSunDir'), SUN_DIR);
    gl.uniform1f(gl.getUniformLocation(meshProg, 'uBurnerGlow'), state.burner);

    function drawOutlinedMesh(mesh, modelMat, outlineScale) {
      gl.bindVertexArray(mesh.vao);
      gl.uniformMatrix4fv(gl.getUniformLocation(meshProg, 'uModel'), false, modelMat);

      // Inverted-hull 1px dark outline pass
      gl.enable(gl.CULL_FACE);
      gl.cullFace(gl.FRONT);
      gl.uniform1i(gl.getUniformLocation(meshProg, 'uIsOutline'), 1);
      gl.uniform1f(gl.getUniformLocation(meshProg, 'uOutlineExpand'), outlineScale);
      gl.drawArrays(gl.TRIANGLES, 0, mesh.count);

      // Flat-shaded 3-tone pass
      gl.cullFace(gl.BACK);
      gl.uniform1i(gl.getUniformLocation(meshProg, 'uIsOutline'), 0);
      gl.uniform1f(gl.getUniformLocation(meshProg, 'uOutlineExpand'), 0.0);
      gl.drawArrays(gl.TRIANGLES, 0, mesh.count);
      gl.disable(gl.CULL_FACE);
    }

    if (showExternalJet) {
      drawOutlinedMesh(jetMesh, jetModel, 0.022);

      // Attached wing rail missiles
      for (let i = 0; i < 4; i++) {
        if (!state.missiles[i].ready) continue;
        const off = state.missiles[i].offset;
        const mPos = [
          state.pos[0] + jetBasis.right[0] * off[0] + jetBasis.up[0] * off[1] - jetBasis.fwd[0] * off[2],
          state.pos[1] + jetBasis.right[1] * off[0] + jetBasis.up[1] * off[1] - jetBasis.fwd[1] * off[2],
          state.pos[2] + jetBasis.right[2] * off[0] + jetBasis.up[2] * off[1] - jetBasis.fwd[2] * off[2]
        ];
        const mModel = mat4FromBasis(mPos, jetBasis.right, jetBasis.up, jetBasis.fwd, 1.0);
        drawOutlinedMesh(missileMesh, mModel, 0.014);
      }
    }

    // Active flying missiles
    for (const m of state.activeMissiles) {
      const mYaw = Math.atan2(m.dir[0], -m.dir[2]);
      const mPitch = Math.asin(Math.max(-0.99, Math.min(0.99, m.dir[1])));
      const mBasis = getJetBasis(mYaw, mPitch, state.time * 12.0);
      const mModel = mat4FromBasis(m.pos, mBasis.right, mBasis.up, mBasis.fwd, 1.25);
      drawOutlinedMesh(missileMesh, mModel, 0.018);
    }

    // 3. Pass 3: FX Geometry (Afterburner Plumes, Wingtip Trails, Explosions, Rings, Scorch)
    let vPtr = 0;
    function pushVert(x, y, z, r, g, b, a) {
      if (vPtr + 7 >= fxData.length) return;
      fxData[vPtr++] = x; fxData[vPtr++] = y; fxData[vPtr++] = z;
      fxData[vPtr++] = r; fxData[vPtr++] = g; fxData[vPtr++] = b;
      fxData[vPtr++] = a;
    }
    function pushTri(a, b, c, col, alpha) {
      pushVert(a[0], a[1], a[2], col[0], col[1], col[2], alpha);
      pushVert(b[0], b[1], b[2], col[0], col[1], col[2], alpha);
      pushVert(c[0], c[1], c[2], col[0], col[1], col[2], alpha);
    }
    function pushBillboard(pos, radius, col, alpha) {
      const r = state.camRight, u = state.camUp;
      const p0 = [pos[0] - r[0]*radius - u[0]*radius, pos[1] - r[1]*radius - u[1]*radius, pos[2] - r[2]*radius - u[2]*radius];
      const p1 = [pos[0] + r[0]*radius - u[0]*radius, pos[1] + r[1]*radius - u[1]*radius, pos[2] + r[2]*radius - u[2]*radius];
      const p2 = [pos[0] + r[0]*radius + u[0]*radius, pos[1] + r[1]*radius + u[1]*radius, pos[2] + r[2]*radius + u[2]*radius];
      const p3 = [pos[0] - r[0]*radius + u[0]*radius, pos[1] - r[1]*radius + u[1]*radius, pos[2] - r[2]*radius + u[2]*radius];
      pushTri(p0, p1, p2, col, alpha);
      pushTri(p0, p2, p3, col, alpha);
    }
    function pushGroundDisc(pos, innerR, outerR, col, alpha, segs = 16) {
      for (let i = 0; i < segs; i++) {
        const a0 = (i / segs) * Math.PI * 2;
        const a1 = ((i + 1) / segs) * Math.PI * 2;
        const c0 = Math.cos(a0), s0 = Math.sin(a0);
        const c1 = Math.cos(a1), s1 = Math.sin(a1);
        const i0 = [pos[0] + c0 * innerR, pos[1], pos[2] + s0 * innerR];
        const i1 = [pos[0] + c1 * innerR, pos[1], pos[2] + s1 * innerR];
        const o0 = [pos[0] + c0 * outerR, pos[1], pos[2] + s0 * outerR];
        const o1 = [pos[0] + c1 * outerR, pos[1], pos[2] + s1 * outerR];
        if (innerR <= 0.001) {
          pushTri(pos, o0, o1, col, alpha);
        } else {
          pushTri(i0, o0, o1, col, alpha);
          pushTri(i0, o1, i1, col, alpha);
        }
      }
    }

    // Twin afterburner plumes with bright white core
    if (showExternalJet) {
      const flicker = 0.88 + Math.sin(state.time * 55.0) * 0.12;
      const plumeLen = (0.55 + state.burner * 1.65) * flicker;
      const plumeRad = 0.085 + state.burner * 0.065;
      for (const side of [-1, 1]) {
        const base = [
          state.pos[0] + jetBasis.right[0] * side * 0.14 - jetBasis.fwd[0] * 1.33,
          state.pos[1] + jetBasis.right[1] * side * 0.14 - jetBasis.fwd[1] * 1.33,
          state.pos[2] + jetBasis.right[2] * side * 0.14 - jetBasis.fwd[2] * 1.33
        ];
        const tip = [
          base[0] - jetBasis.fwd[0] * plumeLen,
          base[1] - jetBasis.fwd[1] * plumeLen,
          base[2] - jetBasis.fwd[2] * plumeLen
        ];
        const coreTip = [
          base[0] - jetBasis.fwd[0] * (plumeLen * 0.56),
          base[1] - jetBasis.fwd[1] * (plumeLen * 0.56),
          base[2] - jetBasis.fwd[2] * (plumeLen * 0.56)
        ];
        const r = jetBasis.right, u = jetBasis.up;
        // Outer orange/gold cone
        pushTri([base[0] - r[0]*plumeRad, base[1] - r[1]*plumeRad, base[2] - r[2]*plumeRad],
                [base[0] + r[0]*plumeRad, base[1] + r[1]*plumeRad, base[2] + r[2]*plumeRad], tip, [1.0, 0.52, 0.16], 0.92);
        pushTri([base[0] - u[0]*plumeRad, base[1] - u[1]*plumeRad, base[2] - u[2]*plumeRad],
                [base[0] + u[0]*plumeRad, base[1] + u[1]*plumeRad, base[2] + u[2]*plumeRad], tip, [1.0, 0.52, 0.16], 0.92);
        // Inner white-hot core
        const cr = plumeRad * 0.52;
        pushTri([base[0] - r[0]*cr, base[1] - r[1]*cr, base[2] - r[2]*cr],
                [base[0] + r[0]*cr, base[1] + r[1]*cr, base[2] + r[2]*cr], coreTip, [1.0, 0.98, 0.90], 1.0);
        pushTri([base[0] - u[0]*cr, base[1] - u[1]*cr, base[2] - u[2]*cr],
                [base[0] + u[0]*cr, base[1] + u[1]*cr, base[2] + u[2]*cr], coreTip, [1.0, 0.98, 0.90], 1.0);
      }
    }

    // Active missile rocket exhaust flames
    for (const m of state.activeMissiles) {
      const fPos = [m.pos[0] - m.dir[0] * 0.55, m.pos[1] - m.dir[1] * 0.55, m.pos[2] - m.dir[2] * 0.55];
      pushBillboard(fPos, 0.28, [1.0, 0.62, 0.20], 0.95);
      pushBillboard(fPos, 0.14, [1.0, 0.98, 0.90], 1.0);
    }

    // Thin white wingtip vapour trails
    for (const trail of [state.wingTrailsL, state.wingTrailsR]) {
      for (let i = 1; i < trail.length; i++) {
        const a = trail[i - 1];
        const b = trail[i];
        if (Math.hypot(b.pos[0] - a.pos[0], b.pos[1] - a.pos[1], b.pos[2] - a.pos[2]) > 4.0) continue;
        const life = 1.0 - b.age / 1.1;
        if (life <= 0) continue;
        const w = 0.032 * life;
        const r = state.camRight;
        const a0 = [a.pos[0] - r[0]*w, a.pos[1] - r[1]*w, a.pos[2] - r[2]*w];
        const a1 = [a.pos[0] + r[0]*w, a.pos[1] + r[1]*w, a.pos[2] + r[2]*w];
        const b0 = [b.pos[0] - r[0]*w, b.pos[1] - r[1]*w, b.pos[2] - r[2]*w];
        const b1 = [b.pos[0] + r[0]*w, b.pos[1] + r[1]*w, b.pos[2] + r[2]*w];
        pushTri(a0, a1, b1, [0.96, 0.95, 1.0], life * 0.65);
        pushTri(a0, b1, b0, [0.96, 0.95, 1.0], life * 0.65);
      }
    }

    // Land scorch marks with glowing embers
    for (const s of state.scorchMarks) {
      const fade = Math.max(0, 1.0 - s.age / s.maxAge);
      pushGroundDisc(s.pos, 0, 1.85, [0.10, 0.08, 0.12], fade * 0.85, 12);
      if (s.age < 7.0) {
        const emberPulse = 0.5 + 0.5 * Math.sin(state.time * 8.0 + s.pos[0]);
        pushGroundDisc([s.pos[0], s.pos[1] + 0.02, s.pos[2]], 0, 0.85, [1.0, 0.42, 0.10], emberPulse * (1 - s.age / 7.0), 10);
      }
    }

    // Expanding water foam rings
    for (const ring of state.waterRings) {
      const t = ring.age / ring.maxAge;
      const rad = 0.5 + t * 5.2;
      pushGroundDisc(ring.pos, rad - 0.22, rad, [0.96, 0.97, 1.0], (1 - t) * 0.85, 18);
    }

    // Missile impact flash, fireball, water column & shock ring
    for (const ex of state.explosions) {
      const t = ex.age / ex.maxAge;
      if (ex.isWater) {
        // Tall white spray plume + foam ring
        const colH = Math.sin(Math.min(1, t * 1.4) * Math.PI) * 5.2;
        if (colH > 0.1) {
          pushBillboard([ex.pos[0], ex.pos[1] + colH * 0.45, ex.pos[2]], 0.95 * (1 - t * 0.4), [0.94, 0.98, 1.0], 1 - t);
          pushBillboard([ex.pos[0], ex.pos[1] + colH * 0.85, ex.pos[2]], 0.65 * (1 - t * 0.5), [1.0, 1.0, 1.0], 1 - t);
        }
      } else {
        // Bright flash + multi-puff pixel fireball + expanding shock ring
        if (t < 0.25) {
          pushBillboard([ex.pos[0], ex.pos[1] + 0.8, ex.pos[2]], 2.6 * (1 - t * 2.0), [1.0, 0.98, 0.88], 1.0);
        }
        const fireRad = (0.8 + t * 2.4) * (1 - t * 0.5);
        const fireCol = t < 0.4 ? [1.0, 0.68, 0.22] : [0.34, 0.30, 0.38];
        pushBillboard([ex.pos[0], ex.pos[1] + 0.6 + t * 1.8, ex.pos[2]], fireRad, fireCol, 1 - t);
        const shockR = 0.6 + t * 6.5;
        pushGroundDisc([ex.pos[0], ex.pos[1] + 0.08, ex.pos[2]], shockR - 0.28, shockR, [1.0, 0.84, 0.58], (1 - t) * 0.9, 20);
      }
    }

    // General particles (smoke trail puffs, embers, splash droplets)
    for (const p of state.particles) {
      const life = 1.0 - p.age / p.maxAge;
      pushBillboard(p.pos, p.size * (0.6 + (1 - life) * 0.8), p.col, life * 0.9);
    }

    if (vPtr > 0) {
      gl.useProgram(fxProg);
      gl.bindVertexArray(fxVao);
      gl.bindBuffer(gl.ARRAY_BUFFER, fxBuf);
      gl.bufferSubData(gl.ARRAY_BUFFER, 0, fxData.subarray(0, vPtr));
      gl.uniformMatrix4fv(gl.getUniformLocation(fxProg, 'uViewProj'), false, viewProj);
      gl.drawArrays(gl.TRIANGLES, 0, vPtr / 7);
    }
  }

  // ============================================================================
  // 11. CANVAS 2D PIXEL COCKPIT PANEL & CONFORMAL HUD OVERLAY
  // ============================================================================
  const hudCanvas = document.getElementById('hudCanvas');
  const ctx = hudCanvas.getContext('2d');

  // Crisp 5x7 bitmap pixel font for instrument readouts & HUD
  const FONT_5X7 = {
    '0':['01110','10001','10011','10101','11001','10001','01110'],
    '1':['00100','01100','00100','00100','00100','00100','01110'],
    '2':['01110','10001','00001','00110','01000','10000','11111'],
    '3':['11110','00001','00001','01110','00001','00001','11110'],
    '4':['00010','00110','01010','10010','11111','00010','00010'],
    '5':['11111','10000','11110','00001','00001','10001','01110'],
    '6':['00110','01000','10000','11110','10001','10001','01110'],
    '7':['11111','00001','00010','00100','01000','01000','01000'],
    '8':['01110','10001','10001','01110','10001','10001','01110'],
    '9':['01110','10001','10001','01111','00001','00010','01100'],
    'A':['01110','10001','10001','11111','10001','10001','10001'],
    'B':['11110','10001','10001','11110','10001','10001','11110'],
    'C':['01110','10001','10000','10000','10000','10001','01110'],
    'D':['11100','10010','10001','10001','10001','10010','11100'],
    'E':['11111','10000','10000','11110','10000','10000','11111'],
    'F':['11111','10000','10000','11110','10000','10000','10000'],
    'G':['01110','10001','10000','10111','10001','10001','01111'],
    'H':['10001','10001','10001','11111','10001','10001','10001'],
    'I':['01110','00100','00100','00100','00100','00100','01110'],
    'K':['10001','10010','10100','11000','10100','10010','10001'],
    'L':['10000','10000','10000','10000','10000','10000','11111'],
    'M':['10001','11011','10101','10101','10001','10001','10001'],
    'N':['10001','11001','10101','10011','10001','10001','10001'],
    'O':['01110','10001','10001','10001','10001','10001','01110'],
    'P':['11110','10001','10001','11110','10000','10000','10000'],
    'R':['11110','10001','10001','11110','10100','10010','10001'],
    'S':['01111','10000','10000','01110','00001','00001','11110'],
    'T':['11111','00100','00100','00100','00100','00100','00100'],
    'U':['10001','10001','10001','10001','10001','10001','01110'],
    'V':['10001','10001','10001','10001','10001','01010','00100'],
    'W':['10001','10001','10001','10101','10101','11011','10001'],
    'X':['10001','10001','01010','00100','01010','10001','10001'],
    'Y':['10001','10001','01010','00100','00100','00100','00100'],
    '-':['00000','00000','00000','11111','00000','00000','00000'],
    '+':['00000','00100','00100','11111','00100','00100','00000'],
    ':':['00000','00100','00100','00000','00100','00100','00000'],
    '.':['00000','00000','00000','00000','00000','01100','01100'],
    '/':['00001','00010','00010','00100','01000','01000','10000'],
    ' ':['00000','00000','00000','00000','00000','00000','00000']
  };

  function drawPixelText(text, x, y, color, align = 'left', scale = 1) {
    const str = String(text).toUpperCase();
    const charW = 6 * scale;
    const totalW = str.length * charW - scale;
    let ox = Math.round(x);
    if (align === 'center') ox -= Math.round(totalW / 2);
    else if (align === 'right') ox -= totalW;
    const oy = Math.round(y);

    ctx.fillStyle = color;
    for (let i = 0; i < str.length; i++) {
      const glyph = FONT_5X7[str[i]] || FONT_5X7[' '];
      const gx = ox + i * charW;
      for (let r = 0; r < 7; r++) {
        const row = glyph[r];
        for (let c = 0; c < 5; c++) {
          if (row[c] === '1') {
            ctx.fillRect(gx + c * scale, oy + r * scale, scale, scale);
          }
        }
      }
    }
  }

  function pxRect(x, y, w, h, fill, stroke) {
    const rx = Math.round(x), ry = Math.round(y), rw = Math.round(w), rh = Math.round(h);
    if (fill) {
      ctx.fillStyle = fill;
      ctx.fillRect(rx, ry, rw, rh);
    }
    if (stroke) {
      ctx.strokeStyle = stroke;
      ctx.lineWidth = 1;
      ctx.strokeRect(rx + 0.5, ry + 0.5, rw - 1, rh - 1);
    }
  }

  function pxLine(x0, y0, x1, y1, color) {
    x0 = Math.round(x0); y0 = Math.round(y0);
    x1 = Math.round(x1); y1 = Math.round(y1);
    ctx.fillStyle = color;
    const dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
    const dy = -Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
    let err = dx + dy;
    while (true) {
      ctx.fillRect(x0, y0, 1, 1);
      if (x0 === x1 && y0 === y1) break;
      const e2 = 2 * err;
      if (e2 >= dy) { err += dy; x0 += sx; }
      if (e2 <= dx) { err += dx; y0 += sy; }
    }
  }

  function pxCircle(cx, cy, r, color) {
    cx = Math.round(cx); cy = Math.round(cy); r = Math.round(r);
    ctx.fillStyle = color;
    let x = r, y = 0, err = 0;
    while (x >= y) {
      ctx.fillRect(cx + x, cy + y, 1, 1);
      ctx.fillRect(cx + y, cy + x, 1, 1);
      ctx.fillRect(cx - y, cy + x, 1, 1);
      ctx.fillRect(cx - x, cy + y, 1, 1);
      ctx.fillRect(cx - x, cy - y, 1, 1);
      ctx.fillRect(cx - y, cy - x, 1, 1);
      ctx.fillRect(cx + y, cy - x, 1, 1);
      ctx.fillRect(cx + x, cy - y, 1, 1);
      y += 1;
      err += 1 + 2 * y;
      if (2 * (err - x) + 1 > 0) {
        x -= 1;
        err += 1 - 2 * x;
      }
    }
  }

  function renderCockpitAndHUD(w, h) {
    ctx.clearRect(0, 0, w, h);

    // Compute cockpit visibility factor (fades in smoothly during camera transition)
    let cockpitVis = 0;
    if (state.viewMode === 2) cockpitVis = state.viewBlend;
    else if (state.prevViewMode === 2) cockpitVis = 1.0 - state.viewBlend;

    if (cockpitVis <= 0.01) return;

    const ease = cockpitVis * cockpitVis * (3 - 2 * cockpitVis);
    const panelOffsetY = Math.round((1.0 - ease) * (h * 0.48));

    // Real flight metrics
    const airspeedKts = Math.round(state.speed * 33.5);
    const altFeet = Math.round(state.pos[1] * 115);
    const groundY = sampleTerrainHeightCPU(state.pos[0], state.pos[2]);
    const radarAltFeet = Math.max(0, Math.round((state.pos[1] - groundY) * 115));
    const headingDeg = (((Math.round(state.yaw * 180 / Math.PI)) % 360) + 360) % 360;
    const vsiFpm = Math.round(Math.sin(state.pitch) * state.speed * 115 * 60);
    const totalRoll = state.roll + (state.barrelRollTimer > 0 ? (1 - state.barrelRollTimer / 0.72) * Math.PI * 2 * state.barrelRollDir : 0);

    // ========================================================================
    // A. CONFORMAL HEAD-UP DISPLAY (HUD) — Pitch ladder sits on real horizon
    // ========================================================================
    if (ease > 0.35) {
      const hudGreen = '#7aff9c';
      const hudDim   = '#359e58';
      const hudWarn  = '#ff9e42';

      const aspect = w / Math.max(h, 1);
      const target = [
        state.camPos[0] + state.camFwd[0],
        state.camPos[1] + state.camFwd[1],
        state.camPos[2] + state.camFwd[2]
      ];
      const view = mat4LookAt(state.camPos, target, state.camUp);
      const proj = mat4Perspective(state.camFov, aspect, 0.15, 420.0);
      const viewProj = mat4Multiply(proj, view);

      const jetBasis = getJetBasis(state.yaw, state.pitch, totalRoll);
      const flatFwd = normalize3([Math.sin(state.yaw), 0, -Math.cos(state.yaw)]);
      const flatRight = normalize3([Math.cos(state.yaw), 0, Math.sin(state.yaw)]);

      // Aircraft boresight / nose reference marker
      const nosePt = [
        state.camPos[0] + jetBasis.fwd[0] * 100,
        state.camPos[1] + jetBasis.fwd[1] * 100,
        state.camPos[2] + jetBasis.fwd[2] * 100
      ];
      const noseScr = worldToScreen(nosePt, viewProj, w, h);
      if (noseScr) {
        const nx = Math.round(noseScr[0]), ny = Math.round(noseScr[1]);
        pxLine(nx - 10, ny, nx - 4, ny, hudGreen);
        pxLine(nx - 4, ny, nx - 2, ny + 3, hudGreen);
        pxLine(nx - 2, ny + 3, nx, ny, hudGreen);
        pxLine(nx, ny, nx + 2, ny + 3, hudGreen);
        pxLine(nx + 2, ny + 3, nx + 4, ny, hudGreen);
        pxLine(nx + 4, ny, nx + 10, ny, hudGreen);
      }

      // Conformal pitch ladder (0° sits directly on the world horizon outside!)
      const hudClipBottom = Math.round(h * 0.59) + panelOffsetY;
      ctx.save();
      ctx.beginPath();
      ctx.rect(Math.round(w * 0.22), 14, Math.round(w * 0.56), Math.max(10, hudClipBottom - 14));
      ctx.clip();

      for (let deg = -30; deg <= 30; deg += 10) {
        const rad = deg * Math.PI / 180;
        const dir = [
          flatFwd[0] * Math.cos(rad),
          Math.sin(rad),
          flatFwd[2] * Math.cos(rad)
        ];
        const centerWorld = [
          state.camPos[0] + dir[0] * 200,
          state.camPos[1] + dir[1] * 200,
          state.camPos[2] + dir[2] * 200
        ];
        const leftWorld = [
          centerWorld[0] - flatRight[0] * (deg === 0 ? 44 : 22),
          centerWorld[1],
          centerWorld[2] - flatRight[2] * (deg === 0 ? 44 : 22)
        ];
        const rightWorld = [
          centerWorld[0] + flatRight[0] * (deg === 0 ? 44 : 22),
          centerWorld[1],
          centerWorld[2] + flatRight[2] * (deg === 0 ? 44 : 22)
        ];
        const pL = worldToScreen(leftWorld, viewProj, w, h);
        const pR = worldToScreen(rightWorld, viewProj, w, h);
        const pC = worldToScreen(centerWorld, viewProj, w, h);
        if (pL && pR && pC) {
          const gap = 0.26;
          const mLx = pC[0] + (pL[0] - pC[0]) * gap;
          const mLy = pC[1] + (pL[1] - pC[1]) * gap;
          const mRx = pC[0] + (pR[0] - pC[0]) * gap;
          const mRy = pC[1] + (pR[1] - pC[1]) * gap;
          pxLine(pL[0], pL[1], mLx, mLy, deg === 0 ? hudGreen : hudDim);
          pxLine(mRx, mRy, pR[0], pR[1], deg === 0 ? hudGreen : hudDim);
          if (deg !== 0) {
            drawPixelText(Math.abs(deg), pR[0] + 3, pR[1] - 3, hudGreen, 'left', 1);
          }
        }
      }
      ctx.restore();

      // Top Heading Tape
      const tapeY = 16;
      const tapeCenter = Math.round(w * 0.5);
      pxLine(tapeCenter - 54, tapeY + 11, tapeCenter + 54, tapeY + 11, hudDim);
      pxLine(tapeCenter, tapeY + 12, tapeCenter - 3, tapeY + 15, hudGreen);
      pxLine(tapeCenter, tapeY + 12, tapeCenter + 3, tapeY + 15, hudGreen);
      const cardinals = { 0: 'N', 45: 'NE', 90: 'E', 135: 'SE', 180: 'S', 225: 'SW', 270: 'W', 315: 'NW' };
      for (let off = -30; off <= 30; off += 5) {
        const d = (((headingDeg + off) % 360) + 360) % 360;
        const snapped = Math.round(d / 5) * 5 % 360;
        const delta = snapped - headingDeg;
        const normDelta = ((delta + 540) % 360) - 180;
        const tx = tapeCenter + Math.round(normDelta * 1.8);
        if (Math.abs(tx - tapeCenter) <= 52) {
          const major = snapped % 15 === 0;
          pxLine(tx, tapeY + (major ? 7 : 9), tx, tapeY + 11, hudGreen);
          if (major) {
            const lbl = cardinals[snapped] || String(snapped / 10).padStart(2, '0');
            drawPixelText(lbl, tx, tapeY - 1, hudGreen, 'center', 1);
          }
        }
      }

      // Left Airspeed Box & Right Altitude Box
      const boxY = Math.round(h * 0.30);
      const leftX = Math.round(w * 0.24);
      const rightX = Math.round(w * 0.76);
      pxRect(leftX - 30, boxY - 5, 32, 11, 'rgba(12, 28, 18, 0.55)', hudGreen);
      drawPixelText(airspeedKts, leftX - 2, boxY - 3, hudGreen, 'right', 1);
      drawPixelText('KT', leftX - 28, boxY + 9, hudDim, 'left', 1);

      pxRect(rightX - 2, boxY - 5, 36, 11, 'rgba(12, 28, 18, 0.55)', hudGreen);
      drawPixelText(altFeet, rightX + 32, boxY - 3, hudGreen, 'right', 1);
      drawPixelText('R ' + radarAltFeet, rightX, boxY + 9, radarAltFeet < 400 ? hudWarn : hudGreen, 'left', 1);

      // G-Load & Missile Pips on HUD
      drawPixelText('G ' + state.gLoad.toFixed(1), leftX - 28, boxY + 21, hudGreen, 'left', 1);
      const readyCount = state.missiles.filter(m => m.ready).length;
      drawPixelText('MSL ' + readyCount, leftX - 28, boxY + 31, readyCount > 0 ? hudGreen : hudWarn, 'left', 1);

      if (state.pullUpActive) {
        drawPixelText('PULL UP', tapeCenter, Math.round(h * 0.44), hudWarn, 'center', 2);
      } else if (state.burner > 0.5) {
        drawPixelText('MAX AB', rightX, boxY + 21, hudWarn, 'left', 1);
      }
    }

    // ========================================================================
    // B. HAND-PLOTTED PIXEL COCKPIT INSTRUMENT PANEL
    // ========================================================================
    const panelTop = Math.round(h * 0.60) + panelOffsetY;
    const panelH = h - panelTop;

    // Canopy windshield side pillars & upper glareshield frame
    ctx.fillStyle = '#181422';
    // Left & right canopy A-pillars
    for (let y = 0; y < panelTop; y++) {
      const frac = y / Math.max(panelTop, 1);
      const pillarW = Math.round(8 + frac * 18);
      ctx.fillRect(0, y, pillarW, 1);
      ctx.fillRect(w - pillarW, y, pillarW, 1);
      ctx.fillStyle = '#38304c';
      ctx.fillRect(pillarW, y, 2, 1);
      ctx.fillRect(w - pillarW - 2, y, 2, 1);
      ctx.fillStyle = '#181422';
    }

    // Glareshield coaming
    pxRect(0, panelTop - 5, w, 6, '#2b243b', '#52466b');
    pxRect(0, panelTop, w, panelH, '#1d1929');

    // Warning Annunciator Strip along glareshield
    const lamps = [
      { label: 'PULL UP', active: state.pullUpActive, col: '#ff4838' },
      { label: 'LOW ALT', active: state.lowAltActive, col: '#ffaa33' },
      { label: 'OVERSPD', active: state.overspeedActive, col: '#ffaa33' },
      { label: 'MSL REL', active: state.missileWarnTimer > 0, col: '#58f28c' }
    ];
    const lampW = 46;
    const lampStartX = Math.round(w * 0.5 - (lamps.length * (lampW + 4)) * 0.5);
    for (let i = 0; i < lamps.length; i++) {
      const lp = lamps[i];
      const lx = lampStartX + i * (lampW + 4);
      const ly = panelTop + 3;
      pxRect(lx, ly, lampW, 10, lp.active ? lp.col : '#14111c', '#453b59');
      drawPixelText(lp.label, lx + lampW * 0.5, ly + 2, lp.active ? '#120d18' : '#4a415e', 'center', 1);
    }

    // Layout geometry for instruments across panel width
    const instrTop = panelTop + 17;
    const dialR = Math.max(16, Math.min(25, Math.floor(panelH * 0.21)));
    const row1Y = instrTop + dialR + 2;
    const row2Y = Math.min(h - dialR - 14, row1Y + dialR * 2 + 12);
    const cx = Math.round(w * 0.5);

    function drawDialBezel(x, y, r, title) {
      pxRect(x - r - 2, y - r - 2, r * 2 + 5, r * 2 + 5, '#120f1a', '#493f61');
      pxCircle(x, y, r, '#756894');
      if (title) drawPixelText(title, x, y - r - 9, '#b5a8cc', 'center', 1);
    }

    // 1. AIRSPEED INDICATOR (Top-Left of T-cluster)
    const asiX = cx - dialR * 2 - 14;
    drawDialBezel(asiX, row1Y, dialR, 'IAS');
    for (let a = 0; a < 10; a++) {
      const ang = -Math.PI * 0.75 + (a / 9) * Math.PI * 1.5;
      pxLine(
        asiX + Math.cos(ang) * (dialR - 4), row1Y + Math.sin(ang) * (dialR - 4),
        asiX + Math.cos(ang) * (dialR - 1), row1Y + Math.sin(ang) * (dialR - 1),
        a >= 8 ? '#ff5947' : '#e8dec8'
      );
    }
    const asiAng = -Math.PI * 0.75 + Math.min(1, airspeedKts / 900) * Math.PI * 1.5;
    pxLine(asiX, row1Y, asiX + Math.cos(asiAng) * (dialR - 4), row1Y + Math.sin(asiAng) * (dialR - 4), '#ffbe66');
    drawPixelText(airspeedKts, asiX, row1Y + Math.round(dialR * 0.35), '#9be8b8', 'center', 1);

    // 2. ARTIFICIAL HORIZON / ADI (Top-Center)
    const adiX = cx;
    drawDialBezel(adiX, row1Y, dialR, 'ADI');
    ctx.save();
    ctx.beginPath();
    ctx.arc(adiX, row1Y, dialR - 1, 0, Math.PI * 2);
    ctx.clip();
    // Sky & Earth halves rotated by aircraft bank and shifted by pitch
    const pitchPx = Math.max(-dialR, Math.min(dialR, Math.round((state.pitch / 0.85) * dialR)));
    const cosR = Math.cos(-totalRoll), sinR = Math.sin(-totalRoll);
    for (let py = -dialR; py <= dialR; py++) {
      for (let px = -dialR; px <= dialR; px++) {
        const localY = px * sinR + py * cosR + pitchPx;
        ctx.fillStyle = localY < 0 ? '#2f5f99' : (localY === 0 ? '#ffffff' : '#6e452b');
        ctx.fillRect(adiX + px, row1Y + py, 1, 1);
      }
    }
    // Fixed yellow miniature aircraft reference
    pxLine(adiX - 10, row1Y, adiX - 4, row1Y, '#ffd452');
    pxLine(adiX - 4, row1Y, adiX, row1Y + 3, '#ffd452');
    pxLine(adiX, row1Y + 3, adiX + 4, row1Y, '#ffd452');
    pxLine(adiX + 4, row1Y, adiX + 10, row1Y, '#ffd452');
    ctx.restore();

    // 3. ALTIMETER WITH DIGITAL DRUM READOUT (Top-Right of T-cluster)
    const altX = cx + dialR * 2 + 14;
    drawDialBezel(altX, row1Y, dialR, 'ALT');
    for (let a = 0; a < 10; a++) {
      const ang = -Math.PI * 0.5 + (a / 10) * Math.PI * 2;
      pxLine(
        altX + Math.cos(ang) * (dialR - 3), row1Y + Math.sin(ang) * (dialR - 3),
        altX + Math.cos(ang) * (dialR - 1), row1Y + Math.sin(ang) * (dialR - 1),
        '#e8dec8'
      );
    }
    const altAng = -Math.PI * 0.5 + ((altFeet % 1000) / 1000) * Math.PI * 2;
    pxLine(altX, row1Y, altX + Math.cos(altAng) * (dialR - 3), row1Y + Math.sin(altAng) * (dialR - 3), '#ffffff');
    // Digital stepped altitude window
    pxRect(altX - 15, row1Y - 4, 31, 9, '#0a0810', '#8b7ea6');
    drawPixelText(String(altFeet).padStart(4, '0'), altX + 14, row1Y - 3, '#ffd27d', 'right', 1);

    // 4. TURN & SLIP COORDINATOR (Bottom-Left of T-cluster)
    drawDialBezel(asiX, row2Y, dialR, 'TURN');
    const turnOffset = Math.max(-1, Math.min(1, -state.roll / 0.9));
    const wingTilt = turnOffset * 0.45;
    pxLine(
      asiX - Math.cos(wingTilt) * (dialR - 5), row2Y - Math.sin(wingTilt) * (dialR - 5) - 3,
      asiX + Math.cos(wingTilt) * (dialR - 5), row2Y + Math.sin(wingTilt) * (dialR - 5) - 3,
      '#ffbe66'
    );
    // Inclinometer slip ball tube
    pxRect(asiX - 12, row2Y + 6, 25, 6, '#232924', '#869488');
    const ballX = asiX + Math.round(Math.sin(state.roll) * 5);
    pxRect(ballX - 2, row2Y + 7, 4, 4, '#f5f2e6');

    // 5. HEADING COMPASS HSI (Bottom-Center)
    drawDialBezel(adiX, row2Y, dialR, 'HDG');
    const hdgRad = -state.yaw;
    for (let d = 0; d < 360; d += 30) {
      const a = hdgRad + (d * Math.PI / 180) - Math.PI * 0.5;
      const rIn = d % 90 === 0 ? dialR - 5 : dialR - 3;
      pxLine(
        adiX + Math.cos(a) * rIn, row2Y + Math.sin(a) * rIn,
        adiX + Math.cos(a) * (dialR - 1), row2Y + Math.sin(a) * (dialR - 1),
        d === 0 ? '#ff6452' : '#d8cee8'
      );
    }
    // Fixed lubber triangle & heading digits
    pxLine(adiX, row2Y - dialR + 1, adiX - 2, row2Y - dialR + 5, '#ffbe66');
    pxLine(adiX, row2Y - dialR + 1, adiX + 2, row2Y - dialR + 5, '#ffbe66');
    drawPixelText(String(headingDeg).padStart(3, '0'), adiX, row2Y - 3, '#9be8b8', 'center', 1);

    // 6. VERTICAL SPEED INDICATOR (Bottom-Right of T-cluster)
    drawDialBezel(altX, row2Y, dialR, 'VSI');
    const vsiNorm = Math.max(-1, Math.min(1, vsiFpm / 6000));
    const vsiAng = Math.PI + vsiNorm * (Math.PI * 0.72);
    pxLine(altX, row2Y, altX + Math.cos(vsiAng) * (dialR - 4), row2Y + Math.sin(vsiAng) * (dialR - 4), '#9be8b8');
    drawPixelText(vsiFpm >= 0 ? 'UP' : 'DN', altX + 4, row2Y + 5, vsiFpm >= 0 ? '#9be8b8' : '#ff9e42', 'center', 1);

    // 7. AMBER GROUND-MAPPING RADAR WITH SWEEP (Right MFD)
    const radarSize = Math.min(Math.floor(panelH * 0.78), Math.floor(w * 0.21));
    const radarX = Math.min(w - radarSize - 16, altX + dialR + 16);
    const radarY = instrTop + 2;
    if (radarX + radarSize < w - 6 && radarSize >= 36) {
      pxRect(radarX - 3, radarY - 3, radarSize + 6, radarSize + 6, '#100d17', '#5a4e73');
      drawPixelText('GND RDR', radarX + radarSize * 0.5, radarY - 11, '#ffb85c', 'center', 1);

      const sweepPhase = (state.time * 0.85) % 1.0; // Left-to-right sector sweep
      const forwardX = Math.sin(state.yaw);
      const forwardZ = -Math.cos(state.yaw);
      const rightX = Math.cos(state.yaw);
      const rightZ = Math.sin(state.yaw);

      // Plot terrain elevation & water returns ahead of aircraft
      const stepPx = 2;
      for (let py = 0; py < radarSize; py += stepPx) {
        const fwdDist = (1.0 - py / radarSize) * 95.0 + 4.0;
        for (let px = 0; px < radarSize; px += stepPx) {
          const latFrac = (px / radarSize) * 2 - 1;
          const latDist = latFrac * fwdDist * 0.85;
          if (Math.abs(latFrac) > 0.92) continue;

          const wx = state.pos[0] + forwardX * fwdDist + rightX * latDist;
          const wz = state.pos[2] + forwardZ * fwdDist + rightZ * latDist;
          const hNorm = sampleRawNormCPU(wx, wz);

          // Sweep phosphor persistence
          const scanPos = px / radarSize;
          const distToSweep = ((sweepPhase - scanPos) + 1.0) % 1.0;
          const phosphor = Math.max(0.25, 1.0 - distToSweep * 0.85);

          let col = '#1f1206';
          if (hNorm > SEA_LEVEL) {
            const relH = (hNorm - SEA_LEVEL) / (1.0 - SEA_LEVEL);
            if (relH > 0.52) col = phosphor > 0.75 ? '#ffe082' : '#d9821e';
            else if (relH > 0.20) col = phosphor > 0.75 ? '#ffb03a' : '#9c5210';
            else col = '#5e2e08';
          }
          ctx.fillStyle = col;
          ctx.fillRect(radarX + px, radarY + py, stepPx, stepPx);
        }
      }
      // Sweep line & range arcs
      const sx = radarX + Math.round(sweepPhase * (radarSize - 1));
      pxLine(sx, radarY, sx, radarY + radarSize - 1, '#ffe699');
      pxLine(radarX + Math.round(radarSize * 0.5), radarY + radarSize - 4, radarX + Math.round(radarSize * 0.5), radarY + radarSize - 1, '#ffe699');
    }

    // 8. LEFT CONSOLE: DUAL ENGINE GAUGES, LOCAL CLOCK & ANIMATED THROTTLE LEVER
    const leftPanelW = Math.min(Math.floor(w * 0.21), asiX - dialR - 18);
    if (leftPanelW >= 46) {
      const lx = Math.max(10, asiX - dialR - leftPanelW - 12);
      // Throttle quadrant
      const thX = lx + 4;
      const thY = instrTop + 4;
      const thH = Math.max(36, panelH - 28);
      pxRect(thX, thY, 14, thH, '#0d0a14', '#574b70');
      drawPixelText('THR', thX + 7, thY - 9, '#b5a8cc', 'center', 1);
      // Afterburner detent mark
      const abDetentY = thY + Math.round(thH * 0.34);
      pxLine(thX + 1, abDetentY, thX + 12, abDetentY, '#ff6d42');
      // Throttle handle position tracks cruise -> afterburner
      const thrustNorm = 0.62 + state.burner * 0.36;
      const knobY = thY + Math.round((1.0 - thrustNorm) * (thH - 8));
      pxRect(thX - 2, knobY, 18, 8, state.burner > 0.4 ? '#ff8e3c' : '#9aa3b8', '#ffffff');

      // Dual Engine RPM & EGT vertical bar gauges
      const gX = thX + 22;
      const rpmPct = Math.round(86 + state.burner * 14);
      const egtC   = Math.round(640 + state.burner * 290);
      drawPixelText('RPM', gX + 7, thY - 9, '#b5a8cc', 'center', 1);
      drawPixelText('EGT', gX + 24, thY - 9, '#b5a8cc', 'center', 1);

      const barH = Math.max(24, thH - 14);
      pxRect(gX + 2, thY, 10, barH, '#100d18', '#52466b');
      const rpmFill = Math.round((rpmPct / 105) * (barH - 2));
      pxRect(gX + 3, thY + barH - 1 - rpmFill, 8, rpmFill, state.burner > 0.4 ? '#ffb84d' : '#69e898');

      pxRect(gX + 19, thY, 10, barH, '#100d18', '#52466b');
      const egtFill = Math.round((egtC / 1000) * (barH - 2));
      pxRect(gX + 20, thY + barH - 1 - egtFill, 8, egtFill, state.burner > 0.4 ? '#ff6442' : '#ffbe5c');

      // Real local time digital clock at bottom of left console
      const now = new Date();
      const hh = String(now.getHours()).padStart(2, '0');
      const mm = String(now.getMinutes()).padStart(2, '0');
      const ss = String(now.getSeconds()).padStart(2, '0');
      const clkY = thY + barH + 4;
      pxRect(gX, clkY, 44, 10, '#0b0912', '#52466b');
      drawPixelText(`${hh}:${mm}:${ss}`, gX + 22, clkY + 2, '#9be8b8', 'center', 1);
    }
  }

  // ============================================================================
  // 12. ADAPTIVE RESOLUTION SCALING & MAIN LOOP
  // ============================================================================
  let resScale = 1.0;
  let internalW = 604;
  let internalH = BASE_TARGET_H;
  let frameTimeAccum = 0;
  let frameCount = 0;

  function resizeCanvases() {
    const cssW = window.innerWidth || 1280;
    const cssH = window.innerHeight || 720;
    const targetH = Math.max(200, Math.round(BASE_TARGET_H * resScale));
    const targetW = Math.max(260, Math.round(targetH * (cssW / cssH)));
    if (glCanvas.width !== targetW || glCanvas.height !== targetH) {
      glCanvas.width = targetW;
      glCanvas.height = targetH;
      hudCanvas.width = targetW;
      hudCanvas.height = targetH;
      internalW = targetW;
      internalH = targetH;
    }
  }
  window.addEventListener('resize', resizeCanvases);
  resizeCanvases();

  // Upload generated height/biome/shadow map to WebGL2 texture
  let worldTex = null;
  function createWorldGLTexture(bytes) {
    const tex = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, MAP_SIZE, MAP_SIZE, 0, gl.RGBA, gl.UNSIGNED_BYTE, bytes);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
    return tex;
  }

  // Start async world generation and launch main loop
  buildWorldTexture().then((bytes) => {
    worldBytes = bytes;
    worldTex = createWorldGLTexture(bytes);

    // Ensure starting altitude is comfortably above local mountains
    const startGround = sampleTerrainHeightCPU(state.pos[0], state.pos[2]);
    state.pos[1] = Math.max(34.5, startGround + 14.0);

    setTimeout(() => {
      document.getElementById('loader').classList.add('hidden');
    }, 180);

    let lastTime = performance.now();
    function frame(now) {
      const rawDt = (now - lastTime) * 0.001;
      lastTime = now;
      const dt = Math.min(0.05, Math.max(0.001, rawDt));

      // Adaptive resolution guard for integrated GPUs
      frameTimeAccum += rawDt;
      frameCount++;
      if (frameCount >= 45) {
        const avgMs = (frameTimeAccum / frameCount) * 1000;
        if (avgMs > 25.0 && resScale > 0.65) {
          resScale = Math.max(0.65, resScale - 0.1);
          resizeCanvases();
        } else if (avgMs < 13.5 && resScale < 1.0) {
          resScale = Math.min(1.0, resScale + 0.05);
          resizeCanvases();
        }
        frameTimeAccum = 0;
        frameCount = 0;
      }

      stepSimulation(dt);
      renderWebGL(internalW, internalH);
      renderCockpitAndHUD(internalW, internalH);

      requestAnimationFrame(frame);
    }

    requestAnimationFrame(frame);
  });
})();
</script>
</body>
</html>