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