// Composition 4: descent. // // One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about // `fallAfter` seconds. Short piano notes mark the outer bob's height as it passes a ladder of // levels (higher level, higher note), so you hear it come down. Whenever the pendulum is fully // extended (the arms pass through a straight line, at any angle) there is an extension note: a // short violin note at a fixed pitch, its strength from the bob's speed, the first one accented. // The outer bob sweeping past the pivot (a folded pendulum) is a click. Slight friction // throughout, growing toward the end until it comes to rest; the last extension note 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 { NOTE_INSTRUMENTS } from "../../instruments/index.ts"; import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts"; import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts"; import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts"; import { type DoublePendulum, type PendulumConfig, wrapAngle } from "../../physics/doublePendulum.ts"; import { cssColor, fitCanvas } from "../shared/section.ts"; import { OVERLAP_BUDGET, overlapCapacity, 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) const BLUR_MAX_SAMPLES = 48; const BLUR_SPACING_PX = 2; const RING_S = 0.9; // extension-note ring lifetime const EXT_ARM = 0.05; // rad: the arms must bend this far from straight before the next extension note const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it const CLICK_RING_S = 0.35; // click ring lifetime interface Snap { t: number; th1: number; th2: number; } interface Mark { t: number; x: number; // bob position (pendulum units) y: number; strength: number; click?: boolean; // a pass by the pivot, not an extension note } export function createDescentPiece(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 marks: Mark[] = []; let extCount = 0; // extension notes so far let prevPhi = 0; // relative arm angle at the previous step let extArmed = false; 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 = ""; // height notes: levels (MIDI pitches, ascending) and where the bob is among them let heightBus: GainNode | null = null; let heightInst: NoteInstrument | null = null; let heightKey = ""; let levels: number[] = []; let levelIdx = 0; // number of levels below the bob's current pitch position let heightCount = 0; 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 = []; marks = []; extCount = 0; prevPhi = wrapAngle(pend.y[1] - pend.y[0]); extArmed = false; 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.extInstrument 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 }); } /** Short notes at height levels: their own instrument and level. */ function ensureHeight() { if (!audio || !out) return; const P = params(); const ctx = audio.ctx; if (!heightBus) { heightBus = ctx.createGain(); heightBus.connect(out); } heightBus.gain.setTargetAtTime(dbToGain(P.heightLevel as number), ctx.currentTime, 0.05); const name = P.heightInstrument as string; const key = P.heightNotes ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : ""; if (heightKey === key && (heightInst || !key)) return; heightInst?.dispose(); heightInst = null; heightKey = key; if (!key) return; const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name]; heightInst = factory(ctx, heightBus, { custom: P.modalCustom as string }); } /** The ladder: scale notes between the low and high pitch, every `step`-th. */ function makeLevels(P: Params): number[] { const lo = P.heightLow as number, hi = P.heightHigh as number; const root = NOTE_NAMES.indexOf(P.root as string); const all: number[] = []; if (P.scale === "continuous") for (let m = Math.ceil(lo); m <= hi; m++) all.push(m); else for (let m = Math.ceil(lo); m <= hi; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) all.push(m); const step = Math.max(1, Math.round(P.heightStep as number)); return all.filter((_, i) => i % step === 0); } /** The bob's height as a pitch position on the ladder (bottom → heightLow, top → heightHigh). */ function pitchPos(P: Params, y: number): number { const L = cfg.l1 + cfg.l2; const hn = (L - y) / (2 * L); // 0 at the bottom, 1 at the top return (P.heightLow as number) + ((P.heightHigh as number) - (P.heightLow as number)) * hn; } function countBelow(p: number): number { let i = 0; while (i < levels.length && levels[i] < p) i++; return i; } // ── 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.maxOverlap as number); voicesAllowed = wanted; if (P.deviceLimit) { checking = true; try { capacity = await overlapCapacity(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()); levels = makeLevels(P); levelIdx = countBelow(pitchPos(P, bob(cfg, pend!.y)[1])); heightCount = 0; simPieceT = 0; if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at") out = ctx.createGain(); out.connect(a.input); ensureInstrument(); ensureClick(); ensureHeight(); await Promise.all([inst?.ready, clickInst?.ready, heightInst?.ready]); if (token !== startToken) return; pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset; playing = true; tick(); timer = window.setInterval(tick, TICK_MS); } function stop() { startToken++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; if (playing) { stoppedAt = now(); playing = false; } if (!audio) return; const t = audio.ctx.currentTime; 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; heightInst?.dispose(); heightInst = null; heightKey = ""; heightBus = 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); if (restAt === null && levels.length) heightLevels(t0, pitchPos(P, y), P, sound); // the outer bob sweeping past the pivot (crossing the vertical close to it): a click if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) { const f = prevX / (prevX - x); const tc = t0 + f * (simPieceT - t0); clickCount++; if (sound) click(tc, y, P); } prevX = x; // full extension: the arms pass through a straight line (relative angle crosses 0, not ±π), // at any orientation. It re-arms once the arms bend at least EXT_ARM away from straight. const phi = wrapAngle(p.y[1] - p.y[0]); if (Math.abs(phi) > EXT_ARM) extArmed = true; if (restAt === null && extArmed && ((prevPhi < 0 && phi >= 0) || (prevPhi > 0 && phi <= 0)) && Math.abs(phi - prevPhi) < Math.PI) { const f = prevPhi / (prevPhi - phi); const tc = t0 + f * (simPieceT - t0); extArmed = false; extCount++; if (sound) extensionNote(tc, P); else marks.push({ t: tc, x, y, strength: 0.5 }); } prevPhi = phi; 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); } } /** Notes for every level the bob's pitch position has passed since the last step (with hysteresis). */ function heightLevels(t0: number, pos: number, P: Params, sound: boolean) { const h = HEIGHT_HYST * (levels.length > 1 ? (levels[levels.length - 1] - levels[0]) / (levels.length - 1) : 1); // moving up past levels[levelIdx] while (levelIdx < levels.length && pos > levels[levelIdx] + h) { if (sound) heightNote(t0, levels[levelIdx], P); levelIdx++; } // moving down past levels[levelIdx − 1] while (levelIdx > 0 && pos < levels[levelIdx - 1] - h) { levelIdx--; if (sound) heightNote(t0, levels[levelIdx], P); } } function heightNote(t0: number, midi: number, P: Params) { if (!audio || !heightInst || !pend) return; const tc = t0 + DT / (P.speed as number); const when = pieceStart + tc; if (when < audio.ctx.currentTime - 0.02) return; // strength: ramps in over the opening, fades with the energy at the end const ru = (P.heightRamp as number) > 0 ? Math.max(0, Math.min(1, tc / (P.heightRamp as number))) : 1; const from = P.heightRampFrom as number; const ramp = from + (1 - from) * ru * ru * (3 - 2 * ru); const e = Math.min(1, Math.max(0, pend.energy()) / E0); const velocity = (P.heightVel as number) * ramp * Math.pow(e, P.heightFollow as number); heightInst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.heightLength as number }); heightCount++; } function extensionNote(tc: number, P: Params) { if (!audio || !inst || !pend) return; const when = pieceStart + tc; if (when < audio.ctx.currentTime - 0.02) return; const midi = P.extPitch as number; // strength: the first extension note is the accent; later ones follow the bob's speed const velocity = extCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P); const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.extLength as number }); if (handle) lastNote = { handle, when }; const [bx, by] = bob(cfg, pend.y); marks.push({ t: tc, x: bx, y: by, 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 }); marks.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(); ensureHeight(); advanceTo(t + simAhead, true); for (const i of [inst, clickInst, heightInst]) i?.horizon?.(pieceStart + simPieceT); // keep the states drawing, blur and trail 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 (marks.length && marks[0].t < t - RING_S - 1) marks.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; } // rings, where each extension note (and click) happened if (P.rings) { for (const c of marks) { 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 > OVERLAP_BUDGET) return "this device can't render the extension notes in real time; expect glitches"; const want = Math.round(P.maxOverlap as number); return voicesAllowed < want ? `${voicesAllowed} overlapping note${voicesAllowed > 1 ? "s" : ""} (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" : extCount === 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` : "–", "extension notes": String(extCount), clicks: String(clickCount), "height notes": String(heightCount), 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) : "–", "overlapping notes": capacity ? `${voicesAllowed} (one ringing note: ${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; }