• 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

DIAMOND VESSEL 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>Diamond Vessel</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=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
:root{--bg:#020403;--fg:#eef4ef;--muted:rgba(226,238,230,.62);--faint:rgba(226,238,230,.14);--glass:rgba(12,18,15,.48);--stroke:rgba(255,255,255,.09);--accent:#b4ff52;--accent2:#4ff0c8;color-scheme:dark;box-sizing:border-box}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#020403;--fg:#eef4ef}}
:root[data-theme="dark"]{--bg:#020403;--fg:#eef4ef}
*,*::before,*::after{box-sizing:inherit}
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}
#fade{position:fixed;inset:0;background:#000;opacity:0;pointer-events:none}

#load{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(320px,calc(100% - 48px));text-align:center;font-family:Inter,system-ui,-apple-system,"Segoe UI",sans-serif}
#load[hidden]{display:none}
#msg{margin:0 0 14px;color:var(--muted);font-size:14px;font-weight:400;line-height:1.5}
#load .bar{display:block;height:3px;border-radius:3px;background:var(--faint);overflow:hidden}
#loadBar{display:block;height:100%;width:0;border-radius:3px;background:linear-gradient(90deg,var(--accent),var(--accent2));}

#hud{position:fixed;inset:0;pointer-events:none;color:var(--fg);font-family:Inter,system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
#hud[hidden]{display:none}
.top{position:absolute;left:clamp(16px,3vw,48px);top:clamp(16px,4vh,44px)}
.brand{display:flex;align-items:center;gap:10px;font-size:13px;font-weight:600;letter-spacing:.01em}
.logo{width:9px;height:9px;border-radius:2px;background:linear-gradient(135deg,var(--accent),var(--accent2));transform:rotate(45deg);box-shadow:0 0 14px rgba(180,255,82,.55)}
.chapter{display:flex;align-items:baseline;gap:14px;margin-top:18px}
.chapter .num{font-size:13px;font-weight:500;color:var(--accent);font-variant-numeric:tabular-nums}
.chapter h1{margin:0;font-size:clamp(32px,4.4vw,68px);font-weight:300;letter-spacing:-.025em;line-height:1;will-change:transform,opacity}
.tags{position:absolute;right:clamp(16px,3vw,48px);top:clamp(16px,4vh,44px);display:flex;gap:8px}
.tags span{font-size:12px;font-weight:500;color:var(--muted);padding:7px 12px;border-radius:999px;background:var(--glass);border:1px solid var(--stroke);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px)}

