/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / lab-ensemble / piece.ts
185 lines · 6.3 KBBlameHistoryRaw
1// Ensemble lab: six audio-rate pendulums; a steady tempo pushes energy into pendulums 1…k.
2// Keys 0–6 set k; R resets them all to rest. Not part of the album; reachable at #/ensemble.
4import { dbToGain, type AudioEngine } from "../../core/audio.ts";
5import type { Piece } from "../../core/composition.ts";
6import type { Params } from "../../core/params.ts";
7import workletUrl from "../../lab/ensembleWorklet.ts?worker&url";
8import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap, type Signal } from "../../lab/protocol.ts";
9import { cssColor, fitCanvas } from "../shared/section.ts";
11const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
13export function createEnsemblePiece(view: HTMLElement, params: () => Params): Piece {
14 const canvas = document.createElement("canvas");
15 view.append(canvas);
17 let audio: AudioEngine | null = null;
18 let node: AudioWorkletNode | null = null;
19 let out: GainNode | null = null;
20 let timer: number | undefined;
21 let playing = false;
22 let startedAt = 0;
23 let snap: EnsembleSnap | null = null;
24 let lastSent = "";
25 let token = 0;
26 let lastBeat = -1;
27 const flash = new Array<number>(ENSEMBLE).fill(0); // wall time of each pendulum's last pulse
29 const settings = (P: Params): EnsembleSettings => ({
30 voices: Array.from({ length: ENSEMBLE }, (_, i) => ({
31 pitch: P[`pitch${i + 1}`] as number,
32 massRatio: P[`mass${i + 1}`] as number,
33 lengthRatio: P[`length${i + 1}`] as number,
34 ringTime: P[`ring${i + 1}`] as number,
35 level: dbToGain(P[`level${i + 1}`] as number),
36 })),
37 tempo: P.tempo as number,
38 pulseAdds: P.pulseAdds as number,
39 active: Math.round(P.active as number),
40 build: Math.round(P.build as number),
41 signal: P.signal as Signal,
42 gain: dbToGain(P.gain as number),
43 dcCut: P.dcCut as number,
44 spread: P.spread as number,
45 });
47 const send = (m: EnsembleMsg) => node?.port.postMessage(m);
48 const onKey = (e: KeyboardEvent) => {
49 const el = e.target;
50 if (el instanceof Element && el.closest("input, select, textarea")) return;
51 if (/^[0-6]$/.test(e.key)) send({ type: "active", k: Number(e.key) });
52 else if (e.key === "r" || e.key === "R") send({ type: "reset" });
53 };
54 window.addEventListener("keydown", onKey);
56 function sync() {
57 if (!node || !audio || !out) return;
58 const P = params();
59 const key = JSON.stringify(settings(P));
60 if (key !== lastSent) {
61 lastSent = key;
62 send({ type: "settings", s: settings(P) });
63 }
64 out.gain.setTargetAtTime(dbToGain(P.level as number), audio.ctx.currentTime, 0.05);
65 }
67 async function start(a: AudioEngine) {
68 stop();
69 const my = ++token;
70 audio = a;
71 const ctx = a.ctx;
72 let p = loaded.get(ctx);
73 if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl)));
74 await p;
75 if (my !== token) return;
76 out = ctx.createGain();
77 out.gain.value = 0;
78 node = new AudioWorkletNode(ctx, "pendulum-ensemble", { numberOfInputs: 0, outputChannelCount: [2] });
79 node.port.onmessage = (e: MessageEvent<EnsembleSnap>) => {
80 const s = e.data;
81 if (s.beat !== lastBeat) {
82 lastBeat = s.beat;
83 const now = performance.now() - s.sinceBeat * 1000;
84 for (let i = 0; i < s.active; i++) flash[i] = now;
85 }
86 snap = s;
87 };
88 node.connect(out).connect(a.input);
89 lastSent = "";
90 sync();
91 playing = true;
92 startedAt = ctx.currentTime;
93 timer = window.setInterval(sync, 50);
94 }
96 function stop() {
97 token++;
98 if (timer !== undefined) window.clearInterval(timer);
99 timer = undefined;
100 playing = false;
101 if (!audio) return;
102 const o = out, n = node;
103 if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03);
104 window.setTimeout(() => {
105 n?.disconnect();
106 o?.disconnect();
107 }, 300);
108 node = out = null;
109 }
111 function draw() {
112 const P = params();
113 const g = fitCanvas(canvas);
114 const w = canvas.clientWidth, h = canvas.clientHeight;
115 g.clearRect(0, 0, w, h);
116 const fg = cssColor(view, "--fg"), dim = cssColor(view, "--dim"), muted = cssColor(view, "--muted");
117 const cols = 3, rows = 2, cw = w / cols, ch = h / rows;
118 const TR = snap ? snap.trails.length / (2 * ENSEMBLE) : 0;
119 const now = performance.now();
120 for (let i = 0; i < ENSEMBLE; i++) {
121 const cx = (i % cols) * cw + cw / 2, cy = Math.floor(i / cols) * ch + ch / 2;
122 const active = snap ? i < snap.active : false;
123 const L = 1 + (P[`length${i + 1}`] as number);
124 const sc = (0.4 * Math.min(cw, ch)) / L;
125 // pulse flash: a ring that fades
126 const age = (now - flash[i]) / 1000;
127 if (age < 0.35) {
128 g.strokeStyle = fg;
129 g.globalAlpha = 0.5 * (1 - age / 0.35);
130 g.beginPath();
131 g.arc(cx, cy, 0.42 * Math.min(cw, ch), 0, 2 * Math.PI);
132 g.stroke();
133 }
134 g.globalAlpha = 1;
135 if (snap) {
136 const o = i * 2 * TR;
137 g.strokeStyle = active ? fg : muted;
138 g.globalAlpha = active ? 0.9 : 0.35;
139 g.lineWidth = 1;
140 g.beginPath();
141 for (let j = 0; j < TR; j++) {
142 const x = cx + sc * snap.trails[o + 2 * j], y = cy + sc * snap.trails[o + 2 * j + 1];
143 if (j) g.lineTo(x, y);
144 else g.moveTo(x, y);
145 }
146 g.stroke();
147 g.globalAlpha = 1;
148 }
149 g.fillStyle = active ? fg : dim;
150 g.font = "11px ui-monospace, monospace";
151 g.fillText(`${i + 1} · ${Math.round(P[`pitch${i + 1}`] as number)} Hz${snap ? ` · E ${snap.energy[i].toFixed(2)}` : ""}`, (i % cols) * cw + 6, Math.floor(i / cols) * ch + 14);
152 }
153 if (!playing) {
154 g.fillStyle = muted;
155 g.font = "12px ui-monospace, monospace";
156 g.fillText("play; keys 0–6 choose how many get the pulse; R resets", 6, h - 8);
157 }
158 }
160 function readouts(): Record<string, string> {
161 return {
162 active: snap ? `${snap.active} of ${ENSEMBLE}` : "–",
163 beat: snap ? String(snap.beat) : "–",
164 energies: snap ? snap.energy.map((e) => e.toFixed(2)).join(" ") : "–",
165 keys: "0–6: how many get the pulse · R: reset to rest",
166 };
167 }
169 return {
170 get playing() {
171 return playing;
172 },
173 start: (a) => start(a),
174 stop,
175 draw,
176 now: () => (playing && audio ? audio.ctx.currentTime - startedAt : 0),
177 length: () => Infinity,
178 readouts,
179 dispose() {
180 stop();
181 window.removeEventListener("keydown", onKey);
182 view.replaceChildren();
183 },
184 };
↑↓ move↵openescclose