// Composition 4: crash. // // One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about // `fallAfter` seconds. A soft high voice follows the outer bob's height, so you hear it come down; // when the bob first swings through the bottom, a big low crash. From then on, every time the outer // bob crosses the vertical below the pivot there is a crash whose pitch rises with the height of // the crossing (continuous). Slight friction throughout, growing toward the end until it comes to // rest; the last crash rings out and the piece ends with the fade. import type { AudioEngine } from "../../core/audio.ts"; import { dbToGain } from "../../core/audio.ts"; import type { Piece } from "../../core/composition.ts"; import type { Params } from "../../core/params.ts"; import { mulberry32, randomSeed } from "../../core/rng.ts"; import { GlideVoice } from "../../instruments/glide.ts"; import { DRONE_INSTRUMENTS, NOTE_INSTRUMENTS } from "../../instruments/index.ts"; import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts"; import type { DroneInstrument, NoteHandle, NoteInstrument } from "../../instruments/types.ts"; import { midiToFreq } from "../../music/scales.ts"; import type { DoublePendulum, PendulumConfig } from "../../physics/doublePendulum.ts"; import { cssColor, fitCanvas } from "../shared/section.ts"; import { CRASH_BUDGET, crashCapacity, type VoiceCapacity } from "./capacity.ts"; import { DT, bob, inverted, nudgeForTip } from "./fall.ts"; const STREAMED = streamedModalInstruments(); const LOOKAHEAD = 0.15; const STREAM_PREBUFFER = 0.4; const TICK_MS = 25; const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest regardless const HISTORY_DT = 1 / 480; // piece-time spacing of stored states (drawing, blur, trail, voice) const BLUR_MAX_SAMPLES = 48; const BLUR_SPACING_PX = 2; const RING_S = 0.9; // crash ring lifetime // modal voice tone: the hum's mellow → reedy mapping (pickup position, spectral tilt) const VOICE_TONE = [ { target: "pickup", from: 0.15, to: 0.75 }, { target: "tilt", from: 0.3333, to: 0.5833 }, ]; const CLICK_RING_S = 0.35; // click ring lifetime interface Snap { t: number; th1: number; th2: number; } interface Crash { t: number; x: number; // bob position (pendulum units) y: number; strength: number; click?: boolean; // a pass by the pivot, not a crash } export function createCrashPiece(view: HTMLElement, params: () => Params): Piece { view.classList.add("c04"); const canvas = document.createElement("canvas"); view.append(canvas); let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 }; let pend: DoublePendulum | null = null; let prevX = 0; let E0 = 1; let vmax = 1; let history: Snap[] = []; let lastHistT = -Infinity; let crashes: Crash[] = []; let crashCount = 0; let clickCount = 0; let lastNote: { handle: NoteHandle; when: number } | null = null; let restAt: number | null = null; let audio: AudioEngine | null = null; let out: GainNode | null = null; let noteBus: GainNode | null = null; let inst: NoteInstrument | null = null; let instKey = ""; let clickBus: GainNode | null = null; let clickInst: NoteInstrument | null = null; let clickKey = ""; let voice: GlideVoice | null = null; // "soft sine" let modalVoice: DroneInstrument | null = null; // a held modal-synth note, glided with pitch bend let timer: number | undefined; let playing = false; let startToken = 0; let pieceStart = 0; let simPieceT = 0; let seedUsed = 0; let stoppedAt = 0; let stream = false; let simAhead = LOOKAHEAD; let nudge = { d: 0, ratio: 1, side: 1, tipsAt: 0 }; let capacity: VoiceCapacity | null = null; let checking = false; let voicesAllowed = 4; const piece: Piece = { get playing() { return playing; }, start, stop, draw, now, length: () => endTime(params()), readouts, notice, dispose() { stop(); view.classList.remove("c04"); view.replaceChildren(); }, }; function now(): number { if (!audio || !playing) return stoppedAt; return audio.ctx.currentTime - pieceStart; } // ── setup ── function makePendulum(P: Params, rand: (() => number) | null) { cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number }; const side = rand ? (rand() < 0.5 ? -1 : 1) : 1; const ratio = rand ? 0.6 + 0.8 * rand() : 1; const speed = P.speed as number; const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2)); nudge = { d: cal.nudge, ratio, side, tipsAt: cal.tipsAt / speed }; pend = inverted(cfg, cal.nudge, ratio, side); prevX = bob(cfg, pend.y)[0]; E0 = pend.energy(); vmax = Math.sqrt((2 * E0) / cfg.m2); history = []; crashes = []; crashCount = 0; clickCount = 0; lastNote = null; restAt = null; pushHistory(0); } function ensureInstrument() { if (!audio || !out) return; const P = params(); const ctx = audio.ctx; if (!noteBus) { noteBus = ctx.createGain(); noteBus.connect(out); } noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05); const name = P.crashInstrument as string; const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`; if (inst && instKey === key) return; inst?.dispose(); instKey = key; const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name]; inst = factory(ctx, noteBus, { custom: P.modalCustom as string, overrides: { voices: voicesAllowed } }); } /** The click for passes by the pivot: its own (cheap) instrument and level. */ function ensureClick() { if (!audio || !out) return; const P = params(); const ctx = audio.ctx; if (!clickBus) { clickBus = ctx.createGain(); clickBus.connect(out); } clickBus.gain.setTargetAtTime(dbToGain(P.clickLevel as number), ctx.currentTime, 0.05); const name = P.clickInstrument as string; const key = P.click ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : ""; if (clickKey === key && (clickInst || !key)) return; clickInst?.dispose(); clickInst = null; clickKey = key; if (!key) return; const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name]; clickInst = factory(ctx, clickBus, { custom: P.modalCustom as string }); } // ── transport ── async function start(a: AudioEngine, offset: number) { stop(); const token = ++startToken; audio = a; const P = params(); const ctx = a.ctx; stream = !!P.streamAudio; simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD; const wanted = Math.round(P.maxCrashes as number); voicesAllowed = wanted; if (P.deviceLimit) { checking = true; try { capacity = await crashCapacity(P, ctx.sampleRate, wanted); voicesAllowed = capacity.cap; } finally { checking = false; } if (token !== startToken) return; } seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed(); const rng = mulberry32(seedUsed); makePendulum(P, () => rng()); simPieceT = 0; if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at") out = ctx.createGain(); out.connect(a.input); ensureInstrument(); ensureClick(); const vName = P.voiceInstrument as string; if (P.voice && vName !== "soft sine" && DRONE_INSTRUMENTS[vName]) { const lo = P.voiceLow as number, hi = P.voiceHigh as number; const center = Math.round((lo + hi) / 2); modalVoice = DRONE_INSTRUMENTS[vName](ctx, out, { custom: P.voiceCustom as string, glide: { center, range: Math.max(1, Math.ceil(Math.max(hi - center, center - lo))) } }); } await Promise.all([inst?.ready, clickInst?.ready, modalVoice?.ready]); if (token !== startToken) return; pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset; if (modalVoice) modalVoice.start(ctx.currentTime + 0.05, midiToFreq(P.voiceHigh as number)); else if (P.voice) { voice = new GlideVoice(ctx, out); voice.start(ctx.currentTime + 0.05, midiToFreq(P.voiceHigh as number)); } playing = true; tick(); timer = window.setInterval(tick, TICK_MS); } function stop() { startToken++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; const wasPlaying = playing; if (playing) { stoppedAt = now(); playing = false; } if (!audio) return; const t = audio.ctx.currentTime; if (voice) { if (wasPlaying) voice.stop(t + 0.3, 0.3); voice.dispose(); voice = null; } if (modalVoice) { if (wasPlaying) modalVoice.stop(t + 0.3, 0.3); const mv = modalVoice; window.setTimeout(() => mv.dispose(), 600); modalVoice = null; } const o = out; if (o) { o.gain.setTargetAtTime(0, t, 0.05); window.setTimeout(() => o.disconnect(), 600); } inst?.dispose(); inst = null; instKey = ""; clickInst?.dispose(); clickInst = null; clickKey = ""; clickBus = null; noteBus = null; out = null; } // ── simulation ── function pushHistory(t: number) { if (!pend) return; history.push({ t, th1: pend.y[0], th2: pend.y[1] }); lastHistT = t; } /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */ function damping(P: Params, t: number): number { const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number))); const s = u * u * (3 - 2 * u); return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s; } function advanceTo(target: number, sound: boolean) { if (!pend) return; const P = params(); const speed = P.speed as number; const end = (P.freeTime as number) + (P.dampTime as number); const restE = P.restEnergy as number; const minY = (P.minDepth as number) * (cfg.l1 + cfg.l2); const p = pend; while (simPieceT < target) { const t0 = simPieceT; simPieceT += DT / speed; p.damping = damping(P, t0); p.step(DT); const [x, y] = bob(cfg, p.y); // the outer bob crossing the vertical below the pivot (not near the pivot itself: a folded // pendulum sweeping its bob through the middle doesn't count) if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) { // sweeping past the pivot: a click const f = prevX / (prevX - x); const tc = t0 + f * (simPieceT - t0); clickCount++; if (sound) click(tc, y, P); } else if (restAt === null && y > minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) { const f = prevX / (prevX - x); const tc = t0 + f * (simPieceT - t0); crashCount++; if (sound) crash(tc, y, P); else crashes.push({ t: tc, x: 0, y, strength: 0.5 }); } prevX = x; if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) { restAt = simPieceT; if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number); } if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT); } } function crash(tc: number, y: number, P: Params) { if (!audio || !inst || !pend) return; const when = pieceStart + tc; if (when < audio.ctx.currentTime - 0.02) return; const L = cfg.l1 + cfg.l2; // pitch: lowest with the bob straight down (y = L), highest at the shallowest crossing that counts const yMin = (P.minDepth as number) * L; const u = Math.max(0, Math.min(1, (L - y) / Math.max(1e-9, L - yMin))); const midi = (P.crashLow as number) + ((P.crashHigh as number) - (P.crashLow as number)) * Math.pow(u, P.crashCurve as number); // strength: the first crash is the accent; later ones follow the bob's speed const velocity = crashCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P); const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: 0.5 }); if (handle) lastNote = { handle, when }; crashes.push({ t: tc, x: 0, y, strength: velocity }); } /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */ function speedStrength(P: Params): number { if (!pend) return 0; const w = pend.derived(); const yv = pend.y; const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2; const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2; const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax)); const floor = P.loudFloor as number; return floor + (1 - floor) * Math.pow(xs, P.loudCurve as number); } function click(tc: number, y: number, P: Params) { if (!audio || !clickInst) return; const when = pieceStart + tc; if (when < audio.ctx.currentTime - 0.02) return; const velocity = (P.clickMaxVel as number) * speedStrength(P); clickInst.play({ when, freq: midiToFreq(P.clickPitch as number), velocity, pan: 0, duration: P.clickLength as number }); crashes.push({ t: tc, x: 0, y, strength: velocity, click: true }); } function endTime(P: Params): number { const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3; return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring; } function tick() { if (!audio || !playing || !pend) return; const P = params(); ensureInstrument(); const ctx = audio.ctx; const t = ctx.currentTime - pieceStart; const total = endTime(P); if (restAt !== null && t >= total) { stop(); stoppedAt = total; piece.onEnded?.(); return; } ensureClick(); advanceTo(t + simAhead, true); inst?.horizon?.(pieceStart + simPieceT); clickInst?.horizon?.(pieceStart + simPieceT); // the height voice: pitch from the outer bob's height now (not ahead) if (voice || modalVoice) { const s = stateAt(t); const L = cfg.l1 + cfg.l2; const yb = cfg.l1 * Math.cos(s.th1) + cfg.l2 * Math.cos(s.th2); // +L at the bottom, −L at the top const hn = (L - yb) / (2 * L); // 0 at the bottom, 1 at the top const midi = (P.voiceLow as number) + ((P.voiceHigh as number) - (P.voiceLow as number)) * hn; const e = Math.max(0, pend.energy()) / E0; // ramp in over the opening (from a fraction of full, smoothly), fade out at the end const ru = (P.voiceRamp as number) > 0 ? Math.max(0, Math.min(1, t / (P.voiceRamp as number))) : 1; const from = P.voiceRampFrom as number; const ramp = Math.min(1, Math.max(0, t) / 0.5) * (from + (1 - from) * ru * ru * (3 - 2 * ru)); const fadeOut = restAt !== null ? Math.max(0, Math.min(1, (total - t) / Math.max(0.1, P.finalFade as number))) : 1; const level = P.voice ? dbToGain(P.voiceLevel as number) * Math.pow(Math.min(1, e), P.voiceFollow as number) * ramp * fadeOut : 0; const freq = midiToFreq(midi); if (modalVoice) modalVoice.set(ctx.currentTime, { level, color: P.voiceTone as number, freq, normalize: true, timbre: VOICE_TONE }); else voice?.set(ctx.currentTime, freq, level, P.voiceBright as number, P.voiceVibrato as number); } // keep the states drawing, blur, trail and voice still need const keep = t - (P.trailLength as number) - 0.5; let i = 0; while (i < history.length - 2 && history[i + 1].t < keep) i++; if (i > 0) history.splice(0, i); while (crashes.length && crashes[0].t < t - RING_S - 1) crashes.shift(); } // ── drawing ── function stateAt(t: number): Snap { const n = history.length; if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI }; if (t <= history[0].t) return history[0]; if (t >= history[n - 1].t) return history[n - 1]; let lo = 0, hi = n - 1; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (history[mid].t <= t) lo = mid; else hi = mid; } const a = history[lo], b = history[hi]; const f = (t - a.t) / (b.t - a.t); return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) }; } let lastWall = 0; let frameDt = 1 / 60; function draw() { const P = params(); if (!pend) makePendulum(P, null); // preview: balanced straight up const t = now(); const wall = performance.now() / 1000; const dtw = wall - lastWall; lastWall = wall; if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1; const g = fitCanvas(canvas); const w = canvas.clientWidth, h = canvas.clientHeight; g.clearRect(0, 0, w, h); const fg = cssColor(view, "--fg"); const l1 = cfg.l1, l2 = cfg.l2; const scale = (0.46 * Math.min(w, h)) / (l1 + l2); const x0 = w / 2, y0 = h / 2; const pos = (s: { th1: number; th2: number }) => { const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1); return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)]; }; // trail of the outer bob, fading with age if (P.trails && history.length > 1) { const len = P.trailLength as number; const BANDS = 6; g.strokeStyle = fg; g.lineWidth = 1; g.lineJoin = g.lineCap = "round"; for (let band = 0; band < BANDS; band++) { const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS; g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS); g.beginPath(); let started = false; for (let i = 0; i < history.length; i += 2) { const hs = history[i]; if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue; if (hs.t > t) break; const [, , bx, by] = pos(hs); if (started) g.lineTo(bx, by); else g.moveTo(bx, by), (started = true); } g.stroke(); } g.globalAlpha = 1; } // crash rings, where each crash happened if (P.crashRings) { for (const c of crashes) { const age = t - c.t; const life = c.click ? CLICK_RING_S : RING_S; if (age < 0 || age > life) continue; const s = stateAt(c.t); const [, , bx, by] = pos(s); g.strokeStyle = fg; g.globalAlpha = (1 - age / life) * (0.4 + 0.6 * c.strength); g.lineWidth = c.click ? 1 : 1.2; g.beginPath(); const grow = c.click ? 14 : 60 * (0.5 + c.strength); g.arc(bx, by, (c.click ? 3 : 6) + grow * Math.sqrt(age / life), 0, 2 * Math.PI); g.stroke(); } g.globalAlpha = 1; } // the pendulum, with motion blur const shutter = playing ? (P.motionBlur as number) * frameDt : 0; let k = 1; if (shutter > 0) { let path = 0; let a = stateAt(t); for (let j = 1; j <= 8; j++) { const b = stateAt(t - (shutter * j) / 8); path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2)); a = b; } k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX))); } const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k); const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2); g.strokeStyle = fg; g.fillStyle = fg; g.lineWidth = 1.5; g.lineCap = "round"; g.globalAlpha = alpha; for (let i = 0; i < k; i++) { const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1))); g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.beginPath(); g.arc(x1, y1, r1, 0, 2 * Math.PI); g.moveTo(x2 + r2, y2); g.arc(x2, y2, r2, 0, 2 * Math.PI); g.fill(); } g.globalAlpha = 1; g.beginPath(); g.arc(x0, y0, 1.5, 0, 2 * Math.PI); g.fill(); } function notice(): string | null { if (checking) return "checking what this device can play…"; const P = params(); if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null; if (capacity.perVoice > CRASH_BUDGET) return "this device can't render the crashes in real time; expect glitches"; const want = Math.round(P.maxCrashes as number); return voicesAllowed < want ? `${voicesAllowed} overlapping crash${voicesAllowed > 1 ? "es" : ""} (of ${want}): reduced to what this device can play` : null; } function readouts(): Record { const P = params(); const t = now(); const free = P.freeTime as number, damp = P.dampTime as number; const phase = restAt !== null && simPieceT >= restAt ? "at rest" : crashCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling"; return { time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`, phase, energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–", crashes: String(crashCount), clicks: String(clickCount), nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`, friction: `${damping(P, t).toFixed(4)} /sim s`, "seed used": seedUsed ? String(seedUsed) : "–", "crash voices": capacity ? `${voicesAllowed} (one ringing crash: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed), "audio load": stream ? `renderer ${Math.round(100 * (inst?.load?.() ?? 0))}%, ${inst?.underruns?.() ?? 0} underruns` : `${Math.round(100 * (inst?.load?.() ?? 0))}%`, }; } return piece; }