1// Islands in a sea of chaos: the Poincaré section of the driven Duffing
2// oscillator (js/duffing.js), filled in live, with clickable orbits and a
3// sonification (js/voices.js).
4//
5// - Seed orbits, started on the axes of the view at drive phase 0, fill the
6// section in the background, a few thousand points per frame.
7// - A click adds an orbit from that point (drive phase 0), up to MAX_CLICKED
8// (or, with Clicks set to replace, takes the place of the clicked ones);
9// clicking an orbit's start ring removes it. Its dots fill in fast and
10// larger, and a playhead walks it one drive period per beat: a live trail
11// traces the motion through the period, and at each return to the section
12// a note is played, its pitch set by x (left to right over three octaves
13// of the chosen scale). All the clicked orbits play together, on the same
14// beat, each in its own voice (harp, marimba, ...), listed in the panel.
15// - Rhythm 'natural' instead plays the motion in slowed time (still one
16// drive period per beat) and plucks wherever x' crosses 0 upward (the
17// left turning point of each swing), at that x: each orbit makes its own
18// rhythm, regular on an island, irregular in the sea. 'both' plucks at
19// both turning points of each swing, where x' crosses 0 either way.
20// - Changing a parameter or preset restarts everything from the same starts,
21// the clicked orbits included.
22// - Coupling (optional; off by default) joins the clicked orbits into one
23// system: a spring and damper on each one's difference from their mean
24// (duffing.js, stepMany), so they pull together and, strong enough, fall
25// into step. Coupled, the clicked orbits restart from their starts
26// whenever one is added or removed, or the coupling changes (the dots are
27// computed ahead from the starts, and the playheads must follow the same
28// coupled motion).
30import { createStepper, physicsOf, X_MAX } from './js/duffing.js';
31import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
32import { PRESETS } from './js/presets.js';
34const SEEDS_X = 24; // seed orbits along x' = 0
35const SEEDS_V = 8; // and along x = 0
36const SEED_POINTS = 1500;
37const CLICK_POINTS = 4000;
38const CLICK_PER_FRAME = 40; // so a clicked orbit visibly grows
39const MAX_CLICKED = 8;
40const HIT_RADIUS = 9; // px: a click this close to a start ring removes it
41const FRAME_BUDGET = 7; // ms of integration per frame
42const TAIL = 2; // trail length, in drive periods
43const LOOKAHEAD = 0.12; // s of notes scheduled ahead
44const RING = 0.35; // s a pluck's ring takes to fade (at most 3 beats)
45const MARGIN = { left: 56, right: 12, top: 12, bottom: 34 };
47const SLIDERS = [
48 { name: 'freq', label: 'f<sub>0</sub>', unit: 'Hz', min: -1000, max: 1000, step: 5, fmt: (v) => `${v < 0 ? '−' : ''}${Math.abs(v)} Hz` },
49 { name: 'alpha', label: 'α', min: -5, max: 10, step: 0.1, scale: 1e7, fmt: (v) => `${v.toFixed(1)}·10⁷` },
50 { name: 'delta', label: 'δ', min: 0, max: 50, step: 0.5, fmt: (v) => `${v.toFixed(1)} s⁻¹` },
51 { name: 'F', label: 'F', min: 0, max: 30, step: 0.1, scale: 1e4, fmt: (v) => `${v.toFixed(1)}·10⁴` },
52 { name: 'drive', label: 'Ω / 2π', min: 20, max: 2000, step: 5, fmt: (v) => `${v} Hz` },
53 { name: 'view', label: 'View ±x', min: 0.1, max: X_MAX, step: 0.05, fmt: (v) => v.toFixed(2) },
54];
56const $ = (id) => document.getElementById(id);
57const canvas = $('plot');
58const ctx = canvas.getContext('2d');
59// the section points, accumulated: seed orbits, and clicked ones on top
60const dots = document.createElement('canvas');
61const top = document.createElement('canvas');
62const layers = [dots, top];
64let params = { ...PRESETS[0].params };
65let stepper;
66let view; // { xr, vr }: half-ranges of x and x'
67let orbits = []; // seed and clicked orbits
68let clicked = []; // clicked orbits: { x, v, hue, voice, ph }, ph its playhead
69let nextBeat = 0; // clock time of the next beat not yet scheduled
70let synth = null;
71let key = DEFAULT_KEY; // 0 = C, ..., 11 = B
72let soundOn = false;
73let hueCounter = 0;
74let coupling = 0; // r (s^-1) of the coupling between clicked orbits; 0: off
75let theme;
77// ---- physics ---------------------------------------------------------------
79// x' half-range: the speed at the bottom of the well of a free orbit that
80// just reaches x = +/-xr, so the view frames the motions of that size
81function speedRange(p, xr) {
82 const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4;
83 const vMin = p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0;
84 const v = Math.sqrt(Math.max(0, 2 * (V(xr) - vMin)));
85 return Math.max(v, 0.3 * xr * p.Omega, 1);
86}
88// skip: drive periods to run before recording (a seed's transient)
89function newOrbit(x, v, cap, hue, isClicked, skip = 0) {
90 return { x0: x, v0: v, s: { x, v, escaped: false }, pts: new Float32Array(2 * cap), n: 0, cap, hue, clicked: isClicked, skip };
91}
93function reset() {
94 const p = physicsOf(params);
95 stepper = createStepper(p);
96 view = { xr: params.view, vr: speedRange(p, params.view) };
97 // damped: the seeds settle onto the attractors before they are drawn,
98 // for about 5 / delta (clicked orbits show the way in)
99 const skip = p.delta > 0 ? Math.min(5000, Math.ceil((5 / p.delta) / stepper.T)) : 0;
100 orbits = [];
101 for (let i = 0; i < SEEDS_X; i++) {
102 const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X);
103 orbits.push(newOrbit(x, 0, SEED_POINTS, (i * 0.618) % 1, false, skip));
104 }
105 for (let i = 0; i < SEEDS_V; i++) {
106 const v = 0.9 * view.vr * (-1 + (2 * (i + 0.5)) / SEEDS_V);
107 orbits.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip));
108 }
109 for (const c of clicked) {
110 orbits.unshift(newOrbit(c.x, c.v, CLICK_POINTS, c.hue, true));
111 c.ph = newPlayhead(c.x, c.v);
112 }
113 clearDots();
114}
116// whether the clicked orbits move as one coupled system
117const coupled = () => coupling > 0 && clicked.length > 1;
119// the clicked orbits' dot clouds, in the order of `clicked`
120const clickedOrbits = () => clicked.map((c) => orbits.find((o) => o.clicked && o.hue === c.hue));
122// restart the clicked orbits (dots and playheads) from their starts
123function restartClicked() {
124 orbits = orbits.filter((o) => !o.clicked);
125 for (const c of clicked) {
126 orbits.unshift(newOrbit(c.x, c.v, CLICK_POINTS, c.hue, true));
127 c.ph = newPlayhead(c.x, c.v);
128 }
129 clearDots([top]);
130}
132// ---- playhead and sound -----------------------------------------------------
134const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
135const noteDt = () => 1 / Number($('tempo').value);
136const ringTime = () => Math.min(RING, 3 * noteDt());
138// a playhead: the orbit's state, and its scheduled beats ({ time, path,
139// last, notes }) still needed for the trail; notes: [{ t, x, v }]
140const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [] });
142// The crossings of x' = 0 along a drive period's path (N + 1 points, evenly
143// spaced in time over dt from time t0), interpolated linearly: upward only
144// (from x' < 0 to x' >= 0), or both ways (also from x' > 0 to x' <= 0).
145function crossings(path, t0, dt, both) {
146 const N = path.length / 2 - 1;
147 const notes = [];
148 for (let j = 1; j <= N; j++) {
149 const v0 = path[2 * j - 1];
150 const v1 = path[2 * j + 1];
151 if ((v0 < 0 && v1 >= 0) || (both && v0 > 0 && v1 <= 0)) {
152 const f = v0 / (v0 - v1);
153 notes.push({ t: t0 + ((j - 1 + f) / N) * dt, x: path[2 * j - 2] + f * (path[2 * j] - path[2 * j - 2]), v: 0 });
154 }
155 }
156 return notes;
157}
159// schedule the beats due within LOOKAHEAD: on each, every playhead advances
160// one drive period (keeping the path for the trail) and plucks its notes
161// (steady: one at the section point; natural: at each upward x' = 0;
162// both: at each x' = 0),
163// softer the more orbits there are
164function schedule() {
165 const now = clock();
166 // fallen behind (a stalled frame, a hidden tab), or nothing playing: carry
167 // on from now rather than play the missed notes in a burst
168 if (nextBeat < now) nextBeat = now + 0.02;
169 if (!clicked.length) return;
170 const scale = SCALES[$('scale').selectedIndex];
171 const gain = 1 / Math.sqrt(clicked.length);
172 const rhythm = $('rhythm').value;
173 const dt = noteDt();
174 while (nextBeat < now + LOOKAHEAD) {
175 // advance every playhead one drive period: together if coupled
176 const before = clicked.map(({ ph }) => ({ ...ph.s }));
177 const paths = clicked.map(() => new Float32Array(2 * (stepper.N + 1)));
178 if (coupled()) stepper.stepMany(clicked.map(({ ph }) => ph.s), coupling, paths);
179 else clicked.forEach(({ ph }, k) => stepper.step(ph.s, paths[k]));
180 for (const [k, { ph, voice }] of clicked.entries()) {
181 if (before[k].escaped) continue;
182 const { x, v } = before[k];
183 const path = paths[k];
184 // (at crossings: none in the period it escapes, whose path ends at rest)
185 const notes = rhythm === 'steady' ? [{ t: nextBeat, x, v }]
186 : ph.s.escaped ? [] : crossings(path, nextBeat, dt, rhythm === 'both');
187 ph.queue.push({ time: nextBeat, path, last: ph.s.escaped, notes });
188 if (soundOn && synth) {
189 for (const n of notes) {
190 const u = (n.x / view.xr + 1) / 2;
191 synth.play(voice, pitchOf(u, scale, key), n.t, Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain);
192 }
193 }
194 }
195 nextBeat += dt;
196 }
197 const keep = Math.max((TAIL + 1) * dt, ringTime() + dt);
198 for (const { ph } of clicked) {
199 while (ph.queue.length > 1 && ph.queue[1].time < now - keep) ph.queue.shift();
200 }
201}
203function setSound(on) {
204 soundOn = on;
205 const btn = $('sound');
206 btn.setAttribute('aria-pressed', on);
207 btn.textContent = on ? '♪ Sound on' : '♪ Sound off';
208 if (on && !synth) {
209 // the clock switches to the audio context's
210 synth = createSynth();
211 synth.setSustain(Number($('sustain').value));
212 for (const { ph } of clicked) ph.queue = [];
213 nextBeat = 0;
214 }
215 if (synth) {
216 synth.ctx.resume();
217 synth.setVolume(on ? Number($('volume').value) : 0);
218 }
219}
221// ---- drawing -----------------------------------------------------------------
223function readTheme() {
224 const cs = getComputedStyle(document.documentElement);
225 theme = {
226 bg: cs.getPropertyValue('--bg').trim(),
227 fg: cs.getPropertyValue('--fg').trim(),
228 muted: cs.getPropertyValue('--muted').trim(),
229 line: cs.getPropertyValue('--line').trim(),
230 accent: cs.getPropertyValue('--accent').trim(),
231 light: cs.getPropertyValue('--dot-light').trim(),
232 };
233}
235const orbitColor = (hue, clickedOrbit, alpha = 1) =>
236 `hsla(${Math.round(hue * 360)}, ${clickedOrbit ? 85 : 50}%, ${theme.light}, ${alpha})`;
238function plotRect() {
239 const dpr = devicePixelRatio || 1;
240 const w = canvas.width / dpr;
241 const h = canvas.height / dpr;
242 return { x: MARGIN.left, y: MARGIN.top, w: Math.max(10, w - MARGIN.left - MARGIN.right), h: Math.max(10, h - MARGIN.top - MARGIN.bottom) };
243}
245const toPx = (r, x, v) => [r.x + ((x / view.xr + 1) / 2) * r.w, r.y + ((1 - v / view.vr) / 2) * r.h];
247function drawPoints(o, from) {
248 const r = plotRect();
249 const dctx = (o.clicked ? top : dots).getContext('2d');
250 dctx.fillStyle = orbitColor(o.hue, o.clicked, o.clicked ? 0.95 : 0.7);
251 const size = o.clicked ? 2.2 : 1.4;
252 for (let i = from; i < o.n; i++) {
253 const [px, py] = toPx(r, o.pts[2 * i], o.pts[2 * i + 1]);
254 dctx.fillRect(px - size / 2, py - size / 2, size, size);
255 }
256}
258function clearDots(which = layers) {
259 const dpr = devicePixelRatio || 1;
260 for (const layer of which) {
261 const c = layer.getContext('2d');
262 c.setTransform(1, 0, 0, 1, 0, 0);
263 c.clearRect(0, 0, layer.width, layer.height);
264 c.setTransform(dpr, 0, 0, dpr, 0, 0);
265 }
266}
268function resize() {
269 const dpr = devicePixelRatio || 1;
270 const { width, height } = canvas.getBoundingClientRect();
271 canvas.width = dots.width = top.width = Math.round(width * dpr);
272 canvas.height = dots.height = top.height = Math.round(height * dpr);
273 clearDots();
274 for (const o of orbits) drawPoints(o, 0);
275}
277// advance the orbits within the frame's budget, drawing their new points
278function fill() {
279 const deadline = performance.now() + FRAME_BUDGET;
280 const advance = (o, count) => {
281 const from = o.n;
282 for (let k = 0; k < count && o.n < o.cap && !o.s.escaped; k++) {
283 stepper.step(o.s);
284 if (o.s.escaped) break;
285 if (o.skip > 0) { o.skip--; continue; }
286 o.pts[2 * o.n] = o.s.x;
287 o.pts[2 * o.n + 1] = o.s.v;
288 o.n++;
289 }
290 drawPoints(o, from);
291 };
292 if (coupled()) {
293 // the clicked orbits together, as the playheads will move
294 const os = clickedOrbits();
295 const from = os.map((o) => o.n);
296 for (let k = 0; k < CLICK_PER_FRAME && os.some((o) => o.n < o.cap && !o.s.escaped); k++) {
297 stepper.stepMany(os.map((o) => o.s), coupling);
298 for (const o of os) {
299 if (o.s.escaped || o.n >= o.cap) continue;
300 o.pts[2 * o.n] = o.s.x;
301 o.pts[2 * o.n + 1] = o.s.v;
302 o.n++;
303 }
304 }
305 os.forEach((o, k) => drawPoints(o, from[k]));
306 } else {
307 for (const o of orbits) if (o.clicked) advance(o, CLICK_PER_FRAME);
308 }
309 let busy = true;
310 while (busy && performance.now() < deadline) {
311 busy = false;
312 for (const o of orbits) {
313 if (o.clicked || o.n >= o.cap || o.s.escaped) continue;
314 advance(o, 10);
315 busy = true;
316 }
317 }
318}
320function drawAxes(r) {
321 ctx.strokeStyle = theme.line;
322 ctx.lineWidth = 1;
323 ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
324 ctx.beginPath();
325 ctx.moveTo(r.x + r.w / 2, r.y);
326 ctx.lineTo(r.x + r.w / 2, r.y + r.h);
327 ctx.moveTo(r.x, r.y + r.h / 2);
328 ctx.lineTo(r.x + r.w, r.y + r.h / 2);
329 ctx.stroke();
330 ctx.fillStyle = theme.muted;
331 ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
332 ctx.textBaseline = 'top';
333 ctx.textAlign = 'left';
334 ctx.fillText(`−${view.xr.toFixed(2)}`, r.x, r.y + r.h + 6);
335 ctx.textAlign = 'right';
336 ctx.fillText(view.xr.toFixed(2), r.x + r.w, r.y + r.h + 6);
337 ctx.textAlign = 'center';
338 ctx.fillText('displacement x', r.x + r.w / 2, r.y + r.h + 6);
339 ctx.save();
340 ctx.translate(r.x - 8, r.y + r.h / 2);
341 ctx.rotate(-Math.PI / 2);
342 ctx.textBaseline = 'bottom';
343 ctx.fillText('velocity ẋ (s⁻¹)', 0, 0);
344 ctx.textAlign = 'right';
345 ctx.fillText(`${Math.round(view.vr)}`, r.h / 2, 0);
346 ctx.textAlign = 'left';
347 ctx.fillText(`−${Math.round(view.vr)}`, -r.h / 2, 0);
348 ctx.restore();
349}
351function drawPlayhead(r, ph, hue) {
352 if (!ph.queue.length) return;
353 const now = clock();
354 const dt = noteDt();
355 const N = stepper.N;
356 const q = ph.queue;
357 let cur = -1;
358 for (let k = 0; k < q.length; k++) if (q[k].time <= now) cur = k;
359 if (cur < 0) return;
360 ctx.save();
361 ctx.beginPath();
362 ctx.rect(r.x, r.y, r.w, r.h);
363 ctx.clip();
364 ctx.lineWidth = 1.6;
365 ctx.lineCap = 'round';
366 ctx.lineJoin = 'round';
367 const CHUNK = Math.max(4, Math.ceil(N / 24));
368 let head = null;
369 for (let k = 0; k <= cur; k++) {
370 const e = q[k];
371 const span = q[k + 1] ? q[k + 1].time - e.time : dt;
372 const f = Math.min(1, (now - e.time) / span);
373 const end = Math.floor(f * N);
374 for (let j0 = 0; j0 < end; j0 += CHUNK) {
375 const age = (now - (e.time + (j0 / N) * span)) / dt;
376 const alpha = 1 - age / TAIL;
377 if (alpha <= 0) continue;
378 ctx.strokeStyle = orbitColor(hue, true, 0.85 * alpha);
379 ctx.beginPath();
380 for (let j = j0; j <= Math.min(end, j0 + CHUNK); j++) {
381 const [px, py] = toPx(r, e.path[2 * j], e.path[2 * j + 1]);
382 if (j === j0) ctx.moveTo(px, py);
383 else ctx.lineTo(px, py);
384 }
385 ctx.stroke();
386 }
387 if (k === cur) {
388 const j = Math.min(N, f * N);
389 const i0 = Math.floor(j);
390 const i1 = Math.min(N, i0 + 1);
391 const w = j - i0;
392 head = toPx(r, (1 - w) * e.path[2 * i0] + w * e.path[2 * i1], (1 - w) * e.path[2 * i0 + 1] + w * e.path[2 * i1 + 1]);
393 if (e.last) head = null;
394 }
395 // each pluck: a ring growing and fading where it was played
396 for (const n of e.notes) {
397 const g = (now - n.t) / ringTime();
398 if (g < 0 || g >= 1) continue;
399 const [sx, sy] = toPx(r, n.x, n.v);
400 ctx.strokeStyle = orbitColor(hue, true);
401 ctx.globalAlpha = 1 - g;
402 ctx.lineWidth = 2;
403 ctx.beginPath();
404 ctx.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI);
405 ctx.stroke();
406 ctx.globalAlpha = 1;
407 }
408 }
409 if (head) {
410 ctx.fillStyle = orbitColor(hue, true);
411 ctx.beginPath();
412 ctx.arc(head[0], head[1], 4.5, 0, 2 * Math.PI);
413 ctx.fill();
414 }
415 ctx.restore();
416}
418function drawStarts(r) {
419 for (const o of orbits) {
420 if (!o.clicked) continue;
421 const [px, py] = toPx(r, o.x0, o.v0);
422 ctx.strokeStyle = orbitColor(o.hue, true);
423 ctx.lineWidth = 1.5;
424 ctx.beginPath();
425 if (o.s.escaped) {
426 // escaped: a cross at its start
427 ctx.moveTo(px - 5, py - 5); ctx.lineTo(px + 5, py + 5);
428 ctx.moveTo(px + 5, py - 5); ctx.lineTo(px - 5, py + 5);
429 } else {
430 ctx.arc(px, py, 5, 0, 2 * Math.PI);
431 }
432 ctx.stroke();
433 }
434}
436function frame() {
437 requestAnimationFrame(frame);
438 if (!canvas.width || !canvas.height) return;
439 fill();
440 schedule();
441 const dpr = devicePixelRatio || 1;
442 const r = plotRect();
443 ctx.setTransform(1, 0, 0, 1, 0, 0);
444 ctx.fillStyle = theme.bg;
445 ctx.fillRect(0, 0, canvas.width, canvas.height);
446 ctx.drawImage(dots, 0, 0);
447 ctx.drawImage(top, 0, 0);
448 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
449 drawAxes(r);
450 drawStarts(r);
451 for (const c of clicked) drawPlayhead(r, c.ph, c.hue);
452}
454// ---- controls ----------------------------------------------------------------
456function buildControls() {
457 const presetSel = $('preset');
458 presetSel.innerHTML = PRESETS.map((pr, i) => `<option value="${i}">${pr.name}</option>`).join('')
459 + '<option value="custom" hidden>Custom</option>';
461 $('sliders').innerHTML = SLIDERS.map((s) => `
462 <label class="row">
463 <span>${s.label}</span>
464 <input type="range" id="s-${s.name}" min="${s.min}" max="${s.max}" step="${s.step}">
465 <output id="o-${s.name}"></output>
466 </label>`).join('');
468 const show = () => {
469 for (const s of SLIDERS) {
470 const v = params[s.name] / (s.scale ?? 1);
471 $(`s-${s.name}`).value = v;
472 $(`o-${s.name}`).textContent = s.fmt(Number($(`s-${s.name}`).value));
473 }
474 };
475 for (const s of SLIDERS) {
476 $(`s-${s.name}`).addEventListener('input', (e) => {
477 params[s.name] = Number(e.target.value) * (s.scale ?? 1);
478 $(`o-${s.name}`).textContent = s.fmt(Number(e.target.value));
479 presetSel.value = 'custom';
480 reset();
481 });
482 }
483 presetSel.addEventListener('change', () => {
484 if (presetSel.value === 'custom') return;
485 // the clicked orbits stay, restarted from the same (x, x') under the new
486 // parameters (a start outside the new view still plays; its chip in the
487 // legend removes it)
488 params = { ...PRESETS[presetSel.value].params };
489 show();
490 reset();
491 });
492 show();
494 $('scale').innerHTML = SCALES.map((s) => `<option${s.name === DEFAULT_SCALE ? ' selected' : ''}>${s.name}</option>`).join('');
495 $('keys').innerHTML = KEYS.map((k, i) => `<button data-key="${i}" aria-pressed="${i === key}">${k}</button>`).join('');
496 $('keys').addEventListener('click', (e) => {
497 const btn = e.target.closest('button[data-key]');
498 if (!btn) return;
499 key = Number(btn.dataset.key);
500 for (const b of $('keys').children) b.setAttribute('aria-pressed', b === btn);
501 });
502 // coupling: off, then 1 to about 3000 s^-1 on a log scale
503 const cpl = $('coupling');
504 const cplOut = () => { cpl.nextElementSibling.textContent = coupling ? `${Math.round(coupling)} s⁻¹` : 'off'; };
505 cpl.addEventListener('input', () => {
506 const u = Number(cpl.value);
507 coupling = u ? 10 ** (u / 20) : 0;
508 cplOut();
509 restartClicked();
510 });
511 cplOut();
512 const sus = $('sustain');
513 Object.assign(sus, { min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, value: SUSTAIN.default });
514 const susOut = () => { sus.nextElementSibling.textContent = `${Number(sus.value).toFixed(1)} s`; };
515 sus.addEventListener('input', () => {
516 susOut();
517 synth?.setSustain(Number(sus.value));
518 });
519 susOut();
520 const tempoOut = () => { $('tempo-out').textContent = `${$('tempo').value} /s`; };
521 $('tempo').addEventListener('input', tempoOut);
522 tempoOut();
523 const vol = $('volume');
524 const volOut = () => { vol.nextElementSibling.textContent = `${Math.round(100 * vol.value)}%`; };
525 vol.addEventListener('input', () => {
526 volOut();
527 if (synth && soundOn) synth.setVolume(Number(vol.value));
528 });
529 volOut();
530 $('sound').addEventListener('click', () => setSound(!soundOn));
531 $('clear').addEventListener('click', () => {
532 clicked = [];
533 reset();
534 renderLegend();
535 });
536 $('orbit-list').addEventListener('click', (e) => {
537 const btn = e.target.closest('button[data-hue]');
538 if (btn) removeOrbit(clicked.find((c) => String(c.hue) === btn.dataset.hue));
539 });
541 const hintOut = () => {
542 $('hint').textContent = $('click-mode').value === 'replace'
543 ? 'Click to start an orbit · click its start ring to remove it'
544 : 'Click to add orbits · click a start ring to remove it';
545 };
546 $('click-mode').addEventListener('change', hintOut);
547 hintOut();
549 canvas.addEventListener('pointerdown', (e) => {
550 const rect = canvas.getBoundingClientRect();
551 const r = plotRect();
552 const px = e.clientX - rect.left;
553 const py = e.clientY - rect.top;
554 if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return;
555 // on a start ring: remove that orbit; otherwise add one from here
556 const hit = clicked.find((c) => {
557 const [cx, cy] = toPx(r, c.x, c.v);
558 return Math.hypot(cx - px, cy - py) <= HIT_RADIUS;
559 });
560 if (hit) {
561 removeOrbit(hit);
562 return;
563 }
564 const x = ((px - r.x) / r.w * 2 - 1) * view.xr;
565 const v = (1 - (py - r.y) / r.h * 2) * view.vr;
566 if ($('click-mode').value === 'replace') {
567 // the new orbit takes the place of all the clicked ones
568 clicked = [];
569 orbits = orbits.filter((o) => !o.clicked);
570 clearDots([top]);
571 } else if (clicked.length >= MAX_CLICKED) removeOrbit(clicked[0]);
572 // the first voice no other orbit is playing
573 const voice = VOICES.findIndex((_, i) => !clicked.some((c) => c.voice === i));
574 const hue = (0.08 + hueCounter++ * 0.382) % 1;
575 clicked.push({ x, v, hue, voice, ph: newPlayhead(x, v) });
576 orbits.unshift(newOrbit(x, v, CLICK_POINTS, hue, true));
577 // coupled: the system has changed, so all restart together
578 if (coupling > 0) restartClicked();
579 renderLegend();
580 });
581}
583function removeOrbit(c) {
584 if (!c) return;
585 clicked = clicked.filter((q) => q !== c);
586 orbits = orbits.filter((o) => !o.clicked || o.hue !== c.hue);
587 if (coupling > 0) {
588 // coupled: the system has changed, so all restart together
589 restartClicked();
590 } else {
591 // redraw the clicked layer, so its dots go
592 clearDots([top]);
593 for (const o of orbits) if (o.clicked) drawPoints(o, 0);
594 }
595 renderLegend();
596}
598// the playing orbits: their color and voice, and a button to remove each
599function renderLegend() {
600 $('orbit-list').innerHTML = clicked.map((c) => `
601 <li>
602 <span class="swatch" style="background: ${orbitColor(c.hue, true)}"></span>
603 ${VOICES[c.voice].name}
604 <button data-hue="${c.hue}" aria-label="Remove the ${VOICES[c.voice].name} orbit">×</button>
605 </li>`).join('');
606}
608readTheme();
609matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); renderLegend(); });
610buildControls();
611reset();
612new ResizeObserver(resize).observe(canvas);
613resize();
614requestAnimationFrame(frame);