faustwave 0.93.1 → 0.94.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -44
- package/dist/npm/faustwave.mjs +73 -18
- package/dist/npm/pagekit/pagekit.js +2347 -0
- package/dist/npm/pagekit/parts/device-button.glb +0 -0
- package/dist/npm/pagekit/parts/device-fader.glb +0 -0
- package/dist/npm/pagekit/parts/device-knob.glb +0 -0
- package/dist/npm/pagekit/parts/device-meter.glb +0 -0
- package/dist/npm/pagekit/parts/device-panel.glb +0 -0
- package/dist/npm/pagekit/parts/models-provenance.json +46 -0
- package/dist/npm/pagekit/player/THIRD-PARTY-NOTICES.md +12358 -0
- package/dist/npm/pagekit/player/assets/AppView-BV9Obknn.js +1 -0
- package/dist/npm/pagekit/player/assets/AppView-CdET0bgZ.css +1 -0
- package/dist/npm/pagekit/player/assets/FontLoader-C8xh6Irz.js +64 -0
- package/dist/npm/pagekit/player/assets/StageView-CSu--ASd.css +1 -0
- package/dist/npm/pagekit/player/assets/StageView-_SwGWnwx.js +1 -0
- package/dist/npm/pagekit/player/assets/actionRegistry-DrQhww6a.js +1 -0
- package/dist/npm/pagekit/player/assets/actionRegistry-hOkUYNvI.js +1 -0
- package/dist/npm/pagekit/player/assets/ahead-BNQHG1e8.js +1 -0
- package/dist/npm/pagekit/player/assets/api-BrGhAVvb.js +1 -0
- package/dist/npm/pagekit/player/assets/autoLayout-C5ue2K3x.js +1 -0
- package/dist/npm/pagekit/player/assets/bundledSources-2GoXdU5z.js +1 -0
- package/dist/npm/pagekit/player/assets/clapModule-CB6_36hc.js +1 -0
- package/dist/npm/pagekit/player/assets/client-DksDHYQL.js +1 -0
- package/dist/npm/pagekit/player/assets/codeEditorBridge-Bl202hrO.js +1 -0
- package/dist/npm/pagekit/player/assets/disclose-version-BvIhFN19.js +1 -0
- package/dist/npm/pagekit/player/assets/dist-BvRk9kiK.js +0 -0
- package/dist/npm/pagekit/player/assets/dist-DfaMbR-1.js +1 -0
- package/dist/npm/pagekit/player/assets/engine.worklet-BTB8yjdk.js +1865 -0
- package/dist/npm/pagekit/player/assets/engineCost.worker-Cv0PY3S-.js +2167 -0
- package/dist/npm/pagekit/player/assets/errors-BdUU2zPt.js +1 -0
- package/dist/npm/pagekit/player/assets/faust-analysis.nodepack-Bg1ixSAB.js +1 -0
- package/dist/npm/pagekit/player/assets/faust-physical-models.nodepack-DxbqTZII.js +1 -0
- package/dist/npm/pagekit/player/assets/faust-reverbs.nodepack-c-ZIKLrJ.js +1 -0
- package/dist/npm/pagekit/player/assets/faust-spatial.nodepack-C6GwVzOM.js +1 -0
- package/dist/npm/pagekit/player/assets/faust-vintage.nodepack-D8g5LX-U.js +1 -0
- package/dist/npm/pagekit/player/assets/faust.nodepack-Do7P1z0H.js +1 -0
- package/dist/npm/pagekit/player/assets/faustSource-Blr9zzKL.js +1 -0
- package/dist/npm/pagekit/player/assets/faustwasm-webclap-double-BX3OrOpF.js +1 -0
- package/dist/npm/pagekit/player/assets/faustwasm-webclap-double-Drn3DiHA.wasm +0 -0
- package/dist/npm/pagekit/player/assets/faustwasm.js +1 -0
- package/dist/npm/pagekit/player/assets/faustwave-conventions.nodepack-D2jA38Q6.js +1 -0
- package/dist/npm/pagekit/player/assets/fileMirror-CkgB9zNS.js +1 -0
- package/dist/npm/pagekit/player/assets/fileRef-BmnWhXuY.js +1 -0
- package/dist/npm/pagekit/player/assets/host-DPIuYxlL.js +1 -0
- package/dist/npm/pagekit/player/assets/instantiate-Dh0T46aH.js +1 -0
- package/dist/npm/pagekit/player/assets/inter-500.typeface-B6jxeZL_.js +21 -0
- package/dist/npm/pagekit/player/assets/inter-700.typeface-COCE0d_R.js +21 -0
- package/dist/npm/pagekit/player/assets/kernel-BErAMnKr.js +1 -0
- package/dist/npm/pagekit/player/assets/kernel-D6spGIFh.js +1 -0
- package/dist/npm/pagekit/player/assets/kernel-DKiI3Wqx.js +2 -0
- package/dist/npm/pagekit/player/assets/kit--nsV_OZy.js +1 -0
- package/dist/npm/pagekit/player/assets/kit-vVQ5cDnW.css +1 -0
- package/dist/npm/pagekit/player/assets/lazy-BkjipY-3.css +1 -0
- package/dist/npm/pagekit/player/assets/lazy-ClEpU-Ev.js +1 -0
- package/dist/npm/pagekit/player/assets/libraryFacts-B_z-Kv6i.js +1 -0
- package/dist/npm/pagekit/player/assets/mono-500.typeface-CuX9Pbhu.js +21 -0
- package/dist/npm/pagekit/player/assets/mono-700.typeface-BpIQdJao.js +21 -0
- package/dist/npm/pagekit/player/assets/newId-DuoSrkVn.js +1 -0
- package/dist/npm/pagekit/player/assets/notes-D-zF5qJ1.js +1 -0
- package/dist/npm/pagekit/player/assets/opfsStore-CXd1Yz_2.js +1 -0
- package/dist/npm/pagekit/player/assets/panic-ckha9YOX.js +1 -0
- package/dist/npm/pagekit/player/assets/patchSnippets-Dsccmpj6.js +1 -0
- package/dist/npm/pagekit/player/assets/paths-DFjX1bFA.js +1 -0
- package/dist/npm/pagekit/player/assets/player-CgcvekqS.js +2 -0
- package/dist/npm/pagekit/player/assets/playerApp-BmyTSXxw.js +2 -0
- package/dist/npm/pagekit/player/assets/playerApp-DO80EIpx.css +1 -0
- package/dist/npm/pagekit/player/assets/preArm-ifXM2Buj.js +1 -0
- package/dist/npm/pagekit/player/assets/preload-helper-9MKZsTCd.js +1 -0
- package/dist/npm/pagekit/player/assets/projectFiles-BEdLy3nE.js +1 -0
- package/dist/npm/pagekit/player/assets/projectPicker-mteZ2tiI.js +1 -0
- package/dist/npm/pagekit/player/assets/rocket-CgRnlVoE.js +1 -0
- package/dist/npm/pagekit/player/assets/runtime-36oA_YiG.js +1 -0
- package/dist/npm/pagekit/player/assets/runtime-7lvdeERt.js +1 -0
- package/dist/npm/pagekit/player/assets/runtime-BNLxaYPi.js +2 -0
- package/dist/npm/pagekit/player/assets/runtime-CL1M0Epi.js +1 -0
- package/dist/npm/pagekit/player/assets/runtime-bQsuRbRM.js +2 -0
- package/dist/npm/pagekit/player/assets/runtime-vj8wKnnG.js +1 -0
- package/dist/npm/pagekit/player/assets/runtime-wuc1seO8.js +1 -0
- package/dist/npm/pagekit/player/assets/scale-D2nqiPek.js +1 -0
- package/dist/npm/pagekit/player/assets/sha256-B9lHpAF4.js +1 -0
- package/dist/npm/pagekit/player/assets/soundfiles-DMZ8HKDZ.js +1 -0
- package/dist/npm/pagekit/player/assets/src-BvHr5YSH.js +2 -0
- package/dist/npm/pagekit/player/assets/src-Co7ihhBK.js +1 -0
- package/dist/npm/pagekit/player/assets/src-DyDfRe65.js +1 -0
- package/dist/npm/pagekit/player/assets/src-LMfGAjlj.js +1 -0
- package/dist/npm/pagekit/player/assets/stageWorker-ggqqFf5m.js +20869 -0
- package/dist/npm/pagekit/player/assets/store-CJdayqZa.js +1 -0
- package/dist/npm/pagekit/player/assets/sun-Bi-OgPry.js +1 -0
- package/dist/npm/pagekit/player/assets/time-aboh42pX.js +1 -0
- package/dist/npm/pagekit/player/assets/toasts-BCcM1yGS.js +1 -0
- package/dist/npm/pagekit/player/assets/toasts-ChPacqdd.js +1 -0
- package/dist/npm/pagekit/player/assets/transportFollow-Ox91SKLF.js +1 -0
- package/dist/npm/pagekit/player/favicon.svg +77 -0
- package/dist/npm/pagekit/player/files.json +1 -0
- package/dist/npm/pagekit/player/player.html +35 -0
- package/package.json +58 -43
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./errors-BdUU2zPt.js";import{s as t}from"./paths-DFjX1bFA.js";import{a as s,s as n}from"./src-DyDfRe65.js";import{f as i,h as a,m as o,p as r}from"./dist-DfaMbR-1.js";function p(e){if("boolean"==typeof e)return e;if("string"==typeof e){const t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}if("number"==typeof e){if(1===e)return!0;if(0===e)return!1}return null}var d={type:"string",description:"The document to act on — a Builder or a Faust DSP. Discover ids via documents.list; both kinds answer to this family."};function l(e){if(!e||"object"!=typeof e)return null;const t=e;return"function"==typeof t.compile&&"function"==typeof t.run&&"function"==typeof t.stop&&"function"==typeof t.setMidiChannel&&"function"==typeof t.setFollowTransport?e:null}function c(e,t){if("string"!=typeof t||0===t.length)return{ok:!1,error:`module_id is required. ${u(e)}`};const s=e.documents.get(t),n=l(s);if(!n){const n=e.documents.listModules().find(e=>e.id===t);return n?null==s?{ok:!1,error:`"${n.title||t}" (${n.type}) has no runtime registered yet — a document registers one when it MOUNTS. If it is a Builder or a .dsp, bring it on screen first (documents.active.set / documents.reveal) and call again. ${u(e)}`}:{ok:!1,error:`"${n.title||t}" is a ${n.type} document — it does not produce DSP, so it has no run / compile / stop. ${u(e)}`}:{ok:!1,error:`No document with id "${t}". ${u(e)}`}}return{ok:!0,dsp:n}}function u(e){const t=e.documents.listModules().filter(t=>l(e.documents.get(t.id))).map(e=>`${e.id} ("${e.title||"Untitled"}")`);return t.length?`Documents that can make sound: ${t.join(", ")}.`:"No open document can make sound right now — open a Builder or a .dsp first."}var m={type:"string",description:"The running instance whose param this is — a document id (Builder or Faust DSP) or an FX-slot id. Discover document ids via documents.list, slot ids via master.fx.slots.list or mixer.tracks.*."};function h(t){return[{id:"dsp.state",title:"DSP: Get State",category:"DSP",description:"What the engine is doing: running, compiled, status, the compile error if any, the param paths it exposes, and — where the kind knows them — whether it is polyphonic, which MIDI channel it listens on, and whether it follows the transport. Read this before dsp.run to see whether a document is already going, and after a failed compile to see WHY. A Builder reports no param paths: its params live on nodes, so read them via builder.graph.node.param.get. For live param VALUES rather than paths, use dsp.params.list.",input_schema:{type:"object",properties:{module_id:d},required:["module_id"],additionalProperties:!1},mcpRun:({module_id:s})=>{const n=c(t,s);return n.ok||e(n.error),{module_id:s,...n.dsp.getEngineState()}}},{id:"dsp.compile",slow:!0,title:"DSP: Compile",category:"DSP",description:"Compile a document to Faust WASM without starting audio — a Builder compiles its graph, a Faust DSP its source. Returns success or the libfaust diagnostic. Distinct from dsp.run: nothing starts.",input_schema:{type:"object",properties:{module_id:d},required:["module_id"],additionalProperties:!1},mcpRun:async({module_id:s})=>{const n=c(t,s);n.ok||e(n.error);const i=await n.dsp.compile();return i.ok||e(`Compile failed: ${i.error}`),`Compiled successfully.${i.note??""}`}},{id:"dsp.run",plays:!0,slow:!0,title:"DSP: Run",category:"DSP",description:"Start audio for a document. Auto-compiles if needed. NOTE: running is NOT the same as audible — the result reports whether the document is routed anywhere, because an unrouted one plays into silence (attach via mixer.tracks.input.set).",input_schema:{type:"object",properties:{module_id:d},required:["module_id"],additionalProperties:!1},mcpRun:async({module_id:s})=>{const n=c(t,s);n.ok||e(n.error);const i=await n.dsp.run();i.ok||e(`Run failed: ${i.error}`);const{message:a}=function(e,t){const s=e.routing.getTable(),n=s.connections.filter(e=>"audio"===e.kind&&e.from.sourceId===t&&!1!==e.enabled),i=`${t}:midi-in`,a=s.sinks.some(e=>e.id===i&&!0===e.isAudible),o=s.connections.some(e=>"midi"===e.kind&&e.to.sinkId===i&&!1!==e.enabled),r=a&&!o?` NOTE: this document listens for MIDI but has no ENABLED incoming MIDI edge — notes cannot reach it until one exists (non-MIDI sources may still sound). Connect e.g. routing.connect { kind: "midi", from_source: "keyboard-default", from_port: "out", to_sink: "${i}", to_port: "in" } (and/or sequencer-default).`:"",p=e.routing.wiringFailures(),d=n.filter(e=>p[e.id]),l=n.filter(e=>!p[e.id]),c=d.length>0?` WARNING: ${d.length} of this document's ${n.length} audio edge(s) are in the routing table but the audio graph REFUSED them, so no signal flows through them: ${d.map(e=>`${e.to.sinkId}:${e.to.portId} (${p[e.id]})`).join("; ")}.`:"";return 0===l.length&&d.length>0?{message:"Audio is running, but this document is INAUDIBLE — every audio edge it has was refused by the audio graph."+c+r}:0===n.length?{message:'Audio is running — but this document is NOT routed anywhere, so it is INAUDIBLE. Attach it to a MixerTrack via mixer.tracks.input.set (preferred — gives the user a fader strip) or connect an edge yourself. Verify audibility via system.state { sections: ["master"] } — peak/hold > 0 means signal reaches the output.'+r}:{message:`Audio is running (routed to ${l.map(e=>`${e.to.sinkId}:${e.to.portId}`).join(", ")}).${c}${r}`}}(t,s);return{ok:!0,message:a+(i.note??""),...i.params?{params:i.params}:{}}}},{id:"dsp.stop",title:"DSP: Stop",category:"DSP",description:"Stop audio for a document. Idempotent — stopping a stopped document is not an error. The document keeps its place in the mixer, so a later run picks up the same fader.",input_schema:{type:"object",properties:{module_id:d},required:["module_id"],additionalProperties:!1},mcpRun:async({module_id:s})=>{const n=c(t,s);return n.ok||e(n.error),await n.dsp.stop(),"Audio stopped."}},{id:"dsp.midi.channel.set",title:"DSP: Set MIDI Channel",category:"DSP",description:"Which MIDI channel this document listens on. 0 = Omni (accept any), 1-16 = accept only that channel; system messages always pass. Lets one multi-track sequencer drive several instruments, each on its own channel. The mechanism differs by kind and the reply says what it did: a Builder writes the channel onto its midi_note nodes, a Faust DSP writes a `[midichannel:N]` token into its source — the latter marks the buffer dirty, so it needs saving to persist.",input_schema:{type:"object",properties:{module_id:d,channel:{type:"integer",minimum:0,maximum:16,description:"0 = Omni (no filter), 1-16 = accept only this channel."}},required:["module_id","channel"],additionalProperties:!1},mcpRun:({module_id:s,channel:n})=>{const i=c(t,s);i.ok||e(i.error);const a=i.dsp.setMidiChannel(n);return a.ok||e(a.error),a.message}},{id:"dsp.transport.follow.set",title:"DSP: Follow Global Transport",category:"DSP",description:"Whether this document starts and stops with the global transport, or stays independent and is driven by dsp.run / dsp.stop. Default is follower. A document that takes audio input (`process(l, r) = …`) starts on Play only when an audio cable leaves it (its sound goes somewhere), whatever this flag says. The flag of a document is kept by the project (its source stays untouched), a Faust DSP and a Builder alike.",input_schema:{type:"object",properties:{module_id:d,enabled:{type:"boolean",description:"true = follows the global transport. false = independent; drive via dsp.run."}},required:["module_id","enabled"],additionalProperties:!1},mcpRun:({module_id:s,enabled:n})=>{const i=c(t,s);i.ok||e(i.error);const a=p(n);null===a&&e(`dsp.transport.follow.set needs a boolean enabled, got ${typeof n}: ${String(n)}.`);const o=i.dsp.setFollowTransport(a);return o.ok||e(o.error),o.message}},{id:"dsp.params.list",title:"DSP: List Params",category:"DSP",description:"Every parameter on a running instance — full Faust path, min/max/init range, and the current live value. Call this before dsp.param.set to discover paths and ranges; dsp.param.set refuses an unknown path, naming the known ones. `voice_controlled: true` marks a param the poly voice allocator writes on every note (a patch's freq / gate / gain / key): setting it works for an instant and the next note-on overwrites it, so it is NOT a usable target for controller.bind.add, a modulation edge or a sequencer value track. Such a param also reads back as 0 on a poly patch — that is the engine, not a stale value. While it plays, each row also carries what the plugin says of it (clap.params): its CLAP id, name, hidden and group; a control with no id is one the voices play.",input_schema:{type:"object",properties:{instance_id:m},required:["instance_id"],additionalProperties:!1},mcpRun:({instance_id:e})=>({params:t.params.list(e).map(e=>({path:e.path,value:e.value,min:e.min,max:e.max,init:e.init,voice_controlled:e.voiceControlled,...e.transportFed?{transport_fed:!0}:{},...e.options?{options:e.options}:{},...void 0!==e.cc?{cc:e.cc}:{},...e.scale?{scale:e.scale}:{},...void 0!==e.id?{id:e.id,name:e.name,...e.hidden?{hidden:!0}:{},...e.group?{group:e.group}:{}}:{}}))})},{id:"dsp.param.set",title:"DSP: Set Param",category:"DSP",description:"Write a parameter of an instance — running or silent: its knobs exist from its compile on (a document is compiled when opened), and a value set while it is silent is kept and heard when it plays. A poly runtime broadcasts across all voices, so one call updates the whole instrument. This is the LIVE value — for the base a modulator swings around, use modulation.base.set; for a persisted FX-slot param, master.fx.slot.param.set.",input_schema:{type:"object",properties:{instance_id:m,path:{type:"string",description:"The param's path from dsp.params.list: its Faust address, or the CLAP id of a plugin of another toolchain's."},value:{type:"number",description:"Value to write. Out-of-range is accepted by the runtime but clamped by the Faust slider's own min/max — read the range from dsp.params.list."}},required:["instance_id","path","value"],additionalProperties:!1},mcpRun:({instance_id:s,path:n,value:i})=>(t.params.list(s).some(e=>e.path===n)||e(`"${n}" is not one of the params of "${s}" (or it is not compiled yet). Run dsp.params.list to see what it has.`),t.params.set(s,n,i),`Set ${n} = ${i} on ${s}.${null===t.params.get(s,n)?" It is silent now — kept, heard when it plays.":""}`)},{id:"dsp.param.get",title:"DSP: Get Param",category:"DSP",description:"Read a parameter's live value — the post-modulation number the knob currently shows, not the user's base. Companion to dsp.param.set: it lets a client confirm that modulation or automation actually moved a param, without eyes on the UI. On a silent instance (compiled, not playing) it answers the value the param is set to, with running: false.",input_schema:{type:"object",properties:{instance_id:m,path:{type:"string",description:"The param's path from dsp.params.list: its Faust address, or the CLAP id of a plugin of another toolchain's."}},required:["instance_id","path"],additionalProperties:!1},mcpRun:({instance_id:s,path:n})=>{const i=t.params.get(s,n);return null!==i?{instance_id:s,path:n,value:i}:t.params.list(s).some(e=>e.path===n)?{instance_id:s,path:n,value:t.params.getBase(s,n),running:!1,note:"not playing yet — the value it is set to, heard when it plays"}:void e(`"${n}" is unknown on "${s}" — dsp.params.list says what it has.`)}}]}var g=n({}),y={key:"presets",save:()=>({standing:{...s(g)}}),restore:e=>{const t=e?.standing;g.set(Object.fromEntries(Object.entries(t&&"object"==typeof t?t:{}).filter(([e,t])=>"string"==typeof e&&"string"==typeof t&&""!==t.trim())))},subscribe:e=>g.subscribe(()=>e())},f={type:"string",description:"The patch — a document id (documents.list): a .dsp or a Builder graph of the project."};function v(n){const p=t=>{const s=n.documents.listModules().find(e=>e.id===t);return s||e(`"${t}" is not open — documents.list names the open documents.`),s.filePath||e(`"${t}" is no file of the project — its presets lie beside its file.`),{patch:s.filePath,file:o(s.filePath)}},d=async s=>{if(!(await n.project.listAssets("json")).some(e=>t(e.ref,s)))return[];try{return i(await n.files.readText(s))}catch(a){return e(`${s}: ${a instanceof Error?a.message:String(a)}`)}},l=t=>{const s=n.params.list(t).filter(e=>!e.voiceControlled&&!e.transportFed);return s.length||e(`"${t}" has no knobs (or it is not compiled yet) — dsp.params.list says what it has.`),s},c=(e,t)=>{const{patch:s}=p(e);g.update(e=>{const{[s]:n,...i}=e;return null===t?i:{...i,[s]:t}}),n.events.emit("dsp.preset",{instance_id:e,name:t})},u=e=>s(g)[p(e).patch]??null,m=async(e,t,s)=>{await n.files.writeText(t,a(s)),n.events.emit("dsp.presets",{instance_id:e})},h=(t,s)=>{const n=t.findIndex(e=>e.name===s.trim());return n<0&&e(t.length?`No preset "${s}" — it has ${t.map(e=>`"${e.name}"`).join(", ")}.`:"It has no presets yet — dsp.preset.save makes one."),n},y=t=>{const s=t.trim();return s||e("A preset needs a name."),(new TextEncoder).encode(s).length>31&&e(`"${s}" is longer than 31 bytes — a plugin keeps a preset's name in 31; choose a shorter one.`),s};return[{id:"dsp.preset.list",title:"DSP: List Presets",category:"DSP",description:"A patch's presets: their names in order, from <patch>.presets.json beside it (a built plugin carries them — any CLAP host loads them), and the one that stands (last loaded or saved; null: none since it was opened).",input_schema:{type:"object",properties:{instance_id:f},required:["instance_id"],additionalProperties:!1},mcpRun:async({instance_id:e})=>{const{file:t}=p(e),s=await d(t),n=u(e);return{file:t,presets:s.map(e=>e.name),standing:null!==n&&s.some(e=>e.name===n)?n:null}}},{id:"dsp.preset.load",title:"DSP: Load Preset",category:"DSP",description:"Load a preset of a patch (dsp.preset.list): its knobs set as a hand sets them — each the preset's value, kept in its range; one it does not name to its start (what a built plugin sets loading it through CLAP). By name, or step: 1 the next, -1 the one before (round). The voices' and the transport's params are left.",input_schema:{type:"object",properties:{instance_id:f,name:{type:"string",description:"The preset's name."},step:{type:"integer",enum:[1,-1],description:"Instead of a name: 1 the next preset after the one that stands, -1 the one before."}},required:["instance_id"],additionalProperties:!1},mcpRun:async({instance_id:t,name:s,step:i})=>{const{file:a}=p(t),o=await d(a);let m;if(o.length||e(`${a} has no presets — dsp.preset.save makes one of the knobs as they stand.`),s?.trim())m=h(o,s);else{if(1!==i&&-1!==i)return e("Name the preset (name) or step to the next or the one before (step: 1 | -1).");{const e=o.findIndex(e=>e.name===u(t));m=e<0?1===i?0:o.length-1:(e+i+o.length)%o.length}}const g=o[m],y=l(t);for(const e of y)n.params.set(t,e.path,r(g,e.path,e));return c(t,g.name),`${g.name} (${m+1} of ${o.length}) loaded: ${y.length} knobs set.`}},{id:"dsp.preset.save",title:"DSP: Save Preset",category:"DSP",description:"Save a patch's knobs as they stand (where the hand set them, not a modulation's swing) as a preset into <patch>.presets.json beside it — a preset of that name is written over, else it is added at the end. The next plugin built of the patch carries it.",input_schema:{type:"object",properties:{instance_id:f,name:{type:"string",description:"The preset's name (at most 31 bytes: a plugin's room for it)."}},required:["instance_id","name"],additionalProperties:!1},mcpRun:async({instance_id:e,name:t})=>{const s=y(t),{file:i}=p(e),a=await d(i),o=Object.fromEntries(l(e).map(t=>[t.path,n.params.getBase(e,t.path)])),r=a.findIndex(e=>e.name===s),u=r<0?[...a,{name:s,values:o}]:a.map((e,t)=>t===r?{name:s,values:o}:e);return await m(e,i,u),c(e,s),`${s} ${r<0?`added (${u.length} preset${1===u.length?"":"s"})`:"written over"} in ${i}.`}},{id:"dsp.preset.delete",title:"DSP: Delete Preset",category:"DSP",description:"Delete a preset of a patch from <patch>.presets.json — the knobs stay as they are. The last one gone, the file stays, empty.",input_schema:{type:"object",properties:{instance_id:f,name:{type:"string",description:"The preset's name (dsp.preset.list)."}},required:["instance_id","name"],additionalProperties:!1},mcpRun:async({instance_id:e,name:t})=>{const{file:s}=p(e),n=await d(s),i=h(n,t),a=n[i].name;return await m(e,s,n.filter((e,t)=>t!==i)),u(e)===a&&c(e,null),`${a} deleted (${n.length-1} left) in ${s}.`}},{id:"dsp.preset.rename",title:"DSP: Rename Preset",category:"DSP",description:"Rename a preset of a patch — its values and its place stay. A name another preset has is refused.",input_schema:{type:"object",properties:{instance_id:f,name:{type:"string",description:"The preset's name now (dsp.preset.list)."},to:{type:"string",description:"Its new name (at most 31 bytes)."}},required:["instance_id","name","to"],additionalProperties:!1},mcpRun:async({instance_id:t,name:s,to:n})=>{const i=y(n),{file:a}=p(t),o=await d(a),r=h(o,s),l=o[r].name;return i===l?`${l} keeps its name.`:(o.some(e=>e.name===i)&&e(`There is a preset "${i}" already — delete it or choose another name.`),await m(t,a,o.map((e,t)=>t===r?{...e,name:i}:e)),u(t)===l&&c(t,i),`${l} is ${i} now.`)}},{id:"dsp.preset.move",title:"DSP: Move Preset",category:"DSP",description:"Move a preset of a patch to another place in its list — the order ◀ ▶ steps in and a host lists them in. `to`: its place, 0 the first.",input_schema:{type:"object",properties:{instance_id:f,name:{type:"string",description:"The preset's name (dsp.preset.list)."},to:{type:"integer",minimum:0,description:"Its place in the list, 0 the first (past the end: the last)."}},required:["instance_id","name","to"],additionalProperties:!1},mcpRun:async({instance_id:e,name:t,to:s})=>{const{file:n}=p(e),i=await d(n),a=h(i,t),o=i.filter((e,t)=>t!==a),r=Math.max(0,Math.min(o.length,Math.floor(s)));return r===a?`${i[a].name} stays at ${a+1} of ${i.length}.`:(await m(e,n,[...o.slice(0,r),i[a],...o.slice(r)]),`${i[a].name} is ${r+1} of ${i.length} now.`)}}]}function b(t){return[{id:"transport.play",plays:!0,title:"Transport: Play",category:"TRANSPORT",description:"Master Play: start the global transport (or, when it already runs, the linked players that are not playing). Every open instrument that follows the transport (every Builder and .dsp by default, and whatever a MIDI cable plays — a world's sounds) arms or starts its engine, and every player that follows Master Play starts too — the one that leads first (it sets the tempo). A player whose link is off, or one with nothing to play, stays silent. When the one that leads cannot start, nothing plays and the result says why. system.state transport lists the players.",input_schema:{type:"object",properties:{},additionalProperties:!1},run:async()=>{const e=await t.transport.masterPlay();e.ok||t.messages.notify({kind:"warning",title:"Nothing started",description:e.message})},mcpRun:async()=>{const s=await t.transport.masterPlay();return s.ok||e(s.message),s.message}},{id:"transport.stop",title:"Transport: Stop",category:"TRANSPORT",description:"Stop the global transport. What the transport started stops (an instrument it armed or started; the Performer stops the band it started) — not what was started by hand (dsp.run), which dsp.stop stops. Local module RUN state isn't restored when transport plays again — modules rejoin only on the next play transition.",input_schema:{type:"object",properties:{},additionalProperties:!1},run:()=>t.transport.stop(),mcpRun:()=>(t.transport.stop(),"Transport stopped.")},{id:"transport.clock.stats",title:"Transport: Clock Stats",category:"TRANSPORT",description:"How the master clock's steps came while playing (a measurement, docs/AUDIO-CLAP-FAKTEN-ZIEL.md S4): steps; delay_ms — each step's report after its sample (min, median, p99, max); margin_ms — the time it left to schedule the step after it (min, p1, median; the sequencer plans s + 1 at the report of s); late — steps whose margin was below 0; skipped — steps a report jumped over. Read along, it changes nothing. reset: true begins anew.",input_schema:{type:"object",properties:{reset:{description:"true: begin anew after reading.",type:"boolean"}},additionalProperties:!1},mcpRun:({reset:e})=>JSON.stringify(t.transport.clockStats(!0===e))},{id:"transport.bpm.set",title:"Transport: Set BPM",category:"TRANSPORT",description:"Set the global BPM. Clamped to 30..300. Modules with clock nodes that have transport_link enabled follow this immediately without recompile. Refused while an external MIDI clock drives the tempo — change it on the clock source.",input_schema:{type:"object",properties:{bpm:{description:"Beats per minute for the shared clock. Every sequencer, every transport-following document and the Bar.Beat readout move with it — there is one clock, not one per surface.",type:"number",minimum:30,maximum:300}},required:["bpm"],additionalProperties:!1},mcpRun:({bpm:s})=>{const n="number"==typeof s?s:parseFloat(String(s));return Number.isFinite(n)||e(`transport.bpm.set needs a finite number bpm (got ${typeof s}: ${String(s)}).`),t.transport.setBpm(n),`BPM set to ${t.transport.getBpm()}.`}}]}function w(t){return[{id:"master.volume.set",title:"Master: Set Volume",category:"AUDIO",description:"Set master output volume (linear 0..1, unity = 1.0). Stereo dual-knob: `volume` is a ganged-aware convenience that writes both channels when the master is ganged (the default); `volume_l` / `volume_r` set per-channel (L = 0, R = 1) — independent control; `ganged` locks (true) or unlocks (false) L = R. At least one field must be provided. All values applied with a 5 ms ramp so live changes do not click. Above-unity boost is not allowed.",input_schema:{type:"object",properties:{volume:{description:"Linear gain for both sides at once, 0..1 (unity = 1.0). Convenience for the ganged case; pass volume_l / volume_r to set them apart.",type:"number",minimum:0,maximum:1},volume_l:{description:"Linear gain for the LEFT side, 0..1. Setting only one side implies ganged: false.",type:"number",minimum:0,maximum:1},volume_r:{description:"Linear gain for the RIGHT side, 0..1.",type:"number",minimum:0,maximum:1},ganged:{description:"true = the two sides move together and one value drives both. false = they hold independent values, which is how a master balance is made.",type:"boolean"}},additionalProperties:!1},examples:[{volume:.8},{volume_l:.7,volume_r:.5},{ganged:!1,volume_r:.6}],mcpRun:s=>{void 0===s.volume&&void 0===s.volume_l&&void 0===s.volume_r&&void 0===s.ganged&&e("master.volume.set needs at least one of volume / volume_l / volume_r / ganged.");const n=(t,s)=>("number"==typeof s&&Number.isFinite(s)||e(`master.volume.set ${t} must be a finite number, got ${String(s)}.`),Math.max(0,Math.min(1,s))),i=void 0!==s.ganged?p(s.ganged):void 0;null===i&&e(`master.volume.set ganged must be boolean, got ${typeof s.ganged}: ${String(s.ganged)}.`);const a=void 0!==s.volume?n("volume",s.volume):void 0,o=void 0!==s.volume_l?n("volume_l",s.volume_l):void 0,r=void 0!==s.volume_r?n("volume_r",s.volume_r):void 0,d=[];void 0!==i&&(t.audio.setMasterVolumeGanged(i),d.push(`ganged=${i}`)),void 0!==a&&(t.audio.setMasterVolume(a),d.push(`volume=${a.toFixed(3)}`)),void 0!==o&&(t.audio.setMasterVolumeL(o),d.push(`volume_l=${o.toFixed(3)}`)),void 0!==r&&(t.audio.setMasterVolumeR(r),d.push(`volume_r=${r.toFixed(3)}`));const l=t.audio.getMasterVolumeL(),c=t.audio.getMasterVolumeR(),u=t.audio.getMasterVolumeGanged(),m=l<=0?"−∞":(20*Math.log10(l)).toFixed(1),h=c<=0?"−∞":(20*Math.log10(c)).toFixed(1);return`Master ${d.join(", ")}. Now L=${l.toFixed(3)} (${m} dB), R=${c.toFixed(3)} (${h} dB), ganged=${u}.`}}]}function _(e){return[{id:"view.fullscreen",title:"View: Fullscreen Mode",category:"VIEW",description:"Toggle OS-level fullscreen for the app window (covers the whole screen, no OS chrome). The in-app topbar stays, so exit via the window controls or by running this again.",input_schema:{type:"object",properties:{},additionalProperties:!1},run:()=>(e.views.toggleFullscreen(),"Fullscreen toggled."),mcpRun:()=>(e.views.toggleFullscreen(),"Fullscreen toggled.")}]}var $=e=>{const t=e.net.status();if(!t.connected)return"Not connected to a multiplayer host.";const s=t.peers.map(e=>`${e.id} (${e.channels.join(", ")}${e.state?`, ${Object.entries(e.state).map(([e,t])=>`${e} ${Math.round(100*t)/100}`).join(" ")}`:""})`);return`Connected to ${t.url}, in ${t.channels.join(", ")} — ${s.length?`with ${s.join("; ")}`:"nobody else there yet"}.`};function P(t){return[{id:"net.join",title:"Net: Join a Multiplayer Host",category:"SYSTEM",description:'Connect to a local multiplayer host (started with `npm run net:host`, which prints its ws:// address and room code) and enter a channel: "main" (default), "portal:<name>", "stream". Everyone computes their own state; the host passes states between the players in a channel. One connection at a time — joining again leaves the one before.',input_schema:{type:"object",properties:{url:{type:"string",description:'The host, e.g. "ws://127.0.0.1:4242".'},code:{type:"string",description:"The room code the host printed."},channel:{type:"string",description:'The channel to enter: "main" (default), "portal:<name>" or "stream".'}},required:["url","code"],additionalProperties:!1},mcpRun:async s=>{s.url&&/^wss?:\/\//.test(s.url)||e("net.join needs the host as ws://… (npm run net:host prints it)."),s.code||e("net.join needs the room code the host printed.");try{await t.net.join({url:s.url,code:s.code,...s.channel?{channel:s.channel}:{}})}catch(n){e(n.message)}return $(t)}},{id:"net.leave",title:"Net: Leave the Multiplayer Host",category:"SYSTEM",description:"Leave the multiplayer host (every channel). Not connected is fine.",input_schema:{type:"object",properties:{},additionalProperties:!1},run:()=>t.net.leave(),mcpRun:()=>{const e=t.net.status().connected;return t.net.leave(),e?"Left the multiplayer host.":"Not connected — nothing to leave."}},{id:"net.state",title:"Net: Who Is There",category:"SYSTEM",description:"The multiplayer connection: the host, the channels this IDE is in, and the other players with their last states.",input_schema:{type:"object",properties:{},additionalProperties:!1},mcpRun:()=>$(t)}]}var k=["CC0-1.0","CC-BY-4.0","CC-BY-SA-4.0","MIT","Apache-2.0"],S=["web","webview2","electron","wclap"],T=["archive","install"],j=e=>T.includes(e),D=["instrument","effect","game","tool"],I=e=>D.includes(e),R=e=>"string"==typeof e&&/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?$/.test(e),M={starter:"web",view:"",patch:"",form:"archive",sources:!0,icon:"",licence:"CC0-1.0",author:"",version:"1.0.0",appType:"game",pluginIds:{}},x=n({...M}),A=e=>k.includes(e),F={key:"build",save:()=>({...s(x),pluginIds:{...s(x).pluginIds}}),restore:e=>{const t=e??{};var s;x.set({starter:(s=t.starter,S.includes(s)?t.starter:M.starter),view:"string"==typeof t.view?t.view:"",patch:"string"==typeof t.patch?t.patch:"",form:j(t.form)?t.form:M.form,sources:!1!==t.sources,icon:"string"==typeof t.icon?t.icon:"",licence:A(t.licence)?t.licence:M.licence,author:"string"==typeof t.author?t.author.slice(0,120):"",version:R(t.version)?t.version:M.version,appType:I(t.appType)?t.appType:M.appType,pluginIds:Object.fromEntries(Object.entries(t.pluginIds&&"object"==typeof t.pluginIds?t.pluginIds:{}).filter(([e,t])=>"string"==typeof e&&(e=>"string"==typeof e&&/^[a-z0-9]+(\.[a-z0-9-]+)+$/.test(e))(t)))})},subscribe:e=>x.subscribe(()=>e())};function N(e){for(const t of[...b(e),...h(e),...v(e),...w(e),..._(e),...P(e)])e.actions.register(t);e.project.registerSection(F),e.project.registerSection(y)}export{N as activateCoreRuntime,p as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./errors-BdUU2zPt.js";import{r as t}from"./fileRef-BmnWhXuY.js";import{s}from"./paths-DFjX1bFA.js";import{a as o,s as n}from"./src-DyDfRe65.js";import"./dist-DfaMbR-1.js";import{n as r,r as a}from"./scale-D2nqiPek.js";var i=null;function l(e){i=e}function u(){if(!i)throw new Error("[extension-stage] IDEAPI not initialized. Did the factory run?");return i}var h=new Map;function c(e){const t=h.get(e);if(t)return t;const s=u().log.create(e);return h.set(e,s),s}var d=(e,t)=>e.max===e.min?0:Math.min(1,Math.max(0,r(t,e.min,e.max,e.scale??"linear"))),m=(e,t)=>a(Math.min(1,Math.max(0,t)),e.min,e.max,e.scale??"linear");var p=(e,t,s)=>({mode:"free",at:e,beat:t,bpm:s});function f(e,t,s){return"follow"===e.mode?{beat:null===s.step?null:s.step/4,bpm:s.bpm}:{beat:e.beat+(t-e.at)*e.bpm/60,bpm:e.bpm}}var g=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i,y=["preset-next","preset-prev"],b=(e,t,s)=>Math.min(1,Math.max(0,e-t/200/(s?4:1))),w=["glow","turn","tilt","rise","grow","chase","slide"],v={glow:[0,2],turn:[-135,135],tilt:[-30,30],rise:[0,.2],grow:[.05,1],chase:[0,2],slide:[0,-.1]},$={start:"where a mission begins: walking (or driving) into it starts the mission that names it",trigger:"an area that tells when the player goes in and out",checkpoint:"a place a mission passes on its way",goal:"where a mission is to be brought (a garage, a meeting point)",door:'a door to another stage — its "to": { "stage", "mark"? } (where it leads, at which of its marks)'},k=e=>"string"==typeof e&&e in $,j=[1,1,1],A=["idle","walk","sprint","aim","shoot","walk-back","walk-left","walk-right","jump","fall","land","crouch","crouch-walk","mantle","climb"],x={forward:"walk on, the way the camera looks — in a car: the throttle; in a ship: the thrust; on a ladder: up (walked into one at its foot or its top: onto it)",back:"walk back — in a car: the brake, then reverse; in a ship: the brake; on a ladder: down",left:"walk left — in a car: steer left; in a ship: turn left (it banks into the turn)",right:"walk right — in a car: steer right; in a ship: turn right",run:"run while held — in a ship: the boost",crouch:"crouch while held (on foot): lower, slower — it stands up again only where there is room",jump:"jump (a hit, on foot): up off the floor — before a ledge within reach (about 1–2 m) it climbs up onto it; on a ladder it lets go; in low cover it vaults over it",cover:"take cover (a hit, on foot): against the wall before it (the way it walks, else it faces) — low cover (up to about 1.1 m) crouched, high cover standing; the stick slides it along the wall to its ends, aim peeks (over low cover, round a corner of high cover), fire without aim is blind fire; again (or the stick away from the wall): out of it",dive:"dive (a hit, on foot, on the floor — out of cover too): low through the air the way the stick points (none: back from the look), about 3 m, landing prone and getting up; it aims and fires all the while — and while it flies and lies the world goes in slow motion (0.3 of its speed, the look as quick as ever) as long as its meter holds: the meter drains in slow motion and fills with each target struck",aim:"aim while held (on foot): the camera over the player's shoulder, nearer, its view narrower, the body turned with the look — it walks, it does not run",enter:"get into the car or ship near the player, or out of the car it drives; in a ship: land on the ground below and get out (a hit)",horn:"the horn of the car it drives (a hit)",fire:"a shot on foot (a hit): along the middle of the picture — a target it hits falls",turn:"the camera's turn round the player (a look's turn) — in a ship: where it flies, the ship follows",tilt:"the camera's tilt (a look's tilt) — in a ship: its nose up and down"},z=["enter","horn","fire","jump","cover","dive"],M=["run","aim","crouch"],O={land:"the car driven comes down on its wheels after a jump — as hard as its velocity changed (step 7's knock); the player on its feet after a jump or a fall — as hard as it fell; softly, its back against cover (and down again after a vault)",impact:"the car driven is knocked hard (a wall, a house), the ship flown hits something — as hard as its velocity changed",door:"the player gets into a car or a ship, or out of it",horn:"the horn of the car driven (the world's input horn)",shot:"the player fires (the world's input fire): the gun — best sent at once (quantise now)",hit:"a shot strikes something: a target (strength 1) or the world — a wall, the ground (0.4)",mission:"a mission of the stage begins (its start mark walked into, or stage.mission.start)",objective:"a mission's objective is done — the next one begins",win:"a mission is won (its last objective done in time) — a sting",lose:"a mission is lost (its time is up) — a sting",shift:"the car driven's automatic gearbox shifts (up as it speeds up, down as it slows, a kickdown when the gas goes on at a middling speed) — as hard as its revs jump; best at once (quantise now): the revs drop at once"},N={engine:"the engine of the car driven: its revs, idle (0.15) to the most, from its speed in its gear (dropping as it shifts up); of the ship flown: from its speed and thrust, the boost the most (0 on foot)",load:"how hard the engine works: the gas of the car driven (a share of it while it shifts), the thrust of the ship flown (0 on foot, off the gas)",slip:"how much the car driven slides sideways on its wheels (a skid, a drift)",slow:"how slowed the world is: 0 at its speed, 1 in a dive's full slow motion (eased in and out) — for the music to sound slowed (a low-pass, a pitch down, a tape's brake), its clock running on"},S={sky:"#a8d8f0",skybox:null,streaks:null,ambient:{sky:"#ffffff",ground:"#8a7d6a",strength:2},sun:{color:"#ffffff",strength:2.5,from:[5,10,7]},fog:null,bloom:null,materials:[],lamps:[],lights:{count:0,range:3,strength:1}},q=e=>Array.isArray(e)&&3===e.length&&e.every(e=>"number"==typeof e&&Number.isFinite(e));function F(e){let s;try{s=JSON.parse(e)}catch(E){return{world:null,problems:[`not JSON — ${E.message}`]}}if("object"!=typeof s||null===s||Array.isArray(s))return{world:null,problems:['a world is a JSON object { "format": "world", "camera", "models" }']};const o=[];"world"!==s.format&&o.push('"format" is "world"');const n=s.players,r=Array.isArray(n)&&n.length>0,a=s.camera??(r?{}:void 0);if("object"!=typeof a||null===a||Array.isArray(a))o.push('"camera" is { "at": [x, y, z], "look": [x, y, z], "orbit"?: degrees a second, "fov"?: degrees }');else if(r){const e=Object.keys(a).filter(e=>"fov"!==e);e.length&&o.push(`camera: with players it follows the first — it has only "fov", not ${e.map(e=>`"${e}"`).join(", ")}`),void 0===a.fov||"number"==typeof a.fov&&a.fov>=10&&a.fov<=120||o.push('camera "fov" is its field of view, degrees 10..120')}else q(a.at)||o.push('camera "at" is where it stands, [x, y, z] in metres'),q(a.look)||o.push('camera "look" is where it looks, [x, y, z] in metres'),void 0===a.orbit||"number"==typeof a.orbit&&Math.abs(a.orbit)<=360||o.push('camera "orbit" is degrees a second round "look", -360..360'),void 0===a.fov||"number"==typeof a.fov&&a.fov>=10&&a.fov<=120||o.push('camera "fov" is its field of view, degrees 10..120'),void 0===a.fovAcross||"number"==typeof a.fovAcross&&a.fovAcross>=10&&a.fovAcross<=150||o.push('camera "fovAcross" is its view across, degrees 10..150'),void 0!==a.fovAcross&&void 0!==a.fov&&o.push('camera: "fov" (up and down) or "fovAcross" (across), not both');const i=s.models;Array.isArray(i)||o.push('"models" is a list of { "name", "src": "asset:assets/<name>.glb" }');const l=new Set;for(const[v,$]of(Array.isArray(i)?i:[]).entries()){const e=`model ${"string"==typeof $?.name?`"${$.name}"`:v+1}`;if("string"==typeof $?.name&&/^[a-z0-9-]+$/.test($.name)?l.has($.name)?o.push(`${e}: a name only once`):l.add($.name):o.push(`${e}: a name of lower-case letters, digits and dashes`),"string"==typeof $?.src&&t($.src,".glb")||o.push(`${e}: "src" is the model, "asset:assets/<name>.glb"`),void 0===$?.at||q($.at)||o.push(`${e}: "at" is where it stands, [x, y, z] in metres`),void 0===$?.turn||"number"==typeof $.turn&&Number.isFinite($.turn)||o.push(`${e}: "turn" is degrees round the up axis`),void 0===$?.scale||"number"==typeof $.scale&&$.scale>0&&$.scale<=100||o.push(`${e}: "scale" is above 0, at most 100`),void 0!==$?.solid&&"boolean"!=typeof $.solid&&"shape"!==$.solid&&o.push(`${e}: "solid" is true (a player bumps into its box), "shape" (into its very shape: a ramp, a road's curbs) or false`),void 0!==$?.follows){Array.isArray($.follows)||o.push(`${e}: "follows" lists what of it follows a value, [{ "value", "moves" }]`);for(const t of Array.isArray($.follows)?$.follows:[]){"string"==typeof t?.value&&/^[a-z0-9-]+$/.test(t.value)||o.push(`${e}: a follow's "value" is a scene quantity of the stage, lower-case letters, digits and dashes`),w.includes(t?.moves)||o.push(`${e}: a follow's "moves" is one of ${w.join(", ")}`),void 0!==t?.part&&"string"!=typeof t.part&&o.push(`${e}: a follow's "part" is a node of its model, by name`);for(const s of["from","to"])void 0===t?.[s]||"number"==typeof t[s]&&Number.isFinite(t[s])||o.push(`${e}: a follow's "${s}" is a number`);void 0===t?.color||"string"==typeof t.color&&g.test(t.color)||o.push(`${e}: a follow's "color" is "#rgb" or "#rrggbb"`)}}const s=$?.grab;void 0===s||"object"==typeof s&&null!==s&&"string"==typeof s.value&&/^[a-z0-9-]+$/.test(s.value)||o.push(`${e}: "grab" is what a drag on it writes, { "value": "<a scene quantity of the stage>" }`),void 0===$?.press||y.includes($.press)||o.push(`${e}: "press" is what a press on it does: ${y.join(", ")}`);const n=e=>"string"==typeof e&&e.length>0;void 0===$?.move||n($.move)||Array.isArray($.move)&&$.move.length>0&&$.move.every(n)||o.push(`${e}: "move" is the clip its figure plays, by name (e.g. "Dance"), or a list of them it plays in turn`),void 0===$?.clips||Array.isArray($.clips)&&$.clips.every(e=>"string"==typeof e&&t(e,".glb"))||o.push(`${e}: "clips" lists files of more clips for its figure: ["asset:assets/<name>.glb" …] (npm run anim:retarget)`);const r=$?.holds,a=e=>{const s=e;return"object"==typeof s&&null!==s&&"string"==typeof s.src&&t(s.src,".glb")&&"string"==typeof s.bone&&s.bone.length>0&&(void 0===s.at||q(s.at))&&(void 0===s.turn||q(s.turn))&&(void 0===s.scale||"number"==typeof s.scale&&s.scale>0&&s.scale<=100)};void 0===r||Array.isArray(r)&&r.every(a)||o.push(`${e}: "holds" lists things hung on its bones: [{ "src": "asset:assets/<name>.glb", "bone", "at"?: [x, y, z], "turn"?: [x, y, z], "scale"? }]`)}void 0===s.ground||"string"==typeof s.ground&&g.test(s.ground)||o.push('"ground" is the floor\'s colour, "#rgb" or "#rrggbb"');const u=function(e,t){if(void 0===e)return null;const s='terrain is { "seed", "from": [x, z], "to": [x, z] (to beyond from), "cell"?: world units (1; at most 2048 cells a side), "hills", "mountains": heights, "flat"?: [[x0, z0, x1, z1] …], "ease"?: world units (8) }';if("object"!=typeof e||null===e||Array.isArray(e))return t.push(s),null;const o=e,n=(e,t)=>"number"==typeof e&&Number.isFinite(e)&&e>=t,r=o.flat??[],a=o.cell??1;return Number.isInteger(o.seed)&&W(o.from)&&W(o.to)&&o.to[0]>o.from[0]&&o.to[1]>o.from[1]&&n(a,.1)&&Math.max(o.to[0]-o.from[0],o.to[1]-o.from[1])/a<=2048&&n(o.hills,0)&&n(o.mountains,0)&&(void 0===o.ease||n(o.ease,.01))&&Array.isArray(r)&&r.every(e=>Array.isArray(e)&&4===e.length&&e.every(e=>"number"==typeof e&&Number.isFinite(e)))?{seed:o.seed,from:o.from,to:o.to,cell:a,hills:o.hills,mountains:o.mountains,flat:r,ease:o.ease??8}:(t.push(s),null)}(s.terrain,o),h=function(e,s){if(void 0===e)return null;const o=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);if(!o(e))return s.push('"look" is { "sky"?, "skybox"?, "streaks"?, "ambient"?, "sun"?, "fog"?, "bloom"?, "materials"?, "lamps"?, "lights"? }'),null;const n=e=>"string"==typeof e&&g.test(e),r=(e,t=0,s=1/0)=>"number"==typeof e&&Number.isFinite(e)&&e>=t&&e<=s,a=e=>s.push(`look: ${e}`),i=structuredClone(S);void 0!==e.sky&&(n(e.sky)?i.sky=e.sky:a('"sky" is the colour behind the world, "#rrggbb"'));void 0!==e.skybox&&("string"==typeof e.skybox&&t(e.skybox,".png",".jpg",".jpeg")?i.skybox=e.skybox:a('"skybox" is a picture all round behind the world: "asset:assets/<name>.png", a panorama twice as wide as high'));const l=e.streaks;void 0!==l&&(o(l)&&Number.isInteger(l.count)&&r(l.count,1,2e3)&&(void 0===l.color||n(l.color))&&(void 0===l.length||r(l.length,0,10))?i.streaks={count:l.count,color:l.color??"#ffffff",length:l.length??.05}:a('"streaks" is dust round the camera, stretched by its speed: { "count": 1..2000, "color"?: "#rrggbb", "length"?: world units per world unit a second (0.05) }'));const u=e.ambient;void 0!==u&&(!o(u)||void 0!==u.sky&&!n(u.sky)||void 0!==u.ground&&!n(u.ground)||void 0!==u.strength&&!r(u.strength,0,100)?a('"ambient" is the light from all round: { "sky"?: "#rrggbb" above, "ground"?: "#rrggbb" below, "strength"?: 0..100 }'):i.ambient={sky:u.sky??S.ambient.sky,ground:u.ground??S.ambient.ground,strength:u.strength??S.ambient.strength});const h=e.sun;void 0!==h&&(!o(h)||void 0!==h.color&&!n(h.color)||void 0!==h.strength&&!r(h.strength,0,100)||void 0!==h.from&&!q(h.from)?a('"sun" is the one far light (the moon at night): { "color"?: "#rrggbb", "strength"?: 0..100, "from"?: [x, y, z] the way it comes from }'):i.sun={color:h.color??S.sun.color,strength:h.strength??S.sun.strength,from:h.from??S.sun.from});const c=e.fog;void 0!==c&&(o(c)&&n(c.color)&&r(c.near)&&r(c.far,.01)&&c.far>c.near?i.fog={color:c.color,near:c.near,far:c.far}:a('"fog" is { "color": "#rrggbb", "near": clear up to (world units), "far": all fog from, beyond near — the sight ends there }'));const d=e.bloom;void 0!==d&&(o(d)&&r(d.strength,0,10)&&(void 0===d.radius||r(d.radius,0,1))&&(void 0===d.threshold||r(d.threshold,0,10))?i.bloom={strength:d.strength,radius:d.radius??.4,threshold:d.threshold??.8}:a('"bloom" is the bright parts glowing over their edges: { "strength": 0..10, "radius"?: 0..1 (0.4), "threshold"?: the brightness it starts at (0.8) }'));const m=e.materials??[];if(Array.isArray(m))for(const[g,y]of m.entries())!(o(y)&&(void 0===y.src||"string"==typeof y.src&&t(y.src,".glb"))&&(void 0===y.material||"string"==typeof y.material&&y.material.length>0))||void 0===y.src&&void 0===y.material||void 0!==y.glow&&!n(y.glow)||void 0!==y.strength&&!r(y.strength,0,100)||void 0!==y.rough&&!r(y.rough,0,1)||void 0===y.glow&&void 0===y.rough?a(`material ${g+1} is { "src"?: "asset:assets/<name>.glb" (its model's), "material"?: the start of its material's name — one of them at least; "glow"?: "#rrggbb", "strength"?: 0..100 (1), "rough"?: 0..1 — one of them at least }`):i.materials.push({src:y.src??null,material:y.material??null,glow:y.glow??null,strength:y.strength??1,rough:y.rough??null});else a('"materials" lists materials changed: [{ "src"?, "material"?, "glow"?, "strength"?, "rough"? }]');const p=e.lamps??[];if(Array.isArray(p))for(const[g,y]of p.entries())o(y)&&"string"==typeof y.src&&t(y.src,".glb")&&q(y.at)&&n(y.color)&&r(y.size,1e-4,100)&&(void 0===y.strength||r(y.strength,0,100))?i.lamps.push({src:y.src,at:y.at,color:y.color,size:y.size,strength:y.strength??4}):a(`lamp ${g+1} is { "src": "asset:assets/<name>.glb" (the lamp's model), "at": [x, y, z] its bulb in the model's own frame, "color": "#rrggbb", "size": across, "strength"?: 0..100 (4) }`);else a('"lamps" lists the lamps: [{ "src", "at", "color", "size", "strength"? }]');const f=e.lights;void 0!==f&&(o(f)&&Number.isInteger(f.count)&&r(f.count,0,16)&&r(f.range,.01)&&(void 0===f.strength||r(f.strength,0,1e3))?i.lights={count:f.count,range:f.range,strength:f.strength??1}:a('"lights" is how many of the lamps nearest the player cast light: { "count": 0..16, "range": how far it reaches (world units), "strength"? }'));return i}(s.look,o),c=s.wall,d=e=>"number"==typeof e&&e>0&&e<=1e3;void 0===c||"object"==typeof c&&null!==c&&"number"==typeof c.z&&Number.isFinite(c.z)&&d(c.width)&&d(c.height)&&"string"==typeof c.color&&g.test(c.color)||o.push('"wall" is a wall across the back on the floor, facing +z: { "z", "width", "height" (metres), "color": "#rrggbb" }'),void 0===n||Array.isArray(n)&&1===n.length||o.push('"players" lists one player for now: [{ "name", "src": "asset:assets/<name>.glb", "at"?, "turn"?, "scale"? }]');for(const g of r?n:[]){const e="string"==typeof g?.name?`player "${g.name}"`:"the player";"string"==typeof g?.name&&/^[a-z0-9-]+$/.test(g.name)?l.has(g.name)?o.push(`${e}: a name only once`):l.add(g.name):o.push(`${e}: a name of lower-case letters, digits and dashes`),"string"==typeof g?.src&&t(g.src,".glb")||o.push(`${e}: "src" is the figure, "asset:assets/<name>.glb" (its moves ${A.join(", ")} — or "moves" names its own clips)`),void 0===g?.at||q(g.at)||o.push(`${e}: "at" is where it starts, [x, y, z]`),void 0===g?.turn||"number"==typeof g.turn&&Number.isFinite(g.turn)||o.push(`${e}: "turn" is degrees round the up axis`),void 0===g?.scale||"number"==typeof g.scale&&g.scale>0&&g.scale<=100||o.push(`${e}: "scale" is above 0, at most 100`);const s=g?.moves,n=e=>"object"==typeof e&&null!==e&&!Array.isArray(e)&&Object.entries(e).every(([e,t])=>A.includes(e)&&"string"==typeof t&&t.length>0);void 0===s||n(s)||o.push(`${e}: "moves" names its figure's clip for a move of another name: { ${A.map(e=>`"${e}"?`).join(", ")} } (e.g. { "sprint": "Run" })`);const r=g?.clips;void 0===r||Array.isArray(r)&&r.every(e=>"string"==typeof e&&t(e,".glb"))||o.push(`${e}: "clips" lists files of more clips for its figure: ["asset:assets/<name>.glb" …] (npm run anim:retarget)`)}const m=(e,n,a)=>{const i=s[e];void 0===i||Array.isArray(i)?Array.isArray(i)&&i.length&&!r&&o.push(`"${e}" want a player to ${{cars:"drive",ships:"fly",targets:"shoot"}[e]} them ("players")`):o.push(`"${e}" lists the ${e}: [{ "name", "src": "asset:assets/<name>.glb", "at"?, "turn"?, "scale"? }]`);for(const[s,r]of(Array.isArray(i)?i:[]).entries()){const e=`${n} ${"string"==typeof r?.name?`"${r.name}"`:s+1}`;"string"==typeof r?.name&&/^[a-z0-9-]+$/.test(r.name)?l.has(r.name)?o.push(`${e}: a name only once`):l.add(r.name):o.push(`${e}: a name of lower-case letters, digits and dashes`),"string"==typeof r?.src&&t(r.src,".glb")||o.push(`${e}: "src" is the ${n}, "asset:assets/<name>.glb" (${a})`),void 0===r?.at||q(r.at)||o.push(`${e}: "at" is where it is parked, [x, y, z]`),void 0===r?.turn||"number"==typeof r.turn&&Number.isFinite(r.turn)||o.push(`${e}: "turn" is degrees round the up axis`),void 0===r?.scale||"number"==typeof r.scale&&r.scale>0&&r.scale<=100||o.push(`${e}: "scale" is above 0, at most 100`)}return(Array.isArray(i)?i:[]).map(e=>({name:e.name,src:e.src,at:e.at??[0,0,0],turn:e.turn??0,scale:e.scale??1}))},p=m("cars","car","its wheels the nodes named wheel-…: Kenney's Car Kit"),f=m("ships","ship","its nose along -z: Kenney's Space Kit"),b=m("targets","target","a thing to shoot: Kenney's Blaster Kit target, a Pirate Kit bottle"),x=function(e,s,o){if(void 0===e)return[];const n=Object.keys($).join(", ");if(!Array.isArray(e))return o.push(`"marks" lists places without a picture: [{ "name", "kind": ${n}, "at": [x, y, z], "size"? | "radius"?, "turn"?, "to"? }]`),[];const r=[];for(const[a,i]of e.entries()){const e=`mark ${"string"==typeof i?.name?`"${i.name}"`:a+1}`,l=o.length;"string"==typeof i?.name&&/^[a-z0-9-]+$/.test(i.name)?s.has(i.name)?o.push(`${e}: a name only once (a mark's among the world's things)`):s.add(i.name):o.push(`${e}: a name of lower-case letters, digits and dashes`),k(i?.kind)||o.push(`${e}: "kind" is ${n}`),q(i?.at)||o.push(`${e}: "at" is its foot, [x, y, z] — a box rises from it, a ball's centre is its radius above`);const u=e=>"number"==typeof e&&Number.isFinite(e)&&e>0&&e<=1e3;void 0===i?.size||q(i.size)&&i.size.every(u)||o.push(`${e}: "size" is a box's [x, y, z], each above 0`),void 0===i?.radius||u(i.radius)||o.push(`${e}: "radius" is a ball's, above 0`),void 0!==i?.size&&void 0!==i?.radius&&o.push(`${e}: a box ("size") or a ball ("radius"), not both`),void 0===i?.turn||"number"==typeof i.turn&&Number.isFinite(i.turn)||o.push(`${e}: "turn" is degrees round the up axis`);const h=i?.to,c=void 0!==h&&"object"==typeof h&&null!==h&&"string"==typeof h.stage&&t(h.stage,".stage")&&(void 0===h.mark||"string"==typeof h.mark&&/^[a-z0-9-]+$/.test(h.mark));"door"!==i?.kind||c?"door"!==i?.kind&&void 0!==h&&o.push(`${e}: only a door has "to"`):o.push(`${e}: a door leads somewhere — "to": { "stage": "asset:assets/<name>.stage", "mark"?: its mark there }`),o.length>l||r.push({name:i.name,kind:i.kind,at:i.at,size:void 0!==i.radius?null:i.size??j,radius:i.radius??null,turn:i.turn??0,to:c?{stage:h.stage,mark:h.mark??null}:null})}return r}(s.marks,l,o),z=function(e,t,s){if(void 0===e)return[];if(!Array.isArray(e))return s.push('"ladders" lists where the player climbs: [{ "name", "from": [x, y, z], "to": [x, y, z], "face": degrees }]'),[];const o=[];for(const[n,r]of e.entries()){const e=`ladder ${"string"==typeof r?.name?`"${r.name}"`:n+1}`,a=s.length;"string"==typeof r?.name&&/^[a-z0-9-]+$/.test(r.name)?t.has(r.name)?s.push(`${e}: a name only once (a ladder's among the world's things)`):t.add(r.name):s.push(`${e}: a name of lower-case letters, digits and dashes`),q(r?.from)||s.push(`${e}: "from" is its foot, [x, y, z] — where the player's feet start up it`),q(r?.to)?!q(r?.from)||r.to[1]>r.from[1]||s.push(`${e}: its top ("to") is above its foot ("from")`):s.push(`${e}: "to" is its top, [x, y, z] — the floor it leads onto`),"number"==typeof r?.face&&Number.isFinite(r.face)||s.push(`${e}: "face" is the way the player faces on it, degrees (towards the wall; 0 along +z)`),s.length>a||o.push({name:r.name,from:r.from,to:r.to,face:r.face})}return o}(s.ladders,l,o),M=function(e,t,s){if(void 0===e)return[];if(!Array.isArray(e))return s.push('"texts" lists words in the scene: [{ "name", "text" | "value": { "of" }, "at": [x, y, z] }]'),[];const o=[];for(const[n,r]of e.entries()){const e=`text ${"string"==typeof r?.name?`"${r.name}"`:n+1}`,a=s.length;"string"==typeof r?.name&&/^[a-z0-9-]+$/.test(r.name)?t.has(r.name)?s.push(`${e}: a name only once (a text's among the world's things)`):t.add(r.name):s.push(`${e}: a name of lower-case letters, digits and dashes`);const i=r?.value;if(1!==["string"==typeof r?.text,void 0!==i,void 0!==r?.says].filter(Boolean).length&&s.push(`${e}: one of "text" (its words), "value" (a quantity it shows) or "says": "preset" (the stage's preset's name)`),void 0!==r?.says&&"preset"!==r.says&&s.push(`${e}: "says" is "preset" (the name of the preset that stands)`),void 0!==i)if("object"==typeof i&&null!==i&&"string"==typeof i.of&&/^[a-z0-9-]+$/.test(i.of)){for(const t of["from","to"])void 0===i[t]||"number"==typeof i[t]&&Number.isFinite(i[t])||s.push(`${e}: value "${t}" is a number`);void 0===i.digits||Number.isInteger(i.digits)&&i.digits>=0&&i.digits<=6||s.push(`${e}: value "digits" is 0..6`),void 0!==i.unit&&"string"!=typeof i.unit&&s.push(`${e}: value "unit" is words (Hz, dB …)`),void 0!==i.scale&&"linear"!==i.scale&&"log"!==i.scale&&"exp"!==i.scale&&s.push(`${e}: value "scale" is linear, log or exp (a [scale:log] param's knob)`)}else s.push(`${e}: "value" is { "of": a scene quantity of the stage, "from"?, "to"?, "digits"?, "unit"? }`);q(r?.at)||s.push(`${e}: "at" is where it stands, [x, y, z] (its foot, the middle of its line)`),void 0===r?.size||"number"==typeof r.size&&r.size>0||s.push(`${e}: "size" is its letters' height, more than 0`),void 0===r?.color||"string"==typeof r.color&&P.test(r.color)||s.push(`${e}: "color" is "#rrggbb"`),void 0===r?.turn||"number"==typeof r.turn&&Number.isFinite(r.turn)||s.push(`${e}: "turn" is degrees round the up axis`),void 0!==r?.lie&&"boolean"!=typeof r.lie&&s.push(`${e}: "lie" is true (flat, read from above) or false`),void 0===r?.align||I.includes(r.align)||s.push(`${e}: "align" is ${I.join(", ")}`),s.length>a||o.push({name:r.name,text:"string"==typeof r.text?r.text:null,says:"preset"===r.says?"preset":null,value:i?{of:i.of,from:i.from??0,to:i.to??1,digits:i.digits??0,unit:i.unit??"",scale:i.scale??"linear"}:null,at:r.at,size:r.size??.1,color:r.color??"#d8dce6",turn:r.turn??0,lie:!0===r.lie,align:r.align??"center"})}return o}(s.texts,l,o),O=function(e,t,s){if(void 0===e)return[];if(!Array.isArray(e))return s.push('"traces" lists lines through quantities: [{ "name", "values": [quantities], "at": [x, y, z], "width", "height" }]'),[];const o=[];for(const[n,r]of e.entries()){const e=`trace ${"string"==typeof r?.name?`"${r.name}"`:n+1}`,a=s.length;"string"==typeof r?.name&&/^[a-z0-9-]+$/.test(r.name)?t.has(r.name)?s.push(`${e}: a name only once (a trace's among the world's things)`):t.add(r.name):s.push(`${e}: a name of lower-case letters, digits and dashes`);const i=r?.values;(!Array.isArray(i)||i.length<2||i.length>256||!i.every(e=>"string"==typeof e&&/^[a-z0-9-]+$/.test(e)))&&s.push(`${e}: "values" lists 2 to 256 scene quantities of the stage, the line goes through them in order`),q(r?.at)||s.push(`${e}: "at" is its middle, [x, y, z]`);for(const t of["width","height"])"number"==typeof r?.[t]&&r[t]>0||s.push(`${e}: "${t}" is more than 0`);void 0===r?.color||"string"==typeof r.color&&P.test(r.color)||s.push(`${e}: "color" is "#rrggbb"`),void 0===r?.screen||"string"==typeof r.screen&&P.test(r.screen)||s.push(`${e}: "screen" is "#rrggbb" (the screen behind it)`),void 0!==r?.lie&&"boolean"!=typeof r.lie&&s.push(`${e}: "lie" is true (flat, read from above) or false`),s.length>a||o.push({name:r.name,values:[...i],at:r.at,width:r.width,height:r.height,color:r.color??"#35d6ff",lie:!0===r.lie,screen:r.screen??null})}return o}(s.traces,l,o),N=function(e,t,s){if(void 0===e)return[];if(!Array.isArray(e))return s.push('"rings" lists arcs following quantities: [{ "name", "value", "at": [x, y, z], "radius" }]'),[];const o=[];for(const[n,r]of e.entries()){const e=`ring ${"string"==typeof r?.name?`"${r.name}"`:n+1}`,a=s.length;"string"==typeof r?.name&&/^[a-z0-9-]+$/.test(r.name)?t.has(r.name)?s.push(`${e}: a name only once (a ring's among the world's things)`):t.add(r.name):s.push(`${e}: a name of lower-case letters, digits and dashes`),"string"==typeof r?.value&&/^[a-z0-9-]+$/.test(r.value)||s.push(`${e}: "value" is a scene quantity of the stage`),q(r?.at)||s.push(`${e}: "at" is its middle, [x, y, z]`),"number"==typeof r?.radius&&r.radius>0||s.push(`${e}: "radius" is more than 0`);for(const t of["from","to"])void 0===r?.[t]||"number"==typeof r[t]&&Number.isFinite(r[t])||s.push(`${e}: "${t}" is degrees`);void 0===r?.color||"string"==typeof r.color&&P.test(r.color)||s.push(`${e}: "color" is "#rrggbb"`),void 0!==r?.lie&&"boolean"!=typeof r.lie&&s.push(`${e}: "lie" is true (flat, read from above) or false`),s.length>a||o.push({name:r.name,value:r.value,at:r.at,radius:r.radius,from:r.from??-135,to:r.to??135,color:r.color??"#35d6ff",lie:!0===r.lie})}return o}(s.rings,l,o);if(z.length&&!r&&o.push('"ladders" want a player to climb them ("players")'),o.length)return{world:null,problems:o};const F=a;return{world:{camera:{at:F.at??[0,0,0],look:F.look??[0,0,0],orbit:F.orbit??0,fov:F.fov??50,across:F.fovAcross??null},ground:s.ground??null,terrain:u,models:i.map(e=>({name:e.name,src:e.src,at:e.at??[0,0,0],turn:e.turn??0,scale:e.scale??1,solid:"shape"===e.solid?"shape":!0===e.solid,follows:(e.follows??[]).map(e=>{const t=e.moves;return{value:e.value,moves:t,part:e.part??null,from:e.from??v[t][0],to:e.to??v[t][1],color:e.color??null}}),grab:e.grab?{value:e.grab.value}:null,press:e.press??null,move:void 0===e.move?[]:Array.isArray(e.move)?[...e.move]:[e.move],clips:e.clips??[],holds:(e.holds??[]).map(e=>({src:e.src,bone:e.bone,at:e.at??[0,0,0],turn:e.turn??[0,0,0],scale:e.scale??1}))})),players:(r?n:[]).map(e=>({name:e.name,src:e.src,at:e.at??[0,0,0],turn:e.turn??0,scale:e.scale??1,moves:{...e.moves},clips:[...e.clips??[]]})),cars:p,ships:f,targets:b,marks:x,ladders:z,texts:M,traces:O,rings:N,look:h,...c?{wall:{z:c.z,width:c.width,height:c.height,color:c.color}}:{}},problems:[]}}var I=["left","center","right"],P=/^#[0-9a-fA-F]{6}$/;var W=e=>Array.isArray(e)&&2===e.length&&e.every(e=>"number"==typeof e&&Number.isFinite(e));var E=(e,t,s)=>Number.isInteger(e)&&e>=t&&e<=s;function D(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return[`${t}: "sounds" is { "<event>": { "channel": 1..16, "note": 0..127, "quantise"?: "16th" | "now" }, "<value>": { "channel": 1..16, "cc": 0..119 } }`];const s=[];for(const[o,n]of Object.entries(e)){const e=o in O;e||o in N?(E(n?.channel,1,16)||s.push(`${t}: sound "${o}" has a "channel", 1..16`),e?(E(n?.note,0,127)&&void 0===n?.cc||s.push(`${t}: sound "${o}" is an event — a "note", 0..127 (no "cc")`),void 0!==n?.quantise&&"16th"!==n.quantise&&"now"!==n.quantise&&s.push(`${t}: sound "${o}": "quantise" is "16th" (the next sixteenth of the stage's clock) or "now"`)):E(n?.cc,0,119)&&void 0===n?.note&&void 0===n?.quantise||s.push(`${t}: sound "${o}" is a value — a "cc", 0..119 (no "note", no "quantise": it is sent as it changes)`)):s.push(`${t}: sound "${o}" is none of the world's — events ${Object.keys(O).join(", ")}; values ${Object.keys(N).join(", ")}`)}return s}function T(e,t){if("now"===e||null===t.beat)return t.now;if(t.grid){for(let e=Math.floor(t.grid.audible)+1,s=0;s<64;e++,s++){const s=t.grid.stepTime(e);if(null===s)return t.now;if(s>=t.now)return s}return t.now}const s=4*t.beat;return t.now+15*(Math.floor(s)+1-s)/t.bpm}var _=["left","right","up","down"],B=["left","right","middle","wheelup","wheeldown"],K={arrows:{left:"arrowleft",right:"arrowright",up:"arrowup",down:"arrowdown"},wasd:{left:"a",right:"d",up:"w",down:"s"}},H=4/3,C=e=>{const t=e;return!!t&&Number.isInteger(t.channel)&&t.channel>=1&&t.channel<=16&&Number.isInteger(t.note)&&t.note>=0&&t.note<=127},J=e=>"string"==typeof e&&e.length>0&&!e.startsWith("mouse")&&!e.startsWith("wheel");function U(e){return e.filter(e=>"world"===e?.type).map(e=>e.name)}function L(e,t,s){if("menu"===e.kind)return null;const o=e.element??s[0];if(!o)return null;if("hit"===e.kind||"hold"===e.kind)return{element:o,input:e.input};if("stick"===e.kind){const s=t?e.inputs[t]:void 0;return s?{element:o,input:s}:null}return null}function R(e,t){return(void 0===e.keys?[]:"string"==typeof e.keys?[e.keys]:e.keys).map(e=>K[e]?.[t]).filter(e=>!!e)}function V(e,t){const s=[],o=(t,o,n,r=!0)=>{const a={module_id:e,control:o,...n?{part:n}:{}};s.push({id:`${o}${n?`.${n}`:""}:${t}`,key:t,actionId:"stage.control.press",input:a,...r?{release:{actionId:"stage.control.release",input:a}}:{}})};for(const[n,r]of Object.entries(t))if("menu"===r.kind)for(const e of void 0===r.key?[]:"string"==typeof r.key?[r.key]:r.key)o(e.toLowerCase(),n,void 0,!1);else if("hit"===r.kind||"hold"===r.kind){for(const e of void 0===r.key?[]:"string"==typeof r.key?[r.key]:r.key)o(e.toLowerCase(),n,void 0,"hold"===r.kind);r.mouse&&o(r.mouse.startsWith("wheel")?r.mouse:`mouse${r.mouse}`,n,void 0,"hold"===r.kind)}else if("stick"===r.kind){for(const e of _)if(r.inputs[e])for(const t of R(r,e))o(t,n,e)}else"look"===r.kind&&s.push({id:`${n}:mouse`,key:"mouse",actionId:"stage.control.look",input:{module_id:e,control:n}});return s}function Z(e,t,s){const o=e.speed??.15;return{turn:t*o,tilt:-s*o*H}}function G(e){const t=[];for(const[s,o]of Object.entries(e))if("hit"!==o.kind&&"hold"!==o.kind&&"menu"!==o.kind||!o.midi||t.push({...o.midi,control:s}),"stick"===o.kind)for(const e of _)o.midi?.[e]&&t.push({...o.midi[e],control:s,part:e});return t}function Q(e,t){const s=e=>e?` midi ch ${e.channel} note ${e.note}`:"";if("menu"===t.kind){const o=void 0===t.key?[]:"string"==typeof t.key?[t.key]:t.key;return`${e}: menu → the pause menu, opened or closed (stage.pause)${o.length?` keys ${o.join(", ")}`:""}${s(t.midi)}; the pointer lock let go (Esc) opens it too`}if("hit"===t.kind||"hold"===t.kind){const o=void 0===t.key?[]:"string"==typeof t.key?[t.key]:t.key;return`${e}: ${t.kind} → ${t.input}${o.length?` keys ${o.join(", ")}`:""}${t.mouse?` mouse ${t.mouse}`:""}${s(t.midi)}`}if("stick"===t.kind)return`${e}: stick → ${_.filter(e=>t.inputs[e]).map(e=>`${e} ${t.inputs[e]}${R(t,e).length?` [${R(t,e).join(", ")}]`:""}${s(t.midi?.[e])}`).join("; ")}`;const o=t;return`${e}: look → ${Object.entries(o.inputs).map(([e,t])=>`${e} ${t}`).join(", ")}, the mouse while the pointer is locked on the stage (${o.speed??.15}° a pixel)`}var X={enter:'get into a car or a ship — "vehicle"?: its name (any when left out)',reach:'reach a mark — "mark": its name, "by"?: "foot" | "car" | "ship" (any way when left out)',hit:'hit targets — "count": so many struck since the mission began'},Y=["foot","car","ship"],ee=["start","step","hurry","win","lose"];function te(e,t){const s=new Set(t.marks.map(e=>e.name)),o=new Set([...t.cars,...t.ships].map(e=>e.name)),n=[];e.start&&!s.has(e.start)&&n.push(`mission "${e.name}": its start "${e.start}" is no mark of the world`);for(const[r,a]of e.steps.entries())"reach"!==a.do||s.has(a.mark)||n.push(`mission "${e.name}" step ${r+1}: no mark "${a.mark}" in the world`),"enter"===a.do&&a.vehicle&&!o.has(a.vehicle)&&n.push(`mission "${e.name}" step ${r+1}: no car or ship "${a.vehicle}" in the world`),"enter"!==a.do||o.size||n.push(`mission "${e.name}" step ${r+1}: the world has no car or ship to get into`),"hit"===a.do&&t.targets.length<a.count&&n.push(`mission "${e.name}" step ${r+1}: the world has ${t.targets.length} targets, not ${a.count}`);return n}var se={mission:"the mission playing — its title, its objective, the time left (in the error colour its last 10 s), how far its mark is or how many are hit; at the top",result:"a mission's end — passed, failed or stopped, with its time or why; a banner across the middle for 6 s",crosshair:"while the player aims — a crosshair in the middle, opened by a shot, a cross while the shot struck a target",targets:"a world of targets — how many are struck of how many, and under it the slow motion's meter once the player has dived; top right",speed:"in a car or a ship — km/h, the car's gear and its revs; bottom right"},oe=Object.keys(se);function ne(e){return new Set(e??oe)}var re={dimmer:.6,red:1,green:1,blue:1,hue:.6,rate:0},ae={par:["dimmer","red","green","blue"],strobe:["dimmer","rate"],wash:["dimmer","hue"]},ie=Object.keys(ae),le={...ae,world:[],camera:[]},ue=["fade","wipe","iris","mist"],he=/^cut:([a-z0-9-]+)(?:@(\d+(?:\.\d+)?)(?: ([a-z]+))?)?$/,ce=/^dance:([A-Za-z0-9_-]+(?:,[A-Za-z0-9_-]+)*)$/;function de(e){const[t,s]=e.split(".");return void 0===s?ge(t):ye(t,s)}var me=e=>e*e*(3-2*e);function pe(e,t){if(t<=e[0][0])return e[0][1];for(let s=0;s<e.length-1;s++){const[o,n,r="linear"]=e[s],[a,i]=e[s+1];if(t>a)continue;if("hold"===r||a===o)return n;const l=(t-o)/(a-o);return n+(i-n)*("ease"===r?me(l):l)}return e[e.length-1][1]}var fe=e=>Array.isArray(e)&&e.length>0&&e.every(e=>Array.isArray(e)&&"number"==typeof e[0]&&ke(e[1])&&(void 0===e[2]||["linear","ease","hold"].includes(e[2]))),ge=e=>`/stage/scene/${e}`,ye=(e,t)=>`/stage/${e}/${t}`,be=/^set:([^.=]+)\.([^=]+)=(1(?:\.0*)?|0(?:\.\d+)?|\.\d+)(?:@(\d+(?:\.\d+)?))?$/,we=e=>e.channels??le[e.type]??[];function ve(e,t){return!(e.at!==t.name&&e.at!==t.role||void 0!==e.chapter&&e.chapter!==t.chapter)}function $e(e){return[...e.elements.flatMap(e=>we(e).map(t=>{return{path:(s=e.name,o=t,`/stage/${s}/${o}`),init:e.start?.[t]??re[t]};var s,o})),{path:"/stage/master",init:1},...Object.entries(e.scene).map(([e,t])=>({path:ge(e),init:t}))]}var ke=e=>"number"==typeof e&&Number.isFinite(e)&&e>=0&&e<=1,je=e=>Array.isArray(e)&&3===e.length&&e.every(e=>"number"==typeof e&&Number.isFinite(e));function Ae(e,t){const s="string"==typeof t?t:null,o=s?.startsWith("wish:")?s.slice(5):null,n=s?.startsWith("energy:")?Number(s.slice(7)):null,r=s?.startsWith("set:")?be.exec(s):null;return null!==s&&["hold:on","hold:off","next"].includes(s)||null!==o||null!==n||s?.startsWith("set:")||s?.startsWith("cut:")||s?.startsWith("dance:")?s?.startsWith("dance:")&&!ce.test(s)?'"dance:" is dance:<a move of the world\'s dancers> (e.g. dance:Dance_Jump), several to take turns among (dance:Dance_Dream,Dance_Float) or dance:mix':s?.startsWith("cut:")?function(e,t){const s=he.exec(t);if(!s)return'"cut:" is cut:<camera>, "@<bars> <mask>" after it to go through a mask (fade, wipe, iris, mist) over bars';const o=(e.elements??[]).filter(e=>"camera"===e?.type).map(e=>e.name);return"world"===s[1]||o.includes(s[1])?void 0===s[2]||Number(s[2])>0&&Number(s[2])<=16?void 0===s[3]||ue.includes(s[3])?null:`a cut goes through ${ue.join(", ")}`:'"cut:" goes over more than 0 and up to 16 bars':`no camera "${s[1]}" — one of the stage's camera elements (${o.join(", ")||"none"}) or "world"`}(e,s):null===o||["more","less","breathe","build"].includes(o)?null===n||n>=-1&&n<=1?s?.startsWith("set:")&&!r?'"set:" is set:<element>.<param>=<0..1>, "@<bars>" after it to glide':r&&!function(e,t){const s=(e.elements??[]).find(e=>e?.name===t);if(!s)return[];const o=`/stage/${t}/`;try{return $e({...e,scene:{},elements:[s]}).filter(e=>e.path.startsWith(o)).map(e=>e.path.slice(o.length))}catch(n){if(n instanceof TypeError)return[];throw n}}(e,r[1]).includes(r[2])?'no element "'+r[1]+'" with a param "'+r[2]+'" — one of its channels':null:'"energy:" is -1 (calm) .. 1 (all in)':'"wish:" is more, less, breathe or build':'"do" is "wish:<more|less|breathe|build>" or "energy:<-1..1>" (told to the Performer), "hold:on" / "hold:off" / "next" (the conductor: the section held, let go, the next one), "set:<element>.<param>=<0..1>[@<bars>]" (an element\'s param, gliding over bars), "cut:<camera>[@<bars> <mask>]" (the picture seen from a camera element, or "world" — through fade, wipe, iris or mist), "dance:<move>" (the world\'s dancers all dance that move) or "dance:mix" (each its own again)'}function xe(e){let s;try{s=JSON.parse(e)}catch(d){return{doc:null,problems:[`not JSON: ${d.message}`]}}const o=[],n=s;if("stage"!==n?.format)return{doc:null,problems:['not a stage document (no "format": "stage")']};if(!Array.isArray(n.elements))return{doc:null,problems:['"elements" is missing — a list, the first furthest back']};void 0!==n.follow&&"boolean"!=typeof n.follow&&o.push('"follow" is true or false'),void 0!==n.cues&&(Array.isArray(n.cues)?n.cues.forEach((e,t)=>{const s="cue "+(t+1);"string"==typeof e?.at&&e.at||o.push(s+': "at" is a part of the song — its name or role');const r=Ae(n,e?.do);r?o.push(`${s}: ${r}`):void 0===e?.bar||"number"==typeof e.bar&&e.bar>=0&&e.bar<=256?void 0===e?.chapter||Number.isInteger(e.chapter)&&e.chapter>=1||o.push(s+': "chapter" is the chapter of the run it is done in, 1 the first'):o.push(s+': "bar" is the bar of its part it is done at, 0 (as it begins) up to 256')}):o.push('"cues" is a list of { "at": a part of the song, "do": "set:…" | "wish:…" … }')),void 0!==n.controls&&o.push(...function(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return['"controls" is { "<name>": { "kind": "stick" | "hit" | "hold" | "look" | "menu", … } }'];const s=[];for(const[o,n]of Object.entries(e)){const e=`control "${o}"`,r=n;if(/^[a-z0-9-]+$/.test(o)||s.push(`${e}: a name of lower-case letters, digits and dashes`),!r||"object"!=typeof r){s.push(`${e}: { "kind": "stick" | "hit" | "hold" | "look" | "menu", … }`);continue}if("menu"===r.kind){const t=Object.keys(r).filter(e=>!["kind","key","midi"].includes(e));t.length&&s.push(`${e}: a menu knows key, midi — not ${t.join(", ")}`),void 0===r.key||J(r.key)||Array.isArray(r.key)&&r.key.length>0&&r.key.every(J)||s.push(`${e}: "key" is a key ("escape", "p") or a list of them`),void 0===r.midi||C(r.midi)||s.push(`${e}: "midi" is { "channel": 1..16, "note": 0..127 } — a note that opens it too`);continue}(void 0!==r.element?t.includes(r.element):t.length)||s.push(`${e}: "element" is a world element of the stage (${t.join(", ")||"none"}) — the first when left out`);const a=["forward","back","left","right",...M],i=r.inputs&&"object"==typeof r.inputs?r.inputs:{},l="hit"===r.kind||"hold"===r.kind?[r.input]:Object.values(i);"hit"===r.kind?z.includes(r.input)||s.push(`${e}: a world's hit fires ${z.map(e=>`${e} (${x[e]})`).join(", ")} — a hold or a stick walks its player (${a.join(", ")})`):"look"===r.kind?Object.entries(i).some(([e,t])=>e!==t)&&s.push(`${e}: a world's look is { "turn": "turn", "tilt": "tilt" } — the camera round its player`):"hold"!==r.kind&&"stick"!==r.kind||!l.some(e=>!a.includes(e))||s.push(`${e}: a world's player takes ${Object.entries(x).filter(([e])=>a.includes(e)).map(([e,t])=>`${e} (${t})`).join(", ")}`);const u=t=>{const o=Object.keys(r).filter(e=>!["kind","element",...t].includes(e));o.length&&s.push(`${e}: a ${String(r.kind)} knows ${t.join(", ")} — not ${o.join(", ")}`)};if("hit"===r.kind||"hold"===r.kind)u(["input","key","mouse","midi"]),void 0===r.key||J(r.key)||Array.isArray(r.key)&&r.key.length>0&&r.key.every(J)||s.push(`${e}: "key" is a key ("space", "e", "mod+x") or a list of them`),void 0===r.mouse||B.includes(r.mouse)?"hold"!==r.kind||"wheelup"!==r.mouse&&"wheeldown"!==r.mouse||s.push(`${e}: the wheel only fires — a hit, not a hold`):s.push(`${e}: "mouse" is ${B.join(", ")} — while the pointer is locked on the stage`),void 0===r.midi||C(r.midi)||s.push(`${e}: "midi" is { "channel": 1..16, "note": 0..127 } — a note that presses it too`);else if("stick"===r.kind){u(["inputs","keys","midi"]),Object.keys(i).length&&Object.keys(i).every(e=>_.includes(e))||s.push(`${e}: "inputs" is { "left"?, "right"?, "up"?, "down"? } — the world's walking inputs`);const t="string"==typeof r.keys?[r.keys]:r.keys;void 0===r.keys||Array.isArray(t)&&t.length>0&&t.every(e=>"string"==typeof e&&e in K)||s.push(`${e}: "keys" is ${Object.keys(K).join(" or ")}, or a list of them`);const o=r.midi;void 0===o||"object"==typeof o&&null!==o&&Object.entries(o).every(([e,t])=>_.includes(e)&&C(t))||s.push(`${e}: "midi" is { "left"?: { "channel", "note" }, … } — the notes that press its parts too`)}else"look"===r.kind?(u(["inputs","speed"]),Object.keys(i).length&&Object.keys(i).every(e=>"turn"===e||"tilt"===e)||s.push(`${e}: "inputs" is { "turn"?, "tilt"? } — the camera's turn round the player and its tilt`),void 0===r.speed||"number"==typeof r.speed&&r.speed>0&&r.speed<=10||s.push(`${e}: "speed" is degrees a mouse pixel turns, above 0, at most 10 (0.15)`)):s.push(`${e}: "kind" is stick, hit, hold, look or menu`)}return s}(n.controls,U(n.elements??[]))),void 0!==n.hud&&o.push(...function(e){const t=`"hud" lists the parts the HUD over the world shows — ${oe.join(", ")} (left out: all of them, []: none)`;if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))return[t];const s=e.filter(e=>!(e in se));return s.length?[`"hud": ${s.map(e=>`"${e}"`).join(", ")} is no part of it — ${oe.join(", ")}`]:new Set(e).size!==e.length?['"hud": each part once']:[]}(n.hud)),void 0===n.fps||Number.isInteger(n.fps)&&n.fps>=10&&n.fps<=144||o.push('"fps" is a whole number 10..144');const r=function(e,t){const s=[];if(void 0===e)return{missions:[],problems:s};const o='"missions" lists [{ "name", "title"?, "start"?: a mark, "within"?: seconds, "steps": [{ "do": enter | reach | hit, … }], "music"? }]';if(!Array.isArray(e))return{missions:[],problems:[o]};const n=new Set,r=[],a=e=>"string"==typeof e&&/^[a-z0-9-]+$/.test(e),i=(e,o)=>{if(!Array.isArray(e)||!e.length)return s.push(`${o} is a list of what the music does — cue "do"s ("energy:0.8", "wish:build", "next" …)`),null;for(const n of e){const e=t(n);e&&s.push(`${o}: ${e}`)}return e};for(const[l,u]of e.entries()){const e=`mission ${a(u?.name)?`"${u.name}"`:l+1}`,t=s.length;if("object"!=typeof u||null===u||Array.isArray(u)){s.push(`${e}: ${o}`);continue}a(u.name)?n.has(u.name)?s.push(`${e}: a name only once`):n.add(u.name):s.push(`${e}: a name of lower-case letters, digits and dashes`),void 0===u.title||"string"==typeof u.title&&u.title||s.push(`${e}: "title" is its words — what the HUD shows over its objective`),void 0===u.start||a(u.start)||s.push(`${e}: "start" is a mark of its world — walking into it begins the mission`),void 0===u.within||"number"==typeof u.within&&u.within>0&&u.within<=3600||s.push(`${e}: "within" is the seconds it must be done in, above 0, at most 3600`);const h=u.steps;Array.isArray(h)&&h.length||s.push(`${e}: "steps" lists its objectives in order, at least one: ${Object.entries(X).map(([e,t])=>`"${e}" (${t})`).join("; ")}`);for(const[o,n]of(Array.isArray(h)?h:[]).entries()){const t=`${e} step ${o+1}`;if("string"!=typeof n?.do||!(n.do in X)){s.push(`${t}: "do" is ${Object.keys(X).join(", ")}`);continue}const r={enter:["vehicle"],reach:["mark","by"],hit:["count"]},i=Object.keys(n).filter(e=>"do"!==e&&"say"!==e&&!r[n.do].includes(e));i.length&&s.push(`${t}: "${n.do}" takes ${r[n.do].map(e=>`"${e}"`).join(", ")} and "say" — not ${i.map(e=>`"${e}"`).join(", ")}`),void 0===n.say||"string"==typeof n.say&&n.say||s.push(`${t}: "say" is the words the HUD shows for it`),"enter"!==n.do||void 0===n.vehicle||a(n.vehicle)||s.push(`${t}: "vehicle" is the name of a car or a ship of its world`),"reach"!==n.do||a(n.mark)||s.push(`${t}: "mark" is the mark of its world to reach`),"reach"!==n.do||void 0===n.by||Y.includes(n.by)||s.push(`${t}: "by" is ${Y.join(", ")} — how it is reached`),"hit"!==n.do||Number.isInteger(n.count)&&n.count>=1||s.push(`${t}: "count" is how many targets, 1 or more`)}const c=u.music,d={};if(void 0!==c)if("object"!=typeof c||null===c||Array.isArray(c))s.push(`${e}: "music" is { "start"?, "step"?, "win"?, "lose"?: [do …], "hurry"?: { "at": seconds left, "do": [do …] } }`);else for(const[o,n]of Object.entries(c))if("hurry"===o){const t=n;"object"==typeof t&&null!==t&&"number"==typeof t.at&&t.at>0?void 0===u.within&&s.push(`${e}: music "hurry" wants a time — "within"`):s.push(`${e}: music "hurry" is { "at": the seconds left it comes at, "do": [do …] }`);const o=i(t?.do,`${e}: music "hurry" "do"`);o&&"number"==typeof t?.at&&(d.hurry={at:t.at,do:o})}else if("start"===o||"step"===o||"win"===o||"lose"===o){const t=i(n,`${e}: music "${o}"`);t&&(d[o]=t)}else s.push(`${e}: music "${o}" is none of its moments — ${ee.join(", ")}`);s.length>t||r.push({name:u.name,title:u.title??u.name,start:u.start??null,within:u.within??null,steps:h.map(e=>({...e})),music:d})}return{missions:r,problems:s}}(n.missions,e=>Ae(n,e));o.push(...r.problems),r.missions.length&&!(n.elements??[]).some(e=>"world"===e?.type)&&o.push('"missions" play on a world — the stage has no world element');const a=n.scene??{};if("object"!=typeof a||Array.isArray(a))o.push('"scene" is an object of names and 0..1 values');else for(const[t,m]of Object.entries(a))/^[a-z0-9-]+$/.test(t)||o.push(`scene "${t}": a name of lower-case letters, digits and dashes`),ke(m)||o.push(`scene "${t}": a value 0..1`);if(void 0!==n.knobs)if("object"!=typeof n.knobs||null===n.knobs||Array.isArray(n.knobs))o.push('"knobs" names scene quantities that are a patch\'s knob, { "<quantity>": { "doc": "asset:assets/<its file>", "param": "/<name>/<param>" } }');else for(const[m,p]of Object.entries(n.knobs))"object"==typeof a&&m in a||o.push(`knob "${m}": no scene quantity of that name — add it to "scene"`),"string"==typeof p?.doc&&t(p.doc)||o.push(`knob "${m}": "doc" is the patch, a file of the project ("asset:assets/<name>")`),"string"==typeof p?.param&&/^\/.+\/.+/.test(p.param)||o.push(`knob "${m}": "param" is the full address of the patch's param ("/<name>/<param>", dsp.params.list)`);const i=new Set;for(const[m,p]of n.elements.entries()){const e=`element ${"string"==typeof p?.name?`"${p.name}"`:m+1}`;"string"==typeof p?.name&&/^[a-z0-9-]+$/.test(p.name)?"master"===p.name||"scene"===p.name?o.push(`${e}: the name is the stage's own`):i.has(p.name)?o.push(`${e}: a name only once`):i.add(p.name):o.push(`${e}: a name of lower-case letters, digits and dashes`);const s=le[p?.type];if(s){if(void 0!==p.channels)if(Array.isArray(p.channels)&&p.channels.length)for(const t of p.channels)s.includes(t)||o.push(`${e}: a ${p.type} has no channel "${t}" (${s.join(", ")||"none"})`);else o.push(`${e}: "channels" lists at least one, or is left out for all`);for(const[t,s]of Object.entries(p.start??{}))we(p).includes(t)&&ke(s)||o.push(`${e}: start "${t}" is one of its channels, 0..1`);void 0!==p.sounds&&"world"!==p.type&&o.push(`${e}: "sounds" are a world's — what it tells the music`),"world"===p.type&&("string"==typeof p.src&&t(p.src,".world")||o.push(`${e}: "src" is the world, "asset:assets/<name>.world"`),void 0!==p.sounds&&o.push(...D(p.sounds,e)),void 0===p.at&&void 0===p.aim||o.push(`${e}: a world is the stage's scene — it has no "at" and no "aim"`)),void 0!==p.fov&&"camera"!==p.type&&o.push(`${e}: "fov" is a camera's`),"camera"===p.type&&("world"===p.name&&o.push(`${e}: "world" is the world's own camera — a camera element is named otherwise`),je(p.at)||o.push(`${e}: "at" is where the camera stands, [x, y, z] in metres of the world`),(!je(p.aim)||je(p.at)&&p.aim.every((e,t)=>e===p.at[t]))&&o.push(`${e}: "aim" is the point it looks at, [x, y, z] — not where it stands`),void 0===p.fov||"number"==typeof p.fov&&p.fov>=10&&p.fov<=120||o.push(`${e}: "fov" is its view in degrees, 10..120`)),ie.includes(p.type)&&(je(p.at)||o.push(`${e}: "at" is a 3D point now — [x, y, z] in metres of the world (the dark room's without one: x across, y up, z towards the camera); [x, y] of the picture is no more`),void 0!==p.aim&&"strobe"===p.type?o.push(`${e}: a strobe flashes all round — it has no "aim"`):void 0!==p.aim&&(!je(p.aim)||je(p.at)&&p.aim.every((e,t)=>e===p.at[t]))&&o.push(`${e}: "aim" is where it points, [x, y, z] — not where it hangs`))}else o.push(`${e}: type is one of ${Object.keys(le).join(", ")}`)}if(o.length)return{doc:null,problems:o};const l=n.elements,u={};for(const t of l)ie.includes(t.type)&&(u[t.name]={type:t.type,at:t.at,aim:t.aim??null,channels:[...we(t)],start:t.start});const h={format:"stage",follow:n.follow,...n.controls?{controls:n.controls}:{},...r.missions.length?{missions:r.missions}:{},...n.hud?{hud:n.hud}:{},fps:n.fps,tests:n.tests,story:n.story,cues:n.cues,scene:a,...n.knobs?{knobs:n.knobs}:{},elements:l,fixtures:u},c=new Set($e(h).map(e=>e.path));if(void 0!==n.story){const e=new Set($e(h).map(e=>e.path));Array.isArray(n.story)?n.story.forEach((t,s)=>{const r=`story shot ${s+1}${t?.name?` "${t.name}"`:""}`;"string"==typeof t?.name&&t.name?n.story.findIndex(e=>e?.name===t.name)!==s&&o.push(`${r}: a second shot of that name — each shot is named once (its cues name it)`):o.push(`${r}: "name" is what its cues name`),"number"==typeof t?.bars&&t.bars>0&&t.bars<=128||o.push(`${r}: "bars" is its length, more than 0 and up to 128`);for(const[n,a]of Object.entries(t?.set??{}))e.has(n)&&"number"==typeof a&&a>=0&&a<=1||o.push(`${r}: "set" takes a param of the stage (${n}) at 0..1`);for(const e of["see","camera","via","accept"])void 0===t?.[e]||"string"==typeof t[e]&&t[e]||o.push(`${r}: "${e}" is words — what the screenplay says`);for(const[n,a]of Object.entries(t?.sweep??{}))e.has(n)&&Array.isArray(a)&&2===a.length&&a.every(e=>"number"==typeof e&&e>=0&&e<=1)||o.push(`${r}: "sweep" takes a param of the stage (${n}) and [from, to], each 0..1`)}):o.push('"story" is a list of shots: [{ "name", "bars", "set"?: { "<param>": 0..1 }, "sweep"?: { "<param>": [from, to] } }]')}for(const[t,m]of Object.entries(n.tests??{})){const e=`test "${t}"`;"number"==typeof m?.bars&&m.bars>0||o.push(`${e}: "bars" is how long it is, above 0`),void 0!==m?.loop&&"boolean"!=typeof m.loop&&o.push(`${e}: "loop" is true or false`);const s=m?.keys??{};Object.keys(s).length||o.push(`${e}: "keys" moves at least one parameter`);for(const[t,n]of Object.entries(s))c.has(de(t))?fe(n)||o.push(`${e}: "${t}" is a list of [bar, value 0..1, "linear" | "ease" | "hold"?]`):o.push(`${e}: "${t}" is no parameter of this stage — "<element>.<channel>" or a scene quantity`)}return o.length?{doc:null,problems:o}:{doc:h,problems:[]}}function ze(e,t){const s=/("follow"\s*:\s*)(true|false)/;return s.test(e)?e.replace(s,`$1${t}`):e.replace(/("format"\s*:\s*"stage"\s*,)/,`$1\n "follow": ${t},`)}function Me(e,t,s){const o=Pe.get(e);o&&(null===s?o.seen.delete(t):o.seen.set(t,s))}var Oe=e=>e.driven??performance.now(),Ne=new Map;function Se(e,t){return Ne.set(e,t),()=>{Ne.get(e)===t&&Ne.delete(e)}}function qe(e,t,s,o,n){const r=Ne.get(e);return r?.hit?.(t,s,o,n),!!r}function Fe(e,t,s,o){const n=Ne.get(e);return n?.play?.(t,s,o),!!n}var Ie=n(new Set),Pe=new Map;function We(e,t,s,o){Pe.get(e)?.sound?.(t,s,o)}function Ee(e,t,s){Pe.get(e)?.worldEvents?.(t,s);const n=Ue(e),r=(n?o(n).doc?.missions:void 0)??[],a=s.map(e=>"mission"in e?{...e,title:r.find(t=>t.name===e.mission)?.title??e.mission}:e);u().events.emit("stage.world.event",{stage:e,element:t,events:a})}var De=n(new Map),Te=De;function _e(e,t){De.update(s=>{const o=new Map(s);return t?o.set(e,t):o.delete(e),o})}var Be=new Map;function Ke(e,t){t?Be.set(e,t):Be.delete(e)}function He(e,t=[]){u().events.emit("stage.made",{stage:e,failed:t})}function Ce(e,t){const s=Pe.get(e);if(!s)return!1;const n=o(s.state).world.edit;return s.state.update(e=>({...e,paused:!1,world:{...e.world,spawn:t,edit:!1}})),n&&function(e,t){const{edit:s,selected:o,place:n}=t.world;u().documents.updateModuleMeta(e,{view:s||o||n?{world:{edit:s,selected:o,place:n}}:{}})}(e,o(s.state)),s.fresh?.(),!0}function Je(e,t,s){return Ne.get(e)?.mission?.(t,s)??null}function Ue(e){return Pe.get(e)?.state??null}function Le(t){if(Pe.get(t))return{dispose:()=>{}};const r=(u().documents.listModules().find(e=>e.id===t)?.view)?.world??{},a={edit:!0===r.edit,selected:"string"==typeof r.selected?r.selected:null,place:"string"==typeof r.place?r.place:null,read:0},i=n({doc:null,problems:[],values:{},held:[],rehearsal:null,world:a});let l=[],h=null,m=!1,g=null,y=null;const b=new Set;let w=new Map,v={mode:"follow"},$=0;const k=()=>{const e=Oe(q)/1e3,t={step:u().transport.clock.audibleAbsStep(),bpm:Math.max(1,u().transport.getBpm())},s=o(i).rehearsal;if(s){const o=f(s.clock,e,t);return{beat:$=o.beat??$,bpm:o.bpm}}null!==t.step&&"follow"!==v.mode?v={mode:"follow"}:null===t.step&&"follow"===v.mode?v=function(e,t,s,o,n){if("follow"===t)return{mode:"follow"};const r=f(e,s,o);return p(s,r.beat??n??0,r.bpm)}(v,"free",e,t,$):"free"===v.mode&&v.bpm!==t.bpm&&(v=function(e,t,s,o){return"follow"===e.mode?e:p(t,f(e,t,s).beat??0,o.bpm)}(v,e,t,{bpm:t.bpm}));const n=f(v,e,t);return{beat:$=n.beat??$,bpm:n.bpm}};let j="",A=Promise.resolve(new Map),x=Promise.resolve(new Map);const z=function(e,t){let o={},n=new Map,r=null;const a=()=>{const r=new Map;for(const[a,i]of Object.entries(o)){const o=e.documents.listModules().find(e=>s(e.filePath,i.doc)),l=o?e.params.list(o.id).find(e=>e.path===i.param):void 0;if(!o||!l)continue;t(a,d(l,l.value));const u=n.get(a);if(u?.moduleId===o.id){r.set(a,u);continue}const h=e.params.subscribeValues(o.id,e=>{const s=e.get(i.param);void 0!==s&&t(a,d(l,s))});r.set(a,{moduleId:o.id,off:h})}for(const[e,t]of n)r.get(e)!==t&&t.off();n=r},i=()=>{r?.(),r=null;for(const e of n.values())e.off();n=new Map};return{read(t){if(o=t,!Object.keys(t).length)return i();r??=e.routing.subscribe(a),a()},dispose(){i(),o={}}}}(u(),(e,t)=>q.set?.(ge(e),t)),M=i.subscribe(e=>{const t=e.doc?.elements.find(e=>"world"===e.type&&e.src)?.src,s=t?`${t}|${e.world.read}`:"";if(s===j)return;j=s;const o=t?u().files.readText(t).then(e=>F(e).world?.models??[],()=>[]):Promise.resolve([]);A=o.then(e=>new Map(e.flatMap(e=>e.grab?[[e.name,e.grab]]:[]))),x=o.then(e=>new Map(e.flatMap(e=>e.press?[[e.name,e.press]]:[])))});let O=null;const N=i.subscribe(e=>{const t=nt(e.doc),o=t?u().documents.listModules().find(e=>s(e.filePath,t))?.id??null:null;o!==O&&(O=o,o?u().actions.run("dsp.preset.list",{instance_id:o}).then(e=>O===o&&i.update(t=>({...t,preset:e.standing??null})),()=>{}):i.update(e=>e.preset?{...e,preset:null}:e))}),S=u().events.on("dsp.preset",e=>{e.instance_id===O&&i.update(t=>({...t,preset:e.name}))}),q={id:t,state:i,grabs:()=>A,presses:()=>x,flashed:new Map,ticks:new Map,seen:new Map,dispose:()=>{m=!0,M(),N(),S(),z.dispose(),q.ticks.clear(),E.clear();for(const e of l)e();l=[],h?.(),clearInterval(L),Pe.delete(t)}};Pe.set(t,q);const I=(e,t)=>{w.has(e)&&Number.isFinite(t)&&i.update(s=>({...s,values:{...s.values,[e]:Math.min(1,Math.max(0,t))}}))};q.apply=(e,s)=>{const{doc:n,problems:r}=xe(e);if(!n)return i.update(e=>({...e,problems:r})),o(i).doc||c("Stage").warn(`${s}: ${r.join("; ")}`),r;const a=u(),h=$e(n),d=o(i),m=w;w=new Map(h.map(e=>[e.path,e.init]));const p=Object.fromEntries(h.map(e=>{return[e.path,(t=e.path,d.doc&&t in d.values&&d.values[t]!==m.get(t)?d.values[e.path]:e.init)];var t}));for(const o of d.held)w.has(o)||a.params.hold(t,o,!1);i.set({doc:n,problems:[],values:p,held:d.held.filter(e=>w.has(e)),rehearsal:d.rehearsal,world:d.world,...d.paused?{paused:!0}:{}}),q.set=I,z.read(n.knobs??{});for(const t of l)t();return l=[a.routing.registerSink({id:t,kind:"modulation",document:t,label:`Stage: ${s.replace(/^.*\//,"")} (lights)`,inputs:h.map(e=>({id:e.path,label:e.path}))}),a.modulation.registerParamSink(t,{setParam:(e,s)=>{o(i).held.includes(e)||Ge(t,e)||I(e,s)},getDescriptor:e=>w.has(e)?{min:0,max:1,init:w.get(e)}:null,getValue:e=>o(i).values[e]??null,listPaths:()=>[...w.keys()]})],n.elements.some(e=>e.sounds)&&l.push(a.routing.registerSource({id:t,kind:"midi",label:`Stage: ${s.replace(/^.*\//,"")} (world)`,outputs:[{id:"out",label:"out"}],meta:{kind:"stage"}})),[]};let P=!1,W=null;h=u().transport.subscribePlayers(e=>{const s=P,n=!!o(i).doc?.follow;P=it(e,ut(t))||n&&e.some(e=>e.playing&&e.leads),s||!P||o(i).rehearsal||q.fresh?.({keepHeld:!0});const r=lt(e,ut(t),n),a=r?`${r.name}|${r.role}`:null;if(a!==W&&(W=a,C(r)),s&&!P){q.flashed.clear();for(const e of o(i).held)I(e,u().params.getBase(t,e)??w.get(e)??0);!function(e){for(const t of o(e.state).held)u().params.hold(e.id,t,!1);e.state.update(e=>({...e,held:[]}))}(q),W=null}});const E=new Map,D=(e,t)=>{const s=E.get(e);if(!s)return;const n=s.beats>0?Math.min(1,Math.max(0,(t-s.at)/s.beats)):1;o(i).held.includes(e)||I(e,s.from+(s.to-s.from)*(.5-.5*Math.cos(Math.PI*n))),n>=1&&E.delete(e)},_=e=>{q.told?.(e),K(e.do)},B=(e,t)=>{u().actions.run(e,t).catch(t=>c("Stage").warn(`cue ${e}: ${t instanceof Error?t.message:String(t)}`))},K=e=>{if(e.startsWith("wish:"))B("performer.wish",{kind:e.slice(5)});else if(e.startsWith("energy:"))B("performer.energy.set",{value:Number(e.slice(7))});else if("hold:on"===e||"hold:off"===e)B("performer.hold.set",{on:"hold:on"===e});else if("next"===e)B("performer.next",{});else if(e.startsWith("set:"))(e=>{const t=be.exec(e);if(!t)return;const s=ye(t[1],t[2]),[n,r]=[Number(t[3]),Number(t[4]??0)];E.set(s,{from:o(i).values[s]??n,to:n,at:k().beat,beats:4*r}),D(s,k().beat)})(e);else if(e.startsWith("cut:"))H(e);else if(e.startsWith("dance:")){const t=ce.exec(e)?.[1];t&&i.update(e=>({...e,dance:{move:"mix"===t?null:t.split(","),at:k().beat}}))}},H=e=>{const t=function(e){const t=he.exec(e);return t?{to:t[1],beats:4*Number(t[2]??0),mask:t[3]??"fade"}:null}(e);t&&i.update(e=>({...e,cut:{from:e.cut?.to??"world",...t,at:k().beat}}))},C=e=>{g=e,y=e?{at:k().beat}:null;for(const t of e?(o(i).doc?.cues??[]).filter(t=>ve(t,e)&&!t.bar):[])_(t);b.clear()};q.enter=C;const J=()=>{if(o(i).rehearsal&&function(e){const t=o(e.state).rehearsal;if(!t||!e.set||!e.enter)return;const s=f(t.clock,Oe(e)/1e3,{step:null,bpm:at(t)??120}).beat??0,n=t.parts[t.parts.length-1];if(s>=n.from+4*n.bars)return function(e){const t=o(e.state).rehearsal;e.state.update(e=>({...e,rehearsal:null}));const s=new Set((t?.parts??[]).flatMap(e=>[...Object.keys(e.set??{}),...Object.keys(e.sweep??{})]));for(const n of s)e.set(n,void 0===o(e.state).values[n]?0:$e(o(e.state).doc).find(e=>e.path===n)?.init??0)}(e);let r=t.i;for(;r+1<t.parts.length&&s>=t.parts[r+1].from;)r++;if(r!==t.i){const s=t.parts[r],n=t.parts[r+1],a={name:s.name,role:s.role??s.name,bars:s.bars,next:n?{name:n.name,role:n.role??n.name}:null,...s.chapter?{chapter:s.chapter}:{}};if(t.story){e.settle?.();for(const t of $e(o(e.state).doc))t.path in(s.set??{})||t.path in(s.sweep??{})||e.set(t.path,t.init)}for(const[t,o]of Object.entries(s.set??{}))e.set(t,o);e.state.update(e=>({...e,rehearsal:e.rehearsal&&{...e.rehearsal,i:r,part:a}})),e.enter(a)}const a=t.parts[r];if(!a)return;const i=Math.min(1,(s-a.from)/(4*a.bars));for(const[o,[l,u]]of Object.entries(a.sweep??{}))e.set(o,l+(u-l)*i)}(q),!g||!y)return;const e=(g.bar??0)+(k().beat-y.at)/4;for(const t of o(i).doc?.cues??[])t.bar&&!b.has(t)&&ve(t,g)&&e>=t.bar&&(b.add(t),_(t))},U=()=>{J();const e=k().beat;for(const t of[...E.keys()])D(t,e);for(const t of[...q.ticks.values()])t(e)};q.clockNow=k,q.drive=e=>{q.driven=e??void 0,null===e?v={mode:"follow"}:U()};const L=setInterval(()=>{return void 0===q.driven&&(0===(e=q.seen).size||[...e.values()].some(Boolean))&&U();var e},25);return q.sound=(e,s,n)=>{const r=o(i).doc?.elements.find(t=>t.name===e)?.sounds;if(!r)return;const a=u(),l=a.transport.clock.audibleAbsStep(),h=o(i).rehearsal||null!==u().transport.clock.audibleAbsStep()?k().beat:null,c={now:a.audio.getContext().currentTime,beat:h,bpm:null===h?a.transport.getBpm():k().bpm,grid:null===l||o(i).rehearsal?null:{audible:l,stepTime:e=>a.transport.clock.stepTime(e)}};for(const o of function(e,t,s,o){const n=[],r=15/Math.max(1,o.bpm);for(const a of t){const t=e[a.event];if(void 0===t?.note)continue;const s=t.channel-1,i=T(t.quantise,o),l=Math.max(1,Math.min(127,Math.round(127*a.strength)));n.push(i>o.now?{data:[144|s,t.note,l],time:i}:{data:[144|s,t.note,l]}),n.push({data:[128|s,t.note,0],time:i+r})}for(const[a,i]of Object.entries(s)){const t=e[a];void 0!==t?.cc&&n.push({data:[176|t.channel-1,t.cc,i]})}return n}(r,s,n,c))a.midi.dispatchFromSource(t,o.data,{machine:!0,...void 0===o.time?{}:{time:o.time}})},q.worldEvents=(e,t)=>{const s=c("Stage"),n=o(i).doc?.missions??[];for(const o of t){if("mark"in o){s.info(`${e}: ${o.into?"into":"out of"} the mark ${o.mark} (${o.kind}), ${"foot"===o.by?"on foot":`in a ${o.by}`}`);continue}const t=n.find(e=>e.name===o.mission),r={start:"begins",step:`— objective ${(o.objective??0)+1} of ${t?.steps.length??"?"}`,hurry:`— ${t?.music.hurry?.at??"?"} s left`,win:`won in ${o.took?.toFixed(1)} s`,lose:`lost — the time is up (${o.took?.toFixed(1)} s)`}[o.moment];s.info(`${e}: mission ${o.mission} ${r}`);const a="hurry"===o.moment?t?.music.hurry?.do:t?.music[o.moment];for(const e of a??[])K(e)}},(async()=>{const e=u(),s=e.documents.listModules().find(e=>e.id===t)?.filePath;if(!s)return;let o;try{o=await e.files.readText(s)}catch(n){const e=`${s} could not be read: ${n instanceof Error?n.message:String(n)}`;return c("Stage").error(e),void(m||i.update(t=>({...t,problems:[e]})))}m||q.apply(o,s)})(),q.settle=()=>E.clear(),q.fresh=({keepHeld:s=!1}={})=>{E.clear(),Ze.has(t)&&function(t,s,n=""){const r=Pe.get(t);r?.set||e("That stage is not open or not read yet.");const a=o(r.state).doc,i=Ze.get(t),l=s??!(i&&i.run===n),u=n?a.tests?.[n]:void 0;l&&n&&!u&&e(`No test run "${n}" (${Object.keys(a.tests??{}).join(", ")||'the stage has none — "tests" in the .stage'}).`);if(i){i.stop(),Ze.delete(t);const e=o(r.state),s=new Map($e(a).map(e=>[e.path,e.init])),n=i.run?Object.keys(a.tests?.[i.run]?.keys??{}).map(de):Xe(a);for(const t of n)!e.held.includes(t)&&s.has(t)&&r.set(t,s.get(t))}if(!l)return void Qe();const h=Xe(a),c=r.clockNow?.().beat??0,d=e=>{const s=e-c,n=o(r.state),a=(e,t)=>{!n.held.includes(e)&&e in n.values&&r.set(e,t)};if(!u)return h.forEach((e,t)=>a(e,.5-.5*Math.cos(2*Math.PI*s/(8+5*t))));const i=s/4;for(const[t,o]of Object.entries(function(e,t){return Object.fromEntries(Object.entries(e.keys).map(([e,s])=>[de(e),pe(s,t)]))}(u,u.loop?i%u.bars:Math.min(i,u.bars))))a(t,o);!u.loop&&i>=u.bars&&(r.ticks.delete("test"),Ze.delete(t),Qe())};r.ticks.set("test",d),Ze.set(t,{stop:()=>r.ticks.delete("test"),run:n,paths:new Set(u?Object.keys(u.keys).map(de):h)}),Qe()}(t,!1),q.ticks.delete("test"),[g,y]=[null,null],b.clear(),i.update(e=>({...e,values:Object.fromEntries([...w].map(([t,o])=>[t,s&&e.held.includes(t)?e.values[t]??o:o])),fresh:(e.fresh??0)+1,cut:null,dance:null}))},{dispose:q.dispose}}function Re(e,t,s){const o=Pe.get(e);return o?.apply?o.apply(t,s):["That stage is not open."]}var Ve=n(new Map),Ze=new Map,Ge=(e,t)=>!!Ze.get(e)?.paths.has(t),Qe=()=>Ve.set(new Map([...Ze].map(([e,t])=>[e,t.run])));function Xe(e){return Object.keys(e.scene).map(ge)}function Ye(t,s){const n=Pe.get(t);n||e("That stage is not open.");const r=o(n.state);r.doc?.elements.some(e=>"world"===e.type)||e('The stage has no world to pause ("type": "world" in its elements).'),r.world.edit&&e("The world is being edited — it stands already; stage.world.edit { on: false } plays it.");const a=s??!r.paused;return n.state.update(e=>({...e,paused:a})),a?"Paused: the world stands, its mission's time too; the pause menu lies over the picture (stage.pause { on: false } plays on).":"Playing on."}function et(e){const t=Pe.get(e),s=t?o(t.state).doc?.elements.find(e=>"world"===e.type&&e.src):void 0;return s?{name:s.name,src:s.src}:null}function tt(e,t,s){Pe.get(e)?.set?.(ge(t),s)}async function st(e){return await(Pe.get(e)?.grabs())??null}async function ot(e){return await(Pe.get(e)?.presses())??null}function nt(e){const t=new Set(Object.values(e?.knobs??{}).map(e=>e.doc));return 1===t.size?[...t][0]:null}function rt(e,t,s,o){return Ne.get(e)?.pick?.(t,s,o)??null}function at(e){return e&&"follow"!==e.clock.mode?e.clock.bpm:null}function it(e,t){return!!t&&e.some(e=>e.playing&&e.plays.includes(t))}function lt(e,t,s){return(e.find(e=>e.playing&&!!t&&e.plays.includes(t))??(s?e.find(e=>e.playing&&e.leads):void 0))?.part??null}function ut(e){const t=u().documents.listModules().find(t=>t.id===e)?.filePath;return t?.slice(t.lastIndexOf("/")+1)}var ht=n(null),ct=n(new Map);function dt(){return u().documents.subscribeModules((e,t)=>{ht.update(s=>function(e,t,s){return function(e,t,s,o){const n=t.filter(t=>t.type===e);return s&&n.some(e=>e.id===s)?s:o&&n.some(e=>e.id===o)?o:n[0]?.id??null}("stage",e,t,s)}(e,t,s))})}export{ge as A,L as B,We as C,st as D,dt as E,V as F,u as G,F as H,Q as I,c as K,Z as L,ne as M,te as N,et as O,_ as P,G as R,Me as S,Ee as T,d as U,b as V,m as W,tt as _,Ie as a,Te as b,lt as c,Fe as d,it as f,Ke as g,_e as h,ut as i,ze as j,ot as k,Ye as l,Ce as m,Le as n,qe as o,Se as p,l as q,ht as r,Je as s,Re as t,rt as u,ct as v,Ue as w,nt as x,He as y,U as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./autoLayout-C5ue2K3x.js","./instantiate-Dh0T46aH.js","./src-DyDfRe65.js","./newId-DuoSrkVn.js","./patchSnippets-Dsccmpj6.js","./paths-DFjX1bFA.js","./fileRef-BmnWhXuY.js","./api-BrGhAVvb.js","./faustSource-Blr9zzKL.js","./preArm-ifXM2Buj.js","./src-Co7ihhBK.js","./errors-BdUU2zPt.js","./actionRegistry-hOkUYNvI.js","./toasts-BCcM1yGS.js","./transportFollow-Ox91SKLF.js","./notes-D-zF5qJ1.js","./sha256-B9lHpAF4.js","./runtime-vj8wKnnG.js","./projectFiles-BEdLy3nE.js","./fileMirror-CkgB9zNS.js","./panic-ckha9YOX.js","./runtime-36oA_YiG.js","./dist-DfaMbR-1.js","./dist-BvRk9kiK.js","./playerApp-BmyTSXxw.js","./client-DksDHYQL.js","./disclose-version-BvIhFN19.js","./kit--nsV_OZy.js","./kit-vVQ5cDnW.css","./src-BvHr5YSH.js","./faustwasm.js","./preload-helper-9MKZsTCd.js","./libraryFacts-B_z-Kv6i.js","./time-aboh42pX.js","./scale-D2nqiPek.js","./rocket-CgRnlVoE.js","./soundfiles-DMZ8HKDZ.js","./sun-Bi-OgPry.js","./playerApp-DO80EIpx.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as t}from"./errors-BdUU2zPt.js";import{n as e,o as s,t as i}from"./paths-DFjX1bFA.js";import"./client-DksDHYQL.js";import{t as r}from"./transportFollow-Ox91SKLF.js";import{t as n}from"./newId-DuoSrkVn.js";import{n as o,t as a}from"./panic-ckha9YOX.js";import{D as d,K as u,L as l,S as h,j as p,m as c,pt as m,s as g,z as f}from"./src-DyDfRe65.js";import{a as y,c as k,d as b,f as S,g as w,h as P,i as $,l as v,m as I,n as x,o as N,p as E,r as B,s as T,t as R,u as D}from"./api-BrGhAVvb.js";import{c as M,d as C,f as _,i as j,l as V,n as F,o as O,p as A,r as K,s as L,t as U,u as G,x as z}from"./instantiate-Dh0T46aH.js";import{t as W}from"./preload-helper-9MKZsTCd.js";import{i as H,s as J,t as q}from"./src-BvHr5YSH.js";var Q=class{#t=f(m([]));get nodes(){return d(this.#t)}set nodes(t){l(this.#t,t,!0)}#e=f(m([]));get edges(){return d(this.#e)}set edges(t){l(this.#e,t,!0)}#s=f(null);get polyphonic(){return d(this.#s)}set polyphonic(t){l(this.#s,t,!0)}#i=u(()=>S(this.nodes,this.polyphonic??void 0));get playedVoices(){return d(this.#i)}set playedVoices(t){l(this.#i,t)}#r=u(()=>D(this.nodes,this.edges,this.polyphonic??void 0));get faustSource(){return d(this.#r).source}#n=u(()=>v(this.nodes,this.edges,this.polyphonic??void 0));get structureSource(){return d(this.#n)}get genErrors(){return d(this.#r).errors}get selectedNode(){return this.nodes.find(t=>t.selected)}nextPosition(){if(0===this.nodes.length)return{x:200,y:200};const t=this.nodes[this.nodes.length-1],e=t.measured?.width??t.width??190;return{x:t.position.x+e+60,y:t.position.y}}addNode(t,e){const s=j(t,{position:e?.position??this.nextPosition(),params:e?.params});return s?(this.nodes=[...this.nodes,s],s.id):null}duplicateNode(t){const e=this.nodes.find(e=>e.id===t);if(!e||"builderNode"!==e.type)return null;const s=e.data,i=j(s.kind,{position:{x:e.position.x+40,y:e.position.y+40},params:{...s.paramValues},refs:s.refValues?{...s.refValues}:void 0,bypassed:s.bypassed});return i?(this.nodes=[...this.nodes,i],i.id):null}removeNode(t){if(this.nodes.some(e=>e.id===t&&"builderGroup"===e.type))return this.ungroup(t);const e=this.nodes.length;return this.nodes=this.nodes.filter(e=>e.id!==t),this.edges=this.edges.filter(e=>e.source!==t&&e.target!==t),this.nodes.length<e}connect(t){const e=this.nodes.find(e=>e.id===t.sourceId);if(!e)return{ok:!1,error:`Unknown source node "${t.sourceId}".`};const s=this.nodes.find(e=>e.id===t.targetId);if(!s)return{ok:!1,error:`Unknown target node "${t.targetId}".`};const i=e.data?.kind,r=i?O(i):void 0;if(r&&!r.outputs.some(e=>e.id===t.sourcePort))return{ok:!1,error:`Unknown output port "${t.sourcePort}" on node "${t.sourceId}" (kind "${i}"). Valid outputs: ${r.outputs.map(t=>t.id).join(", ")||"(none)"}. Port ids can differ from their labels — see dsp.kind.describe.`};const o=s.data?.kind,a=o?O(o):void 0;if(a&&!a.inputs.some(e=>e.id===t.targetPort))return{ok:!1,error:`Unknown input port "${t.targetPort}" on node "${t.targetId}" (kind "${o}"). Valid inputs: ${a.inputs.map(t=>t.id).join(", ")||"(none)"}. Port ids can differ from their labels — see dsp.kind.describe.`};const d=n("e"),u=this.edges.find(e=>e.target===t.targetId&&e.targetHandle===t.targetPort)?.id;return this.edges=[...this.edges.filter(t=>t.id!==u),{id:d,source:t.sourceId,sourceHandle:t.sourcePort,target:t.targetId,targetHandle:t.targetPort}],u?{ok:!0,id:d,replaced:u}:{ok:!0,id:d}}disconnect(t){const e=this.edges.length;return this.edges=this.edges.filter(e=>e.id!==t),this.edges.length<e}async autoLayout(){const{autoLayout:t}=await W(async()=>{const{autoLayout:t}=await(import("./autoLayout-C5ue2K3x.js"));return{autoLayout:t}},__vite__mapDeps([0,1,2,3]),import.meta.url);this.nodes=t(this.nodes,this.edges,"LR")}selectNode(t){return!(null!==t&&!this.nodes.some(e=>e.id===t))&&(this.nodes=this.nodes.map(e=>e.selected===(e.id===t)?e:{...e,selected:e.id===t}),!0)}setNodeBypassed(t,e){let s=!1;return this.nodes=this.nodes.map(i=>{if(i.id!==t)return i;s=!0;const r={...i.data,bypassed:e};return{...i,data:r}}),s}createGroup(t,e){const s=new Set(t),i=this.nodes.filter(t=>s.has(t.id)&&"builderNode"===t.type&&!t.parentId);if(0===i.length)return null;let r=1/0,n=1/0,o=-1/0,a=-1/0;for(const p of i){const{w:t,h:e}=this.#o(p);p.position.x<r&&(r=p.position.x),p.position.y<n&&(n=p.position.y),p.position.x+t>o&&(o=p.position.x+t),p.position.y+e>a&&(a=p.position.y+e)}const d=r-24,u=n-24,l=K({position:{x:d,y:u},size:{width:o-r+48,height:a-n+48},label:e}),h=new Set(i.map(t=>t.id));return this.nodes=[l,...this.nodes.map(t=>h.has(t.id)?{...t,parentId:l.id,extent:"parent",position:{x:t.position.x-d,y:t.position.y-u}}:t)],l.id}ungroup(t){const e=this.nodes.find(e=>e.id===t&&"builderGroup"===e.type);if(!e)return!1;const s=e.position.x,i=e.position.y;return this.nodes=this.nodes.filter(e=>e.id!==t).map(e=>{if(e.parentId!==t)return e;const r={...e};return delete r.parentId,delete r.extent,r.position={x:e.position.x+s,y:e.position.y+i},r}),!0}setGroupLabel(t,e){let s=!1;return this.nodes=this.nodes.map(i=>i.id!==t||"builderGroup"!==i.type?i:(s=!0,{...i,data:{...i.data,label:e}})),s}listGroups(){return this.nodes.filter(t=>t.type===U).map(t=>({id:t.id,label:t.data?.label??"Group",memberIds:this.nodes.filter(e=>e.parentId===t.id).map(t=>t.id)}))}#o(t){const e=t.measured;return{w:e?.width??t.width??160,h:e?.height??t.height??90}}},X="fwbpatch",Y=class extends q{warnedPaths=new Set;async compile(t,e=X,s){return super.compile(t,e,s)}started(){this.warnedPaths.clear()}async start(t,e,s,i,r){return this.startOn(t,{getInput:s,beforeConnect:i,pluginParts:e,...r?{partsKey:r}:{},warn:(...t)=>x("FaustEngine").warn(...t)})}setRawOutputListener(t){this.listenToOutputs(t)}getParamValue(t){return this.valueAt(t)??NaN}getParamPaths(){return[...this.params]}resolveParamPath(t){const e=this.worklet;if(!e)return null;if(this.params.has(t)||e.outputs.has(t))return t;const s=t.lastIndexOf("/"),i=s>0?t.lastIndexOf("/",s-1):-1;if(s>0&&i>=0){const r=t.substring(i),n=t.substring(i,s)+"_"+t.substring(s+1);for(const t of this.params)if(t.endsWith(r)||t.endsWith(n))return t;for(const t of e.outputs.keys())if(t.endsWith(r)||t.endsWith(n))return t}return null}setParamValue(t,e,s){if(!this.worklet)return;const i=this.resolveParamPath(t);i?this.worklet.set(i,e,s):this.warnedPaths.has(t)||(this.warnedPaths.add(t),x("FaustEngine").warn(`No matching Faust param for "${t}".`,"Available paths:",this.getParamPaths()))}setNodeParam(t,e,s,i){const r=b(t);this.setParamValue(`/${X}/${r}/${e}`,s,i)}trySetNodeParam(t,e,s){if(!this.worklet)return!1;const i=b(t),r=this.resolveParamPath(`/${X}/${i}/${e}`);return!!r&&(this.worklet.set(r,s),!0)}getNodeParam(t,e){if(!this.worklet)return NaN;const s=b(t),i=this.resolveParamPath(`/${X}/${s}/${e}`);return i?this.getParamValue(i):NaN}},Z=class{deps;#a=null;#d=null;#u=null;constructor(t){this.deps=t}register(){this.teardown(),this.registerParams(),this.#l()}registerParams(){this.#a?.(),this.#d?.();const{engine:t,moduleId:e,title:s}=this.deps,i=R(),r=t.getModulatableParams();this.#a=i.routing.registerSink({id:e,kind:"modulation",label:`Builder: ${s} (params)`,document:e,inputs:r.map(t=>({id:t,label:t}))}),this.#d=i.modulation.registerParamSink(e,J(t,{getBase:t=>this.deps.getParamBase(t),setBase:(t,e)=>this.deps.setParamBase(t,e),subscribeValues:t=>this.deps.subscribeValues(t)}))}#l(){const{engine:t,moduleId:e,modSourceId:s,title:i}=this.deps,r=R(),n=t.getModulationOutputs();if(n.length>0){this.#u=r.routing.registerSource({id:s,kind:"modulation",label:`Builder: ${i} (mod)`,document:e,outputs:n.map(t=>({id:t.address,label:t.label}))});const o=new Set(n.map(t=>t.address));t.setRawOutputListener((t,e)=>{o.has(t)&&r.modulation.setSourceValue(s,t,e)})}}stopKeepSource(){const{engine:t,modSourceId:e}=this.deps;t.setRawOutputListener(null),R().modulation.clearSourceValues(e)}teardown(){this.stopKeepSource(),this.#a?.(),this.#a=null,this.#d?.(),this.#d=null,this.#u?.(),this.#u=null}};var tt=class{moduleId;modSourceId;#h=f("");get title(){return d(this.#h)}set title(t){l(this.#h,t,!0)}#p=f(null);get filePath(){return d(this.#p)}set filePath(t){l(this.#p,t,!0)}#c=f(null);get viewport(){return d(this.#c)}set viewport(t){l(this.#c,t,!0)}modulation;constructor(t){this.moduleId=t,this.modSourceId=`${t}-mod`;const e=R();this.filePath=e.documents.listModules().find(e=>e.id===t)?.filePath??null,this.title=e.documents.resolveModuleTitle(t,{defaultExt:".builder"});const s=e.audio.registerModuleOutput(t,{label:`Builder: ${this.title}`,meta:{kind:"builder"}});this.moduleAudio={node:s.node,unregister:s.unregister},this.modulation=new Z({engine:this.engine,moduleId:t,modSourceId:this.modSourceId,title:this.title,getParamBase:t=>this.getGraphParamBase(t),setParamBase:(t,e)=>this.setGraphParamBase(t,e),subscribeValues:t=>this.liveValues.subscribe(e=>t(e))}),this.engine.onValueUpdate(t=>this.liveValues.set(new Map(t))),this.patchRun=new o(R(),{moduleId:t,sourceKey:()=>this.graph.faustSource,runnable:()=>this.graph.nodes.length>0,eager:()=>this.#m(),idleOnPlay:()=>this.#m()&&!this.hasAudioRouteOut(),listenChannel:()=>w(this.graph.nodes),armedLabel:()=>`Builder MIDI: ${this.title} (armed)`,prewarm:()=>{this.compileIsStale&&this.compile()},start:t=>this.#g(t),release:()=>this.#f(),handleMidi:t=>this.handleMidiMessage(t),stateChanged:t=>{this.runState=t}}),this.#y(),this.#k=e.documents.register(t,this.#b())}#m(){return!I(this.graph.nodes,this.engine.isPolyphonic)||E(this.graph.nodes)}#k=null;#S(){return{label:`Builder: ${this.title}`,meta:{kind:"builder"}}}hasAudioRouteOut(){return r(R().routing.getTable().connections,this.moduleId)}graph=new Q;engine=new Y(()=>this.moduleId,()=>this.title);liveValues=g(new Map);#w=f("stopped");get runState(){return d(this.#w)}set runState(t){l(this.#w,t,!0)}#P=f(null);get cost(){return d(this.#P)}set cost(t){l(this.#P,t,!0)}#$=f("idle");get compileStatus(){return d(this.#$)}set compileStatus(t){l(this.#$,t,!0)}#v=f("");get compileError(){return d(this.#v)}set compileError(t){l(this.#v,t,!0)}#I=f(null);get compiledStructure(){return d(this.#I)}set compiledStructure(t){l(this.#I,t,!0)}#x=f("");get runError(){return d(this.#x)}set runError(t){l(this.#x,t,!0)}async compile(){return this.#N||(this.#N=this.#E().finally(()=>{this.#N=null})),this.#N}#B(){if(this.loadError)return`This patch did not load whole: ${this.loadError}`;const t=this.graph.nodes.filter(t=>t.data?.missing).map(t=>`${t.id} (${t.data.kind})`);return t.length>0?`Not compiled — node(s) of a kind no installed pack has: ${t.join(", ")}. Install the pack (packs.list) or remove them.`:this.graph.genErrors.length>0?`Graph error: ${this.graph.genErrors.join("; ")}`:null}async#E(){const t=this.#B();if(t)return this.compileStatus="error",void(this.compileError=t);const e=this.graph.faustSource,s=this.graph.structureSource;this.compileStatus="compiling",this.compileError="";try{const t=await this.engine.compile(e,void 0,this.graph.playedVoices??void 0);t.ok?(this.compiledStructure=s,this.compileStatus="ok",R().audio.registerModuleInput(this.moduleId,this.engine.getInputChannelCount(),this.#S()),this.modulation.registerParams()):(this.compiledStructure=null,this.compileStatus="error",this.compileError=t.error,x("DSP Builder").error("Compile failed:",t.error))}catch(i){this.compiledStructure=null,this.compileStatus="error",this.compileError=i instanceof Error?i.message:String(i),x("DSP Builder").error("Compile threw:",this.compileError)}}#T=f(m(new Map));get sampleStates(){return d(this.#T)}set sampleStates(t){l(this.#T,t,!0)}getSampleState(t){let e=this.sampleStates.get(t);return e||(e={},this.sampleStates.set(t,e)),e}bumpSampleStates(){this.sampleStates=new Map(this.sampleStates)}seedSampleCacheFromDocument(t){if(t.samples){for(const e of t.samples)this.getSampleState(e.sha256).entry={sha256:e.sha256,filename:e.filename,channels:e.channels,sampleRate:e.sampleRate,durationMs:e.durationMs,sizeBytes:0,importedAt:0};this.bumpSampleStates()}}async detectMissingSamples(t){if(t.samples){for(const e of t.samples){const t=this.getSampleState(e.sha256);try{const s=await R().samples.getBySha(e.sha256);s?(t.entry=s.entry,delete t.missing):t.missing={source:"on-open",meta:e}}catch{t.missing={source:"on-open",meta:e}}}this.bumpSampleStates()}}hydrateFromDocument(t){const e=N(t);for(const s of e.notes)x("DSP Builder").info(`${this.title}: migrated — ${s}`);return e.missing.length&&x("DSP Builder").warn(`${this.title}: ${e.missing.length} node(s) of a kind no installed pack has, kept as placeholders: ${e.missing.join(", ")}`),this.graph.polyphonic=t.polyphonic??null,this.graph.nodes=e.nodes,this.graph.edges=e.edges,this.compiledStructure=null,this.seedSampleCacheFromDocument(t),this.detectMissingSamples(t),this.patchRun.wakeCheck(),this.loadError=e.warnings.length>0?e.warnings.join("; "):"",this.loadError&&(this.#R=null,this.#D(!1)),e.warnings}hydrateFromSource(t){return this.hydrateFromDocument(y(t))}async hydrateFromDisk(){if(!this.hydrated){try{const t=await R().documents.loadDocumentSource(this.moduleId);null!==t&&(await L,this.hydrateFromSource(t),this.hydrated=!0,this.loadError||0!==this.graph.genErrors.length||this.compile())}catch(t){this.loadError=t instanceof Error?t.message:String(t),x("builder").warn(`[builder] hydrating "${this.moduleId}" failed:`,t)}this.loadError||(await this.seedDirtyBaseline(),this.hydrated||this.filePath||await this.saveTo())}}#M=f(!1);get hydrated(){return d(this.#M)}set hydrated(t){l(this.#M,t,!0)}#C=f("");get loadError(){return d(this.#C)}set loadError(t){l(this.#C,t,!0)}#_=f(!1);get dirty(){return d(this.#_)}set dirty(t){l(this.#_,t,!0)}#R=null;#j=null;#V=null;#F(){return null!==this.#V&&(clearTimeout(this.#V),this.#V=null,null!==this.#R&&this.#D(this.graphDirtyKey()!==this.#R)),this.dirty}#O=null;#A=null;#K=null;#L=null;collectSamplesForSave(){const t=new Set,e=[];for(const s of this.graph.nodes){const i=s.data;if("soundfile"!==i?.kind)continue;const r=(i.refValues?.sha256??"").trim();if(!r||t.has(r))continue;t.add(r);const n=this.sampleStates.get(r)?.entry;n&&e.push({sha256:n.sha256,filename:n.filename,channels:n.channels,sampleRate:n.sampleRate,durationMs:n.durationMs})}return e}serializeDocument(t){const e={};return t?.name&&(e.name=t.name),t?.stamp&&(e.modified=(new Date).toISOString()),T(this.graph.nodes,this.graph.edges,e,this.graph.faustSource,this.collectSamplesForSave(),this.graph.polyphonic??void 0)}graphDirtyKey(){const t=T(this.graph.nodes,this.graph.edges,{},void 0,this.collectSamplesForSave(),this.graph.polyphonic??void 0);return t.nodes=[...t.nodes].sort((t,e)=>t.id.localeCompare(e.id)),t.edges=[...t.edges].sort((t,e)=>t.id.localeCompare(e.id)),t.groups&&(t.groups=[...t.groups].sort((t,e)=>t.id.localeCompare(e.id))),t.samples&&(t.samples=[...t.samples].sort((t,e)=>t.sha256.localeCompare(e.sha256))),k(t)}async seedDirtyBaseline(){await p(),this.#R=this.graphDirtyKey(),this.#D(!1)}#D(t){t!==this.dirty&&(this.dirty=t,R().documents.updateModuleMeta(this.moduleId,{dirty:t}))}#y(){this.#K=c(()=>{h(()=>{const t=this.loadError?"error":"compiling"===this.compileStatus?"compiling":"error"===this.compileStatus?"error":"running"===this.runState?"running":"idle";t!==this.#L&&(this.#L=t,R().documents.updateModuleMeta(this.moduleId,{runStatus:t}))}),h(()=>{if(this.graph.nodes,this.graph.edges,this.graph.polyphonic,this.sampleStates,null!==this.#R)return null!==this.#V&&clearTimeout(this.#V),this.#V=setTimeout(()=>{this.#V=null,null!==this.#R&&this.#D(this.graphDirtyKey()!==this.#R)},150),()=>{null!==this.#V&&(clearTimeout(this.#V),this.#V=null)}}),h(()=>{this.dirty&&(this.#j&&clearTimeout(this.#j),this.#j=setTimeout(()=>{this.#j=null,this.saveTo()},800))})})}#U(t){this.filePath=t,this.title=i(t),R().documents.updateModuleMeta(this.moduleId,{filePath:t,title:this.title})}async saveTo(t){if(this.loadError)return{ok:!1,error:`Not saved — this patch did not load whole: ${this.loadError}`};const i=k(this.serializeDocument({stamp:!0})),r=this.graphDirtyKey();let n=null!=t?e(t,".builder"):this.filePath;n||(n=await s(R().project,this.title,".builder"));try{return await R().files.writeText(n,i),this.#U(n),this.#R=r,this.#D(this.graphDirtyKey()!==r),this.#G(n,i),{ok:!0,filePath:n}}catch(o){return this.saveError=`Save failed: ${o.message}`,{ok:!1,error:o.message}}}#z=f("");get saveError(){return d(this.#z)}set saveError(t){l(this.#z,t,!0)}#G(t,e){this.#A={path:t,text:e},this.#O&&clearTimeout(this.#O),this.#O=setTimeout(()=>this.flushReindex(),1e4)}flushReindex(){this.#O&&clearTimeout(this.#O),this.#O=null;const t=this.#A;this.#A=null,t&&this.reindexPatch(t.path,t.text)}async reindexPatch(t,e){try{const{buildPatchSnippet:s}=await W(async()=>{const{buildPatchSnippet:t}=await(import("./patchSnippets-Dsccmpj6.js"));return{buildPatchSnippet:t}},__vite__mapDeps([4,5,6,2,7,8,9,1,3]),import.meta.url),{kbPatchUri:i}=await W(async()=>{const{kbPatchUri:t}=await(import("./src-Co7ihhBK.js"));return{kbPatchUri:t}},__vite__mapDeps([10,11,6,5,2,12,13,3,8,14,15,16,17,18,19,9,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38]),import.meta.url),r=s(i(R().project.current(),t),e);if(!r)return;await R().kb.indexBatch([r])}catch(s){x("builder").warn("Patch KB reindex failed:",s)}}#W(t,e){if("string"!=typeof t||""===t)throw new Error(`${e}: paramId must be a non-empty string, got ${String(t)}`)}orphanedOutputNote(){const t=new Set(this.graph.nodes.filter(t=>{const e=t.data?.kind,s=e?O(e):void 0;return!!s&&0===s.outputs.length}).map(t=>t.id));return 0===t.size||this.graph.edges.some(e=>t.has(e.target))?"":"\nWARNING: the output node has NO incoming connection — the graph compiles but produces SILENCE. Wire your final chain into output in_l/in_r before debugging anything else."}applyParamChange(t,e,s){if(this.#W(e,"applyParamChange"),this.graph.nodes=this.graph.nodes.map(i=>{if(i.id!==t)return i;const r=i.data,n={...r,paramValues:{...r.paramValues,[e]:s}};return{...i,data:n}}),!this.isRunning)return;const i=this.graph.nodes.find(e=>e.id===t)?.data,r=i?O(i.kind):void 0,n=r?.params.find(t=>t.id===e),o="notes"===r?.midi?.listens&&r.midi.channelParam===e;n?.recompileOnChange||o?this.recompileLive():n?.controlPlane||(this.engine.setNodeParam(t,e,s),"clock"!==i?.kind||"transport_link"!==e&&"bpm"!==e||this.syncClockBpm(t))}async recompileLive(){this.isRunning&&(await p(),await this.patchRun.renew())}#b(){const e=this.graph;return{getSource:()=>k(this.serializeDocument({stamp:!0,name:this.moduleId})),setSource:e=>{let s;try{s=y(e)}catch(r){t(`Not a Builder patch: ${r.message}`)}const{warnings:i}=N(s);i.length>0&&t(`Not set — it would lose a part of the patch: ${i.join("; ")}`),this.hydrateFromDocument(s)},getState:()=>({title:this.title,filePath:this.filePath,dirty:this.#F()}),getGraph:()=>({nodes:e.nodes,edges:e.edges}),getSelectedNodeId:()=>e.selectedNode?.id,addNode:(t,s)=>e.addNode(t,s),removeNode:t=>e.removeNode(t),duplicateNode:t=>e.duplicateNode(t),connect:t=>e.connect(t),disconnect:t=>e.disconnect(t),autoLayout:()=>e.autoLayout(),setNodeParam:(s,i,r)=>{const n=e.nodes.find(t=>t.id===s);if(!n)return!1;const o=O(n.data.kind),a=o?.params.find(t=>t.id===i);o&&!a&&t(`${s} (${o.kind}) has no param "${i}" — it has ${o.params.map(t=>t.id).join(", ")||"none"}.`);const d=a?Math.min(a.max??1/0,Math.max(a.min??-1/0,r)):r;return this.applyParamChange(s,i,d),!0},getNodeParam:(t,s)=>{if(!this.isRunning||!e.nodes.some(e=>e.id===t))return null;const i=this.engine.getNodeParam(t,s);return Number.isNaN(i)?null:i},setNodeRef:(t,s,i)=>!!e.nodes.some(e=>e.id===t)&&(this.applyRefChange(t,s,i),this.isRunning&&this.recompileLive(),!0),selectNode:t=>e.selectNode(t),setNodeBypassed:(t,s)=>{const i=e.setNodeBypassed(t,s);return i&&this.isRunning&&this.recompileLive(),i},getFaustSource:()=>e.faustSource,pluginParts:async t=>{const e=this.#B();if(e)return{ok:!1,error:e};try{return{ok:!0,parts:await this.pluginPartsNow(t)}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}},compile:async()=>{if(this.isRunning?await this.recompileLive():await this.compile(),"ok"!==this.compileStatus)return{ok:!1,error:this.compileError||"compile failed"};const t=this.orphanedOutputNote();return t?{ok:!0,note:t}:{ok:!0}},run:async()=>{if(await this.run(),"running"!==this.runState)return{ok:!1,error:this.runError||"run failed"};const t=this.orphanedOutputNote();return t?{ok:!0,note:t}:{ok:!0}},stop:async()=>this.stop(),getEngineState:()=>({running:this.isRunning,compiled:this.engine.hasCompiled,status:"compiling"===this.compileStatus?"compiling":"error"===this.compileStatus?"error":this.isRunning?"running":"idle",compile_error:"error"===this.compileStatus?this.compileError:"",params:[],polyphonic:null!==e.polyphonic,transport_follow:R().transport.followsTransport(this.moduleId),cost:this.isRunning&&this.cost?{ms_per_block:this.cost.msPerBlock,share:this.cost.share}:null}),save:t=>this.saveTo(t),exportDoc:()=>this.serializeDocument({stamp:!0,name:this.moduleId}),importDoc:t=>{try{const e="string"==typeof t?y(t):t,{warnings:s}=N(e);return s.length>0?{ok:!1,error:s.join("; ")}:(this.hydrateFromDocument(e),{ok:!0})}catch(e){return{ok:!1,error:e.message}}},createGroup:(t,s)=>e.createGroup(t,s),ungroup:t=>e.ungroup(t),setGroupLabel:(t,s)=>e.setGroupLabel(t,s),listGroups:()=>e.listGroups(),getPolyphonic:()=>e.polyphonic,setPolyphonic:async t=>{(null===e.polyphonic?null!==t:null===t||e.polyphonic.voices!==t.voices)&&(e.polyphonic=t,await p(),this.isRunning&&await this.stop())},setMidiChannel:t=>{if(!Number.isInteger(t)||t<0||t>16)return{ok:!1,error:`MIDI channel must be an integer 0–16, got ${t}.`};const s=e.nodes.map(t=>{const e=O(t.data?.kind??"")?.midi;return"notes"===e?.listens&&e.channelParam?{id:t.id,param:e.channelParam}:null}).filter(t=>null!==t);if(0===s.length)return{ok:!1,error:'Nothing in this Builder listens to notes — add a node that does (e.g. builder.graph.node.add { kind: "midi_note" } for a synth, "midi_key" per drum voice for a kit).'};for(const e of s)this.applyParamChange(e.id,e.param,t);const i=0===t?"Omni (any channel)":`channel ${t}`;return{ok:!0,message:1===s.length?`MIDI input now listening on ${i}.`:`MIDI input on ${s.length} note-listening nodes now listening on ${i}.`}},setFollowTransport:t=>R().transport.setFollowsTransport(this.moduleId,t)?(this.patchRun.followChanged(),{ok:!0,message:t?"Now following the global transport (the project keeps it).":"Now independent of the global transport (the project keeps it) — use the local RUN button."}):{ok:!0,message:t?"Already following the global transport.":"Already independent of the global transport."}}}pluginPartsNow(t={}){return H(X,this.graph.faustSource,this.graph.playedVoices?.voices??null,()=>this.soundfileBuffers(R().audio.getContext()),t)}samplesKey(){return this.graph.nodes.flatMap(t=>{const e=t.data;return"soundfile"===e?.kind?[`${t.id}:${(e.refValues?.sha256??"").trim()}`]:[]}).sort().join("|")}async soundfileBuffers(t){const e={};let s=!1;for(const i of this.graph.nodes){const r=i.data;if("soundfile"!==r?.kind)continue;const n=(r.refValues?.sha256??"").trim();if(!n)continue;const o=this.getSampleState(n);if(!o.buffer){const e=await R().samples.getBySha(n);if(!e){o.missing={source:"on-compile"},s=!0;continue}o.entry=e.entry,delete o.missing,o.buffer=await t.decodeAudioData(e.bytes),s=!0}e[`sf_${b(i.id)}`]=o.buffer}return s&&this.bumpSampleStates(),e}get isRunning(){return"running"===this.runState}pushStoredParams(){for(const t of this.graph.nodes){const e=t.data;if(!e?.kind)continue;const s=O(e.kind);if(s)for(const i of s.params){if("soundfile"===i.type||i.controlPlane||i.recompileOnChange)continue;const s=e.paramValues?.[i.id];if(void 0===s||!Number.isFinite(s))continue;const r=i.port??`${i.id}_in`;if(this.graph.edges.some(e=>e.target===t.id&&e.targetHandle===r))continue;const n=Math.min(i.max??1,Math.max(i.min??0,s));this.engine.trySetNodeParam(t.id,i.id,n)}}for(const t of this.graph.nodes)"clock"===t.data?.kind&&this.syncClockBpm(t.id)}#H=new Map;#J=null;resolveAddressToNodeParam(t){this.#J!==this.graph.nodes&&(this.#H.clear(),this.#J=this.graph.nodes);const e=this.#H.get(t);if(void 0!==e)return e;let s=null;t:for(const i of this.graph.nodes){const e=b(i.id);for(const r of[`/${e}/`,`/${e}_`]){const e=t.lastIndexOf(r);if(e<0)continue;const n=t.slice(e+r.length),o=i.data;if(O(o?.kind)?.params.some(t=>t.id===n)){s={nodeId:i.id,paramId:n};break t}}}return this.#H.set(t,s),s}getGraphParamBase(t){const e=this.resolveAddressToNodeParam(t);if(!e)return null;const s=this.graph.nodes.find(t=>t.id===e.nodeId)?.data,i=s?.paramValues?.[e.paramId];if("number"==typeof i&&Number.isFinite(i))return i;const r=s?.kind?O(s.kind)?.params.find(t=>t.id===e.paramId):void 0;return r?r.init:null}setGraphParamBase(t,e){const s=this.resolveAddressToNodeParam(t);return!!s&&(this.graph.nodes=this.graph.nodes.map(t=>{if(t.id!==s.nodeId)return t;const i=t.data;return{...t,data:{...i,paramValues:{...i.paramValues,[s.paramId]:e}}}}),!0)}syncClockBpm(t){if(!this.isRunning)return;const e=this.graph.nodes.find(e=>e.id===t)?.data;if("clock"!==e?.kind)return;const s=(e.paramValues?.transport_link??0)>.5,i=s?R().transport.getBpm():e.paramValues?.bpm??120;this.#q.get(t)!==i&&(this.#q.set(t,i),s||this.engine.setNodeParam(t,"bpm",i),s&&e.paramValues?.bpm!==i&&(this.graph.nodes=this.graph.nodes.map(e=>{if(e.id!==t)return e;const s=e.data,r={...s,paramValues:{...s.paramValues,bpm:i}};return{...e,data:r}})))}handleTransport(){if(this.isRunning)for(const t of this.graph.nodes)"clock"===t.data?.kind&&this.syncClockBpm(t.id)}handleMidiMessage(t){!function(t,e){const{running:s,nodes:i,engine:r}=e;s&&0!==t.data.length&&P(i,t)&&r.sendMidi(t.data,t.time)}(t,{running:this.isRunning,nodes:this.graph.nodes,engine:this.engine})}get compileIsStale(){return null===this.compiledStructure||this.compiledStructure!==this.graph.structureSource}moduleAudio=null;midiUnsub=null;transportUnsub=null;#q=new Map;#N=null;patchRun;async run(){await this.patchRun.run()}async stop(){await this.patchRun.stop()}async#g(t){if(this.runError="",this.compileIsStale){if(await this.compile(),!t.current())return!1;if("ok"!==this.compileStatus)return this.runError=this.compileError||"Compile failed",!1}const e=this.moduleAudio?.node;if(!e)return this.runError="No audio output registered for this document.",!1;try{const s=await this.engine.start(e,()=>this.pluginPartsNow(),async t=>R().audio.registerModuleInput(this.moduleId,t,this.#S()),()=>this.pushStoredParams(),async()=>this.samplesKey());if(this.cost=this.engine.cost,!s)return!1;if(!t.current()){try{await this.engine.stop()}catch{}return!1}if(!t.live()){try{await this.engine.stop()}catch{}return!1}this.pushStoredParams(),this.modulation.register();const i=I(this.graph.nodes,this.engine.isPolyphonic);return this.midiUnsub?.(),this.midiUnsub=R().midi.onMessage(t=>this.handleMidiMessage(t),{sinkId:`${this.moduleId}:midi-in`,label:`Builder MIDI: ${this.title}`,...i?{isAudible:!0,priority:"user-loaded"}:{},allNotesOff:()=>function(t){const{running:e,nodes:s,engine:i}=t;e&&a(i,{holdsKeys:()=>s.some(t=>{const e=t.data?.kind;return!!e&&"notes"===O(e)?.midi?.listens}),listen:w(s)})}({running:this.isRunning,nodes:this.graph.nodes,engine:this.engine})}),this.transportUnsub?.(),this.#q.clear(),this.transportUnsub=R().transport.subscribe(()=>this.handleTransport()),!0}catch(s){this.runError=s.message,this.midiUnsub?.(),this.midiUnsub=null,this.transportUnsub?.(),this.transportUnsub=null,this.modulation.teardown(),this.modulation.registerParams();try{await this.engine.stop()}catch{}return!1}}async#f(){this.midiUnsub?.(),this.midiUnsub=null,this.transportUnsub?.(),this.transportUnsub=null,this.modulation.stopKeepSource(),this.engine.allNotesOff();try{await this.engine.stop()}catch(t){x("DSP Builder").warn("engine stop failed",t)}}applyRefChange(t,e,s){this.#W(e,"applyRefChange"),this.graph.nodes=this.graph.nodes.map(i=>{if(i.id!==t)return i;const r=i.data;return{...i,data:{...r,refValues:{...r.refValues??{},[e]:s}}}}),s&&R().samples.getBySha(s).then(t=>{t&&(this.getSampleState(s).entry=t.entry,this.bumpSampleStates())}),this.runError=""}dispose(){this.#j&&(clearTimeout(this.#j),this.#j=null),this.#F()&&this.saveTo().then(t=>{t.ok||R().messages.notify({kind:"error",title:`${this.title} was closed with unsaved edits`,description:t.error,durationMs:0})}),this.flushReindex(),this.#K?.(),this.#K=null,this.#k?.(),this.#k=null,this.patchRun.dispose(),this.midiUnsub?.(),this.midiUnsub=null,this.transportUnsub?.(),this.transportUnsub=null,this.modulation.teardown(),this.engine.dispose().catch(t=>x("DSP Builder").error("the engine could not be let go:",t)),this.moduleAudio?.unregister(),this.moduleAudio=null}},et=new Map;var st=t=>{try{const e=JSON.parse(t);return e&&"object"==typeof e?e:null}catch{return null}};var it={id:"builder",label:"Builder",icon:"Grid3x3",description:"Empty node graph in the Builder module.",fileExtensions:[".builder"],sounds:!0,compiles:!0,createRuntime:t=>(function(t){let e=et.get(t);return e||(e=new tt(t),et.set(t,e)),e}(t).hydrateFromDisk(),{dispose:()=>{!function(t){const e=et.get(t);!!e&&(e.dispose(),et.delete(t))}(t)}}),fxSource:t=>{try{const e=JSON.parse(t);return"string"==typeof e.compiledSource?e.compiledSource:null}catch{return null}},samplesOf:t=>(JSON.parse(t).samples??[]).map(t=>t?.sha256).filter(t=>"string"==typeof t&&""!==t),patchOf:function(t){const e=st(t);return e&&"builder"===e.format&&"string"==typeof e.compiledSource?{source:e.compiledSource,takesInput:!0===e.isFx,nodes:Array.isArray(e.nodes)?e.nodes.length:0}:null},instrumentOf:function(t){const e=st(t);if(!e)return"is not a readable builder patch";const s=(e.graph?.nodes??e.nodes??[]).filter(t=>"midi_key"===t.kind);if(!s.length)return"has no midi_key — nothing in it answers a note";const i=[...new Set(s.map(t=>t.params?.channel??1))];return i.length>1?`hears channels ${i.join(", ")} — an instrument hears one`:{channel:i[0],notes:[...new Set(s.map(t=>t.params?.note??60))].sort((t,e)=>t-e)}}},rt=new Set(["audio","control","trigger"]),nt=new Set(["hslider","vslider","nentry","button","checkbox"]),ot=new Map([["soundfile","soundfile params are not supported in node packs — the slot mechanism only recognises the built-in `soundfile` node, so the param would compile to silence and its sample reference would be dropped on save"]]),at=new Set(["volume","cutoff","pitch","drive","mix"]),dt=new Set(["detune","cutoff","none"]);function ut(t){if(!t||"object"!=typeof t)return!1;const e=t;return!(void 0!==e.channels&&("number"!=typeof e.channels||!Number.isInteger(e.channels)||e.channels<1))&&("string"==typeof e.id&&"string"==typeof e.label&&"string"==typeof e.kind&&rt.has(e.kind))}function lt(t){if(!t||"object"!=typeof t)return!1;const e=t;if("string"!=typeof e.id||"string"!=typeof e.label||"string"!=typeof e.type||!nt.has(e.type)||"number"!=typeof e.init)return!1;if(void 0!==e.smoothing_class&&!at.has(e.smoothing_class))return!1;if(void 0!==e.velocity_responds){const t=e.velocity_responds;if("number"!=typeof t||!Number.isFinite(t)||t<0||t>1)return!1}return!0}function ht(t){const e=[];return t.scale&&e.push(`[scale:${t.scale}]`),t.style&&e.push(`[style:${t.style}]`),t.unit&&e.push(`[unit:${t.unit}]`),t.tooltip&&e.push(`[tooltip:${t.tooltip}]`),0===e.length?"":` ${e.join("")}`}var pt={detune:.2,cutoff:1.5,none:0},ct={detune:"freq",cutoff:"cutoff",none:null};function mt(t,e,s,i){if(!s||"none"===s)return t;if(!i||i.voices<=1)return t;if("button"===e.type||"checkbox"===e.type||"soundfile"===e.type)return t;const r=ct[s];if(null===r||r!==e.id)return t;const n=pt[s];return n<=0?t:`(${t} * (1 + (no.noises(${i.voices}, i) : fi.lowpass(1, 0.5) * sqrt(ma.SR / (ma.PI * 0.5))) * ${n/100}))`}function gt(t,e,s,i,r,n){return!s||s<=0?t:i?"button"===e||"checkbox"===e||"soundfile"===e?t:`(${t} + (${i}) * ${s} * (${n} - (${t})))`:t}function ft(t,e,s,i){if(!s)return t;if("button"===e||"checkbox"===e||"soundfile"===e)return t;const r=_[s]/1e3;return i?`(${t} : si.polySmooth(button("gate"), ba.tau2pole(${r}), 1))`:`(${t} : si.smooth(ba.tau2pole(${r})))`}function yt(t,e){const s=function(t,e,s){const i={},r=e.inputs.velocity_in;for(const n of t){const t=n.port??`${n.id}_in`,o=e.inputs[t];if(o){i[n.id]=o;continue}const a=n.min??0,d=n.max??1,u=e.params[n.id]??n.init,l=Math.min(d,Math.max(a,u)),h=n.step??.001,p=ht(n),c=`${e.faustId}/${n.id}${p}`;let m;switch(n.type){case"button":m=`button("${c}")`;break;case"checkbox":m=`checkbox("${c}")`;break;case"hslider":m=`hslider("${c}", ${l}, ${a}, ${d}, ${h})`;break;case"vslider":m=`vslider("${c}", ${l}, ${a}, ${d}, ${h})`;break;case"nentry":m=`nentry("${c}", ${l}, ${a}, ${d}, ${h})`;break;case"soundfile":m=`/* soundfile param ${n.id} (sha=${e.refs[n.id]??"?"}) */`;break;default:m=`${l}`}const g=gt(mt(m,n,s?.drift_param,e.unisonConfig),n.type,n.velocity_responds,r,0,d);i[n.id]=ft(g,n.type,n.smoothing_class,!!e.polyMode)}return i}(t.params,e,{drift_param:t.drift_param}),i={};for(const[l,h]of Object.entries(e.inputs))i[l]=h||"0";const r={};for(const l of t.params){const t=e.params[l.id];r[l.id]="number"==typeof t&&Number.isFinite(t)?t:l.init}const n={};for(const[l,h]of Object.entries(s))n[l]=z(h,{inputs:0,outputs:1});const o={},a=t=>({params:n,inputs:i,defs:t,literals:r,faustId:e.faustId});if(t.toBox.defs)for(const[l,h]of Object.entries(t.toBox.defs))o[l]=A(h,a(o));const d=a(o),u={};if(0===t.outputs.length)u[C]=A(t.toBox.outputs[C],d);else for(const l of t.outputs)u[l.id]=A(t.toBox.outputs[l.id],d);return u}function kt(t){const e=function(t){if(!t||"object"!=typeof t)return{ok:!1,error:"kind is not an object"};const e=t;if("string"!=typeof e.kind||!e.kind)return{ok:!1,error:"missing `kind` (string)"};if("string"!=typeof e.label)return{ok:!1,error:`kind "${e.kind}": missing \`label\` (string)`};if(void 0!==e.category&&("string"!=typeof e.category||!e.category))return{ok:!1,error:`kind "${e.kind}": \`category\` must be a non-empty string when present`};if(void 0!==e.drift_param&&!dt.has(e.drift_param))return{ok:!1,error:`kind "${e.kind}": unknown drift_param "${e.drift_param}" — expected 'detune' | 'cutoff' | 'none'`};if(!Array.isArray(e.inputs)||!e.inputs.every(ut))return{ok:!1,error:`kind "${e.kind}": \`inputs\` must be PortDef[]`};if(!Array.isArray(e.outputs)||!e.outputs.every(ut))return{ok:!1,error:`kind "${e.kind}": \`outputs\` must be PortDef[]`};if(Array.isArray(e.params))for(const r of e.params){const t=ot.get(String(r?.type));if(t)return{ok:!1,error:`kind "${e.kind}", param "${String(r?.id)}": ${t}.`}}if(!Array.isArray(e.params)||!e.params.every(lt))return{ok:!1,error:`kind "${e.kind}": \`params\` must be ParamDef[]`};if(!e.toBox||"object"!=typeof e.toBox)return{ok:!1,error:`kind "${e.kind}": missing \`toBox\` object`};const s=e.toBox;if(!s.outputs||"object"!=typeof s.outputs)return{ok:!1,error:`kind "${e.kind}": missing \`toBox.outputs\``};const i=e.outputs;if(0===i.length){if("string"!=typeof s.outputs.__process)return{ok:!1,error:`kind "${e.kind}": sink kind needs \`toBox.outputs.__process\``}}else for(const r of i)if("string"!=typeof s.outputs[r.id])return{ok:!1,error:`kind "${e.kind}": \`toBox.outputs.${r.id}\` missing or not a string`};if(void 0!==s.defs){if("object"!=typeof s.defs||null===s.defs)return{ok:!1,error:`kind "${e.kind}": \`toBox.defs\` must be object`};for(const[t,i]of Object.entries(s.defs))if("string"!=typeof i)return{ok:!1,error:`kind "${e.kind}": \`toBox.defs.${t}\` not a string`}}if(void 0!==e.bypass&&(!e.bypass||"object"!=typeof e.bypass||"string"!=typeof e.bypass.input||"string"!=typeof e.bypass.output))return{ok:!1,error:`kind "${e.kind}": \`bypass\` must be { input, output }`};if(void 0!==e.imports){if(!Array.isArray(e.imports))return{ok:!1,error:`kind "${e.kind}": \`imports\` must be string[]`};for(const t of e.imports)if("string"!=typeof t||!t.endsWith(".lib"))return{ok:!1,error:`kind "${e.kind}": \`imports\` entry "${String(t)}" must be a string ending in ".lib"`}}return{ok:!0}}(t);if(!e.ok)return{ok:!1,error:e.error};const s=t;return{ok:!0,def:{kind:s.kind,label:s.label,description:s.description,category:s.category,wraps:s.wraps,midi:s.midi,inputs:s.inputs,outputs:s.outputs,params:s.params,bypass:s.bypass,bodyStyle:s.bodyStyle,drift_param:s.drift_param,imports:s.imports,toBox:t=>yt(s,t)}}}var bt=new Set;function St(t){B(t);const e=x("DSP Builder");async function s(s){const i=await t.nodes.getPack(s).catch(()=>null);if(!i)return;G(s);let r=0,n=0;for(const t of i.kinds){const i=kt(t);i.ok&&i.def?V(s,i.def)?r++:e.warn(`Pack "${s}": kind "${i.def.kind}" conflicts with existing registration; skipped.`):(n++,e.warn(`Pack "${s}": skipping invalid kind — ${i.error}`))}r+n>0&&e.info(`Pack "${s}" v${i.version}: registered ${r} kind(s)`+(n>0?`, ${n} invalid`:""))}return async function(){try{const e=await t.nodes.listInstalledPacks();for(const t of e)await s(t.packId)}catch(i){e.warn("Failed to load installed node-packs:",i)}}().finally(M),t.nodes.subscribe(async t=>{"installed"===t.type||"bundled-restored"===t.type?await s(t.packId):"uninstalled"===t.type&&(G(t.packId),e.info(`Pack "${t.packId}" uninstalled — kinds dropped from registry.`));for(const e of bt)await e()}),t.extensions.registerDocumentKind(it)}export{St as activateBuilderRuntime};
|