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";
21import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
22import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
23import { SLOTS } from "./schema.ts";
25const DT = 0.003; // 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 every orbit as at rest regardless
30interface Crossing {
31 t: number; // piece time
32 th2: number; // wrapped
33 p2: number; // normalized
34}
36interface Orbit {
37 index: number;
38 pend: DoublePendulum;
39 prev: number; // wrapped θ1 at the previous step
40 prevTh2: number;
41 prevP2: number;
42 points: Crossing[];
43 lastNote: { handle: NoteHandle; when: number } | null;
44 restAt: number | null;
45}
47export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece {
48 view.classList.add("c02");
49 const canvas = document.createElement("canvas");
50 view.append(canvas);
51 const plot = new SectionPlot(canvas);
52 const hum = new Hum();
53 const portrait = new PortraitLayer(() => now(), () => playing);
54 const portraitSettings = (P: Params): PortraitSettings => ({
55 show: P.portrait as boolean,
56 count: P.portraitCount as number,
57 cpu: P.portraitCpu as number,
58 life: P.portraitLife as number,
59 band: P.portraitBand as number,
60 minHold: P.portraitMinHold as number,
61 maxPoints: P.portraitMaxPoints as number,
62 xfade: P.portraitXfade as number,
63 alpha: P.portraitAlpha as number,
64 size: P.portraitSize as number,
65 tracks: P.traces as boolean,
66 trackMax: P.traceMax as number,
67 trackAlpha: P.traceAlpha as number,
68 trackSize: P.traceSize as number,
69 });
70 const postPortrait = (running: boolean) => {
71 const P = params();
72 // each pendulum's current state, so the worker can trace the orbit it is on
73 const tracks = orbits.filter((o) => o.restAt === null).map((o) => ({ id: o.index, y: Array.from(o.pend.y) }));
74 portrait.post(running, portraitSettings(P), meanEnergy(), P.massRatio as number, P.lengthRatio as number, tracks);
75 };
77 let orbits: Orbit[] = [];
78 let audio: AudioEngine | null = null;
79 let out: GainNode | null = null;
80 let noteBus: GainNode | null = null;
81 let instruments = new Map<string, NoteInstrument>(); // by instrument name (+ custom settings)
82 let timer: number | undefined;
83 let playing = false;
84 let startToken = 0;
85 let pieceStart = 0;
86 let simPieceT = 0;
87 let seedUsed = 0;
88 let noteCount = 0;
89 let stoppedAt = 0;
90 let restAll: number | null = null; // piece time every orbit had come to rest
92 const piece: Piece = {
93 get playing() {
94 return playing;
95 },
96 start,
97 stop,
98 draw,
99 now,
100 length: () => endTime(params()),
101 readouts,
102 dispose() {
103 stop();
104 portrait.dispose();
105 view.classList.remove("c02");
106 view.replaceChildren();
107 },
108 };
110 function now(): number {
111 if (!audio || !playing) return stoppedAt;
112 return audio.ctx.currentTime - pieceStart;
113 }
115 // ── orbits ──
117 function makeOrbit(P: Params, index: number, e: number): Orbit {
118 const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
119 pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1));
120 pend.tau = P.tau as number;
121 return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null };
122 }
124 /** Match the number of orbits to the setting (new ones start at the current target energy). */
125 function syncOrbitCount(P: Params) {
126 const n = Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
127 if (restAll !== null) return;
128 while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT))));
129 if (orbits.length > n) orbits.length = n;
130 }
132 // ── instruments ──
134 function slotOf(o: Orbit): number {
135 return o.index % SLOTS;
136 }
138 function instrumentKey(P: Params, slot: number): { name: string; key: string } {
139 const name = P[`slot${slot + 1}Instrument`] as string;
140 return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name };
141 }
143 /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */
144 function ensureInstruments() {
145 if (!audio || !out) return;
146 const P = params();
147 if (!noteBus) {
148 noteBus = audio.ctx.createGain();
149 noteBus.connect(out);
150 }
151 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
152 const wanted = new Map<string, string>();
153 for (const o of orbits) {
154 const { name, key } = instrumentKey(P, slotOf(o));
155 wanted.set(key, name);
156 }
157 for (const [key, inst] of instruments) {
158 if (!wanted.has(key)) {
159 inst.dispose();
160 instruments.delete(key);
161 }
162 }
163 for (const [key, name] of wanted) {
164 if (!instruments.has(key)) instruments.set(key, NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string }));
165 }
166 hum.ensure(audio.ctx, out, P, playing);
167 }
169 // ── transport ──
171 async function start(a: AudioEngine, offset: number) {
172 stop();
173 const token = ++startToken;
174 audio = a;
175 const P = params();
176 const ctx = a.ctx;
177 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
178 simPieceT = 0;
179 restAll = null;
180 noteCount = 0;
181 orbits = [];
182 portrait.reset(); // the worker starts a fresh portrait
183 syncOrbitCount(P); // random starts at the starting energy, from the seed
184 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
186 out = ctx.createGain();
187 out.connect(a.input);
188 ensureInstruments();
189 await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]);
190 if (token !== startToken) return;
191 pieceStart = ctx.currentTime + 0.1 - offset;
192 hum.start(ctx, P);
193 playing = true;
194 tick();
195 timer = window.setInterval(tick, TICK_MS);
196 }
198 function stop() {
199 startToken++;
200 if (timer !== undefined) window.clearInterval(timer);
201 timer = undefined;
202 const wasPlaying = playing;
203 if (playing) {
204 stoppedAt = now();
205 playing = false;
206 postPortrait(false);
207 }
208 if (!audio) return;
209 const t = audio.ctx.currentTime;
210 hum.release(audio.ctx, wasPlaying);
211 const o = out;
212 if (o) {
213 o.gain.setTargetAtTime(0, t, 0.05);
214 window.setTimeout(() => o.disconnect(), 600);
215 }
216 for (const inst of instruments.values()) inst.dispose();
217 instruments = new Map();
218 noteBus = null;
219 out = null;
220 }
222 // ── simulation ──
224 function advanceTo(target: number, sound: boolean) {
225 const P = params();
226 const speed = P.speed as number;
227 const duration = P.duration as number;
228 const restE = P.restEnergy as number;
229 for (const o of orbits) {
230 o.pend.cfg.m2 = P.massRatio as number;
231 o.pend.cfg.l2 = P.lengthRatio as number;
232 o.pend.tau = P.tau as number;
233 }
234 while (simPieceT < target) {
235 const eT = energyTarget(P, simPieceT);
236 const t0 = simPieceT;
237 simPieceT += DT / speed;
238 for (const o of orbits) {
239 const pend = o.pend, y = pend.y;
240 pend.eTarget = eT * pend.vTop;
241 pend.step(DT);
242 const cur = wrapAngle(y[0]);
243 if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
244 const f = -o.prev / (cur - o.prev);
245 const c: Crossing = {
246 t: t0 + f * (simPieceT - t0),
247 th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)),
248 p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale,
249 };
250 o.points.push(c);
251 if (sound) playNote(o, c, P);
252 }
253 if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
254 o.restAt = simPieceT;
255 // let this orbit's last real note ring: sustain, then fade
256 if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number);
257 }
258 o.prev = cur;
259 o.prevTh2 = y[1];
260 o.prevP2 = y[3];
261 }
262 if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT;
263 }
264 }
266 function playNote(o: Orbit, c: Crossing, P: Params) {
267 if (!audio) return;
268 const when = pieceStart + c.t;
269 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
270 const slot = slotOf(o);
271 const inst = instruments.get(instrumentKey(P, slot).key);
272 if (!inst) return;
273 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number);
274 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number });
275 if (handle) o.lastNote = { handle, when };
276 noteCount++;
277 }
279 /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */
280 function endTime(P: Params): number {
281 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
282 return (restAll ?? (P.duration as number) + 0.5) + ring;
283 }
285 function meanEnergy(): number {
286 if (!orbits.length) return 0;
287 return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length;
288 }
290 function tick() {
291 if (!audio || !playing) return;
292 const P = params();
293 syncOrbitCount(P);
294 ensureInstruments();
295 const ctx = audio.ctx;
296 const t = ctx.currentTime - pieceStart;
297 const total = endTime(P);
298 if (restAll !== null && t >= total) {
299 stop();
300 stoppedAt = total;
301 piece.onEnded?.();
302 return;
303 }
304 advanceTo(t + LOOKAHEAD, true);
305 postPortrait(true);
306 hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null);
307 }
309 // ── drawing ──
311 function colors(P: Params): string[] {
312 const list = String(P.colors)
313 .split(",")
314 .map((s) => s.trim())
315 .filter(Boolean);
316 return list.length ? list : [cssColor(view, "--fg")];
317 }
319 function draw() {
320 const P = params();
321 const t = now();
322 const ref = orbits[0]?.pend ?? null;
323 const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null;
324 const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim"));
325 const fade = P.fade as number;
326 const size = P.pointSize as number;
327 const cols = colors(P);
328 portrait.draw(f, t, portraitSettings(P), cssColor(view, "--fg"), (id) => cols[id % cols.length]);
329 for (const o of orbits) {
330 let drop = 0;
331 while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++;
332 if (drop > 0) o.points.splice(0, drop);
333 const col = cols[o.index % cols.length];
334 for (const c of o.points) {
335 const age = t - c.t;
336 if (age < 0) break; // not sounded yet
337 drawCrossing(f, c.th2, c.p2, age, fade, size, col);
338 }
339 }
340 }
342 function readouts(): Record<string, string> {
343 const P = params();
344 const t = now();
345 return {
346 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
347 "energy target": energyTarget(P, t).toFixed(4),
348 "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–",
349 notes: String(noteCount),
350 "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
351 instruments: String(instruments.size),
352 "seed used": seedUsed ? String(seedUsed) : "–",
353 hum: hum.describe(),
354 portrait: portrait.describe(),
355 };
356 }
358 return piece;
359}