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