• 01 - Games
  • 02 - Creative Instruments & Explorers
  • 03 - Language, Signals & Text
  • 04 - Developer & Web Utilities
  • 05 - Generators & Data
  • 06 - Colour Theory
  • 07 - Music 26
  • 08 - 3D, Shaders & Visuals
ARCHIVE
  • Pip
  • Great White
  • Canyon Run
  • Diamond Vessel
  • T-6 Jedi Shuttle
  • N1 Starfighter
  • Clawdia

CANYON RUN SOURCE CODE

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Wayfarer canyon run</title>
<style>
:root{--bg:#e6dccd;--fg:#2b2521;--chip-bg:rgba(255,248,238,.74);--chip-fg:#2b2521;--chip-line:rgba(43,37,33,.16);color-scheme:light dark;box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#15130f;--fg:#eadfcd;--chip-bg:rgba(24,20,16,.62);--chip-fg:#f1e6d6;--chip-line:rgba(241,230,214,.18);color-scheme:dark}}
:root[data-theme="dark"]{--bg:#15130f;--fg:#eadfcd;--chip-bg:rgba(24,20,16,.62);--chip-fg:#f1e6d6;--chip-line:rgba(241,230,214,.18);color-scheme:dark}
html,body{margin:0;height:100%;overflow:hidden;background:var(--bg)}
#app{position:fixed;inset:0;background:var(--bg)}
#gl{position:absolute;inset:0;width:100%;height:100%;display:block}
#hud{position:fixed;right:0;bottom:0;z-index:2;padding:0 max(16px,env(safe-area-inset-right,0px)) calc(16px + env(safe-area-inset-bottom,0px)) 0}
@media (max-width:767px){#hud{padding:0 24px 56px 0}}
@media (min-width:768px){#hud{padding:0 80px 44px 0}}
#snd{display:inline-flex;align-items:center;gap:.5rem;min-height:44px;padding:0 1.05rem 0 .9rem;border-radius:999px;border:1px solid var(--chip-line);background:var(--chip-bg);color:var(--chip-fg);font:500 .9375rem/1 system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);cursor:pointer}
#snd:focus-visible{outline:2px solid var(--chip-fg);outline-offset:3px}
#snd svg{width:18px;height:18px;flex:none}
#snd .on{display:none}#snd[aria-pressed="true"] .on{display:inline}#snd[aria-pressed="true"] .off{display:none}
#msg{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);max-width:min(32rem,calc(100% - 3rem));margin:0;color:var(--fg);font:400 1rem/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;text-align:center}
</style>
</head>
<body>
<div id="app"></div>
<p id="msg" role="status" hidden></p>
<div id="hud" hidden><button id="snd" type="button" aria-pressed="false">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 9.5h3.2L12 5.5v13l-4.8-4H4z"/><g class="on"><path d="M15.5 9a4.2 4.2 0 0 1 0 6"/><path d="M18.3 6.5a8 8 0 0 1 0 11"/></g><g class="off"><path d="m16 9.5 5 5"/><path d="m21 9.5-5 5"/></g></svg>
<span class="off">Play soundtrack</span><span class="on">Mute soundtrack</span></button></div>
<script type="module">
const THREE_URL = "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js";
let THREE;

// ---------- helpers ----------
const D2R = Math.PI / 180;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const clamp01 = v => clamp(v, 0, 1);
const sstep = (a, b, x) => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };
const smoother = v => { const t = clamp01(v); return t * t * t * (t * (t * 6 - 15) + 10); };
const phase = (a, b, x) => smoother((x - a) / (b - a));
const smin = (a, b, k) => { const h = clamp01(.5 + .5 * (b - a) / k); return b + (a - b) * h - k * h * (1 - h); };
const rng = seed => () => {
  seed = seed + 0x6D2B79F5 | 0;
  let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
  t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
  return ((t ^ t >>> 14) >>> 0) / 4294967296;
};

// ---------- noise ----------
function makeNoise(seed) {
  const R = rng(seed), p = new Uint8Array(256), perm = new Uint8Array(512);
  const gx = new Float32Array(256), gy = new Float32Array(256);
  for (let i = 0; i < 256; i++) { p[i] = i; const a = R() * Math.PI * 2; gx[i] = Math.cos(a); gy[i] = Math.sin(a); }
  for (let i = 255; i > 0; i--) { const j = R() * (i + 1) | 0, t = p[i]; p[i] = p[j]; p[j] = t; }
  for (let i = 0; i < 512; i++) perm[i] = p[i & 255];
  return (x, y) => {
    const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi, X = xi & 255, Y = yi & 255;
    const a = perm[perm[X] + Y], b = perm[perm[X + 1] + Y], c = perm[perm[X] + Y + 1], d = perm[perm[X + 1] + Y + 1];
    const u = xf * xf * xf * (xf * (xf * 6 - 15) + 10), v = yf * yf * yf * (yf * (yf * 6 - 15) + 10);
    const na = gx[a] * xf + gy[a] * yf, nb = gx[b] * (xf - 1) + gy[b] * yf;
    const nc = gx[c] * xf + gy[c] * (yf - 1), nd = gx[d] * (xf - 1) + gy[d] * (yf - 1);
    const x1 = na + (nb - na) * u, x2 = nc + (nd - nc) * u;
    return (x1 + (x2 - x1) * v) * 1.4;
  };
}
const fbm = (n, x, y, o) => {
  let s = 0, a = .5, f = 1, w = 0;
  for (let i = 0; i < o; i++) { s += a * n(x * f + i * 17.31, y * f - i * 9.13); w += a; a *= .5; f *= 2.03; }
  return s / w;
};

// ---------- the world (metres; y is up) ----------
const WORLD = { size: 4400, n: 449, plains: 58, plateau: 176, water: 50, clear: 18 };
const PAD = { x: 0, z: 1100, r: 34, ground: 58, deck: 59.4 };
const ZONES = [{ x: 0, z: 1060, r: 420 }, { x: 120, z: -980, r: 540 }, { x: -760, z: -520, r: 450 }];
const LAKE = { x: 120, z: -980 };
const ARCH_AT = [1085, 10];
const SUN_DIR = [-.683, .454, -.573];
const MOON_DIR = [.596, .375, .71];
const SKY = { zen: "#3c7592", hor: "#e0bd98", gnd: "#b08565" };
// The circuit: [x, z, altitude]. It starts and ends hovering over the pad.
const ROUTE = [
  [0, 1100, 0], [250, 1082, 84], [520, 950, 78], [760, 700, 78], [820, 420, 80], [1050, 180, 80],
  [1100, -150, 84], [950, -450, 78], [1150, -750, 200], [850, -1050, 150], [500, -1150, 70],
  [150, -900, 62], [-250, -1000, 62], [-600, -800, 75], [-850, -500, 78], [-700, -200, 78],
  [-1000, 100, 80], [-1100, 450, 82], [-850, 750, 80], [-500, 900, 84], [-250, 1100, 85],
];

// ---------- the ship: an original swing-wing courier (nose at +x, stations aft from the nose) ----------
const XS = s => 10 - s;
const HULL = { r: 1.6, sy: .82, sz: 1.12 };
const BELLY = -HULL.r * HULL.sy;
const NAC = { y: -.46, z: 2.15, r: .85 };
const WINGP = { s: 9.5, y: .55, z: 2.6 };
const GEAR = { stroke: 1.4, padR: .38, legs: [{ s: 4.6, z: 0, y: -1.24 }, { s: 15.2, z: -NAC.z, y: BELLY }, { s: 15.2, z: NAC.z, y: BELLY }] };
const LANDED_H = -BELLY + GEAR.stroke;
const HOVER = 24;

// ---------- the flight: one 136-second loop ----------
// pad 0–4 s · lift 4–10 · accelerate 10–16 · cruise to 118 · brake to 124 · descend to 132 · settle
const LOOP = 136;

// ---------- world data (pure numbers, no rendering) ----------
function buildWorldData() {
  const n1 = makeNoise(11), n2 = makeNoise(29);
  const { size, n: N, plains, plateau, clear } = WORLD;
  const half = size / 2, cell = size / (N - 1);

  const pts = ROUTE.map(([x, z, y], i) => new THREE.Vector3(x, i ? y : PAD.deck + LANDED_H + HOVER, z));
  const curve = new THREE.CatmullRomCurve3(pts, true, "centripetal");
  curve.arcLengthDivisions = 4000;
  const L = curve.getLength();
  const NS = Math.ceil(L / 4), samples = [];
  for (let i = 0; i < NS; i++) samples.push(curve.getPointAt(i / NS));
  const nearestS = (x, z) => {
    let b = 0, bd = Infinity;
    samples.forEach((p, i) => { const d = (p.x - x) ** 2 + (p.z - z) ** 2; if (d < bd) { bd = d; b = i; } });
    return b / NS * L;
  };

  const baseHeight = (x, z) => {
    let open = 0;
    for (const zn of ZONES) open = Math.max(open, 1 - sstep(.8, 1, Math.hypot(x - zn.x, z - zn.z) / zn.r + .2 * fbm(n1, x / 260, z / 260, 3)));
    open *= 1 - .92 * sstep(.3, .4, fbm(n2, x / 300, z / 300, 4));
    const m = 1 - open;
    let h = plains + (plateau - plains) * m;
    h += m * (14 * fbm(n1, x / 600 + 5, z / 600 - 2, 3) + 70 * sstep(.3, .52, fbm(n2, x / 380 + 20, z / 380 + 11, 4)));
    const k = h / 15, fl = Math.floor(k);
    h = .3 * h + .7 * 15 * (fl + sstep(.5, .85, k - fl));
    const lake = 1 - sstep(190, 470, Math.hypot(x - LAKE.x, z - LAKE.z) + 70 * fbm(n1, x / 200 + 9, z / 200, 3));
    h += lake * (32 * sstep(.2, .45, fbm(n2, x / 130 - 4, z / 130 + 6, 3)) - 34);
    h += 2.2 * fbm(n1, x / 40, z / 40, 3);
    const R = Math.hypot(x, z) + 90 * fbm(n1, x / 300 - 7, z / 300 + 4, 3);
    return h + sstep(1550, 2120, R) * (230 + 120 * fbm(n2, x / 500 + 3, z / 500 - 8, 4));
  };

  // Distance from every grid point to the flight path, and the path's altitude there.
  const RAD = 200, dist = new Float32Array(N * N).fill(1e9), pathY = new Float32Array(N * N);
  for (const p of samples) {
    const i0 = Math.max(0, Math.floor((p.x - RAD + half) / cell)), i1 = Math.min(N - 1, Math.ceil((p.x + RAD + half) / cell));
    const j0 = Math.max(0, Math.floor((p.z - RAD + half) / cell)), j1 = Math.min(N - 1, Math.ceil((p.z + RAD + half) / cell));
    for (let j = j0; j <= j1; j++) {
      const dz = j * cell - half - p.z;
      for (let i = i0; i <= i1; i++) {
        const dx = i * cell - half - p.x, d2 = dx * dx + dz * dz, k = j * N + i;
        if (d2 < dist[k]) { dist[k] = d2; pathY[k] = p.y; }
      }
    }
  }
  for (let k = 0; k < dist.length; k++) dist[k] = Math.sqrt(dist[k]);

  // Heights: mesas and basins, with a canyon carved along the route and the pad levelled.
  const H = new Float32Array(N * N);
  for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) {
    const x = i * cell - half, z = j * cell - half, k = j * N + i;
    let h = baseHeight(x, z);
    const d = dist[k];
    if (d < RAD) {
      const floor = pathY[k] - clear - 1.5 * Math.max(0, fbm(n2, x / 90, z / 90, 2));
      const hw = 46 + 16 * fbm(n1, x / 170 + 3, z / 170, 2);
      h = smin(h, floor + .9 * Math.pow(Math.max(0, d - hw), 1.22), 9);
    }
    const pm = 1 - sstep(64, 110, Math.hypot(x - PAD.x, z - PAD.z));
    H[k] = h + (PAD.ground - h) * pm;
  }
  const sampler = A => (x, z) => {
    const fx = clamp((x + half) / cell, 0, N - 1.001), fz = clamp((z + half) / cell, 0, N - 1.001);
    const i = fx | 0, j = fz | 0, u = fx - i, v = fz - j, k = j * N + i;
    return (A[k] * (1 - u) + A[k + 1] * u) * (1 - v) + (A[k + N] * (1 - u) + A[k + N + 1] * u) * v;
  };
  const heightAt = sampler(H), pathDistAt = sampler(dist);

  // Baked sunlight: march toward the sun across the heightmap for soft terrain shadows.
  const sh = Math.hypot(SUN_DIR[0], SUN_DIR[2]);
  const stx = SUN_DIR[0] / sh * cell, stz = SUN_DIR[2] / sh * cell, rise = SUN_DIR[1] / sh * cell;
  let maxH = -Infinity;
  for (let k = 0; k < H.length; k++) if (H[k] > maxH) maxH = H[k];
  const lit = new Float32Array(N * N);
  for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) {
    const k = j * N + i, x = i * cell - half, z = j * cell - half, h0 = H[k] + 1;
    let occ = 0;
    for (let s = 1; s <= 56; s++) {
      const ry = h0 + rise * s;
      if (ry > maxH) break;
      const o = (heightAt(x + stx * s, z + stz * s) - ry) / (1.5 + s * .8);
      if (o > occ) { occ = o; if (occ >= 1) break; }
    }
    lit[k] = 1 - clamp01(occ);
  }
  // Cheap ambient occlusion: how far below its neighbourhood each point sits.
  const blurPass = (src, dst, dx, dy) => {
    for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) {
      let s = 0;
      for (let t = -4; t <= 4; t++) s += src[clamp(j + dy * t, 0, N - 1) * N + clamp(i + dx * t, 0, N - 1)];
      dst[j * N + i] = s / 9;
    }
  };
  const tmp = new Float32Array(N * N), B = new Float32Array(N * N), ao = new Float32Array(N * N);
  blurPass(H, tmp, 1, 0); blurPass(tmp, B, 0, 1);
  for (let k = 0; k < H.length; k++) ao[k] = 1 - .38 * clamp01((B[k] - H[k]) / 50);

  // Rock spires in the open valley, kept clear of the route.
  const spires = [], R = rng(7), zs = ZONES[2];
  for (let tries = 0; spires.length < 30 && tries < 4000; tries++) {
    const a = R() * Math.PI * 2, r = Math.sqrt(R()) * zs.r * .92;
    const x = zs.x + Math.cos(a) * r, z = zs.z + Math.sin(a) * r;
    const rad = 7 + R() * 9, hgt = 45 + R() * 85, pd = pathDistAt(x, z);
    if (pd < 30 + rad * 1.5 || pd > 300 || (pd > 120 && R() < .55) || heightAt(x, z) > 75) continue;
    if (spires.some(s => Math.hypot(s.x - x, s.z - z) < s.rad + rad + 18)) continue;
    spires.push({ x, z, rad, hgt, y0: heightAt(x, z) - 6 });
  }

  // A natural arch spanning the canyon.
  const sArch = nearestS(...ARCH_AT);
  const ap = curve.getPointAt(sArch / L), at = curve.getTangentAt(sArch / L);
  const arch = { s: sArch, c: new THREE.Vector3(ap.x, ap.y - clear - 10, ap.z), n: new THREE.Vector3(-at.z, 0, at.x).normalize(), R: 84, tube: 13 };

  return { n1, n2, N, half, cell, curve, L, H, lit, ao, heightAt, pathDistAt, keyS: ROUTE.map(([x, z]) => nearestS(x, z)), arch, spires };
}

