/ music / double-pendulum
Sign in
music / double-pendulum
Overhaul playback: background-computed, buffered, one clock
Each performance is now a function of piece time alone, computed ahead in workers and played from a buffer: - a score worker runs the composition's simulation and sends drawing data to the page and timed notes to the instruments (held back 2.5 s so the final-note hold still works); - one synth worker per instrument renders modal-synth in fixed blocks at 48 kHz on every device; - a player worklet owns the playhead: it advances only while every stem is buffered, pauses everything (sound fades, picture freezes, spinner) when one runs short, and on slow devices waits long enough to play through. The page draws each piece from the score's data at the playhead, so sound and picture share one clock. Seeks and non-live author edits start a new performance from that moment with the same seed. Physics uses deterministic math (fdlibm ports), so a seed plays the same everywhere. Device-dependent caps (orbit count, voice limits) are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 75ca48a5c2c1 parent 97bd308 Browse files
93 changed files+3209−3942
README.mdmodified+27−19View file
@@ -1,6 +1,6 @@
11 # double pendulum
22
3-An album of electroacoustic compositions. Each composition's sound and image are computed live in the browser from a double pendulum simulation.
3+An album of electroacoustic compositions. Each composition's sound and image are computed in the browser, in the background, from a double pendulum simulation. The same seed and settings play the same performance on every device.
44
55 ```bash
66 npm install
@@ -13,24 +13,37 @@ npm run build # static site in dist/ (relative paths, so it works under any s
1313 - `#/`: the track list
1414 - `#/<id>`: a composition with its published defaults (what visitors hear)
1515 - `#/<id>/edit`: author mode. Adds a panel of every parameter, readouts, "start at", and click-to-seek on the progress line.
16+- `?slow=N` (before the `#`): testing only. Renders the instruments N× slower, to see how a slow device buffers.
1617
1718 ## Author workflow
1819
19-1. Open a composition, click **edit**, and tweak while it plays. Most changes are heard immediately. Instrument choice and the seed apply on the next play.
20+1. Open a composition, click **edit**, and tweak while it plays. Levels and drawing settings apply immediately. Any other change recomputes the performance from the current moment (same seed), after a brief buffering pause.
2021 2. Your edits persist in this browser (localStorage), and only in author mode.
2122 3. **copy config** copies the full parameter set as JSON. Paste it over
2223 `src/compositions/<dir>/defaults.json` and rebuild to publish it.
2324 4. **seed** = 0 gives a new variation each play. The readouts show the seed that was used, so you can pin a variation you liked.
2425
26+## How a performance plays
27+
28+Nothing is computed on the audio thread or the page's main thread in real time. A performance is a function of piece time alone, computed ahead in background workers and played from a buffer (`src/stream/`):
29+
30+- **Score worker** (`scoreWorker.ts`, one per performance): runs the composition's *score* (`<dir>/score.ts`), which simulates the piece in piece time. It sends drawing data (rows of state, and events such as crossings) to the page, and timed note commands to the synth workers. It holds note commands back 2.5 s of piece time before releasing them, so a score can still lengthen a note it has already played (the final-note hold) once it finds, a little later, that the piece has ended. The ensemble's score renders its audio itself.
31+- **Synth workers** (`synthWorker.ts`, one per instrument): render the modal-synth engine from those commands in 128-frame blocks from piece frame 0, at 48 kHz on every device. They render as fast as they can, up to whatever the score has released and the buffer the player asks for.
32+- **Player worklet** (`player.ts`): owns the piece's clock. Its playhead advances only while every stem has audio for it. When any stem runs short, everything pauses: the sound fades, and the picture freezes. A spinner shows how full the buffer is. Play resumes once every stem is buffered ahead. The player measures how fast the stems are being rendered. On a device that renders slower than real time, a pause waits long enough to play through to the end; otherwise each pause doubles the wait (1, 2, 4… s), so pauses get rarer.
33+- **Page** (`performance.ts`, `piece.ts`): wires the workers to the player with message ports, applies each output's effects (modal-synth's own, or one shared reverb) and live levels, and draws. Each composition's view (`<dir>/view.ts`) draws from the score's data at the player's playhead (less the output latency), so sound and picture share one clock. A seek or an edit starts a new performance at that moment. The score fast-forwards silently and computes sound from 4 s before it, so notes already ringing are heard.
34+
35+**Same on every device**: the AudioContext runs at 48 kHz, so it is the same rate the performance is computed at. Nothing depends on device speed; a slow device just buffers more. The physics uses `src/physics/dmath.ts`, ports of the fdlibm algorithms for sin, cos, exp, log and pow built from + − × ÷. Browsers' own `Math.sin` and the like differ in the last bit, and a chaotic pendulum turns that into a different performance within seconds. Scores never call `Math.random`; variations come from the seed.
36+
2537 ## Layout
2638
2739 - `src/physics/doublePendulum.ts`: Hamiltonian double pendulum, RK4. Energy is steered to a target by a force `λ·p` (`dE/dt = 2λT`), so it rises and falls smoothly.
28-- `src/instruments/`: instrument interfaces (`NoteInstrument`, `DroneInstrument`), placeholders, and the registry. Add real instruments here and they appear in the composition's instrument menus.
29-- `src/instruments/modal.ts`: instruments from the sibling **modal-synth** project (`../modal-synth`), imported live through the `@modal-synth` alias (see `vite.config.ts` and `tsconfig.json`). Every built-in modal-synth preset appears as `modal: <name>`. For your own sounds, press **Copy** in modal-synth, choose `modal: custom`, and paste the JSON into **modal custom**. The JSON then becomes part of the composition's config. Building requires `../modal-synth` to be present.
40+- `src/stream/`: the performance system above.
41+- `src/instruments/sounds.ts`: the instrument menus: every modal-synth preset from the sibling **modal-synth** project (`../modal-synth`), imported live through the `@modal-synth` alias (see `vite.config.ts` and `tsconfig.json`), as `modal: <name>`. For your own sounds, press **Copy** in modal-synth, choose `modal: custom`, and paste the JSON into **modal custom**. The JSON then becomes part of the composition's config. Building requires `../modal-synth` to be present.
42+- `src/instruments/effects.ts`: effects on the page (modal-synth's, or a shared reverb).
3043 - `src/music/scales.ts`: scales and quantization (including continuous and harmonic series).
31-- `src/core/`: params schema, author panel, audio context, and the composition interface.
32-- `src/compositions/`: one folder per track (`schema.ts`, `defaults.json`, `piece.ts`), listed in `index.ts`.
33-- `src/compositions/c01-poincare/orbitWorker.ts`: background orbit portrait, run in short work slices that use about `orbitCpu` of one core.
44+- `src/core/`: params schema (settings marked `live` apply without recomputing), author panel, audio context, and the composition interface.
45+- `src/compositions/`: one folder per track: `schema.ts`, `defaults.json`, `layout.ts` (stems and outputs), `score.ts` (worker), `view.ts` (drawing), `index.ts`. They are listed in `index.ts`, and their scores in `scores.ts`.
46+- `src/compositions/shared/orbitWorker.ts`: the background orbit portrait (pieces 1 and 2), drawing only, run in short work slices that use about `orbitCpu` of one core.
3447
3548 ## 1. poincaré
3649
@@ -38,9 +51,8 @@ The section is θ1 = 0, crossed with dθ1/dt > 0, and plotted at (θ2, p2). Each
3851
3952 - θ2 sets the pitch (signed or absolute, range, curve, scale, root)
4053 - |p2| sets the loudness
41-- θ2 sets the pan
4254
43-Notes stop at `duration − finalAt`. The last note is then held for `finalHold` and faded over `finalFade`, all within `tail`.
55+After `duration`, once the pendulum has come to rest, no more crossings register: the last note is held for `finalHold` and faded over `finalFade`, the hum fades with it, and the piece ends.
4456
4557 Behind the live crossings, a pool of energy-conserving orbits at the current energy keeps drawing the section's structure (islands and chaotic sea). They're reseeded as the energy moves.
4658
@@ -50,17 +62,13 @@ Units: energy is in units of the potential energy with both arms up, and p2 is i
5062
5163 ## 2. orbits
5264
53-Several pendulums at once (6 by default, up to 20). All follow the same energy envelope from random starts. Only the section is shown: each orbit traces its crossings in its own color (**colors**, cycling). Each orbit plays instrument slot n (cycling through 6 slots), with a register shift per slot. Orbits on the same instrument share one polyphonic instance. The note mapping, hum, and rest-based ending match composition 1. The piece ends when every orbit has come to rest and its last note has faded.
65+Several pendulums at once (8 by default, up to 20). All follow the same energy envelope from random starts. Only the section is shown: each orbit traces its crossings in its own color (**colors**, cycling). Each orbit plays instrument slot n (cycling through 6 slots), with a register shift per slot. Orbits on the same instrument share one polyphonic instance. The note mapping, hum, and rest-based ending match composition 1. The piece ends when every orbit has come to rest and its last note has faded.
5466
5567 Behind the live dots: the grey portrait of the section at the current energy, and each pendulum's *traced orbit* in its color. Each time the portrait refreshes, every pendulum's current state is followed forward with its energy frozen. That draws the orbit it is on right now: a closed loop on an island, a cloud in the chaotic sea. Traces refresh and crossfade with the portrait as the energy moves.
5668
57-**Render ahead** (on by default): each modal instrument runs in its own Web Worker. Each worker renders with the same modal-synth engine about 2 s ahead of playback and streams audio chunks to a small player worklet (`src/instruments/stream/`). The synthesis uses the device's other cores, and the buffer absorbs momentary slowdowns. The real-time audio thread only copies samples. The simulation runs 2.5 s ahead. After each step, the page sends a *horizon* ("every note before this time has been sent"), and workers never render past it, so a note can't be late; a stall becomes an underrun instead (a page stall up to about 2 s plays through). An underrun fades out and back in, a soft dip rather than a click. Final-note holds reach the renderer as timed parameter changes.
58-
59-**Voice caps** (every streamed instrument, every piece): the first time a sound is used on a device, a render worker times one ringing voice of it (cached in localStorage, `double-pendulum:voice-cost:*`). The instrument then allows only as many simultaneous notes as fit 60% of a core, stealing a released or the quietest one when more arrive. Author mode shows the caps in the readouts.
60-
61-**Device limit**: almost all the cost of this piece is audio. Before the first play on a device, a check estimates how many orbits it can handle. With render ahead, every instrument's worker renders its share of the notes as fast as it can, all in parallel, and the busiest one must stay under 60% of real time. Without it, the instruments play silently on the audio thread and their reported load must stay under 35%. If the device is over budget, fewer orbits are played. The result is cached per device and settings. When orbits are cut, the page says so ("8 of 15 orbits: reduced to what this device can play live"). In author mode, the readouts show the measured load and live **audio load**; **limit to device** turns the limit off.
69+Each distinct instrument renders in its own synth worker, in parallel; this is the heaviest piece, so it buffers longest on slow devices. Every device plays all the orbits.
6270
63-Shared machinery lives in `src/compositions/shared/`: the energy envelope, crossing → note mapping, hum control, section plot with its "fit energy" zoom, and the portrait/trace layer with its throttled worker.
71+Shared machinery lives in `src/compositions/shared/`: the energy envelope, crossing → note mapping, hum score, section plot with its "fit energy" zoom, and the portrait/trace layer with its throttled worker.
6472
6573 ## 3. divergence
6674
@@ -78,7 +86,7 @@ One pendulum, balanced straight up. It gets a tiny nudge, calibrated so it visib
7886 - **Extension notes**: whenever the pendulum is fully extended (the arms pass through a straight line, at any angle), a short violin note plays at a fixed pitch (G3), with its strength from the bob's speed. The first one is accented. The arms must bend about 3° from straight before the next extension can sound.
7987 - **Clicks**: when the outer bob crosses the vertical close to the pivot (within **near the pivot**, 25% of the length), a click plays (by default a 0.5 s Viola note at C5). With equal arms, a folded pendulum sweeps its bob right through the pivot.
8088
81-There's slight friction throughout. Over the damping section it grows smoothly to **final damping**, until the pendulum comes to rest. The last extension note rings out. The instruments render ahead in workers, and a device check limits how many extension 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%. The piano and viola get the same voice caps as every streamed instrument; the readouts show each renderer's load, underruns, and any cap.
89+There's slight friction throughout. Over the damping section it grows smoothly to **final damping**, until the pendulum comes to rest. The last extension note rings out. **overlapping notes** is the most extension notes ringing at once (a new one replaces the quietest), the same on every device.
8290
8391 ## 5. ensemble
8492
@@ -86,9 +94,9 @@ Six double pendulums hung in a row, sounding directly: each one's waveform *is*
8694
8795 - **Tuned by their shapes**: a double pendulum swinging gently has two natural frequencies, so each pendulum sounds two pitches. All six share one time scale, so their pitches come from their sizes and proportions. For each pendulum you choose its lower pitch (as a ratio to **base pitch**) and the interval up to its second pitch; `harmony.ts` solves the mass ratio that gives that interval (at the chosen **l2 / l1** shape), and the length that gives that pitch. The default is a D-major chord: D2+D3, A2+A3, D3+A3, F♯3+F♯4, A3+A4, D4+A4. The pendulums are drawn by size (length^**size drawing**, since true scale would make the highest a speck); the lowest is biggest.
8896 - **The score**: one step per word, each word the pendulums pushed together; `!` after a digit accents that push (**accent** × the energy); `.` is a rest. The default, `36 25 36 25 36 25 1!4`, alternates two chords and ends on the low pendulum, loud. **step length** is in beats at **tempo** (4 beats = a whole note, 2 s at 120 bpm). Each push adds energy along the pendulum's motion, or in a random direction from rest (the seed picks those directions, so each play mixes the two pitches differently). After the last step they ring out for **ring out**, fading over the last **fade**.
89-- Pushed hard, a pendulum's pitch sags and the tone roughens: it heads into chaos. Keys **1–6** push a pendulum by hand; **R** brings them all to rest.
97+- Pushed hard, a pendulum's pitch sags and the tone roughens: it heads into chaos.
9098
91-The six are simulated in an AudioWorklet with RK4, at least 40 steps per cycle of each one's faster mode (usually one per sample): about 5% of a desktop core.
99+The six are simulated by the score itself, sample by sample, with RK4 at least 40 steps per cycle of each one's faster mode (usually one per sample). The score sends the audio straight to the player and the pendulums' positions to the page.
92100
93101 ## Lab: the pendulum as instrument (`#/lab/edit`, not on the album)
94102
site/assets/ensembleWorklet-CYqndnPl.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-var e=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ 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 t(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 n(e,t,n){let r=e.y;if(!(t>0))return;let i=r[2],a=r[3],o=Math.hypot(i,a);if(o>1e-9)i/=o,a/=o;else{let e=n()*2*Math.PI;i=Math.cos(e),a=Math.sin(e)}let s=e.derived(),c=i*s.w1+a*s.w2,l=e.derived([r[0],r[1],i,a]),u=i*l.w1+a*l.w2,d=(-c+Math.sqrt(Math.max(0,c*c+2*u*t)))/u;r[2]+=d*i,r[3]+=d*a}function r(e,t,n,r){let{l1:i,l2:a,m2:o}=e.cfg,s=e.y,c=i+a,l=Math.sqrt(2*e.vTop/o)+1e-9,u=Math.sin(s[0]),d=Math.cos(s[0]),f=Math.sin(s[1]),p=Math.cos(s[1]);switch(t){case`x2`:return(i*u+a*f)/c;case`y2`:return-(i*d+a*p)/c;case`vx2`:return(i*d*n+a*p*r)/l;case`vy2`:return(i*u*n+a*f*r)/l;case`x1`:return u;case`vx1`:return i*d*n/l;case`θ1`:return Math.atan2(u,d)/Math.PI;case`θ2`:return Math.atan2(f,p)/Math.PI;case`θ2−θ1`:return Math.atan2(Math.sin(s[1]-s[0]),Math.cos(s[1]-s[0]))/Math.PI;case`ω1`:return n*i/l;case`ω2`:return r*a/l;case`p1`:return s[2]/(l*(1+o)*i*i+1e-9);case`p2`:return s[3]/(l*o*a*a+1e-9);case`speed2`:return Math.hypot(i*d*n+a*p*r,i*u*n+a*f*r)/l}}var i=class{x=0;y=0;run(e,t){let n=e-this.x+t*this.y;return this.x=e,this.y=n,n}},a=class extends AudioWorkletProcessor{s=null;v=[];rand=t(777);seed=0;clock=0;step=0;trailW=0;count=0;sinceSnap=0;constructor(){super();for(let t=0;t<6;t++){let t=new e({m1:1,m2:1,l1:1,l2:1,g:1});t.controlled=!1,this.v.push({p:t,dc:new i,trail:/* @__PURE__ */ new Float32Array(384),struck:1e9})}this.port.onmessage=e=>{let r=e.data;if(r.type===`settings`){this.s=r.s,r.s.seed!==this.seed&&(this.seed=r.s.seed,this.rand=t(r.s.seed));for(let e=0;e<6;e++){let t=this.v[e].p.cfg,n=r.s.voices[e];t.m1=1,t.g=1,t.m2=n.m2,t.l1=n.l1,t.l2=n.l2}}else if(r.type===`strike`){let e=this.v[r.i];e&&this.s&&(n(e.p,this.s.pulseAdds*e.p.vTop,this.rand),e.struck=0)}else if(r.type===`reset`)for(let e of this.v)e.p.y.fill(0)}}process(e,t){let i=t[0],a=i[0],o=i[1]??i[0],s=this.s;if(!s)return!0;let c=a.length,l=Math.max(1,s.stepSec*sampleRate),u=s.startDelay*sampleRate,d=1-2*Math.PI*s.dcCut/sampleRate,f=this.v.map((e,t)=>{let n=s.voices[t],r=s.k,i=r/sampleRate,a=Math.max(1,Math.ceil(40*n.upperHz/sampleRate)),o=(s.spread*(2*t/5-1)+1)*Math.PI/4;return e.p.damping=n.ringTime>0?13.8156/(n.ringTime*r):0,{h:i/a,sub:a,gl:Math.cos(o)*n.level,gr:Math.sin(o)*n.level}});for(let e=0;e<c;e++){if(this.step<s.score.length&&this.clock>=u+this.step*l){for(let{i:e,add:t}of s.score[this.step]){let r=this.v[e];r&&(n(r.p,t*r.p.vTop,this.rand),r.struck=0)}this.step++}this.clock++;let t=0,i=0;for(let e=0;e<6;e++){let n=this.v[e],a=f[e],o=n.p;for(let e=0;e<a.sub;e++)o.step(a.h);Number.isFinite(o.y[0])||o.y.fill(0);let c=o.derived(),l=Math.tanh(s.gain*n.dc.run(r(o,s.signal,c.w1,c.w2),d));t+=a.gl*l,i+=a.gr*l}a[e]=t,o[e]=i;for(let e of this.v)e.struck++;if(++this.count%3==0){for(let e of this.v){let t=e.p.y,n=e.p.cfg,r=2*this.trailW;e.trail[r]=n.l1*Math.sin(t[0])+n.l2*Math.sin(t[1]),e.trail[r+1]=n.l1*Math.cos(t[0])+n.l2*Math.cos(t[1])}this.trailW=(this.trailW+1)%192}}if(this.sinceSnap+=c,this.sinceSnap>=sampleRate/30){this.sinceSnap=0;let e=/* @__PURE__ */ new Float32Array(2304);this.v.forEach((t,n)=>{let r=n*2*192;e.set(t.trail.subarray(2*this.trailW),r),e.set(t.trail.subarray(0,2*this.trailW),r+2*(192-this.trailW))});let t=/* @__PURE__ */ new Float32Array(24);this.v.forEach((e,n)=>{let r=e.p.y,i=e.p.cfg,a=i.l1*Math.sin(r[0]),o=i.l1*Math.cos(r[0]);t.set([a,o,a+i.l2*Math.sin(r[1]),o+i.l2*Math.cos(r[1])],4*n)});let n={type:`snap`,joints:t,struck:this.v.map(e=>e.struck/sampleRate),time:this.clock/sampleRate,step:this.step,energy:this.v.map(e=>e.p.energyNorm()),trails:e};this.port.postMessage(n,[e.buffer,t.buffer])}return!0}};registerProcessor(`pendulum-ensemble`,a);
\ No newline at end of file
site/assets/index-C8mMpV0u.css →site/assets/index-BFl0mzg8.cssrenamed+1−1View file
@@ -1 +1 @@
1-:root{--bg:#0b0b0b;--fg:#d8d8d8;--dim:#2e2e2e;--muted:#777;--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark}*{box-sizing:border-box}html,body{background:var(--bg);color:var(--fg);margin:0}body{font:14px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}a{color:var(--fg);text-decoration:none}a:hover{text-decoration:underline}button{font:inherit;color:var(--fg);border:1px solid var(--dim);cursor:pointer;background:0 0;padding:2px 10px}button:hover{border-color:var(--muted)}.album{max-width:640px;margin:15vh auto;padding:0 16px}.album h1{margin:0 0 24px;font-size:18px;font-weight:400}.tracks{padding-left:1.5em}.page{min-height:100vh;min-height:100dvh;display:flex}.stage{min-width:0;height:100vh;flex-direction:column;flex:1;gap:12px;height:100dvh;padding:16px;display:flex}header{color:var(--muted)}.notice{color:var(--muted);min-height:1.4em;margin-top:-6px;font-size:12px}header a{color:var(--muted)}.sep{color:var(--dim)}.view{flex:1;justify-content:center;align-items:center;min-height:0;display:flex;position:relative;overflow:hidden}.view canvas{flex:none;display:block}@media (max-width:720px){.page{flex-direction:column}}.big-play{border:1px solid var(--muted);width:88px;height:88px;color:var(--fg);cursor:pointer;background:#0b0b0b8c;border-radius:50%;margin:auto;padding:0 0 0 6px;font-size:30px;line-height:1;position:absolute;inset:0}.big-play:hover{border-color:var(--fg)}.big-play[hidden]{display:none}.transport{align-items:center;gap:12px;display:flex}.transport .play{min-width:64px}.progress{background:var(--dim);flex:1;height:1px;position:relative}.progress.seekable{cursor:pointer;background:linear-gradient(var(--dim), var(--dim)) center / 100% 1px no-repeat;height:9px}.progress .bar{background:var(--fg);width:0;height:1px;margin-top:-.5px;position:absolute;top:50%;left:0}.edit{color:var(--muted)}.author{border-left:1px solid var(--dim);flex:none;width:360px;height:100vh;padding:12px;font-size:12px;position:sticky;top:0;overflow-y:auto}@media (max-width:720px){.author{border-left:none;border-top:1px solid var(--dim);width:auto;height:auto;position:static}}.author .actions{flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:10px;display:flex}.author .status{color:var(--muted)}.author fieldset{border:none;border-top:1px solid var(--dim);margin:10px 0 0;padding:6px 0 0}.author legend{color:var(--muted);padding:0 6px 0 0}.author .row{grid-template-columns:110px 1fr 64px 36px;align-items:center;gap:6px;margin:3px 0;display:grid}.author .row>span:first-child{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}:is(.author .row:has(select),.author .row:has(input[type=checkbox])){grid-template-columns:110px 1fr}.author .row:has(select) select{justify-self:start}.author .row:has(input[type=checkbox]) input{justify-self:start}.author>.row{grid-template-columns:110px 80px}.author input[type=number],.author select{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--dim);width:100%;padding:1px 3px}.author input[type=range]{width:100%;accent-color:var(--muted)}.author .unit{color:var(--muted)}.readouts{color:var(--muted);grid-template-columns:110px 1fr;gap:2px 6px;margin:8px 0;display:grid}.readouts dt,.readouts dd{margin:0}.readouts dd{color:var(--fg)}.author .row.text{grid-template-columns:110px 1fr;align-items:start}.author textarea{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--dim);resize:vertical;width:100%;font-size:11px}
1+:root{--bg:#0b0b0b;--fg:#d8d8d8;--dim:#2e2e2e;--muted:#777;--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark}*{box-sizing:border-box}html,body{background:var(--bg);color:var(--fg);margin:0}body{font:14px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}a{color:var(--fg);text-decoration:none}a:hover{text-decoration:underline}button{font:inherit;color:var(--fg);border:1px solid var(--dim);cursor:pointer;background:0 0;padding:2px 10px}button:hover{border-color:var(--muted)}.album{max-width:640px;margin:15vh auto;padding:0 16px}.album h1{margin:0 0 24px;font-size:18px;font-weight:400}.tracks{padding-left:1.5em}.page{min-height:100vh;min-height:100dvh;display:flex}.stage{min-width:0;height:100vh;flex-direction:column;flex:1;gap:12px;height:100dvh;padding:16px;display:flex}header{color:var(--muted)}.notice{color:var(--muted);min-height:1.4em;margin-top:-6px;font-size:12px}header a{color:var(--muted)}.sep{color:var(--dim)}.view{flex:1;justify-content:center;align-items:center;min-height:0;display:flex;position:relative;overflow:hidden}.view canvas{flex:none;display:block}@media (max-width:720px){.page{flex-direction:column}}.big-play{border:1px solid var(--muted);width:88px;height:88px;color:var(--fg);cursor:pointer;background:#0b0b0b8c;border-radius:50%;margin:auto;padding:0 0 0 6px;font-size:30px;line-height:1;position:absolute;inset:0}.big-play:hover{border-color:var(--fg)}.big-play[hidden]{display:none}.transport{align-items:center;gap:12px;display:flex}.transport .play{min-width:64px}.progress{background:var(--dim);flex:1;height:1px;position:relative}.progress.seekable{cursor:pointer;background:linear-gradient(var(--dim), var(--dim)) center / 100% 1px no-repeat;height:9px}.progress .bar{background:var(--fg);width:0;height:1px;margin-top:-.5px;position:absolute;top:50%;left:0}.edit{color:var(--muted)}.author{border-left:1px solid var(--dim);flex:none;width:360px;height:100vh;padding:12px;font-size:12px;position:sticky;top:0;overflow-y:auto}@media (max-width:720px){.author{border-left:none;border-top:1px solid var(--dim);width:auto;height:auto;position:static}}.author .actions{flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:10px;display:flex}.author .status{color:var(--muted)}.author fieldset{border:none;border-top:1px solid var(--dim);margin:10px 0 0;padding:6px 0 0}.author legend{color:var(--muted);padding:0 6px 0 0}.author .row{grid-template-columns:110px 1fr 64px 36px;align-items:center;gap:6px;margin:3px 0;display:grid}.author .row>span:first-child{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}:is(.author .row:has(select),.author .row:has(input[type=checkbox])){grid-template-columns:110px 1fr}.author .row:has(select) select{justify-self:start}.author .row:has(input[type=checkbox]) input{justify-self:start}.author>.row{grid-template-columns:110px 80px}.author input[type=number],.author select{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--dim);width:100%;padding:1px 3px}.author input[type=range]{width:100%;accent-color:var(--muted)}.author .unit{color:var(--muted)}.readouts{color:var(--muted);grid-template-columns:110px 1fr;gap:2px 6px;margin:8px 0;display:grid}.readouts dt,.readouts dd{margin:0}.readouts dd{color:var(--fg)}.author .row.text{grid-template-columns:110px 1fr;align-items:start}.author textarea{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--dim);resize:vertical;width:100%;font-size:11px}.buffering{pointer-events:none;flex-direction:column;justify-content:center;align-items:center;gap:8px;width:88px;height:88px;margin:auto;display:flex;position:absolute;inset:0}.buffering[hidden]{display:none}.buffering .spinner{border:1px solid var(--dim);border-top-color:var(--fg);border-radius:50%;width:28px;height:28px;animation:1s linear infinite spin}.buffering .fill{color:var(--muted);font-size:11px}@keyframes spin{to{transform:rotate(360deg)}}
site/assets/index-D9r0IF3O.jsadded+2−0View file
@@ -0,0 +1,2 @@
1+(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=48e3,t=null;async function n(){if(!t){let n;try{n=new AudioContext({latencyHint:`playback`,sampleRate:e})}catch{n=new AudioContext({latencyHint:`playback`})}let r=n.createGain(),i=n.createDynamicsCompressor();i.threshold.value=-6,i.knee.value=6,i.ratio.value=12,i.attack.value=.003,i.release.value=.25,r.connect(i).connect(n.destination),t={ctx:n,input:r}}return t.ctx.state!==`running`&&await t.ctx.resume(),t}function r(e){return 10**(e/20)}function i(e){let t={};for(let n of e)t[n.key]=n.default;return t}function a(e,...t){let n=i(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 o(e,t){let n={};for(let r of e)n[r.key]=t[r.key];return JSON.stringify(n,null,2)+`
2+`}var s=1e3;function c(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))*s)}function l(e,t){let n=t/s,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 u(e){return String(Number(e.toPrecision(4)))}function d(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function f(e){let t=d(`aside`,{className:`author`}),n=[],r=(t,n)=>{e.set({...e.get(),[t]:n})},i=d(`span`,{className:`status`}),f=e=>{i.textContent=e,window.setTimeout(()=>{i.textContent===e&&(i.textContent=``)},2e3)},p=d(`button`,{textContent:`copy config`});p.onclick=async()=>{let t=o(e.schema,e.get());try{await navigator.clipboard.writeText(t),f(`copied`)}catch{window.prompt(`copy:`,t)}};let m=d(`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(a(e.schema,JSON.parse(t))),y(),f(`pasted`)}catch{f(`not valid JSON`)}};let h=d(`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(d(`div`,{className:`actions`},p,m,h,i));let g=d(`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(d(`label`,{className:`row`},d(`span`,{textContent:`start at (s)`}),g));let _=d(`dl`,{className:`readouts`});t.append(_);let v=new Map;for(let i of e.schema){let a=v.get(i.group);a||(a=d(`fieldset`,{},d(`legend`,{textContent:i.group})),v.set(i.group,a),t.append(a));let o=d(`label`,{className:`row`},d(`span`,{textContent:i.label,title:i.hint??``}));if(i.kind===`number`){let t=d(`input`,{type:`range`,min:`0`,max:String(s),step:`1`}),a=d(`input`,{type:`number`,step:`any`}),f=d(`span`,{className:`unit`,textContent:i.unit??``});t.oninput=()=>{let e=l(i,Number(t.value));a.value=u(e),r(i.key,e)},a.onchange=()=>{let e=Number(a.value);Number.isFinite(e)&&(t.value=String(c(i,e)),r(i.key,e))},n.push(()=>{let n=e.get()[i.key];t.value=String(c(i,n)),a.value=u(n)}),o.append(t,a,f)}else if(i.kind===`select`){let t=d(`select`);for(let e of i.options)t.append(d(`option`,{value:e,textContent:e}));t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),o.append(t)}else if(i.kind===`text`){let t=d(`textarea`,{rows:3,spellcheck:!1,placeholder:i.hint??``});t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),o.classList.add(`text`),o.append(t)}else{let t=d(`input`,{type:`checkbox`});t.onchange=()=>r(i.key,t.checked),n.push(()=>t.checked=e.get()[i.key]),o.append(t)}a.append(o)}function y(){for(let e of n)e()}function b(){let t=e.readouts();_.replaceChildren(...Object.entries(t).flatMap(([e,t])=>[d(`dt`,{textContent:e}),d(`dd`,{textContent:t})]))}return y(),b(),{el:t,sync:y,updateReadouts:b}}function p(){return 1+Math.floor(Math.random()*999999)}var m=(e,t)=>e[t],h=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,g=(...e)=>t=>e.includes(t.geometry),_=(...e)=>t=>e.includes(t.exciter),v=[`bow`,`reed`,`selfosc`,`noise`],y=[[`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`]],b=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function x(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:y,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:b,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 S=[{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:g(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:g(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:g(`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&&h(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:h},{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:_(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:_(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:_(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:_(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:_(`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:_(`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:_(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:_(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:_(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:_(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:_(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:_(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:_(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:_(...v)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:_(...v)},{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},...x(1),...x(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:h},{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`}];Object.fromEntries(S.map(e=>[e.id,e]));var C=Object.fromEntries(S.map(e=>[e.id,e.def]));S.filter(e=>e.model).map(e=>e.id);var w=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=m(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=m(e,`delayMix`);n(this.delaySend.gain,i);let a=m(e,`delayTime`)/1e3;n(this.dL.delayTime,a),n(this.dR.delayTime,a),n(this.fbL.gain,m(e,`delayFb`)),n(this.fbR.gain,m(e,`delayFb`));let o=m(e,`reverbMix`);n(this.revSend.gain,o),n(this.dry.gain,r>0?1/(1+2*r):1),n(this.master.gain,10**(m(e,`volume`)/20));let s=m(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}};function T(e,t,n,r,i){if(!r){t.connect(n);return}if(i===`own`){let i=new w(e,n);t.connect(i.input),i.set(r);return}let a=e.createGain();if(a.gain.value=10**(r.volume/20),t.connect(a).connect(n),i!==`none`){let n=e.createGain();n.gain.value=r.reverbMix*a.gain.value,t.connect(n).connect(i.send)}}var E=class{input;conv;constructor(e,t,n){this.input=e.createGain(),this.conv=e.createConvolver(),this.conv.buffer=D(e,n),this.input.connect(this.conv).connect(t)}dispose(){this.input.disconnect(),this.conv.disconnect()}};function D(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 O=class{tracks=new Map;events=[];infos=[];add(e,t,n){if(!n.length)return;let r=this.tracks.get(e);r||this.tracks.set(e,r=[]),r.push({t0:n[0],t1:n[n.length-t],stride:t,data:n})}addEvents(e){for(let t of e)this.events.push(t)}addInfo(e,t){this.infos.push({t:e,info:t})}info(e){let t={};for(let n of this.infos)n.t<=e&&(t=n.info);return t}trim(e){for(let t of this.tracks.values())for(;t.length>1&&t[1].t0<=e&&t[0].t1<e;)t.shift();let t=0;for(;t<this.events.length&&this.events[t].t<e;)t++;for(t>0&&this.events.splice(0,t);this.infos.length>1&&this.infos[1].t<=e;)this.infos.shift()}last(e){let t=this.tracks.get(e);return t?.length?t[t.length-1].t1:-1/0}at(e,t,n){let r=this.tracks.get(e);if(!r?.length)return null;let i=r.length-1;for(;i>0&&r[i].t0>t;)i--;let a=r[i],o=a.stride,s=a.data.length/o,c=a.data,l=0,u=s-1;if(t<=c[0])u=0;else if(t>=c[(s-1)*o])l=u=s-1;else for(;u-l>1;){let e=l+u>>1;c[e*o]<=t?l=e:u=e}let d=l*o,f=u*o,p=c,m=c;l===u&&l===s-1&&i+1<r.length&&t>c[d]&&(m=r[i+1].data,f=0);let h=p[d],g=m[f],_=g>h?Math.min(1,Math.max(0,(t-h)/(g-h))):0;for(let e=1;e<o;e++)n[e-1]=p[d+e]+_*(m[f+e]-p[d+e]);return n}rows(e,t,n,r){let i=this.tracks.get(e);if(i)for(let e of i){if(e.t1<t)continue;if(e.t0>n)break;let i=e.stride,a=e.data;for(let e=0;e<a.length;e+=i){let i=a[e];if(!(i<t)){if(i>n)break;r(a,e)}}}}},k=new URL(`player-CFiFcj0f.js`,import.meta.url).href,ee=4,te=new WeakMap,ne=class{store=new O;start;seed;state=`loading`;endT=null;error=null;fill=0;rebuffers=0;ahead=0;ready;ctx;layout;workers=[];node=null;master;levels=[];pans=[];reverb=null;status=null;disposed=!1;estimatedEnd;constructor(e,t,n,r,i,a,o,s){this.ctx=e,this.start=a,this.seed=i,this.layout=o,this.estimatedEnd=s,this.master=e.createGain(),this.master.connect(t),this.ready=this.open(n,r)}async open(t,n){let r=this.ctx,i=te.get(r);if(i||te.set(r,i=r.audioWorklet.addModule(k)),await i,this.disposed)return;let{stems:a,outputs:o}=this.layout,s={stems:a.length,outputs:o.length,route:a.map(e=>e.output),startFrame:Math.round(this.start*e),estimatedEnd:Math.round(this.estimatedEnd*e)},c=new AudioWorkletNode(r,`stream-player`,{numberOfInputs:0,numberOfOutputs:o.length,outputChannelCount:o.map(()=>2),processorOptions:s});this.node=c,o.some(e=>e.effects===`shared`)&&(this.reverb=new E(r,this.master,this.layout.reverbTime??3)),o.forEach((e,t)=>{let i=r.createGain();i.gain.value=10**(e.level(n)/20),c.connect(i,t);let a=i,o=null;e.pan&&(o=r.createStereoPanner(),o.pan.value=e.pan(n),i.connect(o),a=o),T(r,a,this.master,e.sound,e.effects===`shared`?{send:this.reverb.input}:e.effects),this.levels.push(i),this.pans.push(o)}),c.port.onmessage=e=>this.onStatus(e.data);let l=Math.max(0,this.start-ee),u=[],d=[];a.forEach((t,n)=>{if(t.kind!==`synth`){d.push(null);return}let r=new Worker(new URL(new URL(`synthWorker-ByLtHWda.js`,import.meta.url).href,``+import.meta.url),{type:`module`});this.workers.push(r);let i=new MessageChannel,a=new MessageChannel;d.push(i.port1),u.push(a.port2);let o={type:`init`,sound:t.sound??{},fromFrame:Math.floor(l*e/128)*128,sendFrame:Math.round(this.start*e),stem:n,scorePort:i.port2,playerPort:a.port1,slow:Number(new URLSearchParams(location.search).get(`slow`))||void 0};r.postMessage(o,[i.port2,a.port1]),r.onerror=e=>this.fail(`instrument: ${e.message}`)});let f=new Worker(new URL(new URL(`scoreWorker-B3-6tjqi.js`,import.meta.url).href,``+import.meta.url),{type:`module`});this.workers.push(f);let p=new MessageChannel;u.push(p.port2),f.onmessage=e=>this.onScore(e.data),f.onerror=e=>this.fail(`score: ${e.message}`);let m={type:`init`,comp:t,P:n,seed:this.seed,start:this.start,from:l,synthPorts:d,playerPort:p.port1};f.postMessage(m,[...d.filter(e=>!!e),p.port1]),c.port.postMessage({type:`ports`,ports:u},u),this.state=`buffering`}onScore(e){e.type===`frames`?this.store.add(e.track,e.stride,e.data):e.type===`events`?this.store.addEvents(e.events):e.type===`info`?this.store.addInfo(e.t,e.info):e.type===`end`?this.endT=e.t:e.type===`error`&&this.fail(e.message)}onStatus(e){this.status=e,this.state!==`error`&&(this.state=e.state,this.fill=e.fill,this.rebuffers=e.rebuffers,this.ahead=e.ahead)}fail(e){this.state=`error`,this.error=e,console.error(e)}time(){let t=this.status;if(!t)return this.start;let n=t.playhead;t.state===`playing`&&(n+=Math.min(4096,Math.max(0,this.ctx.currentTime*e-t.at)));let r=(this.ctx.outputLatency||0)+(this.ctx.baseLatency||0);return Math.max(this.start,n/e-r)}update(e){let t=this.ctx.currentTime;this.layout.outputs.forEach((n,r)=>{this.levels[r]?.gain.setTargetAtTime(10**(n.level(e)/20),t,.05),n.pan&&this.pans[r]?.pan.setTargetAtTime(n.pan(e),t,.05)})}dispose(){if(this.disposed)return;this.disposed=!0;for(let e of this.workers)e.terminate();let e=this.ctx.currentTime,t=this.master,n=this.node,r=this.reverb;t.gain.setTargetAtTime(0,e,.02),window.setTimeout(()=>{n?.disconnect(),n?.port.close(),r?.dispose(),t.disconnect()},200)}},re=400;function A(e,t,n){let r=e.view(t,n),i=e.schema.filter(e=>!e.live).map(e=>e.key),a=e=>JSON.stringify(i.map(t=>e[t])),o=null,s=null,c=``,l=null,u=0,d=null,f=0,m=0,h=null,g=window.setInterval(()=>l?.trim(y.now()-r.keep(n())),1e3);function _(t,r,i){let u=n();s?.dispose(),o=t,i&&f||(f=u.seed>0?Math.round(u.seed):p()),s=new ne(t.ctx,t.input,e.id,u,f,Math.max(0,r),e.layout(u),e.estimateLength(u)),c=a(u),l=s.store,d=null,h=null,m=0}function v(){s&&=(u=s.time(),s.endT!==null&&(d=s.endT),s.dispose(),null)}let y={get playing(){return s!==null},async start(e,t){_(e,t,!1),await s.ready},stop:v,seek(e){o&&_(o,e,!0)},draw(){let e=n();if(s){if(s.state===`error`)h=`something went wrong computing this piece; try play again`,v();else if(s.state===`ended`){let e=s.endT??s.time();v(),u=e,y.onEnded?.()}else if(s.update(e),a(e)!==c){let e=performance.now();m?e>=m&&o&&_(o,s.time(),!0):m=e+re}else m=0}let t=y.now();l?.trim(t-r.keep(e)),r.draw(t,l,s?.state===`playing`)},now:()=>s?s.time():u,length:()=>s?.endT??d??e.estimateLength(n()),status:()=>({buffering:s!==null&&(s.state===`loading`||s.state===`buffering`),fill:s?.fill??0}),notice:()=>h,readouts(){let e=y.now();return{time:`${e.toFixed(1)} / ${y.length().toFixed(1)} s`,buffer:s?`${s.state}, ${s.ahead.toFixed(1)} s ahead, ${s.rebuffers} pause${s.rebuffers===1?``:`s`}`:`–`,"seed used":f?String(f):`–`,...l?.info(e)??{},...r.readouts?.(e,l)??{}}},dispose(){v(),window.clearInterval(g),r.dispose?.(),t.replaceChildren()}};return y}var ie={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,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},j={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},M=[{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:{...j,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...j,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:{...j,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...j,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:{...j,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 ae(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}}var oe=[`bow`,`reed`,`selfosc`,`noise`],N=[...M.map(e=>`modal: ${e.name}`),`modal: custom`],se=[...M.filter(e=>{let t={...C,...e.p};return oe.includes(t.exciter)||t.fbGain>0}).map(e=>`modal: ${e.name}`),`modal: custom`];function P(e,t,n={}){let r=e===`modal: custom`?ae(t):M.find(t=>`modal: ${t.name}`===e)?.p;return{...C,...r??{},...n}}var F=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function ce(e){let t=P(e.noteInstrument,e.modalCustom),n=P(e.humInstrument,e.humCustom,{voices:1});return{stems:[{kind:`synth`,sound:t,output:0},{kind:`synth`,sound:n,output:1}],outputs:[{effects:`own`,sound:t,level:e=>e.notesLevel},{effects:`own`,sound:n,level:e=>e.humLevel}]}}function le(e){return e.duration+.5+e.finalHold+e.finalFade+.3}var I=[{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:`modal: Nylon harp`,options:N,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:Object.keys({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})},{group:`notes`,key:`root`,label:`root`,kind:`select`,default:`D`,options:[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`]},{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`,live:!0},{group:`notes`,key:`noteLength`,label:`length`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`},{group:`hum`,key:`humInstrument`,label:`instrument`,kind:`select`,default:`modal: Clarinet-ish`,options:se,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`,live:!0},{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`,...F],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`,...F]},{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`,live:!0},{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)`,live:!0},{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`,live:!0},{group:`visual`,key:`fade`,label:`point fade`,kind:`number`,default:10,min:.2,max:120,log:!0,unit:`s`,live:!0},{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`,live:!0},{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`,live:!0},{group:`visual`,key:`plotP`,label:`fixed p2 range`,kind:`number`,default:1.5,min:.05,max:5,log:!0,live:!0},{group:`visual`,key:`pointSize`,label:`point size`,kind:`number`,default:2,min:.5,max:8,step:.1,unit:`px`,live:!0},{group:`orbits`,key:`orbits`,label:`show orbits`,kind:`bool`,default:!0,live:!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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{group:`orbits`,key:`orbitAlpha`,label:`brightness`,kind:`number`,default:.3,min:.02,max:1,step:.01,live:!0},{group:`orbits`,key:`orbitSize`,label:`point size`,kind:`number`,default:1,min:.5,max:4,step:.1,unit:`px`,live:!0}],ue=100,de=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-CV_Zv_V1.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>=ue){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}};function L(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 R(e,t,n=`#ccc`){return getComputedStyle(e).getPropertyValue(t).trim()||n}var fe=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=L(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 z(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 pe=64,me=2,he=50;function ge(e,t){return 2*(1+e)+2*e*t}function _e(e,t){e.classList.add(`c01`);let n=document.createElement(`canvas`);e.append(n);let r=new fe(n),i=0,a=!1,o=new de(()=>i,()=>a),s=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}),c=new Float64Array(3),l=null,u=0,d=0,f=1/60;function p(t,n,r,i,o,s){let l=i.pendulumAlpha;if(l<=0)return;let u=e=>{let t=s?.at(0,e,c);return t?[t[0],t[1]]:[0,0]},d=a?i.motionBlur*f:0,p=i.lengthRatio,m=i.pendulumSize*Math.min(n,r)/2,h=.9*m/(1+p),g=8+m,_=8+m,v=1;if(d>0){let e=0,t=u(o);for(let n=1;n<=8;n++){let r=u(o-d*n/8);e+=h*(+Math.abs(r[0]-t[0])+p*Math.abs(r[1]-t[1])),t=r}v=Math.max(2,Math.min(pe,Math.ceil(e/me)))}let y=l*(v===1?1:1-.03**(1/v)),b=3*Math.cbrt(i.massRatio),x=R(e,`--fg`);t.strokeStyle=x,t.fillStyle=x,t.lineWidth=1.5,t.lineCap=`round`,t.globalAlpha=y;for(let e=0;e<v;e++){let[n,r]=u(o-d*e/Math.max(1,v-1)),i=g+h*1*Math.sin(n),a=_+h*1*Math.cos(n),s=i+h*p*Math.sin(r),c=a+h*p*Math.cos(r);t.beginPath(),t.moveTo(g,_),t.lineTo(i,a),t.lineTo(s,c),t.stroke(),t.beginPath(),t.arc(i,a,3,0,2*Math.PI),t.moveTo(s+b,c),t.arc(s,c,b,0,2*Math.PI),t.fill()}t.globalAlpha=l,t.beginPath(),t.arc(g,_,1.5,0,2*Math.PI),t.fill(),t.globalAlpha=1}return{keep:e=>4.6*e.fade+.5,draw(n,m,h){let g=t();i=n,a=h;let _=performance.now(),v=(_-d)/1e3;d=_,v>0&&v<.1&&(f+=(v-f)*.1),m!==l&&(l=m,o.reset());let y=m?.at(0,n,c),b=y?y[2]:null,x=g.massRatio,S=g.lengthRatio,C=R(e,`--fg`);_-u>he&&(u=_,o.post(h,s(g),b??0,x,S,[]));let w=r.begin(g,b,{m1:1,l1:1,g:1,m2:x,l2:S},ge(x,S),R(e,`--dim`));if(o.draw(w,n,s(g),C,()=>C),m){let e=g.fade,t=g.pointSize;for(let r of m.events){let i=n-r.t;if(i<0)break;z(w,r.th2,r.p2,i,e,t,C)}}p(w.g,w.w,w.h,g,n,m)},readouts:()=>({"orbit portrait":o.describe()}),dispose(){o.dispose(),e.classList.remove(`c01`)}}}var ve={id:`01-poincare`,schema:I,layout:ce,estimateLength:le,view:_e},ye={id:ve.id,title:`poincaré`,schema:I,defaults:ie,create:(e,t)=>A(ve,e,t)},be={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,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,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};function xe(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function Se(e){let t=[],n=[];for(let r=0;r<xe(e);r++){let i=e[`slot${r%6+1}Instrument`],a=t.indexOf(i);a<0&&(a=t.push(i)-1),n.push(a)}return{names:t,stemOf:n}}function Ce(e){let{names:t}=Se(e),n=t.map(t=>P(t,e.modalCustom)),r=P(e.humInstrument,e.humCustom,{voices:1});return{stems:[...n.map((e,t)=>({kind:`synth`,sound:e,output:t})),{kind:`synth`,sound:r,output:t.length}],outputs:[...n.map(e=>({effects:`shared`,sound:e,level:e=>e.notesLevel})),{effects:`own`,sound:r,level:e=>e.humLevel}],reverbTime:e.reverbTime}}function we(e){return e.duration+.5+e.finalHold+e.finalFade+.3}var B=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Te=[[`modal: Nylon harp`,0],[`modal: Marimba`,-1],[`modal: Vibraphone`,0],[`modal: Church bell`,-1],[`modal: Steel-string pluck`,0],[`modal: Glass harmonics`,1]],Ee=[...[`duration`,`peakTime`,`holdTime`,`energyStart`].map(e=>B(e)),B(`energyPeak`,{default:.4}),...[`riseShape`,`riseCurve`,`fallCurve`,`restEnergy`,`finalHold`,`finalFade`].map(e=>B(e)),B(`speed`,{default:40}),...[`massRatio`,`lengthRatio`,`tau`,`seed`].map(e=>B(e)),{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)`,live:!0},...Array.from({length:6},(e,t)=>[{group:`orbits`,key:`slot${t+1}Instrument`,label:`instrument ${t+1}`,kind:`select`,default:Te[t][0],options:N,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:Te[t][1],min:-3,max:3,step:1,hint:`register shift for this instrument`}]).flat(),B(`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)`},B(`scale`,{default:`dorian`}),...[`root`,`pitchSource`,`thetaRange`,`pitchLow`,`pitchHigh`,`pitchCurve`,`invertPitch`,`p2Ref`,`loudCurve`,`loudFloor`,`notesLevel`,`noteLength`].map(e=>B(e)),...I.filter(e=>e.group===`hum`),B(`fade`,{default:20,hint:`how long each live crossing dot stays visible`}),...[`plotZoom`,`zoomSmooth`,`plotP`].map(e=>B(e)),B(`pointSize`,{default:2.5}),B(`orbits`,{key:`portrait`,group:`portrait`,label:`show portrait`,hint:`grey background: the section's structure at the current energy`}),B(`orbitCount`,{key:`portraitCount`,group:`portrait`}),B(`orbitCpu`,{key:`portraitCpu`,group:`portrait`}),B(`orbitLife`,{key:`portraitLife`,group:`portrait`}),B(`orbitBand`,{key:`portraitBand`,group:`portrait`}),B(`orbitMinHold`,{key:`portraitMinHold`,group:`portrait`}),B(`orbitMaxPoints`,{key:`portraitMaxPoints`,group:`portrait`}),B(`orbitXfade`,{key:`portraitXfade`,group:`portrait`}),B(`orbitAlpha`,{key:`portraitAlpha`,group:`portrait`,default:.15}),B(`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`,live:!0},{group:`portrait`,key:`traceMax`,label:`trace length`,kind:`number`,default:1500,min:50,max:1e4,log:!0,hint:`crossings computed per orbit trace`,live:!0},{group:`portrait`,key:`traceAlpha`,label:`trace brightness`,kind:`number`,default:.75,min:.02,max:1,step:.01,live:!0},{group:`portrait`,key:`traceSize`,label:`trace point size`,kind:`number`,default:1.5,min:.5,max:4,step:.1,unit:`px`,live:!0}],De=50;function Oe(e,t){e.classList.add(`c02`);let n=document.createElement(`canvas`);e.append(n);let r=new fe(n),i=0,a=!1,o=new de(()=>i,()=>a),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=t=>{let n=String(t.colors).split(`,`).map(e=>e.trim()).filter(Boolean);return n.length?n:[R(e,`--fg`)]},l=new Float64Array(2),u=null,d=0;return{keep:e=>4.6*e.fade+.5,draw(n,f,p){let m=t();i=n,a=p,f!==u&&(u=f,o.reset());let h=xe(m);l.length!==2+5*h&&(l=new Float64Array(2+5*h));let g=f?.at(0,n,l)??null,_=m.massRatio,v=m.lengthRatio,y=performance.now();if(y-d>De){d=y;let e=[];if(g)for(let t=0;t<h;t++)g[2+5*t+4]>.5&&e.push({id:t,y:[g[2+5*t],g[3+5*t],g[4+5*t],g[5+5*t]]});o.post(p,s(m),g?g[0]:0,_,v,e)}let b=r.begin(m,g?g[1]:null,{m1:1,l1:1,g:1,m2:_,l2:v},ge(_,v),R(e,`--dim`)),x=c(m);if(o.draw(b,n,s(m),R(e,`--fg`),e=>x[e%x.length]),f){let e=m.fade,t=m.pointSize;for(let r of f.events){let i=n-r.t;if(i<0)break;z(b,r.th2,r.p2,i,e,t,x[r.o%x.length])}}},readouts:()=>({portrait:o.describe()}),dispose(){o.dispose(),e.classList.remove(`c02`)}}}var ke={id:`02-orbits`,schema:Ee,layout:Ce,estimateLength:we,view:Oe},Ae={id:ke.id,title:`orbits`,schema:Ee,defaults:be,create:(e,t)=>A(ke,e,t)},je={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,trails:!0,trailLength:3,trailWidth:1.2,armAlpha:.75,bobSize:3,saturation:35};function Me(e){let t=P(e.instrument,e.modalCustom);return{stems:[{kind:`synth`,sound:t,output:0},{kind:`synth`,sound:t,output:1}],outputs:[{effects:`shared`,sound:t,level:e=>e.notesLevel,pan:e=>-e.directionPan},{effects:`shared`,sound:t,level:e=>e.notesLevel,pan:e=>e.directionPan}],reverbTime:e.reverbTime}}function Ne(e){return e.freeTime+e.dampTime+1+e.finalHold+e.finalFade+.3}var V=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Pe=[{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`},V(`restEnergy`,{hint:`after the damping, a pendulum counts as at rest below this energy: its last note rings out`}),V(`finalHold`),V(`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`},V(`massRatio`,{group:`pendulums`}),V(`lengthRatio`,{group:`pendulums`}),V(`seed`,{group:`pendulums`,hint:`0 = a different release every play`}),{group:`notes`,key:`instrument`,label:`instrument`,kind:`select`,default:`modal: Vibraphone`,options:N},V(`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`},V(`scale`,{default:`dorian`}),V(`root`),V(`pitchLow`,{default:50}),V(`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)`},V(`loudCurve`),V(`loudFloor`),V(`notesLevel`,{default:-8,live:!0}),V(`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`,live:!0},{group:`notes`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`},{group:`visual`,key:`trails`,label:`trails`,kind:`bool`,default:!0,live:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:3,min:.2,max:20,log:!0,unit:`s`,live:!0},{group:`visual`,key:`trailWidth`,label:`trail width`,kind:`number`,default:1.2,min:.3,max:5,step:.1,unit:`px`,live:!0},{group:`visual`,key:`armAlpha`,label:`arm opacity`,kind:`number`,default:.75,min:.05,max:1,step:.01,live:!0},{group:`visual`,key:`bobSize`,label:`bob size`,kind:`number`,default:3,min:.5,max:10,step:.1,unit:`px`,live:!0},{group:`visual`,key:`saturation`,label:`color saturation`,kind:`number`,default:35,min:0,max:100,step:1,unit:`%`,live:!0}];function Fe(e,t){let n=Math.PI/180,r=e.releaseAngle*n,i=e.jitter*n;return t?[r+(2*t()-1)*i,r+(2*t()-1)*i]:[r,r]}var Ie=1/120;function Le(e,t){e.classList.add(`c03`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array,i=(e,t,n)=>`hsl(${((30+360*t/Math.max(1,n))%360).toFixed(0)} ${e.saturation}% 70%)`;return{keep:e=>e.trailLength+.5,draw(a,o){let s=t(),c=L(n),l=n.clientWidth,u=n.clientHeight;c.clearRect(0,0,l,u);let d=Math.max(1,Math.round(s.count)),f=s.lengthRatio,p=.46*Math.min(l,u)/(1+f),m=l/2,h=u/2,g=(e,t)=>{let n=m+p*1*Math.sin(e),r=h+p*1*Math.cos(e);return[n,r,n+p*f*Math.sin(t),r+p*f*Math.cos(t)]};if(s.trails&&o){let e=s.trailLength;c.lineWidth=s.trailWidth,c.lineJoin=c.lineCap=`round`;for(let t=0;t<d;t++){c.strokeStyle=i(s,t,d);for(let n=0;n<6;n++){let r=a-n*e/6,i=a-(n+1)*e/6;c.globalAlpha=.7*(1-(n+.5)/6),c.beginPath();let s=!1;o.rows(0,i-Ie,Math.min(a,r+Ie),(e,n)=>{let[,,r,i]=g(e[n+1+2*t],e[n+2+2*t]);s?c.lineTo(r,i):(c.moveTo(r,i),s=!0)}),c.stroke()}}c.globalAlpha=1}r.length!==2*d&&(r=new Float64Array(2*d));let _=o?.at(0,a,r)??null,[v,y]=Fe(s,null);c.lineWidth=1.5,c.lineCap=`round`;let b=s.bobSize;for(let e=d-1;e>=0;e--){let[t,n,r,a]=_?g(_[2*e],_[2*e+1]):g(v,y),o=i(s,e,d);c.strokeStyle=o,c.fillStyle=o,c.globalAlpha=s.armAlpha,c.beginPath(),c.moveTo(m,h),c.lineTo(t,n),c.lineTo(r,a),c.stroke(),c.globalAlpha=1,c.beginPath(),c.arc(t,n,b*.8,0,2*Math.PI),c.moveTo(r+b,a),c.arc(r,a,b,0,2*Math.PI),c.fill()}c.fillStyle=R(e,`--fg`),c.beginPath(),c.arc(m,h,1.5,0,2*Math.PI),c.fill()},dispose(){e.classList.remove(`c03`)}}}var H={id:`03-divergence`,schema:Pe,layout:Me,estimateLength:Ne,view:Le},Re={id:H.id,title:`divergence`,schema:Pe,defaults:je,create:(e,t)=>A(H,e,t)},ze={fallAfter:2.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,extInstrument:`modal: Violin`,modalCustom:``,extPitch:55,minDepth:.25,extLength:.4,firstVel:1,maxVel:.6,loudRef:.8,loudCurve:1,loudFloor:.15,notesLevel:2,maxOverlap:4,click:!0,clickInstrument:`modal: Viola`,clickPitch:72,clickLength:.5,clickMaxVel:.7,clickLevel:-8,heightNotes:!0,heightInstrument:`modal: Piano-ish`,heightLow:60,heightHigh:96,scale:`dorian`,root:`D`,heightStep:2,heightLength:.3,heightVel:.7,heightLevel:14,heightRamp:6,heightRampFrom:.5,heightFollow:.3,trails:!0,trailLength:2.5,rings:!0,motionBlur:1};function Be(e){let t=e.modalCustom,n=P(e.extInstrument,t,{voices:Math.round(e.maxOverlap)}),r=P(e.clickInstrument,t),i=P(e.heightInstrument,t);return{stems:[{kind:`synth`,sound:n,output:0},{kind:`synth`,sound:r,output:1},{kind:`synth`,sound:i,output:2}],outputs:[{effects:`own`,sound:n,level:e=>e.notesLevel},{effects:`own`,sound:r,level:e=>e.clickLevel},{effects:`own`,sound:i,level:e=>e.heightLevel}]}}function Ve(e){return e.freeTime+e.dampTime+3+e.finalHold+e.finalFade+.3}var U=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},He=[{group:`form`,key:`fallAfter`,label:`tips after`,kind:`number`,default:2.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`},U(`restEnergy`,{hint:`after the damping, the pendulum counts as at rest below this energy: the last extension note rings out`}),U(`finalHold`),U(`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`},U(`massRatio`,{group:`pendulum`}),U(`lengthRatio`,{group:`pendulum`}),U(`seed`,{group:`pendulum`,hint:`0 = a different nudge (side and shape) every play`}),{group:`extension`,key:`extInstrument`,label:`instrument`,kind:`select`,default:`modal: Violin`,options:N},U(`modalCustom`,{group:`extension`}),{group:`extension`,key:`extPitch`,label:`pitch`,kind:`number`,default:55,min:12,max:108,step:.5,unit:`midi`},{group:`extension`,key:`extLength`,label:`length`,kind:`number`,default:.4,min:.05,max:5,log:!0,unit:`s`},{group:`extension`,key:`firstVel`,label:`first note`,kind:`number`,default:1,min:.05,max:1,step:.01,hint:`strength of the first extension note (accent)`},{group:`extension`,key:`maxVel`,label:`strongest`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`strength of later extension notes at full speed`},{group:`extension`,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`},U(`loudCurve`,{group:`extension`}),U(`loudFloor`,{group:`extension`,default:.15}),U(`notesLevel`,{group:`extension`,default:2,max:18,live:!0}),{group:`extension`,key:`maxOverlap`,label:`overlapping notes`,kind:`number`,default:4,min:1,max:16,step:1,hint:`most extension notes ringing at once (a new one replaces the quietest)`},{group:`click`,key:`minDepth`,label:`near the pivot`,kind:`number`,default:.25,min:0,max:.95,step:.01,hint:`a click when the outer bob crosses the vertical within this distance of the pivot (fraction of the length)`},{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:N},{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 extension notes)`},{group:`click`,key:`clickLevel`,label:`level`,kind:`number`,default:-8,min:-48,max:6,step:.5,unit:`dB`,live:!0},{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:N},{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`},U(`scale`,{group:`height`,default:`dorian`}),U(`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:14,min:-48,max:18,step:.5,unit:`dB`,live:!0},{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,live:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:2.5,min:.2,max:20,log:!0,unit:`s`,live:!0},{group:`visual`,key:`rings`,label:`rings`,kind:`bool`,default:!0,hint:`a brief ring where each extension note (and, smaller, each click) happens`,live:!0},U(`motionBlur`)],Ue=48,We=2,Ge=.9,Ke=.35;function qe(e,t){e.classList.add(`c04`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array(2),i=0,a=1/60;return{keep:e=>Math.max(e.trailLength,Ge)+.5,draw(o,s,c){let l=t(),u=performance.now()/1e3,d=u-i;i=u,d>0&&d<.1&&(a+=(d-a)*.1);let f=L(n),p=n.clientWidth,m=n.clientHeight;f.clearRect(0,0,p,m);let h=R(e,`--fg`),g=l.lengthRatio,_=.46*Math.min(p,m)/(1+g),v=p/2,y=m/2,b=(e,t)=>{let n=v+_*1*Math.sin(e),r=y+_*1*Math.cos(e);return[n,r,n+_*g*Math.sin(t),r+_*g*Math.cos(t)]},x=e=>{let t=s?.at(0,e,r);return t?[t[0],t[1]]:[Math.PI,Math.PI]};if(l.trails&&s){let e=l.trailLength;f.strokeStyle=h,f.lineWidth=1,f.lineJoin=f.lineCap=`round`;for(let t=0;t<6;t++){let n=o-t*e/6,r=o-(t+1)*e/6;f.globalAlpha=.45*(1-(t+.5)/6),f.beginPath();let i=!1,a=0;s.rows(0,r-.01,Math.min(o,n+.01),(e,t)=>{if(a++%2)return;let[,,n,r]=b(e[t+1],e[t+2]);i?f.lineTo(n,r):(f.moveTo(n,r),i=!0)}),f.stroke()}f.globalAlpha=1}if(l.rings&&s){for(let e of s.events){if(e.kind!==`ring`)continue;let t=o-e.t,n=e.click===1,r=n?Ke:Ge;if(t<0||t>r)continue;let i=e.strength,a=v+_*e.x,s=y+_*e.y;f.strokeStyle=h,f.globalAlpha=(1-t/r)*(.4+.6*i),f.lineWidth=n?1:1.2,f.beginPath();let c=n?14:60*(.5+i);f.arc(a,s,(n?3:6)+c*Math.sqrt(t/r),0,2*Math.PI),f.stroke()}f.globalAlpha=1}let S=c?l.motionBlur*a:0,C=1;if(S>0){let e=0,t=x(o);for(let n=1;n<=8;n++){let r=x(o-S*n/8);e+=_*(+Math.abs(r[0]-t[0])+g*Math.abs(r[1]-t[1])),t=r}C=Math.max(2,Math.min(Ue,Math.ceil(e/We)))}let w=C===1?1:1-.03**(1/C),T=4*Math.cbrt(l.massRatio);f.strokeStyle=h,f.fillStyle=h,f.lineWidth=1.5,f.lineCap=`round`,f.globalAlpha=w;for(let e=0;e<C;e++){let[t,n]=x(o-S*e/Math.max(1,C-1)),[r,i,a,s]=b(t,n);f.beginPath(),f.moveTo(v,y),f.lineTo(r,i),f.lineTo(a,s),f.stroke(),f.beginPath(),f.arc(r,i,4,0,2*Math.PI),f.moveTo(a+T,s),f.arc(a,s,T,0,2*Math.PI),f.fill()}f.globalAlpha=1,f.beginPath(),f.arc(v,y,1.5,0,2*Math.PI),f.fill()},dispose(){e.classList.remove(`c04`)}}}var W={id:`04-descent`,schema:He,layout:Be,estimateLength:Ve,view:qe},Je={id:W.id,title:`descent`,schema:He,defaults:ze,create:(e,t)=>A(W,e,t)},Ye={basePitch:73.42,sizeExp:.5,trail:.35,score:`36 25 36 25 36 25 1!4`,tempo:120,stepBeats:4,pulseAdds:.08,accent:4,tail:16,seed:0,fade:6,signal:`x2`,gain:0,spread:.7,dcCut:20,level:0,ratio1:`1`,partial1:`2`,shape1:1,ring1:20,level1:0,ratio2:`3/2`,partial2:`2`,shape2:1.3,ring2:18,level2:-6,ratio3:`2`,partial3:`3/2`,shape3:.8,ring3:16,level3:-6,ratio4:`5/2`,partial4:`2`,shape4:1.6,ring4:14,level4:-6,ratio5:`3`,partial5:`2`,shape5:.7,ring5:12,level5:-6,ratio6:`4`,partial6:`3/2`,shape6:1.2,ring6:10,level6:-6};function Xe(){return{stems:[{kind:`score`,output:0}],outputs:[{effects:`none`,level:e=>e.level}]}}var Ze=.4;function Qe(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++)/[1-6]/.test(e[i])&&r.push({i:Number(e[i])-1,add:t*(e[i+1]===`!`?n:1)});return r})}var $e=e=>e.stepBeats*60/Math.max(1,e.tempo),et=e=>Ze+Qe(e.score,0,1).length*$e(e),tt=e=>et(e)+e.tail,G=[`x2`,`y2`,`vx2`,`vy2`,`x1`,`vx1`,`θ1`,`θ2`,`θ2−θ1`,`ω1`,`ω2`,`p1`,`p2`,`speed2`];function K(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function nt(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=K(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function rt(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function it(e,t,n,r,i){let a=nt(n,r),[o,s]=K(a,r),c=2*Math.PI*e*t,l=o*i/c,u=l*l;return{l1:u,l2:r*u,m2:a,lower:e*t,upper:e*t*(s/o)}}function at(e,t,n,r){let[i]=K(nt(n,r),r);return 2*Math.PI*e*t/i}var ot=`1.16/15.9/8.6/5.5/4.4/3.45/32.3/2.8/5.5/3.9/5.15/8.2.9/4.12/5.5/2.8/3.3.16/5.10/3.15/4.4.9/2.5.6.8`.split(`.`),st=[`5/4`,`4/3`,`3/2`,`5/3`,`2`,`5/2`,`3`,`4`,`5`,`6`,`8`],ct=[[`1`,`2`,1,20],[`3/2`,`2`,1.3,18],[`2`,`3/2`,.8,16],[`5/2`,`2`,1.6,14],[`3`,`2`,.7,12],[`4`,`3/2`,1.2,10]],lt=[{group:`harmony`,key:`basePitch`,label:`base pitch`,kind:`number`,default:73.42,min:20,max:1e3,log:!0,unit:`Hz`,hint:`pitch ratio 1 sounds here (D2 by default); all pendulums share one time scale, so each pitch comes from its size`},{group:`visual`,key:`sizeExp`,label:`size drawing`,kind:`number`,default:.5,min:0,max:1,step:.05,hint:`drawn size ∝ length^this (1 = true scale: two octaves = 16× the length)`,live:!0},{group:`visual`,key:`trail`,label:`trail`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`opacity of the bobs' recent paths`,live:!0},{group:`score`,key:`score`,label:`score`,kind:`text`,default:`36 25 36 25 36 25 1!4`,hint:`one step per word: the pendulums pushed together (1–6); ! after a digit = accented; . = a rest`},{group:`score`,key:`tempo`,label:`tempo`,kind:`number`,default:120,min:10,max:400,log:!0,unit:`bpm`},{group:`score`,key:`stepBeats`,label:`step length`,kind:`number`,default:4,min:.25,max:16,step:.25,unit:`beats`,hint:`4 = a whole note per step`},{group:`score`,key:`pulseAdds`,label:`push adds`,kind:`number`,default:.08,min:5e-4,max:2,log:!0,hint:`energy each push adds, in units of E_top`},{group:`score`,key:`accent`,label:`accent`,kind:`number`,default:4,min:1,max:20,log:!0,unit:`×`,hint:`an accented push (!) adds this many times the energy`},{group:`score`,key:`tail`,label:`ring out`,kind:`number`,default:16,min:1,max:120,log:!0,unit:`s`,hint:`after the last step, before the end`},{group:`score`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`pushes from rest go in random directions (the mix of each pendulum's two pitches); 0 = a new variation every play`},{group:`score`,key:`fade`,label:`fade`,kind:`number`,default:6,min:.1,max:60,log:!0,unit:`s`,hint:`the last part of the ring-out fades to silence`},{group:`sound`,key:`signal`,label:`signal`,kind:`select`,default:`x2`,options:[...G],hint:`what each pendulum contributes (bob position, velocity, angles…)`},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:0,min:-40,max:30,step:.5,unit:`dB`,hint:`per pendulum, before its soft limiter`},{group:`sound`,key:`spread`,label:`stereo spread`,kind:`number`,default:.7,min:0,max:1,step:.01},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:20,min:1,max:500,log:!0,unit:`Hz`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:0,min:-48,max:12,step:.5,unit:`dB`,live:!0},...ct.flatMap(([e,t,n,r],i)=>{let a=`pendulum ${i+1}`;return[{group:a,key:`ratio${i+1}`,label:`pitch ratio`,kind:`select`,default:e,options:ot,hint:`lower partial = base pitch × this (sets the size)`},{group:a,key:`partial${i+1}`,label:`partials`,kind:`select`,default:t,options:st,hint:`upper/lower partial interval (sets the mass ratio)`},{group:a,key:`shape${i+1}`,label:`l2 / l1`,kind:`number`,default:n,min:.2,max:5,log:!0,hint:`the pendulum's shape`},{group:a,key:`ring${i+1}`,label:`ring time`,kind:`number`,default:r,min:.05,max:60,log:!0,unit:`s`},{group:a,key:`level${i+1}`,label:`level`,kind:`number`,default:-6,min:-48,max:12,step:.5,unit:`dB`}]})];function q(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:rt(e[`ratio${n+1}`]),partial:rt(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=at(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>it(t,e.ratio,e.partial,e.shape,i))}}var ut=.012;function dt(e,t,n){let r=1.5,i=.2,a=e.reduce((e,t)=>e+r*t,0)+i*(e.length-1),o=Math.min(.92*t/a,.5*n/Math.max(...e)),s=n/2-Math.max(...e)*o/2,c=(t-a*o)/2;return{unit:o,at:e.map(e=>{let t={x:c+r/2*e*o,y:s};return c+=(r*e+i)*o,t})}}function ft(e,t){e.classList.add(`c05`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array(24),i=``,a=q(t()).built;return{keep:()=>1.5,draw(o,s){let c=t(),l=JSON.stringify([c.basePitch,...Array.from({length:6},(e,t)=>[c[`ratio${t+1}`],c[`partial${t+1}`],c[`shape${t+1}`]])]);l!==i&&(i=l,a=q(c).built);let u=L(n),d=n.clientWidth,f=n.clientHeight;u.clearRect(0,0,d,f);let p=R(e,`--fg`),m=R(e,`--muted`),h=c.sizeExp,g=a.map(e=>e.l1+e.l2),_=g.map(e=>e**+h),{unit:v,at:y}=dt(_,d,f),b=s?.at(0,o,r)??null,x=c.trail,S=[,,,,,,].fill(-1/0);if(s)for(let e of s.events)e.kind===`push`&&e.t<=o&&(S[e.i]=e.t);u.lineCap=`round`,u.lineJoin=`round`;for(let e=0;e<6;e++){let{x:t,y:n}=y[e],r=v*_[e]/g[e];if(s&&x>0){u.strokeStyle=m,u.globalAlpha=x,u.lineWidth=1,u.beginPath();let i=!1;s.rows(1,o-ut,o,(a,o)=>{let s=t+r*a[o+1+2*e],c=n+r*a[o+2+2*e];i?u.lineTo(s,c):(u.moveTo(s,c),i=!0)}),u.stroke()}let i=a[e],c=b?b.subarray(4*e,4*e+4):[0,i.l1,0,g[e]],l=t+r*c[0],d=n+r*c[1],f=t+r*c[2],h=n+r*c[3];u.globalAlpha=.6+.4*Math.max(0,1-(o-S[e])),u.strokeStyle=p,u.fillStyle=p,u.lineWidth=1.5,u.beginPath(),u.moveTo(t,n),u.lineTo(l,d),u.lineTo(f,h),u.stroke();let C=2.2*Math.cbrt(i.m2)+1;u.beginPath(),u.arc(l,d,2,0,2*Math.PI),u.moveTo(f+C,h),u.arc(f,h,C,0,2*Math.PI),u.moveTo(t+1.5,n),u.arc(t,n,1.5,0,2*Math.PI),u.fill()}u.globalAlpha=1},readouts(){let{k:e}=q(t()),n={"time scale":`${e.toFixed(0)} sim s per s`};return a.forEach((e,t)=>{n[`pendulum ${t+1}`]=`${e.lower.toFixed(1)} + ${e.upper.toFixed(1)} Hz; l1 ${e.l1.toFixed(3)}, l2 ${e.l2.toFixed(3)}, m2/m1 ${e.m2.toFixed(2)}`}),n},dispose(){e.classList.remove(`c05`)}}}var pt={id:`05-ensemble`,schema:lt,layout:Xe,estimateLength:tt,view:ft},mt={id:pt.id,title:`ensemble`,schema:lt,defaults:Ye,create:(e,t)=>A(pt,e,t)},ht={mode:`strike`,strikeEnergy:.3,energy:1,pitch:110,ringTime:4,restrike:5,swellTime:2,follow:3,left:`x2`,right:`x1`,gain:-6,dcCut:15,level:-12,massRatio:1,lengthRatio:1,trailMs:12},gt=new URL(`pendulumWorklet-BpTttuTz.js`,import.meta.url).href,_t=new WeakMap;function vt(e,t){let n=document.createElement(`canvas`);n.title=`click (or press S) to strike`,n.style.cursor=`pointer`,e.append(n);let i=null,a=null,o=null,s=null,c,l=!1,u=0,d=null,f=``,p=0,m=e=>({mode:e.mode,pitch:e.pitch,energy:e.energy,strikeEnergy:e.strikeEnergy,ringTime:e.ringTime,restrike:e.restrike,swellTime:e.swellTime,massRatio:e.massRatio,lengthRatio:e.lengthRatio,left:e.left,right:e.right,gain:r(e.gain),dcCut:e.dcCut,follow:e.follow}),h=e=>a?.port.postMessage(e),g=()=>h({type:`strike`});n.onclick=g;let _=e=>{let t=e.target;e.key!==`s`&&e.key!==`S`||t instanceof Element&&t.closest(`input, select, textarea`)||g()};window.addEventListener(`keydown`,_);function v(){if(!a||!i||!o)return;let e=t(),n=m(e),s=JSON.stringify(n);s!==f&&(f=s,h({type:`settings`,s:n})),o.gain.setTargetAtTime(r(e.level),i.ctx.currentTime,.05)}async function y(e){b();let t=++p;i=e;let n=e.ctx,r=_t.get(n);r||_t.set(n,r=n.audioWorklet.addModule(gt)),await r,t===p&&(o=n.createGain(),o.gain.value=0,s=n.createAnalyser(),s.fftSize=4096,s.smoothingTimeConstant=.6,a=new AudioWorkletNode(n,`pendulum-voice`,{numberOfInputs:0,outputChannelCount:[2]}),a.port.onmessage=e=>d=e.data,a.connect(o),o.connect(e.input),o.connect(s),f=``,v(),l=!0,u=n.currentTime,c=window.setInterval(v,50))}function b(){if(p++,c!==void 0&&window.clearInterval(c),c=void 0,l=!1,!i)return;let e=o,t=a,n=s;e&&e.gain.setTargetAtTime(0,i.ctx.currentTime,.03),window.setTimeout(()=>{t?.disconnect(),e?.disconnect(),n?.disconnect()},300),a=o=s=null}let x=new Float32Array(2048),S=null;function C(){let r=t(),a=L(n),o=n.clientWidth,c=n.clientHeight;a.clearRect(0,0,o,c);let u=R(e,`--fg`),f=R(e,`--dim`),p=R(e,`--muted`),m=c*.62;if(d){let e=d.trail,t=e.length/4,n=Math.min(t,Math.round(r.trailMs/(2/48e3*1e3))),i=1+r.lengthRatio,s=.46*Math.min(o,m)/i,c=o/2,l=m/2;a.lineWidth=1,a.strokeStyle=u,a.beginPath();for(let r=t-n;r<t;r++){let i=c+s*e[4*r+2],o=l+s*e[4*r+3];r===t-n?a.moveTo(i,o):a.lineTo(i,o)}a.globalAlpha=.8,a.stroke();let f=t-1;a.globalAlpha=1,a.strokeStyle=p,a.beginPath(),a.moveTo(c,l),a.lineTo(c+s*e[4*f],l+s*e[4*f+1]),a.lineTo(c+s*e[4*f+2],l+s*e[4*f+3]),a.stroke()}if(s){let e=(c-m)*.45,t=m+8;s.getFloatTimeDomainData(x),a.strokeStyle=u,a.lineWidth=1,a.beginPath();for(let n=0;n<1024;n++){let r=n/1023*o,i=t+e/2-x[n]*e/2;n?a.lineTo(r,i):a.moveTo(r,i)}a.stroke(),S&&S.length===s.frequencyBinCount||(S=new Float32Array(s.frequencyBinCount)),s.getFloatFrequencyData(S);let n=(c-m)*.45,r=c-4,l=i.ctx.sampleRate,d=e=>Math.log(e/20)/Math.log(1e3)*o;a.strokeStyle=f,a.beginPath();for(let e of[100,1e3,1e4])a.moveTo(d(e),r-n),a.lineTo(d(e),r);a.stroke(),a.strokeStyle=u,a.beginPath();let p=!1;for(let e=1;e<S.length;e++){let t=e*l/(2*S.length);if(t<20||t>2e4)continue;let i=Math.max(0,Math.min(1,(S[e]+110)/100)),o=d(t),s=r-i*n;p?a.lineTo(o,s):(a.moveTo(o,s),p=!0)}a.stroke()}l||(a.fillStyle=p,a.font=`12px ui-monospace, monospace`,a.fillText(`play, then click here (or press S) to strike`,8,16))}function w(){return{mode:l&&d?d.phase:`–`,energy:d?d.energy.toFixed(4):`–`,"time scale":d?`${d.k.toFixed(0)} sim s per s`:`–`,strike:`click the plot or press S`}}return{get playing(){return l},start:e=>y(e),stop:b,draw:C,now:()=>l&&i?i.ctx.currentTime-u:0,length:()=>1/0,readouts:w,dispose(){b(),window.removeEventListener(`keydown`,_),e.replaceChildren()}}}var yt={id:`lab`,title:`lab: the pendulum as instrument`,hidden:!0,schema:[{group:`play`,key:`mode`,label:`mode`,kind:`select`,default:`strike`,options:[`strike`,`sustain`,`swell`],hint:`strike: start at the energy and ring down; sustain: energy held (like bowing); swell: energy rises, then rings down`},{group:`play`,key:`strikeEnergy`,label:`strike adds`,kind:`number`,default:.3,min:5e-4,max:5,log:!0,hint:`energy each strike adds to the current motion (units of E_top, both arms up)`},{group:`play`,key:`energy`,label:`energy`,kind:`number`,default:1,min:.001,max:5,log:!0,hint:`sustain level and swell target (units of E_top). Low: nearly periodic, two inharmonic modes. ~0.3–1.5: chaos. High: regular again (rotations)`},{group:`play`,key:`pitch`,label:`pitch`,kind:`number`,default:110,min:5,max:2e3,log:!0,unit:`Hz`,hint:`the lower small-swing mode lands here (time scaling)`},{group:`play`,key:`ringTime`,label:`ring time`,kind:`number`,default:4,min:.05,max:60,log:!0,unit:`s`,hint:`damping: amplitude falls 60 dB in this time (strike and swell)`},{group:`play`,key:`restrike`,label:`restrike every`,kind:`number`,default:5,min:0,max:60,step:.1,unit:`s`,hint:`0 = strike once`},{group:`play`,key:`swellTime`,label:`swell time`,kind:`number`,default:2,min:.05,max:30,log:!0,unit:`s`},{group:`play`,key:`follow`,label:`energy follow`,kind:`number`,default:3,min:.2,max:200,log:!0,unit:`periods`,hint:`sustain/swell: how quickly the energy controller corrects`},{group:`sound`,key:`left`,label:`left signal`,kind:`select`,default:`x2`,options:[...G],hint:`x/y: bob position, v: velocity, θ: angles, ω: angular velocities, p: momenta`},{group:`sound`,key:`right`,label:`right signal`,kind:`select`,default:`x1`,options:[...G]},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:-6,min:-40,max:30,step:.5,unit:`dB`,hint:`before a soft limiter (high gain = saturated)`},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:15,min:1,max:500,log:!0,unit:`Hz`,hint:`removes constant offsets and very slow drift`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:-12,min:-48,max:6,step:.5,unit:`dB`},{group:`pendulum`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`pendulum`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`visual`,key:`trailMs`,label:`path length`,kind:`number`,default:12,min:1,max:16,step:.5,unit:`ms`,hint:`how much of the bob's recent path to draw`}],defaults:ht,create:vt},J=`double pendulum`,Y=[ye,Ae,Re,Je,mt,yt],X=document.getElementById(`app`),Z=null;function Q(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}var $={"04-crash":`04-descent`,ensemble:`05-ensemble`};for(let[e,t]of Object.entries($))try{let n=localStorage.getItem(`double-pendulum:author:${e}`);n!==null&&localStorage.getItem(`double-pendulum:author:${t}`)===null&&localStorage.setItem(`double-pendulum:author:${t}`,n),localStorage.removeItem(`double-pendulum:author:${e}`)}catch{}function bt(){Z?.(),Z=null,X.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean);if(e[0]&&$[e[0]]){location.replace(`#/${[$[e[0]],...e.slice(1)].join(`/`)}`);return}let t=Y.find(t=>t.id===e[0]);if(!t)return xt();Z=Tt(t,e[1]===`edit`)}function xt(){document.title=J;let e=Q(`ol`,{className:`tracks`});for(let t of Y)t.hidden||e.append(Q(`li`,{},Q(`a`,{href:`#/${t.id}`,textContent:t.title})));X.append(Q(`main`,{className:`album`},Q(`h1`,{textContent:J}),e))}var St=e=>`double-pendulum:author:${e.id}`;function Ct(e){try{let t=localStorage.getItem(St(e));return t?JSON.parse(t):null}catch{return null}}function wt(e,t){try{localStorage.setItem(St(e),JSON.stringify(t))}catch{}}function Tt(e,t){let r=Y.filter(e=>!e.hidden).indexOf(e)+1;document.title=`${e.title} · ${J}`;let i=()=>a(e.schema,e.defaults),o=t?a(e.schema,e.defaults,Ct(e)):i(),s=Q(`div`,{className:`view`}),c=Q(`button`,{className:`big-play`,textContent:`▶`,title:`play`});c.setAttribute(`aria-label`,`play`);let l=Q(`button`,{className:`play`,textContent:`play`}),u=Q(`div`,{className:`bar`}),d=Q(`div`,{className:`progress`},u),p=Q(`a`,{className:`edit`,href:t?`#/${e.id}`:`#/${e.id}/edit`,textContent:t?`done`:`edit`}),m=Q(`header`,{},Q(`a`,{href:`#/`,textContent:J}),Q(`span`,{className:`sep`,textContent:` / `}),Q(`span`,{textContent:e.hidden?e.title:`${r}. ${e.title}`})),h=Q(`div`,{className:`notice`}),g=Q(`div`,{className:`buffering`,hidden:!0},Q(`div`,{className:`spinner`}),Q(`div`,{className:`fill`})),_=Q(`main`,{className:`stage`},m,h,s,Q(`div`,{className:`transport`},l,d,p)),v=Q(`div`,{className:t?`page with-author`:`page`},_);X.append(v);let y=e.create(s,()=>o);s.append(c,g);let b=()=>{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`},x=new ResizeObserver(b);x.observe(s),b();let S={value:0},C=!1,w=async e=>{C=!0;try{let t=await n();await y.start(t,e)}finally{C=!1}};l.onclick=()=>y.playing?y.stop():w(t?S.value:0),c.onclick=()=>l.click(),t&&(d.classList.add(`seekable`),d.onclick=e=>{let t=d.getBoundingClientRect(),n=Math.max(0,(e.clientX-t.left)/t.width*y.length());y.playing&&y.seek?y.seek(n):w(n)});let T=null;t&&(T=f({schema:e.schema,get:()=>o,set:t=>{o=t,wt(e,t)},defaults:i,readouts:()=>y.readouts(),startAt:S}),v.append(T.el));let E=e=>{let t=e.target.tagName;e.code===`Space`&&t!==`INPUT`&&t!==`SELECT`&&t!==`BUTTON`&&(e.preventDefault(),l.click())};window.addEventListener(`keydown`,E);let D=0,O=0,k=e=>{y.draw(),l.textContent=y.playing?`stop`:`play`,c.hidden=y.playing||C;let t=y.playing?y.status?.():void 0,n=!!t?.buffering||C;g.hidden=!n,n&&(g.lastChild.textContent=`${Math.round(100*(t?.fill??0))}%`);let r=y.notice?.()??``;h.textContent!==r&&(h.textContent=r),u.style.width=`${Math.min(100,100*y.now()/y.length())}%`,T&&e-O>200&&(T.updateReadouts(),O=e),D=requestAnimationFrame(k)};return D=requestAnimationFrame(k),()=>{cancelAnimationFrame(D),window.removeEventListener(`keydown`,E),x.disconnect(),y.dispose()}}window.addEventListener(`hashchange`,bt),bt();
\ No newline at end of file
site/assets/index-DA4h_SiO.jsdeleted+0−2View file
@@ -1,2 +0,0 @@
1-(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 ue(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 de=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 fe(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 pe(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 Y(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=pe(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 de,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(ue(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=ue(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}=fe(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 Y(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":ue(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, ~2 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-CJ7uyr_q.js`,import.meta.url).href,Je=.6;function Ye(e){let t=0x811c9dc5;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return(t>>>0).toString(36)}var Xe=new Map;function Ze(e,t){let n=`double-pendulum:voice-cost:${Ye(JSON.stringify({v:1,sr:t,sound:e}))}`;try{let e=localStorage.getItem(n);if(e!==null&&Number.isFinite(Number(e)))return Promise.resolve(Number(e))}catch{}let r=Xe.get(n);return r||(r=new Promise(r=>{let i=[];for(let e=0;e<2;e+=.7)i.push({time:e,note:31+Math.round(e*10),vel:.8,len:.5});let a=new Worker(new URL(new URL(`renderWorker-8kKMa0Za.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),o=e=>{a.terminate(),Xe.delete(n);try{localStorage.setItem(n,String(e))}catch{}r(e)};a.onmessage=e=>{e.data.type===`bench`&&o(e.data.load)},a.onerror=()=>{a.terminate(),Xe.delete(n),r(0)};let s={type:`bench`,sampleRate:t,params:{...e,voices:1},notes:i,seconds:2,warmup:.5};a.postMessage(s)}),Xe.set(n,r),r)}function Qe(e,t){return e>0?Math.max(1,Math.min(t,Math.floor(Je/e))):t}var $e=2.5,et=2.3,tt=50,nt=new WeakMap;function rt(e){let t=nt.get(e);return t||(t=e.audioWorklet.addModule(qe),nt.set(e,t)),t}function it(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=Math.round(i.voices),d=u,f=null,p=(async()=>{let[e]=await Promise.all([Ze({...i,voices:1},t.sampleRate),rt(t)]);d=Qe(e,u),f=new AudioWorkletNode(t,`pcm-player`,{numberOfInputs:0,outputChannelCount:[2]}),f.connect(a);let n=new MessageChannel;f.port.postMessage({type:`port`,port:n.port2},[n.port2]);let r=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,voices:d},port:n.port1,startFrame:Math.round((t.currentTime+.05)*t.sampleRate),aheadFrames:Math.round(2*t.sampleRate)},[n.port1]),await r})(),m=e=>s({type:`synth`,msg:e}),h=[],g=new Map,_=window.setInterval(()=>{let e=t.currentTime+et,n=[];for(let t of h)t.time>e?n.push(t):(g.get(t.note)??-1/0)<=t.on&&m({type:`noteOff`,note:t.note,time:t.time});h=n},tt),v=!1;return{ready:p,load:()=>c,underruns:()=>l,voices:()=>({allowed:d,wanted:u}),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(m({type:`noteOn`,note:l,vel:Math.max(.01,Math.min(1,o)),time:e}),r.immediateRelease)return m({type:`noteOff`,note:l,time:e+c}),null;g.set(l,e);let u={note:l,on:e,time:e+c};return h.push(u),{hold(e,n,r){let o=Math.max(e,t.currentTime);if(u.time=o+n+r,v)return;v=!0;let c=n+r,l=Math.min(60,Math.max(i.t60,6*c)),f=l/i.t60;s({type:`timedParams`,time:o,params:{...i,voices:d,t60:l,hfDamp:i.hfDamp/f}}),a.gain.setValueCurveAtTime(A(1),o+Math.max(n,.005),r)}}},dispose(){window.clearInterval(_),s({type:`stop`}),window.setTimeout(()=>{o.terminate(),f?.disconnect(),a.disconnect()},1e3)}}}}function at(){let e={};for(let t of k)e[`modal: ${t.name}`]=it(t.p);return e[`modal: custom`]=it(null),e}var ot=at(),st=.4,ct=.003,lt=.15,ut=25,dt=10;function ft(e,t){e.classList.add(`c02`);let r=document.createElement(`canvas`);e.append(r);let i=new me(r),a=new de,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=lt,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,ue(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&&ot[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?$e:lt,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?st:0)-n,a.start(s,i),v=!0,K(),_=window.setInterval(K,ut))}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=ue(r,x),t=x;x+=ct/i;for(let i of l){let s=i.pend,c=s.y;s.eTarget=e*s.vTop,s.step(ct);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+dt)&&(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}=fe(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:[Y(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,Y(e,`--dim`)),d=n.fade,f=n.pointSize,p=ee(n);o.draw(u,r,s(n),Y(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":ue(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 pt={id:`02-orbits`,title:`orbits`,schema:We,defaults:Oe,create:ft},mt={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},ht=.002;function gt(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 _t(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 vt(e,t,n,r,i,a){let o=gt(e,t,n,-r/2),s=gt(e,t,n,r/2);for(let t=0;t<a;t+=ht){o.step(ht),s.step(ht);let[n,r]=_t(e,o.y),[a,c]=_t(e,s.y);if(Math.hypot(n-a,r-c)>i)return t+ht}return 1/0}function yt(e,t,n,r,i){let a=3*r+10,o=1e-15,s=.01;if(vt(e,t,n,o,i,a)<=r)return{offset:o,separatesAt:vt(e,t,n,o,i,a)};if(vt(e,t,n,s,i,a)>=r)return{offset:s,separatesAt:vt(e,t,n,s,i,a)};for(let c=0;c<16;c++){let c=Math.sqrt(o*s);vt(e,t,n,c,i,a)>r?o=c:s=c}let c=Math.sqrt(o*s);return{offset:c,separatesAt:vt(e,t,n,c,i,a)}}var bt=at(),xt=.15,St=.4,Ct=25,wt=10,Tt=1/120;function Et(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=xt,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=yt(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=gt(a,u,f,t);i.push({index:e,p:n,prevX:_t(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&&bt[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?$e:xt,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?St:0)-n,b=!0,W(),y=window.setInterval(W,Ct))}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+=ht/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(ht);let s=_t(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+wt)&&(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>=Tt&&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=pe(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-Tt||e.t>r+Tt)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=Y(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}},Dt={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, ~2 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:mt,create:Et},Ot={fallAfter:2.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,extInstrument:`modal: Violin`,modalCustom:``,extPitch:55,minDepth:.25,extLength:.4,firstVel:1,maxVel:.6,loudRef:.8,loudCurve:1,loudFloor:.15,notesLevel:2,maxOverlap:4,deviceLimit:!0,streamAudio:!0,click:!0,clickInstrument:`modal: Viola`,clickPitch:72,clickLength:.5,clickMaxVel:.7,clickLevel:-8,heightNotes:!0,heightInstrument:`modal: Piano-ish`,heightLow:60,heightHigh:96,scale:`dorian`,root:`D`,heightStep:2,heightLength:.3,heightVel:.7,heightLevel:14,heightRamp:6,heightRampFrom:.5,heightFollow:.3,trails:!0,trailLength:2.5,rings:!0,motionBlur:1};function kt(e){let t=e.extInstrument;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 At(e,t,n){let r=kt(e);if(!r)return{cap:n,perVoice:0};let i=await Ze({...r,voices:1},t);return{cap:Qe(i,n),perVoice:i}}var jt=Je,Mt=.002;function Nt(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 Pt(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 Ft(e,t,n,r,i){let a=Nt(e,t,n,1);for(let t=0;t<i;t+=Mt)if(a.step(Mt),Math.abs(Pt(e,a.y)[0])>r)return t+Mt;return 1/0}function It(e,t,n,r){let i=3*n+10,a=n=>Ft(e,n,t,r,i),o=[];for(let e=-15;e<=-.5;e+=.25)o.push({d:10**e,t:a(10**e)});let s=[...o];for(let e=0;e+1<o.length;e++){let t=o[e],r=o[e+1];if(t.t>n&&r.t<=n){for(let e=0;e<14;e++){let e=Math.sqrt(t.d*r.d),i=a(e);i>n?t={d:e,t:i}:r={d:e,t:i}}s.push(t,r)}}let c=e=>Math.abs(e.t-n),l=Math.min(...s.map(c)),u=s.filter(e=>c(e)<=l+.01*n).reduce((e,t)=>t.d<e.d?t:e);return{nudge:u.d,tipsAt:u.t}}var Lt=at(),Rt=.15,zt=.4,Bt=25,Vt=15,Ht=1/480,Ut=48,Wt=2,Gt=.9,Kt=.05,qt=.3,Jt=.35;function Yt(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=!1,_=0,v=null,y=null,b=null,x=null,S=null,C=null,w=``,T=null,E=null,D=``,O=null,k=null,A=``,j=[],M=0,N=0,P,F=!1,I=0,L=0,R=0,z=0,B=0,V=!1,H=Rt,U={d:0,ratio:1,side:1,tipsAt:0},W=null,G=!1,K=4,ee={get playing(){return F},start:fe,stop:me,draw:Oe,now:te,length:()=>Ce(t()),readouts:Ae,notice:ke,dispose(){me(),e.classList.remove(`c04`),e.replaceChildren()}};function te(){return!b||!F?B:b.ctx.currentTime-L}function ne(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=It(i,r,e.fallAfter*u,e.tipThreshold*(i.l1+i.l2));U={d:p.nudge,ratio:r,side:n,tipsAt:p.tipsAt/u},a=Nt(i,p.nudge,r,n),o=Pt(i,a.y)[0],s=a.energy(),c=Math.sqrt(2*s/i.m2),l=[],d=[],f=0,h=le(a.y[1]-a.y[0]),g=!1,_=0,v=null,y=null,he(0)}function re(){if(!b||!x)return;let e=t(),r=b.ctx;S||(S=r.createGain(),S.connect(x)),S.gain.setTargetAtTime(n(e.notesLevel),r.currentTime,.05);let i=e.extInstrument,a=`${i}\n${i===`modal: custom`?e.modalCustom:``}\n${K}`;C&&w===a||(C?.dispose(),w=a,C=(V&&Lt[i]||q[i])(r,S,{custom:e.modalCustom,overrides:{voices:K}}))}function ie(){if(!b||!x)return;let e=t(),r=b.ctx;T||(T=r.createGain(),T.connect(x)),T.gain.setTargetAtTime(n(e.clickLevel),r.currentTime,.05);let i=e.clickInstrument,a=e.click?`${i}\n${i===`modal: custom`?e.modalCustom:``}`:``;(D!==a||!E&&a)&&(E?.dispose(),E=null,D=a,a&&(E=(V&&Lt[i]||q[i])(r,T,{custom:e.modalCustom})))}function ae(){if(!b||!x)return;let e=t(),r=b.ctx;O||(O=r.createGain(),O.connect(x)),O.gain.setTargetAtTime(n(e.heightLevel),r.currentTime,.05);let i=e.heightInstrument,a=e.heightNotes?`${i}\n${i===`modal: custom`?e.modalCustom:``}`:``;(A!==a||!k&&a)&&(k?.dispose(),k=null,A=a,a&&(k=(V&&Lt[i]||q[i])(r,O,{custom:e.modalCustom})))}function ce(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 ue(e,t){let n=i.l1+i.l2,r=(n-t)/(2*n);return e.heightLow+(e.heightHigh-e.heightLow)*r}function de(e){let t=0;for(;t<j.length&&j[t]<e;)t++;return t}async function fe(e,n){me();let r=++I;b=e;let o=t(),s=e.ctx;V=!!o.streamAudio,H=V?$e:Rt;let c=Math.round(o.maxOverlap);if(K=c,o.deviceLimit){G=!0;try{W=await At(o,s.sampleRate,c),K=W.cap}finally{G=!1}if(r!==I)return}z=o.seed>0?Math.round(o.seed):m();let l=p(z);ne(o,()=>l()),j=ce(o),M=de(ue(o,Pt(i,a.y)[1])),N=0,R=0,n>0&&_e(n,!1),x=s.createGain(),x.connect(e.input),re(),ie(),ae(),await Promise.all([C?.ready,E?.ready,k?.ready]),r===I&&(L=s.currentTime+.1+(V?zt:0)-n,F=!0,we(),P=window.setInterval(we,Bt))}function me(){if(I++,P!==void 0&&window.clearInterval(P),P=void 0,F&&=(B=te(),!1),!b)return;let e=b.ctx.currentTime,t=x;t&&(t.gain.setTargetAtTime(0,e,.05),window.setTimeout(()=>t.disconnect(),600)),C?.dispose(),C=null,w=``,E?.dispose(),E=null,D=``,T=null,k?.dispose(),k=null,A=``,O=null,S=null,x=null}function he(e){a&&(l.push({t:e,th1:a.y[0],th2:a.y[1]}),u=e)}function ge(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 _e(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(;R<e;){let e=R;R+=Mt/s,m.damping=ge(r,e),m.step(Mt);let[t,a]=Pt(i,m.y);if(y===null&&j.length&&ve(e,ue(r,a),r,n),y===null&&Math.abs(a)<=p&&(o<0&&t>=0||o>0&&t<=0)){let i=e+o/(o-t)*(R-e);_++,n&&Se(i,a,r)}o=t;let b=le(m.y[1]-m.y[0]);if(Math.abs(b)>Kt&&(g=!0),y===null&&g&&(h<0&&b>=0||h>0&&b<=0)&&Math.abs(b-h)<Math.PI){let i=e+h/(h-b)*(R-e);g=!1,f++,n?be(i,r):d.push({t:i,x:t,y:a,strength:.5})}h=b,y===null&&R>=c&&(m.energyNorm()<l||R>=c+Vt)&&(y=R,n&&v&&v.handle.hold(v.when,r.finalHold,r.finalFade)),R-u>=Ht&&he(R)}}function ve(e,t,n,r){let i=qt*(j.length>1?(j[j.length-1]-j[0])/(j.length-1):1);for(;M<j.length&&t>j[M]+i;)r&&ye(e,j[M],n),M++;for(;M>0&&t<j[M-1]-i;)M--,r&&ye(e,j[M],n)}function ye(e,t,n){if(!b||!k||!a)return;let r=e+Mt/n.speed,i=L+r;if(i<b.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;k.play({when:i,freq:J(t),velocity:d,pan:0,duration:n.heightLength}),N++}function be(e,t){if(!b||!C||!a)return;let n=L+e;if(n<b.ctx.currentTime-.02)return;let r=t.extPitch,o=f===1?t.firstVel:t.maxVel*xe(t),s=C.play({when:n,freq:J(r),velocity:o,pan:0,duration:t.extLength});s&&(v={handle:s,when:n});let[c,l]=Pt(i,a.y);d.push({t:e,x:c,y:l,strength:o})}function xe(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 Se(e,t,n){if(!b||!E)return;let r=L+e;if(r<b.ctx.currentTime-.02)return;let i=n.clickMaxVel*xe(n);E.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 Ce(e){let t=e.finalHold+e.finalFade+.3;return(y??e.freeTime+e.dampTime+3)+t}function we(){if(!b||!F||!a)return;let e=t();re();let n=b.ctx.currentTime-L,r=Ce(e);if(y!==null&&n>=r){me(),B=r,ee.onEnded?.();return}ie(),ae(),_e(n+H,!0);for(let e of[C,E,k])e?.horizon?.(L+R);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-Gt-1;)d.shift()}function Te(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 Ee=0,De=1/60;function Oe(){let n=t();a||ne(n,null);let o=te(),s=performance.now()/1e3,c=s-Ee;Ee=s,c>0&&c<.1&&(De+=(c-De)*.1);let u=pe(r),f=r.clientWidth,p=r.clientHeight;u.clearRect(0,0,f,p);let m=Y(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?Jt:Gt;if(t<0||t>n)continue;let[,,r,i]=b(Te(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=F?n.motionBlur*De:0,S=1;if(x>0){let e=0,t=Te(o);for(let n=1;n<=8;n++){let r=Te(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(Ut,Math.ceil(e/Wt)))}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(Te(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 ke(){if(G)return`checking what this device can play…`;let e=t();if(!e.deviceLimit||!W||W.perVoice===0)return null;if(W.perVoice>jt)return`this device can't render the extension notes in real time; expect glitches`;let n=Math.round(e.maxOverlap);return K<n?`${K} overlapping note${K>1?`s`:``} (of ${n}): reduced to what this device can play`:null}function Ae(){let e=t(),n=te(),r=e.freeTime,i=e.dampTime,o=y!==null&&R>=y?`at rest`:f===0?`falling`:n<r?`swinging`:n<r+i?`damping`:`settling`;return{time:`${n.toFixed(1)} / ${ee.length().toFixed(0)} s`,phase:o,energy:a?`${(a.energy()/s).toFixed(3)} of start`:`–`,"extension notes":String(f),clicks:String(_),"height notes":String(N),nudge:`${U.d.toExponential(2)} rad ${U.side>0?`→`:`←`} (shape ${U.ratio.toFixed(2)}), tips at ${U.tipsAt.toFixed(1)} s`,friction:`${ge(e,n).toFixed(4)} /sim s`,"seed used":z?String(z):`–`,"overlapping notes":W?`${K} (one ringing note: ${Math.round(100*W.perVoice)}% of a core)`:String(K),"audio load":[[`extension`,C],[`click`,E],[`height`,k]].filter(([,e])=>e).map(([e,t])=>{let n=t,r=n.voices?.(),i=r&&r.allowed<r.wanted?`, ${r.allowed} of ${r.wanted} voices`:``;return`${e} ${Math.round(100*(n.load?.()??0))}%${V?`, ${n.underruns?.()??0} underruns`:``}${i}`}).join(` · `)}}return ee}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}},Xt={id:`04-descent`,title:`descent`,schema:[{group:`form`,key:`fallAfter`,label:`tips after`,kind:`number`,default:2.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 extension 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:`extension`,key:`extInstrument`,label:`instrument`,kind:`select`,default:`modal: Violin`,options:Object.keys(q)},Q(`modalCustom`,{group:`extension`}),{group:`extension`,key:`extPitch`,label:`pitch`,kind:`number`,default:55,min:12,max:108,step:.5,unit:`midi`},{group:`extension`,key:`extLength`,label:`length`,kind:`number`,default:.4,min:.05,max:5,log:!0,unit:`s`},{group:`extension`,key:`firstVel`,label:`first note`,kind:`number`,default:1,min:.05,max:1,step:.01,hint:`strength of the first extension note (accent)`},{group:`extension`,key:`maxVel`,label:`strongest`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`strength of later extension notes at full speed`},{group:`extension`,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:`extension`}),Q(`loudFloor`,{group:`extension`,default:.15}),Q(`notesLevel`,{group:`extension`,default:2,max:18}),{group:`extension`,key:`maxOverlap`,label:`overlapping notes`,kind:`number`,default:4,min:1,max:16,step:1,hint:`most extension notes ringing at once (a new one replaces the oldest)`},{group:`extension`,key:`deviceLimit`,label:`limit to device`,kind:`bool`,default:!0,hint:`measure (once per device) how many ringing extension notes it can render, and allow no more`},{group:`extension`,key:`streamAudio`,label:`render ahead`,kind:`bool`,default:!0,hint:`render the instruments in background threads, ~2 s ahead (applies on the next play)`},{group:`click`,key:`minDepth`,label:`near the pivot`,kind:`number`,default:.25,min:0,max:.95,step:.01,hint:`a click when the outer bob crosses the vertical within this distance of the pivot (fraction of the length)`},{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 extension notes)`},{group:`click`,key:`clickLevel`,label:`level`,kind:`number`,default:-8,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:14,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 extension note (and, smaller, each click) happens`},Q(`motionBlur`)],defaults:Ot,create:Yt},Zt={basePitch:73.42,sizeExp:.5,trail:.35,score:`36 25 36 25 36 25 1!4`,tempo:120,stepBeats:4,pulseAdds:.08,accent:4,tail:16,seed:0,fade:6,signal:`x2`,gain:0,spread:.7,dcCut:20,level:0,ratio1:`1`,partial1:`2`,shape1:1,ring1:20,level1:0,ratio2:`3/2`,partial2:`2`,shape2:1.3,ring2:18,level2:-6,ratio3:`2`,partial3:`3/2`,shape3:.8,ring3:16,level3:-6,ratio4:`5/2`,partial4:`2`,shape4:1.6,ring4:14,level4:-6,ratio5:`3`,partial5:`2`,shape5:.7,ring5:12,level5:-6,ratio6:`4`,partial6:`3/2`,shape6:1.2,ring6:10,level6:-6},Qt=new URL(`ensembleWorklet-CYqndnPl.js`,import.meta.url).href,$t=[`x2`,`y2`,`vx2`,`vy2`,`x1`,`vx1`,`θ1`,`θ2`,`θ2−θ1`,`ω1`,`ω2`,`p1`,`p2`,`speed2`];function en(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function tn(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=en(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function nn(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function rn(e,t,n,r,i){let a=tn(n,r),[o,s]=en(a,r),c=2*Math.PI*e*t,l=(o*i/c)**2;return{l1:l,l2:r*l,m2:a,lower:e*t,upper:e*t*(s/o)}}function an(e,t,n,r){let[i]=en(tn(n,r),r);return 2*Math.PI*e*t/i}var on=`1.16/15.9/8.6/5.5/4.4/3.45/32.3/2.8/5.5/3.9/5.15/8.2.9/4.12/5.5/2.8/3.3.16/5.10/3.15/4.4.9/2.5.6.8`.split(`.`),sn=[`5/4`,`4/3`,`3/2`,`5/3`,`2`,`5/2`,`3`,`4`,`5`,`6`,`8`],cn=new WeakMap,ln=.4;function un(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++){if(!/[1-6]/.test(e[i]))continue;let a=e[i+1]===`!`;r.push({i:Number(e[i])-1,add:t*(a?n:1)})}return r})}function dn(e,t){let r=document.createElement(`canvas`);e.append(r);let i=null,a=null,o=null,s,c=!1,l=0,u=null,d=``,f=0,p=!1,h=0;function g(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:nn(e[`ratio${n+1}`]),partial:nn(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=an(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>rn(t,e.ratio,e.partial,e.shape,i))}}let _=e=>{let{k:t,built:r}=g(e);return{voices:r.map((t,r)=>({l1:t.l1,l2:t.l2,m2:t.m2,upperHz:t.upper,ringTime:e[`ring${r+1}`],level:n(e[`level${r+1}`])})),k:t,pulseAdds:e.pulseAdds,score:un(e.score,e.pulseAdds,e.accent),stepSec:v(e),startDelay:ln,seed:h,signal:e.signal,gain:n(e.gain),dcCut:e.dcCut,spread:e.spread}},v=e=>e.stepBeats*60/Math.max(1,e.tempo),y=e=>ln+un(e.score,0,1).length*v(e),b=e=>y(e)+e.tail,x=e=>a?.port.postMessage(e),S=e=>{let t=e.target;t instanceof Element&&t.closest(`input, select, textarea`)||(/^[1-6]$/.test(e.key)?x({type:`strike`,i:Number(e.key)-1}):(e.key===`r`||e.key===`R`)&&x({type:`reset`}))};window.addEventListener(`keydown`,S);function C(){if(!a||!i||!o)return;let e=t(),r=JSON.stringify(_(e));r!==d&&(d=r,x({type:`settings`,s:_(e)}));let s=i.ctx.currentTime-l,c=b(e),u=Math.min(e.fade,e.tail),f=Math.max(0,Math.min(1,(c-s)/u));o.gain.setTargetAtTime(n(e.level)*f*f,i.ctx.currentTime,.05),s>=c&&!p&&(p=!0,T(),k.onEnded?.())}async function w(e){T();let n=++f;i=e;let r=e.ctx,g=cn.get(r);if(g||cn.set(r,g=r.audioWorklet.addModule(Qt)),await g,n!==f)return;p=!1,u=null;let _=t();h=_.seed>0?Math.round(_.seed):m(),o=r.createGain(),o.gain.value=0,a=new AudioWorkletNode(r,`pendulum-ensemble`,{numberOfInputs:0,outputChannelCount:[2]}),a.port.onmessage=e=>u=e.data,a.connect(o).connect(e.input),d=``,C(),c=!0,l=r.currentTime,s=window.setInterval(C,50)}function T(){if(f++,s!==void 0&&window.clearInterval(s),s=void 0,c=!1,!i)return;let e=o,t=a;e&&e.gain.setTargetAtTime(0,i.ctx.currentTime,.03),window.setTimeout(()=>{t?.disconnect(),e?.disconnect()},300),a=o=null}function E(e,t,n){let r=1.5,i=.2,{rows:a,rh:o,unit:s}=(a=>{let o=n/a.length,s=1/0;for(let n of a){let a=n.reduce((t,n)=>t+r*e[n],0)+i*(n.length-1);s=Math.min(s,.92*t/a,.5*o/Math.max(...n.map(t=>e[t])))}return{rows:a,rh:o,unit:s}})([[0,1,2,3,4,5]]),c=[];return a.forEach((n,a)=>{let l=(n.reduce((t,n)=>t+r*e[n],0)+i*(n.length-1))*s,u=a*o+o/2-Math.max(...n.map(t=>e[t]))*s/2,d=(t-l)/2;for(let t of n)c[t]={x:d+r/2*e[t]*s,y:u},d+=(r*e[t]+i)*s}),{unit:s,at:c}}function D(){let n=t(),i=pe(r),a=r.clientWidth,o=r.clientHeight;i.clearRect(0,0,a,o);let s=Y(e,`--fg`),c=Y(e,`--muted`),{built:l}=g(n),d=n.sizeExp,f=l.map(e=>e.l1+e.l2),p=f.map(e=>e**+d),{unit:m,at:h}=E(p,a,o),_=u?u.trails.length/12:0,v=n.trail;i.lineCap=`round`,i.lineJoin=`round`;for(let e=0;e<6;e++){let{x:t,y:n}=h[e],r=m*p[e]/f[e];if(u&&v>0){let a=e*2*_;i.strokeStyle=c,i.globalAlpha=v,i.lineWidth=1,i.beginPath();for(let e=0;e<_;e++){let o=t+r*u.trails[a+2*e],s=n+r*u.trails[a+2*e+1];e?i.lineTo(o,s):i.moveTo(o,s)}i.stroke()}let a=u?u.joints.subarray(4*e,4*e+4):[0,l[e].l1,0,f[e]],o=t+r*a[0],d=n+r*a[1],g=t+r*a[2],y=n+r*a[3],b=u?u.struck[e]:1e9;i.globalAlpha=.6+.4*Math.max(0,1-b),i.strokeStyle=s,i.fillStyle=s,i.lineWidth=1.5,i.beginPath(),i.moveTo(t,n),i.lineTo(o,d),i.lineTo(g,y),i.stroke();let x=2.2*Math.cbrt(l[e].m2)+1;i.beginPath(),i.arc(o,d,2,0,2*Math.PI),i.moveTo(g+x,y),i.arc(g,y,x,0,2*Math.PI),i.moveTo(t+1.5,n),i.arc(t,n,1.5,0,2*Math.PI),i.fill()}i.globalAlpha=1}function O(){let{k:e,built:n}=g(t()),r={keys:`1–6: push that pendulum · R: reset to rest`,score:u?`step ${u.step} of ${un(t().score,0,1).length}`:`–`,length:`${b(t()).toFixed(1)} s`,"seed used":h?String(h):`–`,"time scale":`${e.toFixed(0)} sim s per s`};return n.forEach((e,t)=>{r[`pendulum ${t+1}`]=`${e.lower.toFixed(1)} + ${e.upper.toFixed(1)} Hz; l1 ${e.l1.toFixed(3)}, l2 ${e.l2.toFixed(3)}, m2/m1 ${e.m2.toFixed(2)}${u?`; E ${u.energy[t].toFixed(2)}`:``}`}),r}let k={get playing(){return c},start:e=>w(e),stop:T,draw:D,now:()=>c&&i?i.ctx.currentTime-l:p?b(t()):0,length:()=>b(t()),readouts:O,dispose(){T(),window.removeEventListener(`keydown`,S),e.replaceChildren()}};return k}var fn=[[`1`,`2`,1,20],[`3/2`,`2`,1.3,18],[`2`,`3/2`,.8,16],[`5/2`,`2`,1.6,14],[`3`,`2`,.7,12],[`4`,`3/2`,1.2,10]],pn={id:`05-ensemble`,title:`ensemble`,schema:[{group:`harmony`,key:`basePitch`,label:`base pitch`,kind:`number`,default:73.42,min:20,max:1e3,log:!0,unit:`Hz`,hint:`pitch ratio 1 sounds here (D2 by default); all pendulums share one time scale, so each pitch comes from its size`},{group:`visual`,key:`sizeExp`,label:`size drawing`,kind:`number`,default:.5,min:0,max:1,step:.05,hint:`drawn size ∝ length^this (1 = true scale: two octaves = 16× the length)`},{group:`visual`,key:`trail`,label:`trail`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`opacity of the bobs' recent paths`},{group:`score`,key:`score`,label:`score`,kind:`text`,default:`36 25 36 25 36 25 1!4`,hint:`one step per word: the pendulums pushed together (1–6); ! after a digit = accented; . = a rest`},{group:`score`,key:`tempo`,label:`tempo`,kind:`number`,default:120,min:10,max:400,log:!0,unit:`bpm`},{group:`score`,key:`stepBeats`,label:`step length`,kind:`number`,default:4,min:.25,max:16,step:.25,unit:`beats`,hint:`4 = a whole note per step`},{group:`score`,key:`pulseAdds`,label:`push adds`,kind:`number`,default:.08,min:5e-4,max:2,log:!0,hint:`energy each push (score or keys 1–6) adds, in units of E_top`},{group:`score`,key:`accent`,label:`accent`,kind:`number`,default:4,min:1,max:20,log:!0,unit:`×`,hint:`an accented push (!) adds this many times the energy`},{group:`score`,key:`tail`,label:`ring out`,kind:`number`,default:16,min:1,max:120,log:!0,unit:`s`,hint:`after the last step, before the end`},{group:`score`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`pushes from rest go in random directions (the mix of each pendulum's two pitches); 0 = a new variation every play`},{group:`score`,key:`fade`,label:`fade`,kind:`number`,default:6,min:.1,max:60,log:!0,unit:`s`,hint:`the last part of the ring-out fades to silence`},{group:`sound`,key:`signal`,label:`signal`,kind:`select`,default:`x2`,options:[...$t],hint:`what each pendulum contributes (bob position, velocity, angles…)`},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:0,min:-40,max:30,step:.5,unit:`dB`,hint:`per pendulum, before its soft limiter`},{group:`sound`,key:`spread`,label:`stereo spread`,kind:`number`,default:.7,min:0,max:1,step:.01},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:20,min:1,max:500,log:!0,unit:`Hz`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:0,min:-48,max:12,step:.5,unit:`dB`},...fn.flatMap(([e,t,n,r],i)=>{let a=`pendulum ${i+1}`;return[{group:a,key:`ratio${i+1}`,label:`pitch ratio`,kind:`select`,default:e,options:on,hint:`lower partial = base pitch × this (sets the size)`},{group:a,key:`partial${i+1}`,label:`partials`,kind:`select`,default:t,options:sn,hint:`upper/lower partial interval (sets the mass ratio)`},{group:a,key:`shape${i+1}`,label:`l2 / l1`,kind:`number`,default:n,min:.2,max:5,log:!0,hint:`the pendulum's shape`},{group:a,key:`ring${i+1}`,label:`ring time`,kind:`number`,default:r,min:.05,max:60,log:!0,unit:`s`},{group:a,key:`level${i+1}`,label:`level`,kind:`number`,default:-6,min:-48,max:12,step:.5,unit:`dB`}]})],defaults:Zt,create:dn},mn={mode:`strike`,strikeEnergy:.3,energy:1,pitch:110,ringTime:4,restrike:5,swellTime:2,follow:3,left:`x2`,right:`x1`,gain:-6,dcCut:15,level:-12,massRatio:1,lengthRatio:1,trailMs:12},hn=new URL(`pendulumWorklet-CX1TnpQQ.js`,import.meta.url).href,gn=new WeakMap;function _n(e,t){let r=document.createElement(`canvas`);r.title=`click (or press S) to strike`,r.style.cursor=`pointer`,e.append(r);let i=null,a=null,o=null,s=null,c,l=!1,u=0,d=null,f=``,p=0,m=e=>({mode:e.mode,pitch:e.pitch,energy:e.energy,strikeEnergy:e.strikeEnergy,ringTime:e.ringTime,restrike:e.restrike,swellTime:e.swellTime,massRatio:e.massRatio,lengthRatio:e.lengthRatio,left:e.left,right:e.right,gain:n(e.gain),dcCut:e.dcCut,follow:e.follow}),h=e=>a?.port.postMessage(e),g=()=>h({type:`strike`});r.onclick=g;let _=e=>{let t=e.target;e.key!==`s`&&e.key!==`S`||t instanceof Element&&t.closest(`input, select, textarea`)||g()};window.addEventListener(`keydown`,_);function v(){if(!a||!i||!o)return;let e=t(),r=m(e),s=JSON.stringify(r);s!==f&&(f=s,h({type:`settings`,s:r})),o.gain.setTargetAtTime(n(e.level),i.ctx.currentTime,.05)}async function y(e){b();let t=++p;i=e;let n=e.ctx,r=gn.get(n);r||gn.set(n,r=n.audioWorklet.addModule(hn)),await r,t===p&&(o=n.createGain(),o.gain.value=0,s=n.createAnalyser(),s.fftSize=4096,s.smoothingTimeConstant=.6,a=new AudioWorkletNode(n,`pendulum-voice`,{numberOfInputs:0,outputChannelCount:[2]}),a.port.onmessage=e=>d=e.data,a.connect(o),o.connect(e.input),o.connect(s),f=``,v(),l=!0,u=n.currentTime,c=window.setInterval(v,50))}function b(){if(p++,c!==void 0&&window.clearInterval(c),c=void 0,l=!1,!i)return;let e=o,t=a,n=s;e&&e.gain.setTargetAtTime(0,i.ctx.currentTime,.03),window.setTimeout(()=>{t?.disconnect(),e?.disconnect(),n?.disconnect()},300),a=o=s=null}let x=new Float32Array(2048),S=null;function C(){let n=t(),a=pe(r),o=r.clientWidth,c=r.clientHeight;a.clearRect(0,0,o,c);let u=Y(e,`--fg`),f=Y(e,`--dim`),p=Y(e,`--muted`),m=c*.62;if(d){let e=d.trail,t=e.length/4,r=Math.min(t,Math.round(n.trailMs/(2/48e3*1e3))),i=1+n.lengthRatio,s=.46*Math.min(o,m)/i,c=o/2,l=m/2;a.lineWidth=1,a.strokeStyle=u,a.beginPath();for(let n=t-r;n<t;n++){let i=c+s*e[4*n+2],o=l+s*e[4*n+3];n===t-r?a.moveTo(i,o):a.lineTo(i,o)}a.globalAlpha=.8,a.stroke();let f=t-1;a.globalAlpha=1,a.strokeStyle=p,a.beginPath(),a.moveTo(c,l),a.lineTo(c+s*e[4*f],l+s*e[4*f+1]),a.lineTo(c+s*e[4*f+2],l+s*e[4*f+3]),a.stroke()}if(s){let e=(c-m)*.45,t=m+8;s.getFloatTimeDomainData(x),a.strokeStyle=u,a.lineWidth=1,a.beginPath();for(let n=0;n<1024;n++){let r=n/1023*o,i=t+e/2-x[n]*e/2;n?a.lineTo(r,i):a.moveTo(r,i)}a.stroke(),S&&S.length===s.frequencyBinCount||(S=new Float32Array(s.frequencyBinCount)),s.getFloatFrequencyData(S);let n=(c-m)*.45,r=c-4,l=i.ctx.sampleRate,d=e=>Math.log(e/20)/Math.log(1e3)*o;a.strokeStyle=f,a.beginPath();for(let e of[100,1e3,1e4])a.moveTo(d(e),r-n),a.lineTo(d(e),r);a.stroke(),a.strokeStyle=u,a.beginPath();let p=!1;for(let e=1;e<S.length;e++){let t=e*l/(2*S.length);if(t<20||t>2e4)continue;let i=Math.max(0,Math.min(1,(S[e]+110)/100)),o=d(t),s=r-i*n;p?a.lineTo(o,s):(a.moveTo(o,s),p=!0)}a.stroke()}l||(a.fillStyle=p,a.font=`12px ui-monospace, monospace`,a.fillText(`play, then click here (or press S) to strike`,8,16))}function w(){return{mode:l&&d?d.phase:`–`,energy:d?d.energy.toFixed(4):`–`,"time scale":d?`${d.k.toFixed(0)} sim s per s`:`–`,strike:`click the plot or press S`}}return{get playing(){return l},start:e=>y(e),stop:b,draw:C,now:()=>l&&i?i.ctx.currentTime-u:0,length:()=>1/0,readouts:w,dispose(){b(),window.removeEventListener(`keydown`,_),e.replaceChildren()}}}var vn={id:`lab`,title:`lab: the pendulum as instrument`,hidden:!0,schema:[{group:`play`,key:`mode`,label:`mode`,kind:`select`,default:`strike`,options:[`strike`,`sustain`,`swell`],hint:`strike: start at the energy and ring down; sustain: energy held (like bowing); swell: energy rises, then rings down`},{group:`play`,key:`strikeEnergy`,label:`strike adds`,kind:`number`,default:.3,min:5e-4,max:5,log:!0,hint:`energy each strike adds to the current motion (units of E_top, both arms up)`},{group:`play`,key:`energy`,label:`energy`,kind:`number`,default:1,min:.001,max:5,log:!0,hint:`sustain level and swell target (units of E_top). Low: nearly periodic, two inharmonic modes. ~0.3–1.5: chaos. High: regular again (rotations)`},{group:`play`,key:`pitch`,label:`pitch`,kind:`number`,default:110,min:5,max:2e3,log:!0,unit:`Hz`,hint:`the lower small-swing mode lands here (time scaling)`},{group:`play`,key:`ringTime`,label:`ring time`,kind:`number`,default:4,min:.05,max:60,log:!0,unit:`s`,hint:`damping: amplitude falls 60 dB in this time (strike and swell)`},{group:`play`,key:`restrike`,label:`restrike every`,kind:`number`,default:5,min:0,max:60,step:.1,unit:`s`,hint:`0 = strike once`},{group:`play`,key:`swellTime`,label:`swell time`,kind:`number`,default:2,min:.05,max:30,log:!0,unit:`s`},{group:`play`,key:`follow`,label:`energy follow`,kind:`number`,default:3,min:.2,max:200,log:!0,unit:`periods`,hint:`sustain/swell: how quickly the energy controller corrects`},{group:`sound`,key:`left`,label:`left signal`,kind:`select`,default:`x2`,options:[...$t],hint:`x/y: bob position, v: velocity, θ: angles, ω: angular velocities, p: momenta`},{group:`sound`,key:`right`,label:`right signal`,kind:`select`,default:`x1`,options:[...$t]},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:-6,min:-40,max:30,step:.5,unit:`dB`,hint:`before a soft limiter (high gain = saturated)`},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:15,min:1,max:500,log:!0,unit:`Hz`,hint:`removes constant offsets and very slow drift`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:-12,min:-48,max:6,step:.5,unit:`dB`},{group:`pendulum`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`pendulum`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`visual`,key:`trailMs`,label:`path length`,kind:`number`,default:12,min:1,max:16,step:.5,unit:`ms`,hint:`how much of the bob's recent path to draw`}],defaults:mn,create:_n},yn=`double pendulum`,bn=[De,pt,Dt,Xt,pn,vn],xn=document.getElementById(`app`),Sn=null;function $(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}var Cn={"04-crash":`04-descent`,ensemble:`05-ensemble`};for(let[e,t]of Object.entries(Cn))try{let n=localStorage.getItem(`double-pendulum:author:${e}`);n!==null&&localStorage.getItem(`double-pendulum:author:${t}`)===null&&localStorage.setItem(`double-pendulum:author:${t}`,n),localStorage.removeItem(`double-pendulum:author:${e}`)}catch{}function wn(){Sn?.(),Sn=null,xn.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean);if(e[0]&&Cn[e[0]]){location.replace(`#/${[Cn[e[0]],...e.slice(1)].join(`/`)}`);return}let t=bn.find(t=>t.id===e[0]);if(!t)return Tn();Sn=kn(t,e[1]===`edit`)}function Tn(){document.title=yn;let e=$(`ol`,{className:`tracks`});for(let t of bn)t.hidden||e.append($(`li`,{},$(`a`,{href:`#/${t.id}`,textContent:t.title})));xn.append($(`main`,{className:`album`},$(`h1`,{textContent:yn}),e))}var En=e=>`double-pendulum:author:${e.id}`;function Dn(e){try{let t=localStorage.getItem(En(e));return t?JSON.parse(t):null}catch{return null}}function On(e,t){try{localStorage.setItem(En(e),JSON.stringify(t))}catch{}}function kn(e,n){let r=bn.filter(e=>!e.hidden).indexOf(e)+1;document.title=`${e.title} · ${yn}`;let a=()=>i(e.schema,e.defaults),o=n?i(e.schema,e.defaults,Dn(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:yn}),$(`span`,{className:`sep`,textContent:` / `}),$(`span`,{textContent:e.hidden?e.title:`${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);xn.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,On(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`,wn),wn();
\ No newline at end of file
site/assets/orbitWorker-CMBL8zS4.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-var e=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ 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 t(e,t,n){let{m1:r,m2:i,l1:a,l2:o,g:s}=e.cfg,c=t*e.vTop,l=Math.sqrt(2*c*i*o*o*(1+i/r))+1e-12;for(let t=0;t<400;t++){let t=(2*n()-1)*Math.PI,u=(2*n()-1)*l,d=i*s*o*(1-Math.cos(t));if(d>=c)continue;let f=Math.cos(-t),p=Math.sin(-t),m=r+i*p*p,h=i*o*o,g=-2*i*a*o*u*f,_=(r+i)*a*a*u*u-2*i*a*a*o*o*m*(c-d),v=g*g-4*h*_;if(v<0)continue;let y=(-g+Math.sqrt(v))/(2*h);return e.y[0]=0,e.y[1]=t,e.y[2]=y,e.y[3]=u,e.t=0,!0}return!1}function n(e){return Math.atan2(Math.sin(e),Math.cos(e))}function r(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}}let i=null,a=null;const o=r(Math.random()*2**31|0);let s=0,c=0,l=0,u=0,d=0,f=0,p=[],m=[];self.onmessage=e=>{let t=i?.reset??!1;i=e.data,i.reset||=t,i.running&&a===null&&(a=setTimeout(b,0))};function h(){let t=new e({m1:1,l1:1,g:1,m2:d,l2:f});return t.controlled=!1,t}function g(e){let t=h();for(let n=0;n<4;n++)t.y[n]=e.y[n];m.push({id:e.id,pend:t,crossings:0,prev:n(e.y[0]),ok:!0})}function _(e){s++,c=e.energy,l=performance.now(),u=0,d=e.m2,f=e.l2,p=[],m=[];for(let t of e.tracks)g(t)}function v(e){e.crossings=0,e.prev=0,e.ok=t(e.pend,c,o)}function y(e,t){let r=e.pend,i=r.y;for(let a=0;a<100;a++){let a=i[1],o=i[3];r.step(.005);let s=n(i[0]);if(e.prev<0&&s>=0&&s-e.prev<Math.PI){let c=-e.prev/(s-e.prev);t.push(n(a+c*(i[1]-a)),(o+c*(i[3]-o))/r.p2Scale),e.crossings++}e.prev=s}}function b(){a=null;let e=i;if(!e||!e.running)return;let t=e=>a=setTimeout(b,e);if(e.energy<1e-5)return void t(100);let n=(performance.now()-l)/1e3,r=c>0?Math.abs(Math.log(e.energy/c)):1/0;(s===0||e.reset||e.m2!==d||e.l2!==f||r>Math.log(1+e.band)&&n>=e.minHold)&&(e.reset=!1,_(e));let o=new Set(e.tracks.map(e=>e.id));m=m.filter(e=>o.has(e.id));for(let t of e.tracks)m.some(e=>e.id===t.id)||g(t);let x=u>=e.maxPoints,S=m.every(t=>t.crossings>=e.trackMax);if(x&&S)return void t(50);let C=x?0:Math.max(1,Math.round(e.count));for(;p.length<C;){let e={pend:h(),crossings:0,prev:0,ok:!1};v(e),p.push(e)}p.length>C&&(p.length=C);let w=[],T=/* @__PURE__ */ new Map,E=performance.now();for(;performance.now()-E<8;){let t=!1;for(let n of p)(!n.ok||n.crossings>=e.life)&&(v(n),!n.ok)||(y(n,w),t=!0);for(let n of m){if(n.crossings>=e.trackMax)continue;let r=T.get(n.id);r||T.set(n.id,r=[]),y(n,r),t=!0}if(!t)break}u+=w.length/2;let D=[...T].filter(([,e])=>e.length).map(([e,t])=>({id:e,pts:new Float32Array(t)}));if(w.length||D.length){let e=new Float32Array(w),t={gen:s,energy:c,pts:e,tracks:D};self.postMessage(t,[e.buffer,...D.map(e=>e.pts.buffer)])}let O=Math.max(.02,Math.min(1,e.cpu));t(8*(1-O)/O)}
\ No newline at end of file
site/assets/orbitWorker-CV_Zv_V1.jsadded+1−0View file
@@ -0,0 +1 @@
1+function e(e,t){let n=e*e,r=n*e,i=.00833333333332249+n*(-.0001984126982985795+n*(27557313707070068e-22+n*(-2.5050760253406863e-8+n*158969099521155e-24)));return e-(n*(.5*t-r*i)-t-r*-.16666666666666632)}function t(e,t){let n=e*e,r=n*(.0416666666666666+n*(-.001388888888887411+n*(2480158728947673e-20+n*(-2.7557314351390663e-7+n*(2.087572321298175e-9+n*-11359647557788195e-27))))),i=.5*n,a=1-i;return a+(1-a-i+(n*r-e*t))}let n=0,r=0;function i(e){let t=Math.round(e*.6366197723675814),i=e-t*1.5707963267341256,a=t*6077100506303966e-26,o;return o=i-a,a=t*20222662487959506e-37-(i-o-a),n=o-a,r=o-n-a,t}function a(a){if(!Number.isFinite(a))return NaN;if(Math.abs(a)<.7853981633974483)return e(a,0);let o=i(a)&3;return o===0?e(n,r):o===1?t(n,r):o===2?-e(n,r):-t(n,r)}function o(a){if(!Number.isFinite(a))return NaN;if(Math.abs(a)<.7853981633974483)return t(a,0);let o=i(a)&3;return o===0?t(n,r):o===1?-e(n,r):o===2?-t(n,r):e(n,r)}const s=6.283185307179586;function c(e){return e-s*Math.floor((e+Math.PI)/s)}var l=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ 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:s}=this.cfg,[c,l,u,d]=[e[0],e[1],e[2],e[3]],f=c-l,p=o(f),m=a(f),h=t+n*m*m,g=(i*u-r*d*p)/(r*r*i*h),_=(r*(t+n)*d-i*n*u*p)/(r*i*i*n*h);return{w1:g,w2:_,T:.5*(u*g+d*_),V:(t+n)*s*r*(1-o(c))+n*s*i*(1-o(l))}}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:s,g:c}=this.cfg,l=e[0],u=e[1],d=e[2],f=e[3],p=l-u,m=o(p),h=a(p),g=n+r*h*h,_=(s*d-i*f*m)/(i*i*s*g),v=(i*(n+r)*f-s*r*d*m)/(i*s*s*r*g),y=d*f*h/(i*s*g),b=(s*s*r*d*d+i*i*(n+r)*f*f-2*i*s*r*d*f*m)*a(2*p)/(2*i*i*s*s*g*g),x=.5*(d*_+f*v),S=(n+r)*c*i*(1-o(l))+r*c*s*(1-o(u)),C=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;C=(this.eTarget-(x+S))/(this.tau*(2*x+e)),C>t?C=t:C<-t&&(C=-t)}C-=this.damping,t[0]=_,t[1]=v,t[2]=-(n+r)*c*i*a(l)-y+b+C*d,t[3]=-r*c*s*a(u)+y-b+C*f}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:s}=this.cfg,c=Math.max(e,1e-6)*this.vTop,l=Math.min(Math.PI,3*Math.sqrt(c/(r*this.cfg.g*Math.min(i,s)))),u=0,d=0,f=0;for(let e=0;e<1e3&&(u=(2*t()-1)*l,d=(2*t()-1)*l,f=this.derived([u,d,0,0]).V,!(f<.9*c));e++)u=d=0,f=0;let p=c-f,m=t()*2*Math.PI,h=o(m),g=a(m),_=o(u-d),v=(n+r)*i*i,y=r*i*s*_,b=r*s*s,x=.5*(v*h*h+2*y*h*g+b*g*g),S=Math.sqrt(p/x),C=S*h,w=S*g;this.y[0]=u,this.y[1]=d,this.y[2]=v*C+y*w,this.y[3]=y*C+b*w,this.t=0}};function u(e,t,n){let{m1:r,m2:i,l1:s,l2:c,g:l}=e.cfg,u=t*e.vTop,d=Math.sqrt(2*u*i*c*c*(1+i/r))+1e-12;for(let t=0;t<400;t++){let t=(2*n()-1)*Math.PI,f=(2*n()-1)*d,p=i*l*c*(1-o(t));if(p>=u)continue;let m=o(-t),h=a(-t),g=r+i*h*h,_=i*c*c,v=-2*i*s*c*f*m,y=(r+i)*s*s*f*f-2*i*s*s*c*c*g*(u-p),b=v*v-4*_*y;if(b<0)continue;let x=(-v+Math.sqrt(b))/(2*_);return e.y[0]=0,e.y[1]=t,e.y[2]=x,e.y[3]=f,e.t=0,!0}return!1}function d(e){return c(e)}function f(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}}let p=null,m=null;const h=f(Math.random()*2**31|0);let g=0,_=0,v=0,y=0,b=0,x=0,S=[],C=[];self.onmessage=e=>{let t=p?.reset??!1;p=e.data,p.reset||=t,p.running&&m===null&&(m=setTimeout(k,0))};function w(){let e=new l({m1:1,l1:1,g:1,m2:b,l2:x});return e.controlled=!1,e}function T(e){let t=w();for(let n=0;n<4;n++)t.y[n]=e.y[n];C.push({id:e.id,pend:t,crossings:0,prev:d(e.y[0]),ok:!0})}function E(e){g++,_=e.energy,v=performance.now(),y=0,b=e.m2,x=e.l2,S=[],C=[];for(let t of e.tracks)T(t)}function D(e){e.crossings=0,e.prev=0,e.ok=u(e.pend,_,h)}function O(e,t){let n=e.pend,r=n.y;for(let i=0;i<100;i++){let i=r[1],a=r[3];n.step(.005);let o=d(r[0]);if(e.prev<0&&o>=0&&o-e.prev<Math.PI){let s=-e.prev/(o-e.prev);t.push(d(i+s*(r[1]-i)),(a+s*(r[3]-a))/n.p2Scale),e.crossings++}e.prev=o}}function k(){m=null;let e=p;if(!e||!e.running)return;let t=e=>m=setTimeout(k,e);if(e.energy<1e-5)return void t(100);let n=(performance.now()-v)/1e3,r=_>0?Math.abs(Math.log(e.energy/_)):1/0;(g===0||e.reset||e.m2!==b||e.l2!==x||r>Math.log(1+e.band)&&n>=e.minHold)&&(e.reset=!1,E(e));let i=new Set(e.tracks.map(e=>e.id));C=C.filter(e=>i.has(e.id));for(let t of e.tracks)C.some(e=>e.id===t.id)||T(t);let a=y>=e.maxPoints,o=C.every(t=>t.crossings>=e.trackMax);if(a&&o)return void t(50);let s=a?0:Math.max(1,Math.round(e.count));for(;S.length<s;){let e={pend:w(),crossings:0,prev:0,ok:!1};D(e),S.push(e)}S.length>s&&(S.length=s);let c=[],l=/* @__PURE__ */ new Map,u=performance.now();for(;performance.now()-u<8;){let t=!1;for(let n of S)(!n.ok||n.crossings>=e.life)&&(D(n),!n.ok)||(O(n,c),t=!0);for(let n of C){if(n.crossings>=e.trackMax)continue;let r=l.get(n.id);r||l.set(n.id,r=[]),O(n,r),t=!0}if(!t)break}y+=c.length/2;let d=[...l].filter(([,e])=>e.length).map(([e,t])=>({id:e,pts:new Float32Array(t)}));if(c.length||d.length){let e=new Float32Array(c),t={gen:g,energy:_,pts:e,tracks:d};self.postMessage(t,[e.buffer,...d.map(e=>e.pts.buffer)])}let f=Math.max(.02,Math.min(1,e.cpu));t(8*(1-f)/f)}
\ No newline at end of file
site/assets/pendulumWorklet-BpTttuTz.jsadded+1−0View file
@@ -0,0 +1 @@
1+function e(e,t){let n=e*e,r=n*e,i=.00833333333332249+n*(-.0001984126982985795+n*(27557313707070068e-22+n*(-2.5050760253406863e-8+n*158969099521155e-24)));return e-(n*(.5*t-r*i)-t-r*-.16666666666666632)}function t(e,t){let n=e*e,r=n*(.0416666666666666+n*(-.001388888888887411+n*(2480158728947673e-20+n*(-2.7557314351390663e-7+n*(2.087572321298175e-9+n*-11359647557788195e-27))))),i=.5*n,a=1-i;return a+(1-a-i+(n*r-e*t))}let n=0,r=0;function i(e){let t=Math.round(e*.6366197723675814),i=e-t*1.5707963267341256,a=t*6077100506303966e-26,o;return o=i-a,a=t*20222662487959506e-37-(i-o-a),n=o-a,r=o-n-a,t}function a(a){if(!Number.isFinite(a))return NaN;if(Math.abs(a)<.7853981633974483)return e(a,0);let o=i(a)&3;return o===0?e(n,r):o===1?t(n,r):o===2?-e(n,r):-t(n,r)}function o(a){if(!Number.isFinite(a))return NaN;if(Math.abs(a)<.7853981633974483)return t(a,0);let o=i(a)&3;return o===0?t(n,r):o===1?-e(n,r):o===2?-t(n,r):e(n,r)}function s(e,t){return Math.sqrt(e*e+t*t)}const c=6.283185307179586;function l(e){return e-c*Math.floor((e+Math.PI)/c)}var u=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ 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:s}=this.cfg,[c,l,u,d]=[e[0],e[1],e[2],e[3]],f=c-l,p=o(f),m=a(f),h=t+n*m*m,g=(i*u-r*d*p)/(r*r*i*h),_=(r*(t+n)*d-i*n*u*p)/(r*i*i*n*h);return{w1:g,w2:_,T:.5*(u*g+d*_),V:(t+n)*s*r*(1-o(c))+n*s*i*(1-o(l))}}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:s,g:c}=this.cfg,l=e[0],u=e[1],d=e[2],f=e[3],p=l-u,m=o(p),h=a(p),g=n+r*h*h,_=(s*d-i*f*m)/(i*i*s*g),v=(i*(n+r)*f-s*r*d*m)/(i*s*s*r*g),y=d*f*h/(i*s*g),b=(s*s*r*d*d+i*i*(n+r)*f*f-2*i*s*r*d*f*m)*a(2*p)/(2*i*i*s*s*g*g),x=.5*(d*_+f*v),S=(n+r)*c*i*(1-o(l))+r*c*s*(1-o(u)),C=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;C=(this.eTarget-(x+S))/(this.tau*(2*x+e)),C>t?C=t:C<-t&&(C=-t)}C-=this.damping,t[0]=_,t[1]=v,t[2]=-(n+r)*c*i*a(l)-y+b+C*d,t[3]=-r*c*s*a(u)+y-b+C*f}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:s}=this.cfg,c=Math.max(e,1e-6)*this.vTop,l=Math.min(Math.PI,3*Math.sqrt(c/(r*this.cfg.g*Math.min(i,s)))),u=0,d=0,f=0;for(let e=0;e<1e3&&(u=(2*t()-1)*l,d=(2*t()-1)*l,f=this.derived([u,d,0,0]).V,!(f<.9*c));e++)u=d=0,f=0;let p=c-f,m=t()*2*Math.PI,h=o(m),g=a(m),_=o(u-d),v=(n+r)*i*i,y=r*i*s*_,b=r*s*s,x=.5*(v*h*h+2*y*h*g+b*g*g),S=Math.sqrt(p/x),C=S*h,w=S*g;this.y[0]=u,this.y[1]=d,this.y[2]=v*C+y*w,this.y[3]=y*C+b*w,this.t=0}};function d(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 f(e){let{m1:t,m2:n,l1:r,l2:i,g:a}=e.cfg,o=(t+n)*r*r,s=n*r*i,c=n*i*i,l=(t+n)*a*r,u=n*a*i,d=o*c-s*s,f=(l*c+u*o)/d,p=l*u/d,m=(f-Math.sqrt(Math.max(0,f*f-4*p)))/2;return Math.sqrt(Math.max(m,1e-9))}function p(e,t,n){let r=e.y;if(!(t>0))return;let i=r[2],c=r[3],l=s(i,c);if(l>1e-9)i/=l,c/=l;else{let e=n()*2*Math.PI;i=o(e),c=a(e)}let u=e.derived(),d=i*u.w1+c*u.w2,f=e.derived([r[0],r[1],i,c]),p=i*f.w1+c*f.w2,m=(-d+Math.sqrt(Math.max(0,d*d+2*p*t)))/p;r[2]+=m*i,r[3]+=m*c}function m(e,t,n,r){let{l1:i,l2:c,m2:u}=e.cfg,d=e.y,f=i+c,p=Math.sqrt(2*e.vTop/u)+1e-9,m=a(d[0]),h=o(d[0]),g=a(d[1]),_=o(d[1]);switch(t){case`x2`:return(i*m+c*g)/f;case`y2`:return-(i*h+c*_)/f;case`vx2`:return(i*h*n+c*_*r)/p;case`vy2`:return(i*m*n+c*g*r)/p;case`x1`:return m;case`vx1`:return i*h*n/p;case`θ1`:return l(d[0])/Math.PI;case`θ2`:return l(d[1])/Math.PI;case`θ2−θ1`:return l(d[1]-d[0])/Math.PI;case`ω1`:return n*i/p;case`ω2`:return r*c/p;case`p1`:return d[2]/(p*(1+u)*i*i+1e-9);case`p2`:return d[3]/(p*u*c*c+1e-9);case`speed2`:return s(i*h*n+c*_*r,i*m*n+c*g*r)/p}}var h=class extends AudioWorkletProcessor{s=null;p=new u({m1:1,m2:1,l1:1,l2:1,g:1});rand=d(12345);t=0;swellFrom=0;phase=`silent`;dcL={x:0,y:0};dcR={x:0,y:0};trail=/* @__PURE__ */ new Float32Array(1536);trailW=0;sinceSnap=0;sampleCount=0;constructor(){super(),this.p.controlled=!1,this.port.onmessage=e=>{if(e.data.type===`settings`){let t=!this.s;this.s=e.data.s,this.p.cfg.m2=this.s.massRatio,this.p.cfg.l2=this.s.lengthRatio,t&&(this.p.y.fill(0),this.strike())}else e.data.type===`strike`&&this.strike()}}strike(){let e=this.s;e&&(this.t=0,e.mode===`swell`?(this.swellFrom=this.p.energyNorm(),this.phase=`swelling`,this.swellFrom<1e-6&&this.kick(1e-4*this.p.vTop)):this.kick(e.strikeEnergy*this.p.vTop))}kick(e){p(this.p,e,this.rand)}signal(e,t,n){return m(this.p,e,t,n)}process(e,t){let n=t[0],r=n[0],i=n[1]??n[0],a=this.s;if(!a)return!0;let o=r.length,s=this.p,c=f(s),l=2*Math.PI*a.pitch/c,u=l/sampleRate,d=Math.max(1,Math.ceil(u/.004)),p=u/d,m=a.ringTime>0?13.8156/(a.ringTime*l):0,h=1-2*Math.PI*a.dcCut/sampleRate,g=2*Math.PI/c;s.tau=Math.max(.05,a.follow*g);for(let e=0;e<o;e++){if(a.mode===`sustain`)this.phase=`sustaining`,s.controlled=!0,s.eTarget=a.energy*s.vTop,s.damping=0;else if(a.mode===`swell`){if(this.t<a.swellTime){s.controlled=!0;let e=this.t/Math.max(.01,a.swellTime);s.eTarget=(this.swellFrom+(a.energy-this.swellFrom)*e*e)*s.vTop,s.damping=0,this.phase=`swelling`}else s.controlled=!1,s.damping=m,this.phase=`ringing`}else s.controlled=!1,s.damping=m,this.phase=`ringing`;for(let e=0;e<d;e++)s.step(p);this.t+=1/sampleRate,a.restrike>0&&this.t>=a.restrike&&this.strike();let t=s.derived(),n=this.signal(a.left,t.w1,t.w2),o=a.right===a.left?n:this.signal(a.right,t.w1,t.w2),c=n-this.dcL.x+h*this.dcL.y;this.dcL.x=n,this.dcL.y=c;let l=o-this.dcR.x+h*this.dcR.y;if(this.dcR.x=o,this.dcR.y=l,n=Math.tanh(a.gain*c),o=Math.tanh(a.gain*l),r[e]=Number.isFinite(n)?n:0,i[e]=Number.isFinite(o)?o:0,Number.isFinite(s.y[0])||this.strike(),++this.sampleCount%2==0){let e=s.y,t=s.cfg,n=4*this.trailW,r=t.l1*Math.sin(e[0]),i=t.l1*Math.cos(e[0]);this.trail[n]=r,this.trail[n+1]=i,this.trail[n+2]=r+t.l2*Math.sin(e[1]),this.trail[n+3]=i+t.l2*Math.cos(e[1]),this.trailW=(this.trailW+1)%384}}if(this.sinceSnap+=o,this.sinceSnap>=sampleRate/60){this.sinceSnap=0;let e=/* @__PURE__ */ new Float32Array(1536);e.set(this.trail.subarray(4*this.trailW)),e.set(this.trail.subarray(0,4*this.trailW),4*(384-this.trailW));let t={type:`snap`,energy:s.energyNorm(),phase:this.phase,trail:e,k:l};this.port.postMessage(t,[e.buffer])}return currentTime,!0}};registerProcessor(`pendulum-voice`,h);
\ No newline at end of file
site/assets/pendulumWorklet-CX1TnpQQ.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-var e=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ 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 t(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 n(e){let{m1:t,m2:n,l1:r,l2:i,g:a}=e.cfg,o=(t+n)*r*r,s=n*r*i,c=n*i*i,l=(t+n)*a*r,u=n*a*i,d=o*c-s*s,f=(l*c+u*o)/d,p=l*u/d,m=(f-Math.sqrt(Math.max(0,f*f-4*p)))/2;return Math.sqrt(Math.max(m,1e-9))}function r(e,t,n){let r=e.y;if(!(t>0))return;let i=r[2],a=r[3],o=Math.hypot(i,a);if(o>1e-9)i/=o,a/=o;else{let e=n()*2*Math.PI;i=Math.cos(e),a=Math.sin(e)}let s=e.derived(),c=i*s.w1+a*s.w2,l=e.derived([r[0],r[1],i,a]),u=i*l.w1+a*l.w2,d=(-c+Math.sqrt(Math.max(0,c*c+2*u*t)))/u;r[2]+=d*i,r[3]+=d*a}function i(e,t,n,r){let{l1:i,l2:a,m2:o}=e.cfg,s=e.y,c=i+a,l=Math.sqrt(2*e.vTop/o)+1e-9,u=Math.sin(s[0]),d=Math.cos(s[0]),f=Math.sin(s[1]),p=Math.cos(s[1]);switch(t){case`x2`:return(i*u+a*f)/c;case`y2`:return-(i*d+a*p)/c;case`vx2`:return(i*d*n+a*p*r)/l;case`vy2`:return(i*u*n+a*f*r)/l;case`x1`:return u;case`vx1`:return i*d*n/l;case`θ1`:return Math.atan2(u,d)/Math.PI;case`θ2`:return Math.atan2(f,p)/Math.PI;case`θ2−θ1`:return Math.atan2(Math.sin(s[1]-s[0]),Math.cos(s[1]-s[0]))/Math.PI;case`ω1`:return n*i/l;case`ω2`:return r*a/l;case`p1`:return s[2]/(l*(1+o)*i*i+1e-9);case`p2`:return s[3]/(l*o*a*a+1e-9);case`speed2`:return Math.hypot(i*d*n+a*p*r,i*u*n+a*f*r)/l}}var a=class extends AudioWorkletProcessor{s=null;p=new e({m1:1,m2:1,l1:1,l2:1,g:1});rand=t(12345);t=0;swellFrom=0;phase=`silent`;dcL={x:0,y:0};dcR={x:0,y:0};trail=/* @__PURE__ */ new Float32Array(1536);trailW=0;sinceSnap=0;sampleCount=0;constructor(){super(),this.p.controlled=!1,this.port.onmessage=e=>{if(e.data.type===`settings`){let t=!this.s;this.s=e.data.s,this.p.cfg.m2=this.s.massRatio,this.p.cfg.l2=this.s.lengthRatio,t&&(this.p.y.fill(0),this.strike())}else e.data.type===`strike`&&this.strike()}}strike(){let e=this.s;e&&(this.t=0,e.mode===`swell`?(this.swellFrom=this.p.energyNorm(),this.phase=`swelling`,this.swellFrom<1e-6&&this.kick(1e-4*this.p.vTop)):this.kick(e.strikeEnergy*this.p.vTop))}kick(e){r(this.p,e,this.rand)}signal(e,t,n){return i(this.p,e,t,n)}process(e,t){let r=t[0],i=r[0],a=r[1]??r[0],o=this.s;if(!o)return!0;let s=i.length,c=this.p,l=n(c),u=2*Math.PI*o.pitch/l,d=u/sampleRate,f=Math.max(1,Math.ceil(d/.004)),p=d/f,m=o.ringTime>0?13.8156/(o.ringTime*u):0,h=1-2*Math.PI*o.dcCut/sampleRate,g=2*Math.PI/l;c.tau=Math.max(.05,o.follow*g);for(let e=0;e<s;e++){if(o.mode===`sustain`)this.phase=`sustaining`,c.controlled=!0,c.eTarget=o.energy*c.vTop,c.damping=0;else if(o.mode===`swell`){if(this.t<o.swellTime){c.controlled=!0;let e=this.t/Math.max(.01,o.swellTime);c.eTarget=(this.swellFrom+(o.energy-this.swellFrom)*e*e)*c.vTop,c.damping=0,this.phase=`swelling`}else c.controlled=!1,c.damping=m,this.phase=`ringing`}else c.controlled=!1,c.damping=m,this.phase=`ringing`;for(let e=0;e<f;e++)c.step(p);this.t+=1/sampleRate,o.restrike>0&&this.t>=o.restrike&&this.strike();let t=c.derived(),n=this.signal(o.left,t.w1,t.w2),r=o.right===o.left?n:this.signal(o.right,t.w1,t.w2),s=n-this.dcL.x+h*this.dcL.y;this.dcL.x=n,this.dcL.y=s;let l=r-this.dcR.x+h*this.dcR.y;if(this.dcR.x=r,this.dcR.y=l,n=Math.tanh(o.gain*s),r=Math.tanh(o.gain*l),i[e]=Number.isFinite(n)?n:0,a[e]=Number.isFinite(r)?r:0,Number.isFinite(c.y[0])||this.strike(),++this.sampleCount%2==0){let e=c.y,t=c.cfg,n=4*this.trailW,r=t.l1*Math.sin(e[0]),i=t.l1*Math.cos(e[0]);this.trail[n]=r,this.trail[n+1]=i,this.trail[n+2]=r+t.l2*Math.sin(e[1]),this.trail[n+3]=i+t.l2*Math.cos(e[1]),this.trailW=(this.trailW+1)%384}}if(this.sinceSnap+=s,this.sinceSnap>=sampleRate/60){this.sinceSnap=0;let e=/* @__PURE__ */ new Float32Array(1536);e.set(this.trail.subarray(4*this.trailW)),e.set(this.trail.subarray(0,4*this.trailW),4*(384-this.trailW));let t={type:`snap`,energy:c.energyNorm(),phase:this.phase,trail:e,k:u};this.port.postMessage(t,[e.buffer])}return currentTime,!0}};registerProcessor(`pendulum-voice`,a);
\ No newline at end of file
site/assets/player-CFiFcj0f.jsadded+1−0View file
@@ -0,0 +1 @@
1+const e=.985;var t=class extends AudioWorkletProcessor{o;queues;avail;doneAt;ports=[];playhead;endFrame=1/0;state=`buffering`;resume=1;rebuffers=0;fadeIn=0;tail;blocks=0;rateLog=[];constructor(e){super(e),this.o=e.processorOptions,this.queues=Array.from({length:this.o.stems},()=>[]),this.avail=Array(this.o.stems).fill(this.o.startFrame),this.doneAt=Array(this.o.stems).fill(1/0),this.playhead=this.o.startFrame,this.tail=Array.from({length:this.o.outputs},()=>[0,0]),this.port.onmessage=e=>{if(e.data?.type===`ports`){for(let t of e.data.ports)this.ports.push(t),t.onmessage=e=>this.receive(e.data);this.clock()}}}receive(e){if(e.type===`chunk`){let t=this.queues[e.stem];if(!t)return;t.push({frame:e.frame,L:e.L,R:e.R}),this.avail[e.stem]=Math.max(this.avail[e.stem],e.frame+e.L.length)}else e.type===`done`?this.doneAt[e.stem]=Math.min(this.doneAt[e.stem],e.frame):e.type===`end`&&(this.endFrame=e.frame)}readyTo(e){for(let t=0;t<this.o.stems;t++){let n=Math.min(e,this.doneAt[t],this.endFrame);if(this.avail[t]<n)return!1}return!0}least(){let e=1/0;for(let t=0;t<this.o.stems;t++)this.doneAt[t]>this.playhead&&(e=Math.min(e,this.avail[t]));return e}rate(){let e=this.rateLog;if(e.length<2)return null;let[t,n]=e[0],[r,i]=e[e.length-1];return r-t<+sampleRate?null:(i-n)/(r-t)}aheadFrames(){return Math.round(Math.max(4,2*this.resume,this.target()+2)*sampleRate)}measure(){let e=this.least(),t=this.aheadFrames();if(!Number.isFinite(e)||e-this.playhead>.8*t)this.rateLog=[];else for(this.rateLog.push([currentFrame,e]);this.rateLog.length>2&&currentFrame-this.rateLog[0][0]>2*sampleRate;)this.rateLog.shift()}target(){let e=this.rate();if(e===null||e>=1)return this.resume;let t=((Number.isFinite(this.endFrame)?this.endFrame:this.o.estimatedEnd)-this.playhead)/sampleRate*(1-e)*1.15+.5;return Math.min(32,Math.max(this.resume,t))}fill(){let e=Math.min(this.playhead+this.target()*sampleRate,this.endFrame);if(e<=this.playhead)return 1;let t=1;for(let n=0;n<this.o.stems;n++){let r=Math.min(e,this.doneAt[n]);r<=this.playhead||(t=Math.min(t,Math.max(0,(this.avail[n]-this.playhead)/(r-this.playhead))))}return t}ahead(){let e=1/0;for(let t=0;t<this.o.stems;t++)this.doneAt[t]>this.playhead&&(e=Math.min(e,this.avail[t]-this.playhead));return e===1/0?0:e/sampleRate}clock(){let e=this.aheadFrames(),t={type:`clock`,playhead:this.playhead,ahead:e};for(let e of this.ports)e.postMessage(t)}report(){let e={type:`status`,state:this.state,playhead:this.playhead,at:currentFrame,fill:this.state===`buffering`?this.fill():1,rebuffers:this.rebuffers,ahead:this.ahead()};this.port.postMessage(e)}process(t,n){if(this.state===`playing`&&this.playhead>=this.endFrame&&(this.state=`ended`),this.blocks%12==0&&this.measure(),this.state===`buffering`){let e=Math.min(this.playhead+Math.round(this.target()*sampleRate),this.endFrame);this.readyTo(e)&&(this.state=`playing`,this.fadeIn=0)}if(this.state===`playing`&&!this.readyTo(this.playhead+128)&&(this.state=`buffering`,this.rebuffers++,this.resume=Math.min(32,this.resume*2)),this.state!==`playing`)for(let t=0;t<n.length;t++){let r=n[t][0],i=n[t][1]??r,a=this.tail[t];for(let t=0;t<128;t++)a[0]*=e,a[1]*=e,r[t]=a[0],i!==r&&(i[t]=a[1])}else{let e=this.playhead;for(let t=0;t<this.o.stems;t++){let r=this.queues[t];for(;r.length&&r[0].frame+r[0].L.length<=e;)r.shift();if(e>=this.doneAt[t])continue;let i=n[this.o.route[t]];if(!i)continue;let a=i[0],o=i[1]??a,s=0;for(let t of r){if(s>=128)break;let n=e+s;if(t.frame+t.L.length<=n)continue;if(t.frame>n)break;let r=n-t.frame,i=Math.min(128-s,t.L.length-r);for(let e=0;e<i;e++)a[s+e]+=t.L[r+e],o!==a&&(o[s+e]+=t.R[r+e]);s+=i}}for(let e=0;e<n.length;e++){let t=n[e][0],r=n[e][1]??t;if(this.fadeIn<512)for(let e=0;e<128;e++){let n=Math.min(1,(this.fadeIn+e)/512);t[e]*=n,r!==t&&(r[e]*=n)}this.tail[e][0]=t[127],this.tail[e][1]=r[127]}this.fadeIn+=128,this.playhead+=128}return++this.blocks%6==0&&(this.report(),this.clock()),!0}};registerProcessor(`stream-player`,t);
\ No newline at end of file
site/assets/player-CJ7uyr_q.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-const e=.985;var t=class extends AudioWorkletProcessor{queue=[];src=null;underruns=0;started=!1;lastReport=0;tailL=0;tailR=0;fadeIn=256;constructor(){super(),this.port.onmessage=e=>{e.data?.type===`port`&&(this.src=e.data.port,this.src.onmessage=e=>this.queue.push(e.data))}}process(t,n){let r=n[0],i=r[0],a=r[1]??r[0],o=i.length,s=currentFrame,c=this.queue;for(;c.length&&c[0].frame+c[0].L.length<=s;)c.shift();let l=0;for(;l<o;){let t=s+l,n=c.find(e=>e.frame<=t&&t<e.frame+e.L.length);if(!n){let n=c.find(e=>e.frame>t),r=n?Math.min(o,n.frame-s):o;this.started&&this.underruns++;let u=Math.max(r,l+1);for(;l<u;l++)this.tailL*=e,this.tailR*=e,i[l]=this.tailL,a!==i&&(a[l]=this.tailR);this.started&&(this.fadeIn=0);continue}this.started=!0;let r=t-n.frame,u=Math.min(o-l,n.L.length-r);if(this.fadeIn>=256)i.set(n.L.subarray(r,r+u),l),a!==i&&a.set(n.R.subarray(r,r+u),l);else for(let t=0;t<u;t++){let o=Math.min(1,this.fadeIn++/256);this.tailL*=e,this.tailR*=e,i[l+t]=o*n.L[r+t]+(1-o)*this.tailL,a!==i&&(a[l+t]=o*n.R[r+t]+(1-o)*this.tailR)}l+=u,this.tailL=i[l-1],this.tailR=a[l-1]}if(this.src&&s+o-this.lastReport>=sampleRate/50){this.lastReport=s+o;let e={consumed:s+o,underruns:this.underruns};this.src.postMessage(e)}return!0}};registerProcessor(`pcm-player`,t);
\ No newline at end of file
site/assets/renderWorker-8kKMa0Za.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-const e=(e,t)=>e[t],t=(e,t)=>e[t],n=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,r=(...e)=>t=>e.includes(t.geometry),i=(...e)=>t=>e.includes(t.exciter),a=[`bow`,`reed`,`selfosc`,`noise`],o=[[`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`]],s=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function c(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:o,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:s,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}]}const l=[{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:r(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:r(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:r(`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&&n(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:n},{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:i(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:i(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:i(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:i(`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:i(`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:i(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:i(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:i(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:i(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:i(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:i(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:i(...a)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:i(...a)},{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},...c(1),...c(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:n},{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`}];Object.fromEntries(l.map(e=>[e.id,e]));const u=Object.fromEntries(l.map(e=>[e.id,e.def])),d=l.filter(e=>e.model).map(e=>e.id),f=Math.SQRT2,p=Math.PI;function m(e,t){let n=Math.ceil(Math.abs(t)+e)+24,r=0;for(let i=0;i<=n;i++){let a=p*i/n;r+=(i===0||i===n?.5:1)*Math.cos(e*a-t*Math.sin(a))}return r/n}function h(e,t){let n=[],r=e===0?.5:e,i=m(e,r);for(let a=r+.05;a<=t;a+=.05){let t=m(e,a);if(i*t<0){let t=r,o=a,s=i;for(let n=0;n<50;n++){let n=.5*(t+o),r=m(e,n);s*r<=0?o=n:(t=n,s=r)}n.push(.5*(t+o))}r=a,i=t}return n}const g=[4.730040745,7.853204624,10.99560784,14.13716549,17.27875966],_=e=>e<g.length?g[e]:(2*e+3)*p/2;function v(e,t,n){if(t<12){let e=(Math.cosh(t)-Math.cos(t))/(Math.sinh(t)-Math.sin(t));return Math.cosh(t*n)+Math.cos(t*n)-e*(Math.sinh(t*n)+Math.sin(t*n))}let r=e%2==0?1:-1;return Math.cos(t*n)-Math.sin(t*n)+Math.exp(-t*n)+r*Math.exp(-t*(1-n))}const y=[[.5,2],[1,2],[1.2,3],[1.5,3],[2,4],[2.5,4],[2.67,3],[3,5],[4,6],[4.24,5],[5.33,7],[5.7,6],[6.67,8],[7.2,7],[8,9],[9,8],[10,10],[11.1,9],[12.1,11],[13.5,10]];function b(e,t,n,r,i=2){let a=new Float64Array(t),o=new Float64Array(t),s={kind:e,N:t,ratios:a,wavenum:o,aspect:n};switch(e){case`string`:case`free`:for(let n=0;n<t;n++){let t=n+1;a[n]=e===`string`?t:t**+r,o[n]=t}return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.sin((e+1)*p*t)};case`tube_co`:for(let e=0;e<t;e++)a[e]=2*e+1,o[e]=(2*e+1)/2;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((2*e+1)*p*t/2)};case`tube_oo`:for(let e=0;e<t;e++)a[e]=e+1,o[e]=e+1;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((e+1)*p*t)};case`bar`:{let e=_(0),n=new Float64Array(t),r=2048;for(let i=0;i<t;i++){let t=_(i);a[i]=(t/e)**2,o[i]=t/p;let s=0;for(let e=0;e<r;e++)s+=v(i,t,(e+.5)/r)**2;n[i]=1/Math.sqrt(s/r)}return{...s,view:`line`,dim:1,shape:(e,t)=>n[e]*v(e,_(e),t)}}case`ring`:{let e=[],n=[],r=0,i=0,c=2;for(;e.length<t;){r<y.length?[i,c]=y[r]:(i*=1.09,c+=+(r%2==0));for(let s=0;s<2&&e.length<t;s++)a[e.length]=i*(s===0?1:1+6e-4*(1+r%3)),o[e.length]=2*c,e.push(c),n.push(s);r++}return{...s,view:`ring`,dim:1,shape:(t,r)=>{let i=2*p*r*e[t];return f*(n[t]===0?Math.cos(i):Math.sin(i))}}}case`plate`:{let e=Math.ceil(3*Math.sqrt(t))+3,r=[];for(let t=1;t<=e;t++)for(let i=1;i<=e;i++)r.push([t*t+(i/n)**2,t,i]);r.sort((e,t)=>e[0]-t[0]);let i=new Int32Array(t),c=new Int32Array(t),l=r[0][0];for(let e=0;e<t;e++){let[t,s,u]=r[e];a[e]=t/l,o[e]=Math.sqrt(s*s+(u/n)**2),i[e]=s,c[e]=u}return{...s,view:`rect`,dim:2,shape:(e,t,n)=>2*Math.sin(i[e]*p*t)*Math.sin(c[e]*p*n)}}case`membrane`:{let e=2*Math.sqrt(t)+6,n=[];for(;;){n=[];for(let t=0;t<=Math.ceil(e);t++)for(let r of h(t,e))n.push([r,t,0]),t>0&&n.push([r,t,1]);if(n.length>=t)break;e*=1.3}n.sort((e,t)=>e[0]-t[0]||e[2]-t[2]);let r=n[0][0],i=new Int32Array(t),c=new Int32Array(t),l=new Float64Array(t),u=new Float64Array(t);for(let e=0;e<t;e++){let[t,s,d]=n[e];a[e]=t/r,o[e]=t/p,i[e]=s,c[e]=d,l[e]=t,u[e]=s===0?1/Math.abs(m(1,t)):f/Math.abs(m(s+1,t))}return S(s,i,c,l,u)}case`disc`:{let e=i,n=Math.ceil(Math.sqrt(2*t))+4,r=[];for(let t=0;t<=n;t++)for(let i=0;t+2*i<=n;i++){if(i===0&&t<2)continue;let n=(t+2.1*i)**+e;r.push([n,t,i,0]),t>0&&r.push([n*1.0004,t,i,1])}r.sort((e,t)=>e[0]-t[0]);let c=r.slice(0,t),l=c.reduce((e,t)=>Math.max(e,t[1]),0),u=c.reduce((e,t)=>Math.max(e,t[2]),0),d=[];for(let e=0;e<=l;e++)d.push(x(e,u+1));let f=new Int32Array(t),m=new Int32Array(t),h=new Float64Array(t),g=c[0][0];for(let e=0;e<t;e++){let[t,n,r,i]=c[e];a[e]=t/g,f[e]=n,m[e]=i,h[e]=d[n][n===0?r-1:r],o[e]=h[e]/p}return S(s,f,m,h,null)}}}function x(e,t){let n=t=>e===0?-m(1,t):.5*(m(e-1,t)-m(e+1,t)),r=[],i=e===0?.5:Math.max(.3,e*.8),a=n(i);for(let e=i+.05;r.length<t;e+=.05){let t=n(e);if(a*t<0){let t=i,o=e,s=a;for(let e=0;e<50;e++){let e=.5*(t+o),r=n(e);s*r<=0?o=e:(t=e,s=r)}r.push(.5*(t+o))}i=e,a=t}return r}function S(e,t,n,r,i){let a=e.N,o=Array(a).fill(null),s=i??new Float64Array(a),c=(e,n)=>{let a=o[e];if(!a){a=/* @__PURE__ */ new Float64Array(258);for(let n=0;n<=256;n++)a[n]=m(t[e],r[e]*n/256);if(a[257]=a[256],o[e]=a,!i){let n=0;for(let e=0;e<=256;e++)n+=(e===0||e===256?.5:1)*a[e]*a[e]*e/256/256;s[e]=1/Math.sqrt(Math.max(1e-12,(t[e]===0?2:1)*n))}}let c=n*256,l=Math.floor(c),u=c-l;return a[l]*(1-u)+a[l+1]*u};return{...e,view:`disk`,dim:2,shape:(e,r,i)=>{let a=2*r-1,o=2*i-1,l=Math.hypot(a,o);if(l>=1)return 0;let u=c(e,l),d=t[e],f=d===0?1:n[e]===0?Math.cos(d*Math.atan2(o,a)):Math.sin(d*Math.atan2(o,a));return s[e]*u*f}}}function C(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 w(e){let t=Math.max(e(),1e-12);return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*e())}const T=e=>d.map(t=>String(e[t])).join(`|`);function E(n){let r=Math.round(e(n,`modes`)),i=b(t(n,`geometry`),r,e(n,`aspect`),e(n,`powerExp`),e(n,`discExp`)),a=Math.round(e(n,`seed`)),o=C(a*7919+13),s=e(n,`stretch`),c=e(n,`inharm`),l=e(n,`harmonize`),u=e(n,`jitter`),d=0;for(let e=0;e<r;e++)if(Math.abs(i.ratios[e]-1)<1e-9){d=e;break}let f=new Float64Array(r);for(let e=0;e<r;e++){let t=i.ratios[e]**+s;if(t*=Math.sqrt(1+c*t*t)/Math.sqrt(1+c),l>0){let e=t<.75?.5:Math.max(1,Math.round(t));t=t**(1-l)*e**+l}let n=w(o);e!==d&&u>0&&(t*=2**(u*n/1200)),f[e]=t}let p=Int32Array.from({length:r},(e,t)=>t).sort((e,t)=>f[e]-f[t]),m=new Float64Array(r),h=new Float64Array(r),g=0;for(let e=0;e<r;e++)m[e]=f[p[e]],h[e]=i.wavenum[p[e]],p[e]===d&&(g=e);let _=Math.min(r,Math.round(e(n,`nlModes`))),v=Math.round(e(n,`terms`)),y=C(a*104729+7),x=[],S=new Float64Array(v*_);for(let e=0;e<v;e++){let t=[],n=Math.max(2,Math.round(_*.75)),r=0;for(let e=0;e<n;e++){let e=Math.floor(y()*_),n=y()<.25?e:Math.floor(y()*_),i=w(y);t.push([e,n,i]),r+=(e===n?1:2)*i*i}let i=1/Math.sqrt(r),a=[];for(let[e,n,r]of t)a.push([e,n,r*i]),e!==n&&a.push([n,e,r*i]);x.push(a);let o=0;for(let t=0;t<_;t++){let n=w(y);S[e*_+t]=n,o+=n*n}o=1/Math.sqrt(o);for(let t=0;t<_;t++)S[e*_+t]*=o}let E=x.reduce((e,t)=>e+t.length,0),D=new Int32Array(v+1),O=new Int32Array(E),k=new Int32Array(E),A=new Float64Array(E),j=0;for(let e=0;e<v;e++){D[e]=j;for(let[t,n,r]of x[e])O[j]=t,k[j]=n,A[j]=r,j++}D[v]=j;let M=C(a*31337+1),N=new Float64Array(_),P=0;for(let e=0;e<_;e++)N[e]=w(M),P+=N[e]**2;for(let e=0;e<_;e++)N[e]/=Math.sqrt(P);let F=new Float64Array(r);for(let e=0;e<r;e++)F[e]=(M()<.5?-1:1)*(.5+.5*M());return{key:T(n),geom:i,N:r,ratios:m,wavenum:h,pitchK:g,perm:p,Nnl:_,M:v,tStart:D,ti:O,tj:k,tv:A,tb:S,bx:N,rad:F,shape:(e,t,n)=>i.shape(p[e],t,n)}}const D={violin:{name:`Violin`,low:[[275,22,0],[405,30,-12],[470,40,-8],[460,32,0],[540,32,2]],hill:2600,hillDb:6,top:5500},viola:{name:`Viola`,low:[[230,22,0],[340,30,-12],[390,40,-8],[380,32,0],[445,32,2]],hill:2100,hillDb:5,top:4800},cello:{name:`Cello`,low:[[102,20,0],[145,30,-10],[170,40,-8],[178,30,1],[210,30,2]],hill:1500,hillDb:4,top:3500},bass:{name:`Double bass`,low:[[62,18,0],[92,28,-10],[104,38,-8],[112,30,1],[138,30,2]],hill:900,hillDb:3,top:2400},guitar:{name:`Guitar`,low:[[98,18,0],[204,28,3],[230,35,-6],[390,30,-3],[440,35,-2]],hill:2500,hillDb:2,top:5e3}};function O(e,t,n,r=1){let i=D[e];if(!i)return[];let a=C(r*6151+17),o=[];for(let[e,r,s]of i.low){let i=10**(s/20);o.push({f:e/t,q:r/n,gL:i,gR:i*(.8+.4*a())})}let s=1.2*Math.max(...i.low.map(e=>e[0]));for(;s<4.5*i.top;){let e=Math.log2(s/i.hill),r=-6+i.hillDb*Math.exp(-(e*e)/.72);r-=12*Math.max(0,Math.log2(s/i.top));let c=10**((r+3*w(a))/20),l=10**((r+3*w(a))/20);o.push({f:s/t,q:(20+25*a())/n,gL:c*(a()<.5?-1:1),gR:l*(a()<.5?-1:1)}),s*=1+.07*(.5+a())}return o}function k(e,t){let n=0,r=0,i=0,a=0;for(let o of e){let e=t/o.f,s=1-e*e,c=e/o.q,l=s*s+c*c,u=c*c/l,d=c*s/l;n+=o.gL*u,r+=o.gL*d,i+=o.gR*u,a+=o.gR*d}return .5*(n*n+r*r+i*i+a*a)}var A=class{n=0;b0=/* @__PURE__ */ new Float64Array;a1=/* @__PURE__ */ new Float64Array;a2=/* @__PURE__ */ new Float64Array;gL=/* @__PURE__ */ new Float64Array;gR=/* @__PURE__ */ new Float64Array;x1=0;x2=0;y1=/* @__PURE__ */ new Float64Array;y2=/* @__PURE__ */ new Float64Array;key=``;configure(e,t,n,r){let i=`${e}|${t}|${n}|${r}`;if(i===this.key)return;this.key=i;let a=O(e,t,n).filter(e=>e.f<.45*r),o=0,s=0;if(a.length){let e=.8*a[0].f,t=Math.min(1e4,.45*r);for(let n=0;n<=200;n++)o+=k(a,e*(t/e)**(n/200)),s++}let c=s?1/Math.sqrt(o/s):0,l=a.length,u=this.n!==l;if(this.n=l,u)for(let e of[`b0`,`a1`,`a2`,`gL`,`gR`,`y1`,`y2`])this[e]=new Float64Array(l);a.forEach((e,t)=>{let n=2*Math.PI*e.f/r,i=Math.sin(n)/(2*e.q),a=1+i;this.b0[t]=i/a,this.a1[t]=-2*Math.cos(n)/a,this.a2[t]=(1-i)/a,this.gL[t]=e.gL*c,this.gR[t]=e.gR*c})}reset(){this.x1=this.x2=0,this.y1.fill(0),this.y2.fill(0)}tick(e,t){let n=this.n,r=this.b0,i=this.a1,a=this.a2,o=this.y1,s=this.y2,c=this.gL,l=this.gR,u=e-this.x2;this.x2=this.x1,this.x1=e;let d=0,f=0;for(let e=0;e<n;e++){let t=r[e]*u-i[e]*o[e]-a[e]*s[e];s[e]=o[e],o[e]=t,d+=c[e]*t,f+=l[e]*t}t[0]=d,t[1]=f}};const j=.5,M=1e-14,N=.002,P=.05,F=e=>{let t=Math.abs(e);return t+Math.log1p(Math.exp(-2*t))-Math.LN2},I=6.907755,ee=10**-9,L=.1;var te=class{idx;active=!1;note=60;baseHz=261.6;vel=1;gate=!1;held=!1;sustained=!1;touching=!1;damped=!0;order=0;N=0;nAct=0;nTune=0;cull=1/0;nNL=0;nNLTune=0;q=/* @__PURE__ */ new Float64Array;qp=/* @__PURE__ */ new Float64Array;qn=/* @__PURE__ */ new Float64Array;A=/* @__PURE__ */ new Float64Array;B=/* @__PURE__ */ new Float64Array;C=/* @__PURE__ */ new Float64Array;om=/* @__PURE__ */ new Float64Array;sw=/* @__PURE__ */ new Float64Array;sw2=/* @__PURE__ */ new Float64Array;grad=/* @__PURE__ */ new Float64Array;pv=/* @__PURE__ */ new Float64Array;gp=/* @__PURE__ */ new Float64Array;phiE=/* @__PURE__ */ new Float64Array;phiB=/* @__PURE__ */ new Float64Array;wL=/* @__PURE__ */ new Float64Array;wR=/* @__PURE__ */ new Float64Array;wsum=0;omega1=1;Z0=1;tunedPitch=-1;tunedDamp=-1;tunedGate=!1;glideMul=1;tunedGlide=1;vibMul=1;tunedVib=1;vibPh=0;vibAge=0;vibRateJ=1;dirtyTune=!0;dirtyVec=!0;posX=-1;posY=-1;ham=!1;hz=0;hzp=0;hzn=0;hamISM=1;hamK=0;hamA=2.5;hamTimer=0;gz=0;buzzK=0;buzzGap=0;buzzPhi1=1;beta=.11;env=0;fLaw=0;nz=0;f=0;fb=/* @__PURE__ */ new Float32Array(32768);fbW=0;bx1=0;bx2=0;by1=0;by2=0;S=0;X=0;Vv=0;useG=!1;fast=!1;tc=0;tq=0;pred=!1;energy=0;outMono=0;constructor(e){this.idx=e}alloc(e){let t=t=>{let n=new Float64Array(e);return n.set(t.subarray(0,Math.min(e,t.length))),n};this.q=t(this.q),this.qp=t(this.qp),this.qn=new Float64Array(e);for(let t of[`A`,`B`,`C`,`om`,`sw`,`sw2`,`grad`,`pv`,`gp`,`phiE`,`phiB`,`wL`,`wR`])this[t]=new Float64Array(e);this.N=e,this.dirtyTune=this.dirtyVec=!0}reset(){this.q.fill(0),this.qp.fill(0),this.qn.fill(0),this.ham=!1,this.env=0,this.fLaw=0,this.fb.fill(0),this.bx1=this.bx2=this.by1=this.by2=0,this.energy=0,this.uncull()}uncull(){this.cull=1/0,this.nAct=this.nTune,this.nNL=this.nNLTune}};const ne=e=>440*2**((e-69)/12),re=e=>e<0?0:e>1?1:e,R=e=>e-Math.floor(e);var ie=class{sr;h;p={...u};model;voices=[];act=[];eps=M;vMax=0;vHold=0;psi=Math.sqrt(M);psiReset=!1;order=0;bend=0;sustain=!1;lastNote=60;focus=null;touchVoice=null;pending=[];post=()=>{};paramVersion=0;rngS=0x9e3779b9;lfoPh=[0,0];lfoA=[0,0];lfoB=[0,0];kt=0;kc=0;cc=0;ct=0;cl=0;crossOn=!1;buzzA=1.5;buzzTwo=!1;ampMul=1;fbMul=1;excMul=1;pitchMul=1;dampMul=1;posOff=0;pickOff=0;vecVersion=-1;lastPosOff=0;lastPickOff=0;law=0;lwF=0;lwVb=0;lwGam=0;lwD=0;lawK=/* @__PURE__ */ new Float64Array(3);envAtt=0;envRel=0;noiseC=0;noiseNorm=1;fbD=1;fb0=0;fb2=0;fa1=0;fa2=0;snapCount=0;cpuMs=0;cpuWall=0;cpu=0;lastTouch=null;box=new A;boxOut=/* @__PURE__ */ new Float64Array(2);constructor(e){this.sr=e,this.h=1/e,this.model=E(this.p);for(let e=0;e<16;e++){let t=new te(e);t.alloc(this.model.N),this.voices.push(t)}}message(e){e.type===`params`?this.setParams(e.params):this.pending.push(e)}setParams(n){if(this.p={...u,...n},this.paramVersion++,T(this.p)!==this.model.key){this.model=E(this.p);for(let e of this.voices)e.alloc(this.model.N);this.psiReset=!0}for(let e of this.voices)e.dirtyTune=e.dirtyVec=!0;let r=t(this.p,`soundbox`);r===`off`?(this.box.configure(``,1,1,this.sr),this.box.reset()):this.box.configure(r,e(this.p,`boxSize`),e(this.p,`boxDamp`),this.sr)}handle(e){switch(e.type){case`noteOn`:this.noteOn(e.note,e.vel,e.x,e.y);break;case`noteOff`:this.noteOff(e.note);break;case`sustain`:if(this.sustain=e.on,!e.on)for(let e of this.voices)e.sustained&&(e.sustained=!1,this.updateGate(e));break;case`bend`:this.bend=e.value;break;case`touchStart`:this.touchStart(e.x,e.y,e.vel);break;case`touchMove`:this.lastTouch={x:e.x,y:e.y},this.touchVoice&&(this.touchVoice.posX=e.x,this.touchVoice.posY=e.y,this.touchVoice.dirtyVec=!0);break;case`touchEnd`:this.lastTouch=null,this.touchVoice&&=(this.touchVoice.touching=!1,this.updateGate(this.touchVoice),null);break;case`panic`:for(let e of this.voices)e.reset(),e.active=!1;this.box.reset(),this.psi=Math.sqrt(this.eps)}}allocVoice(t){let n=this.voices.find(e=>e.active&&e.note===t);if(n)return n;let r=Math.round(e(this.p,`voices`)),i=this.voices.filter(e=>e.active);return i.length>=r?(i.sort((e,t)=>Number(e.gate)-Number(t.gate)||e.energy-t.energy||e.order-t.order),n=i[0]):n=this.voices.find(e=>!e.active),n.reset(),n.active=!0,n.glideMul=1,n.vibMul=1,n.vibPh=this.rand(),n.vibRateJ=1+.1*(this.rand()*2-1),n.note=t,n.baseHz=ne(t),n.held=n.sustained=n.touching=!1,n.gate=!1,n.dirtyTune=n.dirtyVec=!0,n.tunedPitch=-1,this.psiReset=!0,n}updateGate(e){let t=e.held||e.sustained||e.touching;t!==e.gate&&(e.gate=t,e.dirtyTune=!0)}noteOn(e,t,n,r){let i=this.allocVoice(e);i.uncull(),i.order=++this.order,i.vel=Math.max(.01,Math.min(1,t)),i.held=!0,i.damped=!0,i.vibAge=0,i.posX=n??-1,i.posY=r??-1,i.dirtyVec=!0,this.updateGate(i),this.lastNote=e,this.focus=i,this.prepare(i),this.excite(i,i.vel)}noteOff(e){for(let t of this.voices)t.active&&t.note===e&&t.held&&(t.held=!1,this.sustain&&(t.sustained=!0),this.updateGate(t))}touchStart(e,t,n){this.lastTouch={x:e,y:t};let r=this.focus&&this.focus.active?this.focus:null;r||(r=this.allocVoice(this.lastNote),r.order=++this.order,r.damped=!1,this.focus=r),r.posX=e,r.posY=t,r.vel=n,r.dirtyVec=!0;let i=this.law!==0;i&&(r.touching=!0,this.touchVoice=r,this.updateGate(r)),this.prepare(r),i||this.excite(r,n)}prepare(e){e.dirtyVec&&this.vecVoice(e),(e.dirtyTune||e.tunedPitch!==this.pitchMul||e.tunedDamp!==this.dampMul||e.tunedGate!==e.gate||e.tunedGlide!==e.glideMul||e.tunedVib!==e.vibMul)&&this.tuneVoice(e)}excite(n,r){n.uncull();let i=t(this.p,`exciter`),a=j*(e(this.p,`strength`)*r)**2;if(a<=0)return;let o=n.nAct,s=n.phiE,c=n.om,l=this.h;if(i===`strike`){let t=e(this.p,`hammerMass`),r=e(this.p,`hardness`)/1e3,i=e(this.p,`feltExp`),c=Math.sqrt(2*a/t),u=Math.sqrt(2*j/t)*r/Math.PI,d=0,f=0;for(let e=0;e<o;e++)d+=s[e]*n.q[e],f+=s[e]*(n.q[e]-n.qp[e])/l;let p=Math.sqrt(t);n.ham=!0,n.hamTimer=0,n.hamISM=1/p,n.hamK=t*(Math.PI/r)**2/u**(i-1),n.hamA=i,n.hz=d*p,n.hzp=(d-(f+c)*l)*p}else if(i===`pluck`){let e=0;for(let t=0;t<o;t++)e+=s[t]*s[t]/(c[t]*c[t]);if(e<=0)return;let t=Math.sqrt(2*a/e);for(let e=0;e<o;e++){let r=t*s[e]/(c[e]*c[e]);n.q[e]+=r,n.qp[e]+=r}this.psiReset=!0}else if(i===`impulse`){let t=e(this.p,`hardness`)/1e3,r=0,i=n.qn;for(let e=0;e<o;e++){let n=c[e]*t/2,a=1-(n/Math.PI)**2,o=n<1e-9?1:Math.abs(a)<1e-6?.5:Math.abs(Math.sin(n)/n/a);i[e]=s[e]*o,r+=i[e]*i[e]}if(r<=0)return;let u=Math.sqrt(2*a/r);for(let e=0;e<o;e++)n.qp[e]-=l*u*i[e];i.fill(0)}}tuneVoice(t){let n=this.model,r=n.N,i=this.h,a=this.p,o=t.baseHz*this.pitchMul*t.glideMul*t.vibMul,s=I/e(a,`t60`),c=e(a,`hfDamp`),l=e(a,`damper`),u=!t.gate&&t.damped&&l<19.9?I/l:0,d=.45*this.sr,f=0,p=0;for(let e=0;e<r;e++){let r=o*n.ratios[e],a=2*Math.PI*r;if(t.om[e]=a,r>=d){t.A[e]=t.B[e]=t.C[e]=t.sw[e]=t.sw2[e]=0;continue}f=e+1;let l=(s+c*(r/1e3)**2)*this.dampMul+u,m=Math.exp(-l*i);if(l<a)t.A[e]=2*m*Math.cos(Math.sqrt(a*a-l*l)*i);else{let n=Math.sqrt(l*l-a*a)*i;t.A[e]=m*(Math.exp(n)+Math.exp(-n))}t.B[e]=m*m,t.C[e]=i*i/(1+Math.tanh(l*i));let h=2-2*Math.cos(a*i),g=Math.max(0,Math.min(1,(3.6/h-1)/12));t.sw[e]=a*Math.sqrt(g),t.sw2[e]=a*a*g,g>0&&(p=e+1)}for(let e=f;e<r;e++)t.q[e]=t.qp[e]=0;t.nTune=f,t.nNLTune=Math.min(p,f),t.nAct=Math.min(f,t.cull),t.nNL=Math.min(t.nNLTune,t.nAct),t.omega1=2*Math.PI*o,t.Z0=2*o;let m=0;for(let e=0;e<f;e++)m+=t.phiE[e]*t.phiE[e]*t.C[e];t.wsum=m;let h=+Math.max(t.buzzPhi1,.05)/t.omega1,g=e(a,`buzz`);t.buzzGap=e(a,`buzzGap`)*h,t.buzzK=g>0?g*(2*Math.PI*4e3)**2*.1*h**(1-this.buzzA):0,t.tunedPitch=this.pitchMul,t.tunedDamp=this.dampMul,t.tunedGate=t.gate,t.tunedGlide=t.glideMul,t.tunedVib=t.vibMul,t.dirtyTune=!1}vecVoice(t){let n=this.model,r=n.N,i=this.p,a=t.posX>=0?t.posX:re(e(i,`exPos`)+this.posOff),o=t.posY>=0?t.posY:re(e(i,`exPosY`)+this.posOff),s=e(i,`exWidth`)*.15,c=e(i,`buzzPos`),l=e(i,`buzzPosY`),u=R(e(i,`pickup`)+this.pickOff),d=e(i,`pickupY`),f=e(i,`width`),p=R(u+.5*f),m=R(d+.37*f),h=e(i,`spread`),g=e(i,`tilt`)/6.0206;for(let e=0;e<r;e++){let i=Math.exp(-.5*(Math.PI*n.wavenum[e]*s)**2);t.phiE[e]=n.shape(e,a,o)*i,t.phiB[e]=n.shape(e,c,l);let f=n.ratios[e]**+g;t.wL[e]=((1-h)*n.shape(e,u,d)+h*n.rad[e])*f,t.wR[e]=((1-h)*n.shape(e,p,m)+h*n.rad[(e+1)%r]*(e%2?1:-1))*f}t.buzzPhi1=Math.abs(n.shape(n.pitchK,c,l)),t.beta=Math.max(.02,Math.min(a,1-a)),t.dirtyVec=!1,t.dirtyTune=!0}rand(){let e=this.rngS;return e^=e<<13,e^=e>>>17,e^=e<<5,this.rngS=e>>>0,this.rngS/4294967296}lfo(n,r){let i=this.p,a=e(i,`lfo${n+1}Rate`),o=this.lfoPh[n]+a*r;switch(o>=1&&(o-=Math.floor(o),this.lfoA[n]=this.lfoB[n],this.lfoB[n]=this.rand()*2-1),this.lfoPh[n]=o,t(i,`lfo${n+1}Shape`)){case`tri`:return 1-4*Math.abs(o-.5);case`saw`:return 2*o-1;case`square`:return o<.5?1:-1;case`sh`:return this.lfoB[n];case`smooth`:return this.lfoA[n]+(this.lfoB[n]-this.lfoA[n])*(.5-.5*Math.cos(Math.PI*o));default:return Math.sin(2*Math.PI*o)}}blockUpdate(n){let r=this.p,i=this.sr,a=n/i,o=this.bend*e(r,`bendRange`),s=1,c=0,l=0,u=e(r,`tension`),d=e(r,`cascade`),f=1,p=1,m=1;for(let n=0;n<2;n++){let i=t(r,`lfo${n+1}Target`);if(i===`off`)continue;let h=e(r,`lfo${n+1}Depth`),g=this.lfo(n,a)*h;switch(i){case`pitch`:o+=4*g;break;case`amp`:s*=Math.max(0,1+g);break;case`position`:c+=.5*g;break;case`pickup`:l+=.5*g;break;case`tension`:u*=Math.max(0,1+g);break;case`cascade`:d*=Math.max(0,1+g);break;case`damping`:f*=2**(3*g);break;case`feedback`:p*=Math.max(0,1+g);break;case`exciter`:m*=Math.max(0,1+g)}}this.pitchMul=2**(o/12),this.dampMul=f,this.ampMul=s,this.fbMul=p,this.excMul=m,this.kt=u,this.kc=this.model.M>0?d:0,this.cc=+e(r,`curvature`),this.ct=e(r,`crossTension`),this.cl=e(r,`crossLink`),this.crossOn=this.ct>0||this.cl>0,this.buzzTwo=t(r,`buzzSides`)===`two`;let h=t(r,`exciter`);this.law=h===`bow`?1:h===`reed`?2:h===`selfosc`?3:h===`noise`?4:0;let g=this.lawK;this.law===1?(g[0]=e(r,`bowSpeed`)*.5,g[1]=+e(r,`bowForce`),g[2]=e(r,`bowNoise`)):this.law===2?(g[0]=e(r,`reedGain`)*2,g[1]=e(r,`reedPressure`),g[2]=e(r,`breath`)):this.law===3&&(g[0]=+e(r,`selfGain`),g[1]=e(r,`selfSat`)),this.envAtt=1-Math.exp(-1/(e(r,`attack`)/1e3*i)),this.envRel=1-Math.exp(-1/(e(r,`release`)/1e3*i));let _=Math.min(e(r,`noiseColor`),.45*i);this.noiseC=1-Math.exp(-2*Math.PI*_/i),this.noiseNorm=Math.sqrt(3*(2-this.noiseC)/this.noiseC),this.fbD=Math.max(1,Math.min(32767,Math.round(e(r,`fbDelay`)/1e3*i)));let v=2*Math.PI*Math.min(e(r,`fbFreq`),.45*i)/i,y=Math.sin(v)/(2*e(r,`fbQ`)),b=1+y;this.fb0=y/b,this.fb2=-y/b,this.fa1=-2*Math.cos(v)/b,this.fa2=(1-y)/b;let x=c!==this.lastPosOff||l!==this.lastPickOff||this.vecVersion!==this.paramVersion;this.posOff=c,this.pickOff=l,this.lastPosOff=c,this.lastPickOff=l,this.vecVersion=this.paramVersion;let S=e(r,`vibDepth`),C=e(r,`vibRate`),w=e(r,`vibDelay`)/1e3;this.act.length=0;for(let e of this.voices)if(e.active){if(S>0){e.vibAge+=a;let t=e.vibAge,n=w>0?(t-.3*w)/(.7*w):1;n=n<0?0:n>1?1:n*n*(3-2*n),e.vibPh+=C*e.vibRateJ*(1+.06*Math.sin(2.3*t+7*e.vibRateJ))*a,e.vibPh-=Math.floor(e.vibPh);let r=2**(S*n*Math.sin(2*Math.PI*e.vibPh)/1200);(Math.abs(r/e.vibMul-1)>1e-5||n===0&&e.vibMul!==1)&&(e.vibMul=r)}else e.vibMul=1;x&&(e.dirtyVec=!0),this.prepare(e),this.act.push(e)}}nl(e){if(this.kt<=0&&this.ct<=0&&this.kc<=0&&!this.crossOn&&!e.ham&&e.buzzK<=0){e.S=e.X=e.Vv=e.gz=0,e.useG=!1;return}let t=e.nAct,n=e.q,r=e.sw,i=e.grad,a=this.model,o=0,s=!1,c=e.nNL,l=0;if(this.kt>0||this.ct>0||this.kc>0)for(let e=0;e<c;e++){let t=r[e]*n[e];l+=t*t}if(e.S=l,i.fill(0,0,t),e.gz=0,this.kt>0&&l>0){let e=3/this.kt,t=l/j;o+=this.kt*j*.5*e*e*F(t/e);let a=this.kt*e*Math.tanh(t/e);for(let e=0;e<c;e++)i[e]+=a*r[e]*r[e]*n[e];s=!0}let u=this.kc;if(u>0){let t=a.Nnl,l=Math.min(c,t),d=e.pv,f=e.gp,p=this.cc,m=3/(u*a.M);for(let e=0;e<t;e++)d[e]=e<l?r[e]*n[e]:0,f[e]=0;let h=a.ti,g=a.tj,_=a.tv,v=a.tb;for(let e=0;e<a.M;e++){let n=a.tStart[e],r=a.tStart[e+1],i=0;for(let e=n;e<r;e++)i+=_[e]*d[h[e]]*d[g[e]];let s=0,c=e*t;if(p!==0)for(let e=0;e<l;e++)s+=v[c+e]*d[e];let y=(i+p*s)/j;o+=u*j*m*m*F(y/m);let b=u*m*Math.tanh(y/m),x=2*b;for(let e=n;e<r;e++)f[h[e]]+=x*_[e]*d[g[e]];let S=b*p;if(S!==0)for(let e=0;e<l;e++)f[e]+=S*v[c+e]}for(let e=0;e<l;e++)i[e]+=r[e]*f[e];s=!0}if(e.ham){let r=e.phiE,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=e.hz*e.hamISM-a;if(c>0){let n=e.hamA,a=e.hamK*c**+n;o+=a*c/(n+1);for(let e=0;e<t;e++)i[e]-=a*r[e];e.gz=a*e.hamISM,e.hamTimer=0,s=!0}else++e.hamTimer>.05*this.sr&&(e.ham=!1)}if(e.buzzK>0){let r=e.phiB,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=this.buzzA,l=0,u=a-e.buzzGap;if(u>0){let t=e.buzzK*u**+c;o+=t*u/(c+1),l+=t}if(this.buzzTwo){let t=-a-e.buzzGap;if(t>0){let n=e.buzzK*t**+c;o+=n*t/(c+1),l-=n}}if(l!==0){for(let e=0;e<t;e++)i[e]+=l*r[e];s=!0}}if(this.crossOn){let t=0,r=Math.min(c,a.Nnl),i=a.bx;if(this.cl>0)for(let a=0;a<r;a++)t+=i[a]*e.sw[a]*n[a];e.X=.5*this.ct*l+this.cl*1*t}else e.X=0;e.Vv=o,e.useG=s||this.crossOn}nlTension(e){let t=e.nNL,n=e.q,r=e.qp,i=e.sw2,a=0,o=0;for(let e=0;e<t;e++){let t=i[e]*n[e];a+=t*n[e],o+=t*r[e]}if(e.S=a,e.X=0,e.gz=0,e.fast=!0,a>0){let t=3/this.kt,n=a/j;e.Vv=this.kt*j*.5*t*t*F(n/t),e.tc=this.kt*t*Math.tanh(n/t),e.tq=e.tc===0?0:o,e.useG=!0}else e.Vv=0,e.tc=0,e.tq=0,e.useG=!1}lawEval(e){let t=0,n=0;if(this.law===1){let r=e-this.lwVb,i=Math.tanh(r/N),a=1+Math.abs(r)/P,o=.35+.65/a,s=-.65/(P*a*a)*(r>=0?1:-1);t=-this.lwF*i*o,n=-this.lwF*((1-i*i)/N*o+i*s)}else if(this.law===2){let r=this.lwGam-e;if(r<1){let e=Math.sqrt(Math.abs(r)+1e-9),i=this.lwF;r>=0?(t=i*(1-r)*e,n=-i*(-e+(1-r)/(2*e))):(t=-i*(1-r)*e,n=-i*(e+(1-r)/(2*e)))}}else{let r=this.lwF,i=this.lwVb;t=r*(e-e*e*e/(3*i*i)),n=r*(1-e*e/(i*i))}return this.lwD=n,t}solveLaw(e,t,n){let r=e.nAct,i=e.phiE,a=e.A,o=e.B,s=e.q,c=e.qp,l=e.qn,u=0;for(let e=0;e<r;e++){let t=a[e]*s[e]-o[e]*c[e];l[e]=t,u+=i[e]*(t-c[e])}e.pred=!0;let d=.5/this.h,f=(u+t*e.wsum)*d,p=e.wsum*d,m=e.env*this.excMul,h=e.Z0,g=this.lawK;if(this.law===1){this.lwVb=g[0]*m;let t=g[2];this.lwF=g[1]*h*(this.lwVb/.05)*(.11/e.beta)*(t>0?Math.max(0,1+t*n):1)}else this.law===2?(this.lwF=g[0]*h,this.lwGam=g[1]*m*(1+g[2]*n)):(this.lwF=g[0]*h*m,this.lwVb=g[1]);let _=this.lwF+1e-9,v=1e-9*_,y=e.fLaw,b=!1;for(let e=0;e<8;e++){let e=y-this.lawEval(f+p*y);if(Math.abs(e)<v){b=!0;break}let t=1-p*this.lwD;if(t<.05)break;y-=e/t}if(!b||!Number.isFinite(y)){let t=Number.isFinite(e.fLaw)?e.fLaw:0,n=.01*_,r=t,i=t,a=0,o=0;for(let e=0;e<60&&(r=t-n,i=t+n,a=r-this.lawEval(f+p*r),o=i-this.lawEval(f+p*i),!(a<=0&&o>=0));e++)n*=2;for(let e=0;e<50;e++){let e=.5*(r+i);e-this.lawEval(f+p*e)<0?r=e:i=e}y=.5*(r+i),Number.isFinite(y)||(y=0)}return e.fLaw=y,y}process(t,n,r,i=0){let a=Date.now(),o=r/this.sr;if(this.pending.length){let e=[];for(let t of this.pending)(`time`in t&&t.time!==void 0?t.time:0)<=i+o?this.handle(t):e.push(t);this.pending=e}this.blockUpdate(r);let s=this.act,c=this.h,l=c*c,u=1/c,d=this.p,f=e(d,`fbGain`)*this.fbMul,p=e(d,`fbSat`),m=e(d,`noiseLevel`),h=this.law,g=h===4||h===3||h===2&&e(d,`breath`)>0||h===1&&e(d,`bowNoise`)>0,_=this.box,v=_.n>0,y=v?e(d,`boxMix`):0,b=1-y,x=this.boxOut,S=.25*this.ampMul*u*10**(e(d,`level`)/20),C=32767,w=this.kt>0&&this.kt<=L&&this.kc<=0&&!this.crossOn;for(let e=0;e<r;e++){let r=0,i=0,a=!1;for(let e=0;e<s.length;e++){let t=s[e];t.env+=((t.gate?t.vel:0)-t.env)*(t.gate?this.envAtt:this.envRel);let n=0;if(t.env>1e-6){let e=0;if(g&&(t.nz+=this.noiseC*(this.rand()*2-1-t.nz),e=t.nz*this.noiseNorm),f>0){let e=t.fb[t.fbW-this.fbD&C],r=this.fb0*e+this.fb2*t.bx2-this.fa1*t.by1-this.fa2*t.by2;t.bx2=t.bx1,t.bx1=e,t.by2=t.by1,t.by1=r,n+=p*t.Z0*Math.tanh(f*r/p)*t.env}h===3&&(n+=.001*t.Z0*t.env*e),h===4?n+=m*t.Z0*t.env*this.excMul*e*.5:h!==0&&(n+=this.solveLaw(t,n,e))}else t.fLaw=0;t.f=n,w&&!t.ham&&t.buzzK<=0?this.nlTension(t):(t.fast=!1,this.nl(t)),r+=t.Vv,i+=t.X,t.useG&&(a=!0)}if(this.crossOn&&s.length){let e=i/j;r+=j*3*3*F(e/3);let t=3*Math.tanh(e/3),n=this.ct,a=+this.cl,o=this.model.bx,c=this.model.Nnl;for(let e of s){let r=e.nNL,i=e.grad,s=e.q,l=e.sw;for(let e=0;e<r;e++)i[e]+=t*(n*l[e]*l[e]*s[e]+(e<c?a*o[e]*l[e]:0))}}let o=0;if(!a)this.psi=Math.sqrt(this.eps);else{r>this.vMax&&(this.vMax=r),this.psiReset&&(this.eps=.01);let e=Math.sqrt(2*r+this.eps),t=1/e;if(this.psiReset)this.psi=e,this.psiReset=!1;else{let t=this.psi+.01*(e-this.psi);Math.abs(t)<Math.abs(this.psi)&&(this.psi=t)}let n=0;for(let e of s){if(!e.useG)continue;if(e.fast){n+=e.tc*e.tq;continue}let t=e.nAct,r=e.grad,i=e.qp;for(let e=0;e<t;e++)n+=r[e]*i[e];e.ham&&(n+=e.gz*e.hzp)}n*=t;let i=this.psi,a=n/4-i,c=0,u=0;for(let e of s){if(!e.useG)continue;e.pred=!1;let n=e.nAct,r=e.q,i=e.qp,o=e.qn,s=e.A,d=e.B,f=e.C,p=e.phiE,m=e.f;if(e.fast){let l=e.nNL,h=e.sw2,g=e.tc*t;for(let e=0;e<l;e++){let t=g*h[e]*r[e],n=f[e],l=s[e]*r[e]-d[e]*i[e]+n*(p[e]*m+t*a);o[e]=l,c+=t*l,u+=n*t*t}for(let e=l;e<n;e++)o[e]=s[e]*r[e]-d[e]*i[e]+f[e]*p[e]*m;continue}let h=e.grad;for(let e=0;e<n;e++){let n=h[e]*t,l=s[e]*r[e]-d[e]*i[e]+f[e]*(p[e]*m+n*a);o[e]=l,c+=n*l,u+=f[e]*n*n}if(e.ham){let n=e.gz*t,r=2*e.hz-e.hzp+l*n*a;e.hzn=r,c+=n*r,u+=l*n*n}}let d=c/(1+u/4);o=d*t/4;for(let e of s){if(!e.useG||e.fast)continue;let t=e.nAct,n=e.grad,r=e.qn,i=e.C;for(let e=0;e<t;e++)r[e]-=i[e]*n[e]*o;e.ham&&(e.hzn-=l*e.gz*o)}this.psi=i+(d-n)/2}let c=0,d=0;for(let e of s){let t=e.nAct,n=e.q,r=e.qp,i=e.qn,a=e.wL,s=e.wR,l=0,f=0;if(!e.useG){let o=e.A,c=e.B,u=e.C,d=e.phiE,p=e.f;if(e.pred){e.pred=!1;for(let e=0;e<t;e++){let t=i[e]+u[e]*d[e]*p;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}}else if(p!==0)for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e]+u[e]*d[e]*p;i[e]=t;let m=t-n[e];l+=a[e]*m,f+=s[e]*m}else for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e];i[e]=t;let u=t-n[e];l+=a[e]*u,f+=s[e]*u}e.ham&&(e.hzn=2*e.hz-e.hzp)}else if(e.fast){let r=e.nNL,c=e.sw2,u=e.C,d=e.tc*o;for(let e=0;e<r;e++){let t=i[e]-u[e]*c[e]*n[e]*d;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}for(let e=r;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}}else for(let e=0;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}c+=l,d+=f,e.fb[e.fbW]=.5*(l+f)*u,e.fbW=e.fbW+1&C;let p=e.qp;e.qp=e.q,e.q=e.qn,e.qn=p,e.ham&&(e.hzp=e.hz,e.hz=e.hzn)}v?(_.tick(.5*(c+d)*S,x),t[e]=b*c*S+y*x[0],n[e]=b*d*S+y*x[1]):(t[e]=c*S,n[e]=d*S)}this.blockEnd(r),this.cpuMs+=Date.now()-a,this.cpuWall+=o*1e3}blockEnd(t){let n=1/this.h,r=this.kc<=0&&this.kt<=L&&!this.crossOn&&!(e(this.p,`fbGain`)>0);for(let t of this.act){let i=t.nAct,a=t.q,o=t.qp,s=t.om,c=0,l=0;for(let e=0;e<i;e++){let t=(a[e]-o[e])*n,r=.5*(t*t+s[e]*s[e]*a[e]*a[e]);c+=r,r>l&&(l=r)}if(r&&!t.ham&&t.buzzK<=0&&(this.law===0||t.env<=1e-6)){let e=l*ee,r=i;for(;r>1;){let t=r-1,i=(a[t]-o[t])*n;if(.5*(i*i+s[t]*s[t]*a[t]*a[t])>e)break;r--}if(r<i){for(let e=r;e<i;e++)a[e]=o[e]=0;t.cull=r,t.nAct=r,t.nNL=Math.min(t.nNLTune,r)}}else t.cull!==1/0&&t.uncull();if(!Number.isFinite(c)||c>1e8){t.reset(),t.active=!1,this.psiReset=!0;continue}t.energy=c;let u=e(this.p,`glide`),d=1;if(u!==0){let e=4*c/j;d=2**(u*e/(1+e)/12)}(Math.abs(d/t.glideMul-1)>2e-5||d===1&&t.glideMul!==1)&&(t.glideMul=d),!t.gate&&!t.ham&&c<1e-10&&t.env<1e-4&&(t.active=!1)}let i=0;for(let e of this.act)e.active&&(i+=e.energy);this.vHold=Math.max(this.vMax,this.vHold*.95),this.vMax=0;let a=Math.max(M,.02*i+2*this.vHold);if(a<this.eps){let e=Math.max(a,this.eps*.95),t=this.psi*this.psi-(this.eps-e);this.psi=(this.psi<0?-1:1)*Math.sqrt(Math.max(0,t)),this.eps=e}this.snapCount+=t,this.snapCount>=this.sr/30&&(this.snapCount=0,this.cpuWall>0&&(this.cpu=this.cpuMs/this.cpuWall),this.cpuMs=this.cpuWall=0,this.snapshot())}snapshot(){let e=this.focus&&this.focus.active?this.focus:null;if(!e)for(let t of this.voices)t.active&&(!e||t.order>e.order)&&(e=t);let t=this.model.N,n=new Float32Array(t),r=new Float32Array(t),i=new Float32Array(t),a=new Float32Array(t);if(e){let o=1/this.h;for(let s=0;s<t;s++){n[s]=e.q[s];let t=(e.q[s]-e.qp[s])*o;r[s]=t,i[s]=.5*(t*t+e.om[s]*e.om[s]*e.q[s]*e.q[s]),a[s]=e.om[s]/(2*Math.PI)}}let o=[];for(let e of this.voices)e.active&&o.push(e.note);let s={type:`snap`,cpu:this.cpu,nVoices:o.length,notes:o,focusNote:e?e.note:-1,focusHz:e?e.baseHz*this.pitchMul:0,nAct:e?e.nAct:0,q:n,qd:r,energy:i,freqs:a,touch:this.lastTouch};this.post(s,[n.buffer,r.buffer,i.buffer,a.buffer])}};const z=1024;let B=null,V=48e3,H=null,U=0,W=0,G=48e3,K=0,q=!1,J=!1,Y=[],ae=0,X=0,Z=0,oe=0;const Q=e=>self.postMessage(e);self.onmessage=e=>{let t=e.data;switch(t.type){case`init`:V=t.sampleRate,B=new ie(V),B.message({type:`params`,params:{...u,...t.params}}),H=t.port,H.onmessage=e=>{W=Math.max(W,e.data.consumed),ae=e.data.underruns,$()},U=t.startFrame,W=t.startFrame,K=t.startFrame,G=t.aheadFrames,q=!0,Q({type:`ready`}),$();break;case`synth`:B?.message(t.msg);break;case`horizon`:K=Math.max(K,Math.floor(t.time*V)),$();break;case`timedParams`:Y.push({time:t.time,params:t.params}),Y.sort((e,t)=>e.time-t.time);break;case`stop`:q=!1,H?.close();break;case`bench`:Q({type:`bench`,load:ce(t)})}};function $(){!J&&q&&(J=!0,setTimeout(se,0))}function se(){if(J=!1,!q||!B||!H||(U<W&&(U=Math.ceil(W/128)*128),U>=W+G||U+z>K))return;let e=performance.now(),t=new Float32Array(z),n=new Float32Array(z),r=/* @__PURE__ */ new Float32Array(128),i=/* @__PURE__ */ new Float32Array(128);for(let e=0;e<z;e+=128){let a=(U+e)/V;for(;Y.length&&Y[0].time<=a;)B.message({type:`params`,params:{...u,...Y.shift().params}});r.fill(0),i.fill(0),B.process(r,i,128,a),t.set(r,e),n.set(i,e)}let a={frame:U,L:t,R:n};H.postMessage(a,[t.buffer,n.buffer]),U+=z,X+=performance.now()-e,Z+=z/V*1e3,(Z>=1e3||performance.now()-oe>1e3)&&(Q({type:`load`,load:Z>0?X/Z:0,underruns:ae}),X=Z=0,oe=performance.now()),$()}function ce(e){let t=new ie(e.sampleRate);t.message({type:`params`,params:{...u,...e.params}});for(let n of e.notes)t.message({type:`noteOn`,note:n.note,vel:n.vel,time:n.time}),t.message({type:`noteOff`,note:n.note,time:n.time+n.len});let n=/* @__PURE__ */ new Float32Array(128),r=/* @__PURE__ */ new Float32Array(128),i=Math.round(e.seconds*e.sampleRate),a=Math.round(e.warmup*e.sampleRate),o=performance.now();for(let s=0;s<i;s+=128)s===Math.floor(a/128)*128&&(o=performance.now()),n.fill(0),r.fill(0),t.process(n,r,128,s/e.sampleRate);let s=(i-Math.floor(a/128)*128)/e.sampleRate;return(performance.now()-o)/1e3/s}
\ No newline at end of file
site/assets/scoreWorker-B3-6tjqi.jsadded+1−0View file
@@ -0,0 +1 @@
1+function e(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}}const t=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)),n=e=>(t.setFloat64(0,e),t.getInt32(0)),r=(e,n)=>(t.setInt32(0,e),t.setInt32(4,n),t.getFloat64(0)),i=e=>(t.setFloat64(0,e),t.getInt32(4));function a(e,t){let n=e*e,r=n*e,i=.00833333333332249+n*(-.0001984126982985795+n*(27557313707070068e-22+n*(-2.5050760253406863e-8+n*158969099521155e-24)));return e-(n*(.5*t-r*i)-t-r*-.16666666666666632)}function o(e,t){let n=e*e,r=n*(.0416666666666666+n*(-.001388888888887411+n*(2480158728947673e-20+n*(-2.7557314351390663e-7+n*(2.087572321298175e-9+n*-11359647557788195e-27))))),i=.5*n,a=1-i;return a+(1-a-i+(n*r-e*t))}let s=0,c=0;function l(e){let t=Math.round(e*.6366197723675814),n=e-t*1.5707963267341256,r=t*6077100506303966e-26,i;return i=n-r,r=t*20222662487959506e-37-(n-i-r),s=i-r,c=i-s-r,t}function u(e){if(!Number.isFinite(e))return NaN;if(Math.abs(e)<.7853981633974483)return a(e,0);let t=l(e)&3;return t===0?a(s,c):t===1?o(s,c):t===2?-a(s,c):-o(s,c)}function d(e){if(!Number.isFinite(e))return NaN;if(Math.abs(e)<.7853981633974483)return o(e,0);let t=l(e)&3;return t===0?o(s,c):t===1?-a(s,c):t===2?-o(s,c):a(s,c)}const f=.6931471803691238,p=19082149292705877e-26;function m(e,t){for(;t>1023;)e*=r(0x7fe00000,0),t-=1023;for(;t<-1022;)e*=r(1048576,0),t+=1022;return e*r(t+1023<<20,0)}function h(e){if(Number.isNaN(e))return NaN;if(e>709.782712893384)return 1/0;if(e<-745.1332191019411)return 0;let t,n,r,i=Math.abs(e);if(i>.34657359027997264)r=Math.trunc(1.4426950408889634*e+(e<0?-.5:.5)),t=e-r*f,n=r*p,e=t-n;else if(i>3.7252902984e-9)r=0,t=e,n=0;else return 1+e;let a=e*e,o=e-a*(.16666666666666602+a*(-.0027777777777015593+a*(6613756321437934e-20+a*(-16533902205465252e-22+a*4.1381367970572385e-8)))),s=1+(e*o/(2-o)-n+t);return r===0?s:m(s,r)}function g(e){if(Number.isNaN(e)||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return 1/0;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t-=54);let a=n(e),o=i(e);a+=614242,t+=(a>>20)-1023,a=(a&0xfffff)+0x3fe6a09e,e=r(a,o);let s=e-1,c=.5*s*s,l=s/(2+s),u=l*l,d=u*u,m=d*(.3999999999940942+d*(.22222198432149784+d*.15313837699209373));return l*(c+(u*(.6666666666666735+d*(.2857142874366239+d*(.1818357216161805+d*.14798198605116586)))+m))+t*p-c+s+t*f}function _(e,t){if(t===0||e===1)return 1;if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(e===0)return t>0?0:1/0;if(e<0){if(!Number.isInteger(t))return NaN;let n=h(t*g(-e));return t%2==0?n:-n}return t===1?e:t===2?e*e:t===.5?Math.sqrt(e):h(t*g(e))}function v(e,t){return Math.sqrt(e*e+t*t)}function y(e){if(e>20)return 1;if(e<-20)return-1;let t=h(2*e);return(t-1)/(t+1)}const b=6.283185307179586;function x(e){return e-b*Math.floor((e+Math.PI)/b)}var S=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ 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]],f=o-s,p=d(f),m=u(f),h=t+n*m*m,g=(i*c-r*l*p)/(r*r*i*h),_=(r*(t+n)*l-i*n*c*p)/(r*i*i*n*h);return{w1:g,w2:_,T:.5*(c*g+l*_),V:(t+n)*a*r*(1-d(o))+n*a*i*(1-d(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],f=e[3],p=s-c,m=d(p),h=u(p),g=n+r*h*h,_=(a*l-i*f*m)/(i*i*a*g),v=(i*(n+r)*f-a*r*l*m)/(i*a*a*r*g),y=l*f*h/(i*a*g),b=(a*a*r*l*l+i*i*(n+r)*f*f-2*i*a*r*l*f*m)*u(2*p)/(2*i*i*a*a*g*g),x=.5*(l*_+f*v),S=(n+r)*o*i*(1-d(s))+r*o*a*(1-d(c)),C=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;C=(this.eTarget-(x+S))/(this.tau*(2*x+e)),C>t?C=t:C<-t&&(C=-t)}C-=this.damping,t[0]=_,t[1]=v,t[2]=-(n+r)*o*i*u(s)-y+b+C*l,t[3]=-r*o*a*u(c)+y-b+C*f}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,f=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,f=this.derived([c,l,0,0]).V,!(f<.9*o));e++)c=l=0,f=0;let p=o-f,m=t()*2*Math.PI,h=d(m),g=u(m),_=d(c-l),v=(n+r)*i*i,y=r*i*a*_,b=r*a*a,x=.5*(v*h*h+2*y*h*g+b*g*g),S=Math.sqrt(p/x),C=S*h,w=S*g;this.y[0]=c,this.y[1]=l,this.y[2]=v*C+y*w,this.y[3]=y*C+b*w,this.t=0}};function C(e){return x(e)}function w(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}const T=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,E=(...e)=>t=>e.includes(t.geometry),D=(...e)=>t=>e.includes(t.exciter),O=[`bow`,`reed`,`selfosc`,`noise`],k=[[`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`]],A=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function j(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:k,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:A,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}]}const M=[{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:E(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:E(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:E(`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&&T(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:T},{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:D(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:D(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:D(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:D(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:D(`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:D(`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:D(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:D(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:D(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:D(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:D(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:D(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:D(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:D(...O)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:D(...O)},{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},...j(1),...j(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:T},{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`}],N=Object.fromEntries(M.map(e=>[e.id,e])),P=Object.fromEntries(M.map(e=>[e.id,e.def]));M.filter(e=>e.model).map(e=>e.id);const F={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},I=[{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:{...F,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...F,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:{...F,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...F,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:{...F,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}}],ee=[`bow`,`reed`,`selfosc`,`noise`];[...I.map(e=>`modal: ${e.name}`)],[...I.filter(e=>{let t={...P,...e.p};return ee.includes(t.exciter)||t.fbGain>0}).map(e=>`modal: ${e.name}`)];const te=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function ne(e,t,n){let r=N[e];if(!r||r.kind!==`num`)return NaN;let i=Math.max(0,Math.min(1,t));return r.scale===`log`?r.min*n(r.max/r.min,i):r.scale===`pow2`?r.min+(r.max-r.min)*i*i:r.min+(r.max-r.min)*i}function re(e){let t=N[e];return t&&t.min!==void 0&&t.max!==void 0?t.max-t.min:1}var L=class{started=!1;next=0;sent={};P;stem;sink;constructor(e,t,n){this.P=e,this.stem=t,this.sink=n}update(e,t,n){let{P:r,sink:i,stem:a}=this;if(!i.emitting||e<this.next)return;this.next=e+.05,this.started||(this.started=!0,i.cmd(a,{t:e,type:`gain`,value:0,tau:0}),i.cmd(a,{t:e,type:`noteOn`,note:r.humPitch,vel:1}));let o=r.energyPeak,s=Math.max(0,Math.min(1,t/o)),c=Math.min(r.energyStart,.999*o),l=r.humColorMode===`log`?Math.max(0,Math.min(1,g(Math.max(t,1e-12)/c)/g(o/c))):s,u=r.humFadeIn,d=r.humFadeOut,f=Math.max(0,Math.min(1,u>0?e/u:1,n!==null&&d>0?(n-e)/d:1)),p=r.humFollow;i.cmd(a,{t:e,type:`gain`,value:f*(1-p+p*s),tau:.08,normalize:r.humNormalize});let m=_(l,r.humColorCurve),h={},v=!1;for(let e of[1,2]){let t=r[`humTarget${e}`];if(t===`none`||!te.includes(t))continue;let n=r[`humFrom${e}`],i=ne(t,n+(r[`humTo${e}`]-n)*m,_);Number.isFinite(i)&&(h[t]=i,(this.sent[t]===void 0||Math.abs(i-this.sent[t])>.002*re(t))&&(v=!0))}v&&(this.sent=h,i.cmd(a,{t:e,type:`params`,params:h}))}};const 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};Object.keys(ie);const R=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function ae(e){return 440*_(2,(e-69)/12)}function z(e,t,n){if(t===`harmonic series`){let t=ae(n+12*Math.floor((24-n)/12));return 69+12*g(Math.max(1,Math.round(ae(e)/t))*t/440)/g(2)}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}function oe(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=_(a,e.pitchCurve);let o=e.pitchLow,s=e.pitchHigh,c=R.indexOf(e.root),l=z(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)}}const se=.002,ce=(t,n,r)=>{let i=new S({m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio});i.randomize(w(t,0),e(n)),i.tau=t.tau;let a=t.speed,o=t.duration,s=t.restEnergy,c=t.finalHold+t.finalFade+.3,l=new L(t,1,r),u=i.y,d=0,f=C(u[0]),p=u[1],m=u[3],h=null,g=null,_=0,v=0,y=0;function b(){i.eTarget=w(t,d)*i.vTop;let e=d;i.step(se),d+=se/a;let n=C(u[0]);if(h===null&&f<0&&n>=0&&n-f<Math.PI){let a=-f/(n-f),o=e+a*(d-e),s=C(p+a*(u[1]-p)),c=(m+a*(u[3]-m))/i.p2Scale;r.event({t:o,kind:`x`,th2:s,p2:c});let{midi:l,velocity:h}=oe(t,s,c);g=r.note(0,o,l,h,t.noteLength)??g,_++}h===null&&d>=o&&(i.energyNorm()<s||d>=o+10)&&(h=d,g&&r.hold(g,g.t,t.finalHold,t.finalFade),r.end(d+c)),f=n,p=u[1],m=u[3];let b=i.energyNorm();l.update(d,b,h===null?null:h+c),d>=v&&(r.frame(0,d,[u[0],u[1],b]),v=d+.0010416666666666667),d>=y&&(y=d+.1,r.info(d,{"energy target":w(t,d).toFixed(4),energy:b.toFixed(4),notes:String(_)}))}return{get time(){return d},advance(e){for(;d<e;)b()}}};function le(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function ue(e){let t=[],n=[];for(let r=0;r<le(e);r++){let i=e[`slot${r%6+1}Instrument`],a=t.indexOf(i);a<0&&(a=t.push(i)-1),n.push(a)}return{names:t,stemOf:n}}function de(e){return ue(e).names.length}const fe=.003,pe=(t,n,r)=>{let i=t.speed,a=t.duration,o=t.restEnergy,s=t.finalHold+t.finalFade+.3,{stemOf:c}=ue(t),l=new L(t,de(t),r),u=Math.max(1e-4,w(t,0)),d=Array.from({length:le(t)},(r,i)=>{let a=new S({m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio});return a.randomize(u,e(n*1009+i*7919+1)),a.tau=t.tau,{pend:a,prev:C(a.y[0]),prevTh2:a.y[1],prevP2:a.y[3],lastNote:null,restAt:null,stem:c[i],octave:t[`slot${i%6+1}Octave`]}}),f=0,p=null,m=0,h=0,g=0,_=[];function v(){let e=w(t,f),n=f;f+=fe/i,d.forEach((i,s)=>{let c=i.pend,l=c.y;c.eTarget=e*c.vTop,c.step(fe);let u=C(l[0]);if(i.restAt===null&&i.prev<0&&u>=0&&u-i.prev<Math.PI){let e=-i.prev/(u-i.prev),a=n+e*(f-n),o=C(i.prevTh2+e*(l[1]-i.prevTh2)),d=(i.prevP2+e*(l[3]-i.prevP2))/c.p2Scale;r.event({t:a,kind:`x`,o:s,th2:o,p2:d});let{midi:p,velocity:h}=oe(t,o,d,i.octave);i.lastNote=r.note(i.stem,a,p,h,t.noteLength)??i.lastNote,m++}i.restAt===null&&f>=a&&(c.energyNorm()<o||f>=a+10)&&(i.restAt=f,i.lastNote&&r.hold(i.lastNote,i.lastNote.t,t.finalHold,t.finalFade)),i.prev=u,i.prevTh2=l[1],i.prevP2=l[3]}),p===null&&d.every(e=>e.restAt!==null)&&(p=f,r.end(f+s));let c=0,u=0;for(let e of d){let t=e.pend.energyNorm();c+=t,u=Math.max(u,t)}let v=c/d.length;if(l.update(f,v,p===null?null:p+s),f>=h){h=f+.03333333333333333,_.length=0,_.push(v,u);for(let e of d)_.push(e.pend.y[0],e.pend.y[1],e.pend.y[2],e.pend.y[3],+(e.restAt===null));r.frame(0,f,_)}f>=g&&(g=f+.1,r.info(f,{"energy target":e.toFixed(4),"energy (mean)":v.toFixed(4),notes:String(m),"at rest":`${d.filter(e=>e.restAt!==null).length} / ${d.length}`}))}return{get time(){return f},advance(e){for(;f<e;)v()}}},B=.002;function me(e,t,n,r){let i=new S(e);return i.controlled=!1,i.y[0]=t,i.y[1]=n+r,i.y[2]=0,i.y[3]=0,i}function V(e,t){return[e.l1*u(t[0])+e.l2*u(t[1]),e.l1*d(t[0])+e.l2*d(t[1])]}function H(e,t,n,r,i,a){let o=me(e,t,n,-r/2),s=me(e,t,n,r/2);for(let t=0;t<a;t+=B){o.step(B),s.step(B);let[n,r]=V(e,o.y),[a,c]=V(e,s.y);if(v(n-a,r-c)>i)return t+B}return 1/0}function he(e,t,n,r,i){let a=3*r+10,o=1e-15,s=.01;if(H(e,t,n,o,i,a)<=r)return{offset:o,separatesAt:H(e,t,n,o,i,a)};if(H(e,t,n,s,i,a)>=r)return{offset:s,separatesAt:H(e,t,n,s,i,a)};for(let c=0;c<16;c++){let c=Math.sqrt(o*s);H(e,t,n,c,i,a)>r?o=c:s=c}let c=Math.sqrt(o*s);return{offset:c,separatesAt:H(e,t,n,c,i,a)}}function ge(e,t){let n=Math.PI/180,r=e.releaseAngle*n,i=e.jitter*n;return t?[r+(2*t()-1)*i,r+(2*t()-1)*i]:[r,r]}function _e(e,t){let n=e.pitchLow,r=e.pitchHigh,i=R.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(z(t,e.scale,i)-t)<1e-6&&s.push(t);s.length||(s=[z((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}}const ve=(t,n,r)=>{let i={m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio},a=t.speed,[o,s]=ge(t,e(n)),c=he(i,o,s,t.separateAt*a,t.sepThreshold*(i.l1+i.l2)),l=Math.max(1,Math.round(t.count)),f=Array.from({length:l},(e,t)=>{let n=me(i,o,s,l>1?(t/(l-1)-.5)*c.offset:0);return{p:n,prevX:V(i,n.y)[0],E0:0,lastNote:null,restAt:null}}),p=Math.sqrt(2*f[0].p.energy()/i.m2),m=t.freeTime,h=t.dampTime,g=t.dampCurve,y=t.tau,b=t.restEnergy,x=t.finalHold+t.finalFade+.3,S=_e(t,l),C=180/Math.PI,w=`${(o*C).toFixed(2)}°, ${(s*C).toFixed(2)}°`,T=`${c.offset.toExponential(2)} rad → separate at ${(c.separatesAt/a).toFixed(1)} s`,E=0,D=null,O=0,k=0,A=0,j=new Float64Array(2*l);function M(e,n,a){let o=f[e],s=o.p.y,c=o.p.derived(),l=i.l1*d(s[0])*c.w1+i.l2*d(s[1])*c.w2,m=i.l1*u(s[0])*c.w1+i.l2*u(s[1])*c.w2,h=Math.min(1,v(l,m)/(t.loudRef*p)),g=t.loudFloor,y=g+(1-g)*_(h,t.loudCurve),b=t.pitchMode===`motion`?z(t.pitchLow+(t.pitchHigh-t.pitchLow)*h,t.scale,R.indexOf(t.root)):S[a>0?`right`:`left`][e];o.lastNote=r.note(+(a>0),n,b,y,t.noteLength)??o.lastNote,O++}function N(){let e=E;E+=B/a;let n=(e-m)/h;if(f.forEach((a,o)=>{let s=a.p;n>=0&&(s.controlled||(s.controlled=!0,a.E0=s.energy()),s.tau=y,s.eTarget=n<1?a.E0*_(1-n,g):0,s.damping=n>=1?1/y:0),s.step(B);let c=V(i,s.y)[0];a.restAt===null&&(a.prevX<0&&c>=0||a.prevX>0&&c<=0)&&M(o,e+a.prevX/(a.prevX-c)*(E-e),c>a.prevX?1:-1),a.prevX=c,a.restAt===null&&n>=1&&(s.energyNorm()<b||E>=m+h+10)&&(a.restAt=E,a.lastNote&&r.hold(a.lastNote,a.lastNote.t,t.finalHold,t.finalFade))}),D===null&&f.every(e=>e.restAt!==null)&&(D=E,r.end(E+x)),E>=k&&(k=E+.008333333333333333,f.forEach((e,t)=>{j[2*t]=e.p.y[0],j[2*t+1]=e.p.y[1]}),r.frame(0,E,j)),E>=A){A=E+.1;let e=D===null?E<m?`swinging`:E<m+h?`damping`:`settling`:`at rest`;r.info(E,{phase:e,"energy (mean)":(f.reduce((e,t)=>e+t.p.energyNorm(),0)/l).toFixed(4),notes:String(O),release:w,"offset (outermost)":T,"at rest":`${f.filter(e=>e.restAt!==null).length} / ${l}`})}}return{get time(){return E},advance(e){for(;E<e;)N()}}},U=.002;function ye(e,t,n,r){let i=new S(e);return i.controlled=!1,i.y[0]=Math.PI+r*t,i.y[1]=Math.PI+r*t*n,i}function W(e,t){return[e.l1*u(t[0])+e.l2*u(t[1]),e.l1*d(t[0])+e.l2*d(t[1])]}function be(e,t,n,r,i){let a=ye(e,t,n,1);for(let t=0;t<i;t+=U)if(a.step(U),Math.abs(W(e,a.y)[0])>r)return t+U;return 1/0}function xe(e,t,n,r){let i=3*n+10,a=n=>be(e,n,t,r,i),o=[];for(let e=0;e<=58;e++){let t=_(10,-15+.25*e);o.push({d:t,t:a(t)})}let s=[...o];for(let e=0;e+1<o.length;e++){let t=o[e],r=o[e+1];if(t.t>n&&r.t<=n){for(let e=0;e<14;e++){let e=Math.sqrt(t.d*r.d),i=a(e);i>n?t={d:e,t:i}:r={d:e,t:i}}s.push(t,r)}}let c=e=>Math.abs(e.t-n),l=Math.min(...s.map(c)),u=s.filter(e=>c(e)<=l+.01*n).reduce((e,t)=>t.d<e.d?t:e);return{nudge:u.d,tipsAt:u.t}}const Se=(t,n,r)=>{let i={m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio},a=t.speed,o=e(n),s=o()<.5?-1:1,c=.6+.8*o(),l=xe(i,c,t.fallAfter*a,t.tipThreshold*(i.l1+i.l2)),f=ye(i,l.nudge,c,s),p=i.l1+i.l2,m=f.energy(),h=Math.sqrt(2*m/i.m2),g=t.freeTime+t.dampTime,y=t.restEnergy,b=t.minDepth*p,S=`${l.nudge.toExponential(2)} rad ${s>0?`→`:`←`} (shape ${c.toFixed(2)}), tips at ${(l.tipsAt/a).toFixed(1)} s`,C=(()=>{if(!t.heightNotes)return[];let e=t.heightLow,n=t.heightHigh,r=R.indexOf(t.root),i=[];for(let a=Math.ceil(e);a<=n;a++)(t.scale===`continuous`||Math.abs(z(a,t.scale,r)-a)<1e-6)&&i.push(a);let a=Math.max(1,Math.round(t.heightStep));return i.filter((e,t)=>t%a===0)})(),w=e=>t.heightLow+(t.heightHigh-t.heightLow)*((p-e)/(2*p)),T=e=>{let t=0;for(;t<C.length&&C[t]<e;)t++;return t},E=.3*(C.length>1?(C[C.length-1]-C[0])/(C.length-1):1),D=0,O=W(i,f.y)[0],k=x(f.y[1]-f.y[0]),A=!1,j=T(w(W(i,f.y)[1])),M=null,N=null,P=0,F=0,I=0,ee=0,te=0,ne=e=>{let n=Math.max(0,Math.min(1,(e-t.freeTime)/t.dampTime)),r=n*n*(3-2*n);return t.dampBase+(t.dampEnd-t.dampBase)*r},re=()=>{let e=f.derived(),n=f.y,r=i.l1*d(n[0])*e.w1+i.l2*d(n[1])*e.w2,a=i.l1*u(n[0])*e.w1+i.l2*u(n[1])*e.w2,o=Math.min(1,v(r,a)/(t.loudRef*h)),s=t.loudFloor;return s+(1-s)*_(o,t.loudCurve)},L=(e,n)=>{let i=t.heightRamp>0?Math.max(0,Math.min(1,e/t.heightRamp)):1,a=t.heightRampFrom,o=a+(1-a)*i*i*(3-2*i),s=Math.min(1,Math.max(0,f.energy())/m);r.note(2,e,n,t.heightVel*o*_(s,t.heightFollow),t.heightLength),I++};function ie(){let e=D;D+=U/a,f.damping=ne(e),f.step(U);let[n,o]=W(i,f.y);if(M===null&&C.length){let e=w(o);for(;j<C.length&&e>C[j]+E;)L(D,C[j++]);for(;j>0&&e<C[j-1]-E;)L(D,C[--j])}if(M===null&&Math.abs(o)<=b&&(O<0&&n>=0||O>0&&n<=0)){let i=e+O/(O-n)*(D-e);if(F++,t.click){let e=t.clickMaxVel*re();r.note(1,i,t.clickPitch,e,t.clickLength),r.event({t:i,kind:`ring`,x:0,y:o,strength:e,click:1})}}O=n;let s=x(f.y[1]-f.y[0]);if(Math.abs(s)>.05&&(A=!0),M===null&&A&&(k<0&&s>=0||k>0&&s<=0)&&Math.abs(s-k)<Math.PI){let i=e+k/(k-s)*(D-e);A=!1,P++;let a=P===1?t.firstVel:t.maxVel*re();N=r.note(0,i,t.extPitch,a,t.extLength)??N,r.event({t:i,kind:`ring`,x:n,y:o,strength:a,click:0})}if(k=s,M===null&&D>=g&&(f.energyNorm()<y||D>=g+15)&&(M=D,N&&r.hold(N,N.t,t.finalHold,t.finalFade),r.end(D+t.finalHold+t.finalFade+.3)),D>=ee&&(r.frame(0,D,[f.y[0],f.y[1]]),ee=D+.0020833333333333333),D>=te){te=D+.1;let e=t.freeTime,n=M===null?P===0?`falling`:D<e?`swinging`:D<g?`damping`:`settling`:`at rest`;r.info(D,{phase:n,energy:`${(f.energy()/m).toFixed(3)} of start`,"extension notes":String(P),clicks:String(F),"height notes":String(I),nudge:S,friction:`${ne(D).toFixed(4)} /sim s`})}}return r.emitting&&r.frame(0,0,[f.y[0],f.y[1]]),{get time(){return D},advance(e){for(;D<e;)ie()}}};function Ce(e,t,n){let r=e.y;if(!(t>0))return;let i=r[2],a=r[3],o=v(i,a);if(o>1e-9)i/=o,a/=o;else{let e=n()*2*Math.PI;i=d(e),a=u(e)}let s=e.derived(),c=i*s.w1+a*s.w2,l=e.derived([r[0],r[1],i,a]),f=i*l.w1+a*l.w2,p=(-c+Math.sqrt(Math.max(0,c*c+2*f*t)))/f;r[2]+=p*i,r[3]+=p*a}function we(e,t,n,r){let{l1:i,l2:a,m2:o}=e.cfg,s=e.y,c=i+a,l=Math.sqrt(2*e.vTop/o)+1e-9,f=u(s[0]),p=d(s[0]),m=u(s[1]),h=d(s[1]);switch(t){case`x2`:return(i*f+a*m)/c;case`y2`:return-(i*p+a*h)/c;case`vx2`:return(i*p*n+a*h*r)/l;case`vy2`:return(i*f*n+a*m*r)/l;case`x1`:return f;case`vx1`:return i*p*n/l;case`θ1`:return x(s[0])/Math.PI;case`θ2`:return x(s[1])/Math.PI;case`θ2−θ1`:return x(s[1]-s[0])/Math.PI;case`ω1`:return n*i/l;case`ω2`:return r*a/l;case`p1`:return s[2]/(l*(1+o)*i*i+1e-9);case`p2`:return s[3]/(l*o*a*a+1e-9);case`speed2`:return v(i*p*n+a*h*r,i*f*n+a*m*r)/l}}var Te=class{x=0;y=0;run(e,t){let n=e-this.x+t*this.y;return this.x=e,this.y=n,n}};const G=48e3;function Ee(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function De(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=Ee(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function Oe(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function ke(e,t,n,r,i){let a=De(n,r),[o,s]=Ee(a,r),c=2*Math.PI*e*t,l=o*i/c,u=l*l;return{l1:u,l2:r*u,m2:a,lower:e*t,upper:e*t*(s/o)}}function Ae(e,t,n,r){let[i]=Ee(De(n,r),r);return 2*Math.PI*e*t/i}function je(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++)/[1-6]/.test(e[i])&&r.push({i:Number(e[i])-1,add:t*(e[i+1]===`!`?n:1)});return r})}const Me=e=>e.stepBeats*60/Math.max(1,e.tempo),Ne=e=>.4+je(e.score,0,1).length*Me(e);function Pe(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:Oe(e[`ratio${n+1}`]),partial:Oe(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=Ae(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>ke(t,e.ratio,e.partial,e.shape,i))}}const Fe={"01-poincare":ce,"02-orbits":pe,"03-divergence":ve,"04-descent":Se,"05-ensemble":(t,n,r)=>{let{k:i,built:a}=Pe(t),o=e(n),s=t.signal,c=h(t.gain*.11512925464970229),l=1-2*Math.PI*t.dcCut/G,f=je(t.score,t.pulseAdds,t.accent),p=Me(t),m=Ne(t)+t.tail,g=Math.min(t.fade,t.tail),_=i/G,v=a.map((e,n)=>{let r=new S({m1:1,m2:e.m2,l1:e.l1,l2:e.l2,g:1});r.controlled=!1;let a=t[`ring${n+1}`];r.damping=a>0?13.8156/(a*i):0;let o=Math.max(1,Math.ceil(40*e.upper/G)),s=(t.spread*(2*n/5-1)+1)*Math.PI/4,c=h(t[`level${n+1}`]*.11512925464970229);return{p:r,dc:new Te,sub:o,h:_/o,gl:d(s)*c,gr:u(s)*c}}),b=0,x=0,C=!1,w=/* @__PURE__ */ new Float64Array(24),T=/* @__PURE__ */ new Float64Array(12);function E(e){C||(C=!0,r.end(m));let t=Math.round(e*G)-b;if(t<=0)return;let n=new Float32Array(t),i=new Float32Array(t);for(let e=0;e<t;e++,b++){let t=b/G;if(x<f.length&&t>=.4+x*p){for(let e of f[x]){let n=v[e.i];n&&(Ce(n.p,e.add*n.p.vTop,o),r.event({t,kind:`push`,i:e.i}))}x++}let a=0,h=0;for(let e of v){for(let t=0;t<e.sub;t++)e.p.step(e.h);Number.isFinite(e.p.y[0])||e.p.y.fill(0);let t=e.p.derived(),n=y(c*e.dc.run(we(e.p,s,t.w1,t.w2),l));a+=e.gl*n,h+=e.gr*n}let _=Math.max(0,Math.min(1,(m-t)/g));n[e]=a*_*_,i[e]=h*_*_,b%6==0&&(v.forEach((e,t)=>{let n=e.p.y,r=e.p.cfg;T[2*t]=r.l1*u(n[0])+r.l2*u(n[1]),T[2*t+1]=r.l1*d(n[0])+r.l2*d(n[1])}),r.frame(1,t,T)),b%400==0&&(v.forEach((e,t)=>{let n=e.p.y,r=e.p.cfg,i=r.l1*u(n[0]),a=r.l1*d(n[0]);w.set([i,a,i+r.l2*u(n[1]),a+r.l2*d(n[1])],4*t)}),r.frame(0,t,w),r.info(t,{score:`step ${x} of ${f.length}`,energies:v.map(e=>e.p.energyNorm().toFixed(2)).join(` `)}))}r.audio(0,n,i)}return{get time(){return b/G},advance:E}}},Ie=2.5;let K,q,J=!1,Le=0,Re=4*G,Y=1/0,X=!1,ze=!1,Z=[],Be=-1/0;const Ve=/* @__PURE__ */ new Map;let He=[],Q=null,Ue=-1/0;const We=/* @__PURE__ */ new Map,$=(e,t=[])=>self.postMessage(e,t),Ge=(e,t=[])=>q.playerPort.postMessage(e,t),Ke={get emitting(){return J},frame(e,t,n){if(!J)return;let r=Ve.get(e);r||Ve.set(e,r={stride:n.length+1,rows:[]}),r.rows.push(t);for(let e=0;e<n.length;e++)r.rows.push(n[e])},event(e){J&&He.push(e)},info(e,t){J&&(Q={t:e,info:t})},note(e,t,n,r,i){if(!J||!Z[e]||r<=0)return null;let a={t,type:`noteOn`,note:n,vel:Math.max(.01,Math.min(1,r))},o={t:t+i,type:`noteOff`,note:n,on:t};return Z[e].push(a,o),{stem:e,t,off:o}},hold(e,t,n,r){if(!J||!Z[e.stem])return;let i=Math.max(t,Be),a=i+n+r;Z[e.stem].includes(e.off)&&e.off.t<a&&(e.off.t=a),Z[e.stem].push({t:i,type:`hold`,hold:n,fade:r})},cmd(e,t){J&&Z[e]&&Z[e].push(t)},audio(e,t,n){if(!J)return;let r=We.get(e)??Math.round(q.from*48e3);We.set(e,r+t.length);let i=Math.round(q.start*G);if(r+t.length<=i)return;let a=Math.max(0,i-r),o=a?t.slice(a):t,s=a?n.slice(a):n;Ge({type:`chunk`,stem:e,frame:r+a,L:o,R:s},[o.buffer,s.buffer])},end(e){Y===1/0&&(Y=e,$({type:`end`,t:e}),Ge({type:`end`,frame:Math.round(e*G)}))}};function qe(e,t=!1){if(e>Be&&(q.synthPorts.forEach((t,n)=>{if(!t)return;let r=Z[n];r.sort((e,t)=>e.t-t.t);let i=0;for(;i<r.length&&r[i].t<e;)i++;let a={type:`cmds`,cmds:r.splice(0,i),horizon:e};t.postMessage(a)}),Be=e),!(!t&&K.time-Ue<.1)){Ue=K.time;for(let[e,t]of Ve){if(!t.rows.length)continue;let n=Float64Array.from(t.rows);t.rows=[],$({type:`frames`,track:e,stride:t.stride,data:n},[n.buffer])}He.length&&($({type:`events`,events:He}),He=[]),Q&&=($({type:`info`,t:Q.t,info:Q.info}),null)}}function Je(){ze||X||(ze=!0,setTimeout(Ye,0))}function Ye(){ze=!1;try{if(K.time>=Y){qe(Y+1,!0),q.synthPorts.forEach(e=>e?.postMessage({type:`end`,t:Y})),X=!0;return}let e=Math.min(Y,(Le+Re)/G+Ie+.5);if(K.time>=e)return;K.advance(Math.min(K.time+.05,e,Y)),qe(K.time-Ie)}catch(e){X=!0,$({type:`error`,message:String(e?.stack??e)});return}Je()}self.onmessage=e=>{let t=e.data;if(t.type===`init`){q=t,Z=t.synthPorts.map(()=>[]),Le=Math.round(t.start*G),t.playerPort.onmessage=e=>{Le=e.data.playhead,Re=e.data.ahead,Je()};try{let e=Fe[t.comp];if(!e)throw Error(`no score for ${t.comp}`);K=e(t.P,t.seed,Ke),t.from>0&&K.advance(t.from),J=!0,Be=t.from}catch(e){X=!0,$({type:`error`,message:String(e?.stack??e)});return}Je()}};
\ No newline at end of file
site/assets/synthWorker-ByLtHWda.jsadded+1−0View file
@@ -0,0 +1 @@
1+const e=(e,t)=>e[t],t=(e,t)=>e[t],n=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,r=(...e)=>t=>e.includes(t.geometry),i=(...e)=>t=>e.includes(t.exciter),a=[`bow`,`reed`,`selfosc`,`noise`],o=[[`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`]],s=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function c(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:o,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:s,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}]}const l=[{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:r(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:r(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:r(`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&&n(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:n},{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:i(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:i(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:i(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:i(`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:i(`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:i(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:i(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:i(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:i(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:i(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:i(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:i(...a)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:i(...a)},{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},...c(1),...c(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:n},{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`}];Object.fromEntries(l.map(e=>[e.id,e]));const u=Object.fromEntries(l.map(e=>[e.id,e.def])),d=l.filter(e=>e.model).map(e=>e.id),f=Math.SQRT2,p=Math.PI;function m(e,t){let n=Math.ceil(Math.abs(t)+e)+24,r=0;for(let i=0;i<=n;i++){let a=p*i/n;r+=(i===0||i===n?.5:1)*Math.cos(e*a-t*Math.sin(a))}return r/n}function h(e,t){let n=[],r=e===0?.5:e,i=m(e,r);for(let a=r+.05;a<=t;a+=.05){let t=m(e,a);if(i*t<0){let t=r,o=a,s=i;for(let n=0;n<50;n++){let n=.5*(t+o),r=m(e,n);s*r<=0?o=n:(t=n,s=r)}n.push(.5*(t+o))}r=a,i=t}return n}const g=[4.730040745,7.853204624,10.99560784,14.13716549,17.27875966],_=e=>e<g.length?g[e]:(2*e+3)*p/2;function v(e,t,n){if(t<12){let e=(Math.cosh(t)-Math.cos(t))/(Math.sinh(t)-Math.sin(t));return Math.cosh(t*n)+Math.cos(t*n)-e*(Math.sinh(t*n)+Math.sin(t*n))}let r=e%2==0?1:-1;return Math.cos(t*n)-Math.sin(t*n)+Math.exp(-t*n)+r*Math.exp(-t*(1-n))}const y=[[.5,2],[1,2],[1.2,3],[1.5,3],[2,4],[2.5,4],[2.67,3],[3,5],[4,6],[4.24,5],[5.33,7],[5.7,6],[6.67,8],[7.2,7],[8,9],[9,8],[10,10],[11.1,9],[12.1,11],[13.5,10]];function b(e,t,n,r,i=2){let a=new Float64Array(t),o=new Float64Array(t),s={kind:e,N:t,ratios:a,wavenum:o,aspect:n};switch(e){case`string`:case`free`:for(let n=0;n<t;n++){let t=n+1;a[n]=e===`string`?t:t**+r,o[n]=t}return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.sin((e+1)*p*t)};case`tube_co`:for(let e=0;e<t;e++)a[e]=2*e+1,o[e]=(2*e+1)/2;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((2*e+1)*p*t/2)};case`tube_oo`:for(let e=0;e<t;e++)a[e]=e+1,o[e]=e+1;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((e+1)*p*t)};case`bar`:{let e=_(0),n=new Float64Array(t),r=2048;for(let i=0;i<t;i++){let t=_(i);a[i]=(t/e)**2,o[i]=t/p;let s=0;for(let e=0;e<r;e++)s+=v(i,t,(e+.5)/r)**2;n[i]=1/Math.sqrt(s/r)}return{...s,view:`line`,dim:1,shape:(e,t)=>n[e]*v(e,_(e),t)}}case`ring`:{let e=[],n=[],r=0,i=0,c=2;for(;e.length<t;){r<y.length?[i,c]=y[r]:(i*=1.09,c+=+(r%2==0));for(let s=0;s<2&&e.length<t;s++)a[e.length]=i*(s===0?1:1+6e-4*(1+r%3)),o[e.length]=2*c,e.push(c),n.push(s);r++}return{...s,view:`ring`,dim:1,shape:(t,r)=>{let i=2*p*r*e[t];return f*(n[t]===0?Math.cos(i):Math.sin(i))}}}case`plate`:{let e=Math.ceil(3*Math.sqrt(t))+3,r=[];for(let t=1;t<=e;t++)for(let i=1;i<=e;i++)r.push([t*t+(i/n)**2,t,i]);r.sort((e,t)=>e[0]-t[0]);let i=new Int32Array(t),c=new Int32Array(t),l=r[0][0];for(let e=0;e<t;e++){let[t,s,u]=r[e];a[e]=t/l,o[e]=Math.sqrt(s*s+(u/n)**2),i[e]=s,c[e]=u}return{...s,view:`rect`,dim:2,shape:(e,t,n)=>2*Math.sin(i[e]*p*t)*Math.sin(c[e]*p*n)}}case`membrane`:{let e=2*Math.sqrt(t)+6,n=[];for(;;){n=[];for(let t=0;t<=Math.ceil(e);t++)for(let r of h(t,e))n.push([r,t,0]),t>0&&n.push([r,t,1]);if(n.length>=t)break;e*=1.3}n.sort((e,t)=>e[0]-t[0]||e[2]-t[2]);let r=n[0][0],i=new Int32Array(t),c=new Int32Array(t),l=new Float64Array(t),u=new Float64Array(t);for(let e=0;e<t;e++){let[t,s,d]=n[e];a[e]=t/r,o[e]=t/p,i[e]=s,c[e]=d,l[e]=t,u[e]=s===0?1/Math.abs(m(1,t)):f/Math.abs(m(s+1,t))}return S(s,i,c,l,u)}case`disc`:{let e=i,n=Math.ceil(Math.sqrt(2*t))+4,r=[];for(let t=0;t<=n;t++)for(let i=0;t+2*i<=n;i++){if(i===0&&t<2)continue;let n=(t+2.1*i)**+e;r.push([n,t,i,0]),t>0&&r.push([n*1.0004,t,i,1])}r.sort((e,t)=>e[0]-t[0]);let c=r.slice(0,t),l=c.reduce((e,t)=>Math.max(e,t[1]),0),u=c.reduce((e,t)=>Math.max(e,t[2]),0),d=[];for(let e=0;e<=l;e++)d.push(x(e,u+1));let f=new Int32Array(t),m=new Int32Array(t),h=new Float64Array(t),g=c[0][0];for(let e=0;e<t;e++){let[t,n,r,i]=c[e];a[e]=t/g,f[e]=n,m[e]=i,h[e]=d[n][n===0?r-1:r],o[e]=h[e]/p}return S(s,f,m,h,null)}}}function x(e,t){let n=t=>e===0?-m(1,t):.5*(m(e-1,t)-m(e+1,t)),r=[],i=e===0?.5:Math.max(.3,e*.8),a=n(i);for(let e=i+.05;r.length<t;e+=.05){let t=n(e);if(a*t<0){let t=i,o=e,s=a;for(let e=0;e<50;e++){let e=.5*(t+o),r=n(e);s*r<=0?o=e:(t=e,s=r)}r.push(.5*(t+o))}i=e,a=t}return r}function S(e,t,n,r,i){let a=e.N,o=Array(a).fill(null),s=i??new Float64Array(a),c=(e,n)=>{let a=o[e];if(!a){a=/* @__PURE__ */ new Float64Array(258);for(let n=0;n<=256;n++)a[n]=m(t[e],r[e]*n/256);if(a[257]=a[256],o[e]=a,!i){let n=0;for(let e=0;e<=256;e++)n+=(e===0||e===256?.5:1)*a[e]*a[e]*e/256/256;s[e]=1/Math.sqrt(Math.max(1e-12,(t[e]===0?2:1)*n))}}let c=n*256,l=Math.floor(c),u=c-l;return a[l]*(1-u)+a[l+1]*u};return{...e,view:`disk`,dim:2,shape:(e,r,i)=>{let a=2*r-1,o=2*i-1,l=Math.hypot(a,o);if(l>=1)return 0;let u=c(e,l),d=t[e],f=d===0?1:n[e]===0?Math.cos(d*Math.atan2(o,a)):Math.sin(d*Math.atan2(o,a));return s[e]*u*f}}}function C(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 w(e){let t=Math.max(e(),1e-12);return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*e())}const ee=e=>d.map(t=>String(e[t])).join(`|`);function T(n){let r=Math.round(e(n,`modes`)),i=b(t(n,`geometry`),r,e(n,`aspect`),e(n,`powerExp`),e(n,`discExp`)),a=Math.round(e(n,`seed`)),o=C(a*7919+13),s=e(n,`stretch`),c=e(n,`inharm`),l=e(n,`harmonize`),u=e(n,`jitter`),d=0;for(let e=0;e<r;e++)if(Math.abs(i.ratios[e]-1)<1e-9){d=e;break}let f=new Float64Array(r);for(let e=0;e<r;e++){let t=i.ratios[e]**+s;if(t*=Math.sqrt(1+c*t*t)/Math.sqrt(1+c),l>0){let e=t<.75?.5:Math.max(1,Math.round(t));t=t**(1-l)*e**+l}let n=w(o);e!==d&&u>0&&(t*=2**(u*n/1200)),f[e]=t}let p=Int32Array.from({length:r},(e,t)=>t).sort((e,t)=>f[e]-f[t]),m=new Float64Array(r),h=new Float64Array(r),g=0;for(let e=0;e<r;e++)m[e]=f[p[e]],h[e]=i.wavenum[p[e]],p[e]===d&&(g=e);let _=Math.min(r,Math.round(e(n,`nlModes`))),v=Math.round(e(n,`terms`)),y=C(a*104729+7),x=[],S=new Float64Array(v*_);for(let e=0;e<v;e++){let t=[],n=Math.max(2,Math.round(_*.75)),r=0;for(let e=0;e<n;e++){let e=Math.floor(y()*_),n=y()<.25?e:Math.floor(y()*_),i=w(y);t.push([e,n,i]),r+=(e===n?1:2)*i*i}let i=1/Math.sqrt(r),a=[];for(let[e,n,r]of t)a.push([e,n,r*i]),e!==n&&a.push([n,e,r*i]);x.push(a);let o=0;for(let t=0;t<_;t++){let n=w(y);S[e*_+t]=n,o+=n*n}o=1/Math.sqrt(o);for(let t=0;t<_;t++)S[e*_+t]*=o}let T=x.reduce((e,t)=>e+t.length,0),E=new Int32Array(v+1),D=new Int32Array(T),O=new Int32Array(T),te=new Float64Array(T),k=0;for(let e=0;e<v;e++){E[e]=k;for(let[t,n,r]of x[e])D[k]=t,O[k]=n,te[k]=r,k++}E[v]=k;let A=C(a*31337+1),j=new Float64Array(_),M=0;for(let e=0;e<_;e++)j[e]=w(A),M+=j[e]**2;for(let e=0;e<_;e++)j[e]/=Math.sqrt(M);let N=new Float64Array(r);for(let e=0;e<r;e++)N[e]=(A()<.5?-1:1)*(.5+.5*A());return{key:ee(n),geom:i,N:r,ratios:m,wavenum:h,pitchK:g,perm:p,Nnl:_,M:v,tStart:E,ti:D,tj:O,tv:te,tb:S,bx:j,rad:N,shape:(e,t,n)=>i.shape(p[e],t,n)}}const E={violin:{name:`Violin`,low:[[275,22,0],[405,30,-12],[470,40,-8],[460,32,0],[540,32,2]],hill:2600,hillDb:6,top:5500},viola:{name:`Viola`,low:[[230,22,0],[340,30,-12],[390,40,-8],[380,32,0],[445,32,2]],hill:2100,hillDb:5,top:4800},cello:{name:`Cello`,low:[[102,20,0],[145,30,-10],[170,40,-8],[178,30,1],[210,30,2]],hill:1500,hillDb:4,top:3500},bass:{name:`Double bass`,low:[[62,18,0],[92,28,-10],[104,38,-8],[112,30,1],[138,30,2]],hill:900,hillDb:3,top:2400},guitar:{name:`Guitar`,low:[[98,18,0],[204,28,3],[230,35,-6],[390,30,-3],[440,35,-2]],hill:2500,hillDb:2,top:5e3}};function D(e,t,n,r=1){let i=E[e];if(!i)return[];let a=C(r*6151+17),o=[];for(let[e,r,s]of i.low){let i=10**(s/20);o.push({f:e/t,q:r/n,gL:i,gR:i*(.8+.4*a())})}let s=1.2*Math.max(...i.low.map(e=>e[0]));for(;s<4.5*i.top;){let e=Math.log2(s/i.hill),r=-6+i.hillDb*Math.exp(-(e*e)/.72);r-=12*Math.max(0,Math.log2(s/i.top));let c=10**((r+3*w(a))/20),l=10**((r+3*w(a))/20);o.push({f:s/t,q:(20+25*a())/n,gL:c*(a()<.5?-1:1),gR:l*(a()<.5?-1:1)}),s*=1+.07*(.5+a())}return o}function O(e,t){let n=0,r=0,i=0,a=0;for(let o of e){let e=t/o.f,s=1-e*e,c=e/o.q,l=s*s+c*c,u=c*c/l,d=c*s/l;n+=o.gL*u,r+=o.gL*d,i+=o.gR*u,a+=o.gR*d}return .5*(n*n+r*r+i*i+a*a)}var te=class{n=0;b0=/* @__PURE__ */ new Float64Array;a1=/* @__PURE__ */ new Float64Array;a2=/* @__PURE__ */ new Float64Array;gL=/* @__PURE__ */ new Float64Array;gR=/* @__PURE__ */ new Float64Array;x1=0;x2=0;y1=/* @__PURE__ */ new Float64Array;y2=/* @__PURE__ */ new Float64Array;key=``;configure(e,t,n,r){let i=`${e}|${t}|${n}|${r}`;if(i===this.key)return;this.key=i;let a=D(e,t,n).filter(e=>e.f<.45*r),o=0,s=0;if(a.length){let e=.8*a[0].f,t=Math.min(1e4,.45*r);for(let n=0;n<=200;n++)o+=O(a,e*(t/e)**(n/200)),s++}let c=s?1/Math.sqrt(o/s):0,l=a.length,u=this.n!==l;if(this.n=l,u)for(let e of[`b0`,`a1`,`a2`,`gL`,`gR`,`y1`,`y2`])this[e]=new Float64Array(l);a.forEach((e,t)=>{let n=2*Math.PI*e.f/r,i=Math.sin(n)/(2*e.q),a=1+i;this.b0[t]=i/a,this.a1[t]=-2*Math.cos(n)/a,this.a2[t]=(1-i)/a,this.gL[t]=e.gL*c,this.gR[t]=e.gR*c})}reset(){this.x1=this.x2=0,this.y1.fill(0),this.y2.fill(0)}tick(e,t){let n=this.n,r=this.b0,i=this.a1,a=this.a2,o=this.y1,s=this.y2,c=this.gL,l=this.gR,u=e-this.x2;this.x2=this.x1,this.x1=e;let d=0,f=0;for(let e=0;e<n;e++){let t=r[e]*u-i[e]*o[e]-a[e]*s[e];s[e]=o[e],o[e]=t,d+=c[e]*t,f+=l[e]*t}t[0]=d,t[1]=f}};const k=.5,A=1e-14,j=.002,M=.05,N=e=>{let t=Math.abs(e);return t+Math.log1p(Math.exp(-2*t))-Math.LN2},ne=6.907755,re=10**-9,ie=.1;var ae=class{idx;active=!1;note=60;baseHz=261.6;vel=1;gate=!1;held=!1;sustained=!1;touching=!1;damped=!0;order=0;N=0;nAct=0;nTune=0;cull=1/0;nNL=0;nNLTune=0;q=/* @__PURE__ */ new Float64Array;qp=/* @__PURE__ */ new Float64Array;qn=/* @__PURE__ */ new Float64Array;A=/* @__PURE__ */ new Float64Array;B=/* @__PURE__ */ new Float64Array;C=/* @__PURE__ */ new Float64Array;om=/* @__PURE__ */ new Float64Array;sw=/* @__PURE__ */ new Float64Array;sw2=/* @__PURE__ */ new Float64Array;grad=/* @__PURE__ */ new Float64Array;pv=/* @__PURE__ */ new Float64Array;gp=/* @__PURE__ */ new Float64Array;phiE=/* @__PURE__ */ new Float64Array;phiB=/* @__PURE__ */ new Float64Array;wL=/* @__PURE__ */ new Float64Array;wR=/* @__PURE__ */ new Float64Array;wsum=0;omega1=1;Z0=1;tunedPitch=-1;tunedDamp=-1;tunedGate=!1;glideMul=1;tunedGlide=1;vibMul=1;tunedVib=1;vibPh=0;vibAge=0;vibRateJ=1;dirtyTune=!0;dirtyVec=!0;posX=-1;posY=-1;ham=!1;hz=0;hzp=0;hzn=0;hamISM=1;hamK=0;hamA=2.5;hamTimer=0;gz=0;buzzK=0;buzzGap=0;buzzPhi1=1;beta=.11;env=0;fLaw=0;nz=0;f=0;fb=/* @__PURE__ */ new Float32Array(32768);fbW=0;bx1=0;bx2=0;by1=0;by2=0;S=0;X=0;Vv=0;useG=!1;fast=!1;tc=0;tq=0;pred=!1;energy=0;outMono=0;constructor(e){this.idx=e}alloc(e){let t=t=>{let n=new Float64Array(e);return n.set(t.subarray(0,Math.min(e,t.length))),n};this.q=t(this.q),this.qp=t(this.qp),this.qn=new Float64Array(e);for(let t of[`A`,`B`,`C`,`om`,`sw`,`sw2`,`grad`,`pv`,`gp`,`phiE`,`phiB`,`wL`,`wR`])this[t]=new Float64Array(e);this.N=e,this.dirtyTune=this.dirtyVec=!0}reset(){this.q.fill(0),this.qp.fill(0),this.qn.fill(0),this.ham=!1,this.env=0,this.fLaw=0,this.fb.fill(0),this.bx1=this.bx2=this.by1=this.by2=0,this.energy=0,this.uncull()}uncull(){this.cull=1/0,this.nAct=this.nTune,this.nNL=this.nNLTune}};const oe=e=>440*2**((e-69)/12),se=e=>e<0?0:e>1?1:e,P=e=>e-Math.floor(e);var ce=class{sr;h;p={...u};model;voices=[];act=[];eps=A;vMax=0;vHold=0;psi=Math.sqrt(A);psiReset=!1;order=0;bend=0;sustain=!1;lastNote=60;focus=null;touchVoice=null;pending=[];post=()=>{};paramVersion=0;rngS=0x9e3779b9;lfoPh=[0,0];lfoA=[0,0];lfoB=[0,0];kt=0;kc=0;cc=0;ct=0;cl=0;crossOn=!1;buzzA=1.5;buzzTwo=!1;ampMul=1;fbMul=1;excMul=1;pitchMul=1;dampMul=1;posOff=0;pickOff=0;vecVersion=-1;lastPosOff=0;lastPickOff=0;law=0;lwF=0;lwVb=0;lwGam=0;lwD=0;lawK=/* @__PURE__ */ new Float64Array(3);envAtt=0;envRel=0;noiseC=0;noiseNorm=1;fbD=1;fb0=0;fb2=0;fa1=0;fa2=0;snapCount=0;cpuMs=0;cpuWall=0;cpu=0;lastTouch=null;box=new te;boxOut=/* @__PURE__ */ new Float64Array(2);constructor(e){this.sr=e,this.h=1/e,this.model=T(this.p);for(let e=0;e<16;e++){let t=new ae(e);t.alloc(this.model.N),this.voices.push(t)}}message(e){e.type===`params`?this.setParams(e.params):this.pending.push(e)}setParams(n){if(this.p={...u,...n},this.paramVersion++,ee(this.p)!==this.model.key){this.model=T(this.p);for(let e of this.voices)e.alloc(this.model.N);this.psiReset=!0}for(let e of this.voices)e.dirtyTune=e.dirtyVec=!0;let r=t(this.p,`soundbox`);r===`off`?(this.box.configure(``,1,1,this.sr),this.box.reset()):this.box.configure(r,e(this.p,`boxSize`),e(this.p,`boxDamp`),this.sr)}handle(e){switch(e.type){case`noteOn`:this.noteOn(e.note,e.vel,e.x,e.y);break;case`noteOff`:this.noteOff(e.note);break;case`sustain`:if(this.sustain=e.on,!e.on)for(let e of this.voices)e.sustained&&(e.sustained=!1,this.updateGate(e));break;case`bend`:this.bend=e.value;break;case`touchStart`:this.touchStart(e.x,e.y,e.vel);break;case`touchMove`:this.lastTouch={x:e.x,y:e.y},this.touchVoice&&(this.touchVoice.posX=e.x,this.touchVoice.posY=e.y,this.touchVoice.dirtyVec=!0);break;case`touchEnd`:this.lastTouch=null,this.touchVoice&&=(this.touchVoice.touching=!1,this.updateGate(this.touchVoice),null);break;case`panic`:for(let e of this.voices)e.reset(),e.active=!1;this.box.reset(),this.psi=Math.sqrt(this.eps)}}allocVoice(t){let n=this.voices.find(e=>e.active&&e.note===t);if(n)return n;let r=Math.round(e(this.p,`voices`)),i=this.voices.filter(e=>e.active);return i.length>=r?(i.sort((e,t)=>Number(e.gate)-Number(t.gate)||e.energy-t.energy||e.order-t.order),n=i[0]):n=this.voices.find(e=>!e.active),n.reset(),n.active=!0,n.glideMul=1,n.vibMul=1,n.vibPh=this.rand(),n.vibRateJ=1+.1*(this.rand()*2-1),n.note=t,n.baseHz=oe(t),n.held=n.sustained=n.touching=!1,n.gate=!1,n.dirtyTune=n.dirtyVec=!0,n.tunedPitch=-1,this.psiReset=!0,n}updateGate(e){let t=e.held||e.sustained||e.touching;t!==e.gate&&(e.gate=t,e.dirtyTune=!0)}noteOn(e,t,n,r){let i=this.allocVoice(e);i.uncull(),i.order=++this.order,i.vel=Math.max(.01,Math.min(1,t)),i.held=!0,i.damped=!0,i.vibAge=0,i.posX=n??-1,i.posY=r??-1,i.dirtyVec=!0,this.updateGate(i),this.lastNote=e,this.focus=i,this.prepare(i),this.excite(i,i.vel)}noteOff(e){for(let t of this.voices)t.active&&t.note===e&&t.held&&(t.held=!1,this.sustain&&(t.sustained=!0),this.updateGate(t))}touchStart(e,t,n){this.lastTouch={x:e,y:t};let r=this.focus&&this.focus.active?this.focus:null;r||(r=this.allocVoice(this.lastNote),r.order=++this.order,r.damped=!1,this.focus=r),r.posX=e,r.posY=t,r.vel=n,r.dirtyVec=!0;let i=this.law!==0;i&&(r.touching=!0,this.touchVoice=r,this.updateGate(r)),this.prepare(r),i||this.excite(r,n)}prepare(e){e.dirtyVec&&this.vecVoice(e),(e.dirtyTune||e.tunedPitch!==this.pitchMul||e.tunedDamp!==this.dampMul||e.tunedGate!==e.gate||e.tunedGlide!==e.glideMul||e.tunedVib!==e.vibMul)&&this.tuneVoice(e)}excite(n,r){n.uncull();let i=t(this.p,`exciter`),a=k*(e(this.p,`strength`)*r)**2;if(a<=0)return;let o=n.nAct,s=n.phiE,c=n.om,l=this.h;if(i===`strike`){let t=e(this.p,`hammerMass`),r=e(this.p,`hardness`)/1e3,i=e(this.p,`feltExp`),c=Math.sqrt(2*a/t),u=Math.sqrt(2*k/t)*r/Math.PI,d=0,f=0;for(let e=0;e<o;e++)d+=s[e]*n.q[e],f+=s[e]*(n.q[e]-n.qp[e])/l;let p=Math.sqrt(t);n.ham=!0,n.hamTimer=0,n.hamISM=1/p,n.hamK=t*(Math.PI/r)**2/u**(i-1),n.hamA=i,n.hz=d*p,n.hzp=(d-(f+c)*l)*p}else if(i===`pluck`){let e=0;for(let t=0;t<o;t++)e+=s[t]*s[t]/(c[t]*c[t]);if(e<=0)return;let t=Math.sqrt(2*a/e);for(let e=0;e<o;e++){let r=t*s[e]/(c[e]*c[e]);n.q[e]+=r,n.qp[e]+=r}this.psiReset=!0}else if(i===`impulse`){let t=e(this.p,`hardness`)/1e3,r=0,i=n.qn;for(let e=0;e<o;e++){let n=c[e]*t/2,a=1-(n/Math.PI)**2,o=n<1e-9?1:Math.abs(a)<1e-6?.5:Math.abs(Math.sin(n)/n/a);i[e]=s[e]*o,r+=i[e]*i[e]}if(r<=0)return;let u=Math.sqrt(2*a/r);for(let e=0;e<o;e++)n.qp[e]-=l*u*i[e];i.fill(0)}}tuneVoice(t){let n=this.model,r=n.N,i=this.h,a=this.p,o=t.baseHz*this.pitchMul*t.glideMul*t.vibMul,s=ne/e(a,`t60`),c=e(a,`hfDamp`),l=e(a,`damper`),u=!t.gate&&t.damped&&l<19.9?ne/l:0,d=.45*this.sr,f=0,p=0;for(let e=0;e<r;e++){let r=o*n.ratios[e],a=2*Math.PI*r;if(t.om[e]=a,r>=d){t.A[e]=t.B[e]=t.C[e]=t.sw[e]=t.sw2[e]=0;continue}f=e+1;let l=(s+c*(r/1e3)**2)*this.dampMul+u,m=Math.exp(-l*i);if(l<a)t.A[e]=2*m*Math.cos(Math.sqrt(a*a-l*l)*i);else{let n=Math.sqrt(l*l-a*a)*i;t.A[e]=m*(Math.exp(n)+Math.exp(-n))}t.B[e]=m*m,t.C[e]=i*i/(1+Math.tanh(l*i));let h=2-2*Math.cos(a*i),g=Math.max(0,Math.min(1,(3.6/h-1)/12));t.sw[e]=a*Math.sqrt(g),t.sw2[e]=a*a*g,g>0&&(p=e+1)}for(let e=f;e<r;e++)t.q[e]=t.qp[e]=0;t.nTune=f,t.nNLTune=Math.min(p,f),t.nAct=Math.min(f,t.cull),t.nNL=Math.min(t.nNLTune,t.nAct),t.omega1=2*Math.PI*o,t.Z0=2*o;let m=0;for(let e=0;e<f;e++)m+=t.phiE[e]*t.phiE[e]*t.C[e];t.wsum=m;let h=+Math.max(t.buzzPhi1,.05)/t.omega1,g=e(a,`buzz`);t.buzzGap=e(a,`buzzGap`)*h,t.buzzK=g>0?g*(2*Math.PI*4e3)**2*.1*h**(1-this.buzzA):0,t.tunedPitch=this.pitchMul,t.tunedDamp=this.dampMul,t.tunedGate=t.gate,t.tunedGlide=t.glideMul,t.tunedVib=t.vibMul,t.dirtyTune=!1}vecVoice(t){let n=this.model,r=n.N,i=this.p,a=t.posX>=0?t.posX:se(e(i,`exPos`)+this.posOff),o=t.posY>=0?t.posY:se(e(i,`exPosY`)+this.posOff),s=e(i,`exWidth`)*.15,c=e(i,`buzzPos`),l=e(i,`buzzPosY`),u=P(e(i,`pickup`)+this.pickOff),d=e(i,`pickupY`),f=e(i,`width`),p=P(u+.5*f),m=P(d+.37*f),h=e(i,`spread`),g=e(i,`tilt`)/6.0206;for(let e=0;e<r;e++){let i=Math.exp(-.5*(Math.PI*n.wavenum[e]*s)**2);t.phiE[e]=n.shape(e,a,o)*i,t.phiB[e]=n.shape(e,c,l);let f=n.ratios[e]**+g;t.wL[e]=((1-h)*n.shape(e,u,d)+h*n.rad[e])*f,t.wR[e]=((1-h)*n.shape(e,p,m)+h*n.rad[(e+1)%r]*(e%2?1:-1))*f}t.buzzPhi1=Math.abs(n.shape(n.pitchK,c,l)),t.beta=Math.max(.02,Math.min(a,1-a)),t.dirtyVec=!1,t.dirtyTune=!0}rand(){let e=this.rngS;return e^=e<<13,e^=e>>>17,e^=e<<5,this.rngS=e>>>0,this.rngS/4294967296}lfo(n,r){let i=this.p,a=e(i,`lfo${n+1}Rate`),o=this.lfoPh[n]+a*r;switch(o>=1&&(o-=Math.floor(o),this.lfoA[n]=this.lfoB[n],this.lfoB[n]=this.rand()*2-1),this.lfoPh[n]=o,t(i,`lfo${n+1}Shape`)){case`tri`:return 1-4*Math.abs(o-.5);case`saw`:return 2*o-1;case`square`:return o<.5?1:-1;case`sh`:return this.lfoB[n];case`smooth`:return this.lfoA[n]+(this.lfoB[n]-this.lfoA[n])*(.5-.5*Math.cos(Math.PI*o));default:return Math.sin(2*Math.PI*o)}}blockUpdate(n){let r=this.p,i=this.sr,a=n/i,o=this.bend*e(r,`bendRange`),s=1,c=0,l=0,u=e(r,`tension`),d=e(r,`cascade`),f=1,p=1,m=1;for(let n=0;n<2;n++){let i=t(r,`lfo${n+1}Target`);if(i===`off`)continue;let h=e(r,`lfo${n+1}Depth`),g=this.lfo(n,a)*h;switch(i){case`pitch`:o+=4*g;break;case`amp`:s*=Math.max(0,1+g);break;case`position`:c+=.5*g;break;case`pickup`:l+=.5*g;break;case`tension`:u*=Math.max(0,1+g);break;case`cascade`:d*=Math.max(0,1+g);break;case`damping`:f*=2**(3*g);break;case`feedback`:p*=Math.max(0,1+g);break;case`exciter`:m*=Math.max(0,1+g)}}this.pitchMul=2**(o/12),this.dampMul=f,this.ampMul=s,this.fbMul=p,this.excMul=m,this.kt=u,this.kc=this.model.M>0?d:0,this.cc=+e(r,`curvature`),this.ct=e(r,`crossTension`),this.cl=e(r,`crossLink`),this.crossOn=this.ct>0||this.cl>0,this.buzzTwo=t(r,`buzzSides`)===`two`;let h=t(r,`exciter`);this.law=h===`bow`?1:h===`reed`?2:h===`selfosc`?3:h===`noise`?4:0;let g=this.lawK;this.law===1?(g[0]=e(r,`bowSpeed`)*.5,g[1]=+e(r,`bowForce`),g[2]=e(r,`bowNoise`)):this.law===2?(g[0]=e(r,`reedGain`)*2,g[1]=e(r,`reedPressure`),g[2]=e(r,`breath`)):this.law===3&&(g[0]=+e(r,`selfGain`),g[1]=e(r,`selfSat`)),this.envAtt=1-Math.exp(-1/(e(r,`attack`)/1e3*i)),this.envRel=1-Math.exp(-1/(e(r,`release`)/1e3*i));let _=Math.min(e(r,`noiseColor`),.45*i);this.noiseC=1-Math.exp(-2*Math.PI*_/i),this.noiseNorm=Math.sqrt(3*(2-this.noiseC)/this.noiseC),this.fbD=Math.max(1,Math.min(32767,Math.round(e(r,`fbDelay`)/1e3*i)));let v=2*Math.PI*Math.min(e(r,`fbFreq`),.45*i)/i,y=Math.sin(v)/(2*e(r,`fbQ`)),b=1+y;this.fb0=y/b,this.fb2=-y/b,this.fa1=-2*Math.cos(v)/b,this.fa2=(1-y)/b;let x=c!==this.lastPosOff||l!==this.lastPickOff||this.vecVersion!==this.paramVersion;this.posOff=c,this.pickOff=l,this.lastPosOff=c,this.lastPickOff=l,this.vecVersion=this.paramVersion;let S=e(r,`vibDepth`),C=e(r,`vibRate`),w=e(r,`vibDelay`)/1e3;this.act.length=0;for(let e of this.voices)if(e.active){if(S>0){e.vibAge+=a;let t=e.vibAge,n=w>0?(t-.3*w)/(.7*w):1;n=n<0?0:n>1?1:n*n*(3-2*n),e.vibPh+=C*e.vibRateJ*(1+.06*Math.sin(2.3*t+7*e.vibRateJ))*a,e.vibPh-=Math.floor(e.vibPh);let r=2**(S*n*Math.sin(2*Math.PI*e.vibPh)/1200);(Math.abs(r/e.vibMul-1)>1e-5||n===0&&e.vibMul!==1)&&(e.vibMul=r)}else e.vibMul=1;x&&(e.dirtyVec=!0),this.prepare(e),this.act.push(e)}}nl(e){if(this.kt<=0&&this.ct<=0&&this.kc<=0&&!this.crossOn&&!e.ham&&e.buzzK<=0){e.S=e.X=e.Vv=e.gz=0,e.useG=!1;return}let t=e.nAct,n=e.q,r=e.sw,i=e.grad,a=this.model,o=0,s=!1,c=e.nNL,l=0;if(this.kt>0||this.ct>0||this.kc>0)for(let e=0;e<c;e++){let t=r[e]*n[e];l+=t*t}if(e.S=l,i.fill(0,0,t),e.gz=0,this.kt>0&&l>0){let e=3/this.kt,t=l/k;o+=this.kt*k*.5*e*e*N(t/e);let a=this.kt*e*Math.tanh(t/e);for(let e=0;e<c;e++)i[e]+=a*r[e]*r[e]*n[e];s=!0}let u=this.kc;if(u>0){let t=a.Nnl,l=Math.min(c,t),d=e.pv,f=e.gp,p=this.cc,m=3/(u*a.M);for(let e=0;e<t;e++)d[e]=e<l?r[e]*n[e]:0,f[e]=0;let h=a.ti,g=a.tj,_=a.tv,v=a.tb;for(let e=0;e<a.M;e++){let n=a.tStart[e],r=a.tStart[e+1],i=0;for(let e=n;e<r;e++)i+=_[e]*d[h[e]]*d[g[e]];let s=0,c=e*t;if(p!==0)for(let e=0;e<l;e++)s+=v[c+e]*d[e];let y=(i+p*s)/k;o+=u*k*m*m*N(y/m);let b=u*m*Math.tanh(y/m),x=2*b;for(let e=n;e<r;e++)f[h[e]]+=x*_[e]*d[g[e]];let S=b*p;if(S!==0)for(let e=0;e<l;e++)f[e]+=S*v[c+e]}for(let e=0;e<l;e++)i[e]+=r[e]*f[e];s=!0}if(e.ham){let r=e.phiE,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=e.hz*e.hamISM-a;if(c>0){let n=e.hamA,a=e.hamK*c**+n;o+=a*c/(n+1);for(let e=0;e<t;e++)i[e]-=a*r[e];e.gz=a*e.hamISM,e.hamTimer=0,s=!0}else++e.hamTimer>.05*this.sr&&(e.ham=!1)}if(e.buzzK>0){let r=e.phiB,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=this.buzzA,l=0,u=a-e.buzzGap;if(u>0){let t=e.buzzK*u**+c;o+=t*u/(c+1),l+=t}if(this.buzzTwo){let t=-a-e.buzzGap;if(t>0){let n=e.buzzK*t**+c;o+=n*t/(c+1),l-=n}}if(l!==0){for(let e=0;e<t;e++)i[e]+=l*r[e];s=!0}}if(this.crossOn){let t=0,r=Math.min(c,a.Nnl),i=a.bx;if(this.cl>0)for(let a=0;a<r;a++)t+=i[a]*e.sw[a]*n[a];e.X=.5*this.ct*l+this.cl*1*t}else e.X=0;e.Vv=o,e.useG=s||this.crossOn}nlTension(e){let t=e.nNL,n=e.q,r=e.qp,i=e.sw2,a=0,o=0;for(let e=0;e<t;e++){let t=i[e]*n[e];a+=t*n[e],o+=t*r[e]}if(e.S=a,e.X=0,e.gz=0,e.fast=!0,a>0){let t=3/this.kt,n=a/k;e.Vv=this.kt*k*.5*t*t*N(n/t),e.tc=this.kt*t*Math.tanh(n/t),e.tq=e.tc===0?0:o,e.useG=!0}else e.Vv=0,e.tc=0,e.tq=0,e.useG=!1}lawEval(e){let t=0,n=0;if(this.law===1){let r=e-this.lwVb,i=Math.tanh(r/j),a=1+Math.abs(r)/M,o=.35+.65/a,s=-.65/(M*a*a)*(r>=0?1:-1);t=-this.lwF*i*o,n=-this.lwF*((1-i*i)/j*o+i*s)}else if(this.law===2){let r=this.lwGam-e;if(r<1){let e=Math.sqrt(Math.abs(r)+1e-9),i=this.lwF;r>=0?(t=i*(1-r)*e,n=-i*(-e+(1-r)/(2*e))):(t=-i*(1-r)*e,n=-i*(e+(1-r)/(2*e)))}}else{let r=this.lwF,i=this.lwVb;t=r*(e-e*e*e/(3*i*i)),n=r*(1-e*e/(i*i))}return this.lwD=n,t}solveLaw(e,t,n){let r=e.nAct,i=e.phiE,a=e.A,o=e.B,s=e.q,c=e.qp,l=e.qn,u=0;for(let e=0;e<r;e++){let t=a[e]*s[e]-o[e]*c[e];l[e]=t,u+=i[e]*(t-c[e])}e.pred=!0;let d=.5/this.h,f=(u+t*e.wsum)*d,p=e.wsum*d,m=e.env*this.excMul,h=e.Z0,g=this.lawK;if(this.law===1){this.lwVb=g[0]*m;let t=g[2];this.lwF=g[1]*h*(this.lwVb/.05)*(.11/e.beta)*(t>0?Math.max(0,1+t*n):1)}else this.law===2?(this.lwF=g[0]*h,this.lwGam=g[1]*m*(1+g[2]*n)):(this.lwF=g[0]*h*m,this.lwVb=g[1]);let _=this.lwF+1e-9,v=1e-9*_,y=e.fLaw,b=!1;for(let e=0;e<8;e++){let e=y-this.lawEval(f+p*y);if(Math.abs(e)<v){b=!0;break}let t=1-p*this.lwD;if(t<.05)break;y-=e/t}if(!b||!Number.isFinite(y)){let t=Number.isFinite(e.fLaw)?e.fLaw:0,n=.01*_,r=t,i=t,a=0,o=0;for(let e=0;e<60&&(r=t-n,i=t+n,a=r-this.lawEval(f+p*r),o=i-this.lawEval(f+p*i),!(a<=0&&o>=0));e++)n*=2;for(let e=0;e<50;e++){let e=.5*(r+i);e-this.lawEval(f+p*e)<0?r=e:i=e}y=.5*(r+i),Number.isFinite(y)||(y=0)}return e.fLaw=y,y}process(t,n,r,i=0){let a=Date.now(),o=r/this.sr;if(this.pending.length){let e=[];for(let t of this.pending)(`time`in t&&t.time!==void 0?t.time:0)<=i+o?this.handle(t):e.push(t);this.pending=e}this.blockUpdate(r);let s=this.act,c=this.h,l=c*c,u=1/c,d=this.p,f=e(d,`fbGain`)*this.fbMul,p=e(d,`fbSat`),m=e(d,`noiseLevel`),h=this.law,g=h===4||h===3||h===2&&e(d,`breath`)>0||h===1&&e(d,`bowNoise`)>0,_=this.box,v=_.n>0,y=v?e(d,`boxMix`):0,b=1-y,x=this.boxOut,S=.25*this.ampMul*u*10**(e(d,`level`)/20),C=32767,w=this.kt>0&&this.kt<=ie&&this.kc<=0&&!this.crossOn;for(let e=0;e<r;e++){let r=0,i=0,a=!1;for(let e=0;e<s.length;e++){let t=s[e];t.env+=((t.gate?t.vel:0)-t.env)*(t.gate?this.envAtt:this.envRel);let n=0;if(t.env>1e-6){let e=0;if(g&&(t.nz+=this.noiseC*(this.rand()*2-1-t.nz),e=t.nz*this.noiseNorm),f>0){let e=t.fb[t.fbW-this.fbD&C],r=this.fb0*e+this.fb2*t.bx2-this.fa1*t.by1-this.fa2*t.by2;t.bx2=t.bx1,t.bx1=e,t.by2=t.by1,t.by1=r,n+=p*t.Z0*Math.tanh(f*r/p)*t.env}h===3&&(n+=.001*t.Z0*t.env*e),h===4?n+=m*t.Z0*t.env*this.excMul*e*.5:h!==0&&(n+=this.solveLaw(t,n,e))}else t.fLaw=0;t.f=n,w&&!t.ham&&t.buzzK<=0?this.nlTension(t):(t.fast=!1,this.nl(t)),r+=t.Vv,i+=t.X,t.useG&&(a=!0)}if(this.crossOn&&s.length){let e=i/k;r+=k*3*3*N(e/3);let t=3*Math.tanh(e/3),n=this.ct,a=+this.cl,o=this.model.bx,c=this.model.Nnl;for(let e of s){let r=e.nNL,i=e.grad,s=e.q,l=e.sw;for(let e=0;e<r;e++)i[e]+=t*(n*l[e]*l[e]*s[e]+(e<c?a*o[e]*l[e]:0))}}let o=0;if(!a)this.psi=Math.sqrt(this.eps);else{r>this.vMax&&(this.vMax=r),this.psiReset&&(this.eps=.01);let e=Math.sqrt(2*r+this.eps),t=1/e;if(this.psiReset)this.psi=e,this.psiReset=!1;else{let t=this.psi+.01*(e-this.psi);Math.abs(t)<Math.abs(this.psi)&&(this.psi=t)}let n=0;for(let e of s){if(!e.useG)continue;if(e.fast){n+=e.tc*e.tq;continue}let t=e.nAct,r=e.grad,i=e.qp;for(let e=0;e<t;e++)n+=r[e]*i[e];e.ham&&(n+=e.gz*e.hzp)}n*=t;let i=this.psi,a=n/4-i,c=0,u=0;for(let e of s){if(!e.useG)continue;e.pred=!1;let n=e.nAct,r=e.q,i=e.qp,o=e.qn,s=e.A,d=e.B,f=e.C,p=e.phiE,m=e.f;if(e.fast){let l=e.nNL,h=e.sw2,g=e.tc*t;for(let e=0;e<l;e++){let t=g*h[e]*r[e],n=f[e],l=s[e]*r[e]-d[e]*i[e]+n*(p[e]*m+t*a);o[e]=l,c+=t*l,u+=n*t*t}for(let e=l;e<n;e++)o[e]=s[e]*r[e]-d[e]*i[e]+f[e]*p[e]*m;continue}let h=e.grad;for(let e=0;e<n;e++){let n=h[e]*t,l=s[e]*r[e]-d[e]*i[e]+f[e]*(p[e]*m+n*a);o[e]=l,c+=n*l,u+=f[e]*n*n}if(e.ham){let n=e.gz*t,r=2*e.hz-e.hzp+l*n*a;e.hzn=r,c+=n*r,u+=l*n*n}}let d=c/(1+u/4);o=d*t/4;for(let e of s){if(!e.useG||e.fast)continue;let t=e.nAct,n=e.grad,r=e.qn,i=e.C;for(let e=0;e<t;e++)r[e]-=i[e]*n[e]*o;e.ham&&(e.hzn-=l*e.gz*o)}this.psi=i+(d-n)/2}let c=0,d=0;for(let e of s){let t=e.nAct,n=e.q,r=e.qp,i=e.qn,a=e.wL,s=e.wR,l=0,f=0;if(!e.useG){let o=e.A,c=e.B,u=e.C,d=e.phiE,p=e.f;if(e.pred){e.pred=!1;for(let e=0;e<t;e++){let t=i[e]+u[e]*d[e]*p;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}}else if(p!==0)for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e]+u[e]*d[e]*p;i[e]=t;let m=t-n[e];l+=a[e]*m,f+=s[e]*m}else for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e];i[e]=t;let u=t-n[e];l+=a[e]*u,f+=s[e]*u}e.ham&&(e.hzn=2*e.hz-e.hzp)}else if(e.fast){let r=e.nNL,c=e.sw2,u=e.C,d=e.tc*o;for(let e=0;e<r;e++){let t=i[e]-u[e]*c[e]*n[e]*d;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}for(let e=r;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}}else for(let e=0;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}c+=l,d+=f,e.fb[e.fbW]=.5*(l+f)*u,e.fbW=e.fbW+1&C;let p=e.qp;e.qp=e.q,e.q=e.qn,e.qn=p,e.ham&&(e.hzp=e.hz,e.hz=e.hzn)}v?(_.tick(.5*(c+d)*S,x),t[e]=b*c*S+y*x[0],n[e]=b*d*S+y*x[1]):(t[e]=c*S,n[e]=d*S)}this.blockEnd(r),this.cpuMs+=Date.now()-a,this.cpuWall+=o*1e3}blockEnd(t){let n=1/this.h,r=this.kc<=0&&this.kt<=ie&&!this.crossOn&&!(e(this.p,`fbGain`)>0);for(let t of this.act){let i=t.nAct,a=t.q,o=t.qp,s=t.om,c=0,l=0;for(let e=0;e<i;e++){let t=(a[e]-o[e])*n,r=.5*(t*t+s[e]*s[e]*a[e]*a[e]);c+=r,r>l&&(l=r)}if(r&&!t.ham&&t.buzzK<=0&&(this.law===0||t.env<=1e-6)){let e=l*re,r=i;for(;r>1;){let t=r-1,i=(a[t]-o[t])*n;if(.5*(i*i+s[t]*s[t]*a[t]*a[t])>e)break;r--}if(r<i){for(let e=r;e<i;e++)a[e]=o[e]=0;t.cull=r,t.nAct=r,t.nNL=Math.min(t.nNLTune,r)}}else t.cull!==1/0&&t.uncull();if(!Number.isFinite(c)||c>1e8){t.reset(),t.active=!1,this.psiReset=!0;continue}t.energy=c;let u=e(this.p,`glide`),d=1;if(u!==0){let e=4*c/k;d=2**(u*e/(1+e)/12)}(Math.abs(d/t.glideMul-1)>2e-5||d===1&&t.glideMul!==1)&&(t.glideMul=d),!t.gate&&!t.ham&&c<1e-10&&t.env<1e-4&&(t.active=!1)}let i=0;for(let e of this.act)e.active&&(i+=e.energy);this.vHold=Math.max(this.vMax,this.vHold*.95),this.vMax=0;let a=Math.max(A,.02*i+2*this.vHold);if(a<this.eps){let e=Math.max(a,this.eps*.95),t=this.psi*this.psi-(this.eps-e);this.psi=(this.psi<0?-1:1)*Math.sqrt(Math.max(0,t)),this.eps=e}this.snapCount+=t,this.snapCount>=this.sr/30&&(this.snapCount=0,this.cpuWall>0&&(this.cpu=this.cpuMs/this.cpuWall),this.cpuMs=this.cpuWall=0,this.snapshot())}snapshot(){let e=this.focus&&this.focus.active?this.focus:null;if(!e)for(let t of this.voices)t.active&&(!e||t.order>e.order)&&(e=t);let t=this.model.N,n=new Float32Array(t),r=new Float32Array(t),i=new Float32Array(t),a=new Float32Array(t);if(e){let o=1/this.h;for(let s=0;s<t;s++){n[s]=e.q[s];let t=(e.q[s]-e.qp[s])*o;r[s]=t,i[s]=.5*(t*t+e.om[s]*e.om[s]*e.q[s]*e.q[s]),a[s]=e.om[s]/(2*Math.PI)}}let o=[];for(let e of this.voices)e.active&&o.push(e.note);let s={type:`snap`,cpu:this.cpu,nVoices:o.length,notes:o,focusNote:e?e.note:-1,focusHz:e?e.baseHz*this.pitchMul:0,nAct:e?e.nAct:0,q:n,qd:r,energy:i,freqs:a,touch:this.lastTouch};this.post(s,[n.buffer,r.buffer,i.buffer,a.buffer])}};const F=48e3,I=.3;let L,R,z,B=0,le,V=0,ue=0,H=0,U=1/0,W=0,de=4*F,fe=!1;const G=[],pe=/* @__PURE__ */ new Map;let K=!1,q=1,J=1,me=1,Y=0,X=!1,Z=I*I,he=!1,ge=1/0,_e=1;self.onmessage=e=>{let t=e.data;t.type===`init`&&(R={...u,...t.sound},z=R,L=new ce(F),L.message({type:`params`,params:R}),B=t.stem,q=Math.max(1,t.slow??1),V=t.fromFrame,H=t.fromFrame,ue=t.sendFrame,W=t.sendFrame,le=t.playerPort,le.onmessage=e=>{W=e.data.playhead,de=e.data.ahead,ve()},t.scorePort.onmessage=e=>{let t=e.data;if(t.type===`cmds`){for(let e of t.cmds)G.push(e);H=Math.max(H,Math.floor(t.horizon*F))}else t.type===`end`&&(U=Math.round(t.t*F),H=Math.max(H,U));ve()})};function ve(){K||(K=!0,setTimeout(xe,0))}function ye(e){switch(e.type){case`noteOn`:L.message({type:`noteOn`,note:e.note,vel:e.vel}),pe.set(e.note,e.t);break;case`noteOff`:if(e.on!==void 0&&(pe.get(e.note)??-1/0)>e.on)break;L.message({type:`noteOff`,note:e.note});break;case`params`:z={...z,...e.params},L.message({type:`params`,params:z});break;case`bend`:L.message({type:`bend`,value:e.value});break;case`gain`:me=e.value,Y=e.tau,X=!!e.normalize;break;case`hold`:{if(he)break;he=!0;let t=e.hold+e.fade,n=Math.min(60,Math.max(R.t60,6*t)),r=n/R.t60;z={...z,t60:n,hfDamp:R.hfDamp/r},L.message({type:`params`,params:z}),ge=e.t+Math.max(e.hold,.005),_e=Math.max(.01,e.fade);break}}}const Q=/* @__PURE__ */ new Float32Array(128),$=/* @__PURE__ */ new Float32Array(128);function be(e,t,n){let r=V/F,i=(V+128)/F;for(;G.length&&G[0].t<i;)ye(G.shift());if(Q.fill(0),$.fill(0),L.process(Q,$,128,r),X){let e=0;for(let t=0;t<128;t++)e+=Q[t]*Q[t]+$[t]*$[t];e/=256,e>1e-10&&(Z+=(e-Z)*(1-Math.exp(-128/F/1.5)))}let a=X?Math.max(.05,Math.min(20,I/Math.sqrt(Z))):1,o=me*a,s=J;J=Y>0?J+(o-J)*(1-Math.exp(-128/F/Y)):o;for(let r=0;r<128;r++){let i=s+(J-s)*(r+1)/128,a=(V+r)/F;if(a>=ge){let e=Math.min(1,(a-ge)/_e),t=Math.cos(Math.PI/2*e);i*=t*t}e[n+r]=Q[r]*i,t[n+r]=$[r]*i}V+=128}function xe(){if(K=!1,!L)return;if(V>=U){fe||(fe=!0,Se({type:`done`,stem:B,frame:U}));return}let e=Math.min(H,W+de,U+128-1),t=Math.min(2048,Math.floor((e-V)/128)*128);if(t<=0)return;let n=V,r=new Float32Array(t),i=new Float32Array(t),a=performance.now();for(let e=0;e<t;e+=128)be(r,i,e);if(q>1){let e=performance.now()+(q-1)*(performance.now()-a);for(;performance.now()<e;);}if(n+t>ue){let e=Math.max(0,ue-n),t=e?r.slice(e):r,a=e?i.slice(e):i;Se({type:`chunk`,stem:B,frame:n+e,L:t,R:a},[t.buffer,a.buffer])}ve()}function Se(e,t=[]){le.postMessage(e,t)}
\ No newline at end of file
site/assets/worklet-B7ys4Kw_.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-const e=Math.SQRT2,t=Math.PI;function n(e,n){let r=Math.ceil(Math.abs(n)+e)+24,i=0;for(let a=0;a<=r;a++){let o=t*a/r;i+=(a===0||a===r?.5:1)*Math.cos(e*o-n*Math.sin(o))}return i/r}function r(e,t){let r=[],i=e===0?.5:e,a=n(e,i);for(let o=i+.05;o<=t;o+=.05){let t=n(e,o);if(a*t<0){let t=i,s=o,c=a;for(let r=0;r<50;r++){let r=.5*(t+s),i=n(e,r);c*i<=0?s=r:(t=r,c=i)}r.push(.5*(t+s))}i=o,a=t}return r}const i=[4.730040745,7.853204624,10.99560784,14.13716549,17.27875966],a=e=>e<i.length?i[e]:(2*e+3)*t/2;function o(e,t,n){if(t<12){let e=(Math.cosh(t)-Math.cos(t))/(Math.sinh(t)-Math.sin(t));return Math.cosh(t*n)+Math.cos(t*n)-e*(Math.sinh(t*n)+Math.sin(t*n))}let r=e%2==0?1:-1;return Math.cos(t*n)-Math.sin(t*n)+Math.exp(-t*n)+r*Math.exp(-t*(1-n))}const s=[[.5,2],[1,2],[1.2,3],[1.5,3],[2,4],[2.5,4],[2.67,3],[3,5],[4,6],[4.24,5],[5.33,7],[5.7,6],[6.67,8],[7.2,7],[8,9],[9,8],[10,10],[11.1,9],[12.1,11],[13.5,10]];function c(i,c,d,f,p=2){let m=new Float64Array(c),h=new Float64Array(c),g={kind:i,N:c,ratios:m,wavenum:h,aspect:d};switch(i){case`string`:case`free`:for(let e=0;e<c;e++){let t=e+1;m[e]=i===`string`?t:t**+f,h[e]=t}return{...g,view:`line`,dim:1,shape:(n,r)=>e*Math.sin((n+1)*t*r)};case`tube_co`:for(let e=0;e<c;e++)m[e]=2*e+1,h[e]=(2*e+1)/2;return{...g,view:`line`,dim:1,shape:(n,r)=>e*Math.cos((2*n+1)*t*r/2)};case`tube_oo`:for(let e=0;e<c;e++)m[e]=e+1,h[e]=e+1;return{...g,view:`line`,dim:1,shape:(n,r)=>e*Math.cos((n+1)*t*r)};case`bar`:{let e=a(0),n=new Float64Array(c),r=2048;for(let i=0;i<c;i++){let s=a(i);m[i]=(s/e)**2,h[i]=s/t;let c=0;for(let e=0;e<r;e++)c+=o(i,s,(e+.5)/r)**2;n[i]=1/Math.sqrt(c/r)}return{...g,view:`line`,dim:1,shape:(e,t)=>n[e]*o(e,a(e),t)}}case`ring`:{let n=[],r=[],i=0,a=0,o=2;for(;n.length<c;){i<s.length?[a,o]=s[i]:(a*=1.09,o+=+(i%2==0));for(let e=0;e<2&&n.length<c;e++)m[n.length]=a*(e===0?1:1+6e-4*(1+i%3)),h[n.length]=2*o,n.push(o),r.push(e);i++}return{...g,view:`ring`,dim:1,shape:(i,a)=>{let o=2*t*a*n[i];return e*(r[i]===0?Math.cos(o):Math.sin(o))}}}case`plate`:{let e=Math.ceil(3*Math.sqrt(c))+3,n=[];for(let t=1;t<=e;t++)for(let r=1;r<=e;r++)n.push([t*t+(r/d)**2,t,r]);n.sort((e,t)=>e[0]-t[0]);let r=new Int32Array(c),i=new Int32Array(c),a=n[0][0];for(let e=0;e<c;e++){let[t,o,s]=n[e];m[e]=t/a,h[e]=Math.sqrt(o*o+(s/d)**2),r[e]=o,i[e]=s}return{...g,view:`rect`,dim:2,shape:(e,n,a)=>2*Math.sin(r[e]*t*n)*Math.sin(i[e]*t*a)}}case`membrane`:{let i=2*Math.sqrt(c)+6,a=[];for(;;){a=[];for(let e=0;e<=Math.ceil(i);e++)for(let t of r(e,i))a.push([t,e,0]),e>0&&a.push([t,e,1]);if(a.length>=c)break;i*=1.3}a.sort((e,t)=>e[0]-t[0]||e[2]-t[2]);let o=a[0][0],s=new Int32Array(c),l=new Int32Array(c),d=new Float64Array(c),f=new Float64Array(c);for(let r=0;r<c;r++){let[i,c,u]=a[r];m[r]=i/o,h[r]=i/t,s[r]=c,l[r]=u,d[r]=i,f[r]=c===0?1/Math.abs(n(1,i)):e/Math.abs(n(c+1,i))}return u(g,s,l,d,f)}case`disc`:{let e=p,n=Math.ceil(Math.sqrt(2*c))+4,r=[];for(let t=0;t<=n;t++)for(let i=0;t+2*i<=n;i++){if(i===0&&t<2)continue;let n=(t+2.1*i)**+e;r.push([n,t,i,0]),t>0&&r.push([n*1.0004,t,i,1])}r.sort((e,t)=>e[0]-t[0]);let i=r.slice(0,c),a=i.reduce((e,t)=>Math.max(e,t[1]),0),o=i.reduce((e,t)=>Math.max(e,t[2]),0),s=[];for(let e=0;e<=a;e++)s.push(l(e,o+1));let d=new Int32Array(c),f=new Int32Array(c),_=new Float64Array(c),v=i[0][0];for(let e=0;e<c;e++){let[n,r,a,o]=i[e];m[e]=n/v,d[e]=r,f[e]=o,_[e]=s[r][r===0?a-1:a],h[e]=_[e]/t}return u(g,d,f,_,null)}}}function l(e,t){let r=t=>e===0?-n(1,t):.5*(n(e-1,t)-n(e+1,t)),i=[],a=e===0?.5:Math.max(.3,e*.8),o=r(a);for(let e=a+.05;i.length<t;e+=.05){let t=r(e);if(o*t<0){let t=a,n=e,s=o;for(let e=0;e<50;e++){let e=.5*(t+n),i=r(e);s*i<=0?n=e:(t=e,s=i)}i.push(.5*(t+n))}a=e,o=t}return i}function u(e,t,r,i,a){let o=e.N,s=Array(o).fill(null),c=a??new Float64Array(o),l=(e,r)=>{let o=s[e];if(!o){o=/* @__PURE__ */ new Float64Array(258);for(let r=0;r<=256;r++)o[r]=n(t[e],i[e]*r/256);if(o[257]=o[256],s[e]=o,!a){let n=0;for(let e=0;e<=256;e++)n+=(e===0||e===256?.5:1)*o[e]*o[e]*e/256/256;c[e]=1/Math.sqrt(Math.max(1e-12,(t[e]===0?2:1)*n))}}let l=r*256,u=Math.floor(l),d=l-u;return o[u]*(1-d)+o[u+1]*d};return{...e,view:`disk`,dim:2,shape:(e,n,i)=>{let a=2*n-1,o=2*i-1,s=Math.hypot(a,o);if(s>=1)return 0;let u=l(e,s),d=t[e],f=d===0?1:r[e]===0?Math.cos(d*Math.atan2(o,a)):Math.sin(d*Math.atan2(o,a));return c[e]*u*f}}}const d=(e,t)=>e[t],f=(e,t)=>e[t],p=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,m=(...e)=>t=>e.includes(t.geometry),h=(...e)=>t=>e.includes(t.exciter),g=[`bow`,`reed`,`selfosc`,`noise`],_=[[`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`]],v=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function y(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:_,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:v,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}]}const b=[{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:m(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:m(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:m(`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&&p(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:p},{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:h(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:h(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:h(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:h(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:h(`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:h(`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:h(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:h(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:h(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:h(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:h(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:h(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:h(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:h(...g)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:h(...g)},{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},...y(1),...y(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:p},{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`}];Object.fromEntries(b.map(e=>[e.id,e]));const x=Object.fromEntries(b.map(e=>[e.id,e.def])),S=b.filter(e=>e.model).map(e=>e.id);function C(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 w(e){let t=Math.max(e(),1e-12);return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*e())}const T=e=>S.map(t=>String(e[t])).join(`|`);function E(e){let t=Math.round(d(e,`modes`)),n=c(f(e,`geometry`),t,d(e,`aspect`),d(e,`powerExp`),d(e,`discExp`)),r=Math.round(d(e,`seed`)),i=C(r*7919+13),a=d(e,`stretch`),o=d(e,`inharm`),s=d(e,`harmonize`),l=d(e,`jitter`),u=0;for(let e=0;e<t;e++)if(Math.abs(n.ratios[e]-1)<1e-9){u=e;break}let p=new Float64Array(t);for(let e=0;e<t;e++){let t=n.ratios[e]**+a;if(t*=Math.sqrt(1+o*t*t)/Math.sqrt(1+o),s>0){let e=t<.75?.5:Math.max(1,Math.round(t));t=t**(1-s)*e**+s}let r=w(i);e!==u&&l>0&&(t*=2**(l*r/1200)),p[e]=t}let m=Int32Array.from({length:t},(e,t)=>t).sort((e,t)=>p[e]-p[t]),h=new Float64Array(t),g=new Float64Array(t),_=0;for(let e=0;e<t;e++)h[e]=p[m[e]],g[e]=n.wavenum[m[e]],m[e]===u&&(_=e);let v=Math.min(t,Math.round(d(e,`nlModes`))),y=Math.round(d(e,`terms`)),b=C(r*104729+7),x=[],S=new Float64Array(y*v);for(let e=0;e<y;e++){let t=[],n=Math.max(2,Math.round(v*.75)),r=0;for(let e=0;e<n;e++){let e=Math.floor(b()*v),n=b()<.25?e:Math.floor(b()*v),i=w(b);t.push([e,n,i]),r+=(e===n?1:2)*i*i}let i=1/Math.sqrt(r),a=[];for(let[e,n,r]of t)a.push([e,n,r*i]),e!==n&&a.push([n,e,r*i]);x.push(a);let o=0;for(let t=0;t<v;t++){let n=w(b);S[e*v+t]=n,o+=n*n}o=1/Math.sqrt(o);for(let t=0;t<v;t++)S[e*v+t]*=o}let E=x.reduce((e,t)=>e+t.length,0),D=new Int32Array(y+1),O=new Int32Array(E),k=new Int32Array(E),A=new Float64Array(E),j=0;for(let e=0;e<y;e++){D[e]=j;for(let[t,n,r]of x[e])O[j]=t,k[j]=n,A[j]=r,j++}D[y]=j;let M=C(r*31337+1),N=new Float64Array(v),P=0;for(let e=0;e<v;e++)N[e]=w(M),P+=N[e]**2;for(let e=0;e<v;e++)N[e]/=Math.sqrt(P);let F=new Float64Array(t);for(let e=0;e<t;e++)F[e]=(M()<.5?-1:1)*(.5+.5*M());return{key:T(e),geom:n,N:t,ratios:h,wavenum:g,pitchK:_,perm:m,Nnl:v,M:y,tStart:D,ti:O,tj:k,tv:A,tb:S,bx:N,rad:F,shape:(e,t,r)=>n.shape(m[e],t,r)}}const D={violin:{name:`Violin`,low:[[275,22,0],[405,30,-12],[470,40,-8],[460,32,0],[540,32,2]],hill:2600,hillDb:6,top:5500},viola:{name:`Viola`,low:[[230,22,0],[340,30,-12],[390,40,-8],[380,32,0],[445,32,2]],hill:2100,hillDb:5,top:4800},cello:{name:`Cello`,low:[[102,20,0],[145,30,-10],[170,40,-8],[178,30,1],[210,30,2]],hill:1500,hillDb:4,top:3500},bass:{name:`Double bass`,low:[[62,18,0],[92,28,-10],[104,38,-8],[112,30,1],[138,30,2]],hill:900,hillDb:3,top:2400},guitar:{name:`Guitar`,low:[[98,18,0],[204,28,3],[230,35,-6],[390,30,-3],[440,35,-2]],hill:2500,hillDb:2,top:5e3}};function O(e,t,n,r=1){let i=D[e];if(!i)return[];let a=C(r*6151+17),o=[];for(let[e,r,s]of i.low){let i=10**(s/20);o.push({f:e/t,q:r/n,gL:i,gR:i*(.8+.4*a())})}let s=1.2*Math.max(...i.low.map(e=>e[0]));for(;s<4.5*i.top;){let e=Math.log2(s/i.hill),r=-6+i.hillDb*Math.exp(-(e*e)/.72);r-=12*Math.max(0,Math.log2(s/i.top));let c=10**((r+3*w(a))/20),l=10**((r+3*w(a))/20);o.push({f:s/t,q:(20+25*a())/n,gL:c*(a()<.5?-1:1),gR:l*(a()<.5?-1:1)}),s*=1+.07*(.5+a())}return o}function k(e,t){let n=0,r=0,i=0,a=0;for(let o of e){let e=t/o.f,s=1-e*e,c=e/o.q,l=s*s+c*c,u=c*c/l,d=c*s/l;n+=o.gL*u,r+=o.gL*d,i+=o.gR*u,a+=o.gR*d}return .5*(n*n+r*r+i*i+a*a)}var A=class{n=0;b0=/* @__PURE__ */ new Float64Array;a1=/* @__PURE__ */ new Float64Array;a2=/* @__PURE__ */ new Float64Array;gL=/* @__PURE__ */ new Float64Array;gR=/* @__PURE__ */ new Float64Array;x1=0;x2=0;y1=/* @__PURE__ */ new Float64Array;y2=/* @__PURE__ */ new Float64Array;key=``;configure(e,t,n,r){let i=`${e}|${t}|${n}|${r}`;if(i===this.key)return;this.key=i;let a=O(e,t,n).filter(e=>e.f<.45*r),o=0,s=0;if(a.length){let e=.8*a[0].f,t=Math.min(1e4,.45*r);for(let n=0;n<=200;n++)o+=k(a,e*(t/e)**(n/200)),s++}let c=s?1/Math.sqrt(o/s):0,l=a.length,u=this.n!==l;if(this.n=l,u)for(let e of[`b0`,`a1`,`a2`,`gL`,`gR`,`y1`,`y2`])this[e]=new Float64Array(l);a.forEach((e,t)=>{let n=2*Math.PI*e.f/r,i=Math.sin(n)/(2*e.q),a=1+i;this.b0[t]=i/a,this.a1[t]=-2*Math.cos(n)/a,this.a2[t]=(1-i)/a,this.gL[t]=e.gL*c,this.gR[t]=e.gR*c})}reset(){this.x1=this.x2=0,this.y1.fill(0),this.y2.fill(0)}tick(e,t){let n=this.n,r=this.b0,i=this.a1,a=this.a2,o=this.y1,s=this.y2,c=this.gL,l=this.gR,u=e-this.x2;this.x2=this.x1,this.x1=e;let d=0,f=0;for(let e=0;e<n;e++){let t=r[e]*u-i[e]*o[e]-a[e]*s[e];s[e]=o[e],o[e]=t,d+=c[e]*t,f+=l[e]*t}t[0]=d,t[1]=f}};const j=.5,M=1e-14,N=.002,P=.05,F=e=>{let t=Math.abs(e);return t+Math.log1p(Math.exp(-2*t))-Math.LN2},I=6.907755,L=10**-9,R=.1;var z=class{idx;active=!1;note=60;baseHz=261.6;vel=1;gate=!1;held=!1;sustained=!1;touching=!1;damped=!0;order=0;N=0;nAct=0;nTune=0;cull=1/0;nNL=0;nNLTune=0;q=/* @__PURE__ */ new Float64Array;qp=/* @__PURE__ */ new Float64Array;qn=/* @__PURE__ */ new Float64Array;A=/* @__PURE__ */ new Float64Array;B=/* @__PURE__ */ new Float64Array;C=/* @__PURE__ */ new Float64Array;om=/* @__PURE__ */ new Float64Array;sw=/* @__PURE__ */ new Float64Array;sw2=/* @__PURE__ */ new Float64Array;grad=/* @__PURE__ */ new Float64Array;pv=/* @__PURE__ */ new Float64Array;gp=/* @__PURE__ */ new Float64Array;phiE=/* @__PURE__ */ new Float64Array;phiB=/* @__PURE__ */ new Float64Array;wL=/* @__PURE__ */ new Float64Array;wR=/* @__PURE__ */ new Float64Array;wsum=0;omega1=1;Z0=1;tunedPitch=-1;tunedDamp=-1;tunedGate=!1;glideMul=1;tunedGlide=1;vibMul=1;tunedVib=1;vibPh=0;vibAge=0;vibRateJ=1;dirtyTune=!0;dirtyVec=!0;posX=-1;posY=-1;ham=!1;hz=0;hzp=0;hzn=0;hamISM=1;hamK=0;hamA=2.5;hamTimer=0;gz=0;buzzK=0;buzzGap=0;buzzPhi1=1;beta=.11;env=0;fLaw=0;nz=0;f=0;fb=/* @__PURE__ */ new Float32Array(32768);fbW=0;bx1=0;bx2=0;by1=0;by2=0;S=0;X=0;Vv=0;useG=!1;fast=!1;tc=0;tq=0;pred=!1;energy=0;outMono=0;constructor(e){this.idx=e}alloc(e){let t=t=>{let n=new Float64Array(e);return n.set(t.subarray(0,Math.min(e,t.length))),n};this.q=t(this.q),this.qp=t(this.qp),this.qn=new Float64Array(e);for(let t of[`A`,`B`,`C`,`om`,`sw`,`sw2`,`grad`,`pv`,`gp`,`phiE`,`phiB`,`wL`,`wR`])this[t]=new Float64Array(e);this.N=e,this.dirtyTune=this.dirtyVec=!0}reset(){this.q.fill(0),this.qp.fill(0),this.qn.fill(0),this.ham=!1,this.env=0,this.fLaw=0,this.fb.fill(0),this.bx1=this.bx2=this.by1=this.by2=0,this.energy=0,this.uncull()}uncull(){this.cull=1/0,this.nAct=this.nTune,this.nNL=this.nNLTune}};const B=e=>440*2**((e-69)/12),V=e=>e<0?0:e>1?1:e,H=e=>e-Math.floor(e);var U=class{sr;h;p={...x};model;voices=[];act=[];eps=M;vMax=0;vHold=0;psi=Math.sqrt(M);psiReset=!1;order=0;bend=0;sustain=!1;lastNote=60;focus=null;touchVoice=null;pending=[];post=()=>{};paramVersion=0;rngS=0x9e3779b9;lfoPh=[0,0];lfoA=[0,0];lfoB=[0,0];kt=0;kc=0;cc=0;ct=0;cl=0;crossOn=!1;buzzA=1.5;buzzTwo=!1;ampMul=1;fbMul=1;excMul=1;pitchMul=1;dampMul=1;posOff=0;pickOff=0;vecVersion=-1;lastPosOff=0;lastPickOff=0;law=0;lwF=0;lwVb=0;lwGam=0;lwD=0;lawK=/* @__PURE__ */ new Float64Array(3);envAtt=0;envRel=0;noiseC=0;noiseNorm=1;fbD=1;fb0=0;fb2=0;fa1=0;fa2=0;snapCount=0;cpuMs=0;cpuWall=0;cpu=0;lastTouch=null;box=new A;boxOut=/* @__PURE__ */ new Float64Array(2);constructor(e){this.sr=e,this.h=1/e,this.model=E(this.p);for(let e=0;e<16;e++){let t=new z(e);t.alloc(this.model.N),this.voices.push(t)}}message(e){e.type===`params`?this.setParams(e.params):this.pending.push(e)}setParams(e){if(this.p={...x,...e},this.paramVersion++,T(this.p)!==this.model.key){this.model=E(this.p);for(let e of this.voices)e.alloc(this.model.N);this.psiReset=!0}for(let e of this.voices)e.dirtyTune=e.dirtyVec=!0;let t=f(this.p,`soundbox`);t===`off`?(this.box.configure(``,1,1,this.sr),this.box.reset()):this.box.configure(t,d(this.p,`boxSize`),d(this.p,`boxDamp`),this.sr)}handle(e){switch(e.type){case`noteOn`:this.noteOn(e.note,e.vel,e.x,e.y);break;case`noteOff`:this.noteOff(e.note);break;case`sustain`:if(this.sustain=e.on,!e.on)for(let e of this.voices)e.sustained&&(e.sustained=!1,this.updateGate(e));break;case`bend`:this.bend=e.value;break;case`touchStart`:this.touchStart(e.x,e.y,e.vel);break;case`touchMove`:this.lastTouch={x:e.x,y:e.y},this.touchVoice&&(this.touchVoice.posX=e.x,this.touchVoice.posY=e.y,this.touchVoice.dirtyVec=!0);break;case`touchEnd`:this.lastTouch=null,this.touchVoice&&=(this.touchVoice.touching=!1,this.updateGate(this.touchVoice),null);break;case`panic`:for(let e of this.voices)e.reset(),e.active=!1;this.box.reset(),this.psi=Math.sqrt(this.eps)}}allocVoice(e){let t=this.voices.find(t=>t.active&&t.note===e);if(t)return t;let n=Math.round(d(this.p,`voices`)),r=this.voices.filter(e=>e.active);return r.length>=n?(r.sort((e,t)=>Number(e.gate)-Number(t.gate)||e.energy-t.energy||e.order-t.order),t=r[0]):t=this.voices.find(e=>!e.active),t.reset(),t.active=!0,t.glideMul=1,t.vibMul=1,t.vibPh=this.rand(),t.vibRateJ=1+.1*(this.rand()*2-1),t.note=e,t.baseHz=B(e),t.held=t.sustained=t.touching=!1,t.gate=!1,t.dirtyTune=t.dirtyVec=!0,t.tunedPitch=-1,this.psiReset=!0,t}updateGate(e){let t=e.held||e.sustained||e.touching;t!==e.gate&&(e.gate=t,e.dirtyTune=!0)}noteOn(e,t,n,r){let i=this.allocVoice(e);i.uncull(),i.order=++this.order,i.vel=Math.max(.01,Math.min(1,t)),i.held=!0,i.damped=!0,i.vibAge=0,i.posX=n??-1,i.posY=r??-1,i.dirtyVec=!0,this.updateGate(i),this.lastNote=e,this.focus=i,this.prepare(i),this.excite(i,i.vel)}noteOff(e){for(let t of this.voices)t.active&&t.note===e&&t.held&&(t.held=!1,this.sustain&&(t.sustained=!0),this.updateGate(t))}touchStart(e,t,n){this.lastTouch={x:e,y:t};let r=this.focus&&this.focus.active?this.focus:null;r||(r=this.allocVoice(this.lastNote),r.order=++this.order,r.damped=!1,this.focus=r),r.posX=e,r.posY=t,r.vel=n,r.dirtyVec=!0;let i=this.law!==0;i&&(r.touching=!0,this.touchVoice=r,this.updateGate(r)),this.prepare(r),i||this.excite(r,n)}prepare(e){e.dirtyVec&&this.vecVoice(e),(e.dirtyTune||e.tunedPitch!==this.pitchMul||e.tunedDamp!==this.dampMul||e.tunedGate!==e.gate||e.tunedGlide!==e.glideMul||e.tunedVib!==e.vibMul)&&this.tuneVoice(e)}excite(e,t){e.uncull();let n=f(this.p,`exciter`),r=j*(d(this.p,`strength`)*t)**2;if(r<=0)return;let i=e.nAct,a=e.phiE,o=e.om,s=this.h;if(n===`strike`){let t=d(this.p,`hammerMass`),n=d(this.p,`hardness`)/1e3,o=d(this.p,`feltExp`),c=Math.sqrt(2*r/t),l=Math.sqrt(2*j/t)*n/Math.PI,u=0,f=0;for(let t=0;t<i;t++)u+=a[t]*e.q[t],f+=a[t]*(e.q[t]-e.qp[t])/s;let p=Math.sqrt(t);e.ham=!0,e.hamTimer=0,e.hamISM=1/p,e.hamK=t*(Math.PI/n)**2/l**(o-1),e.hamA=o,e.hz=u*p,e.hzp=(u-(f+c)*s)*p}else if(n===`pluck`){let t=0;for(let e=0;e<i;e++)t+=a[e]*a[e]/(o[e]*o[e]);if(t<=0)return;let n=Math.sqrt(2*r/t);for(let t=0;t<i;t++){let r=n*a[t]/(o[t]*o[t]);e.q[t]+=r,e.qp[t]+=r}this.psiReset=!0}else if(n===`impulse`){let t=d(this.p,`hardness`)/1e3,n=0,c=e.qn;for(let e=0;e<i;e++){let r=o[e]*t/2,i=1-(r/Math.PI)**2,s=r<1e-9?1:Math.abs(i)<1e-6?.5:Math.abs(Math.sin(r)/r/i);c[e]=a[e]*s,n+=c[e]*c[e]}if(n<=0)return;let l=Math.sqrt(2*r/n);for(let t=0;t<i;t++)e.qp[t]-=s*l*c[t];c.fill(0)}}tuneVoice(e){let t=this.model,n=t.N,r=this.h,i=this.p,a=e.baseHz*this.pitchMul*e.glideMul*e.vibMul,o=I/d(i,`t60`),s=d(i,`hfDamp`),c=d(i,`damper`),l=!e.gate&&e.damped&&c<19.9?I/c:0,u=.45*this.sr,f=0,p=0;for(let i=0;i<n;i++){let n=a*t.ratios[i],c=2*Math.PI*n;if(e.om[i]=c,n>=u){e.A[i]=e.B[i]=e.C[i]=e.sw[i]=e.sw2[i]=0;continue}f=i+1;let d=(o+s*(n/1e3)**2)*this.dampMul+l,m=Math.exp(-d*r);if(d<c)e.A[i]=2*m*Math.cos(Math.sqrt(c*c-d*d)*r);else{let t=Math.sqrt(d*d-c*c)*r;e.A[i]=m*(Math.exp(t)+Math.exp(-t))}e.B[i]=m*m,e.C[i]=r*r/(1+Math.tanh(d*r));let h=2-2*Math.cos(c*r),g=Math.max(0,Math.min(1,(3.6/h-1)/12));e.sw[i]=c*Math.sqrt(g),e.sw2[i]=c*c*g,g>0&&(p=i+1)}for(let t=f;t<n;t++)e.q[t]=e.qp[t]=0;e.nTune=f,e.nNLTune=Math.min(p,f),e.nAct=Math.min(f,e.cull),e.nNL=Math.min(e.nNLTune,e.nAct),e.omega1=2*Math.PI*a,e.Z0=2*a;let m=0;for(let t=0;t<f;t++)m+=e.phiE[t]*e.phiE[t]*e.C[t];e.wsum=m;let h=+Math.max(e.buzzPhi1,.05)/e.omega1,g=d(i,`buzz`);e.buzzGap=d(i,`buzzGap`)*h,e.buzzK=g>0?g*(2*Math.PI*4e3)**2*.1*h**(1-this.buzzA):0,e.tunedPitch=this.pitchMul,e.tunedDamp=this.dampMul,e.tunedGate=e.gate,e.tunedGlide=e.glideMul,e.tunedVib=e.vibMul,e.dirtyTune=!1}vecVoice(e){let t=this.model,n=t.N,r=this.p,i=e.posX>=0?e.posX:V(d(r,`exPos`)+this.posOff),a=e.posY>=0?e.posY:V(d(r,`exPosY`)+this.posOff),o=d(r,`exWidth`)*.15,s=d(r,`buzzPos`),c=d(r,`buzzPosY`),l=H(d(r,`pickup`)+this.pickOff),u=d(r,`pickupY`),f=d(r,`width`),p=H(l+.5*f),m=H(u+.37*f),h=d(r,`spread`),g=d(r,`tilt`)/6.0206;for(let r=0;r<n;r++){let d=Math.exp(-.5*(Math.PI*t.wavenum[r]*o)**2);e.phiE[r]=t.shape(r,i,a)*d,e.phiB[r]=t.shape(r,s,c);let f=t.ratios[r]**+g;e.wL[r]=((1-h)*t.shape(r,l,u)+h*t.rad[r])*f,e.wR[r]=((1-h)*t.shape(r,p,m)+h*t.rad[(r+1)%n]*(r%2?1:-1))*f}e.buzzPhi1=Math.abs(t.shape(t.pitchK,s,c)),e.beta=Math.max(.02,Math.min(i,1-i)),e.dirtyVec=!1,e.dirtyTune=!0}rand(){let e=this.rngS;return e^=e<<13,e^=e>>>17,e^=e<<5,this.rngS=e>>>0,this.rngS/4294967296}lfo(e,t){let n=this.p,r=d(n,`lfo${e+1}Rate`),i=this.lfoPh[e]+r*t;switch(i>=1&&(i-=Math.floor(i),this.lfoA[e]=this.lfoB[e],this.lfoB[e]=this.rand()*2-1),this.lfoPh[e]=i,f(n,`lfo${e+1}Shape`)){case`tri`:return 1-4*Math.abs(i-.5);case`saw`:return 2*i-1;case`square`:return i<.5?1:-1;case`sh`:return this.lfoB[e];case`smooth`:return this.lfoA[e]+(this.lfoB[e]-this.lfoA[e])*(.5-.5*Math.cos(Math.PI*i));default:return Math.sin(2*Math.PI*i)}}blockUpdate(e){let t=this.p,n=this.sr,r=e/n,i=this.bend*d(t,`bendRange`),a=1,o=0,s=0,c=d(t,`tension`),l=d(t,`cascade`),u=1,p=1,m=1;for(let e=0;e<2;e++){let n=f(t,`lfo${e+1}Target`);if(n===`off`)continue;let h=d(t,`lfo${e+1}Depth`),g=this.lfo(e,r)*h;switch(n){case`pitch`:i+=4*g;break;case`amp`:a*=Math.max(0,1+g);break;case`position`:o+=.5*g;break;case`pickup`:s+=.5*g;break;case`tension`:c*=Math.max(0,1+g);break;case`cascade`:l*=Math.max(0,1+g);break;case`damping`:u*=2**(3*g);break;case`feedback`:p*=Math.max(0,1+g);break;case`exciter`:m*=Math.max(0,1+g)}}this.pitchMul=2**(i/12),this.dampMul=u,this.ampMul=a,this.fbMul=p,this.excMul=m,this.kt=c,this.kc=this.model.M>0?l:0,this.cc=+d(t,`curvature`),this.ct=d(t,`crossTension`),this.cl=d(t,`crossLink`),this.crossOn=this.ct>0||this.cl>0,this.buzzTwo=f(t,`buzzSides`)===`two`;let h=f(t,`exciter`);this.law=h===`bow`?1:h===`reed`?2:h===`selfosc`?3:h===`noise`?4:0;let g=this.lawK;this.law===1?(g[0]=d(t,`bowSpeed`)*.5,g[1]=+d(t,`bowForce`),g[2]=d(t,`bowNoise`)):this.law===2?(g[0]=d(t,`reedGain`)*2,g[1]=d(t,`reedPressure`),g[2]=d(t,`breath`)):this.law===3&&(g[0]=+d(t,`selfGain`),g[1]=d(t,`selfSat`)),this.envAtt=1-Math.exp(-1/(d(t,`attack`)/1e3*n)),this.envRel=1-Math.exp(-1/(d(t,`release`)/1e3*n));let _=Math.min(d(t,`noiseColor`),.45*n);this.noiseC=1-Math.exp(-2*Math.PI*_/n),this.noiseNorm=Math.sqrt(3*(2-this.noiseC)/this.noiseC),this.fbD=Math.max(1,Math.min(32767,Math.round(d(t,`fbDelay`)/1e3*n)));let v=2*Math.PI*Math.min(d(t,`fbFreq`),.45*n)/n,y=Math.sin(v)/(2*d(t,`fbQ`)),b=1+y;this.fb0=y/b,this.fb2=-y/b,this.fa1=-2*Math.cos(v)/b,this.fa2=(1-y)/b;let x=o!==this.lastPosOff||s!==this.lastPickOff||this.vecVersion!==this.paramVersion;this.posOff=o,this.pickOff=s,this.lastPosOff=o,this.lastPickOff=s,this.vecVersion=this.paramVersion;let S=d(t,`vibDepth`),C=d(t,`vibRate`),w=d(t,`vibDelay`)/1e3;this.act.length=0;for(let e of this.voices)if(e.active){if(S>0){e.vibAge+=r;let t=e.vibAge,n=w>0?(t-.3*w)/(.7*w):1;n=n<0?0:n>1?1:n*n*(3-2*n),e.vibPh+=C*e.vibRateJ*(1+.06*Math.sin(2.3*t+7*e.vibRateJ))*r,e.vibPh-=Math.floor(e.vibPh);let i=2**(S*n*Math.sin(2*Math.PI*e.vibPh)/1200);(Math.abs(i/e.vibMul-1)>1e-5||n===0&&e.vibMul!==1)&&(e.vibMul=i)}else e.vibMul=1;x&&(e.dirtyVec=!0),this.prepare(e),this.act.push(e)}}nl(e){if(this.kt<=0&&this.ct<=0&&this.kc<=0&&!this.crossOn&&!e.ham&&e.buzzK<=0){e.S=e.X=e.Vv=e.gz=0,e.useG=!1;return}let t=e.nAct,n=e.q,r=e.sw,i=e.grad,a=this.model,o=0,s=!1,c=e.nNL,l=0;if(this.kt>0||this.ct>0||this.kc>0)for(let e=0;e<c;e++){let t=r[e]*n[e];l+=t*t}if(e.S=l,i.fill(0,0,t),e.gz=0,this.kt>0&&l>0){let e=3/this.kt,t=l/j;o+=this.kt*j*.5*e*e*F(t/e);let a=this.kt*e*Math.tanh(t/e);for(let e=0;e<c;e++)i[e]+=a*r[e]*r[e]*n[e];s=!0}let u=this.kc;if(u>0){let t=a.Nnl,l=Math.min(c,t),d=e.pv,f=e.gp,p=this.cc,m=3/(u*a.M);for(let e=0;e<t;e++)d[e]=e<l?r[e]*n[e]:0,f[e]=0;let h=a.ti,g=a.tj,_=a.tv,v=a.tb;for(let e=0;e<a.M;e++){let n=a.tStart[e],r=a.tStart[e+1],i=0;for(let e=n;e<r;e++)i+=_[e]*d[h[e]]*d[g[e]];let s=0,c=e*t;if(p!==0)for(let e=0;e<l;e++)s+=v[c+e]*d[e];let y=(i+p*s)/j;o+=u*j*m*m*F(y/m);let b=u*m*Math.tanh(y/m),x=2*b;for(let e=n;e<r;e++)f[h[e]]+=x*_[e]*d[g[e]];let S=b*p;if(S!==0)for(let e=0;e<l;e++)f[e]+=S*v[c+e]}for(let e=0;e<l;e++)i[e]+=r[e]*f[e];s=!0}if(e.ham){let r=e.phiE,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=e.hz*e.hamISM-a;if(c>0){let n=e.hamA,a=e.hamK*c**+n;o+=a*c/(n+1);for(let e=0;e<t;e++)i[e]-=a*r[e];e.gz=a*e.hamISM,e.hamTimer=0,s=!0}else++e.hamTimer>.05*this.sr&&(e.ham=!1)}if(e.buzzK>0){let r=e.phiB,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=this.buzzA,l=0,u=a-e.buzzGap;if(u>0){let t=e.buzzK*u**+c;o+=t*u/(c+1),l+=t}if(this.buzzTwo){let t=-a-e.buzzGap;if(t>0){let n=e.buzzK*t**+c;o+=n*t/(c+1),l-=n}}if(l!==0){for(let e=0;e<t;e++)i[e]+=l*r[e];s=!0}}if(this.crossOn){let t=0,r=Math.min(c,a.Nnl),i=a.bx;if(this.cl>0)for(let a=0;a<r;a++)t+=i[a]*e.sw[a]*n[a];e.X=.5*this.ct*l+this.cl*1*t}else e.X=0;e.Vv=o,e.useG=s||this.crossOn}nlTension(e){let t=e.nNL,n=e.q,r=e.qp,i=e.sw2,a=0,o=0;for(let e=0;e<t;e++){let t=i[e]*n[e];a+=t*n[e],o+=t*r[e]}if(e.S=a,e.X=0,e.gz=0,e.fast=!0,a>0){let t=3/this.kt,n=a/j;e.Vv=this.kt*j*.5*t*t*F(n/t),e.tc=this.kt*t*Math.tanh(n/t),e.tq=e.tc===0?0:o,e.useG=!0}else e.Vv=0,e.tc=0,e.tq=0,e.useG=!1}lawEval(e){let t=0,n=0;if(this.law===1){let r=e-this.lwVb,i=Math.tanh(r/N),a=1+Math.abs(r)/P,o=.35+.65/a,s=-.65/(P*a*a)*(r>=0?1:-1);t=-this.lwF*i*o,n=-this.lwF*((1-i*i)/N*o+i*s)}else if(this.law===2){let r=this.lwGam-e;if(r<1){let e=Math.sqrt(Math.abs(r)+1e-9),i=this.lwF;r>=0?(t=i*(1-r)*e,n=-i*(-e+(1-r)/(2*e))):(t=-i*(1-r)*e,n=-i*(e+(1-r)/(2*e)))}}else{let r=this.lwF,i=this.lwVb;t=r*(e-e*e*e/(3*i*i)),n=r*(1-e*e/(i*i))}return this.lwD=n,t}solveLaw(e,t,n){let r=e.nAct,i=e.phiE,a=e.A,o=e.B,s=e.q,c=e.qp,l=e.qn,u=0;for(let e=0;e<r;e++){let t=a[e]*s[e]-o[e]*c[e];l[e]=t,u+=i[e]*(t-c[e])}e.pred=!0;let d=.5/this.h,f=(u+t*e.wsum)*d,p=e.wsum*d,m=e.env*this.excMul,h=e.Z0,g=this.lawK;if(this.law===1){this.lwVb=g[0]*m;let t=g[2];this.lwF=g[1]*h*(this.lwVb/.05)*(.11/e.beta)*(t>0?Math.max(0,1+t*n):1)}else this.law===2?(this.lwF=g[0]*h,this.lwGam=g[1]*m*(1+g[2]*n)):(this.lwF=g[0]*h*m,this.lwVb=g[1]);let _=this.lwF+1e-9,v=1e-9*_,y=e.fLaw,b=!1;for(let e=0;e<8;e++){let e=y-this.lawEval(f+p*y);if(Math.abs(e)<v){b=!0;break}let t=1-p*this.lwD;if(t<.05)break;y-=e/t}if(!b||!Number.isFinite(y)){let t=Number.isFinite(e.fLaw)?e.fLaw:0,n=.01*_,r=t,i=t,a=0,o=0;for(let e=0;e<60&&(r=t-n,i=t+n,a=r-this.lawEval(f+p*r),o=i-this.lawEval(f+p*i),!(a<=0&&o>=0));e++)n*=2;for(let e=0;e<50;e++){let e=.5*(r+i);e-this.lawEval(f+p*e)<0?r=e:i=e}y=.5*(r+i),Number.isFinite(y)||(y=0)}return e.fLaw=y,y}process(e,t,n,r=0){let i=Date.now(),a=n/this.sr;if(this.pending.length){let e=[];for(let t of this.pending)(`time`in t&&t.time!==void 0?t.time:0)<=r+a?this.handle(t):e.push(t);this.pending=e}this.blockUpdate(n);let o=this.act,s=this.h,c=s*s,l=1/s,u=this.p,f=d(u,`fbGain`)*this.fbMul,p=d(u,`fbSat`),m=d(u,`noiseLevel`),h=this.law,g=h===4||h===3||h===2&&d(u,`breath`)>0||h===1&&d(u,`bowNoise`)>0,_=this.box,v=_.n>0,y=v?d(u,`boxMix`):0,b=1-y,x=this.boxOut,S=.25*this.ampMul*l*10**(d(u,`level`)/20),C=32767,w=this.kt>0&&this.kt<=R&&this.kc<=0&&!this.crossOn;for(let r=0;r<n;r++){let n=0,i=0,a=!1;for(let e=0;e<o.length;e++){let t=o[e];t.env+=((t.gate?t.vel:0)-t.env)*(t.gate?this.envAtt:this.envRel);let r=0;if(t.env>1e-6){let e=0;if(g&&(t.nz+=this.noiseC*(this.rand()*2-1-t.nz),e=t.nz*this.noiseNorm),f>0){let e=t.fb[t.fbW-this.fbD&C],n=this.fb0*e+this.fb2*t.bx2-this.fa1*t.by1-this.fa2*t.by2;t.bx2=t.bx1,t.bx1=e,t.by2=t.by1,t.by1=n,r+=p*t.Z0*Math.tanh(f*n/p)*t.env}h===3&&(r+=.001*t.Z0*t.env*e),h===4?r+=m*t.Z0*t.env*this.excMul*e*.5:h!==0&&(r+=this.solveLaw(t,r,e))}else t.fLaw=0;t.f=r,w&&!t.ham&&t.buzzK<=0?this.nlTension(t):(t.fast=!1,this.nl(t)),n+=t.Vv,i+=t.X,t.useG&&(a=!0)}if(this.crossOn&&o.length){let e=i/j;n+=j*3*3*F(e/3);let t=3*Math.tanh(e/3),r=this.ct,a=+this.cl,s=this.model.bx,c=this.model.Nnl;for(let e of o){let n=e.nNL,i=e.grad,o=e.q,l=e.sw;for(let e=0;e<n;e++)i[e]+=t*(r*l[e]*l[e]*o[e]+(e<c?a*s[e]*l[e]:0))}}let s=0;if(!a)this.psi=Math.sqrt(this.eps);else{n>this.vMax&&(this.vMax=n),this.psiReset&&(this.eps=.01);let e=Math.sqrt(2*n+this.eps),t=1/e;if(this.psiReset)this.psi=e,this.psiReset=!1;else{let t=this.psi+.01*(e-this.psi);Math.abs(t)<Math.abs(this.psi)&&(this.psi=t)}let r=0;for(let e of o){if(!e.useG)continue;if(e.fast){r+=e.tc*e.tq;continue}let t=e.nAct,n=e.grad,i=e.qp;for(let e=0;e<t;e++)r+=n[e]*i[e];e.ham&&(r+=e.gz*e.hzp)}r*=t;let i=this.psi,a=r/4-i,l=0,u=0;for(let e of o){if(!e.useG)continue;e.pred=!1;let n=e.nAct,r=e.q,i=e.qp,o=e.qn,s=e.A,d=e.B,f=e.C,p=e.phiE,m=e.f;if(e.fast){let c=e.nNL,h=e.sw2,g=e.tc*t;for(let e=0;e<c;e++){let t=g*h[e]*r[e],n=f[e],c=s[e]*r[e]-d[e]*i[e]+n*(p[e]*m+t*a);o[e]=c,l+=t*c,u+=n*t*t}for(let e=c;e<n;e++)o[e]=s[e]*r[e]-d[e]*i[e]+f[e]*p[e]*m;continue}let h=e.grad;for(let e=0;e<n;e++){let n=h[e]*t,c=s[e]*r[e]-d[e]*i[e]+f[e]*(p[e]*m+n*a);o[e]=c,l+=n*c,u+=f[e]*n*n}if(e.ham){let n=e.gz*t,r=2*e.hz-e.hzp+c*n*a;e.hzn=r,l+=n*r,u+=c*n*n}}let d=l/(1+u/4);s=d*t/4;for(let e of o){if(!e.useG||e.fast)continue;let t=e.nAct,n=e.grad,r=e.qn,i=e.C;for(let e=0;e<t;e++)r[e]-=i[e]*n[e]*s;e.ham&&(e.hzn-=c*e.gz*s)}this.psi=i+(d-r)/2}let u=0,d=0;for(let e of o){let t=e.nAct,n=e.q,r=e.qp,i=e.qn,a=e.wL,o=e.wR,c=0,f=0;if(!e.useG){let s=e.A,l=e.B,u=e.C,d=e.phiE,p=e.f;if(e.pred){e.pred=!1;for(let e=0;e<t;e++){let t=i[e]+u[e]*d[e]*p;i[e]=t;let r=t-n[e];c+=a[e]*r,f+=o[e]*r}}else if(p!==0)for(let e=0;e<t;e++){let t=s[e]*n[e]-l[e]*r[e]+u[e]*d[e]*p;i[e]=t;let m=t-n[e];c+=a[e]*m,f+=o[e]*m}else for(let e=0;e<t;e++){let t=s[e]*n[e]-l[e]*r[e];i[e]=t;let u=t-n[e];c+=a[e]*u,f+=o[e]*u}e.ham&&(e.hzn=2*e.hz-e.hzp)}else if(e.fast){let r=e.nNL,l=e.sw2,u=e.C,d=e.tc*s;for(let e=0;e<r;e++){let t=i[e]-u[e]*l[e]*n[e]*d;i[e]=t;let r=t-n[e];c+=a[e]*r,f+=o[e]*r}for(let e=r;e<t;e++){let t=i[e]-n[e];c+=a[e]*t,f+=o[e]*t}}else for(let e=0;e<t;e++){let t=i[e]-n[e];c+=a[e]*t,f+=o[e]*t}u+=c,d+=f,e.fb[e.fbW]=.5*(c+f)*l,e.fbW=e.fbW+1&C;let p=e.qp;e.qp=e.q,e.q=e.qn,e.qn=p,e.ham&&(e.hzp=e.hz,e.hz=e.hzn)}v?(_.tick(.5*(u+d)*S,x),e[r]=b*u*S+y*x[0],t[r]=b*d*S+y*x[1]):(e[r]=u*S,t[r]=d*S)}this.blockEnd(n),this.cpuMs+=Date.now()-i,this.cpuWall+=a*1e3}blockEnd(e){let t=1/this.h,n=this.kc<=0&&this.kt<=R&&!this.crossOn&&!(d(this.p,`fbGain`)>0);for(let e of this.act){let r=e.nAct,i=e.q,a=e.qp,o=e.om,s=0,c=0;for(let e=0;e<r;e++){let n=(i[e]-a[e])*t,r=.5*(n*n+o[e]*o[e]*i[e]*i[e]);s+=r,r>c&&(c=r)}if(n&&!e.ham&&e.buzzK<=0&&(this.law===0||e.env<=1e-6)){let n=c*L,s=r;for(;s>1;){let e=s-1,r=(i[e]-a[e])*t;if(.5*(r*r+o[e]*o[e]*i[e]*i[e])>n)break;s--}if(s<r){for(let e=s;e<r;e++)i[e]=a[e]=0;e.cull=s,e.nAct=s,e.nNL=Math.min(e.nNLTune,s)}}else e.cull!==1/0&&e.uncull();if(!Number.isFinite(s)||s>1e8){e.reset(),e.active=!1,this.psiReset=!0;continue}e.energy=s;let l=d(this.p,`glide`),u=1;if(l!==0){let e=4*s/j;u=2**(l*e/(1+e)/12)}(Math.abs(u/e.glideMul-1)>2e-5||u===1&&e.glideMul!==1)&&(e.glideMul=u),!e.gate&&!e.ham&&s<1e-10&&e.env<1e-4&&(e.active=!1)}let r=0;for(let e of this.act)e.active&&(r+=e.energy);this.vHold=Math.max(this.vMax,this.vHold*.95),this.vMax=0;let i=Math.max(M,.02*r+2*this.vHold);if(i<this.eps){let e=Math.max(i,this.eps*.95),t=this.psi*this.psi-(this.eps-e);this.psi=(this.psi<0?-1:1)*Math.sqrt(Math.max(0,t)),this.eps=e}this.snapCount+=e,this.snapCount>=this.sr/30&&(this.snapCount=0,this.cpuWall>0&&(this.cpu=this.cpuMs/this.cpuWall),this.cpuMs=this.cpuWall=0,this.snapshot())}snapshot(){let e=this.focus&&this.focus.active?this.focus:null;if(!e)for(let t of this.voices)t.active&&(!e||t.order>e.order)&&(e=t);let t=this.model.N,n=new Float32Array(t),r=new Float32Array(t),i=new Float32Array(t),a=new Float32Array(t);if(e){let o=1/this.h;for(let s=0;s<t;s++){n[s]=e.q[s];let t=(e.q[s]-e.qp[s])*o;r[s]=t,i[s]=.5*(t*t+e.om[s]*e.om[s]*e.q[s]*e.q[s]),a[s]=e.om[s]/(2*Math.PI)}}let o=[];for(let e of this.voices)e.active&&o.push(e.note);let s={type:`snap`,cpu:this.cpu,nVoices:o.length,notes:o,focusNote:e?e.note:-1,focusHz:e?e.baseHz*this.pitchMul:0,nAct:e?e.nAct:0,q:n,qd:r,energy:i,freqs:a,touch:this.lastTouch};this.post(s,[n.buffer,r.buffer,i.buffer,a.buffer])}},W=class extends AudioWorkletProcessor{synth=new U(sampleRate);constructor(){super(),this.port.onmessage=e=>this.synth.message(e.data),this.synth.post=(e,t)=>this.port.postMessage(e,t)}process(e,t){let n=t[0],r=n[0],i=n[1]??n[0];return this.synth.process(r,i,r.length,currentTime),!0}};registerProcessor(`modal-synth`,W);
\ No newline at end of file
site/index.htmlmodified+2−2View file
@@ -5,8 +5,8 @@
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-DA4h_SiO.js"></script>
9- <link rel="stylesheet" crossorigin href="./assets/index-C8mMpV0u.css">
8+ <script type="module" crossorigin src="./assets/index-D9r0IF3O.js"></script>
9+ <link rel="stylesheet" crossorigin href="./assets/index-BFl0mzg8.css">
1010 </head>
1111 <body>
1212 <div id="app"></div>
src/compositions/c01-poincare/defaults.jsonmodified+0−1View file
@@ -30,7 +30,6 @@
3030 "loudFloor": 0.08,
3131 "notesLevel": -6,
3232 "noteLength": 1.5,
33- "panAmount": 0.6,
3433 "humInstrument": "modal: Clarinet-ish",
3534 "humCustom": "",
3635 "humPitch": 38,
src/compositions/c01-poincare/index.tsmodified+7−3View file
@@ -1,12 +1,16 @@
11 import type { Composition } from "../../core/composition.ts";
2+import { createStreamPiece, type StreamDef } from "../../stream/piece.ts";
23 import defaults from "./defaults.json";
3-import { createPoincarePiece } from "./piece.ts";
4+import { estimateLength, layout } from "./layout.ts";
45 import { schema } from "./schema.ts";
6+import { poincareView } from "./view.ts";
7+
8+const def: StreamDef = { id: "01-poincare", schema, layout, estimateLength, view: poincareView };
59
610 export const poincare: Composition = {
7- id: "01-poincare",
11+ id: def.id,
812 title: "poincaré",
913 schema,
1014 defaults,
11- create: createPoincarePiece,
15+ create: (view, params) => createStreamPiece(def, view, params),
1216 };
src/compositions/c01-poincare/layout.tsadded+25−0View file
@@ -0,0 +1,25 @@
1+import type { Params } from "../../core/params.ts";
2+import { soundOf } from "../../instruments/sounds.ts";
3+import type { Layout } from "../../stream/layout.ts";
4+
5+/** Stems: 0 the crossing notes, 1 the hum. */
6+export const NOTES = 0, HUM = 1;
7+
8+export function layout(P: Params): Layout {
9+ const notes = soundOf(P.noteInstrument as string, P.modalCustom as string);
10+ const hum = soundOf(P.humInstrument as string, P.humCustom as string, { voices: 1 });
11+ return {
12+ stems: [
13+ { kind: "synth", sound: notes, output: NOTES },
14+ { kind: "synth", sound: hum, output: HUM },
15+ ],
16+ outputs: [
17+ { effects: "own", sound: notes, level: (Q) => Q.notesLevel as number },
18+ { effects: "own", sound: hum, level: (Q) => Q.humLevel as number },
19+ ],
20+ };
21+}
22+
23+export function estimateLength(P: Params): number {
24+ return (P.duration as number) + 0.5 + (P.finalHold as number) + (P.finalFade as number) + 0.3;
25+}
src/compositions/c01-poincare/piece.tsdeleted+0−431View file
@@ -1,431 +0,0 @@
1-// Composition 1: a double pendulum and its Poincaré section.
2-//
3-// Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2).
4-// Each crossing plays a note: θ2 → pitch, |p2| → loudness, θ2 → pan.
5-// A hum runs throughout; its timbre follows the energy.
6-// Energy is steered along an envelope: small → peak → hold → zero.
7-// Notes stop at the end and the last one is held and faded.
8-// Behind the live crossings, a worker draws the section's orbits at the current energy.
9-
10-import type { AudioEngine } from "../../core/audio.ts";
11-import { dbToGain } from "../../core/audio.ts";
12-import type { Piece } from "../../core/composition.ts";
13-import type { Params } from "../../core/params.ts";
14-import { mulberry32, randomSeed } from "../../core/rng.ts";
15-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
16-import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
17-import { midiToFreq } from "../../music/scales.ts";
18-import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
19-import { energyTarget } from "../shared/form.ts";
20-import { Hum } from "../shared/hum.ts";
21-import { noteFor } from "../shared/noteMap.ts";
22-import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
23-import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
24-
25-const DT = 0.002; // simulation step (sim seconds)
26-const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
27-const TICK_MS = 25;
28-const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
29-const HISTORY_DT = 1 / 960; // piece-time spacing of stored pendulum snapshots
30-const BLUR_MAX_SAMPLES = 64; // cap on sub-frame positions drawn for motion blur
31-const BLUR_SPACING_PX = 2; // target distance the tip moves between blur samples
32-
33-interface Snapshot {
34- t: number;
35- th1: number;
36- th2: number;
37-}
38-
39-interface Crossing {
40- t: number; // piece time
41- th2: number; // wrapped
42- p2: number; // normalized
43-}
44-
45-export function createPoincarePiece(view: HTMLElement, params: () => Params): Piece {
46- view.classList.add("c01");
47- // one canvas: the Poincaré section, with the pendulum as an inset in its upper-left corner
48- const plotCanvas = document.createElement("canvas");
49- view.append(plotCanvas);
50- const plot = new SectionPlot(plotCanvas);
51- const hum = new Hum();
52-
53- let pend: DoublePendulum | null = null;
54- let audio: AudioEngine | null = null;
55- let notes: NoteInstrument | null = null;
56- let noteKey = ""; // instrument name (+ custom settings) the current instance was built from
57- let noteBus: GainNode | null = null; // notes level
58- let startToken = 0;
59- let out: GainNode | null = null;
60- let timer: number | undefined;
61- let playing = false;
62- let pieceStart = 0; // AudioContext time of piece time 0
63- let simPieceT = 0; // piece time of the simulation state
64- let seedUsed = 0;
65- let noteCount = 0;
66- let stoppedAt = 0;
67- let history: Snapshot[] = [];
68- let lastHistT = -Infinity;
69- let points: Crossing[] = [];
70- // final note
71- let lastNote: { handle: NoteHandle; when: number } | null = null;
72- // The ending comes from the simulation: once the energy target is zero and the pendulum's
73- // energy falls below restEnergy it is at rest. No crossings register after that; the last
74- // real note is held and faded, the hum fades with it, and the piece ends with the fade.
75- let restAt: number | null = null; // piece time the pendulum came to rest
76-
77- // background portrait of the section at the current energy (throttled worker)
78- const portrait = new PortraitLayer(() => now(), () => playing);
79- const portraitSettings = (P: Params): PortraitSettings => ({
80- show: P.orbits as boolean,
81- count: P.orbitCount as number,
82- cpu: P.orbitCpu as number,
83- life: P.orbitLife as number,
84- band: P.orbitBand as number,
85- minHold: P.orbitMinHold as number,
86- maxPoints: P.orbitMaxPoints as number,
87- xfade: P.orbitXfade as number,
88- alpha: P.orbitAlpha as number,
89- size: P.orbitSize as number,
90- tracks: false,
91- trackMax: 0,
92- trackAlpha: 0,
93- trackSize: 1,
94- });
95- const postPortrait = (running: boolean) => {
96- const P = params();
97- portrait.post(running, portraitSettings(P), pend ? pend.energyNorm() : 0, P.massRatio as number, P.lengthRatio as number, []);
98- };
99-
100- const piece: Piece = {
101- get playing() {
102- return playing;
103- },
104- start,
105- stop,
106- draw,
107- now,
108- length: () => endTime(params()),
109- readouts,
110- dispose() {
111- stop();
112- portrait.dispose();
113- view.classList.remove("c01");
114- view.replaceChildren();
115- },
116- };
117-
118- function now(): number {
119- if (!audio || !playing) return stoppedAt;
120- return audio.ctx.currentTime - pieceStart;
121- }
122-
123- // ── transport ──
124-
125- function makePendulum(P: Params): DoublePendulum {
126- return new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
127- }
128-
129- async function start(a: AudioEngine, offset: number) {
130- stop();
131- const token = ++startToken;
132- audio = a;
133- const P = params();
134- const ctx = a.ctx;
135- seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
136- pend = makePendulum(P);
137- pend.randomize(energyTarget(P, 0), mulberry32(seedUsed));
138- pend.tau = P.tau as number;
139- simPieceT = 0;
140- history = [];
141- lastHistT = -Infinity;
142- points = [];
143- portrait.reset(); // the worker starts a fresh portrait
144- noteCount = 0;
145- lastNote = null;
146- restAt = null;
147- // fast-forward silently to the start offset (author "start at")
148- if (offset > 0) advanceTo(offset, false);
149-
150- out = ctx.createGain();
151- out.connect(a.input);
152- ensureInstruments();
153- await Promise.all([notes?.ready, hum.ready]); // e.g. the modal-synth worklet loading
154- if (token !== startToken) return; // stopped or restarted meanwhile
155- pieceStart = ctx.currentTime + 0.1 - offset;
156- hum.start(ctx, P);
157- playing = true;
158- tick();
159- timer = window.setInterval(tick, TICK_MS);
160- }
161-
162- function ensureInstruments() {
163- if (!audio || !out) return;
164- const P = params();
165- if (!noteBus) {
166- noteBus = audio.ctx.createGain();
167- noteBus.connect(out);
168- }
169- noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
170- const name = P.noteInstrument as string;
171- const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
172- if (!notes || noteKey !== key) {
173- notes?.dispose();
174- noteKey = key;
175- notes = NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string });
176- }
177- hum.ensure(audio.ctx, out, P, playing);
178- }
179-
180- function stop() {
181- startToken++;
182- if (timer !== undefined) window.clearInterval(timer);
183- timer = undefined;
184- const wasPlaying = playing;
185- if (playing) {
186- stoppedAt = now();
187- playing = false;
188- postPortrait(false);
189- }
190- // release the audio graph (also when a start is still waiting for its instrument to load)
191- if (!audio) return;
192- const t = audio.ctx.currentTime;
193- hum.release(audio.ctx, wasPlaying);
194- const o = out;
195- if (o) {
196- o.gain.setTargetAtTime(0, t, 0.05);
197- window.setTimeout(() => o.disconnect(), 600);
198- }
199- notes?.dispose();
200- notes = null;
201- noteKey = "";
202- noteBus = null;
203- out = null;
204- }
205-
206- // ── simulation ──
207-
208- /** Simulate up to piece time `target`; schedule notes if `sound`. */
209- function advanceTo(target: number, sound: boolean) {
210- if (!pend) return;
211- const P = params();
212- pend.cfg.m2 = P.massRatio as number;
213- pend.cfg.l2 = P.lengthRatio as number;
214- pend.tau = P.tau as number;
215- const speed = P.speed as number;
216- const duration = P.duration as number;
217- const restE = P.restEnergy as number;
218- const y = pend.y;
219- let prev = wrapAngle(y[0]);
220- let prevTh2 = y[1];
221- let prevP2 = y[3];
222- let prevT = simPieceT;
223- while (simPieceT < target) {
224- pend.eTarget = energyTarget(P, simPieceT) * pend.vTop;
225- pend.step(DT);
226- simPieceT += DT / speed;
227- const cur = wrapAngle(y[0]);
228- if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) {
229- const f = -prev / (cur - prev);
230- const c: Crossing = {
231- t: prevT + f * (simPieceT - prevT),
232- th2: wrapAngle(prevTh2 + f * (y[1] - prevTh2)),
233- p2: (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale,
234- };
235- points.push(c);
236- if (sound) playNote(c, P);
237- }
238- if (restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
239- restAt = simPieceT;
240- if (sound) holdFinalNote(P);
241- }
242- prev = cur;
243- prevTh2 = y[1];
244- prevP2 = y[3];
245- prevT = simPieceT;
246- if (simPieceT - lastHistT >= HISTORY_DT) {
247- history.push({ t: simPieceT, th1: y[0], th2: y[1] });
248- lastHistT = simPieceT;
249- }
250- }
251- }
252-
253- function playNote(c: Crossing, P: Params) {
254- if (!audio || !notes) return;
255- const when = pieceStart + c.t;
256- if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
257-
258- const { midi, velocity, pan } = noteFor(P, c.th2, c.p2);
259- const freq = midiToFreq(midi);
260- const handle = notes.play({ when, freq, velocity, pan, duration: P.noteLength as number });
261- if (handle) lastNote = { handle, when };
262- noteCount++;
263- }
264-
265- /** Let the last real note ring: sustain it for finalHold, then fade over finalFade. */
266- function holdFinalNote(P: Params) {
267- if (!lastNote) return;
268- lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
269- }
270-
271- /** Piece time at which everything has faded: known once the pendulum is at rest, estimated before. */
272- function endTime(P: Params): number {
273- const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
274- return (restAt ?? (P.duration as number) + 0.5) + ring;
275- }
276-
277- function tick() {
278- if (!audio || !pend || !playing) return;
279- const P = params();
280- ensureInstruments();
281- const ctx = audio.ctx;
282- const t = ctx.currentTime - pieceStart;
283- const total = endTime(P);
284- if (restAt !== null && t >= total) {
285- stop();
286- stoppedAt = total;
287- piece.onEnded?.();
288- return;
289- }
290- advanceTo(t + LOOKAHEAD, true);
291- postPortrait(true);
292-
293- hum.update(ctx, P, pend.energyNorm(), t, restAt !== null ? total : null);
294-
295- // trim history to what drawing still needs
296- let i = 0;
297- while (i < history.length - 1 && history[i + 1].t <= t - 0.1) i++;
298- if (i > 0) history.splice(0, i);
299- }
300-
301- // ── drawing ──
302-
303- function color(name: string): string {
304- return cssColor(view, name);
305- }
306-
307- /** Pendulum angles at piece time t, interpolated between stored snapshots. */
308- function stateAt(t: number): { th1: number; th2: number } {
309- const n = history.length;
310- if (!n) return pend ? { th1: pend.y[0], th2: pend.y[1] } : { th1: 0, th2: 0 };
311- if (t <= history[0].t) return history[0];
312- if (t >= history[n - 1].t) return history[n - 1];
313- let lo = 0, hi = n - 1; // history[lo].t <= t < history[hi].t
314- while (hi - lo > 1) {
315- const mid = (lo + hi) >> 1;
316- if (history[mid].t <= t) lo = mid;
317- else hi = mid;
318- }
319- const a = history[lo], b = history[hi];
320- const f = (t - a.t) / (b.t - a.t);
321- return { th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
322- }
323-
324- let lastDrawWall = 0;
325- let frameDt = 1 / 60; // smoothed display frame interval (s)
326-
327- /**
328- * The pendulum as an inset in the plot's upper-left corner (outside the energetically allowed
329- * region of the section most of the time), drawn as before: solid arms and filled bobs.
330- * Motion blur: several faint positions spread over the last frame interval.
331- */
332- function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number) {
333- const opacity = P.pendulumAlpha as number;
334- if (opacity <= 0) return;
335- const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
336- const l1 = 1, l2 = P.lengthRatio as number;
337- const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2; // inset radius
338- const scale = (0.9 * R) / (l1 + l2);
339- const x0 = 8 + R, y0 = 8 + R; // pivot
340-
341- // enough samples that the tip moves ~BLUR_SPACING_PX between them
342- let k = 1;
343- if (shutter > 0) {
344- let path = 0;
345- let a = stateAt(t);
346- for (let j = 1; j <= 8; j++) {
347- const b = stateAt(t - (shutter * j) / 8);
348- path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
349- a = b;
350- }
351- k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
352- }
353- // per-sample alpha so a still pendulum still draws (nearly) fully opaque
354- const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k));
355- const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number);
356- const fg = color("--fg");
357- g.strokeStyle = fg;
358- g.fillStyle = fg;
359- g.lineWidth = 1.5;
360- g.lineCap = "round";
361- g.globalAlpha = alpha;
362- for (let i = 0; i < k; i++) {
363- const { th1, th2 } = stateAt(t - (shutter * i) / Math.max(1, k - 1));
364- const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
365- const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2);
366- g.beginPath();
367- g.moveTo(x0, y0);
368- g.lineTo(x1, y1);
369- g.lineTo(x2, y2);
370- g.stroke();
371- g.beginPath();
372- g.arc(x1, y1, r1, 0, 2 * Math.PI);
373- g.moveTo(x2 + r2, y2);
374- g.arc(x2, y2, r2, 0, 2 * Math.PI);
375- g.fill();
376- }
377- g.globalAlpha = opacity;
378- g.beginPath();
379- g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
380- g.fill();
381- g.globalAlpha = 1;
382- }
383-
384- function draw() {
385- const P = params();
386- const t = now();
387- const wall = performance.now() / 1000;
388- const dtw = wall - lastDrawWall;
389- lastDrawWall = wall;
390- if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
391- const fg = color("--fg");
392- const dim = color("--dim");
393-
394- // Poincaré section
395- {
396- const f = plot.begin(P, pend ? pend.energyNorm() : null, pend?.cfg ?? null, pend?.vTop ?? 1, dim);
397- const { g, w, h } = f;
398-
399- portrait.draw(f, t, portraitSettings(P), fg, () => fg);
400-
401- // the pendulum's own crossings
402- const fade = P.fade as number;
403- const size = P.pointSize as number;
404- let drop = 0;
405- while (drop < points.length && t - points[drop].t > 4.6 * fade) drop++;
406- if (drop > 0) points.splice(0, drop);
407- for (const c of points) {
408- const age = t - c.t;
409- if (age < 0) break; // not sounded yet
410- drawCrossing(f, c.th2, c.p2, age, fade, size, fg);
411- }
412- drawPendulum(g, w, h, P, t);
413- }
414- }
415-
416- function readouts(): Record<string, string> {
417- const P = params();
418- const t = now();
419- return {
420- time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
421- "energy target": energyTarget(P, t).toFixed(4),
422- energy: pend ? pend.energyNorm().toFixed(4) : "–",
423- notes: String(noteCount),
424- "seed used": seedUsed ? String(seedUsed) : "–",
425- hum: hum.describe(),
426- "orbit portrait": portrait.describe(),
427- };
428- }
429-
430- return piece;
431-}
src/compositions/c01-poincare/schema.tsmodified+23−25View file
@@ -1,6 +1,5 @@
11 import type { ParamSpec } from "../../core/params.ts";
2-import { DRONE_INSTRUMENTS, NOTE_INSTRUMENTS } from "../../instruments/index.ts";
3-import { LIVE_TARGETS } from "../../instruments/modal.ts";
2+import { DRONE_SOUNDS, LIVE_TARGETS, NOTE_SOUNDS } from "../../instruments/sounds.ts";
43 import { NOTE_NAMES, SCALE_NAMES } from "../../music/scales.ts";
54
65 // Energies are in units of the potential energy with both arms straight up.
@@ -28,7 +27,7 @@ export const schema: ParamSpec[] = [
2827 { group: "physics", key: "seed", label: "seed", kind: "number", default: 0, min: 0, max: 999999, step: 1, hint: "0 = a new variation every play" },
2928
3029 // ── notes (one per Poincaré crossing) ──
31- { group: "notes", key: "noteInstrument", label: "instrument", kind: "select", default: "placeholder tone", options: Object.keys(NOTE_INSTRUMENTS), hint: "modal: … instruments come from the modal-synth project" },
30+ { group: "notes", key: "noteInstrument", label: "instrument", kind: "select", default: "modal: Nylon harp", options: NOTE_SOUNDS, hint: "modal: … instruments come from the modal-synth project" },
3231 { group: "notes", key: "modalCustom", label: "modal custom", kind: "text", default: "", hint: "for “modal: custom”: paste JSON from modal-synth’s Copy button" },
3332 { group: "notes", key: "scale", label: "scale", kind: "select", default: "pentatonic minor", options: SCALE_NAMES },
3433 { group: "notes", key: "root", label: "root", kind: "select", default: "D", options: NOTE_NAMES },
@@ -41,15 +40,14 @@ export const schema: ParamSpec[] = [
4140 { group: "notes", key: "p2Ref", label: "|p2| for full", kind: "number", default: 1, min: 0.01, max: 4, log: true, hint: "|p2| that gives full loudness" },
4241 { group: "notes", key: "loudCurve", label: "loudness curve", kind: "number", default: 1, min: 0.2, max: 5, log: true },
4342 { group: "notes", key: "loudFloor", label: "loudness floor", kind: "number", default: 0.08, min: 0, max: 1, step: 0.01, hint: "loudness of a crossing with p2 = 0" },
44- { group: "notes", key: "notesLevel", label: "level", kind: "number", default: -6, min: -48, max: 6, step: 0.5, unit: "dB" },
43+ { group: "notes", key: "notesLevel", label: "level", kind: "number", default: -6, min: -48, max: 6, step: 0.5, unit: "dB", live: true },
4544 { group: "notes", key: "noteLength", label: "length", kind: "number", default: 1.5, min: 0.05, max: 10, log: true, unit: "s" },
46- { group: "notes", key: "panAmount", label: "pan from θ2", kind: "number", default: 0.6, min: 0, max: 1, step: 0.01, hint: "placeholder tone only; modal instruments have their own stereo image" },
4745
4846 // ── hum (energy) ──
49- { group: "hum", key: "humInstrument", label: "instrument", kind: "select", default: "modal: Clarinet-ish", options: Object.keys(DRONE_INSTRUMENTS), hint: "modal: … = one held note of a sustained modal-synth preset" },
47+ { group: "hum", key: "humInstrument", label: "instrument", kind: "select", default: "modal: Clarinet-ish", options: DRONE_SOUNDS, hint: "modal: … = one held note of a sustained modal-synth preset" },
5048 { group: "hum", key: "humCustom", label: "modal custom", kind: "text", default: "", hint: "for “modal: custom”: paste JSON from modal-synth’s Copy button" },
5149 { group: "hum", key: "humPitch", label: "pitch", kind: "number", default: 38, min: 12, max: 72, step: 0.5, unit: "midi" },
52- { group: "hum", key: "humLevel", label: "level", kind: "number", default: -24, min: -60, max: 0, step: 0.5, unit: "dB" },
50+ { group: "hum", key: "humLevel", label: "level", kind: "number", default: -24, min: -60, max: 0, step: 0.5, unit: "dB", live: true },
5351 { group: "hum", key: "humFollow", label: "loudness follows energy", kind: "number", default: 0, min: 0, max: 1, step: 0.01, hint: "0 = constant loudness" },
5452 { group: "hum", key: "humNormalize", label: "normalize loudness", kind: "bool", default: true, hint: "modal hum: measure the output and compensate slowly, so timbre changes don't change loudness" },
5553 { 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" },
@@ -64,24 +62,24 @@ export const schema: ParamSpec[] = [
6462 { group: "hum", key: "humFadeOut", label: "fade out", kind: "number", default: 6, min: 0, max: 60, step: 0.5, unit: "s", hint: "ends together with the last note's fade" },
6563
6664 // ── visual ──
67- { group: "visual", key: "pendulumAlpha", label: "pendulum opacity", kind: "number", default: 1, min: 0, max: 1, step: 0.01, hint: "0 = hide the pendulum" },
68- { group: "visual", key: "pendulumSize", label: "pendulum size", kind: "number", default: 0.32, min: 0.1, max: 1, step: 0.01, hint: "inset diameter, as a fraction of the plot (upper-left corner)" },
69- { group: "visual", key: "motionBlur", label: "motion blur", kind: "number", default: 1, min: 0, max: 4, step: 0.05, hint: "pendulum shutter, in display frames; 0 = off" },
70- { group: "visual", key: "fade", label: "point fade", kind: "number", default: 10, min: 0.2, max: 120, log: true, unit: "s" },
71- { 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" },
72- { group: "visual", key: "zoomSmooth", label: "zoom smoothing", kind: "number", default: 1.5, min: 0.05, max: 20, log: true, unit: "s", hint: "time constant of zoom changes" },
73- { group: "visual", key: "plotP", label: "fixed p2 range", kind: "number", default: 1.5, min: 0.05, max: 5, log: true },
74- { group: "visual", key: "pointSize", label: "point size", kind: "number", default: 2, min: 0.5, max: 8, step: 0.1, unit: "px" },
65+ { group: "visual", key: "pendulumAlpha", label: "pendulum opacity", kind: "number", default: 1, min: 0, max: 1, step: 0.01, hint: "0 = hide the pendulum", live: true },
66+ { group: "visual", key: "pendulumSize", label: "pendulum size", kind: "number", default: 0.32, min: 0.1, max: 1, step: 0.01, hint: "inset diameter, as a fraction of the plot (upper-left corner)", live: true },
67+ { group: "visual", key: "motionBlur", label: "motion blur", kind: "number", default: 1, min: 0, max: 4, step: 0.05, hint: "pendulum shutter, in display frames; 0 = off", live: true },
68+ { group: "visual", key: "fade", label: "point fade", kind: "number", default: 10, min: 0.2, max: 120, log: true, unit: "s", live: true },
69+ { 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", live: true },
70+ { group: "visual", key: "zoomSmooth", label: "zoom smoothing", kind: "number", default: 1.5, min: 0.05, max: 20, log: true, unit: "s", hint: "time constant of zoom changes", live: true },
71+ { group: "visual", key: "plotP", label: "fixed p2 range", kind: "number", default: 1.5, min: 0.05, max: 5, log: true, live: true },
72+ { group: "visual", key: "pointSize", label: "point size", kind: "number", default: 2, min: 0.5, max: 8, step: 0.1, unit: "px", live: true },
7573
7674 // ── orbits: live background portrait of the section at the current energy ──
77- { group: "orbits", key: "orbits", label: "show orbits", kind: "bool", default: true },
78- { 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" },
79- { group: "orbits", key: "orbitCpu", label: "cpu", kind: "number", default: 0.4, min: 0.02, max: 0.9, step: 0.01, hint: "fraction of one core the background computation may use" },
80- { group: "orbits", key: "orbitLife", label: "life", kind: "number", default: 300, min: 10, max: 5000, log: true, hint: "crossings before an orbit is reseeded elsewhere on the section" },
81- { group: "orbits", key: "orbitBand", label: "refresh at", kind: "number", default: 0.25, min: 0.01, max: 2, log: true, hint: "start a new portrait when the energy has changed by this fraction" },
82- { group: "orbits", key: "orbitMinHold", label: "min hold", kind: "number", default: 3, min: 0, max: 30, step: 0.1, unit: "s", hint: "a portrait is kept at least this long" },
83- { group: "orbits", key: "orbitMaxPoints", label: "max points", kind: "number", default: 8000, min: 500, max: 40000, log: true, hint: "a portrait stops computing (and using CPU) once it has this many points" },
84- { group: "orbits", key: "orbitXfade", label: "crossfade", kind: "number", default: 1.5, min: 0.05, max: 10, log: true, unit: "s", hint: "time for the old portrait to fade out once a new one starts" },
85- { group: "orbits", key: "orbitAlpha", label: "brightness", kind: "number", default: 0.3, min: 0.02, max: 1, step: 0.01 },
86- { group: "orbits", key: "orbitSize", label: "point size", kind: "number", default: 1, min: 0.5, max: 4, step: 0.1, unit: "px" },
75+ { group: "orbits", key: "orbits", label: "show orbits", kind: "bool", default: true, live: true },
76+ { 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", live: true },
77+ { group: "orbits", key: "orbitCpu", label: "cpu", kind: "number", default: 0.4, min: 0.02, max: 0.9, step: 0.01, hint: "fraction of one core the background computation may use", live: true },
78+ { group: "orbits", key: "orbitLife", label: "life", kind: "number", default: 300, min: 10, max: 5000, log: true, hint: "crossings before an orbit is reseeded elsewhere on the section", live: true },
79+ { group: "orbits", key: "orbitBand", label: "refresh at", kind: "number", default: 0.25, min: 0.01, max: 2, log: true, hint: "start a new portrait when the energy has changed by this fraction", live: true },
80+ { group: "orbits", key: "orbitMinHold", label: "min hold", kind: "number", default: 3, min: 0, max: 30, step: 0.1, unit: "s", hint: "a portrait is kept at least this long", live: true },
81+ { group: "orbits", key: "orbitMaxPoints", label: "max points", kind: "number", default: 8000, min: 500, max: 40000, log: true, hint: "a portrait stops computing (and using CPU) once it has this many points", live: true },
82+ { group: "orbits", key: "orbitXfade", label: "crossfade", kind: "number", default: 1.5, min: 0.05, max: 10, log: true, unit: "s", hint: "time for the old portrait to fade out once a new one starts", live: true },
83+ { group: "orbits", key: "orbitAlpha", label: "brightness", kind: "number", default: 0.3, min: 0.02, max: 1, step: 0.01, live: true },
84+ { group: "orbits", key: "orbitSize", label: "point size", kind: "number", default: 1, min: 0.5, max: 4, step: 0.1, unit: "px", live: true },
8785 ];
src/compositions/c01-poincare/score.tsadded+85−0View file
@@ -0,0 +1,85 @@
1+// Composition 1: a double pendulum and its Poincaré section — the score (score worker).
2+//
3+// Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2). Each crossing plays a note:
4+// θ2 → pitch, |p2| → loudness. A hum runs throughout; its timbre follows the energy. Energy is
5+// steered along an envelope: small → peak → hold → zero. Once the pendulum is at rest, no more
6+// crossings register; the last note is held and faded, the hum fades with it, and the piece ends.
7+//
8+// Drawing data: track 0 = [θ1, θ2, energy] (960 per piece second); events "x" = crossings.
9+
10+import type { Params } from "../../core/params.ts";
11+import { mulberry32 } from "../../core/rng.ts";
12+import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
13+import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
14+import { energyTarget } from "../shared/form.ts";
15+import { HumScore } from "../shared/humScore.ts";
16+import { noteFor } from "../shared/noteMap.ts";
17+import { HUM, NOTES } from "./layout.ts";
18+
19+const DT = 0.002; // simulation step (sim seconds)
20+const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
21+const FRAME_DT = 1 / 960;
22+const INFO_DT = 0.1;
23+
24+export const poincareScore: ScoreFactory = (P: Params, seed: number, sink) => {
25+ const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
26+ pend.randomize(energyTarget(P, 0), mulberry32(seed));
27+ pend.tau = P.tau as number;
28+ const speed = P.speed as number, duration = P.duration as number, restE = P.restEnergy as number;
29+ const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
30+ const hum = new HumScore(P, HUM, sink);
31+ const y = pend.y;
32+
33+ let time = 0;
34+ let prev = wrapAngle(y[0]), prevTh2 = y[1], prevP2 = y[3];
35+ let restAt: number | null = null;
36+ let lastNote: NoteRef | null = null;
37+ let notes = 0;
38+ let nextFrame = 0, nextInfo = 0;
39+
40+ function step() {
41+ pend.eTarget = energyTarget(P, time) * pend.vTop;
42+ const t0 = time;
43+ pend.step(DT);
44+ time += DT / speed;
45+ const cur = wrapAngle(y[0]);
46+ if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) {
47+ const f = -prev / (cur - prev);
48+ const tc = t0 + f * (time - t0);
49+ const th2 = wrapAngle(prevTh2 + f * (y[1] - prevTh2));
50+ const p2 = (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale;
51+ sink.event({ t: tc, kind: "x", th2, p2 });
52+ const { midi, velocity } = noteFor(P, th2, p2);
53+ lastNote = sink.note(NOTES, tc, midi, velocity, P.noteLength as number) ?? lastNote;
54+ notes++;
55+ }
56+ if (restAt === null && time >= duration && (pend.energyNorm() < restE || time >= duration + MAX_SETTLE)) {
57+ restAt = time;
58+ // the last real note rings: sustain, then fade; the piece ends with the fade
59+ if (lastNote) sink.hold(lastNote, lastNote.t, P.finalHold as number, P.finalFade as number);
60+ sink.end(time + ring);
61+ }
62+ prev = cur;
63+ prevTh2 = y[1];
64+ prevP2 = y[3];
65+ const e = pend.energyNorm();
66+ hum.update(time, e, restAt !== null ? restAt + ring : null);
67+ if (time >= nextFrame) {
68+ sink.frame(0, time, [y[0], y[1], e]);
69+ nextFrame = time + FRAME_DT;
70+ }
71+ if (time >= nextInfo) {
72+ nextInfo = time + INFO_DT;
73+ sink.info(time, { "energy target": energyTarget(P, time).toFixed(4), energy: e.toFixed(4), notes: String(notes) });
74+ }
75+ }
76+
77+ return {
78+ get time() {
79+ return time;
80+ },
81+ advance(t: number) {
82+ while (time < t) step();
83+ },
84+ };
85+};
src/compositions/c01-poincare/view.tsadded+139−0View file
@@ -0,0 +1,139 @@
1+// Composition 1: poincaré — drawing at the playhead: the Poincaré section (axes zoomed to the
2+// energy, the crossings fading with age, a background portrait of the orbits at the current energy
3+// computed by a throttled worker) with the pendulum as an inset in the upper-left corner.
4+
5+import type { Params } from "../../core/params.ts";
6+import type { FrameStore } from "../../stream/frames.ts";
7+import type { View } from "../../stream/piece.ts";
8+import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
9+import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
10+
11+const BLUR_MAX_SAMPLES = 64;
12+const BLUR_SPACING_PX = 2;
13+const PORTRAIT_POST_MS = 50;
14+
15+export function vTopOf(m2: number, l2: number): number {
16+ return 2 * (1 + m2) + 2 * m2 * l2; // m1 = l1 = g = 1
17+}
18+
19+export function poincareView(el: HTMLElement, params: () => Params): View {
20+ el.classList.add("c01");
21+ const canvas = document.createElement("canvas");
22+ el.append(canvas);
23+ const plot = new SectionPlot(canvas);
24+ let now = 0, moving = false;
25+ const portrait = new PortraitLayer(() => now, () => moving);
26+ const settings = (P: Params): PortraitSettings => ({
27+ show: P.orbits as boolean,
28+ count: P.orbitCount as number,
29+ cpu: P.orbitCpu as number,
30+ life: P.orbitLife as number,
31+ band: P.orbitBand as number,
32+ minHold: P.orbitMinHold as number,
33+ maxPoints: P.orbitMaxPoints as number,
34+ xfade: P.orbitXfade as number,
35+ alpha: P.orbitAlpha as number,
36+ size: P.orbitSize as number,
37+ tracks: false,
38+ trackMax: 0,
39+ trackAlpha: 0,
40+ trackSize: 1,
41+ });
42+ const st = new Float64Array(3);
43+ let lastStore: FrameStore | null = null;
44+ let lastPost = 0, lastWall = 0, frameDt = 1 / 60;
45+
46+ function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number, store: FrameStore | null) {
47+ const opacity = P.pendulumAlpha as number;
48+ if (opacity <= 0) return;
49+ const at = (u: number): [number, number] => {
50+ const s = store?.at(0, u, st);
51+ return s ? [s[0], s[1]] : [0, 0];
52+ };
53+ const shutter = moving ? (P.motionBlur as number) * frameDt : 0;
54+ const l1 = 1, l2 = P.lengthRatio as number;
55+ const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2;
56+ const scale = (0.9 * R) / (l1 + l2);
57+ const x0 = 8 + R, y0 = 8 + R;
58+ let k = 1;
59+ if (shutter > 0) {
60+ let path = 0;
61+ let a = at(t);
62+ for (let j = 1; j <= 8; j++) {
63+ const b = at(t - (shutter * j) / 8);
64+ path += scale * (l1 * Math.abs(b[0] - a[0]) + l2 * Math.abs(b[1] - a[1]));
65+ a = b;
66+ }
67+ k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
68+ }
69+ const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k));
70+ const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number);
71+ const fg = cssColor(el, "--fg");
72+ g.strokeStyle = fg;
73+ g.fillStyle = fg;
74+ g.lineWidth = 1.5;
75+ g.lineCap = "round";
76+ g.globalAlpha = alpha;
77+ for (let i = 0; i < k; i++) {
78+ const [th1, th2] = at(t - (shutter * i) / Math.max(1, k - 1));
79+ const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
80+ const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2);
81+ g.beginPath();
82+ g.moveTo(x0, y0);
83+ g.lineTo(x1, y1);
84+ g.lineTo(x2, y2);
85+ g.stroke();
86+ g.beginPath();
87+ g.arc(x1, y1, r1, 0, 2 * Math.PI);
88+ g.moveTo(x2 + r2, y2);
89+ g.arc(x2, y2, r2, 0, 2 * Math.PI);
90+ g.fill();
91+ }
92+ g.globalAlpha = opacity;
93+ g.beginPath();
94+ g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
95+ g.fill();
96+ g.globalAlpha = 1;
97+ }
98+
99+ return {
100+ keep: (P) => 4.6 * (P.fade as number) + 0.5,
101+ draw(t, store, playing) {
102+ const P = params();
103+ now = t;
104+ moving = playing;
105+ const wall = performance.now();
106+ const dtw = (wall - lastWall) / 1000;
107+ lastWall = wall;
108+ if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
109+ if (store !== lastStore) {
110+ lastStore = store;
111+ portrait.reset(); // a new performance: a fresh portrait
112+ }
113+ const s = store?.at(0, t, st);
114+ const e = s ? s[2] : null;
115+ const m2 = P.massRatio as number, l2 = P.lengthRatio as number;
116+ const fg = cssColor(el, "--fg");
117+ if (wall - lastPost > PORTRAIT_POST_MS) {
118+ lastPost = wall;
119+ portrait.post(playing, settings(P), e ?? 0, m2, l2, []);
120+ }
121+ const f = plot.begin(P, e, { m1: 1, l1: 1, g: 1, m2, l2 }, vTopOf(m2, l2), cssColor(el, "--dim"));
122+ portrait.draw(f, t, settings(P), fg, () => fg);
123+ if (store) {
124+ const fade = P.fade as number, size = P.pointSize as number;
125+ for (const c of store.events) {
126+ const age = t - c.t;
127+ if (age < 0) break; // not sounded yet
128+ drawCrossing(f, c.th2 as number, c.p2 as number, age, fade, size, fg);
129+ }
130+ }
131+ drawPendulum(f.g, f.w, f.h, P, t, store);
132+ },
133+ readouts: () => ({ "orbit portrait": portrait.describe() }),
134+ dispose() {
135+ portrait.dispose();
136+ el.classList.remove("c01");
137+ },
138+ };
139+}
src/compositions/c02-orbits/capacity.tsdeleted+0−183View file
@@ -1,183 +0,0 @@
1-// How many orbits can this device play live?
2-//
3-// Almost all the cost is audio: the modal-synth instruments run on the single real-time audio
4-// thread, and their load grows with the number of orbits (more notes → more ringing voices).
5-// So, before the first play, we play the composition's actual instruments silently (into a muted
6-// bus) for about a second at the note density the orbit count produces, and read the load the
7-// synths report from the audio thread itself. That measures exactly what glitches, on this
8-// device, and isn't affected by background-tab throttling. If the load is over BUDGET we try
9-// fewer orbits. The answer is cached per device and settings.
10-
11-import { DEFAULTS } from "@modal-synth/engine/params.ts";
12-import { PRESETS } from "@modal-synth/presets.ts";
13-import type { Params } from "../../core/params.ts";
14-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
15-import { parseModalPreset } from "../../instruments/modal.ts";
16-import type { BenchNote, FromWorker, ToWorker } from "../../instruments/stream/protocol.ts";
17-import { midiToFreq } from "../../music/scales.ts";
18-
19-// Synth load (share of real time) we accept on the audio thread. The synths' own measure excludes
20-// the reverb, the hum, browser overhead, and what the page's own drawing and physics take from a
21-// phone's CPU. A phone measured within 0.55 still glitched, so stay well below that.
22-const BUDGET = 0.35;
23-// With rendering ahead in workers (one per instrument, on other cores, buffered), each worker must
24-// render comfortably faster than real time; the buffer absorbs momentary slowdowns.
25-const BUDGET_STREAM = 0.6;
26-const NOTES_PER_SIM_SECOND = 0.2; // crossings per orbit per simulated second (busy parts of the piece)
27-const PLAY_S = 1.3; // how long the silent test plays
28-const MEASURE_FROM = 0.5; // ignore the first part (voices filling up)
29-const MAX_TRIES = 2;
30-
31-export interface CapacityResult {
32- cap: number; // orbits this device can play
33- tested: number; // the count asked for when this was measured
34- load: number; // measured synth load at the last count tried
35- at: number; // that count
36-}
37-
38-function cacheKey(P: Params, sampleRate: number, slots: number, stream: boolean): string {
39- const sig = {
40- v: 5, // bump when the check itself (or the engine's speed) changes
41- stream,
42- sr: sampleRate,
43- speed: P.speed,
44- len: P.noteLength,
45- inst: Array.from({ length: slots }, (_, i) => P[`slot${i + 1}Instrument`]),
46- custom: P.modalCustom,
47- };
48- return `double-pendulum:capacity:02-orbits:${JSON.stringify(sig)}`;
49-}
50-
51-function readCache(key: string): CapacityResult | null {
52- try {
53- const s = localStorage.getItem(key);
54- return s ? (JSON.parse(s) as CapacityResult) : null;
55- } catch {
56- return null;
57- }
58-}
59-
60-function writeCache(key: string, r: CapacityResult) {
61- try {
62- localStorage.setItem(key, JSON.stringify(r));
63- } catch {
64- /* storage unavailable: we'll just measure again next time */
65- }
66-}
67-
68-const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
69-
70-/** Play `n` orbits' worth of notes silently on the live context; returns the measured synth load. */
71-async function measure(ctx: AudioContext, P: Params, n: number, slots: number): Promise<number> {
72- const mute = ctx.createGain();
73- mute.gain.value = 0;
74- mute.connect(ctx.destination); // connected so the audio thread renders it, but silent
75- const perSlot = new Array<number>(slots).fill(0);
76- for (let i = 0; i < n; i++) perSlot[i % slots]++;
77- const rate = (P.speed as number) * NOTES_PER_SIM_SECOND; // notes per second per orbit
78- const len = P.noteLength as number;
79- const insts = [];
80- for (let s = 0; s < slots; s++) {
81- if (!perSlot[s]) continue;
82- const inst = NOTE_INSTRUMENTS[P[`slot${s + 1}Instrument`] as string](ctx, mute, { custom: P.modalCustom as string, immediateRelease: true, effects: "none" });
83- insts.push({ inst, rate: rate * perSlot[s] });
84- }
85- try {
86- await Promise.all(insts.map((x) => x.inst.ready));
87- let seed = 12345;
88- const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
89- const t0 = ctx.currentTime + 0.05;
90- for (const { inst, rate: r } of insts) {
91- const note = (when: number) => inst.play({ when, freq: midiToFreq(50 + Math.floor(rnd() * 36)), velocity: 0.6, pan: 0, duration: len });
92- // start at the steady state: as many notes ringing as `rate × length` keeps going
93- const warm = Math.min(16, Math.round(r * len));
94- for (let k = 0; k < warm; k++) note(t0 + 0.002 * k);
95- for (let t = 0.05; t < PLAY_S; t += 1 / r) note(t0 + t);
96- }
97- // average the synths' reported load over the second part of the test
98- await sleep(MEASURE_FROM * 1000);
99- const samples: number[] = [];
100- const end = performance.now() + (PLAY_S - MEASURE_FROM) * 1000;
101- while (performance.now() < end) {
102- await sleep(100);
103- samples.push(insts.reduce((s, x) => s + (x.inst.load?.() ?? 0), 0));
104- }
105- return samples.length ? samples.reduce((a, b) => a + b, 0) / samples.length : 0;
106- } finally {
107- for (const x of insts) x.inst.dispose();
108- window.setTimeout(() => mute.disconnect(), 1200);
109- }
110-}
111-
112-/** The modal-synth settings for an instrument slot (null: not a modal instrument). */
113-function modalSound(P: Params, slot: number): Params | null {
114- const name = P[`slot${slot + 1}Instrument`] as string;
115- if (!name.startsWith("modal: ")) return null;
116- const p = name === "modal: custom" ? parseModalPreset(P.modalCustom as string) : PRESETS.find((x) => `modal: ${x.name}` === name)?.p;
117- return { ...DEFAULTS, ...(p ?? {}) };
118-}
119-
120-/**
121- * Rendered-ahead check: every instrument's worker renders its share of `n` orbits' notes as fast
122- * as it can, all at once (as they would run). Returns the busiest worker's render time / audio time.
123- */
124-async function measureWorkers(sampleRate: number, P: Params, n: number, slots: number): Promise<number> {
125- const perSlot = new Array<number>(slots).fill(0);
126- for (let i = 0; i < n; i++) perSlot[i % slots]++;
127- const rate = (P.speed as number) * NOTES_PER_SIM_SECOND;
128- const len = P.noteLength as number;
129- const SECONDS = 1.5, WARMUP = 0.5;
130- const jobs: Promise<number>[] = [];
131- for (let s = 0; s < slots; s++) {
132- const sound = perSlot[s] ? modalSound(P, s) : null;
133- if (!sound) continue;
134- const r = rate * perSlot[s];
135- let seed = 12345 + s;
136- const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
137- const notes: BenchNote[] = [];
138- const warm = Math.min(16, Math.round(r * len));
139- for (let k = 0; k < warm; k++) notes.push({ time: 0.002 * k, note: 50 + Math.floor(rnd() * 36), vel: 0.6, len });
140- for (let t = 0.05; t < SECONDS; t += 1 / r) notes.push({ time: t, note: 50 + Math.floor(rnd() * 36), vel: 0.6, len });
141- jobs.push(
142- new Promise<number>((resolve) => {
143- const w = new Worker(new URL("../../instruments/stream/renderWorker.ts", import.meta.url), { type: "module" });
144- w.onmessage = (e: MessageEvent<FromWorker>) => {
145- if (e.data.type === "bench") {
146- resolve(e.data.load);
147- w.terminate();
148- }
149- };
150- const m: ToWorker = { type: "bench", sampleRate, params: sound, notes, seconds: SECONDS, warmup: WARMUP };
151- w.postMessage(m);
152- }),
153- );
154- }
155- const loads = await Promise.all(jobs);
156- return loads.length ? Math.max(...loads) : 0;
157-}
158-
159-/**
160- * Largest orbit count ≤ `wanted` this device can play live (cached when the cache covers `wanted`).
161- * `stream`: instruments render ahead in workers (measured that way, with its own budget).
162- */
163-export async function orbitCapacity(ctx: AudioContext, P: Params, wanted: number, slots: number, stream = false): Promise<CapacityResult> {
164- const key = cacheKey(P, ctx.sampleRate, slots, stream);
165- const budget = stream ? BUDGET_STREAM : BUDGET;
166- const run = (n: number) => (stream ? measureWorkers(ctx.sampleRate, P, n, slots) : measure(ctx, P, n, slots));
167- const cached = readCache(key);
168- if (cached && (cached.cap < cached.tested || cached.tested >= wanted)) return { ...cached, cap: Math.min(cached.cap, wanted) };
169-
170- let n = wanted;
171- let load = await run(n);
172- let at = n;
173- for (let tries = 1; load > budget && n > 1 && tries < MAX_TRIES; tries++) {
174- // cost grows a little less than linearly with orbits (voices saturate), so step down generously
175- n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(budget / load, 1.3))));
176- load = await run(n);
177- at = n;
178- }
179- if (load > budget) n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(budget / load, 1.3)))); // estimate
180- const result: CapacityResult = { cap: n, tested: wanted, load, at };
181- writeCache(key, result);
182- return result;
183-}
src/compositions/c02-orbits/defaults.jsonmodified+0−3View file
@@ -15,8 +15,6 @@
1515 "lengthRatio": 1,
1616 "tau": 2,
1717 "seed": 0,
18- "streamAudio": true,
19- "deviceLimit": true,
2018 "orbitCount": 8,
2119 "colors": "#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0",
2220 "slot1Instrument": "modal: Nylon harp",
@@ -46,7 +44,6 @@
4644 "loudFloor": 0.08,
4745 "notesLevel": -6,
4846 "noteLength": 1.5,
49- "panAmount": 0.6,
5047 "humInstrument": "modal: Clarinet-ish",
5148 "humCustom": "",
5249 "humPitch": 38,
src/compositions/c02-orbits/index.tsmodified+7−3View file
@@ -1,12 +1,16 @@
11 import type { Composition } from "../../core/composition.ts";
2+import { createStreamPiece, type StreamDef } from "../../stream/piece.ts";
23 import defaults from "./defaults.json";
3-import { createOrbitsPiece } from "./piece.ts";
4+import { estimateLength, layout } from "./layout.ts";
45 import { schema } from "./schema.ts";
6+import { orbitsView } from "./view.ts";
7+
8+const def: StreamDef = { id: "02-orbits", schema, layout, estimateLength, view: orbitsView };
59
610 export const orbits: Composition = {
7- id: "02-orbits",
11+ id: def.id,
812 title: "orbits",
913 schema,
1014 defaults,
11- create: createOrbitsPiece,
15+ create: (view, params) => createStreamPiece(def, view, params),
1216 };
src/compositions/c02-orbits/layout.tsadded+48−0View file
@@ -0,0 +1,48 @@
1+import type { Params } from "../../core/params.ts";
2+import { soundOf } from "../../instruments/sounds.ts";
3+import type { Layout } from "../../stream/layout.ts";
4+
5+export const SLOTS = 6;
6+
7+export function orbitCount(P: Params): number {
8+ return Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
9+}
10+
11+/**
12+ * Orbit n plays instrument slot n (cycling). One stem (synth worker) per distinct instrument, so
13+ * the instruments render in parallel; orbits on the same instrument share it (it's polyphonic).
14+ */
15+export function orbitStems(P: Params): { names: string[]; stemOf: number[] } {
16+ const names: string[] = [];
17+ const stemOf: number[] = [];
18+ for (let i = 0; i < orbitCount(P); i++) {
19+ const name = P[`slot${(i % SLOTS) + 1}Instrument`] as string;
20+ let s = names.indexOf(name);
21+ if (s < 0) s = names.push(name) - 1;
22+ stemOf.push(s);
23+ }
24+ return { names, stemOf };
25+}
26+
27+/** The hum's stem comes after the instruments'. */
28+export function humStem(P: Params): number {
29+ return orbitStems(P).names.length;
30+}
31+
32+export function layout(P: Params): Layout {
33+ const { names } = orbitStems(P);
34+ const sounds = names.map((n) => soundOf(n, P.modalCustom as string));
35+ const hum = soundOf(P.humInstrument as string, P.humCustom as string, { voices: 1 });
36+ return {
37+ stems: [...sounds.map((sound, i) => ({ kind: "synth" as const, sound, output: i })), { kind: "synth", sound: hum, output: names.length }],
38+ outputs: [
39+ ...sounds.map((sound) => ({ effects: "shared" as const, sound, level: (Q: Params) => Q.notesLevel as number })),
40+ { effects: "own", sound: hum, level: (Q) => Q.humLevel as number },
41+ ],
42+ reverbTime: P.reverbTime as number,
43+ };
44+}
45+
46+export function estimateLength(P: Params): number {
47+ return (P.duration as number) + 0.5 + (P.finalHold as number) + (P.finalFade as number) + 0.3;
48+}
src/compositions/c02-orbits/piece.tsdeleted+0−418View file
@@ -1,418 +0,0 @@
1-// Composition 2: orbits.
2-//
3-// Several double pendulums at once, all steered along the same energy envelope from random
4-// starting states. Only the Poincaré section is shown: each orbit traces its crossings in its own
5-// color, and plays its own instrument (orbit n uses instrument slot n, cycling) in its own register.
6-// A hum follows the energy. Each orbit plays until it comes to rest; its last note rings out,
7-// and the piece ends when every orbit has rested and faded.
8-
9-import type { AudioEngine } from "../../core/audio.ts";
10-import { dbToGain } from "../../core/audio.ts";
11-import type { Piece } from "../../core/composition.ts";
12-import type { Params } from "../../core/params.ts";
13-import { mulberry32, randomSeed } from "../../core/rng.ts";
14-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
15-import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
16-import { midiToFreq } from "../../music/scales.ts";
17-import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
18-import { energyTarget } from "../shared/form.ts";
19-import { Hum } from "../shared/hum.ts";
20-import { noteFor } from "../shared/noteMap.ts";
21-import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
22-import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
23-import { orbitCapacity, type CapacityResult } from "./capacity.ts";
24-import { SLOTS } from "./schema.ts";
25-import { SharedReverb } from "../../instruments/reverb.ts";
26-import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
27-import type { NoteInstrumentFactory } from "../../instruments/types.ts";
28-
29-// rendered-ahead (worker) versions of the modal instruments
30-const STREAMED = streamedModalInstruments();
31-const STREAM_PREBUFFER = 0.4; // extra delay before the piece starts, so the renderers fill up
32-
33-const DT = 0.003; // simulation step (sim seconds)
34-const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
35-const TICK_MS = 25;
36-const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
37-
38-interface Crossing {
39- t: number; // piece time
40- th2: number; // wrapped
41- p2: number; // normalized
42-}
43-
44-interface Orbit {
45- index: number;
46- pend: DoublePendulum;
47- prev: number; // wrapped θ1 at the previous step
48- prevTh2: number;
49- prevP2: number;
50- points: Crossing[];
51- lastNote: { handle: NoteHandle; when: number } | null;
52- restAt: number | null;
53-}
54-
55-export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece {
56- view.classList.add("c02");
57- const canvas = document.createElement("canvas");
58- view.append(canvas);
59- const plot = new SectionPlot(canvas);
60- const hum = new Hum();
61- const portrait = new PortraitLayer(() => now(), () => playing);
62- const portraitSettings = (P: Params): PortraitSettings => ({
63- show: P.portrait as boolean,
64- count: P.portraitCount as number,
65- cpu: P.portraitCpu as number,
66- life: P.portraitLife as number,
67- band: P.portraitBand as number,
68- minHold: P.portraitMinHold as number,
69- maxPoints: P.portraitMaxPoints as number,
70- xfade: P.portraitXfade as number,
71- alpha: P.portraitAlpha as number,
72- size: P.portraitSize as number,
73- tracks: P.traces as boolean,
74- trackMax: P.traceMax as number,
75- trackAlpha: P.traceAlpha as number,
76- trackSize: P.traceSize as number,
77- });
78- const postPortrait = (running: boolean) => {
79- const P = params();
80- // each pendulum's current state, so the worker can trace the orbit it is on
81- const tracks = orbits.filter((o) => o.restAt === null).map((o) => ({ id: o.index, y: Array.from(o.pend.y) }));
82- portrait.post(running, portraitSettings(P), meanEnergy(), P.massRatio as number, P.lengthRatio as number, tracks);
83- };
84-
85- let orbits: Orbit[] = [];
86- let audio: AudioEngine | null = null;
87- let out: GainNode | null = null;
88- let noteBus: GainNode | null = null;
89- let instruments = new Map<string, NoteInstrument>(); // by instrument name (+ custom settings)
90- let reverb: SharedReverb | null = null; // one reverb for all the orbit instruments
91- let timer: number | undefined;
92- let playing = false;
93- let startToken = 0;
94- let pieceStart = 0;
95- let simPieceT = 0;
96- let seedUsed = 0;
97- let noteCount = 0;
98- let stoppedAt = 0;
99- let restAll: number | null = null; // piece time every orbit had come to rest
100- let stream = false; // instruments rendered ahead in workers (fixed per play)
101- let simAhead = LOOKAHEAD; // how far the simulation (and note scheduling) runs ahead
102- // device limit (measured on the first play, then cached)
103- let capacity: CapacityResult | null = null;
104- let checking = false;
105-
106- const piece: Piece = {
107- get playing() {
108- return playing;
109- },
110- start,
111- stop,
112- draw,
113- now,
114- length: () => endTime(params()),
115- readouts,
116- notice,
117- dispose() {
118- stop();
119- portrait.dispose();
120- view.classList.remove("c02");
121- view.replaceChildren();
122- },
123- };
124-
125- function now(): number {
126- if (!audio || !playing) return stoppedAt;
127- return audio.ctx.currentTime - pieceStart;
128- }
129-
130- // ── orbits ──
131-
132- function makeOrbit(P: Params, index: number, e: number): Orbit {
133- const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
134- pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1));
135- pend.tau = P.tau as number;
136- return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null };
137- }
138-
139- function wantedOrbits(P: Params): number {
140- return Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
141- }
142-
143- /** Orbits actually played: the setting, limited to what this device can handle. */
144- function playableOrbits(P: Params): number {
145- const want = wantedOrbits(P);
146- return P.deviceLimit && capacity ? Math.min(want, capacity.cap) : want;
147- }
148-
149- /** Match the number of orbits to the setting (new ones start at the current target energy). */
150- function syncOrbitCount(P: Params) {
151- const n = playableOrbits(P);
152- if (restAll !== null) return;
153- while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT))));
154- if (orbits.length > n) orbits.length = n;
155- }
156-
157- // ── instruments ──
158-
159- function slotOf(o: Orbit): number {
160- return o.index % SLOTS;
161- }
162-
163- function instrumentKey(P: Params, slot: number): { name: string; key: string } {
164- const name = P[`slot${slot + 1}Instrument`] as string;
165- return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name };
166- }
167-
168- function factory(name: string): NoteInstrumentFactory {
169- return (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
170- }
171-
172- /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */
173- function ensureInstruments() {
174- if (!audio || !out) return;
175- const P = params();
176- if (!noteBus) {
177- noteBus = audio.ctx.createGain();
178- noteBus.connect(out);
179- reverb = new SharedReverb(audio.ctx, noteBus, P.reverbTime as number);
180- }
181- noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
182- const wanted = new Map<string, string>();
183- for (const o of orbits) {
184- const { name, key } = instrumentKey(P, slotOf(o));
185- wanted.set(key, name);
186- }
187- for (const [key, inst] of instruments) {
188- if (!wanted.has(key)) {
189- inst.dispose();
190- instruments.delete(key);
191- }
192- }
193- for (const [key, name] of wanted) {
194- if (!instruments.has(key))
195- instruments.set(key, factory(name)(audio.ctx, noteBus, { custom: P.modalCustom as string, effects: { send: reverb!.input } }));
196- }
197- hum.ensure(audio.ctx, out, P, playing);
198- }
199-
200- // ── transport ──
201-
202- async function start(a: AudioEngine, offset: number) {
203- stop();
204- const token = ++startToken;
205- audio = a;
206- const P = params();
207- const ctx = a.ctx;
208- stream = !!P.streamAudio;
209- simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
210- if (P.deviceLimit) {
211- checking = true;
212- try {
213- capacity = await orbitCapacity(ctx, P, wantedOrbits(P), SLOTS, stream);
214- } finally {
215- checking = false;
216- }
217- if (token !== startToken) return; // stopped or restarted meanwhile
218- }
219- seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
220- simPieceT = 0;
221- restAll = null;
222- noteCount = 0;
223- orbits = [];
224- portrait.reset(); // the worker starts a fresh portrait
225- syncOrbitCount(P); // random starts at the starting energy, from the seed
226- if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
227-
228- out = ctx.createGain();
229- out.connect(a.input);
230- ensureInstruments();
231- await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]);
232- if (token !== startToken) return;
233- pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
234- hum.start(ctx, P);
235- playing = true;
236- tick();
237- timer = window.setInterval(tick, TICK_MS);
238- }
239-
240- function stop() {
241- startToken++;
242- if (timer !== undefined) window.clearInterval(timer);
243- timer = undefined;
244- const wasPlaying = playing;
245- if (playing) {
246- stoppedAt = now();
247- playing = false;
248- postPortrait(false);
249- }
250- if (!audio) return;
251- const t = audio.ctx.currentTime;
252- hum.release(audio.ctx, wasPlaying);
253- const o = out;
254- if (o) {
255- o.gain.setTargetAtTime(0, t, 0.05);
256- window.setTimeout(() => o.disconnect(), 600);
257- }
258- for (const inst of instruments.values()) inst.dispose();
259- instruments = new Map();
260- reverb?.dispose();
261- reverb = null;
262- noteBus = null;
263- out = null;
264- }
265-
266- // ── simulation ──
267-
268- function advanceTo(target: number, sound: boolean) {
269- const P = params();
270- const speed = P.speed as number;
271- const duration = P.duration as number;
272- const restE = P.restEnergy as number;
273- for (const o of orbits) {
274- o.pend.cfg.m2 = P.massRatio as number;
275- o.pend.cfg.l2 = P.lengthRatio as number;
276- o.pend.tau = P.tau as number;
277- }
278- while (simPieceT < target) {
279- const eT = energyTarget(P, simPieceT);
280- const t0 = simPieceT;
281- simPieceT += DT / speed;
282- for (const o of orbits) {
283- const pend = o.pend, y = pend.y;
284- pend.eTarget = eT * pend.vTop;
285- pend.step(DT);
286- const cur = wrapAngle(y[0]);
287- if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
288- const f = -o.prev / (cur - o.prev);
289- const c: Crossing = {
290- t: t0 + f * (simPieceT - t0),
291- th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)),
292- p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale,
293- };
294- o.points.push(c);
295- if (sound) playNote(o, c, P);
296- }
297- if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
298- o.restAt = simPieceT;
299- // let this orbit's last real note ring: sustain, then fade
300- if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number);
301- }
302- o.prev = cur;
303- o.prevTh2 = y[1];
304- o.prevP2 = y[3];
305- }
306- if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT;
307- }
308- }
309-
310- function playNote(o: Orbit, c: Crossing, P: Params) {
311- if (!audio) return;
312- const when = pieceStart + c.t;
313- if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
314- const slot = slotOf(o);
315- const inst = instruments.get(instrumentKey(P, slot).key);
316- if (!inst) return;
317- const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number);
318- const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number });
319- if (handle) o.lastNote = { handle, when };
320- noteCount++;
321- }
322-
323- /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */
324- function endTime(P: Params): number {
325- const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
326- return (restAll ?? (P.duration as number) + 0.5) + ring;
327- }
328-
329- function meanEnergy(): number {
330- if (!orbits.length) return 0;
331- return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length;
332- }
333-
334- function tick() {
335- if (!audio || !playing) return;
336- const P = params();
337- syncOrbitCount(P);
338- ensureInstruments();
339- const ctx = audio.ctx;
340- const t = ctx.currentTime - pieceStart;
341- const total = endTime(P);
342- if (restAll !== null && t >= total) {
343- stop();
344- stoppedAt = total;
345- piece.onEnded?.();
346- return;
347- }
348- advanceTo(t + simAhead, true);
349- // tell the renderers every note up to here has been sent
350- for (const inst of instruments.values()) inst.horizon?.(pieceStart + simPieceT);
351- postPortrait(true);
352- hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null);
353- }
354-
355- // ── drawing ──
356-
357- function colors(P: Params): string[] {
358- const list = String(P.colors)
359- .split(",")
360- .map((s) => s.trim())
361- .filter(Boolean);
362- return list.length ? list : [cssColor(view, "--fg")];
363- }
364-
365- function draw() {
366- const P = params();
367- const t = now();
368- const ref = orbits[0]?.pend ?? null;
369- const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null;
370- const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim"));
371- const fade = P.fade as number;
372- const size = P.pointSize as number;
373- const cols = colors(P);
374- portrait.draw(f, t, portraitSettings(P), cssColor(view, "--fg"), (id) => cols[id % cols.length]);
375- for (const o of orbits) {
376- let drop = 0;
377- while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++;
378- if (drop > 0) o.points.splice(0, drop);
379- const col = cols[o.index % cols.length];
380- for (const c of o.points) {
381- const age = t - c.t;
382- if (age < 0) break; // not sounded yet
383- drawCrossing(f, c.th2, c.p2, age, fade, size, col);
384- }
385- }
386- }
387-
388- function notice(): string | null {
389- if (checking) return "checking what this device can play…";
390- const P = params();
391- const want = wantedOrbits(P);
392- const n = playableOrbits(P);
393- return n < want ? `${n} of ${want} orbits: reduced to what this device can play live` : null;
394- }
395-
396- function readouts(): Record<string, string> {
397- const P = params();
398- const t = now();
399- return {
400- time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
401- "energy target": energyTarget(P, t).toFixed(4),
402- "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–",
403- notes: String(noteCount),
404- "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
405- "device limit": capacity ? `${capacity.cap} orbits (synth load ${(100 * capacity.load).toFixed(0)}% with ${capacity.at})` : "–",
406- instruments: String(instruments.size),
407- "audio load": stream
408- ? `renderers ${Math.round(100 * Math.max(0, ...[...instruments.values()].map((i) => i.load?.() ?? 0)))}% (busiest), ` +
409- `${[...instruments.values()].reduce((s, i) => s + (i.underruns?.() ?? 0), 0)} underruns; hum ${Math.round(100 * (hum.inst?.load?.() ?? 0))}%`
410- : `${Math.round(100 * ([...instruments.values()].reduce((s, i) => s + (i.load?.() ?? 0), 0) + (hum.inst?.load?.() ?? 0)))}%`,
411- "seed used": seedUsed ? String(seedUsed) : "–",
412- hum: hum.describe(),
413- portrait: portrait.describe(),
414- };
415- }
416-
417- return piece;
418-}
src/compositions/c02-orbits/schema.tsmodified+10−12View file
@@ -1,5 +1,5 @@
11 import type { ParamSpec } from "../../core/params.ts";
2-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
2+import { NOTE_SOUNDS } from "../../instruments/sounds.ts";
33 import { schema as c01 } from "../c01-poincare/schema.ts";
44
55 // Composition 2 shares most settings with composition 1 (same meanings and ranges).
@@ -9,7 +9,7 @@ const pick = (key: string, o: Partial<ParamSpec> = {}): ParamSpec => {
99 return { ...s, ...o } as ParamSpec;
1010 };
1111
12-export const SLOTS = 6;
12+import { SLOTS } from "./layout.ts";
1313 const SLOT_DEFAULTS: [string, number][] = [
1414 ["modal: Nylon harp", 0],
1515 ["modal: Marimba", -1],
@@ -30,28 +30,26 @@ export const schema: ParamSpec[] = [
3030 ...["massRatio", "lengthRatio", "tau", "seed"].map((k) => pick(k)),
3131
3232 // ── orbits ──
33- { group: "orbits", key: "streamAudio", label: "render ahead", kind: "bool", default: true, hint: "render each instrument in its own background thread, ~2 s ahead of playback (uses more cores, no glitches from momentary slowdowns); applies on the next play" },
34- { group: "orbits", key: "deviceLimit", label: "limit to device", kind: "bool", default: true, hint: "measure (once per device) how many orbits this device can play live, and play no more than that" },
3533 { 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" },
3634 {
3735 group: "orbits", key: "colors", label: "colors", kind: "text",
3836 default: "#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0",
39- hint: "comma-separated CSS colors; orbit n uses color n (cycling)",
37+ hint: "comma-separated CSS colors; orbit n uses color n (cycling)", live: true,
4038 },
4139 ...Array.from({ length: SLOTS }, (_, i): ParamSpec[] => [
4240 {
4341 group: "orbits", key: `slot${i + 1}Instrument`, label: `instrument ${i + 1}`, kind: "select",
44- default: SLOT_DEFAULTS[i][0], options: Object.keys(NOTE_INSTRUMENTS),
42+ default: SLOT_DEFAULTS[i][0], options: NOTE_SOUNDS,
4543 hint: `orbits ${i + 1}, ${i + 1 + SLOTS}, ${i + 1 + 2 * SLOTS}, … play this instrument`,
4644 },
4745 { group: "orbits", key: `slot${i + 1}Octave`, label: `octave ${i + 1}`, kind: "number", default: SLOT_DEFAULTS[i][1], min: -3, max: 3, step: 1, hint: "register shift for this instrument" },
4846 ]).flat(),
4947 pick("modalCustom", { group: "orbits", hint: "for “modal: custom” in any slot: paste JSON from modal-synth’s Copy button" }),
50- { group: "orbits", key: "reverbTime", label: "reverb time", kind: "number", default: 3.5, min: 0.3, max: 12, log: true, unit: "s", hint: "one reverb shared by all the orbit instruments (each sends its preset's reverb amount); applies on the next play" },
48+ { group: "orbits", key: "reverbTime", label: "reverb time", kind: "number", default: 3.5, min: 0.3, max: 12, log: true, unit: "s", hint: "one reverb shared by all the orbit instruments (each sends its preset's reverb amount)" },
5149
5250 // ── notes (one per crossing, per orbit) ──
5351 pick("scale", { default: "dorian" }),
54- ...["root", "pitchSource", "thetaRange", "pitchLow", "pitchHigh", "pitchCurve", "invertPitch", "p2Ref", "loudCurve", "loudFloor", "notesLevel", "noteLength", "panAmount"].map((k) => pick(k)),
52+ ...["root", "pitchSource", "thetaRange", "pitchLow", "pitchHigh", "pitchCurve", "invertPitch", "p2Ref", "loudCurve", "loudFloor", "notesLevel", "noteLength"].map((k) => pick(k)),
5553
5654 // ── hum ──
5755 ...c01.filter((s) => s.group === "hum"),
@@ -72,8 +70,8 @@ export const schema: ParamSpec[] = [
7270 pick("orbitXfade", { key: "portraitXfade", group: "portrait" }),
7371 pick("orbitAlpha", { key: "portraitAlpha", group: "portrait", default: 0.15 }),
7472 pick("orbitSize", { key: "portraitSize", group: "portrait" }),
75- { group: "portrait", key: "traces", label: "trace orbits", kind: "bool", default: true, hint: "with each portrait, follow every pendulum from its current state (energy frozen) and draw the orbit it's on, in its color" },
76- { group: "portrait", key: "traceMax", label: "trace length", kind: "number", default: 1500, min: 50, max: 10000, log: true, hint: "crossings computed per orbit trace" },
77- { group: "portrait", key: "traceAlpha", label: "trace brightness", kind: "number", default: 0.75, min: 0.02, max: 1, step: 0.01 },
78- { group: "portrait", key: "traceSize", label: "trace point size", kind: "number", default: 1.5, min: 0.5, max: 4, step: 0.1, unit: "px" },
73+ { group: "portrait", key: "traces", label: "trace orbits", kind: "bool", default: true, hint: "with each portrait, follow every pendulum from its current state (energy frozen) and draw the orbit it's on, in its color", live: true },
74+ { group: "portrait", key: "traceMax", label: "trace length", kind: "number", default: 1500, min: 50, max: 10000, log: true, hint: "crossings computed per orbit trace", live: true },
75+ { group: "portrait", key: "traceAlpha", label: "trace brightness", kind: "number", default: 0.75, min: 0.02, max: 1, step: 0.01, live: true },
76+ { group: "portrait", key: "traceSize", label: "trace point size", kind: "number", default: 1.5, min: 0.5, max: 4, step: 0.1, unit: "px", live: true },
7977 ];
src/compositions/c02-orbits/score.tsadded+121−0View file
@@ -0,0 +1,121 @@
1+// Composition 2: orbits — the score (score worker).
2+//
3+// Several double pendulums at once, all steered along the same energy envelope from random
4+// starting states. Each orbit's crossings play its own instrument (orbit n uses slot n, cycling)
5+// in its own register. A hum follows the energy. Each orbit plays until it comes to rest; its last
6+// note rings out, and the piece ends when every orbit has rested and faded.
7+//
8+// Drawing data: track 0 = [mean energy, max energy, then per orbit θ1, θ2, p1, p2, active]
9+// (30 per piece second, for the zoom and the portrait's traces); events "x" = crossings (o = orbit).
10+
11+import type { Params } from "../../core/params.ts";
12+import { mulberry32 } from "../../core/rng.ts";
13+import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
14+import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
15+import { energyTarget } from "../shared/form.ts";
16+import { HumScore } from "../shared/humScore.ts";
17+import { noteFor } from "../shared/noteMap.ts";
18+import { SLOTS, humStem, orbitCount, orbitStems } from "./layout.ts";
19+
20+const DT = 0.003; // simulation step (sim seconds)
21+const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
22+const FRAME_DT = 1 / 30;
23+const INFO_DT = 0.1;
24+
25+interface Orbit {
26+ pend: DoublePendulum;
27+ prev: number;
28+ prevTh2: number;
29+ prevP2: number;
30+ lastNote: NoteRef | null;
31+ restAt: number | null;
32+ stem: number;
33+ octave: number;
34+}
35+
36+export const orbitsScore: ScoreFactory = (P: Params, seed: number, sink) => {
37+ const speed = P.speed as number, duration = P.duration as number, restE = P.restEnergy as number;
38+ const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
39+ const { stemOf } = orbitStems(P);
40+ const hum = new HumScore(P, humStem(P), sink);
41+ const e0 = Math.max(1e-4, energyTarget(P, 0));
42+ const orbits: Orbit[] = Array.from({ length: orbitCount(P) }, (_, i) => {
43+ const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
44+ pend.randomize(e0, mulberry32(seed * 1009 + i * 7919 + 1));
45+ pend.tau = P.tau as number;
46+ return { pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], lastNote: null, restAt: null, stem: stemOf[i], octave: P[`slot${(i % SLOTS) + 1}Octave`] as number };
47+ });
48+
49+ let time = 0;
50+ let restAll: number | null = null;
51+ let notes = 0;
52+ let nextFrame = 0, nextInfo = 0;
53+ const row: number[] = [];
54+
55+ function step() {
56+ const eT = energyTarget(P, time);
57+ const t0 = time;
58+ time += DT / speed;
59+ orbits.forEach((o, i) => {
60+ const pend = o.pend, y = pend.y;
61+ pend.eTarget = eT * pend.vTop;
62+ pend.step(DT);
63+ const cur = wrapAngle(y[0]);
64+ if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
65+ const f = -o.prev / (cur - o.prev);
66+ const tc = t0 + f * (time - t0);
67+ const th2 = wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2));
68+ const p2 = (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale;
69+ sink.event({ t: tc, kind: "x", o: i, th2, p2 });
70+ const { midi, velocity } = noteFor(P, th2, p2, o.octave);
71+ o.lastNote = sink.note(o.stem, tc, midi, velocity, P.noteLength as number) ?? o.lastNote;
72+ notes++;
73+ }
74+ if (o.restAt === null && time >= duration && (pend.energyNorm() < restE || time >= duration + MAX_SETTLE)) {
75+ o.restAt = time;
76+ // this orbit's last real note rings: sustain, then fade
77+ if (o.lastNote) sink.hold(o.lastNote, o.lastNote.t, P.finalHold as number, P.finalFade as number);
78+ }
79+ o.prev = cur;
80+ o.prevTh2 = y[1];
81+ o.prevP2 = y[3];
82+ });
83+ if (restAll === null && orbits.every((o) => o.restAt !== null)) {
84+ restAll = time;
85+ sink.end(time + ring);
86+ }
87+ let sum = 0, max = 0;
88+ for (const o of orbits) {
89+ const e = o.pend.energyNorm();
90+ sum += e;
91+ max = Math.max(max, e);
92+ }
93+ const mean = sum / orbits.length;
94+ hum.update(time, mean, restAll !== null ? restAll + ring : null);
95+ if (time >= nextFrame) {
96+ nextFrame = time + FRAME_DT;
97+ row.length = 0;
98+ row.push(mean, max);
99+ for (const o of orbits) row.push(o.pend.y[0], o.pend.y[1], o.pend.y[2], o.pend.y[3], o.restAt === null ? 1 : 0);
100+ sink.frame(0, time, row);
101+ }
102+ if (time >= nextInfo) {
103+ nextInfo = time + INFO_DT;
104+ sink.info(time, {
105+ "energy target": eT.toFixed(4),
106+ "energy (mean)": mean.toFixed(4),
107+ notes: String(notes),
108+ "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
109+ });
110+ }
111+ }
112+
113+ return {
114+ get time() {
115+ return time;
116+ },
117+ advance(t: number) {
118+ while (time < t) step();
119+ },
120+ };
121+};
src/compositions/c02-orbits/view.tsadded+85−0View file
@@ -0,0 +1,85 @@
1+// Composition 2: orbits — drawing at the playhead: the Poincaré section, each orbit's crossings in
2+// its own color, over a background portrait at the current energy (with each orbit's trace).
3+
4+import type { Params } from "../../core/params.ts";
5+import type { FrameStore } from "../../stream/frames.ts";
6+import type { View } from "../../stream/piece.ts";
7+import { vTopOf } from "../c01-poincare/view.ts";
8+import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
9+import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
10+import { orbitCount } from "./layout.ts";
11+
12+const PORTRAIT_POST_MS = 50;
13+
14+export function orbitsView(el: HTMLElement, params: () => Params): View {
15+ el.classList.add("c02");
16+ const canvas = document.createElement("canvas");
17+ el.append(canvas);
18+ const plot = new SectionPlot(canvas);
19+ let now = 0, moving = false;
20+ const portrait = new PortraitLayer(() => now, () => moving);
21+ const settings = (P: Params): PortraitSettings => ({
22+ show: P.portrait as boolean,
23+ count: P.portraitCount as number,
24+ cpu: P.portraitCpu as number,
25+ life: P.portraitLife as number,
26+ band: P.portraitBand as number,
27+ minHold: P.portraitMinHold as number,
28+ maxPoints: P.portraitMaxPoints as number,
29+ xfade: P.portraitXfade as number,
30+ alpha: P.portraitAlpha as number,
31+ size: P.portraitSize as number,
32+ tracks: P.traces as boolean,
33+ trackMax: P.traceMax as number,
34+ trackAlpha: P.traceAlpha as number,
35+ trackSize: P.traceSize as number,
36+ });
37+ const colors = (P: Params): string[] => {
38+ const list = String(P.colors).split(",").map((s) => s.trim()).filter(Boolean);
39+ return list.length ? list : [cssColor(el, "--fg")];
40+ };
41+ let row = new Float64Array(2);
42+ let lastStore: FrameStore | null = null;
43+ let lastPost = 0;
44+
45+ return {
46+ keep: (P) => 4.6 * (P.fade as number) + 0.5,
47+ draw(t, store, playing) {
48+ const P = params();
49+ now = t;
50+ moving = playing;
51+ if (store !== lastStore) {
52+ lastStore = store;
53+ portrait.reset();
54+ }
55+ const n = orbitCount(P);
56+ if (row.length !== 2 + 5 * n) row = new Float64Array(2 + 5 * n);
57+ const s = store?.at(0, t, row) ?? null;
58+ const m2 = P.massRatio as number, l2 = P.lengthRatio as number;
59+ const wall = performance.now();
60+ if (wall - lastPost > PORTRAIT_POST_MS) {
61+ lastPost = wall;
62+ // each active orbit's state, so the portrait worker can trace the orbit it is on
63+ const tracks = [];
64+ if (s) for (let i = 0; i < n; i++) if (s[2 + 5 * i + 4] > 0.5) tracks.push({ id: i, y: [s[2 + 5 * i], s[3 + 5 * i], s[4 + 5 * i], s[5 + 5 * i]] });
65+ portrait.post(playing, settings(P), s ? s[0] : 0, m2, l2, tracks);
66+ }
67+ const f = plot.begin(P, s ? s[1] : null, { m1: 1, l1: 1, g: 1, m2, l2 }, vTopOf(m2, l2), cssColor(el, "--dim"));
68+ const cols = colors(P);
69+ portrait.draw(f, t, settings(P), cssColor(el, "--fg"), (id) => cols[id % cols.length]);
70+ if (store) {
71+ const fade = P.fade as number, size = P.pointSize as number;
72+ for (const c of store.events) {
73+ const age = t - c.t;
74+ if (age < 0) break; // not sounded yet
75+ drawCrossing(f, c.th2 as number, c.p2 as number, age, fade, size, cols[(c.o as number) % cols.length]);
76+ }
77+ }
78+ },
79+ readouts: () => ({ portrait: portrait.describe() }),
80+ dispose() {
81+ portrait.dispose();
82+ el.classList.remove("c02");
83+ },
84+ };
85+}
src/compositions/c03-divergence/defaults.jsonmodified+0−1View file
@@ -30,7 +30,6 @@
3030 "noteLength": 2,
3131 "directionPan": 0.35,
3232 "reverbTime": 3.5,
33- "streamAudio": true,
3433 "trails": true,
3534 "trailLength": 3,
3635 "trailWidth": 1.2,
src/compositions/c03-divergence/index.tsmodified+7−3View file
@@ -1,12 +1,16 @@
11 import type { Composition } from "../../core/composition.ts";
2+import { createStreamPiece, type StreamDef } from "../../stream/piece.ts";
23 import defaults from "./defaults.json";
3-import { createDivergencePiece } from "./piece.ts";
4+import { estimateLength, layout } from "./layout.ts";
45 import { schema } from "./schema.ts";
6+import { divergenceView } from "./view.ts";
7+
8+const def: StreamDef = { id: "03-divergence", schema, layout, estimateLength, view: divergenceView };
59
610 export const divergence: Composition = {
7- id: "03-divergence",
11+ id: def.id,
812 title: "divergence",
913 schema,
1014 defaults,
11- create: createDivergencePiece,
15+ create: (view, params) => createStreamPiece(def, view, params),
1216 };
src/compositions/c03-divergence/layout.tsadded+25−0View file
@@ -0,0 +1,25 @@
1+import type { Params } from "../../core/params.ts";
2+import { soundOf } from "../../instruments/sounds.ts";
3+import type { Layout } from "../../stream/layout.ts";
4+
5+/** Stems: two copies of the instrument, panned apart: 0 notes moving left, 1 moving right. */
6+export const LEFT = 0, RIGHT = 1;
7+
8+export function layout(P: Params): Layout {
9+ const sound = soundOf(P.instrument as string, P.modalCustom as string);
10+ return {
11+ stems: [
12+ { kind: "synth", sound, output: LEFT },
13+ { kind: "synth", sound, output: RIGHT },
14+ ],
15+ outputs: [
16+ { effects: "shared", sound, level: (Q) => Q.notesLevel as number, pan: (Q) => -(Q.directionPan as number) },
17+ { effects: "shared", sound, level: (Q) => Q.notesLevel as number, pan: (Q) => Q.directionPan as number },
18+ ],
19+ reverbTime: P.reverbTime as number,
20+ };
21+}
22+
23+export function estimateLength(P: Params): number {
24+ return (P.freeTime as number) + (P.dampTime as number) + 1 + (P.finalHold as number) + (P.finalFade as number) + 0.3;
25+}
src/compositions/c03-divergence/piece.tsdeleted+0−456View file
@@ -1,456 +0,0 @@
1-// Composition 3: divergence.
2-//
3-// N double pendulums released together from rest at a wide angle, each outer arm offset by a tiny,
4-// calibrated amount, so they swing as one and then visibly separate at about `separateAt` seconds,
5-// and chaos takes over. Only the pendulums are shown, drawn from one pivot, with trails.
6-// A note sounds whenever a bottom bob crosses the vertical through the pivot (either direction):
7-// in "chord" mode each pendulum has its own note of a chord, so the opening is one chord that
8-// breaks into arpeggios; in "motion" mode the pitch follows the bob's speed. Notes are panned
9-// toward the side the bob is heading. After `freeTime` the pendulums are damped to rest over
10-// `dampTime`; each one's last note rings out and the piece ends with the fade.
11-
12-import type { AudioEngine } from "../../core/audio.ts";
13-import { dbToGain } from "../../core/audio.ts";
14-import type { Piece } from "../../core/composition.ts";
15-import type { Params } from "../../core/params.ts";
16-import { mulberry32, randomSeed } from "../../core/rng.ts";
17-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
18-import { SharedReverb } from "../../instruments/reverb.ts";
19-import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
20-import type { NoteHandle, NoteInstrument, NoteInstrumentFactory } from "../../instruments/types.ts";
21-import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
22-import type { DoublePendulum, PendulumConfig } from "../../physics/doublePendulum.ts";
23-import { cssColor, fitCanvas } from "../shared/section.ts";
24-import { DT, bob, offsetForSeparation, released } from "./release.ts";
25-
26-const STREAMED = streamedModalInstruments();
27-const LOOKAHEAD = 0.15;
28-const STREAM_PREBUFFER = 0.4;
29-const TICK_MS = 25;
30-const MAX_SETTLE = 10; // s after the damping: count every pendulum as at rest regardless
31-const HISTORY_DT = 1 / 120; // piece-time spacing of stored states (drawing and trails)
32-
33-interface Pend {
34- index: number;
35- p: DoublePendulum;
36- prevX: number; // bottom bob's x at the previous step
37- E0: number; // energy when the damping began
38- lastNote: { handle: NoteHandle; when: number } | null;
39- restAt: number | null;
40-}
41-
42-interface Snapshot {
43- t: number;
44- s: Float64Array; // [θ1, θ2] per pendulum
45-}
46-
47-export function createDivergencePiece(view: HTMLElement, params: () => Params): Piece {
48- view.classList.add("c03");
49- const canvas = document.createElement("canvas");
50- view.append(canvas);
51-
52- let pends: Pend[] = [];
53- let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
54- let history: Snapshot[] = [];
55- let lastHistT = -Infinity;
56- let audio: AudioEngine | null = null;
57- let out: GainNode | null = null;
58- let noteBus: GainNode | null = null;
59- let reverb: SharedReverb | null = null;
60- let panL: StereoPannerNode | null = null;
61- let panR: StereoPannerNode | null = null;
62- let instL: NoteInstrument | null = null; // notes moving left
63- let instR: NoteInstrument | null = null; // notes moving right
64- let instKey = "";
65- let timer: number | undefined;
66- let playing = false;
67- let startToken = 0;
68- let pieceStart = 0;
69- let simPieceT = 0;
70- let seedUsed = 0;
71- let noteCount = 0;
72- let stoppedAt = 0;
73- let restAll: number | null = null;
74- let stream = false;
75- let simAhead = LOOKAHEAD;
76- let vmax0 = 1; // fastest possible bob speed at the release energy
77- let release = { th1: 0, th2: 0, offset: 0, separatesAt: 0 };
78-
79- const piece: Piece = {
80- get playing() {
81- return playing;
82- },
83- start,
84- stop,
85- draw,
86- now,
87- length: () => endTime(params()),
88- readouts,
89- dispose() {
90- stop();
91- view.classList.remove("c03");
92- view.replaceChildren();
93- },
94- };
95-
96- function now(): number {
97- if (!audio || !playing) return stoppedAt;
98- return audio.ctx.currentTime - pieceStart;
99- }
100-
101- // ── release ──
102-
103- function makePendulums(P: Params, rand: () => number | null) {
104- cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
105- const deg = Math.PI / 180;
106- const base = (P.releaseAngle as number) * deg;
107- const j = (P.jitter as number) * deg;
108- const r = rand();
109- const th1 = r === null ? base : base + (2 * r - 1) * j;
110- const r2 = rand();
111- const th2 = r2 === null ? base : base + (2 * r2 - 1) * j;
112- const speed = P.speed as number;
113- const cal = offsetForSeparation(cfg, th1, th2, (P.separateAt as number) * speed, (P.sepThreshold as number) * (cfg.l1 + cfg.l2));
114- release = { th1, th2, offset: cal.offset, separatesAt: cal.separatesAt / speed };
115- const n = Math.max(1, Math.round(P.count as number));
116- pends = [];
117- for (let i = 0; i < n; i++) {
118- const d = n > 1 ? (i / (n - 1) - 0.5) * cal.offset : 0;
119- const p = released(cfg, th1, th2, d);
120- pends.push({ index: i, p, prevX: bob(cfg, p.y)[0], E0: 0, lastNote: null, restAt: null });
121- }
122- vmax0 = Math.sqrt((2 * pends[0].p.energy()) / cfg.m2);
123- history = [];
124- lastHistT = -Infinity;
125- pushHistory(0);
126- }
127-
128- // ── instruments ──
129-
130- function factory(name: string): NoteInstrumentFactory {
131- return (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
132- }
133-
134- /** Two copies of the instrument, panned left and right: a note goes to the side its bob is heading. */
135- function ensureInstruments() {
136- if (!audio || !out) return;
137- const P = params();
138- const ctx = audio.ctx;
139- if (!noteBus) {
140- noteBus = ctx.createGain();
141- noteBus.connect(out);
142- reverb = new SharedReverb(ctx, noteBus, P.reverbTime as number);
143- panL = ctx.createStereoPanner();
144- panR = ctx.createStereoPanner();
145- panL.connect(noteBus);
146- panR.connect(noteBus);
147- }
148- noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
149- const pan = P.directionPan as number;
150- panL!.pan.setTargetAtTime(-pan, ctx.currentTime, 0.05);
151- panR!.pan.setTargetAtTime(pan, ctx.currentTime, 0.05);
152- const name = P.instrument as string;
153- const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
154- if (instL && instKey === key) return;
155- instL?.dispose();
156- instR?.dispose();
157- instKey = key;
158- const opts = { custom: P.modalCustom as string, effects: { send: reverb!.input } };
159- instL = factory(name)(ctx, panL!, opts);
160- instR = factory(name)(ctx, panR!, opts);
161- }
162-
163- // ── transport ──
164-
165- async function start(a: AudioEngine, offset: number) {
166- stop();
167- const token = ++startToken;
168- audio = a;
169- const P = params();
170- const ctx = a.ctx;
171- seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
172- const rng = mulberry32(seedUsed);
173- makePendulums(P, () => rng());
174- simPieceT = 0;
175- restAll = null;
176- noteCount = 0;
177- stream = !!P.streamAudio;
178- simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
179- if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
180-
181- out = ctx.createGain();
182- out.connect(a.input);
183- ensureInstruments();
184- await Promise.all([instL?.ready, instR?.ready]);
185- if (token !== startToken) return;
186- pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
187- playing = true;
188- tick();
189- timer = window.setInterval(tick, TICK_MS);
190- }
191-
192- function stop() {
193- startToken++;
194- if (timer !== undefined) window.clearInterval(timer);
195- timer = undefined;
196- if (playing) {
197- stoppedAt = now();
198- playing = false;
199- }
200- if (!audio) return;
201- const t = audio.ctx.currentTime;
202- const o = out;
203- if (o) {
204- o.gain.setTargetAtTime(0, t, 0.05);
205- window.setTimeout(() => o.disconnect(), 600);
206- }
207- instL?.dispose();
208- instR?.dispose();
209- instL = instR = null;
210- instKey = "";
211- reverb?.dispose();
212- reverb = null;
213- noteBus = panL = panR = null;
214- out = null;
215- }
216-
217- // ── simulation ──
218-
219- function pushHistory(t: number) {
220- const s = new Float64Array(2 * pends.length);
221- for (let i = 0; i < pends.length; i++) {
222- s[2 * i] = pends[i].p.y[0];
223- s[2 * i + 1] = pends[i].p.y[1];
224- }
225- history.push({ t, s });
226- lastHistT = t;
227- }
228-
229- function advanceTo(target: number, sound: boolean) {
230- const P = params();
231- const speed = P.speed as number;
232- const free = P.freeTime as number, damp = P.dampTime as number;
233- const curve = P.dampCurve as number, tau = P.tau as number;
234- const restE = P.restEnergy as number;
235- while (simPieceT < target) {
236- const t0 = simPieceT;
237- simPieceT += DT / speed;
238- const u = (t0 - free) / damp; // damping progress (< 0: free swinging)
239- for (const d of pends) {
240- const p = d.p;
241- if (u >= 0) {
242- if (!p.controlled) {
243- p.controlled = true;
244- d.E0 = p.energy();
245- }
246- p.tau = tau;
247- p.eTarget = u < 1 ? d.E0 * Math.pow(1 - u, curve) : 0;
248- // the energy controller fades out near zero energy; real friction settles the last of it
249- p.damping = u >= 1 ? 1 / tau : 0;
250- }
251- p.step(DT);
252- const x = bob(cfg, p.y)[0];
253- if (d.restAt === null && ((d.prevX < 0 && x >= 0) || (d.prevX > 0 && x <= 0))) {
254- const f = d.prevX / (d.prevX - x);
255- const tc = t0 + f * (simPieceT - t0);
256- if (sound) playNote(d, tc, x > d.prevX ? 1 : -1, P);
257- }
258- d.prevX = x;
259- if (d.restAt === null && u >= 1 && (p.energyNorm() < restE || simPieceT >= free + damp + MAX_SETTLE)) {
260- d.restAt = simPieceT;
261- if (sound && d.lastNote) d.lastNote.handle.hold(d.lastNote.when, P.finalHold as number, P.finalFade as number);
262- }
263- }
264- if (restAll === null && pends.every((d) => d.restAt !== null)) restAll = simPieceT;
265- if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
266- }
267- }
268-
269- /**
270- * The chord pitches per pendulum, low to high, from the scale's notes in range (an even spread
271- * if continuous). With two chords, 2n notes are spread over the range and alternate between
272- * them: left-to-right crossings play one, right-to-left the other (its neighbour above).
273- */
274- function chords(P: Params, n: number): { right: number[]; left: number[] } {
275- const low = P.pitchLow as number, high = P.pitchHigh as number;
276- const root = NOTE_NAMES.indexOf(P.root as string);
277- const two = !!P.directionChords;
278- const k = two ? 2 * n : n;
279- let notes: number[] = [];
280- if (P.scale === "continuous") notes = Array.from({ length: Math.max(k, 2) }, (_, i) => low + ((high - low) * i) / Math.max(1, Math.max(k, 2) - 1));
281- else for (let m = Math.ceil(low); m <= high; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) notes.push(m);
282- if (!notes.length) notes = [quantize((low + high) / 2, P.scale as string, root)];
283- const spread = Array.from({ length: k }, (_, i) => notes[k > 1 ? Math.round((i * (notes.length - 1)) / (k - 1)) : Math.floor(notes.length / 2)]);
284- if (!two) return { right: spread, left: spread };
285- return { right: spread.filter((_, i) => i % 2 === 0), left: spread.filter((_, i) => i % 2 === 1) };
286- }
287-
288- function playNote(d: Pend, tc: number, dir: number, P: Params) {
289- if (!audio) return;
290- const when = pieceStart + tc;
291- if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
292- const inst = dir > 0 ? instR : instL;
293- if (!inst) return;
294- // bottom bob's speed at the crossing
295- const y = d.p.y, w = d.p.derived();
296- const vx = cfg.l1 * Math.cos(y[0]) * w.w1 + cfg.l2 * Math.cos(y[1]) * w.w2;
297- const vy = cfg.l1 * Math.sin(y[0]) * w.w1 + cfg.l2 * Math.sin(y[1]) * w.w2;
298- const x = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax0));
299- const floor = P.loudFloor as number;
300- const velocity = floor + (1 - floor) * Math.pow(x, P.loudCurve as number);
301- const midi =
302- P.pitchMode === "motion"
303- ? quantize((P.pitchLow as number) + ((P.pitchHigh as number) - (P.pitchLow as number)) * x, P.scale as string, NOTE_NAMES.indexOf(P.root as string))
304- : chords(P, pends.length)[dir > 0 ? "right" : "left"][d.index];
305- const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.noteLength as number });
306- if (handle) d.lastNote = { handle, when };
307- noteCount++;
308- }
309-
310- function endTime(P: Params): number {
311- const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
312- return (restAll ?? (P.freeTime as number) + (P.dampTime as number) + 1) + ring;
313- }
314-
315- function tick() {
316- if (!audio || !playing) return;
317- const P = params();
318- ensureInstruments();
319- const t = audio.ctx.currentTime - pieceStart;
320- const total = endTime(P);
321- if (restAll !== null && t >= total) {
322- stop();
323- stoppedAt = total;
324- piece.onEnded?.();
325- return;
326- }
327- advanceTo(t + simAhead, true);
328- for (const inst of [instL, instR]) inst?.horizon?.(pieceStart + simPieceT);
329- // keep the states drawing and trails still need
330- const keep = t - (P.trailLength as number) - 0.5;
331- let i = 0;
332- while (i < history.length - 2 && history[i + 1].t < keep) i++;
333- if (i > 0) history.splice(0, i);
334- }
335-
336- // ── drawing ──
337-
338- function colorOf(P: Params, i: number, n: number): string {
339- const hue = (30 + (360 * i) / Math.max(1, n)) % 360;
340- return `hsl(${hue.toFixed(0)} ${P.saturation}% 70%)`;
341- }
342-
343- /** States at piece time t, interpolated between stored snapshots. */
344- function statesAt(t: number): Float64Array | null {
345- const n = history.length;
346- if (!n) return null;
347- if (t <= history[0].t) return history[0].s;
348- if (t >= history[n - 1].t) return history[n - 1].s;
349- let lo = 0, hi = n - 1;
350- while (hi - lo > 1) {
351- const mid = (lo + hi) >> 1;
352- if (history[mid].t <= t) lo = mid;
353- else hi = mid;
354- }
355- const a = history[lo], b = history[hi];
356- const f = (t - a.t) / (b.t - a.t);
357- const s = new Float64Array(a.s.length);
358- for (let k = 0; k < s.length; k++) s[k] = a.s[k] + f * (b.s[k] - a.s[k]);
359- return s;
360- }
361-
362- function draw() {
363- const P = params();
364- const t = now();
365- const g = fitCanvas(canvas);
366- const w = canvas.clientWidth, h = canvas.clientHeight;
367- g.clearRect(0, 0, w, h);
368- if (!pends.length) makePendulums(P, () => null); // preview at the nominal release
369- const n = pends.length;
370- const l1 = cfg.l1, l2 = cfg.l2;
371- const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
372- const x0 = w / 2, y0 = h / 2;
373- const px = (th1: number, th2: number): [number, number, number, number] => {
374- const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
375- return [x1, y1, x1 + scale * l2 * Math.sin(th2), y1 + scale * l2 * Math.cos(th2)];
376- };
377-
378- // trails: the bottom bobs' recent paths, fading with age (drawn in a few alpha bands)
379- if (P.trails && history.length > 1) {
380- const len = P.trailLength as number;
381- const BANDS = 6;
382- g.lineWidth = P.trailWidth as number;
383- g.lineJoin = g.lineCap = "round";
384- for (let i = 0; i < n; i++) {
385- g.strokeStyle = colorOf(P, i, n);
386- for (let band = 0; band < BANDS; band++) {
387- const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
388- g.globalAlpha = 0.7 * (1 - (band + 0.5) / BANDS);
389- g.beginPath();
390- let started = false;
391- for (const hs of history) {
392- if (hs.t < aOld - HISTORY_DT || hs.t > aNew + HISTORY_DT) continue;
393- if (hs.t > t) break;
394- const [, , bx, by] = px(hs.s[2 * i], hs.s[2 * i + 1]);
395- if (started) g.lineTo(bx, by);
396- else g.moveTo(bx, by), (started = true);
397- }
398- g.stroke();
399- }
400- }
401- g.globalAlpha = 1;
402- }
403-
404- // pendulums, all from the one pivot
405- const s = statesAt(t);
406- g.lineWidth = 1.5;
407- g.lineCap = "round";
408- const r = P.bobSize as number;
409- for (let i = n - 1; i >= 0; i--) {
410- const th1 = s ? s[2 * i] : pends[i].p.y[0], th2 = s ? s[2 * i + 1] : pends[i].p.y[1];
411- const [x1, y1, x2, y2] = px(th1, th2);
412- const col = colorOf(P, i, n);
413- g.strokeStyle = col;
414- g.fillStyle = col;
415- g.globalAlpha = P.armAlpha as number;
416- g.beginPath();
417- g.moveTo(x0, y0);
418- g.lineTo(x1, y1);
419- g.lineTo(x2, y2);
420- g.stroke();
421- g.globalAlpha = 1;
422- g.beginPath();
423- g.arc(x1, y1, r * 0.8, 0, 2 * Math.PI);
424- g.moveTo(x2 + r, y2);
425- g.arc(x2, y2, r, 0, 2 * Math.PI);
426- g.fill();
427- }
428- g.fillStyle = cssColor(view, "--fg");
429- g.beginPath();
430- g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
431- g.fill();
432- }
433-
434- function readouts(): Record<string, string> {
435- const P = params();
436- const t = now();
437- const free = P.freeTime as number, damp = P.dampTime as number;
438- const phase = restAll !== null && simPieceT >= restAll ? "at rest" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
439- const deg = 180 / Math.PI;
440- const loads = [instL, instR].map((i) => i?.load?.() ?? 0);
441- const under = [instL, instR].reduce((s, i) => s + (i?.underruns?.() ?? 0), 0);
442- return {
443- time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
444- phase,
445- "energy (mean)": pends.length ? (pends.reduce((s, d) => s + d.p.energyNorm(), 0) / pends.length).toFixed(4) : "–",
446- notes: String(noteCount),
447- release: `${(release.th1 * deg).toFixed(2)}°, ${(release.th2 * deg).toFixed(2)}°`,
448- "offset (outermost)": `${release.offset.toExponential(2)} rad → separate at ${release.separatesAt.toFixed(1)} s`,
449- "seed used": seedUsed ? String(seedUsed) : "–",
450- "at rest": `${pends.filter((d) => d.restAt !== null).length} / ${pends.length}`,
451- "audio load": stream ? `renderers ${Math.round(100 * Math.max(...loads))}% (busiest), ${under} underruns` : `${Math.round(100 * (loads[0] + loads[1]))}%`,
452- };
453- }
454-
455- return piece;
456-}
src/compositions/c03-divergence/release.tsmodified+3−2View file
@@ -1,4 +1,5 @@
11 // Release states and the offset that makes the pendulums separate at a chosen time.
2+import { cos, hypot, sin } from "../../physics/dmath.ts";
23 import { DoublePendulum, type PendulumConfig } from "../../physics/doublePendulum.ts";
34
45 export const DT = 0.002; // simulation step (sim seconds), shared with the piece
@@ -16,7 +17,7 @@ export function released(cfg: PendulumConfig, th1: number, th2: number, d: numbe
1617
1718 /** Bottom-bob position. */
1819 export function bob(cfg: PendulumConfig, y: ArrayLike<number>): [number, number] {
19- return [cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]), cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1])];
20+ return [cfg.l1 * sin(y[0]) + cfg.l2 * sin(y[1]), cfg.l1 * cos(y[0]) + cfg.l2 * cos(y[1])];
2021 }
2122
2223 /** Sim time at which two pendulums offset by ±d/2 first have their bobs `thr` apart (Infinity if not by maxT). */
@@ -27,7 +28,7 @@ function separationTime(cfg: PendulumConfig, th1: number, th2: number, d: number
2728 a.step(DT);
2829 b.step(DT);
2930 const [ax, ay] = bob(cfg, a.y), [bx, by] = bob(cfg, b.y);
30- if (Math.hypot(ax - bx, ay - by) > thr) return t + DT;
31+ if (hypot(ax - bx, ay - by) > thr) return t + DT;
3132 }
3233 return Infinity;
3334 }
src/compositions/c03-divergence/schema.tsmodified+11−12View file
@@ -1,5 +1,5 @@
11 import type { ParamSpec } from "../../core/params.ts";
2-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
2+import { NOTE_SOUNDS } from "../../instruments/sounds.ts";
33 import { schema as c01 } from "../c01-poincare/schema.ts";
44
55 const pick = (key: string, o: Partial<ParamSpec> = {}): ParamSpec => {
@@ -30,7 +30,7 @@ export const schema: ParamSpec[] = [
3030 pick("seed", { group: "pendulums", hint: "0 = a different release every play" }),
3131
3232 // ── notes: one per crossing of the vertical by a bottom bob ──
33- { group: "notes", key: "instrument", label: "instrument", kind: "select", default: "modal: Vibraphone", options: Object.keys(NOTE_INSTRUMENTS) },
33+ { group: "notes", key: "instrument", label: "instrument", kind: "select", default: "modal: Vibraphone", options: NOTE_SOUNDS },
3434 pick("modalCustom"),
3535 { 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" },
3636 { group: "notes", key: "directionChords", label: "two chords", kind: "bool", default: true, hint: "chord mode: left-to-right and right-to-left crossings play two interleaved chords, so the swings alternate between them" },
@@ -41,17 +41,16 @@ export const schema: ParamSpec[] = [
4141 { group: "notes", key: "loudRef", label: "speed for full", kind: "number", default: 0.6, min: 0.05, max: 1, step: 0.01, hint: "bob speed (fraction of the fastest possible at release energy) that gives full loudness (and top pitch in motion mode)" },
4242 pick("loudCurve"),
4343 pick("loudFloor"),
44- pick("notesLevel", { default: -8 }),
44+ pick("notesLevel", { default: -8, live: true }),
4545 pick("noteLength", { default: 2 }),
46- { group: "notes", key: "directionPan", label: "pan with direction", kind: "number", default: 0.35, min: 0, max: 1, step: 0.01, hint: "a crossing is panned toward the side the bob is heading" },
47- { group: "notes", key: "reverbTime", label: "reverb time", kind: "number", default: 3.5, min: 0.3, max: 12, log: true, unit: "s", hint: "applies on the next play" },
48- { group: "notes", key: "streamAudio", label: "render ahead", kind: "bool", default: true, hint: "render the instrument in a background thread, ~2 s ahead (applies on the next play)" },
46+ { group: "notes", key: "directionPan", label: "pan with direction", kind: "number", default: 0.35, min: 0, max: 1, step: 0.01, hint: "a crossing is panned toward the side the bob is heading", live: true },
47+ { group: "notes", key: "reverbTime", label: "reverb time", kind: "number", default: 3.5, min: 0.3, max: 12, log: true, unit: "s" },
4948
5049 // ── visual ──
51- { group: "visual", key: "trails", label: "trails", kind: "bool", default: true },
52- { group: "visual", key: "trailLength", label: "trail length", kind: "number", default: 3, min: 0.2, max: 20, log: true, unit: "s" },
53- { group: "visual", key: "trailWidth", label: "trail width", kind: "number", default: 1.2, min: 0.3, max: 5, step: 0.1, unit: "px" },
54- { group: "visual", key: "armAlpha", label: "arm opacity", kind: "number", default: 0.75, min: 0.05, max: 1, step: 0.01 },
55- { group: "visual", key: "bobSize", label: "bob size", kind: "number", default: 3, min: 0.5, max: 10, step: 0.1, unit: "px" },
56- { group: "visual", key: "saturation", label: "color saturation", kind: "number", default: 35, min: 0, max: 100, step: 1, unit: "%" },
50+ { group: "visual", key: "trails", label: "trails", kind: "bool", default: true, live: true },
51+ { group: "visual", key: "trailLength", label: "trail length", kind: "number", default: 3, min: 0.2, max: 20, log: true, unit: "s", live: true },
52+ { group: "visual", key: "trailWidth", label: "trail width", kind: "number", default: 1.2, min: 0.3, max: 5, step: 0.1, unit: "px", live: true },
53+ { group: "visual", key: "armAlpha", label: "arm opacity", kind: "number", default: 0.75, min: 0.05, max: 1, step: 0.01, live: true },
54+ { group: "visual", key: "bobSize", label: "bob size", kind: "number", default: 3, min: 0.5, max: 10, step: 0.1, unit: "px", live: true },
55+ { group: "visual", key: "saturation", label: "color saturation", kind: "number", default: 35, min: 0, max: 100, step: 1, unit: "%", live: true },
5756 ];
src/compositions/c03-divergence/score.tsadded+160−0View file
@@ -0,0 +1,160 @@
1+// Composition 3: divergence — the score (score worker).
2+//
3+// N double pendulums released together from rest at a wide angle, each outer arm offset by a tiny,
4+// calibrated amount, so they swing as one and then visibly separate at about `separateAt` seconds,
5+// and chaos takes over. A note sounds whenever a bottom bob crosses the vertical through the pivot
6+// (either direction): in "chord" mode each pendulum has its own note of a chord (two interleaved
7+// chords by direction); in "motion" mode the pitch follows the bob's speed. Notes go to the side
8+// the bob is heading. After `freeTime` the pendulums are damped to rest over `dampTime`; each one's
9+// last note rings out and the piece ends with the fade.
10+//
11+// Drawing data: track 0 = [θ1, θ2] per pendulum (120 per piece second).
12+
13+import type { Params } from "../../core/params.ts";
14+import { mulberry32 } from "../../core/rng.ts";
15+import { NOTE_NAMES, quantize } from "../../music/scales.ts";
16+import { cos, hypot, pow, sin } from "../../physics/dmath.ts";
17+import type { DoublePendulum } from "../../physics/doublePendulum.ts";
18+import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
19+import { LEFT, RIGHT } from "./layout.ts";
20+import { DT, bob, offsetForSeparation, released } from "./release.ts";
21+
22+const MAX_SETTLE = 10; // s after the damping: count every pendulum as at rest regardless
23+const FRAME_DT = 1 / 120;
24+const INFO_DT = 0.1;
25+
26+interface Pend {
27+ p: DoublePendulum;
28+ prevX: number;
29+ E0: number;
30+ lastNote: NoteRef | null;
31+ restAt: number | null;
32+}
33+
34+/** Release angles: the nominal angle, varied per play by up to `jitter` (null rand: nominal). */
35+export function releaseAngles(P: Params, rand: (() => number) | null): [number, number] {
36+ const deg = Math.PI / 180;
37+ const base = (P.releaseAngle as number) * deg, j = (P.jitter as number) * deg;
38+ return rand ? [base + (2 * rand() - 1) * j, base + (2 * rand() - 1) * j] : [base, base];
39+}
40+
41+/**
42+ * The chord pitches per pendulum, low to high, from the scale's notes in range (an even spread
43+ * if continuous). With two chords, 2n notes are spread over the range and alternate between
44+ * them: left-to-right crossings play one, right-to-left the other (its neighbour above).
45+ */
46+function chords(P: Params, n: number): { right: number[]; left: number[] } {
47+ const low = P.pitchLow as number, high = P.pitchHigh as number;
48+ const root = NOTE_NAMES.indexOf(P.root as string);
49+ const two = !!P.directionChords;
50+ const k = two ? 2 * n : n;
51+ let notes: number[] = [];
52+ if (P.scale === "continuous") notes = Array.from({ length: Math.max(k, 2) }, (_, i) => low + ((high - low) * i) / Math.max(1, Math.max(k, 2) - 1));
53+ else for (let m = Math.ceil(low); m <= high; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) notes.push(m);
54+ if (!notes.length) notes = [quantize((low + high) / 2, P.scale as string, root)];
55+ const spread = Array.from({ length: k }, (_, i) => notes[k > 1 ? Math.round((i * (notes.length - 1)) / (k - 1)) : Math.floor(notes.length / 2)]);
56+ if (!two) return { right: spread, left: spread };
57+ return { right: spread.filter((_, i) => i % 2 === 0), left: spread.filter((_, i) => i % 2 === 1) };
58+}
59+
60+export const divergenceScore: ScoreFactory = (P: Params, seed: number, sink) => {
61+ const cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
62+ const speed = P.speed as number;
63+ const [th1, th2] = releaseAngles(P, mulberry32(seed));
64+ const cal = offsetForSeparation(cfg, th1, th2, (P.separateAt as number) * speed, (P.sepThreshold as number) * (cfg.l1 + cfg.l2));
65+ const n = Math.max(1, Math.round(P.count as number));
66+ const pends: Pend[] = Array.from({ length: n }, (_, i) => {
67+ const p = released(cfg, th1, th2, n > 1 ? (i / (n - 1) - 0.5) * cal.offset : 0);
68+ return { p, prevX: bob(cfg, p.y)[0], E0: 0, lastNote: null, restAt: null };
69+ });
70+ const vmax0 = Math.sqrt((2 * pends[0].p.energy()) / cfg.m2);
71+ const free = P.freeTime as number, damp = P.dampTime as number;
72+ const curve = P.dampCurve as number, tau = P.tau as number, restE = P.restEnergy as number;
73+ const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
74+ const chord = chords(P, n);
75+ const deg = 180 / Math.PI;
76+ const releaseInfo = `${(th1 * deg).toFixed(2)}°, ${(th2 * deg).toFixed(2)}°`;
77+ const offsetInfo = `${cal.offset.toExponential(2)} rad → separate at ${(cal.separatesAt / speed).toFixed(1)} s`;
78+
79+ let time = 0;
80+ let restAll: number | null = null;
81+ let notes = 0;
82+ let nextFrame = 0, nextInfo = 0;
83+ const row = new Float64Array(2 * n);
84+
85+ function note(i: number, tc: number, dir: number) {
86+ const d = pends[i], y = d.p.y, w = d.p.derived();
87+ // bottom bob's speed at the crossing
88+ const vx = cfg.l1 * cos(y[0]) * w.w1 + cfg.l2 * cos(y[1]) * w.w2;
89+ const vy = cfg.l1 * sin(y[0]) * w.w1 + cfg.l2 * sin(y[1]) * w.w2;
90+ const x = Math.min(1, hypot(vx, vy) / ((P.loudRef as number) * vmax0));
91+ const floor = P.loudFloor as number;
92+ const velocity = floor + (1 - floor) * pow(x, P.loudCurve as number);
93+ const midi =
94+ P.pitchMode === "motion"
95+ ? quantize((P.pitchLow as number) + ((P.pitchHigh as number) - (P.pitchLow as number)) * x, P.scale as string, NOTE_NAMES.indexOf(P.root as string))
96+ : chord[dir > 0 ? "right" : "left"][i];
97+ d.lastNote = sink.note(dir > 0 ? RIGHT : LEFT, tc, midi, velocity, P.noteLength as number) ?? d.lastNote;
98+ notes++;
99+ }
100+
101+ function step() {
102+ const t0 = time;
103+ time += DT / speed;
104+ const u = (t0 - free) / damp; // damping progress (< 0: free swinging)
105+ pends.forEach((d, i) => {
106+ const p = d.p;
107+ if (u >= 0) {
108+ if (!p.controlled) {
109+ p.controlled = true;
110+ d.E0 = p.energy();
111+ }
112+ p.tau = tau;
113+ p.eTarget = u < 1 ? d.E0 * pow(1 - u, curve) : 0;
114+ // the energy controller fades out near zero energy; real friction settles the last of it
115+ p.damping = u >= 1 ? 1 / tau : 0;
116+ }
117+ p.step(DT);
118+ const x = bob(cfg, p.y)[0];
119+ if (d.restAt === null && ((d.prevX < 0 && x >= 0) || (d.prevX > 0 && x <= 0))) note(i, t0 + (d.prevX / (d.prevX - x)) * (time - t0), x > d.prevX ? 1 : -1);
120+ d.prevX = x;
121+ if (d.restAt === null && u >= 1 && (p.energyNorm() < restE || time >= free + damp + MAX_SETTLE)) {
122+ d.restAt = time;
123+ if (d.lastNote) sink.hold(d.lastNote, d.lastNote.t, P.finalHold as number, P.finalFade as number);
124+ }
125+ });
126+ if (restAll === null && pends.every((d) => d.restAt !== null)) {
127+ restAll = time;
128+ sink.end(time + ring);
129+ }
130+ if (time >= nextFrame) {
131+ nextFrame = time + FRAME_DT;
132+ pends.forEach((d, i) => {
133+ row[2 * i] = d.p.y[0];
134+ row[2 * i + 1] = d.p.y[1];
135+ });
136+ sink.frame(0, time, row);
137+ }
138+ if (time >= nextInfo) {
139+ nextInfo = time + INFO_DT;
140+ const phase = restAll !== null ? "at rest" : time < free ? "swinging" : time < free + damp ? "damping" : "settling";
141+ sink.info(time, {
142+ phase,
143+ "energy (mean)": (pends.reduce((s, d) => s + d.p.energyNorm(), 0) / n).toFixed(4),
144+ notes: String(notes),
145+ release: releaseInfo,
146+ "offset (outermost)": offsetInfo,
147+ "at rest": `${pends.filter((d) => d.restAt !== null).length} / ${n}`,
148+ });
149+ }
150+ }
151+
152+ return {
153+ get time() {
154+ return time;
155+ },
156+ advance(t: number) {
157+ while (time < t) step();
158+ },
159+ };
160+};
src/compositions/c03-divergence/view.tsadded+92−0View file
@@ -0,0 +1,92 @@
1+// Composition 3: divergence — drawing at the playhead: all the pendulums from one pivot, with the
2+// bottom bobs' fading trails.
3+
4+import type { Params } from "../../core/params.ts";
5+import type { View } from "../../stream/piece.ts";
6+import { cssColor, fitCanvas } from "../shared/section.ts";
7+import { releaseAngles } from "./score.ts";
8+
9+const FRAME_DT = 1 / 120;
10+
11+export function divergenceView(el: HTMLElement, params: () => Params): View {
12+ el.classList.add("c03");
13+ const canvas = document.createElement("canvas");
14+ el.append(canvas);
15+ let row = new Float64Array(0);
16+ const colorOf = (P: Params, i: number, n: number) => `hsl(${((30 + (360 * i) / Math.max(1, n)) % 360).toFixed(0)} ${P.saturation}% 70%)`;
17+
18+ return {
19+ keep: (P) => (P.trailLength as number) + 0.5,
20+ draw(t, store) {
21+ const P = params();
22+ const g = fitCanvas(canvas);
23+ const w = canvas.clientWidth, h = canvas.clientHeight;
24+ g.clearRect(0, 0, w, h);
25+ const n = Math.max(1, Math.round(P.count as number));
26+ const l1 = 1, l2 = P.lengthRatio as number;
27+ const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
28+ const x0 = w / 2, y0 = h / 2;
29+ const px = (th1: number, th2: number): [number, number, number, number] => {
30+ const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
31+ return [x1, y1, x1 + scale * l2 * Math.sin(th2), y1 + scale * l2 * Math.cos(th2)];
32+ };
33+
34+ // trails: the bottom bobs' recent paths, fading with age (drawn in a few alpha bands)
35+ if (P.trails && store) {
36+ const len = P.trailLength as number;
37+ const BANDS = 6;
38+ g.lineWidth = P.trailWidth as number;
39+ g.lineJoin = g.lineCap = "round";
40+ for (let i = 0; i < n; i++) {
41+ g.strokeStyle = colorOf(P, i, n);
42+ for (let band = 0; band < BANDS; band++) {
43+ const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
44+ g.globalAlpha = 0.7 * (1 - (band + 0.5) / BANDS);
45+ g.beginPath();
46+ let started = false;
47+ store.rows(0, aOld - FRAME_DT, Math.min(t, aNew + FRAME_DT), (d, o) => {
48+ const [, , bx, by] = px(d[o + 1 + 2 * i], d[o + 2 + 2 * i]);
49+ if (started) g.lineTo(bx, by);
50+ else g.moveTo(bx, by), (started = true);
51+ });
52+ g.stroke();
53+ }
54+ }
55+ g.globalAlpha = 1;
56+ }
57+
58+ // pendulums, all from the one pivot (before the first play: at the nominal release)
59+ if (row.length !== 2 * n) row = new Float64Array(2 * n);
60+ const s = store?.at(0, t, row) ?? null;
61+ const [a1, a2] = releaseAngles(P, null);
62+ g.lineWidth = 1.5;
63+ g.lineCap = "round";
64+ const r = P.bobSize as number;
65+ for (let i = n - 1; i >= 0; i--) {
66+ const [x1, y1, x2, y2] = s ? px(s[2 * i], s[2 * i + 1]) : px(a1, a2);
67+ const col = colorOf(P, i, n);
68+ g.strokeStyle = col;
69+ g.fillStyle = col;
70+ g.globalAlpha = P.armAlpha as number;
71+ g.beginPath();
72+ g.moveTo(x0, y0);
73+ g.lineTo(x1, y1);
74+ g.lineTo(x2, y2);
75+ g.stroke();
76+ g.globalAlpha = 1;
77+ g.beginPath();
78+ g.arc(x1, y1, r * 0.8, 0, 2 * Math.PI);
79+ g.moveTo(x2 + r, y2);
80+ g.arc(x2, y2, r, 0, 2 * Math.PI);
81+ g.fill();
82+ }
83+ g.fillStyle = cssColor(el, "--fg");
84+ g.beginPath();
85+ g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
86+ g.fill();
87+ },
88+ dispose() {
89+ el.classList.remove("c03");
90+ },
91+ };
92+}
src/compositions/c04-descent/capacity.tsdeleted+0−30View file
@@ -1,30 +0,0 @@
1-// How many ringing extension notes can this device render? Instruments like Chaos gong are costly
2-// per ringing voice (strongly coupled modes can't be culled), so measure one voice's cost in a
3-// render worker (see instruments/stream/capacity.ts) and allow as many voices as fit the budget.
4-
5-import { DEFAULTS } from "@modal-synth/engine/params.ts";
6-import { PRESETS } from "@modal-synth/presets.ts";
7-import type { Params } from "../../core/params.ts";
8-import { parseModalPreset } from "../../instruments/modal.ts";
9-import { VOICE_BUDGET, voiceCost, voicesThatFit } from "../../instruments/stream/capacity.ts";
10-
11-export interface VoiceCapacity {
12- cap: number; // voices allowed
13- perVoice: number; // measured load of one ringing voice
14-}
15-
16-function sound(P: Params): Params | null {
17- const name = P.extInstrument as string;
18- if (!name.startsWith("modal: ")) return null;
19- const p = name === "modal: custom" ? parseModalPreset(P.modalCustom as string) : PRESETS.find((x) => `modal: ${x.name}` === name)?.p;
20- return { ...DEFAULTS, ...(p ?? {}) };
21-}
22-
23-export async function overlapCapacity(P: Params, sampleRate: number, wanted: number): Promise<VoiceCapacity> {
24- const s = sound(P);
25- if (!s) return { cap: wanted, perVoice: 0 };
26- const perVoice = await voiceCost({ ...s, voices: 1 }, sampleRate);
27- return { cap: voicesThatFit(perVoice, wanted), perVoice };
28-}
29-
30-export const OVERLAP_BUDGET = VOICE_BUDGET;
src/compositions/c04-descent/defaults.jsonmodified+0−2View file
@@ -24,8 +24,6 @@
2424 "loudFloor": 0.15,
2525 "notesLevel": 2,
2626 "maxOverlap": 4,
27- "deviceLimit": true,
28- "streamAudio": true,
2927 "click": true,
3028 "clickInstrument": "modal: Viola",
3129 "clickPitch": 72,
src/compositions/c04-descent/fall.tsmodified+6−2View file
@@ -1,4 +1,5 @@
11 // Starting from straight up: the nudge that makes the pendulum visibly tip at a chosen time.
2+import { cos, pow, sin } from "../../physics/dmath.ts";
23 import { DoublePendulum, type PendulumConfig } from "../../physics/doublePendulum.ts";
34
45 export const DT = 0.002; // simulation step (sim seconds), shared with the piece
@@ -13,7 +14,7 @@ export function inverted(cfg: PendulumConfig, d: number, ratio: number, side: nu
1314 }
1415
1516 export function bob(cfg: PendulumConfig, y: ArrayLike<number>): [number, number] {
16- return [cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]), cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1])];
17+ return [cfg.l1 * sin(y[0]) + cfg.l2 * sin(y[1]), cfg.l1 * cos(y[0]) + cfg.l2 * cos(y[1])];
1718 }
1819
1920 function tipTime(cfg: PendulumConfig, d: number, ratio: number, thr: number, maxT: number): number {
@@ -36,7 +37,10 @@ export function nudgeForTip(cfg: PendulumConfig, ratio: number, T: number, thr:
3637 const maxT = 3 * T + 10;
3738 const tip = (d: number) => tipTime(cfg, d, ratio, thr, maxT);
3839 const grid: { d: number; t: number }[] = [];
39- for (let e = -15; e <= -0.5; e += 0.25) grid.push({ d: 10 ** e, t: tip(10 ** e) });
40+ for (let i = 0; i <= 58; i++) {
41+ const d = pow(10, -15 + 0.25 * i);
42+ grid.push({ d, t: tip(d) });
43+ }
4044 // refine every bracket (tip(a) > T ≥ tip(b)); keep whatever lands closest to T
4145 const cands = [...grid];
4246 for (let i = 0; i + 1 < grid.length; i++) {
src/compositions/c04-descent/index.tsmodified+7−3View file
@@ -1,12 +1,16 @@
11 import type { Composition } from "../../core/composition.ts";
2+import { createStreamPiece, type StreamDef } from "../../stream/piece.ts";
23 import defaults from "./defaults.json";
3-import { createDescentPiece } from "./piece.ts";
4+import { estimateLength, layout } from "./layout.ts";
45 import { schema } from "./schema.ts";
6+import { descentView } from "./view.ts";
7+
8+const def: StreamDef = { id: "04-descent", schema, layout, estimateLength, view: descentView };
59
610 export const descent: Composition = {
7- id: "04-descent",
11+ id: def.id,
812 title: "descent",
913 schema,
1014 defaults,
11- create: createDescentPiece,
15+ create: (view, params) => createStreamPiece(def, view, params),
1216 };
src/compositions/c04-descent/layout.tsadded+29−0View file
@@ -0,0 +1,29 @@
1+import type { Params } from "../../core/params.ts";
2+import { soundOf } from "../../instruments/sounds.ts";
3+import type { Layout } from "../../stream/layout.ts";
4+
5+/** Stems: 0 extension notes, 1 clicks, 2 height notes — each its own instrument and effects. */
6+export const EXT = 0, CLICK = 1, HEIGHT = 2;
7+
8+export function layout(P: Params): Layout {
9+ const custom = P.modalCustom as string;
10+ const ext = soundOf(P.extInstrument as string, custom, { voices: Math.round(P.maxOverlap as number) });
11+ const click = soundOf(P.clickInstrument as string, custom);
12+ const height = soundOf(P.heightInstrument as string, custom);
13+ return {
14+ stems: [
15+ { kind: "synth", sound: ext, output: EXT },
16+ { kind: "synth", sound: click, output: CLICK },
17+ { kind: "synth", sound: height, output: HEIGHT },
18+ ],
19+ outputs: [
20+ { effects: "own", sound: ext, level: (Q) => Q.notesLevel as number },
21+ { effects: "own", sound: click, level: (Q) => Q.clickLevel as number },
22+ { effects: "own", sound: height, level: (Q) => Q.heightLevel as number },
23+ ],
24+ };
25+}
26+
27+export function estimateLength(P: Params): number {
28+ return (P.freeTime as number) + (P.dampTime as number) + 3 + (P.finalHold as number) + (P.finalFade as number) + 0.3;
29+}
src/compositions/c04-descent/piece.tsdeleted+0−622View file
@@ -1,622 +0,0 @@
1-// Composition 4: descent.
2-//
3-// One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about
4-// `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. Whenever the pendulum is fully
6-// extended (the arms pass through a straight line, at any angle) there is an extension note: a
7-// short violin note at a fixed pitch, its strength from the bob's speed, the first one accented.
8-// The outer bob sweeping past the pivot (a folded pendulum) is a click. Slight friction
9-// throughout, growing toward the end until it comes to rest; the last extension note rings out
10-// and the piece ends with the fade.
11-
12-import type { AudioEngine } from "../../core/audio.ts";
13-import { dbToGain } from "../../core/audio.ts";
14-import type { Piece } from "../../core/composition.ts";
15-import type { Params } from "../../core/params.ts";
16-import { mulberry32, randomSeed } from "../../core/rng.ts";
17-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
18-import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
19-import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
20-import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
21-import { type DoublePendulum, type PendulumConfig, wrapAngle } from "../../physics/doublePendulum.ts";
22-import { cssColor, fitCanvas } from "../shared/section.ts";
23-import { OVERLAP_BUDGET, overlapCapacity, type VoiceCapacity } from "./capacity.ts";
24-import { DT, bob, inverted, nudgeForTip } from "./fall.ts";
25-
26-const STREAMED = streamedModalInstruments();
27-const LOOKAHEAD = 0.15;
28-const STREAM_PREBUFFER = 0.4;
29-const TICK_MS = 25;
30-const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest regardless
31-const HISTORY_DT = 1 / 480; // piece-time spacing of stored states (drawing, blur, trail)
32-const BLUR_MAX_SAMPLES = 48;
33-const BLUR_SPACING_PX = 2;
34-const RING_S = 0.9; // extension-note ring lifetime
35-const EXT_ARM = 0.05; // rad: the arms must bend this far from straight before the next extension note
36-const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it
37-const CLICK_RING_S = 0.35; // click ring lifetime
38-
39-interface Snap {
40- t: number;
41- th1: number;
42- th2: number;
43-}
44-
45-interface Mark {
46- t: number;
47- x: number; // bob position (pendulum units)
48- y: number;
49- strength: number;
50- click?: boolean; // a pass by the pivot, not an extension note
51-}
52-
53-export function createDescentPiece(view: HTMLElement, params: () => Params): Piece {
54- view.classList.add("c04");
55- const canvas = document.createElement("canvas");
56- view.append(canvas);
57-
58- let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
59- let pend: DoublePendulum | null = null;
60- let prevX = 0;
61- let E0 = 1;
62- let vmax = 1;
63- let history: Snap[] = [];
64- let lastHistT = -Infinity;
65- let marks: Mark[] = [];
66- let extCount = 0; // extension notes so far
67- let prevPhi = 0; // relative arm angle at the previous step
68- let extArmed = false;
69- let clickCount = 0;
70- let lastNote: { handle: NoteHandle; when: number } | null = null;
71- let restAt: number | null = null;
72- let audio: AudioEngine | null = null;
73- let out: GainNode | null = null;
74- let noteBus: GainNode | null = null;
75- let inst: NoteInstrument | null = null;
76- let instKey = "";
77- let clickBus: GainNode | null = null;
78- let clickInst: NoteInstrument | null = null;
79- let clickKey = "";
80- // height notes: levels (MIDI pitches, ascending) and where the bob is among them
81- let heightBus: GainNode | null = null;
82- let heightInst: NoteInstrument | null = null;
83- let heightKey = "";
84- let levels: number[] = [];
85- let levelIdx = 0; // number of levels below the bob's current pitch position
86- let heightCount = 0;
87- let timer: number | undefined;
88- let playing = false;
89- let startToken = 0;
90- let pieceStart = 0;
91- let simPieceT = 0;
92- let seedUsed = 0;
93- let stoppedAt = 0;
94- let stream = false;
95- let simAhead = LOOKAHEAD;
96- let nudge = { d: 0, ratio: 1, side: 1, tipsAt: 0 };
97- let capacity: VoiceCapacity | null = null;
98- let checking = false;
99- let voicesAllowed = 4;
100-
101- const piece: Piece = {
102- get playing() {
103- return playing;
104- },
105- start,
106- stop,
107- draw,
108- now,
109- length: () => endTime(params()),
110- readouts,
111- notice,
112- dispose() {
113- stop();
114- view.classList.remove("c04");
115- view.replaceChildren();
116- },
117- };
118-
119- function now(): number {
120- if (!audio || !playing) return stoppedAt;
121- return audio.ctx.currentTime - pieceStart;
122- }
123-
124- // ── setup ──
125-
126- function makePendulum(P: Params, rand: (() => number) | null) {
127- cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
128- const side = rand ? (rand() < 0.5 ? -1 : 1) : 1;
129- const ratio = rand ? 0.6 + 0.8 * rand() : 1;
130- const speed = P.speed as number;
131- const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
132- nudge = { d: cal.nudge, ratio, side, tipsAt: cal.tipsAt / speed };
133- pend = inverted(cfg, cal.nudge, ratio, side);
134- prevX = bob(cfg, pend.y)[0];
135- E0 = pend.energy();
136- vmax = Math.sqrt((2 * E0) / cfg.m2);
137- history = [];
138- marks = [];
139- extCount = 0;
140- prevPhi = wrapAngle(pend.y[1] - pend.y[0]);
141- extArmed = false;
142- clickCount = 0;
143- lastNote = null;
144- restAt = null;
145- pushHistory(0);
146- }
147-
148- function ensureInstrument() {
149- if (!audio || !out) return;
150- const P = params();
151- const ctx = audio.ctx;
152- if (!noteBus) {
153- noteBus = ctx.createGain();
154- noteBus.connect(out);
155- }
156- noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
157- const name = P.extInstrument as string;
158- const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`;
159- if (inst && instKey === key) return;
160- inst?.dispose();
161- instKey = key;
162- const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
163- inst = factory(ctx, noteBus, { custom: P.modalCustom as string, overrides: { voices: voicesAllowed } });
164- }
165-
166- /** The click for passes by the pivot: its own (cheap) instrument and level. */
167- function ensureClick() {
168- if (!audio || !out) return;
169- const P = params();
170- const ctx = audio.ctx;
171- if (!clickBus) {
172- clickBus = ctx.createGain();
173- clickBus.connect(out);
174- }
175- clickBus.gain.setTargetAtTime(dbToGain(P.clickLevel as number), ctx.currentTime, 0.05);
176- const name = P.clickInstrument as string;
177- const key = P.click ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
178- if (clickKey === key && (clickInst || !key)) return;
179- clickInst?.dispose();
180- clickInst = null;
181- clickKey = key;
182- if (!key) return;
183- const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
184- clickInst = factory(ctx, clickBus, { custom: P.modalCustom as string });
185- }
186-
187- /** Short notes at height levels: their own instrument and level. */
188- function ensureHeight() {
189- if (!audio || !out) return;
190- const P = params();
191- const ctx = audio.ctx;
192- if (!heightBus) {
193- heightBus = ctx.createGain();
194- heightBus.connect(out);
195- }
196- heightBus.gain.setTargetAtTime(dbToGain(P.heightLevel as number), ctx.currentTime, 0.05);
197- const name = P.heightInstrument as string;
198- const key = P.heightNotes ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
199- if (heightKey === key && (heightInst || !key)) return;
200- heightInst?.dispose();
201- heightInst = null;
202- heightKey = key;
203- if (!key) return;
204- const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
205- heightInst = factory(ctx, heightBus, { custom: P.modalCustom as string });
206- }
207-
208- /** The ladder: scale notes between the low and high pitch, every `step`-th. */
209- function makeLevels(P: Params): number[] {
210- const lo = P.heightLow as number, hi = P.heightHigh as number;
211- const root = NOTE_NAMES.indexOf(P.root as string);
212- const all: number[] = [];
213- if (P.scale === "continuous") for (let m = Math.ceil(lo); m <= hi; m++) all.push(m);
214- else for (let m = Math.ceil(lo); m <= hi; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) all.push(m);
215- const step = Math.max(1, Math.round(P.heightStep as number));
216- return all.filter((_, i) => i % step === 0);
217- }
218-
219- /** The bob's height as a pitch position on the ladder (bottom → heightLow, top → heightHigh). */
220- function pitchPos(P: Params, y: number): number {
221- const L = cfg.l1 + cfg.l2;
222- const hn = (L - y) / (2 * L); // 0 at the bottom, 1 at the top
223- return (P.heightLow as number) + ((P.heightHigh as number) - (P.heightLow as number)) * hn;
224- }
225-
226- function countBelow(p: number): number {
227- let i = 0;
228- while (i < levels.length && levels[i] < p) i++;
229- return i;
230- }
231-
232- // ── transport ──
233-
234- async function start(a: AudioEngine, offset: number) {
235- stop();
236- const token = ++startToken;
237- audio = a;
238- const P = params();
239- const ctx = a.ctx;
240- stream = !!P.streamAudio;
241- simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
242- const wanted = Math.round(P.maxOverlap as number);
243- voicesAllowed = wanted;
244- if (P.deviceLimit) {
245- checking = true;
246- try {
247- capacity = await overlapCapacity(P, ctx.sampleRate, wanted);
248- voicesAllowed = capacity.cap;
249- } finally {
250- checking = false;
251- }
252- if (token !== startToken) return;
253- }
254- seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
255- const rng = mulberry32(seedUsed);
256- makePendulum(P, () => rng());
257- levels = makeLevels(P);
258- levelIdx = countBelow(pitchPos(P, bob(cfg, pend!.y)[1]));
259- heightCount = 0;
260- simPieceT = 0;
261- if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
262-
263- out = ctx.createGain();
264- out.connect(a.input);
265- ensureInstrument();
266- ensureClick();
267- ensureHeight();
268- await Promise.all([inst?.ready, clickInst?.ready, heightInst?.ready]);
269- if (token !== startToken) return;
270- pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
271- playing = true;
272- tick();
273- timer = window.setInterval(tick, TICK_MS);
274- }
275-
276- function stop() {
277- startToken++;
278- if (timer !== undefined) window.clearInterval(timer);
279- timer = undefined;
280- if (playing) {
281- stoppedAt = now();
282- playing = false;
283- }
284- if (!audio) return;
285- const t = audio.ctx.currentTime;
286- const o = out;
287- if (o) {
288- o.gain.setTargetAtTime(0, t, 0.05);
289- window.setTimeout(() => o.disconnect(), 600);
290- }
291- inst?.dispose();
292- inst = null;
293- instKey = "";
294- clickInst?.dispose();
295- clickInst = null;
296- clickKey = "";
297- clickBus = null;
298- heightInst?.dispose();
299- heightInst = null;
300- heightKey = "";
301- heightBus = null;
302- noteBus = null;
303- out = null;
304- }
305-
306- // ── simulation ──
307-
308- function pushHistory(t: number) {
309- if (!pend) return;
310- history.push({ t, th1: pend.y[0], th2: pend.y[1] });
311- lastHistT = t;
312- }
313-
314- /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
315- function damping(P: Params, t: number): number {
316- const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
317- const s = u * u * (3 - 2 * u);
318- return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
319- }
320-
321- function advanceTo(target: number, sound: boolean) {
322- if (!pend) return;
323- const P = params();
324- const speed = P.speed as number;
325- const end = (P.freeTime as number) + (P.dampTime as number);
326- const restE = P.restEnergy as number;
327- const minY = (P.minDepth as number) * (cfg.l1 + cfg.l2);
328- const p = pend;
329- while (simPieceT < target) {
330- const t0 = simPieceT;
331- simPieceT += DT / speed;
332- p.damping = damping(P, t0);
333- p.step(DT);
334- const [x, y] = bob(cfg, p.y);
335- if (restAt === null && levels.length) heightLevels(t0, pitchPos(P, y), P, sound);
336- // the outer bob sweeping past the pivot (crossing the vertical close to it): a click
337- if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
338- const f = prevX / (prevX - x);
339- const tc = t0 + f * (simPieceT - t0);
340- clickCount++;
341- if (sound) click(tc, y, P);
342- }
343- prevX = x;
344- // full extension: the arms pass through a straight line (relative angle crosses 0, not ±π),
345- // at any orientation. It re-arms once the arms bend at least EXT_ARM away from straight.
346- const phi = wrapAngle(p.y[1] - p.y[0]);
347- if (Math.abs(phi) > EXT_ARM) extArmed = true;
348- if (restAt === null && extArmed && ((prevPhi < 0 && phi >= 0) || (prevPhi > 0 && phi <= 0)) && Math.abs(phi - prevPhi) < Math.PI) {
349- const f = prevPhi / (prevPhi - phi);
350- const tc = t0 + f * (simPieceT - t0);
351- extArmed = false;
352- extCount++;
353- if (sound) extensionNote(tc, P);
354- else marks.push({ t: tc, x, y, strength: 0.5 });
355- }
356- prevPhi = phi;
357- if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
358- restAt = simPieceT;
359- if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
360- }
361- if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
362- }
363- }
364-
365- /** Notes for every level the bob's pitch position has passed since the last step (with hysteresis). */
366- function heightLevels(t0: number, pos: number, P: Params, sound: boolean) {
367- const h = HEIGHT_HYST * (levels.length > 1 ? (levels[levels.length - 1] - levels[0]) / (levels.length - 1) : 1);
368- // moving up past levels[levelIdx]
369- while (levelIdx < levels.length && pos > levels[levelIdx] + h) {
370- if (sound) heightNote(t0, levels[levelIdx], P);
371- levelIdx++;
372- }
373- // moving down past levels[levelIdx − 1]
374- while (levelIdx > 0 && pos < levels[levelIdx - 1] - h) {
375- levelIdx--;
376- if (sound) heightNote(t0, levels[levelIdx], P);
377- }
378- }
379-
380- function heightNote(t0: number, midi: number, P: Params) {
381- if (!audio || !heightInst || !pend) return;
382- const tc = t0 + DT / (P.speed as number);
383- const when = pieceStart + tc;
384- if (when < audio.ctx.currentTime - 0.02) return;
385- // strength: ramps in over the opening, fades with the energy at the end
386- const ru = (P.heightRamp as number) > 0 ? Math.max(0, Math.min(1, tc / (P.heightRamp as number))) : 1;
387- const from = P.heightRampFrom as number;
388- const ramp = from + (1 - from) * ru * ru * (3 - 2 * ru);
389- const e = Math.min(1, Math.max(0, pend.energy()) / E0);
390- const velocity = (P.heightVel as number) * ramp * Math.pow(e, P.heightFollow as number);
391- heightInst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.heightLength as number });
392- heightCount++;
393- }
394-
395- function extensionNote(tc: number, P: Params) {
396- if (!audio || !inst || !pend) return;
397- const when = pieceStart + tc;
398- if (when < audio.ctx.currentTime - 0.02) return;
399- const midi = P.extPitch as number;
400- // strength: the first extension note is the accent; later ones follow the bob's speed
401- const velocity = extCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P);
402- const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.extLength as number });
403- if (handle) lastNote = { handle, when };
404- const [bx, by] = bob(cfg, pend.y);
405- marks.push({ t: tc, x: bx, y: by, strength: velocity });
406- }
407-
408- /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
409- function speedStrength(P: Params): number {
410- if (!pend) return 0;
411- const w = pend.derived();
412- const yv = pend.y;
413- const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2;
414- const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2;
415- const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax));
416- const floor = P.loudFloor as number;
417- return floor + (1 - floor) * Math.pow(xs, P.loudCurve as number);
418- }
419-
420- function click(tc: number, y: number, P: Params) {
421- if (!audio || !clickInst) return;
422- const when = pieceStart + tc;
423- if (when < audio.ctx.currentTime - 0.02) return;
424- const velocity = (P.clickMaxVel as number) * speedStrength(P);
425- clickInst.play({ when, freq: midiToFreq(P.clickPitch as number), velocity, pan: 0, duration: P.clickLength as number });
426- marks.push({ t: tc, x: 0, y, strength: velocity, click: true });
427- }
428-
429- function endTime(P: Params): number {
430- const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
431- return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring;
432- }
433-
434- function tick() {
435- if (!audio || !playing || !pend) return;
436- const P = params();
437- ensureInstrument();
438- const ctx = audio.ctx;
439- const t = ctx.currentTime - pieceStart;
440- const total = endTime(P);
441- if (restAt !== null && t >= total) {
442- stop();
443- stoppedAt = total;
444- piece.onEnded?.();
445- return;
446- }
447- ensureClick();
448- ensureHeight();
449- advanceTo(t + simAhead, true);
450- for (const i of [inst, clickInst, heightInst]) i?.horizon?.(pieceStart + simPieceT);
451-
452- // keep the states drawing, blur and trail still need
453- const keep = t - (P.trailLength as number) - 0.5;
454- let i = 0;
455- while (i < history.length - 2 && history[i + 1].t < keep) i++;
456- if (i > 0) history.splice(0, i);
457- while (marks.length && marks[0].t < t - RING_S - 1) marks.shift();
458- }
459-
460- // ── drawing ──
461-
462- function stateAt(t: number): Snap {
463- const n = history.length;
464- if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI };
465- if (t <= history[0].t) return history[0];
466- if (t >= history[n - 1].t) return history[n - 1];
467- let lo = 0, hi = n - 1;
468- while (hi - lo > 1) {
469- const mid = (lo + hi) >> 1;
470- if (history[mid].t <= t) lo = mid;
471- else hi = mid;
472- }
473- const a = history[lo], b = history[hi];
474- const f = (t - a.t) / (b.t - a.t);
475- return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
476- }
477-
478- let lastWall = 0;
479- let frameDt = 1 / 60;
480-
481- function draw() {
482- const P = params();
483- if (!pend) makePendulum(P, null); // preview: balanced straight up
484- const t = now();
485- const wall = performance.now() / 1000;
486- const dtw = wall - lastWall;
487- lastWall = wall;
488- if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
489- const g = fitCanvas(canvas);
490- const w = canvas.clientWidth, h = canvas.clientHeight;
491- g.clearRect(0, 0, w, h);
492- const fg = cssColor(view, "--fg");
493- const l1 = cfg.l1, l2 = cfg.l2;
494- const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
495- const x0 = w / 2, y0 = h / 2;
496- const pos = (s: { th1: number; th2: number }) => {
497- const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1);
498- return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)];
499- };
500-
501- // trail of the outer bob, fading with age
502- if (P.trails && history.length > 1) {
503- const len = P.trailLength as number;
504- const BANDS = 6;
505- g.strokeStyle = fg;
506- g.lineWidth = 1;
507- g.lineJoin = g.lineCap = "round";
508- for (let band = 0; band < BANDS; band++) {
509- const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
510- g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
511- g.beginPath();
512- let started = false;
513- for (let i = 0; i < history.length; i += 2) {
514- const hs = history[i];
515- if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue;
516- if (hs.t > t) break;
517- const [, , bx, by] = pos(hs);
518- if (started) g.lineTo(bx, by);
519- else g.moveTo(bx, by), (started = true);
520- }
521- g.stroke();
522- }
523- g.globalAlpha = 1;
524- }
525-
526- // rings, where each extension note (and click) happened
527- if (P.rings) {
528- for (const c of marks) {
529- const age = t - c.t;
530- const life = c.click ? CLICK_RING_S : RING_S;
531- if (age < 0 || age > life) continue;
532- const s = stateAt(c.t);
533- const [, , bx, by] = pos(s);
534- g.strokeStyle = fg;
535- g.globalAlpha = (1 - age / life) * (0.4 + 0.6 * c.strength);
536- g.lineWidth = c.click ? 1 : 1.2;
537- g.beginPath();
538- const grow = c.click ? 14 : 60 * (0.5 + c.strength);
539- g.arc(bx, by, (c.click ? 3 : 6) + grow * Math.sqrt(age / life), 0, 2 * Math.PI);
540- g.stroke();
541- }
542- g.globalAlpha = 1;
543- }
544-
545- // the pendulum, with motion blur
546- const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
547- let k = 1;
548- if (shutter > 0) {
549- let path = 0;
550- let a = stateAt(t);
551- for (let j = 1; j <= 8; j++) {
552- const b = stateAt(t - (shutter * j) / 8);
553- path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
554- a = b;
555- }
556- k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
557- }
558- const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
559- const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2);
560- g.strokeStyle = fg;
561- g.fillStyle = fg;
562- g.lineWidth = 1.5;
563- g.lineCap = "round";
564- g.globalAlpha = alpha;
565- for (let i = 0; i < k; i++) {
566- const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1)));
567- g.beginPath();
568- g.moveTo(x0, y0);
569- g.lineTo(x1, y1);
570- g.lineTo(x2, y2);
571- g.stroke();
572- g.beginPath();
573- g.arc(x1, y1, r1, 0, 2 * Math.PI);
574- g.moveTo(x2 + r2, y2);
575- g.arc(x2, y2, r2, 0, 2 * Math.PI);
576- g.fill();
577- }
578- g.globalAlpha = 1;
579- g.beginPath();
580- g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
581- g.fill();
582- }
583-
584- function notice(): string | null {
585- if (checking) return "checking what this device can play…";
586- const P = params();
587- if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
588- if (capacity.perVoice > OVERLAP_BUDGET) return "this device can't render the extension notes in real time; expect glitches";
589- const want = Math.round(P.maxOverlap as number);
590- return voicesAllowed < want ? `${voicesAllowed} overlapping note${voicesAllowed > 1 ? "s" : ""} (of ${want}): reduced to what this device can play` : null;
591- }
592-
593- function readouts(): Record<string, string> {
594- const P = params();
595- const t = now();
596- const free = P.freeTime as number, damp = P.dampTime as number;
597- const phase = restAt !== null && simPieceT >= restAt ? "at rest" : extCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
598- return {
599- time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
600- phase,
601- energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
602- "extension notes": String(extCount),
603- clicks: String(clickCount),
604- "height notes": String(heightCount),
605- nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
606- friction: `${damping(P, t).toFixed(4)} /sim s`,
607- "seed used": seedUsed ? String(seedUsed) : "–",
608- "overlapping notes": capacity ? `${voicesAllowed} (one ringing note: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
609- "audio load": [["extension", inst], ["click", clickInst], ["height", heightInst]]
610- .filter(([, i]) => i)
611- .map(([n, i]) => {
612- const x = i as NoteInstrument;
613- const v = x.voices?.();
614- const cap = v && v.allowed < v.wanted ? `, ${v.allowed} of ${v.wanted} voices` : "";
615- return `${n} ${Math.round(100 * (x.load?.() ?? 0))}%${stream ? `, ${x.underruns?.() ?? 0} underruns` : ""}${cap}`;
616- })
617- .join(" · "),
618- };
619- }
620-
621- return piece;
622-}
src/compositions/c04-descent/schema.tsmodified+11−13View file
@@ -1,5 +1,5 @@
11 import type { ParamSpec } from "../../core/params.ts";
2-import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
2+import { NOTE_SOUNDS } from "../../instruments/sounds.ts";
33 import { schema as c01 } from "../c01-poincare/schema.ts";
44
55 const pick = (key: string, o: Partial<ParamSpec> = {}): ParamSpec => {
@@ -27,7 +27,7 @@ export const schema: ParamSpec[] = [
2727 pick("seed", { group: "pendulum", hint: "0 = a different nudge (side and shape) every play" }),
2828
2929 // ── extension notes: the pendulum fully extended (arms in a straight line, at any angle) ──
30- { group: "extension", key: "extInstrument", label: "instrument", kind: "select", default: "modal: Violin", options: Object.keys(NOTE_INSTRUMENTS) },
30+ { group: "extension", key: "extInstrument", label: "instrument", kind: "select", default: "modal: Violin", options: NOTE_SOUNDS },
3131 pick("modalCustom", { group: "extension" }),
3232 { group: "extension", key: "extPitch", label: "pitch", kind: "number", default: 55, min: 12, max: 108, step: 0.5, unit: "midi" },
3333 { group: "extension", key: "extLength", label: "length", kind: "number", default: 0.4, min: 0.05, max: 5, log: true, unit: "s" },
@@ -36,23 +36,21 @@ export const schema: ParamSpec[] = [
3636 { group: "extension", 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" },
3737 pick("loudCurve", { group: "extension" }),
3838 pick("loudFloor", { group: "extension", default: 0.15 }),
39- pick("notesLevel", { group: "extension", default: 2, max: 18 }),
40- { group: "extension", key: "maxOverlap", label: "overlapping notes", kind: "number", default: 4, min: 1, max: 16, step: 1, hint: "most extension notes ringing at once (a new one replaces the oldest)" },
41- { group: "extension", key: "deviceLimit", label: "limit to device", kind: "bool", default: true, hint: "measure (once per device) how many ringing extension notes it can render, and allow no more" },
42- { group: "extension", key: "streamAudio", label: "render ahead", kind: "bool", default: true, hint: "render the instruments in background threads, ~2 s ahead (applies on the next play)" },
39+ pick("notesLevel", { group: "extension", default: 2, max: 18, live: true }),
40+ { group: "extension", key: "maxOverlap", label: "overlapping notes", kind: "number", default: 4, min: 1, max: 16, step: 1, hint: "most extension notes ringing at once (a new one replaces the quietest)" },
4341
4442 // ── click: the outer bob sweeping past the pivot (within the minimum depth) ──
4543 { group: "click", key: "minDepth", label: "near the pivot", kind: "number", default: 0.25, min: 0, max: 0.95, step: 0.01, hint: "a click when the outer bob crosses the vertical within this distance of the pivot (fraction of the length)" },
4644 { 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)" },
47- { group: "click", key: "clickInstrument", label: "instrument", kind: "select", default: "modal: Viola", options: Object.keys(NOTE_INSTRUMENTS) },
45+ { group: "click", key: "clickInstrument", label: "instrument", kind: "select", default: "modal: Viola", options: NOTE_SOUNDS },
4846 { group: "click", key: "clickPitch", label: "pitch", kind: "number", default: 72, min: 24, max: 120, step: 0.5, unit: "midi" },
4947 { group: "click", key: "clickLength", label: "length", kind: "number", default: 0.5, min: 0.01, max: 2, log: true, unit: "s" },
5048 { 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 extension notes)" },
51- { group: "click", key: "clickLevel", label: "level", kind: "number", default: -8, min: -48, max: 6, step: 0.5, unit: "dB" },
49+ { group: "click", key: "clickLevel", label: "level", kind: "number", default: -8, min: -48, max: 6, step: 0.5, unit: "dB", live: true },
5250
5351 // ── height notes: a short note each time the outer bob's height passes a level ──
5452 { group: "height", key: "heightNotes", label: "height notes", kind: "bool", default: true, hint: "levels are the scale's notes between the low and high pitch (every `step`-th); passing one, up or down, plays it" },
55- { group: "height", key: "heightInstrument", label: "instrument", kind: "select", default: "modal: Piano-ish", options: Object.keys(NOTE_INSTRUMENTS) },
53+ { group: "height", key: "heightInstrument", label: "instrument", kind: "select", default: "modal: Piano-ish", options: NOTE_SOUNDS },
5654 { group: "height", key: "heightLow", label: "pitch at bottom", kind: "number", default: 60, min: 24, max: 108, step: 0.5, unit: "midi", hint: "bob straight down" },
5755 { group: "height", key: "heightHigh", label: "pitch at top", kind: "number", default: 96, min: 24, max: 120, step: 0.5, unit: "midi", hint: "bob straight up" },
5856 pick("scale", { group: "height", default: "dorian" }),
@@ -60,14 +58,14 @@ export const schema: ParamSpec[] = [
6058 { 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)" },
6159 { group: "height", key: "heightLength", label: "length", kind: "number", default: 0.3, min: 0.05, max: 3, log: true, unit: "s" },
6260 { group: "height", key: "heightVel", label: "strength", kind: "number", default: 0.7, min: 0.05, max: 1, step: 0.01 },
63- { group: "height", key: "heightLevel", label: "level", kind: "number", default: 14, min: -48, max: 18, step: 0.5, unit: "dB" },
61+ { group: "height", key: "heightLevel", label: "level", kind: "number", default: 14, min: -48, max: 18, step: 0.5, unit: "dB", live: true },
6462 { group: "height", key: "heightRamp", label: "ramp in", kind: "number", default: 6, min: 0, max: 60, step: 0.5, unit: "s", hint: "the notes grow to full strength over the opening" },
6563 { group: "height", key: "heightRampFrom", label: "ramp from", kind: "number", default: 0.5, min: 0, max: 1, step: 0.01, hint: "starting strength, as a fraction of full" },
6664 { group: "height", key: "heightFollow", label: "fades with energy", kind: "number", default: 0.3, min: 0, max: 2, step: 0.05, hint: "strength × (energy / start energy)^this" },
6765
6866 // ── visual ──
69- { group: "visual", key: "trails", label: "trail", kind: "bool", default: true },
70- { group: "visual", key: "trailLength", label: "trail length", kind: "number", default: 2.5, min: 0.2, max: 20, log: true, unit: "s" },
71- { group: "visual", key: "rings", label: "rings", kind: "bool", default: true, hint: "a brief ring where each extension note (and, smaller, each click) happens" },
67+ { group: "visual", key: "trails", label: "trail", kind: "bool", default: true, live: true },
68+ { group: "visual", key: "trailLength", label: "trail length", kind: "number", default: 2.5, min: 0.2, max: 20, log: true, unit: "s", live: true },
69+ { group: "visual", key: "rings", label: "rings", kind: "bool", default: true, hint: "a brief ring where each extension note (and, smaller, each click) happens", live: true },
7270 pick("motionBlur"),
7371 ];
src/compositions/c04-descent/score.tsadded+171−0View file
@@ -0,0 +1,171 @@
1+// Composition 4: descent — the score (runs in the score worker).
2+//
3+// One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about
4+// `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. Whenever the pendulum is fully
6+// extended (the arms pass through a straight line, at any angle) there is an extension note: a
7+// short violin note at a fixed pitch, its strength from the bob's speed, the first one accented.
8+// The outer bob sweeping past the pivot (a folded pendulum) is a click. Slight friction
9+// throughout, growing toward the end until it comes to rest; the last extension note rings out
10+// and the piece ends with the fade.
11+//
12+// Drawing data: track 0 = [θ1, θ2] (480 per piece second); events "ring" where notes happen.
13+
14+import type { Params } from "../../core/params.ts";
15+import { mulberry32 } from "../../core/rng.ts";
16+import { NOTE_NAMES, quantize } from "../../music/scales.ts";
17+import { cos, hypot, pow, sin, wrap } from "../../physics/dmath.ts";
18+import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
19+import { DT, bob, inverted, nudgeForTip } from "./fall.ts";
20+import { CLICK, EXT, HEIGHT } from "./layout.ts";
21+
22+const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest regardless
23+const FRAME_DT = 1 / 480; // piece-time spacing of drawing rows
24+const INFO_DT = 0.1;
25+const EXT_ARM = 0.05; // rad: the arms must bend this far from straight before the next extension note
26+const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it
27+
28+export const descentScore: ScoreFactory = (P: Params, seed: number, sink) => {
29+ const cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
30+ const speed = P.speed as number;
31+ const rand = mulberry32(seed);
32+ const side = rand() < 0.5 ? -1 : 1;
33+ const ratio = 0.6 + 0.8 * rand();
34+ const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
35+ const p = inverted(cfg, cal.nudge, ratio, side);
36+ const L = cfg.l1 + cfg.l2;
37+ const E0 = p.energy();
38+ const vmax = Math.sqrt((2 * E0) / cfg.m2);
39+ const end = (P.freeTime as number) + (P.dampTime as number);
40+ const restE = P.restEnergy as number;
41+ const minY = (P.minDepth as number) * L;
42+ const nudgeInfo = `${cal.nudge.toExponential(2)} rad ${side > 0 ? "→" : "←"} (shape ${ratio.toFixed(2)}), tips at ${(cal.tipsAt / speed).toFixed(1)} s`;
43+
44+ // the height ladder: scale notes between the low and high pitch, every `step`-th
45+ const levels: number[] = (() => {
46+ if (!P.heightNotes) return [];
47+ const lo = P.heightLow as number, hi = P.heightHigh as number;
48+ const root = NOTE_NAMES.indexOf(P.root as string);
49+ const all: number[] = [];
50+ for (let m = Math.ceil(lo); m <= hi; m++) if (P.scale === "continuous" || Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) all.push(m);
51+ const step = Math.max(1, Math.round(P.heightStep as number));
52+ return all.filter((_, i) => i % step === 0);
53+ })();
54+ const pitchPos = (y: number) => (P.heightLow as number) + ((P.heightHigh as number) - (P.heightLow as number)) * ((L - y) / (2 * L));
55+ const countBelow = (q: number) => {
56+ let i = 0;
57+ while (i < levels.length && levels[i] < q) i++;
58+ return i;
59+ };
60+ const hyst = HEIGHT_HYST * (levels.length > 1 ? (levels[levels.length - 1] - levels[0]) / (levels.length - 1) : 1);
61+
62+ let time = 0;
63+ let prevX = bob(cfg, p.y)[0];
64+ let prevPhi = wrap(p.y[1] - p.y[0]);
65+ let extArmed = false;
66+ let levelIdx = countBelow(pitchPos(bob(cfg, p.y)[1]));
67+ let restAt: number | null = null;
68+ let lastNote: NoteRef | null = null;
69+ let extCount = 0, clickCount = 0, heightCount = 0;
70+ let nextFrame = 0, nextInfo = 0;
71+
72+ /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
73+ const damping = (t: number) => {
74+ const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
75+ const s = u * u * (3 - 2 * u);
76+ return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
77+ };
78+
79+ /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
80+ const speedStrength = () => {
81+ const w = p.derived(), y = p.y;
82+ const vx = cfg.l1 * cos(y[0]) * w.w1 + cfg.l2 * cos(y[1]) * w.w2;
83+ const vy = cfg.l1 * sin(y[0]) * w.w1 + cfg.l2 * sin(y[1]) * w.w2;
84+ const x = Math.min(1, hypot(vx, vy) / ((P.loudRef as number) * vmax));
85+ const floor = P.loudFloor as number;
86+ return floor + (1 - floor) * pow(x, P.loudCurve as number);
87+ };
88+
89+ const heightNote = (t: number, midi: number) => {
90+ // strength: ramps in over the opening, fades with the energy at the end
91+ const ru = (P.heightRamp as number) > 0 ? Math.max(0, Math.min(1, t / (P.heightRamp as number))) : 1;
92+ const from = P.heightRampFrom as number;
93+ const ramp = from + (1 - from) * ru * ru * (3 - 2 * ru);
94+ const e = Math.min(1, Math.max(0, p.energy()) / E0);
95+ sink.note(HEIGHT, t, midi, (P.heightVel as number) * ramp * pow(e, P.heightFollow as number), P.heightLength as number);
96+ heightCount++;
97+ };
98+
99+ function step() {
100+ const t0 = time;
101+ time += DT / speed;
102+ p.damping = damping(t0);
103+ p.step(DT);
104+ const [x, y] = bob(cfg, p.y);
105+ // height levels passed since the last step (with hysteresis)
106+ if (restAt === null && levels.length) {
107+ const pos = pitchPos(y);
108+ while (levelIdx < levels.length && pos > levels[levelIdx] + hyst) heightNote(time, levels[levelIdx++]);
109+ while (levelIdx > 0 && pos < levels[levelIdx - 1] - hyst) heightNote(time, levels[--levelIdx]);
110+ }
111+ // the outer bob sweeping past the pivot (crossing the vertical close to it): a click
112+ if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
113+ const tc = t0 + (prevX / (prevX - x)) * (time - t0);
114+ clickCount++;
115+ if (P.click) {
116+ const vel = (P.clickMaxVel as number) * speedStrength();
117+ sink.note(CLICK, tc, P.clickPitch as number, vel, P.clickLength as number);
118+ sink.event({ t: tc, kind: "ring", x: 0, y, strength: vel, click: 1 });
119+ }
120+ }
121+ prevX = x;
122+ // full extension: the arms pass through a straight line (relative angle crosses 0, not ±π),
123+ // at any orientation. It re-arms once the arms bend at least EXT_ARM away from straight.
124+ const phi = wrap(p.y[1] - p.y[0]);
125+ if (Math.abs(phi) > EXT_ARM) extArmed = true;
126+ if (restAt === null && extArmed && ((prevPhi < 0 && phi >= 0) || (prevPhi > 0 && phi <= 0)) && Math.abs(phi - prevPhi) < Math.PI) {
127+ const tc = t0 + (prevPhi / (prevPhi - phi)) * (time - t0);
128+ extArmed = false;
129+ extCount++;
130+ // the first extension note is the accent; later ones follow the bob's speed
131+ const vel = extCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength();
132+ lastNote = sink.note(EXT, tc, P.extPitch as number, vel, P.extLength as number) ?? lastNote;
133+ sink.event({ t: tc, kind: "ring", x, y, strength: vel, click: 0 });
134+ }
135+ prevPhi = phi;
136+ if (restAt === null && time >= end && (p.energyNorm() < restE || time >= end + MAX_SETTLE)) {
137+ restAt = time;
138+ // the last extension note rings: sustain, then fade; the piece ends with it
139+ if (lastNote) sink.hold(lastNote, lastNote.t, P.finalHold as number, P.finalFade as number);
140+ sink.end(time + (P.finalHold as number) + (P.finalFade as number) + 0.3);
141+ }
142+ if (time >= nextFrame) {
143+ sink.frame(0, time, [p.y[0], p.y[1]]);
144+ nextFrame = time + FRAME_DT;
145+ }
146+ if (time >= nextInfo) {
147+ nextInfo = time + INFO_DT;
148+ const free = P.freeTime as number;
149+ const phase = restAt !== null ? "at rest" : extCount === 0 ? "falling" : time < free ? "swinging" : time < end ? "damping" : "settling";
150+ sink.info(time, {
151+ phase,
152+ energy: `${(p.energy() / E0).toFixed(3)} of start`,
153+ "extension notes": String(extCount),
154+ clicks: String(clickCount),
155+ "height notes": String(heightCount),
156+ nudge: nudgeInfo,
157+ friction: `${damping(time).toFixed(4)} /sim s`,
158+ });
159+ }
160+ }
161+
162+ if (sink.emitting) sink.frame(0, 0, [p.y[0], p.y[1]]);
163+ return {
164+ get time() {
165+ return time;
166+ },
167+ advance(t: number) {
168+ while (time < t) step();
169+ },
170+ };
171+};
src/compositions/c04-descent/view.tsadded+134−0View file
@@ -0,0 +1,134 @@
1+// Composition 4: descent — drawing, from the score's data at the playhead: the pendulum (with
2+// motion blur), the outer bob's fading trail, and rings where extension notes and clicks happen.
3+
4+import type { Params } from "../../core/params.ts";
5+import type { FrameStore } from "../../stream/frames.ts";
6+import type { View } from "../../stream/piece.ts";
7+import { cssColor, fitCanvas } from "../shared/section.ts";
8+
9+const BLUR_MAX_SAMPLES = 48;
10+const BLUR_SPACING_PX = 2;
11+const RING_S = 0.9; // extension-note ring lifetime
12+const CLICK_RING_S = 0.35;
13+
14+export function descentView(el: HTMLElement, params: () => Params): View {
15+ el.classList.add("c04");
16+ const canvas = document.createElement("canvas");
17+ el.append(canvas);
18+ const st = new Float64Array(2);
19+ let lastWall = 0;
20+ let frameDt = 1 / 60;
21+
22+ return {
23+ keep: (P) => Math.max(P.trailLength as number, RING_S) + 0.5,
24+ draw(t: number, store: FrameStore | null, playing: boolean) {
25+ const P = params();
26+ const wall = performance.now() / 1000;
27+ const dtw = wall - lastWall;
28+ lastWall = wall;
29+ if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
30+ const g = fitCanvas(canvas);
31+ const w = canvas.clientWidth, h = canvas.clientHeight;
32+ g.clearRect(0, 0, w, h);
33+ const fg = cssColor(el, "--fg");
34+ const l1 = 1, l2 = P.lengthRatio as number;
35+ const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
36+ const x0 = w / 2, y0 = h / 2;
37+ const pos = (th1: number, th2: number) => {
38+ const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
39+ return [x1, y1, x1 + scale * l2 * Math.sin(th2), y1 + scale * l2 * Math.cos(th2)];
40+ };
41+ // the state at a time (balanced straight up before anything is computed)
42+ const at = (u: number): [number, number] => {
43+ const s = store?.at(0, u, st);
44+ return s ? [s[0], s[1]] : [Math.PI, Math.PI];
45+ };
46+
47+ // trail of the outer bob, fading with age
48+ if (P.trails && store) {
49+ const len = P.trailLength as number;
50+ const BANDS = 6;
51+ g.strokeStyle = fg;
52+ g.lineWidth = 1;
53+ g.lineJoin = g.lineCap = "round";
54+ for (let band = 0; band < BANDS; band++) {
55+ const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
56+ g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
57+ g.beginPath();
58+ let started = false, k = 0;
59+ store.rows(0, aOld - 0.01, Math.min(t, aNew + 0.01), (d, o) => {
60+ if (k++ % 2) return; // every other row is plenty for the trail
61+ const [, , bx, by] = pos(d[o + 1], d[o + 2]);
62+ if (started) g.lineTo(bx, by);
63+ else g.moveTo(bx, by), (started = true);
64+ });
65+ g.stroke();
66+ }
67+ g.globalAlpha = 1;
68+ }
69+
70+ // rings, where each extension note (and click) happened
71+ if (P.rings && store) {
72+ for (const c of store.events) {
73+ if (c.kind !== "ring") continue;
74+ const age = t - c.t;
75+ const click = c.click === 1;
76+ const life = click ? CLICK_RING_S : RING_S;
77+ if (age < 0 || age > life) continue;
78+ const strength = c.strength as number;
79+ const bx = x0 + scale * (c.x as number), by = y0 + scale * (c.y as number);
80+ g.strokeStyle = fg;
81+ g.globalAlpha = (1 - age / life) * (0.4 + 0.6 * strength);
82+ g.lineWidth = click ? 1 : 1.2;
83+ g.beginPath();
84+ const grow = click ? 14 : 60 * (0.5 + strength);
85+ g.arc(bx, by, (click ? 3 : 6) + grow * Math.sqrt(age / life), 0, 2 * Math.PI);
86+ g.stroke();
87+ }
88+ g.globalAlpha = 1;
89+ }
90+
91+ // the pendulum, with motion blur
92+ const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
93+ let k = 1;
94+ if (shutter > 0) {
95+ let path = 0;
96+ let a = at(t);
97+ for (let j = 1; j <= 8; j++) {
98+ const b = at(t - (shutter * j) / 8);
99+ path += scale * (l1 * Math.abs(b[0] - a[0]) + l2 * Math.abs(b[1] - a[1]));
100+ a = b;
101+ }
102+ k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
103+ }
104+ const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
105+ const r1 = 4, r2 = 4 * Math.cbrt(P.massRatio as number);
106+ g.strokeStyle = fg;
107+ g.fillStyle = fg;
108+ g.lineWidth = 1.5;
109+ g.lineCap = "round";
110+ g.globalAlpha = alpha;
111+ for (let i = 0; i < k; i++) {
112+ const [th1, th2] = at(t - (shutter * i) / Math.max(1, k - 1));
113+ const [x1, y1, x2, y2] = pos(th1, th2);
114+ g.beginPath();
115+ g.moveTo(x0, y0);
116+ g.lineTo(x1, y1);
117+ g.lineTo(x2, y2);
118+ g.stroke();
119+ g.beginPath();
120+ g.arc(x1, y1, r1, 0, 2 * Math.PI);
121+ g.moveTo(x2 + r2, y2);
122+ g.arc(x2, y2, r2, 0, 2 * Math.PI);
123+ g.fill();
124+ }
125+ g.globalAlpha = 1;
126+ g.beginPath();
127+ g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
128+ g.fill();
129+ },
130+ dispose() {
131+ el.classList.remove("c04");
132+ },
133+ };
134+}
src/compositions/c05-ensemble/harmony.tsmodified+2−1View file
@@ -51,7 +51,8 @@ export function build(basePitch: number, ratio: number, partial: number, lam: nu
5151 const [w1, w2] = modes(mu, lam); // sim rad/s at l1 = 1
5252 const target = 2 * Math.PI * basePitch * ratio; // audio rad/s for the lower partial
5353 // audio ω = sim ω · k; sim ω at size L is w1/√L → L = (w1·k / target)²
54- const L = ((w1 * k) / target) ** 2;
54+ const q = (w1 * k) / target;
55+ const L = q * q;
5556 return { l1: L, l2: lam * L, m2: mu, lower: basePitch * ratio, upper: basePitch * ratio * (w2 / w1) };
5657 }
5758
src/compositions/c05-ensemble/index.tsmodified+7−3View file
@@ -1,12 +1,16 @@
11 import type { Composition } from "../../core/composition.ts";
2+import { createStreamPiece, type StreamDef } from "../../stream/piece.ts";
23 import defaults from "./defaults.json";
3-import { createEnsemblePiece } from "./piece.ts";
4+import { estimateLength, layout } from "./layout.ts";
45 import { schema } from "./schema.ts";
6+import { ensembleView } from "./view.ts";
7+
8+const def: StreamDef = { id: "05-ensemble", schema, layout, estimateLength, view: ensembleView };
59
610 export const ensemble: Composition = {
7- id: "05-ensemble",
11+ id: def.id,
812 title: "ensemble",
913 schema,
1014 defaults,
11- create: createEnsemblePiece,
15+ create: (view, params) => createStreamPiece(def, view, params),
1216 };
src/compositions/c05-ensemble/layout.tsadded+32−0View file
@@ -0,0 +1,32 @@
1+import type { Params } from "../../core/params.ts";
2+import type { Layout } from "../../stream/layout.ts";
3+
4+/** One stem: the six pendulums' own sound, rendered by the score. */
5+export function layout(): Layout {
6+ return {
7+ stems: [{ kind: "score", output: 0 }],
8+ outputs: [{ effects: "none", level: (Q) => Q.level as number }],
9+ };
10+}
11+
12+export const START_DELAY = 0.4; // s before the first step
13+
14+/** "36 25 1!4": one step per word, the pendulums pushed together; ! accents the digit before it. */
15+export function parseScore(text: string, add: number, accent: number): { i: number; add: number }[][] {
16+ return text
17+ .trim()
18+ .split(/\s+/)
19+ .filter(Boolean)
20+ .map((w) => {
21+ const step: { i: number; add: number }[] = [];
22+ for (let c = 0; c < w.length; c++) {
23+ if (!/[1-6]/.test(w[c])) continue;
24+ step.push({ i: Number(w[c]) - 1, add: add * (w[c + 1] === "!" ? accent : 1) });
25+ }
26+ return step;
27+ });
28+}
29+
30+export const stepSec = (P: Params) => ((P.stepBeats as number) * 60) / Math.max(1, P.tempo as number);
31+export const scoreEnd = (P: Params) => START_DELAY + parseScore(P.score as string, 0, 1).length * stepSec(P);
32+export const estimateLength = (P: Params) => scoreEnd(P) + (P.tail as number);
src/compositions/c05-ensemble/piece.tsdeleted+0−278View file
@@ -1,278 +0,0 @@
1-// Ensemble lab: six audio-rate pendulums sharing one time scale, so each one's pitch comes from its
2-// size; their proportions are solved from musical ratios (see harmony.ts). A score pushes them in
3-// chords (e.g. "36 25 … 1!4"); keys 1–6 also push that pendulum, R resets them all to rest.
4-
5-import { dbToGain, type AudioEngine } from "../../core/audio.ts";
6-import type { Piece } from "../../core/composition.ts";
7-import type { Params } from "../../core/params.ts";
8-import workletUrl from "../../lab/ensembleWorklet.ts?worker&url";
9-import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap, type Signal } from "../../lab/protocol.ts";
10-import { randomSeed } from "../../core/rng.ts";
11-import { cssColor, fitCanvas } from "../shared/section.ts";
12-import { build, parseRatio, timeScale, type Built } from "./harmony.ts";
13-
14-const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
15-const START_DELAY = 0.4; // s before the first step
16-
17-/** "36 25 1!4": one step per word, the pendulums pushed together; ! accents the digit before it. */
18-export function parseScore(text: string, add: number, accent: number): { i: number; add: number }[][] {
19- return text
20- .trim()
21- .split(/\s+/)
22- .filter(Boolean)
23- .map((w) => {
24- const step: { i: number; add: number }[] = [];
25- for (let c = 0; c < w.length; c++) {
26- if (!/[1-6]/.test(w[c])) continue;
27- const loud = w[c + 1] === "!";
28- step.push({ i: Number(w[c]) - 1, add: add * (loud ? accent : 1) });
29- }
30- return step;
31- });
32-}
33-
34-export function createEnsemblePiece(view: HTMLElement, params: () => Params): Piece {
35- const canvas = document.createElement("canvas");
36- view.append(canvas);
37-
38- let audio: AudioEngine | null = null;
39- let node: AudioWorkletNode | null = null;
40- let out: GainNode | null = null;
41- let timer: number | undefined;
42- let playing = false;
43- let startedAt = 0;
44- let snap: EnsembleSnap | null = null;
45- let lastSent = "";
46- let token = 0;
47- let ended = false;
48- let seedUsed = 0;
49-
50- /** Physics for every pendulum from the musical ratios: one time scale, sizes and masses solved. */
51- function physics(P: Params): { k: number; built: Built[] } {
52- const base = P.basePitch as number;
53- const v = Array.from({ length: ENSEMBLE }, (_, i) => ({
54- ratio: parseRatio(P[`ratio${i + 1}`] as string),
55- partial: parseRatio(P[`partial${i + 1}`] as string),
56- shape: P[`shape${i + 1}`] as number,
57- }));
58- // the lowest-pitched pendulum is the biggest: give it l1 = 1
59- const low = v.reduce((a, b) => (b.ratio < a.ratio ? b : a));
60- const k = timeScale(base, low.ratio, low.partial, low.shape);
61- return { k, built: v.map((x) => build(base, x.ratio, x.partial, x.shape, k)) };
62- }
63-
64- const settings = (P: Params): EnsembleSettings => {
65- const { k, built } = physics(P);
66- return {
67- voices: built.map((b, i) => ({
68- l1: b.l1,
69- l2: b.l2,
70- m2: b.m2,
71- upperHz: b.upper,
72- ringTime: P[`ring${i + 1}`] as number,
73- level: dbToGain(P[`level${i + 1}`] as number),
74- })),
75- k,
76- pulseAdds: P.pulseAdds as number,
77- score: parseScore(P.score as string, P.pulseAdds as number, P.accent as number),
78- stepSec: stepSec(P),
79- startDelay: START_DELAY,
80- seed: seedUsed,
81- signal: P.signal as Signal,
82- gain: dbToGain(P.gain as number),
83- dcCut: P.dcCut as number,
84- spread: P.spread as number,
85- };
86- };
87-
88- const stepSec = (P: Params) => ((P.stepBeats as number) * 60) / Math.max(1, P.tempo as number);
89- const scoreEnd = (P: Params) => START_DELAY + parseScore(P.score as string, 0, 1).length * stepSec(P);
90- const total = (P: Params) => scoreEnd(P) + (P.tail as number);
91-
92- const send = (m: EnsembleMsg) => node?.port.postMessage(m);
93- const onKey = (e: KeyboardEvent) => {
94- const el = e.target;
95- if (el instanceof Element && el.closest("input, select, textarea")) return;
96- if (/^[1-6]$/.test(e.key)) send({ type: "strike", i: Number(e.key) - 1 });
97- else if (e.key === "r" || e.key === "R") send({ type: "reset" });
98- };
99- window.addEventListener("keydown", onKey);
100-
101- function sync() {
102- if (!node || !audio || !out) return;
103- const P = params();
104- const key = JSON.stringify(settings(P));
105- if (key !== lastSent) {
106- lastSent = key;
107- send({ type: "settings", s: settings(P) });
108- }
109- // the end: fade over the last `fade` s of the ring-out, then stop
110- const t = audio.ctx.currentTime - startedAt, T = total(P);
111- const fade = Math.min(P.fade as number, P.tail as number);
112- const k = Math.max(0, Math.min(1, (T - t) / fade));
113- out.gain.setTargetAtTime(dbToGain(P.level as number) * k * k, audio.ctx.currentTime, 0.05);
114- if (t >= T && !ended) {
115- ended = true;
116- stop();
117- piece.onEnded?.();
118- }
119- }
120-
121- async function start(a: AudioEngine) {
122- stop();
123- const my = ++token;
124- audio = a;
125- const ctx = a.ctx;
126- let p = loaded.get(ctx);
127- if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl)));
128- await p;
129- if (my !== token) return;
130- ended = false;
131- snap = null;
132- const P0 = params();
133- seedUsed = (P0.seed as number) > 0 ? Math.round(P0.seed as number) : randomSeed();
134- out = ctx.createGain();
135- out.gain.value = 0;
136- node = new AudioWorkletNode(ctx, "pendulum-ensemble", { numberOfInputs: 0, outputChannelCount: [2] });
137- node.port.onmessage = (e: MessageEvent<EnsembleSnap>) => (snap = e.data);
138- node.connect(out).connect(a.input);
139- lastSent = "";
140- sync();
141- playing = true;
142- startedAt = ctx.currentTime;
143- timer = window.setInterval(sync, 50);
144- }
145-
146- function stop() {
147- token++;
148- if (timer !== undefined) window.clearInterval(timer);
149- timer = undefined;
150- playing = false;
151- if (!audio) return;
152- const o = out, n = node;
153- if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03);
154- window.setTimeout(() => {
155- n?.disconnect();
156- o?.disconnect();
157- }, 300);
158- node = out = null;
159- }
160-
161- // Layout: the pendulums hang from one line, left to right as listed, each given room in proportion
162- // to its size (most of its sideways reach: big swings may overlap a neighbour).
163- function layout(dr: number[], w: number, h: number) {
164- const ROOM = 1.5, GAP = 0.2; // drawn reaches of room per pendulum, and between pendulums
165- const fit = (rows: number[][]) => {
166- const rh = h / rows.length;
167- let unit = Infinity;
168- for (const r of rows) {
169- const span = r.reduce((a, i) => a + ROOM * dr[i], 0) + GAP * (r.length - 1);
170- unit = Math.min(unit, (0.92 * w) / span, (0.5 * rh) / Math.max(...r.map((i) => dr[i])));
171- }
172- return { rows, rh, unit };
173- };
174- const { rows, rh, unit } = fit([[0, 1, 2, 3, 4, 5]]);
175- const at: { x: number; y: number }[] = [];
176- rows.forEach((r, ri) => {
177- const span = (r.reduce((a, i) => a + ROOM * dr[i], 0) + GAP * (r.length - 1)) * unit;
178- // hang the row so its resting pendulums sit centred in the row
179- const y = ri * rh + rh / 2 - (Math.max(...r.map((i) => dr[i])) * unit) / 2;
180- let x = (w - span) / 2;
181- for (const i of r) {
182- at[i] = { x: x + (ROOM / 2) * dr[i] * unit, y };
183- x += (ROOM * dr[i] + GAP) * unit;
184- }
185- });
186- return { unit, at };
187- }
188-
189- function draw() {
190- const P = params();
191- const g = fitCanvas(canvas);
192- const w = canvas.clientWidth, h = canvas.clientHeight;
193- g.clearRect(0, 0, w, h);
194- const fg = cssColor(view, "--fg"), muted = cssColor(view, "--muted");
195- const { built } = physics(P);
196- // compared sizes: length^sizeExp (true scale would make the highest a speck)
197- const ex = P.sizeExp as number;
198- const reach = built.map((b) => b.l1 + b.l2);
199- const dr = reach.map((r) => Math.pow(r, ex));
200- const { unit, at } = layout(dr, w, h);
201- const TR = snap ? snap.trails.length / (2 * ENSEMBLE) : 0;
202- const trailA = P.trail as number;
203- g.lineCap = "round";
204- g.lineJoin = "round";
205- for (let i = 0; i < ENSEMBLE; i++) {
206- const { x: cx, y: cy } = at[i];
207- const f = (unit * dr[i]) / reach[i]; // physical units → px for this pendulum
208- if (snap && trailA > 0) {
209- const o = i * 2 * TR;
210- g.strokeStyle = muted;
211- g.globalAlpha = trailA;
212- g.lineWidth = 1;
213- g.beginPath();
214- for (let j = 0; j < TR; j++) {
215- const x = cx + f * snap.trails[o + 2 * j], y = cy + f * snap.trails[o + 2 * j + 1];
216- if (j) g.lineTo(x, y);
217- else g.moveTo(x, y);
218- }
219- g.stroke();
220- }
221- const jt = snap ? snap.joints.subarray(4 * i, 4 * i + 4) : [0, built[i].l1, 0, reach[i]];
222- const x1 = cx + f * jt[0], y1 = cy + f * jt[1], x2 = cx + f * jt[2], y2 = cy + f * jt[3];
223- // a push brightens the pendulum, fading over a second
224- const age = snap ? snap.struck[i] : 1e9;
225- g.globalAlpha = 0.6 + 0.4 * Math.max(0, 1 - age);
226- g.strokeStyle = fg;
227- g.fillStyle = fg;
228- g.lineWidth = 1.5;
229- g.beginPath();
230- g.moveTo(cx, cy);
231- g.lineTo(x1, y1);
232- g.lineTo(x2, y2);
233- g.stroke();
234- const r2 = 2.2 * Math.cbrt(built[i].m2) + 1;
235- g.beginPath();
236- g.arc(x1, y1, 2, 0, 2 * Math.PI);
237- g.moveTo(x2 + r2, y2);
238- g.arc(x2, y2, r2, 0, 2 * Math.PI);
239- g.moveTo(cx + 1.5, cy);
240- g.arc(cx, cy, 1.5, 0, 2 * Math.PI);
241- g.fill();
242- }
243- g.globalAlpha = 1;
244- }
245-
246- function readouts(): Record<string, string> {
247- const { k, built } = physics(params());
248- const r: Record<string, string> = {
249- keys: "1–6: push that pendulum · R: reset to rest",
250- score: snap ? `step ${snap.step} of ${parseScore(params().score as string, 0, 1).length}` : "–",
251- length: `${total(params()).toFixed(1)} s`,
252- "seed used": seedUsed ? String(seedUsed) : "–",
253- "time scale": `${k.toFixed(0)} sim s per s`,
254- };
255- built.forEach((b, i) => {
256- r[`pendulum ${i + 1}`] = `${b.lower.toFixed(1)} + ${b.upper.toFixed(1)} Hz; l1 ${b.l1.toFixed(3)}, l2 ${b.l2.toFixed(3)}, m2/m1 ${b.m2.toFixed(2)}${snap ? `; E ${snap.energy[i].toFixed(2)}` : ""}`;
257- });
258- return r;
259- }
260-
261- const piece: Piece = {
262- get playing() {
263- return playing;
264- },
265- start: (a) => start(a),
266- stop,
267- draw,
268- now: () => (playing && audio ? audio.ctx.currentTime - startedAt : ended ? total(params()) : 0),
269- length: () => total(params()),
270- readouts,
271- dispose() {
272- stop();
273- window.removeEventListener("keydown", onKey);
274- view.replaceChildren();
275- },
276- };
277- return piece;
278-}
src/compositions/c05-ensemble/schema.tsmodified+4−4View file
@@ -16,13 +16,13 @@ const VOICE_DEFAULTS: [string, string, number, number][] = [
1616
1717 export const schema: ParamSpec[] = [
1818 { group: "harmony", key: "basePitch", label: "base pitch", kind: "number", default: 73.42, min: 20, max: 1000, log: true, unit: "Hz", hint: "pitch ratio 1 sounds here (D2 by default); all pendulums share one time scale, so each pitch comes from its size" },
19- { group: "visual", key: "sizeExp", label: "size drawing", kind: "number", default: 0.5, min: 0, max: 1, step: 0.05, hint: "drawn size ∝ length^this (1 = true scale: two octaves = 16× the length)" },
20- { group: "visual", key: "trail", label: "trail", kind: "number", default: 0.35, min: 0, max: 1, step: 0.01, hint: "opacity of the bobs' recent paths" },
19+ { group: "visual", key: "sizeExp", label: "size drawing", kind: "number", default: 0.5, min: 0, max: 1, step: 0.05, hint: "drawn size ∝ length^this (1 = true scale: two octaves = 16× the length)", live: true },
20+ { group: "visual", key: "trail", label: "trail", kind: "number", default: 0.35, min: 0, max: 1, step: 0.01, hint: "opacity of the bobs' recent paths", live: true },
2121
2222 { group: "score", key: "score", label: "score", kind: "text", default: "36 25 36 25 36 25 1!4", hint: "one step per word: the pendulums pushed together (1–6); ! after a digit = accented; . = a rest" },
2323 { group: "score", key: "tempo", label: "tempo", kind: "number", default: 120, min: 10, max: 400, log: true, unit: "bpm" },
2424 { group: "score", key: "stepBeats", label: "step length", kind: "number", default: 4, min: 0.25, max: 16, step: 0.25, unit: "beats", hint: "4 = a whole note per step" },
25- { group: "score", key: "pulseAdds", label: "push adds", kind: "number", default: 0.08, min: 0.0005, max: 2, log: true, hint: "energy each push (score or keys 1–6) adds, in units of E_top" },
25+ { group: "score", key: "pulseAdds", label: "push adds", kind: "number", default: 0.08, min: 0.0005, max: 2, log: true, hint: "energy each push adds, in units of E_top" },
2626 { group: "score", key: "accent", label: "accent", kind: "number", default: 4, min: 1, max: 20, log: true, unit: "×", hint: "an accented push (!) adds this many times the energy" },
2727 { group: "score", key: "tail", label: "ring out", kind: "number", default: 16, min: 1, max: 120, log: true, unit: "s", hint: "after the last step, before the end" },
2828 { group: "score", key: "seed", label: "seed", kind: "number", default: 0, min: 0, max: 999999, step: 1, hint: "pushes from rest go in random directions (the mix of each pendulum's two pitches); 0 = a new variation every play" },
@@ -32,7 +32,7 @@ export const schema: ParamSpec[] = [
3232 { group: "sound", key: "gain", label: "gain", kind: "number", default: 0, min: -40, max: 30, step: 0.5, unit: "dB", hint: "per pendulum, before its soft limiter" },
3333 { group: "sound", key: "spread", label: "stereo spread", kind: "number", default: 0.7, min: 0, max: 1, step: 0.01 },
3434 { group: "sound", key: "dcCut", label: "low cut", kind: "number", default: 20, min: 1, max: 500, log: true, unit: "Hz" },
35- { group: "sound", key: "level", label: "level", kind: "number", default: 0, min: -48, max: 12, step: 0.5, unit: "dB" },
35+ { group: "sound", key: "level", label: "level", kind: "number", default: 0, min: -48, max: 12, step: 0.5, unit: "dB", live: true },
3636
3737 ...VOICE_DEFAULTS.flatMap(([ratio, partial, shape, ring], i): ParamSpec[] => {
3838 const g = `pendulum ${i + 1}`;
src/compositions/c05-ensemble/score.tsadded+129−0View file
@@ -0,0 +1,129 @@
1+// Composition 5: ensemble — the score (score worker). The sound is the pendulums themselves:
2+// six double pendulums simulated at audio rate on one shared time scale (so each one's pitch comes
3+// from its size; proportions solved from musical ratios in harmony.ts), each contributing a state
4+// quantity (by default its outer bob's horizontal position) as its waveform. The score pushes them
5+// in chords ("36 25 … 1!4"); after the last step they ring out and fade.
6+//
7+// Drawing data: track 0 = per pendulum [x1, y1, x2, y2] (120 per piece second); track 1 = per
8+// pendulum [x2, y2] (8000 per piece second, for the bobs' short paths); events "push" (i).
9+
10+import type { Params } from "../../core/params.ts";
11+import { mulberry32 } from "../../core/rng.ts";
12+import { DcBlock, kick, signal } from "../../lab/voice.ts";
13+import type { Signal } from "../../lab/protocol.ts";
14+import { cos, exp, sin, tanh } from "../../physics/dmath.ts";
15+import { DoublePendulum } from "../../physics/doublePendulum.ts";
16+import { SAMPLE_RATE } from "../../stream/protocol.ts";
17+import type { ScoreFactory } from "../../stream/score.ts";
18+import { build, parseRatio, timeScale, type Built } from "./harmony.ts";
19+import { START_DELAY, parseScore, scoreEnd, stepSec } from "./layout.ts";
20+
21+export const N = 6;
22+const STEPS_PER_CYCLE = 40; // RK4 steps per cycle of a pendulum's faster mode, at least
23+const JOINTS_EVERY = SAMPLE_RATE / 120;
24+const BOBS_EVERY = 6; // samples between rows of the bobs' paths (8 kHz)
25+
26+/** Physics for every pendulum from the musical ratios: one time scale, sizes and masses solved. */
27+export function physics(P: Params): { k: number; built: Built[] } {
28+ const base = P.basePitch as number;
29+ const v = Array.from({ length: N }, (_, i) => ({
30+ ratio: parseRatio(P[`ratio${i + 1}`] as string),
31+ partial: parseRatio(P[`partial${i + 1}`] as string),
32+ shape: P[`shape${i + 1}`] as number,
33+ }));
34+ // the lowest-pitched pendulum is the biggest: give it l1 = 1
35+ const low = v.reduce((a, b) => (b.ratio < a.ratio ? b : a));
36+ const k = timeScale(base, low.ratio, low.partial, low.shape);
37+ return { k, built: v.map((x) => build(base, x.ratio, x.partial, x.shape, k)) };
38+}
39+
40+export const ensembleScore: ScoreFactory = (P: Params, seed: number, sink) => {
41+ const { k, built } = physics(P);
42+ const rand = mulberry32(seed);
43+ const sig = P.signal as Signal;
44+ const gain = exp((P.gain as number) * 0.11512925464970229); // dB → linear
45+ const dcR = 1 - (2 * Math.PI * (P.dcCut as number)) / SAMPLE_RATE;
46+ const steps = parseScore(P.score as string, P.pulseAdds as number, P.accent as number);
47+ const stepS = stepSec(P);
48+ const end = scoreEnd(P) + (P.tail as number);
49+ const fadeLen = Math.min(P.fade as number, P.tail as number);
50+ const dtS = k / SAMPLE_RATE;
51+ const voices = built.map((b, i) => {
52+ const p = new DoublePendulum({ m1: 1, m2: b.m2, l1: b.l1, l2: b.l2, g: 1 });
53+ p.controlled = false;
54+ const ring = P[`ring${i + 1}`] as number;
55+ p.damping = ring > 0 ? (2 * 6.9078) / (ring * k) : 0;
56+ const sub = Math.max(1, Math.ceil((STEPS_PER_CYCLE * b.upper) / SAMPLE_RATE));
57+ const pan = P.spread as number * ((2 * i) / (N - 1) - 1);
58+ const a = ((pan + 1) * Math.PI) / 4; // equal-power
59+ const level = exp((P[`level${i + 1}`] as number) * 0.11512925464970229);
60+ return { p, dc: new DcBlock(), sub, h: dtS / sub, gl: cos(a) * level, gr: sin(a) * level };
61+ });
62+
63+ let sample = 0; // samples simulated
64+ let step = 0; // score steps played
65+ let ended = false;
66+ const joints = new Float64Array(4 * N), bobs = new Float64Array(2 * N);
67+
68+ function advance(t: number) {
69+ if (!ended) {
70+ ended = true;
71+ sink.end(end);
72+ }
73+ const target = Math.round(t * SAMPLE_RATE);
74+ const n = target - sample;
75+ if (n <= 0) return;
76+ const L = new Float32Array(n), R = new Float32Array(n);
77+ for (let j = 0; j < n; j++, sample++) {
78+ const time = sample / SAMPLE_RATE;
79+ // the score: step k falls at START_DELAY + k·step
80+ if (step < steps.length && time >= START_DELAY + step * stepS) {
81+ for (const push of steps[step]) {
82+ const v = voices[push.i];
83+ if (!v) continue;
84+ kick(v.p, push.add * v.p.vTop, rand);
85+ sink.event({ t: time, kind: "push", i: push.i });
86+ }
87+ step++;
88+ }
89+ let l = 0, r = 0;
90+ for (const v of voices) {
91+ for (let s = 0; s < v.sub; s++) v.p.step(v.h);
92+ if (!Number.isFinite(v.p.y[0])) v.p.y.fill(0);
93+ const d = v.p.derived();
94+ const x = tanh(gain * v.dc.run(signal(v.p, sig, d.w1, d.w2), dcR));
95+ l += v.gl * x;
96+ r += v.gr * x;
97+ }
98+ // the end: fade over the last `fadeLen` s
99+ const u = Math.max(0, Math.min(1, (end - time) / fadeLen));
100+ L[j] = l * u * u;
101+ R[j] = r * u * u;
102+ if (sample % BOBS_EVERY === 0) {
103+ voices.forEach((v, i) => {
104+ const y = v.p.y, c = v.p.cfg;
105+ bobs[2 * i] = c.l1 * sin(y[0]) + c.l2 * sin(y[1]);
106+ bobs[2 * i + 1] = c.l1 * cos(y[0]) + c.l2 * cos(y[1]);
107+ });
108+ sink.frame(1, time, bobs);
109+ }
110+ if (sample % JOINTS_EVERY === 0) {
111+ voices.forEach((v, i) => {
112+ const y = v.p.y, c = v.p.cfg;
113+ const x1 = c.l1 * sin(y[0]), y1 = c.l1 * cos(y[0]);
114+ joints.set([x1, y1, x1 + c.l2 * sin(y[1]), y1 + c.l2 * cos(y[1])], 4 * i);
115+ });
116+ sink.frame(0, time, joints);
117+ sink.info(time, { score: `step ${step} of ${steps.length}`, energies: voices.map((v) => v.p.energyNorm().toFixed(2)).join(" ") });
118+ }
119+ }
120+ sink.audio(0, L, R);
121+ }
122+
123+ return {
124+ get time() {
125+ return sample / SAMPLE_RATE;
126+ },
127+ advance,
128+ };
129+};
src/compositions/c05-ensemble/view.tsadded+112−0View file
@@ -0,0 +1,112 @@
1+// Composition 5: ensemble — drawing at the playhead: the six pendulums hanging in one row, left to
2+// right as listed (lowest pitch first), each given room in proportion to its drawn size. A push
3+// brightens a pendulum briefly; a faint trail follows each bob over the last few milliseconds.
4+
5+import type { Params } from "../../core/params.ts";
6+import type { View } from "../../stream/piece.ts";
7+import { cssColor, fitCanvas } from "../shared/section.ts";
8+import { N, physics } from "./score.ts";
9+
10+const TRAIL_S = 0.012; // the bobs' paths over this long
11+
12+/** Each pendulum's pivot, and drawing units → px (most of a pendulum's sideways reach as room). */
13+function rowLayout(dr: number[], w: number, h: number) {
14+ const ROOM = 1.5, GAP = 0.2;
15+ const span = dr.reduce((a, d) => a + ROOM * d, 0) + GAP * (dr.length - 1);
16+ const unit = Math.min((0.92 * w) / span, (0.5 * h) / Math.max(...dr));
17+ const y = h / 2 - (Math.max(...dr) * unit) / 2; // the resting row sits centred
18+ let x = (w - span * unit) / 2;
19+ const at = dr.map((d) => {
20+ const p = { x: x + (ROOM / 2) * d * unit, y };
21+ x += (ROOM * d + GAP) * unit;
22+ return p;
23+ });
24+ return { unit, at };
25+}
26+
27+export function ensembleView(el: HTMLElement, params: () => Params): View {
28+ el.classList.add("c05");
29+ const canvas = document.createElement("canvas");
30+ el.append(canvas);
31+ const joints = new Float64Array(4 * N);
32+ let physKey = "";
33+ let built = physics(params()).built;
34+
35+ return {
36+ keep: () => 1.5,
37+ draw(t, store) {
38+ const P = params();
39+ const key = JSON.stringify([P.basePitch, ...Array.from({ length: N }, (_, i) => [P[`ratio${i + 1}`], P[`partial${i + 1}`], P[`shape${i + 1}`]])]);
40+ if (key !== physKey) {
41+ physKey = key;
42+ built = physics(P).built;
43+ }
44+ const g = fitCanvas(canvas);
45+ const w = canvas.clientWidth, h = canvas.clientHeight;
46+ g.clearRect(0, 0, w, h);
47+ const fg = cssColor(el, "--fg"), muted = cssColor(el, "--muted");
48+ // compared sizes: length^sizeExp (true scale would make the highest a speck)
49+ const ex = P.sizeExp as number;
50+ const reach = built.map((b) => b.l1 + b.l2);
51+ const dr = reach.map((r) => Math.pow(r, ex));
52+ const { unit, at } = rowLayout(dr, w, h);
53+ const s = store?.at(0, t, joints) ?? null;
54+ const trailA = P.trail as number;
55+ // when each pendulum was last pushed
56+ const pushed = Array(N).fill(-Infinity);
57+ if (store) for (const e of store.events) if (e.kind === "push" && e.t <= t) pushed[e.i as number] = e.t;
58+ g.lineCap = "round";
59+ g.lineJoin = "round";
60+ for (let i = 0; i < N; i++) {
61+ const { x: cx, y: cy } = at[i];
62+ const f = (unit * dr[i]) / reach[i]; // physical units → px for this pendulum
63+ if (store && trailA > 0) {
64+ g.strokeStyle = muted;
65+ g.globalAlpha = trailA;
66+ g.lineWidth = 1;
67+ g.beginPath();
68+ let started = false;
69+ store.rows(1, t - TRAIL_S, t, (d, o) => {
70+ const x = cx + f * d[o + 1 + 2 * i], y = cy + f * d[o + 2 + 2 * i];
71+ if (started) g.lineTo(x, y);
72+ else g.moveTo(x, y), (started = true);
73+ });
74+ g.stroke();
75+ }
76+ const b = built[i];
77+ const jt = s ? s.subarray(4 * i, 4 * i + 4) : [0, b.l1, 0, reach[i]];
78+ const x1 = cx + f * jt[0], y1 = cy + f * jt[1], x2 = cx + f * jt[2], y2 = cy + f * jt[3];
79+ // a push brightens the pendulum, fading over a second
80+ g.globalAlpha = 0.6 + 0.4 * Math.max(0, 1 - (t - pushed[i]));
81+ g.strokeStyle = fg;
82+ g.fillStyle = fg;
83+ g.lineWidth = 1.5;
84+ g.beginPath();
85+ g.moveTo(cx, cy);
86+ g.lineTo(x1, y1);
87+ g.lineTo(x2, y2);
88+ g.stroke();
89+ const r2 = 2.2 * Math.cbrt(b.m2) + 1;
90+ g.beginPath();
91+ g.arc(x1, y1, 2, 0, 2 * Math.PI);
92+ g.moveTo(x2 + r2, y2);
93+ g.arc(x2, y2, r2, 0, 2 * Math.PI);
94+ g.moveTo(cx + 1.5, cy);
95+ g.arc(cx, cy, 1.5, 0, 2 * Math.PI);
96+ g.fill();
97+ }
98+ g.globalAlpha = 1;
99+ },
100+ readouts() {
101+ const { k } = physics(params());
102+ const r: Record<string, string> = { "time scale": `${k.toFixed(0)} sim s per s` };
103+ built.forEach((b, i) => {
104+ r[`pendulum ${i + 1}`] = `${b.lower.toFixed(1)} + ${b.upper.toFixed(1)} Hz; l1 ${b.l1.toFixed(3)}, l2 ${b.l2.toFixed(3)}, m2/m1 ${b.m2.toFixed(2)}`;
105+ });
106+ return r;
107+ },
108+ dispose() {
109+ el.classList.remove("c05");
110+ },
111+ };
112+}
src/compositions/scores.tsadded+15−0View file
@@ -0,0 +1,15 @@
1+// Every composition's score, by id, for the score worker (worker-safe modules only).
2+import type { ScoreFactory } from "../stream/score.ts";
3+import { poincareScore } from "./c01-poincare/score.ts";
4+import { orbitsScore } from "./c02-orbits/score.ts";
5+import { divergenceScore } from "./c03-divergence/score.ts";
6+import { descentScore } from "./c04-descent/score.ts";
7+import { ensembleScore } from "./c05-ensemble/score.ts";
8+
9+export const SCORES: Record<string, ScoreFactory> = {
10+ "01-poincare": poincareScore,
11+ "02-orbits": orbitsScore,
12+ "03-divergence": divergenceScore,
13+ "04-descent": descentScore,
14+ "05-ensemble": ensembleScore,
15+};
src/compositions/shared/form.tsmodified+4−3View file
@@ -1,4 +1,5 @@
11 import type { Params } from "../../core/params.ts";
2+import { pow } from "../../physics/dmath.ts";
23
34 /** Target energy (units of E_top) at piece time t: start → peak → hold → zero at duration. */
45 export function energyTarget(P: Params, t: number): number {
@@ -9,13 +10,13 @@ export function energyTarget(P: Params, t: number): number {
910 const e1 = P.energyPeak as number;
1011 if (t < 0) return e0;
1112 if (t < peakT) {
12- const u = Math.pow(t / peakT, P.riseCurve as number);
13- return P.riseShape === "exponential" ? e0 * Math.pow(e1 / e0, u) : e0 + (e1 - e0) * u;
13+ const u = pow(t / peakT, P.riseCurve as number);
14+ return P.riseShape === "exponential" ? e0 * pow(e1 / e0, u) : e0 + (e1 - e0) * u;
1415 }
1516 if (t < holdEnd) return e1;
1617 if (t < dur) {
1718 const u = (t - holdEnd) / (dur - holdEnd);
18- return e1 * Math.pow(1 - u, P.fallCurve as number);
19+ return e1 * pow(1 - u, P.fallCurve as number);
1920 }
2021 return 0;
2122 }
src/compositions/shared/hum.tsdeleted+0−77View file
@@ -1,77 +0,0 @@
1-// The energy hum: one drone instrument whose timbre follows the energy, with fade-in at the start
2-// and a fade-out that ends with the piece. Shared by the compositions.
3-import { dbToGain } from "../../core/audio.ts";
4-import type { Params } from "../../core/params.ts";
5-import { DRONE_INSTRUMENTS } from "../../instruments/index.ts";
6-import type { DroneInstrument } from "../../instruments/types.ts";
7-import { midiToFreq } from "../../music/scales.ts";
8-
9-export class Hum {
10- inst: DroneInstrument | null = null;
11- private key = "";
12-
13- /** Create the instrument (or switch it, crossfading, if the setting changed while playing). */
14- ensure(ctx: AudioContext, out: AudioNode, P: Params, playing: boolean) {
15- const name = P.humInstrument as string;
16- const key = name === "modal: custom" ? `${name}\n${P.humCustom}` : name;
17- if (this.inst && this.key === key) return;
18- const old = this.inst;
19- this.key = key;
20- const h = DRONE_INSTRUMENTS[name](ctx, out, { custom: P.humCustom as string });
21- this.inst = h;
22- if (old && playing) {
23- const t = ctx.currentTime;
24- old.stop(t + 0.5, 0.5);
25- window.setTimeout(() => old.dispose(), 1500);
26- void (h.ready ?? Promise.resolve()).then(() => h === this.inst && h.start(ctx.currentTime + 0.05, midiToFreq(P.humPitch as number)));
27- }
28- }
29-
30- get ready(): Promise<void> | undefined {
31- return this.inst?.ready;
32- }
33-
34- start(ctx: AudioContext, P: Params) {
35- this.inst?.start(ctx.currentTime + 0.05, midiToFreq(P.humPitch as number));
36- }
37-
38- /**
39- * e: normalized energy now; t: piece time; end: piece time everything has faded, or null while
40- * still running (the fade-out only begins once the end is known).
41- */
42- update(ctx: AudioContext, P: Params, e: number, t: number, end: number | null) {
43- if (!this.inst) return;
44- const peak = P.energyPeak as number;
45- const rel = Math.max(0, Math.min(1, e / peak));
46- const e0 = Math.min(P.energyStart as number, 0.999 * peak);
47- const colorBase =
48- P.humColorMode === "log" ? Math.max(0, Math.min(1, Math.log(Math.max(e, 1e-12) / e0) / Math.log(peak / e0))) : rel;
49- const fadeIn = P.humFadeIn as number;
50- const fadeOut = P.humFadeOut as number;
51- const fade = Math.min(1, fadeIn > 0 ? t / fadeIn : 1, end !== null && fadeOut > 0 ? (end - t) / fadeOut : 1);
52- const follow = P.humFollow as number;
53- this.inst.set(ctx.currentTime, {
54- level: dbToGain(P.humLevel as number) * Math.max(0, fade) * (1 - follow + follow * rel),
55- color: Math.pow(colorBase, P.humColorCurve as number),
56- freq: midiToFreq(P.humPitch as number),
57- normalize: P.humNormalize as boolean,
58- timbre: [1, 2]
59- .filter((i) => P[`humTarget${i}`] !== "none")
60- .map((i) => ({ target: P[`humTarget${i}`] as string, from: P[`humFrom${i}`] as number, to: P[`humTo${i}`] as number })),
61- });
62- }
63-
64- describe(): string {
65- return this.inst?.describe?.() || "–";
66- }
67-
68- /** Release: fade out if it was sounding, then dispose. */
69- release(ctx: AudioContext, wasPlaying: boolean) {
70- const h = this.inst;
71- if (!h) return;
72- if (wasPlaying) h.stop(ctx.currentTime + 0.3, 0.3); // a hum is only started once playing
73- window.setTimeout(() => h.dispose(), 600);
74- this.inst = null;
75- this.key = "";
76- }
77-}
src/compositions/shared/humScore.tsadded+63−0View file
@@ -0,0 +1,63 @@
1+// The energy hum, in the score: one held note of a sustained sound whose timbre follows the energy,
2+// with a fade-in at the start and a fade-out that ends with the piece. Its overall level is the
3+// output's live level (humLevel); the score sends the fades, the loudness-follow and the timbre.
4+
5+import type { Params } from "../../core/params.ts";
6+import { LIVE_TARGETS, targetRange, targetValue } from "../../instruments/sounds.ts";
7+import { log, pow } from "../../physics/dmath.ts";
8+import type { ScoreSink } from "../../stream/score.ts";
9+
10+const CONTROL_DT = 0.05; // s of piece time between control updates
11+
12+export class HumScore {
13+ private started = false;
14+ private next = 0;
15+ private sent: Record<string, number> = {};
16+
17+ private P: Params;
18+ private stem: number;
19+ private sink: ScoreSink;
20+
21+ constructor(P: Params, stem: number, sink: ScoreSink) {
22+ this.P = P;
23+ this.stem = stem;
24+ this.sink = sink;
25+ }
26+
27+ /** e: normalized energy at piece time t; end: piece time everything has faded (null until known). */
28+ update(t: number, e: number, end: number | null) {
29+ const { P, sink, stem } = this;
30+ if (!sink.emitting || t < this.next) return;
31+ this.next = t + CONTROL_DT;
32+ if (!this.started) {
33+ this.started = true;
34+ sink.cmd(stem, { t, type: "gain", value: 0, tau: 0 });
35+ sink.cmd(stem, { t, type: "noteOn", note: P.humPitch as number, vel: 1 });
36+ }
37+ const peak = P.energyPeak as number;
38+ const rel = Math.max(0, Math.min(1, e / peak));
39+ const e0 = Math.min(P.energyStart as number, 0.999 * peak);
40+ const colorBase = P.humColorMode === "log" ? Math.max(0, Math.min(1, log(Math.max(e, 1e-12) / e0) / log(peak / e0))) : rel;
41+ const fadeIn = P.humFadeIn as number, fadeOut = P.humFadeOut as number;
42+ const fade = Math.max(0, Math.min(1, fadeIn > 0 ? t / fadeIn : 1, end !== null && fadeOut > 0 ? (end - t) / fadeOut : 1));
43+ const follow = P.humFollow as number;
44+ sink.cmd(stem, { t, type: "gain", value: fade * (1 - follow + follow * rel), tau: 0.08, normalize: P.humNormalize as boolean });
45+ // timbre: the mapped settings, sent when they move noticeably
46+ const color = pow(colorBase, P.humColorCurve as number);
47+ const params: Record<string, number> = {};
48+ let changed = false;
49+ for (const i of [1, 2]) {
50+ const target = P[`humTarget${i}`] as string;
51+ if (target === "none" || !LIVE_TARGETS.includes(target)) continue;
52+ const from = P[`humFrom${i}`] as number, to = P[`humTo${i}`] as number;
53+ const v = targetValue(target, from + (to - from) * color, pow);
54+ if (!Number.isFinite(v)) continue;
55+ params[target] = v;
56+ if (this.sent[target] === undefined || Math.abs(v - this.sent[target]) > 0.002 * targetRange(target)) changed = true;
57+ }
58+ if (changed) {
59+ this.sent = params;
60+ sink.cmd(stem, { t, type: "params", params });
61+ }
62+ }
63+}
src/compositions/shared/noteMap.tsmodified+5−6View file
@@ -1,11 +1,11 @@
1-// Poincaré crossing → note: θ2 → pitch (scale-quantized), |p2| → loudness, θ2 → pan.
1+// Poincaré crossing → note: θ2 → pitch (scale-quantized), |p2| → loudness. Deterministic (dmath).
22 import type { Params } from "../../core/params.ts";
33 import { NOTE_NAMES, quantize } from "../../music/scales.ts";
4+import { pow } from "../../physics/dmath.ts";
45
56 export interface MappedNote {
67 midi: number;
78 velocity: number;
8- pan: number;
99 }
1010
1111 /** `octave` shifts the pitch range (e.g. per orbit in composition 2) before quantizing. */
@@ -16,14 +16,13 @@ export function noteFor(P: Params, th2: number, p2: number, octave = 0): MappedN
1616 ? Math.min(1, Math.abs(th2) / range)
1717 : Math.max(0, Math.min(1, 0.5 + (0.5 * th2) / range));
1818 if (P.invertPitch) u = 1 - u;
19- u = Math.pow(u, P.pitchCurve as number);
19+ u = pow(u, P.pitchCurve as number);
2020 const low = P.pitchLow as number, high = P.pitchHigh as number;
2121 const root = NOTE_NAMES.indexOf(P.root as string);
2222 const midi = quantize(low + (high - low) * u + 12 * octave, P.scale as string, root);
2323
2424 const x = Math.min(1, Math.abs(p2) / (P.p2Ref as number));
2525 const floor = P.loudFloor as number;
26- const velocity = floor + (1 - floor) * Math.pow(x, P.loudCurve as number);
27- const pan = (P.panAmount as number) * Math.max(-1, Math.min(1, th2 / Math.PI));
28- return { midi, velocity, pan };
26+ const velocity = floor + (1 - floor) * pow(x, P.loudCurve as number);
27+ return { midi, velocity };
2928 }
src/core/audio.tsmodified+10−2View file
@@ -1,4 +1,6 @@
1-// One shared AudioContext for the whole album, created on the first user gesture.
1+// One shared AudioContext for the whole album, created on the first user gesture. It runs at the
2+// rate performances are computed at (48 kHz) on every device; the browser resamples if needed.
3+import { SAMPLE_RATE } from "../stream/protocol.ts";
24
35 export interface AudioEngine {
46 ctx: AudioContext;
@@ -10,7 +12,12 @@ let engine: AudioEngine | null = null;
1012
1113 export async function getAudio(): Promise<AudioEngine> {
1214 if (!engine) {
13- const ctx = new AudioContext({ latencyHint: "playback" });
15+ let ctx: AudioContext;
16+ try {
17+ ctx = new AudioContext({ latencyHint: "playback", sampleRate: SAMPLE_RATE });
18+ } catch {
19+ ctx = new AudioContext({ latencyHint: "playback" }); // very old browsers: the player resamples nothing, pitch may differ
20+ }
1421 const input = ctx.createGain();
1522 // gentle safety limiter on the master bus
1623 const limiter = ctx.createDynamicsCompressor();
@@ -21,6 +28,7 @@ export async function getAudio(): Promise<AudioEngine> {
2128 limiter.release.value = 0.25;
2229 input.connect(limiter).connect(ctx.destination);
2330 engine = { ctx, input };
31+ if (import.meta.env.DEV) (globalThis as { __audioEngine?: AudioEngine }).__audioEngine = engine; // for tests in the dev server
2432 }
2533 if (engine.ctx.state !== "running") await engine.ctx.resume();
2634 return engine;
src/core/composition.tsmodified+4−0View file
@@ -6,6 +6,10 @@ export interface Piece {
66 /** Start (or restart) from piece time `offset` seconds. Resolves once sound has begun. */
77 start(audio: AudioEngine, offset: number): Promise<void>;
88 stop(): void;
9+ /** Jump to piece time t while playing (same variation). */
10+ seek?(t: number): void;
11+ /** While playing: waiting for the background computation to catch up, and how far along (0..1). */
12+ status?(): { buffering: boolean; fill: number };
913 /** Called every animation frame, playing or not. */
1014 draw(): void;
1115 readonly playing: boolean;
src/core/params.tsmodified+5−0View file
@@ -9,6 +9,11 @@ interface Base {
99 label: string;
1010 group: string;
1111 hint?: string;
12+ /**
13+ * Takes effect immediately while playing (drawing, mix levels). Every other setting changes the
14+ * performance itself, so editing it while playing recomputes from the current moment.
15+ */
16+ live?: boolean;
1217 }
1318
1419 export interface NumberSpec extends Base {
src/instruments/effects.tsadded+62−0View file
@@ -0,0 +1,62 @@
1+// Effects after the rendered audio, on the page (native Web Audio nodes: cheap and steady):
2+// a sound's own modal-synth effects, or dry plus a send to one reverb shared by several outputs.
3+
4+import { FX } from "@modal-synth/audio/fx.ts";
5+import type { Params } from "@modal-synth/engine/params.ts";
6+
7+export function routeEffects(ctx: AudioContext, from: AudioNode, out: AudioNode, sound: Params | undefined, effects: "own" | "none" | { send: AudioNode }) {
8+ if (!sound) {
9+ from.connect(out);
10+ return;
11+ }
12+ if (effects === "own") {
13+ const fx = new FX(ctx, out);
14+ from.connect(fx.input);
15+ fx.set(sound);
16+ return;
17+ }
18+ const vol = ctx.createGain();
19+ vol.gain.value = Math.pow(10, (sound.volume as number) / 20);
20+ from.connect(vol).connect(out);
21+ if (effects !== "none") {
22+ const send = ctx.createGain();
23+ send.gain.value = (sound.reverbMix as number) * vol.gain.value;
24+ from.connect(send).connect(effects.send);
25+ }
26+}
27+
28+/** One convolution reverb shared by several outputs (decaying noise whose tail darkens). */
29+export class SharedReverb {
30+ input: GainNode;
31+ private conv: ConvolverNode;
32+
33+ constructor(ctx: AudioContext, out: AudioNode, T60: number) {
34+ this.input = ctx.createGain();
35+ this.conv = ctx.createConvolver();
36+ this.conv.buffer = makeIR(ctx, T60);
37+ this.input.connect(this.conv).connect(out);
38+ }
39+
40+ dispose() {
41+ this.input.disconnect();
42+ this.conv.disconnect();
43+ }
44+}
45+
46+function makeIR(ctx: BaseAudioContext, T60: number): AudioBuffer {
47+ const sr = ctx.sampleRate;
48+ const n = Math.round(sr * Math.min(T60 * 1.1, 12));
49+ const buf = ctx.createBuffer(2, n, sr);
50+ for (let ch = 0; ch < 2; ch++) {
51+ const d = buf.getChannelData(ch);
52+ let lp = 0;
53+ for (let i = 0; i < n; i++) {
54+ const t = i / sr;
55+ const fc = 9000 * Math.exp(-t / (0.6 * T60)) + 400;
56+ const a = 1 - Math.exp((-2 * Math.PI * fc) / sr);
57+ lp += a * (Math.random() * 2 - 1 - lp);
58+ d[i] = lp * Math.exp((-6.9 * t) / T60) * Math.min(1, t / 0.004) * 0.5;
59+ }
60+ }
61+ return buf;
62+}
src/instruments/fade.tsdeleted+0−6View file
@@ -1,6 +0,0 @@
1-/** Gain curve for a musical fade-out: cos², so -6 dB at the midpoint and the drop concentrated at the end. */
2-export function fadeCurve(from: number, n = 128): Float32Array {
3- const c = new Float32Array(n);
4- for (let i = 0; i < n; i++) c[i] = from * Math.cos((Math.PI / 2) * (i / (n - 1))) ** 2;
5- return c;
6-}
src/instruments/index.tsdeleted+0−13View file
@@ -1,13 +0,0 @@
1-import { modalDrones, modalInstruments } from "./modal.ts";
2-import { placeholderHum, placeholderTone } from "./placeholders.ts";
3-import type { DroneInstrumentFactory, NoteInstrumentFactory } from "./types.ts";
4-
5-export const NOTE_INSTRUMENTS: Record<string, NoteInstrumentFactory> = {
6- "placeholder tone": placeholderTone,
7- ...modalInstruments(),
8-};
9-
10-export const DRONE_INSTRUMENTS: Record<string, DroneInstrumentFactory> = {
11- "placeholder hum": placeholderHum,
12- ...modalDrones(),
13-};
src/instruments/modal.tsdeleted+0−324View file
@@ -1,324 +0,0 @@
1-// Instruments from the sibling modal-synth project (coupled nonlinear modal oscillators),
2-// imported live via the @modal-synth alias. Each instrument instance is one AudioWorklet synth
3-// (up to 16 voices) followed by modal-synth's own effects (saturation, delay, reverb).
4-
5-import { FX } from "@modal-synth/audio/fx.ts";
6-import workletUrl from "@modal-synth/audio/worklet.ts?worker&url";
7-import { DEFAULTS, PARAM_BY_ID, type Params } from "@modal-synth/engine/params.ts";
8-import type { Msg } from "@modal-synth/engine/synth.ts";
9-import { PRESETS } from "@modal-synth/presets.ts";
10-import { fadeCurve } from "./fade.ts";
11-import type { DroneInstrumentFactory, InstrumentOptions, NoteHandle, NoteInstrument, NoteInstrumentFactory } from "./types.ts";
12-
13-const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
14-function loadWorklet(ctx: AudioContext): Promise<void> {
15- let p = loaded.get(ctx);
16- if (!p) {
17- p = ctx.audioWorklet.addModule(workletUrl);
18- loaded.set(ctx, p);
19- }
20- return p;
21-}
22-
23-/** Parse a pasted preset (the JSON from modal-synth's Copy button). */
24-export function parseModalPreset(text: string | undefined): Params | null {
25- if (!text || !text.trim()) return null;
26- try {
27- const v = JSON.parse(text);
28- return v && typeof v === "object" && !Array.isArray(v) ? (v as Params) : null;
29- } catch {
30- return null;
31- }
32-}
33-
34-/**
35- * Effects after an instrument: its own modal-synth FX (reverb/delay/saturation), nothing, or a
36- * shared reverb send (dry at the preset's volume, send at its reverb amount; the preset's
37- * delay/saturation, unused by the album's instruments, are skipped).
38- */
39-export function routeEffects(ctx: AudioContext, from: AudioNode, out: AudioNode, sound: Params, opts: InstrumentOptions) {
40- const effects = opts.effects ?? "own";
41- if (effects === "own") {
42- const fx = new FX(ctx, out);
43- from.connect(fx.input);
44- fx.set(sound);
45- return;
46- }
47- const vol = ctx.createGain();
48- vol.gain.value = Math.pow(10, (sound.volume as number) / 20);
49- from.connect(vol).connect(out);
50- if (effects !== "none") {
51- const send = ctx.createGain();
52- send.gain.value = (sound.reverbMix as number) * vol.gain.value;
53- from.connect(send).connect(effects.send);
54- }
55-}
56-
57-const NOTE_OFF_LEAD = 0.2; // post noteOffs to the worklet this far ahead of their time
58-const FLUSH_MS = 25;
59-
60-export function makeModalFactory(preset: Params | null): NoteInstrumentFactory {
61- return (ctx, out, opts) => {
62- const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), ...(opts.overrides ?? {}) };
63-
64- // synth → fade (used by the final-note hold) → effects → our output
65- const fade = ctx.createGain();
66- routeEffects(ctx, fade, out, sound, opts);
67-
68- let node: AudioWorkletNode | null = null;
69- let cpu = 0; // smoothed audio-thread load of this synth
70- const early: Msg[] = [];
71- const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
72-
73- const ready = loadWorklet(ctx).then(() => {
74- node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
75- // snapshots (30/s) carry the synth's own measure of its processing time / real time
76- node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => {
77- if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2;
78- };
79- node.port.postMessage({ type: "params", params: sound } satisfies Msg);
80- for (const m of early.splice(0)) node.port.postMessage(m);
81- node.connect(fade);
82- });
83-
84- // noteOffs are held here until shortly before they're due, so the final note can be extended.
85- // Notes are identified by pitch in the synth; a noteOff is skipped if the same pitch was
86- // re-struck after its noteOn (the newer note has its own noteOff).
87- interface Off { note: number; on: number; time: number }
88- let offs: Off[] = [];
89- const lastOn = new Map<number, number>();
90- const flush = () => {
91- const horizon = ctx.currentTime + NOTE_OFF_LEAD;
92- const keep: Off[] = [];
93- for (const o of offs) {
94- if (o.time > horizon) keep.push(o);
95- else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) post({ type: "noteOff", note: o.note, time: o.time });
96- }
97- offs = keep;
98- };
99- const timer = window.setInterval(flush, FLUSH_MS);
100- const offline = typeof OfflineAudioContext !== "undefined" && (ctx as BaseAudioContext) instanceof OfflineAudioContext;
101- const immediate = offline || !!opts.immediateRelease;
102- let holding = false;
103-
104- const inst: NoteInstrument = {
105- ready,
106- load: () => cpu,
107- play({ when, freq, velocity, duration }) {
108- if (velocity <= 0) return null;
109- const note = 69 + 12 * Math.log2(freq / 440);
110- post({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when });
111- if (immediate) {
112- // device checks (and offline renders, which can't run the release timer): release now
113- post({ type: "noteOff", note, time: when + duration });
114- return null;
115- }
116- lastOn.set(note, when);
117- const off: Off = { note, on: when, time: when + duration };
118- offs.push(off);
119- const handle: NoteHandle = {
120- hold(from, holdLen, fadeLen) {
121- const t = Math.max(from, ctx.currentTime);
122- const ring = holdLen + fadeLen;
123- // keep the damper off through the whole hold and fade (if still queued, the release moves later)
124- off.time = t + ring;
125- // the decay change and fade are instrument-wide: when several voices (orbits) end on this
126- // instrument, the first hold schedules them and later ones just keep their dampers off
127- if (holding) return;
128- holding = true;
129- // a plucked or struck body decays by itself: lengthen its decay so it really rings through
130- // the hold. Only the final note is sounding by then, so the instrument-wide change is safe.
131- // Both the base decay (t60) and the frequency-dependent loss (hfDamp) are slowed by the same
132- // factor, so the note keeps its tone color while it rings.
133- const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
134- const slow = t60 / (sound.t60 as number);
135- const ringing: Params = { ...sound, t60, hfDamp: (sound.hfDamp as number) / slow };
136- window.setTimeout(() => post({ type: "params", params: ringing }), Math.max(0, (t - ctx.currentTime) * 1000));
137- fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen);
138- },
139- };
140- return handle;
141- },
142- dispose() {
143- window.clearInterval(timer);
144- post({ type: "panic" });
145- window.setTimeout(() => {
146- node?.disconnect();
147- node?.port.close();
148- fade.disconnect();
149- }, 1000);
150- },
151- };
152- return inst;
153- };
154-}
155-
156-/** Menu name → factory, for every built-in modal-synth preset plus "modal: custom". */
157-export function modalInstruments(): Record<string, NoteInstrumentFactory> {
158- const out: Record<string, NoteInstrumentFactory> = {};
159- for (const p of PRESETS) out[`modal: ${p.name}`] = makeModalFactory(p.p);
160- out["modal: custom"] = makeModalFactory(null);
161- return out;
162-}
163-
164-// ── drones: one held note of a sustained preset, with color mapped onto synth settings ──
165-
166-/** Settings the synth reads every block, so they can follow the energy while a note is held. */
167-export const LIVE_TARGETS = [
168- "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath",
169- "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature",
170- "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth",
171-];
172-
173-/** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */
174-export function targetValue(id: string, u: number): number {
175- const d = PARAM_BY_ID[id];
176- if (!d || d.kind !== "num") return NaN;
177- const x = Math.max(0, Math.min(1, u));
178- if (d.scale === "log") return d.min * Math.pow(d.max / d.min, x);
179- if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x;
180- return d.min + (d.max - d.min) * x;
181-}
182-
183-const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"];
184-const DRONE_UPDATE_MS = 50; // at most this often, a "params" message to the worklet
185-const NORM_REF = 0.3; // with normalize on, level 1 ≈ this RMS (about the placeholder hum's)
186-const NORM_TAU = 1.5; // seconds: how slowly the loudness compensation follows
187-const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
188-
189-export function makeModalDroneFactory(preset: Params | null): DroneInstrumentFactory {
190- return (ctx, out, opts) => {
191- const glide = opts.glide;
192- const base: Params = {
193- ...DEFAULTS,
194- ...(preset ?? parseModalPreset(opts.custom) ?? {}),
195- ...(opts.overrides ?? {}),
196- voices: 1,
197- ...(glide ? { bendRange: Math.max(1, Math.min(24, Math.round(glide.range))) } : {}),
198- };
199- const gain = ctx.createGain();
200- gain.gain.value = 0;
201- const fx = new FX(ctx, out);
202- gain.connect(fx.input);
203- fx.set(base);
204- // loudness meter on the raw synth output, for normalization
205- const meter = ctx.createAnalyser();
206- meter.fftSize = 2048;
207- const buf = new Float32Array(meter.fftSize);
208- let msq = NORM_REF * NORM_REF; // smoothed mean square
209- let lastMeter = 0;
210- let comp = 1;
211-
212- let node: AudioWorkletNode | null = null;
213- let cpu = 0; // smoothed audio-thread load of this synth
214- const early: Msg[] = [];
215- const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
216- const ready = loadWorklet(ctx).then(() => {
217- node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
218- node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => {
219- if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2;
220- };
221- node.port.postMessage({ type: "params", params: base } satisfies Msg);
222- for (const m of early.splice(0)) node.port.postMessage(m);
223- node.connect(gain);
224- node.connect(meter);
225- });
226-
227- let note: number | null = null;
228- let bend = 0;
229- let sent: Params = base;
230- let lastPost = 0;
231- let desc = "";
232- const midi = (f: number) => 69 + 12 * Math.log2(f / 440);
233-
234- return {
235- ready,
236- load: () => cpu,
237- start(when, freq) {
238- if (glide) {
239- // begin already bent to the starting pitch
240- bend = Math.max(-1, Math.min(1, (midi(freq) - glide.center) / (base.bendRange as number)));
241- post({ type: "bend", value: bend });
242- }
243- note = glide ? glide.center : midi(freq);
244- post({ type: "noteOn", note, vel: 1, time: when });
245- },
246- stop(when, release) {
247- const t = Math.max(ctx.currentTime, when - release);
248- gain.gain.cancelScheduledValues(t);
249- gain.gain.setTargetAtTime(0, t, release / 4);
250- if (note !== null) post({ type: "noteOff", note, time: t });
251- note = null;
252- },
253- set(when, { level, color, freq, timbre, normalize }) {
254- // loudness normalization: follow the measured level slowly, compensate toward NORM_REF
255- const now = performance.now() / 1000;
256- const dt = lastMeter ? Math.min(0.5, now - lastMeter) : 0;
257- lastMeter = now;
258- if (normalize && node) {
259- meter.getFloatTimeDomainData(buf);
260- let s = 0;
261- for (const x of buf) s += x * x;
262- s /= buf.length;
263- if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-dt / NORM_TAU));
264- comp = Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq)));
265- } else comp = 1;
266- gain.gain.setTargetAtTime(level * comp, when, 0.08);
267- // follow the pitch: glide with pitch bend, or restart the note if the pitch setting moved
268- const m = midi(freq);
269- if (glide && note !== null) {
270- const range = base.bendRange as number;
271- const b = Math.max(-1, Math.min(1, (m - glide.center) / range));
272- if (Math.abs(b - bend) > 1e-4) {
273- bend = b;
274- post({ type: "bend", value: b });
275- }
276- } else if (note !== null && Math.abs(m - note) > 0.01) {
277- post({ type: "noteOff", note, time: when });
278- note = m;
279- post({ type: "noteOn", note, vel: 1, time: when });
280- }
281- // color → mapped settings, throttled
282- const wall = performance.now();
283- if (!timbre?.length || wall - lastPost < DRONE_UPDATE_MS) return;
284- const next: Params = { ...base };
285- const parts: string[] = [];
286- let changed = false;
287- for (const tm of timbre) {
288- if (!LIVE_TARGETS.includes(tm.target)) continue;
289- const v = targetValue(tm.target, tm.from + (tm.to - tm.from) * color);
290- if (!Number.isFinite(v)) continue;
291- next[tm.target] = v;
292- parts.push(`${tm.target} ${Number(v.toPrecision(3))}`);
293- const d = PARAM_BY_ID[tm.target] as { min: number; max: number };
294- if (Math.abs(v - (sent[tm.target] as number)) > 0.002 * (d.max - d.min)) changed = true;
295- }
296- desc = parts.join(", ");
297- if (!changed) return;
298- sent = next;
299- lastPost = wall;
300- post({ type: "params", params: next });
301- },
302- describe: () => (comp !== 1 ? `${desc}${desc ? ", " : ""}gain ${(20 * Math.log10(comp)).toFixed(1)} dB` : desc),
303- dispose() {
304- post({ type: "panic" });
305- window.setTimeout(() => {
306- node?.disconnect();
307- node?.port.close();
308- gain.disconnect();
309- }, 1000);
310- },
311- };
312- };
313-}
314-
315-/** Sustained presets (bowed, blown, self-oscillating, fed back) as "modal: <name>", plus "modal: custom". */
316-export function modalDrones(): Record<string, DroneInstrumentFactory> {
317- const out: Record<string, DroneInstrumentFactory> = {};
318- for (const p of PRESETS) {
319- const q = { ...DEFAULTS, ...p.p };
320- if (SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0) out[`modal: ${p.name}`] = makeModalDroneFactory(p.p);
321- }
322- out["modal: custom"] = makeModalDroneFactory(null);
323- return out;
324-}
src/instruments/placeholders.tsdeleted+0−112View file
@@ -1,112 +0,0 @@
1-// Placeholder instruments: deliberately plain, to be replaced later.
2-import { fadeCurve } from "./fade.ts";
3-import type { DroneInstrument, NoteEvent, NoteHandle, NoteInstrument } from "./types.ts";
4-
5-/** Sine + soft octave triangle with a percussive exponential decay. */
6-export function placeholderTone(ctx: AudioContext, out: AudioNode): NoteInstrument {
7- return {
8- play({ when, freq, velocity, pan, duration }: NoteEvent): NoteHandle | null {
9- if (velocity <= 0) return null;
10- const t0 = Math.max(when, ctx.currentTime);
11- const end = t0 + duration;
12- const peak = 0.3 * velocity;
13- const ta = t0 + 0.004;
14- const env = ctx.createGain();
15- env.gain.setValueAtTime(0, t0);
16- env.gain.linearRampToValueAtTime(peak, ta);
17- env.gain.exponentialRampToValueAtTime(0.0001, end);
18- const panner = ctx.createStereoPanner();
19- panner.pan.value = Math.max(-1, Math.min(1, pan));
20- env.connect(panner).connect(out);
21-
22- const a = ctx.createOscillator();
23- a.frequency.value = freq;
24- a.connect(env);
25- const b = ctx.createOscillator();
26- b.type = "triangle";
27- b.frequency.value = freq * 2;
28- const bg = ctx.createGain();
29- bg.gain.value = 0.08 + 0.15 * velocity; // a touch brighter when louder
30- b.connect(bg).connect(env);
31-
32- for (const o of [a, b]) {
33- o.start(t0);
34- o.stop(end + 0.05);
35- }
36- b.onended = () => panner.disconnect();
37-
38- return {
39- hold(from, holdLen, fadeLen) {
40- const t = Math.max(from, ta, ctx.currentTime);
41- if (t >= end) return;
42- // level of the exponential decay at t
43- const v = peak * Math.pow(0.0001 / peak, (t - ta) / (end - ta));
44- const g = env.gain;
45- if (typeof g.cancelAndHoldAtTime === "function") g.cancelAndHoldAtTime(t);
46- else g.cancelScheduledValues(t);
47- g.setValueAtTime(v, t);
48- g.setValueCurveAtTime(fadeCurve(v), t + Math.max(holdLen, 0.005), fadeLen);
49- const stopAt = t + holdLen + fadeLen + 0.05;
50- a.stop(stopAt);
51- b.stop(stopAt);
52- },
53- };
54- },
55- dispose() {},
56- };
57-}
58-
59-/**
60- * Hum: sub sine + two detuned saws through a low-pass. `color` (0..1) opens the
61- * filter and adds resonance, so the timbre brightens with energy at fixed pitch.
62- */
63-export function placeholderHum(ctx: AudioContext, out: AudioNode): DroneInstrument {
64- const gain = ctx.createGain();
65- gain.gain.value = 0;
66- const filter = ctx.createBiquadFilter();
67- filter.type = "lowpass";
68- filter.frequency.value = 120;
69- filter.Q.value = 0.7;
70- filter.connect(gain).connect(out);
71-
72- const sub = ctx.createOscillator();
73- const subGain = ctx.createGain();
74- subGain.gain.value = 0.5;
75- sub.connect(subGain).connect(gain); // sub bypasses the filter: the stable core of the hum
76-
77- const saws = [-6, 6].map((cents) => {
78- const o = ctx.createOscillator();
79- o.type = "sawtooth";
80- o.detune.value = cents;
81- const g = ctx.createGain();
82- g.gain.value = 0.25;
83- o.connect(g).connect(filter);
84- return o;
85- });
86- const oscs = [sub, ...saws];
87-
88- return {
89- start(when, freq) {
90- sub.frequency.value = freq;
91- for (const o of saws) o.frequency.value = freq * 2;
92- for (const o of oscs) o.start(when);
93- },
94- stop(when, release) {
95- gain.gain.cancelScheduledValues(when - release);
96- gain.gain.setTargetAtTime(0, when - release, release / 4);
97- for (const o of oscs) o.stop(when + 0.1);
98- },
99- set(when, { level, color, freq }) {
100- const tc = 0.08;
101- gain.gain.setTargetAtTime(level, when, tc);
102- sub.frequency.setTargetAtTime(freq, when, tc);
103- for (const o of saws) o.frequency.setTargetAtTime(freq * 2, when, tc);
104- const c = Math.max(0, Math.min(1, color));
105- filter.frequency.setTargetAtTime(freq * 2 * Math.pow(2, 6 * c), when, tc);
106- filter.Q.setTargetAtTime(0.7 + 5 * c * c, when, tc);
107- },
108- dispose() {
109- gain.disconnect();
110- },
111- };
112-}
src/instruments/reverb.tsdeleted+0−42View file
@@ -1,42 +0,0 @@
1-// One convolution reverb shared by several instruments (instead of one per instrument, which is
2-// costly on phones). The impulse response is the same kind modal-synth's effects use: decaying
3-// noise whose tail darkens over time.
4-
5-export class SharedReverb {
6- /** send instruments' wet signal here */
7- input: GainNode;
8- private conv: ConvolverNode;
9-
10- constructor(ctx: AudioContext, out: AudioNode, T60: number) {
11- this.input = ctx.createGain();
12- this.conv = ctx.createConvolver();
13- this.conv.buffer = makeIR(ctx, T60);
14- this.input.connect(this.conv).connect(out);
15- }
16-
17- dispose() {
18- const i = this.input, c = this.conv;
19- window.setTimeout(() => {
20- i.disconnect();
21- c.disconnect();
22- }, 1500);
23- }
24-}
25-
26-function makeIR(ctx: BaseAudioContext, T60: number): AudioBuffer {
27- const sr = ctx.sampleRate;
28- const n = Math.round(sr * Math.min(T60 * 1.1, 12));
29- const buf = ctx.createBuffer(2, n, sr);
30- for (let ch = 0; ch < 2; ch++) {
31- const d = buf.getChannelData(ch);
32- let lp = 0;
33- for (let i = 0; i < n; i++) {
34- const t = i / sr;
35- const fc = 9000 * Math.exp(-t / (0.6 * T60)) + 400;
36- const a = 1 - Math.exp((-2 * Math.PI * fc) / sr);
37- lp += a * (Math.random() * 2 - 1 - lp);
38- d[i] = lp * Math.exp((-6.9 * t) / T60) * Math.min(1, t / 0.004) * 0.5;
39- }
40- }
41- return buf;
42-}
src/instruments/sounds.tsadded+60−0View file
@@ -0,0 +1,60 @@
1+// The instrument sounds compositions can pick: modal-synth's presets (imported live from the
2+// sibling project through the @modal-synth alias) and pasted custom presets. Worker-safe: the
3+// sounds are just parameter sets; the synth workers render them.
4+
5+import { DEFAULTS, PARAM_BY_ID, type Params } from "@modal-synth/engine/params.ts";
6+import { PRESETS } from "@modal-synth/presets.ts";
7+
8+/** Parse a pasted preset (the JSON from modal-synth's Copy button). */
9+export function parseModalPreset(text: string | undefined): Params | null {
10+ if (!text || !text.trim()) return null;
11+ try {
12+ const v = JSON.parse(text);
13+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Params) : null;
14+ } catch {
15+ return null;
16+ }
17+}
18+
19+const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"];
20+
21+/** Menu names for note instruments: every preset, plus "modal: custom". */
22+export const NOTE_SOUNDS: string[] = [...PRESETS.map((p) => `modal: ${p.name}`), "modal: custom"];
23+
24+/** Menu names for drones: sustained presets (bowed, blown, self-oscillating, fed back), plus custom. */
25+export const DRONE_SOUNDS: string[] = [
26+ ...PRESETS.filter((p) => {
27+ const q = { ...DEFAULTS, ...p.p };
28+ return SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0;
29+ }).map((p) => `modal: ${p.name}`),
30+ "modal: custom",
31+];
32+
33+/** The full synth parameters for a menu name (custom: the pasted JSON). */
34+export function soundOf(name: string, custom: string, overrides: Params = {}): Params {
35+ const preset = name === "modal: custom" ? parseModalPreset(custom) : PRESETS.find((p) => `modal: ${p.name}` === name)?.p;
36+ return { ...DEFAULTS, ...(preset ?? {}), ...overrides };
37+}
38+
39+/** Settings the synth reads every block, so they can follow the energy while a drone is held. */
40+export const LIVE_TARGETS = [
41+ "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath",
42+ "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature",
43+ "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth",
44+];
45+
46+/** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */
47+export function targetValue(id: string, u: number, pow: (x: number, y: number) => number): number {
48+ const d = PARAM_BY_ID[id];
49+ if (!d || d.kind !== "num") return NaN;
50+ const x = Math.max(0, Math.min(1, u));
51+ if (d.scale === "log") return d.min * pow(d.max / d.min, x);
52+ if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x;
53+ return d.min + (d.max - d.min) * x;
54+}
55+
56+/** A setting's range, for deciding whether a change is worth sending. */
57+export function targetRange(id: string): number {
58+ const d = PARAM_BY_ID[id] as { min?: number; max?: number } | undefined;
59+ return d && d.min !== undefined && d.max !== undefined ? d.max - d.min : 1;
60+}
src/instruments/stream/capacity.tsdeleted+0−63View file
@@ -1,63 +0,0 @@
1-// What one ringing voice of a modal-synth sound costs on this device, measured in a render worker
2-// (as playback runs it) and remembered per sound. Every streamed instrument uses it to cap its
3-// polyphony, so a burst of notes can't push its renderer past real time.
4-
5-import type { Params } from "@modal-synth/engine/params.ts";
6-import type { BenchNote, FromWorker, ToWorker } from "./protocol.ts";
7-
8-/** render time / audio time allowed for one instrument's worker */
9-export const VOICE_BUDGET = 0.6;
10-
11-function hash(s: string): string {
12- let h = 2166136261;
13- for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
14- return (h >>> 0).toString(36);
15-}
16-
17-const pending = new Map<string, Promise<number>>();
18-
19-/** Load (render time / audio time) of one voice of `sound`, struck repeatedly so it always rings. */
20-export function voiceCost(sound: Params, sampleRate: number): Promise<number> {
21- const key = `double-pendulum:voice-cost:${hash(JSON.stringify({ v: 1, sr: sampleRate, sound }))}`;
22- try {
23- const c = localStorage.getItem(key);
24- if (c !== null && Number.isFinite(Number(c))) return Promise.resolve(Number(c));
25- } catch {
26- /* no storage */
27- }
28- let p = pending.get(key);
29- if (p) return p;
30- p = new Promise<number>((resolve) => {
31- const notes: BenchNote[] = [];
32- for (let t = 0; t < 2; t += 0.7) notes.push({ time: t, note: 31 + Math.round(t * 10), vel: 0.8, len: 0.5 });
33- const w = new Worker(new URL("./renderWorker.ts", import.meta.url), { type: "module" });
34- const done = (load: number) => {
35- w.terminate();
36- pending.delete(key);
37- try {
38- localStorage.setItem(key, String(load));
39- } catch {
40- /* no storage */
41- }
42- resolve(load);
43- };
44- w.onmessage = (e: MessageEvent<FromWorker>) => {
45- if (e.data.type === "bench") done(e.data.load);
46- };
47- w.onerror = () => {
48- w.terminate();
49- pending.delete(key);
50- resolve(0); // can't tell: don't limit
51- };
52- const m: ToWorker = { type: "bench", sampleRate, params: { ...sound, voices: 1 }, notes, seconds: 2, warmup: 0.5 };
53- w.postMessage(m);
54- });
55- pending.set(key, p);
56- return p;
57-}
58-
59-/** Voices that fit the budget (at least one), given what was asked for. */
60-export function voicesThatFit(perVoice: number, wanted: number): number {
61- if (!(perVoice > 0)) return wanted;
62- return Math.max(1, Math.min(wanted, Math.floor(VOICE_BUDGET / perVoice)));
63-}
src/instruments/stream/player.tsdeleted+0−94View file
@@ -1,94 +0,0 @@
1-// AudioWorklet that plays audio rendered elsewhere (render workers), on the audio clock.
2-// Chunks carry absolute frame numbers; the player outputs whatever covers the current frames
3-// (silence if nothing has arrived: an underrun) and reports how far it has played, so the
4-// renderer can stay a fixed distance ahead. An underrun fades out from the last sample instead of
5-// cutting to silence, and the audio after it fades back in, so a gap is a soft dip, not a click.
6-
7-import type { Chunk, Consumed } from "./protocol.ts";
8-
9-declare const currentFrame: number;
10-declare const sampleRate: number;
11-declare class AudioWorkletProcessor {
12- readonly port: MessagePort;
13- constructor();
14-}
15-declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
16-
17-const FADE = 256; // samples to fade back in after a gap
18-const TAIL = 0.985; // per-sample decay of the last sample during a gap (≈ 5 ms to −40 dB)
19-
20-class PcmPlayer extends AudioWorkletProcessor {
21- private queue: Chunk[] = [];
22- private src: MessagePort | null = null;
23- private underruns = 0;
24- private started = false;
25- private lastReport = 0;
26- private tailL = 0; // what a gap fades out from (the last sample played, decaying)
27- private tailR = 0;
28- private fadeIn = FADE; // samples since audio resumed after a gap (FADE = fully in)
29-
30- constructor() {
31- super();
32- this.port.onmessage = (e: MessageEvent<{ type: "port"; port: MessagePort }>) => {
33- if (e.data?.type !== "port") return;
34- this.src = e.data.port;
35- this.src.onmessage = (ev: MessageEvent<Chunk>) => this.queue.push(ev.data);
36- };
37- }
38-
39- process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
40- const out = outputs[0];
41- const L = out[0], R = out[1] ?? out[0];
42- const n = L.length;
43- const F = currentFrame;
44- const q = this.queue;
45- while (q.length && q[0].frame + q[0].L.length <= F) q.shift();
46- let i = 0;
47- while (i < n) {
48- const f = F + i;
49- const c = q.find((x) => x.frame <= f && f < x.frame + x.L.length);
50- if (!c) {
51- // nothing for this frame: silence (counts as an underrun once audio has started)
52- const next = q.find((x) => x.frame > f);
53- const end = next ? Math.min(n, next.frame - F) : n;
54- if (this.started) this.underruns++;
55- const stop = Math.max(end, i + 1);
56- for (; i < stop; i++) {
57- this.tailL *= TAIL;
58- this.tailR *= TAIL;
59- L[i] = this.tailL;
60- if (R !== L) R[i] = this.tailR;
61- }
62- if (this.started) this.fadeIn = 0;
63- continue;
64- }
65- this.started = true;
66- const off = f - c.frame;
67- const len = Math.min(n - i, c.L.length - off);
68- if (this.fadeIn >= FADE) {
69- L.set(c.L.subarray(off, off + len), i);
70- if (R !== L) R.set(c.R.subarray(off, off + len), i);
71- } else {
72- // crossfade from the decaying tail into the resumed audio
73- for (let j = 0; j < len; j++) {
74- const g = Math.min(1, this.fadeIn++ / FADE);
75- this.tailL *= TAIL;
76- this.tailR *= TAIL;
77- L[i + j] = g * c.L[off + j] + (1 - g) * this.tailL;
78- if (R !== L) R[i + j] = g * c.R[off + j] + (1 - g) * this.tailR;
79- }
80- }
81- i += len;
82- this.tailL = L[i - 1];
83- this.tailR = R[i - 1];
84- }
85- if (this.src && F + n - this.lastReport >= sampleRate / 50) {
86- this.lastReport = F + n;
87- const m: Consumed = { consumed: F + n, underruns: this.underruns };
88- this.src.postMessage(m);
89- }
90- return true;
91- }
92-}
93-
94-registerProcessor("pcm-player", PcmPlayer);
src/instruments/stream/protocol.tsdeleted+0−48View file
@@ -1,48 +0,0 @@
1-// Messages between the page, the render workers, and the player worklet.
2-import type { Params } from "@modal-synth/engine/params.ts";
3-import type { Msg } from "@modal-synth/engine/synth.ts";
4-
5-/** page → render worker */
6-export type ToWorker =
7- | {
8- type: "init";
9- sampleRate: number;
10- params: Params;
11- /** where to send rendered audio (the player's port) */
12- port: MessagePort;
13- /** absolute audio-context frame of the first rendered sample */
14- startFrame: number;
15- /** keep this many frames rendered ahead of what the player has consumed */
16- aheadFrames: number;
17- }
18- | { type: "synth"; msg: Msg } // noteOn/noteOff (with `time`), params, panic
19- | { type: "timedParams"; params: Params; time: number } // apply when rendering reaches `time`
20- | { type: "horizon"; time: number } // every note before `time` has been sent: render up to it
21- | { type: "stop" }
22- | { type: "bench"; sampleRate: number; params: Params; notes: BenchNote[]; seconds: number; warmup: number };
23-
24-export interface BenchNote {
25- time: number;
26- note: number;
27- vel: number;
28- len: number;
29-}
30-
31-/** render worker → page */
32-export type FromWorker =
33- | { type: "ready" }
34- | { type: "load"; load: number; underruns: number }
35- | { type: "bench"; load: number };
36-
37-/** render worker → player (over the MessageChannel) */
38-export interface Chunk {
39- frame: number; // absolute frame of L[0]
40- L: Float32Array;
41- R: Float32Array;
42-}
43-
44-/** player → render worker */
45-export interface Consumed {
46- consumed: number; // absolute frame the player has played up to
47- underruns: number;
48-}
src/instruments/stream/renderWorker.tsdeleted+0−135View file
@@ -1,135 +0,0 @@
1-// Renders one modal-synth instrument off the real-time audio thread, ahead of playback.
2-//
3-// The synth is the same engine the AudioWorklet runs. Here it renders chunks of audio up to
4-// `aheadFrames` beyond what the player has consumed, and posts them straight to the player's port.
5-// Several of these workers run in parallel, one per instrument, on the device's other cores.
6-// Notes arrive early (the page simulates ahead) with absolute audio-context times; the synth
7-// applies them at the exact sample.
8-
9-import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
10-import { Synth } from "@modal-synth/engine/synth.ts";
11-import type { Chunk, Consumed, FromWorker, ToWorker } from "./protocol.ts";
12-
13-const BLOCK = 128;
14-const CHUNK = 1024; // frames per posted chunk (~21 ms)
15-
16-let synth: Synth | null = null;
17-let sr = 48000;
18-let port: MessagePort | null = null;
19-let rendered = 0; // next frame to render (absolute)
20-let consumed = 0; // frames the player has played (absolute)
21-let ahead = 48000;
22-let horizon = 0; // frame up to which all notes are known (sent by the page)
23-let running = false;
24-let scheduled = false;
25-let timed: { time: number; params: Params }[] = [];
26-let underruns = 0;
27-// load: render time / audio time, over the last ~second
28-let busyMs = 0;
29-let audioMs = 0;
30-let lastLoadPost = 0;
31-
32-const post = (m: FromWorker) => (self as unknown as Worker).postMessage(m);
33-
34-self.onmessage = (ev: MessageEvent<ToWorker>) => {
35- const m = ev.data;
36- switch (m.type) {
37- case "init": {
38- sr = m.sampleRate;
39- synth = new Synth(sr);
40- synth.message({ type: "params", params: { ...DEFAULTS, ...m.params } });
41- port = m.port;
42- port.onmessage = (e: MessageEvent<Consumed>) => {
43- consumed = Math.max(consumed, e.data.consumed);
44- underruns = e.data.underruns;
45- pump();
46- };
47- rendered = m.startFrame;
48- consumed = m.startFrame;
49- horizon = m.startFrame;
50- ahead = m.aheadFrames;
51- running = true;
52- post({ type: "ready" });
53- pump();
54- break;
55- }
56- case "synth":
57- synth?.message(m.msg);
58- break;
59- case "horizon":
60- horizon = Math.max(horizon, Math.floor(m.time * sr));
61- pump();
62- break;
63- case "timedParams":
64- timed.push({ time: m.time, params: m.params });
65- timed.sort((a, b) => a.time - b.time);
66- break;
67- case "stop":
68- running = false;
69- port?.close();
70- break;
71- case "bench":
72- post({ type: "bench", load: bench(m) });
73- break;
74- }
75-};
76-
77-function pump() {
78- if (scheduled || !running) return;
79- scheduled = true;
80- setTimeout(loop, 0);
81-}
82-
83-function loop() {
84- scheduled = false;
85- if (!running || !synth || !port) return;
86- if (rendered < consumed) rendered = Math.ceil(consumed / BLOCK) * BLOCK; // never render the past
87- // far enough ahead (wait for the player), or at the edge of what the page has scheduled
88- // (wait for more notes: rendering past it would play them late)
89- if (rendered >= consumed + ahead || rendered + CHUNK > horizon) return;
90- const t0 = performance.now();
91- const L = new Float32Array(CHUNK), R = new Float32Array(CHUNK);
92- const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
93- for (let i = 0; i < CHUNK; i += BLOCK) {
94- const now = (rendered + i) / sr;
95- while (timed.length && timed[0].time <= now) synth.message({ type: "params", params: { ...DEFAULTS, ...timed.shift()!.params } });
96- bl.fill(0);
97- br.fill(0);
98- synth.process(bl, br, BLOCK, now);
99- L.set(bl, i);
100- R.set(br, i);
101- }
102- const chunk: Chunk = { frame: rendered, L, R };
103- port.postMessage(chunk, [L.buffer, R.buffer]);
104- rendered += CHUNK;
105- busyMs += performance.now() - t0;
106- audioMs += (CHUNK / sr) * 1000;
107- if (audioMs >= 1000 || performance.now() - lastLoadPost > 1000) {
108- post({ type: "load", load: audioMs > 0 ? busyMs / audioMs : 0, underruns });
109- busyMs = audioMs = 0;
110- lastLoadPost = performance.now();
111- }
112- pump(); // yield between chunks so incoming notes are handled before later frames are rendered
113-}
114-
115-/** Device check: render a note pattern as fast as possible; returns render time / audio time. */
116-function bench(m: Extract<ToWorker, { type: "bench" }>): number {
117- const s = new Synth(m.sampleRate);
118- s.message({ type: "params", params: { ...DEFAULTS, ...m.params } });
119- for (const n of m.notes) {
120- s.message({ type: "noteOn", note: n.note, vel: n.vel, time: n.time });
121- s.message({ type: "noteOff", note: n.note, time: n.time + n.len });
122- }
123- const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
124- const total = Math.round(m.seconds * m.sampleRate);
125- const warm = Math.round(m.warmup * m.sampleRate);
126- let t0 = performance.now();
127- for (let f = 0; f < total; f += BLOCK) {
128- if (f === Math.floor(warm / BLOCK) * BLOCK) t0 = performance.now(); // time only after warm-up (JIT, voices filling)
129- bl.fill(0);
130- br.fill(0);
131- s.process(bl, br, BLOCK, f / m.sampleRate);
132- }
133- const audio = (total - Math.floor(warm / BLOCK) * BLOCK) / m.sampleRate;
134- return (performance.now() - t0) / 1000 / audio;
135-}
src/instruments/stream/streamed.tsdeleted+0−152View file
@@ -1,152 +0,0 @@
1-// A modal-synth instrument rendered in a Web Worker, ahead of playback, and streamed to a player
2-// worklet. Same sound and interface as the direct (AudioWorklet) modal instrument, but the
3-// synthesis runs on another core with a buffer of AHEAD seconds, so the real-time audio thread
4-// only copies samples. Notes must be played at least AHEAD + a little before their time.
5-// Each instrument measures what one voice costs on this device (once, remembered) and caps its
6-// polyphony to fit, so a burst of notes can't push its renderer past real time.
7-
8-import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
9-import type { Msg } from "@modal-synth/engine/synth.ts";
10-import { PRESETS } from "@modal-synth/presets.ts";
11-import playerUrl from "./player.ts?worker&url";
12-import { fadeCurve } from "../fade.ts";
13-import { voiceCost, voicesThatFit } from "./capacity.ts";
14-import { parseModalPreset, routeEffects } from "../modal.ts";
15-import type { NoteHandle, NoteInstrument, NoteInstrumentFactory } from "../types.ts";
16-import type { FromWorker, ToWorker } from "./protocol.ts";
17-
18-/** seconds of audio kept rendered ahead of playback */
19-export const AHEAD = 2.0;
20-/** how early notes must be played (scheduled) relative to their time */
21-export const SCHEDULE_AHEAD = AHEAD + 0.5;
22-const NOTE_OFF_LEAD = AHEAD + 0.3; // release messages are sent this far ahead of their time
23-const FLUSH_MS = 50;
24-
25-const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
26-function loadPlayer(ctx: AudioContext): Promise<void> {
27- let p = loaded.get(ctx);
28- if (!p) {
29- p = ctx.audioWorklet.addModule(playerUrl);
30- loaded.set(ctx, p);
31- }
32- return p;
33-}
34-
35-export function makeStreamedFactory(preset: Params | null): NoteInstrumentFactory {
36- return (ctx, out, opts) => {
37- const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), ...(opts.overrides ?? {}) };
38- const fade = ctx.createGain();
39- routeEffects(ctx, fade, out, sound, opts);
40-
41- const worker = new Worker(new URL("./renderWorker.ts", import.meta.url), { type: "module" });
42- const send = (m: ToWorker, transfer: Transferable[] = []) => worker.postMessage(m, transfer);
43- let load = 0;
44- let underruns = 0;
45- const wanted = Math.round(sound.voices as number);
46- let allowed = wanted;
47- let node: AudioWorkletNode | null = null;
48- const ready = (async () => {
49- const [perVoice] = await Promise.all([voiceCost({ ...sound, voices: 1 }, ctx.sampleRate), loadPlayer(ctx)]);
50- allowed = voicesThatFit(perVoice, wanted);
51- node = new AudioWorkletNode(ctx, "pcm-player", { numberOfInputs: 0, outputChannelCount: [2] });
52- node.connect(fade);
53- const ch = new MessageChannel();
54- node.port.postMessage({ type: "port", port: ch.port2 }, [ch.port2]);
55- const workerReady = new Promise<void>((resolve) => {
56- worker.onmessage = (e: MessageEvent<FromWorker>) => {
57- if (e.data.type === "ready") resolve();
58- else if (e.data.type === "load") {
59- load = e.data.load;
60- underruns = e.data.underruns;
61- }
62- };
63- });
64- send(
65- {
66- type: "init",
67- sampleRate: ctx.sampleRate,
68- params: { ...sound, voices: allowed },
69- port: ch.port1,
70- startFrame: Math.round((ctx.currentTime + 0.05) * ctx.sampleRate),
71- aheadFrames: Math.round(AHEAD * ctx.sampleRate),
72- },
73- [ch.port1],
74- );
75- await workerReady;
76- })();
77-
78- const synthMsg = (msg: Msg) => send({ type: "synth", msg });
79-
80- // releases wait here until shortly before they're due, so the final note can be extended;
81- // a release is skipped if the same pitch was struck again after its note began
82- interface Off { note: number; on: number; time: number }
83- let offs: Off[] = [];
84- const lastOn = new Map<number, number>();
85- const flush = () => {
86- const horizon = ctx.currentTime + NOTE_OFF_LEAD;
87- const keep: Off[] = [];
88- for (const o of offs) {
89- if (o.time > horizon) keep.push(o);
90- else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) synthMsg({ type: "noteOff", note: o.note, time: o.time });
91- }
92- offs = keep;
93- };
94- const timer = window.setInterval(flush, FLUSH_MS);
95- let holding = false;
96-
97- const inst: NoteInstrument = {
98- ready,
99- load: () => load,
100- underruns: () => underruns,
101- voices: () => ({ allowed, wanted }),
102- horizon: (time) => send({ type: "horizon", time }),
103- play({ when, freq, velocity, duration }) {
104- if (velocity <= 0) return null;
105- const note = 69 + 12 * Math.log2(freq / 440);
106- synthMsg({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when });
107- if (opts.immediateRelease) {
108- synthMsg({ type: "noteOff", note, time: when + duration });
109- return null;
110- }
111- lastOn.set(note, when);
112- const off: Off = { note, on: when, time: when + duration };
113- offs.push(off);
114- const handle: NoteHandle = {
115- hold(from, holdLen, fadeLen) {
116- const t = Math.max(from, ctx.currentTime);
117- off.time = t + holdLen + fadeLen;
118- if (holding) return; // instrument-wide: the first hold schedules it
119- holding = true;
120- // lengthen the decay (base and high-frequency loss alike) from `t`, as the direct
121- // instrument does; the renderer applies it when it reaches that time
122- const ring = holdLen + fadeLen;
123- const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
124- const slow = t60 / (sound.t60 as number);
125- send({ type: "timedParams", time: t, params: { ...sound, voices: allowed, t60, hfDamp: (sound.hfDamp as number) / slow } });
126- fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen);
127- },
128- };
129- return handle;
130- },
131- dispose() {
132- window.clearInterval(timer);
133- send({ type: "stop" });
134- window.setTimeout(() => {
135- worker.terminate();
136- node?.disconnect();
137- fade.disconnect();
138- }, 1000);
139- },
140- };
141- return inst;
142- };
143-}
144-
145-/** "modal: <name>" → streamed factory, for every built-in preset plus "modal: custom". */
146-export function streamedModalInstruments(): Record<string, NoteInstrumentFactory> {
147- const out: Record<string, NoteInstrumentFactory> = {};
148- for (const p of PRESETS) out[`modal: ${p.name}`] = makeStreamedFactory(p.p);
149- out["modal: custom"] = makeStreamedFactory(null);
150- return out;
151-}
152-
src/instruments/types.tsdeleted+0−95View file
@@ -1,95 +0,0 @@
1-// Instrument interfaces. Real instruments drop in by implementing these and
2-// registering in ./index.ts; compositions pick them by name.
3-
4-export interface NoteEvent {
5- /** AudioContext time */
6- when: number;
7- freq: number;
8- /** dynamics, 0..1 (overall level is set by the composition's mixer, not here) */
9- velocity: number;
10- /** -1..1 */
11- pan: number;
12- /** seconds; how long the note rings (instrument may interpret freely) */
13- duration: number;
14-}
15-
16-/** Control over a note after it has been scheduled. */
17-export interface NoteHandle {
18- /**
19- * Stop the note's natural decay at `from` (AudioContext time), sustain its level for
20- * `holdLen` seconds, then fade out over `fadeLen` seconds. Used for the final note of a piece.
21- */
22- hold(from: number, holdLen: number, fadeLen: number): void;
23-}
24-
25-export interface NoteInstrument {
26- /** resolves when the instrument can play (e.g. an AudioWorklet has loaded) */
27- ready?: Promise<void>;
28- /** share of real time the audio thread spends on this instrument (0..1), if it can tell */
29- load?(): number;
30- /** rendered-ahead instruments: every note before `time` (AudioContext time) has been played */
31- horizon?(time: number): void;
32- /** rendered-ahead instruments: how often playback ran out of rendered audio */
33- underruns?(): number;
34- /** rendered-ahead instruments: polyphony allowed on this device, and what the sound asked for */
35- voices?(): { allowed: number; wanted: number };
36- play(ev: NoteEvent): NoteHandle | null;
37- dispose(): void;
38-}
39-
40-/** Map the drone's color (0..1) onto one instrument setting. from/to are 0..1 of that setting's range. */
41-export interface TimbreMap {
42- target: string;
43- from: number;
44- to: number;
45-}
46-
47-export interface DroneInstrument {
48- /** resolves when the instrument can play */
49- ready?: Promise<void>;
50- /** share of real time the audio thread spends on this instrument (0..1), if it can tell */
51- load?(): number;
52- start(when: number, freq: number): void;
53- /** Stop with a release ending at `when`. */
54- stop(when: number, release: number): void;
55- /**
56- * Continuous controls, called often.
57- * level: linear gain 0..1; color: 0..1 timbre control (driven by energy).
58- */
59- set(
60- when: number,
61- controls: {
62- level: number;
63- color: number;
64- freq: number;
65- timbre?: TimbreMap[];
66- /** hold the output loudness steady while the timbre changes (instruments that support it) */
67- normalize?: boolean;
68- },
69- ): void;
70- /** current values of mapped settings, for the author readouts */
71- describe?(): string;
72- dispose(): void;
73-}
74-
75-export interface InstrumentOptions {
76- /** instrument-specific settings, e.g. a pasted modal-synth preset (JSON) */
77- custom?: string;
78- /** schedule each note's release when it is played (no final-note hold); for device checks */
79- immediateRelease?: boolean;
80- /**
81- * Effects: "own" (default: the instrument's own, e.g. modal-synth's reverb/delay), "none" (dry),
82- * or a shared reverb to send to (the instrument's reverb amount sets the send).
83- */
84- effects?: "own" | "none" | { send: AudioNode };
85- /** instrument settings to override (modal-synth parameters, e.g. { voices: 2 }) */
86- overrides?: Record<string, number | string | boolean>;
87- /**
88- * Drones: hold one note at `center` (MIDI) and glide its pitch with pitch bend over ±`range`
89- * semitones (≤ 24), instead of re-striking when the pitch changes.
90- */
91- glide?: { center: number; range: number };
92-}
93-
94-export type NoteInstrumentFactory = (ctx: AudioContext, out: AudioNode, opts: InstrumentOptions) => NoteInstrument;
95-export type DroneInstrumentFactory = (ctx: AudioContext, out: AudioNode, opts: InstrumentOptions) => DroneInstrument;
src/lab/ensembleWorklet.tsdeleted+0−159View file
@@ -1,159 +0,0 @@
1-// Ensemble lab: six audio-rate double pendulums with their own physics (pitch, mass and length
2-// ratios, ring time), mixed across the stereo field. A score, kept here on the audio clock so it is
3-// sample-accurate, pushes energy into chosen pendulums at each step; keys on the page push too.
4-
5-import { DoublePendulum } from "../physics/doublePendulum.ts";
6-import { mulberry32 } from "../core/rng.ts";
7-import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap } from "./protocol.ts";
8-import { DcBlock, kick, signal } from "./voice.ts";
9-
10-declare const sampleRate: number;
11-declare class AudioWorkletProcessor {
12- readonly port: MessagePort;
13- constructor();
14-}
15-declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
16-
17-const TRAIL = 192; // bob positions per pendulum in each snapshot
18-const DECIM = 3; // one trail sample every DECIM audio samples
19-const STEPS_PER_CYCLE = 40; // RK4 steps per cycle of a pendulum's faster mode, at least
20-
21-interface V {
22- p: DoublePendulum;
23- dc: DcBlock;
24- trail: Float32Array;
25- struck: number; // samples since the last push
26-}
27-
28-class Ensemble extends AudioWorkletProcessor {
29- private s: EnsembleSettings | null = null;
30- private v: V[] = [];
31- private rand = mulberry32(777);
32- private seed = 0;
33- private clock = 0; // samples since the score began
34- private step = 0; // score steps played
35- private trailW = 0;
36- private count = 0;
37- private sinceSnap = 0;
38-
39- constructor() {
40- super();
41- for (let i = 0; i < ENSEMBLE; i++) {
42- const p = new DoublePendulum({ m1: 1, m2: 1, l1: 1, l2: 1, g: 1 });
43- p.controlled = false;
44- this.v.push({ p, dc: new DcBlock(), trail: new Float32Array(2 * TRAIL), struck: 1e9 });
45- }
46- this.port.onmessage = (e: MessageEvent<EnsembleMsg>) => {
47- const m = e.data;
48- if (m.type === "settings") {
49- this.s = m.s;
50- if (m.s.seed !== this.seed) {
51- this.seed = m.s.seed;
52- this.rand = mulberry32(m.s.seed);
53- }
54- for (let i = 0; i < ENSEMBLE; i++) {
55- const cfg = this.v[i].p.cfg, vs = m.s.voices[i];
56- cfg.m1 = 1;
57- cfg.g = 1;
58- cfg.m2 = vs.m2;
59- cfg.l1 = vs.l1;
60- cfg.l2 = vs.l2;
61- }
62- } else if (m.type === "strike") {
63- const v = this.v[m.i];
64- if (v && this.s) {
65- kick(v.p, this.s.pulseAdds * v.p.vTop, this.rand);
66- v.struck = 0;
67- }
68- }
69- else if (m.type === "reset") {
70- for (const v of this.v) v.p.y.fill(0);
71- }
72- };
73- }
74-
75- process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
76- const out = outputs[0];
77- const Lo = out[0], Ro = out[1] ?? out[0];
78- const s = this.s;
79- if (!s) return true;
80- const n = Lo.length;
81- const stepSamples = Math.max(1, s.stepSec * sampleRate), delay = s.startDelay * sampleRate;
82- const dcR = 1 - (2 * Math.PI * s.dcCut) / sampleRate;
83- // per-voice constants for this block
84- const per = this.v.map((v, i) => {
85- const vs = s.voices[i];
86- const k = s.k; // one time scale: each pendulum's pitch comes from its size
87- const dtS = k / sampleRate;
88- // RK4 is very accurate at ≥ 40 steps per cycle: at audio rate that is usually one per sample
89- const sub = Math.max(1, Math.ceil((STEPS_PER_CYCLE * vs.upperHz) / sampleRate));
90- const pan = ENSEMBLE > 1 ? s.spread * ((2 * i) / (ENSEMBLE - 1) - 1) : 0;
91- const a = ((pan + 1) * Math.PI) / 4; // equal-power
92- v.p.damping = vs.ringTime > 0 ? (2 * 6.9078) / (vs.ringTime * k) : 0;
93- return { h: dtS / sub, sub, gl: Math.cos(a) * vs.level, gr: Math.sin(a) * vs.level };
94- });
95- for (let t = 0; t < n; t++) {
96- // the score: step k falls at delay + k·step
97- if (this.step < s.score.length && this.clock >= delay + this.step * stepSamples) {
98- for (const { i, add } of s.score[this.step]) {
99- const v = this.v[i];
100- if (!v) continue;
101- kick(v.p, add * v.p.vTop, this.rand);
102- v.struck = 0;
103- }
104- this.step++;
105- }
106- this.clock++;
107- let l = 0, r = 0;
108- for (let i = 0; i < ENSEMBLE; i++) {
109- const v = this.v[i], c = per[i], p = v.p;
110- for (let j = 0; j < c.sub; j++) p.step(c.h);
111- if (!Number.isFinite(p.y[0])) p.y.fill(0);
112- const d = p.derived();
113- const x = Math.tanh(s.gain * v.dc.run(signal(p, s.signal, d.w1, d.w2), dcR));
114- l += c.gl * x;
115- r += c.gr * x;
116- }
117- Lo[t] = l;
118- Ro[t] = r;
119- for (const v of this.v) v.struck++;
120- if (++this.count % DECIM === 0) {
121- for (const v of this.v) {
122- const y = v.p.y, cfg = v.p.cfg, o = 2 * this.trailW;
123- v.trail[o] = cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]);
124- v.trail[o + 1] = cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1]);
125- }
126- this.trailW = (this.trailW + 1) % TRAIL;
127- }
128- }
129- this.sinceSnap += n;
130- if (this.sinceSnap >= sampleRate / 30) {
131- this.sinceSnap = 0;
132- const trails = new Float32Array(ENSEMBLE * 2 * TRAIL);
133- this.v.forEach((v, i) => {
134- const o = i * 2 * TRAIL;
135- trails.set(v.trail.subarray(2 * this.trailW), o);
136- trails.set(v.trail.subarray(0, 2 * this.trailW), o + 2 * (TRAIL - this.trailW));
137- });
138- const joints = new Float32Array(4 * ENSEMBLE);
139- this.v.forEach((v, i) => {
140- const y = v.p.y, c = v.p.cfg;
141- const x1 = c.l1 * Math.sin(y[0]), y1 = c.l1 * Math.cos(y[0]);
142- joints.set([x1, y1, x1 + c.l2 * Math.sin(y[1]), y1 + c.l2 * Math.cos(y[1])], 4 * i);
143- });
144- const snap: EnsembleSnap = {
145- type: "snap",
146- joints,
147- struck: this.v.map((v) => v.struck / sampleRate),
148- time: this.clock / sampleRate,
149- step: this.step,
150- energy: this.v.map((v) => v.p.energyNorm()),
151- trails,
152- };
153- this.port.postMessage(snap, [trails.buffer, joints.buffer]);
154- }
155- return true;
156- }
157-}
158-
159-registerProcessor("pendulum-ensemble", Ensemble);
src/lab/protocol.tsmodified+0−42View file
@@ -31,45 +31,3 @@ export interface LabSnap {
3131 }
3232
3333 // ── ensemble lab ──
34-
35-export const ENSEMBLE = 6;
36-
37-export interface EnsembleVoice {
38- // physics (computed on the page from the musical ratios: see c05-ensemble/harmony.ts)
39- l1: number;
40- l2: number;
41- m2: number; // m1 = 1, g = 1
42- upperHz: number; // the faster mode's pitch at small swings (sets the integration step)
43- ringTime: number; // s: amplitude −60 dB
44- level: number; // linear
45-}
46-
47-export interface EnsembleSettings {
48- voices: EnsembleVoice[];
49- k: number; // sim seconds per audio second (one time scale for all: pitch comes from size)
50- pulseAdds: number; // normalized energy a key push adds
51- /** the score: step k (at startDelay + k·stepSec) pushes these pendulums by these energies */
52- score: { i: number; add: number }[][];
53- stepSec: number;
54- startDelay: number; // s
55- seed: number; // the random push directions from rest (a new one each play)
56- signal: Signal;
57- gain: number; // linear, before the soft limiter
58- dcCut: number; // Hz
59- spread: number; // 0..1 stereo spread
60-}
61-
62-export type EnsembleMsg =
63- | { type: "settings"; s: EnsembleSettings }
64- | { type: "strike"; i: number }
65- | { type: "reset" };
66-
67-export interface EnsembleSnap {
68- type: "snap";
69- time: number; // s since the score began (audio clock)
70- step: number; // score steps played so far
71- energy: number[]; // normalized, per pendulum
72- trails: Float32Array; // per pendulum: TRAIL × [x2, y2] (oldest → newest), physical units
73- joints: Float32Array; // per pendulum, now: [x1, y1, x2, y2]
74- struck: number[]; // per pendulum: s since its last push (beat or key)
75-}
src/lab/voice.tsmodified+10−9View file
@@ -1,5 +1,6 @@
11 // Shared by the labs: one double pendulum as an audio-rate voice (time scaling, strikes that add
2-// energy, signal extraction, DC removal).
2+// energy, signal extraction, DC removal). Deterministic math (dmath), as scores require.
3+import { cos, hypot, sin, wrap } from "../physics/dmath.ts";
34 import { DoublePendulum } from "../physics/doublePendulum.ts";
45 import type { Signal } from "./protocol.ts";
56
@@ -22,14 +23,14 @@ export function kick(p: DoublePendulum, add: number, rand: () => number) {
2223 const y = p.y;
2324 if (!(add > 0)) return;
2425 let u0 = y[2], u1 = y[3];
25- const pn = Math.hypot(u0, u1);
26+ const pn = hypot(u0, u1);
2627 if (pn > 1e-9) {
2728 u0 /= pn;
2829 u1 /= pn;
2930 } else {
3031 const a = rand() * 2 * Math.PI;
31- u0 = Math.cos(a);
32- u1 = Math.sin(a);
32+ u0 = cos(a);
33+ u1 = sin(a);
3334 }
3435 // energy after p → p + a·u is E + a·(u·ω) + ½a²·(u·M⁻¹u); solve for the positive a
3536 const now = p.derived();
@@ -47,7 +48,7 @@ export function signal(p: DoublePendulum, sig: Signal, w1: number, w2: number):
4748 const y = p.y;
4849 const L = l1 + l2;
4950 const vmax = Math.sqrt((2 * p.vTop) / m2) + 1e-9;
50- const s1 = Math.sin(y[0]), c1 = Math.cos(y[0]), s2 = Math.sin(y[1]), c2 = Math.cos(y[1]);
51+ const s1 = sin(y[0]), c1 = cos(y[0]), s2 = sin(y[1]), c2 = cos(y[1]);
5152 switch (sig) {
5253 case "x2": return (l1 * s1 + l2 * s2) / L;
5354 case "y2": return -(l1 * c1 + l2 * c2) / L;
@@ -55,14 +56,14 @@ export function signal(p: DoublePendulum, sig: Signal, w1: number, w2: number):
5556 case "vy2": return (l1 * s1 * w1 + l2 * s2 * w2) / vmax;
5657 case "x1": return s1;
5758 case "vx1": return (l1 * c1 * w1) / vmax;
58- case "θ1": return Math.atan2(s1, c1) / Math.PI;
59- case "θ2": return Math.atan2(s2, c2) / Math.PI;
60- case "θ2−θ1": return Math.atan2(Math.sin(y[1] - y[0]), Math.cos(y[1] - y[0])) / Math.PI;
59+ case "θ1": return wrap(y[0]) / Math.PI;
60+ case "θ2": return wrap(y[1]) / Math.PI;
61+ case "θ2−θ1": return wrap(y[1] - y[0]) / Math.PI;
6162 case "ω1": return (w1 * l1) / vmax;
6263 case "ω2": return (w2 * l2) / vmax;
6364 case "p1": return y[2] / (vmax * (1 + m2) * l1 * l1 + 1e-9);
6465 case "p2": return y[3] / (vmax * m2 * l2 * l2 + 1e-9);
65- case "speed2": return Math.hypot(l1 * c1 * w1 + l2 * c2 * w2, l1 * s1 * w1 + l2 * s2 * w2) / vmax;
66+ case "speed2": return hypot(l1 * c1 * w1 + l2 * c2 * w2, l1 * s1 * w1 + l2 * s2 * w2) / vmax;
6667 }
6768 }
6869
src/main.tsmodified+9−2View file
@@ -94,12 +94,14 @@ function showComposition(comp: Composition, author: boolean): () => void {
9494 h("span", { textContent: comp.hidden ? comp.title : `${index}. ${comp.title}` }),
9595 );
9696 const noticeEl = h("div", { className: "notice" });
97+ // shown while the performance is computing ahead (at the start, or if it has to catch up)
98+ const bufferingEl = h("div", { className: "buffering", hidden: true }, h("div", { className: "spinner" }), h("div", { className: "fill" }));
9799 const stage = h("main", { className: "stage" }, header, noticeEl, view, h("div", { className: "transport" }, playBtn, progress, editLink));
98100 const page = h("div", { className: author ? "page with-author" : "page" }, stage);
99101 app.append(page);
100102
101103 const piece: Piece = comp.create(view, () => params);
102- view.append(bigPlay);
104+ view.append(bigPlay, bufferingEl);
103105 // canvases fill the largest square that fits between the header and the transport
104106 const fit = () => {
105107 const s = Math.floor(Math.min(view.clientWidth, view.clientHeight));
@@ -131,7 +133,8 @@ function showComposition(comp: Composition, author: boolean): () => void {
131133 progress.onclick = (ev) => {
132134 const r = progress.getBoundingClientRect();
133135 const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
134- void play(t);
136+ if (piece.playing && piece.seek) piece.seek(t);
137+ else void play(t);
135138 };
136139 }
137140
@@ -166,6 +169,10 @@ function showComposition(comp: Composition, author: boolean): () => void {
166169 piece.draw();
167170 playBtn.textContent = piece.playing ? "stop" : "play";
168171 bigPlay.hidden = piece.playing || starting;
172+ const st = piece.playing ? piece.status?.() : undefined;
173+ const buffering = !!st?.buffering || starting;
174+ bufferingEl.hidden = !buffering;
175+ if (buffering) (bufferingEl.lastChild as HTMLElement).textContent = `${Math.round(100 * (st?.fill ?? 0))}%`;
169176 const note = piece.notice?.() ?? "";
170177 if (noticeEl.textContent !== note) noticeEl.textContent = note;
171178 bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
src/music/scales.tsmodified+4−2View file
@@ -1,4 +1,6 @@
11 // Scales as semitone offsets within an octave. "continuous" means no quantization.
2+// Deterministic math (dmath), since scores use these to choose notes.
3+import { log, pow } from "../physics/dmath.ts";
24
35 export const SCALES: Record<string, number[] | null> = {
46 continuous: null,
@@ -17,7 +19,7 @@ export const SCALE_NAMES = Object.keys(SCALES);
1719 export const NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
1820
1921 export function midiToFreq(m: number): number {
20- return 440 * Math.pow(2, (m - 69) / 12);
22+ return 440 * pow(2, (m - 69) / 12);
2123 }
2224
2325 /** Snap a (fractional) MIDI pitch to the nearest pitch of the scale. */
@@ -26,7 +28,7 @@ export function quantize(midi: number, scale: string, root: number): number {
2628 // partials of the root an octave or more below the pitch range
2729 const f0 = midiToFreq(root + 12 * Math.floor((24 - root) / 12)); // root in octave 1 (≈ 32–62 Hz)
2830 const n = Math.max(1, Math.round(midiToFreq(midi) / f0));
29- return 69 + 12 * Math.log2((n * f0) / 440);
31+ return 69 + (12 * log((n * f0) / 440)) / log(2);
3032 }
3133 const steps = SCALES[scale];
3234 if (!steps) return midi;
src/physics/dmath.tsadded+175−0View file
@@ -0,0 +1,175 @@
1+// Deterministic math for the simulations. Math.sin, Math.exp, Math.pow … may differ in the last bit
2+// between browsers (V8, JavaScriptCore and SpiderMonkey use different implementations), and a
3+// chaotic double pendulum amplifies a last-bit difference into a different performance within
4+// seconds. These are ports of the standard fdlibm/musl algorithms built only from + − × ÷ and
5+// Math.sqrt/round/floor/abs, which IEEE 754 makes identical everywhere. So the same seed and
6+// settings play the same physics, and the same notes, on every device.
7+//
8+// Rule: simulation code (everything in a score) uses these, never Math.sin/cos/exp/log/pow/hypot.
9+
10+const buf = new DataView(new ArrayBuffer(8));
11+const hiWord = (x: number) => (buf.setFloat64(0, x), buf.getInt32(0));
12+const fromWords = (hi: number, lo: number) => (buf.setInt32(0, hi), buf.setInt32(4, lo), buf.getFloat64(0));
13+const loWord = (x: number) => (buf.setFloat64(0, x), buf.getInt32(4));
14+
15+// ── sin / cos ──
16+
17+const S1 = -1.66666666666666324348e-1, S2 = 8.33333333332248946124e-3, S3 = -1.98412698298579493134e-4;
18+const S4 = 2.75573137070700676789e-6, S5 = -2.50507602534068634195e-8, S6 = 1.58969099521155010221e-10;
19+const C1 = 4.16666666666666019037e-2, C2 = -1.38888888888741095749e-3, C3 = 2.48015872894767294178e-5;
20+const C4 = -2.75573143513906633035e-7, C5 = 2.08757232129817482790e-9, C6 = -1.13596475577881948265e-11;
21+
22+function ksin(x: number, y: number): number {
23+ const z = x * x, v = z * x;
24+ const r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)));
25+ return x - ((z * (0.5 * y - v * r) - y) - v * S1);
26+}
27+
28+function kcos(x: number, y: number): number {
29+ const z = x * x;
30+ const r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6)))));
31+ const hz = 0.5 * z, w = 1 - hz;
32+ return w + (((1 - w) - hz) + (z * r - x * y));
33+}
34+
35+const INV_PIO2 = 6.36619772367581382433e-1;
36+const PIO2_1 = 1.57079632673412561417;
37+const PIO2_2 = 6.07710050630396597660e-11, PIO2_2T = 2.02226624879595063154e-21;
38+
39+/** x = n·π/2 + (y0 + y1), |y0 + y1| ≤ π/4 (Cody–Waite, two stages: accurate for |x| ≲ 1e6). */
40+let red0 = 0, red1 = 0;
41+function reduce(x: number): number {
42+ const fn = Math.round(x * INV_PIO2);
43+ const t = x - fn * PIO2_1; // exact (fn·PIO2_1 has trailing zeros)
44+ let w = fn * PIO2_2;
45+ let r: number;
46+ r = t - w;
47+ w = fn * PIO2_2T - ((t - r) - w);
48+ red0 = r - w;
49+ red1 = (r - red0) - w;
50+ return fn;
51+}
52+
53+export function sin(x: number): number {
54+ if (!Number.isFinite(x)) return NaN;
55+ if (Math.abs(x) < 7.85398163397448278999e-1) return ksin(x, 0);
56+ const n = reduce(x) & 3;
57+ if (n === 0) return ksin(red0, red1);
58+ if (n === 1) return kcos(red0, red1);
59+ if (n === 2) return -ksin(red0, red1);
60+ return -kcos(red0, red1);
61+}
62+
63+export function cos(x: number): number {
64+ if (!Number.isFinite(x)) return NaN;
65+ if (Math.abs(x) < 7.85398163397448278999e-1) return kcos(x, 0);
66+ const n = reduce(x) & 3;
67+ if (n === 0) return kcos(red0, red1);
68+ if (n === 1) return -ksin(red0, red1);
69+ if (n === 2) return -kcos(red0, red1);
70+ return ksin(red0, red1);
71+}
72+
73+// ── exp / log / pow ──
74+
75+const LN2_HI = 6.93147180369123816490e-1, LN2_LO = 1.90821492927058770002e-10, INV_LN2 = 1.44269504088896338700;
76+const P1 = 1.66666666666666019037e-1, P2 = -2.77777777770155933842e-3, P3 = 6.61375632143793436117e-5;
77+const P4 = -1.65339022054652515390e-6, P5 = 4.13813679705723846039e-8;
78+
79+/** y·2^k without libm (exact scaling, splitting k so each factor is a normal power of two). */
80+function scale2(y: number, k: number): number {
81+ while (k > 1023) {
82+ y *= fromWords(0x7fe00000, 0); // 2^1023
83+ k -= 1023;
84+ }
85+ while (k < -1022) {
86+ y *= fromWords(0x00100000, 0); // 2^-1022
87+ k += 1022;
88+ }
89+ return y * fromWords((k + 1023) << 20, 0);
90+}
91+
92+export function exp(x: number): number {
93+ if (Number.isNaN(x)) return NaN;
94+ if (x > 709.782712893383973096) return Infinity;
95+ if (x < -745.13321910194110842) return 0;
96+ let hi: number, lo: number, k: number;
97+ const ax = Math.abs(x);
98+ if (ax > 0.5 * 6.93147180559945286227e-1) {
99+ k = Math.trunc(INV_LN2 * x + (x < 0 ? -0.5 : 0.5));
100+ hi = x - k * LN2_HI;
101+ lo = k * LN2_LO;
102+ x = hi - lo;
103+ } else if (ax > 3.7252902984e-9) {
104+ k = 0;
105+ hi = x;
106+ lo = 0;
107+ } else return 1 + x;
108+ const xx = x * x;
109+ const c = x - xx * (P1 + xx * (P2 + xx * (P3 + xx * (P4 + xx * P5))));
110+ const y = 1 + ((x * c) / (2 - c) - lo + hi);
111+ return k === 0 ? y : scale2(y, k);
112+}
113+
114+const LG1 = 6.666666666666735130e-1, LG2 = 3.999999999940941908e-1, LG3 = 2.857142874366239149e-1;
115+const LG4 = 2.222219843214978396e-1, LG5 = 1.818357216161805012e-1, LG6 = 1.531383769920937332e-1;
116+const LG7 = 1.479819860511658591e-1;
117+
118+export function log(x: number): number {
119+ if (Number.isNaN(x) || x < 0) return NaN;
120+ if (x === 0) return -Infinity;
121+ if (x === Infinity) return Infinity;
122+ let k = 0;
123+ if (x < 2.2250738585072014e-308) {
124+ x *= 18014398509481984; // 2^54: subnormal → normal
125+ k -= 54;
126+ }
127+ let hx = hiWord(x);
128+ const lx = loWord(x);
129+ // reduce x into [√2/2, √2)
130+ hx += 0x3ff00000 - 0x3fe6a09e;
131+ k += (hx >> 20) - 0x3ff;
132+ hx = (hx & 0x000fffff) + 0x3fe6a09e;
133+ x = fromWords(hx, lx);
134+ const f = x - 1;
135+ const hfsq = 0.5 * f * f;
136+ const s = f / (2 + f);
137+ const z = s * s, w = z * z;
138+ const t1 = w * (LG2 + w * (LG4 + w * LG6));
139+ const t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
140+ const R = t2 + t1;
141+ return s * (hfsq + R) + k * LN2_LO - hfsq + f + k * LN2_HI;
142+}
143+
144+/** x^y for the cases simulations use (x ≥ 0, or x < 0 with integer y). */
145+export function pow(x: number, y: number): number {
146+ if (y === 0 || x === 1) return 1;
147+ if (Number.isNaN(x) || Number.isNaN(y)) return NaN;
148+ if (x === 0) return y > 0 ? 0 : Infinity;
149+ if (x < 0) {
150+ if (!Number.isInteger(y)) return NaN;
151+ const r = exp(y * log(-x));
152+ return y % 2 === 0 ? r : -r;
153+ }
154+ if (y === 1) return x;
155+ if (y === 2) return x * x;
156+ if (y === 0.5) return Math.sqrt(x);
157+ return exp(y * log(x));
158+}
159+
160+export function hypot(x: number, y: number): number {
161+ return Math.sqrt(x * x + y * y);
162+}
163+
164+export function tanh(x: number): number {
165+ if (x > 20) return 1;
166+ if (x < -20) return -1;
167+ const e = exp(2 * x);
168+ return (e - 1) / (e + 1);
169+}
170+
171+const TWO_PI = 6.283185307179586;
172+/** Angle wrapped to [−π, π), by arithmetic (no atan2). */
173+export function wrap(a: number): number {
174+ return a - TWO_PI * Math.floor((a + Math.PI) / TWO_PI);
175+}
src/physics/doublePendulum.tsmodified+19−15View file
@@ -1,4 +1,5 @@
11 // Frictionless double pendulum in canonical (Hamiltonian) coordinates.
2+// Uses deterministic math (dmath.ts), so a simulation is bit-identical in every browser.
23 // State y = [θ1, θ2, p1, p2]; angles measured from straight down.
34 //
45 // Energy is steered toward a target with a generalized force Q = λ·p.
@@ -6,6 +7,8 @@
67 // λ = (E* − E) / (τ (2T + ε))
78 // makes E relax toward E* with time constant ≈ τ while the motion stays smooth.
89
10+import { cos, sin, wrap } from "./dmath.ts";
11+
912 export interface PendulumConfig {
1013 m1: number;
1114 m2: number;
@@ -59,13 +62,13 @@ export class DoublePendulum {
5962 const { m1, m2, l1, l2, g } = this.cfg;
6063 const [th1, th2, p1, p2] = [y[0], y[1], y[2], y[3]];
6164 const d = th1 - th2;
62- const cd = Math.cos(d);
63- const sd = Math.sin(d);
65+ const cd = cos(d);
66+ const sd = sin(d);
6467 const den = m1 + m2 * sd * sd;
6568 const w1 = (l2 * p1 - l1 * p2 * cd) / (l1 * l1 * l2 * den);
6669 const w2 = (l1 * (m1 + m2) * p2 - l2 * m2 * p1 * cd) / (l1 * l2 * l2 * m2 * den);
6770 const T = 0.5 * (p1 * w1 + p2 * w2);
68- const V = (m1 + m2) * g * l1 * (1 - Math.cos(th1)) + m2 * g * l2 * (1 - Math.cos(th2));
71+ const V = (m1 + m2) * g * l1 * (1 - cos(th1)) + m2 * g * l2 * (1 - cos(th2));
6972 return { w1, w2, T, V };
7073 }
7174
@@ -83,20 +86,20 @@ export class DoublePendulum {
8386 const { m1, m2, l1, l2, g } = this.cfg;
8487 const th1 = y[0], th2 = y[1], p1 = y[2], p2 = y[3];
8588 const d = th1 - th2;
86- const cd = Math.cos(d);
87- const sd = Math.sin(d);
89+ const cd = cos(d);
90+ const sd = sin(d);
8891 const den = m1 + m2 * sd * sd;
8992 const w1 = (l2 * p1 - l1 * p2 * cd) / (l1 * l1 * l2 * den);
9093 const w2 = (l1 * (m1 + m2) * p2 - l2 * m2 * p1 * cd) / (l1 * l2 * l2 * m2 * den);
9194 const C1 = (p1 * p2 * sd) / (l1 * l2 * den);
9295 const C2 =
9396 ((l2 * l2 * m2 * p1 * p1 + l1 * l1 * (m1 + m2) * p2 * p2 - 2 * l1 * l2 * m2 * p1 * p2 * cd) *
94- Math.sin(2 * d)) /
97+ sin(2 * d)) /
9598 (2 * l1 * l1 * l2 * l2 * den * den);
9699
97100 // energy controller
98101 const T = 0.5 * (p1 * w1 + p2 * w2);
99- const V = (m1 + m2) * g * l1 * (1 - Math.cos(th1)) + m2 * g * l2 * (1 - Math.cos(th2));
102+ const V = (m1 + m2) * g * l1 * (1 - cos(th1)) + m2 * g * l2 * (1 - cos(th2));
100103 let lam = 0;
101104 if (this.controlled) {
102105 const eps = 0.02 * this.vTop;
@@ -109,8 +112,8 @@ export class DoublePendulum {
109112
110113 out[0] = w1;
111114 out[1] = w2;
112- out[2] = -(m1 + m2) * g * l1 * Math.sin(th1) - C1 + C2 + lam * p1;
113- out[3] = -m2 * g * l2 * Math.sin(th2) + C1 - C2 + lam * p2;
115+ out[2] = -(m1 + m2) * g * l1 * sin(th1) - C1 + C2 + lam * p1;
116+ out[3] = -m2 * g * l2 * sin(th2) + C1 - C2 + lam * p2;
114117 }
115118
116119 /** One RK4 step. */
@@ -146,8 +149,8 @@ export class DoublePendulum {
146149 }
147150 const K = E - V;
148151 const phi = rand() * 2 * Math.PI;
149- const u1 = Math.cos(phi), u2 = Math.sin(phi);
150- const cd = Math.cos(th1 - th2);
152+ const u1 = cos(phi), u2 = sin(phi);
153+ const cd = cos(th1 - th2);
151154 // mass matrix M
152155 const M11 = (m1 + m2) * l1 * l1;
153156 const M12 = m2 * l1 * l2 * cd;
@@ -176,10 +179,10 @@ export function seedOnSection(P: DoublePendulum, e: number, rand: () => number):
176179 for (let tries = 0; tries < 400; tries++) {
177180 const th2 = (2 * rand() - 1) * Math.PI;
178181 const p2 = (2 * rand() - 1) * pMax;
179- const V = m2 * g * l2 * (1 - Math.cos(th2));
182+ const V = m2 * g * l2 * (1 - cos(th2));
180183 if (V >= E) continue;
181- const cd = Math.cos(-th2);
182- const sd = Math.sin(-th2);
184+ const cd = cos(-th2);
185+ const sd = sin(-th2);
183186 const den = m1 + m2 * sd * sd;
184187 // T(p1) = E − V is a quadratic in p1
185188 const a = m2 * l2 * l2;
@@ -199,6 +202,7 @@ export function seedOnSection(P: DoublePendulum, e: number, rand: () => number):
199202 return false;
200203 }
201204
205+/** Angle wrapped to [−π, π) (deterministic). */
202206 export function wrapAngle(a: number): number {
203- return Math.atan2(Math.sin(a), Math.cos(a));
207+ return wrap(a);
204208 }
src/stream/frames.tsadded+107−0View file
@@ -0,0 +1,107 @@
1+// Drawing data from the score, kept on the page: tracks of rows [t, v…] in time order, and events.
2+// Views read what they need at the playhead time (interpolated state, a trail's recent rows…).
3+
4+import type { VisEvent } from "./protocol.ts";
5+
6+interface Batch {
7+ t0: number;
8+ t1: number;
9+ stride: number;
10+ data: Float64Array;
11+}
12+
13+export class FrameStore {
14+ private tracks = new Map<number, Batch[]>();
15+ events: VisEvent[] = [];
16+ /** the latest readouts from the score, by piece time */
17+ private infos: { t: number; info: Record<string, string> }[] = [];
18+
19+ add(track: number, stride: number, data: Float64Array) {
20+ if (!data.length) return;
21+ let list = this.tracks.get(track);
22+ if (!list) this.tracks.set(track, (list = []));
23+ list.push({ t0: data[0], t1: data[data.length - stride], stride, data });
24+ }
25+
26+ addEvents(e: VisEvent[]) {
27+ for (const x of e) this.events.push(x);
28+ }
29+
30+ addInfo(t: number, info: Record<string, string>) {
31+ this.infos.push({ t, info });
32+ }
33+
34+ /** Readouts as of piece time t. */
35+ info(t: number): Record<string, string> {
36+ let best: Record<string, string> = {};
37+ for (const x of this.infos) if (x.t <= t) best = x.info;
38+ return best;
39+ }
40+
41+ /** Drop what's older than t (keep one row before it, for interpolation). */
42+ trim(t: number) {
43+ for (const list of this.tracks.values()) while (list.length > 1 && list[1].t0 <= t && list[0].t1 < t) list.shift();
44+ let i = 0;
45+ while (i < this.events.length && this.events[i].t < t) i++;
46+ if (i > 0) this.events.splice(0, i);
47+ while (this.infos.length > 1 && this.infos[1].t <= t) this.infos.shift();
48+ }
49+
50+ /** Last time covered by a track (−∞ if none). */
51+ last(track: number): number {
52+ const list = this.tracks.get(track);
53+ return list?.length ? list[list.length - 1].t1 : -Infinity;
54+ }
55+
56+ /**
57+ * The track's values at time t, linearly interpolated between rows (clamped at the ends).
58+ * Writes into `out` (length stride − 1) and returns it, or null if the track is empty.
59+ */
60+ at(track: number, t: number, out: Float64Array): Float64Array | null {
61+ const list = this.tracks.get(track);
62+ if (!list?.length) return null;
63+ // the batch holding t (or the nearest end)
64+ let bi = list.length - 1;
65+ while (bi > 0 && list[bi].t0 > t) bi--;
66+ const b = list[bi], S = b.stride, n = b.data.length / S;
67+ const d = b.data;
68+ // the row at or before t, by bisection
69+ let lo = 0, hi = n - 1;
70+ if (t <= d[0]) hi = 0;
71+ else if (t >= d[(n - 1) * S]) lo = hi = n - 1;
72+ else {
73+ while (hi - lo > 1) {
74+ const mid = (lo + hi) >> 1;
75+ if (d[mid * S] <= t) lo = mid;
76+ else hi = mid;
77+ }
78+ }
79+ let ra = lo * S, rb = hi * S, src = d, srcB = d;
80+ // past the batch's last row: interpolate toward the next batch's first row
81+ if (lo === hi && lo === n - 1 && bi + 1 < list.length && t > d[ra]) {
82+ srcB = list[bi + 1].data;
83+ rb = 0;
84+ }
85+ const ta = src[ra], tb = srcB[rb];
86+ const f = tb > ta ? Math.min(1, Math.max(0, (t - ta) / (tb - ta))) : 0;
87+ for (let k = 1; k < S; k++) out[k - 1] = src[ra + k] + f * (srcB[rb + k] - src[ra + k]);
88+ return out;
89+ }
90+
91+ /** Call fn for every row with t0 ≤ t ≤ t1, in order (fn gets the array and the row's offset). */
92+ rows(track: number, t0: number, t1: number, fn: (d: Float64Array, o: number) => void) {
93+ const list = this.tracks.get(track);
94+ if (!list) return;
95+ for (const b of list) {
96+ if (b.t1 < t0) continue;
97+ if (b.t0 > t1) break;
98+ const S = b.stride, d = b.data;
99+ for (let o = 0; o < d.length; o += S) {
100+ const t = d[o];
101+ if (t < t0) continue;
102+ if (t > t1) break;
103+ fn(d, o);
104+ }
105+ }
106+ }
107+}
src/stream/layout.tsadded+35−0View file
@@ -0,0 +1,35 @@
1+// How a composition's performance is laid out: its stems (each rendered by one producer) and the
2+// outputs they play on (each with its effects and live level on the page). Worker-safe: the score
3+// uses the same layout to know its stem numbers.
4+
5+import type { Params as SynthParams } from "@modal-synth/engine/params.ts";
6+import type { Params } from "../core/params.ts";
7+
8+export interface StemSpec {
9+ /** "synth": a modal-synth instrument in its own worker, played by the score's notes;
10+ * "score": audio the score renders itself (e.g. the ensemble's pendulums) */
11+ kind: "synth" | "score";
12+ sound?: SynthParams;
13+ output: number;
14+}
15+
16+export interface OutputSpec {
17+ /**
18+ * "own": the sound's own modal-synth effects (saturation, delay, reverb);
19+ * "shared": dry at the sound's volume plus a send to the piece's one shared reverb;
20+ * "none": dry (at the sound's volume, if it has one)
21+ */
22+ effects: "own" | "shared" | "none";
23+ sound?: SynthParams;
24+ /** dB, read live */
25+ level: (P: Params) => number;
26+ /** −1..1, read live */
27+ pan?: (P: Params) => number;
28+}
29+
30+export interface Layout {
31+ stems: StemSpec[];
32+ outputs: OutputSpec[];
33+ /** T60 of the shared reverb (outputs with effects "shared") */
34+ reverbTime?: number;
35+}
src/stream/performance.tsadded+185−0View file
@@ -0,0 +1,185 @@
1+// One performance of a composition from a start time: the score worker, one synth worker per
2+// instrument stem, the player worklet, and the effects. The page only draws: it reads the player's
3+// playhead (so picture and sound share one clock) and the drawing data the score sends.
4+
5+import type { Params } from "../core/params.ts";
6+import { SharedReverb, routeEffects } from "../instruments/effects.ts";
7+import { FrameStore } from "./frames.ts";
8+import type { Layout } from "./layout.ts";
9+import playerUrl from "./player.ts?worker&url";
10+import { BLOCK, SAMPLE_RATE, type PlayerOptions, type PlayerStatus, type ScoreInit, type ScoreOut, type SynthInit } from "./protocol.ts";
11+
12+/** Sound is computed from this long before the start point, so notes already ringing are heard. */
13+const PREROLL = 4;
14+
15+const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
16+
17+export type PerformanceState = "loading" | "buffering" | "playing" | "ended" | "error";
18+
19+export class Performance {
20+ readonly store = new FrameStore();
21+ readonly start: number;
22+ readonly seed: number;
23+ state: PerformanceState = "loading";
24+ endT: number | null = null;
25+ error: string | null = null;
26+ fill = 0;
27+ rebuffers = 0;
28+ ahead = 0;
29+ readonly ready: Promise<void>;
30+
31+ private ctx: AudioContext;
32+ private layout: Layout;
33+ private workers: Worker[] = [];
34+ private node: AudioWorkletNode | null = null;
35+ private master: GainNode;
36+ private levels: GainNode[] = [];
37+ private pans: (StereoPannerNode | null)[] = [];
38+ private reverb: SharedReverb | null = null;
39+ private status: PlayerStatus | null = null;
40+ private disposed = false;
41+ private estimatedEnd: number;
42+
43+ constructor(ctx: AudioContext, dest: AudioNode, comp: string, P: Params, seed: number, start: number, layout: Layout, estimatedEnd: number) {
44+ this.ctx = ctx;
45+ this.start = start;
46+ this.seed = seed;
47+ this.layout = layout;
48+ this.estimatedEnd = estimatedEnd;
49+ this.master = ctx.createGain();
50+ this.master.connect(dest);
51+ this.ready = this.open(comp, P);
52+ }
53+
54+ private async open(comp: string, P: Params) {
55+ const ctx = this.ctx;
56+ let p = loaded.get(ctx);
57+ if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(playerUrl)));
58+ await p;
59+ if (this.disposed) return;
60+ const { stems, outputs } = this.layout;
61+
62+ // the player, and each output's level → pan → effects
63+ const opts: PlayerOptions = { stems: stems.length, outputs: outputs.length, route: stems.map((s) => s.output), startFrame: Math.round(this.start * SAMPLE_RATE), estimatedEnd: Math.round(this.estimatedEnd * SAMPLE_RATE) };
64+ const node = new AudioWorkletNode(ctx, "stream-player", {
65+ numberOfInputs: 0,
66+ numberOfOutputs: outputs.length,
67+ outputChannelCount: outputs.map(() => 2),
68+ processorOptions: opts,
69+ });
70+ this.node = node;
71+ if (outputs.some((o) => o.effects === "shared")) this.reverb = new SharedReverb(ctx, this.master, this.layout.reverbTime ?? 3);
72+ outputs.forEach((o, i) => {
73+ const level = ctx.createGain();
74+ level.gain.value = Math.pow(10, o.level(P) / 20);
75+ node.connect(level, i);
76+ let tail: AudioNode = level;
77+ let pan: StereoPannerNode | null = null;
78+ if (o.pan) {
79+ pan = ctx.createStereoPanner();
80+ pan.pan.value = o.pan(P);
81+ level.connect(pan);
82+ tail = pan;
83+ }
84+ routeEffects(ctx, tail, this.master, o.sound, o.effects === "shared" ? { send: this.reverb!.input } : o.effects);
85+ this.levels.push(level);
86+ this.pans.push(pan);
87+ });
88+ node.port.onmessage = (e: MessageEvent<PlayerStatus>) => this.onStatus(e.data);
89+
90+ // workers: score, and a synth per synth stem; ports between them and to the player
91+ const from = Math.max(0, this.start - PREROLL);
92+ const playerPorts: MessagePort[] = [];
93+ const synthPorts: (MessagePort | null)[] = [];
94+ stems.forEach((s, i) => {
95+ if (s.kind !== "synth") {
96+ synthPorts.push(null);
97+ return;
98+ }
99+ const w = new Worker(new URL("./synthWorker.ts", import.meta.url), { type: "module" });
100+ this.workers.push(w);
101+ const toScore = new MessageChannel(), toPlayer = new MessageChannel();
102+ synthPorts.push(toScore.port1);
103+ playerPorts.push(toPlayer.port2);
104+ const init: SynthInit = {
105+ type: "init",
106+ sound: s.sound ?? {},
107+ fromFrame: Math.floor((from * SAMPLE_RATE) / BLOCK) * BLOCK,
108+ sendFrame: Math.round(this.start * SAMPLE_RATE),
109+ stem: i,
110+ scorePort: toScore.port2,
111+ playerPort: toPlayer.port1,
112+ slow: Number(new URLSearchParams(location.search).get("slow")) || undefined,
113+ };
114+ w.postMessage(init, [toScore.port2, toPlayer.port1]);
115+ w.onerror = (ev) => this.fail(`instrument: ${ev.message}`);
116+ });
117+ const sw = new Worker(new URL("./scoreWorker.ts", import.meta.url), { type: "module" });
118+ this.workers.push(sw);
119+ const scoreToPlayer = new MessageChannel();
120+ playerPorts.push(scoreToPlayer.port2);
121+ sw.onmessage = (e: MessageEvent<ScoreOut>) => this.onScore(e.data);
122+ sw.onerror = (ev) => this.fail(`score: ${ev.message}`);
123+ const init: ScoreInit = { type: "init", comp, P, seed: this.seed, start: this.start, from, synthPorts, playerPort: scoreToPlayer.port1 };
124+ sw.postMessage(init, [...synthPorts.filter((x): x is MessagePort => !!x), scoreToPlayer.port1]);
125+ node.port.postMessage({ type: "ports", ports: playerPorts }, playerPorts);
126+ this.state = "buffering";
127+ }
128+
129+ private onScore(m: ScoreOut) {
130+ if (m.type === "frames") this.store.add(m.track, m.stride, m.data);
131+ else if (m.type === "events") this.store.addEvents(m.events);
132+ else if (m.type === "info") this.store.addInfo(m.t, m.info);
133+ else if (m.type === "end") this.endT = m.t;
134+ else if (m.type === "error") this.fail(m.message);
135+ }
136+
137+ private onStatus(s: PlayerStatus) {
138+ this.status = s;
139+ if (this.state === "error") return;
140+ this.state = s.state;
141+ this.fill = s.fill;
142+ this.rebuffers = s.rebuffers;
143+ this.ahead = s.ahead;
144+ }
145+
146+ private fail(message: string) {
147+ this.state = "error";
148+ this.error = message;
149+ console.error(message);
150+ }
151+
152+ /** Time the listener is hearing now (piece seconds): the player's playhead, less output latency. */
153+ time(): number {
154+ const s = this.status;
155+ if (!s) return this.start;
156+ let frames = s.playhead;
157+ if (s.state === "playing") frames += Math.min(4096, Math.max(0, this.ctx.currentTime * SAMPLE_RATE - s.at));
158+ const latency = (this.ctx.outputLatency || 0) + (this.ctx.baseLatency || 0);
159+ return Math.max(this.start, frames / SAMPLE_RATE - latency);
160+ }
161+
162+ /** Live settings: output levels and pans. */
163+ update(P: Params) {
164+ const t = this.ctx.currentTime;
165+ this.layout.outputs.forEach((o, i) => {
166+ this.levels[i]?.gain.setTargetAtTime(Math.pow(10, o.level(P) / 20), t, 0.05);
167+ if (o.pan) this.pans[i]?.pan.setTargetAtTime(o.pan(P), t, 0.05);
168+ });
169+ }
170+
171+ dispose() {
172+ if (this.disposed) return;
173+ this.disposed = true;
174+ for (const w of this.workers) w.terminate();
175+ const t = this.ctx.currentTime;
176+ const m = this.master, node = this.node, rev = this.reverb;
177+ m.gain.setTargetAtTime(0, t, 0.02);
178+ window.setTimeout(() => {
179+ node?.disconnect();
180+ node?.port.close();
181+ rev?.dispose();
182+ m.disconnect();
183+ }, 200);
184+ }
185+}
src/stream/piece.tsadded+133−0View file
@@ -0,0 +1,133 @@
1+// A composition played through the streaming system. The composition provides its layout, its
2+// score (in the score worker, by id) and a view that draws from the score's data at the
3+// playhead; this turns them into a Piece for the album shell: play, stop, seek, buffering status,
4+// and author edits (live settings apply at once; others recompute the performance from the
5+// current moment, with the same seed).
6+
7+import type { AudioEngine } from "../core/audio.ts";
8+import type { Piece } from "../core/composition.ts";
9+import type { ParamSpec, Params } from "../core/params.ts";
10+import { randomSeed } from "../core/rng.ts";
11+import type { FrameStore } from "./frames.ts";
12+import type { Layout } from "./layout.ts";
13+import { Performance } from "./performance.ts";
14+
15+export interface View {
16+ /** Draw at piece time t from the score's data (null before the first play: a preview). */
17+ draw(t: number, store: FrameStore | null, playing: boolean): void;
18+ /** seconds of drawing data to keep before the playhead (trails, fading points) */
19+ keep(P: Params): number;
20+ readouts?(t: number, store: FrameStore | null): Record<string, string>;
21+ dispose?(): void;
22+}
23+
24+export interface StreamDef {
25+ id: string;
26+ schema: ParamSpec[];
27+ layout(P: Params): Layout;
28+ /** length before the score knows its end */
29+ estimateLength(P: Params): number;
30+ view(el: HTMLElement, params: () => Params): View;
31+}
32+
33+const RESTART_DELAY = 400; // ms after the last non-live edit
34+
35+export function createStreamPiece(def: StreamDef, el: HTMLElement, params: () => Params): Piece {
36+ const view = def.view(el, params);
37+ const fixedKeys = def.schema.filter((s) => !s.live).map((s) => s.key);
38+ const fixedKey = (P: Params) => JSON.stringify(fixedKeys.map((k) => P[k]));
39+
40+ let audio: AudioEngine | null = null;
41+ let perf: Performance | null = null;
42+ let perfKey = "";
43+ let store: FrameStore | null = null; // what's drawn (kept after a stop)
44+ let stoppedAt = 0;
45+ let lastEnd: number | null = null;
46+ let seed = 0;
47+ let restartAt = 0;
48+ let notice: string | null = null;
49+ // drawing data is also trimmed on a timer: animation frames stop while the page is hidden
50+ const trimTimer = window.setInterval(() => store?.trim(piece.now() - view.keep(params())), 1000);
51+
52+ function open(a: AudioEngine, offset: number, keepSeed: boolean) {
53+ const P = params();
54+ perf?.dispose();
55+ audio = a;
56+ if (!keepSeed || !seed) seed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
57+ perf = new Performance(a.ctx, a.input, def.id, P, seed, Math.max(0, offset), def.layout(P), def.estimateLength(P));
58+ perfKey = fixedKey(P);
59+ store = perf.store;
60+ lastEnd = null;
61+ notice = null;
62+ restartAt = 0;
63+ }
64+
65+ function stop() {
66+ if (!perf) return;
67+ stoppedAt = perf.time();
68+ if (perf.endT !== null) lastEnd = perf.endT;
69+ perf.dispose();
70+ perf = null;
71+ }
72+
73+ const piece: Piece = {
74+ get playing() {
75+ return perf !== null;
76+ },
77+ async start(a, offset) {
78+ open(a, offset, false);
79+ await perf!.ready;
80+ },
81+ stop,
82+ seek(t) {
83+ if (audio) open(audio, t, true);
84+ },
85+ draw() {
86+ const P = params();
87+ if (perf) {
88+ if (perf.state === "error") {
89+ notice = "something went wrong computing this piece; try play again";
90+ stop();
91+ } else if (perf.state === "ended") {
92+ const end = perf.endT ?? perf.time();
93+ stop();
94+ stoppedAt = end;
95+ piece.onEnded?.();
96+ } else {
97+ perf.update(P);
98+ // a change to the performance itself: recompute from here, with the same seed
99+ if (fixedKey(P) !== perfKey) {
100+ const now = performance.now();
101+ if (!restartAt) restartAt = now + RESTART_DELAY;
102+ else if (now >= restartAt && audio) open(audio, perf.time(), true);
103+ } else restartAt = 0;
104+ }
105+ }
106+ const t = piece.now();
107+ store?.trim(t - view.keep(P));
108+ view.draw(t, store, perf?.state === "playing");
109+ },
110+ now: () => (perf ? perf.time() : stoppedAt),
111+ length: () => perf?.endT ?? lastEnd ?? def.estimateLength(params()),
112+ status: () => ({ buffering: perf !== null && (perf.state === "loading" || perf.state === "buffering"), fill: perf?.fill ?? 0 }),
113+ notice: () => notice,
114+ readouts() {
115+ const t = piece.now();
116+ return {
117+ time: `${t.toFixed(1)} / ${piece.length().toFixed(1)} s`,
118+ buffer: perf ? `${perf.state}, ${perf.ahead.toFixed(1)} s ahead, ${perf.rebuffers} pause${perf.rebuffers === 1 ? "" : "s"}` : "–",
119+ "seed used": seed ? String(seed) : "–",
120+ ...(store?.info(t) ?? {}),
121+ ...(view.readouts?.(t, store) ?? {}),
122+ };
123+ },
124+ dispose() {
125+ stop();
126+ window.clearInterval(trimTimer);
127+ view.dispose?.();
128+ el.replaceChildren();
129+ },
130+ };
131+ if (import.meta.env.DEV) (globalThis as { __piece?: Piece }).__piece = piece; // for tests in the dev server
132+ return piece;
133+}
src/stream/player.tsadded+243−0View file
@@ -0,0 +1,243 @@
1+// AudioWorklet that plays a performance: audio rendered ahead by workers ("stems"), mixed onto
2+// outputs (each output feeds its own effects on the page). It owns the piece's clock: the playhead
3+// advances only while every stem has audio for it. When any stem runs short, everything pauses
4+// (sound fades, the page's picture freezes at the playhead) until all stems are buffered `resume`
5+// seconds ahead. It measures how fast the stems are being rendered: on a device that renders
6+// slower than real time, a pause waits long enough to play through to the end (like a video's
7+// "can play through"); otherwise each pause doubles `resume`, so waits get fewer and longer.
8+
9+import { BLOCK, type Clock, type PlayerOptions, type PlayerStatus, type ToPlayer } from "./protocol.ts";
10+
11+declare const currentFrame: number;
12+declare const sampleRate: number;
13+declare class AudioWorkletProcessor {
14+ readonly port: MessagePort;
15+ constructor(options?: { processorOptions?: unknown });
16+}
17+declare function registerProcessor(name: string, ctor: new (options: { processorOptions?: unknown }) => AudioWorkletProcessor): void;
18+
19+const RESUME_START = 1.0; // s buffered before playing at first
20+const RESUME_MAX = 32; // s
21+const AHEAD_MIN = 4; // s producers keep rendered ahead, at least
22+const FADE_IN = 512; // samples
23+const TAIL = 0.985; // per-sample decay of the last sample when sound stops for buffering
24+const REPORT_EVERY = 6; // blocks between status reports (~16 ms)
25+const RATE_EVERY = 12; // blocks between render-rate samples
26+const RATE_WINDOW = 2; // s of render-rate samples kept
27+const RATE_MIN = 1; // s of uncapped samples needed before the rate counts
28+
29+interface Chunk {
30+ frame: number;
31+ L: Float32Array;
32+ R: Float32Array;
33+}
34+
35+class StreamPlayer extends AudioWorkletProcessor {
36+ private o: PlayerOptions;
37+ private queues: Chunk[][];
38+ private avail: number[]; // per stem: frame up to which audio has arrived (contiguous)
39+ private doneAt: number[]; // per stem: silent from this frame on
40+ private ports: MessagePort[] = [];
41+ private playhead: number;
42+ private endFrame = Infinity;
43+ private state: PlayerStatus["state"] = "buffering";
44+ private resume = RESUME_START;
45+ private rebuffers = 0;
46+ private fadeIn = 0;
47+ private tail: number[][]; // per output: [L, R] last samples, decaying while paused
48+ private blocks = 0;
49+ // render-rate samples: [audio-clock frame, least rendered frame of the stems], while not capped
50+ private rateLog: [number, number][] = [];
51+
52+ constructor(options: { processorOptions?: unknown }) {
53+ super(options);
54+ this.o = options.processorOptions as PlayerOptions;
55+ this.queues = Array.from({ length: this.o.stems }, () => []);
56+ this.avail = Array(this.o.stems).fill(this.o.startFrame);
57+ this.doneAt = Array(this.o.stems).fill(Infinity);
58+ this.playhead = this.o.startFrame;
59+ this.tail = Array.from({ length: this.o.outputs }, () => [0, 0]);
60+ this.port.onmessage = (e: MessageEvent<{ type: "ports"; ports: MessagePort[] }>) => {
61+ if (e.data?.type !== "ports") return;
62+ for (const p of e.data.ports) {
63+ this.ports.push(p);
64+ p.onmessage = (ev: MessageEvent<ToPlayer>) => this.receive(ev.data);
65+ }
66+ this.clock();
67+ };
68+ }
69+
70+ private receive(m: ToPlayer) {
71+ if (m.type === "chunk") {
72+ const q = this.queues[m.stem];
73+ if (!q) return;
74+ q.push({ frame: m.frame, L: m.L, R: m.R });
75+ this.avail[m.stem] = Math.max(this.avail[m.stem], m.frame + m.L.length);
76+ } else if (m.type === "done") this.doneAt[m.stem] = Math.min(this.doneAt[m.stem], m.frame);
77+ else if (m.type === "end") this.endFrame = m.frame;
78+ }
79+
80+ /** Is every stem ready up to frame `to` (from the playhead)? */
81+ private readyTo(to: number): boolean {
82+ for (let s = 0; s < this.o.stems; s++) {
83+ const need = Math.min(to, this.doneAt[s], this.endFrame);
84+ if (this.avail[s] < need) return false;
85+ }
86+ return true;
87+ }
88+
89+ /** Least rendered frame over the stems still sounding (Infinity if none). */
90+ private least(): number {
91+ let a = Infinity;
92+ for (let s = 0; s < this.o.stems; s++) if (this.doneAt[s] > this.playhead) a = Math.min(a, this.avail[s]);
93+ return a;
94+ }
95+
96+ /** Render speed (s of audio per s), from recent samples; null until measured. */
97+ private rate(): number | null {
98+ const log = this.rateLog;
99+ if (log.length < 2) return null;
100+ const [f0, a0] = log[0], [f1, a1] = log[log.length - 1];
101+ if (f1 - f0 < RATE_MIN * sampleRate) return null;
102+ return (a1 - a0) / (f1 - f0);
103+ }
104+
105+ /** Frames producers should keep rendered ahead: comfortably more than any buffering target. */
106+ private aheadFrames(): number {
107+ return Math.round(Math.max(AHEAD_MIN, 2 * this.resume, this.target() + 2) * sampleRate);
108+ }
109+
110+ private measure() {
111+ const least = this.least();
112+ const ahead = this.aheadFrames();
113+ // only while the producers are working flat out (not waiting at their buffer limit)
114+ if (!Number.isFinite(least) || least - this.playhead > 0.8 * ahead) {
115+ this.rateLog = [];
116+ return;
117+ }
118+ this.rateLog.push([currentFrame, least]);
119+ while (this.rateLog.length > 2 && currentFrame - this.rateLog[0][0] > RATE_WINDOW * sampleRate) this.rateLog.shift();
120+ }
121+
122+ /** Seconds to buffer before resuming: `resume`, or enough to play through if rendering is slow. */
123+ private target(): number {
124+ const r = this.rate();
125+ if (r === null || r >= 1) return this.resume;
126+ const end = Number.isFinite(this.endFrame) ? this.endFrame : this.o.estimatedEnd;
127+ const through = ((end - this.playhead) / sampleRate) * (1 - r) * 1.15 + 0.5;
128+ return Math.min(RESUME_MAX, Math.max(this.resume, through));
129+ }
130+
131+ private fill(): number {
132+ const target = Math.min(this.playhead + this.target() * sampleRate, this.endFrame);
133+ if (target <= this.playhead) return 1;
134+ let f = 1;
135+ for (let s = 0; s < this.o.stems; s++) {
136+ const need = Math.min(target, this.doneAt[s]);
137+ if (need <= this.playhead) continue;
138+ f = Math.min(f, Math.max(0, (this.avail[s] - this.playhead) / (need - this.playhead)));
139+ }
140+ return f;
141+ }
142+
143+ private ahead(): number {
144+ let a = Infinity;
145+ for (let s = 0; s < this.o.stems; s++) if (this.doneAt[s] > this.playhead) a = Math.min(a, this.avail[s] - this.playhead);
146+ return a === Infinity ? 0 : a / sampleRate;
147+ }
148+
149+ private clock() {
150+ const ahead = this.aheadFrames();
151+ const m: Clock = { type: "clock", playhead: this.playhead, ahead };
152+ for (const p of this.ports) p.postMessage(m);
153+ }
154+
155+ private report() {
156+ const m: PlayerStatus = {
157+ type: "status",
158+ state: this.state,
159+ playhead: this.playhead,
160+ at: currentFrame,
161+ fill: this.state === "buffering" ? this.fill() : 1,
162+ rebuffers: this.rebuffers,
163+ ahead: this.ahead(),
164+ };
165+ this.port.postMessage(m);
166+ }
167+
168+ process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
169+ const n = BLOCK;
170+ if (this.state === "playing" && this.playhead >= this.endFrame) this.state = "ended";
171+ if (this.blocks % RATE_EVERY === 0) this.measure();
172+ if (this.state === "buffering") {
173+ const target = Math.min(this.playhead + Math.round(this.target() * sampleRate), this.endFrame);
174+ if (this.readyTo(target)) {
175+ this.state = "playing";
176+ this.fadeIn = 0;
177+ }
178+ }
179+ if (this.state === "playing" && !this.readyTo(this.playhead + n)) {
180+ // a stem ran short: pause everything until it's buffered further ahead
181+ this.state = "buffering";
182+ this.rebuffers++;
183+ this.resume = Math.min(RESUME_MAX, this.resume * 2);
184+ }
185+
186+ if (this.state !== "playing") {
187+ for (let o = 0; o < outputs.length; o++) {
188+ const L = outputs[o][0], R = outputs[o][1] ?? L, tl = this.tail[o];
189+ for (let i = 0; i < n; i++) {
190+ tl[0] *= TAIL;
191+ tl[1] *= TAIL;
192+ L[i] = tl[0];
193+ if (R !== L) R[i] = tl[1];
194+ }
195+ }
196+ } else {
197+ const p = this.playhead;
198+ for (let s = 0; s < this.o.stems; s++) {
199+ const q = this.queues[s];
200+ while (q.length && q[0].frame + q[0].L.length <= p) q.shift();
201+ if (p >= this.doneAt[s]) continue;
202+ const out = outputs[this.o.route[s]];
203+ if (!out) continue;
204+ const L = out[0], R = out[1] ?? L;
205+ let i = 0;
206+ for (const c of q) {
207+ if (i >= n) break;
208+ const f = p + i;
209+ if (c.frame + c.L.length <= f) continue;
210+ if (c.frame > f) break; // gap (can't happen: producers send in order)
211+ const off = f - c.frame, len = Math.min(n - i, c.L.length - off);
212+ for (let j = 0; j < len; j++) {
213+ L[i + j] += c.L[off + j];
214+ if (R !== L) R[i + j] += c.R[off + j];
215+ }
216+ i += len;
217+ }
218+ }
219+ // fade in after a pause; remember the last samples in case the next block pauses
220+ for (let o = 0; o < outputs.length; o++) {
221+ const L = outputs[o][0], R = outputs[o][1] ?? L;
222+ if (this.fadeIn < FADE_IN) {
223+ for (let i = 0; i < n; i++) {
224+ const g = Math.min(1, (this.fadeIn + i) / FADE_IN);
225+ L[i] *= g;
226+ if (R !== L) R[i] *= g;
227+ }
228+ }
229+ this.tail[o][0] = L[n - 1];
230+ this.tail[o][1] = R[n - 1];
231+ }
232+ this.fadeIn += n;
233+ this.playhead += n;
234+ }
235+ if (++this.blocks % REPORT_EVERY === 0) {
236+ this.report();
237+ this.clock();
238+ }
239+ return true;
240+ }
241+}
242+
243+registerProcessor("stream-player", StreamPlayer);
src/stream/protocol.tsadded+120−0View file
@@ -0,0 +1,120 @@
1+// The streaming system: messages between the page, the score worker, the synth workers and the
2+// player worklet. Every time here is *piece time* (seconds from the start of the piece), never
3+// AudioContext time: a performance is computed in the background as a function of piece time
4+// alone, and the player maps it onto the audio clock, pausing whenever something isn't ready.
5+//
6+// score worker ──notes──▶ synth workers ──audio──▶ player worklet ──▶ effects ──▶ speakers
7+// │ (or audio itself, e.g. the ensemble) ──────────▲ │ clock (playhead, how far ahead)
8+// └──frames, events──▶ page (draws at the player's playhead) ◀──┘ status
9+
10+import type { Params as SynthParams } from "@modal-synth/engine/params.ts";
11+import type { Params } from "../core/params.ts";
12+
13+/** Every performance renders at this rate on every device (the AudioContext runs at it too). */
14+export const SAMPLE_RATE = 48000;
15+/** Synth rendering is done in blocks of this many frames, from piece frame 0 (deterministic). */
16+export const BLOCK = 128;
17+/** Frames per audio chunk sent to the player. */
18+export const CHUNK = 2048;
19+
20+// ── score worker ──
21+
22+export interface ScoreInit {
23+ type: "init";
24+ comp: string; // composition id
25+ P: Params;
26+ seed: number;
27+ /** piece time playback starts at */
28+ start: number;
29+ /** piece time sound is computed from (start minus a pre-roll, so ringing notes are heard) */
30+ from: number;
31+ /** one port per synth stem, in stem order (null for stems the score renders itself) */
32+ synthPorts: (MessagePort | null)[];
33+ /** the score's own link to the player: clock in, audio chunks (score stems) and the end out */
34+ playerPort: MessagePort;
35+}
36+
37+/** score worker → page */
38+export type ScoreOut =
39+ | { type: "frames"; track: number; stride: number; data: Float64Array } // [t, v…] per row
40+ | { type: "events"; events: VisEvent[] }
41+ | { type: "info"; t: number; info: Record<string, string> }
42+ | { type: "end"; t: number } // the piece ends (everything faded) at piece time t
43+ | { type: "error"; message: string };
44+
45+/** Something to draw at a moment: a crossing, a ring… (fields are up to the piece). */
46+export interface VisEvent {
47+ t: number;
48+ kind: string;
49+ [k: string]: number | string;
50+}
51+
52+// ── synth workers ──
53+
54+export interface SynthInit {
55+ type: "init";
56+ sound: SynthParams;
57+ /** first piece frame to render (block-aligned) */
58+ fromFrame: number;
59+ /** first piece frame to send to the player (earlier frames are rendered silently) */
60+ sendFrame: number;
61+ stem: number;
62+ scorePort: MessagePort;
63+ playerPort: MessagePort;
64+ /** testing: render this many times slower (simulates a slow device; ?slow=N in the page URL) */
65+ slow?: number;
66+}
67+
68+/** score → synth worker: timed instructions, in time order */
69+export type SynthCmd =
70+ | { t: number; type: "noteOn"; note: number; vel: number }
71+ /** `on`: when its note began; skipped if the same pitch was struck again since */
72+ | { t: number; type: "noteOff"; note: number; on?: number }
73+ | { t: number; type: "params"; params: Record<string, number | string | boolean> } // merged over the sound
74+ | { t: number; type: "bend"; value: number }
75+ /** output gain: move toward `value` with time constant `tau`; `normalize` holds the loudness steady */
76+ | { t: number; type: "gain"; value: number; tau: number; normalize?: boolean }
77+ /** the final note: from t, slow the decay so it rings `hold + fade` s, and fade out over the last `fade` s */
78+ | { t: number; type: "hold"; hold: number; fade: number };
79+
80+export type ScoreToSynth =
81+ | { type: "cmds"; cmds: SynthCmd[]; horizon: number } // every command before `horizon` has been sent
82+ | { type: "end"; t: number }; // render up to t, then stop
83+
84+// ── player ──
85+
86+/** producer (synth or score worker) → player */
87+export type ToPlayer =
88+ | { type: "chunk"; stem: number; frame: number; L: Float32Array; R: Float32Array }
89+ | { type: "done"; stem: number; frame: number } // this stem is silent from `frame` on
90+ | { type: "end"; frame: number }; // the piece ends here (from the score)
91+
92+/** player → producers, ~50 times a second */
93+export interface Clock {
94+ type: "clock";
95+ playhead: number; // piece frame
96+ ahead: number; // frames to keep rendered ahead of the playhead
97+}
98+
99+/** player → page */
100+export interface PlayerStatus {
101+ type: "status";
102+ state: "buffering" | "playing" | "ended";
103+ playhead: number; // piece frame
104+ at: number; // AudioContext frame (currentFrame) when the playhead was there
105+ /** 0..1: how full the buffer is toward resuming (while buffering) */
106+ fill: number;
107+ rebuffers: number;
108+ /** seconds rendered ahead of the playhead (the least of all stems) */
109+ ahead: number;
110+}
111+
112+export interface PlayerOptions {
113+ stems: number;
114+ outputs: number;
115+ /** stem → output it plays on */
116+ route: number[];
117+ startFrame: number;
118+ /** the piece's likely end (frame), until the score knows it */
119+ estimatedEnd: number;
120+}
src/stream/score.tsadded+43−0View file
@@ -0,0 +1,43 @@
1+// What a composition's score implements, and the sink it writes to. A score runs in the score
2+// worker: it simulates the piece in piece time and emits everything the performance needs.
3+// It must be deterministic (same params + seed → same output everywhere): use physics/dmath.ts,
4+// never Math.sin/cos/exp/log/pow/hypot or Math.random.
5+
6+import type { Params } from "../core/params.ts";
7+import type { SynthCmd, VisEvent } from "./protocol.ts";
8+
9+/** A note whose release can still be moved (the final-note hold). */
10+export interface NoteRef {
11+ stem: number;
12+ t: number;
13+ off: SynthCmd;
14+}
15+
16+export interface ScoreSink {
17+ /** false while fast-forwarding silently to the start point (then nothing is emitted) */
18+ readonly emitting: boolean;
19+ /** one row of drawing data on a track (rows in time order) */
20+ frame(track: number, t: number, values: ArrayLike<number>): void;
21+ event(e: VisEvent): void;
22+ /** author readouts, as of piece time t */
23+ info(t: number, info: Record<string, string>): void;
24+ /** a note on a synth stem: pitch as MIDI (fractional ok), velocity 0..1, length in s */
25+ note(stem: number, t: number, midi: number, vel: number, dur: number): NoteRef | null;
26+ /** let a note ring: its release moves to the end of the fade (see SynthCmd "hold") */
27+ hold(ref: NoteRef, at: number, hold: number, fade: number): void;
28+ /** any other timed command for a synth stem (drones: gain, params, …) */
29+ cmd(stem: number, c: SynthCmd): void;
30+ /** audio the score renders itself, for a "score" stem: consecutive samples from `from` */
31+ audio(stem: number, L: Float32Array, R: Float32Array): void;
32+ /** the piece ends (everything faded) at piece time t */
33+ end(t: number): void;
34+}
35+
36+export interface PieceScore {
37+ /** simulate up to piece time t, emitting through the sink */
38+ advance(t: number): void;
39+ /** piece time simulated so far */
40+ readonly time: number;
41+}
42+
43+export type ScoreFactory = (P: Params, seed: number, sink: ScoreSink) => PieceScore;
src/stream/scoreWorker.tsadded+180−0View file
@@ -0,0 +1,180 @@
1+// Runs a composition's score in the background. It fast-forwards silently to the start point,
2+// then simulates ahead of the player's playhead (no further than the buffer the player asks for),
3+// sending drawing data to the page, timed commands to the synth workers, and its own audio (if
4+// any) to the player.
5+//
6+// Synth commands are held back LAG seconds of piece time before they're released (with a horizon:
7+// "every command before this time has been sent"), so a score can still lengthen a note it has
8+// already played (the final-note hold) when it finds, a little later, that the piece has ended.
9+
10+import { SCORES } from "../compositions/scores.ts";
11+import { SAMPLE_RATE, type Clock, type ScoreInit, type ScoreOut, type ScoreToSynth, type SynthCmd, type ToPlayer, type VisEvent } from "./protocol.ts";
12+import type { NoteRef, PieceScore, ScoreSink } from "./score.ts";
13+
14+const LAG = 2.5; // s of piece time synth commands are held back
15+const STEP = 0.05; // s of piece time simulated between checks for messages
16+const FLUSH = 0.1; // s of piece time between posts to the page
17+const EXTRA = 0.5; // s simulated beyond what the player needs (covers LAG and the synths' blocks)
18+
19+let score: PieceScore;
20+let init: ScoreInit;
21+let emitting = false;
22+let playhead = 0; // piece frame
23+let ahead = 4 * SAMPLE_RATE;
24+let endT = Infinity;
25+let finished = false;
26+let scheduled = false;
27+
28+// held-back synth commands per stem, and what has been released
29+let pending: SynthCmd[][] = [];
30+let released = -Infinity; // horizon sent so far
31+// drawing data waiting to be posted
32+const tracks = new Map<number, { stride: number; rows: number[] }>();
33+let events: VisEvent[] = [];
34+let lastInfo: { t: number; info: Record<string, string> } | null = null;
35+let lastFlushT = -Infinity;
36+// score-rendered audio, per stem: next frame
37+const audioFrame = new Map<number, number>();
38+
39+const toPage = (m: ScoreOut, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(m, transfer);
40+const toPlayer = (m: ToPlayer, transfer: Transferable[] = []) => init.playerPort.postMessage(m, transfer);
41+
42+const sink: ScoreSink = {
43+ get emitting() {
44+ return emitting;
45+ },
46+ frame(track, t, values) {
47+ if (!emitting) return;
48+ let tr = tracks.get(track);
49+ if (!tr) tracks.set(track, (tr = { stride: values.length + 1, rows: [] }));
50+ tr.rows.push(t);
51+ for (let i = 0; i < values.length; i++) tr.rows.push(values[i]);
52+ },
53+ event(e) {
54+ if (emitting) events.push(e);
55+ },
56+ info(t, info) {
57+ if (emitting) lastInfo = { t, info };
58+ },
59+ note(stem, t, midi, vel, dur) {
60+ if (!emitting || !pending[stem] || vel <= 0) return null;
61+ const on: SynthCmd = { t, type: "noteOn", note: midi, vel: Math.max(0.01, Math.min(1, vel)) };
62+ const off: SynthCmd = { t: t + dur, type: "noteOff", note: midi, on: t };
63+ pending[stem].push(on, off);
64+ return { stem, t, off };
65+ },
66+ hold(ref: NoteRef, at, hold, fade) {
67+ if (!emitting || !pending[ref.stem]) return;
68+ const from = Math.max(at, released);
69+ const end = from + hold + fade;
70+ // the note's release, if not yet sent, moves to the end of the fade
71+ if (pending[ref.stem].includes(ref.off) && ref.off.t < end) ref.off.t = end;
72+ pending[ref.stem].push({ t: from, type: "hold", hold, fade });
73+ },
74+ cmd(stem, c) {
75+ if (emitting && pending[stem]) pending[stem].push(c);
76+ },
77+ audio(stem, L, R) {
78+ if (!emitting) return;
79+ const frame = audioFrame.get(stem) ?? Math.round(init.from * SAMPLE_RATE);
80+ audioFrame.set(stem, frame + L.length);
81+ const send = Math.round(init.start * SAMPLE_RATE);
82+ if (frame + L.length <= send) return;
83+ const off = Math.max(0, send - frame);
84+ const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R;
85+ toPlayer({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]);
86+ },
87+ end(t) {
88+ if (endT !== Infinity) return;
89+ endT = t;
90+ toPage({ type: "end", t });
91+ toPlayer({ type: "end", frame: Math.round(t * SAMPLE_RATE) });
92+ },
93+};
94+
95+/** Release synth commands before `horizon` (in time order) and post drawing data. */
96+function flush(horizon: number, force = false) {
97+ if (horizon > released) {
98+ init.synthPorts.forEach((port, s) => {
99+ if (!port) return;
100+ const q = pending[s];
101+ q.sort((a, b) => a.t - b.t);
102+ let n = 0;
103+ while (n < q.length && q[n].t < horizon) n++;
104+ const m: ScoreToSynth = { type: "cmds", cmds: q.splice(0, n), horizon };
105+ port.postMessage(m);
106+ });
107+ released = horizon;
108+ }
109+ if (!force && score.time - lastFlushT < FLUSH) return;
110+ lastFlushT = score.time;
111+ for (const [track, tr] of tracks) {
112+ if (!tr.rows.length) continue;
113+ const data = Float64Array.from(tr.rows);
114+ tr.rows = [];
115+ toPage({ type: "frames", track, stride: tr.stride, data }, [data.buffer]);
116+ }
117+ if (events.length) {
118+ toPage({ type: "events", events });
119+ events = [];
120+ }
121+ if (lastInfo) {
122+ toPage({ type: "info", t: lastInfo.t, info: lastInfo.info });
123+ lastInfo = null;
124+ }
125+}
126+
127+function pump() {
128+ if (scheduled || finished) return;
129+ scheduled = true;
130+ setTimeout(loop, 0);
131+}
132+
133+function loop() {
134+ scheduled = false;
135+ try {
136+ if (score.time >= endT) {
137+ // everything is known: release the rest and tell the synths where to stop
138+ flush(endT + 1, true);
139+ init.synthPorts.forEach((port) => port?.postMessage({ type: "end", t: endT } satisfies ScoreToSynth));
140+ finished = true;
141+ return;
142+ }
143+ const need = Math.min(endT, (playhead + ahead) / SAMPLE_RATE + LAG + EXTRA);
144+ if (score.time >= need) return; // far enough ahead: wait for the clock
145+ score.advance(Math.min(score.time + STEP, need, endT));
146+ flush(score.time - LAG);
147+ } catch (err) {
148+ finished = true;
149+ toPage({ type: "error", message: String((err as Error)?.stack ?? err) });
150+ return;
151+ }
152+ pump();
153+}
154+
155+self.onmessage = (e: MessageEvent<ScoreInit>) => {
156+ const m = e.data;
157+ if (m.type !== "init") return;
158+ init = m;
159+ pending = m.synthPorts.map(() => []);
160+ playhead = Math.round(m.start * SAMPLE_RATE);
161+ m.playerPort.onmessage = (ev: MessageEvent<Clock>) => {
162+ playhead = ev.data.playhead;
163+ ahead = ev.data.ahead;
164+ pump();
165+ };
166+ try {
167+ const make = SCORES[m.comp];
168+ if (!make) throw new Error(`no score for ${m.comp}`);
169+ score = make(m.P, m.seed, sink);
170+ // silently up to where sound starts (start minus a pre-roll), then for real
171+ if (m.from > 0) score.advance(m.from);
172+ emitting = true;
173+ released = m.from;
174+ } catch (err) {
175+ finished = true;
176+ toPage({ type: "error", message: String((err as Error)?.stack ?? err) });
177+ return;
178+ }
179+ pump();
180+};
src/stream/synthWorker.tsadded+182−0View file
@@ -0,0 +1,182 @@
1+// One instrument ("stem") of a performance, rendered in its own worker: the modal-synth engine,
2+// driven by timed commands from the score, in 128-frame blocks from a fixed piece frame, so the
3+// result depends only on the commands (the same on every device). It renders as fast as it can,
4+// up to whichever comes first: what the score has sent (its horizon), or the player's playhead
5+// plus the buffer it asks for. Audio goes straight to the player.
6+
7+import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
8+import { Synth } from "@modal-synth/engine/synth.ts";
9+import { BLOCK, CHUNK, SAMPLE_RATE, type Clock, type ScoreToSynth, type SynthCmd, type SynthInit, type ToPlayer } from "./protocol.ts";
10+
11+const NORM_REF = 0.3; // normalized loudness: level 1 ≈ this RMS
12+const NORM_TAU = 1.5; // s
13+const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
14+
15+let synth: Synth;
16+let sound: Params;
17+let cur: Params; // sound with the latest timed changes
18+let stem = 0;
19+let player: MessagePort;
20+let rendered = 0; // next piece frame to render
21+let sendFrame = 0;
22+let horizon = 0; // frame: every command before it has arrived
23+let endFrame = Infinity;
24+let playhead = 0;
25+let ahead = 4 * SAMPLE_RATE;
26+let doneSent = false;
27+const cmds: SynthCmd[] = [];
28+const lastOn = new Map<number, number>(); // pitch → when it was last struck
29+let scheduled = false;
30+let slow = 1;
31+
32+// output gain (hum levels), loudness normalization, and the final-note fade
33+let gain = 1, gainTarget = 1, gainTau = 0, normalize = false;
34+let msq = NORM_REF * NORM_REF;
35+let holding = false;
36+let fadeFrom = Infinity, fadeLen = 1; // s
37+
38+self.onmessage = (e: MessageEvent<SynthInit>) => {
39+ const m = e.data;
40+ if (m.type !== "init") return;
41+ sound = { ...DEFAULTS, ...m.sound };
42+ cur = sound;
43+ synth = new Synth(SAMPLE_RATE);
44+ synth.message({ type: "params", params: sound });
45+ stem = m.stem;
46+ slow = Math.max(1, m.slow ?? 1);
47+ rendered = m.fromFrame;
48+ horizon = m.fromFrame;
49+ sendFrame = m.sendFrame;
50+ playhead = m.sendFrame;
51+ player = m.playerPort;
52+ player.onmessage = (ev: MessageEvent<Clock>) => {
53+ playhead = ev.data.playhead;
54+ ahead = ev.data.ahead;
55+ pump();
56+ };
57+ m.scorePort.onmessage = (ev: MessageEvent<ScoreToSynth>) => {
58+ const d = ev.data;
59+ if (d.type === "cmds") {
60+ for (const c of d.cmds) cmds.push(c);
61+ horizon = Math.max(horizon, Math.floor(d.horizon * SAMPLE_RATE));
62+ } else if (d.type === "end") {
63+ endFrame = Math.round(d.t * SAMPLE_RATE);
64+ horizon = Math.max(horizon, endFrame);
65+ }
66+ pump();
67+ };
68+};
69+
70+function pump() {
71+ if (scheduled) return;
72+ scheduled = true;
73+ setTimeout(loop, 0);
74+}
75+
76+function apply(c: SynthCmd) {
77+ switch (c.type) {
78+ case "noteOn":
79+ synth.message({ type: "noteOn", note: c.note, vel: c.vel });
80+ lastOn.set(c.note, c.t);
81+ break;
82+ case "noteOff":
83+ // notes are identified by pitch: a release from before a re-strike would cut the new note
84+ if (c.on !== undefined && (lastOn.get(c.note) ?? -Infinity) > c.on) break;
85+ synth.message({ type: "noteOff", note: c.note });
86+ break;
87+ case "params":
88+ cur = { ...cur, ...c.params };
89+ synth.message({ type: "params", params: cur });
90+ break;
91+ case "bend":
92+ synth.message({ type: "bend", value: c.value });
93+ break;
94+ case "gain":
95+ gainTarget = c.value;
96+ gainTau = c.tau;
97+ normalize = !!c.normalize;
98+ break;
99+ case "hold": {
100+ if (holding) break; // instrument-wide: the first hold sets it up
101+ holding = true;
102+ // a struck body decays by itself: slow its decay (base and high-frequency loss alike, so the
103+ // tone color stays) so it rings through the hold and fade
104+ const ring = c.hold + c.fade;
105+ const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
106+ const slow = t60 / (sound.t60 as number);
107+ cur = { ...cur, t60, hfDamp: (sound.hfDamp as number) / slow };
108+ synth.message({ type: "params", params: cur });
109+ fadeFrom = c.t + Math.max(c.hold, 0.005);
110+ fadeLen = Math.max(0.01, c.fade);
111+ break;
112+ }
113+ }
114+}
115+
116+const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
117+
118+function renderBlock(L: Float32Array, R: Float32Array, at: number) {
119+ const now = rendered / SAMPLE_RATE;
120+ const blockEnd = (rendered + BLOCK) / SAMPLE_RATE;
121+ // commands due in this block apply at its start (block-accurate, like the synth's own timing)
122+ while (cmds.length && cmds[0].t < blockEnd) apply(cmds.shift()!);
123+ bl.fill(0);
124+ br.fill(0);
125+ synth.process(bl, br, BLOCK, now);
126+ if (normalize) {
127+ let s = 0;
128+ for (let i = 0; i < BLOCK; i++) s += bl[i] * bl[i] + br[i] * br[i];
129+ s /= 2 * BLOCK;
130+ if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / NORM_TAU));
131+ }
132+ const comp = normalize ? Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq))) : 1;
133+ const target = gainTarget * comp;
134+ const g0 = gain;
135+ gain = gainTau > 0 ? gain + (target - gain) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / gainTau)) : target;
136+ for (let i = 0; i < BLOCK; i++) {
137+ let g = g0 + ((gain - g0) * (i + 1)) / BLOCK;
138+ const t = (rendered + i) / SAMPLE_RATE;
139+ if (t >= fadeFrom) {
140+ const u = Math.min(1, (t - fadeFrom) / fadeLen);
141+ const c = Math.cos((Math.PI / 2) * u);
142+ g *= c * c;
143+ }
144+ L[at + i] = bl[i] * g;
145+ R[at + i] = br[i] * g;
146+ }
147+ rendered += BLOCK;
148+}
149+
150+function loop() {
151+ scheduled = false;
152+ if (!synth) return;
153+ if (rendered >= endFrame) {
154+ if (!doneSent) {
155+ doneSent = true;
156+ post({ type: "done", stem, frame: endFrame });
157+ }
158+ return;
159+ }
160+ // render whole blocks, up to what the score has sent, the buffer the player wants, and the end
161+ const cap = Math.min(horizon, playhead + ahead, endFrame + BLOCK - 1);
162+ const n = Math.min(CHUNK, Math.floor((cap - rendered) / BLOCK) * BLOCK);
163+ if (n <= 0) return;
164+ const frame = rendered;
165+ const L = new Float32Array(n), R = new Float32Array(n);
166+ const t0 = performance.now();
167+ for (let i = 0; i < n; i += BLOCK) renderBlock(L, R, i);
168+ if (slow > 1) {
169+ const until = performance.now() + (slow - 1) * (performance.now() - t0);
170+ while (performance.now() < until); // testing only: pretend to be a slower device
171+ }
172+ if (frame + n > sendFrame) {
173+ const off = Math.max(0, sendFrame - frame);
174+ const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R;
175+ post({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]);
176+ }
177+ pump(); // yield between chunks so new commands and the clock get through
178+}
179+
180+function post(m: ToPlayer, transfer: Transferable[] = []) {
181+ player.postMessage(m, transfer);
182+}
src/style.cssmodified+7−0View file
@@ -77,3 +77,10 @@ header a { color: var(--muted); }
7777 .readouts dd { color: var(--fg); }
7878 .author .row.text { grid-template-columns: 110px 1fr; align-items: start; }
7979 .author textarea { font: inherit; font-size: 11px; color: var(--fg); background: var(--bg); border: 1px solid var(--dim); width: 100%; resize: vertical; }
80+
81+/* buffering: a quiet spinner over the picture while the performance computes ahead */
82+.buffering { position: absolute; inset: 0; margin: auto; width: 88px; height: 88px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; pointer-events: none; }
83+.buffering[hidden] { display: none; }
84+.buffering .spinner { width: 28px; height: 28px; border-radius: 50%; border: 1px solid var(--dim); border-top-color: var(--fg); animation: spin 1s linear infinite; }
85+.buffering .fill { color: var(--muted); font-size: 11px; }
86+@keyframes spin { to { transform: rotate(360deg); } }
↑↓ move↵openescclose