.dock{position:absolute;left:50%;bottom:clamp(16px,3.5vh,36px);transform:translateX(-50%);width:min(1120px,calc(100% - 32px));padding:14px 18px 12px;border-radius:22px;background:var(--glass);border:1px solid var(--stroke);-webkit-backdrop-filter:blur(18px) saturate(140%);backdrop-filter:blur(18px) saturate(140%);box-shadow:0 24px 60px rgba(0,0,0,.35)}
#spec{display:block;width:100%;height:52px}
.row{display:flex;align-items:center;gap:18px;margin-top:10px}
#sound{pointer-events:auto;display:inline-flex;align-items:center;gap:10px;height:40px;padding:0 16px 0 6px;border-radius:999px;border:1px solid var(--stroke);background:rgba(255,255,255,.06);color:var(--fg);font:500 13px/1 Inter,system-ui,sans-serif;cursor:pointer;white-space:nowrap}
#sound:hover{background:rgba(255,255,255,.12)}
#sound:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
#sound[hidden]{display:none}
#sound .ic{width:28px;height:28px;border-radius:50%;display:grid;place-items:center;background:linear-gradient(135deg,var(--accent),var(--accent2));color:#06110a}
#sound .ic svg{width:12px;height:12px}
#sound .pause,#sound.playing .play{display:none}
#sound.playing .pause{display:block}
.time{font-size:13px;font-weight:500;font-variant-numeric:tabular-nums;color:var(--muted);white-space:nowrap}
.time b{color:var(--fg);font-weight:600}
.track{position:relative;flex:1;min-width:0;height:34px}
.rail{position:absolute;left:0;right:0;top:6px;height:4px;border-radius:4px;background:var(--faint);overflow:hidden}
#fill{position:absolute;inset:0;transform-origin:0 50%;transform:scaleX(0);background:linear-gradient(90deg,var(--accent),var(--accent2))}
.tick{position:absolute;top:0;width:0}
.tick::before{content:"";position:absolute;left:-1px;top:3px;width:2px;height:10px;border-radius:2px;background:rgba(226,238,230,.3)}
.tick span{position:absolute;left:0;top:18px;font-size:11px;font-weight:500;color:var(--muted);white-space:nowrap}
.tick.on span{color:var(--fg)}
.tick.on::before{background:var(--accent)}
.rings{display:flex;gap:12px}
.rings figure{margin:0;display:flex;flex-direction:column;align-items:center;gap:3px}
.rings svg{width:32px;height:32px;transform:rotate(-90deg)}
.rings circle{fill:none;stroke-width:3.2;stroke-linecap:round}
.rings .bg{stroke:var(--faint)}
.rings .lv{stroke:url(#lvGrad);stroke-dasharray:0 100}
.rings figcaption{font-size:10px;font-weight:500;color:var(--muted);letter-spacing:.03em}
@media (max-width:860px){.tags{display:none}.tick span{display:none}.track{height:16px}}
@media (max-width:600px){.rings{display:none}.time span{display:none}.dock{padding:10px 12px}.row{gap:12px}}
@media (max-width:767px){.top{left:24px;top:144px}.dock{bottom:60px;width:calc(100% - 48px)}}
@media (min-width:768px){.top{left:80px;top:148px}.tags{right:80px;top:148px}.dock{bottom:84px;width:min(1120px,calc(100% - 160px))}}
</style>
<script type="importmap">
{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"}}
</script>
</head>
<body>
<div id="app"></div>
<div id="hud" hidden>
  <header class="top">
    <div class="brand"><span class="logo"></span>Diamond Vessel</div>
    <div class="chapter"><span class="num" id="secNum">01</span><h1 id="sec">Awaken</h1></div>
  </header>
  <div class="tags"><span>Audio-reactive</span><span>172 BPM</span><span>D minor</span></div>
  <section class="dock" aria-label="Player">
    <canvas id="spec" aria-hidden="true"></canvas>
    <div class="row">
      <button id="sound" type="button" hidden aria-label="Play with sound">
        <span class="ic">
          <svg class="play" viewBox="0 0 12 12" aria-hidden="true"><path d="M3 1.6v8.8L10.2 6z" fill="currentColor"/></svg>
          <svg class="pause" viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 1.5h2.6v9H2.5zM6.9 1.5h2.6v9H6.9z" fill="currentColor"/></svg>
        </span>
        <span class="lbl">Play with sound</span>
      </button>
      <div class="time"><b id="tNow">0:00</b><span> / <span id="tDur">2:00</span></span></div>
      <div class="track"><div class="rail"><div id="fill"></div></div><div id="ticks"></div></div>
      <div class="rings">
        <svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs><linearGradient id="lvGrad" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#b4ff52"/><stop offset="1" stop-color="#4ff0c8"/></linearGradient></defs></svg>
        <figure><svg viewBox="0 0 36 36" aria-hidden="true"><circle class="bg" cx="18" cy="18" r="15.915"/><circle class="lv" id="rLow" cx="18" cy="18" r="15.915"/></svg><figcaption>Low</figcaption></figure>
        <figure><svg viewBox="0 0 36 36" aria-hidden="true"><circle class="bg" cx="18" cy="18" r="15.915"/><circle class="lv" id="rMid" cx="18" cy="18" r="15.915"/></svg><figcaption>Mid</figcaption></figure>
        <figure><svg viewBox="0 0 36 36" aria-hidden="true"><circle class="bg" cx="18" cy="18" r="15.915"/><circle class="lv" id="rHigh" cx="18" cy="18" r="15.915"/></svg><figcaption>High</figcaption></figure>
      </div>
    </div>
  </section>
</div>
<div id="fade"></div>
<div id="load" role="status" hidden><p id="msg"></p><span class="bar"><span id="loadBar"></span></span></div>
<script type="module">
let THREE;
const RENDER = new URLSearchParams(location.search).has("render");

// ---------- 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 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 lerp = (a, b, k) => a + (b - a) * k;
const keys = (ks, t) => {
  if (t <= ks[0][0]) return ks[0][1];
  for (let i = 0; i < ks.length - 1; i++) if (t <= ks[i + 1][0]) return lerp(ks[i][1], ks[i + 1][1], (t - ks[i][0]) / (ks[i + 1][0] - ks[i][0]));
  return ks[ks.length - 1][1];
};
function rng(seed) {
  let s = seed >>> 0;
  return () => {
    s = (s + 0x6D2B79F5) >>> 0;
    let t = s;
    t = Math.imul(t ^ t >>> 15, t | 1);
    t ^= t + Math.imul(t ^ t >>> 7, t | 61);
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}

// ---------- the film: 120 s of 172 BPM drum and bass, 86 bars ----------
const DURATION = 120, FPS = 60, SR = 48000, BPM = 172, BEAT = 60 / BPM, BAR = 4 * BEAT, STEP = BAR / 16;
const bt = b => b * BAR;
const SECTIONS = [
  { b: 0, name: "Awaken" }, { b: 8, name: "Signal" }, { b: 16, name: "Drop" }, { b: 32, name: "Lattice" },
  { b: 40, name: "Build" }, { b: 48, name: "Unfold" }, { b: 64, name: "Charge" }, { b: 72, name: "Discharge" }, { b: 80, name: "Drift" },
].map(s => ({ ...s, t: bt(s.b) }));
const HIT = bt(72);
const sectionAt = t => { let i = 0; while (i < SECTIONS.length - 1 && SECTIONS[i + 1].t <= t) i++; return i; };
const DROPS = [[16, 32], [48, 64], [72, 80]];
const inDrop = b => DROPS.some(([a, z]) => b >= a && b < z);

// Glitch edits: a stutter or a bit-crushed break on the last beat of every fourth bar of a drop, plus seeded
// stray blips. The score plays them and the picture jumps on them, both from this one list.
const GLITCHES = (() => {
  const R = rng(303), out = [];
  for (let b = 16; b < 80; b++) {
    if (!inDrop(b)) continue;
    if (b % 4 === 3) out.push({ t: bt(b) + 3 * BEAT, dur: BEAT, kind: R() < .5 ? "stutter" : "crush" });
    else if (R() < .3) out.push({ t: bt(b) + (1 + Math.floor(R() * 2)) * BEAT + (R() < .5 ? BEAT / 2 : 0), dur: BEAT / 2, kind: "blip" });
  }
  return out;
})();
const inEdit = t => GLITCHES.some(e => e.kind !== "blip" && t >= e.t - 1e-4 && t < e.t + e.dur);
const glitchAt = t => {
  let g = 0;
  for (const e of GLITCHES) if (t >= e.t && t < e.t + e.dur + .12) g = Math.max(g, (e.kind === "blip" ? .55 : 1) * (1 - Math.max(0, t - e.t - e.dur) / .12));
  return g;
};

// ---------- the score (WebAudio, rendered offline so picture and sound share one buffer) ----------
const hz = m => 440 * Math.pow(2, (m - 69) / 12);
const PROG = [
  { root: 38, ch: [62, 65, 69] }, // Dm
  { root: 34, ch: [58, 62, 65] }, // Bb
  { root: 31, ch: [55, 58, 62] }, // Gm
  { root: 33, ch: [57, 61, 64] }, // A
];
// Two bars per chord; the charge sits on Bb then the dominant A, the outro rocks Dm–Bb.
const chordAt = b => b >= 80 ? PROG[(b >> 1) % 2] : b >= 72 ? PROG[(b >> 1) % 4] : b >= 68 ? PROG[3] : b >= 64 ? PROG[1] : PROG[(b >> 1) % 4];
const PAD_CUT = [[0, 260], [bt(8), 600], [bt(16), 1300], [bt(32), 900], [bt(40), 700], [bt(48), 1900], [bt(64), 1100], [HIT, 5000], [HIT + .5, 1600], [bt(80), 900], [DURATION, 500]];

async function renderScore(progress = () => {}) {
  const ctx = new OfflineAudioContext(2, Math.round(SR * DURATION), SR);
  const R = rng(1977);
  const noise = ctx.createBuffer(1, SR * 3, SR);
  { const d = noise.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = R() * 2 - 1; }

  const comp = ctx.createDynamicsCompressor();
  comp.threshold.value = -16; comp.knee.value = 8; comp.ratio.value = 4; comp.attack.value = .003; comp.release.value = .12;
  comp.connect(ctx.destination);

  const gain = v => { const g = ctx.createGain(); g.gain.value = v; return g; };
  const filt = (type, f, q = .7) => { const b = ctx.createBiquadFilter(); b.type = type; b.frequency.value = f; b.Q.value = q; return b; };

  // Reverb: damped feedback combs per channel. A long ConvolverNode renders many times slower offline.
  // The damping filter needs Q below 0 dB: any resonant peak lifts the loop gain over 1 and the comb runs away.
  const verbIn = ctx.createGain(), verbOut = gain(.07), split = ctx.createChannelSplitter(2), merge = ctx.createChannelMerger(2);
  verbIn.connect(split); merge.connect(verbOut).connect(comp);
  [[.0297, .0371, .0411, .0437, .0503, .0571], [.0307, .0383, .0421, .0449, .0517, .0587]].forEach((ds, ch) => {
    for (const dt of ds) {
      const d = ctx.createDelay(.1), lp = filt("lowpass", 3200, -3), fb = gain(Math.pow(.001, dt / 2.2));
      d.delayTime.value = dt;
      split.connect(d, ch); d.connect(lp).connect(fb).connect(d); lp.connect(merge, 0, ch);
    }
  });

  const dly = ctx.createDelay(2), dlyFb = gain(.38), dlyLp = filt("lowpass", 2800, -3), dlyOut = gain(.5);
  dly.delayTime.value = BEAT * .75;
  dly.connect(dlyLp); dlyLp.connect(dlyFb).connect(dly); dlyLp.connect(dlyOut).connect(comp);

  const bus = (level, { v = 0, d = 0, p = 0 } = {}) => {
    const g = gain(level), pan = ctx.createStereoPanner();
    pan.pan.value = p;
    g.connect(pan).connect(comp);
    if (v) pan.connect(gain(v)).connect(verbIn);
    if (d) pan.connect(gain(d)).connect(dly);
    return g;
  };
  const B = {
    kick: bus(.95, { v: .03 }), snare: bus(.5, { v: .22, p: .04 }), hat: bus(.16, { v: .08, p: .2 }),
    reese: bus(.26), sub: bus(.6), arp: bus(.12, { v: .3, d: .5, p: -.22 }), ping: bus(.18, { v: .75, d: .4, p: .25 }),
    pad: bus(.06, { v: .6 }), fx: bus(.3, { v: .55 }), drone: bus(.28, { v: .2 }), hit: bus(.85, { v: .9 }),
  };
  // Bit crusher: a 9-step staircase shaper. The glitch bleeps always pass through it; the reese joins it in the second drop.
  {
    const ws = ctx.createWaveShaper(), n = 4096, curve = new Float32Array(n);
    for (let i = 0; i < n; i++) curve[i] = Math.round((i / (n - 1) * 2 - 1) * 4) / 4;
    ws.curve = curve;
    B.crush = gain(1);
    B.crush.connect(ws).connect(bus(.13, { v: .2, d: .35, p: -.15 }));
    const send = gain(0);
    send.gain.setValueAtTime(0, 0); send.gain.setValueAtTime(.55, bt(48)); send.gain.setValueAtTime(0, bt(64));
    send.gain.setValueAtTime(.35, HIT); send.gain.setValueAtTime(0, bt(80));
    B.reese.connect(send).connect(B.crush);
  }
  const osc = (type, f, det = 0) => { const o = ctx.createOscillator(); o.type = type; o.frequency.value = f; o.detune.value = det; return o; };
  const noiseSrc = (t, dur) => { const s = ctx.createBufferSource(); s.buffer = noise; s.loop = true; s.start(t, R() * 2); s.stop(t + dur); return s; };

  const kick = (t, a = 1) => {
    const o = osc("sine", 190), g = gain(0);
    o.frequency.setValueAtTime(190, t); o.frequency.exponentialRampToValueAtTime(48, t + .07);
    g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + .002); g.gain.exponentialRampToValueAtTime(.0005, t + .32);
    o.connect(g).connect(B.kick); o.start(t); o.stop(t + .34);
    const ng = gain(0);
    ng.gain.setValueAtTime(.3 * a, t); ng.gain.exponentialRampToValueAtTime(.001, t + .02);
    noiseSrc(t, .025).connect(filt("highpass", 3000)).connect(ng).connect(B.kick);
  };
  const snare = (t, a = 1, pitch = 1) => {
    const o = osc("triangle", 240 * pitch), og = gain(0);
    o.frequency.setValueAtTime(240 * pitch, t); o.frequency.exponentialRampToValueAtTime(170 * pitch, t + .05);
    og.gain.setValueAtTime(.7 * a, t); og.gain.exponentialRampToValueAtTime(.001, t + .09);
    o.connect(og).connect(B.snare); o.start(t); o.stop(t + .1);
    const ng = gain(0), dec = a > .6 ? .2 : .1;
    ng.gain.setValueAtTime(a, t); ng.gain.exponentialRampToValueAtTime(.001, t + dec);
    noiseSrc(t, dec + .02).connect(filt("bandpass", Math.min(7000, 2200 * pitch), .6)).connect(ng).connect(B.snare);
  };
  const hat = (t, a = 1, dec = .04) => {
    const g = gain(0);
    g.gain.setValueAtTime(a, t); g.gain.exponentialRampToValueAtTime(.001, t + dec);
    noiseSrc(t, dec + .02).connect(filt("highpass", 7800)).connect(g).connect(B.hat);
  };
  const bleep = (t, m, dur, a = 1) => {
    const o = osc("square", hz(m)), g = gain(0);
    g.gain.setValueAtTime(a, t); g.gain.setValueAtTime(a, t + dur * .8); g.gain.linearRampToValueAtTime(0, t + dur);
    o.connect(g).connect(B.crush); o.start(t); o.stop(t + dur + .01);
  };
  // Reese: detuned saws through a gentle lowpass, optionally wobbled by an LFO, with a clean sine sub an octave down.
  // `stop` pitches it down like a tape stop. Filter Q stays low: a resonant filter under automation goes unstable.
  const reese = (t, m, dur, a = 1, wob = 0, stop = false) => {
    const f = filt("lowpass", 600, 1.2), g = gain(0), sg = gain(0);
    f.frequency.setValueAtTime(420 + 700 * a, t); f.frequency.linearRampToValueAtTime(320 + 300 * a, t + dur);
    if (wob) { const l = osc("sine", wob), lg = gain(260); l.connect(lg).connect(f.frequency); l.start(t); l.stop(t + dur + .02); }
    for (const env of [g, sg]) {
      const k = env === g ? a : .9 * a;
      env.gain.setValueAtTime(0, t); env.gain.linearRampToValueAtTime(k, t + .008);
      env.gain.setValueAtTime(k, Math.max(t + .01, t + dur - .03)); env.gain.linearRampToValueAtTime(0, t + dur);
    }
    const pitch = (o, f0) => { o.frequency.setValueAtTime(f0, t); if (stop) o.frequency.exponentialRampToValueAtTime(f0 * .3, t + dur); };
    for (const det of [-22, 22, -7]) { const o = osc("sawtooth", hz(m), det); pitch(o, hz(m)); o.connect(f); o.start(t); o.stop(t + dur + .02); }
    const s = osc("sine", hz(m - 12)); pitch(s, hz(m - 12)); s.connect(sg).connect(B.sub); s.start(t); s.stop(t + dur + .02);
    f.connect(g).connect(B.reese);
  };
  const pluck = (t, m, a = 1) => {
    const f = filt("lowpass", 4200, 2.5), g = gain(0);
    f.frequency.setValueAtTime(4200, t); f.frequency.exponentialRampToValueAtTime(500, t + .25);
    g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + .003); g.gain.exponentialRampToValueAtTime(.001, t + .3);
    for (const [type, det] of [["square", -5], ["sawtooth", 5]]) { const o = osc(type, hz(m), det); o.connect(f); o.start(t); o.stop(t + .32); }
    f.connect(g).connect(B.arp);
  };
  const ping = (t, m, a = 1, len = 2.6) => {
    const c = osc("sine", hz(m)), mo = osc("sine", hz(m) * 3.51), mg = gain(0), g = gain(0);
    mg.gain.setValueAtTime(hz(m) * 2.2, t); mg.gain.exponentialRampToValueAtTime(1, t + len * .7);
    mo.connect(mg).connect(c.frequency);
    g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + .004); g.gain.exponentialRampToValueAtTime(.0005, t + len);
    c.connect(g).connect(B.ping);
    for (const o of [c, mo]) { o.start(t); o.stop(t + len + .05); }
  };
  const pad = (t, dur, ms, a = 1, rel = .9) => {
    const f = filt("lowpass", 400, .7), g = gain(0);
    f.frequency.setValueAtTime(keys(PAD_CUT, t), t); f.frequency.linearRampToValueAtTime(keys(PAD_CUT, t + dur), t + dur);
    g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + Math.min(.6, dur * .4));
    g.gain.setValueAtTime(a, t + dur); g.gain.linearRampToValueAtTime(0, t + dur + rel);
    for (const m of ms) for (const det of [-11, 11]) { const o = osc("sawtooth", hz(m), det); o.connect(f); o.start(t); o.stop(t + dur + rel + .05); }
    f.connect(g).connect(B.pad);
  };
  const riser = (t0, t1, a = 1) => {
    const bp = filt("bandpass", 250, 3), g = gain(0);
    bp.frequency.setValueAtTime(250, t0); bp.frequency.exponentialRampToValueAtTime(6500, t1);
    g.gain.setValueAtTime(.001, t0); g.gain.exponentialRampToValueAtTime(a, t1 - .02); g.gain.linearRampToValueAtTime(0, t1 + .02);
    noiseSrc(t0, t1 - t0 + .05).connect(bp).connect(g).connect(B.fx);
    const o = osc("sawtooth", 110), lp = filt("lowpass", 1800), og = gain(0);
    o.frequency.setValueAtTime(110, t0); o.frequency.exponentialRampToValueAtTime(880, t1);
    og.gain.setValueAtTime(0, t0); og.gain.linearRampToValueAtTime(.22 * a, t1 - .02); og.gain.linearRampToValueAtTime(0, t1 + .02);
    o.connect(lp).connect(og).connect(B.fx); o.start(t0); o.stop(t1 + .05);
  };
  const impact = t => {
    const s = osc("sine", 95), sg = gain(0);
    s.frequency.setValueAtTime(95, t); s.frequency.exponentialRampToValueAtTime(26, t + 2.2);
    sg.gain.setValueAtTime(1, t); sg.gain.exponentialRampToValueAtTime(.001, t + 3);
    s.connect(sg).connect(B.hit); s.start(t); s.stop(t + 3.05);
    const lp = filt("lowpass", 9000), ng = gain(0);
    lp.frequency.setValueAtTime(9000, t); lp.frequency.exponentialRampToValueAtTime(140, t + 2.4);
    ng.gain.setValueAtTime(.8, t); ng.gain.exponentialRampToValueAtTime(.001, t + 2.8);
    noiseSrc(t, 2.9).connect(lp).connect(ng).connect(B.hit);
    const cg = gain(0);
    cg.gain.setValueAtTime(.35, t); cg.gain.exponentialRampToValueAtTime(.001, t + 3.6);
    noiseSrc(t, 3.7).connect(filt("highpass", 4500)).connect(cg).connect(B.hit);
    kick(t, 1.2);
  };

  // Drone under everything: swells in, sits back under the drops, tightens for the charge, falls away at the end.
  {
    const g = gain(0), D = [[0, 0], [6, 1], [bt(16) - .1, 1], [bt(16), .45], [bt(32), .45], [bt(33), .9], [bt(48) - .1, .9], [bt(48), .45],
      [bt(64), .5], [HIT, 1.2], [HIT + .5, .5], [bt(80), .7], [DURATION, 0]];
    for (const [t, v] of D) g.gain.linearRampToValueAtTime(v, t);
    const lp = filt("lowpass", 240);
    for (const [type, m, lvl] of [["sine", 26, .9], ["sawtooth", 38, .35], ["sawtooth", 38.08, .35]]) {
      const o = osc(type, hz(m)); o.connect(gain(lvl)).connect(lp); o.start(0); o.stop(DURATION);
    }
    lp.connect(g).connect(B.drone);
  }

  // Each bar's voices are built only when the renderer reaches that bar: a scheduled node that hasn't started
  // yet still costs processing in every render block, which made the full score take tens of seconds.
  const queue = [], later = f => (t, ...a) => queue.push([t, () => f(t, ...a)]);
  const Q = Object.fromEntries(Object.entries({ kick, snare, hat, bleep, reese, pluck, ping, pad, riser, impact }).map(([k, f]) => [k, later(f)]));
  {
  const { kick, snare, hat, bleep, reese, pluck, ping, pad, riser, impact } = Q;

  // Two-step break: kick on 1 and the "and" of 3, snare on 2 and 4, seeded ghost notes and kick pickups,
  // swung off-sixteenths. Steps under a glitch edit are left out so the edit owns that beat.
  const drums = (b, mode, energy = 1) => {
    const r = rng(b * 7919 + 13), t0 = bt(b);
    const step = (s, fn) => { const t = t0 + s * STEP + (s % 2 ? .008 : 0); if (!inEdit(t)) fn(t); };
    if (mode === "half") {
      step(0, t => kick(t, 1)); step(8, t => snare(t, .95));
      if (r() < .5) step(14, t => kick(t, .7));
      for (let s = 0; s < 16; s += 2) step(s, t => hat(t, s % 4 ? .35 : .6, s === 4 || s === 12 ? .2 : .04));
      return;
    }
    if (mode !== "hats") {
      const kicks = [0, 10], light = mode === "light";
      if (!light && r() < .5) kicks.push(r() < .5 ? 7 : 13);
      if (!light && b % 4 === 2) kicks.push(15);
      for (const s of kicks) step(s, t => kick(t, (s === 0 ? 1 : .88) * (light ? .55 : 1)));
      for (const s of [4, 12]) step(s, t => snare(t, light ? .42 : energy));
      if (!light) for (const s of [3, 7, 9, 11, 14, 15]) if (r() < .34 * energy) step(s, t => snare(t, .16 + r() * .12, 1.18));
    }
    for (let s = 0; s < 16; s++) {
      if ((mode === "light" || mode === "hats") && s % 2) continue;
      if (r() < .08) continue;
      const a = [1, .35, .65, .35][s % 4] * (mode === "full" ? .85 : .55);
      step(s, t => hat(t, a, (s === 2 || s === 10) && r() < .4 ? .2 : .04));
    }
  };
  // Reese riff: three syncopated notes a bar, shortened before an edit so the stutter lands in a gap.
  const bassBar = (b, wob = 0) => {
    const t0 = bt(b), c = chordAt(b), r = rng(b * 104729 + 7), edit = inDrop(b) && b % 4 === 3;
    const notes = [[0, 6, 0], [7, 3, r() < .3 ? 12 : 0], [10, edit ? 2 : 6, r() < .25 ? 7 : r() < .2 ? -2 : 0]];
    for (const [s, len, iv] of notes) reese(t0 + s * STEP, c.root + iv, len * STEP * .95, s === 0 ? 1 : .85, wob);
  };
  const roll = (t0, t1, a0, a1) => {
    for (let t = t0; t < t1 - 1e-6;) {
      const k = (t - t0) / (t1 - t0);
      snare(t, a0 + (a1 - a0) * k, 1 + .5 * k);
      t += k < .5 ? BEAT / 2 : k < .75 ? BEAT / 4 : BEAT / 8;
    }
  };

  for (let b = 0; b < 86; b++) {
    const t = bt(b), c = chordAt(b), sec = sectionAt(t + 1e-3);
    if (b % 2 === 0) {
      const amp = [.6, .5, .32, .62, .5, .3, .5, .32, .7][sec];
      if (b < 80) pad(t, 2 * BAR, [c.root + 12, ...c.ch], amp);
    }
    if (b < 8 && b % 2 === 0) { ping(t, c.ch[2] + 12, .8); ping(t + BEAT * 2.5, c.ch[1] + 24, .45); }
    if (b >= 8 && b < 16) {
      drums(b, "light");
      if (b % 2 === 0) reese(t, c.root, 2 * BAR * .98, .42);
    }
    if (b >= 16 && b < 32) { drums(b, "full"); bassBar(b); }
    if (b >= 32 && b < 40) {
      drums(b, "hats");
      if (b % 2 === 0) ping(t, c.ch[2] + 24, .55, 2.2);
      for (let i = 0; i < 8; i++) pluck(t + i * BEAT / 2, [c.ch[0], c.ch[1], c.ch[2], c.ch[1]][i % 4] + 12 + (i >= 4 ? 12 : 0), i % 2 ? .55 : .9);
    }
    if (b >= 40 && b < 48) {
      if (b < 46) drums(b, "light");
      for (let i = 0; i < 8; i++) pluck(t + i * BEAT / 2, [c.ch[0], c.ch[1], c.ch[2], c.ch[1]][i % 4] + 12 + (i >= 4 ? 12 : 0), (i % 2 ? .5 : .85) * (.7 + .3 * (b - 40) / 8));
      if (b % 2 === 0) reese(t, c.root, 2 * BAR * .98, .5);
    }
    if (b >= 48 && b < 64) { drums(b, "full", 1.1); bassBar(b, b % 2 ? 2 / BEAT : 1 / BEAT); }
    if (b >= 64 && b < 72) {
      if (b < 70) drums(b, "half");
      reese(t, c.root, BAR * .96, .75, 1 / BEAT);
      if (b >= 68) for (let i = 0; i < 8; i++) pluck(t + i * BEAT / 2, c.ch[i % 3] + 24, .6 + .4 * (b - 68 + i / 8) / 4);
    }
    if (b >= 72 && b < 80) { drums(b, "full", 1.15); bassBar(b, 1 / BEAT); }
    if (b >= 80) {
      if (b % 2 === 0) ping(t, c.ch[2] + 12, .5, 2.6);
      if (b === 82) bleep(t + BEAT, 81, STEP * .6, .5);
    }
  }
  pad(bt(80), DURATION - bt(80) - 1.4, [38, 50, 57, 62, 65, 69], .8, 1.3);
  riser(bt(14), bt(16), .6); riser(bt(44), bt(48), .8); riser(bt(64), HIT, 1);
  roll(bt(46), bt(48), .2, .85); roll(bt(70), HIT, .2, .9);
  impact(HIT);
  ping(HIT + .02, 74, .9, 3.8);

  for (const e of GLITCHES) {
    const c = chordAt(Math.floor(e.t / BAR)), r = rng(Math.round(e.t * 1000)), notes = [...c.ch, ...c.ch.map(m => m + 12)];
    if (e.kind === "stutter") {
      for (let i = 0; i < 8; i++) snare(e.t + i * e.dur / 8, .25 + .55 * i / 8, 1 + i * .14);
      kick(e.t, .9);
    } else if (e.kind === "crush") {
      for (let i = 0; i < 8; i++) bleep(e.t + i * e.dur / 8, notes[Math.floor(r() * notes.length)] + 12, e.dur / 8 * .8, .85);
      reese(e.t, c.root, e.dur, .9, 0, true);
    } else {
      for (let i = 0; i < 3; i++) bleep(e.t + i * STEP / 2, c.ch[i] + 24, STEP / 2 * .7, .6);
    }
  }
  }
  queue.sort((x, y) => x[0] - y[0]);
  const build = (t0, t1) => { for (const [t, f] of queue) if (t >= t0 && t < t1) f(); };
  // Suspend a little ahead of each bar: suspend times snap to 128-frame blocks, and bar lines at 172 BPM don't.
  const lead = .02;
  build(-1, BAR);
  for (let b = 1; b * BAR < DURATION; b++) ctx.suspend(b * BAR - lead).then(() => { progress(b * BAR / DURATION); build(b * BAR, (b + 1) * BAR); ctx.resume(); });

  const buf = await ctx.startRendering();
  // A single non-finite sample would turn the normalised score, and every visual driven by it, into NaN.
  let peak = 0;
  for (let c = 0; c < 2; c++) { const d = buf.getChannelData(c); for (let i = 0; i < d.length; i++) { if (!Number.isFinite(d[i])) d[i] = 0; peak = Math.max(peak, Math.abs(d[i])); } }
  const k = .89 / Math.max(peak, 1e-6), fadeN = Math.round(SR * .8);
  for (let c = 0; c < 2; c++) {
    const d = buf.getChannelData(c);
    for (let i = 0; i < d.length; i++) d[i] *= k * Math.min(1, (d.length - i) / fadeN);
  }
  return buf;
}

