Back to Gem Warden
SOURCE / PINNED RELEASE

Made of little things.

Gem Warden

Release
d7ee3a74bdb5…
Author-recorded commit
1bfb3fd0904c…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-3929629ef1d

Archive hash verified: 73f8647f6ce3701b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/audio.ts
// Synthesised sound and generative music. Nothing is sampled: every voice is
// built from oscillators and filtered noise, so the napplet stays one file and
// needs no network. Effects are pitched from the chord the music is on, so a
// busy fight plays along with the tune instead of over it.

let ac: BaseAudioContext | null = null;
let master: GainNode;
let sfxBus: GainNode;
let musBus: GainNode;
let musFilter: BiquadFilterNode;
/** What one tune plays through. A new tune gets a new one and the old one
 *  fades, so a long chord of the last tune never rings on in another key. */
interface TuneBus {
  out: GainNode;
  /** Softens the saw-based voices. */
  soft: BiquadFilterNode;
  /** A filtered echo for the arpeggio and the lead. */
  echo: GainNode;
}
let tuneBus: TuneBus;
let noiseBuf: AudioBuffer;
let voices = 0;
let maxVoices = 84;
let sfxOn = true;
let musicOn = true;
/** Added to the context clock; lets a test lay sounds out along an offline render. */
let clockOffset = 0;

/** There is a context and the host has not closed it. */
function live(): boolean {
  return !!ac && ac.state !== 'closed';
}

function now(): number {
  return (ac as BaseAudioContext).currentTime + clockOffset;
}

/** For rendering offline: nothing ends before the render starts, so the
 *  voice limit, which counts ended voices, has to go as well. */
export function layOutAt(seconds: number): void {
  clockOffset = seconds;
  maxVoices = Infinity;
}

/** Builds the audio graph on a context, playing into `out`. The caller owns
 *  the context and its start from a user gesture. */
export function init(ctx: BaseAudioContext, out: AudioNode = ctx.destination): boolean {
  if (ac) return ac === ctx;
  ac = ctx;
  const comp = ac.createDynamicsCompressor();
  // A slow leveller. A fast one follows the beating between the notes of a
  // chord and adds a low rumble of its own.
  comp.threshold.value = -12;
  comp.knee.value = 10;
  comp.ratio.value = 4;
  comp.attack.value = 0.015;
  comp.release.value = 0.25;
  // The leveller is too slow for a sudden pile-up of loud effects, so a fast
  // limiter with a high threshold sits behind it. It only acts near full scale.
  const limiter = ac.createDynamicsCompressor();
  limiter.threshold.value = -4;
  limiter.knee.value = 0;
  limiter.ratio.value = 20;
  limiter.attack.value = 0.001;
  limiter.release.value = 0.08;
  const trim = ac.createGain();
  trim.gain.value = 0.85;
  master = ac.createGain();
  master.gain.value = 1.6;
  master.connect(comp).connect(limiter).connect(trim).connect(out);

  sfxBus = ac.createGain();
  sfxBus.gain.value = sfxOn ? 1 : 0;
  sfxBus.connect(master);
  musFilter = ac.createBiquadFilter();
  musFilter.type = 'lowpass';
  musFilter.frequency.value = 16000;
  musFilter.connect(master);
  musBus = ac.createGain();
  musBus.gain.value = 0;
  musBus.connect(musFilter);
  // A generated hall: decaying noise as the impulse response.
  const len = Math.floor(ac.sampleRate * 2.3);
  const ir = ac.createBuffer(2, len, ac.sampleRate);
  for (let ch = 0; ch < 2; ch++) {
    const d = ir.getChannelData(ch);
    for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, 3.2);
  }
  const hall = ac.createConvolver();
  hall.buffer = ir;
  const hallOut = ac.createGain();
  hallOut.gain.value = 0.5;
  hall.connect(hallOut).connect(master);
  const sfxSend = ac.createGain();
  sfxSend.gain.value = 0.2;
  sfxBus.connect(sfxSend).connect(hall);
  const musSend = ac.createGain();
  musSend.gain.value = 0.34;
  musFilter.connect(musSend).connect(hall);

  tuneBus = makeTuneBus();

  noiseBuf = ac.createBuffer(1, ac.sampleRate, ac.sampleRate);
  const nd = noiseBuf.getChannelData(0);
  for (let i = 0; i < nd.length; i++) nd[i] = Math.random() * 2 - 1;
  return true;
}

