7212d95Hardening and softening tutorialJeremy Magland 1// The interactive panel of an oscillator slide, built into a container
2// element: the animated diagram (slowed down by SLOWDOWN) with Start, reset,
3// Play and volume in its corner, a slider for each parameter (see
4// controls.js), and an optional live spectrogram of the sound.
5//
6// Changing x0 resets the animation to rest at the new x0 and scales the
7// playing sound. The other parameters change both live, keeping the current
8// size of the swing (see retune in duffing.js).
10import { createLoop } from './canvas.js';
11import { bindSliders, createPresetSelect, physicsOf, sliderSpecs, slidersHTML, volumeHTML } from './controls.js';
12import { amplitude, omegaBound, retune, step } from './duffing.js';
13import { drawOscillator } from './oscillator-diagram.js';
14import { createSound } from './sound.js';
15import { createSpectrogram, SPEC_FFT } from './spectrogram.js';
17const SLOWDOWN = 100;
19function buildPanel(container, names, spec) {
20 container.innerHTML = `
21 <div class="stage">
22 <canvas class="oscillator"></canvas>
23 <div class="run-controls">
24 <button class="run" data-role="toggle">Start</button>
25 <button class="run" data-role="reset" aria-label="Reset" title="Reset">↺</button>
26 <button class="run" data-role="play" title="Play x(t) as sound, in real time">♫ Play</button>
27 ${volumeHTML()}
28 </div>
29 </div>
30 ${slidersHTML(names, spec)}
31 <div class="demo-footer">
32 <span class="caption">Simulation runs at 1/${SLOWDOWN}× real time</span>
33 <button class="link" data-role="spectrogram-toggle">Show spectrogram</button>
34 </div>
35 <canvas class="spectrogram" hidden></canvas>`;
36}
38// container: the element to build into. params: initial values, whose keys
39// pick the sliders (in SLIDERS order). sliders: per-slider overrides of
40// SLIDERS, by name. labels, damper: see drawOscillator. presets (optional):
41// [{ name, group?, params }] for a dropdown built into presetContainer;
42// choosing one sets the sliders and restarts the motion from rest at x0 (a
43// running animation, or one stopped by an escape, keeps running; a playing
44// sound keeps playing), and moving a slider by hand shows "Custom".
45// Returns the page's sim for deck.js: { draw, pause }.
46export function createOscillatorPage({ container, params, sliders = {}, labels, damper = false, presets = null, presetContainer = null }) {
47 const { names, spec } = sliderSpecs(params, sliders);
48 buildPanel(container, names, spec);
49 const q = (selector) => container.querySelector(selector);
50 const role = (name) => q(`[data-role="${name}"]`);
51 const canvas = q('canvas.oscillator');
52 const specCanvas = q('canvas.spectrogram');
53 const toggle = role('toggle');
55 const physics = () => physicsOf(params);
56 let p = physics();
57 const state = { x: params.x0, v: 0, phase: 0, escaped: false };
58 // the sound's normalization (see oscillator-worklet.js): without a drive,
59 // the largest |x| of the motion from rest at x0, which is x0 itself unless
60 // x0 is on the inner side of one of a double well's wells
61 const driven = 'F' in params;
62 const ref = () => (driven ? spec('x0').max : Math.max(Math.abs(params.x0), amplitude(p, params.x0, 0)));
64 const spectrogram = createSpectrogram(specCanvas);
65 // the driving force as an arrow on the block, longer for a stronger force
66 const drive = () => (driven && params.F > 0
67 ? Math.cos(state.phase) * Math.sqrt(params.F / (spec('F').max * spec('F').scale))
68 : null);
69 const drawDiagram = () => drawOscillator(canvas, state.x, { labels, damper, drive: drive(), escaped: state.escaped });
70 // Back to rest at x0, with the driving force at phase 0.
71 function restart() {
72 state.x = params.x0;
73 state.v = 0;
74 state.phase = 0;
75 state.escaped = false;
76 }
78 // If the block escapes, the animation stops with a note on the diagram;
79 // Start, or changing any slider, restarts it from x0 (a slider change
80 // keeps it running if it was).
81 let runAfterEscape = false;
82 // registered before createLoop's own handler, so it runs first
83 toggle.addEventListener('click', () => {
84 if (state.escaped) restart();
85 });
86 const loop = createLoop({
87 button: toggle,
88 step: (dt) => {
89 if (state.escaped) return; // the rest of the frame after an escape
90 step(p, state, dt, omegaBound(p, amplitude(p, state.x, state.v)));
91 if (state.escaped) {
92 loop.pause();
93 toggle.textContent = 'Start';
94 runAfterEscape = true;
95 }
96 },
97 draw: drawDiagram,
98 speed: 1 / SLOWDOWN,
99 });
100 const sound = createSound({
101 button: role('play'),
102 volume: role('volume'),
103 params: () => ({ ...p, x0: params.x0, ref: ref() }),
104 fftSize: SPEC_FFT,
105 onPlay: spectrogram.attach,
106 onStop: spectrogram.detach,
107 });
109 function reset() {
110 restart();
111 runAfterEscape = false;
112 loop.reset();
113 }
114 role('reset').addEventListener('click', reset);
116 const specToggle = role('spectrogram-toggle');
117 specToggle.addEventListener('click', () => {
118 specCanvas.hidden = !specCanvas.hidden;
119 specToggle.textContent = specCanvas.hidden ? 'Show spectrogram' : 'Hide spectrogram';
120 spectrogram.draw();
121 });
123 let presets_ = null;
124 const sliderControls = bindSliders({
125 root: container,
126 names,
127 spec,
128 params,
129 onInput: (name) => {
130 presets_?.markCustom();
131 const old = p;
132 p = physics();
133 if (state.escaped) {
134 restart();
135 if (runAfterEscape) loop.start();
136 runAfterEscape = false;
137 } else if (name === 'x0') {
138 reset();
139 } else {
140 retune(old, p, state);
141 }
142 drawDiagram();
143 sound.update();
144 },
145 });
147 if (presets) {
148 presets_ = createPresetSelect({
149 container: presetContainer,
150 presets,
151 params,
152 names,
153 onChoose: () => {
154 sliderControls.showAll();
155 p = physics();
156 const wasRunning = loop.isRunning() || runAfterEscape;
157 reset();
158 if (wasRunning) loop.start();
159 sound.restart();
160 },
161 });
162 }
164 // the sliders may have raised alpha to its bound
165 p = physics();
166 restart();
168 return {
169 draw: () => {
170 drawDiagram();
171 spectrogram.draw();
172 },
173 pause: () => {
174 loop.pause();
175 sound.stop();
176 },
177 };
178}