function wavBase64(buf) {
  const n = buf.length, ch = 2, bytes = 44 + n * ch * 2, dv = new DataView(new ArrayBuffer(bytes));
  const w = (o, s) => { for (let i = 0; i < s.length; i++) dv.setUint8(o + i, s.charCodeAt(i)); };
  w(0, "RIFF"); dv.setUint32(4, bytes - 8, true); w(8, "WAVE"); w(12, "fmt ");
  dv.setUint32(16, 16, true); dv.setUint16(20, 1, true); dv.setUint16(22, ch, true); dv.setUint32(24, SR, true);
  dv.setUint32(28, SR * ch * 2, true); dv.setUint16(32, ch * 2, true); dv.setUint16(34, 16, true);
  w(36, "data"); dv.setUint32(40, n * ch * 2, true);
  const L = buf.getChannelData(0), Rt = buf.getChannelData(1);
  for (let i = 0, o = 44; i < n; i++) for (const d of [L, Rt]) { dv.setInt16(o, Math.round(clamp(d[i], -1, 1) * 32767), true); o += 2; }
  const u8 = new Uint8Array(dv.buffer);
  let s = "";
  for (let i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
  return btoa(s);
}

// ---------- listening: the picture reads features measured from the rendered score ----------
function fft(re, im) {
  const n = re.length;
  for (let i = 1, j = 0; i < n; i++) {
    let bit = n >> 1;
    for (; j & bit; bit >>= 1) j ^= bit;
    j ^= bit;
    if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
  }
  for (let len = 2; len <= n; len <<= 1) {
    const ang = -2 * Math.PI / len, wr = Math.cos(ang), wi = Math.sin(ang), h = len >> 1;
    for (let i = 0; i < n; i += len) {
      let cr = 1, ci = 0;
      for (let k = 0; k < h; k++) {
        const a = i + k, b = a + h, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr;
        re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi;
        const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;
      }
    }
  }
}

const BANDS = 40;
function analyse(buf) {
  const N = 1024, F = Math.round(DURATION * FPS) + 1;
  const a = buf.getChannelData(0), b = buf.getChannelData(1);
  const win = Float32Array.from({ length: N }, (_, i) => .5 - .5 * Math.cos(2 * Math.PI * i / (N - 1)));
  const edges = Array.from({ length: BANDS + 1 }, (_, i) => 40 * Math.pow(16000 / 40, i / BANDS));
  const binOf = f => clamp(Math.round(f / SR * N), 1, N / 2 - 1);
  const re = new Float32Array(N), im = new Float32Array(N), pw = new Float32Array(N / 2);
  const mean = (f0, f1) => { const b0 = binOf(f0), b1 = Math.max(b0 + 1, binOf(f1)); let s = 0; for (let k = b0; k < b1; k++) s += pw[k]; return s / (b1 - b0); };
  const spec = new Float32Array(F * BANDS), raw = { low: new Float32Array(F), mid: new Float32Array(F), high: new Float32Array(F) };
  for (let f = 0; f < F; f++) {
    const c = Math.round(f / FPS * SR) - Math.round(N * .6);
    for (let i = 0; i < N; i++) { const j = c + i; re[i] = j >= 0 && j < a.length ? (a[j] + b[j]) * .5 * win[i] : 0; im[i] = 0; }
    fft(re, im);
    for (let k = 0; k < N / 2; k++) pw[k] = re[k] * re[k] + im[k] * im[k];
    for (let k = 0; k < BANDS; k++) spec[f * BANDS + k] = 10 * Math.log10(mean(edges[k], edges[k + 1]) + 1e-12);
    raw.low[f] = Math.sqrt(mean(40, 150)); raw.mid[f] = Math.sqrt(mean(200, 2000)); raw.high[f] = Math.sqrt(mean(4000, 14000));
  }
  // Each band is scaled against its own loud end, so the equaliser shows movement in the highs as well as the bass.
  for (let k = 0; k < BANDS; k++) {
    const col = Float32Array.from({ length: F }, (_, f) => spec[f * BANDS + k]).sort(), top = col[Math.floor(F * .985)];
    for (let f = 0; f < F; f++) spec[f * BANDS + k] = clamp01((spec[f * BANDS + k] - (top - 42)) / 42);
  }

  const norm = arr => { const s = Float32Array.from(arr).sort(); const p = s[Math.floor(s.length * .98)] || 1; return arr.map(v => Math.min(1.25, v / p)); };
  const follow = (arr, tau) => { const r = Math.exp(-1 / (FPS * tau)), out = new Float32Array(F); for (let f = 0; f < F; f++) out[f] = Math.max(arr[f], (f ? out[f - 1] : 0) * r); return out; };
  const low = norm(raw.low), mid = norm(raw.mid), high = norm(raw.high);
  const kick = new Float32Array(F);
  { const r = Math.exp(-1 / (FPS * .16)); let cool = 0;
    for (let f = 0; f < F; f++) {
      const rise = f > 1 ? low[f] - Math.min(low[f - 1], low[f - 2]) : 0;
      kick[f] = f ? kick[f - 1] * r : 0; cool--;
      if (rise > .28 && cool <= 0) { kick[f] = 1; cool = 8; }
    } }
  const A = { F, spec, low: follow(low, .1), mid: follow(mid, .25), high: follow(high, .07), kick };
  A.cumMid = new Float32Array(F); A.cumHigh = new Float32Array(F);
  for (let f = 1; f < F; f++) { A.cumMid[f] = A.cumMid[f - 1] + (.15 + A.mid[f]) / FPS; A.cumHigh[f] = A.cumHigh[f - 1] + A.high[f] / FPS; }
  return A;
}
const at = (arr, t) => { const x = clamp(t * FPS, 0, arr.length - 1), i = Math.floor(x), j = Math.min(i + 1, arr.length - 1); return lerp(arr[i], arr[j], x - i); };

// ---------- vessel dimensions (one unit ≈ 1 m; Y is the spindle axis, X the spar, Z faces the viewer) ----------
const CORE = { r: 4.3 };
const SPINDLE = [[2.3, 3.6], [2.4, 7.4], [3.4, 7.8], [3.4, 8.9], [3.0, 9.3], [6.8, 15.0], [7.0, 16.2], [6.0, 17.4], [5.2, 19.5], [4.8, 22.6], [3.6, 23.6], [.001, 23.6]];
const SPAR = { r: 1.1, half: 22, tip: -24.2 };
const SPAR_BLOCKS = [ // [x, length, height, depth, material]
  [-20.2, 1.6, 1.9, 1.9, "metal"], [-17.6, 2.6, 2.2, 2.2, "hull"], [-14.8, 2.4, 2.4, 2.6, "hull"],
  [-7.2, 2.2, 2.6, 2.4, "metal"], [-5.6, .6, 3.2, 3.2, "dark"], [5.6, .6, 3.2, 3.2, "dark"],
  [9.4, 6.4, 2.4, 2.6, "hull"], [14.4, 1.2, 3.0, 3.0, "dark"], [16.6, 3.2, 2.2, 2.2, "metal"], [19.6, 1.4, 2.8, 2.8, "hull"],
];
const HEX = { x: -10.5, r: 2.4, face: 1.7, depth: 2.8 };
const QUAD = {
  outer: [[6.2, 1.5], [21.2, 1.5], [21.4, 2.2], [6.4, 19.2], [4.6, 19.2], [4.6, 15.5], [7.4, 12.6], [6.2, 7.5]],
  hole: [[9.4, 3.6], [16.6, 3.6], [17.0, 4.6], [11.6, 10.6], [9.8, 10.6], [8.8, 6.4]],
  back: [[9.0, 3.3], [13.4, 3.3], [9.4, 8.6]],
  t: 2.2,
  rim: { a: [22.6, .6], b: [3.6, 21.8], w: 2.0, t: 3.4 },
};
const GIRDER = { pts: [[-4.2, 23], [-9, 12], [-10, 2], [-9, -12], [-4.2, -23]], z: 2.8 };
const UNFOLD = 3.6;

// ---------- geometry helpers ----------
// Box-projected UVs on flat faces, so the panel texture keeps one scale on every part.
function triUV(geo, scale = 1 / 9) {
  const g = geo.index ? geo.toNonIndexed() : geo;
  g.computeVertexNormals();
  const p = g.attributes.position, n = g.attributes.normal, uv = new Float32Array(p.count * 2);
  for (let i = 0; i < p.count; i += 3) {
    const nx = Math.abs(n.getX(i)), ny = Math.abs(n.getY(i)), nz = Math.abs(n.getZ(i));
    for (let k = 0; k < 3; k++) {
      const j = i + k;
      const [u, v] = nx >= ny && nx >= nz ? [p.getZ(j), p.getY(j)] : ny >= nz ? [p.getX(j), p.getZ(j)] : [p.getX(j), p.getY(j)];
      uv[j * 2] = u * scale; uv[j * 2 + 1] = v * scale;
    }
  }
  g.setAttribute("uv", new THREE.BufferAttribute(uv, 2));
  return g;
}
const inPoly = (x, y, poly) => {
  let c = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const [xi, yi] = poly[i], [xj, yj] = poly[j];
    if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
  }
  return c;
};
const centroid = poly => poly.reduce((s, [x, y]) => [s[0] + x / poly.length, s[1] + y / poly.length], [0, 0]);

