/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c01-poincare / piece.ts
605 lines · 21.8 KBCodeBlameHistory
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 1// Composition 1: a double pendulum and its Poincaré section.
2//
3// Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2).
4// Each crossing plays a note: θ2 → pitch, |p2| → loudness, θ2 → pan.
5// A hum runs throughout; its timbre follows the energy.
6// Energy is steered along an envelope: small → peak → hold → zero.
7// Notes stop at the end and the last one is held and faded.
8// Behind the live crossings, a worker draws the section's orbits at the current energy.
10import type { AudioEngine } from "../../core/audio.ts";
11import { dbToGain } from "../../core/audio.ts";
12import type { Piece } from "../../core/composition.ts";
13import type { Params } from "../../core/params.ts";
14import { mulberry32, randomSeed } from "../../core/rng.ts";
15import { DRONE_INSTRUMENTS, NOTE_INSTRUMENTS } from "../../instruments/index.ts";
16import type { DroneInstrument, NoteHandle, NoteInstrument } from "../../instruments/types.ts";
17import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
18import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
19import { energyTarget } from "./form.ts";
20import type { OrbitBatch, OrbitConfig } from "./orbitWorker.ts";
22const DT = 0.002; // simulation step (sim seconds)
23const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
24const TICK_MS = 25;
25const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
26const HISTORY_DT = 1 / 960; // piece-time spacing of stored pendulum snapshots
27const BLUR_MAX_SAMPLES = 64; // cap on sub-frame positions drawn for motion blur
28const BLUR_SPACING_PX = 2; // target distance the tip moves between blur samples
30interface Snapshot {
31 t: number;
32 th1: number;
33 th2: number;
36interface Crossing {
37 t: number; // piece time
38 th2: number; // wrapped
39 p2: number; // normalized
42export function createPoincarePiece(view: HTMLElement, params: () => Params): Piece {
43 view.classList.add("c01");
44 // one canvas: the Poincaré section, with the pendulum as an inset in its upper-left corner
45 const plotCanvas = document.createElement("canvas");
46 view.append(plotCanvas);
48 let pend: DoublePendulum | null = null;
49 let audio: AudioEngine | null = null;
50 let notes: NoteInstrument | null = null;
51 let noteKey = ""; // instrument name (+ custom settings) the current instance was built from
52 let noteBus: GainNode | null = null; // notes level
53 let humKey = "";
54 let startToken = 0;
55 let hum: DroneInstrument | null = null;
56 let out: GainNode | null = null;
57 let timer: number | undefined;
58 let playing = false;
59 let pieceStart = 0; // AudioContext time of piece time 0
60 let simPieceT = 0; // piece time of the simulation state
61 let seedUsed = 0;
62 let noteCount = 0;
63 let stoppedAt = 0;
64 let history: Snapshot[] = [];
65 let lastHistT = -Infinity;
66 let points: Crossing[] = [];
67 let thR = Math.PI; // plot half-ranges (smoothed)
68 let pR = 1;
69 // final note
70 let lastNote: { handle: NoteHandle; when: number } | null = null;
71 // The ending comes from the simulation: once the energy target is zero and the pendulum's
72 // energy falls below restEnergy it is at rest. No crossings register after that; the last
73 // real note is held and faded, the hum fades with it, and the piece ends with the fade.
74 let restAt: number | null = null; // piece time the pendulum came to rest
76 // background orbit portraits (worker). Each portrait is at one fixed energy; when a new one
77 // arrives, the older ones are retired and crossfade out.
78 interface Portrait {
79 gen: number;
80 energy: number;
81 pts: number[]; // [θ2, p2, …]
82 retiredAt: number | null;
83 }
84 let worker: Worker | null = null;
85 let portraits: Portrait[] = [];
86 let resetOrbits = false;
87 let latestGen = 0;
88 let ignoreBelow = 0; // batches from portraits started before the last reset
89 let orbitRate = 0; // points per second, smoothed, for the readout
90 let orbitNew = 0;
91 let orbitRateT = 0;
93 const piece: Piece = {
94 get playing() {
95 return playing;
96 },
97 start,
98 stop,
99 draw,
100 now,
101 length: () => endTime(params()),
102 readouts,
103 dispose() {
104 stop();
105 worker?.terminate();
106 worker = null;
107 view.classList.remove("c01");
108 view.replaceChildren();
109 },
110 };
112 function now(): number {
113 if (!audio || !playing) return stoppedAt;
114 return audio.ctx.currentTime - pieceStart;
115 }
117 // ── orbits ──
119 function ensureWorker(): Worker {
120 if (!worker) {
121 worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" });
122 worker.onmessage = (ev: MessageEvent<OrbitBatch>) => {
123 if (!playing) return;
124 const { gen, energy, pts } = ev.data;
125 latestGen = Math.max(latestGen, gen);
126 if (gen < ignoreBelow) return;
127 let cur = portraits[portraits.length - 1];
128 if (!cur || gen > cur.gen) {
129 const t = now();
130 for (const p of portraits) p.retiredAt ??= t;
131 cur = { gen, energy, pts: [], retiredAt: null };
132 portraits.push(cur);
133 } else if (gen < cur.gen) return; // stale batch from before a reset
134 for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]);
135 orbitNew += pts.length / 2;
136 };
137 }
138 return worker;
139 }
141 function postOrbitConfig(running: boolean) {
142 const P = params();
143 if (!P.orbits && !worker) return;
144 const msg: OrbitConfig = {
145 running: running && (P.orbits as boolean),
146 reset: resetOrbits,
147 energy: pend ? pend.energyNorm() : 0,
148 m2: P.massRatio as number,
149 l2: P.lengthRatio as number,
150 count: Math.round(P.orbitCount as number),
151 life: P.orbitLife as number,
152 band: P.orbitBand as number,
153 minHold: P.orbitMinHold as number,
154 maxPoints: P.orbitMaxPoints as number,
155 cpu: P.orbitCpu as number,
156 };
157 resetOrbits = false;
158 ensureWorker().postMessage(msg);
159 }
161 // ── transport ──
163 function makePendulum(P: Params): DoublePendulum {
164 return new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
165 }
167 async function start(a: AudioEngine, offset: number) {
168 stop();
169 const token = ++startToken;
170 audio = a;
171 const P = params();
172 const ctx = a.ctx;
173 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
174 pend = makePendulum(P);
175 pend.randomize(energyTarget(P, 0), mulberry32(seedUsed));
176 pend.tau = P.tau as number;
177 simPieceT = 0;
178 history = [];
179 lastHistT = -Infinity;
180 points = [];
181 // the worker starts a fresh portrait
182 portraits = [];
183 ignoreBelow = latestGen + 1;
184 resetOrbits = true;
185 noteCount = 0;
186 lastNote = null;
187 restAt = null;
188 // fast-forward silently to the start offset (author "start at")
189 if (offset > 0) advanceTo(offset, false);
191 out = ctx.createGain();
192 out.connect(a.input);
193 ensureInstruments();
194 await Promise.all([notes?.ready, hum?.ready]); // e.g. the modal-synth worklet loading
195 if (token !== startToken) return; // stopped or restarted meanwhile
196 pieceStart = ctx.currentTime + 0.1 - offset;
197 hum!.start(ctx.currentTime + 0.05, midiToFreq(P.humPitch as number));
198 playing = true;
199 tick();
200 timer = window.setInterval(tick, TICK_MS);
201 }
203 function ensureInstruments() {
204 if (!audio || !out) return;
205 const P = params();
206 if (!noteBus) {
207 noteBus = audio.ctx.createGain();
208 noteBus.connect(out);
209 }
210 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
211 const name = P.noteInstrument as string;
212 const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
213 if (!notes || noteKey !== key) {
214 notes?.dispose();
215 noteKey = key;
216 notes = NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string });
217 }
218 const hName = P.humInstrument as string;
219 const hKey = hName === "modal: custom" ? `${hName}\n${P.humCustom}` : hName;
220 if (!hum || humKey !== hKey) {
221 const old = hum;
222 humKey = hKey;
223 hum = DRONE_INSTRUMENTS[hName](audio.ctx, out, { custom: P.humCustom as string });
224 if (old && playing) {
225 // switched while playing: crossfade to the new hum
226 const t = audio.ctx.currentTime;
227 old.stop(t + 0.5, 0.5);
228 window.setTimeout(() => old.dispose(), 1500);
229 const h = hum;
230 void (h.ready ?? Promise.resolve()).then(() => h === hum && h.start(audio!.ctx.currentTime + 0.05, midiToFreq(P.humPitch as number)));
231 }
232 }
233 }
235 function stop() {
236 startToken++;
237 if (timer !== undefined) window.clearInterval(timer);
238 timer = undefined;
239 const wasPlaying = playing;
240 if (playing) {
241 stoppedAt = now();
242 playing = false;
243 postOrbitConfig(false);
244 }
245 // release the audio graph (also when a start is still waiting for its instrument to load)
246 if (!audio) return;
247 const t = audio.ctx.currentTime;
248 if (wasPlaying) hum?.stop(t + 0.3, 0.3); // a hum is only started once playing
249 const o = out;
250 if (o) {
251 o.gain.setTargetAtTime(0, t, 0.05);
252 window.setTimeout(() => o.disconnect(), 600);
253 }
254 const h = hum;
255 window.setTimeout(() => h?.dispose(), 600);
256 hum = null;
257 humKey = "";
258 notes?.dispose();
259 notes = null;
260 noteKey = "";
261 noteBus = null;
262 out = null;
263 }
265 // ── simulation ──
267 /** Simulate up to piece time `target`; schedule notes if `sound`. */
268 function advanceTo(target: number, sound: boolean) {
269 if (!pend) return;
270 const P = params();
271 pend.cfg.m2 = P.massRatio as number;
272 pend.cfg.l2 = P.lengthRatio as number;
273 pend.tau = P.tau as number;
274 const speed = P.speed as number;
275 const duration = P.duration as number;
276 const restE = P.restEnergy as number;
277 const y = pend.y;
278 let prev = wrapAngle(y[0]);
279 let prevTh2 = y[1];
280 let prevP2 = y[3];
281 let prevT = simPieceT;
282 while (simPieceT < target) {
283 pend.eTarget = energyTarget(P, simPieceT) * pend.vTop;
284 pend.step(DT);
285 simPieceT += DT / speed;
286 const cur = wrapAngle(y[0]);
287 if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) {
288 const f = -prev / (cur - prev);
289 const c: Crossing = {
290 t: prevT + f * (simPieceT - prevT),
291 th2: wrapAngle(prevTh2 + f * (y[1] - prevTh2)),
292 p2: (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale,
293 };
294 points.push(c);
295 if (sound) playNote(c, P);
296 }
297 if (restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
298 restAt = simPieceT;
299 if (sound) holdFinalNote(P);
300 }
301 prev = cur;
302 prevTh2 = y[1];
303 prevP2 = y[3];
304 prevT = simPieceT;
305 if (simPieceT - lastHistT >= HISTORY_DT) {
306 history.push({ t: simPieceT, th1: y[0], th2: y[1] });
307 lastHistT = simPieceT;
308 }
309 }
310 }
312 function playNote(c: Crossing, P: Params) {
313 if (!audio || !notes) return;
314 const when = pieceStart + c.t;
315 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
317 const range = P.thetaRange as number;
318 let u =
319 P.pitchSource === "absolute"
320 ? Math.min(1, Math.abs(c.th2) / range)
321 : Math.max(0, Math.min(1, 0.5 + (0.5 * c.th2) / range));
322 if (P.invertPitch) u = 1 - u;
323 u = Math.pow(u, P.pitchCurve as number);
324 const low = P.pitchLow as number, high = P.pitchHigh as number;
325 const root = NOTE_NAMES.indexOf(P.root as string);
326 const midi = quantize(low + (high - low) * u, P.scale as string, root);
328 const x = Math.min(1, Math.abs(c.p2) / (P.p2Ref as number));
329 const floor = P.loudFloor as number;
330 const vel = floor + (1 - floor) * Math.pow(x, P.loudCurve as number);
332 const freq = midiToFreq(midi);
333 const pan = (P.panAmount as number) * Math.max(-1, Math.min(1, c.th2 / Math.PI));
334 const handle = notes.play({ when, freq, velocity: vel, pan, duration: P.noteLength as number });
335 if (handle) lastNote = { handle, when };
336 noteCount++;
337 }
339 /** Let the last real note ring: sustain it for finalHold, then fade over finalFade. */
340 function holdFinalNote(P: Params) {
341 if (!lastNote) return;
342 lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
343 }
345 /** Piece time at which everything has faded: known once the pendulum is at rest, estimated before. */
346 function endTime(P: Params): number {
347 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
348 return (restAt ?? (P.duration as number) + 0.5) + ring;
349 }
351 function tick() {
352 if (!audio || !pend || !playing) return;
353 const P = params();
354 ensureInstruments();
355 const ctx = audio.ctx;
356 const t = ctx.currentTime - pieceStart;
357 const total = endTime(P);
358 if (restAt !== null && t >= total) {
359 stop();
360 stoppedAt = total;
361 piece.onEnded?.();
362 return;
363 }
364 advanceTo(t + LOOKAHEAD, true);
365 postOrbitConfig(true);
367 // hum
368 const e = pend.energyNorm();
369 const peak = P.energyPeak as number;
370 const rel = Math.max(0, Math.min(1, e / peak));
371 const e0 = Math.min(P.energyStart as number, 0.999 * peak);
372 const colorBase =
373 P.humColorMode === "log" ? Math.max(0, Math.min(1, Math.log(Math.max(e, 1e-12) / e0) / Math.log(peak / e0))) : rel;
374 const fadeIn = P.humFadeIn as number;
375 const fadeOut = P.humFadeOut as number;
376 // the hum's fade-out ends with the last note's fade (only once the pendulum is at rest)
377 const fade = Math.min(1, fadeIn > 0 ? t / fadeIn : 1, restAt !== null && fadeOut > 0 ? (total - t) / fadeOut : 1);
378 const follow = P.humFollow as number;
379 const level = dbToGain(P.humLevel as number) * Math.max(0, fade) * (1 - follow + follow * rel);
380 hum?.set(ctx.currentTime, {
381 level,
382 color: Math.pow(colorBase, P.humColorCurve as number),
383 freq: midiToFreq(P.humPitch as number),
384 normalize: P.humNormalize as boolean,
385 timbre: [1, 2]
386 .filter((i) => P[`humTarget${i}`] !== "none")
387 .map((i) => ({ target: P[`humTarget${i}`] as string, from: P[`humFrom${i}`] as number, to: P[`humTo${i}`] as number })),
388 });
390 // trim history to what drawing still needs
391 let i = 0;
392 while (i < history.length - 1 && history[i + 1].t <= t - 0.1) i++;
393 if (i > 0) history.splice(0, i);
394 }
396 // ── drawing ──
398 function fit(c: HTMLCanvasElement): CanvasRenderingContext2D {
399 const dpr = window.devicePixelRatio || 1;
400 const w = Math.round(c.clientWidth * dpr);
401 const h = Math.round(c.clientHeight * dpr);
402 if (c.width !== w || c.height !== h) {
403 c.width = w;
404 c.height = h;
405 }
406 const g = c.getContext("2d")!;
407 g.setTransform(dpr, 0, 0, dpr, 0, 0);
408 return g;
409 }
411 function color(name: string): string {
412 return getComputedStyle(view).getPropertyValue(name).trim() || "#ccc";
413 }
415 /** Pendulum angles at piece time t, interpolated between stored snapshots. */
416 function stateAt(t: number): { th1: number; th2: number } {
417 const n = history.length;
418 if (!n) return pend ? { th1: pend.y[0], th2: pend.y[1] } : { th1: 0, th2: 0 };
419 if (t <= history[0].t) return history[0];
420 if (t >= history[n - 1].t) return history[n - 1];
421 let lo = 0, hi = n - 1; // history[lo].t <= t < history[hi].t
422 while (hi - lo > 1) {
423 const mid = (lo + hi) >> 1;
424 if (history[mid].t <= t) lo = mid;
425 else hi = mid;
426 }
427 const a = history[lo], b = history[hi];
428 const f = (t - a.t) / (b.t - a.t);
429 return { th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
430 }
432 let lastDrawWall = 0;
433 let frameDt = 1 / 60; // smoothed display frame interval (s)
435 /**
436 * The pendulum as an inset in the plot's upper-left corner (outside the energetically allowed
437 * region of the section most of the time), drawn as before: solid arms and filled bobs.
438 * Motion blur: several faint positions spread over the last frame interval.
439 */
440 function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number) {
441 const opacity = P.pendulumAlpha as number;
442 if (opacity <= 0) return;
443 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
444 const l1 = 1, l2 = P.lengthRatio as number;
445 const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2; // inset radius
446 const scale = (0.9 * R) / (l1 + l2);
447 const x0 = 8 + R, y0 = 8 + R; // pivot
449 // enough samples that the tip moves ~BLUR_SPACING_PX between them
450 let k = 1;
451 if (shutter > 0) {
452 let path = 0;
453 let a = stateAt(t);
454 for (let j = 1; j <= 8; j++) {
455 const b = stateAt(t - (shutter * j) / 8);
456 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
457 a = b;
458 }
459 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
460 }
461 // per-sample alpha so a still pendulum still draws (nearly) fully opaque
462 const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k));
463 const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number);
464 const fg = color("--fg");
465 g.strokeStyle = fg;
466 g.fillStyle = fg;
467 g.lineWidth = 1.5;
468 g.lineCap = "round";
469 g.globalAlpha = alpha;
470 for (let i = 0; i < k; i++) {
471 const { th1, th2 } = stateAt(t - (shutter * i) / Math.max(1, k - 1));
472 const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
473 const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2);
474 g.beginPath();
475 g.moveTo(x0, y0);
476 g.lineTo(x1, y1);
477 g.lineTo(x2, y2);
478 g.stroke();
479 g.beginPath();
480 g.arc(x1, y1, r1, 0, 2 * Math.PI);
481 g.moveTo(x2 + r2, y2);
482 g.arc(x2, y2, r2, 0, 2 * Math.PI);
483 g.fill();
484 }
485 g.globalAlpha = opacity;
486 g.beginPath();
487 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
488 g.fill();
489 g.globalAlpha = 1;
490 }
492 function draw() {
493 const P = params();
494 const t = now();
495 const wall = performance.now() / 1000;
496 const dtw = wall - lastDrawWall;
497 lastDrawWall = wall;
498 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
499 const fg = color("--fg");
500 const dim = color("--dim");
502 // Poincaré section
503 {
504 const g = fit(plotCanvas);
505 const w = plotCanvas.clientWidth, h = plotCanvas.clientHeight;
506 g.clearRect(0, 0, w, h);
507 let thT = Math.PI, pT = P.plotP as number;
508 if (P.plotZoom === "fit energy" && pend) {
509 // exact extent of the energetically allowed region of the section (θ1 = 0):
510 // p2² ≤ 2·m2·l2²·(E − V(θ2)), so |p2|max = √(2e) in normalized units,
511 // and |θ2| ≤ acos(1 − E/(m2·g·l2)).
512 const e = Math.max(1e-6, pend.energyNorm());
513 const E = e * pend.vTop;
514 const m2 = pend.cfg.m2, l2 = pend.cfg.l2, gr = pend.cfg.g;
515 const th = E >= 2 * m2 * gr * l2 ? Math.PI : Math.acos(1 - E / (m2 * gr * l2));
516 thT = Math.min(Math.PI, 1.08 * th);
517 pT = 1.08 * Math.sqrt(2 * e);
518 }
519 // ease toward the target range with a time constant, in log space so zooming in and out feel alike
520 const ease = dtw > 0 && dtw < 0.5 ? 1 - Math.exp(-dtw / Math.max(0.01, P.zoomSmooth as number)) : 1;
521 thR *= Math.exp(ease * Math.log(thT / thR));
522 pR *= Math.exp(ease * Math.log(pT / pR));
523 const pad = 8;
524 const kx = (w / 2 - pad) / thR, ky = (h / 2 - pad) / pR;
525 const sx = (th: number) => w / 2 + kx * th;
526 const sy = (p: number) => h / 2 - ky * p;
527 g.strokeStyle = dim;
528 g.lineWidth = 1;
529 g.beginPath();
530 g.moveTo(pad, h / 2);
531 g.lineTo(w - pad, h / 2);
532 g.moveTo(w / 2, pad);
533 g.lineTo(w / 2, h - pad);
534 g.stroke();
536 // background orbit portraits
537 if (P.orbits) {
538 const xfade = P.orbitXfade as number;
539 const alpha = P.orbitAlpha as number;
540 const sz = P.orbitSize as number;
541 portraits = portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < xfade);
542 g.fillStyle = fg;
543 for (const p of portraits) {
544 g.globalAlpha = alpha * (p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / xfade));
545 g.beginPath();
546 const d = p.pts;
547 for (let i = 0; i < d.length; i += 2) g.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
548 g.fill();
549 }
550 g.globalAlpha = 1;
551 }
553 // the pendulum's own crossings
554 const fade = P.fade as number;
555 const size = P.pointSize as number;
556 let drop = 0;
557 while (drop < points.length && t - points[drop].t > 4.6 * fade) drop++;
558 if (drop > 0) points.splice(0, drop);
559 g.fillStyle = fg;
560 for (const c of points) {
561 const age = t - c.t;
562 if (age < 0) break; // not sounded yet
563 g.globalAlpha = Math.exp(-age / fade);
564 g.beginPath();
565 g.arc(sx(c.th2), sy(c.p2), size / 2, 0, 2 * Math.PI);
566 g.fill();
567 if (age < 0.4) {
568 // brief ring on the newest crossings
569 g.globalAlpha = 1 - age / 0.4;
570 g.strokeStyle = fg;
571 g.beginPath();
572 g.arc(sx(c.th2), sy(c.p2), size / 2 + 3 + 12 * age, 0, 2 * Math.PI);
573 g.stroke();
574 }
575 }
576 g.globalAlpha = 1;
577 drawPendulum(g, w, h, P, t);
578 }
579 }
581 function readouts(): Record<string, string> {
582 const P = params();
583 const t = now();
584 const wall = performance.now() / 1000;
585 if (wall - orbitRateT > 1) {
586 orbitRate = orbitNew / (wall - orbitRateT || 1);
587 orbitNew = 0;
588 orbitRateT = wall;
589 }
590 return {
591 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
592 "energy target": energyTarget(P, t).toFixed(4),
593 energy: pend ? pend.energyNorm().toFixed(4) : "–",
594 notes: String(noteCount),
595 "seed used": seedUsed ? String(seedUsed) : "–",
596 hum: hum?.describe?.() || "–",
597 "orbit portrait": (() => {
598 const p = portraits.find((q) => q.retiredAt === null);
599 return p ? `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts, ${Math.round(orbitRate)}/s` : "–";
600 })(),
601 };
602 }
604 return piece;
↑↓ move↵openescclose