/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / lab / ensembleWorklet.ts
139 lines · 5.2 KBCodeBlameHistory
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 1// Ensemble lab: six audio-rate double pendulums with their own physics (pitch, mass and length
2// ratios, ring time), mixed across the stereo field. A steady tempo, kept here on the audio clock,
3// pushes energy into pendulums 1…k on every beat; k is set by the page (keys 0–6 or a slider) or
4// grows by one every `build` beats.
6import { DoublePendulum } from "../physics/doublePendulum.ts";
7import { mulberry32 } from "../core/rng.ts";
8import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap } from "./protocol.ts";
9import { DcBlock, kick, lowMode, signal } from "./voice.ts";
11declare const sampleRate: number;
12declare class AudioWorkletProcessor {
13 readonly port: MessagePort;
14 constructor();
16declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
18const TRAIL = 192; // bob positions per pendulum in each snapshot
19const DECIM = 3; // one trail sample every DECIM audio samples
20const MAX_STEP = 0.006; // sim seconds per RK4 step (audio rate is plenty fine)
22interface V {
23 p: DoublePendulum;
24 dc: DcBlock;
25 trail: Float32Array;
28class Ensemble extends AudioWorkletProcessor {
29 private s: EnsembleSettings | null = null;
30 private v: V[] = [];
31 private rand = mulberry32(777);
32 private k = 0; // active pendulums
33 private lastActiveSetting = -1;
34 private beat = 0;
35 private sinceBeat = 1e9; // samples
36 private trailW = 0;
37 private count = 0;
38 private sinceSnap = 0;
40 constructor() {
41 super();
42 for (let i = 0; i < ENSEMBLE; i++) {
43 const p = new DoublePendulum({ m1: 1, m2: 1, l1: 1, l2: 1, g: 1 });
44 p.controlled = false;
45 this.v.push({ p, dc: new DcBlock(), trail: new Float32Array(2 * TRAIL) });
46 }
47 this.port.onmessage = (e: MessageEvent<EnsembleMsg>) => {
48 const m = e.data;
49 if (m.type === "settings") {
50 this.s = m.s;
51 for (let i = 0; i < ENSEMBLE; i++) {
52 this.v[i].p.cfg.m2 = m.s.voices[i].massRatio;
53 this.v[i].p.cfg.l2 = m.s.voices[i].lengthRatio;
54 }
55 // the slider sets k when it moves; keys (below) set it directly
56 if (m.s.active !== this.lastActiveSetting) {
57 this.lastActiveSetting = m.s.active;
58 this.k = m.s.active;
59 }
60 } else if (m.type === "active") this.k = Math.max(0, Math.min(ENSEMBLE, m.k));
61 else if (m.type === "reset") {
62 for (const v of this.v) v.p.y.fill(0);
63 this.beat = 0;
64 }
65 };
66 }
68 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
69 const out = outputs[0];
70 const Lo = out[0], Ro = out[1] ?? out[0];
71 const s = this.s;
72 if (!s) return true;
73 const n = Lo.length;
74 const beatSamples = (60 / Math.max(1, s.tempo)) * sampleRate;
75 const dcR = 1 - (2 * Math.PI * s.dcCut) / sampleRate;
76 // per-voice constants for this block
77 const per = this.v.map((v, i) => {
78 const vs = s.voices[i];
79 const k = (2 * Math.PI * vs.pitch) / lowMode(v.p); // sim seconds per audio second
80 const dtS = k / sampleRate;
81 const sub = Math.max(1, Math.ceil(dtS / MAX_STEP));
82 const pan = ENSEMBLE > 1 ? s.spread * ((2 * i) / (ENSEMBLE - 1) - 1) : 0;
83 const a = ((pan + 1) * Math.PI) / 4; // equal-power
84 v.p.damping = vs.ringTime > 0 ? (2 * 6.9078) / (vs.ringTime * k) : 0;
85 return { h: dtS / sub, sub, gl: Math.cos(a) * vs.level, gr: Math.sin(a) * vs.level };
86 });
87 for (let t = 0; t < n; t++) {
88 // the beat: push energy into pendulums 1…k
89 if (++this.sinceBeat >= beatSamples) {
90 this.sinceBeat = 0;
91 this.beat++;
92 if (s.build > 0 && this.beat % Math.round(s.build) === 0 && this.k < ENSEMBLE) this.k++;
93 for (let i = 0; i < this.k; i++) kick(this.v[i].p, s.pulseAdds * this.v[i].p.vTop, this.rand);
94 }
95 let l = 0, r = 0;
96 for (let i = 0; i < ENSEMBLE; i++) {
97 const v = this.v[i], c = per[i], p = v.p;
98 for (let j = 0; j < c.sub; j++) p.step(c.h);
99 if (!Number.isFinite(p.y[0])) p.y.fill(0);
100 const d = p.derived();
101 const x = Math.tanh(s.gain * v.dc.run(signal(p, s.signal, d.w1, d.w2), dcR));
102 l += c.gl * x;
103 r += c.gr * x;
104 }
105 Lo[t] = l;
106 Ro[t] = r;
107 if (++this.count % DECIM === 0) {
108 for (const v of this.v) {
109 const y = v.p.y, cfg = v.p.cfg, o = 2 * this.trailW;
110 v.trail[o] = cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]);
111 v.trail[o + 1] = cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1]);
112 }
113 this.trailW = (this.trailW + 1) % TRAIL;
114 }
115 }
116 this.sinceSnap += n;
117 if (this.sinceSnap >= sampleRate / 30) {
118 this.sinceSnap = 0;
119 const trails = new Float32Array(ENSEMBLE * 2 * TRAIL);
120 this.v.forEach((v, i) => {
121 const o = i * 2 * TRAIL;
122 trails.set(v.trail.subarray(2 * this.trailW), o);
123 trails.set(v.trail.subarray(0, 2 * this.trailW), o + 2 * (TRAIL - this.trailW));
124 });
125 const snap: EnsembleSnap = {
126 type: "snap",
127 active: this.k,
128 beat: this.beat,
129 sinceBeat: this.sinceBeat / sampleRate,
130 energy: this.v.map((v) => v.p.energyNorm()),
131 trails,
132 };
133 this.port.postMessage(snap, [trails.buffer]);
134 }
135 return true;
136 }
139registerProcessor("pendulum-ensemble", Ensemble);
↑↓ move↵openescclose