function panelTextures(seed) {
  const S = 1024, R = rng(seed);
  const mk = () => { const c = document.createElement("canvas"); c.width = c.height = S; return [c, c.getContext("2d")]; };
  const [c, g] = mk(), [e, ge] = mk();
  g.fillStyle = "#777b79"; g.fillRect(0, 0, S, S);
  ge.fillStyle = "#000"; ge.fillRect(0, 0, S, S);
  const split = (x, y, w, h, depth) => {
    if (depth > 5 || (w < 80 && h < 80) || (depth > 1 && R() < .22)) {
      const v = 95 + R() * 75 | 0;
      g.fillStyle = `rgb(${v},${v + 4},${v + 2})`; g.fillRect(x + 1, y + 1, w - 2, h - 2);
      g.strokeStyle = "rgba(0,0,0,.6)"; g.lineWidth = 2.5; g.strokeRect(x + 1.5, y + 1.5, w - 3, h - 3);
      if (R() < .4) { g.strokeStyle = "rgba(255,255,255,.08)"; g.lineWidth = 1.5; g.strokeRect(x + 6, y + 6, w - 12, h - 12); }
      ge.fillStyle = "#fff";
      if (R() < .3) { const k = 1 + R() * 4 | 0, sx = x + 8 + R() * Math.max(1, w - 50), sy = y + 8 + R() * Math.max(1, h - 20); for (let i = 0; i < k; i++) ge.fillRect(sx + i * 9, sy, 4, 4); }
      if (R() < .08 && w > 60) ge.fillRect(x + 8, y + h - 10, w * (.3 + R() * .3), 3);
      return;
    }
    if (w > h ? R() < .8 : R() < .2) { const s = w * (.3 + R() * .4); split(x, y, s, h, depth + 1); split(x + s, y, w - s, h, depth + 1); }
    else { const s = h * (.3 + R() * .4); split(x, y, w, s, depth + 1); split(x, y + s, w, h - s, depth + 1); }
  };
  split(0, 0, S, S, 0);
  const tex = (cv, srgb) => {
    const t = new THREE.CanvasTexture(cv);
    t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = 8;
    if (srgb) t.colorSpace = THREE.SRGBColorSpace;
    return t;
  };
  return { map: tex(c, true), emi: tex(e, true) };
}

