// Composition 3: divergence. // // N double pendulums released together from rest at a wide angle, each outer arm offset by a tiny, // calibrated amount, so they swing as one and then visibly separate at about `separateAt` seconds, // and chaos takes over. Only the pendulums are shown, drawn from one pivot, with trails. // A note sounds whenever a bottom bob crosses the vertical through the pivot (either direction): // in "chord" mode each pendulum has its own note of a chord, so the opening is one chord that // breaks into arpeggios; in "motion" mode the pitch follows the bob's speed. Notes are panned // toward the side the bob is heading. After `freeTime` the pendulums are damped to rest over // `dampTime`; each one's last 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 { SharedReverb } from "../../instruments/reverb.ts"; import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts"; import type { NoteHandle, NoteInstrument, NoteInstrumentFactory } from "../../instruments/types.ts"; import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts"; import type { DoublePendulum, PendulumConfig } from "../../physics/doublePendulum.ts"; import { cssColor, fitCanvas } from "../shared/section.ts"; import { DT, bob, offsetForSeparation, released } from "./release.ts"; const STREAMED = streamedModalInstruments(); const LOOKAHEAD = 0.15; const STREAM_PREBUFFER = 0.4; const TICK_MS = 25; const MAX_SETTLE = 10; // s after the damping: count every pendulum as at rest regardless const HISTORY_DT = 1 / 120; // piece-time spacing of stored states (drawing and trails) interface Pend { index: number; p: DoublePendulum; prevX: number; // bottom bob's x at the previous step E0: number; // energy when the damping began lastNote: { handle: NoteHandle; when: number } | null; restAt: number | null; } interface Snapshot { t: number; s: Float64Array; // [θ1, θ2] per pendulum } export function createDivergencePiece(view: HTMLElement, params: () => Params): Piece { view.classList.add("c03"); const canvas = document.createElement("canvas"); view.append(canvas); let pends: Pend[] = []; let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 }; let history: Snapshot[] = []; let lastHistT = -Infinity; let audio: AudioEngine | null = null; let out: GainNode | null = null; let noteBus: GainNode | null = null; let reverb: SharedReverb | null = null; let panL: StereoPannerNode | null = null; let panR: StereoPannerNode | null = null; let instL: NoteInstrument | null = null; // notes moving left let instR: NoteInstrument | null = null; // notes moving right let instKey = ""; let timer: number | undefined; let playing = false; let startToken = 0; let pieceStart = 0; let simPieceT = 0; let seedUsed = 0; let noteCount = 0; let stoppedAt = 0; let restAll: number | null = null; let stream = false; let simAhead = LOOKAHEAD; let vmax0 = 1; // fastest possible bob speed at the release energy let release = { th1: 0, th2: 0, offset: 0, separatesAt: 0 }; const piece: Piece = { get playing() { return playing; }, start, stop, draw, now, length: () => endTime(params()), readouts, dispose() { stop(); view.classList.remove("c03"); view.replaceChildren(); }, }; function now(): number { if (!audio || !playing) return stoppedAt; return audio.ctx.currentTime - pieceStart; } // ── release ── function makePendulums(P: Params, rand: () => number | null) { cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number }; const deg = Math.PI / 180; const base = (P.releaseAngle as number) * deg; const j = (P.jitter as number) * deg; const r = rand(); const th1 = r === null ? base : base + (2 * r - 1) * j; const r2 = rand(); const th2 = r2 === null ? base : base + (2 * r2 - 1) * j; const speed = P.speed as number; const cal = offsetForSeparation(cfg, th1, th2, (P.separateAt as number) * speed, (P.sepThreshold as number) * (cfg.l1 + cfg.l2)); release = { th1, th2, offset: cal.offset, separatesAt: cal.separatesAt / speed }; const n = Math.max(1, Math.round(P.count as number)); pends = []; for (let i = 0; i < n; i++) { const d = n > 1 ? (i / (n - 1) - 0.5) * cal.offset : 0; const p = released(cfg, th1, th2, d); pends.push({ index: i, p, prevX: bob(cfg, p.y)[0], E0: 0, lastNote: null, restAt: null }); } vmax0 = Math.sqrt((2 * pends[0].p.energy()) / cfg.m2); history = []; lastHistT = -Infinity; pushHistory(0); } // ── instruments ── function factory(name: string): NoteInstrumentFactory { return (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name]; } /** Two copies of the instrument, panned left and right: a note goes to the side its bob is heading. */ function ensureInstruments() { if (!audio || !out) return; const P = params(); const ctx = audio.ctx; if (!noteBus) { noteBus = ctx.createGain(); noteBus.connect(out); reverb = new SharedReverb(ctx, noteBus, P.reverbTime as number); panL = ctx.createStereoPanner(); panR = ctx.createStereoPanner(); panL.connect(noteBus); panR.connect(noteBus); } noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05); const pan = P.directionPan as number; panL!.pan.setTargetAtTime(-pan, ctx.currentTime, 0.05); panR!.pan.setTargetAtTime(pan, ctx.currentTime, 0.05); const name = P.instrument as string; const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name; if (instL && instKey === key) return; instL?.dispose(); instR?.dispose(); instKey = key; const opts = { custom: P.modalCustom as string, effects: { send: reverb!.input } }; instL = factory(name)(ctx, panL!, opts); instR = factory(name)(ctx, panR!, opts); } // ── transport ── async function start(a: AudioEngine, offset: number) { stop(); const token = ++startToken; audio = a; const P = params(); const ctx = a.ctx; seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed(); const rng = mulberry32(seedUsed); makePendulums(P, () => rng()); simPieceT = 0; restAll = null; noteCount = 0; stream = !!P.streamAudio; simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD; if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at") out = ctx.createGain(); out.connect(a.input); ensureInstruments(); await Promise.all([instL?.ready, instR?.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); } instL?.dispose(); instR?.dispose(); instL = instR = null; instKey = ""; reverb?.dispose(); reverb = null; noteBus = panL = panR = null; out = null; } // ── simulation ── function pushHistory(t: number) { const s = new Float64Array(2 * pends.length); for (let i = 0; i < pends.length; i++) { s[2 * i] = pends[i].p.y[0]; s[2 * i + 1] = pends[i].p.y[1]; } history.push({ t, s }); lastHistT = t; } function advanceTo(target: number, sound: boolean) { const P = params(); const speed = P.speed as number; const free = P.freeTime as number, damp = P.dampTime as number; const curve = P.dampCurve as number, tau = P.tau as number; const restE = P.restEnergy as number; while (simPieceT < target) { const t0 = simPieceT; simPieceT += DT / speed; const u = (t0 - free) / damp; // damping progress (< 0: free swinging) for (const d of pends) { const p = d.p; if (u >= 0) { if (!p.controlled) { p.controlled = true; d.E0 = p.energy(); } p.tau = tau; p.eTarget = u < 1 ? d.E0 * Math.pow(1 - u, curve) : 0; // the energy controller fades out near zero energy; real friction settles the last of it p.damping = u >= 1 ? 1 / tau : 0; } p.step(DT); const x = bob(cfg, p.y)[0]; if (d.restAt === null && ((d.prevX < 0 && x >= 0) || (d.prevX > 0 && x <= 0))) { const f = d.prevX / (d.prevX - x); const tc = t0 + f * (simPieceT - t0); if (sound) playNote(d, tc, x > d.prevX ? 1 : -1, P); } d.prevX = x; if (d.restAt === null && u >= 1 && (p.energyNorm() < restE || simPieceT >= free + damp + MAX_SETTLE)) { d.restAt = simPieceT; if (sound && d.lastNote) d.lastNote.handle.hold(d.lastNote.when, P.finalHold as number, P.finalFade as number); } } if (restAll === null && pends.every((d) => d.restAt !== null)) restAll = simPieceT; if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT); } } /** The chord's pitches, low to high: the scale's notes in range (or an even spread if continuous). */ function chord(P: Params, n: number): number[] { const low = P.pitchLow as number, high = P.pitchHigh as number; const root = NOTE_NAMES.indexOf(P.root as string); let notes: number[] = []; if (P.scale === "continuous") notes = Array.from({ length: Math.max(n, 2) }, (_, i) => low + ((high - low) * i) / Math.max(1, Math.max(n, 2) - 1)); else for (let m = Math.ceil(low); m <= high; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) notes.push(m); if (!notes.length) notes = [quantize((low + high) / 2, P.scale as string, root)]; return Array.from({ length: n }, (_, i) => notes[n > 1 ? Math.round((i * (notes.length - 1)) / (n - 1)) : Math.floor(notes.length / 2)]); } function playNote(d: Pend, tc: number, dir: number, P: Params) { if (!audio) return; const when = pieceStart + tc; if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background) const inst = dir > 0 ? instR : instL; if (!inst) return; // bottom bob's speed at the crossing const y = d.p.y, w = d.p.derived(); const vx = cfg.l1 * Math.cos(y[0]) * w.w1 + cfg.l2 * Math.cos(y[1]) * w.w2; const vy = cfg.l1 * Math.sin(y[0]) * w.w1 + cfg.l2 * Math.sin(y[1]) * w.w2; const x = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax0)); const floor = P.loudFloor as number; const velocity = floor + (1 - floor) * Math.pow(x, P.loudCurve as number); const midi = P.pitchMode === "motion" ? quantize((P.pitchLow as number) + ((P.pitchHigh as number) - (P.pitchLow as number)) * x, P.scale as string, NOTE_NAMES.indexOf(P.root as string)) : chord(P, pends.length)[d.index]; const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.noteLength as number }); if (handle) d.lastNote = { handle, when }; noteCount++; } function endTime(P: Params): number { const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3; return (restAll ?? (P.freeTime as number) + (P.dampTime as number) + 1) + ring; } function tick() { if (!audio || !playing) return; const P = params(); ensureInstruments(); const t = audio.ctx.currentTime - pieceStart; const total = endTime(P); if (restAll !== null && t >= total) { stop(); stoppedAt = total; piece.onEnded?.(); return; } advanceTo(t + simAhead, true); for (const inst of [instL, instR]) inst?.horizon?.(pieceStart + simPieceT); // keep the states drawing and trails 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); } // ── drawing ── function colorOf(P: Params, i: number, n: number): string { const hue = (30 + (360 * i) / Math.max(1, n)) % 360; return `hsl(${hue.toFixed(0)} ${P.saturation}% 70%)`; } /** States at piece time t, interpolated between stored snapshots. */ function statesAt(t: number): Float64Array | null { const n = history.length; if (!n) return null; if (t <= history[0].t) return history[0].s; if (t >= history[n - 1].t) return history[n - 1].s; 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); const s = new Float64Array(a.s.length); for (let k = 0; k < s.length; k++) s[k] = a.s[k] + f * (b.s[k] - a.s[k]); return s; } function draw() { const P = params(); const t = now(); const g = fitCanvas(canvas); const w = canvas.clientWidth, h = canvas.clientHeight; g.clearRect(0, 0, w, h); if (!pends.length) makePendulums(P, () => null); // preview at the nominal release const n = pends.length; 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 px = (th1: number, th2: number): [number, number, number, number] => { const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1); return [x1, y1, x1 + scale * l2 * Math.sin(th2), y1 + scale * l2 * Math.cos(th2)]; }; // trails: the bottom bobs' recent paths, fading with age (drawn in a few alpha bands) if (P.trails && history.length > 1) { const len = P.trailLength as number; const BANDS = 6; g.lineWidth = P.trailWidth as number; g.lineJoin = g.lineCap = "round"; for (let i = 0; i < n; i++) { g.strokeStyle = colorOf(P, i, n); for (let band = 0; band < BANDS; band++) { const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS; g.globalAlpha = 0.7 * (1 - (band + 0.5) / BANDS); g.beginPath(); let started = false; for (const hs of history) { if (hs.t < aOld - HISTORY_DT || hs.t > aNew + HISTORY_DT) continue; if (hs.t > t) break; const [, , bx, by] = px(hs.s[2 * i], hs.s[2 * i + 1]); if (started) g.lineTo(bx, by); else g.moveTo(bx, by), (started = true); } g.stroke(); } } g.globalAlpha = 1; } // pendulums, all from the one pivot const s = statesAt(t); g.lineWidth = 1.5; g.lineCap = "round"; const r = P.bobSize as number; for (let i = n - 1; i >= 0; i--) { const th1 = s ? s[2 * i] : pends[i].p.y[0], th2 = s ? s[2 * i + 1] : pends[i].p.y[1]; const [x1, y1, x2, y2] = px(th1, th2); const col = colorOf(P, i, n); g.strokeStyle = col; g.fillStyle = col; g.globalAlpha = P.armAlpha as number; g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.globalAlpha = 1; g.beginPath(); g.arc(x1, y1, r * 0.8, 0, 2 * Math.PI); g.moveTo(x2 + r, y2); g.arc(x2, y2, r, 0, 2 * Math.PI); g.fill(); } g.fillStyle = cssColor(view, "--fg"); g.beginPath(); g.arc(x0, y0, 1.5, 0, 2 * Math.PI); g.fill(); } function readouts(): Record { const P = params(); const t = now(); const free = P.freeTime as number, damp = P.dampTime as number; const phase = restAll !== null && simPieceT >= restAll ? "at rest" : t < free ? "swinging" : t < free + damp ? "damping" : "settling"; const deg = 180 / Math.PI; const loads = [instL, instR].map((i) => i?.load?.() ?? 0); const under = [instL, instR].reduce((s, i) => s + (i?.underruns?.() ?? 0), 0); return { time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`, phase, "energy (mean)": pends.length ? (pends.reduce((s, d) => s + d.p.energyNorm(), 0) / pends.length).toFixed(4) : "–", notes: String(noteCount), release: `${(release.th1 * deg).toFixed(2)}°, ${(release.th2 * deg).toFixed(2)}°`, "offset (outermost)": `${release.offset.toExponential(2)} rad → separate at ${release.separatesAt.toFixed(1)} s`, "seed used": seedUsed ? String(seedUsed) : "–", "at rest": `${pends.filter((d) => d.restAt !== null).length} / ${pends.length}`, "audio load": stream ? `renderers ${Math.round(100 * Math.max(...loads))}% (busiest), ${under} underruns` : `${Math.round(100 * (loads[0] + loads[1]))}%`, }; } return piece; }