// 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 { DRONE_INSTRUMENTS, NOTE_INSTRUMENTS } from "../../instruments/index.ts"; import type { DroneInstrument, NoteHandle, NoteInstrument } from "../../instruments/types.ts"; import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts"; import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts"; import { energyTarget } from "./form.ts"; import type { OrbitBatch, OrbitConfig } from "./orbitWorker.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); 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 humKey = ""; let startToken = 0; let hum: DroneInstrument | null = null; 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[] = []; let thR = Math.PI; // plot half-ranges (smoothed) let pR = 1; // 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 orbit portraits (worker). Each portrait is at one fixed energy; when a new one // arrives, the older ones are retired and crossfade out. interface Portrait { gen: number; energy: number; pts: number[]; // [θ2, p2, …] retiredAt: number | null; } let worker: Worker | null = null; let portraits: Portrait[] = []; let resetOrbits = false; let latestGen = 0; let ignoreBelow = 0; // batches from portraits started before the last reset let orbitRate = 0; // points per second, smoothed, for the readout let orbitNew = 0; let orbitRateT = 0; const piece: Piece = { get playing() { return playing; }, start, stop, draw, now, length: () => endTime(params()), readouts, dispose() { stop(); worker?.terminate(); worker = null; view.classList.remove("c01"); view.replaceChildren(); }, }; function now(): number { if (!audio || !playing) return stoppedAt; return audio.ctx.currentTime - pieceStart; } // ── orbits ── function ensureWorker(): Worker { if (!worker) { worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" }); worker.onmessage = (ev: MessageEvent) => { if (!playing) return; const { gen, energy, pts } = ev.data; latestGen = Math.max(latestGen, gen); if (gen < ignoreBelow) return; let cur = portraits[portraits.length - 1]; if (!cur || gen > cur.gen) { const t = now(); for (const p of portraits) p.retiredAt ??= t; cur = { gen, energy, pts: [], retiredAt: null }; portraits.push(cur); } else if (gen < cur.gen) return; // stale batch from before a reset for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]); orbitNew += pts.length / 2; }; } return worker; } function postOrbitConfig(running: boolean) { const P = params(); if (!P.orbits && !worker) return; const msg: OrbitConfig = { running: running && (P.orbits as boolean), reset: resetOrbits, energy: pend ? pend.energyNorm() : 0, m2: P.massRatio as number, l2: P.lengthRatio as number, count: Math.round(P.orbitCount as number), life: P.orbitLife as number, band: P.orbitBand as number, minHold: P.orbitMinHold as number, maxPoints: P.orbitMaxPoints as number, cpu: P.orbitCpu as number, }; resetOrbits = false; ensureWorker().postMessage(msg); } // ── 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 = []; // the worker starts a fresh portrait portraits = []; ignoreBelow = latestGen + 1; resetOrbits = true; 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.currentTime + 0.05, midiToFreq(P.humPitch as number)); 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 }); } const hName = P.humInstrument as string; const hKey = hName === "modal: custom" ? `${hName}\n${P.humCustom}` : hName; if (!hum || humKey !== hKey) { const old = hum; humKey = hKey; hum = DRONE_INSTRUMENTS[hName](audio.ctx, out, { custom: P.humCustom as string }); if (old && playing) { // switched while playing: crossfade to the new hum const t = audio.ctx.currentTime; old.stop(t + 0.5, 0.5); window.setTimeout(() => old.dispose(), 1500); const h = hum; void (h.ready ?? Promise.resolve()).then(() => h === hum && h.start(audio!.ctx.currentTime + 0.05, midiToFreq(P.humPitch as number))); } } } function stop() { startToken++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; const wasPlaying = playing; if (playing) { stoppedAt = now(); playing = false; postOrbitConfig(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; if (wasPlaying) hum?.stop(t + 0.3, 0.3); // a hum is only started once playing const o = out; if (o) { o.gain.setTargetAtTime(0, t, 0.05); window.setTimeout(() => o.disconnect(), 600); } const h = hum; window.setTimeout(() => h?.dispose(), 600); hum = null; humKey = ""; 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 range = P.thetaRange as number; let u = P.pitchSource === "absolute" ? Math.min(1, Math.abs(c.th2) / range) : Math.max(0, Math.min(1, 0.5 + (0.5 * c.th2) / range)); if (P.invertPitch) u = 1 - u; u = Math.pow(u, P.pitchCurve as number); const low = P.pitchLow as number, high = P.pitchHigh as number; const root = NOTE_NAMES.indexOf(P.root as string); const midi = quantize(low + (high - low) * u, P.scale as string, root); const x = Math.min(1, Math.abs(c.p2) / (P.p2Ref as number)); const floor = P.loudFloor as number; const vel = floor + (1 - floor) * Math.pow(x, P.loudCurve as number); const freq = midiToFreq(midi); const pan = (P.panAmount as number) * Math.max(-1, Math.min(1, c.th2 / Math.PI)); const handle = notes.play({ when, freq, velocity: vel, 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); postOrbitConfig(true); // hum const e = pend.energyNorm(); const peak = P.energyPeak as number; const rel = Math.max(0, Math.min(1, e / peak)); const e0 = Math.min(P.energyStart as number, 0.999 * peak); const colorBase = P.humColorMode === "log" ? Math.max(0, Math.min(1, Math.log(Math.max(e, 1e-12) / e0) / Math.log(peak / e0))) : rel; const fadeIn = P.humFadeIn as number; const fadeOut = P.humFadeOut as number; // the hum's fade-out ends with the last note's fade (only once the pendulum is at rest) const fade = Math.min(1, fadeIn > 0 ? t / fadeIn : 1, restAt !== null && fadeOut > 0 ? (total - t) / fadeOut : 1); const follow = P.humFollow as number; const level = dbToGain(P.humLevel as number) * Math.max(0, fade) * (1 - follow + follow * rel); hum?.set(ctx.currentTime, { level, color: Math.pow(colorBase, P.humColorCurve as number), freq: midiToFreq(P.humPitch as number), normalize: P.humNormalize as boolean, timbre: [1, 2] .filter((i) => P[`humTarget${i}`] !== "none") .map((i) => ({ target: P[`humTarget${i}`] as string, from: P[`humFrom${i}`] as number, to: P[`humTo${i}`] as number })), }); // 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 fit(c: HTMLCanvasElement): CanvasRenderingContext2D { const dpr = window.devicePixelRatio || 1; const w = Math.round(c.clientWidth * dpr); const h = Math.round(c.clientHeight * dpr); if (c.width !== w || c.height !== h) { c.width = w; c.height = h; } const g = c.getContext("2d")!; g.setTransform(dpr, 0, 0, dpr, 0, 0); return g; } function color(name: string): string { return getComputedStyle(view).getPropertyValue(name).trim() || "#ccc"; } /** 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 g = fit(plotCanvas); const w = plotCanvas.clientWidth, h = plotCanvas.clientHeight; g.clearRect(0, 0, w, h); let thT = Math.PI, pT = P.plotP as number; if (P.plotZoom === "fit energy" && pend) { // exact extent of the energetically allowed region of the section (θ1 = 0): // p2² ≤ 2·m2·l2²·(E − V(θ2)), so |p2|max = √(2e) in normalized units, // and |θ2| ≤ acos(1 − E/(m2·g·l2)). const e = Math.max(1e-6, pend.energyNorm()); const E = e * pend.vTop; const m2 = pend.cfg.m2, l2 = pend.cfg.l2, gr = pend.cfg.g; const th = E >= 2 * m2 * gr * l2 ? Math.PI : Math.acos(1 - E / (m2 * gr * l2)); thT = Math.min(Math.PI, 1.08 * th); pT = 1.08 * Math.sqrt(2 * e); } // ease toward the target range with a time constant, in log space so zooming in and out feel alike const ease = dtw > 0 && dtw < 0.5 ? 1 - Math.exp(-dtw / Math.max(0.01, P.zoomSmooth as number)) : 1; thR *= Math.exp(ease * Math.log(thT / thR)); pR *= Math.exp(ease * Math.log(pT / pR)); const pad = 8; const kx = (w / 2 - pad) / thR, ky = (h / 2 - pad) / pR; const sx = (th: number) => w / 2 + kx * th; const sy = (p: number) => h / 2 - ky * p; g.strokeStyle = dim; g.lineWidth = 1; g.beginPath(); g.moveTo(pad, h / 2); g.lineTo(w - pad, h / 2); g.moveTo(w / 2, pad); g.lineTo(w / 2, h - pad); g.stroke(); // background orbit portraits if (P.orbits) { const xfade = P.orbitXfade as number; const alpha = P.orbitAlpha as number; const sz = P.orbitSize as number; portraits = portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < xfade); g.fillStyle = fg; for (const p of portraits) { g.globalAlpha = alpha * (p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / xfade)); g.beginPath(); const d = p.pts; for (let i = 0; i < d.length; i += 2) g.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz); g.fill(); } g.globalAlpha = 1; } // 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); g.fillStyle = fg; for (const c of points) { const age = t - c.t; if (age < 0) break; // not sounded yet g.globalAlpha = Math.exp(-age / fade); g.beginPath(); g.arc(sx(c.th2), sy(c.p2), size / 2, 0, 2 * Math.PI); g.fill(); if (age < 0.4) { // brief ring on the newest crossings g.globalAlpha = 1 - age / 0.4; g.strokeStyle = fg; g.beginPath(); g.arc(sx(c.th2), sy(c.p2), size / 2 + 3 + 12 * age, 0, 2 * Math.PI); g.stroke(); } } g.globalAlpha = 1; drawPendulum(g, w, h, P, t); } } function readouts(): Record { const P = params(); const t = now(); const wall = performance.now() / 1000; if (wall - orbitRateT > 1) { orbitRate = orbitNew / (wall - orbitRateT || 1); orbitNew = 0; orbitRateT = wall; } 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": (() => { const p = portraits.find((q) => q.retiredAt === null); return p ? `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts, ${Math.round(orbitRate)}/s` : "–"; })(), }; } return piece; }