// ---------- flight model ----------
function createFlight(world) {
  const V3 = THREE.Vector3, { curve, L } = world;
  const V = L / 108;
  const start = curve.getPointAt(0);
  const t0 = curve.getTangentAt(0), f0 = new V3(t0.x, 0, t0.z).normalize();
  const F6 = u => u * u * u * u * (u * (u - 3) + 2.5);
  const distAt = t => t <= 10 ? 0 : t < 16 ? V * 6 * F6((t - 10) / 6) : t < 118 ? V * (t - 13) : t < 124 ? L - V * 6 * F6((124 - t) / 6) : L;
  const wrap = t => ((t % LOOP) + LOOP) % LOOP;
  const posAt = (t, out = new V3()) => {
    t = wrap(t);
    if (t <= 10) { out.copy(start); out.y -= HOVER * (1 - phase(4, 10, t)); return out; }
    if (t >= 124) { out.copy(start); out.y -= HOVER * phase(124, 132, t); return out; }
    return curve.getPointAt(clamp(distAt(t) / L, 0, 1), out);
  };
  const WUP = new V3(0, 1, 0), _a = new V3(), _b = new V3(), _c = new V3(), _m = new THREE.Matrix4();
  const MAXB = 72 * D2R;
  function stateAt(t) {
    t = wrap(t);
    const pos = posAt(t), s = distAt(t);
    const f = t <= 10 || t >= 124 ? f0.clone() : curve.getTangentAt(clamp(s / L, 0, 1));
    if (t > 10 && t < 124) f.lerp(f0, 1 - Math.min(phase(10, 13, t), 1 - phase(121, 124, t))).normalize();
    // Bank into turns from the sideways part of the acceleration.
    const h = .9;
    posAt(t + h, _a); posAt(t - h, _b);
    const acc = _a.add(_b).addScaledVector(pos, -2).divideScalar(h * h);
    const level = WUP.clone().addScaledVector(f, -f.y).normalize();
    acc.addScaledVector(f, -acc.dot(f)).addScaledVector(level, -acc.dot(level));
    const up = level.clone().multiplyScalar(9.81).addScaledVector(acc, 1.25).normalize();
    if (up.angleTo(level) > MAXB) { _c.crossVectors(level, up).normalize(); up.copy(level).applyAxisAngle(_c, MAXB); }
    const side = new V3().crossVectors(f, up).normalize();
    up.crossVectors(side, f).normalize();
    const q = new THREE.Quaternion().setFromRotationMatrix(_m.makeBasis(f, up, side));
    const fh = new V3(f.x, 0, f.z).normalize(), sh = new V3(-fh.z, 0, fh.x);
    const idle = phase(1.5, 4, t) * (1 - phase(132, 135.5, t));
    const main = phase(8.5, 11, t) * (1 - phase(119, 123, t));
    const c = {
      sweep: 16 + 39 * (phase(13, 19, t) - phase(114, 120, t)),
      stroke: GEAR.stroke * (1 - phase(6.5, 8.5, t) + phase(125, 128, t)),
      glow: Math.max(.3 * idle, main),
      thrust: main,
      hover: phase(2.5, 4.5, t) * (1 - phase(11, 15, t)) + phase(115, 119, t) * (1 - phase(131.5, 134, t)),
    };
    return { t, pos, q, f, up, side, fh, sh, s, c };
  }
  return { V, f0, posAt, stateAt, distAt };
}

// ---------- camera director: 18 setups across the loop ----------
function createDirector(world, flight) {
  const V3 = THREE.Vector3, { curve, L, heightAt, keyS, arch } = world, { V, f0, stateAt, posAt } = flight;
  const tOf = s => 13 + s / V, tK = i => tOf(keyS[i]), tArch = tOf(arch.s);
  const u = s => ((s / L) % 1 + 1) % 1;
  const pathAt = s => curve.getPointAt(u(s));
  const sideAt = s => { const t = curve.getTangentAt(u(s)); return new V3(-t.z, 0, t.x).normalize(); };
  const onGround = (p, lift) => { p.y = heightAt(p.x, p.z) + lift; return p; };
  const s0 = new V3(-f0.z, 0, f0.x);

  const lowSpot = onGround(pathAt(130).addScaledVector(sideAt(130), 30), 2.2);
  const archSpot = pathAt(arch.s + 170).addScaledVector(sideAt(arch.s + 170), 8).add(new V3(0, -2, 0));
  const popSpot = onGround(pathAt(keyS[8]).addScaledVector(sideAt(keyS[8]), 75), 4);
  const waterSpot = pathAt(keyS[11]).addScaledVector(sideAt(keyS[11]), 16);
  waterSpot.y = Math.max(WORLD.water + 1.2, heightAt(waterSpot.x, waterSpot.z) + 2);
  const tFly = tK(17) + 6, flySpot = posAt(tFly).addScaledVector(stateAt(tFly).sh, 24).add(new V3(0, -4, 0));
  const approachSpot = new V3(PAD.x, PAD.ground + 9, PAD.z).addScaledVector(s0, -80).addScaledVector(f0, -25);

  const shots = [
    [0, "orbit", { az: 205, ref: 0 }],
    [9, "fixed", { p: lowSpot, fov: 40 }],
    [15, "chase", { back: 38, up: 8, ahead: 30, fov: 50 }],
    [tK(2) + 2, "front", { ahead: 48, up: 4, fov: 46 }],
    [tK(3) + 2, "high", { back: 55, side: 25, alt: 150, lead: 25, fov: 40 }],
    [tArch - 4, "fixed", { p: archSpot, fov: 50 }],
    [tArch + 2.1, "chase", { back: 30, up: 6, ahead: 30, fov: 55 }],
    [tK(7) + 3.2, "fixed", { p: popSpot, fov: 40 }],
    [tK(8) + 2.2, "chase", { back: 60, up: 20, ahead: 40, fov: 48 }],
    [tK(10), "fixed", { p: waterSpot, fov: 44 }],
    [tK(11) + 1.2, "side", { dist: 42, up: 2, lag: 6, fov: 40 }],
    [tK(12) + 1.5, "high", { back: 90, side: 60, alt: 140, lead: 40, fov: 42 }],
    [tK(14) + 1, "chase", { back: 32, up: 4, ahead: 30, fov: 56 }],
    [tK(15) + 3, "shoulder", {}],
    [tK(17) + 2, "fixed", { p: flySpot, fov: 42 }],
    [tK(17) + 8.5, "front", { ahead: 55, up: 8, fov: 46 }],
    [tK(19) + 1, "fixed", { p: approachSpot, fov: 36 }],
    [126, "orbit", { az: 205, ref: LOOP }],
  ];

  const kinds = {
    orbit: (st, t, o) => {
      const az = (o.az + 2 * (t - o.ref)) * D2R;
      return { pos: new V3(PAD.x + Math.sin(az) * 95, PAD.deck + 15, PAD.z + Math.cos(az) * 95), look: st.pos.clone().setY(st.pos.y - .5), fov: 34 };
    },
    fixed: (st, t, o) => ({ pos: o.p.clone(), look: st.pos.clone(), fov: o.fov }),
    chase: (st, t, o) => ({
      pos: pathAt(st.s - o.back).setY(pathAt(st.s - o.back).y + o.up),
      look: st.pos.clone().addScaledVector(st.f, o.ahead).setY(st.pos.y + st.f.y * o.ahead + o.up * .3), fov: o.fov,
    }),
    front: (st, t, o) => { const p = pathAt(st.s + o.ahead); p.y += o.up; return { pos: p, look: st.pos.clone(), fov: o.fov }; },
    high: (st, t, o) => ({
      pos: st.pos.clone().addScaledVector(st.fh, -o.back).addScaledVector(st.sh, o.side).setY(st.pos.y + o.alt),
      look: st.pos.clone().addScaledVector(st.fh, o.lead), fov: o.fov,
    }),
    side: (st, t, o) => ({
      pos: st.pos.clone().addScaledVector(st.sh, o.dist).addScaledVector(st.fh, -o.lag).setY(st.pos.y + o.up),
      look: st.pos.clone().addScaledVector(st.fh, 6), fov: o.fov,
    }),
    shoulder: st => ({
      pos: new V3(-16, 4.4, 0).applyQuaternion(st.q).add(st.pos),
      look: new V3(60, .5, 0).applyQuaternion(st.q).add(st.pos), up: new V3(0, 1, 0).lerp(st.up, .65).normalize(), fov: 56, ride: true,
    }),
  };
  function camAt(t) {
    let i = 0;
    while (i < shots.length - 1 && shots[i + 1][0] <= t) i++;
    const [, kind, o] = shots[i], st = stateAt(t), c = kinds[kind](st, t, o);
    if (!c.ride) c.pos.y = Math.max(c.pos.y, heightAt(c.pos.x, c.pos.z) + 2.5);
    c.st = st; c.shot = i;
    return c;
  }
  let tLow = 10;
  while (flight.distAt(tLow) < 130 && tLow < 16) tLow += .01;
  const marks = { pass: [tLow, tArch, tK(11), tFly], crest: tK(8), touchdown: 131.9 };
  return { camAt, shots, marks };
}