function makeTuneBus(): TuneBus {
  const a = ac as BaseAudioContext;
  const out = a.createGain();
  out.connect(musBus);
  const soft = a.createBiquadFilter();
  soft.type = 'lowpass';
  soft.frequency.value = 2400;
  soft.Q.value = 0.6;
  soft.connect(out);
  const echo = a.createGain();
  echo.gain.value = 0.5;
  const delay = a.createDelay(1);
  delay.delayTime.value = 0.32;
  const fb = a.createGain();
  fb.gain.value = 0.36;
  const damp = a.createBiquadFilter();
  damp.type = 'lowpass';
  damp.frequency.value = 2200;
  echo.connect(delay);
  delay.connect(damp).connect(fb).connect(delay);
  delay.connect(out);
  return { out, soft, echo };
}

/** Runs fn after some seconds of the context's own clock, which also holds in an offline render. */
function afterSeconds(seconds: number, fn: () => void): void {
  const a = ac as BaseAudioContext;
  const o = a.createOscillator();
  const g = a.createGain();
  g.gain.value = 0;
  o.connect(g).connect(master);
  o.onended = fn;
  o.start(now());
  o.stop(now() + seconds);
}

export function setEnabled(effects: boolean, music: boolean): void {
  sfxOn = effects;
  musicOn = music;
  if (!live()) return;
  sfxBus.gain.setTargetAtTime(effects ? 1 : 0, now(), 0.03);
  if (!music) {
    musBus.gain.setTargetAtTime(0, now(), 0.08);
    lastGain = 0;
  }
}

// ------------------------------------------------------------------ voices

interface VoiceOpts {
  type?: OscillatorType;
  /** Frequency at the end, as a factor of the start. */
  slide?: number;
  attack?: number;
  /** −1 left to 1 right. */
  pan?: number;
  dest?: AudioNode;
  detune?: number;
  /** Start time on the context clock; now when left out. */
  at?: number;
}

function output(o: { pan?: number; dest?: AudioNode }): AudioNode {
  const dest = o.dest ?? sfxBus;
  const a = ac as BaseAudioContext;
  if (o.pan === undefined || typeof a.createStereoPanner !== 'function') return dest;
  const p = a.createStereoPanner();
  p.pan.value = Math.max(-1, Math.min(1, o.pan));
  p.connect(dest);
  return p;
}

/** Voices sounding or scheduled right now. */
export function voiceCount(): number {
  return voices;
}

function track(n: AudioScheduledSourceNode): void {
  voices++;
  n.onended = () => {
    voices--;
  };
}

function envelope(g: GainNode, t: number, attack: number, vol: number, dur: number): void {
  // A gain node starts at 1. A voice scheduled between two audio blocks would
  // sound at full volume until its envelope takes hold, so start from silence.
  g.gain.value = 0;
  g.gain.setValueAtTime(0.0001, t);
  g.gain.exponentialRampToValueAtTime(Math.max(0.0002, vol), t + attack);
  g.gain.exponentialRampToValueAtTime(0.0001, t + Math.max(attack + 0.01, dur));
}

function tone(freq: number, dur: number, vol: number, o: VoiceOpts = {}): void {
  if (!ac || !live() || voices > maxVoices) return;
  const t = o.at ?? now();
  const osc = ac.createOscillator();
  const g = ac.createGain();
  osc.type = o.type ?? 'sine';
  osc.frequency.setValueAtTime(freq, t);
  if (o.slide) osc.frequency.exponentialRampToValueAtTime(Math.max(20, freq * o.slide), t + dur);
  if (o.detune) osc.detune.value = o.detune;
  envelope(g, t, o.attack ?? 0.004, vol, dur);
  osc.connect(g).connect(output(o));
  osc.start(t);
  osc.stop(t + dur + 0.03);
  track(osc);
}

interface NoiseOpts {
  type?: BiquadFilterType;
  f0: number;
  f1?: number;
  q?: number;
  attack?: number;
  pan?: number;
  dest?: AudioNode;
  at?: number;
}