// ---------- the vessel ----------
const GREEN = [.42, 1, .16];

function buildShip() {
  const T = panelTextures(11);
  const std = (color, o = {}) => new THREE.MeshStandardMaterial({ color, roughness: .5, metalness: .72, flatShading: true, envMapIntensity: .55, ...o });
  const M = {
    hull: std("#5e6562", { map: T.map, emissiveMap: T.emi, emissive: new THREE.Color(...GREEN), emissiveIntensity: .8 }),
    metal: std("#c4ccce", { map: T.map, roughness: .44, emissiveMap: T.emi, emissive: new THREE.Color(...GREEN), emissiveIntensity: .4 }),
    dark: std("#1d2120", { roughness: .55 }),
    orange: std("#b86a2a", { roughness: .5, metalness: .6, emissive: new THREE.Color("#ff7a1a"), emissiveIntensity: .25 }),
    green: new THREE.MeshBasicMaterial({ color: new THREE.Color(...GREEN) }),
    dots: new THREE.MeshBasicMaterial({ color: new THREE.Color(...GREEN) }),
    hex: new THREE.MeshBasicMaterial({ color: new THREE.Color(...GREEN) }),
    tip: new THREE.MeshBasicMaterial({ color: new THREE.Color(...GREEN), transparent: true, blending: THREE.AdditiveBlending, depthWrite: false }),
    lattice: new THREE.LineBasicMaterial({ color: "#cfe0ff", transparent: true }),
    beam: new THREE.MeshBasicMaterial({ color: "#eaffd8", transparent: true, blending: THREE.AdditiveBlending, depthWrite: false }),
    glow: new THREE.MeshBasicMaterial({ color: new THREE.Color(...GREEN), transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide }),
    shock: new THREE.MeshBasicMaterial({ color: new THREE.Color(...GREEN), transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, side: THREE.DoubleSide }),
    spark: new THREE.PointsMaterial({ color: new THREE.Color(...GREEN), size: 3, sizeAttenuation: false, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false }),
  };
  const root = new THREE.Group();
  const add = (geo, mat, parent = root, uv = true) => { const m = new THREE.Mesh(uv ? triUV(geo) : geo, mat); parent.add(m); return m; };
  const R = rng(42);

  // Core: a faceted sphere caged in a pale geodesic web.
  const core = new THREE.Group(); root.add(core);
  add(new THREE.IcosahedronGeometry(CORE.r, 1), M.hull, core);
  const lattice = new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.IcosahedronGeometry(CORE.r * 1.015, 1)), M.lattice);
  core.add(lattice);
  for (const [y, z] of [[1.6, 1], [-1.9, 1], [1.6, -1], [-1.9, -1]]) {
    const port = add(new THREE.TorusGeometry(.62, .2, 8, 16), M.dark, core);
    port.position.set(0, y, z * Math.sqrt(CORE.r * CORE.r - y * y) * 1.01);
  }

  // Spindles: octagonal hourglass halves, flat facet facing the viewer, counter-rotating.
  const spindle = sign => {
    const g = new THREE.Group();
    const prof = (sign > 0 ? SPINDLE : [...SPINDLE].reverse()).map(([r, y]) => new THREE.Vector2(r, y * sign));
    add(new THREE.LatheGeometry(prof, 8, Math.PI / 8), M.hull, g);
    const ap = Math.cos(Math.PI / 8);
    for (let k = 0; k < 8; k++) {
      const arm = new THREE.Group(); arm.rotation.y = k * Math.PI / 4; g.add(arm);
      if (k % 2 === 0) add(new THREE.BoxGeometry(2.9, .42, .12), M.green, arm, false).position.set(0, sign * 15.6, 6.9 * ap + .06);
      add(new THREE.BoxGeometry(2.1, .26, .1), M.green, arm, false).position.set(0, sign * 21.4, 4.9 * ap + .05);
      add(new THREE.BoxGeometry(2.6, .5, .3), M.dark, arm).position.set(0, sign * 18.4, 5.6 * ap + .1);
      const rib = new THREE.Group(); rib.rotation.y = Math.PI / 8; arm.add(rib);
      const r0 = 3.0, y0 = 9.3, r1 = 6.8, y1 = 15.0, len = Math.hypot(r1 - r0, y1 - y0);
      const m = add(new THREE.BoxGeometry(.38, len, .38), M.metal, rib);
      m.position.set(0, sign * (y0 + y1) / 2, (r0 + r1) / 2 + .12); m.rotation.x = sign * Math.atan2(r1 - r0, y1 - y0);
    }
    root.add(g);
    return g;
  };
  const spinTop = spindle(1), spinBot = spindle(-1);

  // Spar: the long horizontal gun, emitter at the left (−X) tip.
  const spar = new THREE.Group(); root.add(spar);
  {
    const tube = new THREE.CylinderGeometry(SPAR.r, SPAR.r, SPAR.half * 2, 8); tube.rotateZ(Math.PI / 2);
    add(tube, M.metal, spar);
    for (const [x, len, h, d, mat] of SPAR_BLOCKS) add(new THREE.BoxGeometry(len, h, d), M[mat], spar).position.x = x;
    const hub = new THREE.CylinderGeometry(HEX.r, HEX.r, HEX.depth, 6); hub.rotateX(Math.PI / 2);
    add(hub, M.hull, spar).position.x = HEX.x;
    for (const z of [1, -1]) {
      const lip = new THREE.CylinderGeometry(HEX.face + .35, HEX.face + .35, .2, 6); lip.rotateX(Math.PI / 2);
      add(lip, M.dark, spar).position.set(HEX.x, 0, z * (HEX.depth / 2 + .08));
      const face = new THREE.CylinderGeometry(HEX.face, HEX.face, .2, 6); face.rotateX(Math.PI / 2);
      add(face, M.hex, spar, false).position.set(HEX.x, 0, z * (HEX.depth / 2 + .16));
      add(new THREE.BoxGeometry(3.2, .9, .1), M.green, spar, false).position.set(7.4, 0, z * 1.36);
      add(new THREE.BoxGeometry(.9, .5, .1), M.green, spar, false).position.set(-14.8, .4, z * 1.36);
    }
    for (const sd of [1, -1]) {
      const cone = new THREE.ConeGeometry(1.25, 2.6, 8); cone.rotateZ(sd * Math.PI / 2);
      add(cone, M.metal, spar).position.x = -sd * (SPAR.half + 1.2);
    }
    for (let i = 0; i < 6; i++) {
      const h = 2 + R() * 1.4, cone = add(new THREE.ConeGeometry(.22, h, 6), M.orange, spar);
      cone.position.set(8.2 + i * .55, 1.2 + h / 2 - .3, (R() - .5) * 1.6); cone.rotation.z = -.35 - R() * .4;
    }
  }

  // Diamond frame: four quadrant plates with open windows and a heavy rim.
  const frame = new THREE.Group(); root.add(frame);
  const quads = [];
  for (const [sx, sy] of [[1, 1], [-1, 1], [-1, -1], [1, -1]]) {
    const g = new THREE.Group(); frame.add(g);
    const mir = pts => pts.map(([x, y]) => new THREE.Vector2(x * sx, y * sy));
    const ccw = v => THREE.ShapeUtils.isClockWise(v) ? v.reverse() : v;
    const cw = v => THREE.ShapeUtils.isClockWise(v) ? v : v.reverse();
    const shape = (pts, holes = []) => { const s = new THREE.Shape(ccw(mir(pts))); for (const h of holes) s.holes.push(new THREE.Path(cw(mir(h)))); return s; };
    const slab = (s, depth, z, mat) => { const geo = new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: false }); geo.translate(0, 0, z - depth / 2); return add(geo, mat, g); };
    slab(shape(QUAD.outer, [QUAD.hole]), QUAD.t, 0, M.hull);
    const c = centroid(QUAD.hole), lip = QUAD.hole.map(([x, y]) => [c[0] + (x - c[0]) * 1.16, c[1] + (y - c[1]) * 1.16]);
    for (const z of [1, -1]) slab(shape(lip, [QUAD.hole]), .5, z * (QUAD.t / 2 + .25), M.dark);
    slab(shape(QUAD.back), .4, -.5, M.dark);
    const { a, b, w, t } = QUAD.rim, L = Math.hypot(b[0] - a[0], b[1] - a[1]), d = [(b[0] - a[0]) / L, (b[1] - a[1]) / L], n = [-d[1], d[0]];
    const off = (p, k) => [p[0] + n[0] * k, p[1] + n[1] * k];
    slab(shape([a, b, off(b, w), off(a, w)]), t, 0, M.hull);
    for (const z of [1, -1]) slab(shape([off(a, .55), off(b, .55), off(b, 1.45), off(a, 1.45)]), .3, z * (t / 2 + .15), M.metal);
    // Greebles and running lights, scattered over both faces of the plate.
    const keepOut = QUAD.hole.map(([x, y]) => [c[0] + (x - c[0]) * 1.25, c[1] + (y - c[1]) * 1.25]);
    const pick = () => { for (;;) { const x = 5 + R() * 17, y = 1.5 + R() * 18; if (inPoly(x, y, QUAD.outer) && !inPoly(x, y, keepOut)) return [x, y]; } };
    for (let i = 0; i < 26; i++) {
      const [x, y] = pick(), z = R() < .5 ? 1 : -1, w2 = .5 + R() * 1.6, h2 = .4 + R() * 1.4, d2 = .2 + R() * .5;
      add(new THREE.BoxGeometry(w2, h2, d2), R() < .6 ? M.dark : M.metal, g).position.set(x * sx, y * sy, z * (QUAD.t / 2 + d2 / 2));
    }
    const dots = new THREE.InstancedMesh(new THREE.BoxGeometry(.17, .17, .06), M.dots, 70);
    const mtx = new THREE.Matrix4();
    for (let i = 0; i < 70; i++) {
      const [x, y] = pick(), z = i % 2 ? 1 : -1;
      mtx.makeTranslation(x * sx, y * sy, z * (QUAD.t / 2 + .03)); dots.setMatrixAt(i, mtx);
    }
    g.add(dots);
    quads.push({ g, sx, sy });
  }

  // Bent girders sweeping past the spindle, one on each face.
  for (const side of [1, -1]) {
    const gp = GIRDER.pts.map(([x, y]) => [x * side, y]), z = GIRDER.z * side;
    for (let i = 0; i < gp.length - 1; i++) {
      const [x0, y0] = gp[i], [x1, y1] = gp[i + 1], len = Math.hypot(x1 - x0, y1 - y0);
      const m = add(new THREE.BoxGeometry(len + .6, 1.5, 1), M.metal);
      m.position.set((x0 + x1) / 2, (y0 + y1) / 2, z); m.rotation.z = Math.atan2(y1 - y0, x1 - x0);
    }
    for (const [x, y] of gp) { const k = new THREE.CylinderGeometry(.95, .95, 1.4, 8); k.rotateX(Math.PI / 2); add(k, M.dark).position.set(x, y, z); }
  }

  // Emitter, charge sparks, beam and shock ring at the left tip.
  const tipX = SPAR.tip;
  const tip = add(new THREE.SphereGeometry(1, 24, 16), M.tip, root, false); tip.position.x = tipX;
  const beam = new THREE.Group(); beam.position.x = tipX; root.add(beam);
  const beamCore = new THREE.CylinderGeometry(1, 1, 1, 24, 1, true); beamCore.rotateZ(Math.PI / 2); beamCore.translate(-.5, 0, 0);
  const core1 = add(beamCore, M.beam, beam, false), core2 = add(beamCore.clone(), M.glow, beam, false);
  const ring = add(new THREE.RingGeometry(.8, 1, 64), M.shock, root, false); ring.rotation.y = Math.PI / 2; ring.position.x = tipX;
  const light = new THREE.PointLight(new THREE.Color(...GREEN), 0, 90, 1); light.position.x = tipX + 2; root.add(light);
  const SPARKS = 220, sparkDir = [], sparkGeo = new THREE.BufferGeometry();
  for (let i = 0; i < SPARKS; i++) {
    const u = R() * 2 - 1, ph = R() * Math.PI * 2, s = Math.sqrt(1 - u * u);
    sparkDir.push({ d: [u * .6 - .6, s * Math.cos(ph), s * Math.sin(ph)], r: 6 + R() * 12, o: R(), v: .8 + R() * .6 });
  }
  sparkGeo.setAttribute("position", new THREE.BufferAttribute(new Float32Array(SPARKS * 3), 3));
  const sparks = new THREE.Points(sparkGeo, M.spark); sparks.position.x = tipX; sparks.frustumCulled = false; root.add(sparks);

  const setGreen = (m, k) => m.color.setRGB(GREEN[0] * k, GREEN[1] * k, GREEN[2] * k);
  function update(s) {
    root.position.x = s.recoil;
    spinTop.rotation.y = s.spin; spinBot.rotation.y = -s.spin * .8;
    core.rotation.set(s.t * .05, s.coreRot, 0);
    frame.rotation.z = s.frameRot;
    for (const q of quads) q.g.position.set(q.sx * s.unfold, q.sy * s.unfold, q.sx * q.sy * s.unfold * .35);
    setGreen(M.green, s.green);
    setGreen(M.dots, s.dots);
    setGreen(M.hex, s.green * .8 + s.charge * 5 + s.beam * 3);
    M.hull.emissiveIntensity = .5 * s.dots; M.metal.emissiveIntensity = .3 * s.dots;
    M.lattice.color.setRGB(.6 * s.lattice, .75 * s.lattice, 1 * s.lattice);
    tip.scale.setScalar(.35 + .75 * s.charge + .9 * s.beam);
    M.tip.opacity = clamp01(.15 + .6 * s.charge + s.beam); setGreen(M.tip, 1 + 1.6 * s.charge + 2 * s.beam);
    beam.visible = s.beam > .001;
    const w = s.beamW;
    core1.scale.set(260, .55 * w, .55 * w); core2.scale.set(260, 1.9 * w, 1.9 * w);
    M.beam.opacity = clamp01(s.beam * 1.2); M.glow.opacity = .35 * s.beam;
    ring.visible = s.shock >= 0 && s.shock < 2.6;
    if (ring.visible) { ring.scale.setScalar(2 + 34 * Math.pow(s.shock, .6)); M.shock.opacity = .9 * (1 - phase(0, 2.6, s.shock)); }
    light.intensity = 18 * s.charge + 60 * s.beam;
    sparks.visible = s.charge > .01;
    if (sparks.visible) {
      const pos = sparkGeo.attributes.position;
      for (let i = 0; i < SPARKS; i++) {
        const p = sparkDir[i], f = (s.t * p.v * (.6 + 1.2 * s.charge) + p.o) % 1, r = p.r * (1 - f) * (1 - f);
        pos.setXYZ(i, p.d[0] * r, p.d[1] * r, p.d[2] * r);
      }
      pos.needsUpdate = true;
      M.spark.opacity = .7 * s.charge; M.spark.size = 1.5 + 1.5 * s.charge;
    }
  }
  return { root, update };
}

