/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c02-orbits / piece.ts
393 lines · 13.9 KBCodeBlameHistory
5c043e1Add composition 2: orbitsJeremy Magland 1// Composition 2: orbits.
2//
3// Several double pendulums at once, all steered along the same energy envelope from random
4// starting states. Only the Poincaré section is shown: each orbit traces its crossings in its own
5// color, and plays its own instrument (orbit n uses instrument slot n, cycling) in its own register.
6// A hum follows the energy. Each orbit plays until it comes to rest; its last note rings out,
7// and the piece ends when every orbit has rested and faded.
9import type { AudioEngine } from "../../core/audio.ts";
10import { dbToGain } from "../../core/audio.ts";
11import type { Piece } from "../../core/composition.ts";
12import type { Params } from "../../core/params.ts";
13import { mulberry32, randomSeed } from "../../core/rng.ts";
14import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
15import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
16import { midiToFreq } from "../../music/scales.ts";
17import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
18import { energyTarget } from "../shared/form.ts";
19import { Hum } from "../shared/hum.ts";
20import { noteFor } from "../shared/noteMap.ts";
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 21import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
5c043e1Add composition 2: orbitsJeremy Magland 22import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 23import { orbitCapacity, type CapacityResult } from "./capacity.ts";
5c043e1Add composition 2: orbitsJeremy Magland 24import { SLOTS } from "./schema.ts";
26const DT = 0.003; // simulation step (sim seconds)
27const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
28const TICK_MS = 25;
29const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
31interface Crossing {
32 t: number; // piece time
33 th2: number; // wrapped
34 p2: number; // normalized
37interface Orbit {
38 index: number;
39 pend: DoublePendulum;
40 prev: number; // wrapped θ1 at the previous step
41 prevTh2: number;
42 prevP2: number;
43 points: Crossing[];
44 lastNote: { handle: NoteHandle; when: number } | null;
45 restAt: number | null;
48export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece {
49 view.classList.add("c02");
50 const canvas = document.createElement("canvas");
51 view.append(canvas);
52 const plot = new SectionPlot(canvas);
53 const hum = new Hum();
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 54 const portrait = new PortraitLayer(() => now(), () => playing);
55 const portraitSettings = (P: Params): PortraitSettings => ({
56 show: P.portrait as boolean,
57 count: P.portraitCount as number,
58 cpu: P.portraitCpu as number,
59 life: P.portraitLife as number,
60 band: P.portraitBand as number,
61 minHold: P.portraitMinHold as number,
62 maxPoints: P.portraitMaxPoints as number,
63 xfade: P.portraitXfade as number,
64 alpha: P.portraitAlpha as number,
65 size: P.portraitSize as number,
66 tracks: P.traces as boolean,
67 trackMax: P.traceMax as number,
68 trackAlpha: P.traceAlpha as number,
69 trackSize: P.traceSize as number,
70 });
71 const postPortrait = (running: boolean) => {
72 const P = params();
73 // each pendulum's current state, so the worker can trace the orbit it is on
74 const tracks = orbits.filter((o) => o.restAt === null).map((o) => ({ id: o.index, y: Array.from(o.pend.y) }));
75 portrait.post(running, portraitSettings(P), meanEnergy(), P.massRatio as number, P.lengthRatio as number, tracks);
76 };
5c043e1Add composition 2: orbitsJeremy Magland 77
78 let orbits: Orbit[] = [];
79 let audio: AudioEngine | null = null;
80 let out: GainNode | null = null;
81 let noteBus: GainNode | null = null;
82 let instruments = new Map<string, NoteInstrument>(); // by instrument name (+ custom settings)
83 let timer: number | undefined;
84 let playing = false;
85 let startToken = 0;
86 let pieceStart = 0;
87 let simPieceT = 0;
88 let seedUsed = 0;
89 let noteCount = 0;
90 let stoppedAt = 0;
91 let restAll: number | null = null; // piece time every orbit had come to rest
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 92 // device limit (measured on the first play, then cached)
93 let capacity: CapacityResult | null = null;
94 let checking = false;
5c043e1Add composition 2: orbitsJeremy Magland 95
96 const piece: Piece = {
97 get playing() {
98 return playing;
99 },
100 start,
101 stop,
102 draw,
103 now,
104 length: () => endTime(params()),
105 readouts,
5c043e1Add composition 2: orbitsJeremy Magland 107 dispose() {
108 stop();
5c043e1Add composition 2: orbitsJeremy Magland 110 view.classList.remove("c02");
111 view.replaceChildren();
112 },
113 };
115 function now(): number {
116 if (!audio || !playing) return stoppedAt;
117 return audio.ctx.currentTime - pieceStart;
118 }
120 // ── orbits ──
122 function makeOrbit(P: Params, index: number, e: number): Orbit {
123 const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
124 pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1));
125 pend.tau = P.tau as number;
126 return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null };
127 }
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 129 function wantedOrbits(P: Params): number {
130 return Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
131 }
133 /** Orbits actually played: the setting, limited to what this device can handle. */
134 function playableOrbits(P: Params): number {
135 const want = wantedOrbits(P);
136 return P.deviceLimit && capacity ? Math.min(want, capacity.cap) : want;
137 }
5c043e1Add composition 2: orbitsJeremy Magland 139 /** Match the number of orbits to the setting (new ones start at the current target energy). */
140 function syncOrbitCount(P: Params) {
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 141 const n = playableOrbits(P);
5c043e1Add composition 2: orbitsJeremy Magland 142 if (restAll !== null) return;
143 while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT))));
144 if (orbits.length > n) orbits.length = n;
145 }
147 // ── instruments ──
149 function slotOf(o: Orbit): number {
150 return o.index % SLOTS;
151 }
153 function instrumentKey(P: Params, slot: number): { name: string; key: string } {
154 const name = P[`slot${slot + 1}Instrument`] as string;
155 return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name };
156 }
158 /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */
159 function ensureInstruments() {
160 if (!audio || !out) return;
161 const P = params();
162 if (!noteBus) {
163 noteBus = audio.ctx.createGain();
164 noteBus.connect(out);
165 }
166 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
167 const wanted = new Map<string, string>();
168 for (const o of orbits) {
169 const { name, key } = instrumentKey(P, slotOf(o));
170 wanted.set(key, name);
171 }
172 for (const [key, inst] of instruments) {
173 if (!wanted.has(key)) {
174 inst.dispose();
175 instruments.delete(key);
176 }
177 }
178 for (const [key, name] of wanted) {
179 if (!instruments.has(key)) instruments.set(key, NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string }));
180 }
181 hum.ensure(audio.ctx, out, P, playing);
182 }
184 // ── transport ──
186 async function start(a: AudioEngine, offset: number) {
187 stop();
188 const token = ++startToken;
189 audio = a;
190 const P = params();
191 const ctx = a.ctx;
193 checking = true;
194 try {
195 capacity = await orbitCapacity(ctx, P, wantedOrbits(P), SLOTS);
196 } finally {
197 checking = false;
198 }
199 if (token !== startToken) return; // stopped or restarted meanwhile
200 }
5c043e1Add composition 2: orbitsJeremy Magland 201 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
202 simPieceT = 0;
203 restAll = null;
204 noteCount = 0;
205 orbits = [];
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 206 portrait.reset(); // the worker starts a fresh portrait
5c043e1Add composition 2: orbitsJeremy Magland 207 syncOrbitCount(P); // random starts at the starting energy, from the seed
208 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
210 out = ctx.createGain();
211 out.connect(a.input);
212 ensureInstruments();
213 await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]);
214 if (token !== startToken) return;
215 pieceStart = ctx.currentTime + 0.1 - offset;
216 hum.start(ctx, P);
217 playing = true;
218 tick();
219 timer = window.setInterval(tick, TICK_MS);
220 }
222 function stop() {
223 startToken++;
224 if (timer !== undefined) window.clearInterval(timer);
225 timer = undefined;
226 const wasPlaying = playing;
227 if (playing) {
228 stoppedAt = now();
229 playing = false;
5c043e1Add composition 2: orbitsJeremy Magland 231 }
232 if (!audio) return;
233 const t = audio.ctx.currentTime;
234 hum.release(audio.ctx, wasPlaying);
235 const o = out;
236 if (o) {
237 o.gain.setTargetAtTime(0, t, 0.05);
238 window.setTimeout(() => o.disconnect(), 600);
239 }
240 for (const inst of instruments.values()) inst.dispose();
241 instruments = new Map();
242 noteBus = null;
243 out = null;
244 }
246 // ── simulation ──
248 function advanceTo(target: number, sound: boolean) {
249 const P = params();
250 const speed = P.speed as number;
251 const duration = P.duration as number;
252 const restE = P.restEnergy as number;
253 for (const o of orbits) {
254 o.pend.cfg.m2 = P.massRatio as number;
255 o.pend.cfg.l2 = P.lengthRatio as number;
256 o.pend.tau = P.tau as number;
257 }
258 while (simPieceT < target) {
259 const eT = energyTarget(P, simPieceT);
260 const t0 = simPieceT;
261 simPieceT += DT / speed;
262 for (const o of orbits) {
263 const pend = o.pend, y = pend.y;
264 pend.eTarget = eT * pend.vTop;
265 pend.step(DT);
266 const cur = wrapAngle(y[0]);
267 if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
268 const f = -o.prev / (cur - o.prev);
269 const c: Crossing = {
270 t: t0 + f * (simPieceT - t0),
271 th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)),
272 p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale,
273 };
274 o.points.push(c);
275 if (sound) playNote(o, c, P);
276 }
277 if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
278 o.restAt = simPieceT;
279 // let this orbit's last real note ring: sustain, then fade
280 if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number);
281 }
282 o.prev = cur;
283 o.prevTh2 = y[1];
284 o.prevP2 = y[3];
285 }
286 if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT;
287 }
288 }
290 function playNote(o: Orbit, c: Crossing, P: Params) {
291 if (!audio) return;
292 const when = pieceStart + c.t;
293 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
294 const slot = slotOf(o);
295 const inst = instruments.get(instrumentKey(P, slot).key);
296 if (!inst) return;
297 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number);
298 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number });
299 if (handle) o.lastNote = { handle, when };
300 noteCount++;
301 }
303 /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */
304 function endTime(P: Params): number {
305 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
306 return (restAll ?? (P.duration as number) + 0.5) + ring;
307 }
309 function meanEnergy(): number {
310 if (!orbits.length) return 0;
311 return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length;
312 }
314 function tick() {
315 if (!audio || !playing) return;
316 const P = params();
317 syncOrbitCount(P);
318 ensureInstruments();
319 const ctx = audio.ctx;
320 const t = ctx.currentTime - pieceStart;
321 const total = endTime(P);
322 if (restAll !== null && t >= total) {
323 stop();
324 stoppedAt = total;
325 piece.onEnded?.();
326 return;
327 }
328 advanceTo(t + LOOKAHEAD, true);
5c043e1Add composition 2: orbitsJeremy Magland 330 hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null);
331 }
333 // ── drawing ──
335 function colors(P: Params): string[] {
336 const list = String(P.colors)
337 .split(",")
338 .map((s) => s.trim())
339 .filter(Boolean);
340 return list.length ? list : [cssColor(view, "--fg")];
341 }
343 function draw() {
344 const P = params();
345 const t = now();
346 const ref = orbits[0]?.pend ?? null;
347 const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null;
348 const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim"));
349 const fade = P.fade as number;
350 const size = P.pointSize as number;
351 const cols = colors(P);
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 352 portrait.draw(f, t, portraitSettings(P), cssColor(view, "--fg"), (id) => cols[id % cols.length]);
5c043e1Add composition 2: orbitsJeremy Magland 353 for (const o of orbits) {
354 let drop = 0;
355 while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++;
356 if (drop > 0) o.points.splice(0, drop);
357 const col = cols[o.index % cols.length];
358 for (const c of o.points) {
359 const age = t - c.t;
360 if (age < 0) break; // not sounded yet
361 drawCrossing(f, c.th2, c.p2, age, fade, size, col);
362 }
363 }
364 }
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 366 function notice(): string | null {
367 if (checking) return "checking what this device can play…";
368 const P = params();
369 const want = wantedOrbits(P);
370 const n = playableOrbits(P);
371 return n < want ? `${n} of ${want} orbits: reduced to what this device can play live` : null;
372 }
5c043e1Add composition 2: orbitsJeremy Magland 374 function readouts(): Record<string, string> {
375 const P = params();
376 const t = now();
377 return {
378 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
379 "energy target": energyTarget(P, t).toFixed(4),
380 "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–",
381 notes: String(noteCount),
382 "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 383 "device limit": capacity ? `${capacity.cap} orbits (synth load ${(100 * capacity.load).toFixed(0)}% with ${capacity.at})` : "–",
5c043e1Add composition 2: orbitsJeremy Magland 384 instruments: String(instruments.size),
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 385 "audio load": `${Math.round(100 * ([...instruments.values()].reduce((s, i) => s + (i.load?.() ?? 0), 0) + (hum.inst?.load?.() ?? 0)))}%`,
5c043e1Add composition 2: orbitsJeremy Magland 386 "seed used": seedUsed ? String(seedUsed) : "–",
387 hum: hum.describe(),
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 388 portrait: portrait.describe(),
5c043e1Add composition 2: orbitsJeremy Magland 389 };
390 }
392 return piece;
↑↓ move↵openescclose