// ---------- soundtrack: minimal techno at 120 BPM; 68 bars = exactly one 136 s loop ----------
const BPM = 120, STEP = 60 / BPM / 4, STEPS = 68 * 16;
const hz = m => 440 * Math.pow(2, (m - 69) / 12);
const CHORDS = {
  Am: { pad: [45, 52, 55, 59, 60], stab: [57, 60, 64, 67], root: 33 },
  F: { pad: [41, 48, 55, 57, 60], stab: [53, 57, 60, 64], root: 29 },
  G: { pad: [43, 50, 55, 59, 62], stab: [55, 59, 62, 67], root: 31 },
};
const BASS = [[2, 3, 6, 7, 10, 11, 14, 15], [2, 6, 7, 10, 13, 14]];
const STABS = [[3, 10], [6, 13], [3, 11], [7]];
const PERC = [[3, 11], [6, 14], [3, 9, 14], [7, 11]];
const BELLS = [[[0, 69], [3, 72], [6, 76]], [[0, 74], [4, 72]], [[0, 69], [3, 72], [10, 79]], [[2, 76], [6, 74], [8, 72]]];

// The arrangement follows the flight: pad and lift-off riser, the groove kicks in as the ship
// accelerates, a build into the drop at the mesa crest, a breakdown in the spire field, and an
// outro that settles back into the opening pad so the loop is seamless.
function arrangement(b) {
  const m = { chord: "Am", pad: .3, padCut: 700, sub: 0, kick: 0, kickTo: 16, hat: 0, ohat: 0, ride: 0, clap: 0, roll: 0, perc: 0, bass: 0, cut: 400, alt: 0, stab: 0, bell: 0 };
  if (b < 5) return Object.assign(m, { pad: .22 + .05 * b, padCut: 500 + 60 * b, sub: .5, hat: b >= 3 ? .18 : 0 });
  if (b < 13) return Object.assign(m, { kick: 1, hat: .5, ohat: .45, bass: .75, cut: 340 + 30 * (b - 5), pad: .2 });
  if (b < 21) return Object.assign(m, { kick: 1, hat: .55, ohat: .5, clap: .6, perc: .45, bass: .8, cut: 600 + 35 * (b - 13), stab: .6, pad: .2, padCut: 800 });
  if (b < 25) return Object.assign(m, { chord: b < 23 ? "F" : "G", kick: 1, kickTo: b === 24 ? 8 : 16, hat: .6, ohat: .2, perc: .4, bass: .7, cut: 800 - 110 * (b - 21), stab: .7, pad: .32, padCut: 900 + 200 * (b - 21), roll: b >= 23 ? (b - 22) * .3 : 0 });
  if (b < 33) return Object.assign(m, { kick: 1, hat: .6, ohat: .55, clap: .7, perc: .5, bass: .85, cut: 900 + 50 * (b - 25), stab: .65, bell: .5, pad: .18, padCut: 900 });
  if (b < 41) return Object.assign(m, { kick: 1, hat: .6, ohat: .5, ride: .35, clap: .7, perc: .55, bass: .85, cut: 1250 - 40 * (b - 33), alt: 1, stab: .5, bell: .55, pad: .18, padCut: 1000 });
  if (b < 45) return Object.assign(m, { chord: b < 43 ? "F" : "G", hat: .15, pad: .5, padCut: 1600, sub: .25, stab: .55, bell: .6, roll: b === 44 ? .6 : 0 });
  if (b < 57) return Object.assign(m, { kick: 1, hat: .65, ohat: .6, ride: .4, clap: .75, perc: .6, bass: .9, cut: 1000 + 500 * Math.sin((b - 45) / 12 * Math.PI), alt: (b >> 2) & 1, stab: .6, bell: .5, pad: .2, padCut: 1000 });
  if (b < 61) return Object.assign(m, { kick: 1, hat: .5, ohat: .4, perc: .35, bass: .7, cut: 800 - 100 * (b - 57), stab: .4, pad: .25, padCut: 800 });
  return Object.assign(m, { pad: .3 - .01 * (b - 61), padCut: 900 - 50 * (b - 61), sub: .45, hat: b < 64 ? .14 : 0, stab: b < 63 ? .35 : 0 });
}