// ---------- the stage: deep space, cool key light, green rim ----------
const NEB_VS = "varying vec3 vD; void main(){ vD = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }";
const NEB_FS = `uniform float uK; varying vec3 vD;
float h(vec3 p){ return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453); }
float n(vec3 p){ vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
  return mix(mix(mix(h(i), h(i + vec3(1,0,0)), f.x), mix(h(i + vec3(0,1,0)), h(i + vec3(1,1,0)), f.x), f.y),
             mix(mix(h(i + vec3(0,0,1)), h(i + vec3(1,0,1)), f.x), mix(h(i + vec3(0,1,1)), h(i + vec3(1,1,1)), f.x), f.y), f.z); }
float fbm(vec3 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 5; i++){ s += a * n(p); p *= 2.03; a *= 0.5; } return s; }
void main(){
  vec3 d = normalize(vD);
  float m = fbm(d * 2.2 + 3.0), m2 = fbm(d * 5.0 + vec3(7.0));
  float neb = pow(clamp(m * 1.3 - 0.38, 0.0, 1.0), 2.0);
  float wisp = pow(clamp(m2 - 0.45, 0.0, 1.0), 2.0);
  vec3 col = vec3(0.006, 0.01, 0.012) + neb * vec3(0.012, 0.04, 0.022) * uK + wisp * vec3(0.02, 0.025, 0.05);
  gl_FragColor = vec4(col, 1.0);
}`;

