Back to Arañas Pistoleras
SOURCE / PINNED RELEASE

Made of little things.

Arañas Pistoleras

Release
2578a037ceaf…
Author-recorded commit
e35cc0733a7b…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-7bf0a402584

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

src/audio.ts
// Synthesised sound and music. Nothing is sampled: every voice is built from
// oscillators and filtered noise, so the napplet stays one file and needs no
// network. Each place has its own little tune, written out by hand below.

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 fades the old one out. */
interface TuneBus {
  out: GainNode;
  soft: BiquadFilterNode;
  echo: GainNode;
}
let tuneBus: TuneBus;
let noiseBuf: AudioBuffer;
let voices = 0;
let maxVoices = 80;
let sfxOn = true;
let musicOn = true;
/** Added to the context clock; lets a test lay sounds out along an offline render. */
let clockOffset = 0;

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;
  // A slow leveller; a fast one follows the beating between the notes of a
  // chord and adds a rumble of its own.
  const comp = ac.createDynamicsCompressor();
  comp.threshold.value = -12;
  comp.knee.value = 10;
  comp.ratio.value = 4;
  comp.attack.value = 0.015;
  comp.release.value = 0.25;
  // Behind it a fast limiter that 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.5;
  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 room: decaying noise as the impulse response.
  const len = Math.floor(ac.sampleRate * 2.1);
  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.4);
  }
  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.22;
  sfxBus.connect(sfxSend).connect(hall);
  const musSend = ac.createGain();
  musSend.gain.value = 0.4;
  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 = 1500;
  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.36;
  const fb = a.createGain();
  fb.gain.value = 0.34;
  const damp = a.createBiquadFilter();
  damp.type = 'lowpass';
  damp.frequency.value = 2400;
  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;
  /** Vibrato depth in cents and its rate. */
  vibrato?: number;
  rate?: 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;
}

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;
  if (o.vibrato) {
    const lfo = ac.createOscillator();
    const depth = ac.createGain();
    lfo.frequency.value = o.rate ?? 5.5;
    depth.gain.value = 0;
    depth.gain.setValueAtTime(0, t);
    depth.gain.linearRampToValueAtTime(o.vibrato, t + Math.min(0.3, dur * 0.5));
    lfo.connect(depth).connect(osc.detune);
    lfo.start(t);
    lfo.stop(t + dur + 0.03);
  }
  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 {
  if (!live() || !sfxOn || voices > maxVoices - 20) 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);
}

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

function skitter(count: number, pan: number, vol = 0.2, at = now()): void {
  for (let i = 0; i < count; i++) {
    noise(0.022, vol, { type: 'bandpass', q: 1.2, f0: 3600, at: at + i * 0.05 * (0.75 + Math.random() * 0.5), pan });
  }
}

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

/** The key the tune is in, as a midi note around A3; effects take their notes from it. */
let key = 57;
const MINOR_PENTA = [0, 3, 5, 7, 10, 12, 15, 17, 19];