// Builds the synth rig on any audio context (live or offline). playStep(k, when) schedules
// 16th-note step k of the loop at audio time `when`.
function createSoundtrack(ctx, marks) {
  const R = rng(9), t0 = ctx.currentTime;
  const gain = v => { const g = ctx.createGain(); g.gain.value = v; return g; };
  const filt = (type, f, q = .7) => { const n = ctx.createBiquadFilter(); n.type = type; n.frequency.value = f; n.Q.value = q; return n; };
  const pan = v => { const n = ctx.createStereoPanner(); n.pan.value = v; return n; };
  const osc = (type, f) => { const o = ctx.createOscillator(); o.type = type; o.frequency.value = f; return o; };
  const env = (g, t, a, peak, d) => { g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(peak, t + a); g.gain.exponentialRampToValueAtTime(1e-4, t + a + d); };
  const play = (src, t, len) => { src.start(t); src.stop(t + len); };

  const master = gain(0), comp = ctx.createDynamicsCompressor();
  for (const [k, v] of Object.entries({ threshold: -16, knee: 10, ratio: 3.5, attack: .003, release: .2 })) comp[k].value = v;
  const mix = gain(1); mix.connect(filt("highpass", 30, .7)).connect(comp).connect(master);
  const drums = gain(.9); drums.connect(mix);
  const duck = gain(1); duck.connect(mix);

  const nb = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate), nd = nb.getChannelData(0);
  for (let i = 0; i < nd.length; i++) nd[i] = R() * 2 - 1;
  const noise = (t, len) => { const s = ctx.createBufferSource(); s.buffer = nb; s.loop = true; s.start(t, R() * 1.9); s.stop(t + len); return s; };

  const ir = ctx.createBuffer(2, ctx.sampleRate * 3, ctx.sampleRate);
  for (let c = 0; c < 2; c++) { const d = ir.getChannelData(c); for (let i = 0; i < d.length; i++) d[i] = (R() * 2 - 1) * Math.pow(1 - i / d.length, 3.2) * Math.min(1, i / 200); }
  const verb = ctx.createConvolver(); verb.buffer = ir;
  const verbIn = gain(1);
  verbIn.connect(filt("highpass", 250)).connect(verb).connect(gain(.3)).connect(duck);

  // Ping-pong delay on the dotted eighth.
  const dIn = gain(1), dL = ctx.createDelay(1), dR = ctx.createDelay(1), fb = gain(.45), dOut = gain(.55);
  dL.delayTime.value = dR.delayTime.value = STEP * 3;
  dIn.connect(dL); dL.connect(dR); dR.connect(filt("bandpass", 1500, .6)).connect(fb).connect(dL);
  dL.connect(pan(-.7)).connect(dOut); dR.connect(pan(.7)).connect(dOut);
  dOut.connect(duck); dOut.connect(verbIn);

  // Held pad and sub, retuned bar by bar.
  const padF = filt("lowpass", 600, .6), padG = gain(0);
  padF.connect(padG).connect(duck); padG.connect(gain(.6)).connect(verbIn);
  const lfo = osc("sine", .06); lfo.connect(gain(220)).connect(padF.frequency); lfo.start(t0);
  const voices = CHORDS.Am.pad.map(n => [-7, 7].map(d => { const o = osc("sawtooth", hz(n)); o.detune.value = d; o.connect(gain(.09)).connect(pan(d / 12)).connect(padF); o.start(t0); return o; }));
  const sub = osc("sine", hz(33)), subG = gain(0); sub.connect(subG).connect(duck); sub.start(t0);

  function kick(t, v) {
    const o = osc("sine", 155), g = gain(0);
    o.frequency.setValueAtTime(155, t); o.frequency.exponentialRampToValueAtTime(52, t + .06); o.frequency.exponentialRampToValueAtTime(41, t + .35);
    env(g, t, .002, v, .42); o.connect(g).connect(drums); play(o, t, .5);
    const c = gain(0); env(c, t, .001, v * .25, .012); noise(t, .03).connect(filt("highpass", 2500)).connect(c).connect(drums);
    duck.gain.setValueAtTime(.3, t); duck.gain.linearRampToValueAtTime(1, t + .26);
  }
  function hat(t, v, len, p, f = 7500) {
    const g = gain(0); env(g, t, .001, v, len);
    noise(t, len + .03).connect(filt("highpass", f)).connect(g).connect(pan(p)).connect(drums);
  }
  function ride(t, v) {
    const g = gain(0); env(g, t, .002, v * .3, .4);
    noise(t, .45).connect(filt("bandpass", 9000, .9)).connect(g).connect(pan(.35)).connect(drums);
  }
  function clap(t, v) {
    const g = gain(0);
    g.gain.setValueAtTime(0, t);
    for (const k of [0, .011, .022]) { g.gain.setValueAtTime(v, t + k); g.gain.exponentialRampToValueAtTime(v * .2, t + k + .009); }
    g.gain.setValueAtTime(v * .8, t + .033); g.gain.exponentialRampToValueAtTime(1e-4, t + .22);
    noise(t, .26).connect(filt("bandpass", 1350, 1.1)).connect(g).connect(drums);
    g.connect(gain(.5)).connect(verbIn);
  }
  function perc(t, v, f, p) {
    const o = osc("triangle", f * 1.6), g = gain(0), pn = pan(p);
    o.frequency.setValueAtTime(f * 1.6, t); o.frequency.exponentialRampToValueAtTime(f, t + .015);
    env(g, t, .001, v, .07); o.connect(g).connect(pn).connect(drums); play(o, t, .12);
    pn.connect(gain(.35)).connect(dIn);
  }
  function bass(t, note, v, cut) {
    const len = STEP * .9, o = osc("sawtooth", hz(note)), s = osc("sine", hz(note)), f = filt("lowpass", cut, 7), g = gain(0);
    f.frequency.setValueAtTime(cut * 3.2, t); f.frequency.exponentialRampToValueAtTime(cut, t + .09);
    g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(v * .45, t + .004);
    g.gain.setValueAtTime(v * .45, t + len * .6); g.gain.exponentialRampToValueAtTime(1e-4, t + len);
    o.connect(f).connect(g); s.connect(gain(.6)).connect(g); g.connect(duck);
    play(o, t, len + .02); play(s, t, len + .02);
  }
  function stab(t, v, notes, cut) {
    const f = filt("lowpass", cut, 3), g = gain(0);
    for (const n of notes) for (const d of [-8, 8]) { const o = osc("sawtooth", hz(n)); o.detune.value = d; o.connect(f); play(o, t, .4); }
    f.frequency.setValueAtTime(cut * 2.2, t); f.frequency.exponentialRampToValueAtTime(cut * .6, t + .2);
    env(g, t, .003, v * .1, .28); f.connect(g).connect(duck);
    g.connect(gain(.9)).connect(dIn); g.connect(gain(.4)).connect(verbIn);
  }
  function bell(t, note, v, p) {
    const f = hz(note), c = osc("sine", f), m = osc("sine", f * 3.5), mg = gain(0), g = gain(0), pn = pan(p);
    mg.gain.setValueAtTime(f * 2.2, t); mg.gain.exponentialRampToValueAtTime(f * .05, t + .6);
    m.connect(mg).connect(c.frequency); env(g, t, .002, v * .14, 1.1);
    c.connect(g).connect(pn).connect(duck); pn.connect(gain(.7)).connect(dIn); pn.connect(gain(.5)).connect(verbIn);
    play(c, t, 1.3); play(m, t, 1.3);
  }
  function riser(t, len, v) {
    const f = filt("bandpass", 250, 3), g = gain(0);
    f.frequency.setValueAtTime(250, t); f.frequency.exponentialRampToValueAtTime(6000, t + len);
    g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(v, t + len - .05); g.gain.linearRampToValueAtTime(0, t + len + .05);
    noise(t, len + .1).connect(f).connect(g).connect(mix); g.connect(verbIn);
  }
  function impact(t, v) {
    const o = osc("sine", 90), g = gain(0);
    o.frequency.setValueAtTime(90, t); o.frequency.exponentialRampToValueAtTime(30, t + 1.2);
    env(g, t, .005, v, 1.6); o.connect(g).connect(mix); play(o, t, 1.8);
    const n = gain(0); env(n, t, .005, v * .5, 1); noise(t, 1.2).connect(filt("lowpass", 600)).connect(n).connect(mix); n.connect(verbIn);
  }
  // A fly-past: swept noise plus a doppler-shifted engine tone, peaking as the ship passes the lens.
  function whoosh(t, v) {
    const a = t - 1.1, len = 2.1, f = filt("bandpass", 300, 1.4), g = gain(0), p = pan(-.8);
    f.frequency.setValueAtTime(300, a); f.frequency.exponentialRampToValueAtTime(2400, t); f.frequency.exponentialRampToValueAtTime(350, a + len);
    g.gain.setValueAtTime(0, a); g.gain.linearRampToValueAtTime(v * .3, t - .3); g.gain.linearRampToValueAtTime(v, t); g.gain.exponentialRampToValueAtTime(1e-3, a + len);
    p.pan.setValueAtTime(-.8, a); p.pan.linearRampToValueAtTime(.8, a + len);
    noise(a, len).connect(f).connect(g).connect(p).connect(mix); p.connect(gain(.3)).connect(verbIn);
    const o = osc("sawtooth", 212), og = gain(0);
    o.frequency.setValueAtTime(212, a); o.frequency.setTargetAtTime(151, t - .15, .25);
    og.gain.setValueAtTime(0, a); og.gain.linearRampToValueAtTime(v * .12, t); og.gain.exponentialRampToValueAtTime(1e-3, a + len);
    o.connect(filt("lowpass", 900, 1)).connect(og).connect(p); play(o, a, len);
  }
  const fx = [...marks.pass.map(t => [t, () => whoosh, .9]), [marks.touchdown, () => impact, .35]];

  function setBar(b, t) {
    const m = arrangement(b), ch = CHORDS[m.chord];
    padG.gain.setTargetAtTime(m.pad, t, .9);
    padF.frequency.setTargetAtTime(m.padCut, t, 1.5);
    voices.forEach((pair, i) => pair.forEach(o => o.frequency.setTargetAtTime(hz(ch.pad[i]), t, .06)));
    sub.frequency.setTargetAtTime(hz(ch.root), t, .05);
    subG.gain.setTargetAtTime(m.sub * .12, t, .8);
  }
  function playStep(k, t) {
    const b = k >> 4, s = k & 15, m = arrangement(b), ch = CHORDS[m.chord], acc = [1, .35, .7, .4][s & 3];
    if (s === 0) {
      setBar(b, t);
      if (b === 2) riser(t, 6, .22);
      if (b === 22) riser(t, 6, .28);
      if (b === 43) riser(t, 4, .26);
      if (b === 25 || b === 45) impact(t, .8);
    }
    if (m.kick && (s & 3) === 0 && s < m.kickTo) kick(t, .95);
    if (m.hat && !(m.ohat && (s & 3) === 2)) hat(t, m.hat * acc * .7, .03, ((s & 3) - 1.5) * .16);
    if (m.ohat && (s & 3) === 2) hat(t, m.ohat * .6, .19, .15, 6500);
    if (m.ride && (s & 3) === 2) ride(t, m.ride);
    if (m.clap && (s === 4 || s === 12)) clap(t, m.clap);
    if (m.roll && s >= (b === 24 || b === 44 ? 0 : 8) && (b === 24 || b === 44 || (s & 1) === 0)) clap(t, m.roll * (.35 + .65 * s / 15));
    if (m.perc && PERC[b & 3].includes(s)) perc(t, m.perc * .35, s & 1 ? 1150 : 1720, s & 1 ? -.4 : .4);
    if (m.bass && BASS[m.alt].includes(s)) {
      const n = ch.root + (s === 15 && (b & 3) === 3 ? 3 : 0) + (m.alt && s === 7 ? 7 : 0) + (m.alt && s === 13 ? -2 : 0);
      bass(t, n, m.bass * ((s & 3) === 2 ? 1 : .72), m.cut);
    }
    if (m.stab && STABS[b & 3].includes(s)) stab(t, m.stab, ch.stab, 900 + .4 * m.cut);
    if (m.bell && (b & 1) === 0) for (const [st, n] of BELLS[(b >> 1) & 3]) if (st === s) bell(t, n, m.bell, st & 2 ? .45 : -.45);
    const a = k * STEP;
    for (const [ft, fn, v] of fx) if (ft >= a && ft < a + STEP) fn()(t + ft - a, v);
  }
  return { master, playStep, setBar };
}

// Live playback: the audio clock drives the animation while the soundtrack is on.
function createAudio(marks) {
  let ctx = null, st = null, on = false, anchor = 0, next = 0;
  const latency = () => ctx.outputLatency || ctx.baseLatency || 0;
  return {
    get on() { return on; },
    clock() { return ctx.currentTime - anchor - latency(); },
    async enable(clock) {
      if (!ctx) {
        ctx = new (window.AudioContext || window.webkitAudioContext)();
        st = createSoundtrack(ctx, marks);
        st.master.connect(ctx.destination);
      }
      await ctx.resume();
      const now = ctx.currentTime;
      anchor = now - clock - latency();
      next = Math.ceil((clock + .02) / STEP);
      st.setBar(Math.floor(clock % LOOP / (STEP * 16)), now);
      st.master.gain.cancelScheduledValues(now); st.master.gain.setTargetAtTime(.85, now, .2);
      on = true;
    },
    disable() {
      if (!ctx) return;
      on = false;
      const now = ctx.currentTime;
      st.master.gain.cancelScheduledValues(now); st.master.gain.setTargetAtTime(0, now, .08);
      setTimeout(() => { if (!on) ctx.suspend(); }, 500);
    },
    pump() {
      if (!on) return;
      const tNow = ctx.currentTime - anchor, ahead = document.hidden ? 1.6 : .3;
      if (next * STEP < tNow - .05) next = Math.ceil(tNow / STEP);
      while (next * STEP < tNow + ahead) { st.playStep(next % STEPS, anchor + next * STEP); next++; }
    },
  };
}

// ---------- geometry helpers ----------
function lathe(pts, seg = 64, phiStart = 0, phiLength = Math.PI * 2) {
  const g = new THREE.LatheGeometry(pts.map(([s, r]) => new THREE.Vector2(Math.max(1e-4, r), XS(s))).reverse(), seg, phiStart, phiLength);
  g.rotateZ(-Math.PI / 2);
  return g;
}
function roundedBox(w, h, d, segments = 2, radius = .1) {
  const seg = segments * 2 + 1;
  radius = Math.min(w / 2, h / 2, d / 2, radius);
  const g = new THREE.BoxGeometry(1, 1, 1, seg, seg, seg).toNonIndexed();
  const pos = g.attributes.position.array, nor = g.attributes.normal.array;
  const half = new THREE.Vector3(w, h, d).divideScalar(2).subScalar(radius);
  const p = new THREE.Vector3(), n = new THREE.Vector3(), m = .5 / seg;
  for (let i = 0; i < pos.length; i += 3) {
    p.fromArray(pos, i); n.copy(p);
    n.x -= Math.sign(n.x) * m; n.y -= Math.sign(n.y) * m; n.z -= Math.sign(n.z) * m; n.normalize();
    pos[i] = half.x * Math.sign(p.x) + n.x * radius;
    pos[i + 1] = half.y * Math.sign(p.y) + n.y * radius;
    pos[i + 2] = half.z * Math.sign(p.z) + n.z * radius;
    nor[i] = n.x; nor[i + 1] = n.y; nor[i + 2] = n.z;
  }
  g.deleteAttribute("uv");
  return g;
}