function noise(dur: number, vol: number, o: NoiseOpts): void {
  if (!ac || !live() || voices > maxVoices) return;
  const t = o.at ?? now();
  const src = ac.createBufferSource();
  src.buffer = noiseBuf;
  src.loop = true;
  const f = ac.createBiquadFilter();
  f.type = o.type ?? 'lowpass';
  f.frequency.setValueAtTime(o.f0, t);
  if (o.f1) f.frequency.exponentialRampToValueAtTime(o.f1, t + dur);
  f.Q.value = o.q ?? 0.8;
  const g = ac.createGain();
  envelope(g, t, o.attack ?? 0.003, vol, dur);
  src.connect(f).connect(g).connect(output(o));
  src.start(t, Math.random() * 0.9);
  src.stop(t + dur + 0.03);
  track(src);
}

/** A two-operator FM voice: glassy at high ratios, gong-like at odd ones. */
function bell(freq: number, dur: number, vol: number, o: VoiceOpts & { ratio?: number; index?: number } = {}): void {
  if (!ac || !live() || voices > maxVoices) return;
  const t = o.at ?? now();
  const car = ac.createOscillator();
  const mod = ac.createOscillator();
  const mg = ac.createGain();
  const g = ac.createGain();
  car.frequency.setValueAtTime(freq, t);
  if (o.slide) car.frequency.exponentialRampToValueAtTime(Math.max(20, freq * o.slide), t + dur);
  mod.frequency.setValueAtTime(freq * (o.ratio ?? 3.01), t);
  const depth = freq * (o.index ?? 1.6);
  mg.gain.setValueAtTime(depth, t);
  mg.gain.exponentialRampToValueAtTime(Math.max(0.01, depth * 0.04), t + dur * 0.75);
  mod.connect(mg).connect(car.frequency);
  envelope(g, t, o.attack ?? 0.003, vol, dur);
  car.connect(g).connect(output(o));
  car.start(t);
  mod.start(t);
  car.stop(t + dur + 0.03);
  mod.stop(t + dur + 0.03);
  track(car);
}

const lastPlayed = new Map<string, number>();
/** True at most once per `gap` seconds for each id, so a crowd cannot stack one sound. */
function can(id: string, gap: number): boolean {
  // Near the voice limit the effects give way, so the music keeps its notes.
  if (!live() || !sfxOn || voices > maxVoices - 24) return false;
  const t = now();
  if (t - (lastPlayed.get(id) ?? -9) < gap) return false;
  lastPlayed.set(id, t);
  return true;
}

function hz(midi: number): number {
  return 440 * Math.pow(2, (midi - 69) / 12);
}

// ------------------------------------------------------------------ harmony

/** Midi note of the key's root, around A2. */
let key = 45;
let chord = { root: 0, minor: true };

/** The i-th tone going up the chord the music is on, from the key's root. */
function chordNote(i: number): number {
  const third = chord.minor ? 3 : 4;
  const tones = [0, third, 7];
  const n = ((i % 3) + 3) % 3;
  return key + chord.root + tones[n] + 12 * Math.floor(i / 3);
}

// ------------------------------------------------------------------ effects

const GEM_VOICE: Record<string, number> = { red: 0, orange: 1, yellow: 2, green: 3, blue: 4, purple: 5 };

