1// Composition 1: a double pendulum and its Poincaré section.
2//
3// Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2).
4// Each crossing plays a note: θ2 → pitch, |p2| → loudness, θ2 → pan.
5// A hum runs throughout; its timbre follows the energy.
6// Energy is steered along an envelope: small → peak → hold → zero.
7// Notes stop at the end and the last one is held and faded.
8// Behind the live crossings, a worker draws the section's orbits at the current energy.
10import type { AudioEngine } from "../../core/audio.ts";
11import { dbToGain } from "../../core/audio.ts";
12import type { Piece } from "../../core/composition.ts";
13import type { Params } from "../../core/params.ts";
14import { mulberry32, randomSeed } from "../../core/rng.ts";
15import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
16import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
17import { midiToFreq } from "../../music/scales.ts";
18import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
19import { energyTarget } from "../shared/form.ts";
20import { Hum } from "../shared/hum.ts";
21import { noteFor } from "../shared/noteMap.ts";
22import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
23import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
25const DT = 0.002; // simulation step (sim seconds)
26const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
27const TICK_MS = 25;
28const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
29const HISTORY_DT = 1 / 960; // piece-time spacing of stored pendulum snapshots
30const BLUR_MAX_SAMPLES = 64; // cap on sub-frame positions drawn for motion blur
31const BLUR_SPACING_PX = 2; // target distance the tip moves between blur samples
33interface Snapshot {
34 t: number;
35 th1: number;
36 th2: number;
37}
39interface Crossing {
40 t: number; // piece time
41 th2: number; // wrapped
42 p2: number; // normalized
43}
45export function createPoincarePiece(view: HTMLElement, params: () => Params): Piece {
46 view.classList.add("c01");
47 // one canvas: the Poincaré section, with the pendulum as an inset in its upper-left corner
48 const plotCanvas = document.createElement("canvas");
49 view.append(plotCanvas);
50 const plot = new SectionPlot(plotCanvas);
51 const hum = new Hum();
53 let pend: DoublePendulum | null = null;
54 let audio: AudioEngine | null = null;
55 let notes: NoteInstrument | null = null;
56 let noteKey = ""; // instrument name (+ custom settings) the current instance was built from
57 let noteBus: GainNode | null = null; // notes level
58 let startToken = 0;
59 let out: GainNode | null = null;
60 let timer: number | undefined;
61 let playing = false;
62 let pieceStart = 0; // AudioContext time of piece time 0
63 let simPieceT = 0; // piece time of the simulation state
64 let seedUsed = 0;
65 let noteCount = 0;
66 let stoppedAt = 0;
67 let history: Snapshot[] = [];
68 let lastHistT = -Infinity;
69 let points: Crossing[] = [];
70 // final note
71 let lastNote: { handle: NoteHandle; when: number } | null = null;
72 // The ending comes from the simulation: once the energy target is zero and the pendulum's
73 // energy falls below restEnergy it is at rest. No crossings register after that; the last
74 // real note is held and faded, the hum fades with it, and the piece ends with the fade.
75 let restAt: number | null = null; // piece time the pendulum came to rest
77 // background portrait of the section at the current energy (throttled worker)
78 const portrait = new PortraitLayer(() => now(), () => playing);
79 const portraitSettings = (P: Params): PortraitSettings => ({
80 show: P.orbits as boolean,
81 count: P.orbitCount as number,
82 cpu: P.orbitCpu as number,
83 life: P.orbitLife as number,
84 band: P.orbitBand as number,
85 minHold: P.orbitMinHold as number,
86 maxPoints: P.orbitMaxPoints as number,
87 xfade: P.orbitXfade as number,
88 alpha: P.orbitAlpha as number,
89 size: P.orbitSize as number,
90 tracks: false,
91 trackMax: 0,
92 trackAlpha: 0,
93 trackSize: 1,
94 });
95 const postPortrait = (running: boolean) => {
96 const P = params();
97 portrait.post(running, portraitSettings(P), pend ? pend.energyNorm() : 0, P.massRatio as number, P.lengthRatio as number, []);
98 };
100 const piece: Piece = {
101 get playing() {
102 return playing;
103 },
104 start,
105 stop,
106 draw,
107 now,
108 length: () => endTime(params()),
109 readouts,
110 dispose() {
111 stop();
112 portrait.dispose();
113 view.classList.remove("c01");
114 view.replaceChildren();
115 },
116 };
118 function now(): number {
119 if (!audio || !playing) return stoppedAt;
120 return audio.ctx.currentTime - pieceStart;
121 }
123 // ── transport ──
125 function makePendulum(P: Params): DoublePendulum {
126 return new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
127 }
129 async function start(a: AudioEngine, offset: number) {
130 stop();
131 const token = ++startToken;
132 audio = a;
133 const P = params();
134 const ctx = a.ctx;
135 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
136 pend = makePendulum(P);
137 pend.randomize(energyTarget(P, 0), mulberry32(seedUsed));
138 pend.tau = P.tau as number;
139 simPieceT = 0;
140 history = [];
141 lastHistT = -Infinity;
142 points = [];
143 portrait.reset(); // the worker starts a fresh portrait
144 noteCount = 0;
145 lastNote = null;
146 restAt = null;
147 // fast-forward silently to the start offset (author "start at")
148 if (offset > 0) advanceTo(offset, false);
150 out = ctx.createGain();
151 out.connect(a.input);
152 ensureInstruments();
153 await Promise.all([notes?.ready, hum.ready]); // e.g. the modal-synth worklet loading
154 if (token !== startToken) return; // stopped or restarted meanwhile
155 pieceStart = ctx.currentTime + 0.1 - offset;
156 hum.start(ctx, P);
157 playing = true;
158 tick();
159 timer = window.setInterval(tick, TICK_MS);
160 }
162 function ensureInstruments() {
163 if (!audio || !out) return;
164 const P = params();
165 if (!noteBus) {
166 noteBus = audio.ctx.createGain();
167 noteBus.connect(out);
168 }
169 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
170 const name = P.noteInstrument as string;
171 const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
172 if (!notes || noteKey !== key) {
173 notes?.dispose();
174 noteKey = key;
175 notes = NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string });
176 }
177 hum.ensure(audio.ctx, out, P, playing);
178 }
180 function stop() {
181 startToken++;
182 if (timer !== undefined) window.clearInterval(timer);
183 timer = undefined;
184 const wasPlaying = playing;
185 if (playing) {
186 stoppedAt = now();
187 playing = false;
188 postPortrait(false);
189 }
190 // release the audio graph (also when a start is still waiting for its instrument to load)
191 if (!audio) return;
192 const t = audio.ctx.currentTime;
193 hum.release(audio.ctx, wasPlaying);
194 const o = out;
195 if (o) {
196 o.gain.setTargetAtTime(0, t, 0.05);
197 window.setTimeout(() => o.disconnect(), 600);
198 }
199 notes?.dispose();
200 notes = null;
201 noteKey = "";
202 noteBus = null;
203 out = null;
204 }
206 // ── simulation ──
208 /** Simulate up to piece time `target`; schedule notes if `sound`. */
209 function advanceTo(target: number, sound: boolean) {
210 if (!pend) return;
211 const P = params();
212 pend.cfg.m2 = P.massRatio as number;
213 pend.cfg.l2 = P.lengthRatio as number;
214 pend.tau = P.tau as number;
215 const speed = P.speed as number;
216 const duration = P.duration as number;
217 const restE = P.restEnergy as number;
218 const y = pend.y;
219 let prev = wrapAngle(y[0]);
220 let prevTh2 = y[1];
221 let prevP2 = y[3];
222 let prevT = simPieceT;
223 while (simPieceT < target) {
224 pend.eTarget = energyTarget(P, simPieceT) * pend.vTop;
225 pend.step(DT);
226 simPieceT += DT / speed;
227 const cur = wrapAngle(y[0]);
228 if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) {
229 const f = -prev / (cur - prev);
230 const c: Crossing = {
231 t: prevT + f * (simPieceT - prevT),
232 th2: wrapAngle(prevTh2 + f * (y[1] - prevTh2)),
233 p2: (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale,
234 };
235 points.push(c);
236 if (sound) playNote(c, P);
237 }
238 if (restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
239 restAt = simPieceT;
240 if (sound) holdFinalNote(P);
241 }
242 prev = cur;
243 prevTh2 = y[1];
244 prevP2 = y[3];
245 prevT = simPieceT;
246 if (simPieceT - lastHistT >= HISTORY_DT) {
247 history.push({ t: simPieceT, th1: y[0], th2: y[1] });
248 lastHistT = simPieceT;
249 }
250 }
251 }
253 function playNote(c: Crossing, P: Params) {
254 if (!audio || !notes) return;
255 const when = pieceStart + c.t;
256 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
258 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2);
259 const freq = midiToFreq(midi);
260 const handle = notes.play({ when, freq, velocity, pan, duration: P.noteLength as number });
261 if (handle) lastNote = { handle, when };
262 noteCount++;
263 }
265 /** Let the last real note ring: sustain it for finalHold, then fade over finalFade. */
266 function holdFinalNote(P: Params) {
267 if (!lastNote) return;
268 lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
269 }
271 /** Piece time at which everything has faded: known once the pendulum is at rest, estimated before. */
272 function endTime(P: Params): number {
273 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
274 return (restAt ?? (P.duration as number) + 0.5) + ring;
275 }
277 function tick() {
278 if (!audio || !pend || !playing) return;
279 const P = params();
280 ensureInstruments();
281 const ctx = audio.ctx;
282 const t = ctx.currentTime - pieceStart;
283 const total = endTime(P);
284 if (restAt !== null && t >= total) {
285 stop();
286 stoppedAt = total;
287 piece.onEnded?.();
288 return;
289 }
290 advanceTo(t + LOOKAHEAD, true);
291 postPortrait(true);
293 hum.update(ctx, P, pend.energyNorm(), t, restAt !== null ? total : null);
295 // trim history to what drawing still needs
296 let i = 0;
297 while (i < history.length - 1 && history[i + 1].t <= t - 0.1) i++;
298 if (i > 0) history.splice(0, i);
299 }
301 // ── drawing ──
303 function color(name: string): string {
304 return cssColor(view, name);
305 }
307 /** Pendulum angles at piece time t, interpolated between stored snapshots. */
308 function stateAt(t: number): { th1: number; th2: number } {
309 const n = history.length;
310 if (!n) return pend ? { th1: pend.y[0], th2: pend.y[1] } : { th1: 0, th2: 0 };
311 if (t <= history[0].t) return history[0];
312 if (t >= history[n - 1].t) return history[n - 1];
313 let lo = 0, hi = n - 1; // history[lo].t <= t < history[hi].t
314 while (hi - lo > 1) {
315 const mid = (lo + hi) >> 1;
316 if (history[mid].t <= t) lo = mid;
317 else hi = mid;
318 }
319 const a = history[lo], b = history[hi];
320 const f = (t - a.t) / (b.t - a.t);
321 return { th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
322 }
324 let lastDrawWall = 0;
325 let frameDt = 1 / 60; // smoothed display frame interval (s)
327 /**
328 * The pendulum as an inset in the plot's upper-left corner (outside the energetically allowed
329 * region of the section most of the time), drawn as before: solid arms and filled bobs.
330 * Motion blur: several faint positions spread over the last frame interval.
331 */
332 function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number) {
333 const opacity = P.pendulumAlpha as number;
334 if (opacity <= 0) return;
335 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
336 const l1 = 1, l2 = P.lengthRatio as number;
337 const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2; // inset radius
338 const scale = (0.9 * R) / (l1 + l2);
339 const x0 = 8 + R, y0 = 8 + R; // pivot
341 // enough samples that the tip moves ~BLUR_SPACING_PX between them
342 let k = 1;
343 if (shutter > 0) {
344 let path = 0;
345 let a = stateAt(t);
346 for (let j = 1; j <= 8; j++) {
347 const b = stateAt(t - (shutter * j) / 8);
348 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
349 a = b;
350 }
351 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
352 }
353 // per-sample alpha so a still pendulum still draws (nearly) fully opaque
354 const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k));
355 const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number);
356 const fg = color("--fg");
357 g.strokeStyle = fg;
358 g.fillStyle = fg;
359 g.lineWidth = 1.5;
360 g.lineCap = "round";
361 g.globalAlpha = alpha;
362 for (let i = 0; i < k; i++) {
363 const { th1, th2 } = stateAt(t - (shutter * i) / Math.max(1, k - 1));
364 const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
365 const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2);
366 g.beginPath();
367 g.moveTo(x0, y0);
368 g.lineTo(x1, y1);
369 g.lineTo(x2, y2);
370 g.stroke();
371 g.beginPath();
372 g.arc(x1, y1, r1, 0, 2 * Math.PI);
373 g.moveTo(x2 + r2, y2);
374 g.arc(x2, y2, r2, 0, 2 * Math.PI);
375 g.fill();
376 }
377 g.globalAlpha = opacity;
378 g.beginPath();
379 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
380 g.fill();
381 g.globalAlpha = 1;
382 }
384 function draw() {
385 const P = params();
386 const t = now();
387 const wall = performance.now() / 1000;
388 const dtw = wall - lastDrawWall;
389 lastDrawWall = wall;
390 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
391 const fg = color("--fg");
392 const dim = color("--dim");
394 // Poincaré section
395 {
396 const f = plot.begin(P, pend ? pend.energyNorm() : null, pend?.cfg ?? null, pend?.vTop ?? 1, dim);
397 const { g, w, h } = f;
399 portrait.draw(f, t, portraitSettings(P), fg, () => fg);
401 // the pendulum's own crossings
402 const fade = P.fade as number;
403 const size = P.pointSize as number;
404 let drop = 0;
405 while (drop < points.length && t - points[drop].t > 4.6 * fade) drop++;
406 if (drop > 0) points.splice(0, drop);
407 for (const c of points) {
408 const age = t - c.t;
409 if (age < 0) break; // not sounded yet
410 drawCrossing(f, c.th2, c.p2, age, fade, size, fg);
411 }
412 drawPendulum(g, w, h, P, t);
413 }
414 }
416 function readouts(): Record<string, string> {
417 const P = params();
418 const t = now();
419 return {
420 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
421 "energy target": energyTarget(P, t).toFixed(4),
422 energy: pend ? pend.energyNorm().toFixed(4) : "–",
423 notes: String(noteCount),
424 "seed used": seedUsed ? String(seedUsed) : "–",
425 hum: hum.describe(),
426 "orbit portrait": portrait.describe(),
427 };
428 }
430 return piece;
431}