/ interactive_tutorials / hardening_softening
Sign in
interactive_tutorials / hardening_softening
hardening_softening / app / js / phase-page.js
573 lines · 20.1 KBCodeBlameHistory
7212d95Hardening and softening tutorialJeremy Magland 1// The phase-space slide: orbits of the oscillator in the (x, x') plane, with
2// x' = p/m (see orbits.js for which orbits), computed in a worker whenever the
3// parameters change. The orbits show the structure of the phase plane; they
4// all keep one style. Playing means the sound (as on the other slides, normalized to the orbit's largest
5// |x|) and a point running along it with a fading tail, at 1/100 x or real
6// time. Stop, or changing a parameter, stops it. Clicking any point of the
7// plot, on an orbit or not, adds the orbit from that point and plays it from
8// there (on an existing orbit, the same curve); for a driven system it
9// starts at drive phase 0, and the path to its settled motion is drawn
10// faintly. Added orbits are marked at their start and kept (the last
11// MAX_ADDED) until a parameter changes.
12//
13// controls: the element for the presets dropdown and sliders. container: the
14// element for the plot and its buttons. params: initial slider values (see
15// controls.js; no x0, since each orbit has its own start). sliders: per-slider
16// overrides. presets: [{ name, group?, params }]. instruments: also offer
17// instruments, fixed linear filters applied to the sound (instruments.js),
18// with a dry / wet mix and loudness normalization, and optionally a notch
19// (NOTCH_Q) removing the driving frequency first; tuned ones follow the
20// current |f0| (220 Hz when f0 = 0). An optional live spectrogram shows what
21// is heard (before the volume); while it shows, the plot is shorter.
23import { color, DRAW_SCALE, prepare } from './canvas.js';
24import { bindSliders, createPresetSelect, physicsOf, sliderSpecs, slidersHTML, volumeHTML } from './controls.js';
25import { amplitude, omegaBound, step, X_MAX } from './duffing.js';
f598eb6Start the orbits worker on sandboxed sitesJeremy Magland 26import { computeOrbitFrom, computeOrbits } from './orbits.js';
7212d95Hardening and softening tutorialJeremy Magland 27import { createInstrumentChain } from './instrument-chain.js';
28import { DEFAULT_SCALE, impulseResponse, INSTRUMENTS, SCALES } from './instruments.js';
29import { createSound } from './sound.js';
30import { createSpectrogram, SPEC_FFT } from './spectrogram.js';
32const SPEEDS = [{ label: '1/100×', value: 0.01 }, { label: 'real time', value: 1 }];
33const TAIL_SECONDS = 0.5; // on screen
34const MAX_TAIL = 6000;
35const MAX_ADDED = 8;
36const NOTCH_Q = 30; // the drive notch: about (Omega / 2 pi) / NOTCH_Q wide
38// round steps for axis ticks
39function tickStep(range) {
40 const raw = range / 4;
41 const mag = 10 ** Math.floor(Math.log10(raw));
42 return [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw);
f598eb6Start the orbits worker on sandboxed sitesJeremy Magland 45// A worker running orbits-worker.js. A sandboxed page (one served with an
46// opaque origin, as on the vault's sites) may not start a worker from its own
47// URL, so then start one from a small in-memory module that imports it; and if
48// that fails too, compute on the main thread, through the same messages.
49function createOrbitsWorker() {
50 const url = new URL('./orbits-worker.js', import.meta.url);
51 try {
52 return new Worker(url, { type: 'module' });
53 } catch {
54 try {
55 const blob = new Blob([`import ${JSON.stringify(url.href)};`], { type: 'text/javascript' });
56 return new Worker(URL.createObjectURL(blob), { type: 'module' });
57 } catch {
58 const fallback = {
59 onmessage: null,
60 terminate() { this.onmessage = null; },
61 postMessage({ id, p, from }) {
62 setTimeout(() => {
63 const data = from ? { id, orbit: computeOrbitFrom(p, from) } : { id, ...computeOrbits(p) };
64 fallback.onmessage?.({ data });
65 }, 0);
66 },
67 };
68 return fallback;
69 }
70 }
7212d95Hardening and softening tutorialJeremy Magland 73export function createPhasePage({ controls, container, params, sliders = {}, presets, instruments = false }) {
74 const { names, spec } = sliderSpecs(params, sliders);
75 const instrumentOptions = Object.entries(INSTRUMENTS).map(([key, { label }]) => `<option value="${key}">${label}</option>`).join('');
76 controls.innerHTML = `<div class="presets" data-presets></div>${slidersHTML(names, spec)}${instruments ? `
77 <div class="instrument-controls">
78 <label class="preset">Filter <select data-role="instrument">${instrumentOptions}</select></label>
79 <label class="preset">Scale <select data-role="scale">${Object.entries(SCALES).map(([key, { label }]) => `<option value="${key}">${label}</option>`).join('')}</select></label>
80 <div class="sliders">
81 <label class="row"><span>Dry / wet</span>
82 <input data-role="wet" type="range" min="0" max="1" step="0.01">
83 <output data-role="wet-value"></output>
84 </label>
85 </div>
86 <label class="check"><input data-role="normalize" type="checkbox"> Normalize loudness</label>
87 <label class="check"><input data-role="notch" type="checkbox"> Remove the driving frequency</label>
88 </div>` : ''}`;
89 container.innerHTML = `
90 <div class="stage">
91 <canvas class="phase"></canvas>
92 <div class="run-controls">
93 <button class="run" data-role="speed" title="Speed of the point along the orbit">Speed: ${SPEEDS[0].label}</button>
94 <button class="run" data-role="stop" disabled>&#9632; Stop</button>
95 ${volumeHTML()}
96 </div>
97 </div>
98 <div class="demo-footer">
99 <span class="caption">Click any point to start an orbit there and play it.</span>
100 <button class="link" data-role="spectrogram-toggle">Show spectrogram</button>
101 </div>
102 <canvas class="spectrogram" hidden></canvas>`;
103 const canvas = container.querySelector('canvas.phase');
104 const role = (name) => container.querySelector(`[data-role="${name}"]`);
105 const speedButton = role('speed');
106 const stopButton = role('stop');
108 let p = physicsOf(params);
109 let result = null; // { orbits, xmax, vmax }
110 let computing = false;
111 let playing = -1;
112 let speed = 0; // index into SPEEDS
113 let view = null; // the mapping used by the last draw, for hovering
115 // --- the sound and the point along the orbit
117 let playParams = null;
119 // the instrument the sound drives (when offered), live while playing
120 const inst = { name: 'raw', scale: DEFAULT_SCALE, wet: 0.95, normalize: true, notch: false };
121 // the notch before the instrument: on only with a drive; otherwise an all-pass
122 // (which leaves every frequency's level alone)
123 let notch = null;
124 const setNotch = () => {
125 if (!notch) return;
126 const on = inst.notch && p.F > 0 && p.Omega > 0;
127 notch.type = on ? 'notch' : 'allpass';
128 notch.frequency.value = on ? p.Omega / (2 * Math.PI) : 1000;
129 };
130 let chain = null;
131 const instrumentSettings = () => ({ name: inst.name, base: Math.abs(params.freq) || 220, scale: inst.scale, wet: inst.wet });
132 if (instruments) {
133 const q = (r) => controls.querySelector(`[data-role="${r}"]`);
134 const select = q('instrument');
135 const wetInput = q('wet');
136 const wetOutput = q('wet-value');
137 const normalize = q('normalize');
138 normalize.checked = inst.normalize;
139 const notchBox = q('notch');
140 notchBox.checked = inst.notch;
141 notchBox.addEventListener('change', () => {
142 inst.notch = notchBox.checked;
143 setNotch();
144 });
145 normalize.addEventListener('change', () => {
146 inst.normalize = normalize.checked;
147 chain?.setNormalize(inst.normalize);
148 });
149 const scaleSelect = q('scale');
150 // the scale applies to the marimba and harp only
151 const showScale = () => { scaleSelect.disabled = !INSTRUMENTS[inst.name].usesScale; };
152 select.value = inst.name;
153 scaleSelect.value = inst.scale;
154 showScale();
155 wetInput.value = inst.wet;
156 wetOutput.textContent = inst.wet.toFixed(2);
157 select.addEventListener('change', () => {
158 inst.name = select.value;
159 showScale();
160 chain?.set(instrumentSettings());
161 });
162 scaleSelect.addEventListener('change', () => {
163 inst.scale = scaleSelect.value;
164 chain?.set(instrumentSettings());
165 });
166 wetInput.addEventListener('input', () => {
167 inst.wet = Number(wetInput.value);
168 wetOutput.textContent = inst.wet.toFixed(2);
169 chain?.setWet(inst.wet);
170 });
171 }
172 // the live spectrogram: of the instrument when there is one, else of the oscillator
173 const specCanvas = container.querySelector('canvas.spectrogram');
174 const spectrogram = createSpectrogram(specCanvas);
175 const specToggle = role('spectrogram-toggle');
176 specToggle.addEventListener('click', () => {
177 specCanvas.hidden = !specCanvas.hidden;
178 container.classList.toggle('with-spectrogram', !specCanvas.hidden);
179 specToggle.textContent = specCanvas.hidden ? 'Show spectrogram' : 'Hide spectrogram';
180 draw();
181 spectrogram.draw();
182 });
184 const route = instruments
185 ? async (ctx, osc) => {
186 chain = await createInstrumentChain(ctx, impulseResponse);
187 notch = ctx.createBiquadFilter();
188 notch.Q.value = NOTCH_Q;
189 setNotch();
190 osc.connect(notch).connect(chain.input);
191 chain.set(instrumentSettings());
192 chain.setNormalize(inst.normalize);
193 const analyser = ctx.createAnalyser();
194 analyser.fftSize = SPEC_FFT;
195 analyser.smoothingTimeConstant = 0;
196 chain.output.connect(analyser);
197 spectrogram.attach(analyser);
198 return chain.output;
199 }
200 : null;
201 const sound = createSound({
202 volume: role('volume'),
203 params: () => playParams,
204 route,
205 fftSize: instruments ? 0 : SPEC_FFT,
206 onPlay: (analyser) => { if (analyser) spectrogram.attach(analyser); },
207 onStop: () => {
208 chain = null;
209 notch = null;
210 spectrogram.detach();
211 },
212 });
213 let trace = null; // { s, t, tail: [t, x, v, ...] }
214 let rafId = null;
215 let lastFrame = null;
217 function stopPlaying() {
218 playing = -1;
219 trace = null;
220 cancelAnimationFrame(rafId);
221 sound.stop();
222 stopButton.disabled = true;
223 draw();
224 }
226 function play(i) {
227 const o = result.orbits[i];
228 playing = i;
229 playParams = { ...p, x0: o.start.x, ref: o.ref };
230 sound.play({ ...o.start });
231 trace = { s: { ...o.start, escaped: false }, t: 0, tail: [0, o.start.x, o.start.v] };
232 stopButton.disabled = false;
233 lastFrame = null;
234 cancelAnimationFrame(rafId);
235 rafId = requestAnimationFrame(frame);
236 }
238 function frame(now) {
239 if (!trace) return;
240 if (lastFrame !== null && !trace.s.escaped) {
241 const dt = Math.min((now - lastFrame) / 1000, 0.05) * SPEEDS[speed].value;
242 // record about 40 points per oscillation
243 const w = Math.max(omegaBound(p, 0.5), p.F ? p.Omega : 0, 2 * Math.PI);
244 const n = Math.min(4000, Math.max(1, Math.ceil(dt / ((2 * Math.PI) / (w * 40)))));
245 const { s } = trace;
246 for (let i = 0; i < n && !s.escaped; i++) {
247 step(p, s, dt / n, omegaBound(p, Math.min(X_MAX, 1.2 * Math.max(amplitude(p, s.x, s.v), Math.abs(s.x)))));
248 trace.t += dt / n;
249 trace.tail.push(trace.t, s.x, s.v);
250 }
251 const keep = TAIL_SECONDS * SPEEDS[speed].value;
252 let cut = 0;
253 while (cut < trace.tail.length - 3 && (trace.tail[cut] < trace.t - keep || trace.tail.length - cut > 3 * MAX_TAIL)) cut += 3;
254 if (cut) trace.tail.splice(0, cut);
255 }
256 lastFrame = now;
257 draw();
258 rafId = requestAnimationFrame(frame);
259 }
261 speedButton.addEventListener('click', () => {
262 speed = (speed + 1) % SPEEDS.length;
263 speedButton.textContent = `Speed: ${SPEEDS[speed].label}`;
264 if (trace) trace.tail = trace.tail.slice(-3);
265 });
266 stopButton.addEventListener('click', stopPlaying);
268 // --- computing the orbits, in a worker; a new request replaces a running one
270 let worker = null;
271 let busy = false;
272 let requestId = 0;
273 let timer = null;
275 function compute() {
276 if (busy) {
277 worker.terminate();
278 worker = null;
279 }
280 if (!worker) {
f598eb6Start the orbits worker on sandboxed sitesJeremy Magland 281 worker = createOrbitsWorker();
7212d95Hardening and softening tutorialJeremy Magland 282 worker.onmessage = (e) => {
283 if (e.data.id !== requestId) return;
284 busy = false;
285 computing = false;
286 result = e.data;
287 draw();
288 };
289 }
290 busy = true;
291 computing = true;
292 requestId++;
293 worker.postMessage({ id: requestId, p });
294 draw();
295 }
297 // the orbit from a clicked point, in a second worker, so the full set keeps
298 // its own; a new click replaces a pending one
299 let oneWorker = null;
300 let oneBusy = false;
301 let oneId = 0;
302 let pendingPoint = null; // { x, v } being computed
304 function cancelAdded() {
305 if (oneBusy) {
306 oneWorker.terminate();
307 oneWorker = null;
308 oneBusy = false;
309 }
310 oneId++;
311 pendingPoint = null;
312 }
314 function addOrbitFrom(point) {
315 stopPlaying();
316 cancelAdded();
317 if (!oneWorker) {
f598eb6Start the orbits worker on sandboxed sitesJeremy Magland 318 oneWorker = createOrbitsWorker();
7212d95Hardening and softening tutorialJeremy Magland 319 oneWorker.onmessage = (e) => {
320 if (e.data.id !== oneId || !result) return;
321 oneBusy = false;
322 pendingPoint = null;
323 const added = result.orbits.filter((o) => o.added);
324 if (added.length >= MAX_ADDED) result.orbits.splice(result.orbits.indexOf(added[0]), 1);
325 result.orbits.push({ ...e.data.orbit, added: true });
326 play(result.orbits.length - 1);
327 };
328 }
329 oneBusy = true;
330 pendingPoint = point;
331 oneWorker.postMessage({ id: oneId, p, from: point });
332 draw();
333 }
335 function changed() {
336 cancelAdded();
337 stopPlaying();
338 p = physicsOf(params);
339 computing = true;
340 clearTimeout(timer);
341 timer = setTimeout(compute, 100);
342 draw();
343 }
345 let presetSelect = null;
346 const sliderControls = bindSliders({
347 root: controls,
348 names,
349 spec,
350 params,
351 onInput: () => {
352 presetSelect?.markCustom();
353 changed();
354 },
355 });
356 presetSelect = createPresetSelect({
357 container: controls.querySelector('[data-presets]'),
358 presets,
359 params,
360 names,
361 onChoose: () => {
362 sliderControls.showAll();
363 changed();
364 },
365 });
367 // --- drawing
369 function draw() {
370 if (!canvas.clientWidth) return;
371 const { ctx, w, h } = prepare(canvas);
372 const fg = color('--fg');
373 const left = 64;
374 const right = 14;
375 const top = 40; // below the buttons
376 const bottom = 36;
377 const pw = w - left - right;
378 const ph = h - top - bottom;
380 // axes: symmetric, fitted to the orbits; escaping paths do not set x'
381 const orbits = result?.orbits ?? [];
382 let xmax = result?.xmax ?? 0.5;
383 for (const o of orbits) {
384 if (!o.added) continue;
385 for (const arr of [o.pts, o.path ?? []]) for (let i = 0; i < arr.length; i += 2) xmax = Math.max(xmax, Math.abs(arr[i]));
386 }
387 const xr = 1.08 * Math.max(Math.min(xmax, X_MAX), 0.05);
388 let vmax = 0;
389 for (const o of orbits) {
390 if (o.kind === 'escape') continue;
391 for (let i = 1; i < o.pts.length; i += 2) vmax = Math.max(vmax, Math.abs(o.pts[i]));
392 }
393 if (!vmax) vmax = result?.vmax || 1;
394 const vr = 1.08 * vmax;
395 const X = (x) => left + ((x + xr) / (2 * xr)) * pw;
396 const Y = (v) => top + ph / 2 - (v / vr) * (ph / 2);
397 view = { X, Y, left, top, pw, ph, xr, vr };
399 ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
400 ctx.strokeStyle = fg;
401 ctx.fillStyle = fg;
402 ctx.lineWidth = 1;
403 ctx.strokeRect(left, top, pw, ph);
404 ctx.globalAlpha = 0.25;
405 ctx.beginPath();
406 ctx.moveTo(X(0), top);
407 ctx.lineTo(X(0), top + ph);
408 ctx.moveTo(left, Y(0));
409 ctx.lineTo(left + pw, Y(0));
410 ctx.stroke();
411 ctx.globalAlpha = 1;
412 // ticks
413 ctx.textAlign = 'center';
414 ctx.textBaseline = 'top';
415 const xs = tickStep(2 * xr);
416 for (let x = -Math.floor(xr / xs) * xs; x <= xr + 1e-9; x += xs) {
417 ctx.beginPath();
418 ctx.moveTo(X(x), top + ph);
419 ctx.lineTo(X(x), top + ph + 4);
420 ctx.stroke();
421 ctx.fillText(Math.abs(x) < 1e-9 ? '0' : x.toFixed(2).replace(/0$/, ''), X(x), top + ph + 6);
422 }
423 ctx.textAlign = 'right';
424 ctx.textBaseline = 'middle';
425 const vs = tickStep(2 * vr);
426 for (let v = -Math.floor(vr / vs) * vs; v <= vr + 1e-9; v += vs) {
427 ctx.beginPath();
428 ctx.moveTo(left - 4, Y(v));
429 ctx.lineTo(left, Y(v));
430 ctx.stroke();
431 ctx.fillText(Math.abs(v) < 1e-9 ? '0' : String(Math.round(v)), left - 6, Y(v));
432 }
433 ctx.font = 'italic 17px Georgia, serif';
434 ctx.textAlign = 'right';
435 ctx.textBaseline = 'bottom';
436 ctx.fillText('x', left + pw - 4, Y(0) - 4);
437 ctx.textAlign = 'left';
438 ctx.textBaseline = 'top';
439 ctx.fillText('ẋ = p/m', X(0) + 6, top + 4);
441 // orbits, clipped to the plot
442 ctx.save();
443 ctx.beginPath();
444 ctx.rect(left, top, pw, ph);
445 ctx.clip();
446 const accent = color('--accent');
447 const force = color('--force');
448 // a playing added driven orbit's path from the clicked point to its
449 // settled motion, faint (only while it plays, or the paths would bury the
450 // plot)
451 if (playing >= 0 && orbits[playing]?.path) {
452 ctx.globalAlpha = 0.35;
453 ctx.lineWidth = 0.8;
454 ctx.strokeStyle = accent;
455 polyline(ctx, orbits[playing].path, X, Y);
456 }
457 orbits.forEach((o) => {
458 ctx.globalAlpha = o.kind === 'irregular' ? 0.5 : 0.85;
459 ctx.lineWidth = o.kind === 'irregular' ? 0.5 : 1.2;
460 ctx.strokeStyle = o.kind === 'escape' ? force : accent;
461 polyline(ctx, o.pts, X, Y);
462 });
463 // where each added orbit starts, and a click still being computed
464 ctx.globalAlpha = 1;
465 ctx.lineWidth = 1.5;
466 orbits.forEach((o) => {
467 if (!o.added) return;
468 ctx.strokeStyle = o.kind === 'escape' ? force : accent;
469 ctx.beginPath();
470 ctx.arc(X(o.start.x), Y(o.start.v), 4, 0, 2 * Math.PI);
471 ctx.stroke();
472 });
473 if (pendingPoint) {
474 ctx.strokeStyle = fg;
475 ctx.beginPath();
476 ctx.arc(X(pendingPoint.x), Y(pendingPoint.v), 4, 0, 2 * Math.PI);
477 ctx.stroke();
478 }
479 // the point along the playing orbit, with its fading tail
480 if (trace) {
481 const tail = trace.tail;
482 const orange = color('--brand-orange');
483 ctx.strokeStyle = orange;
484 ctx.lineWidth = 2.5;
485 const keep = TAIL_SECONDS * SPEEDS[speed].value;
486 const segs = 24;
487 for (let k = 0; k < segs; k++) {
488 // the tail in segs pieces, older ones fainter
489 const t0 = trace.t - keep * (1 - k / segs);
490 const t1 = trace.t - keep * (1 - (k + 1) / segs);
491 ctx.globalAlpha = (k + 1) / segs;
492 ctx.beginPath();
493 let started = false;
494 for (let j = 0; j < tail.length; j += 3) {
495 if (tail[j] < t0 || tail[j] > t1 + 1e-12) continue;
496 if (!started) {
497 // start from the previous point, so the pieces join up
498 const k0 = Math.max(0, j - 3);
499 ctx.moveTo(X(tail[k0 + 1]), Y(tail[k0 + 2]));
500 started = true;
501 }
502 ctx.lineTo(X(tail[j + 1]), Y(tail[j + 2]));
503 }
504 ctx.stroke();
505 }
506 ctx.globalAlpha = 1;
507 if (!trace.s.escaped) {
508 ctx.fillStyle = orange;
509 ctx.beginPath();
510 ctx.arc(X(trace.s.x), Y(trace.s.v), 5, 0, 2 * Math.PI);
511 ctx.fill();
512 }
513 }
514 ctx.restore();
515 ctx.globalAlpha = 1;
517 if (computing || pendingPoint) {
518 ctx.fillStyle = fg;
519 ctx.globalAlpha = 0.6;
520 ctx.font = '15px "Hanken Grotesk", system-ui, sans-serif';
521 ctx.textAlign = 'left';
522 ctx.textBaseline = 'top';
523 ctx.fillText(computing ? 'Computing orbits\u2026' : 'Computing the orbit\u2026', left + 8, top + 8);
524 ctx.globalAlpha = 1;
525 }
526 }
528 function polyline(ctx, pts, X, Y) {
529 ctx.beginPath();
530 ctx.moveTo(X(pts[0]), Y(pts[1]));
531 for (let i = 2; i < pts.length; i += 2) ctx.lineTo(X(pts[i]), Y(pts[i + 1]));
532 ctx.stroke();
533 }
535 // --- hovering and clicking
537 // the pointer in drawing units
538 function pointer(e) {
539 const rect = canvas.getBoundingClientRect();
540 const scale = canvas.clientWidth / rect.width / DRAW_SCALE; // client pixels to drawing units
541 return [(e.clientX - rect.left) * scale, (e.clientY - rect.top) * scale];
542 }
544 // the point of the plane under the pointer, { x, v }, or null outside the plot
545 function pointAt(e) {
546 if (!view) return null;
547 const [mx, my] = pointer(e);
548 const { left, top, pw, ph, xr, vr } = view;
549 if (mx < left || mx > left + pw || my < top || my > top + ph) return null;
550 const x = ((mx - left) / pw) * 2 * xr - xr;
551 const v = ((top + ph / 2 - my) / (ph / 2)) * vr;
552 return Math.abs(x) < X_MAX ? { x, v } : null;
553 }
555 canvas.addEventListener('mousemove', (e) => {
556 canvas.style.cursor = pointAt(e) ? 'crosshair' : '';
557 });
558 // a click anywhere in the plot starts the orbit from that point
559 canvas.addEventListener('click', (e) => {
560 const point = pointAt(e);
561 if (point) addOrbitFrom(point);
562 });
564 compute();
566 return {
567 draw: () => {
568 draw();
569 spectrogram.draw();
570 },
571 pause: stopPlaying,
572 };
↑↓ move↵openescclose