/ music / double-pendulum
Sign in
music / double-pendulum
crash: fixed-pitch 'bottom notes' (no longer called crashes)
The note when the outer bob crosses below the pivot now has one pitch (G3 by default) instead of following the height, and is called a bottom note throughout (settings group 'bottom', readouts, README, code). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 5d7ea1ad21aa parent 7748f61 Browse files
7 changed files+74−77
README.mdmodified+6−2View file
@@ -70,9 +70,13 @@ The pendulums swing freely (energy conserved) for **swinging** (40 s). Then each
7070
7171 ## 4. crash
7272
73-One pendulum, balanced straight up. It gets a tiny nudge, calibrated so it visibly tips at **tips after** (5 s); each play picks the side and shape at random. Short piano notes (Piano-ish) mark the outer bob's height. Think of a ladder of levels: every other note of the scale between C4 (bottom) and C7 (top). Each time the height passes a level, going up or down, that level's note plays, with a small margin so hovering doesn't re-trigger it. You hear the fall as a descending run. The notes ramp in over the opening and quiet with the energy at the end. When the bob first swings through the bottom, there's an accented "crash": a short violin note at the violin's lowest G. After that, every crossing of the vertical *below* the pivot is a crash. Crossings closer than **minimum depth** (25% of the length) to the pivot are not crashes. With equal arms, a folded pendulum sweeps its bob right through the pivot, and those passes play a **click** instead (a modal-synth instrument, by default a 0.5 s Viola note at C5, with strength from the bob's speed). The pitch rises continuously with the height of the crossing (from **pitch at bottom** to **pitch at min depth**), and its strength follows the bob's speed. The first crash is an accent.
73+One pendulum, balanced straight up. It gets a tiny nudge, calibrated so it visibly tips at **tips after** (5 s); each play picks the side and shape at random.
7474
75-There's slight friction throughout. Over the damping section it grows smoothly to **final damping**, until the pendulum comes to rest. The last crash rings out and the voice fades with it. The crashes render ahead in a worker, and a device check limits how many may ring at once (**overlapping crashes**). This matters for heavy instruments like Chaos gong, about 14% of a core per ringing crash; the violin is about 3%.
75+- **Height notes**: short piano notes (Piano-ish) mark the outer bob's height. Think of a ladder of levels: every other note of the scale between C4 (bottom) and C7 (top). Each time the height passes a level, going up or down, that level's note plays, with a small margin so hovering doesn't re-trigger it. You hear the fall as a descending run. The notes ramp in over the opening and quiet with the energy at the end.
76+- **Bottom notes**: each time the outer bob crosses the vertical below the pivot, a short violin note plays at a fixed pitch (G3), with its strength from the bob's speed. The first one, at the bottom of the fall, is accented.
77+- **Clicks**: crossings closer than **minimum depth** (25% of the length) to the pivot aren't bottom notes. With equal arms, a folded pendulum sweeps its bob right through the pivot, and those passes play a click instead (by default a 0.5 s Viola note at C5).
78+
79+There's slight friction throughout. Over the damping section it grows smoothly to **final damping**, until the pendulum comes to rest. The last bottom note rings out. The instruments render ahead in workers, and a device check limits how many bottom notes may ring at once (**overlapping notes**). This matters for heavy instruments like Chaos gong, about 14% of a core per ringing note; the violin is about 3%.
7680
7781 ## Deploying
7882
site/assets/index-DWceBk6K.js →site/assets/index-6HGfP7XN.jsrenamed+1−1View file
@@ -1,2 +1,2 @@
11 (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=null;async function t(){if(!e){let t=new AudioContext({latencyHint:`playback`}),n=t.createGain(),r=t.createDynamicsCompressor();r.threshold.value=-6,r.knee.value=6,r.ratio.value=12,r.attack.value=.003,r.release.value=.25,n.connect(r).connect(t.destination),e={ctx:t,input:n}}return e.ctx.state!==`running`&&await e.ctx.resume(),e}function n(e){return 10**(e/20)}function r(e){let t={};for(let n of e)t[n.key]=n.default;return t}function i(e,...t){let n=r(e);for(let r of t)if(r)for(let t of e){let e=r[t.key];e!==void 0&&(t.kind===`number`&&typeof e==`number`&&Number.isFinite(e)||t.kind===`select`&&typeof e==`string`&&t.options.includes(e)||t.kind===`bool`&&typeof e==`boolean`||t.kind===`text`&&typeof e==`string`)&&(n[t.key]=e)}return n}function a(e,t){let n={};for(let r of e)n[r.key]=t[r.key];return JSON.stringify(n,null,2)+`
2-`}var o=1e3;function s(e,t){let n=e.log?Math.log(t/e.min)/Math.log(e.max/e.min):(t-e.min)/(e.max-e.min);return Math.round(Math.max(0,Math.min(1,n))*o)}function c(e,t){let n=t/o,r=e.log?e.min*(e.max/e.min)**+n:e.min+n*(e.max-e.min);return e.step&&(r=Math.round(r/e.step)*e.step),Number(r.toPrecision(4))}function l(e){return String(Number(e.toPrecision(4)))}function u(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function d(e){let t=u(`aside`,{className:`author`}),n=[],r=(t,n)=>{e.set({...e.get(),[t]:n})},d=u(`span`,{className:`status`}),f=e=>{d.textContent=e,window.setTimeout(()=>{d.textContent===e&&(d.textContent=``)},2e3)},p=u(`button`,{textContent:`copy config`});p.onclick=async()=>{let t=a(e.schema,e.get());try{await navigator.clipboard.writeText(t),f(`copied`)}catch{window.prompt(`copy:`,t)}};let m=u(`button`,{textContent:`paste config`});m.onclick=async()=>{let t=null;try{t=await navigator.clipboard.readText()}catch{t=window.prompt(`paste config JSON:`)}if(t)try{e.set(i(e.schema,JSON.parse(t))),y(),f(`pasted`)}catch{f(`not valid JSON`)}};let h=u(`button`,{textContent:`reset to defaults`});h.onclick=()=>{window.confirm(`Discard your edits and return to the published defaults?`)&&(e.set(e.defaults()),y())},t.append(u(`div`,{className:`actions`},p,m,h,d));let g=u(`input`,{type:`number`,min:`0`,step:`1`,value:String(e.startAt.value)});g.oninput=()=>{e.startAt.value=Math.max(0,Number(g.value)||0)},t.append(u(`label`,{className:`row`},u(`span`,{textContent:`start at (s)`}),g));let _=u(`dl`,{className:`readouts`});t.append(_);let v=new Map;for(let i of e.schema){let a=v.get(i.group);a||(a=u(`fieldset`,{},u(`legend`,{textContent:i.group})),v.set(i.group,a),t.append(a));let d=u(`label`,{className:`row`},u(`span`,{textContent:i.label,title:i.hint??``}));if(i.kind===`number`){let t=u(`input`,{type:`range`,min:`0`,max:String(o),step:`1`}),a=u(`input`,{type:`number`,step:`any`}),f=u(`span`,{className:`unit`,textContent:i.unit??``});t.oninput=()=>{let e=c(i,Number(t.value));a.value=l(e),r(i.key,e)},a.onchange=()=>{let e=Number(a.value);Number.isFinite(e)&&(t.value=String(s(i,e)),r(i.key,e))},n.push(()=>{let n=e.get()[i.key];t.value=String(s(i,n)),a.value=l(n)}),d.append(t,a,f)}else if(i.kind===`select`){let t=u(`select`);for(let e of i.options)t.append(u(`option`,{value:e,textContent:e}));t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),d.append(t)}else if(i.kind===`text`){let t=u(`textarea`,{rows:3,spellcheck:!1,placeholder:i.hint??``});t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),d.classList.add(`text`),d.append(t)}else{let t=u(`input`,{type:`checkbox`});t.onchange=()=>r(i.key,t.checked),n.push(()=>t.checked=e.get()[i.key]),d.append(t)}a.append(d)}function y(){for(let e of n)e()}function b(){let t=e.readouts();_.replaceChildren(...Object.entries(t).flatMap(([e,t])=>[u(`dt`,{textContent:e}),u(`dd`,{textContent:t})]))}return y(),b(),{el:t,sync:y,updateReadouts:b}}var f={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:50,massRatio:1,lengthRatio:1,tau:2,seed:0,noteInstrument:`modal: Nylon harp`,modalCustom:``,scale:`dorian`,root:`D`,pitchSource:`signed`,thetaRange:3.1416,pitchLow:50,pitchHigh:86,pitchCurve:1,invertPitch:!1,p2Ref:1,loudCurve:1,loudFloor:.08,notesLevel:-6,noteLength:1.5,panAmount:.6,humInstrument:`modal: Clarinet-ish`,humCustom:``,humPitch:38,humLevel:-24,humFollow:0,humNormalize:!0,humColorMode:`log`,humColorCurve:1,humTarget1:`pickup`,humFrom1:.15,humTo1:.75,humTarget2:`tilt`,humFrom2:.3333,humTo2:.5833,humFadeIn:3,humFadeOut:6,pendulumAlpha:1,pendulumSize:.32,motionBlur:1,fade:10,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2,orbits:!0,orbitCount:24,orbitCpu:.4,orbitLife:300,orbitBand:.25,orbitMinHold:3,orbitMaxPoints:8e3,orbitXfade:1.5,orbitAlpha:.3,orbitSize:1};function p(e){let t=e>>>0;return()=>{t=t+0x6d2b79f5>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function m(){return 1+Math.floor(Math.random()*999999)}var h=(e,t)=>e[t],g=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,_=(...e)=>t=>e.includes(t.geometry),v=(...e)=>t=>e.includes(t.exciter),y=[`bow`,`reed`,`selfosc`,`noise`],b=[[`off`,`Off`],[`pitch`,`Pitch`],[`amp`,`Amplitude`],[`position`,`Excite position`],[`pickup`,`Pickup position`],[`tension`,`Tension coupling`],[`cascade`,`Cascade coupling`],[`damping`,`Damping`],[`feedback`,`Feedback gain`],[`exciter`,`Exciter intensity`]],x=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function S(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:b,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:x,def:`sine`,show:t},{kind:`num`,id:`lfo${e}Rate`,label:`Rate`,group:`Modulation`,min:.01,max:40,def:1,scale:`log`,unit:`Hz`,show:t},{kind:`num`,id:`lfo${e}Depth`,label:`Depth`,group:`Modulation`,min:0,max:1,def:.3,scale:`pow2`,show:t}]}var C=[{kind:`enum`,id:`geometry`,label:`Geometry`,group:`Body`,model:!0,def:`string`,options:[[`string`,`String`],[`bar`,`Bar (free–free)`],[`tube_co`,`Tube (closed–open)`],[`tube_oo`,`Tube (open–open)`],[`membrane`,`Membrane (circular)`],[`plate`,`Plate (rectangular)`],[`disc`,`Disc (cymbal / gong)`],[`ring`,`Bell / ring`],[`free`,`Free spectrum (kᵖ)`]],hint:`Sets the mode frequency ratios and mode shapes`},{kind:`num`,id:`modes`,label:`Modes`,group:`Body`,min:4,max:256,def:64,int:!0,model:!0,scale:`log`},{kind:`num`,id:`aspect`,label:`Aspect ratio`,group:`Body`,min:.2,max:1,def:.71,model:!0,show:_(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:_(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:_(`disc`),hint:`f ∝ (m + 2n)^p: 2 = flat plate; lower for domed cymbals and gongs`},{kind:`num`,id:`stretch`,label:`Stretch`,group:`Body`,min:.5,max:2,def:1,model:!0,digits:3,hint:`ratio → ratio^s (bar with s≈1.368 gives the 1:4:10 marimba tuning)`},{kind:`num`,id:`inharm`,label:`Stiffness B`,group:`Body`,min:0,max:.05,def:0,scale:`pow2`,model:!0,digits:5,hint:`ratio·√(1+B·ratio²): piano-like stretched partials`},{kind:`num`,id:`harmonize`,label:`Harmonize`,group:`Body`,min:0,max:1,def:0,model:!0,hint:`pull partials toward integer multiples`},{kind:`num`,id:`jitter`,label:`Detune jitter`,group:`Body`,min:0,max:200,def:0,scale:`pow2`,unit:`¢`,model:!0},{kind:`num`,id:`seed`,label:`Seed`,group:`Body`,min:1,max:999,def:1,int:!0,model:!0,hint:`random detune, coupling topology and radiation`},{kind:`num`,id:`t60`,label:`Decay T60`,group:`Damping`,min:.05,max:60,def:4,scale:`log`,unit:`s`},{kind:`num`,id:`hfDamp`,label:`HF damping`,group:`Damping`,min:0,max:100,def:2,scale:`pow2`,unit:`/s@1k`,hint:`extra decay rate σ = c·(f/1kHz)²`},{kind:`num`,id:`damper`,label:`Damper T60`,group:`Damping`,min:.02,max:20,def:.3,scale:`log`,unit:`s`,hint:`applied on key release; max = no damper`},{kind:`num`,id:`tension`,label:`Tension modulation`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`amplitude-dependent pitch (glides)`},{kind:`num`,id:`cascade`,label:`Cascade coupling`,group:`Nonlinear`,min:0,max:20,def:0,scale:`pow2`,digits:3,hint:`random quartic coupling: energy spreads across modes (gong/cymbal shimmer)`},{kind:`num`,id:`curvature`,label:`Curvature (3-wave)`,group:`Nonlinear`,min:0,max:3,def:0,scale:`pow2`,digits:3,hint:`quadratic forces: sum/difference tones, crashes`},{kind:`num`,id:`terms`,label:`Coupling terms`,group:`Nonlinear`,min:1,max:16,def:6,int:!0,model:!0},{kind:`num`,id:`nlModes`,label:`Coupled modes`,group:`Nonlinear`,min:4,max:128,def:48,int:!0,model:!0,scale:`log`},{kind:`num`,id:`glide`,label:`Pitch glide`,group:`Nonlinear`,min:-12,max:12,def:0,unit:`st`,hint:`pitch offset while loud, relaxing as the note decays: + falls (like tension), − rises (Chinese opera gong)`},{kind:`num`,id:`crossTension`,label:`Cross-note tension`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`notes share one tension: they bend each other`},{kind:`num`,id:`crossLink`,label:`Cross-note link`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`sympathetic coupling + intermodulation between notes`},{kind:`num`,id:`buzz`,label:`Barrier stiffness`,group:`Collision`,min:0,max:1,def:0,scale:`pow2`,digits:3,hint:`sitar bridge, snare wires, rattles`},{kind:`num`,id:`buzzGap`,label:`Gap`,group:`Collision`,min:0,max:2,def:.2,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPos`,label:`Position`,group:`Collision`,min:0,max:1,def:.02,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPosY`,label:`Position Y`,group:`Collision`,min:0,max:1,def:.5,show:e=>e.buzz>0&&g(e)},{kind:`enum`,id:`buzzSides`,label:`Barrier`,group:`Collision`,options:[[`one`,`One-sided (bridge)`],[`two`,`Two-sided (rattle)`]],def:`one`,show:e=>e.buzz>0},{kind:`enum`,id:`exciter`,label:`Key exciter`,group:`Exciter`,def:`strike`,options:[[`strike`,`Strike (hammer / mallet)`],[`pluck`,`Pluck`],[`impulse`,`Impulse`],[`bow`,`Bow`],[`reed`,`Reed / blow`],[`selfosc`,`Self-oscillator`],[`noise`,`Noise`]]},{kind:`num`,id:`strength`,label:`Strength`,group:`Exciter`,min:0,max:6,def:1,scale:`pow2`,hint:`>1 pushes the body into its nonlinear regime`},{kind:`num`,id:`exPos`,label:`Position`,group:`Exciter`,min:0,max:1,def:.13,digits:3},{kind:`num`,id:`exPosY`,label:`Position Y`,group:`Exciter`,min:0,max:1,def:.37,show:g},{kind:`num`,id:`exWidth`,label:`Contact width`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`},{kind:`num`,id:`hammerMass`,label:`Hammer mass`,group:`Exciter`,min:.005,max:5,def:.1,scale:`log`,digits:3,show:v(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:v(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:v(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:v(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:v(`bow`),hint:`scaled by key velocity: sets the loudness`},{kind:`num`,id:`bowNoise`,label:`Bow noise`,group:`Exciter`,min:0,max:1,def:0,scale:`pow2`,show:v(`bow`),hint:`random bow-force fluctuation: rosin and hair noise`},{kind:`num`,id:`reedPressure`,label:`Mouth pressure`,group:`Exciter`,min:0,max:1.5,def:.6,show:v(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:v(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:v(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:v(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:v(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:v(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:v(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:v(...y)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:v(...y)},{kind:`num`,id:`fbGain`,label:`Feedback gain`,group:`Feedback`,min:0,max:8,def:0,scale:`pow2`,hint:`output → delay → band-pass → saturate → back into the body (while a key is held)`},{kind:`num`,id:`fbDelay`,label:`Delay`,group:`Feedback`,min:.05,max:600,def:5,scale:`log`,unit:`ms`,show:e=>e.fbGain>0},{kind:`num`,id:`fbFreq`,label:`Band centre`,group:`Feedback`,min:30,max:12e3,def:800,scale:`log`,unit:`Hz`,show:e=>e.fbGain>0},{kind:`num`,id:`fbQ`,label:`Band Q`,group:`Feedback`,min:.3,max:30,def:1.5,scale:`log`,show:e=>e.fbGain>0},{kind:`num`,id:`fbSat`,label:`Saturation`,group:`Feedback`,min:.01,max:4,def:.4,scale:`log`,show:e=>e.fbGain>0},...S(1),...S(2),{kind:`num`,id:`vibDepth`,label:`Vibrato depth`,group:`Modulation`,min:0,max:100,def:0,scale:`pow2`,unit:`¢`,hint:`per-note vibrato, each note with its own phase and rate`},{kind:`num`,id:`vibRate`,label:`Vibrato rate`,group:`Modulation`,min:1,max:12,def:5.5,unit:`Hz`,show:e=>e.vibDepth>0},{kind:`num`,id:`vibDelay`,label:`Vibrato onset`,group:`Modulation`,min:0,max:2e3,def:300,unit:`ms`,show:e=>e.vibDepth>0,hint:`vibrato fades in after the note starts`},{kind:`num`,id:`bendRange`,label:`Pitch-bend range`,group:`Modulation`,min:0,max:24,def:2,int:!0,unit:`st`},{kind:`enum`,id:`soundbox`,label:`Soundbox`,group:`Soundbox`,def:`off`,options:[[`off`,`Off`],[`violin`,`Violin`],[`viola`,`Viola`],[`cello`,`Cello`],[`bass`,`Double bass`],[`guitar`,`Guitar`]],hint:`fixed resonances that every note passes through (they don't transpose)`},{kind:`num`,id:`boxSize`,label:`Size`,group:`Soundbox`,min:.4,max:3,def:1,scale:`log`,digits:3,show:e=>e.soundbox!==`off`,hint:`>1 lowers every resonance`},{kind:`num`,id:`boxDamp`,label:`Damping`,group:`Soundbox`,min:.3,max:4,def:1,scale:`log`,show:e=>e.soundbox!==`off`,hint:`scales every resonance's bandwidth`},{kind:`num`,id:`boxMix`,label:`Mix`,group:`Soundbox`,min:0,max:1,def:1,show:e=>e.soundbox!==`off`},{kind:`num`,id:`pickup`,label:`Pickup position`,group:`Output`,min:0,max:1,def:.77,digits:3},{kind:`num`,id:`pickupY`,label:`Pickup Y`,group:`Output`,min:0,max:1,def:.61,show:g},{kind:`num`,id:`width`,label:`Stereo width`,group:`Output`,min:0,max:1,def:.3,hint:`right pickup is offset from the left one`},{kind:`num`,id:`spread`,label:`Whole-body radiation`,group:`Output`,min:0,max:1,def:.2,hint:`0 = point pickup, 1 = every mode radiates equally`},{kind:`num`,id:`tilt`,label:`Spectral tilt`,group:`Output`,min:-12,max:12,def:0,unit:`dB/oct`},{kind:`num`,id:`level`,label:`Level`,group:`Output`,min:-24,max:36,def:0,unit:`dB`,hint:`instrument level (saved with presets; Volume is not)`},{kind:`num`,id:`voices`,label:`Max notes`,group:`Output`,min:1,max:16,def:8,int:!0},{kind:`num`,id:`drive`,label:`Saturation`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayMix`,label:`Delay mix`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayTime`,label:`Delay time`,group:`Output`,min:10,max:1500,def:350,scale:`log`,unit:`ms`,show:e=>e.delayMix>0},{kind:`num`,id:`delayFb`,label:`Delay feedback`,group:`Output`,min:0,max:.95,def:.35,show:e=>e.delayMix>0},{kind:`num`,id:`reverbMix`,label:`Reverb mix`,group:`Output`,min:0,max:1,def:.15},{kind:`num`,id:`reverbSize`,label:`Reverb time`,group:`Output`,min:.2,max:12,def:2.5,scale:`log`,unit:`s`,show:e=>e.reverbMix>0},{kind:`num`,id:`volume`,label:`Volume`,group:`Output`,min:-40,max:12,def:-6,unit:`dB`},{kind:`bool`,id:`seqOn`,label:`Auto-play`,group:`Auto`,def:!1},{kind:`enum`,id:`seqMode`,label:`Pattern`,group:`Auto`,def:`mixed`,options:[[`mixed`,`Mixed (changes every 4 bars)`],[`melody`,`Melody`],[`arpeggio`,`Arpeggio`],[`chords`,`Chords`],[`rhythm`,`Rhythm (one pitch)`],[`drone`,`Drone + sparse melody`]]},{kind:`num`,id:`seqTempo`,label:`Tempo`,group:`Auto`,min:20,max:400,def:110,int:!0,unit:`bpm`},{kind:`num`,id:`seqDensity`,label:`Density`,group:`Auto`,min:0,max:1,def:.5},{kind:`enum`,id:`seqScale`,label:`Scale`,group:`Auto`,def:`pentatonic`,options:[[`chromatic`,`Chromatic`],[`major`,`Major`],[`minor`,`Natural minor`],[`dorian`,`Dorian`],[`pentatonic`,`Pentatonic`],[`wholetone`,`Whole tone`],[`harmonic`,`Harmonic series`]]},{kind:`num`,id:`seqRoot`,label:`Root`,group:`Auto`,min:24,max:84,def:48,int:!0},{kind:`num`,id:`seqRange`,label:`Range`,group:`Auto`,min:1,max:4,def:2,int:!0,unit:`oct`},{kind:`num`,id:`seqGate`,label:`Note length`,group:`Auto`,min:.05,max:8,def:.5,scale:`log`,unit:`beats`},{kind:`num`,id:`seqPoly`,label:`Notes per step`,group:`Auto`,min:1,max:4,def:1,int:!0,show:e=>e.seqMode===`melody`||e.seqMode===`mixed`},{kind:`num`,id:`seqVelRand`,label:`Velocity spread`,group:`Auto`,min:0,max:1,def:.3},{kind:`num`,id:`seqPosRand`,label:`Position spread`,group:`Auto`,min:0,max:1,def:0,hint:`randomize where each note is excited`}],w=Object.fromEntries(C.map(e=>[e.id,e])),T=Object.fromEntries(C.map(e=>[e.id,e.def]));C.filter(e=>e.model).map(e=>e.id);var E=class{ctx;input;analyser;scope;shaper;dry;delaySend;dL;dR;fbL;fbR;revSend;conv;master;lastDrive=-1;lastSize=-1;sizeTimer;constructor(e,t=e.destination){this.ctx=e,this.input=e.createGain(),this.analyser=e.createAnalyser(),this.analyser.fftSize=8192,this.analyser.smoothingTimeConstant=0,this.analyser.minDecibels=-120,this.analyser.maxDecibels=-10,this.scope=e.createAnalyser(),this.scope.fftSize=4096,this.input.connect(this.analyser),this.input.connect(this.scope),this.shaper=e.createWaveShaper(),this.shaper.oversample=`4x`,this.dry=e.createGain(),this.master=e.createGain(),this.input.connect(this.shaper),this.shaper.connect(this.dry),this.dry.connect(this.master),this.delaySend=e.createGain();let n=e.createChannelSplitter(2),r=e.createChannelMerger(2);this.dL=e.createDelay(2),this.dR=e.createDelay(2),this.fbL=e.createGain(),this.fbR=e.createGain(),this.shaper.connect(this.delaySend),this.delaySend.connect(n),n.connect(this.dL,0),n.connect(this.dR,1),this.dL.connect(this.fbL),this.fbL.connect(this.dR),this.dR.connect(this.fbR),this.fbR.connect(this.dL),this.dL.connect(r,0,0),this.dR.connect(r,0,1),r.connect(this.master),this.revSend=e.createGain(),this.conv=e.createConvolver(),this.shaper.connect(this.revSend),this.revSend.connect(this.conv),this.conv.connect(this.master);let i=e.createDynamicsCompressor();i.threshold.value=-3,i.knee.value=3,i.ratio.value=20,i.attack.value=.002,i.release.value=.15,this.master.connect(i),i.connect(t)}set(e){let t=this.ctx.currentTime,n=(e,n)=>e.setTargetAtTime(n,t,.02),r=h(e,`drive`);if(r!==this.lastDrive){if(this.lastDrive=r,r<=0)this.shaper.curve=null;else{let e=1+40*r*r,t=2048,n=new Float32Array(t);for(let r=0;r<t;r++){let t=r/2047*2-1;n[r]=Math.tanh(e*t)/Math.tanh(e)}this.shaper.curve=n}}let i=h(e,`delayMix`);n(this.delaySend.gain,i);let a=h(e,`delayTime`)/1e3;n(this.dL.delayTime,a),n(this.dR.delayTime,a),n(this.fbL.gain,h(e,`delayFb`)),n(this.fbR.gain,h(e,`delayFb`));let o=h(e,`reverbMix`);n(this.revSend.gain,o),n(this.dry.gain,r>0?1/(1+2*r):1),n(this.master.gain,10**(h(e,`volume`)/20));let s=h(e,`reverbSize`);s!==this.lastSize&&(this.lastSize=s,clearTimeout(this.sizeTimer),this.sizeTimer=window.setTimeout(()=>this.conv.buffer=this.makeIR(s),150))}makeIR(e){let t=this.ctx.sampleRate,n=Math.round(t*Math.min(e*1.1,12)),r=this.ctx.createBuffer(2,n,t);for(let i=0;i<2;i++){let a=r.getChannelData(i),o=0;for(let r=0;r<n;r++){let n=r/t,i=9e3*Math.exp(-n/(.6*e))+400,s=1-Math.exp(-2*Math.PI*i/t);o+=s*(Math.random()*2-1-o);let c=Math.exp(-6.9*n/e)*Math.min(1,n/.004);a[r]=o*c*.5}}return r}},D=new URL(`worklet-B7ys4Kw_.js`,import.meta.url).href,O={geometry:`string`,t60:3,hfDamp:2,damper:.6,exciter:`bow`,bowForce:1,bowSpeed:.4,bowNoise:.06,noiseColor:4e3,exWidth:.1,attack:80,release:150,pickup:.99,width:0,spread:0,tilt:-6,vibDelay:350,boxMix:.9,level:23,voices:4,reverbMix:.25,reverbSize:2.2},k=[{name:`Piano-ish`,category:`Instrument`,note:48,p:{geometry:`string`,modes:80,inharm:4e-4,t60:9,hfDamp:1.2,damper:.15,exciter:`strike`,strength:1,exPos:.12,exWidth:.04,hammerMass:.04,hardness:1.4,feltExp:2.6,tension:.01,crossLink:.15,pickup:.77,spread:.35,width:.4,reverbMix:.18}},{name:`Steel-string pluck`,category:`Instrument`,note:52,p:{geometry:`string`,modes:64,inharm:8e-5,t60:5,hfDamp:3,damper:.4,exciter:`pluck`,strength:1,exPos:.18,exWidth:.03,tension:.02,pickup:.92,spread:.25,reverbMix:.15}},{name:`Nylon harp`,category:`Instrument`,note:60,p:{geometry:`string`,modes:48,t60:3.5,hfDamp:8,damper:20,exciter:`pluck`,exPos:.35,exWidth:.2,pickup:.5,spread:.5,reverbMix:.25}},{name:`Marimba`,category:`Instrument`,note:60,p:{geometry:`bar`,modes:24,stretch:1.368,t60:1.3,hfDamp:6,damper:20,exciter:`strike`,exPos:.42,exWidth:.05,hammerMass:.25,hardness:1,feltExp:2,pickup:.22,spread:.3,reverbMix:.2}},{name:`Vibraphone`,category:`Instrument`,note:65,p:{geometry:`bar`,modes:24,stretch:1.368,t60:7,hfDamp:1.5,damper:.2,exciter:`strike`,exPos:.45,exWidth:.05,hammerMass:.15,hardness:.8,feltExp:2.2,pickup:.22,spread:.3,lfo1Target:`amp`,lfo1Rate:5,lfo1Depth:.45,reverbMix:.25}},{name:`Church bell`,category:`Instrument`,note:55,p:{geometry:`ring`,modes:40,t60:14,hfDamp:.4,damper:20,jitter:4,exciter:`strike`,exPos:.1,exWidth:.02,hammerMass:.6,hardness:.5,feltExp:1.5,tension:.01,pickup:.3,spread:.5,reverbMix:.35,reverbSize:5}},{name:`Tom drum`,category:`Instrument`,note:43,p:{geometry:`membrane`,modes:40,t60:.7,hfDamp:6,damper:20,tension:.25,exciter:`strike`,strength:1.6,exPos:.35,exPosY:.45,exWidth:.05,hammerMass:.3,hardness:2.5,feltExp:2,pickup:.5,pickupY:.5,spread:.5,reverbMix:.15}},{name:`Snare-ish`,category:`Instrument`,note:50,p:{geometry:`membrane`,modes:64,t60:.5,hfDamp:2,damper:20,tension:.1,buzz:.5,buzzGap:.05,buzzPos:.5,buzzPosY:.55,buzzSides:`two`,exciter:`strike`,strength:1.5,exPos:.4,exPosY:.4,exWidth:.02,hammerMass:.05,hardness:.6,feltExp:1.5,pickup:.5,pickupY:.5,spread:.6,reverbMix:.15}},{name:`Sitar / tanpura`,category:`Instrument`,note:50,p:{geometry:`string`,modes:96,t60:8,hfDamp:.3,damper:20,buzz:.6,buzzGap:.15,buzzPos:.015,buzzSides:`one`,exciter:`pluck`,strength:1.2,exPos:.2,exWidth:.02,pickup:.12,spread:.3,reverbMix:.25}},{name:`Cello`,category:`Instrument`,note:48,p:{...O,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...O,modes:80,inharm:2e-5,exPos:.1,exWidth:.15,vibDepth:14,vibRate:5.8,vibDelay:250,soundbox:`violin`}},{name:`Viola`,category:`Instrument`,note:60,p:{...O,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...O,modes:160,inharm:6e-5,exPos:.08,t60:4,attack:120,vibDepth:12,vibRate:4.8,vibDelay:450,soundbox:`bass`,voices:3,level:20}},{name:`Cello pizzicato`,category:`Instrument`,note:48,p:{...O,modes:96,inharm:4e-5,exciter:`pluck`,strength:1.2,exPos:.3,exWidth:.25,t60:2.2,hfDamp:8,damper:.4,vibDepth:0,soundbox:`cello`,voices:8,level:24}},{name:`Clarinet-ish`,category:`Instrument`,note:50,p:{geometry:`tube_co`,modes:24,t60:.25,hfDamp:6,damper:.05,exciter:`reed`,reedPressure:.7,reedGain:.4,breath:.03,noiseColor:3e3,exPos:0,exWidth:0,attack:30,release:60,pickup:.25,spread:.2,reverbMix:.2}},{name:`Singing bowl`,category:`Instrument`,note:62,p:{geometry:`ring`,modes:24,t60:20,hfDamp:.5,damper:20,jitter:2,exciter:`selfosc`,selfGain:.15,selfSat:.3,exPos:0,exWidth:.01,attack:1500,release:3e3,pickup:.15,spread:.4,width:.6,reverbMix:.35,reverbSize:6}},{name:`Rubber band`,category:`Experimental`,note:40,p:{geometry:`string`,modes:40,t60:1.5,hfDamp:4,damper:.3,tension:1.2,exciter:`pluck`,strength:2.5,exPos:.3,exWidth:.05,pickup:.8,reverbMix:.1}},{name:`Chaos gong`,category:`Experimental`,note:40,p:{geometry:`plate`,modes:128,aspect:.8,nlModes:64,terms:8,cascade:12,curvature:2.2,t60:10,hfDamp:.2,damper:20,crossTension:.4,crossLink:.8,exciter:`strike`,strength:3.5,exPos:.3,exPosY:.3,hammerMass:.4,hardness:2,feltExp:2,pickup:.6,pickupY:.7,spread:.5,width:.6,reverbMix:.3,reverbSize:6,voices:4}},{name:`Ring-mod chords`,category:`Experimental`,note:57,p:{geometry:`free`,powerExp:1.7,modes:32,jitter:15,t60:6,hfDamp:1,damper:1,crossTension:.3,crossLink:1.4,curvature:.5,exciter:`strike`,strength:1.8,exPos:.2,hammerMass:.1,hardness:.8,pickup:.7,spread:.6,width:.6,delayMix:.25,delayTime:375,delayFb:.4,reverbMix:.3}},{name:`Feedback drone plate`,category:`Experimental`,note:45,p:{geometry:`plate`,modes:96,aspect:.62,nlModes:64,cascade:.8,curvature:.3,t60:6,hfDamp:.5,damper:3,exciter:`noise`,noiseLevel:.2,noiseColor:800,attack:800,release:3e3,fbGain:2.5,fbDelay:12,fbFreq:600,fbQ:2,fbSat:.4,lfo1Target:`position`,lfo1Rate:.07,lfo1Depth:.5,lfo1Shape:`smooth`,lfo2Target:`pickup`,lfo2Rate:.11,lfo2Depth:.4,lfo2Shape:`smooth`,pickup:.3,pickupY:.7,spread:.3,width:.7,reverbMix:.35,reverbSize:5,voices:4}},{name:`Buzzing bar organ`,category:`Experimental`,note:48,p:{geometry:`bar`,modes:32,t60:3,hfDamp:1,damper:.3,buzz:.4,buzzGap:.3,buzzPos:.5,buzzSides:`two`,exciter:`selfosc`,selfGain:.6,selfSat:.4,exPos:.02,attack:60,release:300,pickup:.3,spread:.3,reverbMix:.25}},{name:`Glass harmonics`,category:`Experimental`,note:72,p:{geometry:`free`,powerExp:1.25,modes:24,harmonize:.3,t60:12,hfDamp:.3,damper:2,exciter:`impulse`,strength:.8,hardness:.3,exPos:.21,pickup:.6,spread:.6,width:.8,tension:.05,lfo1Target:`pickup`,lfo1Rate:.3,lfo1Depth:.6,delayMix:.3,delayTime:450,delayFb:.5,reverbMix:.45,reverbSize:7}}];function A(e,t=128){let n=new Float32Array(t);for(let r=0;r<t;r++)n[r]=e*Math.cos(Math.PI/2*(r/(t-1)))**2;return n}var j=new WeakMap;function M(e){let t=j.get(e);return t||(t=e.audioWorklet.addModule(D),j.set(e,t)),t}function N(e){if(!e||!e.trim())return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function P(e,t,n,r,i){let a=i.effects??`own`;if(a===`own`){let i=new E(e,n);t.connect(i.input),i.set(r);return}let o=e.createGain();if(o.gain.value=10**(r.volume/20),t.connect(o).connect(n),a!==`none`){let n=e.createGain();n.gain.value=r.reverbMix*o.gain.value,t.connect(n).connect(a.send)}}var F=.2,I=25;function L(e){return(t,n,r)=>{let i={...T,...e??N(r.custom)??{},...r.overrides??{}},a=t.createGain();P(t,a,n,i,r);let o=null,s=0,c=[],l=e=>o?o.port.postMessage(e):c.push(e),u=M(t).then(()=>{o=new AudioWorkletNode(t,`modal-synth`,{numberOfInputs:0,outputChannelCount:[2]}),o.port.onmessage=e=>{e.data?.type===`snap`&&typeof e.data.cpu==`number`&&(s+=(e.data.cpu-s)*.2)},o.port.postMessage({type:`params`,params:i});for(let e of c.splice(0))o.port.postMessage(e);o.connect(a)}),d=[],f=new Map,p=window.setInterval(()=>{let e=t.currentTime+F,n=[];for(let t of d)t.time>e?n.push(t):(f.get(t.note)??-1/0)<=t.on&&l({type:`noteOff`,note:t.note,time:t.time});d=n},I),m=typeof OfflineAudioContext<`u`&&t instanceof OfflineAudioContext||!!r.immediateRelease,h=!1;return{ready:u,load:()=>s,play({when:e,freq:n,velocity:r,duration:o}){if(r<=0)return null;let s=69+12*Math.log2(n/440);if(l({type:`noteOn`,note:s,vel:Math.max(.01,Math.min(1,r)),time:e}),m)return l({type:`noteOff`,note:s,time:e+o}),null;f.set(s,e);let c={note:s,on:e,time:e+o};return d.push(c),{hold(e,n,r){let o=Math.max(e,t.currentTime),s=n+r;if(c.time=o+s,h)return;h=!0;let u=Math.min(60,Math.max(i.t60,6*s)),d=u/i.t60,f={...i,t60:u,hfDamp:i.hfDamp/d};window.setTimeout(()=>l({type:`params`,params:f}),Math.max(0,(o-t.currentTime)*1e3)),a.gain.setValueCurveAtTime(A(1),o+Math.max(n,.005),r)}}},dispose(){window.clearInterval(p),l({type:`panic`}),window.setTimeout(()=>{o?.disconnect(),o?.port.close(),a.disconnect()},1e3)}}}}function R(){let e={};for(let t of k)e[`modal: ${t.name}`]=L(t.p);return e[`modal: custom`]=L(null),e}var z=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function B(e,t){let n=w[e];if(!n||n.kind!==`num`)return NaN;let r=Math.max(0,Math.min(1,t));return n.scale===`log`?n.min*(n.max/n.min)**+r:n.scale===`pow2`?n.min+(n.max-n.min)*r*r:n.min+(n.max-n.min)*r}var V=[`bow`,`reed`,`selfosc`,`noise`],H=50,U=.3,W=1.5,G=20;function K(e){return(t,n,r)=>{let i=r.glide,a={...T,...e??N(r.custom)??{},...r.overrides??{},voices:1,...i?{bendRange:Math.max(1,Math.min(24,Math.round(i.range)))}:{}},o=t.createGain();o.gain.value=0;let s=new E(t,n);o.connect(s.input),s.set(a);let c=t.createAnalyser();c.fftSize=2048;let l=new Float32Array(c.fftSize),u=U*U,d=0,f=1,p=null,m=0,h=[],g=e=>p?p.port.postMessage(e):h.push(e),_=M(t).then(()=>{p=new AudioWorkletNode(t,`modal-synth`,{numberOfInputs:0,outputChannelCount:[2]}),p.port.onmessage=e=>{e.data?.type===`snap`&&typeof e.data.cpu==`number`&&(m+=(e.data.cpu-m)*.2)},p.port.postMessage({type:`params`,params:a});for(let e of h.splice(0))p.port.postMessage(e);p.connect(o),p.connect(c)}),v=null,y=0,b=a,x=0,S=``,C=e=>69+12*Math.log2(e/440);return{ready:_,load:()=>m,start(e,t){i&&(y=Math.max(-1,Math.min(1,(C(t)-i.center)/a.bendRange)),g({type:`bend`,value:y})),v=i?i.center:C(t),g({type:`noteOn`,note:v,vel:1,time:e})},stop(e,n){let r=Math.max(t.currentTime,e-n);o.gain.cancelScheduledValues(r),o.gain.setTargetAtTime(0,r,n/4),v!==null&&g({type:`noteOff`,note:v,time:r}),v=null},set(e,{level:t,color:n,freq:r,timbre:s,normalize:m}){let h=performance.now()/1e3,_=d?Math.min(.5,h-d):0;if(d=h,m&&p){c.getFloatTimeDomainData(l);let e=0;for(let t of l)e+=t*t;e/=l.length,e>1e-10&&(u+=(e-u)*(1-Math.exp(-_/W))),f=Math.max(1/G,Math.min(G,U/Math.sqrt(u)))}else f=1;o.gain.setTargetAtTime(t*f,e,.08);let T=C(r);if(i&&v!==null){let e=a.bendRange,t=Math.max(-1,Math.min(1,(T-i.center)/e));Math.abs(t-y)>1e-4&&(y=t,g({type:`bend`,value:t}))}else v!==null&&Math.abs(T-v)>.01&&(g({type:`noteOff`,note:v,time:e}),v=T,g({type:`noteOn`,note:v,vel:1,time:e}));let E=performance.now();if(!s?.length||E-x<H)return;let D={...a},O=[],k=!1;for(let e of s){if(!z.includes(e.target))continue;let t=B(e.target,e.from+(e.to-e.from)*n);if(!Number.isFinite(t))continue;D[e.target]=t,O.push(`${e.target} ${Number(t.toPrecision(3))}`);let r=w[e.target];Math.abs(t-b[e.target])>.002*(r.max-r.min)&&(k=!0)}S=O.join(`, `),k&&(b=D,x=E,g({type:`params`,params:D}))},describe:()=>f===1?S:`${S}${S?`, `:``}gain ${(20*Math.log10(f)).toFixed(1)} dB`,dispose(){g({type:`panic`}),window.setTimeout(()=>{p?.disconnect(),p?.port.close(),o.disconnect()},1e3)}}}}function ee(){let e={};for(let t of k){let n={...T,...t.p};(V.includes(n.exciter)||n.fbGain>0)&&(e[`modal: ${t.name}`]=K(t.p))}return e[`modal: custom`]=K(null),e}function te(e,t){return{play({when:n,freq:r,velocity:i,pan:a,duration:o}){if(i<=0)return null;let s=Math.max(n,e.currentTime),c=s+o,l=.3*i,u=s+.004,d=e.createGain();d.gain.setValueAtTime(0,s),d.gain.linearRampToValueAtTime(l,u),d.gain.exponentialRampToValueAtTime(1e-4,c);let f=e.createStereoPanner();f.pan.value=Math.max(-1,Math.min(1,a)),d.connect(f).connect(t);let p=e.createOscillator();p.frequency.value=r,p.connect(d);let m=e.createOscillator();m.type=`triangle`,m.frequency.value=r*2;let h=e.createGain();h.gain.value=.08+.15*i,m.connect(h).connect(d);for(let e of[p,m])e.start(s),e.stop(c+.05);return m.onended=()=>f.disconnect(),{hold(t,n,r){let i=Math.max(t,u,e.currentTime);if(i>=c)return;let a=l*(1e-4/l)**((i-u)/(c-u)),o=d.gain;typeof o.cancelAndHoldAtTime==`function`?o.cancelAndHoldAtTime(i):o.cancelScheduledValues(i),o.setValueAtTime(a,i),o.setValueCurveAtTime(A(a),i+Math.max(n,.005),r);let s=i+n+r+.05;p.stop(s),m.stop(s)}}},dispose(){}}}function ne(e,t){let n=e.createGain();n.gain.value=0;let r=e.createBiquadFilter();r.type=`lowpass`,r.frequency.value=120,r.Q.value=.7,r.connect(n).connect(t);let i=e.createOscillator(),a=e.createGain();a.gain.value=.5,i.connect(a).connect(n);let o=[-6,6].map(t=>{let n=e.createOscillator();n.type=`sawtooth`,n.detune.value=t;let i=e.createGain();return i.gain.value=.25,n.connect(i).connect(r),n}),s=[i,...o];return{start(e,t){i.frequency.value=t;for(let e of o)e.frequency.value=t*2;for(let t of s)t.start(e)},stop(e,t){n.gain.cancelScheduledValues(e-t),n.gain.setTargetAtTime(0,e-t,t/4);for(let t of s)t.stop(e+.1)},set(e,{level:t,color:a,freq:s}){let c=.08;n.gain.setTargetAtTime(t,e,c),i.frequency.setTargetAtTime(s,e,c);for(let t of o)t.frequency.setTargetAtTime(s*2,e,c);let l=Math.max(0,Math.min(1,a));r.frequency.setTargetAtTime(s*2*2**(6*l),e,c),r.Q.setTargetAtTime(.7+5*l*l,e,c)},dispose(){n.disconnect()}}}var q={"placeholder tone":te,...R()},re={"placeholder hum":ne,...ee()},ie={continuous:null,chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],major:[0,2,4,5,7,9,11],"natural minor":[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],lydian:[0,2,4,6,7,9,11],"pentatonic major":[0,2,4,7,9],"pentatonic minor":[0,3,5,7,10],"whole tone":[0,2,4,6,8,10],"harmonic series":null},ae=Object.keys(ie),oe=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function J(e){return 440*2**((e-69)/12)}function se(e,t,n){if(t===`harmonic series`){let t=J(n+12*Math.floor((24-n)/12)),r=Math.max(1,Math.round(J(e)/t));return 69+12*Math.log2(r*t/440)}let r=ie[t];if(!r)return e;let i=e-n,a=Math.floor(i/12),o=i-12*a,s=r[0],c=1/0;for(let e of[...r,12]){let t=Math.abs(o-e);t<c&&(c=t,s=e)}return n+12*a+s}var ce=class{cfg;y=new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=new Float64Array(4);k2=new Float64Array(4);k3=new Float64Array(4);k4=new Float64Array(4);tmp=new Float64Array(4);constructor(e){this.cfg={...e}}get vTop(){let{m1:e,m2:t,l1:n,l2:r,g:i}=this.cfg;return 2*(e+t)*i*n+2*t*i*r}get p2Scale(){let{m2:e,l2:t}=this.cfg;return Math.sqrt(e*t*t*this.vTop)}derived(e=this.y){let{m1:t,m2:n,l1:r,l2:i,g:a}=this.cfg,[o,s,c,l]=[e[0],e[1],e[2],e[3]],u=o-s,d=Math.cos(u),f=Math.sin(u),p=t+n*f*f,m=(i*c-r*l*d)/(r*r*i*p),h=(r*(t+n)*l-i*n*c*d)/(r*i*i*n*p);return{w1:m,w2:h,T:.5*(c*m+l*h),V:(t+n)*a*r*(1-Math.cos(o))+n*a*i*(1-Math.cos(s))}}energy(e=this.y){let t=this.derived(e);return t.T+t.V}energyNorm(){return this.energy()/this.vTop}deriv(e,t){let{m1:n,m2:r,l1:i,l2:a,g:o}=this.cfg,s=e[0],c=e[1],l=e[2],u=e[3],d=s-c,f=Math.cos(d),p=Math.sin(d),m=n+r*p*p,h=(a*l-i*u*f)/(i*i*a*m),g=(i*(n+r)*u-a*r*l*f)/(i*a*a*r*m),_=l*u*p/(i*a*m),v=(a*a*r*l*l+i*i*(n+r)*u*u-2*i*a*r*l*u*f)*Math.sin(2*d)/(2*i*i*a*a*m*m),y=.5*(l*h+u*g),b=(n+r)*o*i*(1-Math.cos(s))+r*o*a*(1-Math.cos(c)),x=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;x=(this.eTarget-(y+b))/(this.tau*(2*y+e)),x>t?x=t:x<-t&&(x=-t)}x-=this.damping,t[0]=h,t[1]=g,t[2]=-(n+r)*o*i*Math.sin(s)-_+v+x*l,t[3]=-r*o*a*Math.sin(c)+_-v+x*u}step(e){let{y:t,k1:n,k2:r,k3:i,k4:a,tmp:o}=this;this.deriv(t,n);for(let r=0;r<4;r++)o[r]=t[r]+.5*e*n[r];this.deriv(o,r);for(let n=0;n<4;n++)o[n]=t[n]+.5*e*r[n];this.deriv(o,i);for(let n=0;n<4;n++)o[n]=t[n]+e*i[n];this.deriv(o,a);for(let o=0;o<4;o++)t[o]+=e/6*(n[o]+2*r[o]+2*i[o]+a[o]);this.t+=e}randomize(e,t){let{m1:n,m2:r,l1:i,l2:a}=this.cfg,o=Math.max(e,1e-6)*this.vTop,s=Math.min(Math.PI,3*Math.sqrt(o/(r*this.cfg.g*Math.min(i,a)))),c=0,l=0,u=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,u=this.derived([c,l,0,0]).V,!(u<.9*o));e++)c=l=0,u=0;let d=o-u,f=t()*2*Math.PI,p=Math.cos(f),m=Math.sin(f),h=Math.cos(c-l),g=(n+r)*i*i,_=r*i*a*h,v=r*a*a,y=.5*(g*p*p+2*_*p*m+v*m*m),b=Math.sqrt(d/y),x=b*p,S=b*m;this.y[0]=c,this.y[1]=l,this.y[2]=g*x+_*S,this.y[3]=_*x+v*S,this.t=0}};function le(e){return Math.atan2(Math.sin(e),Math.cos(e))}function Y(e,t){let n=e.duration,r=Math.min(e.peakTime,n),i=Math.min(r+e.holdTime,n),a=e.energyStart,o=e.energyPeak;if(t<0)return a;if(t<r){let n=(t/r)**+e.riseCurve;return e.riseShape===`exponential`?a*(o/a)**+n:a+(o-a)*n}return t<i?o:t<n?o*(1-(t-i)/(n-i))**e.fallCurve:0}var ue=class{inst=null;key=``;ensure(e,t,n,r){let i=n.humInstrument,a=i===`modal: custom`?`${i}\n${n.humCustom}`:i;if(this.inst&&this.key===a)return;let o=this.inst;this.key=a;let s=re[i](e,t,{custom:n.humCustom});if(this.inst=s,o&&r){let t=e.currentTime;o.stop(t+.5,.5),window.setTimeout(()=>o.dispose(),1500),(s.ready??Promise.resolve()).then(()=>s===this.inst&&s.start(e.currentTime+.05,J(n.humPitch)))}}get ready(){return this.inst?.ready}start(e,t){this.inst?.start(e.currentTime+.05,J(t.humPitch))}update(e,t,r,i,a){if(!this.inst)return;let o=t.energyPeak,s=Math.max(0,Math.min(1,r/o)),c=Math.min(t.energyStart,.999*o),l=t.humColorMode===`log`?Math.max(0,Math.min(1,Math.log(Math.max(r,1e-12)/c)/Math.log(o/c))):s,u=t.humFadeIn,d=t.humFadeOut,f=Math.min(1,u>0?i/u:1,a!==null&&d>0?(a-i)/d:1),p=t.humFollow;this.inst.set(e.currentTime,{level:n(t.humLevel)*Math.max(0,f)*(1-p+p*s),color:l**+t.humColorCurve,freq:J(t.humPitch),normalize:t.humNormalize,timbre:[1,2].filter(e=>t[`humTarget${e}`]!==`none`).map(e=>({target:t[`humTarget${e}`],from:t[`humFrom${e}`],to:t[`humTo${e}`]}))})}describe(){return this.inst?.describe?.()||`–`}release(e,t){let n=this.inst;n&&(t&&n.stop(e.currentTime+.3,.3),window.setTimeout(()=>n.dispose(),600),this.inst=null,this.key=``)}};function de(e,t,n,r=0){let i=e.thetaRange,a=e.pitchSource===`absolute`?Math.min(1,Math.abs(t)/i):Math.max(0,Math.min(1,.5+.5*t/i));e.invertPitch&&(a=1-a),a**=+e.pitchCurve;let o=e.pitchLow,s=e.pitchHigh,c=oe.indexOf(e.root),l=se(o+(s-o)*a+12*r,e.scale,c),u=Math.min(1,Math.abs(n)/e.p2Ref),d=e.loudFloor;return{midi:l,velocity:d+(1-d)*u**+e.loudCurve,pan:e.panAmount*Math.max(-1,Math.min(1,t/Math.PI))}}function fe(e){let t=window.devicePixelRatio||1,n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);return i.setTransform(t,0,0,t,0,0),i}function pe(e,t,n=`#ccc`){return getComputedStyle(e).getPropertyValue(t).trim()||n}var me=class{thR=Math.PI;pR=1;lastWall=0;canvas;constructor(e){this.canvas=e}begin(e,t,n,r,i){let a=performance.now()/1e3,o=a-this.lastWall;this.lastWall=a;let s=this.canvas,c=fe(s),l=s.clientWidth,u=s.clientHeight;c.clearRect(0,0,l,u);let d=Math.PI,f=e.plotP;if(e.plotZoom===`fit energy`&&t!==null&&n){let e=Math.max(1e-6,t),i=e*r,a=i>=2*n.m2*n.g*n.l2?Math.PI:Math.acos(1-i/(n.m2*n.g*n.l2));d=Math.min(Math.PI,1.08*a),f=1.08*Math.sqrt(2*e)}let p=o>0&&o<.5?1-Math.exp(-o/Math.max(.01,e.zoomSmooth)):1;this.thR*=Math.exp(p*Math.log(d/this.thR)),this.pR*=Math.exp(p*Math.log(f/this.pR));let m=(l/2-8)/this.thR,h=(u/2-8)/this.pR;return c.strokeStyle=i,c.lineWidth=1,c.beginPath(),c.moveTo(8,u/2),c.lineTo(l-8,u/2),c.moveTo(l/2,8),c.lineTo(l/2,u-8),c.stroke(),{g:c,w:l,h:u,sx:e=>l/2+m*e,sy:e=>u/2-h*e}}};function he(e,t,n,r,i,a,o){let{g:s,sx:c,sy:l}=e;s.fillStyle=o,s.globalAlpha=Math.exp(-r/i),s.beginPath(),s.arc(c(t),l(n),a/2,0,2*Math.PI),s.fill(),r<.4&&(s.globalAlpha=1-r/.4,s.strokeStyle=o,s.beginPath(),s.arc(c(t),l(n),a/2+3+12*r,0,2*Math.PI),s.stroke()),s.globalAlpha=1}var ge=100,_e=class{worker=null;portraits=[];resetPending=!1;latestGen=0;ignoreBelow=0;rate=0;newPts=0;rateT=0;now;live;constructor(e,t){this.now=e,this.live=t}reset(){this.dirty=!0,this.portraits=[],this.ignoreBelow=this.latestGen+1,this.resetPending=!0}ensureWorker(){return this.worker||(this.worker=new Worker(new URL(new URL(`orbitWorker-CMBL8zS4.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),this.worker.onmessage=e=>this.receive(e.data)),this.worker}receive({gen:e,energy:t,pts:n,tracks:r}){if(!this.live()||(this.latestGen=Math.max(this.latestGen,e),e<this.ignoreBelow))return;let i=this.portraits[this.portraits.length-1];if(!i||e>i.gen){let n=this.now();for(let e of this.portraits)e.retiredAt??=n;i={gen:e,energy:t,pts:[],tracks:new Map,retiredAt:null},this.portraits.push(i)}else if(e<i.gen)return;for(let e=0;e<n.length;e++)i.pts.push(n[e]);for(let e of r){let t=i.tracks.get(e.id);t||i.tracks.set(e.id,t=[]);for(let n=0;n<e.pts.length;n++)t.push(e.pts[n])}this.newPts+=n.length/2+r.reduce((e,t)=>e+t.pts.length/2,0),this.dirty=!0}post(e,t,n,r,i,a){if(!t.show&&!t.tracks&&!this.worker)return;let o={running:e&&(t.show||t.tracks),reset:this.resetPending,energy:n,m2:r,l2:i,count:t.show?Math.round(t.count):0,life:t.life,band:t.band,minHold:t.minHold,maxPoints:t.show?t.maxPoints:0,cpu:t.cpu,tracks:t.tracks?a:[],trackMax:t.trackMax};this.resetPending=!1,this.ensureWorker().postMessage(o)}layer=null;layerAt=0;layerKey=``;dirty=!0;lm={cx:0,kx:1,cy:0,ky:1};draw(e,t,n,r,i){let{g:a,w:o,h:s,sx:c,sy:l}=e,u=this.portraits.length;this.portraits=this.portraits.filter(e=>e.retiredAt===null||t-e.retiredAt<n.xfade),this.portraits.length!==u&&(this.dirty=!0);let d=this.portraits.some(e=>e.retiredAt!==null),f=window.devicePixelRatio||1,p=[o,s,f,n.show,n.tracks,n.alpha,n.size,n.trackAlpha,n.trackSize,r].join(`|`),m={cx:c(0),kx:c(1)-c(0),cy:l(0),ky:l(1)-l(0)},h=m.kx/this.lm.kx,g=m.ky/this.lm.ky,_=Math.abs(Math.log(h))>.05||Math.abs(Math.log(g))>.05,v=performance.now();this.layer||=document.createElement(`canvas`);let y=this.layer;if((this.dirty||d||_||p!==this.layerKey)&&v-this.layerAt>=ge){let e=Math.round(o*f),a=Math.round(s*f);(y.width!==e||y.height!==a)&&(y.width=e,y.height=a);let u=y.getContext(`2d`);u.setTransform(f,0,0,f,0,0),u.clearRect(0,0,o,s);for(let e of this.portraits){let a=e.retiredAt===null?1:Math.max(0,1-(t-e.retiredAt)/n.xfade);if(n.show&&e.pts.length){let t=n.size;u.fillStyle=r,u.globalAlpha=n.alpha*a,u.beginPath();let i=e.pts;for(let e=0;e<i.length;e+=2)u.rect(c(i[e])-t/2,l(i[e+1])-t/2,t,t);u.fill()}if(n.tracks){let t=n.trackSize;for(let[r,o]of e.tracks){u.fillStyle=i(r),u.globalAlpha=n.trackAlpha*a,u.beginPath();for(let e=0;e<o.length;e+=2)u.rect(c(o[e])-t/2,l(o[e+1])-t/2,t,t);u.fill()}}}u.globalAlpha=1,this.layerAt=v,this.layerKey=p,this.lm=m,this.dirty=!1}if(y.width){let e=m.kx/this.lm.kx,t=m.ky/this.lm.ky;a.save(),a.setTransform(f*e,0,0,f*t,f*(m.cx-e*this.lm.cx),f*(m.cy-t*this.lm.cy)),a.drawImage(y,0,0,o,s),a.restore()}}describe(){let e=performance.now()/1e3;e-this.rateT>1&&(this.rate=this.newPts/(e-this.rateT||1),this.newPts=0,this.rateT=e);let t=this.portraits.find(e=>e.retiredAt===null);if(!t)return`–`;let n=[...t.tracks.values()].reduce((e,t)=>e+t.length/2,0);return`E ${t.energy.toFixed(4)}, ${t.pts.length/2} pts${t.tracks.size?` + ${n} traced`:``}, ${Math.round(this.rate)}/s`}dispose(){this.worker?.terminate(),this.worker=null}},ve=.002,ye=.15,be=25,xe=10,Se=1/960,Ce=64,we=2;function Te(e,t){e.classList.add(`c01`);let r=document.createElement(`canvas`);e.append(r);let i=new me(r),a=new ue,o=null,s=null,c=null,l=``,u=null,d=0,f=null,h,g=!1,_=0,v=0,y=0,b=0,x=0,S=[],C=-1/0,w=[],T=null,E=null,D=new _e(()=>j(),()=>g),O=e=>({show:e.orbits,count:e.orbitCount,cpu:e.orbitCpu,life:e.orbitLife,band:e.orbitBand,minHold:e.orbitMinHold,maxPoints:e.orbitMaxPoints,xfade:e.orbitXfade,alpha:e.orbitAlpha,size:e.orbitSize,tracks:!1,trackMax:0,trackAlpha:0,trackSize:1}),k=e=>{let n=t();D.post(e,O(n),o?o.energyNorm():0,n.massRatio,n.lengthRatio,[])},A={get playing(){return g},start:N,stop:F,draw:K,now:j,length:()=>z(t()),readouts:ee,dispose(){F(),D.dispose(),e.classList.remove(`c01`),e.replaceChildren()}};function j(){return!s||!g?x:s.ctx.currentTime-_}function M(e){return new ce({m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio})}async function N(e,n){F();let r=++d;s=e;let i=t(),l=e.ctx;y=i.seed>0?Math.round(i.seed):m(),o=M(i),o.randomize(Y(i,0),p(y)),o.tau=i.tau,v=0,S=[],C=-1/0,w=[],D.reset(),b=0,T=null,E=null,n>0&&I(n,!1),f=l.createGain(),f.connect(e.input),P(),await Promise.all([c?.ready,a.ready]),r===d&&(_=l.currentTime+.1-n,a.start(l,i),g=!0,B(),h=window.setInterval(B,be))}function P(){if(!s||!f)return;let e=t();u||(u=s.ctx.createGain(),u.connect(f)),u.gain.setTargetAtTime(n(e.notesLevel),s.ctx.currentTime,.05);let r=e.noteInstrument,i=r===`modal: custom`?`${r}\n${e.modalCustom}`:r;c&&l===i||(c?.dispose(),l=i,c=q[r](s.ctx,u,{custom:e.modalCustom})),a.ensure(s.ctx,f,e,g)}function F(){d++,h!==void 0&&window.clearInterval(h),h=void 0;let e=g;if(g&&(x=j(),g=!1,k(!1)),!s)return;let t=s.ctx.currentTime;a.release(s.ctx,e);let n=f;n&&(n.gain.setTargetAtTime(0,t,.05),window.setTimeout(()=>n.disconnect(),600)),c?.dispose(),c=null,l=``,u=null,f=null}function I(e,n){if(!o)return;let r=t();o.cfg.m2=r.massRatio,o.cfg.l2=r.lengthRatio,o.tau=r.tau;let i=r.speed,a=r.duration,s=r.restEnergy,c=o.y,l=le(c[0]),u=c[1],d=c[3],f=v;for(;v<e;){o.eTarget=Y(r,v)*o.vTop,o.step(ve),v+=ve/i;let e=le(c[0]);if(E===null&&l<0&&e>=0&&e-l<Math.PI){let t=-l/(e-l),i={t:f+t*(v-f),th2:le(u+t*(c[1]-u)),p2:(d+t*(c[3]-d))/o.p2Scale};w.push(i),n&&L(i,r)}E===null&&v>=a&&(o.energyNorm()<s||v>=a+xe)&&(E=v,n&&R(r)),l=e,u=c[1],d=c[3],f=v,v-C>=Se&&(S.push({t:v,th1:c[0],th2:c[1]}),C=v)}}function L(e,t){if(!s||!c)return;let n=_+e.t;if(n<s.ctx.currentTime-.02)return;let{midi:r,velocity:i,pan:a}=de(t,e.th2,e.p2),o=J(r),l=c.play({when:n,freq:o,velocity:i,pan:a,duration:t.noteLength});l&&(T={handle:l,when:n}),b++}function R(e){T&&T.handle.hold(T.when,e.finalHold,e.finalFade)}function z(e){let t=e.finalHold+e.finalFade+.3;return(E??e.duration+.5)+t}function B(){if(!s||!o||!g)return;let e=t();P();let n=s.ctx,r=n.currentTime-_,i=z(e);if(E!==null&&r>=i){F(),x=i,A.onEnded?.();return}I(r+ye,!0),k(!0),a.update(n,e,o.energyNorm(),r,E===null?null:i);let c=0;for(;c<S.length-1&&S[c+1].t<=r-.1;)c++;c>0&&S.splice(0,c)}function V(t){return pe(e,t)}function H(e){let t=S.length;if(!t)return o?{th1:o.y[0],th2:o.y[1]}:{th1:0,th2:0};if(e<=S[0].t)return S[0];if(e>=S[t-1].t)return S[t-1];let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;S[t].t<=e?n=t:r=t}let i=S[n],a=S[r],s=(e-i.t)/(a.t-i.t);return{th1:i.th1+s*(a.th1-i.th1),th2:i.th2+s*(a.th2-i.th2)}}let U=0,W=1/60;function G(e,t,n,r,i){let a=r.pendulumAlpha;if(a<=0)return;let o=g?r.motionBlur*W:0,s=r.lengthRatio,c=r.pendulumSize*Math.min(t,n)/2,l=.9*c/(1+s),u=8+c,d=8+c,f=1;if(o>0){let e=0,t=H(i);for(let n=1;n<=8;n++){let r=H(i-o*n/8);e+=l*(+Math.abs(r.th1-t.th1)+s*Math.abs(r.th2-t.th2)),t=r}f=Math.max(2,Math.min(Ce,Math.ceil(e/we)))}let p=a*(f===1?1:1-.03**(1/f)),m=3*Math.cbrt(r.massRatio),h=V(`--fg`);e.strokeStyle=h,e.fillStyle=h,e.lineWidth=1.5,e.lineCap=`round`,e.globalAlpha=p;for(let t=0;t<f;t++){let{th1:n,th2:r}=H(i-o*t/Math.max(1,f-1)),a=u+l*1*Math.sin(n),c=d+l*1*Math.cos(n),p=a+l*s*Math.sin(r),h=c+l*s*Math.cos(r);e.beginPath(),e.moveTo(u,d),e.lineTo(a,c),e.lineTo(p,h),e.stroke(),e.beginPath(),e.arc(a,c,3,0,2*Math.PI),e.moveTo(p+m,h),e.arc(p,h,m,0,2*Math.PI),e.fill()}e.globalAlpha=a,e.beginPath(),e.arc(u,d,1.5,0,2*Math.PI),e.fill(),e.globalAlpha=1}function K(){let e=t(),n=j(),r=performance.now()/1e3,a=r-U;U=r,a>0&&a<.1&&(W+=(a-W)*.1);let s=V(`--fg`),c=V(`--dim`);{let t=i.begin(e,o?o.energyNorm():null,o?.cfg??null,o?.vTop??1,c),{g:r,w:a,h:l}=t;D.draw(t,n,O(e),s,()=>s);let u=e.fade,d=e.pointSize,f=0;for(;f<w.length&&n-w[f].t>4.6*u;)f++;f>0&&w.splice(0,f);for(let e of w){let r=n-e.t;if(r<0)break;he(t,e.th2,e.p2,r,u,d,s)}G(r,a,l,e,n)}}function ee(){let e=t(),n=j();return{time:`${n.toFixed(1)} / ${A.length().toFixed(0)} s`,"energy target":Y(e,n).toFixed(4),energy:o?o.energyNorm().toFixed(4):`–`,notes:String(b),"seed used":y?String(y):`–`,hum:a.describe(),"orbit portrait":D.describe()}}return A}var Ee=[{group:`form`,key:`duration`,label:`duration`,kind:`number`,default:60,min:10,max:600,step:1,unit:`s`,hint:`energy returns to zero at this time`},{group:`form`,key:`peakTime`,label:`peak at`,kind:`number`,default:25,min:1,max:600,step:.5,unit:`s`},{group:`form`,key:`holdTime`,label:`hold`,kind:`number`,default:10,min:0,max:600,step:.5,unit:`s`},{group:`form`,key:`energyStart`,label:`start energy`,kind:`number`,default:.005,min:1e-4,max:1,log:!0},{group:`form`,key:`energyPeak`,label:`peak energy`,kind:`number`,default:1.2,min:.01,max:5,log:!0},{group:`form`,key:`riseShape`,label:`rise shape`,kind:`select`,default:`exponential`,options:[`exponential`,`linear`]},{group:`form`,key:`riseCurve`,label:`rise curve`,kind:`number`,default:1,min:.2,max:5,log:!0,hint:`exponent on the rise; >1 starts slow`},{group:`form`,key:`fallCurve`,label:`fall curve`,kind:`number`,default:1,min:.2,max:5,log:!0,hint:`exponent on the fall; >1 drops fast then lingers`},{group:`form`,key:`restEnergy`,label:`rest energy`,kind:`number`,default:.001,min:1e-5,max:.05,log:!0,hint:`after duration, the pendulum counts as at rest below this energy: no more crossings; the last note rings out`},{group:`form`,key:`finalHold`,label:`final hold`,kind:`number`,default:2,min:0,max:20,step:.1,unit:`s`,hint:`the last note sustains this long…`},{group:`form`,key:`finalFade`,label:`final fade`,kind:`number`,default:5,min:.1,max:30,step:.1,unit:`s`,hint:`…then fades out over this long; the piece ends with it`},{group:`physics`,key:`speed`,label:`speed`,kind:`number`,default:12,min:.5,max:100,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`physics`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.1,max:10,log:!0},{group:`physics`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.1,max:10,log:!0},{group:`physics`,key:`tau`,label:`energy follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how quickly the energy tracks its target`},{group:`physics`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`0 = a new variation every play`},{group:`notes`,key:`noteInstrument`,label:`instrument`,kind:`select`,default:`placeholder tone`,options:Object.keys(q),hint:`modal: … instruments come from the modal-synth project`},{group:`notes`,key:`modalCustom`,label:`modal custom`,kind:`text`,default:``,hint:`for “modal: custom”: paste JSON from modal-synth’s Copy button`},{group:`notes`,key:`scale`,label:`scale`,kind:`select`,default:`pentatonic minor`,options:ae},{group:`notes`,key:`root`,label:`root`,kind:`select`,default:`D`,options:oe},{group:`notes`,key:`pitchSource`,label:`pitch from θ2`,kind:`select`,default:`signed`,options:[`signed`,`absolute`],hint:`signed: −range→low, +range→high. absolute: 0→low, ±range→high`},{group:`notes`,key:`thetaRange`,label:`θ2 range`,kind:`number`,default:3.1416,min:.02,max:3.1416,log:!0,unit:`rad`},{group:`notes`,key:`pitchLow`,label:`low pitch`,kind:`number`,default:50,min:12,max:120,step:.5,unit:`midi`},{group:`notes`,key:`pitchHigh`,label:`high pitch`,kind:`number`,default:86,min:12,max:120,step:.5,unit:`midi`},{group:`notes`,key:`pitchCurve`,label:`pitch curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`notes`,key:`invertPitch`,label:`invert pitch`,kind:`bool`,default:!1},{group:`notes`,key:`p2Ref`,label:`|p2| for full`,kind:`number`,default:1,min:.01,max:4,log:!0,hint:`|p2| that gives full loudness`},{group:`notes`,key:`loudCurve`,label:`loudness curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`notes`,key:`loudFloor`,label:`loudness floor`,kind:`number`,default:.08,min:0,max:1,step:.01,hint:`loudness of a crossing with p2 = 0`},{group:`notes`,key:`notesLevel`,label:`level`,kind:`number`,default:-6,min:-48,max:6,step:.5,unit:`dB`},{group:`notes`,key:`noteLength`,label:`length`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`},{group:`notes`,key:`panAmount`,label:`pan from θ2`,kind:`number`,default:.6,min:0,max:1,step:.01,hint:`placeholder tone only; modal instruments have their own stereo image`},{group:`hum`,key:`humInstrument`,label:`instrument`,kind:`select`,default:`modal: Clarinet-ish`,options:Object.keys(re),hint:`modal: … = one held note of a sustained modal-synth preset`},{group:`hum`,key:`humCustom`,label:`modal custom`,kind:`text`,default:``,hint:`for “modal: custom”: paste JSON from modal-synth’s Copy button`},{group:`hum`,key:`humPitch`,label:`pitch`,kind:`number`,default:38,min:12,max:72,step:.5,unit:`midi`},{group:`hum`,key:`humLevel`,label:`level`,kind:`number`,default:-24,min:-60,max:0,step:.5,unit:`dB`},{group:`hum`,key:`humFollow`,label:`loudness follows energy`,kind:`number`,default:0,min:0,max:1,step:.01,hint:`0 = constant loudness`},{group:`hum`,key:`humNormalize`,label:`normalize loudness`,kind:`bool`,default:!0,hint:`modal hum: measure the output and compensate slowly, so timbre changes don't change loudness`},{group:`hum`,key:`humColorMode`,label:`timbre from energy`,kind:`select`,default:`log`,options:[`log`,`power`],hint:`log: even steps per energy doubling, from start energy (0) to peak (1). power: (energy / peak)^curve`},{group:`hum`,key:`humColorCurve`,label:`timbre curve`,kind:`number`,default:1,min:.1,max:5,log:!0,hint:`exponent applied to the timbre value`},{group:`hum`,key:`humTarget1`,label:`timbre → A`,kind:`select`,default:`pickup`,options:[`none`,...z],hint:`modal hum: synth setting driven by timbre (bow position, force, pressure, feedback, …)`},{group:`hum`,key:`humFrom1`,label:`A at low energy`,kind:`number`,default:.15,min:0,max:1,step:.005,hint:`fraction of the setting's range in modal-synth`},{group:`hum`,key:`humTo1`,label:`A at peak`,kind:`number`,default:.75,min:0,max:1,step:.005},{group:`hum`,key:`humTarget2`,label:`timbre → B`,kind:`select`,default:`tilt`,options:[`none`,...z]},{group:`hum`,key:`humFrom2`,label:`B at low energy`,kind:`number`,default:.3333,min:0,max:1,step:.005},{group:`hum`,key:`humTo2`,label:`B at peak`,kind:`number`,default:.5833,min:0,max:1,step:.005},{group:`hum`,key:`humFadeIn`,label:`fade in`,kind:`number`,default:3,min:0,max:60,step:.5,unit:`s`},{group:`hum`,key:`humFadeOut`,label:`fade out`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`ends together with the last note's fade`},{group:`visual`,key:`pendulumAlpha`,label:`pendulum opacity`,kind:`number`,default:1,min:0,max:1,step:.01,hint:`0 = hide the pendulum`},{group:`visual`,key:`pendulumSize`,label:`pendulum size`,kind:`number`,default:.32,min:.1,max:1,step:.01,hint:`inset diameter, as a fraction of the plot (upper-left corner)`},{group:`visual`,key:`motionBlur`,label:`motion blur`,kind:`number`,default:1,min:0,max:4,step:.05,hint:`pendulum shutter, in display frames; 0 = off`},{group:`visual`,key:`fade`,label:`point fade`,kind:`number`,default:10,min:.2,max:120,log:!0,unit:`s`},{group:`visual`,key:`plotZoom`,label:`plot zoom`,kind:`select`,default:`fit energy`,options:[`fit energy`,`fixed`],hint:`fit energy: frame the region the pendulum can reach at its current energy`},{group:`visual`,key:`zoomSmooth`,label:`zoom smoothing`,kind:`number`,default:1.5,min:.05,max:20,log:!0,unit:`s`,hint:`time constant of zoom changes`},{group:`visual`,key:`plotP`,label:`fixed p2 range`,kind:`number`,default:1.5,min:.05,max:5,log:!0},{group:`visual`,key:`pointSize`,label:`point size`,kind:`number`,default:2,min:.5,max:8,step:.1,unit:`px`},{group:`orbits`,key:`orbits`,label:`show orbits`,kind:`bool`,default:!0},{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:24,min:1,max:64,step:1,hint:`trajectories integrated in parallel, all at the portrait's energy`},{group:`orbits`,key:`orbitCpu`,label:`cpu`,kind:`number`,default:.4,min:.02,max:.9,step:.01,hint:`fraction of one core the background computation may use`},{group:`orbits`,key:`orbitLife`,label:`life`,kind:`number`,default:300,min:10,max:5e3,log:!0,hint:`crossings before an orbit is reseeded elsewhere on the section`},{group:`orbits`,key:`orbitBand`,label:`refresh at`,kind:`number`,default:.25,min:.01,max:2,log:!0,hint:`start a new portrait when the energy has changed by this fraction`},{group:`orbits`,key:`orbitMinHold`,label:`min hold`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`s`,hint:`a portrait is kept at least this long`},{group:`orbits`,key:`orbitMaxPoints`,label:`max points`,kind:`number`,default:8e3,min:500,max:4e4,log:!0,hint:`a portrait stops computing (and using CPU) once it has this many points`},{group:`orbits`,key:`orbitXfade`,label:`crossfade`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`,hint:`time for the old portrait to fade out once a new one starts`},{group:`orbits`,key:`orbitAlpha`,label:`brightness`,kind:`number`,default:.3,min:.02,max:1,step:.01},{group:`orbits`,key:`orbitSize`,label:`point size`,kind:`number`,default:1,min:.5,max:4,step:.1,unit:`px`}],De={id:`01-poincare`,title:`poincaré`,schema:Ee,defaults:f,create:Te},Oe={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:40,massRatio:1,lengthRatio:1,tau:2,seed:0,streamAudio:!0,deviceLimit:!0,orbitCount:8,colors:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,slot1Instrument:`modal: Nylon harp`,slot1Octave:0,slot2Instrument:`modal: Marimba`,slot2Octave:-1,slot3Instrument:`modal: Vibraphone`,slot3Octave:0,slot4Instrument:`modal: Church bell`,slot4Octave:-1,slot5Instrument:`modal: Steel-string pluck`,slot5Octave:0,slot6Instrument:`modal: Glass harmonics`,slot6Octave:1,modalCustom:``,reverbTime:3.5,scale:`dorian`,root:`D`,pitchSource:`signed`,thetaRange:3.1416,pitchLow:50,pitchHigh:86,pitchCurve:1,invertPitch:!1,p2Ref:1,loudCurve:1,loudFloor:.08,notesLevel:-6,noteLength:1.5,panAmount:.6,humInstrument:`modal: Clarinet-ish`,humCustom:``,humPitch:38,humLevel:-24,humFollow:0,humNormalize:!0,humColorMode:`log`,humColorCurve:1,humTarget1:`pickup`,humFrom1:.15,humTo1:.75,humTarget2:`tilt`,humFrom2:.3333,humTo2:.5833,humFadeIn:3,humFadeOut:6,fade:20,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2.5,portrait:!0,portraitCount:24,portraitCpu:.4,portraitLife:300,portraitBand:.25,portraitMinHold:3,portraitMaxPoints:8e3,portraitXfade:1.5,portraitAlpha:.15,portraitSize:1,traces:!0,traceMax:1500,traceAlpha:.75,traceSize:1.5},ke=.35,Ae=.6,je=.2,Me=1.3,Ne=.5,Pe=2;function Fe(e,t,n,r){let i={v:5,stream:r,sr:t,speed:e.speed,len:e.noteLength,inst:Array.from({length:n},(t,n)=>e[`slot${n+1}Instrument`]),custom:e.modalCustom};return`double-pendulum:capacity:02-orbits:${JSON.stringify(i)}`}function Ie(e){try{let t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Le(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}var Re=e=>new Promise(t=>setTimeout(t,e));async function ze(e,t,n,r){let i=e.createGain();i.gain.value=0,i.connect(e.destination);let a=Array(r).fill(0);for(let e=0;e<n;e++)a[e%r]++;let o=t.speed*je,s=t.noteLength,c=[];for(let n=0;n<r;n++){if(!a[n])continue;let r=q[t[`slot${n+1}Instrument`]](e,i,{custom:t.modalCustom,immediateRelease:!0,effects:`none`});c.push({inst:r,rate:o*a[n]})}try{await Promise.all(c.map(e=>e.inst.ready));let t=12345,n=()=>(t=t*16807%0x7fffffff)/0x7fffffff,r=e.currentTime+.05;for(let{inst:e,rate:t}of c){let i=t=>e.play({when:t,freq:J(50+Math.floor(n()*36)),velocity:.6,pan:0,duration:s}),a=Math.min(16,Math.round(t*s));for(let e=0;e<a;e++)i(r+.002*e);for(let e=.05;e<Me;e+=1/t)i(r+e)}await Re(Ne*1e3);let i=[],a=performance.now()+800;for(;performance.now()<a;)await Re(100),i.push(c.reduce((e,t)=>e+(t.inst.load?.()??0),0));return i.length?i.reduce((e,t)=>e+t,0)/i.length:0}finally{for(let e of c)e.inst.dispose();window.setTimeout(()=>i.disconnect(),1200)}}function Be(e,t){let n=e[`slot${t+1}Instrument`];if(!n.startsWith(`modal: `))return null;let r=n===`modal: custom`?N(e.modalCustom):k.find(e=>`modal: ${e.name}`===n)?.p;return{...T,...r??{}}}async function Ve(e,t,n,r){let i=Array(r).fill(0);for(let e=0;e<n;e++)i[e%r]++;let a=t.speed*je,o=t.noteLength,s=1.5,c=[];for(let n=0;n<r;n++){let r=i[n]?Be(t,n):null;if(!r)continue;let l=a*i[n],u=12345+n,d=()=>(u=u*16807%0x7fffffff)/0x7fffffff,f=[],p=Math.min(16,Math.round(l*o));for(let e=0;e<p;e++)f.push({time:.002*e,note:50+Math.floor(d()*36),vel:.6,len:o});for(let e=.05;e<s;e+=1/l)f.push({time:e,note:50+Math.floor(d()*36),vel:.6,len:o});c.push(new Promise(t=>{let n=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`});n.onmessage=e=>{e.data.type===`bench`&&(t(e.data.load),n.terminate())};let i={type:`bench`,sampleRate:e,params:r,notes:f,seconds:s,warmup:.5};n.postMessage(i)}))}let l=await Promise.all(c);return l.length?Math.max(...l):0}async function He(e,t,n,r,i=!1){let a=Fe(t,e.sampleRate,r,i),o=i?Ae:ke,s=n=>i?Ve(e.sampleRate,t,n,r):ze(e,t,n,r),c=Ie(a);if(c&&(c.cap<c.tested||c.tested>=n))return{...c,cap:Math.min(c.cap,n)};let l=n,u=await s(l),d=l;for(let e=1;u>o&&l>1&&e<Pe;e++)l=Math.max(1,Math.min(l-1,Math.floor(l*(o/u)**1.3))),u=await s(l),d=l;u>o&&(l=Math.max(1,Math.min(l-1,Math.floor(l*(o/u)**1.3))));let f={cap:l,tested:n,load:u,at:d};return Le(a,f),f}var X=(e,t={})=>{let n=Ee.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Ue=[[`modal: Nylon harp`,0],[`modal: Marimba`,-1],[`modal: Vibraphone`,0],[`modal: Church bell`,-1],[`modal: Steel-string pluck`,0],[`modal: Glass harmonics`,1]],We=[...[`duration`,`peakTime`,`holdTime`,`energyStart`].map(e=>X(e)),X(`energyPeak`,{default:.4}),...[`riseShape`,`riseCurve`,`fallCurve`,`restEnergy`,`finalHold`,`finalFade`].map(e=>X(e)),X(`speed`,{default:40}),...[`massRatio`,`lengthRatio`,`tau`,`seed`].map(e=>X(e)),{group:`orbits`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render each instrument in its own background thread, ~1 s ahead of playback (uses more cores, no glitches from momentary slowdowns); applies on the next play`},{group:`orbits`,key:`deviceLimit`,label:`limit to device`,kind:`bool`,default:!0,hint:`measure (once per device) how many orbits this device can play live, and play no more than that`},{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:8,min:1,max:20,step:1,hint:`pendulums, all following the same energy; each starts at a random place`},{group:`orbits`,key:`colors`,label:`colors`,kind:`text`,default:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,hint:`comma-separated CSS colors; orbit n uses color n (cycling)`},...Array.from({length:6},(e,t)=>[{group:`orbits`,key:`slot${t+1}Instrument`,label:`instrument ${t+1}`,kind:`select`,default:Ue[t][0],options:Object.keys(q),hint:`orbits ${t+1}, ${t+1+6}, ${t+1+12}, … play this instrument`},{group:`orbits`,key:`slot${t+1}Octave`,label:`octave ${t+1}`,kind:`number`,default:Ue[t][1],min:-3,max:3,step:1,hint:`register shift for this instrument`}]).flat(),X(`modalCustom`,{group:`orbits`,hint:`for “modal: custom” in any slot: paste JSON from modal-synth’s Copy button`}),{group:`orbits`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`,hint:`one reverb shared by all the orbit instruments (each sends its preset's reverb amount); applies on the next play`},X(`scale`,{default:`dorian`}),...[`root`,`pitchSource`,`thetaRange`,`pitchLow`,`pitchHigh`,`pitchCurve`,`invertPitch`,`p2Ref`,`loudCurve`,`loudFloor`,`notesLevel`,`noteLength`,`panAmount`].map(e=>X(e)),...Ee.filter(e=>e.group===`hum`),X(`fade`,{default:20,hint:`how long each live crossing dot stays visible`}),...[`plotZoom`,`zoomSmooth`,`plotP`].map(e=>X(e)),X(`pointSize`,{default:2.5}),X(`orbits`,{key:`portrait`,group:`portrait`,label:`show portrait`,hint:`grey background: the section's structure at the current energy`}),X(`orbitCount`,{key:`portraitCount`,group:`portrait`}),X(`orbitCpu`,{key:`portraitCpu`,group:`portrait`}),X(`orbitLife`,{key:`portraitLife`,group:`portrait`}),X(`orbitBand`,{key:`portraitBand`,group:`portrait`}),X(`orbitMinHold`,{key:`portraitMinHold`,group:`portrait`}),X(`orbitMaxPoints`,{key:`portraitMaxPoints`,group:`portrait`}),X(`orbitXfade`,{key:`portraitXfade`,group:`portrait`}),X(`orbitAlpha`,{key:`portraitAlpha`,group:`portrait`,default:.15}),X(`orbitSize`,{key:`portraitSize`,group:`portrait`}),{group:`portrait`,key:`traces`,label:`trace orbits`,kind:`bool`,default:!0,hint:`with each portrait, follow every pendulum from its current state (energy frozen) and draw the orbit it's on, in its color`},{group:`portrait`,key:`traceMax`,label:`trace length`,kind:`number`,default:1500,min:50,max:1e4,log:!0,hint:`crossings computed per orbit trace`},{group:`portrait`,key:`traceAlpha`,label:`trace brightness`,kind:`number`,default:.75,min:.02,max:1,step:.01},{group:`portrait`,key:`traceSize`,label:`trace point size`,kind:`number`,default:1.5,min:.5,max:4,step:.1,unit:`px`}],Ge=class{input;conv;constructor(e,t,n){this.input=e.createGain(),this.conv=e.createConvolver(),this.conv.buffer=Ke(e,n),this.input.connect(this.conv).connect(t)}dispose(){let e=this.input,t=this.conv;window.setTimeout(()=>{e.disconnect(),t.disconnect()},1500)}};function Ke(e,t){let n=e.sampleRate,r=Math.round(n*Math.min(t*1.1,12)),i=e.createBuffer(2,r,n);for(let e=0;e<2;e++){let a=i.getChannelData(e),o=0;for(let e=0;e<r;e++){let r=e/n,i=9e3*Math.exp(-r/(.6*t))+400,s=1-Math.exp(-2*Math.PI*i/n);o+=s*(Math.random()*2-1-o),a[e]=o*Math.exp(-6.9*r/t)*Math.min(1,r/.004)*.5}}return i}var qe=new URL(`player-BCgNbE7X.js`,import.meta.url).href,Je=1.5,Ye=1.3,Xe=50,Ze=new WeakMap;function Qe(e){let t=Ze.get(e);return t||(t=e.audioWorklet.addModule(qe),Ze.set(e,t)),t}function $e(e){return(t,n,r)=>{let i={...T,...e??N(r.custom)??{},...r.overrides??{}},a=t.createGain();P(t,a,n,i,r);let o=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),s=(e,t=[])=>o.postMessage(e,t),c=0,l=0,u=null,d=(async()=>{await Qe(t),u=new AudioWorkletNode(t,`pcm-player`,{numberOfInputs:0,outputChannelCount:[2]}),u.connect(a);let e=new MessageChannel;u.port.postMessage({type:`port`,port:e.port2},[e.port2]);let n=new Promise(e=>{o.onmessage=t=>{t.data.type===`ready`?e():t.data.type===`load`&&(c=t.data.load,l=t.data.underruns)}});s({type:`init`,sampleRate:t.sampleRate,params:i,port:e.port1,startFrame:Math.round((t.currentTime+.05)*t.sampleRate),aheadFrames:Math.round(+t.sampleRate)},[e.port1]),await n})(),f=e=>s({type:`synth`,msg:e}),p=[],m=new Map,h=window.setInterval(()=>{let e=t.currentTime+Ye,n=[];for(let t of p)t.time>e?n.push(t):(m.get(t.note)??-1/0)<=t.on&&f({type:`noteOff`,note:t.note,time:t.time});p=n},Xe),g=!1;return{ready:d,load:()=>c,underruns:()=>l,horizon:e=>s({type:`horizon`,time:e}),play({when:e,freq:n,velocity:o,duration:c}){if(o<=0)return null;let l=69+12*Math.log2(n/440);if(f({type:`noteOn`,note:l,vel:Math.max(.01,Math.min(1,o)),time:e}),r.immediateRelease)return f({type:`noteOff`,note:l,time:e+c}),null;m.set(l,e);let u={note:l,on:e,time:e+c};return p.push(u),{hold(e,n,r){let o=Math.max(e,t.currentTime);if(u.time=o+n+r,g)return;g=!0;let c=n+r,l=Math.min(60,Math.max(i.t60,6*c)),d=l/i.t60;s({type:`timedParams`,time:o,params:{...i,t60:l,hfDamp:i.hfDamp/d}}),a.gain.setValueCurveAtTime(A(1),o+Math.max(n,.005),r)}}},dispose(){window.clearInterval(h),s({type:`stop`}),window.setTimeout(()=>{o.terminate(),u?.disconnect(),a.disconnect()},1e3)}}}}function et(){let e={};for(let t of k)e[`modal: ${t.name}`]=$e(t.p);return e[`modal: custom`]=$e(null),e}var tt=et(),nt=.4,rt=.003,it=.15,at=25,ot=10;function st(e,t){e.classList.add(`c02`);let r=document.createElement(`canvas`);e.append(r);let i=new me(r),a=new ue,o=new _e(()=>j(),()=>v),s=e=>({show:e.portrait,count:e.portraitCount,cpu:e.portraitCpu,life:e.portraitLife,band:e.portraitBand,minHold:e.portraitMinHold,maxPoints:e.portraitMaxPoints,xfade:e.portraitXfade,alpha:e.portraitAlpha,size:e.portraitSize,tracks:e.traces,trackMax:e.traceMax,trackAlpha:e.traceAlpha,trackSize:e.traceSize}),c=e=>{let n=t(),r=l.filter(e=>e.restAt===null).map(e=>({id:e.index,y:Array.from(e.pend.y)}));o.post(e,s(n),G(),n.massRatio,n.lengthRatio,r)},l=[],u=null,d=null,f=null,h=new Map,g=null,_,v=!1,y=0,b=0,x=0,S=0,C=0,w=0,T=null,E=!1,D=it,O=null,k=!1,A={get playing(){return v},start:B,stop:V,draw:te,now:j,length:()=>W(t()),readouts:re,notice:ne,dispose(){V(),o.dispose(),e.classList.remove(`c02`),e.replaceChildren()}};function j(){return!u||!v?w:u.ctx.currentTime-b}function M(e,t,n){let r=new ce({m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio});return r.randomize(n,p(S*1009+t*7919+1)),r.tau=e.tau,{index:t,pend:r,prev:le(r.y[0]),prevTh2:r.y[1],prevP2:r.y[3],points:[],lastNote:null,restAt:null}}function N(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function P(e){let t=N(e);return e.deviceLimit&&O?Math.min(t,O.cap):t}function F(e){let t=P(e);if(T===null){for(;l.length<t;)l.push(M(e,l.length,Math.max(1e-4,Y(e,x))));l.length>t&&(l.length=t)}}function I(e){return e.index%6}function L(e,t){let n=e[`slot${t+1}Instrument`];return{name:n,key:n===`modal: custom`?`${n}\n${e.modalCustom}`:n}}function R(e){return E&&tt[e]||q[e]}function z(){if(!u||!d)return;let e=t();f||(f=u.ctx.createGain(),f.connect(d),g=new Ge(u.ctx,f,e.reverbTime)),f.gain.setTargetAtTime(n(e.notesLevel),u.ctx.currentTime,.05);let r=new Map;for(let t of l){let{name:n,key:i}=L(e,I(t));r.set(i,n)}for(let[e,t]of h)r.has(e)||(t.dispose(),h.delete(e));for(let[t,n]of r)h.has(t)||h.set(t,R(n)(u.ctx,f,{custom:e.modalCustom,effects:{send:g.input}}));a.ensure(u.ctx,d,e,v)}async function B(e,n){V();let r=++y;u=e;let i=t(),s=e.ctx;if(E=!!i.streamAudio,D=E?Je:it,i.deviceLimit){k=!0;try{O=await He(s,i,N(i),6,E)}finally{k=!1}if(r!==y)return}S=i.seed>0?Math.round(i.seed):m(),x=0,T=null,C=0,l=[],o.reset(),F(i),n>0&&H(n,!1),d=s.createGain(),d.connect(e.input),z(),await Promise.all([...[...h.values()].map(e=>e.ready),a.ready]),r===y&&(b=s.currentTime+.1+(E?nt:0)-n,a.start(s,i),v=!0,K(),_=window.setInterval(K,at))}function V(){y++,_!==void 0&&window.clearInterval(_),_=void 0;let e=v;if(v&&(w=j(),v=!1,c(!1)),!u)return;let t=u.ctx.currentTime;a.release(u.ctx,e);let n=d;n&&(n.gain.setTargetAtTime(0,t,.05),window.setTimeout(()=>n.disconnect(),600));for(let e of h.values())e.dispose();h=new Map,g?.dispose(),g=null,f=null,d=null}function H(e,n){let r=t(),i=r.speed,a=r.duration,o=r.restEnergy;for(let e of l)e.pend.cfg.m2=r.massRatio,e.pend.cfg.l2=r.lengthRatio,e.pend.tau=r.tau;for(;x<e;){let e=Y(r,x),t=x;x+=rt/i;for(let i of l){let s=i.pend,c=s.y;s.eTarget=e*s.vTop,s.step(rt);let l=le(c[0]);if(i.restAt===null&&i.prev<0&&l>=0&&l-i.prev<Math.PI){let e=-i.prev/(l-i.prev),a={t:t+e*(x-t),th2:le(i.prevTh2+e*(c[1]-i.prevTh2)),p2:(i.prevP2+e*(c[3]-i.prevP2))/s.p2Scale};i.points.push(a),n&&U(i,a,r)}i.restAt===null&&x>=a&&(s.energyNorm()<o||x>=a+ot)&&(i.restAt=x,n&&i.lastNote&&i.lastNote.handle.hold(i.lastNote.when,r.finalHold,r.finalFade)),i.prev=l,i.prevTh2=c[1],i.prevP2=c[3]}T===null&&l.length&&l.every(e=>e.restAt!==null)&&(T=x)}}function U(e,t,n){if(!u)return;let r=b+t.t;if(r<u.ctx.currentTime-.02)return;let i=I(e),a=h.get(L(n,i).key);if(!a)return;let{midi:o,velocity:s,pan:c}=de(n,t.th2,t.p2,n[`slot${i+1}Octave`]),l=a.play({when:r,freq:J(o),velocity:s,pan:c,duration:n.noteLength});l&&(e.lastNote={handle:l,when:r}),C++}function W(e){let t=e.finalHold+e.finalFade+.3;return(T??e.duration+.5)+t}function G(){return l.length?l.reduce((e,t)=>e+t.pend.energyNorm(),0)/l.length:0}function K(){if(!u||!v)return;let e=t();F(e),z();let n=u.ctx,r=n.currentTime-b,i=W(e);if(T!==null&&r>=i)V(),w=i,A.onEnded?.();else{H(r+D,!0);for(let e of h.values())e.horizon?.(b+x);c(!0),a.update(n,e,G(),r,T===null?null:i)}}function ee(t){let n=String(t.colors).split(`,`).map(e=>e.trim()).filter(Boolean);return n.length?n:[pe(e,`--fg`)]}function te(){let n=t(),r=j(),a=l[0]?.pend??null,c=l.length?Math.max(...l.map(e=>e.pend.energyNorm())):null,u=i.begin(n,c,a?.cfg??null,a?.vTop??1,pe(e,`--dim`)),d=n.fade,f=n.pointSize,p=ee(n);o.draw(u,r,s(n),pe(e,`--fg`),e=>p[e%p.length]);for(let e of l){let t=0;for(;t<e.points.length&&r-e.points[t].t>4.6*d;)t++;t>0&&e.points.splice(0,t);let n=p[e.index%p.length];for(let t of e.points){let e=r-t.t;if(e<0)break;he(u,t.th2,t.p2,e,d,f,n)}}}function ne(){if(k)return`checking what this device can play…`;let e=t(),n=N(e),r=P(e);return r<n?`${r} of ${n} orbits: reduced to what this device can play live`:null}function re(){let e=t(),n=j();return{time:`${n.toFixed(1)} / ${A.length().toFixed(0)} s`,"energy target":Y(e,n).toFixed(4),"energy (mean)":l.length?G().toFixed(4):`–`,notes:String(C),"at rest":`${l.filter(e=>e.restAt!==null).length} / ${l.length}`,"device limit":O?`${O.cap} orbits (synth load ${(100*O.load).toFixed(0)}% with ${O.at})`:`–`,instruments:String(h.size),"audio load":E?`renderers ${Math.round(100*Math.max(0,...[...h.values()].map(e=>e.load?.()??0)))}% (busiest), ${[...h.values()].reduce((e,t)=>e+(t.underruns?.()??0),0)} underruns; hum ${Math.round(100*(a.inst?.load?.()??0))}%`:`${Math.round(100*([...h.values()].reduce((e,t)=>e+(t.load?.()??0),0)+(a.inst?.load?.()??0)))}%`,"seed used":S?String(S):`–`,hum:a.describe(),portrait:o.describe()}}return A}var ct={id:`02-orbits`,title:`orbits`,schema:We,defaults:Oe,create:st},lt={freeTime:40,dampTime:20,dampCurve:1.5,tau:2,restEnergy:.001,finalHold:2,finalFade:5,count:12,releaseAngle:120,jitter:3,separateAt:8,sepThreshold:.02,speed:2.5,massRatio:1,lengthRatio:1,seed:0,instrument:`modal: Vibraphone`,modalCustom:``,pitchMode:`chord`,directionChords:!0,scale:`dorian`,root:`D`,pitchLow:50,pitchHigh:86,loudRef:.6,loudCurve:1,loudFloor:.08,notesLevel:-8,noteLength:2,directionPan:.35,reverbTime:3.5,streamAudio:!0,trails:!0,trailLength:3,trailWidth:1.2,armAlpha:.75,bobSize:3,saturation:35},ut=.002;function dt(e,t,n,r){let i=new ce(e);return i.controlled=!1,i.y[0]=t,i.y[1]=n+r,i.y[2]=0,i.y[3]=0,i}function ft(e,t){return[e.l1*Math.sin(t[0])+e.l2*Math.sin(t[1]),e.l1*Math.cos(t[0])+e.l2*Math.cos(t[1])]}function pt(e,t,n,r,i,a){let o=dt(e,t,n,-r/2),s=dt(e,t,n,r/2);for(let t=0;t<a;t+=ut){o.step(ut),s.step(ut);let[n,r]=ft(e,o.y),[a,c]=ft(e,s.y);if(Math.hypot(n-a,r-c)>i)return t+ut}return 1/0}function mt(e,t,n,r,i){let a=3*r+10,o=1e-15,s=.01;if(pt(e,t,n,o,i,a)<=r)return{offset:o,separatesAt:pt(e,t,n,o,i,a)};if(pt(e,t,n,s,i,a)>=r)return{offset:s,separatesAt:pt(e,t,n,s,i,a)};for(let c=0;c<16;c++){let c=Math.sqrt(o*s);pt(e,t,n,c,i,a)>r?o=c:s=c}let c=Math.sqrt(o*s);return{offset:c,separatesAt:pt(e,t,n,c,i,a)}}var ht=et(),gt=.15,_t=.4,vt=25,yt=10,bt=1/120;function xt(e,t){e.classList.add(`c03`);let r=document.createElement(`canvas`);e.append(r);let i=[],a={m1:1,l1:1,g:1,m2:1,l2:1},o=[],s=-1/0,c=null,l=null,u=null,d=null,f=null,h=null,g=null,_=null,v=``,y,b=!1,x=0,S=0,C=0,w=0,T=0,E=0,D=null,O=!1,k=gt,A=1,j={th1:0,th2:0,offset:0,separatesAt:0},M={get playing(){return b},start:L,stop:R,draw:ee,now:N,length:()=>U(t()),readouts:te,dispose(){R(),e.classList.remove(`c03`),e.replaceChildren()}};function N(){return!c||!b?E:c.ctx.currentTime-S}function P(e,t){a={m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio};let n=Math.PI/180,r=e.releaseAngle*n,c=e.jitter*n,l=t(),u=l===null?r:r+(2*l-1)*c,d=t(),f=d===null?r:r+(2*d-1)*c,p=e.speed,m=mt(a,u,f,e.separateAt*p,e.sepThreshold*(a.l1+a.l2));j={th1:u,th2:f,offset:m.offset,separatesAt:m.separatesAt/p};let h=Math.max(1,Math.round(e.count));i=[];for(let e=0;e<h;e++){let t=h>1?(e/(h-1)-.5)*m.offset:0,n=dt(a,u,f,t);i.push({index:e,p:n,prevX:ft(a,n.y)[0],E0:0,lastNote:null,restAt:null})}A=Math.sqrt(2*i[0].p.energy()/a.m2),o=[],s=-1/0,z(0)}function F(e){return O&&ht[e]||q[e]}function I(){if(!c||!l)return;let e=t(),r=c.ctx;u||(u=r.createGain(),u.connect(l),d=new Ge(r,u,e.reverbTime),f=r.createStereoPanner(),h=r.createStereoPanner(),f.connect(u),h.connect(u)),u.gain.setTargetAtTime(n(e.notesLevel),r.currentTime,.05);let i=e.directionPan;f.pan.setTargetAtTime(-i,r.currentTime,.05),h.pan.setTargetAtTime(i,r.currentTime,.05);let a=e.instrument,o=a===`modal: custom`?`${a}\n${e.modalCustom}`:a;if(g&&v===o)return;g?.dispose(),_?.dispose(),v=o;let s={custom:e.modalCustom,effects:{send:d.input}};g=F(a)(r,f,s),_=F(a)(r,h,s)}async function L(e,n){R();let r=++x;c=e;let i=t(),a=e.ctx;w=i.seed>0?Math.round(i.seed):m();let o=p(w);P(i,()=>o()),C=0,D=null,T=0,O=!!i.streamAudio,k=O?Je:gt,n>0&&B(n,!1),l=a.createGain(),l.connect(e.input),I(),await Promise.all([g?.ready,_?.ready]),r===x&&(S=a.currentTime+.1+(O?_t:0)-n,b=!0,W(),y=window.setInterval(W,vt))}function R(){if(x++,y!==void 0&&window.clearInterval(y),y=void 0,b&&=(E=N(),!1),!c)return;let e=c.ctx.currentTime,t=l;t&&(t.gain.setTargetAtTime(0,e,.05),window.setTimeout(()=>t.disconnect(),600)),g?.dispose(),_?.dispose(),g=_=null,v=``,d?.dispose(),d=null,u=f=h=null,l=null}function z(e){let t=new Float64Array(2*i.length);for(let e=0;e<i.length;e++)t[2*e]=i[e].p.y[0],t[2*e+1]=i[e].p.y[1];o.push({t:e,s:t}),s=e}function B(e,n){let r=t(),o=r.speed,c=r.freeTime,l=r.dampTime,u=r.dampCurve,d=r.tau,f=r.restEnergy;for(;C<e;){let e=C;C+=ut/o;let t=(e-c)/l;for(let o of i){let i=o.p;t>=0&&(i.controlled||(i.controlled=!0,o.E0=i.energy()),i.tau=d,i.eTarget=t<1?o.E0*(1-t)**u:0,i.damping=t>=1?1/d:0),i.step(ut);let s=ft(a,i.y)[0];if(o.restAt===null&&(o.prevX<0&&s>=0||o.prevX>0&&s<=0)){let t=e+o.prevX/(o.prevX-s)*(C-e);n&&H(o,t,s>o.prevX?1:-1,r)}o.prevX=s,o.restAt===null&&t>=1&&(i.energyNorm()<f||C>=c+l+yt)&&(o.restAt=C,n&&o.lastNote&&o.lastNote.handle.hold(o.lastNote.when,r.finalHold,r.finalFade))}D===null&&i.every(e=>e.restAt!==null)&&(D=C),C-s>=bt&&z(C)}}function V(e,t){let n=e.pitchLow,r=e.pitchHigh,i=oe.indexOf(e.root),a=!!e.directionChords,o=a?2*t:t,s=[];if(e.scale===`continuous`)s=Array.from({length:Math.max(o,2)},(e,t)=>n+(r-n)*t/Math.max(1,Math.max(o,2)-1));else for(let t=Math.ceil(n);t<=r;t++)Math.abs(se(t,e.scale,i)-t)<1e-6&&s.push(t);s.length||(s=[se((n+r)/2,e.scale,i)]);let c=Array.from({length:o},(e,t)=>s[o>1?Math.round(t*(s.length-1)/(o-1)):Math.floor(s.length/2)]);return a?{right:c.filter((e,t)=>t%2==0),left:c.filter((e,t)=>t%2==1)}:{right:c,left:c}}function H(e,t,n,r){if(!c)return;let o=S+t;if(o<c.ctx.currentTime-.02)return;let s=n>0?_:g;if(!s)return;let l=e.p.y,u=e.p.derived(),d=a.l1*Math.cos(l[0])*u.w1+a.l2*Math.cos(l[1])*u.w2,f=a.l1*Math.sin(l[0])*u.w1+a.l2*Math.sin(l[1])*u.w2,p=Math.min(1,Math.hypot(d,f)/(r.loudRef*A)),m=r.loudFloor,h=m+(1-m)*p**+r.loudCurve,v=r.pitchMode===`motion`?se(r.pitchLow+(r.pitchHigh-r.pitchLow)*p,r.scale,oe.indexOf(r.root)):V(r,i.length)[n>0?`right`:`left`][e.index],y=s.play({when:o,freq:J(v),velocity:h,pan:0,duration:r.noteLength});y&&(e.lastNote={handle:y,when:o}),T++}function U(e){let t=e.finalHold+e.finalFade+.3;return(D??e.freeTime+e.dampTime+1)+t}function W(){if(!c||!b)return;let e=t();I();let n=c.ctx.currentTime-S,r=U(e);if(D!==null&&n>=r){R(),E=r,M.onEnded?.();return}B(n+k,!0);for(let e of[g,_])e?.horizon?.(S+C);let i=n-e.trailLength-.5,a=0;for(;a<o.length-2&&o[a+1].t<i;)a++;a>0&&o.splice(0,a)}function G(e,t,n){return`hsl(${((30+360*t/Math.max(1,n))%360).toFixed(0)} ${e.saturation}% 70%)`}function K(e){let t=o.length;if(!t)return null;if(e<=o[0].t)return o[0].s;if(e>=o[t-1].t)return o[t-1].s;let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;o[t].t<=e?n=t:r=t}let i=o[n],a=o[r],s=(e-i.t)/(a.t-i.t),c=new Float64Array(i.s.length);for(let e=0;e<c.length;e++)c[e]=i.s[e]+s*(a.s[e]-i.s[e]);return c}function ee(){let n=t(),s=N(),c=fe(r),l=r.clientWidth,u=r.clientHeight;c.clearRect(0,0,l,u),i.length||P(n,()=>null);let d=i.length,f=a.l1,p=a.l2,m=.46*Math.min(l,u)/(f+p),h=l/2,g=u/2,_=(e,t)=>{let n=h+m*f*Math.sin(e),r=g+m*f*Math.cos(e);return[n,r,n+m*p*Math.sin(t),r+m*p*Math.cos(t)]};if(n.trails&&o.length>1){let e=n.trailLength;c.lineWidth=n.trailWidth,c.lineJoin=c.lineCap=`round`;for(let t=0;t<d;t++){c.strokeStyle=G(n,t,d);for(let n=0;n<6;n++){let r=s-n*e/6,i=s-(n+1)*e/6;c.globalAlpha=.7*(1-(n+.5)/6),c.beginPath();let a=!1;for(let e of o){if(e.t<i-bt||e.t>r+bt)continue;if(e.t>s)break;let[,,n,o]=_(e.s[2*t],e.s[2*t+1]);a?c.lineTo(n,o):(c.moveTo(n,o),a=!0)}c.stroke()}}c.globalAlpha=1}let v=K(s);c.lineWidth=1.5,c.lineCap=`round`;let y=n.bobSize;for(let e=d-1;e>=0;e--){let[t,r,a,o]=_(v?v[2*e]:i[e].p.y[0],v?v[2*e+1]:i[e].p.y[1]),s=G(n,e,d);c.strokeStyle=s,c.fillStyle=s,c.globalAlpha=n.armAlpha,c.beginPath(),c.moveTo(h,g),c.lineTo(t,r),c.lineTo(a,o),c.stroke(),c.globalAlpha=1,c.beginPath(),c.arc(t,r,y*.8,0,2*Math.PI),c.moveTo(a+y,o),c.arc(a,o,y,0,2*Math.PI),c.fill()}c.fillStyle=pe(e,`--fg`),c.beginPath(),c.arc(h,g,1.5,0,2*Math.PI),c.fill()}function te(){let e=t(),n=N(),r=e.freeTime,a=e.dampTime,o=D!==null&&C>=D?`at rest`:n<r?`swinging`:n<r+a?`damping`:`settling`,s=180/Math.PI,c=[g,_].map(e=>e?.load?.()??0),l=[g,_].reduce((e,t)=>e+(t?.underruns?.()??0),0);return{time:`${n.toFixed(1)} / ${M.length().toFixed(0)} s`,phase:o,"energy (mean)":i.length?(i.reduce((e,t)=>e+t.p.energyNorm(),0)/i.length).toFixed(4):`–`,notes:String(T),release:`${(j.th1*s).toFixed(2)}°, ${(j.th2*s).toFixed(2)}°`,"offset (outermost)":`${j.offset.toExponential(2)} rad → separate at ${j.separatesAt.toFixed(1)} s`,"seed used":w?String(w):`–`,"at rest":`${i.filter(e=>e.restAt!==null).length} / ${i.length}`,"audio load":O?`renderers ${Math.round(100*Math.max(...c))}% (busiest), ${l} underruns`:`${Math.round(100*(c[0]+c[1]))}%`}}return M}var Z=(e,t={})=>{let n=Ee.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},St={id:`03-divergence`,title:`divergence`,schema:[{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:40,min:5,max:600,step:1,unit:`s`,hint:`free (undamped) swinging before the damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time for the damping to bring every pendulum to rest`},{group:`form`,key:`dampCurve`,label:`damping curve`,kind:`number`,default:1.5,min:.3,max:5,log:!0,hint:`energy follows (1 − u)^curve during the damping; >1 settles fast then lingers`},{group:`form`,key:`tau`,label:`damping follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how closely each pendulum's energy follows the damping curve`},Z(`restEnergy`,{hint:`after the damping, a pendulum counts as at rest below this energy: its last note rings out`}),Z(`finalHold`),Z(`finalFade`),{group:`pendulums`,key:`count`,label:`pendulums`,kind:`number`,default:12,min:1,max:24,step:1},{group:`pendulums`,key:`releaseAngle`,label:`release angle`,kind:`number`,default:120,min:10,max:179,step:1,unit:`°`,hint:`both arms released from rest at this angle from straight down`},{group:`pendulums`,key:`jitter`,label:`angle variation`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`°`,hint:`each play varies the release angles by up to this much (seed fixes it)`},{group:`pendulums`,key:`separateAt`,label:`separate after`,kind:`number`,default:8,min:1,max:60,step:.5,unit:`s`,hint:`the tiny offsets between pendulums are calibrated so the outermost visibly separate at about this time`},{group:`pendulums`,key:`sepThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`bob separation (fraction of the pendulum's length) that counts as separated`},{group:`pendulums`,key:`speed`,label:`speed`,kind:`number`,default:2.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},Z(`massRatio`,{group:`pendulums`}),Z(`lengthRatio`,{group:`pendulums`}),Z(`seed`,{group:`pendulums`,hint:`0 = a different release every play`}),{group:`notes`,key:`instrument`,label:`instrument`,kind:`select`,default:`modal: Vibraphone`,options:Object.keys(q)},Z(`modalCustom`),{group:`notes`,key:`pitchMode`,label:`pitch`,kind:`select`,default:`chord`,options:[`chord`,`motion`],hint:`chord: each pendulum has its own note of a chord spread over the range. motion: pitch from the bob's speed at the crossing`},{group:`notes`,key:`directionChords`,label:`two chords`,kind:`bool`,default:!0,hint:`chord mode: left-to-right and right-to-left crossings play two interleaved chords, so the swings alternate between them`},Z(`scale`,{default:`dorian`}),Z(`root`),Z(`pitchLow`,{default:50}),Z(`pitchHigh`,{default:86}),{group:`notes`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible at release energy) that gives full loudness (and top pitch in motion mode)`},Z(`loudCurve`),Z(`loudFloor`),Z(`notesLevel`,{default:-8}),Z(`noteLength`,{default:2}),{group:`notes`,key:`directionPan`,label:`pan with direction`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`a crossing is panned toward the side the bob is heading`},{group:`notes`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`,hint:`applies on the next play`},{group:`notes`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render the instrument in a background thread, ~1 s ahead (applies on the next play)`},{group:`visual`,key:`trails`,label:`trails`,kind:`bool`,default:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:3,min:.2,max:20,log:!0,unit:`s`},{group:`visual`,key:`trailWidth`,label:`trail width`,kind:`number`,default:1.2,min:.3,max:5,step:.1,unit:`px`},{group:`visual`,key:`armAlpha`,label:`arm opacity`,kind:`number`,default:.75,min:.05,max:1,step:.01},{group:`visual`,key:`bobSize`,label:`bob size`,kind:`number`,default:3,min:.5,max:10,step:.1,unit:`px`},{group:`visual`,key:`saturation`,label:`color saturation`,kind:`number`,default:35,min:0,max:100,step:1,unit:`%`}],defaults:lt,create:xt},Ct={fallAfter:5,freeTime:60,dampTime:20,dampBase:.004,dampEnd:.2,restEnergy:.001,finalHold:2,finalFade:5,speed:1.5,tipThreshold:.02,massRatio:1,lengthRatio:1,seed:0,crashInstrument:`modal: Violin`,modalCustom:``,crashLow:55,minDepth:.25,crashHigh:79,crashLength:.4,crashCurve:1,firstVel:1,maxVel:.6,loudRef:.8,loudCurve:1,loudFloor:.15,notesLevel:6,maxCrashes:4,deviceLimit:!0,streamAudio:!0,click:!0,clickInstrument:`modal: Viola`,clickPitch:72,clickLength:.5,clickMaxVel:.7,clickLevel:-4,heightNotes:!0,heightInstrument:`modal: Piano-ish`,heightLow:60,heightHigh:96,scale:`dorian`,root:`D`,heightStep:2,heightLength:.3,heightVel:.7,heightLevel:6,heightRamp:6,heightRampFrom:.5,heightFollow:.3,trails:!0,trailLength:2.5,crashRings:!0,motionBlur:1},wt=.6;function Tt(e){let t=e.crashInstrument;if(!t.startsWith(`modal: `))return null;let n=t===`modal: custom`?N(e.modalCustom):k.find(e=>`modal: ${e.name}`===t)?.p;return{...T,...n??{}}}async function Et(e,t,n){let r=Tt(e);if(!r)return{cap:n,perVoice:0};let i=`double-pendulum:capacity:04-crash:${JSON.stringify({v:1,sr:t,i:e.crashInstrument,c:e.modalCustom})}`;try{let e=localStorage.getItem(i);if(e){let t=JSON.parse(e);return{...t,cap:Math.max(1,Math.min(n,t.perVoice>0?Math.floor(wt/t.perVoice):n))}}}catch{}let a=[];for(let e=0;e<2;e+=.7)a.push({time:e,note:31+Math.round(e*10),vel:.8,len:.5});let o=await new Promise(e=>{let n=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`});n.onmessage=t=>{t.data.type===`bench`&&(e(t.data.load),n.terminate())};let i={type:`bench`,sampleRate:t,params:{...r,voices:1},notes:a,seconds:2,warmup:.5};n.postMessage(i)});try{localStorage.setItem(i,JSON.stringify({cap:0,perVoice:o}))}catch{}return{cap:Math.max(1,Math.min(n,Math.floor(wt/o))),perVoice:o}}var Dt=.002;function Ot(e,t,n,r){let i=new ce(e);return i.controlled=!1,i.y[0]=Math.PI+r*t,i.y[1]=Math.PI+r*t*n,i}function kt(e,t){return[e.l1*Math.sin(t[0])+e.l2*Math.sin(t[1]),e.l1*Math.cos(t[0])+e.l2*Math.cos(t[1])]}function At(e,t,n,r,i){let a=Ot(e,t,n,1);for(let t=0;t<i;t+=Dt)if(a.step(Dt),Math.abs(kt(e,a.y)[0])>r)return t+Dt;return 1/0}function jt(e,t,n,r){let i=3*n+10,a=1e-15,o=.3;if(At(e,a,t,r,i)<=n)return{nudge:a,tipsAt:At(e,a,t,r,i)};if(At(e,o,t,r,i)>=n)return{nudge:o,tipsAt:At(e,o,t,r,i)};for(let s=0;s<18;s++){let s=Math.sqrt(a*o);At(e,s,t,r,i)>n?a=s:o=s}let s=Math.sqrt(a*o);return{nudge:s,tipsAt:At(e,s,t,r,i)}}var Mt=et(),Nt=.15,Pt=.4,Ft=25,It=15,Lt=1/480,Rt=48,zt=2,Bt=.9,Vt=.3,Ht=.35;function Ut(e,t){e.classList.add(`c04`);let r=document.createElement(`canvas`);e.append(r);let i={m1:1,l1:1,g:1,m2:1,l2:1},a=null,o=0,s=1,c=1,l=[],u=-1/0,d=[],f=0,h=0,g=null,_=null,v=null,y=null,b=null,x=null,S=``,C=null,w=null,T=``,E=null,D=null,O=``,k=[],A=0,j=0,M,N=!1,P=0,F=0,I=0,L=0,R=0,z=!1,B=Nt,V={d:0,ratio:1,side:1,tipsAt:0},H=null,U=!1,W=4,G={get playing(){return N},start:le,stop:Y,draw:Te,now:K,length:()=>be(t()),readouts:De,notice:Ee,dispose(){Y(),e.classList.remove(`c04`),e.replaceChildren()}};function K(){return!v||!N?R:v.ctx.currentTime-F}function ee(e,t){i={m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio};let n=t&&t()<.5?-1:1,r=t?.6+.8*t():1,u=e.speed,p=jt(i,r,e.fallAfter*u,e.tipThreshold*(i.l1+i.l2));V={d:p.nudge,ratio:r,side:n,tipsAt:p.tipsAt/u},a=Ot(i,p.nudge,r,n),o=kt(i,a.y)[0],s=a.energy(),c=Math.sqrt(2*s/i.m2),l=[],d=[],f=0,h=0,g=null,_=null,ue(0)}function te(){if(!v||!y)return;let e=t(),r=v.ctx;b||(b=r.createGain(),b.connect(y)),b.gain.setTargetAtTime(n(e.notesLevel),r.currentTime,.05);let i=e.crashInstrument,a=`${i}\n${i===`modal: custom`?e.modalCustom:``}\n${W}`;x&&S===a||(x?.dispose(),S=a,x=(z&&Mt[i]||q[i])(r,b,{custom:e.modalCustom,overrides:{voices:W}}))}function ne(){if(!v||!y)return;let e=t(),r=v.ctx;C||(C=r.createGain(),C.connect(y)),C.gain.setTargetAtTime(n(e.clickLevel),r.currentTime,.05);let i=e.clickInstrument,a=e.click?`${i}\n${i===`modal: custom`?e.modalCustom:``}`:``;(T!==a||!w&&a)&&(w?.dispose(),w=null,T=a,a&&(w=(z&&Mt[i]||q[i])(r,C,{custom:e.modalCustom})))}function re(){if(!v||!y)return;let e=t(),r=v.ctx;E||(E=r.createGain(),E.connect(y)),E.gain.setTargetAtTime(n(e.heightLevel),r.currentTime,.05);let i=e.heightInstrument,a=e.heightNotes?`${i}\n${i===`modal: custom`?e.modalCustom:``}`:``;(O!==a||!D&&a)&&(D?.dispose(),D=null,O=a,a&&(D=(z&&Mt[i]||q[i])(r,E,{custom:e.modalCustom})))}function ie(e){let t=e.heightLow,n=e.heightHigh,r=oe.indexOf(e.root),i=[];if(e.scale===`continuous`)for(let e=Math.ceil(t);e<=n;e++)i.push(e);else for(let a=Math.ceil(t);a<=n;a++)Math.abs(se(a,e.scale,r)-a)<1e-6&&i.push(a);let a=Math.max(1,Math.round(e.heightStep));return i.filter((e,t)=>t%a===0)}function ae(e,t){let n=i.l1+i.l2,r=(n-t)/(2*n);return e.heightLow+(e.heightHigh-e.heightLow)*r}function ce(e){let t=0;for(;t<k.length&&k[t]<e;)t++;return t}async function le(e,n){Y();let r=++P;v=e;let o=t(),s=e.ctx;z=!!o.streamAudio,B=z?Je:Nt;let c=Math.round(o.maxCrashes);if(W=c,o.deviceLimit){U=!0;try{H=await Et(o,s.sampleRate,c),W=H.cap}finally{U=!1}if(r!==P)return}L=o.seed>0?Math.round(o.seed):m();let l=p(L);ee(o,()=>l()),k=ie(o),A=ce(ae(o,kt(i,a.y)[1])),j=0,I=0,n>0&&me(n,!1),y=s.createGain(),y.connect(e.input),te(),ne(),re(),await Promise.all([x?.ready,w?.ready,D?.ready]),r===P&&(F=s.currentTime+.1+(z?Pt:0)-n,N=!0,xe(),M=window.setInterval(xe,Ft))}function Y(){if(P++,M!==void 0&&window.clearInterval(M),M=void 0,N&&=(R=K(),!1),!v)return;let e=v.ctx.currentTime,t=y;t&&(t.gain.setTargetAtTime(0,e,.05),window.setTimeout(()=>t.disconnect(),600)),x?.dispose(),x=null,S=``,w?.dispose(),w=null,T=``,C=null,D?.dispose(),D=null,O=``,E=null,b=null,y=null}function ue(e){a&&(l.push({t:e,th1:a.y[0],th2:a.y[1]}),u=e)}function de(e,t){let n=Math.max(0,Math.min(1,(t-e.freeTime)/e.dampTime)),r=n*n*(3-2*n);return e.dampBase+(e.dampEnd-e.dampBase)*r}function me(e,n){if(!a)return;let r=t(),s=r.speed,c=r.freeTime+r.dampTime,l=r.restEnergy,p=r.minDepth*(i.l1+i.l2),m=a;for(;I<e;){let e=I;I+=Dt/s,m.damping=de(r,e),m.step(Dt);let[t,a]=kt(i,m.y);if(_===null&&k.length&&he(e,ae(r,a),r,n),_===null&&Math.abs(a)<=p&&(o<0&&t>=0||o>0&&t<=0)){let i=e+o/(o-t)*(I-e);h++,n&&ye(i,a,r)}else if(_===null&&a>p&&(o<0&&t>=0||o>0&&t<=0)){let i=e+o/(o-t)*(I-e);f++,n?_e(i,a,r):d.push({t:i,x:0,y:a,strength:.5})}o=t,_===null&&I>=c&&(m.energyNorm()<l||I>=c+It)&&(_=I,n&&g&&g.handle.hold(g.when,r.finalHold,r.finalFade)),I-u>=Lt&&ue(I)}}function he(e,t,n,r){let i=Vt*(k.length>1?(k[k.length-1]-k[0])/(k.length-1):1);for(;A<k.length&&t>k[A]+i;)r&&ge(e,k[A],n),A++;for(;A>0&&t<k[A-1]-i;)A--,r&&ge(e,k[A],n)}function ge(e,t,n){if(!v||!D||!a)return;let r=e+Dt/n.speed,i=F+r;if(i<v.ctx.currentTime-.02)return;let o=n.heightRamp>0?Math.max(0,Math.min(1,r/n.heightRamp)):1,c=n.heightRampFrom,l=c+(1-c)*o*o*(3-2*o),u=Math.min(1,Math.max(0,a.energy())/s),d=n.heightVel*l*u**+n.heightFollow;D.play({when:i,freq:J(t),velocity:d,pan:0,duration:n.heightLength}),j++}function _e(e,t,n){if(!v||!x||!a)return;let r=F+e;if(r<v.ctx.currentTime-.02)return;let o=i.l1+i.l2,s=n.minDepth*o,c=Math.max(0,Math.min(1,(o-t)/Math.max(1e-9,o-s))),l=n.crashLow+(n.crashHigh-n.crashLow)*c**+n.crashCurve,u=f===1?n.firstVel:n.maxVel*ve(n),p=x.play({when:r,freq:J(l),velocity:u,pan:0,duration:n.crashLength});p&&(g={handle:p,when:r}),d.push({t:e,x:0,y:t,strength:u})}function ve(e){if(!a)return 0;let t=a.derived(),n=a.y,r=i.l1*Math.cos(n[0])*t.w1+i.l2*Math.cos(n[1])*t.w2,o=i.l1*Math.sin(n[0])*t.w1+i.l2*Math.sin(n[1])*t.w2,s=Math.min(1,Math.hypot(r,o)/(e.loudRef*c)),l=e.loudFloor;return l+(1-l)*s**+e.loudCurve}function ye(e,t,n){if(!v||!w)return;let r=F+e;if(r<v.ctx.currentTime-.02)return;let i=n.clickMaxVel*ve(n);w.play({when:r,freq:J(n.clickPitch),velocity:i,pan:0,duration:n.clickLength}),d.push({t:e,x:0,y:t,strength:i,click:!0})}function be(e){let t=e.finalHold+e.finalFade+.3;return(_??e.freeTime+e.dampTime+3)+t}function xe(){if(!v||!N||!a)return;let e=t();te();let n=v.ctx.currentTime-F,r=be(e);if(_!==null&&n>=r){Y(),R=r,G.onEnded?.();return}ne(),re(),me(n+B,!0);for(let e of[x,w,D])e?.horizon?.(F+I);let i=n-e.trailLength-.5,o=0;for(;o<l.length-2&&l[o+1].t<i;)o++;for(o>0&&l.splice(0,o);d.length&&d[0].t<n-Bt-1;)d.shift()}function Se(e){let t=l.length;if(!t)return{t:e,th1:a?.y[0]??Math.PI,th2:a?.y[1]??Math.PI};if(e<=l[0].t)return l[0];if(e>=l[t-1].t)return l[t-1];let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;l[t].t<=e?n=t:r=t}let i=l[n],o=l[r],s=(e-i.t)/(o.t-i.t);return{t:e,th1:i.th1+s*(o.th1-i.th1),th2:i.th2+s*(o.th2-i.th2)}}let Ce=0,we=1/60;function Te(){let n=t();a||ee(n,null);let o=K(),s=performance.now()/1e3,c=s-Ce;Ce=s,c>0&&c<.1&&(we+=(c-we)*.1);let u=fe(r),f=r.clientWidth,p=r.clientHeight;u.clearRect(0,0,f,p);let m=pe(e,`--fg`),h=i.l1,g=i.l2,_=.46*Math.min(f,p)/(h+g),v=f/2,y=p/2,b=e=>{let t=v+_*h*Math.sin(e.th1),n=y+_*h*Math.cos(e.th1);return[t,n,t+_*g*Math.sin(e.th2),n+_*g*Math.cos(e.th2)]};if(n.trails&&l.length>1){let e=n.trailLength;u.strokeStyle=m,u.lineWidth=1,u.lineJoin=u.lineCap=`round`;for(let t=0;t<6;t++){let n=o-t*e/6,r=o-(t+1)*e/6;u.globalAlpha=.45*(1-(t+.5)/6),u.beginPath();let i=!1;for(let e=0;e<l.length;e+=2){let t=l[e];if(t.t<r-.01||t.t>n+.01)continue;if(t.t>o)break;let[,,a,s]=b(t);i?u.lineTo(a,s):(u.moveTo(a,s),i=!0)}u.stroke()}u.globalAlpha=1}if(n.crashRings){for(let e of d){let t=o-e.t,n=e.click?Ht:Bt;if(t<0||t>n)continue;let[,,r,i]=b(Se(e.t));u.strokeStyle=m,u.globalAlpha=(1-t/n)*(.4+.6*e.strength),u.lineWidth=e.click?1:1.2,u.beginPath();let a=e.click?14:60*(.5+e.strength);u.arc(r,i,(e.click?3:6)+a*Math.sqrt(t/n),0,2*Math.PI),u.stroke()}u.globalAlpha=1}let x=N?n.motionBlur*we:0,S=1;if(x>0){let e=0,t=Se(o);for(let n=1;n<=8;n++){let r=Se(o-x*n/8);e+=_*(h*Math.abs(r.th1-t.th1)+g*Math.abs(r.th2-t.th2)),t=r}S=Math.max(2,Math.min(Rt,Math.ceil(e/zt)))}let C=S===1?1:1-.03**(1/S),w=4*Math.cbrt(i.m2);u.strokeStyle=m,u.fillStyle=m,u.lineWidth=1.5,u.lineCap=`round`,u.globalAlpha=C;for(let e=0;e<S;e++){let[t,n,r,i]=b(Se(o-x*e/Math.max(1,S-1)));u.beginPath(),u.moveTo(v,y),u.lineTo(t,n),u.lineTo(r,i),u.stroke(),u.beginPath(),u.arc(t,n,4,0,2*Math.PI),u.moveTo(r+w,i),u.arc(r,i,w,0,2*Math.PI),u.fill()}u.globalAlpha=1,u.beginPath(),u.arc(v,y,1.5,0,2*Math.PI),u.fill()}function Ee(){if(U)return`checking what this device can play…`;let e=t();if(!e.deviceLimit||!H||H.perVoice===0)return null;if(H.perVoice>.6)return`this device can't render the crashes in real time; expect glitches`;let n=Math.round(e.maxCrashes);return W<n?`${W} overlapping crash${W>1?`es`:``} (of ${n}): reduced to what this device can play`:null}function De(){let e=t(),n=K(),r=e.freeTime,i=e.dampTime,o=_!==null&&I>=_?`at rest`:f===0?`falling`:n<r?`swinging`:n<r+i?`damping`:`settling`;return{time:`${n.toFixed(1)} / ${G.length().toFixed(0)} s`,phase:o,energy:a?`${(a.energy()/s).toFixed(3)} of start`:`–`,crashes:String(f),clicks:String(h),"height notes":String(j),nudge:`${V.d.toExponential(2)} rad ${V.side>0?`→`:`←`} (shape ${V.ratio.toFixed(2)}), tips at ${V.tipsAt.toFixed(1)} s`,friction:`${de(e,n).toFixed(4)} /sim s`,"seed used":L?String(L):`–`,"crash voices":H?`${W} (one ringing crash: ${Math.round(100*H.perVoice)}% of a core)`:String(W),"audio load":z?`renderer ${Math.round(100*(x?.load?.()??0))}%, ${x?.underruns?.()??0} underruns`:`${Math.round(100*(x?.load?.()??0))}%`}}return G}var Q=(e,t={})=>{let n=Ee.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Wt={id:`04-crash`,title:`crash`,schema:[{group:`form`,key:`fallAfter`,label:`tips after`,kind:`number`,default:5,min:1,max:30,step:.5,unit:`s`,hint:`the nudge from straight up is calibrated so the pendulum visibly tips at about this time`},{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:60,min:5,max:600,step:1,unit:`s`,hint:`time before the stronger damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time over which the damping grows to its final strength`},{group:`form`,key:`dampBase`,label:`slight damping`,kind:`number`,default:.004,min:0,max:.1,step:5e-4,unit:`/sim s`,hint:`friction throughout (energy loses roughly this fraction per simulated second)`},{group:`form`,key:`dampEnd`,label:`final damping`,kind:`number`,default:.2,min:.01,max:2,log:!0,unit:`/sim s`,hint:`friction reached by the end of the damping`},Q(`restEnergy`,{hint:`after the damping, the pendulum counts as at rest below this energy: the last crash rings out`}),Q(`finalHold`),Q(`finalFade`),{group:`pendulum`,key:`speed`,label:`speed`,kind:`number`,default:1.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`pendulum`,key:`tipThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`sideways bob movement (fraction of the length) that counts as tipping`},Q(`massRatio`,{group:`pendulum`}),Q(`lengthRatio`,{group:`pendulum`}),Q(`seed`,{group:`pendulum`,hint:`0 = a different nudge (side and shape) every play`}),{group:`crash`,key:`crashInstrument`,label:`instrument`,kind:`select`,default:`modal: Violin`,options:Object.keys(q)},Q(`modalCustom`,{group:`crash`}),{group:`crash`,key:`crashLow`,label:`pitch at bottom`,kind:`number`,default:55,min:12,max:96,step:.5,unit:`midi`,hint:`crossing with the bob straight down (continuous pitch)`},{group:`crash`,key:`minDepth`,label:`minimum depth`,kind:`number`,default:.25,min:0,max:.95,step:.01,hint:`crossings count only this far below the pivot (fraction of the length), so a folded pendulum sweeping its bob past the pivot is silent`},{group:`crash`,key:`crashHigh`,label:`pitch at min depth`,kind:`number`,default:79,min:12,max:108,step:.5,unit:`midi`,hint:`crossing at the minimum depth (the shallowest that counts)`},{group:`crash`,key:`crashLength`,label:`length`,kind:`number`,default:.4,min:.05,max:5,log:!0,unit:`s`},{group:`crash`,key:`crashCurve`,label:`pitch curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`crash`,key:`firstVel`,label:`first crash`,kind:`number`,default:1,min:.05,max:1,step:.01,hint:`strength of the first crash (accent)`},{group:`crash`,key:`maxVel`,label:`strongest crash`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`strength of later crashes at full speed`},{group:`crash`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.8,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible) that gives the strongest crash`},Q(`loudCurve`,{group:`crash`}),Q(`loudFloor`,{group:`crash`,default:.15}),Q(`notesLevel`,{group:`crash`,default:6,max:18}),{group:`crash`,key:`maxCrashes`,label:`overlapping crashes`,kind:`number`,default:4,min:1,max:16,step:1,hint:`most crashes ringing at once (a new one replaces the oldest)`},{group:`crash`,key:`deviceLimit`,label:`limit to device`,kind:`bool`,default:!0,hint:`measure (once per device) how many ringing crashes it can render, and allow no more`},{group:`crash`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render the crashes in a background thread, ~1 s ahead (applies on the next play)`},{group:`click`,key:`click`,label:`click`,kind:`bool`,default:!0,hint:`a click when the outer bob passes the pivot (closer than the minimum depth)`},{group:`click`,key:`clickInstrument`,label:`instrument`,kind:`select`,default:`modal: Viola`,options:Object.keys(q)},{group:`click`,key:`clickPitch`,label:`pitch`,kind:`number`,default:72,min:24,max:120,step:.5,unit:`midi`},{group:`click`,key:`clickLength`,label:`length`,kind:`number`,default:.5,min:.01,max:2,log:!0,unit:`s`},{group:`click`,key:`clickMaxVel`,label:`strongest`,kind:`number`,default:.7,min:.05,max:1,step:.01,hint:`strength at full bob speed (follows the speed like the crashes)`},{group:`click`,key:`clickLevel`,label:`level`,kind:`number`,default:-4,min:-48,max:6,step:.5,unit:`dB`},{group:`height`,key:`heightNotes`,label:`height notes`,kind:`bool`,default:!0,hint:"levels are the scale's notes between the low and high pitch (every `step`-th); passing one, up or down, plays it"},{group:`height`,key:`heightInstrument`,label:`instrument`,kind:`select`,default:`modal: Piano-ish`,options:Object.keys(q)},{group:`height`,key:`heightLow`,label:`pitch at bottom`,kind:`number`,default:60,min:24,max:108,step:.5,unit:`midi`,hint:`bob straight down`},{group:`height`,key:`heightHigh`,label:`pitch at top`,kind:`number`,default:96,min:24,max:120,step:.5,unit:`midi`,hint:`bob straight up`},Q(`scale`,{group:`height`,default:`dorian`}),Q(`root`,{group:`height`}),{group:`height`,key:`heightStep`,label:`step`,kind:`number`,default:2,min:1,max:7,step:1,hint:`levels every this many scale notes (2 = arpeggio-like)`},{group:`height`,key:`heightLength`,label:`length`,kind:`number`,default:.3,min:.05,max:3,log:!0,unit:`s`},{group:`height`,key:`heightVel`,label:`strength`,kind:`number`,default:.7,min:.05,max:1,step:.01},{group:`height`,key:`heightLevel`,label:`level`,kind:`number`,default:6,min:-48,max:18,step:.5,unit:`dB`},{group:`height`,key:`heightRamp`,label:`ramp in`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`the notes grow to full strength over the opening`},{group:`height`,key:`heightRampFrom`,label:`ramp from`,kind:`number`,default:.5,min:0,max:1,step:.01,hint:`starting strength, as a fraction of full`},{group:`height`,key:`heightFollow`,label:`fades with energy`,kind:`number`,default:.3,min:0,max:2,step:.05,hint:`strength × (energy / start energy)^this`},{group:`visual`,key:`trails`,label:`trail`,kind:`bool`,default:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:2.5,min:.2,max:20,log:!0,unit:`s`},{group:`visual`,key:`crashRings`,label:`crash rings`,kind:`bool`,default:!0,hint:`a brief ring where each crash happens`},Q(`motionBlur`)],defaults:Ct,create:Ut},Gt=`double pendulum`,Kt=[De,ct,St,Wt],qt=document.getElementById(`app`),Jt=null;function $(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function Yt(){Jt?.(),Jt=null,qt.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean),t=Kt.find(t=>t.id===e[0]);if(!t)return Xt();Jt=en(t,e[1]===`edit`)}function Xt(){document.title=Gt;let e=$(`ol`,{className:`tracks`});for(let t of Kt)e.append($(`li`,{},$(`a`,{href:`#/${t.id}`,textContent:t.title})));qt.append($(`main`,{className:`album`},$(`h1`,{textContent:Gt}),e))}var Zt=e=>`double-pendulum:author:${e.id}`;function Qt(e){try{let t=localStorage.getItem(Zt(e));return t?JSON.parse(t):null}catch{return null}}function $t(e,t){try{localStorage.setItem(Zt(e),JSON.stringify(t))}catch{}}function en(e,n){let r=Kt.indexOf(e)+1;document.title=`${e.title} · ${Gt}`;let a=()=>i(e.schema,e.defaults),o=n?i(e.schema,e.defaults,Qt(e)):a(),s=$(`div`,{className:`view`}),c=$(`button`,{className:`big-play`,textContent:`▶`,title:`play`});c.setAttribute(`aria-label`,`play`);let l=$(`button`,{className:`play`,textContent:`play`}),u=$(`div`,{className:`bar`}),f=$(`div`,{className:`progress`},u),p=$(`a`,{className:`edit`,href:n?`#/${e.id}`:`#/${e.id}/edit`,textContent:n?`done`:`edit`}),m=$(`header`,{},$(`a`,{href:`#/`,textContent:Gt}),$(`span`,{className:`sep`,textContent:` / `}),$(`span`,{textContent:`${r}. ${e.title}`})),h=$(`div`,{className:`notice`}),g=$(`main`,{className:`stage`},m,h,s,$(`div`,{className:`transport`},l,f,p)),_=$(`div`,{className:n?`page with-author`:`page`},g);qt.append(_);let v=e.create(s,()=>o);s.append(c);let y=()=>{let e=Math.floor(Math.min(s.clientWidth,s.clientHeight));for(let t of s.querySelectorAll(`canvas`))t.style.width=`${e}px`,t.style.height=`${e}px`},b=new ResizeObserver(y);b.observe(s),y();let x={value:0},S=!1,C=async e=>{S=!0;try{let n=await t();await v.start(n,e)}finally{S=!1}};l.onclick=()=>v.playing?v.stop():C(n?x.value:0),c.onclick=()=>l.click(),n&&(f.classList.add(`seekable`),f.onclick=e=>{let t=f.getBoundingClientRect(),n=Math.max(0,(e.clientX-t.left)/t.width*v.length());C(n)});let w=null;n&&(w=d({schema:e.schema,get:()=>o,set:t=>{o=t,$t(e,t)},defaults:a,readouts:()=>v.readouts(),startAt:x}),_.append(w.el));let T=e=>{let t=e.target.tagName;e.code===`Space`&&t!==`INPUT`&&t!==`SELECT`&&t!==`BUTTON`&&(e.preventDefault(),l.click())};window.addEventListener(`keydown`,T);let E=0,D=0,O=e=>{v.draw(),l.textContent=v.playing?`stop`:`play`,c.hidden=v.playing||S;let t=v.notice?.()??``;h.textContent!==t&&(h.textContent=t),u.style.width=`${Math.min(100,100*v.now()/v.length())}%`,w&&e-D>200&&(w.updateReadouts(),D=e),E=requestAnimationFrame(O)};return E=requestAnimationFrame(O),()=>{cancelAnimationFrame(E),window.removeEventListener(`keydown`,T),b.disconnect(),v.dispose()}}window.addEventListener(`hashchange`,Yt),Yt();
\ No newline at end of file
2+`}var o=1e3;function s(e,t){let n=e.log?Math.log(t/e.min)/Math.log(e.max/e.min):(t-e.min)/(e.max-e.min);return Math.round(Math.max(0,Math.min(1,n))*o)}function c(e,t){let n=t/o,r=e.log?e.min*(e.max/e.min)**+n:e.min+n*(e.max-e.min);return e.step&&(r=Math.round(r/e.step)*e.step),Number(r.toPrecision(4))}function l(e){return String(Number(e.toPrecision(4)))}function u(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function d(e){let t=u(`aside`,{className:`author`}),n=[],r=(t,n)=>{e.set({...e.get(),[t]:n})},d=u(`span`,{className:`status`}),f=e=>{d.textContent=e,window.setTimeout(()=>{d.textContent===e&&(d.textContent=``)},2e3)},p=u(`button`,{textContent:`copy config`});p.onclick=async()=>{let t=a(e.schema,e.get());try{await navigator.clipboard.writeText(t),f(`copied`)}catch{window.prompt(`copy:`,t)}};let m=u(`button`,{textContent:`paste config`});m.onclick=async()=>{let t=null;try{t=await navigator.clipboard.readText()}catch{t=window.prompt(`paste config JSON:`)}if(t)try{e.set(i(e.schema,JSON.parse(t))),y(),f(`pasted`)}catch{f(`not valid JSON`)}};let h=u(`button`,{textContent:`reset to defaults`});h.onclick=()=>{window.confirm(`Discard your edits and return to the published defaults?`)&&(e.set(e.defaults()),y())},t.append(u(`div`,{className:`actions`},p,m,h,d));let g=u(`input`,{type:`number`,min:`0`,step:`1`,value:String(e.startAt.value)});g.oninput=()=>{e.startAt.value=Math.max(0,Number(g.value)||0)},t.append(u(`label`,{className:`row`},u(`span`,{textContent:`start at (s)`}),g));let _=u(`dl`,{className:`readouts`});t.append(_);let v=new Map;for(let i of e.schema){let a=v.get(i.group);a||(a=u(`fieldset`,{},u(`legend`,{textContent:i.group})),v.set(i.group,a),t.append(a));let d=u(`label`,{className:`row`},u(`span`,{textContent:i.label,title:i.hint??``}));if(i.kind===`number`){let t=u(`input`,{type:`range`,min:`0`,max:String(o),step:`1`}),a=u(`input`,{type:`number`,step:`any`}),f=u(`span`,{className:`unit`,textContent:i.unit??``});t.oninput=()=>{let e=c(i,Number(t.value));a.value=l(e),r(i.key,e)},a.onchange=()=>{let e=Number(a.value);Number.isFinite(e)&&(t.value=String(s(i,e)),r(i.key,e))},n.push(()=>{let n=e.get()[i.key];t.value=String(s(i,n)),a.value=l(n)}),d.append(t,a,f)}else if(i.kind===`select`){let t=u(`select`);for(let e of i.options)t.append(u(`option`,{value:e,textContent:e}));t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),d.append(t)}else if(i.kind===`text`){let t=u(`textarea`,{rows:3,spellcheck:!1,placeholder:i.hint??``});t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),d.classList.add(`text`),d.append(t)}else{let t=u(`input`,{type:`checkbox`});t.onchange=()=>r(i.key,t.checked),n.push(()=>t.checked=e.get()[i.key]),d.append(t)}a.append(d)}function y(){for(let e of n)e()}function b(){let t=e.readouts();_.replaceChildren(...Object.entries(t).flatMap(([e,t])=>[u(`dt`,{textContent:e}),u(`dd`,{textContent:t})]))}return y(),b(),{el:t,sync:y,updateReadouts:b}}var f={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:50,massRatio:1,lengthRatio:1,tau:2,seed:0,noteInstrument:`modal: Nylon harp`,modalCustom:``,scale:`dorian`,root:`D`,pitchSource:`signed`,thetaRange:3.1416,pitchLow:50,pitchHigh:86,pitchCurve:1,invertPitch:!1,p2Ref:1,loudCurve:1,loudFloor:.08,notesLevel:-6,noteLength:1.5,panAmount:.6,humInstrument:`modal: Clarinet-ish`,humCustom:``,humPitch:38,humLevel:-24,humFollow:0,humNormalize:!0,humColorMode:`log`,humColorCurve:1,humTarget1:`pickup`,humFrom1:.15,humTo1:.75,humTarget2:`tilt`,humFrom2:.3333,humTo2:.5833,humFadeIn:3,humFadeOut:6,pendulumAlpha:1,pendulumSize:.32,motionBlur:1,fade:10,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2,orbits:!0,orbitCount:24,orbitCpu:.4,orbitLife:300,orbitBand:.25,orbitMinHold:3,orbitMaxPoints:8e3,orbitXfade:1.5,orbitAlpha:.3,orbitSize:1};function p(e){let t=e>>>0;return()=>{t=t+0x6d2b79f5>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function m(){return 1+Math.floor(Math.random()*999999)}var h=(e,t)=>e[t],g=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,_=(...e)=>t=>e.includes(t.geometry),v=(...e)=>t=>e.includes(t.exciter),y=[`bow`,`reed`,`selfosc`,`noise`],b=[[`off`,`Off`],[`pitch`,`Pitch`],[`amp`,`Amplitude`],[`position`,`Excite position`],[`pickup`,`Pickup position`],[`tension`,`Tension coupling`],[`cascade`,`Cascade coupling`],[`damping`,`Damping`],[`feedback`,`Feedback gain`],[`exciter`,`Exciter intensity`]],x=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function S(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:b,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:x,def:`sine`,show:t},{kind:`num`,id:`lfo${e}Rate`,label:`Rate`,group:`Modulation`,min:.01,max:40,def:1,scale:`log`,unit:`Hz`,show:t},{kind:`num`,id:`lfo${e}Depth`,label:`Depth`,group:`Modulation`,min:0,max:1,def:.3,scale:`pow2`,show:t}]}var C=[{kind:`enum`,id:`geometry`,label:`Geometry`,group:`Body`,model:!0,def:`string`,options:[[`string`,`String`],[`bar`,`Bar (free–free)`],[`tube_co`,`Tube (closed–open)`],[`tube_oo`,`Tube (open–open)`],[`membrane`,`Membrane (circular)`],[`plate`,`Plate (rectangular)`],[`disc`,`Disc (cymbal / gong)`],[`ring`,`Bell / ring`],[`free`,`Free spectrum (kᵖ)`]],hint:`Sets the mode frequency ratios and mode shapes`},{kind:`num`,id:`modes`,label:`Modes`,group:`Body`,min:4,max:256,def:64,int:!0,model:!0,scale:`log`},{kind:`num`,id:`aspect`,label:`Aspect ratio`,group:`Body`,min:.2,max:1,def:.71,model:!0,show:_(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:_(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:_(`disc`),hint:`f ∝ (m + 2n)^p: 2 = flat plate; lower for domed cymbals and gongs`},{kind:`num`,id:`stretch`,label:`Stretch`,group:`Body`,min:.5,max:2,def:1,model:!0,digits:3,hint:`ratio → ratio^s (bar with s≈1.368 gives the 1:4:10 marimba tuning)`},{kind:`num`,id:`inharm`,label:`Stiffness B`,group:`Body`,min:0,max:.05,def:0,scale:`pow2`,model:!0,digits:5,hint:`ratio·√(1+B·ratio²): piano-like stretched partials`},{kind:`num`,id:`harmonize`,label:`Harmonize`,group:`Body`,min:0,max:1,def:0,model:!0,hint:`pull partials toward integer multiples`},{kind:`num`,id:`jitter`,label:`Detune jitter`,group:`Body`,min:0,max:200,def:0,scale:`pow2`,unit:`¢`,model:!0},{kind:`num`,id:`seed`,label:`Seed`,group:`Body`,min:1,max:999,def:1,int:!0,model:!0,hint:`random detune, coupling topology and radiation`},{kind:`num`,id:`t60`,label:`Decay T60`,group:`Damping`,min:.05,max:60,def:4,scale:`log`,unit:`s`},{kind:`num`,id:`hfDamp`,label:`HF damping`,group:`Damping`,min:0,max:100,def:2,scale:`pow2`,unit:`/s@1k`,hint:`extra decay rate σ = c·(f/1kHz)²`},{kind:`num`,id:`damper`,label:`Damper T60`,group:`Damping`,min:.02,max:20,def:.3,scale:`log`,unit:`s`,hint:`applied on key release; max = no damper`},{kind:`num`,id:`tension`,label:`Tension modulation`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`amplitude-dependent pitch (glides)`},{kind:`num`,id:`cascade`,label:`Cascade coupling`,group:`Nonlinear`,min:0,max:20,def:0,scale:`pow2`,digits:3,hint:`random quartic coupling: energy spreads across modes (gong/cymbal shimmer)`},{kind:`num`,id:`curvature`,label:`Curvature (3-wave)`,group:`Nonlinear`,min:0,max:3,def:0,scale:`pow2`,digits:3,hint:`quadratic forces: sum/difference tones, crashes`},{kind:`num`,id:`terms`,label:`Coupling terms`,group:`Nonlinear`,min:1,max:16,def:6,int:!0,model:!0},{kind:`num`,id:`nlModes`,label:`Coupled modes`,group:`Nonlinear`,min:4,max:128,def:48,int:!0,model:!0,scale:`log`},{kind:`num`,id:`glide`,label:`Pitch glide`,group:`Nonlinear`,min:-12,max:12,def:0,unit:`st`,hint:`pitch offset while loud, relaxing as the note decays: + falls (like tension), − rises (Chinese opera gong)`},{kind:`num`,id:`crossTension`,label:`Cross-note tension`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`notes share one tension: they bend each other`},{kind:`num`,id:`crossLink`,label:`Cross-note link`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`sympathetic coupling + intermodulation between notes`},{kind:`num`,id:`buzz`,label:`Barrier stiffness`,group:`Collision`,min:0,max:1,def:0,scale:`pow2`,digits:3,hint:`sitar bridge, snare wires, rattles`},{kind:`num`,id:`buzzGap`,label:`Gap`,group:`Collision`,min:0,max:2,def:.2,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPos`,label:`Position`,group:`Collision`,min:0,max:1,def:.02,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPosY`,label:`Position Y`,group:`Collision`,min:0,max:1,def:.5,show:e=>e.buzz>0&&g(e)},{kind:`enum`,id:`buzzSides`,label:`Barrier`,group:`Collision`,options:[[`one`,`One-sided (bridge)`],[`two`,`Two-sided (rattle)`]],def:`one`,show:e=>e.buzz>0},{kind:`enum`,id:`exciter`,label:`Key exciter`,group:`Exciter`,def:`strike`,options:[[`strike`,`Strike (hammer / mallet)`],[`pluck`,`Pluck`],[`impulse`,`Impulse`],[`bow`,`Bow`],[`reed`,`Reed / blow`],[`selfosc`,`Self-oscillator`],[`noise`,`Noise`]]},{kind:`num`,id:`strength`,label:`Strength`,group:`Exciter`,min:0,max:6,def:1,scale:`pow2`,hint:`>1 pushes the body into its nonlinear regime`},{kind:`num`,id:`exPos`,label:`Position`,group:`Exciter`,min:0,max:1,def:.13,digits:3},{kind:`num`,id:`exPosY`,label:`Position Y`,group:`Exciter`,min:0,max:1,def:.37,show:g},{kind:`num`,id:`exWidth`,label:`Contact width`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`},{kind:`num`,id:`hammerMass`,label:`Hammer mass`,group:`Exciter`,min:.005,max:5,def:.1,scale:`log`,digits:3,show:v(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:v(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:v(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:v(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:v(`bow`),hint:`scaled by key velocity: sets the loudness`},{kind:`num`,id:`bowNoise`,label:`Bow noise`,group:`Exciter`,min:0,max:1,def:0,scale:`pow2`,show:v(`bow`),hint:`random bow-force fluctuation: rosin and hair noise`},{kind:`num`,id:`reedPressure`,label:`Mouth pressure`,group:`Exciter`,min:0,max:1.5,def:.6,show:v(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:v(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:v(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:v(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:v(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:v(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:v(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:v(...y)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:v(...y)},{kind:`num`,id:`fbGain`,label:`Feedback gain`,group:`Feedback`,min:0,max:8,def:0,scale:`pow2`,hint:`output → delay → band-pass → saturate → back into the body (while a key is held)`},{kind:`num`,id:`fbDelay`,label:`Delay`,group:`Feedback`,min:.05,max:600,def:5,scale:`log`,unit:`ms`,show:e=>e.fbGain>0},{kind:`num`,id:`fbFreq`,label:`Band centre`,group:`Feedback`,min:30,max:12e3,def:800,scale:`log`,unit:`Hz`,show:e=>e.fbGain>0},{kind:`num`,id:`fbQ`,label:`Band Q`,group:`Feedback`,min:.3,max:30,def:1.5,scale:`log`,show:e=>e.fbGain>0},{kind:`num`,id:`fbSat`,label:`Saturation`,group:`Feedback`,min:.01,max:4,def:.4,scale:`log`,show:e=>e.fbGain>0},...S(1),...S(2),{kind:`num`,id:`vibDepth`,label:`Vibrato depth`,group:`Modulation`,min:0,max:100,def:0,scale:`pow2`,unit:`¢`,hint:`per-note vibrato, each note with its own phase and rate`},{kind:`num`,id:`vibRate`,label:`Vibrato rate`,group:`Modulation`,min:1,max:12,def:5.5,unit:`Hz`,show:e=>e.vibDepth>0},{kind:`num`,id:`vibDelay`,label:`Vibrato onset`,group:`Modulation`,min:0,max:2e3,def:300,unit:`ms`,show:e=>e.vibDepth>0,hint:`vibrato fades in after the note starts`},{kind:`num`,id:`bendRange`,label:`Pitch-bend range`,group:`Modulation`,min:0,max:24,def:2,int:!0,unit:`st`},{kind:`enum`,id:`soundbox`,label:`Soundbox`,group:`Soundbox`,def:`off`,options:[[`off`,`Off`],[`violin`,`Violin`],[`viola`,`Viola`],[`cello`,`Cello`],[`bass`,`Double bass`],[`guitar`,`Guitar`]],hint:`fixed resonances that every note passes through (they don't transpose)`},{kind:`num`,id:`boxSize`,label:`Size`,group:`Soundbox`,min:.4,max:3,def:1,scale:`log`,digits:3,show:e=>e.soundbox!==`off`,hint:`>1 lowers every resonance`},{kind:`num`,id:`boxDamp`,label:`Damping`,group:`Soundbox`,min:.3,max:4,def:1,scale:`log`,show:e=>e.soundbox!==`off`,hint:`scales every resonance's bandwidth`},{kind:`num`,id:`boxMix`,label:`Mix`,group:`Soundbox`,min:0,max:1,def:1,show:e=>e.soundbox!==`off`},{kind:`num`,id:`pickup`,label:`Pickup position`,group:`Output`,min:0,max:1,def:.77,digits:3},{kind:`num`,id:`pickupY`,label:`Pickup Y`,group:`Output`,min:0,max:1,def:.61,show:g},{kind:`num`,id:`width`,label:`Stereo width`,group:`Output`,min:0,max:1,def:.3,hint:`right pickup is offset from the left one`},{kind:`num`,id:`spread`,label:`Whole-body radiation`,group:`Output`,min:0,max:1,def:.2,hint:`0 = point pickup, 1 = every mode radiates equally`},{kind:`num`,id:`tilt`,label:`Spectral tilt`,group:`Output`,min:-12,max:12,def:0,unit:`dB/oct`},{kind:`num`,id:`level`,label:`Level`,group:`Output`,min:-24,max:36,def:0,unit:`dB`,hint:`instrument level (saved with presets; Volume is not)`},{kind:`num`,id:`voices`,label:`Max notes`,group:`Output`,min:1,max:16,def:8,int:!0},{kind:`num`,id:`drive`,label:`Saturation`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayMix`,label:`Delay mix`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayTime`,label:`Delay time`,group:`Output`,min:10,max:1500,def:350,scale:`log`,unit:`ms`,show:e=>e.delayMix>0},{kind:`num`,id:`delayFb`,label:`Delay feedback`,group:`Output`,min:0,max:.95,def:.35,show:e=>e.delayMix>0},{kind:`num`,id:`reverbMix`,label:`Reverb mix`,group:`Output`,min:0,max:1,def:.15},{kind:`num`,id:`reverbSize`,label:`Reverb time`,group:`Output`,min:.2,max:12,def:2.5,scale:`log`,unit:`s`,show:e=>e.reverbMix>0},{kind:`num`,id:`volume`,label:`Volume`,group:`Output`,min:-40,max:12,def:-6,unit:`dB`},{kind:`bool`,id:`seqOn`,label:`Auto-play`,group:`Auto`,def:!1},{kind:`enum`,id:`seqMode`,label:`Pattern`,group:`Auto`,def:`mixed`,options:[[`mixed`,`Mixed (changes every 4 bars)`],[`melody`,`Melody`],[`arpeggio`,`Arpeggio`],[`chords`,`Chords`],[`rhythm`,`Rhythm (one pitch)`],[`drone`,`Drone + sparse melody`]]},{kind:`num`,id:`seqTempo`,label:`Tempo`,group:`Auto`,min:20,max:400,def:110,int:!0,unit:`bpm`},{kind:`num`,id:`seqDensity`,label:`Density`,group:`Auto`,min:0,max:1,def:.5},{kind:`enum`,id:`seqScale`,label:`Scale`,group:`Auto`,def:`pentatonic`,options:[[`chromatic`,`Chromatic`],[`major`,`Major`],[`minor`,`Natural minor`],[`dorian`,`Dorian`],[`pentatonic`,`Pentatonic`],[`wholetone`,`Whole tone`],[`harmonic`,`Harmonic series`]]},{kind:`num`,id:`seqRoot`,label:`Root`,group:`Auto`,min:24,max:84,def:48,int:!0},{kind:`num`,id:`seqRange`,label:`Range`,group:`Auto`,min:1,max:4,def:2,int:!0,unit:`oct`},{kind:`num`,id:`seqGate`,label:`Note length`,group:`Auto`,min:.05,max:8,def:.5,scale:`log`,unit:`beats`},{kind:`num`,id:`seqPoly`,label:`Notes per step`,group:`Auto`,min:1,max:4,def:1,int:!0,show:e=>e.seqMode===`melody`||e.seqMode===`mixed`},{kind:`num`,id:`seqVelRand`,label:`Velocity spread`,group:`Auto`,min:0,max:1,def:.3},{kind:`num`,id:`seqPosRand`,label:`Position spread`,group:`Auto`,min:0,max:1,def:0,hint:`randomize where each note is excited`}],w=Object.fromEntries(C.map(e=>[e.id,e])),T=Object.fromEntries(C.map(e=>[e.id,e.def]));C.filter(e=>e.model).map(e=>e.id);var E=class{ctx;input;analyser;scope;shaper;dry;delaySend;dL;dR;fbL;fbR;revSend;conv;master;lastDrive=-1;lastSize=-1;sizeTimer;constructor(e,t=e.destination){this.ctx=e,this.input=e.createGain(),this.analyser=e.createAnalyser(),this.analyser.fftSize=8192,this.analyser.smoothingTimeConstant=0,this.analyser.minDecibels=-120,this.analyser.maxDecibels=-10,this.scope=e.createAnalyser(),this.scope.fftSize=4096,this.input.connect(this.analyser),this.input.connect(this.scope),this.shaper=e.createWaveShaper(),this.shaper.oversample=`4x`,this.dry=e.createGain(),this.master=e.createGain(),this.input.connect(this.shaper),this.shaper.connect(this.dry),this.dry.connect(this.master),this.delaySend=e.createGain();let n=e.createChannelSplitter(2),r=e.createChannelMerger(2);this.dL=e.createDelay(2),this.dR=e.createDelay(2),this.fbL=e.createGain(),this.fbR=e.createGain(),this.shaper.connect(this.delaySend),this.delaySend.connect(n),n.connect(this.dL,0),n.connect(this.dR,1),this.dL.connect(this.fbL),this.fbL.connect(this.dR),this.dR.connect(this.fbR),this.fbR.connect(this.dL),this.dL.connect(r,0,0),this.dR.connect(r,0,1),r.connect(this.master),this.revSend=e.createGain(),this.conv=e.createConvolver(),this.shaper.connect(this.revSend),this.revSend.connect(this.conv),this.conv.connect(this.master);let i=e.createDynamicsCompressor();i.threshold.value=-3,i.knee.value=3,i.ratio.value=20,i.attack.value=.002,i.release.value=.15,this.master.connect(i),i.connect(t)}set(e){let t=this.ctx.currentTime,n=(e,n)=>e.setTargetAtTime(n,t,.02),r=h(e,`drive`);if(r!==this.lastDrive){if(this.lastDrive=r,r<=0)this.shaper.curve=null;else{let e=1+40*r*r,t=2048,n=new Float32Array(t);for(let r=0;r<t;r++){let t=r/2047*2-1;n[r]=Math.tanh(e*t)/Math.tanh(e)}this.shaper.curve=n}}let i=h(e,`delayMix`);n(this.delaySend.gain,i);let a=h(e,`delayTime`)/1e3;n(this.dL.delayTime,a),n(this.dR.delayTime,a),n(this.fbL.gain,h(e,`delayFb`)),n(this.fbR.gain,h(e,`delayFb`));let o=h(e,`reverbMix`);n(this.revSend.gain,o),n(this.dry.gain,r>0?1/(1+2*r):1),n(this.master.gain,10**(h(e,`volume`)/20));let s=h(e,`reverbSize`);s!==this.lastSize&&(this.lastSize=s,clearTimeout(this.sizeTimer),this.sizeTimer=window.setTimeout(()=>this.conv.buffer=this.makeIR(s),150))}makeIR(e){let t=this.ctx.sampleRate,n=Math.round(t*Math.min(e*1.1,12)),r=this.ctx.createBuffer(2,n,t);for(let i=0;i<2;i++){let a=r.getChannelData(i),o=0;for(let r=0;r<n;r++){let n=r/t,i=9e3*Math.exp(-n/(.6*e))+400,s=1-Math.exp(-2*Math.PI*i/t);o+=s*(Math.random()*2-1-o);let c=Math.exp(-6.9*n/e)*Math.min(1,n/.004);a[r]=o*c*.5}}return r}},D=new URL(`worklet-B7ys4Kw_.js`,import.meta.url).href,O={geometry:`string`,t60:3,hfDamp:2,damper:.6,exciter:`bow`,bowForce:1,bowSpeed:.4,bowNoise:.06,noiseColor:4e3,exWidth:.1,attack:80,release:150,pickup:.99,width:0,spread:0,tilt:-6,vibDelay:350,boxMix:.9,level:23,voices:4,reverbMix:.25,reverbSize:2.2},k=[{name:`Piano-ish`,category:`Instrument`,note:48,p:{geometry:`string`,modes:80,inharm:4e-4,t60:9,hfDamp:1.2,damper:.15,exciter:`strike`,strength:1,exPos:.12,exWidth:.04,hammerMass:.04,hardness:1.4,feltExp:2.6,tension:.01,crossLink:.15,pickup:.77,spread:.35,width:.4,reverbMix:.18}},{name:`Steel-string pluck`,category:`Instrument`,note:52,p:{geometry:`string`,modes:64,inharm:8e-5,t60:5,hfDamp:3,damper:.4,exciter:`pluck`,strength:1,exPos:.18,exWidth:.03,tension:.02,pickup:.92,spread:.25,reverbMix:.15}},{name:`Nylon harp`,category:`Instrument`,note:60,p:{geometry:`string`,modes:48,t60:3.5,hfDamp:8,damper:20,exciter:`pluck`,exPos:.35,exWidth:.2,pickup:.5,spread:.5,reverbMix:.25}},{name:`Marimba`,category:`Instrument`,note:60,p:{geometry:`bar`,modes:24,stretch:1.368,t60:1.3,hfDamp:6,damper:20,exciter:`strike`,exPos:.42,exWidth:.05,hammerMass:.25,hardness:1,feltExp:2,pickup:.22,spread:.3,reverbMix:.2}},{name:`Vibraphone`,category:`Instrument`,note:65,p:{geometry:`bar`,modes:24,stretch:1.368,t60:7,hfDamp:1.5,damper:.2,exciter:`strike`,exPos:.45,exWidth:.05,hammerMass:.15,hardness:.8,feltExp:2.2,pickup:.22,spread:.3,lfo1Target:`amp`,lfo1Rate:5,lfo1Depth:.45,reverbMix:.25}},{name:`Church bell`,category:`Instrument`,note:55,p:{geometry:`ring`,modes:40,t60:14,hfDamp:.4,damper:20,jitter:4,exciter:`strike`,exPos:.1,exWidth:.02,hammerMass:.6,hardness:.5,feltExp:1.5,tension:.01,pickup:.3,spread:.5,reverbMix:.35,reverbSize:5}},{name:`Tom drum`,category:`Instrument`,note:43,p:{geometry:`membrane`,modes:40,t60:.7,hfDamp:6,damper:20,tension:.25,exciter:`strike`,strength:1.6,exPos:.35,exPosY:.45,exWidth:.05,hammerMass:.3,hardness:2.5,feltExp:2,pickup:.5,pickupY:.5,spread:.5,reverbMix:.15}},{name:`Snare-ish`,category:`Instrument`,note:50,p:{geometry:`membrane`,modes:64,t60:.5,hfDamp:2,damper:20,tension:.1,buzz:.5,buzzGap:.05,buzzPos:.5,buzzPosY:.55,buzzSides:`two`,exciter:`strike`,strength:1.5,exPos:.4,exPosY:.4,exWidth:.02,hammerMass:.05,hardness:.6,feltExp:1.5,pickup:.5,pickupY:.5,spread:.6,reverbMix:.15}},{name:`Sitar / tanpura`,category:`Instrument`,note:50,p:{geometry:`string`,modes:96,t60:8,hfDamp:.3,damper:20,buzz:.6,buzzGap:.15,buzzPos:.015,buzzSides:`one`,exciter:`pluck`,strength:1.2,exPos:.2,exWidth:.02,pickup:.12,spread:.3,reverbMix:.25}},{name:`Cello`,category:`Instrument`,note:48,p:{...O,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...O,modes:80,inharm:2e-5,exPos:.1,exWidth:.15,vibDepth:14,vibRate:5.8,vibDelay:250,soundbox:`violin`}},{name:`Viola`,category:`Instrument`,note:60,p:{...O,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...O,modes:160,inharm:6e-5,exPos:.08,t60:4,attack:120,vibDepth:12,vibRate:4.8,vibDelay:450,soundbox:`bass`,voices:3,level:20}},{name:`Cello pizzicato`,category:`Instrument`,note:48,p:{...O,modes:96,inharm:4e-5,exciter:`pluck`,strength:1.2,exPos:.3,exWidth:.25,t60:2.2,hfDamp:8,damper:.4,vibDepth:0,soundbox:`cello`,voices:8,level:24}},{name:`Clarinet-ish`,category:`Instrument`,note:50,p:{geometry:`tube_co`,modes:24,t60:.25,hfDamp:6,damper:.05,exciter:`reed`,reedPressure:.7,reedGain:.4,breath:.03,noiseColor:3e3,exPos:0,exWidth:0,attack:30,release:60,pickup:.25,spread:.2,reverbMix:.2}},{name:`Singing bowl`,category:`Instrument`,note:62,p:{geometry:`ring`,modes:24,t60:20,hfDamp:.5,damper:20,jitter:2,exciter:`selfosc`,selfGain:.15,selfSat:.3,exPos:0,exWidth:.01,attack:1500,release:3e3,pickup:.15,spread:.4,width:.6,reverbMix:.35,reverbSize:6}},{name:`Rubber band`,category:`Experimental`,note:40,p:{geometry:`string`,modes:40,t60:1.5,hfDamp:4,damper:.3,tension:1.2,exciter:`pluck`,strength:2.5,exPos:.3,exWidth:.05,pickup:.8,reverbMix:.1}},{name:`Chaos gong`,category:`Experimental`,note:40,p:{geometry:`plate`,modes:128,aspect:.8,nlModes:64,terms:8,cascade:12,curvature:2.2,t60:10,hfDamp:.2,damper:20,crossTension:.4,crossLink:.8,exciter:`strike`,strength:3.5,exPos:.3,exPosY:.3,hammerMass:.4,hardness:2,feltExp:2,pickup:.6,pickupY:.7,spread:.5,width:.6,reverbMix:.3,reverbSize:6,voices:4}},{name:`Ring-mod chords`,category:`Experimental`,note:57,p:{geometry:`free`,powerExp:1.7,modes:32,jitter:15,t60:6,hfDamp:1,damper:1,crossTension:.3,crossLink:1.4,curvature:.5,exciter:`strike`,strength:1.8,exPos:.2,hammerMass:.1,hardness:.8,pickup:.7,spread:.6,width:.6,delayMix:.25,delayTime:375,delayFb:.4,reverbMix:.3}},{name:`Feedback drone plate`,category:`Experimental`,note:45,p:{geometry:`plate`,modes:96,aspect:.62,nlModes:64,cascade:.8,curvature:.3,t60:6,hfDamp:.5,damper:3,exciter:`noise`,noiseLevel:.2,noiseColor:800,attack:800,release:3e3,fbGain:2.5,fbDelay:12,fbFreq:600,fbQ:2,fbSat:.4,lfo1Target:`position`,lfo1Rate:.07,lfo1Depth:.5,lfo1Shape:`smooth`,lfo2Target:`pickup`,lfo2Rate:.11,lfo2Depth:.4,lfo2Shape:`smooth`,pickup:.3,pickupY:.7,spread:.3,width:.7,reverbMix:.35,reverbSize:5,voices:4}},{name:`Buzzing bar organ`,category:`Experimental`,note:48,p:{geometry:`bar`,modes:32,t60:3,hfDamp:1,damper:.3,buzz:.4,buzzGap:.3,buzzPos:.5,buzzSides:`two`,exciter:`selfosc`,selfGain:.6,selfSat:.4,exPos:.02,attack:60,release:300,pickup:.3,spread:.3,reverbMix:.25}},{name:`Glass harmonics`,category:`Experimental`,note:72,p:{geometry:`free`,powerExp:1.25,modes:24,harmonize:.3,t60:12,hfDamp:.3,damper:2,exciter:`impulse`,strength:.8,hardness:.3,exPos:.21,pickup:.6,spread:.6,width:.8,tension:.05,lfo1Target:`pickup`,lfo1Rate:.3,lfo1Depth:.6,delayMix:.3,delayTime:450,delayFb:.5,reverbMix:.45,reverbSize:7}}];function A(e,t=128){let n=new Float32Array(t);for(let r=0;r<t;r++)n[r]=e*Math.cos(Math.PI/2*(r/(t-1)))**2;return n}var j=new WeakMap;function M(e){let t=j.get(e);return t||(t=e.audioWorklet.addModule(D),j.set(e,t)),t}function N(e){if(!e||!e.trim())return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}function P(e,t,n,r,i){let a=i.effects??`own`;if(a===`own`){let i=new E(e,n);t.connect(i.input),i.set(r);return}let o=e.createGain();if(o.gain.value=10**(r.volume/20),t.connect(o).connect(n),a!==`none`){let n=e.createGain();n.gain.value=r.reverbMix*o.gain.value,t.connect(n).connect(a.send)}}var F=.2,I=25;function L(e){return(t,n,r)=>{let i={...T,...e??N(r.custom)??{},...r.overrides??{}},a=t.createGain();P(t,a,n,i,r);let o=null,s=0,c=[],l=e=>o?o.port.postMessage(e):c.push(e),u=M(t).then(()=>{o=new AudioWorkletNode(t,`modal-synth`,{numberOfInputs:0,outputChannelCount:[2]}),o.port.onmessage=e=>{e.data?.type===`snap`&&typeof e.data.cpu==`number`&&(s+=(e.data.cpu-s)*.2)},o.port.postMessage({type:`params`,params:i});for(let e of c.splice(0))o.port.postMessage(e);o.connect(a)}),d=[],f=new Map,p=window.setInterval(()=>{let e=t.currentTime+F,n=[];for(let t of d)t.time>e?n.push(t):(f.get(t.note)??-1/0)<=t.on&&l({type:`noteOff`,note:t.note,time:t.time});d=n},I),m=typeof OfflineAudioContext<`u`&&t instanceof OfflineAudioContext||!!r.immediateRelease,h=!1;return{ready:u,load:()=>s,play({when:e,freq:n,velocity:r,duration:o}){if(r<=0)return null;let s=69+12*Math.log2(n/440);if(l({type:`noteOn`,note:s,vel:Math.max(.01,Math.min(1,r)),time:e}),m)return l({type:`noteOff`,note:s,time:e+o}),null;f.set(s,e);let c={note:s,on:e,time:e+o};return d.push(c),{hold(e,n,r){let o=Math.max(e,t.currentTime),s=n+r;if(c.time=o+s,h)return;h=!0;let u=Math.min(60,Math.max(i.t60,6*s)),d=u/i.t60,f={...i,t60:u,hfDamp:i.hfDamp/d};window.setTimeout(()=>l({type:`params`,params:f}),Math.max(0,(o-t.currentTime)*1e3)),a.gain.setValueCurveAtTime(A(1),o+Math.max(n,.005),r)}}},dispose(){window.clearInterval(p),l({type:`panic`}),window.setTimeout(()=>{o?.disconnect(),o?.port.close(),a.disconnect()},1e3)}}}}function R(){let e={};for(let t of k)e[`modal: ${t.name}`]=L(t.p);return e[`modal: custom`]=L(null),e}var z=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function B(e,t){let n=w[e];if(!n||n.kind!==`num`)return NaN;let r=Math.max(0,Math.min(1,t));return n.scale===`log`?n.min*(n.max/n.min)**+r:n.scale===`pow2`?n.min+(n.max-n.min)*r*r:n.min+(n.max-n.min)*r}var V=[`bow`,`reed`,`selfosc`,`noise`],H=50,U=.3,W=1.5,G=20;function K(e){return(t,n,r)=>{let i=r.glide,a={...T,...e??N(r.custom)??{},...r.overrides??{},voices:1,...i?{bendRange:Math.max(1,Math.min(24,Math.round(i.range)))}:{}},o=t.createGain();o.gain.value=0;let s=new E(t,n);o.connect(s.input),s.set(a);let c=t.createAnalyser();c.fftSize=2048;let l=new Float32Array(c.fftSize),u=U*U,d=0,f=1,p=null,m=0,h=[],g=e=>p?p.port.postMessage(e):h.push(e),_=M(t).then(()=>{p=new AudioWorkletNode(t,`modal-synth`,{numberOfInputs:0,outputChannelCount:[2]}),p.port.onmessage=e=>{e.data?.type===`snap`&&typeof e.data.cpu==`number`&&(m+=(e.data.cpu-m)*.2)},p.port.postMessage({type:`params`,params:a});for(let e of h.splice(0))p.port.postMessage(e);p.connect(o),p.connect(c)}),v=null,y=0,b=a,x=0,S=``,C=e=>69+12*Math.log2(e/440);return{ready:_,load:()=>m,start(e,t){i&&(y=Math.max(-1,Math.min(1,(C(t)-i.center)/a.bendRange)),g({type:`bend`,value:y})),v=i?i.center:C(t),g({type:`noteOn`,note:v,vel:1,time:e})},stop(e,n){let r=Math.max(t.currentTime,e-n);o.gain.cancelScheduledValues(r),o.gain.setTargetAtTime(0,r,n/4),v!==null&&g({type:`noteOff`,note:v,time:r}),v=null},set(e,{level:t,color:n,freq:r,timbre:s,normalize:m}){let h=performance.now()/1e3,_=d?Math.min(.5,h-d):0;if(d=h,m&&p){c.getFloatTimeDomainData(l);let e=0;for(let t of l)e+=t*t;e/=l.length,e>1e-10&&(u+=(e-u)*(1-Math.exp(-_/W))),f=Math.max(1/G,Math.min(G,U/Math.sqrt(u)))}else f=1;o.gain.setTargetAtTime(t*f,e,.08);let T=C(r);if(i&&v!==null){let e=a.bendRange,t=Math.max(-1,Math.min(1,(T-i.center)/e));Math.abs(t-y)>1e-4&&(y=t,g({type:`bend`,value:t}))}else v!==null&&Math.abs(T-v)>.01&&(g({type:`noteOff`,note:v,time:e}),v=T,g({type:`noteOn`,note:v,vel:1,time:e}));let E=performance.now();if(!s?.length||E-x<H)return;let D={...a},O=[],k=!1;for(let e of s){if(!z.includes(e.target))continue;let t=B(e.target,e.from+(e.to-e.from)*n);if(!Number.isFinite(t))continue;D[e.target]=t,O.push(`${e.target} ${Number(t.toPrecision(3))}`);let r=w[e.target];Math.abs(t-b[e.target])>.002*(r.max-r.min)&&(k=!0)}S=O.join(`, `),k&&(b=D,x=E,g({type:`params`,params:D}))},describe:()=>f===1?S:`${S}${S?`, `:``}gain ${(20*Math.log10(f)).toFixed(1)} dB`,dispose(){g({type:`panic`}),window.setTimeout(()=>{p?.disconnect(),p?.port.close(),o.disconnect()},1e3)}}}}function ee(){let e={};for(let t of k){let n={...T,...t.p};(V.includes(n.exciter)||n.fbGain>0)&&(e[`modal: ${t.name}`]=K(t.p))}return e[`modal: custom`]=K(null),e}function te(e,t){return{play({when:n,freq:r,velocity:i,pan:a,duration:o}){if(i<=0)return null;let s=Math.max(n,e.currentTime),c=s+o,l=.3*i,u=s+.004,d=e.createGain();d.gain.setValueAtTime(0,s),d.gain.linearRampToValueAtTime(l,u),d.gain.exponentialRampToValueAtTime(1e-4,c);let f=e.createStereoPanner();f.pan.value=Math.max(-1,Math.min(1,a)),d.connect(f).connect(t);let p=e.createOscillator();p.frequency.value=r,p.connect(d);let m=e.createOscillator();m.type=`triangle`,m.frequency.value=r*2;let h=e.createGain();h.gain.value=.08+.15*i,m.connect(h).connect(d);for(let e of[p,m])e.start(s),e.stop(c+.05);return m.onended=()=>f.disconnect(),{hold(t,n,r){let i=Math.max(t,u,e.currentTime);if(i>=c)return;let a=l*(1e-4/l)**((i-u)/(c-u)),o=d.gain;typeof o.cancelAndHoldAtTime==`function`?o.cancelAndHoldAtTime(i):o.cancelScheduledValues(i),o.setValueAtTime(a,i),o.setValueCurveAtTime(A(a),i+Math.max(n,.005),r);let s=i+n+r+.05;p.stop(s),m.stop(s)}}},dispose(){}}}function ne(e,t){let n=e.createGain();n.gain.value=0;let r=e.createBiquadFilter();r.type=`lowpass`,r.frequency.value=120,r.Q.value=.7,r.connect(n).connect(t);let i=e.createOscillator(),a=e.createGain();a.gain.value=.5,i.connect(a).connect(n);let o=[-6,6].map(t=>{let n=e.createOscillator();n.type=`sawtooth`,n.detune.value=t;let i=e.createGain();return i.gain.value=.25,n.connect(i).connect(r),n}),s=[i,...o];return{start(e,t){i.frequency.value=t;for(let e of o)e.frequency.value=t*2;for(let t of s)t.start(e)},stop(e,t){n.gain.cancelScheduledValues(e-t),n.gain.setTargetAtTime(0,e-t,t/4);for(let t of s)t.stop(e+.1)},set(e,{level:t,color:a,freq:s}){let c=.08;n.gain.setTargetAtTime(t,e,c),i.frequency.setTargetAtTime(s,e,c);for(let t of o)t.frequency.setTargetAtTime(s*2,e,c);let l=Math.max(0,Math.min(1,a));r.frequency.setTargetAtTime(s*2*2**(6*l),e,c),r.Q.setTargetAtTime(.7+5*l*l,e,c)},dispose(){n.disconnect()}}}var q={"placeholder tone":te,...R()},re={"placeholder hum":ne,...ee()},ie={continuous:null,chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],major:[0,2,4,5,7,9,11],"natural minor":[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],lydian:[0,2,4,6,7,9,11],"pentatonic major":[0,2,4,7,9],"pentatonic minor":[0,3,5,7,10],"whole tone":[0,2,4,6,8,10],"harmonic series":null},ae=Object.keys(ie),oe=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function J(e){return 440*2**((e-69)/12)}function se(e,t,n){if(t===`harmonic series`){let t=J(n+12*Math.floor((24-n)/12)),r=Math.max(1,Math.round(J(e)/t));return 69+12*Math.log2(r*t/440)}let r=ie[t];if(!r)return e;let i=e-n,a=Math.floor(i/12),o=i-12*a,s=r[0],c=1/0;for(let e of[...r,12]){let t=Math.abs(o-e);t<c&&(c=t,s=e)}return n+12*a+s}var ce=class{cfg;y=new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=new Float64Array(4);k2=new Float64Array(4);k3=new Float64Array(4);k4=new Float64Array(4);tmp=new Float64Array(4);constructor(e){this.cfg={...e}}get vTop(){let{m1:e,m2:t,l1:n,l2:r,g:i}=this.cfg;return 2*(e+t)*i*n+2*t*i*r}get p2Scale(){let{m2:e,l2:t}=this.cfg;return Math.sqrt(e*t*t*this.vTop)}derived(e=this.y){let{m1:t,m2:n,l1:r,l2:i,g:a}=this.cfg,[o,s,c,l]=[e[0],e[1],e[2],e[3]],u=o-s,d=Math.cos(u),f=Math.sin(u),p=t+n*f*f,m=(i*c-r*l*d)/(r*r*i*p),h=(r*(t+n)*l-i*n*c*d)/(r*i*i*n*p);return{w1:m,w2:h,T:.5*(c*m+l*h),V:(t+n)*a*r*(1-Math.cos(o))+n*a*i*(1-Math.cos(s))}}energy(e=this.y){let t=this.derived(e);return t.T+t.V}energyNorm(){return this.energy()/this.vTop}deriv(e,t){let{m1:n,m2:r,l1:i,l2:a,g:o}=this.cfg,s=e[0],c=e[1],l=e[2],u=e[3],d=s-c,f=Math.cos(d),p=Math.sin(d),m=n+r*p*p,h=(a*l-i*u*f)/(i*i*a*m),g=(i*(n+r)*u-a*r*l*f)/(i*a*a*r*m),_=l*u*p/(i*a*m),v=(a*a*r*l*l+i*i*(n+r)*u*u-2*i*a*r*l*u*f)*Math.sin(2*d)/(2*i*i*a*a*m*m),y=.5*(l*h+u*g),b=(n+r)*o*i*(1-Math.cos(s))+r*o*a*(1-Math.cos(c)),x=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;x=(this.eTarget-(y+b))/(this.tau*(2*y+e)),x>t?x=t:x<-t&&(x=-t)}x-=this.damping,t[0]=h,t[1]=g,t[2]=-(n+r)*o*i*Math.sin(s)-_+v+x*l,t[3]=-r*o*a*Math.sin(c)+_-v+x*u}step(e){let{y:t,k1:n,k2:r,k3:i,k4:a,tmp:o}=this;this.deriv(t,n);for(let r=0;r<4;r++)o[r]=t[r]+.5*e*n[r];this.deriv(o,r);for(let n=0;n<4;n++)o[n]=t[n]+.5*e*r[n];this.deriv(o,i);for(let n=0;n<4;n++)o[n]=t[n]+e*i[n];this.deriv(o,a);for(let o=0;o<4;o++)t[o]+=e/6*(n[o]+2*r[o]+2*i[o]+a[o]);this.t+=e}randomize(e,t){let{m1:n,m2:r,l1:i,l2:a}=this.cfg,o=Math.max(e,1e-6)*this.vTop,s=Math.min(Math.PI,3*Math.sqrt(o/(r*this.cfg.g*Math.min(i,a)))),c=0,l=0,u=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,u=this.derived([c,l,0,0]).V,!(u<.9*o));e++)c=l=0,u=0;let d=o-u,f=t()*2*Math.PI,p=Math.cos(f),m=Math.sin(f),h=Math.cos(c-l),g=(n+r)*i*i,_=r*i*a*h,v=r*a*a,y=.5*(g*p*p+2*_*p*m+v*m*m),b=Math.sqrt(d/y),x=b*p,S=b*m;this.y[0]=c,this.y[1]=l,this.y[2]=g*x+_*S,this.y[3]=_*x+v*S,this.t=0}};function le(e){return Math.atan2(Math.sin(e),Math.cos(e))}function Y(e,t){let n=e.duration,r=Math.min(e.peakTime,n),i=Math.min(r+e.holdTime,n),a=e.energyStart,o=e.energyPeak;if(t<0)return a;if(t<r){let n=(t/r)**+e.riseCurve;return e.riseShape===`exponential`?a*(o/a)**+n:a+(o-a)*n}return t<i?o:t<n?o*(1-(t-i)/(n-i))**e.fallCurve:0}var ue=class{inst=null;key=``;ensure(e,t,n,r){let i=n.humInstrument,a=i===`modal: custom`?`${i}\n${n.humCustom}`:i;if(this.inst&&this.key===a)return;let o=this.inst;this.key=a;let s=re[i](e,t,{custom:n.humCustom});if(this.inst=s,o&&r){let t=e.currentTime;o.stop(t+.5,.5),window.setTimeout(()=>o.dispose(),1500),(s.ready??Promise.resolve()).then(()=>s===this.inst&&s.start(e.currentTime+.05,J(n.humPitch)))}}get ready(){return this.inst?.ready}start(e,t){this.inst?.start(e.currentTime+.05,J(t.humPitch))}update(e,t,r,i,a){if(!this.inst)return;let o=t.energyPeak,s=Math.max(0,Math.min(1,r/o)),c=Math.min(t.energyStart,.999*o),l=t.humColorMode===`log`?Math.max(0,Math.min(1,Math.log(Math.max(r,1e-12)/c)/Math.log(o/c))):s,u=t.humFadeIn,d=t.humFadeOut,f=Math.min(1,u>0?i/u:1,a!==null&&d>0?(a-i)/d:1),p=t.humFollow;this.inst.set(e.currentTime,{level:n(t.humLevel)*Math.max(0,f)*(1-p+p*s),color:l**+t.humColorCurve,freq:J(t.humPitch),normalize:t.humNormalize,timbre:[1,2].filter(e=>t[`humTarget${e}`]!==`none`).map(e=>({target:t[`humTarget${e}`],from:t[`humFrom${e}`],to:t[`humTo${e}`]}))})}describe(){return this.inst?.describe?.()||`–`}release(e,t){let n=this.inst;n&&(t&&n.stop(e.currentTime+.3,.3),window.setTimeout(()=>n.dispose(),600),this.inst=null,this.key=``)}};function de(e,t,n,r=0){let i=e.thetaRange,a=e.pitchSource===`absolute`?Math.min(1,Math.abs(t)/i):Math.max(0,Math.min(1,.5+.5*t/i));e.invertPitch&&(a=1-a),a**=+e.pitchCurve;let o=e.pitchLow,s=e.pitchHigh,c=oe.indexOf(e.root),l=se(o+(s-o)*a+12*r,e.scale,c),u=Math.min(1,Math.abs(n)/e.p2Ref),d=e.loudFloor;return{midi:l,velocity:d+(1-d)*u**+e.loudCurve,pan:e.panAmount*Math.max(-1,Math.min(1,t/Math.PI))}}function fe(e){let t=window.devicePixelRatio||1,n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);return i.setTransform(t,0,0,t,0,0),i}function pe(e,t,n=`#ccc`){return getComputedStyle(e).getPropertyValue(t).trim()||n}var me=class{thR=Math.PI;pR=1;lastWall=0;canvas;constructor(e){this.canvas=e}begin(e,t,n,r,i){let a=performance.now()/1e3,o=a-this.lastWall;this.lastWall=a;let s=this.canvas,c=fe(s),l=s.clientWidth,u=s.clientHeight;c.clearRect(0,0,l,u);let d=Math.PI,f=e.plotP;if(e.plotZoom===`fit energy`&&t!==null&&n){let e=Math.max(1e-6,t),i=e*r,a=i>=2*n.m2*n.g*n.l2?Math.PI:Math.acos(1-i/(n.m2*n.g*n.l2));d=Math.min(Math.PI,1.08*a),f=1.08*Math.sqrt(2*e)}let p=o>0&&o<.5?1-Math.exp(-o/Math.max(.01,e.zoomSmooth)):1;this.thR*=Math.exp(p*Math.log(d/this.thR)),this.pR*=Math.exp(p*Math.log(f/this.pR));let m=(l/2-8)/this.thR,h=(u/2-8)/this.pR;return c.strokeStyle=i,c.lineWidth=1,c.beginPath(),c.moveTo(8,u/2),c.lineTo(l-8,u/2),c.moveTo(l/2,8),c.lineTo(l/2,u-8),c.stroke(),{g:c,w:l,h:u,sx:e=>l/2+m*e,sy:e=>u/2-h*e}}};function he(e,t,n,r,i,a,o){let{g:s,sx:c,sy:l}=e;s.fillStyle=o,s.globalAlpha=Math.exp(-r/i),s.beginPath(),s.arc(c(t),l(n),a/2,0,2*Math.PI),s.fill(),r<.4&&(s.globalAlpha=1-r/.4,s.strokeStyle=o,s.beginPath(),s.arc(c(t),l(n),a/2+3+12*r,0,2*Math.PI),s.stroke()),s.globalAlpha=1}var ge=100,_e=class{worker=null;portraits=[];resetPending=!1;latestGen=0;ignoreBelow=0;rate=0;newPts=0;rateT=0;now;live;constructor(e,t){this.now=e,this.live=t}reset(){this.dirty=!0,this.portraits=[],this.ignoreBelow=this.latestGen+1,this.resetPending=!0}ensureWorker(){return this.worker||(this.worker=new Worker(new URL(new URL(`orbitWorker-CMBL8zS4.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),this.worker.onmessage=e=>this.receive(e.data)),this.worker}receive({gen:e,energy:t,pts:n,tracks:r}){if(!this.live()||(this.latestGen=Math.max(this.latestGen,e),e<this.ignoreBelow))return;let i=this.portraits[this.portraits.length-1];if(!i||e>i.gen){let n=this.now();for(let e of this.portraits)e.retiredAt??=n;i={gen:e,energy:t,pts:[],tracks:new Map,retiredAt:null},this.portraits.push(i)}else if(e<i.gen)return;for(let e=0;e<n.length;e++)i.pts.push(n[e]);for(let e of r){let t=i.tracks.get(e.id);t||i.tracks.set(e.id,t=[]);for(let n=0;n<e.pts.length;n++)t.push(e.pts[n])}this.newPts+=n.length/2+r.reduce((e,t)=>e+t.pts.length/2,0),this.dirty=!0}post(e,t,n,r,i,a){if(!t.show&&!t.tracks&&!this.worker)return;let o={running:e&&(t.show||t.tracks),reset:this.resetPending,energy:n,m2:r,l2:i,count:t.show?Math.round(t.count):0,life:t.life,band:t.band,minHold:t.minHold,maxPoints:t.show?t.maxPoints:0,cpu:t.cpu,tracks:t.tracks?a:[],trackMax:t.trackMax};this.resetPending=!1,this.ensureWorker().postMessage(o)}layer=null;layerAt=0;layerKey=``;dirty=!0;lm={cx:0,kx:1,cy:0,ky:1};draw(e,t,n,r,i){let{g:a,w:o,h:s,sx:c,sy:l}=e,u=this.portraits.length;this.portraits=this.portraits.filter(e=>e.retiredAt===null||t-e.retiredAt<n.xfade),this.portraits.length!==u&&(this.dirty=!0);let d=this.portraits.some(e=>e.retiredAt!==null),f=window.devicePixelRatio||1,p=[o,s,f,n.show,n.tracks,n.alpha,n.size,n.trackAlpha,n.trackSize,r].join(`|`),m={cx:c(0),kx:c(1)-c(0),cy:l(0),ky:l(1)-l(0)},h=m.kx/this.lm.kx,g=m.ky/this.lm.ky,_=Math.abs(Math.log(h))>.05||Math.abs(Math.log(g))>.05,v=performance.now();this.layer||=document.createElement(`canvas`);let y=this.layer;if((this.dirty||d||_||p!==this.layerKey)&&v-this.layerAt>=ge){let e=Math.round(o*f),a=Math.round(s*f);(y.width!==e||y.height!==a)&&(y.width=e,y.height=a);let u=y.getContext(`2d`);u.setTransform(f,0,0,f,0,0),u.clearRect(0,0,o,s);for(let e of this.portraits){let a=e.retiredAt===null?1:Math.max(0,1-(t-e.retiredAt)/n.xfade);if(n.show&&e.pts.length){let t=n.size;u.fillStyle=r,u.globalAlpha=n.alpha*a,u.beginPath();let i=e.pts;for(let e=0;e<i.length;e+=2)u.rect(c(i[e])-t/2,l(i[e+1])-t/2,t,t);u.fill()}if(n.tracks){let t=n.trackSize;for(let[r,o]of e.tracks){u.fillStyle=i(r),u.globalAlpha=n.trackAlpha*a,u.beginPath();for(let e=0;e<o.length;e+=2)u.rect(c(o[e])-t/2,l(o[e+1])-t/2,t,t);u.fill()}}}u.globalAlpha=1,this.layerAt=v,this.layerKey=p,this.lm=m,this.dirty=!1}if(y.width){let e=m.kx/this.lm.kx,t=m.ky/this.lm.ky;a.save(),a.setTransform(f*e,0,0,f*t,f*(m.cx-e*this.lm.cx),f*(m.cy-t*this.lm.cy)),a.drawImage(y,0,0,o,s),a.restore()}}describe(){let e=performance.now()/1e3;e-this.rateT>1&&(this.rate=this.newPts/(e-this.rateT||1),this.newPts=0,this.rateT=e);let t=this.portraits.find(e=>e.retiredAt===null);if(!t)return`–`;let n=[...t.tracks.values()].reduce((e,t)=>e+t.length/2,0);return`E ${t.energy.toFixed(4)}, ${t.pts.length/2} pts${t.tracks.size?` + ${n} traced`:``}, ${Math.round(this.rate)}/s`}dispose(){this.worker?.terminate(),this.worker=null}},ve=.002,ye=.15,be=25,xe=10,Se=1/960,Ce=64,we=2;function Te(e,t){e.classList.add(`c01`);let r=document.createElement(`canvas`);e.append(r);let i=new me(r),a=new ue,o=null,s=null,c=null,l=``,u=null,d=0,f=null,h,g=!1,_=0,v=0,y=0,b=0,x=0,S=[],C=-1/0,w=[],T=null,E=null,D=new _e(()=>j(),()=>g),O=e=>({show:e.orbits,count:e.orbitCount,cpu:e.orbitCpu,life:e.orbitLife,band:e.orbitBand,minHold:e.orbitMinHold,maxPoints:e.orbitMaxPoints,xfade:e.orbitXfade,alpha:e.orbitAlpha,size:e.orbitSize,tracks:!1,trackMax:0,trackAlpha:0,trackSize:1}),k=e=>{let n=t();D.post(e,O(n),o?o.energyNorm():0,n.massRatio,n.lengthRatio,[])},A={get playing(){return g},start:N,stop:F,draw:K,now:j,length:()=>z(t()),readouts:ee,dispose(){F(),D.dispose(),e.classList.remove(`c01`),e.replaceChildren()}};function j(){return!s||!g?x:s.ctx.currentTime-_}function M(e){return new ce({m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio})}async function N(e,n){F();let r=++d;s=e;let i=t(),l=e.ctx;y=i.seed>0?Math.round(i.seed):m(),o=M(i),o.randomize(Y(i,0),p(y)),o.tau=i.tau,v=0,S=[],C=-1/0,w=[],D.reset(),b=0,T=null,E=null,n>0&&I(n,!1),f=l.createGain(),f.connect(e.input),P(),await Promise.all([c?.ready,a.ready]),r===d&&(_=l.currentTime+.1-n,a.start(l,i),g=!0,B(),h=window.setInterval(B,be))}function P(){if(!s||!f)return;let e=t();u||(u=s.ctx.createGain(),u.connect(f)),u.gain.setTargetAtTime(n(e.notesLevel),s.ctx.currentTime,.05);let r=e.noteInstrument,i=r===`modal: custom`?`${r}\n${e.modalCustom}`:r;c&&l===i||(c?.dispose(),l=i,c=q[r](s.ctx,u,{custom:e.modalCustom})),a.ensure(s.ctx,f,e,g)}function F(){d++,h!==void 0&&window.clearInterval(h),h=void 0;let e=g;if(g&&(x=j(),g=!1,k(!1)),!s)return;let t=s.ctx.currentTime;a.release(s.ctx,e);let n=f;n&&(n.gain.setTargetAtTime(0,t,.05),window.setTimeout(()=>n.disconnect(),600)),c?.dispose(),c=null,l=``,u=null,f=null}function I(e,n){if(!o)return;let r=t();o.cfg.m2=r.massRatio,o.cfg.l2=r.lengthRatio,o.tau=r.tau;let i=r.speed,a=r.duration,s=r.restEnergy,c=o.y,l=le(c[0]),u=c[1],d=c[3],f=v;for(;v<e;){o.eTarget=Y(r,v)*o.vTop,o.step(ve),v+=ve/i;let e=le(c[0]);if(E===null&&l<0&&e>=0&&e-l<Math.PI){let t=-l/(e-l),i={t:f+t*(v-f),th2:le(u+t*(c[1]-u)),p2:(d+t*(c[3]-d))/o.p2Scale};w.push(i),n&&L(i,r)}E===null&&v>=a&&(o.energyNorm()<s||v>=a+xe)&&(E=v,n&&R(r)),l=e,u=c[1],d=c[3],f=v,v-C>=Se&&(S.push({t:v,th1:c[0],th2:c[1]}),C=v)}}function L(e,t){if(!s||!c)return;let n=_+e.t;if(n<s.ctx.currentTime-.02)return;let{midi:r,velocity:i,pan:a}=de(t,e.th2,e.p2),o=J(r),l=c.play({when:n,freq:o,velocity:i,pan:a,duration:t.noteLength});l&&(T={handle:l,when:n}),b++}function R(e){T&&T.handle.hold(T.when,e.finalHold,e.finalFade)}function z(e){let t=e.finalHold+e.finalFade+.3;return(E??e.duration+.5)+t}function B(){if(!s||!o||!g)return;let e=t();P();let n=s.ctx,r=n.currentTime-_,i=z(e);if(E!==null&&r>=i){F(),x=i,A.onEnded?.();return}I(r+ye,!0),k(!0),a.update(n,e,o.energyNorm(),r,E===null?null:i);let c=0;for(;c<S.length-1&&S[c+1].t<=r-.1;)c++;c>0&&S.splice(0,c)}function V(t){return pe(e,t)}function H(e){let t=S.length;if(!t)return o?{th1:o.y[0],th2:o.y[1]}:{th1:0,th2:0};if(e<=S[0].t)return S[0];if(e>=S[t-1].t)return S[t-1];let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;S[t].t<=e?n=t:r=t}let i=S[n],a=S[r],s=(e-i.t)/(a.t-i.t);return{th1:i.th1+s*(a.th1-i.th1),th2:i.th2+s*(a.th2-i.th2)}}let U=0,W=1/60;function G(e,t,n,r,i){let a=r.pendulumAlpha;if(a<=0)return;let o=g?r.motionBlur*W:0,s=r.lengthRatio,c=r.pendulumSize*Math.min(t,n)/2,l=.9*c/(1+s),u=8+c,d=8+c,f=1;if(o>0){let e=0,t=H(i);for(let n=1;n<=8;n++){let r=H(i-o*n/8);e+=l*(+Math.abs(r.th1-t.th1)+s*Math.abs(r.th2-t.th2)),t=r}f=Math.max(2,Math.min(Ce,Math.ceil(e/we)))}let p=a*(f===1?1:1-.03**(1/f)),m=3*Math.cbrt(r.massRatio),h=V(`--fg`);e.strokeStyle=h,e.fillStyle=h,e.lineWidth=1.5,e.lineCap=`round`,e.globalAlpha=p;for(let t=0;t<f;t++){let{th1:n,th2:r}=H(i-o*t/Math.max(1,f-1)),a=u+l*1*Math.sin(n),c=d+l*1*Math.cos(n),p=a+l*s*Math.sin(r),h=c+l*s*Math.cos(r);e.beginPath(),e.moveTo(u,d),e.lineTo(a,c),e.lineTo(p,h),e.stroke(),e.beginPath(),e.arc(a,c,3,0,2*Math.PI),e.moveTo(p+m,h),e.arc(p,h,m,0,2*Math.PI),e.fill()}e.globalAlpha=a,e.beginPath(),e.arc(u,d,1.5,0,2*Math.PI),e.fill(),e.globalAlpha=1}function K(){let e=t(),n=j(),r=performance.now()/1e3,a=r-U;U=r,a>0&&a<.1&&(W+=(a-W)*.1);let s=V(`--fg`),c=V(`--dim`);{let t=i.begin(e,o?o.energyNorm():null,o?.cfg??null,o?.vTop??1,c),{g:r,w:a,h:l}=t;D.draw(t,n,O(e),s,()=>s);let u=e.fade,d=e.pointSize,f=0;for(;f<w.length&&n-w[f].t>4.6*u;)f++;f>0&&w.splice(0,f);for(let e of w){let r=n-e.t;if(r<0)break;he(t,e.th2,e.p2,r,u,d,s)}G(r,a,l,e,n)}}function ee(){let e=t(),n=j();return{time:`${n.toFixed(1)} / ${A.length().toFixed(0)} s`,"energy target":Y(e,n).toFixed(4),energy:o?o.energyNorm().toFixed(4):`–`,notes:String(b),"seed used":y?String(y):`–`,hum:a.describe(),"orbit portrait":D.describe()}}return A}var Ee=[{group:`form`,key:`duration`,label:`duration`,kind:`number`,default:60,min:10,max:600,step:1,unit:`s`,hint:`energy returns to zero at this time`},{group:`form`,key:`peakTime`,label:`peak at`,kind:`number`,default:25,min:1,max:600,step:.5,unit:`s`},{group:`form`,key:`holdTime`,label:`hold`,kind:`number`,default:10,min:0,max:600,step:.5,unit:`s`},{group:`form`,key:`energyStart`,label:`start energy`,kind:`number`,default:.005,min:1e-4,max:1,log:!0},{group:`form`,key:`energyPeak`,label:`peak energy`,kind:`number`,default:1.2,min:.01,max:5,log:!0},{group:`form`,key:`riseShape`,label:`rise shape`,kind:`select`,default:`exponential`,options:[`exponential`,`linear`]},{group:`form`,key:`riseCurve`,label:`rise curve`,kind:`number`,default:1,min:.2,max:5,log:!0,hint:`exponent on the rise; >1 starts slow`},{group:`form`,key:`fallCurve`,label:`fall curve`,kind:`number`,default:1,min:.2,max:5,log:!0,hint:`exponent on the fall; >1 drops fast then lingers`},{group:`form`,key:`restEnergy`,label:`rest energy`,kind:`number`,default:.001,min:1e-5,max:.05,log:!0,hint:`after duration, the pendulum counts as at rest below this energy: no more crossings; the last note rings out`},{group:`form`,key:`finalHold`,label:`final hold`,kind:`number`,default:2,min:0,max:20,step:.1,unit:`s`,hint:`the last note sustains this long…`},{group:`form`,key:`finalFade`,label:`final fade`,kind:`number`,default:5,min:.1,max:30,step:.1,unit:`s`,hint:`…then fades out over this long; the piece ends with it`},{group:`physics`,key:`speed`,label:`speed`,kind:`number`,default:12,min:.5,max:100,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`physics`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.1,max:10,log:!0},{group:`physics`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.1,max:10,log:!0},{group:`physics`,key:`tau`,label:`energy follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how quickly the energy tracks its target`},{group:`physics`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`0 = a new variation every play`},{group:`notes`,key:`noteInstrument`,label:`instrument`,kind:`select`,default:`placeholder tone`,options:Object.keys(q),hint:`modal: … instruments come from the modal-synth project`},{group:`notes`,key:`modalCustom`,label:`modal custom`,kind:`text`,default:``,hint:`for “modal: custom”: paste JSON from modal-synth’s Copy button`},{group:`notes`,key:`scale`,label:`scale`,kind:`select`,default:`pentatonic minor`,options:ae},{group:`notes`,key:`root`,label:`root`,kind:`select`,default:`D`,options:oe},{group:`notes`,key:`pitchSource`,label:`pitch from θ2`,kind:`select`,default:`signed`,options:[`signed`,`absolute`],hint:`signed: −range→low, +range→high. absolute: 0→low, ±range→high`},{group:`notes`,key:`thetaRange`,label:`θ2 range`,kind:`number`,default:3.1416,min:.02,max:3.1416,log:!0,unit:`rad`},{group:`notes`,key:`pitchLow`,label:`low pitch`,kind:`number`,default:50,min:12,max:120,step:.5,unit:`midi`},{group:`notes`,key:`pitchHigh`,label:`high pitch`,kind:`number`,default:86,min:12,max:120,step:.5,unit:`midi`},{group:`notes`,key:`pitchCurve`,label:`pitch curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`notes`,key:`invertPitch`,label:`invert pitch`,kind:`bool`,default:!1},{group:`notes`,key:`p2Ref`,label:`|p2| for full`,kind:`number`,default:1,min:.01,max:4,log:!0,hint:`|p2| that gives full loudness`},{group:`notes`,key:`loudCurve`,label:`loudness curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`notes`,key:`loudFloor`,label:`loudness floor`,kind:`number`,default:.08,min:0,max:1,step:.01,hint:`loudness of a crossing with p2 = 0`},{group:`notes`,key:`notesLevel`,label:`level`,kind:`number`,default:-6,min:-48,max:6,step:.5,unit:`dB`},{group:`notes`,key:`noteLength`,label:`length`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`},{group:`notes`,key:`panAmount`,label:`pan from θ2`,kind:`number`,default:.6,min:0,max:1,step:.01,hint:`placeholder tone only; modal instruments have their own stereo image`},{group:`hum`,key:`humInstrument`,label:`instrument`,kind:`select`,default:`modal: Clarinet-ish`,options:Object.keys(re),hint:`modal: … = one held note of a sustained modal-synth preset`},{group:`hum`,key:`humCustom`,label:`modal custom`,kind:`text`,default:``,hint:`for “modal: custom”: paste JSON from modal-synth’s Copy button`},{group:`hum`,key:`humPitch`,label:`pitch`,kind:`number`,default:38,min:12,max:72,step:.5,unit:`midi`},{group:`hum`,key:`humLevel`,label:`level`,kind:`number`,default:-24,min:-60,max:0,step:.5,unit:`dB`},{group:`hum`,key:`humFollow`,label:`loudness follows energy`,kind:`number`,default:0,min:0,max:1,step:.01,hint:`0 = constant loudness`},{group:`hum`,key:`humNormalize`,label:`normalize loudness`,kind:`bool`,default:!0,hint:`modal hum: measure the output and compensate slowly, so timbre changes don't change loudness`},{group:`hum`,key:`humColorMode`,label:`timbre from energy`,kind:`select`,default:`log`,options:[`log`,`power`],hint:`log: even steps per energy doubling, from start energy (0) to peak (1). power: (energy / peak)^curve`},{group:`hum`,key:`humColorCurve`,label:`timbre curve`,kind:`number`,default:1,min:.1,max:5,log:!0,hint:`exponent applied to the timbre value`},{group:`hum`,key:`humTarget1`,label:`timbre → A`,kind:`select`,default:`pickup`,options:[`none`,...z],hint:`modal hum: synth setting driven by timbre (bow position, force, pressure, feedback, …)`},{group:`hum`,key:`humFrom1`,label:`A at low energy`,kind:`number`,default:.15,min:0,max:1,step:.005,hint:`fraction of the setting's range in modal-synth`},{group:`hum`,key:`humTo1`,label:`A at peak`,kind:`number`,default:.75,min:0,max:1,step:.005},{group:`hum`,key:`humTarget2`,label:`timbre → B`,kind:`select`,default:`tilt`,options:[`none`,...z]},{group:`hum`,key:`humFrom2`,label:`B at low energy`,kind:`number`,default:.3333,min:0,max:1,step:.005},{group:`hum`,key:`humTo2`,label:`B at peak`,kind:`number`,default:.5833,min:0,max:1,step:.005},{group:`hum`,key:`humFadeIn`,label:`fade in`,kind:`number`,default:3,min:0,max:60,step:.5,unit:`s`},{group:`hum`,key:`humFadeOut`,label:`fade out`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`ends together with the last note's fade`},{group:`visual`,key:`pendulumAlpha`,label:`pendulum opacity`,kind:`number`,default:1,min:0,max:1,step:.01,hint:`0 = hide the pendulum`},{group:`visual`,key:`pendulumSize`,label:`pendulum size`,kind:`number`,default:.32,min:.1,max:1,step:.01,hint:`inset diameter, as a fraction of the plot (upper-left corner)`},{group:`visual`,key:`motionBlur`,label:`motion blur`,kind:`number`,default:1,min:0,max:4,step:.05,hint:`pendulum shutter, in display frames; 0 = off`},{group:`visual`,key:`fade`,label:`point fade`,kind:`number`,default:10,min:.2,max:120,log:!0,unit:`s`},{group:`visual`,key:`plotZoom`,label:`plot zoom`,kind:`select`,default:`fit energy`,options:[`fit energy`,`fixed`],hint:`fit energy: frame the region the pendulum can reach at its current energy`},{group:`visual`,key:`zoomSmooth`,label:`zoom smoothing`,kind:`number`,default:1.5,min:.05,max:20,log:!0,unit:`s`,hint:`time constant of zoom changes`},{group:`visual`,key:`plotP`,label:`fixed p2 range`,kind:`number`,default:1.5,min:.05,max:5,log:!0},{group:`visual`,key:`pointSize`,label:`point size`,kind:`number`,default:2,min:.5,max:8,step:.1,unit:`px`},{group:`orbits`,key:`orbits`,label:`show orbits`,kind:`bool`,default:!0},{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:24,min:1,max:64,step:1,hint:`trajectories integrated in parallel, all at the portrait's energy`},{group:`orbits`,key:`orbitCpu`,label:`cpu`,kind:`number`,default:.4,min:.02,max:.9,step:.01,hint:`fraction of one core the background computation may use`},{group:`orbits`,key:`orbitLife`,label:`life`,kind:`number`,default:300,min:10,max:5e3,log:!0,hint:`crossings before an orbit is reseeded elsewhere on the section`},{group:`orbits`,key:`orbitBand`,label:`refresh at`,kind:`number`,default:.25,min:.01,max:2,log:!0,hint:`start a new portrait when the energy has changed by this fraction`},{group:`orbits`,key:`orbitMinHold`,label:`min hold`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`s`,hint:`a portrait is kept at least this long`},{group:`orbits`,key:`orbitMaxPoints`,label:`max points`,kind:`number`,default:8e3,min:500,max:4e4,log:!0,hint:`a portrait stops computing (and using CPU) once it has this many points`},{group:`orbits`,key:`orbitXfade`,label:`crossfade`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`,hint:`time for the old portrait to fade out once a new one starts`},{group:`orbits`,key:`orbitAlpha`,label:`brightness`,kind:`number`,default:.3,min:.02,max:1,step:.01},{group:`orbits`,key:`orbitSize`,label:`point size`,kind:`number`,default:1,min:.5,max:4,step:.1,unit:`px`}],De={id:`01-poincare`,title:`poincaré`,schema:Ee,defaults:f,create:Te},Oe={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:40,massRatio:1,lengthRatio:1,tau:2,seed:0,streamAudio:!0,deviceLimit:!0,orbitCount:8,colors:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,slot1Instrument:`modal: Nylon harp`,slot1Octave:0,slot2Instrument:`modal: Marimba`,slot2Octave:-1,slot3Instrument:`modal: Vibraphone`,slot3Octave:0,slot4Instrument:`modal: Church bell`,slot4Octave:-1,slot5Instrument:`modal: Steel-string pluck`,slot5Octave:0,slot6Instrument:`modal: Glass harmonics`,slot6Octave:1,modalCustom:``,reverbTime:3.5,scale:`dorian`,root:`D`,pitchSource:`signed`,thetaRange:3.1416,pitchLow:50,pitchHigh:86,pitchCurve:1,invertPitch:!1,p2Ref:1,loudCurve:1,loudFloor:.08,notesLevel:-6,noteLength:1.5,panAmount:.6,humInstrument:`modal: Clarinet-ish`,humCustom:``,humPitch:38,humLevel:-24,humFollow:0,humNormalize:!0,humColorMode:`log`,humColorCurve:1,humTarget1:`pickup`,humFrom1:.15,humTo1:.75,humTarget2:`tilt`,humFrom2:.3333,humTo2:.5833,humFadeIn:3,humFadeOut:6,fade:20,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2.5,portrait:!0,portraitCount:24,portraitCpu:.4,portraitLife:300,portraitBand:.25,portraitMinHold:3,portraitMaxPoints:8e3,portraitXfade:1.5,portraitAlpha:.15,portraitSize:1,traces:!0,traceMax:1500,traceAlpha:.75,traceSize:1.5},ke=.35,Ae=.6,je=.2,Me=1.3,Ne=.5,Pe=2;function Fe(e,t,n,r){let i={v:5,stream:r,sr:t,speed:e.speed,len:e.noteLength,inst:Array.from({length:n},(t,n)=>e[`slot${n+1}Instrument`]),custom:e.modalCustom};return`double-pendulum:capacity:02-orbits:${JSON.stringify(i)}`}function Ie(e){try{let t=localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Le(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}var Re=e=>new Promise(t=>setTimeout(t,e));async function ze(e,t,n,r){let i=e.createGain();i.gain.value=0,i.connect(e.destination);let a=Array(r).fill(0);for(let e=0;e<n;e++)a[e%r]++;let o=t.speed*je,s=t.noteLength,c=[];for(let n=0;n<r;n++){if(!a[n])continue;let r=q[t[`slot${n+1}Instrument`]](e,i,{custom:t.modalCustom,immediateRelease:!0,effects:`none`});c.push({inst:r,rate:o*a[n]})}try{await Promise.all(c.map(e=>e.inst.ready));let t=12345,n=()=>(t=t*16807%0x7fffffff)/0x7fffffff,r=e.currentTime+.05;for(let{inst:e,rate:t}of c){let i=t=>e.play({when:t,freq:J(50+Math.floor(n()*36)),velocity:.6,pan:0,duration:s}),a=Math.min(16,Math.round(t*s));for(let e=0;e<a;e++)i(r+.002*e);for(let e=.05;e<Me;e+=1/t)i(r+e)}await Re(Ne*1e3);let i=[],a=performance.now()+800;for(;performance.now()<a;)await Re(100),i.push(c.reduce((e,t)=>e+(t.inst.load?.()??0),0));return i.length?i.reduce((e,t)=>e+t,0)/i.length:0}finally{for(let e of c)e.inst.dispose();window.setTimeout(()=>i.disconnect(),1200)}}function Be(e,t){let n=e[`slot${t+1}Instrument`];if(!n.startsWith(`modal: `))return null;let r=n===`modal: custom`?N(e.modalCustom):k.find(e=>`modal: ${e.name}`===n)?.p;return{...T,...r??{}}}async function Ve(e,t,n,r){let i=Array(r).fill(0);for(let e=0;e<n;e++)i[e%r]++;let a=t.speed*je,o=t.noteLength,s=1.5,c=[];for(let n=0;n<r;n++){let r=i[n]?Be(t,n):null;if(!r)continue;let l=a*i[n],u=12345+n,d=()=>(u=u*16807%0x7fffffff)/0x7fffffff,f=[],p=Math.min(16,Math.round(l*o));for(let e=0;e<p;e++)f.push({time:.002*e,note:50+Math.floor(d()*36),vel:.6,len:o});for(let e=.05;e<s;e+=1/l)f.push({time:e,note:50+Math.floor(d()*36),vel:.6,len:o});c.push(new Promise(t=>{let n=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`});n.onmessage=e=>{e.data.type===`bench`&&(t(e.data.load),n.terminate())};let i={type:`bench`,sampleRate:e,params:r,notes:f,seconds:s,warmup:.5};n.postMessage(i)}))}let l=await Promise.all(c);return l.length?Math.max(...l):0}async function He(e,t,n,r,i=!1){let a=Fe(t,e.sampleRate,r,i),o=i?Ae:ke,s=n=>i?Ve(e.sampleRate,t,n,r):ze(e,t,n,r),c=Ie(a);if(c&&(c.cap<c.tested||c.tested>=n))return{...c,cap:Math.min(c.cap,n)};let l=n,u=await s(l),d=l;for(let e=1;u>o&&l>1&&e<Pe;e++)l=Math.max(1,Math.min(l-1,Math.floor(l*(o/u)**1.3))),u=await s(l),d=l;u>o&&(l=Math.max(1,Math.min(l-1,Math.floor(l*(o/u)**1.3))));let f={cap:l,tested:n,load:u,at:d};return Le(a,f),f}var X=(e,t={})=>{let n=Ee.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Ue=[[`modal: Nylon harp`,0],[`modal: Marimba`,-1],[`modal: Vibraphone`,0],[`modal: Church bell`,-1],[`modal: Steel-string pluck`,0],[`modal: Glass harmonics`,1]],We=[...[`duration`,`peakTime`,`holdTime`,`energyStart`].map(e=>X(e)),X(`energyPeak`,{default:.4}),...[`riseShape`,`riseCurve`,`fallCurve`,`restEnergy`,`finalHold`,`finalFade`].map(e=>X(e)),X(`speed`,{default:40}),...[`massRatio`,`lengthRatio`,`tau`,`seed`].map(e=>X(e)),{group:`orbits`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render each instrument in its own background thread, ~1 s ahead of playback (uses more cores, no glitches from momentary slowdowns); applies on the next play`},{group:`orbits`,key:`deviceLimit`,label:`limit to device`,kind:`bool`,default:!0,hint:`measure (once per device) how many orbits this device can play live, and play no more than that`},{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:8,min:1,max:20,step:1,hint:`pendulums, all following the same energy; each starts at a random place`},{group:`orbits`,key:`colors`,label:`colors`,kind:`text`,default:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,hint:`comma-separated CSS colors; orbit n uses color n (cycling)`},...Array.from({length:6},(e,t)=>[{group:`orbits`,key:`slot${t+1}Instrument`,label:`instrument ${t+1}`,kind:`select`,default:Ue[t][0],options:Object.keys(q),hint:`orbits ${t+1}, ${t+1+6}, ${t+1+12}, … play this instrument`},{group:`orbits`,key:`slot${t+1}Octave`,label:`octave ${t+1}`,kind:`number`,default:Ue[t][1],min:-3,max:3,step:1,hint:`register shift for this instrument`}]).flat(),X(`modalCustom`,{group:`orbits`,hint:`for “modal: custom” in any slot: paste JSON from modal-synth’s Copy button`}),{group:`orbits`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`,hint:`one reverb shared by all the orbit instruments (each sends its preset's reverb amount); applies on the next play`},X(`scale`,{default:`dorian`}),...[`root`,`pitchSource`,`thetaRange`,`pitchLow`,`pitchHigh`,`pitchCurve`,`invertPitch`,`p2Ref`,`loudCurve`,`loudFloor`,`notesLevel`,`noteLength`,`panAmount`].map(e=>X(e)),...Ee.filter(e=>e.group===`hum`),X(`fade`,{default:20,hint:`how long each live crossing dot stays visible`}),...[`plotZoom`,`zoomSmooth`,`plotP`].map(e=>X(e)),X(`pointSize`,{default:2.5}),X(`orbits`,{key:`portrait`,group:`portrait`,label:`show portrait`,hint:`grey background: the section's structure at the current energy`}),X(`orbitCount`,{key:`portraitCount`,group:`portrait`}),X(`orbitCpu`,{key:`portraitCpu`,group:`portrait`}),X(`orbitLife`,{key:`portraitLife`,group:`portrait`}),X(`orbitBand`,{key:`portraitBand`,group:`portrait`}),X(`orbitMinHold`,{key:`portraitMinHold`,group:`portrait`}),X(`orbitMaxPoints`,{key:`portraitMaxPoints`,group:`portrait`}),X(`orbitXfade`,{key:`portraitXfade`,group:`portrait`}),X(`orbitAlpha`,{key:`portraitAlpha`,group:`portrait`,default:.15}),X(`orbitSize`,{key:`portraitSize`,group:`portrait`}),{group:`portrait`,key:`traces`,label:`trace orbits`,kind:`bool`,default:!0,hint:`with each portrait, follow every pendulum from its current state (energy frozen) and draw the orbit it's on, in its color`},{group:`portrait`,key:`traceMax`,label:`trace length`,kind:`number`,default:1500,min:50,max:1e4,log:!0,hint:`crossings computed per orbit trace`},{group:`portrait`,key:`traceAlpha`,label:`trace brightness`,kind:`number`,default:.75,min:.02,max:1,step:.01},{group:`portrait`,key:`traceSize`,label:`trace point size`,kind:`number`,default:1.5,min:.5,max:4,step:.1,unit:`px`}],Ge=class{input;conv;constructor(e,t,n){this.input=e.createGain(),this.conv=e.createConvolver(),this.conv.buffer=Ke(e,n),this.input.connect(this.conv).connect(t)}dispose(){let e=this.input,t=this.conv;window.setTimeout(()=>{e.disconnect(),t.disconnect()},1500)}};function Ke(e,t){let n=e.sampleRate,r=Math.round(n*Math.min(t*1.1,12)),i=e.createBuffer(2,r,n);for(let e=0;e<2;e++){let a=i.getChannelData(e),o=0;for(let e=0;e<r;e++){let r=e/n,i=9e3*Math.exp(-r/(.6*t))+400,s=1-Math.exp(-2*Math.PI*i/n);o+=s*(Math.random()*2-1-o),a[e]=o*Math.exp(-6.9*r/t)*Math.min(1,r/.004)*.5}}return i}var qe=new URL(`player-BCgNbE7X.js`,import.meta.url).href,Je=1.5,Ye=1.3,Xe=50,Ze=new WeakMap;function Qe(e){let t=Ze.get(e);return t||(t=e.audioWorklet.addModule(qe),Ze.set(e,t)),t}function $e(e){return(t,n,r)=>{let i={...T,...e??N(r.custom)??{},...r.overrides??{}},a=t.createGain();P(t,a,n,i,r);let o=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),s=(e,t=[])=>o.postMessage(e,t),c=0,l=0,u=null,d=(async()=>{await Qe(t),u=new AudioWorkletNode(t,`pcm-player`,{numberOfInputs:0,outputChannelCount:[2]}),u.connect(a);let e=new MessageChannel;u.port.postMessage({type:`port`,port:e.port2},[e.port2]);let n=new Promise(e=>{o.onmessage=t=>{t.data.type===`ready`?e():t.data.type===`load`&&(c=t.data.load,l=t.data.underruns)}});s({type:`init`,sampleRate:t.sampleRate,params:i,port:e.port1,startFrame:Math.round((t.currentTime+.05)*t.sampleRate),aheadFrames:Math.round(+t.sampleRate)},[e.port1]),await n})(),f=e=>s({type:`synth`,msg:e}),p=[],m=new Map,h=window.setInterval(()=>{let e=t.currentTime+Ye,n=[];for(let t of p)t.time>e?n.push(t):(m.get(t.note)??-1/0)<=t.on&&f({type:`noteOff`,note:t.note,time:t.time});p=n},Xe),g=!1;return{ready:d,load:()=>c,underruns:()=>l,horizon:e=>s({type:`horizon`,time:e}),play({when:e,freq:n,velocity:o,duration:c}){if(o<=0)return null;let l=69+12*Math.log2(n/440);if(f({type:`noteOn`,note:l,vel:Math.max(.01,Math.min(1,o)),time:e}),r.immediateRelease)return f({type:`noteOff`,note:l,time:e+c}),null;m.set(l,e);let u={note:l,on:e,time:e+c};return p.push(u),{hold(e,n,r){let o=Math.max(e,t.currentTime);if(u.time=o+n+r,g)return;g=!0;let c=n+r,l=Math.min(60,Math.max(i.t60,6*c)),d=l/i.t60;s({type:`timedParams`,time:o,params:{...i,t60:l,hfDamp:i.hfDamp/d}}),a.gain.setValueCurveAtTime(A(1),o+Math.max(n,.005),r)}}},dispose(){window.clearInterval(h),s({type:`stop`}),window.setTimeout(()=>{o.terminate(),u?.disconnect(),a.disconnect()},1e3)}}}}function et(){let e={};for(let t of k)e[`modal: ${t.name}`]=$e(t.p);return e[`modal: custom`]=$e(null),e}var tt=et(),nt=.4,rt=.003,it=.15,at=25,ot=10;function st(e,t){e.classList.add(`c02`);let r=document.createElement(`canvas`);e.append(r);let i=new me(r),a=new ue,o=new _e(()=>j(),()=>v),s=e=>({show:e.portrait,count:e.portraitCount,cpu:e.portraitCpu,life:e.portraitLife,band:e.portraitBand,minHold:e.portraitMinHold,maxPoints:e.portraitMaxPoints,xfade:e.portraitXfade,alpha:e.portraitAlpha,size:e.portraitSize,tracks:e.traces,trackMax:e.traceMax,trackAlpha:e.traceAlpha,trackSize:e.traceSize}),c=e=>{let n=t(),r=l.filter(e=>e.restAt===null).map(e=>({id:e.index,y:Array.from(e.pend.y)}));o.post(e,s(n),G(),n.massRatio,n.lengthRatio,r)},l=[],u=null,d=null,f=null,h=new Map,g=null,_,v=!1,y=0,b=0,x=0,S=0,C=0,w=0,T=null,E=!1,D=it,O=null,k=!1,A={get playing(){return v},start:B,stop:V,draw:te,now:j,length:()=>W(t()),readouts:re,notice:ne,dispose(){V(),o.dispose(),e.classList.remove(`c02`),e.replaceChildren()}};function j(){return!u||!v?w:u.ctx.currentTime-b}function M(e,t,n){let r=new ce({m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio});return r.randomize(n,p(S*1009+t*7919+1)),r.tau=e.tau,{index:t,pend:r,prev:le(r.y[0]),prevTh2:r.y[1],prevP2:r.y[3],points:[],lastNote:null,restAt:null}}function N(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function P(e){let t=N(e);return e.deviceLimit&&O?Math.min(t,O.cap):t}function F(e){let t=P(e);if(T===null){for(;l.length<t;)l.push(M(e,l.length,Math.max(1e-4,Y(e,x))));l.length>t&&(l.length=t)}}function I(e){return e.index%6}function L(e,t){let n=e[`slot${t+1}Instrument`];return{name:n,key:n===`modal: custom`?`${n}\n${e.modalCustom}`:n}}function R(e){return E&&tt[e]||q[e]}function z(){if(!u||!d)return;let e=t();f||(f=u.ctx.createGain(),f.connect(d),g=new Ge(u.ctx,f,e.reverbTime)),f.gain.setTargetAtTime(n(e.notesLevel),u.ctx.currentTime,.05);let r=new Map;for(let t of l){let{name:n,key:i}=L(e,I(t));r.set(i,n)}for(let[e,t]of h)r.has(e)||(t.dispose(),h.delete(e));for(let[t,n]of r)h.has(t)||h.set(t,R(n)(u.ctx,f,{custom:e.modalCustom,effects:{send:g.input}}));a.ensure(u.ctx,d,e,v)}async function B(e,n){V();let r=++y;u=e;let i=t(),s=e.ctx;if(E=!!i.streamAudio,D=E?Je:it,i.deviceLimit){k=!0;try{O=await He(s,i,N(i),6,E)}finally{k=!1}if(r!==y)return}S=i.seed>0?Math.round(i.seed):m(),x=0,T=null,C=0,l=[],o.reset(),F(i),n>0&&H(n,!1),d=s.createGain(),d.connect(e.input),z(),await Promise.all([...[...h.values()].map(e=>e.ready),a.ready]),r===y&&(b=s.currentTime+.1+(E?nt:0)-n,a.start(s,i),v=!0,K(),_=window.setInterval(K,at))}function V(){y++,_!==void 0&&window.clearInterval(_),_=void 0;let e=v;if(v&&(w=j(),v=!1,c(!1)),!u)return;let t=u.ctx.currentTime;a.release(u.ctx,e);let n=d;n&&(n.gain.setTargetAtTime(0,t,.05),window.setTimeout(()=>n.disconnect(),600));for(let e of h.values())e.dispose();h=new Map,g?.dispose(),g=null,f=null,d=null}function H(e,n){let r=t(),i=r.speed,a=r.duration,o=r.restEnergy;for(let e of l)e.pend.cfg.m2=r.massRatio,e.pend.cfg.l2=r.lengthRatio,e.pend.tau=r.tau;for(;x<e;){let e=Y(r,x),t=x;x+=rt/i;for(let i of l){let s=i.pend,c=s.y;s.eTarget=e*s.vTop,s.step(rt);let l=le(c[0]);if(i.restAt===null&&i.prev<0&&l>=0&&l-i.prev<Math.PI){let e=-i.prev/(l-i.prev),a={t:t+e*(x-t),th2:le(i.prevTh2+e*(c[1]-i.prevTh2)),p2:(i.prevP2+e*(c[3]-i.prevP2))/s.p2Scale};i.points.push(a),n&&U(i,a,r)}i.restAt===null&&x>=a&&(s.energyNorm()<o||x>=a+ot)&&(i.restAt=x,n&&i.lastNote&&i.lastNote.handle.hold(i.lastNote.when,r.finalHold,r.finalFade)),i.prev=l,i.prevTh2=c[1],i.prevP2=c[3]}T===null&&l.length&&l.every(e=>e.restAt!==null)&&(T=x)}}function U(e,t,n){if(!u)return;let r=b+t.t;if(r<u.ctx.currentTime-.02)return;let i=I(e),a=h.get(L(n,i).key);if(!a)return;let{midi:o,velocity:s,pan:c}=de(n,t.th2,t.p2,n[`slot${i+1}Octave`]),l=a.play({when:r,freq:J(o),velocity:s,pan:c,duration:n.noteLength});l&&(e.lastNote={handle:l,when:r}),C++}function W(e){let t=e.finalHold+e.finalFade+.3;return(T??e.duration+.5)+t}function G(){return l.length?l.reduce((e,t)=>e+t.pend.energyNorm(),0)/l.length:0}function K(){if(!u||!v)return;let e=t();F(e),z();let n=u.ctx,r=n.currentTime-b,i=W(e);if(T!==null&&r>=i)V(),w=i,A.onEnded?.();else{H(r+D,!0);for(let e of h.values())e.horizon?.(b+x);c(!0),a.update(n,e,G(),r,T===null?null:i)}}function ee(t){let n=String(t.colors).split(`,`).map(e=>e.trim()).filter(Boolean);return n.length?n:[pe(e,`--fg`)]}function te(){let n=t(),r=j(),a=l[0]?.pend??null,c=l.length?Math.max(...l.map(e=>e.pend.energyNorm())):null,u=i.begin(n,c,a?.cfg??null,a?.vTop??1,pe(e,`--dim`)),d=n.fade,f=n.pointSize,p=ee(n);o.draw(u,r,s(n),pe(e,`--fg`),e=>p[e%p.length]);for(let e of l){let t=0;for(;t<e.points.length&&r-e.points[t].t>4.6*d;)t++;t>0&&e.points.splice(0,t);let n=p[e.index%p.length];for(let t of e.points){let e=r-t.t;if(e<0)break;he(u,t.th2,t.p2,e,d,f,n)}}}function ne(){if(k)return`checking what this device can play…`;let e=t(),n=N(e),r=P(e);return r<n?`${r} of ${n} orbits: reduced to what this device can play live`:null}function re(){let e=t(),n=j();return{time:`${n.toFixed(1)} / ${A.length().toFixed(0)} s`,"energy target":Y(e,n).toFixed(4),"energy (mean)":l.length?G().toFixed(4):`–`,notes:String(C),"at rest":`${l.filter(e=>e.restAt!==null).length} / ${l.length}`,"device limit":O?`${O.cap} orbits (synth load ${(100*O.load).toFixed(0)}% with ${O.at})`:`–`,instruments:String(h.size),"audio load":E?`renderers ${Math.round(100*Math.max(0,...[...h.values()].map(e=>e.load?.()??0)))}% (busiest), ${[...h.values()].reduce((e,t)=>e+(t.underruns?.()??0),0)} underruns; hum ${Math.round(100*(a.inst?.load?.()??0))}%`:`${Math.round(100*([...h.values()].reduce((e,t)=>e+(t.load?.()??0),0)+(a.inst?.load?.()??0)))}%`,"seed used":S?String(S):`–`,hum:a.describe(),portrait:o.describe()}}return A}var ct={id:`02-orbits`,title:`orbits`,schema:We,defaults:Oe,create:st},lt={freeTime:40,dampTime:20,dampCurve:1.5,tau:2,restEnergy:.001,finalHold:2,finalFade:5,count:12,releaseAngle:120,jitter:3,separateAt:8,sepThreshold:.02,speed:2.5,massRatio:1,lengthRatio:1,seed:0,instrument:`modal: Vibraphone`,modalCustom:``,pitchMode:`chord`,directionChords:!0,scale:`dorian`,root:`D`,pitchLow:50,pitchHigh:86,loudRef:.6,loudCurve:1,loudFloor:.08,notesLevel:-8,noteLength:2,directionPan:.35,reverbTime:3.5,streamAudio:!0,trails:!0,trailLength:3,trailWidth:1.2,armAlpha:.75,bobSize:3,saturation:35},ut=.002;function dt(e,t,n,r){let i=new ce(e);return i.controlled=!1,i.y[0]=t,i.y[1]=n+r,i.y[2]=0,i.y[3]=0,i}function ft(e,t){return[e.l1*Math.sin(t[0])+e.l2*Math.sin(t[1]),e.l1*Math.cos(t[0])+e.l2*Math.cos(t[1])]}function pt(e,t,n,r,i,a){let o=dt(e,t,n,-r/2),s=dt(e,t,n,r/2);for(let t=0;t<a;t+=ut){o.step(ut),s.step(ut);let[n,r]=ft(e,o.y),[a,c]=ft(e,s.y);if(Math.hypot(n-a,r-c)>i)return t+ut}return 1/0}function mt(e,t,n,r,i){let a=3*r+10,o=1e-15,s=.01;if(pt(e,t,n,o,i,a)<=r)return{offset:o,separatesAt:pt(e,t,n,o,i,a)};if(pt(e,t,n,s,i,a)>=r)return{offset:s,separatesAt:pt(e,t,n,s,i,a)};for(let c=0;c<16;c++){let c=Math.sqrt(o*s);pt(e,t,n,c,i,a)>r?o=c:s=c}let c=Math.sqrt(o*s);return{offset:c,separatesAt:pt(e,t,n,c,i,a)}}var ht=et(),gt=.15,_t=.4,vt=25,yt=10,bt=1/120;function xt(e,t){e.classList.add(`c03`);let r=document.createElement(`canvas`);e.append(r);let i=[],a={m1:1,l1:1,g:1,m2:1,l2:1},o=[],s=-1/0,c=null,l=null,u=null,d=null,f=null,h=null,g=null,_=null,v=``,y,b=!1,x=0,S=0,C=0,w=0,T=0,E=0,D=null,O=!1,k=gt,A=1,j={th1:0,th2:0,offset:0,separatesAt:0},M={get playing(){return b},start:L,stop:R,draw:ee,now:N,length:()=>U(t()),readouts:te,dispose(){R(),e.classList.remove(`c03`),e.replaceChildren()}};function N(){return!c||!b?E:c.ctx.currentTime-S}function P(e,t){a={m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio};let n=Math.PI/180,r=e.releaseAngle*n,c=e.jitter*n,l=t(),u=l===null?r:r+(2*l-1)*c,d=t(),f=d===null?r:r+(2*d-1)*c,p=e.speed,m=mt(a,u,f,e.separateAt*p,e.sepThreshold*(a.l1+a.l2));j={th1:u,th2:f,offset:m.offset,separatesAt:m.separatesAt/p};let h=Math.max(1,Math.round(e.count));i=[];for(let e=0;e<h;e++){let t=h>1?(e/(h-1)-.5)*m.offset:0,n=dt(a,u,f,t);i.push({index:e,p:n,prevX:ft(a,n.y)[0],E0:0,lastNote:null,restAt:null})}A=Math.sqrt(2*i[0].p.energy()/a.m2),o=[],s=-1/0,z(0)}function F(e){return O&&ht[e]||q[e]}function I(){if(!c||!l)return;let e=t(),r=c.ctx;u||(u=r.createGain(),u.connect(l),d=new Ge(r,u,e.reverbTime),f=r.createStereoPanner(),h=r.createStereoPanner(),f.connect(u),h.connect(u)),u.gain.setTargetAtTime(n(e.notesLevel),r.currentTime,.05);let i=e.directionPan;f.pan.setTargetAtTime(-i,r.currentTime,.05),h.pan.setTargetAtTime(i,r.currentTime,.05);let a=e.instrument,o=a===`modal: custom`?`${a}\n${e.modalCustom}`:a;if(g&&v===o)return;g?.dispose(),_?.dispose(),v=o;let s={custom:e.modalCustom,effects:{send:d.input}};g=F(a)(r,f,s),_=F(a)(r,h,s)}async function L(e,n){R();let r=++x;c=e;let i=t(),a=e.ctx;w=i.seed>0?Math.round(i.seed):m();let o=p(w);P(i,()=>o()),C=0,D=null,T=0,O=!!i.streamAudio,k=O?Je:gt,n>0&&B(n,!1),l=a.createGain(),l.connect(e.input),I(),await Promise.all([g?.ready,_?.ready]),r===x&&(S=a.currentTime+.1+(O?_t:0)-n,b=!0,W(),y=window.setInterval(W,vt))}function R(){if(x++,y!==void 0&&window.clearInterval(y),y=void 0,b&&=(E=N(),!1),!c)return;let e=c.ctx.currentTime,t=l;t&&(t.gain.setTargetAtTime(0,e,.05),window.setTimeout(()=>t.disconnect(),600)),g?.dispose(),_?.dispose(),g=_=null,v=``,d?.dispose(),d=null,u=f=h=null,l=null}function z(e){let t=new Float64Array(2*i.length);for(let e=0;e<i.length;e++)t[2*e]=i[e].p.y[0],t[2*e+1]=i[e].p.y[1];o.push({t:e,s:t}),s=e}function B(e,n){let r=t(),o=r.speed,c=r.freeTime,l=r.dampTime,u=r.dampCurve,d=r.tau,f=r.restEnergy;for(;C<e;){let e=C;C+=ut/o;let t=(e-c)/l;for(let o of i){let i=o.p;t>=0&&(i.controlled||(i.controlled=!0,o.E0=i.energy()),i.tau=d,i.eTarget=t<1?o.E0*(1-t)**u:0,i.damping=t>=1?1/d:0),i.step(ut);let s=ft(a,i.y)[0];if(o.restAt===null&&(o.prevX<0&&s>=0||o.prevX>0&&s<=0)){let t=e+o.prevX/(o.prevX-s)*(C-e);n&&H(o,t,s>o.prevX?1:-1,r)}o.prevX=s,o.restAt===null&&t>=1&&(i.energyNorm()<f||C>=c+l+yt)&&(o.restAt=C,n&&o.lastNote&&o.lastNote.handle.hold(o.lastNote.when,r.finalHold,r.finalFade))}D===null&&i.every(e=>e.restAt!==null)&&(D=C),C-s>=bt&&z(C)}}function V(e,t){let n=e.pitchLow,r=e.pitchHigh,i=oe.indexOf(e.root),a=!!e.directionChords,o=a?2*t:t,s=[];if(e.scale===`continuous`)s=Array.from({length:Math.max(o,2)},(e,t)=>n+(r-n)*t/Math.max(1,Math.max(o,2)-1));else for(let t=Math.ceil(n);t<=r;t++)Math.abs(se(t,e.scale,i)-t)<1e-6&&s.push(t);s.length||(s=[se((n+r)/2,e.scale,i)]);let c=Array.from({length:o},(e,t)=>s[o>1?Math.round(t*(s.length-1)/(o-1)):Math.floor(s.length/2)]);return a?{right:c.filter((e,t)=>t%2==0),left:c.filter((e,t)=>t%2==1)}:{right:c,left:c}}function H(e,t,n,r){if(!c)return;let o=S+t;if(o<c.ctx.currentTime-.02)return;let s=n>0?_:g;if(!s)return;let l=e.p.y,u=e.p.derived(),d=a.l1*Math.cos(l[0])*u.w1+a.l2*Math.cos(l[1])*u.w2,f=a.l1*Math.sin(l[0])*u.w1+a.l2*Math.sin(l[1])*u.w2,p=Math.min(1,Math.hypot(d,f)/(r.loudRef*A)),m=r.loudFloor,h=m+(1-m)*p**+r.loudCurve,v=r.pitchMode===`motion`?se(r.pitchLow+(r.pitchHigh-r.pitchLow)*p,r.scale,oe.indexOf(r.root)):V(r,i.length)[n>0?`right`:`left`][e.index],y=s.play({when:o,freq:J(v),velocity:h,pan:0,duration:r.noteLength});y&&(e.lastNote={handle:y,when:o}),T++}function U(e){let t=e.finalHold+e.finalFade+.3;return(D??e.freeTime+e.dampTime+1)+t}function W(){if(!c||!b)return;let e=t();I();let n=c.ctx.currentTime-S,r=U(e);if(D!==null&&n>=r){R(),E=r,M.onEnded?.();return}B(n+k,!0);for(let e of[g,_])e?.horizon?.(S+C);let i=n-e.trailLength-.5,a=0;for(;a<o.length-2&&o[a+1].t<i;)a++;a>0&&o.splice(0,a)}function G(e,t,n){return`hsl(${((30+360*t/Math.max(1,n))%360).toFixed(0)} ${e.saturation}% 70%)`}function K(e){let t=o.length;if(!t)return null;if(e<=o[0].t)return o[0].s;if(e>=o[t-1].t)return o[t-1].s;let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;o[t].t<=e?n=t:r=t}let i=o[n],a=o[r],s=(e-i.t)/(a.t-i.t),c=new Float64Array(i.s.length);for(let e=0;e<c.length;e++)c[e]=i.s[e]+s*(a.s[e]-i.s[e]);return c}function ee(){let n=t(),s=N(),c=fe(r),l=r.clientWidth,u=r.clientHeight;c.clearRect(0,0,l,u),i.length||P(n,()=>null);let d=i.length,f=a.l1,p=a.l2,m=.46*Math.min(l,u)/(f+p),h=l/2,g=u/2,_=(e,t)=>{let n=h+m*f*Math.sin(e),r=g+m*f*Math.cos(e);return[n,r,n+m*p*Math.sin(t),r+m*p*Math.cos(t)]};if(n.trails&&o.length>1){let e=n.trailLength;c.lineWidth=n.trailWidth,c.lineJoin=c.lineCap=`round`;for(let t=0;t<d;t++){c.strokeStyle=G(n,t,d);for(let n=0;n<6;n++){let r=s-n*e/6,i=s-(n+1)*e/6;c.globalAlpha=.7*(1-(n+.5)/6),c.beginPath();let a=!1;for(let e of o){if(e.t<i-bt||e.t>r+bt)continue;if(e.t>s)break;let[,,n,o]=_(e.s[2*t],e.s[2*t+1]);a?c.lineTo(n,o):(c.moveTo(n,o),a=!0)}c.stroke()}}c.globalAlpha=1}let v=K(s);c.lineWidth=1.5,c.lineCap=`round`;let y=n.bobSize;for(let e=d-1;e>=0;e--){let[t,r,a,o]=_(v?v[2*e]:i[e].p.y[0],v?v[2*e+1]:i[e].p.y[1]),s=G(n,e,d);c.strokeStyle=s,c.fillStyle=s,c.globalAlpha=n.armAlpha,c.beginPath(),c.moveTo(h,g),c.lineTo(t,r),c.lineTo(a,o),c.stroke(),c.globalAlpha=1,c.beginPath(),c.arc(t,r,y*.8,0,2*Math.PI),c.moveTo(a+y,o),c.arc(a,o,y,0,2*Math.PI),c.fill()}c.fillStyle=pe(e,`--fg`),c.beginPath(),c.arc(h,g,1.5,0,2*Math.PI),c.fill()}function te(){let e=t(),n=N(),r=e.freeTime,a=e.dampTime,o=D!==null&&C>=D?`at rest`:n<r?`swinging`:n<r+a?`damping`:`settling`,s=180/Math.PI,c=[g,_].map(e=>e?.load?.()??0),l=[g,_].reduce((e,t)=>e+(t?.underruns?.()??0),0);return{time:`${n.toFixed(1)} / ${M.length().toFixed(0)} s`,phase:o,"energy (mean)":i.length?(i.reduce((e,t)=>e+t.p.energyNorm(),0)/i.length).toFixed(4):`–`,notes:String(T),release:`${(j.th1*s).toFixed(2)}°, ${(j.th2*s).toFixed(2)}°`,"offset (outermost)":`${j.offset.toExponential(2)} rad → separate at ${j.separatesAt.toFixed(1)} s`,"seed used":w?String(w):`–`,"at rest":`${i.filter(e=>e.restAt!==null).length} / ${i.length}`,"audio load":O?`renderers ${Math.round(100*Math.max(...c))}% (busiest), ${l} underruns`:`${Math.round(100*(c[0]+c[1]))}%`}}return M}var Z=(e,t={})=>{let n=Ee.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},St={id:`03-divergence`,title:`divergence`,schema:[{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:40,min:5,max:600,step:1,unit:`s`,hint:`free (undamped) swinging before the damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time for the damping to bring every pendulum to rest`},{group:`form`,key:`dampCurve`,label:`damping curve`,kind:`number`,default:1.5,min:.3,max:5,log:!0,hint:`energy follows (1 − u)^curve during the damping; >1 settles fast then lingers`},{group:`form`,key:`tau`,label:`damping follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how closely each pendulum's energy follows the damping curve`},Z(`restEnergy`,{hint:`after the damping, a pendulum counts as at rest below this energy: its last note rings out`}),Z(`finalHold`),Z(`finalFade`),{group:`pendulums`,key:`count`,label:`pendulums`,kind:`number`,default:12,min:1,max:24,step:1},{group:`pendulums`,key:`releaseAngle`,label:`release angle`,kind:`number`,default:120,min:10,max:179,step:1,unit:`°`,hint:`both arms released from rest at this angle from straight down`},{group:`pendulums`,key:`jitter`,label:`angle variation`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`°`,hint:`each play varies the release angles by up to this much (seed fixes it)`},{group:`pendulums`,key:`separateAt`,label:`separate after`,kind:`number`,default:8,min:1,max:60,step:.5,unit:`s`,hint:`the tiny offsets between pendulums are calibrated so the outermost visibly separate at about this time`},{group:`pendulums`,key:`sepThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`bob separation (fraction of the pendulum's length) that counts as separated`},{group:`pendulums`,key:`speed`,label:`speed`,kind:`number`,default:2.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},Z(`massRatio`,{group:`pendulums`}),Z(`lengthRatio`,{group:`pendulums`}),Z(`seed`,{group:`pendulums`,hint:`0 = a different release every play`}),{group:`notes`,key:`instrument`,label:`instrument`,kind:`select`,default:`modal: Vibraphone`,options:Object.keys(q)},Z(`modalCustom`),{group:`notes`,key:`pitchMode`,label:`pitch`,kind:`select`,default:`chord`,options:[`chord`,`motion`],hint:`chord: each pendulum has its own note of a chord spread over the range. motion: pitch from the bob's speed at the crossing`},{group:`notes`,key:`directionChords`,label:`two chords`,kind:`bool`,default:!0,hint:`chord mode: left-to-right and right-to-left crossings play two interleaved chords, so the swings alternate between them`},Z(`scale`,{default:`dorian`}),Z(`root`),Z(`pitchLow`,{default:50}),Z(`pitchHigh`,{default:86}),{group:`notes`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible at release energy) that gives full loudness (and top pitch in motion mode)`},Z(`loudCurve`),Z(`loudFloor`),Z(`notesLevel`,{default:-8}),Z(`noteLength`,{default:2}),{group:`notes`,key:`directionPan`,label:`pan with direction`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`a crossing is panned toward the side the bob is heading`},{group:`notes`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`,hint:`applies on the next play`},{group:`notes`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render the instrument in a background thread, ~1 s ahead (applies on the next play)`},{group:`visual`,key:`trails`,label:`trails`,kind:`bool`,default:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:3,min:.2,max:20,log:!0,unit:`s`},{group:`visual`,key:`trailWidth`,label:`trail width`,kind:`number`,default:1.2,min:.3,max:5,step:.1,unit:`px`},{group:`visual`,key:`armAlpha`,label:`arm opacity`,kind:`number`,default:.75,min:.05,max:1,step:.01},{group:`visual`,key:`bobSize`,label:`bob size`,kind:`number`,default:3,min:.5,max:10,step:.1,unit:`px`},{group:`visual`,key:`saturation`,label:`color saturation`,kind:`number`,default:35,min:0,max:100,step:1,unit:`%`}],defaults:lt,create:xt},Ct={fallAfter:5,freeTime:60,dampTime:20,dampBase:.004,dampEnd:.2,restEnergy:.001,finalHold:2,finalFade:5,speed:1.5,tipThreshold:.02,massRatio:1,lengthRatio:1,seed:0,bottomInstrument:`modal: Violin`,modalCustom:``,bottomPitch:55,minDepth:.25,bottomLength:.4,firstVel:1,maxVel:.6,loudRef:.8,loudCurve:1,loudFloor:.15,notesLevel:6,maxOverlap:4,deviceLimit:!0,streamAudio:!0,click:!0,clickInstrument:`modal: Viola`,clickPitch:72,clickLength:.5,clickMaxVel:.7,clickLevel:-4,heightNotes:!0,heightInstrument:`modal: Piano-ish`,heightLow:60,heightHigh:96,scale:`dorian`,root:`D`,heightStep:2,heightLength:.3,heightVel:.7,heightLevel:6,heightRamp:6,heightRampFrom:.5,heightFollow:.3,trails:!0,trailLength:2.5,rings:!0,motionBlur:1},wt=.6;function Tt(e){let t=e.bottomInstrument;if(!t.startsWith(`modal: `))return null;let n=t===`modal: custom`?N(e.modalCustom):k.find(e=>`modal: ${e.name}`===t)?.p;return{...T,...n??{}}}async function Et(e,t,n){let r=Tt(e);if(!r)return{cap:n,perVoice:0};let i=`double-pendulum:capacity:04-crash:${JSON.stringify({v:1,sr:t,i:e.bottomInstrument,c:e.modalCustom})}`;try{let e=localStorage.getItem(i);if(e){let t=JSON.parse(e);return{...t,cap:Math.max(1,Math.min(n,t.perVoice>0?Math.floor(wt/t.perVoice):n))}}}catch{}let a=[];for(let e=0;e<2;e+=.7)a.push({time:e,note:31+Math.round(e*10),vel:.8,len:.5});let o=await new Promise(e=>{let n=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`});n.onmessage=t=>{t.data.type===`bench`&&(e(t.data.load),n.terminate())};let i={type:`bench`,sampleRate:t,params:{...r,voices:1},notes:a,seconds:2,warmup:.5};n.postMessage(i)});try{localStorage.setItem(i,JSON.stringify({cap:0,perVoice:o}))}catch{}return{cap:Math.max(1,Math.min(n,Math.floor(wt/o))),perVoice:o}}var Dt=.002;function Ot(e,t,n,r){let i=new ce(e);return i.controlled=!1,i.y[0]=Math.PI+r*t,i.y[1]=Math.PI+r*t*n,i}function kt(e,t){return[e.l1*Math.sin(t[0])+e.l2*Math.sin(t[1]),e.l1*Math.cos(t[0])+e.l2*Math.cos(t[1])]}function At(e,t,n,r,i){let a=Ot(e,t,n,1);for(let t=0;t<i;t+=Dt)if(a.step(Dt),Math.abs(kt(e,a.y)[0])>r)return t+Dt;return 1/0}function jt(e,t,n,r){let i=3*n+10,a=1e-15,o=.3;if(At(e,a,t,r,i)<=n)return{nudge:a,tipsAt:At(e,a,t,r,i)};if(At(e,o,t,r,i)>=n)return{nudge:o,tipsAt:At(e,o,t,r,i)};for(let s=0;s<18;s++){let s=Math.sqrt(a*o);At(e,s,t,r,i)>n?a=s:o=s}let s=Math.sqrt(a*o);return{nudge:s,tipsAt:At(e,s,t,r,i)}}var Mt=et(),Nt=.15,Pt=.4,Ft=25,It=15,Lt=1/480,Rt=48,zt=2,Bt=.9,Vt=.3,Ht=.35;function Ut(e,t){e.classList.add(`c04`);let r=document.createElement(`canvas`);e.append(r);let i={m1:1,l1:1,g:1,m2:1,l2:1},a=null,o=0,s=1,c=1,l=[],u=-1/0,d=[],f=0,h=0,g=null,_=null,v=null,y=null,b=null,x=null,S=``,C=null,w=null,T=``,E=null,D=null,O=``,k=[],A=0,j=0,M,N=!1,P=0,F=0,I=0,L=0,R=0,z=!1,B=Nt,V={d:0,ratio:1,side:1,tipsAt:0},H=null,U=!1,W=4,G={get playing(){return N},start:le,stop:Y,draw:Te,now:K,length:()=>be(t()),readouts:De,notice:Ee,dispose(){Y(),e.classList.remove(`c04`),e.replaceChildren()}};function K(){return!v||!N?R:v.ctx.currentTime-F}function ee(e,t){i={m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio};let n=t&&t()<.5?-1:1,r=t?.6+.8*t():1,u=e.speed,p=jt(i,r,e.fallAfter*u,e.tipThreshold*(i.l1+i.l2));V={d:p.nudge,ratio:r,side:n,tipsAt:p.tipsAt/u},a=Ot(i,p.nudge,r,n),o=kt(i,a.y)[0],s=a.energy(),c=Math.sqrt(2*s/i.m2),l=[],d=[],f=0,h=0,g=null,_=null,ue(0)}function te(){if(!v||!y)return;let e=t(),r=v.ctx;b||(b=r.createGain(),b.connect(y)),b.gain.setTargetAtTime(n(e.notesLevel),r.currentTime,.05);let i=e.bottomInstrument,a=`${i}\n${i===`modal: custom`?e.modalCustom:``}\n${W}`;x&&S===a||(x?.dispose(),S=a,x=(z&&Mt[i]||q[i])(r,b,{custom:e.modalCustom,overrides:{voices:W}}))}function ne(){if(!v||!y)return;let e=t(),r=v.ctx;C||(C=r.createGain(),C.connect(y)),C.gain.setTargetAtTime(n(e.clickLevel),r.currentTime,.05);let i=e.clickInstrument,a=e.click?`${i}\n${i===`modal: custom`?e.modalCustom:``}`:``;(T!==a||!w&&a)&&(w?.dispose(),w=null,T=a,a&&(w=(z&&Mt[i]||q[i])(r,C,{custom:e.modalCustom})))}function re(){if(!v||!y)return;let e=t(),r=v.ctx;E||(E=r.createGain(),E.connect(y)),E.gain.setTargetAtTime(n(e.heightLevel),r.currentTime,.05);let i=e.heightInstrument,a=e.heightNotes?`${i}\n${i===`modal: custom`?e.modalCustom:``}`:``;(O!==a||!D&&a)&&(D?.dispose(),D=null,O=a,a&&(D=(z&&Mt[i]||q[i])(r,E,{custom:e.modalCustom})))}function ie(e){let t=e.heightLow,n=e.heightHigh,r=oe.indexOf(e.root),i=[];if(e.scale===`continuous`)for(let e=Math.ceil(t);e<=n;e++)i.push(e);else for(let a=Math.ceil(t);a<=n;a++)Math.abs(se(a,e.scale,r)-a)<1e-6&&i.push(a);let a=Math.max(1,Math.round(e.heightStep));return i.filter((e,t)=>t%a===0)}function ae(e,t){let n=i.l1+i.l2,r=(n-t)/(2*n);return e.heightLow+(e.heightHigh-e.heightLow)*r}function ce(e){let t=0;for(;t<k.length&&k[t]<e;)t++;return t}async function le(e,n){Y();let r=++P;v=e;let o=t(),s=e.ctx;z=!!o.streamAudio,B=z?Je:Nt;let c=Math.round(o.maxOverlap);if(W=c,o.deviceLimit){U=!0;try{H=await Et(o,s.sampleRate,c),W=H.cap}finally{U=!1}if(r!==P)return}L=o.seed>0?Math.round(o.seed):m();let l=p(L);ee(o,()=>l()),k=ie(o),A=ce(ae(o,kt(i,a.y)[1])),j=0,I=0,n>0&&me(n,!1),y=s.createGain(),y.connect(e.input),te(),ne(),re(),await Promise.all([x?.ready,w?.ready,D?.ready]),r===P&&(F=s.currentTime+.1+(z?Pt:0)-n,N=!0,xe(),M=window.setInterval(xe,Ft))}function Y(){if(P++,M!==void 0&&window.clearInterval(M),M=void 0,N&&=(R=K(),!1),!v)return;let e=v.ctx.currentTime,t=y;t&&(t.gain.setTargetAtTime(0,e,.05),window.setTimeout(()=>t.disconnect(),600)),x?.dispose(),x=null,S=``,w?.dispose(),w=null,T=``,C=null,D?.dispose(),D=null,O=``,E=null,b=null,y=null}function ue(e){a&&(l.push({t:e,th1:a.y[0],th2:a.y[1]}),u=e)}function de(e,t){let n=Math.max(0,Math.min(1,(t-e.freeTime)/e.dampTime)),r=n*n*(3-2*n);return e.dampBase+(e.dampEnd-e.dampBase)*r}function me(e,n){if(!a)return;let r=t(),s=r.speed,c=r.freeTime+r.dampTime,l=r.restEnergy,p=r.minDepth*(i.l1+i.l2),m=a;for(;I<e;){let e=I;I+=Dt/s,m.damping=de(r,e),m.step(Dt);let[t,a]=kt(i,m.y);if(_===null&&k.length&&he(e,ae(r,a),r,n),_===null&&Math.abs(a)<=p&&(o<0&&t>=0||o>0&&t<=0)){let i=e+o/(o-t)*(I-e);h++,n&&ye(i,a,r)}else if(_===null&&a>p&&(o<0&&t>=0||o>0&&t<=0)){let i=e+o/(o-t)*(I-e);f++,n?_e(i,a,r):d.push({t:i,x:0,y:a,strength:.5})}o=t,_===null&&I>=c&&(m.energyNorm()<l||I>=c+It)&&(_=I,n&&g&&g.handle.hold(g.when,r.finalHold,r.finalFade)),I-u>=Lt&&ue(I)}}function he(e,t,n,r){let i=Vt*(k.length>1?(k[k.length-1]-k[0])/(k.length-1):1);for(;A<k.length&&t>k[A]+i;)r&&ge(e,k[A],n),A++;for(;A>0&&t<k[A-1]-i;)A--,r&&ge(e,k[A],n)}function ge(e,t,n){if(!v||!D||!a)return;let r=e+Dt/n.speed,i=F+r;if(i<v.ctx.currentTime-.02)return;let o=n.heightRamp>0?Math.max(0,Math.min(1,r/n.heightRamp)):1,c=n.heightRampFrom,l=c+(1-c)*o*o*(3-2*o),u=Math.min(1,Math.max(0,a.energy())/s),d=n.heightVel*l*u**+n.heightFollow;D.play({when:i,freq:J(t),velocity:d,pan:0,duration:n.heightLength}),j++}function _e(e,t,n){if(!v||!x||!a)return;let r=F+e;if(r<v.ctx.currentTime-.02)return;let i=n.bottomPitch,o=f===1?n.firstVel:n.maxVel*ve(n),s=x.play({when:r,freq:J(i),velocity:o,pan:0,duration:n.bottomLength});s&&(g={handle:s,when:r}),d.push({t:e,x:0,y:t,strength:o})}function ve(e){if(!a)return 0;let t=a.derived(),n=a.y,r=i.l1*Math.cos(n[0])*t.w1+i.l2*Math.cos(n[1])*t.w2,o=i.l1*Math.sin(n[0])*t.w1+i.l2*Math.sin(n[1])*t.w2,s=Math.min(1,Math.hypot(r,o)/(e.loudRef*c)),l=e.loudFloor;return l+(1-l)*s**+e.loudCurve}function ye(e,t,n){if(!v||!w)return;let r=F+e;if(r<v.ctx.currentTime-.02)return;let i=n.clickMaxVel*ve(n);w.play({when:r,freq:J(n.clickPitch),velocity:i,pan:0,duration:n.clickLength}),d.push({t:e,x:0,y:t,strength:i,click:!0})}function be(e){let t=e.finalHold+e.finalFade+.3;return(_??e.freeTime+e.dampTime+3)+t}function xe(){if(!v||!N||!a)return;let e=t();te();let n=v.ctx.currentTime-F,r=be(e);if(_!==null&&n>=r){Y(),R=r,G.onEnded?.();return}ne(),re(),me(n+B,!0);for(let e of[x,w,D])e?.horizon?.(F+I);let i=n-e.trailLength-.5,o=0;for(;o<l.length-2&&l[o+1].t<i;)o++;for(o>0&&l.splice(0,o);d.length&&d[0].t<n-Bt-1;)d.shift()}function Se(e){let t=l.length;if(!t)return{t:e,th1:a?.y[0]??Math.PI,th2:a?.y[1]??Math.PI};if(e<=l[0].t)return l[0];if(e>=l[t-1].t)return l[t-1];let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;l[t].t<=e?n=t:r=t}let i=l[n],o=l[r],s=(e-i.t)/(o.t-i.t);return{t:e,th1:i.th1+s*(o.th1-i.th1),th2:i.th2+s*(o.th2-i.th2)}}let Ce=0,we=1/60;function Te(){let n=t();a||ee(n,null);let o=K(),s=performance.now()/1e3,c=s-Ce;Ce=s,c>0&&c<.1&&(we+=(c-we)*.1);let u=fe(r),f=r.clientWidth,p=r.clientHeight;u.clearRect(0,0,f,p);let m=pe(e,`--fg`),h=i.l1,g=i.l2,_=.46*Math.min(f,p)/(h+g),v=f/2,y=p/2,b=e=>{let t=v+_*h*Math.sin(e.th1),n=y+_*h*Math.cos(e.th1);return[t,n,t+_*g*Math.sin(e.th2),n+_*g*Math.cos(e.th2)]};if(n.trails&&l.length>1){let e=n.trailLength;u.strokeStyle=m,u.lineWidth=1,u.lineJoin=u.lineCap=`round`;for(let t=0;t<6;t++){let n=o-t*e/6,r=o-(t+1)*e/6;u.globalAlpha=.45*(1-(t+.5)/6),u.beginPath();let i=!1;for(let e=0;e<l.length;e+=2){let t=l[e];if(t.t<r-.01||t.t>n+.01)continue;if(t.t>o)break;let[,,a,s]=b(t);i?u.lineTo(a,s):(u.moveTo(a,s),i=!0)}u.stroke()}u.globalAlpha=1}if(n.rings){for(let e of d){let t=o-e.t,n=e.click?Ht:Bt;if(t<0||t>n)continue;let[,,r,i]=b(Se(e.t));u.strokeStyle=m,u.globalAlpha=(1-t/n)*(.4+.6*e.strength),u.lineWidth=e.click?1:1.2,u.beginPath();let a=e.click?14:60*(.5+e.strength);u.arc(r,i,(e.click?3:6)+a*Math.sqrt(t/n),0,2*Math.PI),u.stroke()}u.globalAlpha=1}let x=N?n.motionBlur*we:0,S=1;if(x>0){let e=0,t=Se(o);for(let n=1;n<=8;n++){let r=Se(o-x*n/8);e+=_*(h*Math.abs(r.th1-t.th1)+g*Math.abs(r.th2-t.th2)),t=r}S=Math.max(2,Math.min(Rt,Math.ceil(e/zt)))}let C=S===1?1:1-.03**(1/S),w=4*Math.cbrt(i.m2);u.strokeStyle=m,u.fillStyle=m,u.lineWidth=1.5,u.lineCap=`round`,u.globalAlpha=C;for(let e=0;e<S;e++){let[t,n,r,i]=b(Se(o-x*e/Math.max(1,S-1)));u.beginPath(),u.moveTo(v,y),u.lineTo(t,n),u.lineTo(r,i),u.stroke(),u.beginPath(),u.arc(t,n,4,0,2*Math.PI),u.moveTo(r+w,i),u.arc(r,i,w,0,2*Math.PI),u.fill()}u.globalAlpha=1,u.beginPath(),u.arc(v,y,1.5,0,2*Math.PI),u.fill()}function Ee(){if(U)return`checking what this device can play…`;let e=t();if(!e.deviceLimit||!H||H.perVoice===0)return null;if(H.perVoice>.6)return`this device can't render the bottom notes in real time; expect glitches`;let n=Math.round(e.maxOverlap);return W<n?`${W} overlapping note${W>1?`s`:``} (of ${n}): reduced to what this device can play`:null}function De(){let e=t(),n=K(),r=e.freeTime,i=e.dampTime,o=_!==null&&I>=_?`at rest`:f===0?`falling`:n<r?`swinging`:n<r+i?`damping`:`settling`;return{time:`${n.toFixed(1)} / ${G.length().toFixed(0)} s`,phase:o,energy:a?`${(a.energy()/s).toFixed(3)} of start`:`–`,"bottom notes":String(f),clicks:String(h),"height notes":String(j),nudge:`${V.d.toExponential(2)} rad ${V.side>0?`→`:`←`} (shape ${V.ratio.toFixed(2)}), tips at ${V.tipsAt.toFixed(1)} s`,friction:`${de(e,n).toFixed(4)} /sim s`,"seed used":L?String(L):`–`,"overlapping notes":H?`${W} (one ringing note: ${Math.round(100*H.perVoice)}% of a core)`:String(W),"audio load":z?`renderer ${Math.round(100*(x?.load?.()??0))}%, ${x?.underruns?.()??0} underruns`:`${Math.round(100*(x?.load?.()??0))}%`}}return G}var Q=(e,t={})=>{let n=Ee.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Wt={id:`04-crash`,title:`crash`,schema:[{group:`form`,key:`fallAfter`,label:`tips after`,kind:`number`,default:5,min:1,max:30,step:.5,unit:`s`,hint:`the nudge from straight up is calibrated so the pendulum visibly tips at about this time`},{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:60,min:5,max:600,step:1,unit:`s`,hint:`time before the stronger damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time over which the damping grows to its final strength`},{group:`form`,key:`dampBase`,label:`slight damping`,kind:`number`,default:.004,min:0,max:.1,step:5e-4,unit:`/sim s`,hint:`friction throughout (energy loses roughly this fraction per simulated second)`},{group:`form`,key:`dampEnd`,label:`final damping`,kind:`number`,default:.2,min:.01,max:2,log:!0,unit:`/sim s`,hint:`friction reached by the end of the damping`},Q(`restEnergy`,{hint:`after the damping, the pendulum counts as at rest below this energy: the last bottom note rings out`}),Q(`finalHold`),Q(`finalFade`),{group:`pendulum`,key:`speed`,label:`speed`,kind:`number`,default:1.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`pendulum`,key:`tipThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`sideways bob movement (fraction of the length) that counts as tipping`},Q(`massRatio`,{group:`pendulum`}),Q(`lengthRatio`,{group:`pendulum`}),Q(`seed`,{group:`pendulum`,hint:`0 = a different nudge (side and shape) every play`}),{group:`bottom`,key:`bottomInstrument`,label:`instrument`,kind:`select`,default:`modal: Violin`,options:Object.keys(q)},Q(`modalCustom`,{group:`bottom`}),{group:`bottom`,key:`bottomPitch`,label:`pitch`,kind:`number`,default:55,min:12,max:108,step:.5,unit:`midi`},{group:`bottom`,key:`bottomLength`,label:`length`,kind:`number`,default:.4,min:.05,max:5,log:!0,unit:`s`},{group:`bottom`,key:`minDepth`,label:`minimum depth`,kind:`number`,default:.25,min:0,max:.95,step:.01,hint:`crossings count only this far below the pivot (fraction of the length); a folded pendulum sweeping its bob past the pivot clicks instead`},{group:`bottom`,key:`firstVel`,label:`first note`,kind:`number`,default:1,min:.05,max:1,step:.01,hint:`strength of the first bottom note (accent)`},{group:`bottom`,key:`maxVel`,label:`strongest`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`strength of later bottom notes at full speed`},{group:`bottom`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.8,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible) that gives the strongest note`},Q(`loudCurve`,{group:`bottom`}),Q(`loudFloor`,{group:`bottom`,default:.15}),Q(`notesLevel`,{group:`bottom`,default:6,max:18}),{group:`bottom`,key:`maxOverlap`,label:`overlapping notes`,kind:`number`,default:4,min:1,max:16,step:1,hint:`most bottom notes ringing at once (a new one replaces the oldest)`},{group:`bottom`,key:`deviceLimit`,label:`limit to device`,kind:`bool`,default:!0,hint:`measure (once per device) how many ringing bottom notes it can render, and allow no more`},{group:`bottom`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render the instruments in background threads, ~1 s ahead (applies on the next play)`},{group:`click`,key:`click`,label:`click`,kind:`bool`,default:!0,hint:`a click when the outer bob passes the pivot (closer than the minimum depth)`},{group:`click`,key:`clickInstrument`,label:`instrument`,kind:`select`,default:`modal: Viola`,options:Object.keys(q)},{group:`click`,key:`clickPitch`,label:`pitch`,kind:`number`,default:72,min:24,max:120,step:.5,unit:`midi`},{group:`click`,key:`clickLength`,label:`length`,kind:`number`,default:.5,min:.01,max:2,log:!0,unit:`s`},{group:`click`,key:`clickMaxVel`,label:`strongest`,kind:`number`,default:.7,min:.05,max:1,step:.01,hint:`strength at full bob speed (follows the speed like the bottom notes)`},{group:`click`,key:`clickLevel`,label:`level`,kind:`number`,default:-4,min:-48,max:6,step:.5,unit:`dB`},{group:`height`,key:`heightNotes`,label:`height notes`,kind:`bool`,default:!0,hint:"levels are the scale's notes between the low and high pitch (every `step`-th); passing one, up or down, plays it"},{group:`height`,key:`heightInstrument`,label:`instrument`,kind:`select`,default:`modal: Piano-ish`,options:Object.keys(q)},{group:`height`,key:`heightLow`,label:`pitch at bottom`,kind:`number`,default:60,min:24,max:108,step:.5,unit:`midi`,hint:`bob straight down`},{group:`height`,key:`heightHigh`,label:`pitch at top`,kind:`number`,default:96,min:24,max:120,step:.5,unit:`midi`,hint:`bob straight up`},Q(`scale`,{group:`height`,default:`dorian`}),Q(`root`,{group:`height`}),{group:`height`,key:`heightStep`,label:`step`,kind:`number`,default:2,min:1,max:7,step:1,hint:`levels every this many scale notes (2 = arpeggio-like)`},{group:`height`,key:`heightLength`,label:`length`,kind:`number`,default:.3,min:.05,max:3,log:!0,unit:`s`},{group:`height`,key:`heightVel`,label:`strength`,kind:`number`,default:.7,min:.05,max:1,step:.01},{group:`height`,key:`heightLevel`,label:`level`,kind:`number`,default:6,min:-48,max:18,step:.5,unit:`dB`},{group:`height`,key:`heightRamp`,label:`ramp in`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`the notes grow to full strength over the opening`},{group:`height`,key:`heightRampFrom`,label:`ramp from`,kind:`number`,default:.5,min:0,max:1,step:.01,hint:`starting strength, as a fraction of full`},{group:`height`,key:`heightFollow`,label:`fades with energy`,kind:`number`,default:.3,min:0,max:2,step:.05,hint:`strength × (energy / start energy)^this`},{group:`visual`,key:`trails`,label:`trail`,kind:`bool`,default:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:2.5,min:.2,max:20,log:!0,unit:`s`},{group:`visual`,key:`rings`,label:`rings`,kind:`bool`,default:!0,hint:`a brief ring where each bottom note (and, smaller, each click) happens`},Q(`motionBlur`)],defaults:Ct,create:Ut},Gt=`double pendulum`,Kt=[De,ct,St,Wt],qt=document.getElementById(`app`),Jt=null;function $(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function Yt(){Jt?.(),Jt=null,qt.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean),t=Kt.find(t=>t.id===e[0]);if(!t)return Xt();Jt=en(t,e[1]===`edit`)}function Xt(){document.title=Gt;let e=$(`ol`,{className:`tracks`});for(let t of Kt)e.append($(`li`,{},$(`a`,{href:`#/${t.id}`,textContent:t.title})));qt.append($(`main`,{className:`album`},$(`h1`,{textContent:Gt}),e))}var Zt=e=>`double-pendulum:author:${e.id}`;function Qt(e){try{let t=localStorage.getItem(Zt(e));return t?JSON.parse(t):null}catch{return null}}function $t(e,t){try{localStorage.setItem(Zt(e),JSON.stringify(t))}catch{}}function en(e,n){let r=Kt.indexOf(e)+1;document.title=`${e.title} · ${Gt}`;let a=()=>i(e.schema,e.defaults),o=n?i(e.schema,e.defaults,Qt(e)):a(),s=$(`div`,{className:`view`}),c=$(`button`,{className:`big-play`,textContent:`▶`,title:`play`});c.setAttribute(`aria-label`,`play`);let l=$(`button`,{className:`play`,textContent:`play`}),u=$(`div`,{className:`bar`}),f=$(`div`,{className:`progress`},u),p=$(`a`,{className:`edit`,href:n?`#/${e.id}`:`#/${e.id}/edit`,textContent:n?`done`:`edit`}),m=$(`header`,{},$(`a`,{href:`#/`,textContent:Gt}),$(`span`,{className:`sep`,textContent:` / `}),$(`span`,{textContent:`${r}. ${e.title}`})),h=$(`div`,{className:`notice`}),g=$(`main`,{className:`stage`},m,h,s,$(`div`,{className:`transport`},l,f,p)),_=$(`div`,{className:n?`page with-author`:`page`},g);qt.append(_);let v=e.create(s,()=>o);s.append(c);let y=()=>{let e=Math.floor(Math.min(s.clientWidth,s.clientHeight));for(let t of s.querySelectorAll(`canvas`))t.style.width=`${e}px`,t.style.height=`${e}px`},b=new ResizeObserver(y);b.observe(s),y();let x={value:0},S=!1,C=async e=>{S=!0;try{let n=await t();await v.start(n,e)}finally{S=!1}};l.onclick=()=>v.playing?v.stop():C(n?x.value:0),c.onclick=()=>l.click(),n&&(f.classList.add(`seekable`),f.onclick=e=>{let t=f.getBoundingClientRect(),n=Math.max(0,(e.clientX-t.left)/t.width*v.length());C(n)});let w=null;n&&(w=d({schema:e.schema,get:()=>o,set:t=>{o=t,$t(e,t)},defaults:a,readouts:()=>v.readouts(),startAt:x}),_.append(w.el));let T=e=>{let t=e.target.tagName;e.code===`Space`&&t!==`INPUT`&&t!==`SELECT`&&t!==`BUTTON`&&(e.preventDefault(),l.click())};window.addEventListener(`keydown`,T);let E=0,D=0,O=e=>{v.draw(),l.textContent=v.playing?`stop`:`play`,c.hidden=v.playing||S;let t=v.notice?.()??``;h.textContent!==t&&(h.textContent=t),u.style.width=`${Math.min(100,100*v.now()/v.length())}%`,w&&e-D>200&&(w.updateReadouts(),D=e),E=requestAnimationFrame(O)};return E=requestAnimationFrame(O),()=>{cancelAnimationFrame(E),window.removeEventListener(`keydown`,T),b.disconnect(),v.dispose()}}window.addEventListener(`hashchange`,Yt),Yt();
\ No newline at end of file
site/index.htmlmodified+1−1View file
@@ -5,7 +5,7 @@
55 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
66 <title>double pendulum</title>
77 <link rel="icon" href="data:," />
8- <script type="module" crossorigin src="./assets/index-DWceBk6K.js"></script>
8+ <script type="module" crossorigin src="./assets/index-6HGfP7XN.js"></script>
99 <link rel="stylesheet" crossorigin href="./assets/index-C8mMpV0u.css">
1010 </head>
1111 <body>
src/compositions/c04-crash/capacity.tsmodified+5−5View file
@@ -1,4 +1,4 @@
1-// How many ringing crashes can this device render? Crash instruments like Chaos gong are costly
1+// How many ringing bottom notes can this device render? Instruments like Chaos gong are costly
22 // per ringing voice (strongly coupled modes can't be culled), so measure one voice's cost in a
33 // render worker (as playback would run it) and allow as many voices as fit the budget.
44
@@ -16,16 +16,16 @@ export interface VoiceCapacity {
1616 }
1717
1818 function sound(P: Params): Params | null {
19- const name = P.crashInstrument as string;
19+ const name = P.bottomInstrument as string;
2020 if (!name.startsWith("modal: ")) return null;
2121 const p = name === "modal: custom" ? parseModalPreset(P.modalCustom as string) : PRESETS.find((x) => `modal: ${x.name}` === name)?.p;
2222 return { ...DEFAULTS, ...(p ?? {}) };
2323 }
2424
25-export async function crashCapacity(P: Params, sampleRate: number, wanted: number): Promise<VoiceCapacity> {
25+export async function overlapCapacity(P: Params, sampleRate: number, wanted: number): Promise<VoiceCapacity> {
2626 const s = sound(P);
2727 if (!s) return { cap: wanted, perVoice: 0 };
28- const key = `double-pendulum:capacity:04-crash:${JSON.stringify({ v: 1, sr: sampleRate, i: P.crashInstrument, c: P.modalCustom })}`;
28+ const key = `double-pendulum:capacity:04-crash:${JSON.stringify({ v: 1, sr: sampleRate, i: P.bottomInstrument, c: P.modalCustom })}`;
2929 try {
3030 const c = localStorage.getItem(key);
3131 if (c) {
@@ -57,4 +57,4 @@ export async function crashCapacity(P: Params, sampleRate: number, wanted: numbe
5757 return { cap: Math.max(1, Math.min(wanted, Math.floor(BUDGET / perVoice))), perVoice };
5858 }
5959
60-export const CRASH_BUDGET = BUDGET;
60+export const OVERLAP_BUDGET = BUDGET;
src/compositions/c04-crash/defaults.jsonmodified+5−7View file
@@ -12,20 +12,18 @@
1212 "massRatio": 1,
1313 "lengthRatio": 1,
1414 "seed": 0,
15- "crashInstrument": "modal: Violin",
15+ "bottomInstrument": "modal: Violin",
1616 "modalCustom": "",
17- "crashLow": 55,
17+ "bottomPitch": 55,
1818 "minDepth": 0.25,
19- "crashHigh": 79,
20- "crashLength": 0.4,
21- "crashCurve": 1,
19+ "bottomLength": 0.4,
2220 "firstVel": 1,
2321 "maxVel": 0.6,
2422 "loudRef": 0.8,
2523 "loudCurve": 1,
2624 "loudFloor": 0.15,
2725 "notesLevel": 6,
28- "maxCrashes": 4,
26+ "maxOverlap": 4,
2927 "deviceLimit": true,
3028 "streamAudio": true,
3129 "click": true,
@@ -49,6 +47,6 @@
4947 "heightFollow": 0.3,
5048 "trails": true,
5149 "trailLength": 2.5,
52- "crashRings": true,
50+ "rings": true,
5351 "motionBlur": 1
5452 }
src/compositions/c04-crash/piece.tsmodified+38−41View file
@@ -1,12 +1,13 @@
1-// Composition 4: crash.
1+// Composition 4 (folder c04-crash).
22 //
33 // One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about
44 // `fallAfter` seconds. Short piano notes mark the outer bob's height as it passes a ladder of
5-// levels (higher level, higher note), so you hear it come down;
6-// when the bob first swings through the bottom, a big low crash. From then on, every time the outer
7-// bob crosses the vertical below the pivot there is a crash whose pitch rises with the height of
8-// the crossing (continuous). Slight friction throughout, growing toward the end until it comes to
9-// rest; the last crash rings out and the piece ends with the fade.
5+// levels (higher level, higher note), so you hear it come down. When the bob first swings through
6+// the bottom, an accented bottom note (a short violin note at a fixed pitch); from then on, every
7+// time the outer bob crosses the vertical below the pivot there is a bottom note, its strength
8+// from the bob's speed. Sweeping past the pivot itself (a folded pendulum) is a click instead.
9+// Slight friction throughout, growing toward the end until it comes to rest; the last bottom note
10+// rings out and the piece ends with the fade.
1011
1112 import type { AudioEngine } from "../../core/audio.ts";
1213 import { dbToGain } from "../../core/audio.ts";
@@ -19,7 +20,7 @@ import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
1920 import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
2021 import type { DoublePendulum, PendulumConfig } from "../../physics/doublePendulum.ts";
2122 import { cssColor, fitCanvas } from "../shared/section.ts";
22-import { CRASH_BUDGET, crashCapacity, type VoiceCapacity } from "./capacity.ts";
23+import { OVERLAP_BUDGET, overlapCapacity, type VoiceCapacity } from "./capacity.ts";
2324 import { DT, bob, inverted, nudgeForTip } from "./fall.ts";
2425
2526 const STREAMED = streamedModalInstruments();
@@ -30,7 +31,7 @@ const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest reg
3031 const HISTORY_DT = 1 / 480; // piece-time spacing of stored states (drawing, blur, trail)
3132 const BLUR_MAX_SAMPLES = 48;
3233 const BLUR_SPACING_PX = 2;
33-const RING_S = 0.9; // crash ring lifetime
34+const RING_S = 0.9; // bottom-note ring lifetime
3435 const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it
3536 const CLICK_RING_S = 0.35; // click ring lifetime
3637
@@ -40,12 +41,12 @@ interface Snap {
4041 th2: number;
4142 }
4243
43-interface Crash {
44+interface Mark {
4445 t: number;
4546 x: number; // bob position (pendulum units)
4647 y: number;
4748 strength: number;
48- click?: boolean; // a pass by the pivot, not a crash
49+ click?: boolean; // a pass by the pivot, not a bottom note
4950 }
5051
5152 export function createCrashPiece(view: HTMLElement, params: () => Params): Piece {
@@ -60,8 +61,8 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
6061 let vmax = 1;
6162 let history: Snap[] = [];
6263 let lastHistT = -Infinity;
63- let crashes: Crash[] = [];
64- let crashCount = 0;
64+ let marks: Mark[] = [];
65+ let bottomCount = 0;
6566 let clickCount = 0;
6667 let lastNote: { handle: NoteHandle; when: number } | null = null;
6768 let restAt: number | null = null;
@@ -131,8 +132,8 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
131132 E0 = pend.energy();
132133 vmax = Math.sqrt((2 * E0) / cfg.m2);
133134 history = [];
134- crashes = [];
135- crashCount = 0;
135+ marks = [];
136+ bottomCount = 0;
136137 clickCount = 0;
137138 lastNote = null;
138139 restAt = null;
@@ -148,7 +149,7 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
148149 noteBus.connect(out);
149150 }
150151 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
151- const name = P.crashInstrument as string;
152+ const name = P.bottomInstrument as string;
152153 const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`;
153154 if (inst && instKey === key) return;
154155 inst?.dispose();
@@ -233,12 +234,12 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
233234 const ctx = a.ctx;
234235 stream = !!P.streamAudio;
235236 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
236- const wanted = Math.round(P.maxCrashes as number);
237+ const wanted = Math.round(P.maxOverlap as number);
237238 voicesAllowed = wanted;
238239 if (P.deviceLimit) {
239240 checking = true;
240241 try {
241- capacity = await crashCapacity(P, ctx.sampleRate, wanted);
242+ capacity = await overlapCapacity(P, ctx.sampleRate, wanted);
242243 voicesAllowed = capacity.cap;
243244 } finally {
244245 checking = false;
@@ -338,9 +339,9 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
338339 } else if (restAt === null && y > minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
339340 const f = prevX / (prevX - x);
340341 const tc = t0 + f * (simPieceT - t0);
341- crashCount++;
342- if (sound) crash(tc, y, P);
343- else crashes.push({ t: tc, x: 0, y, strength: 0.5 });
342+ bottomCount++;
343+ if (sound) bottomNote(tc, y, P);
344+ else marks.push({ t: tc, x: 0, y, strength: 0.5 });
344345 }
345346 prevX = x;
346347 if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
@@ -381,20 +382,16 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
381382 heightCount++;
382383 }
383384
384- function crash(tc: number, y: number, P: Params) {
385+ function bottomNote(tc: number, y: number, P: Params) {
385386 if (!audio || !inst || !pend) return;
386387 const when = pieceStart + tc;
387388 if (when < audio.ctx.currentTime - 0.02) return;
388- const L = cfg.l1 + cfg.l2;
389- // pitch: lowest with the bob straight down (y = L), highest at the shallowest crossing that counts
390- const yMin = (P.minDepth as number) * L;
391- const u = Math.max(0, Math.min(1, (L - y) / Math.max(1e-9, L - yMin)));
392- const midi = (P.crashLow as number) + ((P.crashHigh as number) - (P.crashLow as number)) * Math.pow(u, P.crashCurve as number);
393- // strength: the first crash is the accent; later ones follow the bob's speed
394- const velocity = crashCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P);
395- const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.crashLength as number });
389+ const midi = P.bottomPitch as number;
390+ // strength: the first bottom note is the accent; later ones follow the bob's speed
391+ const velocity = bottomCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P);
392+ const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.bottomLength as number });
396393 if (handle) lastNote = { handle, when };
397- crashes.push({ t: tc, x: 0, y, strength: velocity });
394+ marks.push({ t: tc, x: 0, y, strength: velocity });
398395 }
399396
400397 /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
@@ -415,7 +412,7 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
415412 if (when < audio.ctx.currentTime - 0.02) return;
416413 const velocity = (P.clickMaxVel as number) * speedStrength(P);
417414 clickInst.play({ when, freq: midiToFreq(P.clickPitch as number), velocity, pan: 0, duration: P.clickLength as number });
418- crashes.push({ t: tc, x: 0, y, strength: velocity, click: true });
415+ marks.push({ t: tc, x: 0, y, strength: velocity, click: true });
419416 }
420417
421418 function endTime(P: Params): number {
@@ -446,7 +443,7 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
446443 let i = 0;
447444 while (i < history.length - 2 && history[i + 1].t < keep) i++;
448445 if (i > 0) history.splice(0, i);
449- while (crashes.length && crashes[0].t < t - RING_S - 1) crashes.shift();
446+ while (marks.length && marks[0].t < t - RING_S - 1) marks.shift();
450447 }
451448
452449 // ── drawing ──
@@ -515,9 +512,9 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
515512 g.globalAlpha = 1;
516513 }
517514
518- // crash rings, where each crash happened
519- if (P.crashRings) {
520- for (const c of crashes) {
515+ // rings, where each bottom note (and click) happened
516+ if (P.rings) {
517+ for (const c of marks) {
521518 const age = t - c.t;
522519 const life = c.click ? CLICK_RING_S : RING_S;
523520 if (age < 0 || age > life) continue;
@@ -577,27 +574,27 @@ export function createCrashPiece(view: HTMLElement, params: () => Params): Piece
577574 if (checking) return "checking what this device can play…";
578575 const P = params();
579576 if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
580- if (capacity.perVoice > CRASH_BUDGET) return "this device can't render the crashes in real time; expect glitches";
581- const want = Math.round(P.maxCrashes as number);
582- return voicesAllowed < want ? `${voicesAllowed} overlapping crash${voicesAllowed > 1 ? "es" : ""} (of ${want}): reduced to what this device can play` : null;
577+ if (capacity.perVoice > OVERLAP_BUDGET) return "this device can't render the bottom notes in real time; expect glitches";
578+ const want = Math.round(P.maxOverlap as number);
579+ return voicesAllowed < want ? `${voicesAllowed} overlapping note${voicesAllowed > 1 ? "s" : ""} (of ${want}): reduced to what this device can play` : null;
583580 }
584581
585582 function readouts(): Record<string, string> {
586583 const P = params();
587584 const t = now();
588585 const free = P.freeTime as number, damp = P.dampTime as number;
589- const phase = restAt !== null && simPieceT >= restAt ? "at rest" : crashCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
586+ const phase = restAt !== null && simPieceT >= restAt ? "at rest" : bottomCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
590587 return {
591588 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
592589 phase,
593590 energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
594- crashes: String(crashCount),
591+ "bottom notes": String(bottomCount),
595592 clicks: String(clickCount),
596593 "height notes": String(heightCount),
597594 nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
598595 friction: `${damping(P, t).toFixed(4)} /sim s`,
599596 "seed used": seedUsed ? String(seedUsed) : "–",
600- "crash voices": capacity ? `${voicesAllowed} (one ringing crash: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
597+ "overlapping notes": capacity ? `${voicesAllowed} (one ringing note: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
601598 "audio load": stream ? `renderer ${Math.round(100 * (inst?.load?.() ?? 0))}%, ${inst?.underruns?.() ?? 0} underruns` : `${Math.round(100 * (inst?.load?.() ?? 0))}%`,
602599 };
603600 }
src/compositions/c04-crash/schema.tsmodified+18−20View file
@@ -15,7 +15,7 @@ export const schema: ParamSpec[] = [
1515 { group: "form", key: "dampTime", label: "damping", kind: "number", default: 20, min: 2, max: 300, step: 0.5, unit: "s", hint: "time over which the damping grows to its final strength" },
1616 { group: "form", key: "dampBase", label: "slight damping", kind: "number", default: 0.004, min: 0, max: 0.1, step: 0.0005, unit: "/sim s", hint: "friction throughout (energy loses roughly this fraction per simulated second)" },
1717 { group: "form", key: "dampEnd", label: "final damping", kind: "number", default: 0.2, min: 0.01, max: 2, log: true, unit: "/sim s", hint: "friction reached by the end of the damping" },
18- pick("restEnergy", { hint: "after the damping, the pendulum counts as at rest below this energy: the last crash rings out" }),
18+ pick("restEnergy", { hint: "after the damping, the pendulum counts as at rest below this energy: the last bottom note rings out" }),
1919 pick("finalHold"),
2020 pick("finalFade"),
2121
@@ -26,30 +26,28 @@ export const schema: ParamSpec[] = [
2626 pick("lengthRatio", { group: "pendulum" }),
2727 pick("seed", { group: "pendulum", hint: "0 = a different nudge (side and shape) every play" }),
2828
29- // ── crashes: outer bob crossing the vertical below the pivot ──
30- { group: "crash", key: "crashInstrument", label: "instrument", kind: "select", default: "modal: Violin", options: Object.keys(NOTE_INSTRUMENTS) },
31- pick("modalCustom", { group: "crash" }),
32- { group: "crash", key: "crashLow", label: "pitch at bottom", kind: "number", default: 55, min: 12, max: 96, step: 0.5, unit: "midi", hint: "crossing with the bob straight down (continuous pitch)" },
33- { group: "crash", key: "minDepth", label: "minimum depth", kind: "number", default: 0.25, min: 0, max: 0.95, step: 0.01, hint: "crossings count only this far below the pivot (fraction of the length), so a folded pendulum sweeping its bob past the pivot is silent" },
34- { group: "crash", key: "crashHigh", label: "pitch at min depth", kind: "number", default: 79, min: 12, max: 108, step: 0.5, unit: "midi", hint: "crossing at the minimum depth (the shallowest that counts)" },
35- { group: "crash", key: "crashLength", label: "length", kind: "number", default: 0.4, min: 0.05, max: 5, log: true, unit: "s" },
36- { group: "crash", key: "crashCurve", label: "pitch curve", kind: "number", default: 1, min: 0.2, max: 5, log: true },
37- { group: "crash", key: "firstVel", label: "first crash", kind: "number", default: 1, min: 0.05, max: 1, step: 0.01, hint: "strength of the first crash (accent)" },
38- { group: "crash", key: "maxVel", label: "strongest crash", kind: "number", default: 0.6, min: 0.05, max: 1, step: 0.01, hint: "strength of later crashes at full speed" },
39- { group: "crash", key: "loudRef", label: "speed for full", kind: "number", default: 0.8, min: 0.05, max: 1, step: 0.01, hint: "bob speed (fraction of the fastest possible) that gives the strongest crash" },
40- pick("loudCurve", { group: "crash" }),
41- pick("loudFloor", { group: "crash", default: 0.15 }),
42- pick("notesLevel", { group: "crash", default: 6, max: 18 }),
43- { group: "crash", key: "maxCrashes", label: "overlapping crashes", kind: "number", default: 4, min: 1, max: 16, step: 1, hint: "most crashes ringing at once (a new one replaces the oldest)" },
44- { group: "crash", key: "deviceLimit", label: "limit to device", kind: "bool", default: true, hint: "measure (once per device) how many ringing crashes it can render, and allow no more" },
45- { group: "crash", key: "streamAudio", label: "render ahead", kind: "bool", default: true, hint: "render the crashes in a background thread, ~1 s ahead (applies on the next play)" },
29+ // ── bottom notes: outer bob crossing the vertical below the pivot ──
30+ { group: "bottom", key: "bottomInstrument", label: "instrument", kind: "select", default: "modal: Violin", options: Object.keys(NOTE_INSTRUMENTS) },
31+ pick("modalCustom", { group: "bottom" }),
32+ { group: "bottom", key: "bottomPitch", label: "pitch", kind: "number", default: 55, min: 12, max: 108, step: 0.5, unit: "midi" },
33+ { group: "bottom", key: "bottomLength", label: "length", kind: "number", default: 0.4, min: 0.05, max: 5, log: true, unit: "s" },
34+ { group: "bottom", key: "minDepth", label: "minimum depth", kind: "number", default: 0.25, min: 0, max: 0.95, step: 0.01, hint: "crossings count only this far below the pivot (fraction of the length); a folded pendulum sweeping its bob past the pivot clicks instead" },
35+ { group: "bottom", key: "firstVel", label: "first note", kind: "number", default: 1, min: 0.05, max: 1, step: 0.01, hint: "strength of the first bottom note (accent)" },
36+ { group: "bottom", key: "maxVel", label: "strongest", kind: "number", default: 0.6, min: 0.05, max: 1, step: 0.01, hint: "strength of later bottom notes at full speed" },
37+ { group: "bottom", key: "loudRef", label: "speed for full", kind: "number", default: 0.8, min: 0.05, max: 1, step: 0.01, hint: "bob speed (fraction of the fastest possible) that gives the strongest note" },
38+ pick("loudCurve", { group: "bottom" }),
39+ pick("loudFloor", { group: "bottom", default: 0.15 }),
40+ pick("notesLevel", { group: "bottom", default: 6, max: 18 }),
41+ { group: "bottom", key: "maxOverlap", label: "overlapping notes", kind: "number", default: 4, min: 1, max: 16, step: 1, hint: "most bottom notes ringing at once (a new one replaces the oldest)" },
42+ { group: "bottom", key: "deviceLimit", label: "limit to device", kind: "bool", default: true, hint: "measure (once per device) how many ringing bottom notes it can render, and allow no more" },
43+ { group: "bottom", key: "streamAudio", label: "render ahead", kind: "bool", default: true, hint: "render the instruments in background threads, ~1 s ahead (applies on the next play)" },
4644
4745 // ── click: the outer bob sweeping past the pivot (within the minimum depth) ──
4846 { group: "click", key: "click", label: "click", kind: "bool", default: true, hint: "a click when the outer bob passes the pivot (closer than the minimum depth)" },
4947 { group: "click", key: "clickInstrument", label: "instrument", kind: "select", default: "modal: Viola", options: Object.keys(NOTE_INSTRUMENTS) },
5048 { group: "click", key: "clickPitch", label: "pitch", kind: "number", default: 72, min: 24, max: 120, step: 0.5, unit: "midi" },
5149 { group: "click", key: "clickLength", label: "length", kind: "number", default: 0.5, min: 0.01, max: 2, log: true, unit: "s" },
52- { group: "click", key: "clickMaxVel", label: "strongest", kind: "number", default: 0.7, min: 0.05, max: 1, step: 0.01, hint: "strength at full bob speed (follows the speed like the crashes)" },
50+ { group: "click", key: "clickMaxVel", label: "strongest", kind: "number", default: 0.7, min: 0.05, max: 1, step: 0.01, hint: "strength at full bob speed (follows the speed like the bottom notes)" },
5351 { group: "click", key: "clickLevel", label: "level", kind: "number", default: -4, min: -48, max: 6, step: 0.5, unit: "dB" },
5452
5553 // ── height notes: a short note each time the outer bob's height passes a level ──
@@ -70,6 +68,6 @@ export const schema: ParamSpec[] = [
7068 // ── visual ──
7169 { group: "visual", key: "trails", label: "trail", kind: "bool", default: true },
7270 { group: "visual", key: "trailLength", label: "trail length", kind: "number", default: 2.5, min: 0.2, max: 20, log: true, unit: "s" },
73- { group: "visual", key: "crashRings", label: "crash rings", kind: "bool", default: true, hint: "a brief ring where each crash happens" },
71+ { group: "visual", key: "rings", label: "rings", kind: "bool", default: true, hint: "a brief ring where each bottom note (and, smaller, each click) happens" },
7472 pick("motionBlur"),
7573 ];
↑↓ move↵openescclose