// ---------- the ship ----------
function buildShip() {
  const std = (color, o = {}) => new THREE.MeshStandardMaterial({ color, roughness: .5, metalness: .1, ...o });
  const DS = THREE.DoubleSide;
  const decal = { polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 };
  const M = {
    hull: std("#ebe7de", { roughness: .42 }),
    hullTop: std("#ebe7de", { roughness: .42, ...decal }),
    panel: std("#56616c", { roughness: .55 }),
    belly: std("#56616c", { roughness: .55, ...decal }),
    teal: std("#23a092", { roughness: .4, ...decal }),
    amber: std("#e29f36", { roughness: .5, ...decal }),
    dark: std("#272c33", { roughness: .55 }),
    glass: std("#0f1a24", { roughness: .05, metalness: .6 }),
    steel: std("#b7bcc2", { roughness: .32, metalness: .8 }),
    nozzle: std("#4b5058", { roughness: .38, metalness: .75, side: DS }),
    glow: new THREE.MeshBasicMaterial({ color: "#a6ecff" }),
    plume: new THREE.MeshBasicMaterial({ color: "#5cb8ff", transparent: true, opacity: .3, blending: THREE.AdditiveBlending, depthWrite: false, side: DS }),
    vent: new THREE.MeshBasicMaterial({ color: "#ffd49a" }),
    jet: new THREE.MeshBasicMaterial({ color: "#ffbf70", transparent: true, opacity: .4, blending: THREE.AdditiveBlending, depthWrite: false, side: DS }),
    port: new THREE.MeshBasicMaterial({ color: "#ff4a3d" }),
    star: new THREE.MeshBasicMaterial({ color: "#46ff86" }),
    strobe: new THREE.MeshBasicMaterial({ color: "#ffffff" }),
  };
  const root = new THREE.Group();
  const add = (geo, mat, parent = root, cast = true) => {
    const m = new THREE.Mesh(geo, mat); m.castShadow = cast; m.receiveShadow = true; parent.add(m); return m;
  };

  // Fuselage: a flattened lifting body, pale above and slate below.
  const prof = [[0, 0], [.15, .3], [.6, .62], [1.3, .92], [2.3, 1.2], [3.6, 1.42], [5, 1.55], [6.5, 1.6], [12, 1.6], [14.5, 1.52], [16.5, 1.32], [18, 1.02], [18.9, .78], [19.15, .5], [19.15, 0]];
  const body = new THREE.Group(); body.scale.set(1, HULL.sy, HULL.sz); root.add(body);
  add(lathe(prof, 72), M.hull, body);
  add(lathe(prof.filter(([s]) => s >= 1.3 && s <= 18.9).map(([s, r]) => [s, r + .012]), 72, .5, Math.PI - 1), M.belly, body, false);
  add(lathe([[-.005, 0], [.15, .31], [.6, .63]], 48), M.dark, body, false);
  add(lathe([[7, 1.622], [7.4, 1.622]], 72), M.teal, body, false);
  add(lathe([[7.52, 1.622], [7.6, 1.622]], 72), M.amber, body, false);

  // Canopy with two frame hoops.
  const canopy = new THREE.Mesh(new THREE.SphereGeometry(1, 48, 20, 0, Math.PI * 2, 0, Math.PI / 2), M.glass);
  canopy.scale.set(2.35, .78, .92); canopy.position.set(XS(3.95), .74, 0); root.add(canopy);
  for (const [s, k] of [[3.2, .99], [4.7, .96]]) {
    const hoop = add(new THREE.TorusGeometry(1, .03, 6, 40, Math.PI), M.dark, root, false);
    hoop.rotation.y = Math.PI / 2; hoop.scale.set(1, .79 * k, .93 * k); hoop.position.set(XS(s), .74, 0);
  }

  // Dorsal spine with vents and an antenna.
  add(roundedBox(7.5, .7, 1.1, 2, .2), M.panel).position.set(XS(10.3), 1.2, 0);
  for (const s of [9, 10, 11]) add(new THREE.BoxGeometry(.5, .02, .7), M.dark, root, false).position.set(XS(s), 1.556, 0);
  add(new THREE.CylinderGeometry(.025, .04, .9, 8), M.steel).position.set(XS(12.6), 1.95, 0);

  // Fixed wing gloves.
  const slab = (pts, t, y, mat) => {
    const g = new THREE.ExtrudeGeometry(new THREE.Shape(pts.map(([x, z]) => new THREE.Vector2(x, z))),
      { depth: t, bevelEnabled: true, bevelThickness: .04, bevelSize: .04, bevelSegments: 1, curveSegments: 4 });
    g.rotateX(Math.PI / 2); g.translate(0, y + t / 2, 0);
    return add(g, mat);
  };
  for (const side of [-1, 1]) slab([[5, 1.05], [8.2, 2.35], [9.6, 3.25], [13.2, 3.25], [14.4, 1.4], [10, .9]].map(([s, z]) => [XS(s), side * z]), .5, WINGP.y, M.hull);

  // Swing wings on pivots; sweep animates between 16° and 55°.
  const wings = [];
  for (const side of [-1, 1]) {
    const pivot = new THREE.Group(); pivot.position.set(XS(WINGP.s), WINGP.y, side * WINGP.z); root.add(pivot);
    const outline = [[.6, -.5], [.6, 0], [-1.3, 7], [-2.3, 7.18], [-2.95, 7], [-3.6, 0], [-3.6, -.5]];
    const g = new THREE.ExtrudeGeometry(new THREE.Shape(outline.map(([x, z]) => new THREE.Vector2(x, side * z))), { depth: 1, bevelEnabled: false, curveSegments: 2 });
    g.rotateX(Math.PI / 2);
    const pos = g.attributes.position;
    for (let i = 0; i < pos.count; i++) pos.setY(i, (pos.getY(i) + .5) * (.22 - .11 * clamp01(Math.abs(pos.getZ(i)) / 7)));
    g.computeVertexNormals();
    add(g, M.hull, pivot);
    add(new THREE.BoxGeometry(2, .012, .42), M.teal, pivot, false).position.set(-2.03, .071, side * 5.85);
    add(new THREE.BoxGeometry(1.2, .012, .16), M.amber, pivot, false).position.set(-1.6, .095, side * 3.2);
    add(new THREE.SphereGeometry(.09, 10, 8), side < 0 ? M.port : M.star, pivot, false).position.set(-2.2, 0, side * 7.2);
    wings.push({ pivot, side });
  }

  // Twin engine nacelles on pylons, with canted fins.
  const nacProf = [[11.75, .5], [11.95, .72], [12.35, .83], [13, .85], [18.4, .85], [19.2, .79], [19.5, .74]];
  const glows = [], plumes = [];
  for (const side of [-1, 1]) {
    const n = new THREE.Group(); n.position.set(0, NAC.y, side * NAC.z); root.add(n);
    add(lathe(nacProf, 48), M.panel, n);
    add(lathe(nacProf.slice(1, -1).map(([s, r]) => [s, r + .012]), 48, Math.PI + .5, Math.PI - 1), M.hullTop, n, false);
    const ring = add(new THREE.TorusGeometry(.6, .1, 10, 40), M.steel, n, false);
    ring.rotation.y = Math.PI / 2; ring.position.x = XS(11.82);
    const intake = add(new THREE.CircleGeometry(.58, 32), M.dark, n, false);
    intake.rotation.y = Math.PI / 2; intake.position.x = XS(11.95);
    add(lathe([[19.4, .72], [19.6, .79], [20.35, .84], [20.35, .62], [19.75, .55]], 40), M.nozzle, n);
    const disc = new THREE.Mesh(new THREE.CircleGeometry(.56, 32), M.glow.clone());
    disc.rotation.y = -Math.PI / 2; disc.position.x = XS(19.8); n.add(disc); glows.push(disc);
    const plume = new THREE.Mesh(new THREE.ConeGeometry(.56, 1, 32, 1, true), M.plume.clone());
    plume.rotation.z = Math.PI / 2; n.add(plume); plumes.push(plume);
    add(new THREE.BoxGeometry(5.2, .45, 1), M.panel).position.set(XS(15.4), NAC.y + .05, side * 1.62);

    const fin = new THREE.Group(); fin.position.set(0, NAC.y + NAC.r - .12, side * NAC.z); fin.rotation.x = side * .32; root.add(fin);
    const fg = new THREE.ExtrudeGeometry(new THREE.Shape([[15.7, 0], [18.7, 0], [19.55, 2.1], [18.45, 2.1]].map(([s, h]) => new THREE.Vector2(XS(s), h))), { depth: .14, bevelEnabled: false });
    fg.translate(0, 0, -.07); add(fg, M.hull, fin);
    const tg = new THREE.ExtrudeGeometry(new THREE.Shape([[17.98, 1.75], [19.42, 1.75], [19.57, 2.115], [18.44, 2.115]].map(([s, h]) => new THREE.Vector2(XS(s), h))), { depth: .16, bevelEnabled: false });
    tg.translate(0, 0, -.08); add(tg, M.teal, fin, false);
    add(new THREE.SphereGeometry(.08, 10, 8), M.strobe, fin, false).position.set(XS(19.2), 2.16, 0);
  }

  // Belly lift vents for vertical take-off and landing.
  const vents = [];
  for (const [s, z, y] of [[3.4, 0, -1.15], [10.2, -1, -1.1], [10.2, 1, -1.1], [17, 0, -1.04]]) {
    const d = new THREE.Mesh(new THREE.CircleGeometry(.3, 24), M.vent.clone());
    d.rotation.x = Math.PI / 2; d.position.set(XS(s), y - .01, z); root.add(d);
    const j = new THREE.Mesh(new THREE.ConeGeometry(.3, 1, 24, 1, true), M.jet.clone());
    j.rotation.x = Math.PI; j.position.set(XS(s), y, z); root.add(j);
    vents.push({ d, j, y });
  }

  // Landing gear: struts, telescoping pistons, bay doors.
  const legs = GEAR.legs.map(({ s, z, y }) => {
    const base = new THREE.Group(); base.position.set(XS(s), y, z); root.add(base);
    add(new THREE.BoxGeometry(1, .02, .9), M.dark, base, false).position.y = -.006;
    add(new THREE.CylinderGeometry(.19, .19, 1.1, 18), M.steel, base).position.y = .58;
    const piston = new THREE.Group(); base.add(piston);
    add(new THREE.CylinderGeometry(.12, .12, 1.6, 16), M.steel, piston).position.y = .85;
    add(new THREE.CylinderGeometry(GEAR.padR, GEAR.padR * 1.1, .1, 28), M.dark, piston).position.y = .05;
    const doors = [-1, 1].map(sd => {
      const hinge = new THREE.Group(); hinge.position.set(0, -.012, sd * .45); base.add(hinge);
      add(new THREE.BoxGeometry(.96, .035, .44), M.panel, hinge).position.set(0, -.018, -sd * .22);
      return { hinge, sd };
    });
    return { piston, doors, extra: (y - BELLY) / GEAR.stroke };
  });

  const cold = new THREE.Color("#2f343b"), hot = new THREE.Color("#a6ecff");
  const ventCold = new THREE.Color("#3a3430"), ventHot = new THREE.Color("#ffd49a");
  function update(c, time) {
    for (const w of wings) w.pivot.rotation.y = -w.side * c.sweep * D2R;
    const open = Math.min(1, c.stroke / .25);
    for (const L of legs) {
      L.piston.position.y = -c.stroke * (1 + L.extra);
      for (const d of L.doors) d.hinge.rotation.x = -d.sd * Math.PI / 2 * open;
    }
    for (const g of glows) g.material.color.copy(cold).lerp(hot, c.glow);
    const len = .3 + 4.2 * c.thrust;
    for (const p of plumes) {
      p.scale.set(1, len, 1); p.position.x = XS(20.35) - len / 2;
      p.visible = c.thrust > .01; p.material.opacity = .26 * c.thrust;
    }
    for (const v of vents) {
      v.d.material.color.copy(ventCold).lerp(ventHot, c.hover);
      const jl = .2 + 3.2 * c.hover;
      v.j.scale.set(1, jl, 1); v.j.position.y = v.y - jl / 2;
      v.j.visible = c.hover > .01; v.j.material.opacity = .4 * c.hover;
    }
    const flash = time % 1.4 < .07 || (time + 1.15) % 1.4 < .07;
    M.strobe.color.setScalar(flash ? 1 : .08);
  }
  return { root, update };
}

