/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / shared / portrait.ts
205 lines · 7.5 KBCodeBlameHistory
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 1// The background portrait of the section (grey), plus optional "tracks": the orbit each live
2// pendulum is on at the moment the portrait was computed, drawn in the pendulum's color.
3// Both are computed at frozen energy in a throttled worker (see orbitWorker.ts); when the energy
4// has moved enough, a new portrait starts and the old one crossfades out.
6import type { OrbitBatch, OrbitConfig, TrackSeed } from "./orbitWorker.ts";
7import type { SectionFrame } from "./section.ts";
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 11export interface PortraitSettings {
12 show: boolean;
13 count: number;
14 cpu: number;
15 life: number;
16 band: number;
17 minHold: number;
18 maxPoints: number;
19 xfade: number;
20 alpha: number;
21 size: number;
22 /** trace each live pendulum's current orbit */
23 tracks: boolean;
24 trackMax: number;
25 trackAlpha: number;
26 trackSize: number;
29interface Portrait {
30 gen: number;
31 energy: number;
32 pts: number[]; // [θ2, p2, …]
33 tracks: Map<number, number[]>;
34 retiredAt: number | null;
37export class PortraitLayer {
38 private worker: Worker | null = null;
39 private portraits: Portrait[] = [];
40 private resetPending = false;
41 private latestGen = 0;
42 private ignoreBelow = 0; // batches from portraits started before the last reset
43 private rate = 0; // points per second, for the readout
44 private newPts = 0;
45 private rateT = 0;
46 private now: () => number;
47 private live: () => boolean;
49 /** now: piece time; live: whether the piece is playing (batches are ignored otherwise) */
50 constructor(now: () => number, live: () => boolean) {
51 this.now = now;
52 this.live = live;
53 }
55 /** New play or seek: drop what's shown; the worker starts a fresh portrait. */
56 reset() {
59 this.ignoreBelow = this.latestGen + 1;
60 this.resetPending = true;
61 }
63 private ensureWorker(): Worker {
64 if (!this.worker) {
65 this.worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" });
66 this.worker.onmessage = (ev: MessageEvent<OrbitBatch>) => this.receive(ev.data);
67 }
68 return this.worker;
69 }
71 private receive({ gen, energy, pts, tracks }: OrbitBatch) {
72 if (!this.live()) return;
73 this.latestGen = Math.max(this.latestGen, gen);
74 if (gen < this.ignoreBelow) return;
75 let cur = this.portraits[this.portraits.length - 1];
76 if (!cur || gen > cur.gen) {
77 const t = this.now();
78 for (const p of this.portraits) p.retiredAt ??= t;
79 cur = { gen, energy, pts: [], tracks: new Map(), retiredAt: null };
80 this.portraits.push(cur);
81 } else if (gen < cur.gen) return; // stale batch
82 for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]);
83 for (const tb of tracks) {
84 let arr = cur.tracks.get(tb.id);
85 if (!arr) cur.tracks.set(tb.id, (arr = []));
86 for (let i = 0; i < tb.pts.length; i++) arr.push(tb.pts[i]);
87 }
88 this.newPts += pts.length / 2 + tracks.reduce((s, tb) => s + tb.pts.length / 2, 0);
92 /** Send the current state; call every tick while playing (running=false pauses the worker). */
93 post(running: boolean, s: PortraitSettings, energy: number, m2: number, l2: number, tracks: TrackSeed[]) {
94 if (!s.show && !s.tracks && !this.worker) return;
95 const msg: OrbitConfig = {
96 running: running && (s.show || s.tracks),
97 reset: this.resetPending,
98 energy,
99 m2,
100 l2,
101 count: s.show ? Math.round(s.count) : 0,
102 life: s.life,
103 band: s.band,
104 minHold: s.minHold,
105 maxPoints: s.show ? s.maxPoints : 0,
106 cpu: s.cpu,
107 tracks: s.tracks ? tracks : [],
108 trackMax: s.trackMax,
109 };
110 this.resetPending = false;
111 this.ensureWorker().postMessage(msg);
112 }
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 114 // The portrait and traces can be tens of thousands of points: they are drawn into an offscreen
115 // layer, redrawn at most every LAYER_MS (when points arrive, a crossfade runs, or the zoom
116 // moves), and copied onto the plot every frame.
117 private layer: HTMLCanvasElement | null = null;
118 private layerAt = 0;
119 private layerKey = "";
120 private dirty = true;
121 // the mapping the layer was drawn with: x = cx + kx·θ2, y = cy + ky·p2
122 private lm = { cx: 0, kx: 1, cy: 0, ky: 1 };
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 124 /** Draw the grey portrait and the colored tracks (call before drawing the live crossings). */
125 draw(f: SectionFrame, t: number, s: PortraitSettings, grey: string, trackColor: (id: number) => string) {
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 126 const { g, w, h, sx, sy } = f;
127 const before = this.portraits.length;
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 128 this.portraits = this.portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < s.xfade);
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 129 if (this.portraits.length !== before) this.dirty = true;
130 const fading = this.portraits.some((p) => p.retiredAt !== null);
131 const dpr = window.devicePixelRatio || 1;
132 // appearance the layer was drawn with; the zoom is handled by stretching the cached layer,
133 // which is redrawn only once the zoom has drifted noticeably
134 const key = [w, h, dpr, s.show, s.tracks, s.alpha, s.size, s.trackAlpha, s.trackSize, grey].join("|");
135 const cur = { cx: sx(0), kx: sx(1) - sx(0), cy: sy(0), ky: sy(1) - sy(0) };
136 const rx = cur.kx / this.lm.kx, ry = cur.ky / this.lm.ky;
137 const drift = Math.abs(Math.log(rx)) > 0.05 || Math.abs(Math.log(ry)) > 0.05;
138 const now = performance.now();
139 if (!this.layer) this.layer = document.createElement("canvas");
140 const L = this.layer;
141 if ((this.dirty || fading || drift || key !== this.layerKey) && now - this.layerAt >= LAYER_MS) {
142 const pw = Math.round(w * dpr), ph = Math.round(h * dpr);
143 if (L.width !== pw || L.height !== ph) {
144 L.width = pw;
145 L.height = ph;
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 147 const lg = L.getContext("2d")!;
148 lg.setTransform(dpr, 0, 0, dpr, 0, 0);
149 lg.clearRect(0, 0, w, h);
150 for (const p of this.portraits) {
151 const k = p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / s.xfade);
152 if (s.show && p.pts.length) {
153 const sz = s.size;
154 lg.fillStyle = grey;
155 lg.globalAlpha = s.alpha * k;
156 lg.beginPath();
157 const d = p.pts;
158 for (let i = 0; i < d.length; i += 2) lg.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
159 lg.fill();
160 }
161 if (s.tracks) {
162 const sz = s.trackSize;
163 for (const [id, d] of p.tracks) {
164 lg.fillStyle = trackColor(id);
165 lg.globalAlpha = s.trackAlpha * k;
166 lg.beginPath();
167 for (let i = 0; i < d.length; i += 2) lg.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
168 lg.fill();
169 }
171 }
173 this.layerAt = now;
174 this.layerKey = key;
175 this.lm = cur;
176 this.dirty = false;
177 }
178 if (L.width) {
179 // map the layer's coordinates onto the current zoom
180 const ax = cur.kx / this.lm.kx, ay = cur.ky / this.lm.ky;
181 g.save();
182 g.setTransform(dpr * ax, 0, 0, dpr * ay, dpr * (cur.cx - ax * this.lm.cx), dpr * (cur.cy - ay * this.lm.cy));
183 g.drawImage(L, 0, 0, w, h);
184 g.restore();
186 }
188 describe(): string {
189 const wall = performance.now() / 1000;
190 if (wall - this.rateT > 1) {
191 this.rate = this.newPts / (wall - this.rateT || 1);
192 this.newPts = 0;
193 this.rateT = wall;
194 }
195 const p = this.portraits.find((q) => q.retiredAt === null);
196 if (!p) return "–";
197 const tr = [...p.tracks.values()].reduce((s, a) => s + a.length / 2, 0);
198 return `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts${p.tracks.size ? ` + ${tr} traced` : ""}, ${Math.round(this.rate)}/s`;
199 }
201 dispose() {
202 this.worker?.terminate();
203 this.worker = null;
204 }
↑↓ move↵openescclose