export const sfx = {
  /** A tower firing. Each gem colour has its own timbre and place in the chord. */
  shot(gem: string, grade: number, pan: number): void {
    if (!can('shot', 0.05)) return;
    const v = GEM_VOICE[gem] ?? 0;
    const f = hz(chordNote(v % 4) + 24 + (grade >= 5 ? 12 : 0));
    const vol = 0.06;
    switch (v) {
      case 0: // ruby: a short hot rasp
        tone(f / 2, 0.08, vol, { type: 'sawtooth', slide: 0.6, pan });
        break;
      case 1: // amber: round pluck
        tone(f, 0.1, vol * 1.3, { type: 'triangle', pan });
        break;
      case 2: // topaz: bright ping
        bell(f * 2, 0.09, vol * 0.9, { ratio: 2, index: 1.2, pan });
        break;
      case 3: // jade: a wet blip upwards
        tone(f * 0.75, 0.09, vol * 1.3, { type: 'sine', slide: 1.5, pan });
        break;
      case 4: // sapphire: a falling icy note
        tone(f * 2, 0.12, vol, { type: 'sine', slide: 0.5, pan });
        break;
      default: // amethyst: dark and hollow
        bell(f / 2, 0.11, vol * 1.3, { ratio: 1.41, index: 2.4, pan });
    }
  },
  hit(pan: number): void {
    if (!can('hit', 0.045)) return;
    noise(0.03, 0.04, { type: 'bandpass', f0: 2600, q: 1.5, pan });
  },
  crit(pan: number): void {
    if (!can('crit', 0.07)) return;
    bell(hz(chordNote(2) + 36), 0.22, 0.1, { ratio: 3.5, index: 2.2, pan });
    noise(0.07, 0.07, { type: 'highpass', f0: 5000, pan });
  },
  ward(pan: number): void {
    if (!can('ward', 0.09)) return;
    bell(1900, 0.09, 0.06, { ratio: 5.4, index: 1, pan });
  },
  splash(pan: number): void {
    if (!can('splash', 0.1)) return;
    noise(0.2, 0.1, { f0: 1100, f1: 180, pan });
    tone(120, 0.14, 0.1, { slide: 0.5, pan });
  },
  trap(gem: string, pan: number): void {
    if (!can('trap', 0.09)) return;
    const v = GEM_VOICE[gem] ?? 0;
    tone(hz(chordNote(v % 3) + 12), 0.14, 0.08, { type: 'sawtooth', slide: 0.45, pan });
    noise(0.1, 0.09, { type: 'bandpass', f0: 3200, f1: 900, q: 3, pan });
  },
  /** A kill: a pop plus a note that climbs the chord while kills keep coming. */
  kill(pan: number, combo: number, size: number): void {
    if (!can('kill', 0.05)) return;
    tone(380 - size * 300, 0.09, 0.11, { type: 'triangle', slide: 0.4, pan });
    // Seven steps up is about 2.6 kHz; higher turns shrill in a long streak.
    bell(hz(chordNote(Math.min(combo, 7)) + 24), 0.18, 0.07, { ratio: 2, index: 0.8, pan });
  },
  bigKill(pan: number): void {
    if (!can('bigkill', 0.2)) return;
    tone(120, 0.8, 0.5, { slide: 0.28, pan });
    noise(0.7, 0.3, { f0: 2400, f1: 90, pan });
    for (let i = 0; i < 4; i++) bell(hz(chordNote(i + 3) + 24), 0.5, 0.04, { at: now() + 0.05 + i * 0.07, pan });
  },
  /** Mana reaching the orb. */
  mana(): void {
    if (!can('mana', 0.07)) return;
    tone(hz(chordNote(4) + 36), 0.06, 0.03, { slide: 1.3 });
  },
  build(trap: boolean, pan: number): void {
    if (!can('build', 0.05)) return;
    tone(150, 0.18, 0.3, { slide: 0.33, pan });
    noise(0.14, 0.14, { f0: 1400, f1: 260, pan });
    noise(0.025, 0.06, { type: 'highpass', f0: 3500, pan });
    if (trap) bell(hz(chordNote(1) + 24), 0.4, 0.05, { ratio: 1.5, index: 2, at: now() + 0.06, pan });
  },
  forge(gem: string, grade: number): void {
    if (!can('forge', 0.04)) return;
    const n = chordNote(GEM_VOICE[gem] ?? 0) + 24;
    const t = now();
    bell(hz(n), 0.5, 0.1, { ratio: 3.01, index: 1.4 + grade * 0.15 });
    bell(hz(n + 12), 0.4, 0.04, { at: t + 0.06 });
    bell(hz(n + 19), 0.35, 0.03, { at: t + 0.12 });
    noise(0.05, 0.03, { type: 'highpass', f0: 6000 });
  },
  forgeBatch(): void {
    if (!can('forge', 0.04)) return;
    const t = now();
    for (let i = 0; i < 3; i++) bell(hz(chordNote(i) + 24), 0.45, 0.08, { at: t + i * 0.08 });
    noise(0.3, 0.03, { type: 'bandpass', f0: 2500, f1: 7000, q: 2 });
  },
  combine(grade: number): void {
    if (!can('combine', 0.05)) return;
    const t = now();
    noise(0.22, 0.06, { type: 'bandpass', f0: 400, f1: 3600, q: 2 });
    tone(220, 0.2, 0.05, { type: 'triangle', slide: 3 });
    const voicesUp = Math.min(6, 2 + Math.floor(grade / 2));
    for (let i = 0; i < voicesUp; i++) {
      bell(hz(chordNote(i) + 24), 0.6 + grade * 0.08, 0.07, { at: t + 0.19 + i * 0.035, index: 1.2 + grade * 0.2 });
    }
    if (grade >= 4) tone(70, 0.4, 0.2, { slide: 0.5, at: t + 0.19 });
  },
  place(): void {
    if (!can('place', 0.04)) return;
    bell(hz(chordNote(0) + 24), 0.14, 0.05, { ratio: 2, index: 0.7 });
    noise(0.03, 0.03, { type: 'highpass', f0: 3000 });
  },
  sell(): void {
    if (!can('sell', 0.05)) return;
    const t = now();
    [1568, 1319, 1047].forEach((f, i) => bell(f, 0.2, 0.05, { ratio: 2.76, index: 1.1, at: t + i * 0.055 }));
  },
  pool(): void {
    if (!can('pool', 0.1)) return;
    const t = now();
    tone(110, 0.7, 0.14, { type: 'triangle', slide: 2, attack: 0.25 });
    noise(0.7, 0.07, { type: 'bandpass', f0: 300, f1: 3200, q: 1.5, attack: 0.3 });
    for (let i = 0; i < 5; i++) bell(hz(chordNote(i) + 24), 0.5, 0.05, { at: t + 0.3 + i * 0.06 });
  },
  /** The horn that announces a wave; lower and longer for ice giants. */
  wave(boss: boolean, last: boolean): void {
    if (!can('wave', 0.25)) return;
    const t = now();
    const base = key + (boss ? 0 : 12);
    const dur = boss ? 1.5 : 0.9;
    for (const [semi, at] of boss ? [[0, 0], [1, 0.25]] : last ? [[0, 0], [7, 0.16], [12, 0.32]] : [[0, 0], [7, 0.16]]) {
      for (const d of [-9, 9]) {
        tone(hz(base + semi), dur - at, 0.06, { type: 'sawtooth', attack: 0.08, detune: d, at: t + at, dest: sfxHorn() });
      }
    }
    tone(90, 0.45, 0.35, { slide: 0.6 });
    if (boss) noise(1.5, 0.22, { f0: 160, f1: 60, attack: 0.3 });
  },
  banish(pan: number): void {
    if (!can('banish', 0.08)) return;
    const t = now();
    tone(190, 0.5, 0.45, { slide: 0.2, pan });
    noise(0.3, 0.2, { type: 'bandpass', f0: 2400, f1: 300, q: 1.2, pan });
    tone(660, 0.22, 0.045, { type: 'square', slide: 0.5, at: t + 0.02 });
    tone(660, 0.22, 0.035, { type: 'square', slide: 0.5, at: t + 0.2 });
  },
  heartbeat(): void {
    if (!can('heart', 0.85)) return;
    const t = now();
    tone(64, 0.14, 0.34, { slide: 0.6 });
    tone(58, 0.16, 0.24, { slide: 0.6, at: t + 0.17 });
  },
  overflow(): void {
    if (!can('overflow', 2.2)) return;
    const t = now();
    tone(2093, 0.05, 0.03, {});
    tone(2093, 0.05, 0.03, { at: t + 0.08 });
  },
  error(): void {
    if (!can('error', 0.12)) return;
    const t = now();
    tone(160, 0.09, 0.05, { type: 'square' });
    tone(115, 0.12, 0.05, { type: 'square', at: t + 0.09 });
  },
  click(): void {
    if (!can('click', 0.03)) return;
    tone(880, 0.035, 0.035, { slide: 0.6 });
  },
  bonus(): void {
    if (!can('bonus', 0.3)) return;
    const t = now();
    for (let i = 0; i < 7; i++) bell(hz(chordNote(i) + 24), 0.35, 0.06, { ratio: 2.76, at: t + i * 0.06 });
  },
  start(): void {
    if (!can('start', 0.2)) return;
    noise(0.6, 0.07, { type: 'bandpass', f0: 250, f1: 2800, q: 1.4, attack: 0.25 });
    bell(hz(key + 24), 0.9, 0.07, { ratio: 3.5, index: 2 });
  },
  star(i: number): void {
    if (!sfxOn || !live()) return;
    bell(hz(key + 36 + [0, 4, 7][i % 3]), 0.5, 0.09, { ratio: 3.01, index: 1.5 });
  },
  /** Victory: a rising major arpeggio (the minor key resolved) under a held chord. */
  win(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    [0, 4, 7, 12].forEach((s, i) => {
      tone(hz(key + 24 + s), 0.3, 0.06, { type: 'triangle', at: t + i * 0.13 });
      bell(hz(key + 36 + s), 0.4, 0.035, { at: t + i * 0.13 });
    });
    for (const s of [0, 4, 7, 12, 16]) {
      for (const d of [-8, 8]) tone(hz(key + 12 + s), 1.9, 0.016, { type: 'sawtooth', attack: 0.06, detune: d, at: t + 0.52, dest: sfxHorn() });
    }
    tone(82, 0.9, 0.2, { slide: 0.6, at: t + 0.52 });
    noise(1.2, 0.04, { type: 'highpass', f0: 6000, at: t + 0.52 });
  },
  firework(pan: number): void {
    if (!can('firework', 0.1)) return;
    const t = now();
    noise(0.4, 0.13, { type: 'bandpass', f0: 1900, f1: 500, q: 0.9, pan });
    tone(150, 0.25, 0.15, { slide: 0.4, pan });
    for (let i = 0; i < 7; i++) noise(0.03, 0.035, { type: 'highpass', f0: 5000, at: t + 0.1 + Math.random() * 0.45, pan });
  },
  /** Defeat: the orb breaks like glass over a sinking drone. */
  lose(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    noise(0.6, 0.16, { type: 'highpass', f0: 2200 });
    tone(140, 1.2, 0.25, { slide: 0.2 });
    for (let i = 0; i < 12; i++) {
      bell(1400 + Math.random() * 3800, 0.25, 0.04, { ratio: 4.1, index: 1.3, at: t + Math.random() * 0.7, pan: Math.random() * 2 - 1 });
    }
    for (const d of [-10, 10]) tone(hz(key + 12), 2.4, 0.04, { type: 'sawtooth', slide: 0.5, attack: 0.1, detune: d, dest: sfxHorn() });
  },
};