// ---------- sky ----------
const SKY_VS = "varying vec3 vDir; void main(){ vDir = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }";
const SKY_FS = `uniform vec3 uZen; uniform vec3 uHor; uniform vec3 uGnd; uniform vec3 uSun; uniform vec3 uMoon; varying vec3 vDir;
void main(){
  vec3 d = normalize(vDir);
  float h = d.y;
  vec3 col = mix(uHor, uZen, pow(clamp(h, 0.0, 1.0), 0.55));
  col = mix(col, uGnd, smoothstep(0.0, -0.12, h));
  float sd = max(dot(d, uSun), 0.0);
  col += vec3(1.0, 0.72, 0.45) * (pow(sd, 6.0) * 0.22 + pow(sd, 90.0) * 0.55);
  col = mix(col, vec3(1.6, 1.45, 1.2), smoothstep(0.99955, 0.99975, sd));
  vec3 m = normalize(uMoon);
  vec3 rx = normalize(cross(m, vec3(0.0, 1.0, 0.0))), ry = cross(rx, m);
  vec2 q = vec2(dot(d, rx), dot(d, ry)) / 0.085;
  float r2 = dot(q, q);
  if (dot(d, m) > 0.0 && r2 < 1.1) {
    vec3 nrm = normalize(rx * q.x + ry * q.y - m * sqrt(max(0.0, 1.0 - r2)));
    float lit = smoothstep(-0.05, 0.25, dot(nrm, uSun));
    float band = 0.5 + 0.5 * sin(q.y * 9.0 + sin(q.x * 3.0) * 1.2);
    vec3 moon = mix(vec3(0.80, 0.86, 0.88), vec3(0.60, 0.69, 0.75), band) * (0.07 + 0.95 * lit);
    float edge = 1.0 - smoothstep(0.96, 1.0, r2);
    col = mix(col, mix(col, moon + col * 0.25, 0.35 + 0.65 * smoothstep(0.0, 0.35, h)), edge);
  }
  gl_FragColor = vec4(col, 1.0);
  #include <colorspace_fragment>
}`;

function buildSky(scene, renderer) {
  const mat = new THREE.ShaderMaterial({
    vertexShader: SKY_VS, fragmentShader: SKY_FS, side: THREE.BackSide, depthWrite: false, toneMapped: false,
    uniforms: {
      uZen: { value: new THREE.Color(SKY.zen) }, uHor: { value: new THREE.Color(SKY.hor) }, uGnd: { value: new THREE.Color(SKY.gnd) },
      uSun: { value: new THREE.Vector3(...SUN_DIR).normalize() }, uMoon: { value: new THREE.Vector3(...MOON_DIR).normalize() },
    },
  });
  const sky = new THREE.Mesh(new THREE.SphereGeometry(7000, 48, 24), mat);
  sky.renderOrder = -1; sky.frustumCulled = false; scene.add(sky);
  // Image-based light from the same sky, with a warm rock floor for bounce.
  const env = new THREE.Scene();
  env.add(new THREE.Mesh(new THREE.SphereGeometry(50, 48, 24), mat.clone()));
  const floor = new THREE.Mesh(new THREE.CircleGeometry(48, 32), new THREE.MeshBasicMaterial({ color: "#8a5f45", side: THREE.DoubleSide }));
  floor.rotation.x = -Math.PI / 2; floor.position.y = -8; env.add(floor);
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(env, .03).texture;
  scene.environmentIntensity = .8;
  pmrem.dispose();
  return sky;
}

// ---------- terrain, spires, arch, lake ----------
function waterNormals() {
  const S = 128, d = new Uint8Array(S * S * 4);
  const waves = [[3, 1, .5], [-2, 4, .35], [5, -3, .25], [1, 7, .18], [-8, 2, .12]];
  for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) {
    let hx = 0, hy = 0;
    for (const [kx, ky, a] of waves) { const c = Math.cos(2 * Math.PI * (kx * x / S + ky * y / S) + kx * 1.7) * a; hx += c * kx; hy += c * ky; }
    const nx = -hx * .06, ny = -hy * .06, l = Math.hypot(nx, ny, 1), i = (y * S + x) * 4;
    d[i] = (nx / l * .5 + .5) * 255; d[i + 1] = (ny / l * .5 + .5) * 255; d[i + 2] = (1 / l * .5 + .5) * 255; d[i + 3] = 255;
  }
  const t = new THREE.DataTexture(d, S, S);
  t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(70, 70);
  t.generateMipmaps = true; t.minFilter = THREE.LinearMipmapLinearFilter; t.magFilter = THREE.LinearFilter;
  t.needsUpdate = true;
  return t;
}

const STRATA_GLSL = `
{
  float vn = 0.5 * vnoise(vWPos.xz * 0.07) + 0.3 * vnoise(vWPos.xz * 0.29 + 7.0) + 0.2 * vnoise(vWPos.xz * 1.1 - 3.0);
  diffuseColor.rgb *= 0.86 + 0.26 * vn;
  float rk = smoothstep(0.16, 0.42, 1.0 - normalize(vWNrm).y);
  float warp = 1.7 * sin(vWPos.x * 0.011 + vWPos.z * 0.006) + 0.8 * sin(vWPos.z * 0.021 - vWPos.x * 0.015) + 1.4 * vnoise(vWPos.xz * 0.02);
  float w = vWPos.y * 0.21 + warp;
  float b = 0.5 + 0.5 * sin(w), b2 = 0.5 + 0.5 * sin(w * 2.73 + 1.7), b3 = 0.5 + 0.5 * sin(w * 6.1 + 0.4 + vn);
  vec3 rc = mix(uRockB, uRockA, 0.75 * smoothstep(0.45, 1.0, b));
  rc = mix(rc, uRockC, 0.5 * smoothstep(0.78, 1.0, b2));
  rc = mix(rc, uRockD, 0.4 * smoothstep(0.2, 0.8, b2 * (1.0 - b)));
  rc *= (0.93 + 0.08 * b3) * (0.88 + 0.24 * vn);
  diffuseColor.rgb = mix(diffuseColor.rgb, rc * vLight, rk);
}`;
const NOISE_GLSL = `
float hash2(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float vnoise(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
  return mix(mix(hash2(i), hash2(i + vec2(1.0, 0.0)), f.x), mix(hash2(i + vec2(0.0, 1.0)), hash2(i + vec2(1.0, 1.0)), f.x), f.y); }`;

// Ground and rock share one material: vertex colour carries ground tint and baked light,
// and cliffs get their layered bands per pixel from world height.
function makeGroundMaterial(PAL) {
  const mat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: .93, metalness: 0 });
  mat.onBeforeCompile = sh => {
    Object.assign(sh.uniforms, { uRockA: { value: PAL.rockA }, uRockB: { value: PAL.rockB }, uRockC: { value: PAL.rockC }, uRockD: { value: PAL.rockD } });
    sh.vertexShader = sh.vertexShader
      .replace("#include <common>", "#include <common>\nattribute float aLight;\nvarying float vLight;\nvarying vec3 vWPos;\nvarying vec3 vWNrm;")
      .replace("#include <begin_vertex>", "#include <begin_vertex>\nvLight = aLight;\nvWPos = (modelMatrix * vec4(transformed, 1.0)).xyz;\nvWNrm = normalize(mat3(modelMatrix) * objectNormal);");
    sh.fragmentShader = sh.fragmentShader
      .replace("#include <common>", "#include <common>\nuniform vec3 uRockA;\nuniform vec3 uRockB;\nuniform vec3 uRockC;\nuniform vec3 uRockD;\nvarying float vLight;\nvarying vec3 vWPos;\nvarying vec3 vWNrm;" + NOISE_GLSL)
      .replace("#include <color_fragment>", "#include <color_fragment>" + STRATA_GLSL);
  };
  return mat;
}

