/ simulated_instruments / maraca
Sign in
simulated_instruments / maraca
maraca / webapp / src / App.tsx
308 lines · 10.7 KBBlameHistoryRaw
1import { useCallback, useEffect, useRef, useState } from 'react';
2import { DEFAULTS, loadParams, saveParams, type MaracaParams } from './params';
3import { DEFAULT_MFILES, type MFile } from './mfiles';
4import { useRenderer } from './hooks/useRenderer';
5import { encodeWav } from './lib/wav';
6import ParamPanel from './components/ParamPanel';
7import CodePanel from './components/CodePanel';
8import Scene3D from './components/Scene3D';
9import DiagnosticsPanel from './components/DiagnosticsPanel';
10import WaveformPlot from './components/plots/WaveformPlot';
11import SpectrumPlot from './components/plots/SpectrumPlot';
12import SpectrogramPlot from './components/plots/SpectrogramPlot';
13import ImpactRaster from './components/plots/ImpactRaster';
14import ModeMap from './components/plots/ModeMap';
16export default function App() {
17 const [params, setParams] = useState<MaracaParams>(() => loadParams());
18 // Editable copy of the MATLAB implementation. Deliberately not persisted:
19 // a reload restores the code the app shipped with.
20 const [mfiles, setMfiles] = useState<MFile[]>(() => DEFAULT_MFILES.map((f) => ({ ...f })));
21 const [codeOpen, setCodeOpen] = useState(false);
22 const { result, error, busy, stage, progress, elapsedS, renderPreview, renderFull, cancel } =
23 useRenderer(params, mfiles);
24 const audioCtxRef = useRef<AudioContext | null>(null);
26 useEffect(() => saveParams(params), [params]);
28 const onChange = useCallback((key: keyof MaracaParams, value: number | boolean) => {
29 setParams((p) => ({ ...p, [key]: value }));
30 }, []);
32 const reset = useCallback(() => setParams({ ...DEFAULTS }), []);
34 // A new seed redraws the whole impact process without touching anything
35 // else, which is the quickest way to hear how much of the character is the
36 // particular draw and how much is the parameters.
37 const reseed = useCallback(
38 () => setParams((p) => ({ ...p, seed: 1 + Math.floor(Math.random() * 9999) })),
39 [],
40 );
42 const onChangeFile = useCallback((name: string, source: string) => {
43 setMfiles((fs) => fs.map((f) => (f.name === name ? { ...f, source } : f)));
44 }, []);
46 const onResetFile = useCallback((name: string) => {
47 setMfiles((fs) =>
48 fs.map((f) =>
49 f.name === name
50 ? { ...f, source: DEFAULT_MFILES.find((d) => d.name === name)?.source ?? f.source }
51 : f,
52 ),
53 );
54 }, []);
56 const onResetAllFiles = useCallback(() => setMfiles(DEFAULT_MFILES.map((f) => ({ ...f }))), []);
57 const codeEdited = mfiles.some(
58 (f) => f.source !== DEFAULT_MFILES.find((d) => d.name === f.name)?.source,
59 );
61 const [looping, setLooping] = useState(false);
62 const loopSrcRef = useRef<AudioBufferSourceNode | null>(null);
64 // A failed render clears the result, so a loop left running has nothing to
65 // play; drop out of loop mode rather than leaving the button lit.
66 useEffect(() => {
67 if (!result) setLooping(false);
68 }, [result]);
70 const getAudioCtx = useCallback((sampleRate: number) => {
71 let ctx = audioCtxRef.current;
72 if (!ctx || ctx.state === 'closed') {
73 ctx = new AudioContext({ sampleRate });
74 audioCtxRef.current = ctx;
75 }
76 void ctx.resume();
77 return ctx;
78 }, []);
80 const makeBuffer = useCallback((ctx: AudioContext, r: NonNullable<typeof result>) => {
81 const buf = ctx.createBuffer(1, r.y.length, r.sampleRate);
82 buf.copyToChannel(new Float32Array(r.y), 0);
83 return buf;
84 }, []);
86 const play = useCallback(() => {
87 if (!result) return;
88 const ctx = getAudioCtx(result.sampleRate);
89 const src = ctx.createBufferSource();
90 src.buffer = makeBuffer(ctx, result);
91 src.connect(ctx.destination);
92 src.start();
93 }, [result, getAudioCtx, makeBuffer]);
95 // Loop mode: repeat the last render continuously, swapping in each new
96 // render as it completes.
97 useEffect(() => {
98 if (!looping || !result) return;
99 const ctx = getAudioCtx(result.sampleRate);
100 const src = ctx.createBufferSource();
101 src.buffer = makeBuffer(ctx, result);
102 src.loop = true;
103 src.connect(ctx.destination);
104 src.start();
105 loopSrcRef.current = src;
106 return () => {
107 loopSrcRef.current = null;
108 try {
109 src.stop();
110 } catch {
111 // already stopped
112 }
113 src.disconnect();
114 };
115 }, [looping, result, getAudioCtx, makeBuffer]);
117 const download = useCallback(() => {
118 if (!result) return;
119 const blob = encodeWav(result.y, result.sampleRate, params.bit_depth === 16 ? 16 : 24);
120 const url = URL.createObjectURL(blob);
121 const a = document.createElement('a');
122 a.href = url;
123 a.download = result.quality === 'full' ? 'maraca.wav' : 'maraca_preview.wav';
124 a.click();
125 setTimeout(() => URL.revokeObjectURL(url), 5000);
126 }, [result, params.bit_depth]);
128 return (
129 <div className="app">
130 <div className="topbar">
131 <h1>Maraca Simulator</h1>
132 <button
133 className="primary"
134 onClick={renderPreview}
135 disabled={busy}
136 title="No oversampling, everything else unchanged — the fast pass"
137 >
138 Render preview
139 </button>
140 <button
141 className="primary"
142 onClick={renderFull}
143 disabled={busy}
144 title="Full quality at the oversampling the parameters ask for"
145 >
146 Render full
147 </button>
148 {busy && (
149 <button onClick={cancel} title="Stop the render">
150 ✕ Cancel
151 </button>
152 )}
153 <button
154 className={`play ${result?.quality === 'preview' ? 'preview' : ''}`}
155 onClick={play}
156 disabled={!result}
157 title={
158 result?.quality === 'preview'
159 ? 'Playing the preview render; press Render full for full quality'
160 : 'Play the rendered shake'
161 }
162 >
163 ▶ Play{result?.quality === 'preview' ? ' (preview)' : ''}
164 </button>
165 <button
166 className={`loop ${looping ? 'active' : ''}`}
167 onClick={() => setLooping((v) => !v)}
168 disabled={!result}
169 title="Repeat the last render continuously"
170 >
171 ⟳ Loop{looping ? ' on' : ''}
172 </button>
173 <button onClick={reseed} title="Draw a new impact process from a new random seed">
174 ⚄ New seed
175 </button>
176 <button onClick={download} disabled={!result}>
177 Download .wav{result?.quality === 'preview' ? ' (preview)' : ''}
178 </button>
179 <button onClick={reset}>Reset to defaults</button>
180 <button
181 className={codeOpen ? 'code active' : 'code'}
182 onClick={() => setCodeOpen((v) => !v)}
183 title="View and edit the MATLAB source that numbl executes"
184 >
185 {'{ }'} Code{codeEdited ? ' •' : ''}
186 </button>
187 <div className="status">
188 {error && <span className="badge err">code error</span>}
189 {result && !busy && (
190 <span className={`badge ${result.quality}`}>
191 {result.quality === 'full' ? 'full quality' : 'preview quality'}
192 </span>
193 )}
194 {busy ? (
195 <>
196 <span>
197 {stage}… {elapsedS.toFixed(0)} s
198 </span>
199 <div className="progressbar">
200 <div style={{ width: `${Math.round(progress * 100)}%` }} />
201 </div>
202 </>
203 ) : (
204 <span>ready</span>
205 )}
206 </div>
207 </div>
208 <div className="main">
209 <div className="sidebar">
210 <ParamPanel params={params} onChange={onChange} />
211 </div>
212 <div className="content">
213 {error && (
214 <div className="card wide error-card">
215 <h2>MATLAB error</h2>
216 <div>
217 <strong>
218 {error.file ? `${error.file}${error.line ? `:${error.line}` : ''}` : 'error'}
219 </strong>{' '}
220 {error.message}
221 </div>
222 <div className="code-hint">
223 Nothing is playable until a render succeeds. Open Code to fix the source, or
224 revert it.
225 </div>
226 </div>
227 )}
228 <div className="card wide">
229 <h2>Geometry — shell, grain impacts, microphone</h2>
230 <Scene3D
231 params={params}
232 impactPos={result?.impactPos ?? null}
233 impactV={result?.impactV ?? null}
234 impactT={result?.impactT ?? null}
235 />
236 </div>
237 {result && (
238 <>
239 <div className="card">
240 <h2>Diagnostics</h2>
241 <DiagnosticsPanel result={result} />
242 </div>
243 <div className="card">
244 <h2>Impact process</h2>
245 <ImpactRaster
246 impactT={result.impactT}
247 impactV={result.impactV}
248 rateT={result.rateT}
249 rateHz={result.rateHz}
250 durationS={result.diag.durationS}
251 impactCount={result.diag.impactCount}
252 plotted={result.impactT.length}
253 />
254 </div>
255 <div className="card">
256 <h2>Waveform</h2>
257 <WaveformPlot y={result.y} sampleRate={result.sampleRate} />
258 </div>
259 <div className="card">
260 <h2>Spectrum</h2>
261 <SpectrumPlot
262 y={result.y}
263 sampleRate={result.sampleRate}
264 modeF={result.modeF}
265 breathingHz={result.diag.breathingHz}
266 />
267 </div>
268 <div className="card">
269 <h2>Spectrogram</h2>
270 <SpectrogramPlot y={result.y} sampleRate={result.sampleRate} />
271 </div>
272 <div className="card">
273 <h2>Shell modes</h2>
274 <ModeMap
275 modeF={result.modeF}
276 modeL={result.modeL}
277 modeZeta={result.modeZeta}
278 modeSigma={result.modeSigma}
279 breathingHz={result.diag.breathingHz}
280 />
281 </div>
282 </>
283 )}
284 {!result && !busy && !error && (
285 <div className="card wide">
286 <h2>No render yet</h2>
287 <div className="code-hint">
288 Press Render preview for a fast pass with no oversampling, or Render full for the real thing. Nothing renders on its own: change what you like, then render.
289 </div>
290 </div>
291 )}
292 </div>
293 </div>
294 {codeOpen && (
295 <CodePanel
296 mfiles={mfiles}
297 onChangeFile={onChangeFile}
298 onResetFile={onResetFile}
299 onResetAll={onResetAllFiles}
300 onClose={() => setCodeOpen(false)}
301 onRenderFull={renderFull}
302 error={error}
303 busy={busy}
304 />
305 )}
306 </div>
307 );
↑↓ move↵openescclose