let horn: BiquadFilterNode | null = null;
/** Brass-like voices go through one shared low-pass on the effects bus. */
function sfxHorn(): AudioNode {
  if (!horn) {
    horn = (ac as BaseAudioContext).createBiquadFilter();
    horn.type = 'lowpass';
    horn.frequency.value = 1100;
    horn.Q.value = 1.2;
    horn.connect(sfxBus);
  }
  return horn;
}

// ------------------------------------------------------------------ music

export interface MusicState {
  mode: 'off' | 'menu' | 'play';
  field: number;
  /** 0 calm to 1 full fight: adds bass, drums and the lead in turn. */
  intensity: number;
  /** 0 to 1: monsters about to reach the orb. */
  danger: number;
  /** Ice giants on the field. */
  boss: boolean;
  speed: number;
  paused: boolean;
}

/** One chord per bar: semitones above the key's root, and whether it is minor. */
const PROGRESSIONS: [number, boolean][][] = [
  [[0, true], [8, false], [3, false], [10, false]],
  [[0, true], [5, true], [8, false], [7, true]],
  [[0, true], [10, false], [8, false], [10, false]],
  [[0, true], [3, false], [5, true], [8, false]],
  [[0, true], [7, true], [8, false], [5, true]],
  [[0, true], [8, false], [5, true], [7, false]],
];
const KEYS = [45, 43, 47, 40, 42, 38];
const PENTATONIC = [0, 3, 5, 7, 10];
const ARP = [0, 2, 4, 2, 3, 2, 4, 5, 0, 2, 4, 2, 6, 4, 3, 2];