function buildWorldMeshes(world, scene) {
  const { N, half, cell, H, lit, ao, n1, n2 } = world;
  const C = h => new THREE.Color(h);
  const PAL = {
    sand: C("#c99d70"), sand2: C("#b4875c"), top: C("#a06848"), top2: C("#87553b"),
    rockA: C("#d4a77c"), rockB: C("#b06844"), rockC: C("#86442f"), rockD: C("#c58a5c"),
    shore: C("#735442"), bed: C("#3f4f4b"),
  };

  // Terrain mesh
  const geo = new THREE.BufferGeometry(), pos = new Float32Array(N * N * 3);
  for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) {
    const k = j * N + i; pos[k * 3] = i * cell - half; pos[k * 3 + 1] = H[k]; pos[k * 3 + 2] = j * cell - half;
  }
  const idx = new Uint32Array((N - 1) * (N - 1) * 6);
  for (let j = 0, q = 0; j < N - 1; j++) for (let i = 0; i < N - 1; i++) {
    const a = j * N + i, b = a + 1, c = a + N, d = c + 1;
    idx[q++] = a; idx[q++] = c; idx[q++] = b; idx[q++] = b; idx[q++] = c; idx[q++] = d;
  }
  geo.setAttribute("position", new THREE.BufferAttribute(pos, 3));
  geo.setIndex(new THREE.BufferAttribute(idx, 1));
  geo.computeVertexNormals();
  const col = new Float32Array(N * N * 3), light = new Float32Array(N * N), a = new THREE.Color(), b = new THREE.Color();
  for (let k = 0; k < N * N; k++) {
    const x = pos[k * 3], z = pos[k * 3 + 2], h = H[k];
    a.copy(PAL.sand).lerp(PAL.sand2, sstep(-.25, .3, fbm(n1, x / 70, z / 70, 2)));
    b.copy(PAL.top).lerp(PAL.top2, sstep(-.2, .35, fbm(n2, x / 90, z / 90, 2)));
    a.lerp(b, sstep(95, 140, h));
    a.lerp(PAL.shore, 1 - sstep(WORLD.water + .3, WORLD.water + 3.5, h));
    a.lerp(PAL.bed, 1 - sstep(WORLD.water - 6, WORLD.water - 1, h));
    light[k] = (.5 + .5 * lit[k]) * ao[k];
    a.multiplyScalar(light[k]);
    col[k * 3] = a.r; col[k * 3 + 1] = a.g; col[k * 3 + 2] = a.b;
  }
  geo.setAttribute("color", new THREE.BufferAttribute(col, 3));
  geo.setAttribute("aLight", new THREE.BufferAttribute(light, 1));
  const groundMat = makeGroundMaterial(PAL);
  // Split into 8×8 tiles (sharing the full mesh's normals) so off-screen terrain is culled.
  const TILES = 8, step = (N - 1) / TILES, nr = geo.attributes.normal.array;
  for (let tj = 0; tj < TILES; tj++) for (let ti = 0; ti < TILES; ti++) {
    const i0 = ti * step, j0 = tj * step, n = step + 1;
    const tp = new Float32Array(n * n * 3), tn = new Float32Array(n * n * 3), tc = new Float32Array(n * n * 3), tl = new Float32Array(n * n);
    for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) {
      const k = (j0 + j) * N + i0 + i, q = j * n + i;
      for (let c = 0; c < 3; c++) { tp[q * 3 + c] = pos[k * 3 + c]; tn[q * 3 + c] = nr[k * 3 + c]; tc[q * 3 + c] = col[k * 3 + c]; }
      tl[q] = light[k];
    }
    const ti6 = new Uint16Array((n - 1) * (n - 1) * 6);
    for (let j = 0, q = 0; j < n - 1; j++) for (let i = 0; i < n - 1; i++) {
      const a = j * n + i, b = a + 1, c = a + n, d = c + 1;
      ti6[q++] = a; ti6[q++] = c; ti6[q++] = b; ti6[q++] = b; ti6[q++] = c; ti6[q++] = d;
    }
    const g = new THREE.BufferGeometry();
    g.setAttribute("position", new THREE.BufferAttribute(tp, 3));
    g.setAttribute("normal", new THREE.BufferAttribute(tn, 3));
    g.setAttribute("color", new THREE.BufferAttribute(tc, 3));
    g.setAttribute("aLight", new THREE.BufferAttribute(tl, 1));
    g.setIndex(new THREE.BufferAttribute(ti6, 1));
    g.computeBoundingSphere();
    const tile = new THREE.Mesh(g, groundMat);
    tile.receiveShadow = true; scene.add(tile);
  }

  const paint = g => {
    const nn = g.attributes.normal, n = nn.count, c = new Float32Array(n * 3), l = new Float32Array(n), tc = new THREE.Color();
    for (let i = 0; i < n; i++) {
      tc.copy(PAL.top).lerp(PAL.rockA, .25);
      l[i] = nn.getY(i) < -.3 ? .72 : 1;
      c[i * 3] = tc.r; c[i * 3 + 1] = tc.g; c[i * 3 + 2] = tc.b;
    }
    g.setAttribute("color", new THREE.BufferAttribute(c, 3));
    g.setAttribute("aLight", new THREE.BufferAttribute(l, 1));
  };
  const rockMat = groundMat;

  // Spires
  for (const sp of world.spires) {
    const g = new THREE.CylinderGeometry(sp.rad * .72, sp.rad * 1.25, sp.hgt, 20, 18);
    const p = g.attributes.position;
    for (let i = 0; i < p.count; i++) {
      const x = p.getX(i), y = p.getY(i), z = p.getZ(i), ang = Math.atan2(z, x), yy = y + sp.hgt / 2;
      const k = 1 + .2 * fbm(n1, Math.cos(ang) * 1.4 + sp.x * .013, yy / 24 + Math.sin(ang) * 1.4 + sp.z * .013, 3) + .025 * Math.sin(yy * .3 + sp.x);
      p.setXYZ(i, x * k, y, z * k);
    }
    g.computeVertexNormals();
    paint(g);
    const m = new THREE.Mesh(g, rockMat); m.position.set(sp.x, sp.y0 + sp.hgt / 2, sp.z); m.receiveShadow = true; scene.add(m);
  }

  // Arch
  {
    const A = world.arch, g = new THREE.TorusGeometry(A.R, A.tube, 18, 80, Math.PI);
    const p = g.attributes.position, nn = g.attributes.normal;
    for (let i = 0; i < p.count; i++) {
      const x = p.getX(i), y = p.getY(i), z = p.getZ(i), d = 5 * fbm(n2, (x + z) / 22, y / 22, 3) + 2 * Math.sin(y * .4);
      p.setXYZ(i, x + nn.getX(i) * d, y + nn.getY(i) * d, z + nn.getZ(i) * d);
    }
    g.computeVertexNormals();
    paint(g);
    const m = new THREE.Mesh(g, rockMat);
    m.position.copy(A.c); m.rotation.y = Math.atan2(-A.n.z, A.n.x); m.receiveShadow = true; scene.add(m);
  }

  // Lake
  const wtex = waterNormals();
  const water = new THREE.Mesh(new THREE.PlaneGeometry(1500, 1500),
    new THREE.MeshStandardMaterial({ color: "#25505b", roughness: .08, metalness: 0, normalMap: wtex, normalScale: new THREE.Vector2(.3, .3) }));
  water.rotation.x = -Math.PI / 2; water.position.set(LAKE.x, WORLD.water, LAKE.z); water.receiveShadow = true; scene.add(water);
  return { wtex };
}

// ---------- the landing pad and its buildings ----------
function padTexture() {
  const S = 1024, c = document.createElement("canvas"); c.width = c.height = S;
  const g = c.getContext("2d"), R = rng(5), cx = S / 2;
  g.fillStyle = "#55585d"; g.fillRect(0, 0, S, S);
  for (let i = 0; i < 9000; i++) { const v = 70 + R() * 40 | 0; g.fillStyle = `rgba(${v},${v},${v + 4},.35)`; g.fillRect(R() * S, R() * S, 2, 2); }
  const ring = (r, w, col, dash = []) => { g.beginPath(); g.setLineDash(dash); g.lineWidth = w; g.strokeStyle = col; g.arc(cx, cx, r, 0, Math.PI * 2); g.stroke(); };
  g.strokeStyle = "rgba(25,27,31,.55)"; g.lineWidth = 3;
  for (let k = 0; k < 12; k++) {
    const a = k / 12 * Math.PI * 2;
    g.beginPath(); g.moveTo(cx + Math.cos(a) * 150, cx + Math.sin(a) * 150); g.lineTo(cx + Math.cos(a) * 505, cx + Math.sin(a) * 505); g.stroke();
  }
  ring(150, 3, "rgba(25,27,31,.55)"); ring(330, 3, "rgba(25,27,31,.55)");
  ring(480, 16, "#e2a33a", [38, 26]); ring(440, 6, "#23a092");
  ring(250, 14, "#e8e4da"); ring(205, 5, "#e8e4da");
  g.setLineDash([]); g.strokeStyle = "#e8e4da"; g.lineWidth = 10;
  for (let k = 0; k < 4; k++) {
    const a = k * Math.PI / 2 + Math.PI / 4;
    g.beginPath(); g.moveTo(cx + Math.cos(a) * 270, cx + Math.sin(a) * 270); g.lineTo(cx + Math.cos(a) * 330, cx + Math.sin(a) * 330); g.stroke();
  }
  g.fillStyle = "#e8e4da"; g.font = "700 110px system-ui, sans-serif"; g.textAlign = "center"; g.textBaseline = "middle";
  g.fillText("07", cx, cx - 380);
  g.save(); g.translate(cx, cx + 380); g.rotate(Math.PI); g.fillText("07", 0, 0); g.restore();
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8;
  return t;
}

const DUST_VS = "attribute float aAlpha; varying float vA; uniform float uSize; uniform float uScale; void main(){ vA = aAlpha; vec4 mv = modelViewMatrix * vec4(position, 1.0); gl_PointSize = uSize * uScale / -mv.z; gl_Position = projectionMatrix * mv; }";
const DUST_FS = "uniform vec3 uCol; uniform float uOp; varying float vA; void main(){ float a = smoothstep(0.5, 0.0, length(gl_PointCoord - 0.5)); gl_FragColor = vec4(uCol, a * vA * uOp);\n#include <colorspace_fragment>\n}";

