2//
3// N double pendulums released together from rest at a wide angle, each outer arm offset by a tiny,
4// calibrated amount, so they swing as one and then visibly separate at about `separateAt` seconds,
5// and chaos takes over. Only the pendulums are shown, drawn from one pivot, with trails.
6// A note sounds whenever a bottom bob crosses the vertical through the pivot (either direction):
7// in "chord" mode each pendulum has its own note of a chord, so the opening is one chord that
8// breaks into arpeggios; in "motion" mode the pitch follows the bob's speed. Notes are panned
9// toward the side the bob is heading. After `freeTime` the pendulums are damped to rest over
10// `dampTime`; each one's last note rings out and the piece ends with the fade.
12import type { AudioEngine } from "../../core/audio.ts";
13import { dbToGain } from "../../core/audio.ts";
14import type { Piece } from "../../core/composition.ts";
15import type { Params } from "../../core/params.ts";
16import { mulberry32, randomSeed } from "../../core/rng.ts";
17import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
18import { SharedReverb } from "../../instruments/reverb.ts";
19import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
20import type { NoteHandle, NoteInstrument, NoteInstrumentFactory } from "../../instruments/types.ts";
21import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
22import type { DoublePendulum, PendulumConfig } from "../../physics/doublePendulum.ts";
23import { cssColor, fitCanvas } from "../shared/section.ts";
24import { DT, bob, offsetForSeparation, released } from "./release.ts";
26const STREAMED = streamedModalInstruments();
27const LOOKAHEAD = 0.15;
28const STREAM_PREBUFFER = 0.4;
29const TICK_MS = 25;
30const MAX_SETTLE = 10; // s after the damping: count every pendulum as at rest regardless
31const HISTORY_DT = 1 / 120; // piece-time spacing of stored states (drawing and trails)
33interface Pend {
34 index: number;
35 p: DoublePendulum;
36 prevX: number; // bottom bob's x at the previous step
37 E0: number; // energy when the damping began
38 lastNote: { handle: NoteHandle; when: number } | null;
39 restAt: number | null;
40}
42interface Snapshot {
43 t: number;
44 s: Float64Array; // [θ1, θ2] per pendulum
45}
47export function createDivergencePiece(view: HTMLElement, params: () => Params): Piece {
48 view.classList.add("c03");
49 const canvas = document.createElement("canvas");
50 view.append(canvas);
52 let pends: Pend[] = [];
53 let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
54 let history: Snapshot[] = [];
55 let lastHistT = -Infinity;
56 let audio: AudioEngine | null = null;
57 let out: GainNode | null = null;
58 let noteBus: GainNode | null = null;
59 let reverb: SharedReverb | null = null;
60 let panL: StereoPannerNode | null = null;
61 let panR: StereoPannerNode | null = null;
62 let instL: NoteInstrument | null = null; // notes moving left
63 let instR: NoteInstrument | null = null; // notes moving right
64 let instKey = "";
65 let timer: number | undefined;
66 let playing = false;
67 let startToken = 0;
68 let pieceStart = 0;
69 let simPieceT = 0;
70 let seedUsed = 0;
71 let noteCount = 0;
72 let stoppedAt = 0;
73 let restAll: number | null = null;
74 let stream = false;
75 let simAhead = LOOKAHEAD;
76 let vmax0 = 1; // fastest possible bob speed at the release energy
77 let release = { th1: 0, th2: 0, offset: 0, separatesAt: 0 };
79 const piece: Piece = {
80 get playing() {
81 return playing;
82 },
83 start,
84 stop,
85 draw,
86 now,
87 length: () => endTime(params()),
88 readouts,
89 dispose() {
90 stop();
91 view.classList.remove("c03");
92 view.replaceChildren();
93 },
94 };
96 function now(): number {
97 if (!audio || !playing) return stoppedAt;
98 return audio.ctx.currentTime - pieceStart;
99 }
101 // ── release ──
103 function makePendulums(P: Params, rand: () => number | null) {
104 cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
105 const deg = Math.PI / 180;
106 const base = (P.releaseAngle as number) * deg;
107 const j = (P.jitter as number) * deg;
108 const r = rand();
109 const th1 = r === null ? base : base + (2 * r - 1) * j;
110 const r2 = rand();
111 const th2 = r2 === null ? base : base + (2 * r2 - 1) * j;
112 const speed = P.speed as number;
113 const cal = offsetForSeparation(cfg, th1, th2, (P.separateAt as number) * speed, (P.sepThreshold as number) * (cfg.l1 + cfg.l2));
114 release = { th1, th2, offset: cal.offset, separatesAt: cal.separatesAt / speed };
115 const n = Math.max(1, Math.round(P.count as number));
116 pends = [];
117 for (let i = 0; i < n; i++) {
118 const d = n > 1 ? (i / (n - 1) - 0.5) * cal.offset : 0;
119 const p = released(cfg, th1, th2, d);
120 pends.push({ index: i, p, prevX: bob(cfg, p.y)[0], E0: 0, lastNote: null, restAt: null });
121 }
122 vmax0 = Math.sqrt((2 * pends[0].p.energy()) / cfg.m2);
123 history = [];
124 lastHistT = -Infinity;
125 pushHistory(0);
126 }
128 // ── instruments ──
130 function factory(name: string): NoteInstrumentFactory {
131 return (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
132 }
134 /** Two copies of the instrument, panned left and right: a note goes to the side its bob is heading. */
135 function ensureInstruments() {
136 if (!audio || !out) return;
137 const P = params();
138 const ctx = audio.ctx;
139 if (!noteBus) {
140 noteBus = ctx.createGain();
141 noteBus.connect(out);
142 reverb = new SharedReverb(ctx, noteBus, P.reverbTime as number);
143 panL = ctx.createStereoPanner();
144 panR = ctx.createStereoPanner();
145 panL.connect(noteBus);
146 panR.connect(noteBus);
147 }
148 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
149 const pan = P.directionPan as number;
150 panL!.pan.setTargetAtTime(-pan, ctx.currentTime, 0.05);
151 panR!.pan.setTargetAtTime(pan, ctx.currentTime, 0.05);
152 const name = P.instrument as string;
153 const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
154 if (instL && instKey === key) return;
155 instL?.dispose();
156 instR?.dispose();
157 instKey = key;
158 const opts = { custom: P.modalCustom as string, effects: { send: reverb!.input } };
159 instL = factory(name)(ctx, panL!, opts);
160 instR = factory(name)(ctx, panR!, opts);
161 }
163 // ── transport ──
165 async function start(a: AudioEngine, offset: number) {
166 stop();
167 const token = ++startToken;
168 audio = a;
169 const P = params();
170 const ctx = a.ctx;
171 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
172 const rng = mulberry32(seedUsed);
173 makePendulums(P, () => rng());
174 simPieceT = 0;
175 restAll = null;
176 noteCount = 0;
177 stream = !!P.streamAudio;
178 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
179 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
181 out = ctx.createGain();
182 out.connect(a.input);
183 ensureInstruments();
184 await Promise.all([instL?.ready, instR?.ready]);
185 if (token !== startToken) return;
186 pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
187 playing = true;
188 tick();
189 timer = window.setInterval(tick, TICK_MS);
190 }
192 function stop() {
193 startToken++;
194 if (timer !== undefined) window.clearInterval(timer);
195 timer = undefined;
196 if (playing) {
197 stoppedAt = now();
198 playing = false;
199 }
200 if (!audio) return;
201 const t = audio.ctx.currentTime;
202 const o = out;
203 if (o) {
204 o.gain.setTargetAtTime(0, t, 0.05);
205 window.setTimeout(() => o.disconnect(), 600);
206 }
207 instL?.dispose();
208 instR?.dispose();
209 instL = instR = null;
210 instKey = "";
211 reverb?.dispose();
212 reverb = null;
213 noteBus = panL = panR = null;
214 out = null;
215 }
217 // ── simulation ──
219 function pushHistory(t: number) {
220 const s = new Float64Array(2 * pends.length);
221 for (let i = 0; i < pends.length; i++) {
222 s[2 * i] = pends[i].p.y[0];
223 s[2 * i + 1] = pends[i].p.y[1];
224 }
225 history.push({ t, s });
226 lastHistT = t;
227 }
229 function advanceTo(target: number, sound: boolean) {
230 const P = params();
231 const speed = P.speed as number;
232 const free = P.freeTime as number, damp = P.dampTime as number;
233 const curve = P.dampCurve as number, tau = P.tau as number;
234 const restE = P.restEnergy as number;
235 while (simPieceT < target) {
236 const t0 = simPieceT;
237 simPieceT += DT / speed;
238 const u = (t0 - free) / damp; // damping progress (< 0: free swinging)
239 for (const d of pends) {
240 const p = d.p;
241 if (u >= 0) {
242 if (!p.controlled) {
243 p.controlled = true;
244 d.E0 = p.energy();
245 }
246 p.tau = tau;
247 p.eTarget = u < 1 ? d.E0 * Math.pow(1 - u, curve) : 0;
248 // the energy controller fades out near zero energy; real friction settles the last of it
249 p.damping = u >= 1 ? 1 / tau : 0;
250 }
251 p.step(DT);
252 const x = bob(cfg, p.y)[0];
253 if (d.restAt === null && ((d.prevX < 0 && x >= 0) || (d.prevX > 0 && x <= 0))) {
254 const f = d.prevX / (d.prevX - x);
255 const tc = t0 + f * (simPieceT - t0);
256 if (sound) playNote(d, tc, x > d.prevX ? 1 : -1, P);
257 }
258 d.prevX = x;
259 if (d.restAt === null && u >= 1 && (p.energyNorm() < restE || simPieceT >= free + damp + MAX_SETTLE)) {
260 d.restAt = simPieceT;
261 if (sound && d.lastNote) d.lastNote.handle.hold(d.lastNote.when, P.finalHold as number, P.finalFade as number);
262 }
263 }
264 if (restAll === null && pends.every((d) => d.restAt !== null)) restAll = simPieceT;
265 if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
266 }
267 }
d5df914divergence: different chords for left-to-right and right-to-left crossingsJeremy Magland 269 /**
270 * The chord pitches per pendulum, low to high, from the scale's notes in range (an even spread
271 * if continuous). With two chords, 2n notes are spread over the range and alternate between
272 * them: left-to-right crossings play one, right-to-left the other (its neighbour above).
273 */
274 function chords(P: Params, n: number): { right: number[]; left: number[] } {
bc546ddAdd composition 3: divergenceJeremy Magland 275 const low = P.pitchLow as number, high = P.pitchHigh as number;
276 const root = NOTE_NAMES.indexOf(P.root as string);
d5df914divergence: different chords for left-to-right and right-to-left crossingsJeremy Magland 277 const two = !!P.directionChords;
278 const k = two ? 2 * n : n;
d5df914divergence: different chords for left-to-right and right-to-left crossingsJeremy Magland 280 if (P.scale === "continuous") notes = Array.from({ length: Math.max(k, 2) }, (_, i) => low + ((high - low) * i) / Math.max(1, Math.max(k, 2) - 1));
bc546ddAdd composition 3: divergenceJeremy Magland 281 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);
282 if (!notes.length) notes = [quantize((low + high) / 2, P.scale as string, root)];
d5df914divergence: different chords for left-to-right and right-to-left crossingsJeremy Magland 283 const spread = Array.from({ length: k }, (_, i) => notes[k > 1 ? Math.round((i * (notes.length - 1)) / (k - 1)) : Math.floor(notes.length / 2)]);
284 if (!two) return { right: spread, left: spread };
285 return { right: spread.filter((_, i) => i % 2 === 0), left: spread.filter((_, i) => i % 2 === 1) };
288 function playNote(d: Pend, tc: number, dir: number, P: Params) {
289 if (!audio) return;
290 const when = pieceStart + tc;
291 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
292 const inst = dir > 0 ? instR : instL;
293 if (!inst) return;
294 // bottom bob's speed at the crossing
295 const y = d.p.y, w = d.p.derived();
296 const vx = cfg.l1 * Math.cos(y[0]) * w.w1 + cfg.l2 * Math.cos(y[1]) * w.w2;
297 const vy = cfg.l1 * Math.sin(y[0]) * w.w1 + cfg.l2 * Math.sin(y[1]) * w.w2;
298 const x = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax0));
299 const floor = P.loudFloor as number;
300 const velocity = floor + (1 - floor) * Math.pow(x, P.loudCurve as number);
301 const midi =
302 P.pitchMode === "motion"
303 ? 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))
d5df914divergence: different chords for left-to-right and right-to-left crossingsJeremy Magland 304 : chords(P, pends.length)[dir > 0 ? "right" : "left"][d.index];
bc546ddAdd composition 3: divergenceJeremy Magland 305 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.noteLength as number });
306 if (handle) d.lastNote = { handle, when };
307 noteCount++;
308 }
310 function endTime(P: Params): number {
311 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
312 return (restAll ?? (P.freeTime as number) + (P.dampTime as number) + 1) + ring;
313 }
315 function tick() {
316 if (!audio || !playing) return;
317 const P = params();
318 ensureInstruments();
319 const t = audio.ctx.currentTime - pieceStart;
320 const total = endTime(P);
321 if (restAll !== null && t >= total) {
322 stop();
323 stoppedAt = total;
324 piece.onEnded?.();
325 return;
326 }
327 advanceTo(t + simAhead, true);
328 for (const inst of [instL, instR]) inst?.horizon?.(pieceStart + simPieceT);
329 // keep the states drawing and trails still need
330 const keep = t - (P.trailLength as number) - 0.5;
331 let i = 0;
332 while (i < history.length - 2 && history[i + 1].t < keep) i++;
333 if (i > 0) history.splice(0, i);
334 }
336 // ── drawing ──
338 function colorOf(P: Params, i: number, n: number): string {
339 const hue = (30 + (360 * i) / Math.max(1, n)) % 360;
340 return `hsl(${hue.toFixed(0)} ${P.saturation}% 70%)`;
341 }
343 /** States at piece time t, interpolated between stored snapshots. */
344 function statesAt(t: number): Float64Array | null {
345 const n = history.length;
346 if (!n) return null;
347 if (t <= history[0].t) return history[0].s;
348 if (t >= history[n - 1].t) return history[n - 1].s;
349 let lo = 0, hi = n - 1;
350 while (hi - lo > 1) {
351 const mid = (lo + hi) >> 1;
352 if (history[mid].t <= t) lo = mid;
353 else hi = mid;
354 }
355 const a = history[lo], b = history[hi];
356 const f = (t - a.t) / (b.t - a.t);
357 const s = new Float64Array(a.s.length);
358 for (let k = 0; k < s.length; k++) s[k] = a.s[k] + f * (b.s[k] - a.s[k]);
359 return s;
360 }
362 function draw() {
363 const P = params();
364 const t = now();
365 const g = fitCanvas(canvas);
366 const w = canvas.clientWidth, h = canvas.clientHeight;
367 g.clearRect(0, 0, w, h);
368 if (!pends.length) makePendulums(P, () => null); // preview at the nominal release
369 const n = pends.length;
370 const l1 = cfg.l1, l2 = cfg.l2;
371 const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
372 const x0 = w / 2, y0 = h / 2;
373 const px = (th1: number, th2: number): [number, number, number, number] => {
374 const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
375 return [x1, y1, x1 + scale * l2 * Math.sin(th2), y1 + scale * l2 * Math.cos(th2)];
376 };
378 // trails: the bottom bobs' recent paths, fading with age (drawn in a few alpha bands)
379 if (P.trails && history.length > 1) {
380 const len = P.trailLength as number;
381 const BANDS = 6;
382 g.lineWidth = P.trailWidth as number;
383 g.lineJoin = g.lineCap = "round";
384 for (let i = 0; i < n; i++) {
385 g.strokeStyle = colorOf(P, i, n);
386 for (let band = 0; band < BANDS; band++) {
387 const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
388 g.globalAlpha = 0.7 * (1 - (band + 0.5) / BANDS);
389 g.beginPath();
390 let started = false;
391 for (const hs of history) {
392 if (hs.t < aOld - HISTORY_DT || hs.t > aNew + HISTORY_DT) continue;
393 if (hs.t > t) break;
394 const [, , bx, by] = px(hs.s[2 * i], hs.s[2 * i + 1]);
395 if (started) g.lineTo(bx, by);
396 else g.moveTo(bx, by), (started = true);
397 }
398 g.stroke();
399 }
400 }
401 g.globalAlpha = 1;
402 }
404 // pendulums, all from the one pivot
405 const s = statesAt(t);
406 g.lineWidth = 1.5;
407 g.lineCap = "round";
408 const r = P.bobSize as number;
409 for (let i = n - 1; i >= 0; i--) {
410 const th1 = s ? s[2 * i] : pends[i].p.y[0], th2 = s ? s[2 * i + 1] : pends[i].p.y[1];
411 const [x1, y1, x2, y2] = px(th1, th2);
412 const col = colorOf(P, i, n);
413 g.strokeStyle = col;
414 g.fillStyle = col;
415 g.globalAlpha = P.armAlpha as number;
416 g.beginPath();
417 g.moveTo(x0, y0);
418 g.lineTo(x1, y1);
419 g.lineTo(x2, y2);
420 g.stroke();
421 g.globalAlpha = 1;
422 g.beginPath();
423 g.arc(x1, y1, r * 0.8, 0, 2 * Math.PI);
424 g.moveTo(x2 + r, y2);
425 g.arc(x2, y2, r, 0, 2 * Math.PI);
426 g.fill();
427 }
428 g.fillStyle = cssColor(view, "--fg");
429 g.beginPath();
430 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
431 g.fill();
432 }
434 function readouts(): Record<string, string> {
435 const P = params();
436 const t = now();
437 const free = P.freeTime as number, damp = P.dampTime as number;
438 const phase = restAll !== null && simPieceT >= restAll ? "at rest" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
439 const deg = 180 / Math.PI;
440 const loads = [instL, instR].map((i) => i?.load?.() ?? 0);
441 const under = [instL, instR].reduce((s, i) => s + (i?.underruns?.() ?? 0), 0);
442 return {
443 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
444 phase,
445 "energy (mean)": pends.length ? (pends.reduce((s, d) => s + d.p.energyNorm(), 0) / pends.length).toFixed(4) : "–",
446 notes: String(noteCount),
447 release: `${(release.th1 * deg).toFixed(2)}°, ${(release.th2 * deg).toFixed(2)}°`,
448 "offset (outermost)": `${release.offset.toExponential(2)} rad → separate at ${release.separatesAt.toFixed(1)} s`,
449 "seed used": seedUsed ? String(seedUsed) : "–",
450 "at rest": `${pends.filter((d) => d.restAt !== null).length} / ${pends.length}`,
451 "audio load": stream ? `renderers ${Math.round(100 * Math.max(...loads))}% (busiest), ${under} underruns` : `${Math.round(100 * (loads[0] + loads[1]))}%`,
452 };
453 }
455 return piece;
456}