// Composition 1: a double pendulum and its Poincaré section. // // Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2). // Each crossing plays a note: θ2 → pitch, |p2| → loudness, θ2 → pan. // A hum runs throughout; its timbre follows the energy. // Energy is steered along an envelope: small → peak → hold → zero. // Notes stop at the end and the last one is held and faded. // Behind the live crossings, a worker draws the section's orbits at the current energy. 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 type { NoteHandle, NoteInstrument } from "../../instruments/types.ts"; import { midiToFreq } from "../../music/scales.ts"; import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts"; import { energyTarget } from "../shared/form.ts"; import { Hum } from "../shared/hum.ts"; import { noteFor } from "../shared/noteMap.ts"; import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts"; import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts"; const DT = 0.002; // simulation step (sim seconds) const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s) const TICK_MS = 25; const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless const HISTORY_DT = 1 / 960; // piece-time spacing of stored pendulum snapshots const BLUR_MAX_SAMPLES = 64; // cap on sub-frame positions drawn for motion blur const BLUR_SPACING_PX = 2; // target distance the tip moves between blur samples interface Snapshot { t: number; th1: number; th2: number; } interface Crossing { t: number; // piece time th2: number; // wrapped p2: number; // normalized } export function createPoincarePiece(view: HTMLElement, params: () => Params): Piece { view.classList.add("c01"); // one canvas: the Poincaré section, with the pendulum as an inset in its upper-left corner const plotCanvas = document.createElement("canvas"); view.append(plotCanvas); const plot = new SectionPlot(plotCanvas); const hum = new Hum(); let pend: DoublePendulum | null = null; let audio: AudioEngine | null = null; let notes: NoteInstrument | null = null; let noteKey = ""; // instrument name (+ custom settings) the current instance was built from let noteBus: GainNode | null = null; // notes level let startToken = 0; let out: GainNode | null = null; let timer: number | undefined; let playing = false; let pieceStart = 0; // AudioContext time of piece time 0 let simPieceT = 0; // piece time of the simulation state let seedUsed = 0; let noteCount = 0; let stoppedAt = 0; let history: Snapshot[] = []; let lastHistT = -Infinity; let points: Crossing[] = []; // final note let lastNote: { handle: NoteHandle; when: number } | null = null; // The ending comes from the simulation: once the energy target is zero and the pendulum's // energy falls below restEnergy it is at rest. No crossings register after that; the last // real note is held and faded, the hum fades with it, and the piece ends with the fade. let restAt: number | null = null; // piece time the pendulum came to rest // background portrait of the section at the current energy (throttled worker) const portrait = new PortraitLayer(() => now(), () => playing); const portraitSettings = (P: Params): PortraitSettings => ({ show: P.orbits as boolean, count: P.orbitCount as number, cpu: P.orbitCpu as number, life: P.orbitLife as number, band: P.orbitBand as number, minHold: P.orbitMinHold as number, maxPoints: P.orbitMaxPoints as number, xfade: P.orbitXfade as number, alpha: P.orbitAlpha as number, size: P.orbitSize as number, tracks: false, trackMax: 0, trackAlpha: 0, trackSize: 1, }); const postPortrait = (running: boolean) => { const P = params(); portrait.post(running, portraitSettings(P), pend ? pend.energyNorm() : 0, P.massRatio as number, P.lengthRatio as number, []); }; const piece: Piece = { get playing() { return playing; }, start, stop, draw, now, length: () => endTime(params()), readouts, dispose() { stop(); portrait.dispose(); view.classList.remove("c01"); view.replaceChildren(); }, }; function now(): number { if (!audio || !playing) return stoppedAt; return audio.ctx.currentTime - pieceStart; } // ── transport ── function makePendulum(P: Params): DoublePendulum { return new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number }); } 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(); pend = makePendulum(P); pend.randomize(energyTarget(P, 0), mulberry32(seedUsed)); pend.tau = P.tau as number; simPieceT = 0; history = []; lastHistT = -Infinity; points = []; portrait.reset(); // the worker starts a fresh portrait noteCount = 0; lastNote = null; restAt = null; // fast-forward silently to the start offset (author "start at") if (offset > 0) advanceTo(offset, false); out = ctx.createGain(); out.connect(a.input); ensureInstruments(); await Promise.all([notes?.ready, hum.ready]); // e.g. the modal-synth worklet loading if (token !== startToken) return; // stopped or restarted meanwhile pieceStart = ctx.currentTime + 0.1 - offset; hum.start(ctx, P); playing = true; tick(); timer = window.setInterval(tick, TICK_MS); } function ensureInstruments() { if (!audio || !out) return; const P = params(); if (!noteBus) { noteBus = audio.ctx.createGain(); noteBus.connect(out); } noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05); const name = P.noteInstrument as string; const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name; if (!notes || noteKey !== key) { notes?.dispose(); noteKey = key; notes = NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string }); } hum.ensure(audio.ctx, out, P, playing); } function stop() { startToken++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; const wasPlaying = playing; if (playing) { stoppedAt = now(); playing = false; postPortrait(false); } // release the audio graph (also when a start is still waiting for its instrument to load) if (!audio) return; const t = audio.ctx.currentTime; hum.release(audio.ctx, wasPlaying); const o = out; if (o) { o.gain.setTargetAtTime(0, t, 0.05); window.setTimeout(() => o.disconnect(), 600); } notes?.dispose(); notes = null; noteKey = ""; noteBus = null; out = null; } // ── simulation ── /** Simulate up to piece time `target`; schedule notes if `sound`. */ function advanceTo(target: number, sound: boolean) { if (!pend) return; const P = params(); pend.cfg.m2 = P.massRatio as number; pend.cfg.l2 = P.lengthRatio as number; pend.tau = P.tau as number; const speed = P.speed as number; const duration = P.duration as number; const restE = P.restEnergy as number; const y = pend.y; let prev = wrapAngle(y[0]); let prevTh2 = y[1]; let prevP2 = y[3]; let prevT = simPieceT; while (simPieceT < target) { pend.eTarget = energyTarget(P, simPieceT) * pend.vTop; pend.step(DT); simPieceT += DT / speed; const cur = wrapAngle(y[0]); if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) { const f = -prev / (cur - prev); const c: Crossing = { t: prevT + f * (simPieceT - prevT), th2: wrapAngle(prevTh2 + f * (y[1] - prevTh2)), p2: (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale, }; points.push(c); if (sound) playNote(c, P); } if (restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) { restAt = simPieceT; if (sound) holdFinalNote(P); } prev = cur; prevTh2 = y[1]; prevP2 = y[3]; prevT = simPieceT; if (simPieceT - lastHistT >= HISTORY_DT) { history.push({ t: simPieceT, th1: y[0], th2: y[1] }); lastHistT = simPieceT; } } } function playNote(c: Crossing, P: Params) { if (!audio || !notes) return; const when = pieceStart + c.t; if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background) const { midi, velocity, pan } = noteFor(P, c.th2, c.p2); const freq = midiToFreq(midi); const handle = notes.play({ when, freq, velocity, pan, duration: P.noteLength as number }); if (handle) lastNote = { handle, when }; noteCount++; } /** Let the last real note ring: sustain it for finalHold, then fade over finalFade. */ function holdFinalNote(P: Params) { if (!lastNote) return; lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number); } /** Piece time at which everything has faded: known once the pendulum is at rest, estimated before. */ function endTime(P: Params): number { const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3; return (restAt ?? (P.duration as number) + 0.5) + ring; } function tick() { if (!audio || !pend || !playing) return; const P = params(); ensureInstruments(); const ctx = audio.ctx; const t = ctx.currentTime - pieceStart; const total = endTime(P); if (restAt !== null && t >= total) { stop(); stoppedAt = total; piece.onEnded?.(); return; } advanceTo(t + LOOKAHEAD, true); postPortrait(true); hum.update(ctx, P, pend.energyNorm(), t, restAt !== null ? total : null); // trim history to what drawing still needs let i = 0; while (i < history.length - 1 && history[i + 1].t <= t - 0.1) i++; if (i > 0) history.splice(0, i); } // ── drawing ── function color(name: string): string { return cssColor(view, name); } /** Pendulum angles at piece time t, interpolated between stored snapshots. */ function stateAt(t: number): { th1: number; th2: number } { const n = history.length; if (!n) return pend ? { th1: pend.y[0], th2: pend.y[1] } : { th1: 0, th2: 0 }; if (t <= history[0].t) return history[0]; if (t >= history[n - 1].t) return history[n - 1]; let lo = 0, hi = n - 1; // history[lo].t <= t < history[hi].t 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 { th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) }; } let lastDrawWall = 0; let frameDt = 1 / 60; // smoothed display frame interval (s) /** * The pendulum as an inset in the plot's upper-left corner (outside the energetically allowed * region of the section most of the time), drawn as before: solid arms and filled bobs. * Motion blur: several faint positions spread over the last frame interval. */ function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number) { const opacity = P.pendulumAlpha as number; if (opacity <= 0) return; const shutter = playing ? (P.motionBlur as number) * frameDt : 0; const l1 = 1, l2 = P.lengthRatio as number; const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2; // inset radius const scale = (0.9 * R) / (l1 + l2); const x0 = 8 + R, y0 = 8 + R; // pivot // enough samples that the tip moves ~BLUR_SPACING_PX between them 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))); } // per-sample alpha so a still pendulum still draws (nearly) fully opaque const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k)); const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number); const fg = color("--fg"); g.strokeStyle = fg; g.fillStyle = fg; g.lineWidth = 1.5; g.lineCap = "round"; g.globalAlpha = alpha; for (let i = 0; i < k; i++) { const { th1, th2 } = stateAt(t - (shutter * i) / Math.max(1, k - 1)); const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1); const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2); 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 = opacity; g.beginPath(); g.arc(x0, y0, 1.5, 0, 2 * Math.PI); g.fill(); g.globalAlpha = 1; } function draw() { const P = params(); const t = now(); const wall = performance.now() / 1000; const dtw = wall - lastDrawWall; lastDrawWall = wall; if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1; const fg = color("--fg"); const dim = color("--dim"); // Poincaré section { const f = plot.begin(P, pend ? pend.energyNorm() : null, pend?.cfg ?? null, pend?.vTop ?? 1, dim); const { g, w, h } = f; portrait.draw(f, t, portraitSettings(P), fg, () => fg); // the pendulum's own crossings const fade = P.fade as number; const size = P.pointSize as number; let drop = 0; while (drop < points.length && t - points[drop].t > 4.6 * fade) drop++; if (drop > 0) points.splice(0, drop); for (const c of points) { const age = t - c.t; if (age < 0) break; // not sounded yet drawCrossing(f, c.th2, c.p2, age, fade, size, fg); } drawPendulum(g, w, h, P, t); } } function readouts(): Record { const P = params(); const t = now(); return { time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`, "energy target": energyTarget(P, t).toFixed(4), energy: pend ? pend.energyNorm().toFixed(4) : "–", notes: String(noteCount), "seed used": seedUsed ? String(seedUsed) : "–", hum: hum.describe(), "orbit portrait": portrait.describe(), }; } return piece; }