function buildBase(scene, flight) {
  const g = new THREE.Group();
  g.position.set(PAD.x, PAD.ground, PAD.z); g.rotation.y = Math.atan2(-flight.f0.z, flight.f0.x); scene.add(g);
  const std = (color, o = {}) => new THREE.MeshStandardMaterial({ color, roughness: .8, metalness: .05, ...o });
  const add = (geo, mat, x, y, z) => { const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.receiveShadow = true; g.add(m); return m; };
  const deckH = PAD.deck - PAD.ground;

  add(new THREE.CircleGeometry(50, 64), std("#a08e7b", { roughness: .95, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 }), 0, .06, 0).rotation.x = -Math.PI / 2;
  const sideMat = std("#6b6e73", { roughness: .7 }), topMat = new THREE.MeshStandardMaterial({ map: padTexture(), roughness: .85, metalness: 0 });
  add(new THREE.CylinderGeometry(PAD.r, PAD.r + .8, deckH + .2, 72), [sideMat, topMat, sideMat], 0, (deckH + .2) / 2 - .2, 0);

  const lamps = new THREE.InstancedMesh(new THREE.BoxGeometry(.7, .2, .7), new THREE.MeshBasicMaterial({ color: "#ffffff" }), 36);
  const m4 = new THREE.Matrix4(), amber = new THREE.Color("#ffae3d"), tc = new THREE.Color();
  for (let i = 0; i < 36; i++) {
    const a = i / 36 * Math.PI * 2;
    lamps.setMatrixAt(i, m4.makeTranslation(Math.cos(a) * (PAD.r - .9), deckH + .1, Math.sin(a) * (PAD.r - .9)));
    lamps.setColorAt(i, amber);
  }
  g.add(lamps);

  // Hangar (local x runs along the departure line, local z to its right)
  const wall = std("#a49c90"), roofM = std("#7d8288", { roughness: .6, metalness: .3 });
  add(new THREE.BoxGeometry(32, 9, 18), wall, 0, 4.5, 64);
  const roof = add(new THREE.CylinderGeometry(9, 9, 32, 28, 1, false, 0, Math.PI), roofM, 0, 9, 64);
  roof.rotation.z = Math.PI / 2; roof.scale.x = .5;
  add(new THREE.BoxGeometry(20, 7.5, .3), std("#2c3036"), 0, 3.75, 54.9);
  add(new THREE.BoxGeometry(28, .7, .2), std("#2a2a2a", { emissive: "#ffcf8f", emissiveIntensity: .9 }), 0, 8.1, 54.95);
  for (let k = 0; k < 3; k++) {
    const t = add(new THREE.CylinderGeometry(2.2, 2.2, 10, 24), std("#dcd6ca", { roughness: .5 }), -24 - k * 5.4, 2.3, 62);
    t.rotation.x = Math.PI / 2;
    add(new THREE.CylinderGeometry(2.23, 2.23, .7, 24), std("#23a092"), -24 - k * 5.4, 2.3, 62).rotation.x = Math.PI / 2;
  }
  add(new THREE.CylinderGeometry(.35, .6, 32, 10), std("#b7bcc2", { metalness: .6, roughness: .4 }), 24, 16, 50);
  const dish = add(new THREE.SphereGeometry(2.4, 20, 10, 0, Math.PI * 2, 0, Math.PI / 3), std("#e6e2da", { side: THREE.DoubleSide }), 24, 27, 50);
  dish.rotation.z = 1.1;
  const beaconMat = new THREE.MeshBasicMaterial({ color: "#ff3b2f" });
  add(new THREE.SphereGeometry(.45, 12, 8), beaconMat, 24, 32.3, 50);
  for (const [x, z] of [[30, 30], [-30, 30], [30, -30], [-30, -30]]) {
    add(new THREE.CylinderGeometry(.18, .25, 12, 8), std("#8d9298"), x, 6, z);
    add(new THREE.BoxGeometry(1.4, .5, .9), std("#2b2f35", { emissive: "#fff1d6", emissiveIntensity: .6 }), x * .97, 12, z * .97);
  }

  // Dust kicked up by the lift vents
  const ND = 220, R = rng(3), dpos = new Float32Array(ND * 3), dal = new Float32Array(ND), seeds = [];
  for (let i = 0; i < ND; i++) seeds.push([R() * Math.PI * 2, .6 + R() * .8, R(), .5 + R() * .5]);
  const dgeo = new THREE.BufferGeometry();
  dgeo.setAttribute("position", new THREE.BufferAttribute(dpos, 3));
  dgeo.setAttribute("aAlpha", new THREE.BufferAttribute(dal, 1));
  const dustMat = new THREE.ShaderMaterial({
    vertexShader: DUST_VS, fragmentShader: DUST_FS, transparent: true, depthWrite: false,
    uniforms: { uCol: { value: new THREE.Color("#cfa883") }, uOp: { value: 0 }, uSize: { value: 9 }, uScale: { value: 500 } },
  });
  const dust = new THREE.Points(dgeo, dustMat); dust.frustumCulled = false; g.add(dust);

  function update(clock, st, pointScale) {
    for (let i = 0; i < 36; i++) {
      const ph = ((clock * .9 - i / 36) % 1 + 1) % 1;
      lamps.setColorAt(i, tc.copy(amber).multiplyScalar(.18 + .82 * Math.max(0, 1 - ph * 7)));
    }
    lamps.instanceColor.needsUpdate = true;
    beaconMat.color.setRGB(clock % 2 < .3 ? 1 : .15, .05, .03);
    const alt = st.pos.y - PAD.deck - LANDED_H;
    const k = st.c.hover * (1 - sstep(4, 26, alt)) * (1 - sstep(10, 30, Math.hypot(st.pos.x - PAD.x, st.pos.z - PAD.z)));
    dust.visible = k > .01;
    if (!dust.visible) return;
    dustMat.uniforms.uOp.value = .55 * k; dustMat.uniforms.uScale.value = pointScale;
    for (let i = 0; i < ND; i++) {
      const [ang, sp, ph, w] = seeds[i], age = (clock * sp * .3 + ph) % 1, r = 3 + age * 46;
      dpos[i * 3] = Math.cos(ang) * r; dpos[i * 3 + 1] = deckH + .6 + age * 5; dpos[i * 3 + 2] = Math.sin(ang) * r;
      dal[i] = Math.sin(Math.PI * age) * w;
    }
    dgeo.attributes.position.needsUpdate = true; dgeo.attributes.aAlpha.needsUpdate = true;
  }
  return { update };
}

// ---------- run ----------
const DESIGN_ASPECT = 16 / 9;

function main() {
  const app = document.getElementById("app");
  const canvas = document.createElement("canvas");
  canvas.id = "gl";
  canvas.setAttribute("role", "img");
  canvas.setAttribute("aria-label", "Animated 3D courier ship lifting off a desert landing pad, flying a canyon circuit past an arch, a lake and rock spires, then landing");
  app.appendChild(canvas);

  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: "high-performance" });
  renderer.toneMapping = THREE.NeutralToneMapping;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;

  const scene = new THREE.Scene();
  scene.fog = new THREE.FogExp2(SKY.hor, .0008);
  const camera = new THREE.PerspectiveCamera(45, DESIGN_ASPECT, .8, 9000);

  const world = buildWorldData();
  const flight = createFlight(world);
  const director = createDirector(world, flight);
  const sky = buildSky(scene, renderer);
  const { wtex } = buildWorldMeshes(world, scene);
  const base = buildBase(scene, flight);
  const ship = buildShip();
  scene.add(ship.root);

  const sunDir = new THREE.Vector3(...SUN_DIR).normalize();
  const sun = new THREE.DirectionalLight("#ffe3c4", 2.9);
  sun.castShadow = true;
  const ext = 16;
  Object.assign(sun.shadow.camera, { left: -ext, right: ext, top: ext, bottom: -ext, near: 1, far: 240 });
  sun.shadow.camera.updateProjectionMatrix();
  sun.shadow.mapSize.set(2048, 2048); sun.shadow.bias = -3e-4; sun.shadow.normalBias = .035;
  scene.add(sun, sun.target);
  scene.add(new THREE.HemisphereLight("#a8c6dc", "#8d5e42", .45));

  // Shadow camera follows the ship, snapped to whole texels.
  const across = new THREE.Vector3().crossVectors(new THREE.Vector3(0, 1, 0), sunDir).normalize();
  const upish = new THREE.Vector3().crossVectors(sunDir, across);
  let texel = 2 * ext / sun.shadow.mapSize.x;

  const tiers = [{ shadow: 2048, pr: 2 }, { shadow: 2048, pr: 1.5 }, { shadow: 1024, pr: 1 }];
  let tier = (matchMedia("(pointer: coarse)").matches || Math.min(innerWidth, innerHeight) < 700) ? 2 : 0;
  let fovK = 1, drawH = 1;
  const layout = () => {
    const W = Math.max(1, innerWidth), H = Math.max(1, innerHeight);
    const pr = Math.max(.5, Math.min(clamp(devicePixelRatio || 1, .75, tiers[tier].pr), Math.sqrt(5e6 / (W * H))));
    renderer.setPixelRatio(pr); renderer.setSize(W, H, false);
    camera.aspect = W / H;
    // Narrower than 16:9: widen the lens so the action stays in frame.
    fovK = clamp(DESIGN_ASPECT / camera.aspect, 1, 2.2);
    drawH = H * pr;
  };
  const applyTier = () => {
    const n = tiers[tier].shadow;
    sun.shadow.mapSize.set(n, n); sun.shadow.map?.dispose(); sun.shadow.map = null; texel = 2 * ext / n;
    layout();
  };
  applyTier();
  addEventListener("resize", layout);

  const WUP = new THREE.Vector3(0, 1, 0);
  function render(clock) {
    const t = clock % LOOP, cam = director.camAt(t), st = cam.st;
    ship.root.position.copy(st.pos); ship.root.quaternion.copy(st.q);
    ship.update(st.c, clock);
    camera.position.copy(cam.pos); camera.up.copy(cam.up || WUP); camera.lookAt(cam.look);
    camera.fov = 2 * Math.atan(Math.tan(cam.fov * D2R / 2) * fovK) / D2R;
    camera.updateProjectionMatrix();
    base.update(clock, st, drawH / (2 * Math.tan(camera.fov * D2R / 2)));
    sky.position.copy(camera.position);
    wtex.offset.set(clock * .006, clock * .004);
    const a = Math.round(st.pos.dot(across) / texel) * texel, b = Math.round(st.pos.dot(upish) / texel) * texel;
    sun.target.position.copy(across).multiplyScalar(a).addScaledVector(upish, b).addScaledVector(sunDir, st.pos.dot(sunDir));
    sun.position.copy(sun.target.position).addScaledVector(sunDir, 80);
    sun.target.updateMatrixWorld();
    renderer.render(scene, camera);
  }

  let clock = 0, last = performance.now();
  const audio = createAudio(director.marks);
  const hud = document.getElementById("hud"), snd = document.getElementById("snd");
  const toggleSound = async () => {
    if (audio.on) audio.disable();
    else { try { await audio.enable(clock); } catch (e) { console.error(e); return; } }
    snd.setAttribute("aria-pressed", String(audio.on));
  };
  snd.addEventListener("click", toggleSound);
  addEventListener("keydown", e => { if ((e.key === "m" || e.key === "M") && !e.repeat && !e.metaKey && !e.ctrlKey && !e.altKey && !(e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement)) toggleSound(); });
  setInterval(() => audio.pump(), 250);
  const perf = { n: 0, sum: 0, slow: 0, age: 0 };
  const tick = now => {
    const dt = Math.min(.1, Math.max(0, (now - last) / 1e3));
    last = now;
    clock = audio.on ? audio.clock() : clock + dt;
    audio.pump();
    // Step quality down if frames run long.
    if (tier < tiers.length - 1) {
      perf.age += dt;
      if (perf.age > .6) {
        perf.sum += dt; perf.n++;
        if (perf.sum >= .5 && perf.n >= 6) {
          perf.slow = perf.sum / perf.n > .022 ? perf.slow + 1 : 0;
          perf.sum = 0; perf.n = 0;
          if (perf.slow >= (perf.age < 6 ? 1 : 2)) { tier++; applyTier(); Object.assign(perf, { age: 0, slow: 0 }); }
        }
      }
    }
    render(clock);
    requestAnimationFrame(tick);
  };

  render(0);
  document.getElementById("msg").hidden = true;
  hud.hidden = false;
  Promise.race([
    renderer.compileAsync(scene, camera).catch(() => {}),
    new Promise(r => setTimeout(r, 1500)),
  ]).then(() => { last = performance.now(); requestAnimationFrame(tick); });
}

function say(text) {
  const el = document.getElementById("msg");
  if (el) { el.textContent = text; el.hidden = false; }
}

async function boot() {
  try { THREE = await import(THREE_URL); }
  catch { say("The 3D library didn’t load. Check your connection and reload the page."); return; }
  say("Building the canyon…");
  await new Promise(r => setTimeout(r, 40));
  try { main(); }
  catch (e) { console.error(e); say("This animation needs WebGL, which isn’t available in this browser."); }
}
boot();
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.