export const sfx = {
  click(): void {
    if (!can('click', 0.03)) return;
    tone(740, 0.04, 0.04, { slide: 0.6 });
    noise(0.015, 0.02, { type: 'highpass', f0: 3000 });
  },
  start(): void {
    if (!can('start', 0.2)) return;
    const t = now();
    noise(0.5, 0.06, { type: 'bandpass', f0: 300, f1: 2600, q: 1.4, attack: 0.25 });
    [0, 3, 7].forEach((s, i) => bell(hz(key + 12 + s), 0.6, 0.06, { ratio: 3.01, index: 1.3, at: t + i * 0.09 }));
  },
  /** The name of the place sweeping in. */
  banner(): void {
    if (!can('banner', 0.3)) return;
    noise(0.6, 0.05, { type: 'bandpass', f0: 250, f1: 2400, q: 1.2, attack: 0.3 });
    tone(hz(key - 12), 0.9, 0.12, { type: 'triangle', attack: 0.1 });
  },
  miss(pan: number): void {
    if (!can('miss', 0.05)) return;
    tone(170, 0.07, 0.1, { slide: 0.5, pan });
    noise(0.04, 0.05, { f0: 900, pan });
  },
  hit(pan: number, big: boolean): void {
    if (!can('hit', 0.04)) return;
    noise(0.11, 0.17, { type: 'bandpass', f0: big ? 600 : 950, f1: 200, q: 1.2, pan });
    tone(big ? 170 : 270, 0.1, 0.16, { slide: 0.4, pan });
    if (big) bell(190, 0.25, 0.08, { ratio: 1.41, index: 2.6, pan });
  },
  /** A spider's last word. */
  squeal(pan: number, kind: string): void {
    if (!can('squeal', 0.06)) return;
    const f = kind === 'mini' ? 2500 : kind === 'hat' ? 1150 : kind === 'boss' ? 420 : 1650;
    const dur = kind === 'boss' ? 1.1 : kind === 'mini' ? 0.16 : 0.27;
    tone(f, dur, 0.1, { type: 'sawtooth', slide: 0.45, vibrato: 90, rate: 28, pan, dest: kind === 'boss' ? sfxHorn() : undefined });
    tone(f * 1.5, dur * 0.7, 0.04, { type: 'square', slide: 0.5, pan });
  },
  /** The burst, with a note that climbs while kills keep coming. */
  pop(pan: number, combo: number, size: number): void {
    if (!can('pop', 0.05)) return;
    tone(540 - size * 160, 0.11, 0.17, { type: 'triangle', slide: 0.3, pan });
    noise(0.2, 0.13, { f0: 1900, f1: 280, pan });
    noise(0.05, 0.06, { type: 'highpass', f0: 3800, pan });
    bell(hz(key + 12 + MINOR_PENTA[Math.min(combo, MINOR_PENTA.length - 1)]), 0.3, 0.07, { ratio: 2, index: 0.9, pan });
  },
  hatOff(pan: number): void {
    if (!can('hat', 0.08)) return;
    const t = now();
    tone(230, 0.26, 0.13, { slide: 2.3, pan });
    tone(540, 0.22, 0.08, { slide: 0.55, at: t + 0.14, pan });
  },
  spawn(pan: number, mode: string, kind: string): void {
    if (!can('spawn', 0.08)) return;
    if (kind === 'boss') return;
    if (mode === 'drop') {
      tone(kind === 'mini' ? 1700 : 1250, 0.5, 0.035, { slide: 0.36, attack: 0.08, pan });
      noise(0.4, 0.015, { type: 'bandpass', f0: 5200, f1: 1800, q: 6, pan });
    } else {
      skitter(mode === 'crawl' ? 9 : 5, pan, kind === 'mini' ? 0.14 : 0.2);
    }
  },
  /** The hammer goes back: it is aiming. */
  cock(pan: number): void {
    if (!can('cock', 0.07)) return;
    const t = now();
    bell(1750, 0.04, 0.13, { ratio: 5.4, index: 1, pan });
    noise(0.03, 0.11, { type: 'bandpass', f0: 2600, q: 3, pan });
    bell(1250, 0.05, 0.15, { ratio: 5.4, index: 1.2, at: t + 0.1, pan });
    noise(0.03, 0.13, { type: 'bandpass', f0: 1900, q: 3, at: t + 0.1, pan });
  },
  /** Last warning before a shot. */
  warn(pan: number): void {
    if (!can('warn', 0.16)) return;
    const t = now();
    tone(988, 0.07, 0.08, { type: 'square', pan });
    tone(988, 0.07, 0.08, { type: 'square', at: t + 0.11, pan });
  },
  bang(pan: number, boss: boolean): void {
    if (!sfxOn || !live()) return;
    const t = now();
    for (const at of boss ? [t, t + 0.07] : [t]) {
      noise(0.3, 0.55, { f0: boss ? 3200 : 4400, f1: 220, pan, at });
      tone(boss ? 130 : 175, 0.24, 0.6, { slide: 0.24, pan, at });
      noise(0.045, 0.3, { type: 'highpass', f0: 3200, pan, at });
    }
  },
  /** The player is hit: glass breaks. */
  ouch(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    noise(0.4, 0.2, { type: 'highpass', f0: 2400, at: t + 0.03 });
    tone(230, 0.5, 0.2, { type: 'triangle', slide: 0.4, at: t + 0.03 });
    for (let i = 0; i < 10; i++) {
      bell(1500 + Math.random() * 3800, 0.22, 0.04, { ratio: 4.1, index: 1.3, at: t + 0.04 + Math.random() * 0.55, pan: Math.random() * 2 - 1 });
    }
  },
  /** It got away, and it is pleased with itself. */
  giggle(pan: number): void {
    if (!can('giggle', 0.3)) return;
    const t = now();
    for (let i = 0; i < 5; i++) tone(1350 - i * 95, 0.06, 0.085, { type: 'square', slide: 1.25, at: t + i * 0.085, pan });
  },
  heartAppear(pan: number): void {
    if (!can('heartA', 0.2)) return;
    const t = now();
    [12, 16, 19].forEach((s, i) => bell(hz(key + 12 + s), 0.4, 0.05, { ratio: 3.01, index: 1.2, at: t + i * 0.07, pan }));
  },
  heal(): void {
    if (!can('heal', 0.1)) return;
    const t = now();
    bell(hz(key + 24), 0.4, 0.09, { ratio: 2, index: 1 });
    bell(hz(key + 31), 0.6, 0.09, { ratio: 2, index: 1, at: t + 0.1 });
    tone(hz(key + 12), 0.5, 0.08, { type: 'triangle', attack: 0.05, at: t + 0.1 });
  },
  bossIntro(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    for (const d of [-12, 12]) tone(hz(key - 24), 2.3, 0.22, { type: 'sawtooth', attack: 0.6, detune: d, dest: sfxHorn() });
    noise(2.4, 0.25, { f0: 140, f1: 60, attack: 0.7 });
    for (const at of [0, 0.5, 1.0, 1.25, 1.5]) tone(82, 0.5, 0.38, { slide: 0.6, at: t + at });
    for (const s of [0, 1, 6]) {
      for (const d of [-9, 9]) tone(hz(key + s), 1.3, 0.06, { type: 'sawtooth', attack: 0.12, detune: d, at: t + 1.0, dest: sfxHorn() });
    }
    skitter(14, 0, 0.1, t + 0.3);
  },
  bossStun(pan: number): void {
    if (!can('stun', 0.3)) return;
    const t = now();
    for (let i = 0; i < 8; i++) tone(1250 - i * 115, 0.09, 0.11, { type: 'triangle', slide: 0.8, at: t + i * 0.07, pan });
  },
  bossSummon(): void {
    if (!can('summon', 0.3)) return;
    tone(92, 0.6, 0.3, { type: 'sawtooth', slide: 0.7, dest: sfxHorn() });
    skitter(16, 0, 0.11);
  },
  bossDie(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    tone(210, 1.7, 0.5, { slide: 0.14 });
    noise(1.5, 0.4, { f0: 3200, f1: 80 });
    for (let i = 0; i < 7; i++) {
      const at = t + 0.15 + i * 0.17;
      tone(480 - i * 30, 0.1, 0.14, { type: 'triangle', slide: 0.3, at, pan: Math.random() * 2 - 1 });
      noise(0.16, 0.1, { f0: 1800, f1: 300, at });
    }
  },
  star(i: number): void {
    if (!sfxOn || !live()) return;
    bell(hz(key + 24 + [0, 4, 7][i % 3]), 0.55, 0.1, { ratio: 3.01, index: 1.5 });
    noise(0.05, 0.03, { type: 'highpass', f0: 6000 });
  },
  /** Victory: the minor key turns major. */
  win(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    [0, 4, 7, 12].forEach((s, i) => {
      tone(hz(key + 12 + s), 0.3, 0.07, { type: 'triangle', at: t + i * 0.13 });
      bell(hz(key + 24 + s), 0.4, 0.04, { at: t + i * 0.13 });
    });
    for (const s of [0, 4, 7, 12, 16]) {
      for (const d of [-8, 8]) tone(hz(key + s), 1.9, 0.02, { 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 });
  },
  /** Defeat: a sad trombone, and the spiders laugh. */
  lose(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    [7, 6, 5, 4].forEach((s, i) => {
      const last = i === 3;
      for (const d of [-7, 7]) {
        tone(hz(key + s), last ? 1.2 : 0.4, 0.09, { type: 'sawtooth', slide: last ? 0.8 : 0.95, attack: 0.03, detune: d, at: t + i * 0.42, dest: sfxHorn(), vibrato: last ? 40 : 0 });
      }
    });
    for (let g = 0; g < 2; g++) {
      for (let i = 0; i < 5; i++) tone(1350 - i * 95 + g * 200, 0.06, 0.04, { type: 'square', slide: 1.25, at: t + 1.9 + g * 0.5 + i * 0.085, pan: g ? 0.6 : -0.6 });
    }
  },

  // What the places themselves do.
  drip(pan: number): void {
    if (!can('drip', 0.2)) return;
    const t = now();
    tone(1450, 0.07, 0.1, { slide: 0.45, pan });
    tone(720, 0.1, 0.05, { slide: 1.6, at: t + 0.05, pan });
  },
  tick(pan: number): void {
    if (!can('tick', 0.4)) return;
    noise(0.016, 0.14, { type: 'bandpass', q: 2, f0: 3200, pan });
  },
  hoot(pan: number): void {
    if (!can('hoot', 0.5)) return;
    const t = now();
    tone(392, 0.3, 0.13, { attack: 0.05, slide: 0.93, pan });
    tone(349, 0.2, 0.11, { attack: 0.04, at: t + 0.4, pan });
    tone(349, 0.4, 0.12, { attack: 0.04, slide: 0.9, at: t + 0.62, pan });
  },
  thunder(): void {
    if (!can('thunder', 1)) return;
    noise(0.12, 0.25, { type: 'highpass', f0: 1800 });
    noise(2.6, 0.36, { f0: 500, f1: 50, attack: 0.03 });
    tone(55, 1.8, 0.2, { slide: 0.6, attack: 0.05 });
  },
  bell(pan: number): void {
    if (!can('bell', 0.6)) return;
    const t = now();
    for (let i = 0; i < 12; i++) bell(1568, 0.11, 0.07, { ratio: 3.7, index: 1.8, at: t + i * 0.06, pan });
  },
  clang(pan: number): void {
    if (!can('clang', 0.05)) return;
    const f = 260 + Math.random() * 180;
    bell(f, 1.0, 0.14, { ratio: 2.32, index: 3.2, pan });
    bell(f * 2.7, 0.5, 0.07, { ratio: 1.41, index: 2, pan });
    noise(0.04, 0.1, { type: 'bandpass', f0: 2400, q: 2, pan });
  },
  globe(pan: number): void {
    if (!can('globe', 0.2)) return;
    noise(0.5, 0.12, { type: 'bandpass', f0: 2400, f1: 700, q: 3, pan });
    const t = now();
    for (let i = 0; i < 9; i++) noise(0.014, 0.08, { type: 'highpass', f0: 3000, at: t + i * i * 0.007, pan });
  },
  squeak(pan: number): void {
    if (!can('squeak', 0.12)) return;
    const t = now();
    tone(950, 0.12, 0.09, { type: 'square', slide: 1.7, pan });
    tone(1550, 0.16, 0.06, { type: 'square', slide: 0.5, at: t + 0.12, pan });
  },
  buzz(pan: number): void {
    if (!can('buzz', 0.2)) return;
    const t = now();
    for (let i = 0; i < 4; i++) {
      tone(100, 0.07, 0.11, { type: 'sawtooth', at: t + i * 0.1, pan });
      noise(0.02, 0.08, { type: 'highpass', f0: 5000, at: t + i * 0.1, pan });
    }
  },
  bonk(pan: number): void {
    if (!can('bonk', 0.08)) return;
    tone(135, 0.28, 0.22, { slide: 0.6, pan });
    bell(205, 0.35, 0.1, { ratio: 1.5, index: 2, pan });
  },
  chime(pan: number): void {
    if (!can('chime', 0.12)) return;
    const t = now();
    [7, 12, 15, 19].forEach((s, i) => bell(hz(key + 24 + s), 0.7, 0.05, { ratio: 3.5, index: 1.1, at: t + i * 0.08, pan }));
  },
  lamp(pan: number): void {
    if (!can('lamp', 0.1)) return;
    noise(0.02, 0.09, { type: 'highpass', f0: 2500, pan });
    tone(1900, 0.02, 0.05, { pan });
  },
  cricket(pan: number): void {
    if (!can('cricket', 0.8)) return;
    const t = now();
    for (let i = 0; i < 3; i++) {
      for (let j = 0; j < 4; j++) tone(4300, 0.018, 0.035, { at: t + i * 0.15 + j * 0.03, pan });
    }
  },
  bat(pan: number): void {
    if (!can('bat', 1)) return;
    const t = now();
    for (let i = 0; i < 4; i++) tone(6200, 0.03, 0.035, { slide: 1.2, at: t + i * 0.22, pan: pan - i * 0.3 });
    for (let i = 0; i < 8; i++) noise(0.03, 0.035, { f0: 600, at: t + i * 0.11, pan: pan - i * 0.15 });
  },
  flicker(): void {
    if (!can('flicker', 0.5)) return;
    const t = now();
    for (let i = 0; i < 3; i++) {
      tone(120, 0.05, 0.06, { type: 'sawtooth', at: t + i * 0.13 });
      noise(0.015, 0.06, { type: 'highpass', f0: 6000, at: t + i * 0.13 });
    }
  },
  pot(pan: number): void {
    if (!can('pot', 0.5)) return;
    const t = now();
    for (let i = 0; i < 7; i++) bell(2100 + Math.random() * 300, 0.04, 0.055, { ratio: 3.7, index: 1.2, at: t + i * 0.075, pan });
    noise(0.6, 0.02, { type: 'highpass', f0: 5000, attack: 0.2, pan });
  },
};

/** What the butterflies sound like: glass and air in place of slime and gunpowder. */
const MAJOR_PENTA = [0, 2, 4, 7, 9, 12, 14, 16, 19];

function wingbeats(count: number, pan: number, vol: number, at = now()): void {
  for (let i = 0; i < count; i++) noise(0.04, vol, { type: 'bandpass', f0: 700 + Math.random() * 500, q: 0.8, at: at + i * 0.06, pan });
}

export const bsfx = {
  /** One arrives. */
  flutter(pan: number, small: boolean): void {
    if (!can('flutter', 0.08)) return;
    wingbeats(small ? 5 : 7, pan, 0.14);
    bell(hz(key + 24 + (small ? 16 : 7)), 0.3, 0.03, { ratio: 3.5, index: 1, pan });
  },
  /** It is getting restless. */
  ready(pan: number): void {
    if (!can('ready', 0.07)) return;
    const t = now();
    bell(hz(key + 31), 0.25, 0.07, { ratio: 3.01, index: 1.1, pan });
    bell(hz(key + 36), 0.32, 0.07, { ratio: 3.01, index: 1.1, at: t + 0.1, pan });
  },
  /** Any moment now. */
  warn(pan: number): void {
    if (!can('bwarn', 0.16)) return;
    const t = now();
    for (let i = 0; i < 4; i++) bell(hz(key + 36 + (i % 2 ? 2 : 0)), 0.07, 0.06, { ratio: 2, index: 0.8, at: t + i * 0.055, pan });
  },
  /** It slips away with a heart. */
  away(pan: number, queen: boolean): void {
    if (!sfxOn || !live()) return;
    const t = now();
    noise(0.4, 0.2, { type: 'bandpass', f0: 500, f1: 3600, q: 1.2, attack: 0.05, pan });
    tone(queen ? 380 : 520, 0.32, 0.12, { slide: 3, pan });
    wingbeats(6, pan, 0.08, t + 0.05);
    tone(hz(key + 19), 0.22, 0.13, { type: 'triangle', at: t + 0.3 });
    tone(hz(key + 16), 0.5, 0.13, { type: 'triangle', slide: 0.96, at: t + 0.52 });
  },
  /** A tap that did not catch it yet. */
  tap(pan: number, queen: boolean): void {
    if (!can('btap', 0.04)) return;
    bell(hz(key + (queen ? 19 : 24)), 0.14, 0.12, { ratio: 2, index: 0.7, pan });
    noise(0.03, 0.05, { type: 'highpass', f0: 4000, pan });
  },
  /** Caught: a little run upwards, starting higher while catches keep coming. */
  caught(pan: number, combo: number, size: number): void {
    if (!can('caught', 0.05)) return;
    const t = now();
    const from = Math.min(combo, 4);
    for (let i = 0; i < 4; i++) {
      bell(hz(key + 24 + MAJOR_PENTA[from + i]), 0.3, 0.085, { ratio: 3.01, index: 1.2, at: t + i * 0.05, pan });
    }
    tone(hz(key + 12 + MAJOR_PENTA[from]), 0.2, 0.07 + 0.03 * size, { type: 'triangle', pan });
    noise(0.25, 0.04, { type: 'highpass', f0: 6500, attack: 0.02, pan });
  },
  queenIntro(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    // A harp running up, then a bright chord.
    const scale = [0, 2, 4, 5, 7, 9, 11];
    for (let i = 0; i < 15; i++) {
      bell(hz(key + 12 + scale[i % 7] + 12 * Math.floor(i / 7)), 0.5, 0.06, { ratio: 2, index: 0.9, at: t + i * 0.06, pan: -0.6 + i * 0.08 });
    }
    for (const semi of [0, 4, 7, 12]) {
      for (const d of [-8, 8]) tone(hz(key + semi), 1.4, 0.04, { type: 'sawtooth', attack: 0.1, detune: d, at: t + 1.0, dest: sfxHorn() });
    }
    tone(82, 0.5, 0.25, { slide: 0.6, at: t + 1.0 });
    wingbeats(12, 0, 0.07, t + 0.2);
  },
  queenCalls(): void {
    if (!can('calls', 0.3)) return;
    const t = now();
    wingbeats(14, 0, 0.08);
    [12, 16, 19].forEach((semi, i) => bell(hz(key + 12 + semi), 0.3, 0.06, { ratio: 3.5, index: 1, at: t + i * 0.07 }));
  },
  queenCaught(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    for (let i = 0; i < 18; i++) {
      bell(hz(key + 24 + MAJOR_PENTA[Math.floor(Math.random() * 9)]), 0.5, 0.05, { ratio: 3.5, index: 1.2, at: t + Math.random() * 1.3, pan: Math.random() * 2 - 1 });
    }
    for (let i = 0; i < 9; i++) bell(hz(key + 12 + MAJOR_PENTA[i]), 0.45, 0.08, { ratio: 2, index: 1, at: t + i * 0.07 });
    tone(110, 0.9, 0.25, { slide: 0.5 });
    noise(1.2, 0.06, { type: 'highpass', f0: 6000, attack: 0.1 });
  },
  /** They all flew away. */
  lose(): void {
    if (!sfxOn || !live()) return;
    const t = now();
    [7, 4, 2, 0].forEach((semi, i) => {
      tone(hz(key + 12 + semi), i === 3 ? 1.0 : 0.38, 0.11, { type: 'triangle', attack: 0.03, at: t + i * 0.4, vibrato: i === 3 ? 25 : 0 });
    });
    wingbeats(10, 0.5, 0.06, t + 1.7);
    wingbeats(10, -0.5, 0.06, t + 2.0);
  },
};

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

/** With the butterflies every tune moves to the major key on the same note. */
let major = false;
export function setTheme(butterflies: boolean): void {
  major = butterflies;
}

export interface MusicState {
  mode: 'off' | 'on';
  /** −1 the menu, otherwise the level. */
  tune: number;
  /** The queen is here: faster, with drums. */
  boss: boolean;
  /** 0 to 1: how close the nearest shot is. */
  tension: number;
  paused: boolean;
}

type Lead = 'celesta' | 'xylo' | 'glock' | 'box' | 'theremin' | 'ocarina';
type Backing = 'waltz' | 'tiptoe' | 'drone' | 'six';

interface Tune {
  /** Beats a minute and steps (eighth notes) in a bar. */
  bpm: number;
  steps: number;
  key: number;
  lead: Lead;
  backing: Backing;
  chords: string[];
  /** One string a bar; a note name starts a note, `-` holds it, `.` is silence. */
  melody: string[];
}

const TUNES: Record<string, Tune> = {
  menu: {
    bpm: 100, steps: 6, key: 50, lead: 'celesta', backing: 'waltz',
    chords: ['Dm', 'Dm', 'Gm', 'Dm', 'Bb', 'Gm', 'A', 'A', 'Dm', 'Dm', 'Gm', 'Dm', 'Bb', 'A', 'Dm', 'Dm'],
    melody: [
      'd5 - f5 - a5 -', 'g5 - f5 - e5 -', 'd5 - g5 - bb5 -', 'a5 - - - - -',
      'bb5 - a5 - g5 -', 'g5 - bb5 - g5 -', 'e5 - a5 - c#6 -', 'a5 - - - - -',
      'd6 - a5 - f5 -', 'e5 - f5 - d5 -', 'g5 - bb5 - d6 -', 'a5 - - - f5 -',
      'bb5 - d6 - bb5 -', 'a5 - c#6 - e6 -', 'd6 - - - a5 -', 'd5 - - - - -',
    ],
  },
  colegio: {
    bpm: 112, steps: 8, key: 52, lead: 'xylo', backing: 'tiptoe',
    chords: ['Em', 'Em', 'Am', 'Em', 'C', 'Am', 'B', 'Em', 'Em', 'Em', 'Am', 'Em', 'C', 'Am', 'B', 'Em'],
    melody: [
      'e5 - g5 - f#5 g5 e5 -', 'b4 - e5 - d#5 e5 b4 -', 'a4 - c5 - b4 c5 a4 -', 'e5 - - - b4 - - -',
      'c5 - e5 - g5 - e5 -', 'a4 - c5 - e5 - c5 -', 'b4 - d#5 - f#5 - a5 -', 'g5 f#5 e5 - - - - -',
      'e5 g5 b5 - a5 g5 f#5 -', 'e5 - b4 - e5 - - -', 'a5 - g5 - f#5 - e5 -', 'd#5 - e5 - b4 - - -',
      'c5 e5 g5 - c6 - g5 -', 'a5 - e5 - c5 - a4 -', 'b4 d#5 f#5 a5 b5 - a5 -', 'e5 - - - e4 - - -',
    ],
  },
  cocina: {
    bpm: 132, steps: 6, key: 55, lead: 'glock', backing: 'waltz',
    chords: ['Gm', 'Gm', 'Cm', 'Gm', 'Eb', 'Cm', 'D', 'D', 'Gm', 'Gm', 'Cm', 'Gm', 'Eb', 'D', 'Gm', 'Gm'],
    melody: [
      'g5 - bb5 - d6 -', 'd6 - c6 - bb5 -', 'c6 - eb6 - c6 -', 'bb5 - a5 - g5 -',
      'eb5 - g5 - bb5 -', 'c6 - bb5 - g5 -', 'a5 - f#5 - d5 -', 'd5 - f#5 - a5 -',
      'g5 - d6 - bb5 -', 'g5 - a5 - bb5 -', 'c6 - g5 - eb6 -', 'd6 - - - bb5 -',
      'eb6 - d6 - c6 -', 'a5 - c6 - f#5 -', 'g5 - - - d5 -', 'g4 - - - - -',
    ],
  },
  dormitorio: {
    bpm: 84, steps: 6, key: 57, lead: 'box', backing: 'waltz',
    chords: ['Am', 'Am', 'Dm', 'Am', 'F', 'Dm', 'E', 'E', 'Am', 'Am', 'Dm', 'Am', 'F', 'E', 'Am', 'Am'],
    melody: [
      'e5 - - - c5 -', 'e5 - - - c5 -', 'f5 - e5 - d5 -', 'e5 - - - - -',
      'f5 - - - a5 -', 'f5 - e5 - d5 -', 'e5 - g#5 - b5 -', 'e5 - - - - -',
      'a5 - - - e5 -', 'c6 - b5 - a5 -', 'd6 - - - a5 -', 'e5 - a5 - c6 -',
      'a5 - f5 - c5 -', 'b4 - e5 - g#5 -', 'a5 - - - e5 -', 'a4 - - - - -',
    ],
  },
  bodega: {
    bpm: 80, steps: 8, key: 48, lead: 'theremin', backing: 'drone',
    chords: ['Cm', 'Cm', 'Ab', 'G', 'Cm', 'Fm', 'Db', 'G', 'Cm', 'Cm', 'Ab', 'Fm', 'Cm', 'Db', 'G', 'Cm'],
    melody: [
      'g4 - - - - - eb4 -', 'c5 - - - - - - -', 'ab4 - - - c5 - eb5 -', 'd5 - - - b4 - - -',
      'c5 - - - eb5 - - -', 'f5 - - - ab5 - f5 -', 'f5 - - - db5 - - -', 'd5 - - - g4 - - -',
      'g5 - - - - - eb5 -', 'c5 - - - - - g4 -', 'ab4 - c5 - eb5 - - -', 'f5 - - - c5 - - -',
      'eb5 - - - c5 - - -', 'db5 - - - - - f5 -', 'd5 - - - b4 - - -', 'c5 - - - - - - -',
    ],
  },
  bosque: {
    bpm: 168, steps: 6, key: 47, lead: 'ocarina', backing: 'six',
    chords: ['Bm', 'Bm', 'G', 'F#', 'Bm', 'Em', 'F#', 'F#', 'Bm', 'G', 'Em', 'F#', 'Bm', 'Em', 'F#', 'Bm'],
    melody: [
      'b4 - d5 f#5 - d5', 'b5 - - a5 - f#5', 'g5 - b5 d6 - b5', 'c#6 - - a#5 - f#5',
      'b5 - d6 f#6 - d6', 'e6 - - b5 - g5', 'f#5 - a#5 c#6 - e6', 'f#6 - - - - -',
      'f#6 - d6 b5 - f#5', 'g5 - b5 d6 - -', 'e6 - b5 g5 - e5', 'f#5 - - a#5 - c#6',
      'b5 - - d6 - b5', 'g5 - e5 b5 - g5', 'f#5 - a#5 c#6 - a#5', 'b5 - - - - -',
    ],
  },
};
const LEVEL_TUNES = ['colegio', 'cocina', 'dormitorio', 'bodega', 'bosque'];

const NOTE_BASE: Record<string, number> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };

function noteMidi(name: string): number {
  const m = /^([a-g])(#|b)?(\d)$/.exec(name);
  if (!m) return -1;
  return 12 * (Number(m[3]) + 1) + NOTE_BASE[m[1]] + (m[2] === '#' ? 1 : m[2] === 'b' ? -1 : 0);
}

/** The root (0–11) and the third of a chord name such as Dm, Bb or F#. */
function chordOf(name: string): { root: number; third: number } {
  const m = /^([A-G])(#|b)?(m)?$/.exec(name);
  if (!m) return { root: 0, third: 3 };
  const root = (NOTE_BASE[m[1].toLowerCase()] + (m[2] === '#' ? 1 : m[2] === 'b' ? -1 : 0) + 12) % 12;
  return { root, third: m[3] ? 3 : 4 };
}

interface Parsed {
  tune: Tune;
  /** Per bar and step: the midi note starting there and how many steps it lasts; null for none. */
  notes: ({ midi: number; len: number } | null)[][];
  chords: { root: number; third: number }[];
}
const parsed = new Map<string, Parsed>();

/** Minor to major on the same key note: the third, sixth and seventh go up a step. */
function brighten(midi: number, keyNote: number): number {
  const degree = (((midi - keyNote) % 12) + 12) % 12;
  return degree === 3 || degree === 8 || degree === 10 ? midi + 1 : midi;
}

/** The chord on the same step of the major scale. */
function brightenChord(c: { root: number; third: number }, keyNote: number): { root: number; third: number } {
  const degree = (((c.root - keyNote) % 12) + 12) % 12;
  const map: Record<number, [number, number]> = { 0: [0, 4], 1: [2, 3], 2: [2, 3], 3: [4, 3], 5: [5, 4], 7: [7, 4], 8: [9, 3], 10: [7, 4] };
  const m = map[degree];
  if (!m) return c;
  return { root: (keyNote + m[0]) % 12, third: m[1] };
}

function parse(base: string): Parsed {
  const id = base + (major ? '+' : '');
  let p = parsed.get(id);
  if (p) return p;
  const tune = TUNES[base];
  const notes = tune.melody.map((bar) => {
    const tokens = bar.trim().split(/\s+/);
    return tokens.map((tok, i) => {
      const written = noteMidi(tok);
      if (written < 0) return null;
      const midi = major ? brighten(written, tune.key) : written;
      let len = 1;
      while (i + len < tokens.length && tokens[i + len] === '-') len++;
      return { midi, len };
    });
  });
  p = { tune, notes, chords: tune.chords.map(chordOf).map((c) => (major ? brightenChord(c, tune.key) : c)) };
  parsed.set(id, p);
  return p;
}

let state: MusicState = { mode: 'off', tune: -1, boss: false, tension: 0, paused: false };
let current = '';
/** The tune without its mode, as it is named in TUNES. */
let currentBase = 'menu';
let step = 0;
let nextStep = 0;
let lastGain = -1;
let lastCut = -1;

/** 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 : 0.95 * (s.paused ? 0.55 : 1);
  if (gain !== lastGain) {
    musBus.gain.setTargetAtTime(gain, now(), on ? 0.25 : 0.12);
    lastGain = gain;
  }
  const cut = s.paused ? 600 : 16000;
  if (cut !== lastCut) {
    musFilter.frequency.setTargetAtTime(cut, now(), 0.12);
    lastCut = cut;
  }
  if (!on) return;
  const base = s.tune < 0 ? 'menu' : LEVEL_TUNES[s.tune % LEVEL_TUNES.length];
  const id = base + (major ? '+' : '');
  const t0 = now();
  if (id !== current) {
    if (current) {
      const old = tuneBus;
      old.out.gain.setTargetAtTime(0, t0, 0.07);
      afterSeconds(0.8, () => old.out.disconnect());
      tuneBus = makeTuneBus();
    }
    current = id;
    currentBase = base;
    step = 0;
    nextStep = t0 + 0.1;
    key = TUNES[base].key + 12;
    while (key > 62) key -= 12;
  }
  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 tune = TUNES[currentBase];
  return 60 / (tune.bpm * (state.boss ? 1.2 : 1) * (major ? 1.07 : 1)) / 2;
}

function lead(kind: Lead, midi: number, dur: number, t: number): void {
  const f = hz(midi);
  switch (kind) {
    case 'celesta':
      bell(f, 0.9, 0.075, { ratio: 3.01, index: 1.2, at: t, dest: tuneBus.out });
      tone(f * 2, 0.25, 0.012, { at: t, dest: tuneBus.echo });
      break;
    case 'xylo':
      bell(f, 0.26, 0.12, { ratio: 4, index: 1, at: t, dest: tuneBus.out });
      tone(f, 0.14, 0.045, { type: 'triangle', at: t, dest: tuneBus.echo });
      break;
    case 'glock':
      bell(f, 0.7, 0.06, { ratio: 3.5, index: 1.4, at: t, dest: tuneBus.out });
      tone(f, 0.3, 0.025, { type: 'triangle', at: t, dest: tuneBus.echo });
      break;
    case 'box':
      bell(f, 1.3, 0.075, { ratio: 5.01, index: 0.8, at: t, dest: tuneBus.out });
      tone(f, 0.6, 0.03, { at: t, dest: tuneBus.echo });
      break;
    case 'theremin':
      tone(f, dur + 0.15, 0.07, { attack: 0.12, vibrato: 32, rate: 5.6, at: t, dest: tuneBus.out });
      tone(f * 2, dur, 0.008, { attack: 0.15, vibrato: 32, rate: 5.6, at: t, dest: tuneBus.echo });
      break;
    default:
      tone(f, dur + 0.06, 0.065, { type: 'triangle', attack: 0.03, vibrato: 14, rate: 5, at: t, dest: tuneBus.out });
      tone(f, 0.25, 0.02, { at: t, dest: tuneBus.echo });
  }
}

/** A plucked string: a quick triangle with a duller saw underneath. */
function pizz(midi: number, vol: number, t: number, len = 0.22): void {
  tone(hz(midi), len, vol, { type: 'triangle', at: t, dest: tuneBus.out });
  tone(hz(midi), len * 0.7, vol * 0.4, { type: 'sawtooth', at: t, dest: tuneBus.soft });
}

function playStep(n: number, t: number): void {
  const p = parse(currentBase);
  const tune = p.tune;
  const s = n % tune.steps;
  const bar = Math.floor(n / tune.steps) % p.notes.length;
  const sd = stepSeconds();
  const chord = p.chords[bar];
  // The bass sits between C2 and B2, the chord an octave and a half above.
  const bass = 36 + chord.root;
  const triad = [chord.root, chord.root + chord.third, chord.root + 7].map((x) => 55 + ((x + 5) % 12));

  const note = p.notes[bar][s];
  if (note) lead(tune.lead, note.midi, note.len * sd, t);

  switch (tune.backing) {
    case 'waltz':
      if (s === 0) pizz(bass, 0.16, t, 0.4);
      if (s === 2 || s === 4) for (const m of triad.slice(1)) pizz(m, 0.035, t, 0.16);
      break;
    case 'tiptoe':
      if (s === 0 || s === 4) pizz(bass, 0.15, t, 0.18);
      if (s === 2 || s === 6) pizz(bass + 7, 0.11, t, 0.16);
      if (s === 3 || s === 7) for (const m of triad.slice(1)) pizz(m, 0.022, t, 0.1);
      break;
    case 'drone':
      if (s === 0) {
        for (const d of [-6, 6]) tone(hz(bass), sd * tune.steps * 1.05, 0.05, { type: 'sawtooth', attack: 0.5, detune: d, at: t, dest: tuneBus.soft });
        tone(hz(bass), sd * tune.steps, 0.1, { attack: 0.4, at: t, dest: tuneBus.out });
      }
      if (s === 4) pizz(bass + 7, 0.07, t, 0.5);
      // Something drips in time.
      if (s === 6 && bar % 2 === 1) bell(hz(triad[2] + 24), 0.5, 0.025, { ratio: 3.5, index: 1, at: t, dest: tuneBus.echo });
      break;
    default:
      if (s === 0) pizz(bass, 0.16, t, 0.5);
      if (s === 3) pizz(bass + 7, 0.1, t, 0.4);
      if (s === 1 || s === 2 || s === 4 || s === 5) pizz(triad[(s + bar) % 3] + 12, 0.028, t, 0.18);
      // Wind in the trees, now and then.
      if (s === 0 && bar % 4 === 2) noise(sd * 12, 0.03, { type: 'bandpass', f0: 500, f1: 1100, q: 1.5, attack: sd * 5, at: t, dest: tuneBus.out });
  }

  // A held chord under the slower tunes.
  if (s === 0 && (tune.lead === 'celesta' || tune.lead === 'box' || tune.lead === 'ocarina')) {
    pad(triad, t, sd * tune.steps, 0.012);
  }

  // Nerves: a tick that gets louder as a shot comes near.
  if (state.tension > 0.25 && !state.boss) {
    noise(0.025, 0.05 * state.tension, { type: 'highpass', f0: 7000, at: t, dest: tuneBus.out });
    if (s % 2 === 0 && state.tension > 0.6) tone(hz(bass + 12), 0.08, 0.05 * state.tension, { type: 'square', at: t, dest: tuneBus.soft });
  }

  // The queen brings drums.
  if (state.boss) {
    const half = tune.steps / 2;
    if (s === 0 || (tune.steps === 8 && s === 5)) {
      tone(120, 0.2, 0.24, { slide: 0.3, at: t, dest: tuneBus.out });
      noise(0.02, 0.1, { type: 'highpass', f0: 2500, at: t, dest: tuneBus.out });
    }
    if (s === half || (tune.steps === 6 && s === 4)) {
      noise(0.13, 0.15, { type: 'bandpass', f0: 1800, q: 0.7, at: t, dest: tuneBus.out });
      tone(190, 0.09, 0.09, { type: 'triangle', slide: 0.6, at: t, dest: tuneBus.out });
    }
    noise(0.035, s % 2 ? 0.04 : 0.08, { type: 'highpass', f0: 6500, at: t, dest: tuneBus.out });
    if (s === 0 && bar % 2 === 0) {
      for (const d of [-7, 7]) tone(hz(bass), sd * tune.steps * 2, 0.03, { type: 'sawtooth', attack: 0.3, detune: d, at: t, dest: tuneBus.soft });
    }
    // A fill of toms into every fourth bar.
    if (bar % 4 === 3 && s >= tune.steps - 3) tone(200 - (s - (tune.steps - 3)) * 34, 0.14, 0.16, { slide: 0.6, at: t, dest: tuneBus.out });
  }
}

/** A quiet chord of detuned saws behind one filter. */
function pad(midis: number[], t: number, dur: number, vol: number): void {
  if (!ac || !live() || voices > maxVoices) return;
  const f = ac.createBiquadFilter();
  f.type = 'lowpass';
  f.Q.value = 0.7;
  f.frequency.value = 900;
  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.3);
  f.connect(g).connect(tuneBus.out);
  for (const m of midis) {
    for (const d of [-8, 8]) {
      const o = ac.createOscillator();
      o.type = 'sawtooth';
      o.frequency.value = hz(m);
      o.detune.value = d;
      o.connect(f);
      o.start(t);
      o.stop(t + dur + 0.35);
      track(o);
    }
  }
}