let state: MusicState = { mode: 'off', field: 0, intensity: 0, danger: 0, boss: false, speed: 1, paused: false };
let tune = '';
let step = 0;
let nextStep = 0;
let motifs: number[][] = [];
let lastGain = -1;
let lastCut = -1;

function rngFrom(seed: number): () => number {
  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;
  };
}

/** Two bars of eighth notes as steps on a two-octave pentatonic; −1 rests. */
function makeMotif(rng: () => number, start: number): number[] {
  const out: number[] = [];
  let d = start;
  for (let i = 0; i < 16; i++) {
    const strong = i % 4 === 0;
    if (!strong && rng() < 0.38) {
      out.push(-1);
      continue;
    }
    d = Math.max(0, Math.min(9, d + [-2, -1, -1, 0, 1, 1, 2][Math.floor(rng() * 7)]));
    out.push(d);
  }
  return out;
}

function pentatonicNote(degree: number): number {
  let pc = PENTATONIC[degree % 5];
  // Over the major dominant the scale's seventh is raised to fit the chord.
  if (!chord.minor && chord.root === 7 && pc === 10) pc = 11;
  return key + 24 + pc + 12 * Math.floor(degree / 5);
}

/** Drives the music; call every frame. Schedules a little ahead of the clock. */
export function music(s: MusicState, lookahead = 0.22): void {
  state = s;
  if (!live()) return;
  const on = musicOn && s.mode !== 'off';
  const gain = !on ? 0 : (s.mode === 'menu' ? 0.62 : 0.5) * (s.paused ? 0.6 : 1);
  if (gain !== lastGain) {
    musBus.gain.setTargetAtTime(gain, now(), on ? 0.25 : 0.12);
    lastGain = gain;
  }
  const cut = s.paused ? 520 : 16000;
  if (cut !== lastCut) {
    musFilter.frequency.setTargetAtTime(cut, now(), 0.12);
    lastCut = cut;
  }
  if (!on) return;
  const id = s.mode === 'menu' ? 'menu' : `field${s.field}`;
  const t0 = now();
  if (id !== tune) {
    if (tune) {
      const old = tuneBus;
      old.out.gain.setTargetAtTime(0, t0, 0.07);
      afterSeconds(0.8, () => old.out.disconnect());
      tuneBus = makeTuneBus();
    }
    tune = id;
    step = 0;
    nextStep = t0 + 0.08;
    key = s.mode === 'menu' ? 45 : KEYS[s.field % KEYS.length];
    const rng = rngFrom(777 + (s.mode === 'menu' ? 99 : s.field) * 31);
    motifs = [makeMotif(rng, 5), makeMotif(rng, 7)];
  }
  if (nextStep < t0 - 0.05) nextStep = t0 + 0.06;
  let guard = 0;
  while (nextStep < t0 + lookahead && guard++ < 4000) {
    playStep(step, nextStep);
    nextStep += stepSeconds();
    step++;
  }
}