function createStage(canvas, P) {
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: "high-performance", preserveDrawingBuffer: RENDER });
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.outputColorSpace = THREE.SRGBColorSpace;

  const scene = new THREE.Scene();
  scene.background = new THREE.Color("#020403");
  const camera = new THREE.PerspectiveCamera(32, 16 / 9, .5, 4000);

  // Dark environment with a few soft boxes, so the metal has something to reflect.
  {
    const env = new THREE.Scene();
    env.background = new THREE.Color("#07090a");
    const panel = (w, h, at, col, k) => {
      const p = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({ color: new THREE.Color(col).multiplyScalar(k), side: THREE.DoubleSide }));
      p.position.copy(at); p.lookAt(0, 0, 0); env.add(p);
    };
    panel(12, 12, new THREE.Vector3(4, 14, 8), "#dfe8ff", 2.2);
    panel(3, 14, new THREE.Vector3(-12, 2, -6), "#7dff3a", 1.4);
    panel(3, 14, new THREE.Vector3(12, 4, -4), "#9fb8ff", 1.2);
    panel(18, 2, new THREE.Vector3(0, -6, 12), "#ffffff", .6);
    const pmrem = new THREE.PMREMGenerator(renderer);
    scene.environment = pmrem.fromScene(env, .02).texture;
    pmrem.dispose();
  }
  const key = new THREE.DirectionalLight("#e4ecff", 2.4); key.position.set(30, 40, 50);
  const rim = new THREE.DirectionalLight("#7dff6a", 1.8); rim.position.set(-40, 12, -30);
  const rim2 = new THREE.DirectionalLight("#6f9cff", .9); rim2.position.set(40, -20, -40);
  const hemi = new THREE.HemisphereLight("#41505a", "#050806", .5);
  scene.add(key, rim, rim2, hemi);

  const neb = new THREE.Mesh(new THREE.SphereGeometry(1500, 48, 24), new THREE.ShaderMaterial({
    vertexShader: NEB_VS, fragmentShader: NEB_FS, side: THREE.BackSide, depthWrite: false, uniforms: { uK: { value: 1 } },
  }));
  scene.add(neb);
  {
    const R = rng(5), N = 2600, pos = new Float32Array(N * 3), col = new Float32Array(N * 3);
    for (let i = 0; i < N; i++) {
      const u = R() * 2 - 1, ph = R() * Math.PI * 2, s = Math.sqrt(1 - u * u), r = 1100;
      pos.set([s * Math.cos(ph) * r, u * r, s * Math.sin(ph) * r], i * 3);
      const b = .25 + Math.pow(R(), 3) * 1.4, tint = R();
      col.set([b * (tint < .2 ? .8 : 1), b, b * (tint > .8 ? .8 : 1)], i * 3);
    }
    const g = new THREE.BufferGeometry();
    g.setAttribute("position", new THREE.BufferAttribute(pos, 3)); g.setAttribute("color", new THREE.BufferAttribute(col, 3));
    scene.add(new THREE.Points(g, new THREE.PointsMaterial({ size: 1.6, sizeAttenuation: false, vertexColors: true, depthWrite: false })));
  }

  const ship = buildShip();
  scene.add(ship.root);

  const rt = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4 });
  const composer = new P.EffectComposer(renderer, rt);
  composer.addPass(new P.RenderPass(scene, camera));
  const bloom = new P.UnrealBloomPass(new THREE.Vector2(256, 256), .7, .55, .8);
  composer.addPass(bloom);
  composer.addPass(new P.OutputPass());

  function resize(w, h, pr, fov) {
    renderer.setPixelRatio(pr); renderer.setSize(w, h, false);
    composer.setPixelRatio(pr); composer.setSize(w, h);
    camera.aspect = w / h; camera.fov = fov;
    // Lift the picture so the vessel centres in the space above the player dock.
    camera.setViewOffset(w, h, 0, h * .065, w, h);
    camera.updateProjectionMatrix();
  }
  function frame(s, distK = 1) {
    ship.update(s);
    const c = s.cam, d = c.d * distK, el = c.el * D2R, az = c.az * D2R;
    camera.position.set(
      c.tx + d * Math.cos(el) * Math.sin(az) + s.shake[0] * d / 100,
      c.ty + d * Math.sin(el) + s.shake[1] * d / 100,
      c.tz + d * Math.cos(el) * Math.cos(az));
    camera.lookAt(c.tx, c.ty, c.tz);
    renderer.toneMappingExposure = s.exposure;
    key.intensity = 2.4 * s.power; rim.intensity = 1.8 * s.power * (1 + .5 * s.f.low); rim2.intensity = .9 * s.power;
    scene.environmentIntensity = .4 + .6 * s.power;
    neb.material.uniforms.uK.value = .7 + .8 * s.f.mid + 2 * s.flash;
    bloom.strength = s.bloom;
    composer.render();
  }
  return { renderer, scene, camera, resize, frame };
}

// ---------- camera: one framing per section, eased between them ----------
const VIEWS = [
  t => ({ tx: 0, ty: 0, tz: 0, az: -8 + .8 * t, el: 4, d: 112 - 1.6 * t }),                         // Awaken
  t => ({ tx: 0, ty: 0, tz: 0, az: 20 + 2 * t, el: 10, d: 96 }),                                    // Signal
  t => ({ tx: 0, ty: 0, tz: 0, az: 40 + 7 * t, el: 14 - .6 * t, d: 92 + 6 * Math.sin(t * .4) }),   // Drop
  t => ({ tx: 0, ty: 0, tz: 0, az: -36 + 2.5 * t, el: 6, d: 66 - 1 * t }),                         // Lattice
  t => ({ tx: 0, ty: 0, tz: 0, az: 150 + 2 * t, el: -14, d: 72 + 3 * t }),                         // Build
  t => ({ tx: 0, ty: 0, tz: 0, az: 170 + 6 * t, el: -10 + 1.1 * t, d: 104 }),                      // Unfold
  t => ({ tx: -12, ty: 0, tz: 0, az: -30 - 2 * t, el: 8, d: 72 - 2 * t }),                         // Charge
  t => ({ tx: -26, ty: 0, tz: 0, az: -22 + .8 * t, el: 7, d: 150 + 3 * t }),                       // Discharge
  t => ({ tx: -26 * (1 - phase(0, 6, t)), ty: 0, tz: 0, az: -10 + 2 * t, el: 9, d: 150 - 2 * t }), // Drift
];
function blendCam(a, b, k) {
  const out = {};
  const dAz = ((b.az - a.az) % 360 + 540) % 360 - 180;
  for (const key in b) out[key] = key === "az" ? a.az + dAz * k : a[key] + (b[key] - a[key]) * k;
  const swing = Math.min(1, Math.abs(dAz) / 90);
  out.d += Math.max(0, Math.max(a.d, b.d) * (1 + .15 * swing) - out.d) * Math.sin(Math.PI * k) * swing;
  return out;
}
function camAt(t) {
  const i = sectionAt(t), t0 = SECTIONS[i].t;
  let cam = VIEWS[i](t - t0);
  const blend = i === 7 ? .9 : 1.6;
  if (i > 0) {
    const k = phase(t0, t0 + blend, t);
    if (k < 1) cam = blendCam(VIEWS[i - 1](t - SECTIONS[i - 1].t), cam, k);
  }
  return cam;
}

// ---------- state(t): every pose and light is a pure function of time and the measured score ----------
const GROOVE = [[0, 0], [bt(8) - .5, 0], [bt(8) + .5, .35], [bt(16) - .3, .35], [bt(16), 1], [bt(32), 1], [bt(32) + .6, .2], [bt(40), .2],
  [bt(40) + .5, .4], [bt(48) - .2, .4], [bt(48), 1], [bt(64), 1], [bt(64) + .5, .5], [HIT, .5], [HIT + .3, 1], [bt(80), 1], [bt(80) + 1, 0]];
const hash = n => { const x = Math.sin(n * 12.9898) * 43758.5453; return (x - Math.floor(x)) * 2 - 1; };

function state(t, A) {
  const f = { low: at(A.low, t), mid: at(A.mid, t), high: at(A.high, t), kick: at(A.kick, t), cumMid: at(A.cumMid, t), cumHigh: at(A.cumHigh, t) };
  const wake = phase(.5, 9, t);
  const power = .5 + .5 * wake;
  const charge = phase(bt(64), HIT, t) * (1 - phase(HIT, HIT + .3, t));
  const beam = phase(HIT - .02, HIT + .06, t) * (1 - phase(bt(79), bt(80), t));
  const flash = t >= HIT ? Math.max(0, 1 - (t - HIT) / .7) : 0;
  const groove = keys(GROOVE, t);
  // Glitch edits jump the picture in held steps, 24 per second, like dropped frames.
  const glitch = glitchAt(t), jit = hash(Math.floor(t * 24)), jit2 = hash(Math.floor(t * 24) + 77);
  // Through the unfold the frame clicks 22.5° every two bars, 180° in all, landing back on its own shape.
  let frameRot = 0;
  if (t >= bt(48)) { const u = Math.min((t - bt(48)) / (2 * BAR), 8), k = Math.floor(u); frameRot = (k + (u >= 8 ? 0 : phase(0, .35, (u - k) * 2 * BAR))) * 22.5 * D2R; }
  const unfold = UNFOLD * (phase(bt(48), bt(48) + 1.2, t) - phase(bt(64) - 1.2, bt(64), t)) + .55 * f.low * groove + .9 * charge;
  const shakeM = .35 * f.kick * groove + .25 * charge * (.5 + f.high) + 1.4 * flash;
  const cam = camAt(t);
  cam.az += 2.4 * glitch * jit; cam.el += 1.2 * glitch * jit2;
  const flicker = 1 + glitch * (jit > 0 ? 1.4 : -.55);
  return {
    t, f, power, charge, beam, flash, unfold, frameRot, glitch, jit, cam,
    spin: f.cumMid * .35,
    coreRot: t * .08 + f.cumHigh * .25,
    green: ((.35 + .65 * wake) * (1.3 + 2.2 * f.kick * groove + .6 * f.low + .5 * f.mid * (1 - groove)) + 4 * flash) * flicker,
    dots: ((.6 + .4 * wake) * (.8 + 1.6 * f.high) + 2 * flash) * flicker,
    lattice: power * (.45 + 1.8 * f.high + .7 * f.mid) + 3 * flash,
    beamW: beam * (1 + .3 * f.low + .45 * f.kick),
    recoil: 1.6 * phase(HIT, HIT + .12, t) * (1 - phase(HIT + .3, HIT + 2.5, t)),
    shock: t >= HIT ? t - HIT : -1,
    shake: [Math.sin(t * 61.3) * shakeM, Math.sin(t * 47.9 + 1.3) * shakeM],
    exposure: (.85 + .25 * power) * (1 + .25 * flash),
    bloom: .5 + .3 * f.low + .2 * charge + .8 * flash + .25 * glitch,
    section: sectionAt(t),
    fade: phase(DURATION - 1.6, DURATION, t),
  };
}

// ---------- overlay ----------
const fmtTime = t => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, "0")}`;

function createHud(A) {
  const el = id => document.getElementById(id);
  const hud = el("hud"), sec = el("sec"), num = el("secNum"), tNow = el("tNow"), fill = el("fill"), spec = el("spec"), g = spec.getContext("2d");
  const rings = [el("rLow"), el("rMid"), el("rHigh")];
  el("tDur").textContent = fmtTime(DURATION);
  const ticks = SECTIONS.map(s => {
    const d = document.createElement("div");
    d.className = "tick"; d.style.left = `${s.t / DURATION * 100}%`;
    d.innerHTML = `<span>${s.name}</span>`;
    el("ticks").appendChild(d);
    return d;
  });
  hud.hidden = false;

  // The equaliser: 72 mirrored capsules, each interpolated across the 40 measured bands with its neighbours.
  const BARS = 72;
  let grad = null;
  const fit = () => {
    const r = spec.getBoundingClientRect(), d = devicePixelRatio || 1;
    spec.width = Math.max(1, Math.round(r.width * d)); spec.height = Math.max(1, Math.round(r.height * d));
    grad = g.createLinearGradient(0, 0, spec.width, 0);
    grad.addColorStop(0, "#b4ff52"); grad.addColorStop(.55, "#7dfc8e"); grad.addColorStop(1, "#4ff0c8");
  };
  fit();
  addEventListener("resize", fit);
  const band = (f, x) => { const i = Math.floor(x), j = Math.min(BANDS - 1, i + 1); return lerp(A.spec[f * BANDS + i], A.spec[f * BANDS + j], x - i); };

  let shown = -1;
  return s => {
    const i = s.section;
    if (i !== shown) {
      sec.textContent = SECTIONS[i].name; num.textContent = String(i + 1).padStart(2, "0");
      ticks.forEach((d, k) => d.classList.toggle("on", k === i));
      shown = i;
    }
    const p = i === 0 ? 1 : phase(SECTIONS[i].t, SECTIONS[i].t + .7, s.t);
    sec.style.opacity = p;
    sec.style.transform = `translate3d(${(s.glitch * s.jit * 7).toFixed(1)}px, ${((1 - p) * 14).toFixed(1)}px, 0)`;
    sec.style.textShadow = s.glitch > .02 ? `${(-5 * s.glitch).toFixed(1)}px 0 rgba(255,70,130,.6), ${(5 * s.glitch).toFixed(1)}px 0 rgba(79,240,200,.6)` : "none";
    tNow.textContent = fmtTime(s.t);
    fill.style.transform = `scaleX(${(s.t / DURATION).toFixed(4)})`;

    const f = clamp(Math.round(s.t * FPS), 0, A.F - 1), W = spec.width, H = spec.height, pitch = W / BARS, bw = Math.max(1, pitch * .55);
    g.clearRect(0, 0, W, H);
    g.fillStyle = grad;
    for (let k = 0; k < BARS; k++) {
      const x = k / (BARS - 1) * (BANDS - 1);
      const v = .25 * band(f, Math.max(0, x - .6)) + .5 * band(f, x) + .25 * band(f, Math.min(BANDS - 1, x + .6));
      const h = Math.max(bw, Math.pow(v, 1.35) * H * .96);
      g.globalAlpha = .28 + .72 * v;
      const x0 = k * pitch + (pitch - bw) / 2, y0 = (H - h) / 2;
      if (g.roundRect) { g.beginPath(); g.roundRect(x0, y0, bw, h, bw / 2); g.fill(); } else g.fillRect(x0, y0, bw, h);
    }
    g.globalAlpha = 1;
    [s.f.low, s.f.mid, s.f.high].forEach((v, k) => { rings[k].style.strokeDasharray = `${(clamp01(v) * 100).toFixed(1)} 100`; });
    hud.style.opacity = 1 - s.fade;
  };
}

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

async function main(P) {
  const load = document.getElementById("load"), msg = document.getElementById("msg"), bar = document.getElementById("loadBar");
  msg.textContent = "Composing the score"; load.hidden = false;
  const audio = await renderScore(k => { msg.textContent = `Composing the score · ${Math.round(k * 100)}%`; bar.style.width = `${k * 88}%`; });
  msg.textContent = "Listening to it"; bar.style.width = "94%";
  await new Promise(r => setTimeout(r, 30));
  const A = analyse(audio);
  load.hidden = true;

  const app = document.getElementById("app");
  const canvas = document.createElement("canvas");
  canvas.id = "gl";
  canvas.setAttribute("role", "img");
  canvas.setAttribute("aria-label", "Animated 3D diamond-shaped vessel pulsing, unfolding and firing in time with a drum and bass soundtrack");
  app.appendChild(canvas);
  const stage = createStage(canvas, P);
  const hud = createHud(A);
  const fadeEl = document.getElementById("fade");

  let distK = 1;
  const layout = () => {
    const W = Math.max(1, innerWidth), H = Math.max(1, innerHeight);
    const pr = RENDER ? devicePixelRatio : Math.max(.5, Math.min(devicePixelRatio || 1, 1.5, Math.sqrt(4e6 / (W * H))));
    // Narrower than 16:9: widen the lens a little, then pull back, so the whole vessel stays in frame.
    const k = Math.max(1, Math.pow(DESIGN_ASPECT / (W / H), .75)), kf = Math.min(k, 1.6);
    stage.resize(W, H, pr, 2 * Math.atan(Math.tan(16 * D2R) * kf) / D2R);
    distK = k / kf * 1.08;
  };
  layout();
  addEventListener("resize", layout);

  const render = t => {
    const s = state(clamp(t, 0, DURATION - 1e-4), A);
    stage.frame(s, distK);
    hud(s);
    fadeEl.style.opacity = s.fade;
  };
  render(0);
  await Promise.race([stage.renderer.compileAsync(stage.scene, stage.camera).catch(() => {}), new Promise(r => setTimeout(r, 1500))]);

  window.DURATION = DURATION; window.FPS = FPS;
  window.exportWav = () => wavBase64(audio);
  if (RENDER) { window.seek = render; return; }

  // Live: loop the film; with sound on, the audio clock drives the picture.
  const btn = document.getElementById("sound"), lbl = btn.querySelector(".lbl");
  const show = on => { btn.classList.toggle("playing", on); lbl.textContent = on ? "Mute" : "Play with sound"; btn.setAttribute("aria-label", lbl.textContent); };
  btn.hidden = false;
  let actx = null, src = null, startAt = 0, clock = 0, last = performance.now();
  const now = () => src ? (actx.currentTime - startAt) % DURATION : clock % DURATION;
  btn.addEventListener("click", async () => {
    if (src) { clock = now(); src.stop(); src = null; show(false); return; }
    actx ??= new AudioContext();
    await actx.resume();
    const t0 = clock % DURATION;
    src = actx.createBufferSource(); src.buffer = audio; src.loop = true; src.connect(actx.destination);
    startAt = actx.currentTime + .05 - t0; src.start(actx.currentTime + .05, t0);
    show(true);
  });
  const tick = ms => {
    clock += Math.min(.1, Math.max(0, (ms - last) / 1e3)); last = ms;
    render(now());
    requestAnimationFrame(tick);
  };
  requestAnimationFrame(ms => { last = ms; tick(ms); });
}

function fail(msg) {
  const el = document.getElementById("msg"), load = document.getElementById("load");
  if (el) { el.textContent = msg; load.hidden = false; document.getElementById("loadBar").parentElement.hidden = true; }
}

async function boot() {
  let P;
  try {
    THREE = await import("three");
    const [ec, rp, ub, op] = await Promise.all([
      import("three/addons/postprocessing/EffectComposer.js"), import("three/addons/postprocessing/RenderPass.js"),
      import("three/addons/postprocessing/UnrealBloomPass.js"), import("three/addons/postprocessing/OutputPass.js"),
    ]);
    P = { ...ec, ...rp, ...ub, ...op };
  } catch { fail("The 3D library didn't load. Check your connection and reload the page."); return; }
  try { await main(P); }
  catch (e) { console.error(e); fail("This animation needs WebGL and Web Audio, which aren't available in this browser."); }
}
boot();
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.