function stepSeconds(): number {
  const bpm = state.mode === 'menu' ? 74 : (92 + state.field * 3) * (1 + (state.speed - 1) * 0.11);
  return 60 / bpm / 4;
}

function playStep(n: number, t: number): void {
  const menu = state.mode === 'menu';
  const s = n % 16;
  const bar = Math.floor(n / 16);
  const I = menu ? 0 : state.intensity;
  const sd = stepSeconds();
  const prog = PROGRESSIONS[menu ? 0 : state.field % PROGRESSIONS.length];
  // The menu lingers two bars on each chord.
  const chordBars = menu ? 2 : 1;

  if (s === 0 && bar % chordBars === 0) {
    const c = prog[Math.floor(bar / chordBars) % prog.length];
    chord = { root: c[0], minor: c[1] };
    pad(t, sd * 16 * chordBars, 750 + 1700 * I, 0.03 + 0.012 * I);
  }
  const root = key + chord.root;

  // Bass: two notes a bar when calm, a driving figure in a fight.
  if (!menu && I > 0.12) {
    const pattern = I > 0.65 ? [0, 3, 6, 8, 11, 14] : I > 0.35 ? [0, 6, 8, 14] : [0, 8];
    if (pattern.includes(s)) {
      let b = root;
      while (b > 45) b -= 12;
      while (b < 33) b += 12;
      tone(hz(b), sd * 2.6, 0.14, { type: 'triangle', at: t, dest: tuneBus.out });
      // An octave up for small speakers that cannot reach the fundamental.
      tone(hz(b + 12), sd * 2, 0.05, { type: 'sawtooth', at: t, dest: tuneBus.soft });
    }
  }

  // Arpeggio through the chord.
  const arpOn = menu ? s % 4 === 0 : I < 0.3 ? s % 4 === 0 || s === 6 : I < 0.6 ? s % 2 === 0 : true;
  if (arpOn) {
    const f = hz(chordNote(ARP[s]) + 24);
    const vol = (menu ? 0.07 : 0.055) * (s % 2 ? 0.55 : 1);
    // A plucked glassy voice, with its echo.
    bell(f, menu ? 0.6 : 0.26, vol, { ratio: 2, index: 0.9, at: t, dest: tuneBus.out });
    tone(f, 0.2, vol * 0.7, { type: 'triangle', at: t, dest: tuneBus.echo });
  }

  // Lead: two generated motifs in an A A B A form, from a moderate fight up.
  if (s % 2 === 0 && (menu ? bar % 8 >= 4 : I > 0.32)) {
    const phrase = Math.floor(bar / 2) % 4 === 2 ? motifs[1] : motifs[0];
    const d = phrase[(bar % 2) * 8 + s / 2];
    if (d >= 0) {
      const f = hz(pentatonicNote(d));
      const vol = menu ? 0.03 : 0.035 + 0.02 * I;
      tone(f, sd * 2.4, vol, { type: 'triangle', attack: 0.012, at: t, dest: tuneBus.out });
      tone(f * 2, sd * 1.6, vol * 0.25, { at: t, dest: tuneBus.echo });
      tone(f, sd * 2, vol * 0.5, { type: 'sawtooth', attack: 0.02, at: t, dest: tuneBus.soft });
    }
  }

  // Drums come in with the monsters.
  if (!menu && I > 0.25) {
    const kick = s === 0 || s === 8 || (I > 0.6 && s === 10) || (I > 0.85 && s === 14);
    if (kick) {
      tone(135, 0.17, 0.4, { slide: 0.3, at: t, dest: tuneBus.out });
      noise(0.02, 0.12, { type: 'highpass', f0: 2500, at: t, dest: tuneBus.out });
    }
    const hat = I > 0.75 ? true : I > 0.5 ? s % 2 === 0 : s % 4 === 2;
    if (hat) noise(0.04, s % 2 ? 0.05 : 0.1, { type: 'highpass', f0: 6500, at: t, dest: tuneBus.out });
    if (I > 0.45 && (s === 4 || s === 12)) {
      noise(0.13, 0.16, { type: 'bandpass', f0: 1900, q: 0.7, at: t, dest: tuneBus.out });
      tone(190, 0.09, 0.09, { type: 'triangle', slide: 0.6, at: t, dest: tuneBus.out });
    }
    // A tom fill leads into every fourth bar.
    if (I > 0.6 && bar % 4 === 3 && s >= 12) tone(190 - (s - 12) * 26, 0.14, 0.22, { slide: 0.6, at: t, dest: tuneBus.out });
  }

  // Danger: a nervous two-note figure above everything.
  if (!menu && state.danger > 0.4 && s % 2 === 1) {
    const semi = s % 4 === 1 ? 19 : 20;
    tone(hz(root + 12 + semi), sd * 0.9, 0.028 * state.danger, { type: 'sawtooth', at: t, dest: tuneBus.soft });
  }

  // Ice giants bring a drum and a low drone.
  if (!menu && state.boss && s === 0 && bar % 2 === 0) {
    tone(84, 0.6, 0.35, { slide: 0.6, at: t, dest: tuneBus.out });
    for (const d of [-7, 7]) tone(hz(key - 12), sd * 32, 0.05, { type: 'sawtooth', attack: 0.4, detune: d, at: t, dest: tuneBus.soft });
  }
}

/** A slow chord of detuned saws behind one opening filter. */
function pad(t: number, dur: number, cutoff: number, vol: number): void {
  if (!ac || !live() || voices > maxVoices) return;
  const f = ac.createBiquadFilter();
  f.type = 'lowpass';
  f.Q.value = 0.7;
  f.frequency.setValueAtTime(cutoff * 0.6, t);
  f.frequency.linearRampToValueAtTime(cutoff, t + dur * 0.5);
  f.frequency.linearRampToValueAtTime(cutoff * 0.7, t + dur);
  const g = ac.createGain();
  g.gain.value = 0;
  g.gain.setValueAtTime(0.0001, t);
  g.gain.linearRampToValueAtTime(vol, t + Math.min(0.5, dur * 0.3));
  g.gain.setValueAtTime(vol, t + dur * 0.8);
  g.gain.linearRampToValueAtTime(0.0001, t + dur + 0.35);
  f.connect(g).connect(tuneBus.out);
  const third = chord.minor ? 3 : 4;
  for (const semi of [0, third, 7, 12]) {
    // Fold every voice into one octave and a half so chords move smoothly.
    let n = key + 12 + chord.root + semi;
    while (n > key + 26) n -= 12;
    for (const d of [-8, 8]) {
      const o = ac.createOscillator();
      o.type = 'sawtooth';
      o.frequency.value = hz(n);
      o.detune.value = d;
      o.connect(f);
      o.start(t);
      o.stop(t + dur + 0.4);
      track(o);
    }
  }
}