hayao 0.2.0 → 0.3.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.
Files changed (69) hide show
  1. package/README.md +113 -24
  2. package/bin/create-hayao.mjs +380 -0
  3. package/bin/hayao-mcp-cli.mjs +11 -0
  4. package/dist/app/browser.d.ts +33 -2
  5. package/dist/app/game.d.ts +47 -2
  6. package/dist/app/tuning.d.ts +68 -0
  7. package/dist/art/palette.d.ts +41 -0
  8. package/dist/audio/adaptive.d.ts +58 -0
  9. package/dist/audio/album.d.ts +16 -0
  10. package/dist/audio/analysis.d.ts +59 -0
  11. package/dist/audio/audio.d.ts +21 -0
  12. package/dist/audio/chord.d.ts +17 -0
  13. package/dist/audio/genres.d.ts +11 -0
  14. package/dist/audio/lint.d.ts +29 -0
  15. package/dist/audio/match.d.ts +38 -0
  16. package/dist/audio/music.d.ts +88 -0
  17. package/dist/audio/pcm.d.ts +54 -0
  18. package/dist/audio/quality.d.ts +28 -0
  19. package/dist/audio/reverb.d.ts +15 -0
  20. package/dist/audio/synth.d.ts +56 -0
  21. package/dist/audio/theory.d.ts +64 -0
  22. package/dist/content/campaign.d.ts +69 -0
  23. package/dist/content/generate.d.ts +78 -0
  24. package/dist/content/level.d.ts +93 -0
  25. package/dist/content/worldgraph.d.ts +73 -0
  26. package/dist/core/dmath.d.ts +2 -0
  27. package/dist/hayao.global.js +15 -0
  28. package/dist/index.d.ts +30 -1
  29. package/dist/index.js +4293 -434
  30. package/dist/index.js.map +4 -4
  31. package/dist/index.min.js +15 -0
  32. package/dist/input/source.d.ts +52 -1
  33. package/dist/mcp.js +31225 -0
  34. package/dist/rasterize-worker-lite.mjs +13 -0
  35. package/dist/render/canvas.d.ts +6 -1
  36. package/dist/render/commands.d.ts +46 -0
  37. package/dist/render/paint.d.ts +33 -0
  38. package/dist/render/renderer.d.ts +22 -0
  39. package/dist/render/svg.d.ts +4 -1
  40. package/dist/render/svgString.d.ts +6 -2
  41. package/dist/scene/cameraController.d.ts +42 -0
  42. package/dist/scene/node.d.ts +17 -4
  43. package/dist/scene/nodes.d.ts +14 -0
  44. package/dist/scene/parallax.d.ts +15 -0
  45. package/dist/studio/mcpMain.d.ts +1 -0
  46. package/dist/studio/mcpServer.d.ts +2 -0
  47. package/dist/studio/record.d.ts +54 -0
  48. package/dist/studio/run.d.ts +78 -0
  49. package/dist/studio/session.d.ts +80 -0
  50. package/dist/studio/timeline.d.ts +35 -0
  51. package/dist/studio/vitePlugin.d.ts +6 -0
  52. package/dist/studio-plugin.js +228 -0
  53. package/dist/ui/overlay.d.ts +6 -0
  54. package/dist/verify/audioFilmstrip.d.ts +39 -0
  55. package/dist/verify/ethnography.d.ts +67 -0
  56. package/dist/verify/gates.d.ts +160 -0
  57. package/dist/verify/layout.d.ts +30 -3
  58. package/dist/verify/ramp.d.ts +40 -0
  59. package/dist/world.d.ts +38 -2
  60. package/dist-studio/assets/index-C7tty_Wo.js +109 -0
  61. package/dist-studio/assets/index-CM3tjRQo.css +1 -0
  62. package/dist-studio/index.html +18 -0
  63. package/docs/API.md +233 -9
  64. package/docs/CONVENTIONS.md +223 -0
  65. package/docs/EMBED.md +85 -0
  66. package/docs/QUICKSTART.md +129 -0
  67. package/docs/STUDIO.md +97 -0
  68. package/docs/VERIFICATION.md +226 -0
  69. package/package.json +39 -6
@@ -0,0 +1,15 @@
1
+ var Ko=.6366197723675814,Yo=1.5707963267341256,Xo=6077100506506192e-26,Qo=-.16666666666666632,Zo=.00833333333332249,ei=-.0001984126982985795,ti=27557313707070068e-22,ni=-25050760253406863e-24,ri=158969099521155e-24,oi=.0416666666666666,ii=-.001388888888887411,si=2480158728947673e-20,ai=-27557314351390663e-23,li=2087572321298175e-24,ui=-11359647557788195e-27;function wt(t){let e=t*t;return t+t*e*(Qo+e*(Zo+e*(ei+e*(ti+e*(ni+e*ri)))))}function kt(t){let e=t*t;return 1-.5*e+e*e*(oi+e*(ii+e*(si+e*(ai+e*(li+e*ui)))))}function Wn(t){let e=Math.round(t*Ko),n=t-e*Yo-e*Xo;return{n:(e%4+4)%4,r:n}}function _(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=Wn(t);switch(e){case 0:return wt(n);case 1:return kt(n);case 2:return-wt(n);default:return-kt(n)}}function Q(t){if(!Number.isFinite(t))return NaN;let{n:e,r:n}=Wn(t);switch(e){case 0:return kt(n);case 1:return-wt(n);case 2:return-kt(n);default:return wt(n)}}var vt=[.4636476090008061,.7853981633974483,.982793723247329,1.5707963267948966],zn=[22698777452961687e-33,3061616997868383e-32,13903311031230998e-33,6123233995736766e-32],ye=[.3333333333333293,-.19999999999876483,.14285714272503466,-.11111110405462356,.09090887133436507,-.0769187620504483,.06661073137387531,-.058335701337905735,.049768779946159324,-.036531572744216916,.016285820115365782];function ci(t){if(Number.isNaN(t))return NaN;if(!Number.isFinite(t))return t>0?vt[3]:-vt[3];let e=t<0||Object.is(t,-0)?-1:1,n=Math.abs(t);if(n>=1e19)return e*(vt[3]+zn[3]);let r=-1;if(n<.4375){if(n<1e-9)return t}else n<.6875?(r=0,n=(2*n-1)/(2+n)):n<1.1875?(r=1,n=(n-1)/(n+1)):n<2.4375?(r=2,n=(n-1.5)/(1+1.5*n)):(r=3,n=-1/n);let o=n*n,i=o*o,s=o*(ye[0]+i*(ye[2]+i*(ye[4]+i*(ye[6]+i*(ye[8]+i*ye[10]))))),a=i*(ye[1]+i*(ye[3]+i*(ye[5]+i*(ye[7]+i*ye[9]))));if(r<0)return e*(n-n*(s+a));let l=vt[r]-(n*(s+a)-zn[r]-n);return e*l}var Se=3.141592653589793;function ll(t,e){if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(t===0&&e===0)return Object.is(e,-0)?Object.is(t,-0)?-Se:Se:Object.is(t,-0)?-0:0;if(e===0||!Number.isFinite(t)&&Number.isFinite(e))return t>0?Se/2:-Se/2;if(!Number.isFinite(e)){if(!Number.isFinite(t)){let r=e>0?Se/4:3*Se/4;return t>0?r:-r}return e>0?t<0||Object.is(t,-0)?-0:0:t<0||Object.is(t,-0)?-Se:Se}let n=ci(t/e);return e>0?n:t<0||Object.is(t,-0)?n-Se:n+Se}var mi=.6931471805599453;function he(t){if(Number.isNaN(t))return NaN;if(t>=1024)return 1/0;if(t<=-1075)return 0;let e=Math.round(t),n=(t-e)*mi,r=1,o=1;for(let i=1;i<=13;i++)r=r*n/i,o+=r;return o*2**e}function Oe(t){return he(t*On)}function Z(t,e){return Math.sqrt(t*t+e*e)}var Le=new DataView(new ArrayBuffer(8)),di=.6931471803691238,pi=19082149292705877e-26;function Bn(t){if(Number.isNaN(t)||t<0)return NaN;if(t===0)return-1/0;if(!Number.isFinite(t))return 1/0;Le.setFloat64(0,t);let e=(Le.getUint32(0)>>>20&2047)-1023;e===-1023&&(Le.setFloat64(0,t*0x40000000000000),e=(Le.getUint32(0)>>>20&2047)-1023-54),Le.setUint32(0,Le.getUint32(0)&1048575|1023<<20);let n=Le.getFloat64(0);n>1.4142135623730951&&(n*=.5,e+=1);let r=(n-1)/(n+1),o=r*r,i=1+o*(.3333333333333333+o*(.2+o*(.14285714285714285+o*(.1111111111111111+o*(.09090909090909091+o*(.07692307692307693+o*(.06666666666666667+o*(.058823529411764705+o*.05263157894736842))))))));return e*di+(2*r*i+e*pi)}var hi=.4342944819032518,On=1.4426950408889634,St=t=>Bn(t)*hi,rn=t=>Bn(t)*On;function Pe(t,e){if(Number.isNaN(t)||Number.isNaN(e))return NaN;if(e===0)return 1;if(e===1)return t;if(Number.isInteger(e)&&Math.abs(e)<=1024){let n=Math.abs(e),r=t,o=1;for(;n>0;)n&1&&(o*=r),n>>=1,n>0&&(r*=r);return e<0?1/o:o}return t>0?he(e*rn(t)):t===0?e>0?0:1/0:NaN}var ml=(t=0,e=0)=>({x:t,y:e}),dl=(t,e)=>({x:t.x+e.x,y:t.y+e.y}),pl=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),hl=(t,e)=>({x:t.x*e,y:t.y*e}),fl=(t,e)=>t.x*e.x+t.y*e.y,fi=t=>Z(t.x,t.y),bl=(t,e)=>Z(t.x-e.x,t.y-e.y);function gl(t){let e=fi(t);return e===0?{x:0,y:0}:{x:t.x/e,y:t.y/e}}var K=(t,e,n)=>t<e?e:t>n?n:t,Ee=(t,e,n)=>t+(e-t)*n,Gn=(t,e,n)=>t===e?0:(n-t)/(e-t),yl=(t,e,n,r,o)=>Ee(r,o,Gn(e,n,t)),Vn=(t,e,n)=>{let r=K(t===e?n<t?0:1:Gn(t,e,n),0,1);return r*r*(3-2*r)},se=Math.PI*2,xl=t=>t*Math.PI/180,vl=t=>t*180/Math.PI;function wl(t,e){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h}function kl(t,e){return t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y}var le={a:1,b:0,c:0,d:1,e:0,f:0};function et(t,e){return{a:t.a*e.a+t.c*e.b,b:t.b*e.a+t.d*e.b,c:t.a*e.c+t.c*e.d,d:t.b*e.c+t.d*e.d,e:t.a*e.e+t.c*e.f+t.e,f:t.b*e.e+t.d*e.f+t.f}}function Mt(t,e,n){let r=Q(e),o=_(e);return{a:r*n.x,b:o*n.x,c:-o*n.y,d:r*n.y,e:t.x,f:t.y}}function on(t,e){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function sn(t){let e=t.a*t.d-t.b*t.c;if(e===0)return{...le};let n=1/e;return{a:t.d*n,b:-t.b*n,c:-t.c*n,d:t.a*n,e:(t.c*t.f-t.d*t.e)*n,f:(t.b*t.e-t.a*t.f)*n}}function bi(t){let e=t>>>0;return()=>{e=e+2654435769>>>0;let n=e;return n=Math.imul(n^n>>>16,569420461),n=Math.imul(n^n>>>15,1935289751),(n^n>>>15)>>>0}}var ce=class t{s0;s1;s2;s3;constructor(e=0){if(typeof e=="number"){let n=bi(e===0?305441741:e);this.s0=n(),this.s1=n(),this.s2=n(),this.s3=n()}else[this.s0,this.s1,this.s2,this.s3]=e.s}next(){let e=Math.imul(this.rotl(Math.imul(this.s1,5),7),9)>>>0,n=this.s1<<9>>>0;return this.s2^=this.s0,this.s3^=this.s1,this.s1^=this.s2,this.s0^=this.s3,this.s2=(this.s2^n)>>>0,this.s3=this.rotl(this.s3,11),e>>>0}rotl(e,n){return(e<<n|e>>>32-n)>>>0}float(){return this.next()/4294967296}range(e,n){return e+this.float()*(n-e)}int(e){return Math.floor(this.float()*e)}intRange(e,n){return e+this.int(n-e+1)}chance(e){return this.float()<e}pick(e){return e[this.int(e.length)]}shuffle(e){for(let n=e.length-1;n>0;n--){let r=this.int(n+1);[e[n],e[r]]=[e[r],e[n]]}return e}split(e=0){let n=(this.s0^Math.imul(e+1,2654435769))>>>0,r=new t(n^this.s3);return this.next(),r}getState(){return{s:[this.s0,this.s1,this.s2,this.s3]}}setState(e){[this.s0,this.s1,this.s2,this.s3]=e.s}};function qn(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}var Ct=class{stepMs;dt;maxFrameMs;accumulator=0;_frame=0;_simTimeMs=0;constructor(e={}){let n=e.hz??60;this.stepMs=1e3/n,this.dt=1/n,this.maxFrameMs=e.maxFrameMs??250}advance(e){this.accumulator+=Math.min(e,this.maxFrameMs);let n=0;for(;this.accumulator>=this.stepMs;)this.accumulator-=this.stepMs,n++;return n}tick(){this._frame++,this._simTimeMs+=this.stepMs}get alpha(){return this.accumulator/this.stepMs}get frame(){return this._frame}get simTimeMs(){return this._simTimeMs}get simTimeSec(){return this._simTimeMs/1e3}getState(){return{accumulator:this.accumulator,frame:this._frame,simTimeMs:this._simTimeMs}}setState(e){this.accumulator=e.accumulator,this._frame=e.frame,this._simTimeMs=e.simTimeMs}};var tt=class{listeners=[];connect(e){return this.listeners.push(e),()=>this.disconnect(e)}once(e){let n=this.connect(r=>{n(),e(r)});return n}disconnect(e){let n=this.listeners.indexOf(e);n>=0&&this.listeners.splice(n,1)}emit(e){for(let n of this.listeners.slice())n(e)}get count(){return this.listeners.length}clear(){this.listeners.length=0}},Tt=class{signals=new Map;signalFor(e){let n=this.signals.get(e);return n||(n=new tt,this.signals.set(e,n)),n}on(e,n){return this.signalFor(e).connect(n)}once(e,n){return this.signalFor(e).once(n)}emit(e,n){this.signalFor(e).emit(n)}clear(){this.signals.clear()}};function gi(t){return Number.isNaN(t)?"NaN":t===1/0?"Inf":t===-1/0?"-Inf":t===0?"0":t.toString()}function Rt(t){let e=2166136261,n=2166136261,r=s=>{for(let a=0;a<s.length;a++){let l=s.charCodeAt(a);e=Math.imul(e^l,16777619)>>>0,n=Math.imul(n^(l<<3|l>>>5),2246822519)>>>0}},o=s=>{if(s===null)return r("n");if(s===void 0)return r("u");switch(typeof s){case"number":return r("#"+gi(s));case"boolean":return r(s?"t":"f");case"string":return r('"'+s);case"object":{if(Array.isArray(s)){r("[");for(let u of s)o(u);r("]");return}let a=s,l=Object.keys(a).filter(u=>a[u]!==void 0).sort();r("{");for(let u of l)r(u+":"),o(a[u]);r("}");return}default:r("?")}};o(t);let i=s=>s.toString(16).padStart(8,"0");return i(e)+i(n)}var jn=0;function Hn(t=0){jn=t}var j=class{id;name;type="Node";pos;rotation;scale;z;visible;cosmetic=!1;parent=null;children=[];world=null;onUpdate;behaviors=[];signals=new Map;_ready=!1;_freed=!1;constructor(e={}){this.id=`n${jn++}`,this.name=e.name??this.constructor.name,this.pos=e.pos?{...e.pos}:{x:0,y:0},this.rotation=e.rotation??0,this.scale=e.scale?{...e.scale}:{x:1,y:1},this.z=e.z??0,this.visible=e.visible??!0}addChild(e){return e.parent=this,this.children.push(e),this.world&&this._ready&&e.enterTree(this.world),e}removeChild(e){let n=this.children.indexOf(e);n>=0&&(this.children.splice(n,1),e.parent=null)}free(){this.world?.requestFree(this)}find(e){if(this.name===e)return this;for(let n of this.children){let r=n.find(e);if(r)return r}return null}query(e,n=[]){this.type===e&&n.push(this);for(let r of this.children)r.query(e,n);return n}addBehavior(e){return this.behaviors.push(e),this._ready&&e.ready?.(this),this}signal(e){let n=this.signals.get(e);return n||(n=new tt,this.signals.set(e,n)),n}emit(e,n){this.signals.get(e)?.emit(n)}enterTree(e){if(this.world=e,!this._ready){this._ready=!0,this.onReady();for(let n of this.behaviors)n.ready?.(this)}for(let n of this.children)n.enterTree(e)}updateTree(e){if(this._freed)return;let n=this.world;for(let r of this.behaviors)r.update?.(this,e,n);this.onUpdate?.(this,e,n),this.onProcess(e);for(let r of this.children.slice())r.updateTree(e)}exitTree(){for(let e of this.behaviors)e.exit?.(this);this.onExit();for(let e of this.children.slice())e.exitTree();this._freed=!0}get isFreed(){return this._freed}localTransform(){return Mt(this.pos,this.rotation,this.scale)}worldTransform(){let e=this.localTransform();return this.parent?et(this.parent.worldTransform(),e):e}collectDraw(e,n=le){if(!this.visible)return;let r=et(n,this.localTransform());this.draw(e,r);for(let o of this.children)o.collectDraw(e,r)}draw(e,n){}onReady(){}onProcess(e){}onExit(){}serialize(){return{type:this.type,name:this.name,pos:{...this.pos},rotation:this.rotation,scale:{...this.scale},z:this.z,visible:this.visible,props:this.serializeProps(),children:this.children.filter(e=>!e.cosmetic).map(e=>e.serialize())}}serializeProps(){return{}}applyProps(e){}};var Pt=class extends j{type="Sprite";shape;paint;constructor(e){super(e),this.shape=e.shape,this.paint={fill:e.fill,stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity,round:e.round,gradient:e.gradient,shadow:e.shadow}}draw(e,n){let r=this.paint,o={transform:n,z:this.z,...r};switch(this.shape.kind){case"rect":{let i=this.shape.anchor==="topLeft";e.push({kind:"rect",x:i?0:-this.shape.w/2,y:i?0:-this.shape.h/2,w:this.shape.w,h:this.shape.h,r:this.shape.r,...o});break}case"circle":e.push({kind:"circle",cx:0,cy:0,radius:this.shape.radius,...o});break;case"poly":e.push({kind:"poly",points:this.shape.points,closed:this.shape.closed??!0,...o});break;case"path":e.push({kind:"path",d:this.shape.d,...o});break;case"glyph":e.push({kind:"text",text:this.shape.char,x:0,y:0,size:this.shape.size,align:"center",...o});break}}serializeProps(){return{shape:this.shape,paint:this.paint}}applyProps(e){e.shape&&(this.shape=e.shape),e.paint&&(this.paint=e.paint)}},Dt=class extends j{type="Text";text;size;font;align;weight;paint;constructor(e){super(e),this.text=e.text,this.size=e.size??24,this.font=e.font,this.align=e.align??"left",this.weight=e.weight,this.paint={fill:e.fill??"#000",stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity}}draw(e,n){e.push({kind:"text",text:this.text,x:0,y:0,size:this.size,font:this.font,align:this.align,weight:this.weight,transform:n,z:this.z,...this.paint})}serializeProps(){return{text:this.text,size:this.size,align:this.align,paint:this.paint}}applyProps(e){typeof e.text=="string"&&(this.text=e.text),typeof e.size=="number"&&(this.size=e.size),e.align&&(this.align=e.align),e.paint&&(this.paint=e.paint)}},It=class extends j{type="Camera2D";zoom;current;constructor(e={}){super(e),this.zoom=e.zoom??1,this.current=e.current??!0}onReady(){this.current&&(this.world.activeCamera=this)}serializeProps(){return{zoom:this.zoom,current:this.current}}applyProps(e){typeof e.zoom=="number"&&(this.zoom=e.zoom),typeof e.current=="boolean"&&(this.current=e.current)}},Et=class extends j{type="Timer";duration;oneShot;remaining;running;constructor(e){super(e),this.duration=e.duration,this.oneShot=e.oneShot??!0,this.remaining=e.duration,this.running=e.autostart??!0}start(e){e!==void 0&&(this.duration=e),this.remaining=this.duration,this.running=!0}stop(){this.running=!1}get timeLeft(){return this.remaining}onProcess(e){this.running&&(this.remaining-=e,this.remaining<=0&&(this.emit("timeout",void 0),this.oneShot?this.running=!1:this.remaining+=this.duration))}get timeout(){return this.signal("timeout")}serializeProps(){return{duration:this.duration,oneShot:this.oneShot,remaining:this.remaining,running:this.running}}applyProps(e){typeof e.duration=="number"&&(this.duration=e.duration),typeof e.oneShot=="boolean"&&(this.oneShot=e.oneShot),typeof e.remaining=="number"&&(this.remaining=e.remaining),typeof e.running=="boolean"&&(this.running=e.running)}};var _n=class extends j{type="CameraController";cosmetic=!0;target;cameraRef;deadzone;smooth;bounds;constructor(e={}){super(e),this.target=e.target??null,this.cameraRef=e.camera??null;let n=e.deadzone??0;this.deadzone=typeof n=="number"?{x:n,y:n}:{...n},this.smooth=e.smooth??.15,this.bounds=e.bounds?{...e.bounds}:null}follow(e){return this.target=e,this}host(){return this.world??null}camera(){return this.cameraRef??this.host()?.activeCamera??null}desired(e){let n=this.host(),r=this.target.worldTransform(),o=e.pos.x,i=e.pos.y,s=r.e-e.pos.x,a=r.f-e.pos.y;if(Math.abs(s)>this.deadzone.x&&(o=r.e-Math.sign(s)*this.deadzone.x),Math.abs(a)>this.deadzone.y&&(i=r.f-Math.sign(a)*this.deadzone.y),this.bounds){let l=e.zoom||1,u=n.width/2/l,c=n.height/2/l,m=this.bounds.minX+u,d=this.bounds.maxX-u,p=this.bounds.minY+c,h=this.bounds.maxY-c;o=m>d?(this.bounds.minX+this.bounds.maxX)/2:K(o,m,d),i=p>h?(this.bounds.minY+this.bounds.maxY)/2:K(i,p,h)}return{x:o,y:i}}snap(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e);e.pos.x=n.x,e.pos.y=n.y}onReady(){this.snap()}onProcess(){let e=this.camera();if(!e||!this.target||!this.host())return;let n=this.desired(e),r=K(this.smooth,0,1);e.pos.x=Ee(e.pos.x,n.x,r),e.pos.y=Ee(e.pos.y,n.y,r)}};var Jn=class extends j{type="ParallaxLayer";cosmetic=!0;factor;constructor(e){super(e),this.factor=e.factor}sync(){let e=this.world?.activeCamera;e&&(this.pos.x=e.pos.x*(1-this.factor),this.pos.y=e.pos.y*(1-this.factor))}onReady(){this.sync()}onProcess(){this.sync()}};var Un=class{constructor(e,n){this.parent=e;this.make=n}parent;make;items=[];used=0;begin(){this.used=0}get(){this.used===this.items.length&&this.items.push(this.parent.addChild(this.make()));let e=this.items[this.used++];return e.visible=!0,e}end(){for(let e=this.used;e<this.items.length;e++)this.items[e].visible=!1}get liveCount(){return this.used}};var Vl=(t,e,n,r)=>Ee(e,t,Oe(-n*r)),yi=(t=0)=>({value:t,vel:0});function xi(t,e,n,r){let o=Oe(-n*r),i=t.value-e,s=t.vel+n*i;return t.value=e+(i+s*r)*o,t.vel=(t.vel-s*n*r)*o,t}function ql(t=0,e=.25){let n=4/Math.max(1e-4,e),r=yi(t);return(o,i)=>xi(r,o,n,i).value}var Kn=t=>t*t,an=t=>t*t*t,Yn={linear:t=>t,quadIn:t=>t*t,quadOut:t=>1-(1-t)*(1-t),quadInOut:t=>t<.5?2*t*t:1-Kn(-2*t+2)/2,cubicIn:t=>t*t*t,cubicOut:t=>1-an(1-t),cubicInOut:t=>t<.5?4*t*t*t:1-an(-2*t+2)/2,sineIn:t=>1-Q(t*Math.PI/2),sineOut:t=>_(t*Math.PI/2),sineInOut:t=>-(Q(Math.PI*t)-1)/2,backOut:t=>1+2.70158*an(t-1)+1.70158*Kn(t-1),elasticOut:t=>{let e=2*Math.PI/3;return t===0?0:t===1?1:he(-10*t)*_((t*10-.75)*e)+1},bounceOut:t=>t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},Ft=class extends j{type="AnimationPlayer";tracks=[];to(e,n,r,o,i="cubicOut",s={}){return this.tracks.push({apply:e,from:n,to:r,duration:Math.max(1e-6,o),elapsed:0,ease:typeof i=="function"?i:Yn[i]??Yn.linear,delay:s.delay??0,onDone:s.onDone}),this}get active(){return this.tracks.length>0}get finished(){return this.signal("finished")}onProcess(e){if(this.tracks.length!==0){for(let n=this.tracks.length-1;n>=0;n--){let r=this.tracks[n];if(r.delay>0){r.delay-=e;continue}r.elapsed+=e;let o=K(r.elapsed/r.duration,0,1);r.apply(r.from+(r.to-r.from)*r.ease(o)),o>=1&&(r.onDone?.(),this.tracks.splice(n,1))}this.tracks.length===0&&this.emit("finished",void 0)}}};var Xn=class extends j{type="Particles";pool=[];rng;maxParticles;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ce(e.seed??7),this.maxParticles=e.maxParticles??512}burst(e,n,r){let o=this.rng;for(let i=0;i<e;i++){let s=r.angle!==void 0?r.angle+(o.float()-.5)*(r.spread??.6):o.float()*se,a=r.speedMin+o.float()*(r.speedMax-r.speedMin),l={x:n.x,y:n.y,vx:Q(s)*a,vy:_(s)*a,life:0,maxLife:r.lifeMin+o.float()*(r.lifeMax-r.lifeMin),size:r.sizeMin+o.float()*(r.sizeMax-r.sizeMin),color:r.colors[o.int(r.colors.length)]};this.pool.length>=this.maxParticles&&this.pool.shift(),this.pool.push(l)}this.gravity=r.gravity??0,this.drag=r.drag??0,this.shrink=r.shrink??!0}gravity=0;drag=0;shrink=!0;onProcess(e){let n=Math.max(0,1-this.drag*e),r=0;for(let o of this.pool)o.life+=e,!(o.life>=o.maxLife)&&(o.vy+=this.gravity*e,o.vx*=n,o.vy*=n,o.x+=o.vx*e,o.y+=o.vy*e,this.pool[r++]=o);this.pool.length=r}draw(e,n){for(let r of this.pool){let o=1-r.life/r.maxLife;e.push({kind:"circle",cx:r.x,cy:r.y,radius:this.shrink?r.size*o:r.size,fill:r.color,opacity:Math.min(1,o*2),transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},Kl={dust:(t=["#c8c2b6","#a09a8c"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:30,speedMax:90,lifeMin:.2,lifeMax:.45,gravity:300,drag:3,shrink:!0}),burst:(t=["#ffd75e","#ff9d47","#fff2c9"])=>({colors:t,sizeMin:2,sizeMax:5,speedMin:120,speedMax:320,lifeMin:.25,lifeMax:.6,drag:4,shrink:!0}),hit:(t=["#ff5e5e","#ffd0d0"])=>({colors:t,sizeMin:2,sizeMax:4,speedMin:160,speedMax:380,lifeMin:.15,lifeMax:.35,drag:6,shrink:!0}),sparkle:(t=["#9ef7ff","#e8fdff","#4ed8e8"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,speedMin:20,speedMax:70,lifeMin:.4,lifeMax:.9,gravity:-40,drag:2,shrink:!0})};function vi(t,e){if(e.length===0)return 1;if(t<=e[0].time)return e[0].intensity;for(let n=1;n<e.length;n++)if(t<=e[n].time){let r=e[n-1],o=e[n];return r.intensity+(o.intensity-r.intensity)*Vn(r.time,o.time,t)}return e[e.length-1].intensity}var Qn=class extends j{type="AmbientField";rng;field=[];time=0;style;width;height;envelope;constructor(e){super(e),this.cosmetic=!0,this.rng=new ce(e.seed??11),this.width=e.width,this.height=e.height,this.style=e.style,this.envelope=e.envelope;let n=e.count??120,r=this.style;for(let o=0;o<n;o++)this.field.push({x:this.rng.float()*this.width,y:this.rng.float()*this.height,size:r.sizeMin+this.rng.float()*(r.sizeMax-r.sizeMin),color:r.colors[this.rng.int(r.colors.length)],phase:this.rng.float()*se,depth:.5+this.rng.float()*.5})}intensity(){return this.envelope?vi(this.time,this.envelope):1}onProcess(e){this.time+=e;let n=this.style,r=n.windX??0,o=this.width,i=this.height;for(let s of this.field)s.y+=n.fallY*s.depth*e,s.x+=r*e,s.y>i?s.y-=i:s.y<0&&(s.y+=i),s.x>o?s.x-=o:s.x<0&&(s.x+=o)}draw(e,n){let r=this.style,o=this.intensity();if(o<=0)return;let i=Math.round(this.field.length*o),s=r.swayAmp??0,a=r.swayFreq??0;for(let l=0;l<i;l++){let u=this.field[l],c=s!==0?_(this.time*a*se+u.phase)*s:0,m=u.x+c;if(r.streak){let d=r.streakLen??r.fallY*.03;e.push({kind:"poly",points:[m,u.y,m,u.y+d],closed:!1,stroke:u.color,strokeWidth:u.size,opacity:o,transform:n,z:this.z,transient:!0})}else e.push({kind:"circle",cx:m,cy:u.y,radius:u.size,fill:u.color,opacity:o,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.field.length}},Yl={snow:(t=["#ffffff","#e8f0f8","#cdd9e6"])=>({colors:t,sizeMin:1.5,sizeMax:3.5,windX:8,fallY:42,swayAmp:14,swayFreq:.25}),rain:(t=["#9fb4c8","#c3d2e0"])=>({colors:t,sizeMin:1,sizeMax:1.8,windX:-40,fallY:620,streak:!0,streakLen:16}),ash:(t=["#6b6b6b","#8a8580","#3d3a36"])=>({colors:t,sizeMin:1,sizeMax:2.5,windX:14,fallY:26,swayAmp:20,swayFreq:.18})},Zn=class extends j{type="Shaker";rng;trauma=0;amplitude;decay;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ce(e.seed??99),this.amplitude=e.amplitude??14,this.decay=e.decay??2.6}addTrauma(e){this.trauma=Math.min(1,this.trauma+e)}onProcess(e){this.trauma=Math.max(0,this.trauma-this.decay*e);let n=this.trauma*this.trauma*this.amplitude;this.pos.x=(this.rng.float()*2-1)*n,this.pos.y=(this.rng.float()*2-1)*n}};var er=class extends j{type="FloatingText";pool=[];rng;maxPopups;constructor(e={}){super(e),this.cosmetic=!0,this.rng=new ce(e.seed??31),this.maxPopups=e.maxPopups??128}pop(e,n,r){let o=r.jitter??0,i={x:n.x+(this.rng.float()-.5)*o*.1,y:n.y,vx:(this.rng.float()-.5)*o,vy:-(r.rise??60),life:0,maxLife:Math.max(.05,r.life??.9),text:e,color:r.color,size:r.size??20,font:r.font,weight:r.weight,align:r.align??"center",fade:K(r.fade??.4,0,1)};this.gravity=r.gravity??0,this.pool.length>=this.maxPopups&&this.pool.shift(),this.pool.push(i)}gravity=0;onProcess(e){let n=0;for(let r of this.pool)r.life+=e,!(r.life>=r.maxLife)&&(r.vy+=this.gravity*e,r.x+=r.vx*e,r.y+=r.vy*e,this.pool[n++]=r);this.pool.length=n}draw(e,n){for(let r of this.pool){let o=r.life/r.maxLife,i=1-r.fade,s=o<i?1:K(1-(o-i)/Math.max(1e-4,r.fade),0,1);e.push({kind:"text",text:r.text,x:r.x,y:r.y,size:r.size,font:r.font,weight:r.weight,align:r.align,fill:r.color,opacity:s,transform:n,z:this.z,transient:!0})}}get liveCount(){return this.pool.length}},tu={damage:(t="#e14b4b")=>({color:t,size:22,weight:700,rise:70,gravity:120,life:.8,jitter:40,fade:.4}),crit:(t="#ffb020")=>({color:t,size:32,weight:800,rise:100,gravity:160,life:1,jitter:60,fade:.35}),heal:(t="#4bb06a")=>({color:t,size:20,weight:700,rise:55,gravity:40,life:1,jitter:20,fade:.5}),label:(t="#3d3323")=>({color:t,size:18,weight:600,rise:40,gravity:0,life:1.2,jitter:0,fade:.5})};var tr=new Map;function Ge(t,e){tr.set(t,e)}Ge("Node",()=>new j);Ge("Sprite",()=>new Pt({shape:{kind:"rect",w:1,h:1}}));Ge("Text",()=>new Dt({text:""}));Ge("Camera2D",()=>new It);Ge("Timer",()=>new Et({duration:1}));Ge("AnimationPlayer",()=>new Ft);function ln(t){let e=tr.get(t.type);if(!e)throw new Error(`hayao: unknown node type "${t.type}" (register it first)`);let n=e();n.name=t.name,n.pos={...t.pos},n.rotation=t.rotation,n.scale={...t.scale},n.z=t.z,n.visible=t.visible,n.applyProps(t.props);for(let r of t.children)n.addChild(ln(r));return n}var Nt=class{down=new Set;prev=new Set;axes=new Map;beginFrame(e){this.prev=new Set(this.down),this.down=new Set(e)}isDown(e){return this.down.has(e)}justPressed(e){return this.down.has(e)&&!this.prev.has(e)}justReleased(e){return!this.down.has(e)&&this.prev.has(e)}axis(e){return this.axes.get(e)??0}snapshot(){return[...this.down].sort()}getState(){return{down:[...this.down].sort(),prev:[...this.prev].sort()}}setState(e){this.down=new Set(e.down),this.prev=new Set(e.prev)}};function rr(t,e){let n=[];for(let r in t)t[r].some(o=>e.has(o))&&n.push(r);return n.sort()}var nr=class{frames=[];record(e){this.frames.push(e.slice().sort())}get length(){return this.frames.length}toLog(){return{frames:this.frames.map(e=>e.slice())}}};function nt(t,e){return t.frames[e]??[]}var un={up:["ArrowUp","KeyW"],down:["ArrowDown","KeyS"],left:["ArrowLeft","KeyA"],right:["ArrowRight","KeyD"],confirm:["Enter","Space"],cancel:["Escape","Backspace"],action:["KeyZ","KeyJ"],action2:["KeyX","KeyK"],undo:["KeyU"],restart:["KeyR"]};var Ve=class{keysDown=new Set;pressed=new Set;map;target;onDown;onUp;onBlur;constructor(e,n=document){this.map=e,this.target=n,this.onDown=r=>{this.keysDown.add(r.code),(r.code.startsWith("Arrow")||r.code==="Space")&&r.preventDefault()},this.onUp=r=>this.keysDown.delete(r.code),this.onBlur=()=>this.keysDown.clear(),n.addEventListener("keydown",this.onDown),n.addEventListener("keyup",this.onUp),globalThis.addEventListener?.("blur",this.onBlur)}currentActions(){let e=rr(this.map,this.keysDown);if(this.pressed.size===0)return e;let n=new Set(e);for(let r of this.pressed)n.add(r);return[...n].sort()}press(e){this.pressed.add(e)}clearPressed(){this.pressed.clear()}setMap(e){this.map=e}dispose(){this.target.removeEventListener("keydown",this.onDown),this.target.removeEventListener("keyup",this.onUp),globalThis.removeEventListener?.("blur",this.onBlur)}},$t=class{clientX=0;clientY=0;isDown=!1;seen=!1;target;el;onMove;onDown;onUp;constructor(e){this.target=e,this.el=e.element,this.onMove=n=>{this.clientX=n.clientX,this.clientY=n.clientY,this.seen=!0},this.onDown=n=>{this.clientX=n.clientX,this.clientY=n.clientY,this.isDown=!0,this.seen=!0},this.onUp=()=>{this.isDown=!1},this.el?.addEventListener("pointermove",this.onMove),this.el?.addEventListener("pointerdown",this.onDown),globalThis.addEventListener?.("pointerup",this.onUp),globalThis.addEventListener?.("pointercancel",this.onUp)}read(){let e=this.target.toDesign?.(this.clientX,this.clientY)??{x:0,y:0};return{x:e.x,y:e.y,down:this.isDown,active:this.seen}}sample(e){let n=this.read(),r=o=>Math.round(o*8)/8;e.axes.set("pointer.x",r(n.x)),e.axes.set("pointer.y",r(n.y)),e.axes.set("pointer.down",n.down?1:0)}dispose(){this.el?.removeEventListener("pointermove",this.onMove),this.el?.removeEventListener("pointerdown",this.onDown),globalThis.removeEventListener?.("pointerup",this.onUp),globalThis.removeEventListener?.("pointercancel",this.onUp)}};var H={EMPTY:0,SOLID:1,ONEWAY:2,HAZARD:3},or={"#":H.SOLID,"-":H.ONEWAY,"^":H.HAZARD};function ir(t,e=32,n=or){let r=t.length,o=Math.max(...t.map(s=>s.length)),i=new Array(o*r).fill(H.EMPTY);return t.forEach((s,a)=>{for(let l=0;l<s.length;l++)i[a*o+l]=n[s[l]]??H.EMPTY}),{cols:o,rows:r,tileSize:e,tiles:i}}function cu(t,e=32,n=or){let r=[];return t.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a===" "||a==="."||n[a]!==void 0||r.push({char:a,tx:s,ty:i,x:(s+.5)*e,y:(i+.5)*e})}}),r}function fe(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?H.SOLID:t.tiles[n*t.cols+e]}function mu(t,e,n){return fe(t,Math.floor(e/t.tileSize),Math.floor(n/t.tileSize))}var du=t=>t.cols*t.tileSize,pu=t=>t.rows*t.tileSize;var q=1e-6,ze=(t,e,n)=>[Math.floor(t/n),Math.floor((e-q)/n)];function We(t,e,n,r,o,i=[]){let s=t.tileSize,[a,l]=ze(e,e+r,s),[u,c]=ze(n,n+o,s);for(let m=u;m<=c;m++)for(let d=a;d<=l;d++)if(fe(t,d,m)===H.SOLID)return!0;for(let m of i)if(!m.oneway&&e<m.x+m.w-q&&e+r>m.x+q&&n<m.y+m.h-q&&n+o>m.y+q)return!0;return!1}function At(t,e,n,r,o={}){let i=t.tileSize,s=o.solids??[],{x:a,y:l}=e,{w:u,h:c}=e,m=!1,d=!1,p=!1,h=!1;if(n!==0){let[v,f]=ze(l,l+c,i);if(n>0){let M=a+n,[S,D]=[Math.floor((a+u)/i),Math.floor((a+u+n-q)/i)];for(let C=S;C<=D;C++)for(let y=v;y<=f;y++)fe(t,C,y)===H.SOLID&&(M=Math.min(M,C*i-u));for(let C of s)!C.oneway&&C.y<l+c-q&&C.y+C.h>l+q&&C.x>=a+u-q&&(M=Math.min(M,C.x-u));M<a+n-q&&(m=!0,h=!0),a=Math.min(a+n,M)}else{let M=a+n,[S,D]=[Math.floor((a-q)/i),Math.floor((a+n)/i)];for(let C=S;C>=D;C--)for(let y=v;y<=f;y++)fe(t,C,y)===H.SOLID&&(M=Math.max(M,(C+1)*i));for(let C of s)!C.oneway&&C.y<l+c-q&&C.y+C.h>l+q&&C.x+C.w<=a+q&&(M=Math.max(M,C.x+C.w));M>a+n+q&&(m=!0,p=!0),a=Math.max(a+n,M)}}let g=l+c,x=!1,k=!1,w=-1;if(r!==0){let[v,f]=ze(a,a+u,i);if(r>0){let M=l+r,[S,D]=[Math.floor(g/i),Math.floor((g+r-q)/i)];for(let C=S;C<=D;C++)for(let y=v;y<=f;y++){let T=fe(t,y,C);(T===H.SOLID||T===H.ONEWAY&&!o.dropThrough&&g<=C*i+q)&&(M=Math.min(M,C*i-c))}for(let C=0;C<s.length;C++){let y=s[C];!(y.x<a+u-q&&y.x+y.w>a+q)||y.y<g-q||y.oneway&&(o.dropThrough||g>y.y+q)||y.y-c<M&&(M=y.y-c,w=C)}M<l+r-q?(d=!0,x=!0):w=-1,l=Math.min(l+r,M)}else{let M=l+r,[S,D]=[Math.floor((l-q)/i),Math.floor((l+r)/i)];for(let C=S;C>=D;C--)for(let y=v;y<=f;y++)fe(t,y,C)===H.SOLID&&(M=Math.max(M,(C+1)*i));for(let C of s)!C.oneway&&C.x<a+u-q&&C.x+C.w>a+q&&C.y+C.h<=l+q&&(M=Math.max(M,C.y+C.h));M>l+r+q&&(d=!0,k=!0),l=Math.max(l+r,M)}}if(!x){let v=wi(t,a,l,u,c,s,o.dropThrough??!1);x=v.grounded,w=v.solid}let P=3,$=!1;{let[v,f]=ze(a+P,a+u-P,i),[M,S]=ze(l+P,l+c-P,i);for(let D=M;D<=S&&!$;D++)for(let C=v;C<=f&&!$;C++)fe(t,C,D)===H.HAZARD&&($=!0)}return{x:a,y:l,hitX:m,hitY:d,onFloor:x,onCeiling:k,onWallLeft:p,onWallRight:h,hazard:$,floorSolid:w}}function wi(t,e,n,r,o,i=[],s=!1){let a=t.tileSize,l=n+o,[u,c]=ze(e,e+r,a),m=Math.floor((l+1)/a);for(let d=u;d<=c;d++){let p=fe(t,d,m);if(p===H.SOLID)return{grounded:!0,solid:-1};if(p===H.ONEWAY&&!s&&Math.abs(l-m*a)<=1+q)return{grounded:!0,solid:-1}}for(let d=0;d<i.length;d++){let p=i[d];if(p.x<e+r-q&&p.x+p.w>e+q&&l<=p.y+1+q&&l>=p.y-1-q)return{grounded:!0,solid:d}}return{grounded:!1,solid:-1}}var rt={width:22,height:28,runSpeed:340,groundAccel:3800,groundFriction:4200,airAccel:2600,airFriction:260,gravity:2300,maxFall:660,apexThreshold:60,apexGravityMult:.5,jumpVelocity:650,jumpCutMult:.4,coyoteTime:.1,jumpBuffer:.12,jumpCornerNudge:10,dashCornerNudge:12,airJumps:0,airJumpMult:.92,dashSpeed:640,dashTime:.14,dashCooldown:.25,dashCharges:1,wallSlideMaxFall:150,wallJumpVelX:360,wallJumpVelY:600,wallJumpLock:.13},xu={moveX:0,moveY:0,jumpHeld:!1,jumpPressed:!1,dashPressed:!1};function vu(t,e){return{x:t,y:e,vx:0,vy:0,facing:1,onGround:!1,onWall:0,coyote:0,buffer:0,jumping:!1,wallLock:0,airJumpsLeft:0,dashing:0,dashCd:0,dashesLeft:1,dashVx:0,dashVy:0,carryVx:0,carryVy:0,dead:!1}}var ki=(t,e,n)=>t<e?Math.min(t+n,e):Math.max(t-n,e);function wu(t,e,n,r,o=rt,i=[]){let s={jumped:!1,wallJumped:!1,airJumped:!1,dashed:!1,landed:!1,died:!1};if(t.dead)return s;let a=t.onGround;if(t.coyote=Math.max(0,t.coyote-n),t.buffer=Math.max(0,t.buffer-n),t.wallLock=Math.max(0,t.wallLock-n),t.dashCd=Math.max(0,t.dashCd-n),e.jumpPressed&&(t.buffer=o.jumpBuffer),e.dashPressed&&t.dashing<=0&&t.dashCd<=0&&t.dashesLeft>0){let d=e.moveX,p=e.moveY;d===0&&p===0&&(d=t.facing);let h=1/Z(d,p);t.dashing=o.dashTime,t.dashCd=o.dashCooldown,t.dashesLeft--,t.dashVx=d*h*o.dashSpeed,t.dashVy=p*h*o.dashSpeed,t.jumping=!1,s.dashed=!0}if(t.dashing>0)t.vx=t.dashVx,t.vy=t.dashVy,t.dashing-=n;else if(t.wallLock<=0){let d=e.moveX*o.runSpeed,p=t.onGround?e.moveX!==0?o.groundAccel:o.groundFriction:e.moveX!==0?o.airAccel:o.airFriction;t.vx=ki(t.vx,d,p*n),e.moveX!==0&&(t.facing=e.moveX>0?1:-1)}if(t.dashing<=0&&!t.onGround){let d=o.gravity;Math.abs(t.vy)<o.apexThreshold&&e.jumpHeld&&t.jumping&&(d*=o.apexGravityMult),t.vy=Math.min(t.vy+d*n,o.maxFall),t.onWall!==0&&t.vy>o.wallSlideMaxFall&&e.moveX===t.onWall&&(t.vy=o.wallSlideMaxFall)}t.jumping&&!e.jumpHeld&&t.vy<0&&(t.vy*=o.jumpCutMult,t.jumping=!1),t.buffer>0&&t.dashing<=0&&(t.onGround||t.coyote>0?(t.vy=-o.jumpVelocity,t.vx+=t.carryVx,t.carryVy<0&&(t.vy+=t.carryVy),t.jumping=!0,t.buffer=0,t.coyote=0,t.onGround=!1,s.jumped=!0):t.onWall!==0&&o.wallJumpVelY>0?(t.vx=-t.onWall*o.wallJumpVelX,t.vy=-o.wallJumpVelY,t.facing=-t.onWall,t.jumping=!0,t.buffer=0,t.wallLock=o.wallJumpLock,s.wallJumped=!0,s.jumped=!0):t.airJumpsLeft>0&&(t.vy=-o.jumpVelocity*o.airJumpMult,t.airJumpsLeft--,t.jumping=!0,t.buffer=0,s.jumped=!0,s.airJumped=!0));let l=e.moveY>0&&t.buffer<=0,u=t.vx*n+t.carryVx*n*(t.onGround?1:0),c=t.vy*n+Math.max(0,t.carryVy)*n*(t.onGround?1:0),m=At(r,{x:t.x,y:t.y,w:o.width,h:o.height},u,c,{solids:i,dropThrough:l});if(m.onCeiling&&t.vy<0&&t.dashing<=0){let d=Ci(r,i,m.x,m.y,o.width,o.height,c,o.jumpCornerNudge);d!==null&&(m=At(r,{x:d,y:m.y,w:o.width,h:o.height},0,c,{solids:i,dropThrough:l}),m.x=d)}if(m.hitX&&t.dashing>0&&Math.abs(t.dashVy)<1){let d=Ti(r,i,m.x,m.y,o.width,o.height,u,o.dashCornerNudge);d!==null&&(m=At(r,{x:m.x,y:d,w:o.width,h:o.height},u,0,{solids:i,dropThrough:l}),m.y=d)}if(t.x=m.x,t.y=m.y,m.hitY&&t.vy>0&&(t.vy=0),m.onCeiling&&(t.vy=Math.max(t.vy,0),t.jumping=!1),m.hitX&&t.dashing<=0&&(t.vx=0),t.onWall=m.onWallLeft?-1:m.onWallRight?1:Ri(r,i,t.x,t.y,o.width,o.height),t.onGround=m.onFloor,t.onGround){if(t.coyote=o.coyoteTime,t.dashesLeft=o.dashCharges,t.airJumpsLeft=o.airJumps,a||(s.landed=!0),m.floorSolid>=0){let d=i[m.floorSolid];t.carryVx=d.vx,t.carryVy=d.vy,t.y=d.y-o.height}else t.carryVx=0,t.carryVy=0;t.vy>0&&(t.vy=0),t.jumping=!1}else a&&t.carryVy;return m.hazard&&(t.dead=!0,s.died=!0),s}function ku(t=rt){return t.jumpVelocity*t.jumpVelocity/(2*t.gravity)}function Si(t=rt){return 2*t.jumpVelocity/t.gravity}function Mi(t=rt){return t.runSpeed*Si(t)}function Su(t=rt){return Mi(t)+(t.dashSpeed-t.runSpeed)*t.dashTime}function Ci(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[1,-1]){let c=n+u*l;if(!We(t,c,r+s,o,i,e)&&!We(t,c,r,o,i,e))return c}return null}function Ti(t,e,n,r,o,i,s,a){for(let l=1;l<=a;l++)for(let u of[-1,1]){let c=r+u*l;if(!We(t,n+s,c,o,i,e)&&!We(t,n,c,o,i,e))return c}return null}function Ri(t,e,n,r,o,i){return We(t,n+1,r,o,i,e)?1:We(t,n-1,r,o,i,e)?-1:0}var Lt=class{cells=new Map;bounds=new Map;cellSize;constructor(e=64){this.cellSize=e}clear(){this.cells.clear(),this.bounds.clear()}get size(){return this.bounds.size}key(e,n){return(e+32768)*65536+(n+32768)}insert(e,n){this.bounds.set(e,n);let r=this.cellSize,o=Math.floor(n.x/r),i=Math.floor((n.x+n.w)/r),s=Math.floor(n.y/r),a=Math.floor((n.y+n.h)/r);for(let l=s;l<=a;l++)for(let u=o;u<=i;u++){let c=this.key(u,l),m=this.cells.get(c);m?m.push(e):this.cells.set(c,[e])}}query(e){let n=this.cellSize,r=Math.floor(e.x/n),o=Math.floor((e.x+e.w)/n),i=Math.floor(e.y/n),s=Math.floor((e.y+e.h)/n),a=new Set,l=[];for(let u=i;u<=s;u++)for(let c=r;c<=o;c++){let m=this.cells.get(this.key(c,u));if(m)for(let d of m){if(a.has(d))continue;a.add(d);let p=this.bounds.get(d);p.x<e.x+e.w&&p.x+p.w>e.x&&p.y<e.y+e.h&&p.y+p.h>e.y&&l.push(d)}}return l}queryCircle(e,n,r){return this.query({x:e-r,y:n-r,w:r*2,h:r*2}).filter(i=>{let s=this.bounds.get(i),a=Math.max(s.x,Math.min(e,s.x+s.w)),l=Math.max(s.y,Math.min(n,s.y+s.h));return(e-a)*(e-a)+(n-l)*(n-l)<=r*r})}};function Pi(t,e,n,r,o){let i=t.tileSize,s=r-e,a=o-n,l=Z(s,a);if(l===0)return{blocked:!1,x:r,y:o,dist:0};let u=s/l,c=a/l,m=Math.floor(e/i),d=Math.floor(n/i),p=u>0?1:-1,h=c>0?1:-1,g=u!==0?Math.abs(i/u):1/0,x=c!==0?Math.abs(i/c):1/0,k=u!==0?(u>0?(m+1)*i-e:e-m*i)/Math.abs(u):1/0,w=c!==0?(c>0?(d+1)*i-n:n-d*i)/Math.abs(c):1/0,P=0;for(let $=0;$<512;$++){if(k<w?(P=k,k+=g,m+=p):(P=w,w+=x,d+=h),P>=l)return{blocked:!1,x:r,y:o,dist:l};if(fe(t,m,d)===H.SOLID)return{blocked:!0,x:e+u*P,y:n+c*P,dist:P}}return{blocked:!0,x:e+u*P,y:n+c*P,dist:P}}function Di(t,e,n,r,o){return!Pi(t,e,n,r,o).blocked}function Pu(t,e,n,r,o,i,s,a,l){let u=a-e,c=l-n,m=Z(u,c);return m>s||m===0||(u*r+c*o)/m<Q(i/2)?!1:Di(t,e,n,a,l)}function Eu(t={}){return{gravityX:t.gravityX??0,gravityY:t.gravityY??900,iterations:t.iterations??16,cellSize:t.cellSize??96,nextId:1,bodies:[],joints:[],warm:{}}}function Ii(t){if(t.kind==="circle")return{area:Math.PI*t.r*t.r,unitI:t.r*t.r/2};let e=t.points,n=e.length/2,r=0,o=0;for(let i=0;i<n;i++){let s=e[i*2],a=e[i*2+1],l=(i+1)%n,u=e[l*2],c=e[l*2+1],m=s*c-u*a;r+=m/2,o+=m*(s*s+s*u+u*u+a*a+a*c+c*c)/12}return{area:Math.abs(r),unitI:r!==0?Math.abs(o)/Math.abs(r):0}}var Ei=1e-4;function Fu(t,e){let n=e.kind??"dynamic",r=e.density??1,{area:o,unitI:i}=Ii(e.shape),s=n==="dynamic"?Math.max(o*r*Ei,1e-6):0,a=n==="dynamic"&&!e.fixedRotation?s*i:0,l={id:t.nextId++,kind:n,shape:e.shape,x:e.x??0,y:e.y??0,a:e.a??0,vx:e.vx??0,vy:e.vy??0,w:e.w??0,m:s,invM:s>0?1/s:0,i:a,invI:a>0?1/a:0,restitution:e.restitution??.1,friction:e.friction??.4,linDamp:e.linDamp??0,angDamp:e.angDamp??.6,gravityScale:e.gravityScale??1,bullet:e.bullet??!1,sensor:e.sensor??!1,layer:e.layer??1,mask:e.mask??65535,canSleep:e.canSleep??!0,sleeping:!1,sleepTime:0,sleepR:e.shape.kind==="circle"?e.shape.r:Math.sqrt(e.shape.points.reduce((u,c,m,d)=>m%2?u:Math.max(u,d[m]*d[m]+d[m+1]*d[m+1]),0)),fx:0,fy:0,torque:0};return t.bodies.push(l),l.id}function xe(t,e){let n=t.bodies;for(let r=0;r<n.length;r++)if(n[r].id===e)return n[r]}function Nu(t,e){let n=t.bodies.findIndex(r=>r.id===e);n>=0&&t.bodies.splice(n,1),t.joints=t.joints.filter(r=>r.a!==e&&r.b!==e)}function ve(t){t.sleeping=!1,t.sleepTime=0}function $u(t,e,n,r,o,i){let s=xe(t,e);!s||s.invM===0||(ve(s),s.vx+=n*s.invM,s.vy+=r*s.invM,o!==void 0&&i!==void 0&&(s.w+=((o-s.x)*r-(i-s.y)*n)*s.invI))}function Me(t){if(t.shape.kind!=="poly")return[];let e=Q(t.a),n=_(t.a),r=t.shape.points,o=new Array(r.length);for(let i=0;i<r.length;i+=2)o[i]=t.x+r[i]*e-r[i+1]*n,o[i+1]=t.y+r[i]*n+r[i+1]*e;return o}function cn(t){if(t.shape.kind==="circle"){let s=t.shape.r;return{x:t.x-s,y:t.y-s,w:s*2,h:s*2}}let e=Me(t),n=1/0,r=1/0,o=-1/0,i=-1/0;for(let s=0;s<e.length;s+=2)e[s]<n&&(n=e[s]),e[s]>o&&(o=e[s]),e[s+1]<r&&(r=e[s+1]),e[s+1]>i&&(i=e[s+1]);return{x:n,y:r,w:o-n,h:i-r}}function Au(t,e){let n=t/2,r=e/2;return{kind:"poly",points:[-n,-r,n,-r,n,r,-n,r]}}function Fi(t,e){if(t.shape.kind!=="circle"||e.shape.kind!=="circle")return null;let n=e.x-t.x,r=e.y-t.y,o=t.shape.r+e.shape.r,i=n*n+r*r;if(i>=o*o)return null;let s=Math.sqrt(i),a=s>1e-9?n/s:1,l=s>1e-9?r/s:0;return{a:t,b:e,nx:a,ny:l,points:[{px:t.x+a*t.shape.r,py:t.y+l*t.shape.r,pen:o-s,feature:0}]}}function sr(t,e){if(t.shape.kind!=="poly"||e.shape.kind!=="circle")return null;let n=Me(t),r=n.length/2,o=e.shape.r,i=-1/0,s=0;for(let D=0;D<r;D++){let C=(D+1)%r,y=n[C*2]-n[D*2],T=n[C*2+1]-n[D*2+1],E=Z(y,T)||1,O=T/E,F=-y/E,J=(e.x-n[D*2])*O+(e.y-n[D*2+1])*F;J>i&&(i=J,s=D)}if(i>o)return null;let a=s,l=(s+1)%r,u=n[a*2],c=n[a*2+1],m=n[l*2],d=n[l*2+1];if(i<1e-9){let D=m-u,C=d-c,y=Z(D,C)||1,T=C/y,E=-D/y;return{a:t,b:e,nx:T,ny:E,points:[{px:e.x-T*o,py:e.y-E*o,pen:o-i,feature:s}]}}let p=m-u,h=d-c,g=p*p+h*h||1,x=((e.x-u)*p+(e.y-c)*h)/g;x=x<0?0:x>1?1:x;let k=u+p*x,w=c+h*x,P=e.x-k,$=e.y-w,v=P*P+$*$;if(v>=o*o)return null;let f=Math.sqrt(v)||1e-9,M=P/f,S=$/f;return{a:t,b:e,nx:M,ny:S,points:[{px:k,py:w,pen:o-f,feature:s}]}}function ar(t,e){let n=t.length/2,r=e.length/2,o=-1/0,i=0;for(let s=0;s<n;s++){let a=(s+1)%n,l=t[a*2]-t[s*2],u=t[a*2+1]-t[s*2+1],c=Z(l,u)||1,m=u/c,d=-l/c,p=1/0;for(let h=0;h<r;h++){let g=(e[h*2]-t[s*2])*m+(e[h*2+1]-t[s*2+1])*d;g<p&&(p=g)}p>o&&(o=p,i=s)}return[o,i]}function Ni(t,e){let n=Me(t),r=Me(e),[o,i]=ar(n,r);if(o>0)return null;let[s,a]=ar(r,n);if(s>0)return null;let l,u,c,m;s>o+1e-4?(l=r,u=n,c=a,m=!0):(l=n,u=r,c=i,m=!1);let d=l.length/2,p=u.length/2,h=(c+1)%d,g=l[h*2]-l[c*2],x=l[h*2+1]-l[c*2+1],k=Z(g,x)||1,w=x/k,P=-g/k,$=g/k,v=x/k,f=0,M=1/0;for(let B=0;B<p;B++){let W=(B+1)%p,V=u[W*2]-u[B*2],re=u[W*2+1]-u[B*2+1],oe=Z(V,re)||1,te=re/oe*w+-V/oe*P;te<M&&(M=te,f=B)}let S=(f+1)%p,D=u[f*2],C=u[f*2+1],y=u[S*2],T=u[S*2+1],E=l[c*2],O=l[c*2+1],F=l[h*2],J=l[h*2+1];for(let B=0;B<2;B++){let W=B===0?E:F,V=B===0?O:J,re=B===0?$:-$,oe=B===0?v:-v,te=(D-W)*re+(C-V)*oe,ie=(y-W)*re+(T-V)*oe;if(te<0&&ie<0)return null;if(te<0){let ue=te/(te-ie);D=D+(y-D)*ue,C=C+(T-C)*ue}else if(ie<0){let ue=ie/(ie-te);y=y+(D-y)*ue,T=T+(C-T)*ue}}let Y=m?-w:w,ne=m?-P:P,X=[],ae=-((D-E)*w+(C-O)*P),I=-((y-E)*w+(T-O)*P),z=((m?1:0)*64+c)*64+f;return ae>0&&X.push({px:D,py:C,pen:ae,feature:z*2}),I>0&&X.push({px:y,py:T,pen:I,feature:z*2+1}),X.length===0?null:{a:t,b:e,nx:Y,ny:ne,points:X}}function lr(t,e){let n=t.shape.kind,r=e.shape.kind;if(n==="circle"&&r==="circle")return Fi(t,e);if(n==="poly"&&r==="poly")return Ni(t,e);if(n==="poly"&&r==="circle")return sr(t,e);let o=sr(e,t);return o?{a:t,b:e,nx:-o.nx,ny:-o.ny,points:o.points}:null}function ur(t,e,n){let r=Q(t.a),o=_(t.a),i=e-t.x,s=n-t.y;return[i*r+s*o,-i*o+s*r]}function zt(t,e,n){let r=Q(t.a),o=_(t.a);return[t.x+e*r-n*o,t.y+e*o+n*r]}function Vu(t,e){let n=xe(t,e.a),r=xe(t,e.b);if(!n||!r)throw new Error(`distance joint: missing body ${e.a}/${e.b}`);let o=e.ax??0,i=e.ay??0,s=e.bx??0,a=e.by??0,[l,u]=zt(n,o,i),[c,m]=zt(r,s,a),d={kind:"distance",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,length:e.length??Z(c-l,m-u),rope:e.rope??!1};return t.joints.push(d),ve(n),ve(r),d.id}function qu(t,e){let n=xe(t,e.a),r=xe(t,e.b);if(!n||!r)throw new Error(`revolute joint: missing body ${e.a}/${e.b}`);let[o,i]=ur(n,e.px,e.py),[s,a]=ur(r,e.px,e.py),l={kind:"revolute",id:t.nextId++,a:e.a,b:e.b,ax:o,ay:i,bx:s,by:a,motorSpeed:e.motorSpeed??0,maxMotorTorque:e.maxMotorTorque??0,limitLower:e.limitLower??0,limitUpper:e.limitUpper??0,limitEnabled:e.limitLower!==void 0||e.limitUpper!==void 0,refAngle:r.a-n.a};return t.joints.push(l),ve(n),ve(r),l.id}function ju(t,e){for(let n of t.joints)if(n.id===e)return n}function Hu(t,e){t.joints=t.joints.filter(n=>n.id!==e)}function cr(t,e,n,r,o){let[i,s]=zt(e,t.ax,t.ay),[a,l]=zt(n,t.bx,t.by),u=i-e.x,c=s-e.y,m=a-n.x,d=l-n.y;if(t.kind==="distance"){let y=a-i,T=l-s,E=Z(y,T);if(E<1e-9)return;y/=E,T/=E;let O=E-t.length;if(t.rope&&O<=0)return;let F=e.vx-e.w*c,J=e.vy+e.w*u,Y=n.vx-n.w*d,ne=n.vy+n.w*m,X=(Y-F)*y+(ne-J)*T,ae=u*T-c*y,I=m*T-d*y,z=e.invM+n.invM+e.invI*ae*ae+n.invI*I*I;if(z<1e-12)return;let B=.2/r*O,W=-(X+B)/z;t.rope&&W>0&&(W=0);let V=y*W,re=T*W;e.vx-=V*e.invM,e.vy-=re*e.invM,e.w-=(u*re-c*V)*e.invI,n.vx+=V*n.invM,n.vy+=re*n.invM,n.w+=(m*re-d*V)*n.invI;return}if(t.maxMotorTorque>0){let y=e.invI+n.invI;if(y>1e-12){let E=-(n.w-e.w-t.motorSpeed)/y,O=t.maxMotorTorque*r,F=o.motorImpulse;o.motorImpulse=Math.min(Math.max(F+E,-O),O);let J=o.motorImpulse-F;e.w-=J*e.invI,n.w+=J*n.invI}}if(t.limitEnabled){let y=e.invI+n.invI;if(y>1e-12){let T=n.a-e.a-t.refAngle,E=0;if(T<t.limitLower?E=T-t.limitLower:T>t.limitUpper&&(E=T-t.limitUpper),E!==0){let F=-(n.w-e.w+.2/r*E)/y;(E<0&&F>0||E>0&&F<0)&&(e.w-=F*e.invI,n.w+=F*n.invI)}}}let p=e.vx-e.w*c,h=e.vy+e.w*u,g=n.vx-n.w*d,x=n.vy+n.w*m,k=a-i,w=l-s,P=g-p+.2/r*k,$=x-h+.2/r*w,v=e.invM+n.invM+e.invI*c*c+n.invI*d*d,f=-e.invI*u*c-n.invI*m*d,M=e.invM+n.invM+e.invI*u*u+n.invI*m*m,S=v*M-f*f;if(Math.abs(S)<1e-12)return;let D=-(M*P-f*$)/S,C=-(v*$-f*P)/S;e.vx-=D*e.invM,e.vy-=C*e.invM,e.w-=(u*C-c*D)*e.invI,n.vx+=D*n.invM,n.vy+=C*n.invM,n.w+=(m*C-d*D)*n.invI}var $i=.5,Ai=.2,Li=40,zi=64,Wi=8,Bi=.5,mr=100;function dr(t,e){return t.invM===0&&e.invM===0&&t.kind!=="kinematic"&&e.kind!=="kinematic"&&!t.sensor&&!e.sensor?!1:(t.mask&e.layer)!==0&&(e.mask&t.layer)!==0}function Qu(t,e){let n=t.bodies,r=[];if(e<=0)return r;for(let v=0;v<n.length;v++){let f=n[v];if(f.kind!=="dynamic"||f.sleeping){f.fx=0,f.fy=0,f.torque=0;continue}f.vx+=(t.gravityX*f.gravityScale+f.fx*f.invM)*e,f.vy+=(t.gravityY*f.gravityScale+f.fy*f.invM)*e,f.w+=f.torque*f.invI*e;let M=1/(1+f.linDamp*e);f.vx*=M,f.vy*=M,f.w*=1/(1+f.angDamp*e),f.fx=0,f.fy=0,f.torque=0}let o=new Lt(t.cellSize),i=new Map;for(let v=0;v<n.length;v++)o.insert(n[v],cn(n[v])),i.set(n[v],v);let s=[],a=new Set,l=new Set;for(let v of t.joints){let f=Math.min(v.a,v.b),M=Math.max(v.a,v.b);l.add(f*1048576+M)}for(let v=0;v<n.length;v++){let f=n[v],M=o.query(cn(f));for(let S of M){if(S.id<=f.id)continue;let D=f.id*1048576+S.id;if(a.has(D)||(a.add(D),l.has(D))||!dr(f,S))continue;let C=!f.sleeping&&f.kind!=="static",y=!S.sleeping&&S.kind!=="static";if(!C&&!y)continue;let T=lr(f,S);if(!T)continue;let E=(Y,ne)=>{Y.sleeping&&(ne.vx*ne.vx+ne.vy*ne.vy>mr||ne.kind==="kinematic")&&ve(Y)};if(E(f,S),E(S,f),f.sensor||S.sensor){r.push({a:f.id,b:S.id,px:T.points[0].px,py:T.points[0].py,nx:T.nx,ny:T.ny,impulse:0,sensor:!0});continue}let O=[],F=-T.ny,J=T.nx;for(let Y of T.points){let ne=Y.px-f.x,X=Y.py-f.y,ae=Y.px-S.x,I=Y.py-S.y,z=ne*T.ny-X*T.nx,B=ae*T.ny-I*T.nx,W=f.invM+S.invM+f.invI*z*z+S.invI*B*B,V=ne*J-X*F,re=ae*J-I*F,oe=f.invM+S.invM+f.invI*V*V+S.invI*re*re,te=S.vx-S.w*I-f.vx+f.w*X,ie=S.vy+S.w*ae-f.vy-f.w*ne,ue=te*T.nx+ie*T.ny,ge=Math.max(f.restitution,S.restitution),Ae=`${f.id}:${S.id}:${Y.feature}`,ke=t.warm[Ae],Uo={rax:ne,ray:X,rbx:ae,rby:I,pen:Y.pen,massN:W>1e-12?1/W:0,massT:oe>1e-12?1/oe:0,restBias:ue<-Li?-ge*ue:0,posBias:Ai/e*Math.max(0,Y.pen-$i),pn:ke?ke[0]:0,pt:ke?ke[1]:0,pb:0,key:Ae};O.push(Uo)}s.push({m:T,ia:v,ib:i.get(S),points:O,friction:Math.sqrt(f.friction*S.friction)})}}for(let v of s){let{a:f,b:M,nx:S,ny:D}=v.m,C=-D,y=S;for(let T of v.points){if(T.pn===0&&T.pt===0)continue;let E=S*T.pn+C*T.pt,O=D*T.pn+y*T.pt;f.vx-=E*f.invM,f.vy-=O*f.invM,f.w-=(T.rax*O-T.ray*E)*f.invI,M.vx+=E*M.invM,M.vy+=O*M.invM,M.w+=(T.rbx*O-T.rby*E)*M.invI}}s.sort((v,f)=>{let M=v.m.a.invM===0||v.m.b.invM===0?0:1,S=f.m.a.invM===0||f.m.b.invM===0?0:1;if(M!==S)return M-S;let D=Math.max(v.m.a.y,v.m.b.y),C=Math.max(f.m.a.y,f.m.b.y);return D!==C?C-D:v.m.a.id!==f.m.a.id?v.m.a.id-f.m.a.id:v.m.b.id-f.m.b.id});let u=new Float64Array(n.length),c=new Float64Array(n.length),m=new Float64Array(n.length),d=t.joints.map(()=>({motorImpulse:0}));for(let v=0;v<t.iterations;v++){for(let f=0;f<t.joints.length;f++){let M=t.joints[f],S=xe(t,M.a),D=xe(t,M.b);!S||!D||S.sleeping&&D.sleeping||(S.sleeping&&ve(S),D.sleeping&&ve(D),cr(M,S,D,e,d[f]))}for(let f of s){let{a:M,b:S,nx:D,ny:C}=f.m,{ia:y,ib:T}=f,E=-C,O=D;for(let F of f.points){let J=S.vx-S.w*F.rby-M.vx+M.w*F.ray,Y=S.vy+S.w*F.rbx-M.vy-M.w*F.rax,ne=J*D+Y*C,X=F.massN*(F.restBias-ne),ae=F.pn;F.pn=Math.max(ae+X,0),X=F.pn-ae;let I=D*X,z=C*X;M.vx-=I*M.invM,M.vy-=z*M.invM,M.w-=(F.rax*z-F.ray*I)*M.invI,S.vx+=I*S.invM,S.vy+=z*S.invM,S.w+=(F.rbx*z-F.rby*I)*S.invI,J=S.vx-S.w*F.rby-M.vx+M.w*F.ray,Y=S.vy+S.w*F.rbx-M.vy-M.w*F.rax;let B=J*E+Y*O,W=F.massT*-B,V=f.friction*F.pn,re=F.pt;if(F.pt=Math.min(Math.max(re+W,-V),V),W=F.pt-re,I=E*W,z=O*W,M.vx-=I*M.invM,M.vy-=z*M.invM,M.w-=(F.rax*z-F.ray*I)*M.invI,S.vx+=I*S.invM,S.vy+=z*S.invM,S.w+=(F.rbx*z-F.rby*I)*S.invI,F.posBias>0){let oe=(u[T]-m[T]*F.rby-u[y]+m[y]*F.ray)*D+(c[T]+m[T]*F.rbx-c[y]-m[y]*F.rax)*C,te=F.massN*(F.posBias-oe),ie=F.pb;F.pb=Math.max(ie+te,0),te=F.pb-ie;let ue=D*te,ge=C*te;u[y]-=ue*M.invM,c[y]-=ge*M.invM,u[T]+=ue*S.invM,c[T]+=ge*S.invM}}}}let p=[],h=[];for(let v=0;v<n.length;v++){let f=n[v];p.push(f.x),h.push(f.y),!(f.invM===0&&f.kind!=="kinematic")&&(f.sleeping||(f.x+=(f.vx+u[v])*e,f.y+=(f.vy+c[v])*e,f.a+=(f.w+m[v])*e))}for(let v=0;v<n.length;v++){let f=n[v];if(!f.bullet||f.shape.kind!=="circle"||f.sleeping)continue;let M=f.x-p[v],S=f.y-h[v];if(M*M+S*S<1)continue;let D=1;for(let C=0;C<n.length;C++){let y=n[C];if(y===f||y.bullet||y.sensor||!dr(f,y))continue;let T=Oi(p[v],h[v],M,S,f.shape.r,y);T>=0&&T<D&&(D=T)}if(D<1){let C=Z(M,S)||1;f.x=p[v]+M*D+M/C*.4,f.y=h[v]+S*D+S/C*.4}}let g=new Set,x=[];for(let v=0;v<n.length;v++)x.push(v);let k=v=>{for(;x[v]!==v;)x[v]=x[x[v]],v=x[v];return v},w=(v,f)=>{x[k(v)]=k(f)};for(let v of s)g.add(v.m.a.id),g.add(v.m.b.id),v.m.a.kind==="dynamic"&&v.m.b.kind==="dynamic"&&w(v.ia,v.ib);for(let v of t.joints){g.add(v.a),g.add(v.b);let f=xe(t,v.a),M=xe(t,v.b);f?.kind==="dynamic"&&M?.kind==="dynamic"&&w(i.get(f),i.get(M))}for(let v=0;v<n.length;v++){let f=n[v];if(f.kind!=="dynamic")continue;let M=f.vx*f.vx+f.vy*f.vy;if(f.sleeping){M>mr&&ve(f);continue}if(!f.canSleep||!g.has(f.id)){f.sleepTime=0;continue}f.sleepTime=M<zi&&Math.abs(f.w)*f.sleepR<Wi?f.sleepTime+e:0}let P=new Map;for(let v=0;v<n.length;v++){let f=n[v];if(f.kind!=="dynamic"||f.sleeping)continue;let M=k(v),S=!f.canSleep||!g.has(f.id)?-1:f.sleepTime,D=P.get(M);P.set(M,D===void 0?S:Math.min(D,S))}for(let v=0;v<n.length;v++){let f=n[v];f.kind!=="dynamic"||f.sleeping||(P.get(k(v))??-1)>=Bi&&(f.sleeping=!0,f.vx=0,f.vy=0,f.w=0)}let $={};for(let v of s){let f=0;for(let S of v.points)f+=S.pn,(S.pn!==0||S.pt!==0)&&($[S.key]=[S.pn,S.pt]);let M=v.m.points[0];r.push({a:v.m.a.id,b:v.m.b.id,px:M.px,py:M.py,nx:v.m.nx,ny:v.m.ny,impulse:f,sensor:!1})}return t.warm=$,r}function Oi(t,e,n,r,o,i){if(i.shape.kind==="circle")return pr(t,e,n,r,i.x,i.y,o+i.shape.r);let s=Me(i),a=s.length/2,l=-1;for(let u=0;u<a;u++){let c=(u+1)%a,m=s[u*2],d=s[u*2+1],p=s[c*2],h=s[c*2+1],g=p-m,x=h-d,k=Z(g,x)||1,w=x/k,P=-g/k,$=(t-m)*w+(e-d)*P-o;if(n*w+r*P<0&&$>.5){let f=Gi(t,e,n,r,m+w*o,d+P*o,p+w*o,h+P*o);f>=0&&(l<0||f<l)&&(l=f)}let v=pr(t,e,n,r,m,d,o);v>=0&&(l<0||v<l)&&(l=v)}return l}function pr(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r);if(a*a+l*l<(s+.5)*(s+.5))return-1;let m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let p=(-c-Math.sqrt(d))/(2*u);return p>=0&&p<=1?p:-1}function Gi(t,e,n,r,o,i,s,a){let l=s-o,u=a-i,c=n*u-r*l;if(Math.abs(c)<1e-12)return-1;let m=((o-t)*u-(i-e)*l)/c,d=((o-t)*r-(i-e)*n)/c;return m>=0&&m<=1&&d>=0&&d<=1?m:-1}function Vi(t,e,n){if(t.shape.kind==="circle"){let i=e-t.x,s=n-t.y;return i*i+s*s<=t.shape.r*t.shape.r}let r=Me(t),o=r.length/2;for(let i=0;i<o;i++){let s=(i+1)%o,a=r[s*2]-r[i*2],l=r[s*2+1]-r[i*2+1];if((e-r[i*2])*l-(n-r[i*2+1])*a>0)return!1}return!0}function nc(t,e,n,r=65535){let o;for(let i of t.bodies)(i.layer&r)!==0&&Vi(i,e,n)&&(o=i);return o}function qi(t,e,n,r,o,i,s){let a=t-o,l=e-i,u=n*n+r*r;if(u<1e-12)return-1;let c=2*(a*n+l*r),m=a*a+l*l-s*s,d=c*c-4*u*m;if(d<0)return-1;let p=(-c-Math.sqrt(d))/(2*u);return p>=0&&p<=1?p:-1}function rc(t,e,n,r,o,i=65535){let s=r-e,a=o-n,l=null;for(let u of t.bodies){if((u.layer&i)===0)continue;if(u.shape.kind==="circle"){let d=qi(e,n,s,a,u.x,u.y,u.shape.r);if(d>=0&&(!l||d<l.t)){let p=e+s*d,h=n+a*d,g=Z(p-u.x,h-u.y)||1;l={id:u.id,t:d,x:p,y:h,nx:(p-u.x)/g,ny:(h-u.y)/g}}continue}let c=Me(u),m=c.length/2;for(let d=0;d<m;d++){let p=(d+1)%m,h=c[d*2],g=c[d*2+1],x=c[p*2]-h,k=c[p*2+1]-g,w=s*k-a*x;if(Math.abs(w)<1e-12)continue;let P=((h-e)*k-(g-n)*x)/w,$=((h-e)*a-(g-n)*s)/w;if(!(P<0||P>1||$<0||$>1)&&(!l||P<l.t)){let v=Z(x,k)||1;l={id:u.id,t:P,x:e+s*P,y:n+a*P,nx:k/v,ny:-x/v}}}}return l}function Wt(t){return t.map((e,n)=>[e,n]).sort((e,n)=>e[0].z-n[0].z||e[1]-n[1]).map(([e])=>e)}var we=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function hr(t){let e=Math.max(1,t.length-1);return t.map((n,r)=>typeof n=="string"?{offset:r/e,color:n}:n)}function ac(t,e=90){let n=e*Math.PI/180,r=Q(n)*.5,o=_(n)*.5;return{type:"linear",x1:.5-r,y1:.5-o,x2:.5+r,y2:.5+o,stops:hr(t)}}function lc(t,e={}){return{type:"radial",cx:e.cx??.5,cy:e.cy??.5,r:e.r??.5,stops:hr(t)}}function uc(t,e){return{color:t,blur:e}}function cc(t,e,n=0,r=0){return{color:t,blur:e,dx:n,dy:r}}function ji(t){return`<stop offset="${we(t.offset)}" stop-color="${t.color}"/>`}function fr(t,e){let n=t.stops.map(ji).join("");return t.type==="linear"?`<linearGradient id="${e}" x1="${we(t.x1)}" y1="${we(t.y1)}" x2="${we(t.x2)}" y2="${we(t.y2)}">${n}</linearGradient>`:`<radialGradient id="${e}" cx="${we(t.cx)}" cy="${we(t.cy)}" r="${we(t.r)}">${n}</radialGradient>`}function br(t,e){return`<filter id="${e}" x="-60%" y="-60%" width="220%" height="220%"><feDropShadow dx="${we(t.dx??0)}" dy="${we(t.dy??0)}" stdDeviation="${we(t.blur/2)}" flood-color="${t.color}"/></filter>`}function gr(t){switch(t.kind){case"rect":return{x:t.x,y:t.y,w:t.w,h:t.h};case"circle":return{x:t.cx-t.radius,y:t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{if(t.points.length<2)return null;let e=t.points[0],n=t.points[0],r=t.points[1],o=t.points[1];for(let i=0;i<t.points.length;i+=2)e=Math.min(e,t.points[i]),n=Math.max(n,t.points[i]),r=Math.min(r,t.points[i+1]),o=Math.max(o,t.points[i+1]);return{x:e,y:r,w:n-e,h:o-r}}default:return null}}function yr(t,e,n){let r=s=>n.x+s*n.w,o=s=>n.y+s*n.h,i;if(e.type==="linear")i=t.createLinearGradient(r(e.x1),o(e.y1),r(e.x2),o(e.y2));else{let s=e.r*Math.max(n.w,n.h);i=t.createRadialGradient(r(e.cx),o(e.cy),0,r(e.cx),o(e.cy),s)}for(let s of e.stops)i.addColorStop(Math.max(0,Math.min(1,s.offset)),s.color);return i}function Bt(t,e,n,r,o){let i=Math.min(t.width/e,t.height/n)||1,s=(t.width-e*i)/2,a=(t.height-n*i)/2;return{x:(r-t.left-s)/i,y:(o-t.top-a)/i}}var U=t=>Number.isInteger(t)?String(t):(Math.round(t*1e3)/1e3).toString();function Hi(t){return`matrix(${U(t.a)} ${U(t.b)} ${U(t.c)} ${U(t.d)} ${U(t.e)} ${U(t.f)})`}function _i(t,e,n){let r=[];return r.push(`fill="${e??t.fill??"none"}"`),t.stroke&&(r.push(`stroke="${t.stroke}"`),r.push(`stroke-width="${U(t.strokeWidth??1)}"`),t.round&&r.push('stroke-linejoin="round" stroke-linecap="round"')),t.opacity!==void 0&&t.opacity!==1&&r.push(`opacity="${U(t.opacity)}"`),n&&r.push(`filter="url(#${n})"`),r.join(" ")}function Ji(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ui(t,e,n){let r=`transform="${Hi(t.transform)}"`,o,i;if(t.gradient){let a=`${n}g`;e.push(fr(t.gradient,a)),o=`url(#${a})`}t.shadow&&(i=`${n}s`,e.push(br(t.shadow,i)));let s=_i(t,o,i);switch(t.kind){case"rect":return`<rect x="${U(t.x)}" y="${U(t.y)}" width="${U(t.w)}" height="${U(t.h)}"${t.r?` rx="${U(t.r)}"`:""} ${r} ${s}/>`;case"circle":return`<circle cx="${U(t.cx)}" cy="${U(t.cy)}" r="${U(t.radius)}" ${r} ${s}/>`;case"poly":{let a=[];for(let u=0;u<t.points.length;u+=2)a.push(`${U(t.points[u])},${U(t.points[u+1])}`);return`<${t.closed?"polygon":"polyline"} points="${a.join(" ")}" ${r} ${s}/>`}case"path":return`<path d="${t.d}" ${r} ${s}/>`;case"text":{let a=t.align==="center"?"middle":t.align==="right"?"end":"start",l=t.font?` font-family="${t.font}"`:"",u=t.weight?` font-weight="${t.weight}"`:"",c=o??t.fill??"#000",m=i?` filter="url(#${i})"`:"",d=t.stroke?` stroke="${t.stroke}" stroke-width="${U(t.strokeWidth??1)}" paint-order="stroke"${t.round?' stroke-linejoin="round"':""}`:"",p=t.opacity!==void 0&&t.opacity!==1?` opacity="${U(t.opacity)}"`:"";return`<text x="${U(t.x)}" y="${U(t.y)}" font-size="${U(t.size)}" text-anchor="${a}" dominant-baseline="middle"${l}${u} fill="${c}"${d}${p}${m} ${r}>${Ji(t.text)}</text>`}case"image":{let a=i?` filter="url(#${i})"`:"";return`<image href="${t.href}" x="${U(t.x)}" y="${U(t.y)}" width="${U(t.w)}" height="${U(t.h)}" ${r}${t.opacity!==void 0&&t.opacity!==1?` opacity="${U(t.opacity)}"`:""}${a}/>`}}}function qe(t,e="h"){let n=[],r=Wt(t).map((o,i)=>Ui(o,n,`${e}${i}`)).join("");return(n.length?`<defs>${n.join("")}</defs>`:"")+r}function Ot(t,e,n,r="#ffffff"){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${e} ${n}" width="${e}" height="${n}"><rect x="0" y="0" width="${e}" height="${n}" fill="${r}"/>`+qe(t)+"</svg>"}var mn="http://www.w3.org/2000/svg",je=class{width;height;background;svg;bg;layer;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.svg=document.createElementNS(mn,"svg"),this.svg.setAttribute("viewBox",`0 0 ${this.width} ${this.height}`),this.svg.setAttribute("preserveAspectRatio","xMidYMid meet"),this.svg.style.width="100%",this.svg.style.height="100%",this.svg.style.display="block",this.bg=document.createElementNS(mn,"rect"),this.bg.setAttribute("x","0"),this.bg.setAttribute("y","0"),this.bg.setAttribute("width",String(this.width)),this.bg.setAttribute("height",String(this.height)),this.bg.setAttribute("fill",this.background),this.svg.appendChild(this.bg),this.layer=document.createElementNS(mn,"g"),this.svg.appendChild(this.layer)}mount(e){e.appendChild(this.svg)}draw(e){this.layer.innerHTML=qe(e)}setBackground(e){this.background=e,this.bg.setAttribute("fill",e)}get element(){return this.svg}toDesign(e,n){return Bt(this.svg.getBoundingClientRect(),this.width,this.height,e,n)}dispose(){this.svg.remove()}};var He=class{width;height;background;canvas;ctx;dpr=1;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff",this.canvas=document.createElement("canvas"),this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.objectFit="contain",this.canvas.style.display="block";let n=this.canvas.getContext("2d");if(!n)throw new Error("hayao: 2D canvas context unavailable");this.ctx=n,this.resize()}mount(e){e.appendChild(this.canvas),this.resize()}resize(){this.dpr=Math.min(3,globalThis.devicePixelRatio||1),this.canvas.width=Math.round(this.width*this.dpr),this.canvas.height=Math.round(this.height*this.dpr)}draw(e){let n=this.ctx;n.setTransform(this.dpr,0,0,this.dpr,0,0),n.fillStyle=this.background,n.fillRect(0,0,this.width,this.height);for(let r of Wt(e)){n.save();let o=r.transform;n.transform(o.a,o.b,o.c,o.d,o.e,o.f),n.globalAlpha=r.opacity??1;let i=r.shadow;i&&(n.shadowColor=i.color,n.shadowBlur=i.blur,n.shadowOffsetX=i.dx??0,n.shadowOffsetY=i.dy??0),this.paint(n,r),n.restore()}}fillFor(e,n){let r=n;if(r.gradient){let o=gr(n);if(o&&o.w>0&&o.h>0)return yr(e,r.gradient,o);let i=r.gradient.stops;return i.length?i[i.length-1].color:r.fill}return r.fill}stroke(e,n){let r=this.fillFor(e,n);r&&r!=="none"&&(e.fillStyle=r,e.fill()),n.stroke&&(e.strokeStyle=n.stroke,e.lineWidth=n.strokeWidth??1,n.round&&(e.lineJoin="round",e.lineCap="round"),e.stroke())}paint(e,n){switch(n.kind){case"rect":e.beginPath(),n.r?this.roundRect(e,n.x,n.y,n.w,n.h,n.r):e.rect(n.x,n.y,n.w,n.h),this.stroke(e,n);break;case"circle":e.beginPath(),e.arc(n.cx,n.cy,n.radius,0,Math.PI*2),this.stroke(e,n);break;case"poly":e.beginPath();for(let r=0;r<n.points.length;r+=2)r===0?e.moveTo(n.points[r],n.points[r+1]):e.lineTo(n.points[r],n.points[r+1]);n.closed&&e.closePath(),this.stroke(e,n);break;case"path":{let r=new Path2D(n.d),o=this.fillFor(e,n);o&&o!=="none"&&(e.fillStyle=o,e.fill(r)),n.stroke&&(e.strokeStyle=n.stroke,e.lineWidth=n.strokeWidth??1,n.round&&(e.lineJoin="round",e.lineCap="round"),e.stroke(r))}break;case"text":e.font=`${n.weight??400} ${n.size}px ${n.font??"sans-serif"}`,e.textAlign=n.align??"left",e.textBaseline="middle",n.stroke&&(e.strokeStyle=n.stroke,e.lineWidth=n.strokeWidth??1,e.lineJoin="round",e.lineCap="round",e.strokeText(n.text,n.x,n.y)),e.fillStyle=n.fill??"#000",e.fillText(n.text,n.x,n.y);break;case"image":break}}roundRect(e,n,r,o,i,s){let a=Math.min(s,o/2,i/2);e.moveTo(n+a,r),e.arcTo(n+o,r,n+o,r+i,a),e.arcTo(n+o,r+i,n,r+i,a),e.arcTo(n,r+i,n,r,a),e.arcTo(n,r,n+o,r,a),e.closePath()}get element(){return this.canvas}toDesign(e,n){return Bt(this.canvas.getBoundingClientRect(),this.width,this.height,e,n)}dispose(){this.canvas.remove()}};var xr=class{width;height;background;last=[];frameCount=0;constructor(e){this.width=e.width,this.height=e.height,this.background=e.background??"#ffffff"}draw(e){this.last=e,this.frameCount++}get commands(){return this.last}count(e){return this.last.filter(n=>n.kind===e).length}toSVGString(){return Ot(this.last,this.width,this.height,this.background)}};function Tc(t,e,n=0,r=le){let o=Math.max(0,Math.min(e.border,t.w/2,t.h/2)),i=e.fill??"#fbf6ea",s=e.edge??i,a=e.corner??s,l=[],u=t.x,c=t.x+o,m=t.x+t.w-o,d=t.y,p=t.y+o,h=t.y+t.h-o,g=t.w-2*o,x=t.h-2*o,k=(P,$,v,f,M,S)=>{v<=0||f<=0||l.push({kind:"rect",x:P,y:$,w:v,h:f,r:S,fill:M,transform:r,z:n})};k(c,p,g,x,i),k(c,d,g,o,e.highlight??s),k(c,h,g,o,e.shadow??s),k(u,p,o,x,e.highlight??s),k(m,p,o,x,e.shadow??s);let w=e.radius;return k(u,d,o,o,a,w),k(m,d,o,o,a,w),k(u,h,o,o,a,w),k(m,h,o,o,a,w),e.stroke&&l.push({kind:"rect",x:t.x,y:t.y,w:t.w,h:t.h,r:e.radius,fill:"none",stroke:e.stroke,strokeWidth:e.strokeWidth??2,transform:r,z:n+.001}),l}var Rc={parchment:()=>({border:10,fill:"#fbf6ea",edge:"#efe4c8",corner:"#e2d3a8",highlight:"#fdfaf0",shadow:"#d9c79c",stroke:"#b8a06a",strokeWidth:2,radius:4}),slate:()=>({border:8,fill:"#2c3040",edge:"#363c4f",corner:"#454c63",highlight:"#4a5268",shadow:"#20242f",stroke:"#151821",strokeWidth:2,radius:3})};var L={gofun:"#f7f1e2",washi:"#efe7d3",kinu:"#e4d8bd",line:"#d8cbac",kinako:"#b9a882",stone:"#6c6252",sumiSoft:"#494133",sumi:"#23201a",kuro:"#181820",yohaku:"#12121a",darkLine:"#2c2c36",shuDeep:"#b23a24",shu:"#d9583c",kakiDeep:"#bf6a1c",kaki:"#e79a49",koDeep:"#94741d",ko:"#e3c054",matsuDeep:"#4a7a3a",matsu:"#8bad52",asagiDeep:"#2c7a90",asagi:"#57bad2",aiDeep:"#2b4257",ai:"#5a86ad",fujiDeep:"#63548c",fuji:"#a091cf",sakuDeep:"#b0506e",saku:"#e097ac"},Ki={name:"meadow",bg:L.washi,ink:L.sumi,inkSoft:L.sumiSoft,line:L.line,accent:L.shuDeep,accent2:L.aiDeep,good:L.matsuDeep,warn:L.kakiDeep,ramp:[L.shuDeep,L.kakiDeep,L.koDeep,L.matsuDeep,L.asagiDeep,L.aiDeep,L.fujiDeep,L.sakuDeep],swatches:L},Yi={name:"dusk",bg:L.kuro,ink:L.gofun,inkSoft:L.kinako,line:L.darkLine,accent:L.shu,accent2:L.asagi,good:L.matsu,warn:L.ko,ramp:[L.shu,L.kaki,L.ko,L.matsu,L.asagi,L.ai,L.fuji,L.saku],swatches:L},Xi={name:"paper",bg:L.gofun,ink:L.sumi,inkSoft:L.stone,line:L.kinu,accent:L.sakuDeep,accent2:L.asagiDeep,good:L.matsuDeep,warn:L.kakiDeep,ramp:[L.sakuDeep,L.kakiDeep,L.koDeep,L.matsuDeep,L.asagiDeep,L.aiDeep,L.fujiDeep,L.shuDeep],swatches:L},Ic={meadow:Ki,dusk:Yi,paper:Xi};function Ec(t,e,n){let r=_e(t),o=_e(e),i=Math.round(r[0]+(o[0]-r[0])*n),s=Math.round(r[1]+(o[1]-r[1])*n),a=Math.round(r[2]+(o[2]-r[2])*n);return ot(i,s,a)}function Fc(t,e){let[n,r,o]=_e(t);return`rgba(${n}, ${r}, ${o}, ${e})`}function _e(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(r=>r+r).join(""));let n=parseInt(e,16);return[n>>16&255,n>>8&255,n&255]}function ot(t,e,n){return"#"+[t,e,n].map(r=>Math.max(0,Math.min(255,Math.round(r))).toString(16).padStart(2,"0")).join("")}var kr=t=>(t%360+360)%360,it=t=>t<0?0:t>1?1:t;function Qi(t,e,n){if(t=kr(t)/360,e=it(e),n=it(n),e===0){let s=n*255;return ot(s,s,s)}let r=n<.5?n*(1+e):n+e-n*e,o=2*n-r,i=s=>(s=s<0?s+1:s>1?s-1:s,s<1/6?o+(r-o)*6*s:s<1/2?r:s<2/3?o+(r-o)*(2/3-s)*6:o);return ot(i(t+1/3)*255,i(t)*255,i(t-1/3)*255)}function Nc(t,e,n){t=kr(t)/60,e=it(e),n=it(n);let r=n*e,o=r*(1-Math.abs(t%2-1)),i=n-r,s=0,a=0,l=0;return t<1?[s,a,l]=[r,o,0]:t<2?[s,a,l]=[o,r,0]:t<3?[s,a,l]=[0,r,o]:t<4?[s,a,l]=[0,o,r]:t<5?[s,a,l]=[o,0,r]:[s,a,l]=[r,0,o],ot((s+i)*255,(a+i)*255,(l+i)*255)}function Zi(t){let[e,n,r]=_e(t),o=e/255,i=n/255,s=r/255,a=Math.max(o,i,s),l=Math.min(o,i,s),u=(a+l)/2,c=a-l;if(c===0)return{h:0,s:0,l:u};let m=u>.5?c/(2-a-l):c/(a+l),d;return a===o?d=(i-s)/c+(i<s?6:0):a===i?d=(s-o)/c+2:d=(o-i)/c+4,{h:d*60,s:m,l:u}}function $c(t,e,n={}){let r=Zi(e),o=n.hue??0,i=n.sat??0,s=n.light??0;return Qi(r.h+t.range(-o,o),r.s+t.range(-i,i),r.l+t.range(-s,s))}var vr=t=>t<=.04045?t/12.92:Pe((t+.055)/1.055,2.4),es=t=>t<=.0031308?t*12.92:1.055*Pe(t,1/2.4)-.055;function ts(t,e,n){let r=_e(t),o=_e(e),i=s=>{let a=vr(r[s]/255),l=vr(o[s]/255);return es(a+(l-a)*n)*255};return ot(i(0),i(1),i(2))}function wr(t,e){if(t.length===0)return"#000000";if(t.length===1)return t[0];let r=it(e)*(t.length-1),o=Math.min(t.length-2,Math.floor(r));return ts(t[o],t[o+1],r-o)}function Ac(t,e){return e<=0?[]:e===1?[wr(t,0)]:Array.from({length:e},(n,r)=>wr(t,r/(e-1)))}function Bc(t,e,n=0){let r=[];for(let o=0;o<t;o++){let i=n+o/t*se;r.push(Q(i)*e,_(i)*e)}return r}function Oc(t,e,n,r=-Math.PI/2){let o=[];for(let i=0;i<t*2;i++){let s=i%2===0?e:n,a=r+i/(t*2)*se;o.push(Q(a)*s,_(a)*s)}return o}function Gc(t,e,n=.25,r=7){let o=[];for(let i=0;i<r;i++){let s=i/r*se,a=e*(1-n+t.float()*n*2);o.push({x:Q(s)*a,y:_(s)*a})}return ns(o)}function ns(t,e=1){let n=t.length;if(n<3)return"";let r=s=>t[(s%n+n)%n],o=s=>Math.round(s*100)/100,i=`M ${o(r(0).x)} ${o(r(0).y)}`;for(let s=0;s<n;s++){let a=r(s-1),l=r(s),u=r(s+1),c=r(s+2),m=l.x+(u.x-a.x)/6*e,d=l.y+(u.y-a.y)/6*e,p=u.x-(c.x-l.x)/6*e,h=u.y-(c.y-l.y)/6*e;i+=` C ${o(m)} ${o(d)}, ${o(p)} ${o(h)}, ${o(u.x)} ${o(u.y)}`}return i+" Z"}function Vc(t,e=1){let n=t.length;if(n<2)return"";let r=i=>Math.round(i*100)/100,o=`M ${r(t[0].x)} ${r(t[0].y)}`;for(let i=0;i<n-1;i++){let s=t[Math.max(0,i-1)],a=t[i],l=t[i+1],u=t[Math.min(n-1,i+2)],c=a.x+(l.x-s.x)/6*e,m=a.y+(l.y-s.y)/6*e,d=l.x-(u.x-a.x)/6*e,p=l.y-(u.y-a.y)/6*e;o+=` C ${r(c)} ${r(m)}, ${r(d)} ${r(p)}, ${r(l.x)} ${r(l.y)}`}return o}var st=class t{width;height;data;constructor(e,n,r){this.width=e,this.height=n,this.data=r??new Uint8Array(e*n)}get(e,n){return e<0||n<0||e>=this.width||n>=this.height?0:this.data[n*this.width+e]}set(e,n,r){e<0||n<0||e>=this.width||n>=this.height||(this.data[n*this.width+e]=r)}static fromRows(e,n){let r=e.length,o=e.reduce((s,a)=>Math.max(s,a.length),0),i=new t(o,r);for(let s=0;s<r;s++){let a=e[s];for(let l=0;l<a.length;l++)i.data[s*o+l]=n[a[l]]??0}return i}remap(e){let n=new Uint8Array(this.data.length);for(let r=0;r<this.data.length;r++)n[r]=e[this.data[r]]??0;return new t(this.width,this.height,n)}};function Mr(t){if(typeof t=="bigint")return t;let e=t.trim();return e.startsWith("0x")||e.startsWith("0b")||e.startsWith("0o")?BigInt(e):BigInt("0x"+e)}function _c(t,e,n){let r=Mr(t),o=e*n,i=new st(e,n);for(let s=0;s<o;s++)i.data[s]=Number(r>>BigInt(o-1-s)&1n);return i}function Jc(t,e,n){let r=Mr(t),o=e*n,i=new st(e,n);for(let s=0;s<o;s++){let a=BigInt((o-1-s)*2);i.data[s]=Number(r>>a&3n)}return i}function Uc(t,e,n){let r=new st(e,n),o=0;for(let i=0;i+1<t.length;i+=2){let s=t[i],a=t[i+1];for(let l=0;l<s&&o<r.data.length;l++)r.data[o++]=a}return r}function Kc(t){let e=[],n=t.data;for(let r=0;r<n.length;){let o=n[r],i=1;for(;r+i<n.length&&n[r+i]===o;)i++;e.push(i,o),r+=i}return e}function rs(t,e,n={}){let r=n.cell??1,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??le,l=[];for(let u=0;u<t.height;u++){let c=0;for(;c<t.width;){let m=t.get(c,u),d=e[m];if(d==null){c++;continue}let p=1;for(;c+p<t.width&&t.get(c+p,u)===m;)p++;l.push({kind:"rect",x:o+c*r,y:i+u*r,w:p*r,h:r,transform:a,z:s,fill:d}),c+=p}}return l}var Sr=class extends j{type="TextureSprite";buffer;palette;cell;center;constructor(e){super(e),this.buffer=e.buffer,this.palette=e.palette,this.cell=e.cell??1,this.center=e.center??!0,this.cosmetic=!0}draw(e,n){let r=this.cell,o=this.center?-(this.buffer.width*r)/2:0,i=this.center?-(this.buffer.height*r)/2:0;for(let s of rs(this.buffer,this.palette,{cell:r,x:o,y:i,z:this.z,transform:n}))e.push(s)}};var os={A:[".#.","#.#","###","#.#","#.#"],B:["##.","#.#","##.","#.#","##."],C:[".##","#..","#..","#..",".##"],D:["##.","#.#","#.#","#.#","##."],E:["###","#..","##.","#..","###"],F:["###","#..","##.","#..","#.."],G:[".##","#..","#.#","#.#",".##"],H:["#.#","#.#","###","#.#","#.#"],I:["#","#","#","#","#"],J:["..#","..#","..#","#.#",".#."],K:["#.#","##.","#..","##.","#.#"],L:["#..","#..","#..","#..","###"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#...#","##..#","#.#.#","#..##","#...#"],O:[".#.","#.#","#.#","#.#",".#."],P:["##.","#.#","##.","#..","#.."],Q:[".#.","#.#","#.#","#.#",".##"],R:["##.","#.#","##.","#.#","#.#"],S:[".##","#..",".#.","..#","##."],T:["###",".#.",".#.",".#.",".#."],U:["#.#","#.#","#.#","#.#","###"],V:["#.#","#.#","#.#","#.#",".#."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#.#","#.#",".#.","#.#","#.#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["###","..#",".#.","#..","###"],0:[".#.","#.#","#.#","#.#",".#."],1:[".#.","##.",".#.",".#.","###"],2:["##.","..#",".#.","#..","###"],3:["##.","..#",".#.","..#","##."],4:["#.#","#.#","###","..#","..#"],5:["###","#..","##.","..#","##."],6:[".##","#..","##.","#.#",".#."],7:["###","..#",".#.",".#.",".#."],8:[".#.","#.#",".#.","#.#",".#."],9:[".#.","#.#",".##","..#","##."],".":[".",".",".",".","#"],",":["..","..","..",".#","#."],"!":["#","#","#",".","#"],"?":["##.","..#",".#.","...",".#."],":":[".","#",".","#","."],";":["..",".#","..",".#","#."],"-":["...","...","###","...","..."],"+":["...",".#.","###",".#.","..."],"=":["...","###","...","###","..."],"/":["..#","..#",".#.","#..","#.."],"'":["#","#",".",".","."],'"':["#.#","#.#","...","...","..."],"(":[".#","#.","#.","#.",".#"],")":["#.",".#",".#",".#","#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"%":["#.#","..#",".#.","#..","#.#"],"*":["...","#.#",".#.","#.#","..."],"#":["#.#","###","#.#","###","#.#"]},Cr={height:5,tracking:1,spaceWidth:3,glyphs:os};function is(t,e={}){let n=[],r=[],o=0,i=0;for(;o<t.length;){let s=t[o];if(s==="{"&&t[o+1]==="{"){n.push({ch:"{",color:r[r.length-1],i:i++}),o+=2;continue}if(s==="{"){let a=t.indexOf("}",o);if(a===-1){n.push({ch:s,color:r[r.length-1],i:i++}),o++;continue}let l=t.slice(o+1,a);l==="/"?r.pop():r.push(l[0]==="#"?l:e[l]??l),o=a+1;continue}n.push({ch:s,color:r[r.length-1],i:i++}),o++}return n}function Rr(t,e){if(e===" "||e===`
2
+ `)return e;let n=e.toUpperCase();return t.glyphs[n]?n:t.glyphs[e]?e:t.glyphs["?"]?"?":" "}function Pr(t,e){if(e===" ")return t.spaceWidth;let n=t.glyphs[e];return n?n[0].length:t.spaceWidth}function at(t,e){let n=0;for(let r=0;r<e.length;r++)n+=Pr(t,e[r].ch),r<e.length-1&&(n+=t.tracking);return n}function tm(t,e){return at(t,[...e].map((n,r)=>({ch:Rr(t,n),i:r})))}function ss(t,e,n={}){let r=n.lineSpacing??1,o=typeof e=="string"?[...e].map((m,d)=>({ch:m,i:d})):e.map(m=>({...m})),i=[[]];for(let m of o)m.ch===`
3
+ `?i.push([]):i[i.length-1].push({...m,ch:Rr(t,m.ch)});let s=[];for(let m of i){if(n.maxWidth===void 0){s.push(m);continue}let d=[],p=[],h=()=>{if(p.length===0)return;let g=d.length?t.spaceWidth+t.tracking:0;d.length&&at(t,d)+g+at(t,p)>n.maxWidth&&(s.push(d),d=[]),d.length&&d.push({ch:" ",i:-1}),d.push(...p),p=[]};for(let g of m)g.ch===" "?h():p.push(g);h(),s.push(d)}let a=[],l=0;for(let m of s)l=Math.max(l,at(t,m));let u=n.maxWidth??l,c=0;for(let m of s){let d=at(t,m),p=n.align==="center"?Math.floor((u-d)/2):n.align==="right"?u-d:0;for(let h of m){let g=Pr(t,h.ch);h.ch!==" "&&a.push({ch:h.ch,color:h.color,i:h.i,x:p,y:c,w:g}),p+=g+t.tracking}c+=t.height+r}return{glyphs:a,width:u,height:s.length*(t.height+r)-r,lines:s.length}}function as(t,e,n){if(n<=0)return t;let r=Math.floor(e*n);return r<0?0:r>t?t:r}function ls(t,e,n={}){let r=n.cell??2,o=n.x??0,i=n.y??0,s=n.z??0,a=n.transform??le,l=n.color??"#000",u=n.reveal,c=[];for(let m of e.glyphs){if(u!==void 0&&m.i>=u)continue;let d=t.glyphs[m.ch];if(!d)continue;let p=m.color??l;for(let h=0;h<d.length;h++){let g=d[h],x=0;for(;x<g.length;){if(g[x]!=="#"){x++;continue}let k=1;for(;x+k<g.length&&g[x+k]==="#";)k++;c.push({kind:"rect",x:o+(m.x+x)*r,y:i+(m.y+h)*r,w:k*r,h:r,transform:a,z:s,fill:p}),x+=k}}}return c}var Tr=class extends j{type="BitmapText";text;font;cell;color;colorMap;maxWidth;lineSpacing;align;charsPerSec;center;startTime=0;constructor(e){super(e),this.text=e.text,this.font=e.font??Cr,this.cell=e.cell??2,this.color=e.color??"#000",this.colorMap=e.colorMap??{},this.maxWidth=e.maxWidth,this.lineSpacing=e.lineSpacing??1,this.align=e.align??"left",this.charsPerSec=e.charsPerSec,this.center=e.center??!1,this.cosmetic=!0}onReady(){this.startTime=this.world?.time??0}restartReveal(){this.startTime=this.world?.time??0}buildLayout(){let e=is(this.text,this.colorMap);return ss(this.font,e,{maxWidth:this.maxWidth,lineSpacing:this.lineSpacing,align:this.align})}draw(e,n){let r=this.buildLayout(),o;if(this.charsPerSec!==void 0){let a=(this.world?.time??0)-this.startTime;o=as(this.text.length,a,this.charsPerSec)}let i=this.center?-(r.width*this.cell)/2:0,s=this.center?-(r.height*this.cell)/2:0;for(let a of ls(this.font,r,{cell:this.cell,x:i,y:s,z:this.z,color:this.color,transform:n,reveal:o}))e.push(a)}};function om(t,e="#"){return t.map(n=>[...n].map(r=>e.includes(r)))}function De(t,e,n){return n>=0&&n<t.length&&e>=0&&e<t[n].length&&t[n][e]}var ee={N:1,E:2,S:4,W:8};function Dr(t,e,n){return(De(t,e,n-1)?ee.N:0)|(De(t,e+1,n)?ee.E:0)|(De(t,e,n+1)?ee.S:0)|(De(t,e-1,n)?ee.W:0)}function im(t,e,n){let r=0,o=[[0,-1],[1,-1],[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1]];for(let i=0;i<8;i++)De(t,e+o[i][0],n+o[i][1])&&(r|=1<<i);return r}var Je={Isolated:0,Cap:1,Straight:2,Bend:3,Tee:4,Cross:5};function us(t){let e=0;return t&ee.N&&(e|=ee.E),t&ee.E&&(e|=ee.S),t&ee.S&&(e|=ee.W),t&ee.W&&(e|=ee.N),e}var cs=(()=>{let t=[[Je.Isolated,0],[Je.Cap,ee.N],[Je.Straight,ee.N|ee.S],[Je.Bend,ee.N|ee.E],[Je.Tee,ee.N|ee.E|ee.S],[Je.Cross,15]],e=new Array(16);for(let[n,r]of t){let o=r;for(let i=0;i<4;i++)e[o]===void 0&&(e[o]={mask:o,frame:n,rotation:i}),o=us(o)}return e})();function ms(t){return cs[t&15]}function sm(t){return t.map((e,n)=>e.map((r,o)=>r?ms(Dr(t,o,n)):null))}function ds(t){let e=t.length,n=e?t[0].length:0,r=[];for(let o=0;o<e-1;o++){let i=[];for(let s=0;s<n-1;s++)i.push((De(t,s,o)?1:0)|(De(t,s+1,o)?2:0)|(De(t,s+1,o+1)?4:0)|(De(t,s,o+1)?8:0));r.push(i)}return r}var ps=[[],[["L","T"]],[["T","R"]],[["L","R"]],[["R","B"]],[["L","T"],["R","B"]],[["T","B"]],[["L","B"]],[["B","L"]],[["T","B"]],[["T","R"],["B","L"]],[["R","B"]],[["L","R"]],[["T","R"]],[["L","T"]],[]];function hs(t,e={}){let n=e.cell??1,r=e.x??0,o=e.y??0,i=ds(t),s=[],a=(l,u,c)=>{switch(l){case"T":return{x:u+n/2,y:c};case"R":return{x:u+n,y:c+n/2};case"B":return{x:u+n/2,y:c+n};case"L":return{x:u,y:c+n/2}}};for(let l=0;l<i.length;l++)for(let u=0;u<i[l].length;u++){let c=r+u*n,m=o+l*n;for(let[d,p]of ps[i[l][u]])s.push({a:a(d,c,m),b:a(p,c,m)})}return s}function am(t,e={}){let n=e.tile??8,r=e.x??0,o=e.y??0,i=e.z??0,s=e.transform??le,a=e.fill??"#888",l=e.edge,u=e.edgeWidth??Math.max(1,n/8),c=[];for(let m=0;m<t.length;m++)for(let d=0;d<t[m].length;d++){if(!t[m][d])continue;let p=r+d*n,h=o+m*n;if(c.push({kind:"rect",x:p,y:h,w:n,h:n,transform:s,z:i,fill:a}),!l)continue;let g=Dr(t,d,m),x=k=>c.push({kind:"poly",points:k,closed:!1,transform:s,z:i+1,stroke:l,strokeWidth:u});g&ee.N||x([p,h,p+n,h]),g&ee.E||x([p+n,h,p+n,h+n]),g&ee.S||x([p,h+n,p+n,h+n]),g&ee.W||x([p,h,p,h+n])}return c}function lm(t,e={}){let n=e.tile??8,r=e.transform??le,o=e.z??0,i=e.edge??e.fill??"#333",s=e.edgeWidth??Math.max(1,n/8);return hs(t,{cell:n,x:e.x??0,y:e.y??0}).map(l=>({kind:"poly",points:[l.a.x,l.a.y,l.b.x,l.b.y],closed:!1,transform:r,z:o,stroke:i,strokeWidth:s,round:!0}))}function lt(t,e,n=0){return{cols:t,rows:e,cells:new Array(t*e).fill(n)}}function fs(t,e,n){return e<0||n<0||e>=t.cols||n>=t.rows?1:t.cells[n*t.cols+e]}function Fe(t,e,n,r){e<0||n<0||e>=t.cols||n>=t.rows||(t.cells[n*t.cols+e]=r)}function Ir(t,e,n){let r=0;for(let o=-1;o<=1;o++)for(let i=-1;i<=1;i++)i===0&&o===0||fs(t,e+i,n+o)===1&&r++;return r}function mm(t,e=32){let n=t.cells.map(r=>r===1?H.SOLID:H.EMPTY);return{cols:t.cols,rows:t.rows,tileSize:e,tiles:n}}function bs(t,e,n=0){let r=(n^2654435769)>>>0;return r=Math.imul(r^(t|0),2246822507)>>>0,r=Math.imul(r^(e|0),3266489909)>>>0,r^=r>>>13,r=Math.imul(r,668265263)>>>0,r^=r>>>15,r>>>0}function Ue(t,e,n=0){return bs(t,e,n)/4294967296}function pm(t,e,n,r=0){return Math.floor(Ue(t,e,r)*n)}function gs(t,e,n,r=0){return Ue(t,e,r)<n}function hm(t,e,n,r,o,i=0){let s=[];for(let a=e;a<e+r;a++)for(let l=t;l<t+n;l++)gs(l,a,o,i)&&s.push({x:l,y:a});return s}var Er=t=>t*t*(3-2*t);function ys(t,e,n=0){let r=Math.floor(t),o=Math.floor(e),i=Er(t-r),s=Er(e-o),a=Ue(r,o,n),l=Ue(r+1,o,n),u=Ue(r,o+1,n),c=Ue(r+1,o+1,n),m=a+(l-a)*i,d=u+(c-u)*i;return m+(d-m)*s}function Fr(t,e,n=0,r={}){let o=r.octaves??4,i=r.lacunarity??2,s=r.gain??.5,a=1,l=1,u=0,c=0;for(let m=0;m<o;m++)u+=a*ys(t*l,e*l,n+m),c+=a,a*=s,l*=i;return c===0?0:u/c}function gm(t,e){let{cols:n,rows:r}=e,o=e.fill??.45,i=e.steps??4,s=e.birth??5,a=e.survive??4,l=e.border??!0,u=lt(n,r,0);for(let c=0;c<r;c++)for(let m=0;m<n;m++){let d=l&&(m===0||c===0||m===n-1||c===r-1);Fe(u,m,c,d||t.chance(o)?1:0)}for(let c=0;c<i;c++){let m=lt(n,r,0);for(let d=0;d<r;d++)for(let p=0;p<n;p++){if(l&&(p===0||d===0||p===n-1||d===r-1)){Fe(m,p,d,1);continue}let h=Ir(u,p,d),g=u.cells[d*n+p]===1;Fe(m,p,d,(g?h>=a:h>=s)?1:0)}u=m}return u}function Nr(t,e){let n=e.scale??.08,r=e.seed??0,o=Fr(t*n,0,r,e.fractal)*2-1,i=Math.round(e.base+o*e.amplitude);return(e.minRow!==void 0||e.maxRow!==void 0)&&(i=K(i,e.minRow??-1/0,e.maxRow??1/0)),i}function wm(t,e,n){let r=new Array(e);for(let o=0;o<e;o++)r[o]=Nr(t+o,n);return r}function km(t,e,n){return e>=Nr(t,n)}function $r(t){return{x:Math.floor(t.x+t.w/2),y:Math.floor(t.y+t.h/2)}}function xs(t,e){return t.x<=e.x+e.w&&t.x+t.w>=e.x&&t.y<=e.y+e.h&&t.y+t.h>=e.y}function vs(t,e){for(let n=e.y;n<e.y+e.h;n++)for(let r=e.x;r<e.x+e.w;r++)Fe(t,r,n,0)}function Ar(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,o,r,0)}function Lr(t,e,n,r){for(let o=Math.min(e,n);o<=Math.max(e,n);o++)Fe(t,r,o,0)}function Cm(t,e){let{cols:n,rows:r}=e,o=e.attempts??12,i=e.minSize??4,s=e.maxSize??8,a=e.border??!0?1:0,l=lt(n,r,1),u=[];for(let c=0;c<o;c++){let m=t.intRange(i,s),d=t.intRange(i,s),p=t.intRange(a,n-m-a-1),h=t.intRange(a,r-d-a-1);if(p<a||h<a)continue;let g={x:p,y:h,w:m,h:d};if(!u.some(x=>xs(g,x))){if(vs(l,g),u.length>0){let x=$r(u[u.length-1]),k=$r(g);t.chance(.5)?(Ar(l,x.x,k.x,x.y),Lr(l,x.y,k.y,k.x)):(Lr(l,x.y,k.y,x.x),Ar(l,x.x,k.x,k.y))}u.push(g)}}return{rooms:u,grid:l}}var be=44100;function Wr(t,e=be){let n=Math.max(0,Math.round(t*e));return{sampleRate:e,left:new Float32Array(n),right:new Float32Array(n)}}function Dm(t){return t.left.length}function Im(t){return t.left.length/t.sampleRate}function ws(t){let n=(K(t,-1,1)+1)*.5*(Math.PI/2);return{l:Q(n),r:_(n)}}function Br(t,e,n,r=1,o=0){let{l:i,r:s}=ws(o),a=r*i,l=r*s,u=t.left.length,c=Math.round(n);for(let m=0;m<e.length;m++){let d=c+m;if(d<0)continue;if(d>=u)break;let p=e[m];t.left[d]+=p*a,t.right[d]+=p*l}}function ks(t){let e=0,{left:n,right:r}=t;for(let o=0;o<n.length;o++){let i=n[o]<0?-n[o]:n[o];i>e&&(e=i);let s=r[o]<0?-r[o]:r[o];s>e&&(e=s)}return e}function zr(t){return t/Math.sqrt(1+t*t)}function Or(t){let{left:e,right:n}=t;for(let r=0;r<e.length;r++)e[r]=zr(e[r]),n[r]=zr(n[r])}function Gr(t,e=.89){let n=ks(t);if(n<1e-9)return;let r=e/n,{left:o,right:i}=t;for(let s=0;s<o.length;s++)o[s]*=r,i[s]*=r}function Em(t){let{left:e,right:n,sampleRate:r}=t,o=e.length,i=2,a=i*2,l=o*a,u=new Uint8Array(44+l),c=new DataView(u.buffer),m=(p,h)=>{for(let g=0;g<h.length;g++)c.setUint8(p+g,h.charCodeAt(g))};m(0,"RIFF"),c.setUint32(4,36+l,!0),m(8,"WAVE"),m(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,i,!0),c.setUint32(24,r,!0),c.setUint32(28,r*a,!0),c.setUint16(32,a,!0),c.setUint16(34,16,!0),m(36,"data"),c.setUint32(40,l,!0);let d=44;for(let p=0;p<o;p++){let h=K(e[p],-1,1),g=K(n[p],-1,1);c.setInt16(d,(h<0?h*32768:h*32767)|0,!0),c.setInt16(d+2,(g<0?g*32768:g*32767)|0,!0),d+=4}return u}function Fm(t){let e=2166136261;for(let n=0;n<t.length;n++){let r=K(t[n],-1,1)*32767|0;e^=r&255,e=Math.imul(e,16777619),e^=r>>8&255,e=Math.imul(e,16777619)}return e>>>0}function Ss(t){return{freq:t.freq??220,wave:t.wave??"sine",duty:t.duty??.5,attack:Math.max(0,t.attack??.005),decay:Math.max(0,t.decay??0),sustain:Math.max(0,t.sustain??.08),release:Math.max(0,t.release??.1),sustainLevel:t.sustainLevel??1,punch:t.punch??0,volume:t.volume??.5,slide:t.slide??0,slideAccel:t.slideAccel??0,pitchJump:t.pitchJump??0,pitchJumpTime:t.pitchJumpTime??0,vibrato:t.vibrato??0,vibratoFreq:t.vibratoFreq??6,detune:t.detune??0,sub:Math.max(0,t.sub??0),noise:t.noise??0,shapeCurve:Math.max(.01,t.shapeCurve??1),fm:t.fm??0,fmFreq:t.fmFreq??0,tremolo:t.tremolo??0,tremoloFreq:t.tremoloFreq??8,bitCrush:Math.max(0,Math.floor(t.bitCrush??0)),lowpass:t.lowpass??0,highpass:t.highpass??0,delay:Math.max(0,t.delay??0),delayFeedback:Math.min(.95,Math.max(0,t.delayFeedback??0))}}function Gt(t){return he(t/12)}function Vr(t,e,n,r){switch(t){case"sine":return _(se*e);case"saw":return 2*e-1;case"square":return e<n?1:-1;case"triangle":return(e<.5?e*2:2-e*2)*2-1;case"noise":return r.float()*2-1}}function Vt(t,e={}){let n=Ss(t),r=e.sampleRate??be,o=e.rng??new ce(24301),i=n.attack+n.decay+n.sustain+n.release,s=n.delay>0?n.delay*6:0,a=i+s+.01,l=Math.max(1,Math.round(a*r)),u=new Float32Array(l),c=1/r,m=0,d=0,p=0,h=n.detune!==0?Gt(n.detune/100):1,g=0,x=0,k=0,w=0,P=n.lowpass>0?qr(n.lowpass,r):1,$=n.highpass>0?1-qr(n.highpass,r):0,v=r*.5;for(let f=0;f<l;f++){let M=f*c,S=Ms(M,n);n.punch>0&&(S*=1+n.punch*Math.max(0,1-M/Math.max(1e-4,n.attack+n.decay))),n.tremolo>0&&(S*=1-n.tremolo*.5*(1-_(se*n.tremoloFreq*M)));let D=i>0?M/i:0,C=n.freq*Gt(n.slide*D+n.slideAccel*D*D);n.pitchJump!==0&&M>=n.pitchJumpTime&&(C*=Gt(n.pitchJump)),n.vibrato>0&&(C*=Gt(n.vibrato*_(se*n.vibratoFreq*M))),n.fm>0&&(C+=n.fm*_(se*n.fmFreq*M)),C<0?C=0:C>v&&(C=v),m+=C*c,m-=Math.floor(m);let y=Vr(n.wave,m,n.duty,o);n.detune!==0&&(d+=C*h*c,d-=Math.floor(d),y=(y+Vr(n.wave,d,n.duty,o))*.5),n.sub>0&&(p+=C*.5*c,p-=Math.floor(p),y=y*(1-n.sub*.5)+_(se*p)*n.sub),n.noise>0&&(y=y*(1-n.noise)+(o.float()*2-1)*n.noise),n.shapeCurve!==1&&(y=(y<0?-1:1)*Pe(y<0?-y:y,n.shapeCurve)),y*=S*n.volume,n.bitCrush>0&&(f%n.bitCrush===0&&(g=y),y=g),u[f]=y}if(n.lowpass>0)for(let f=0;f<l;f++)x+=P*(u[f]-x),u[f]=x;if(n.highpass>0)for(let f=0;f<l;f++)k=$*(k+u[f]-w),w=u[f],u[f]=k;if(n.delay>0){let f=Math.max(1,Math.round(n.delay*r));for(let M=f;M<l;M++)u[M]+=u[M-f]*n.delayFeedback}return u}function qr(t,e){let n=se*t*(1/e);return n/(n+1)}function Ms(t,e){let n=e.attack,r=e.decay,o=e.sustain,i=e.release;if(t<n)return n>0?t/n:1;if(t<n+r)return r>0?1+(e.sustainLevel-1)*((t-n)/r):e.sustainLevel;if(t<n+r+o)return e.sustainLevel;let s=t-n-r-o;return s<i&&i>0?e.sustainLevel*(1-s/i):0}var Cs={C:0,"C#":1,Db:1,D:2,"D#":3,Eb:3,E:4,Fb:4,"E#":5,F:5,"F#":6,Gb:6,G:7,"G#":8,Ab:8,A:9,"A#":10,Bb:10,B:11,Cb:11,"B#":0},Ts=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];function me(t){let e=/^([A-Ga-g])([#b]?)(-?\d+)$/.exec(t.trim());if(!e)throw new Error(`bad note name: ${JSON.stringify(t)}`);let n=e[1].toUpperCase(),r=Cs[n+(e[2]||"")];if(r===void 0)throw new Error(`bad note name: ${JSON.stringify(t)}`);let o=parseInt(e[3],10);return r+(o+1)*12}function Om(t){let e=(t%12+12)%12,n=Math.floor(t/12)-1;return Ts[e]+n}function Rs(t,e=440){return e*he((t-69)/12)}function jr(t,e=440){return Rs(typeof t=="number"?t:me(t),e)}var Hr={major:[0,2,4,5,7,9,11],minor:[0,2,3,5,7,8,10],harmonicMinor:[0,2,3,5,7,8,11],melodicMinor:[0,2,3,5,7,9,11],dorian:[0,2,3,5,7,9,10],phrygian:[0,1,3,5,7,8,10],lydian:[0,2,4,6,7,9,11],mixolydian:[0,2,4,5,7,9,10],locrian:[0,1,3,5,6,8,10],majorPentatonic:[0,2,4,7,9],minorPentatonic:[0,3,5,7,10],blues:[0,3,5,6,7,10],chromatic:[0,1,2,3,4,5,6,7,8,9,10,11]};function dn(t,e="major",n=1){let r=Hr[e],o=[];for(let i=0;i<n;i++)for(let s of r)o.push(t+i*12+s);return o.push(t+n*12),o}function _r(t,e="major"){let n=(t%12+12)%12;return new Set(Hr[e].map(r=>(n+r)%12))}function Ps(t,e,n,r=3){let o=(n%7+7)%7,i=dn(t,e,3),s=[];for(let a=0;a<r;a++)s.push(i[o+a*2]);return s}var Ds={i:0,ii:1,iii:2,iv:3,v:4,vi:5,vii:6};function Ke(t,e,n){return n.map(r=>{let o=/^([iv]+|[IV]+)(7)?/i.exec(r.trim());if(!o)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);let i=Ds[o[1].toLowerCase()];if(i===void 0)throw new Error(`bad roman numeral: ${JSON.stringify(r)}`);return Ps(t,e,i,o[2]?4:3)})}function Gm(t,e){return t.map(n=>n+e)}function pn(t){return t.length<2?t.slice():[t[0]-12,...t.slice(1)].sort((e,n)=>e-n)}function ut(t){if(t.length===0)return[];let e=[t[0].slice().sort((n,r)=>n-r)];for(let n=1;n<t.length;n++){let r=e[n-1],o=r.reduce((s,a)=>s+a,0)/r.length,i=t[n].map(s=>{let a=s;for(;a-o>6;)a-=12;for(;o-a>6;)a+=12;return a}).sort((s,a)=>s-a);e.push(i)}return e}var Is=[1116,1188,1277,1356,1422,1491,1557,1617],Es=[556,441,341,225],Fs=23,Ns=.015,hn=class{constructor(e,n,r){this.feedback=n;this.damp=r;this.buf=new Float32Array(Math.max(1,e))}feedback;damp;buf;idx=0;store=0;process(e){let n=this.buf[this.idx];return this.store=n*(1-this.damp)+this.store*this.damp,this.buf[this.idx]=e+this.store*this.feedback,this.idx=(this.idx+1)%this.buf.length,n}},fn=class{constructor(e,n=.5){this.feedback=n;this.buf=new Float32Array(Math.max(1,e))}feedback;buf;idx=0;process(e){let n=this.buf[this.idx],r=-e+n;return this.buf[this.idx]=e+n*this.feedback,this.idx=(this.idx+1)%this.buf.length,r}};function Jr(t,e,n,r){let o=t/44100,i=Is.map(a=>new hn(Math.round((a+r)*o),e,n)),s=Es.map(a=>new fn(Math.round((a+r)*o),.5));return{combs:i,aps:s}}function Ur(t,e={}){let n=K(e.wet??.25,0,1),r=K(e.roomSize??.7,0,1),o=K(e.damp??.5,0,1)*.4,i=.7+r*.28,s=t.sampleRate,a=Jr(s,i,o,0),l=Jr(s,i,o,Fs),u=t.left.length;for(let c=0;c<u;c++){let m=(t.left[c]+t.right[c])*Ns,d=0;for(let h of a.combs)d+=h.process(m);for(let h of a.aps)d=h.process(d);let p=0;for(let h of l.combs)p+=h.process(m);for(let h of l.aps)p=h.process(p);t.left[c]=t.left[c]*(1-n)+d*n,t.right[c]=t.right[c]*(1-n)+p*n}}function $s(t){let e=0;for(let n of t)e+=n.beats;return e}function As(t){let e=0;for(let n of t.sequence)e+=$s(t.patterns[n]??[]);return e}function Ls(t){let e=0;for(let n of t.tracks)e=Math.max(e,As(n));return e}function bn(t){return Ls(t)*60/t.bpm}function Yr(t,e={}){let n=e.sampleRate??be,r=t.a4??440,o=60/t.bpm,i=t.tailSec??2,s=bn(t)+i,a=Wr(s,n),l=Math.max(0,Math.min(1,t.swing??0)),u=Math.max(0,Math.min(1,t.humanize??0)),c=Math.max(0,Math.min(1,t.velBrightness??.5));if(t.tracks.forEach((m,d)=>{let p=m.gain??.7,h=m.pan??0,g=new ce(5292449^(d+1)*2654435769),x=0;for(let k of m.sequence){let w=m.patterns[k];if(w)for(let P of w){if(P.pitch!==null&&P.pitch!==void 0){let $=Math.round(x*2),f=Math.abs(x*2-$)<1e-4&&$%2===1?x+l*.2:x,M=u>0?g.range(-1,1)*u*.012:0,S=Math.round((f*o+M)*n),D=P.beats*o,C=u>0?g.range(-1,1)*u*.12:0,y=Math.max(.05,Math.min(1,(P.vel??1)+C)),T=Array.isArray(P.pitch)?P.pitch:[P.pitch],E=m.instrument.attack??.005,O=m.instrument.decay??0,F=Math.max(.01,D-E-O),J=m.instrument.lowpass,Y=J&&c>0?J*(1-c*(1-y)):J;for(let ne of T){let X={...m.instrument,freq:jr(ne,r),sustain:F,volume:(m.instrument.volume??.5)*y,...Y!==void 0?{lowpass:Y}:{}},ae=Vt(X,{rng:g,sampleRate:n});Br(a,ae,Math.max(0,S),p,h)}}x+=P.beats}}}),t.sidechain){let m=Math.max(0,Math.min(1,t.sidechain.depth??.5)),d=(t.sidechain.beatsPerCycle??1)*o;Bs(a,d,m)}return t.reverb&&Ur(a,t.reverb),t.master&&Ws(a,t.master),t.master?.compress&&zs(a,t.master.compress),Or(a),Gr(a,e.normalizePeak??.89),a}function zs(t,e){let n=Math.max(0,Math.min(1,e)),r=t.sampleRate,o=Kr(-20),i=2+n*3,s=Oe(-1/(r*.005)),a=Oe(-1/(r*.15)),l=Kr(n*6),u=0,c=t.left,m=t.right;for(let d=0;d<c.length;d++){let p=Math.max(Math.abs(c[d]),Math.abs(m[d])),h=p>u?s:a;u=h*u+(1-h)*p;let g=1;if(u>o){let k=u/o;g=o*Pe(k,1/i)/u}let x=g*l;c[d]*=x,m[d]*=x}}function Kr(t){return he(t/6.020599913)}function Ws(t,e){let n=t.sampleRate,r=Math.max(0,e.lowCut??0),o=Math.max(0,e.presence??0),i=Math.max(0,e.air??0),s=c=>{let m=se*c*(1/n);return m/(m+1)},a=s(240),l=1-s(3200),u=1-s(9e3);for(let c of[t.left,t.right]){let m=0,d=0,p=0,h=0,g=0;for(let x=0;x<c.length;x++){let k=c[x];m+=a*(k-m),d=l*(d+k-p),p=k,h=u*(h+k-g),g=k,c[x]=k-r*m+o*d+i*h}}}function Bs(t,e,n){let r=t.sampleRate,o=Math.max(1,e*r);for(let i=0;i<t.left.length;i++){let a=1-i%o/o,l=1-n*a*a;t.left[i]*=l,t.right[i]*=l}}var A={lead:{wave:"square",duty:.5,attack:.008,release:.08,volume:.4,lowpass:4e3,detune:6},pluck:{wave:"triangle",attack:.002,decay:.06,sustainLevel:.3,release:.12,volume:.42},pad:{wave:"saw",attack:.12,release:.5,volume:.26,lowpass:2200,vibrato:.08,vibratoFreq:4,detune:14},bell:{wave:"sine",attack:.002,decay:.3,sustainLevel:.2,release:.5,volume:.4,fm:3,fmFreq:220},piano:{wave:"triangle",attack:.002,decay:.5,sustainLevel:.12,release:.35,volume:.42,lowpass:3600,detune:4},rhodes:{wave:"sine",attack:.003,decay:.45,sustainLevel:.35,release:.4,volume:.4,fm:2.2,fmFreq:440,detune:5},strings:{wave:"saw",attack:.16,decay:.2,sustainLevel:.85,release:.6,volume:.24,lowpass:2600,detune:16,vibrato:.07,vibratoFreq:5},brass:{wave:"saw",attack:.04,decay:.1,sustainLevel:.8,release:.16,volume:.3,lowpass:3200,detune:8,punch:.3},organ:{wave:"sine",attack:.006,release:.05,sustainLevel:1,volume:.32,sub:.5,detune:3},choir:{wave:"triangle",attack:.28,release:.9,sustainLevel:.9,volume:.22,lowpass:2e3,detune:20,vibrato:.1,vibratoFreq:4.5},glocken:{wave:"sine",attack:.001,decay:.6,sustainLevel:0,release:.4,volume:.34,fm:4,fmFreq:1600},vibraphone:{wave:"sine",attack:.002,decay:.5,sustainLevel:.25,release:.7,volume:.4,fm:2,fmFreq:880,tremolo:.25,tremoloFreq:5},clav:{wave:"square",duty:.35,attack:.001,decay:.08,sustainLevel:.25,release:.08,volume:.32,lowpass:3800,detune:4},uprightBass:{wave:"triangle",attack:.004,decay:.12,sustainLevel:.5,release:.1,volume:.5,lowpass:1100,sub:.35},mutedTrumpet:{wave:"saw",attack:.03,decay:.08,sustainLevel:.75,release:.14,volume:.3,lowpass:2600,detune:4,vibrato:.09,vibratoFreq:6},jazzGuitar:{wave:"triangle",attack:.004,decay:.35,sustainLevel:.2,release:.25,volume:.34,lowpass:2400,detune:5},horns:{wave:"saw",attack:.02,decay:.08,sustainLevel:.7,release:.12,volume:.3,lowpass:3600,detune:10,punch:.4},bass:{wave:"saw",attack:.006,release:.06,volume:.5,lowpass:900,detune:6,sub:.3},subBass:{wave:"sine",attack:.004,release:.08,volume:.6,lowpass:400,sub:.5,punch:.2},kick:{wave:"sine",attack:.001,decay:.06,sustainLevel:0,release:.08,slide:-24,volume:.7,sub:.3},snare:{wave:"noise",attack:.001,decay:.05,sustainLevel:.2,release:.12,highpass:1200,volume:.5},hat:{wave:"noise",attack:.001,release:.04,highpass:6e3,volume:.28},rimshot:{wave:"noise",attack:.001,release:.03,highpass:3e3,lowpass:7e3,volume:.3},ride:{wave:"noise",attack:.001,decay:.1,sustainLevel:.14,release:.32,volume:.2,highpass:1600,lowpass:7e3}};var Os={master:.7,music:.6,sfx:.8,muted:!1},gn=class{ctx=null;master=null;musicGain=null;sfxGain=null;vol={...Os};padOn=!1;get available(){return typeof globalThis.AudioContext<"u"||"webkitAudioContext"in globalThis}get started(){return!!this.ctx}start(){if(this.ctx){this.ctx.resume();return}if(!this.available)return;let e=globalThis.AudioContext||globalThis.webkitAudioContext;this.ctx=new e,this.master=this.ctx.createGain(),this.musicGain=this.ctx.createGain(),this.sfxGain=this.ctx.createGain(),this.musicGain.connect(this.master),this.sfxGain.connect(this.master),this.master.connect(this.ctx.destination),this.applyVolumes()}setVolumes(e){this.vol={...this.vol,...e},this.applyVolumes()}getVolumes(){return{...this.vol}}applyVolumes(){if(!this.ctx||!this.master||!this.musicGain||!this.sfxGain)return;let e=this.ctx.currentTime;this.master.gain.setTargetAtTime(this.vol.muted?0:this.vol.master,e,.04),this.musicGain.gain.setTargetAtTime(this.vol.music*.5,e,.04),this.sfxGain.gain.setTargetAtTime(this.vol.sfx,e,.04)}tone(e){if(!this.ctx||!this.sfxGain)return;let{freq:n,duration:r,type:o="sine",gain:i=.2,delay:s=0,pan:a}=e,l=this.ctx.currentTime+s,u=this.ctx.createOscillator();u.type=o,u.frequency.value=n;let c=this.ctx.createGain();if(c.gain.setValueAtTime(0,l),c.gain.linearRampToValueAtTime(i,l+.008),c.gain.exponentialRampToValueAtTime(1e-4,l+r),u.connect(c),a!==void 0&&typeof this.ctx.createStereoPanner=="function"){let m=this.ctx.createStereoPanner();m.pan.value=Math.max(-1,Math.min(1,a)),c.connect(m),m.connect(this.sfxGain)}else c.connect(this.sfxGain);u.start(l),u.stop(l+r+.05)}spatial(e,n,r,o=600,i=.18,s="sawtooth"){if(r>o)return;let a=1-r/o;this.tone({freq:e,duration:i,type:s,gain:.04+a*a*.3,pan:Math.max(-1,Math.min(1,n/(o*.6)))})}play(e){for(let n of e)this.tone(n)}playSpec(e,n={}){if(!this.ctx||!this.sfxGain)return;let r=Vt(e,{sampleRate:this.ctx.sampleRate}),o=this.ctx.createBuffer(1,r.length,this.ctx.sampleRate);o.copyToChannel(new Float32Array(r),0);let i=this.ctx.createBufferSource();i.buffer=o;let s=this.ctx.createGain();if(s.gain.value=n.gain??1,i.connect(s),n.pan!==void 0&&typeof this.ctx.createStereoPanner=="function"){let a=this.ctx.createStereoPanner();a.pan.value=Math.max(-1,Math.min(1,n.pan)),s.connect(a),a.connect(this.sfxGain)}else s.connect(this.sfxGain);i.start(this.ctx.currentTime+(n.when??0))}playSong(e,n={}){if(!this.ctx||!this.musicGain)return()=>{};let r=Yr(e,{sampleRate:this.ctx.sampleRate}),o=this.ctx.createBuffer(2,r.left.length,this.ctx.sampleRate);o.copyToChannel(new Float32Array(r.left),0),o.copyToChannel(new Float32Array(r.right),1);let i=this.ctx.createBufferSource();return i.buffer=o,n.loop&&(i.loop=!0,i.loopStart=0,i.loopEnd=bn(e)),i.connect(this.musicGain),i.start(),()=>{try{i.stop()}catch{}}}blip(e=520){this.tone({freq:e,duration:.06,type:"sine",gain:.18})}chime(){[523.25,659.25,783.99].forEach((e,n)=>this.tone({freq:e,duration:.9-n*.15,type:"sine",gain:.15,delay:n*.04}))}success(){[392,493.88,587.33,783.99].forEach((e,n)=>this.tone({freq:e,duration:.4,type:"triangle",gain:.15,delay:n*.08}))}thud(){this.tone({freq:130,duration:.14,type:"sine",gain:.22})}startAmbient(e=110,n=[1,1.5,2,2.5]){if(!this.ctx||!this.musicGain||this.padOn)return;this.padOn=!0;let r=this.ctx.createBiquadFilter();r.type="lowpass",r.frequency.value=900,r.connect(this.musicGain);let o=this.ctx.createGain();o.gain.value=0,o.connect(r);for(let i of n){let s=this.ctx.createOscillator();s.type="triangle",s.frequency.value=e*i;let a=this.ctx.createGain();a.gain.value=.1/n.length,s.connect(a),a.connect(o),s.start()}o.gain.setTargetAtTime(.9,this.ctx.currentTime,3)}},Be=new gn;function yn(t){let e=t<0?-t:t;return e<1e-12?-1/0:20*St(e)}function ct(t){if(t.length===0)return 0;let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];return Math.sqrt(e/t.length)}function Xr(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n]<0?-t[n]:t[n];r>e&&(e=r)}return e}function Gs(t,e=be){if(t.length<2)return 0;let n=0;for(let r=1;r<t.length;r++)(t[r-1]<0&&t[r]>=0||t[r-1]>=0&&t[r]<0)&&n++;return n*e/t.length}function Vs(t){let e=1;for(;e*2<=t;)e*=2;return e}function qs(t,e){let n=t.length;for(let r=1,o=0;r<n;r++){let i=n>>1;for(;o&i;i>>=1)o^=i;if(o^=i,r<o){let s=t[r];t[r]=t[o],t[o]=s;let a=e[r];e[r]=e[o],e[o]=a}}for(let r=2;r<=n;r<<=1){let o=-se/r,i=Q(o),s=_(o);for(let a=0;a<n;a+=r){let l=1,u=0;for(let c=0;c<r/2;c++){let m=a+c,d=m+r/2,p=l*t[d]-u*e[d],h=l*e[d]+u*t[d];t[d]=t[m]-p,e[d]=e[m]-h,t[m]+=p,e[m]+=h;let g=l*i-u*s;u=l*s+u*i,l=g}}}}function mt(t){let e=Vs(t.length);if(e<2)return new Float32Array(0);let n=new Float32Array(e),r=new Float32Array(e);for(let s=0;s<e;s++){let a=.5-.5*Q(se*s/(e-1));n[s]=t[s]*a}qs(n,r);let o=e>>1,i=new Float32Array(o);for(let s=0;s<o;s++)i[s]=Math.sqrt(n[s]*n[s]+r[s]*r[s]);return i}function js(t,e=be){if(t.length<64)return 0;let r=2048,o=0,i=0;for(let s=0;s+64<=t.length;s+=r){let a=t.subarray(s,Math.min(s+2048,t.length)),l=mt(a),u=e/(l.length*2);for(let c=0;c<l.length;c++)o+=c*u*l[c],i+=l[c]}return i<1e-9?0:o/i}function Qr(t,e=1024,n=512){let r=[],o=null;for(let i=0;i+e<=t.length;i+=n){let s=mt(t.subarray(i,i+e)),a=0;if(o){let l=Math.min(s.length,o.length);for(let u=0;u<l;u++){let c=s[u]-o[u];c>0&&(a+=c)}}r.push(a),o=s}return Float32Array.from(r)}function Hs(t,e=be){let r=Qr(t,1024,512);if(r.length<3)return 0;let o=0;for(let l=0;l<r.length;l++)o+=r[l];o/=r.length;let i=o*1.5,s=0;for(let l=1;l<r.length-1;l++)r[l]>i&&r[l]>=r[l-1]&&r[l]>r[l+1]&&s++;let a=t.length/e;return a<1e-6?0:s/a}function _s(t,e=be){let r=Qr(t,1024,512);if(r.length<8)return 0;let o=e/512,i=Math.max(1,Math.ceil(o*60/200)),s=Math.min(r.length-1,Math.floor(o*60/60)),a=0,l=-1;for(let c=i;c<=s;c++){let m=0;for(let d=c;d<r.length;d++)m+=r[d]*r[d-c];m/=r.length-c,m>l&&(l=m,a=c)}if(a===0)return 0;let u=60*o/a;for(;u>150;)u/=2;for(;u>0&&u<70;)u*=2;return u}function Zr(t){let e=ct(t);return e<1e-9?0:yn(Xr(t))-yn(e)}function eo(t,e=be){let r=[20,60,250,800,2500,8e3,e/2],o=new Float64Array(6);if(t.length>=64)for(let s=0;s+64<=t.length;s+=2048){let a=mt(t.subarray(s,Math.min(s+2048,t.length))),l=e/(a.length*2);for(let u=0;u<a.length;u++){let c=u*l,m=a[u]*a[u];for(let d=0;d<6;d++)if(c>=r[d]&&c<r[d+1]){o[d]+=m;break}}}let i=o.reduce((s,a)=>s+a,0)||1;return{sub:o[0]/i,bass:o[1]/i,lowMid:o[2]/i,mid:o[3]/i,high:o[4]/i,air:o[5]/i}}function dt(t,e=be){return{durationSec:t.length/e,rms:ct(t),peakDb:yn(Xr(t)),centroidHz:js(t,e),zcr:Gs(t,e),onsetDensity:Hs(t,e),tempoBpm:_s(t,e)}}var Js={"":[0,4,7],maj:[0,4,7],M:[0,4,7],m:[0,3,7],min:[0,3,7],"-":[0,3,7],dim:[0,3,6],aug:[0,4,8],"+":[0,4,8],6:[0,4,7,9],m6:[0,3,7,9],"-6":[0,3,7,9],69:[0,4,7,9,14],"6/9":[0,4,7,9,14],maj7:[0,4,7,11],M7:[0,4,7,11],maj9:[0,4,7,11,14],"maj7#11":[0,4,7,11,18],maj13:[0,4,7,11,14,21],7:[0,4,7,10],9:[0,4,7,10,14],11:[0,7,10,14,17],13:[0,4,7,10,14,21],"7b9":[0,4,7,10,13],"7#9":[0,4,7,10,15],"7#11":[0,4,7,10,18],"7b13":[0,4,7,10,20],"7b5":[0,4,6,10],"7#5":[0,4,8,10],"13b9":[0,4,7,10,13,21],"13#11":[0,4,7,10,18,21],"9#11":[0,4,7,10,14,18],"7alt":[0,4,10,13,20],m7:[0,3,7,10],min7:[0,3,7,10],"-7":[0,3,7,10],m9:[0,3,7,10,14],m11:[0,3,7,10,14,17],m13:[0,3,7,10,14,21],m7b5:[0,3,6,10],\u00F8:[0,3,6,10],\u00F87:[0,3,6,10],dim7:[0,3,6,9],mMaj7:[0,3,7,11],"m(maj7)":[0,3,7,11],mMaj9:[0,3,7,11,14],sus4:[0,5,7],sus2:[0,2,7],"7sus4":[0,5,7,10],"9sus4":[0,5,7,10,14],add9:[0,4,7,14],madd9:[0,3,7,14]};function Ce(t,e=4){let r=t.trim().split("/"),o=r[0],i=/^([A-Ga-g][#b]?)(.*)$/.exec(o);if(!i)throw new Error(`bad chord symbol: ${JSON.stringify(t)}`);let s=i[1][0].toUpperCase()+(i[1][1]??""),a=i[2],l=Js[a];if(!l)throw new Error(`unknown chord quality ${JSON.stringify(a)} in ${JSON.stringify(t)}`);let u=me(s+e),c=l.map(m=>u+m);if(r.length===2){let m=/^([A-Ga-g][#b]?)$/.exec(r[1].trim());if(m){let d=m[1][0].toUpperCase()+(m[1][1]??""),p=me(d+(e-1));for(;p>=c[0];)p-=12;c.unshift(p)}}return c}function qt(t,e){let n=t.slice(1);if(e===void 0||n.length===0)return n;let r=n.reduce((i,s)=>i+s,0)/n.length,o=Math.round((e-r)/12)*12;return n.map(i=>i+o).sort((i,s)=>i-s)}function ad(t,e=4){return t.map(n=>Ce(n,e))}function to(t){try{return typeof t=="number"?t:me(t)}catch{return null}}function Us(t){return t.pitch===null||t.pitch===void 0?[]:Array.isArray(t.pitch)?t.pitch:[t.pitch]}function cd(t,e={}){let n=[],r=[];(!(t.bpm>0)||t.bpm<20||t.bpm>400)&&n.push(`bpm ${t.bpm} out of sane range [20,400]`),(!t.tracks||t.tracks.length===0)&&n.push("song has no tracks");let o=e.key?_r(to(e.key.tonic)??0,e.key.mode):null,i=0,s=0,a=new Map;if(t.tracks.forEach((u,c)=>{let m=u.name??`track ${c}`;(!u.patterns||u.patterns.length===0)&&n.push(`${m}: no patterns`),(!u.sequence||u.sequence.length===0)&&n.push(`${m}: empty sequence`),u.pan!==void 0&&(u.pan<-1||u.pan>1)&&n.push(`${m}: pan ${u.pan} out of [-1,1]`);for(let d of u.sequence??[]){if(d<0||d>=(u.patterns?.length??0)){n.push(`${m}: sequence references missing pattern ${d}`);continue}let p=`${c}:${d}`;a.set(p,(a.get(p)??0)+1);for(let h of u.patterns[d]){h.beats>0||n.push(`${m}: note with non-positive beats ${h.beats}`),h.vel!==void 0&&(h.vel<0||h.vel>1)&&n.push(`${m}: velocity ${h.vel} out of [0,1]`);for(let g of Us(h)){let x=to(g);if(x===null){n.push(`${m}: unparseable pitch ${JSON.stringify(g)}`);continue}(x<0||x>127)&&n.push(`${m}: pitch ${g} outside MIDI 0..127`),i++,o&&!o.has((x%12+12)%12)&&s++}}}}),o&&i>0){let u=s/i,c=e.maxOutOfKey??1,m=`${s}/${i} notes (${Math.round(u*100)}%) out of key`;u>c?n.push(m):s>0&&r.push(m)}return![...a.values()].some(u=>u>1)&&t.tracks.length>0&&r.push("no pattern is reused \u2014 piece may lack structure/repetition"),{ok:n.length===0,errors:n,warnings:r}}function md(t){return t.length===0?!1:(r=>r.trim().toLowerCase().replace(/7$/,""))(t[t.length-1])==="i"}var Ks={tempoBpm:20,centroidHz:1200,rms:.1,zcr:1500,onsetDensity:4,peakDb:6},Ys={tempoBpm:["too slow","too fast"],centroidHz:["too dark / muffled","too bright / harsh"],rms:["too quiet","too loud"],zcr:["too smooth / tonal","too noisy / gritty"],onsetDensity:["too sparse","too busy"],peakDb:["more headroom than reference","hotter / less headroom than reference"]};function Xs(t,e,n={}){let r={...Ks,...n},o=Object.keys(r),i=[],s=0;for(let c of o){let m=t[c],d=e[c],p=Number.isFinite(m)?m:0,h=Number.isFinite(d)?d:0,g=(h-p)/r[c];s+=g*g;let[x,k]=Ys[c],w=Math.abs(g)<.25?"ok":g<0?x:k;i.push({feature:c,reference:p,candidate:h,normalized:g,note:w})}i.sort((c,m)=>Math.abs(m.normalized)-Math.abs(c.normalized));let a=Math.sqrt(s/o.length),l=i[0],u=Math.abs(l.normalized)<.25?"close match":`${l.feature}: ${l.note}`;return{distance:a,deltas:i,headline:u}}function pd(t,e){let n=Xs(t,e),r=n.deltas.filter(o=>o.note!=="ok").map(o=>` ${o.feature.padEnd(13)} ${o.candidate.toFixed(1)} vs ${o.reference.toFixed(1)} \u2192 ${o.note}`);return`match distance ${n.distance.toFixed(3)} \u2014 ${n.headline}
4
+ `+(r.length?r.join(`
5
+ `):" (all features within tolerance)")}function gd(t,e){if(t.length===0)return 0;let n=t.length>1?[...t].sort((r,o)=>r.x-o.x):t;if(e<=n[0].x)return n[0].y;if(e>=n[n.length-1].x)return n[n.length-1].y;for(let r=1;r<n.length;r++)if(e<=n[r].x){let o=n[r-1],i=n[r],s=i.x===o.x?0:(e-o.x)/(i.x-o.x);return o.y+(i.y-o.y)*s}return n[n.length-1].y}function Qs(t,e,n=1,r=1e4,o=1){let i=Math.max(1e-6,n);switch(t){case"linear":{let s=K(e,i,r);return 1-o*(s-i)/Math.max(1e-6,r-i)}case"inverse":{let s=Math.max(e,i);return i/(i+o*(Math.max(s,i)-i))}case"exponential":{let s=Math.max(e,i);return he(-o*rn(s/i))}}}function Zs(t,e=400){return K(t/e,-1,1)}function yd(t,e,n=600,r=1){let o=Math.sqrt(t*t+e*e);return o>n?{gain:0,pan:0,audible:!1}:{gain:Qs("inverse",o,n*.15,n,r),pan:Zs(t,n*.7),audible:!0}}function xd(t,e){let n={};for(let r of t){let o=Math.max(1e-6,r.full-r.fadeIn),i=K((e-r.fadeIn)/o,0,1)*(r.maxGain??1);n[r.name]=i}return n}function vd(t,e=-12){return t?he(e/6.0206):1}function ea(t){let e=t.left.length,n=new Float32Array(e),r=new Float32Array(e);for(let i=0;i<e;i++)n[i]=(t.left[i]+t.right[i])*.5,r[i]=(t.left[i]-t.right[i])*.5;let o=ct(n);return o<1e-9?0:ct(r)/o}var Sd={electronic:{tempo:[118,132],centroid:[3e3,7200],onsets:[7,15],rms:[.16,.27],crestDb:[6,15],width:[.03,.6],maxMud:.34},lofi:{tempo:[70,88],centroid:[1600,4300],onsets:[5,13],rms:[.12,.24],crestDb:[7,17],width:[.04,.6],maxMud:.5},piano:{tempo:[58,100],centroid:[700,2100],onsets:[3,11],rms:[.1,.22],crestDb:[9,22],width:[.04,.7],maxMud:.42},orchestral:{tempo:[80,96],centroid:[1100,3e3],onsets:[4,12],rms:[.11,.22],crestDb:[8,21],width:[.05,.7],maxMud:.4},jazzfunk:{tempo:[106,126],centroid:[2200,5600],onsets:[6,16],rms:[.13,.25],crestDb:[7,18],width:[.04,.6],maxMud:.4}};function Te(t,[e,n]){if(t>=e&&t<=n)return 1;let r=Math.max(1e-6,n-e),o=t<e?e-t:t-n;return Math.max(0,1-o/(r*.6))}function Md(t,e){let n=new Float32Array(t.left.length);for(let k=0;k<n.length;k++)n[k]=(t.left[k]+t.right[k])*.5;let r=dt(n),o=Zr(n),i=eo(n),s=ea(t),a=i.lowMid,l=i.high+i.air,u=i.sub+i.bass,c={loudness:Te(r.rms,e.rms),headroom:r.peakDb<=-.5?r.peakDb>=-3?1:Te(r.peakDb,[-3,-.5]):0,dynamics:Te(o,e.crestDb),width:Te(s,e.width),brightness:Te(r.centroidHz,e.centroid),density:Te(r.onsetDensity,e.onsets),tempo:Te(r.tempoBpm,e.tempo),lowEnd:Te(u,[.12,.7]),clarity:Te(a,[0,e.maxMud??.34]),smoothness:Te(l,[0,.4])},m={loudness:1.2,headroom:1.4,dynamics:1,width:.7,brightness:1.1,density:.9,tempo:.7,lowEnd:1,clarity:1.2,smoothness:1.1},d=0,p=0;for(let k of Object.keys(c))d+=c[k]*m[k],p+=m[k];let h=Math.round(d/p*100),g=[],x=(k,w)=>{c[k]<.75&&g.push(`${k}: ${w}`)};return x("loudness",`rms ${r.rms.toFixed(3)} (target ${e.rms.join("\u2013")})`),x("headroom",`peak ${r.peakDb.toFixed(1)}dB (want \u2264 \u22120.5, \u2265 \u22123)`),x("dynamics",`crest ${o.toFixed(1)}dB (target ${e.crestDb.join("\u2013")})`),x("width",`width ${s.toFixed(2)} (target ${e.width.join("\u2013")})`),x("brightness",`centroid ${Math.round(r.centroidHz)}Hz (target ${e.centroid.join("\u2013")})`),x("density",`onsets ${r.onsetDensity.toFixed(1)}/s (target ${e.onsets.join("\u2013")})`),x("tempo",`tempo ${Math.round(r.tempoBpm)} (target ${e.tempo.join("\u2013")})`),x("lowEnd",`low-end fraction ${u.toFixed(2)} (want 0.12\u20130.62)`),x("clarity",`low-mid mud ${a.toFixed(2)} (want \u2264 ${(e.maxMud??.34).toFixed(2)})`),x("smoothness",`high/air ${l.toFixed(2)} (want \u2264 0.40)`),{score:h,dims:c,notes:g}}var R=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),G=t=>({pitch:null,beats:t});function no(t,e,n,r=.9){let o=[];for(let i=0;i<e;i++)o.push(R(t[i%t.length]+Math.floor(i/t.length)*12,n,r));return o}function ta(t,e,n=1){return Array.from({length:e},()=>R(t,1,n))}function na(){let t=Ke(me("A3"),"minor",["i","VI","III","VII"]),e=t.map(a=>a[0]-12),n={name:"sub",instrument:A.subBass,gain:.6,patterns:e.map(a=>[R(a,.5,1),R(a,.5,.6),R(a,.5,.85),R(a,.5,.6),R(a,.5,1),R(a,.5,.6),R(a,.5,.85),R(a,.5,.7)]),sequence:[0,1,2,3,0,1,2,3]},r={name:"kick",instrument:A.kick,gain:.82,patterns:[ta("A1",4)],sequence:Array(8).fill(0)},o={name:"hat",instrument:A.hat,gain:.42,pan:.15,patterns:[[G(.5),R("A6",.5,.7),G(.5),R("A6",.5,.5)]],sequence:Array(16).fill(0)},i={name:"pluck",instrument:{...A.pluck,release:.16,lowpass:2400},gain:.62,pan:-.2,patterns:t.map(a=>no([a[0],a[1],a[2]],4,1,.7)),sequence:[0,1,2,3,0,1,2,3]},s={name:"lead",instrument:{...A.lead,detune:8,lowpass:2800},gain:.52,pan:.1,patterns:[[R(t[0][2]+12,.75),R(t[0][2]+14,.25),R(t[0][0]+12,1),R(t[0][1]+12,2)],[R(t[1][2]+12,1),R(t[1][1]+12,.5),R(t[1][2]+12,.5),R(t[1][0]+24,2)],[R(t[2][2]+12,.75),R(t[2][1]+12,.25),R(t[2][0]+12,1),R(t[2][2]+12,2)],[R(t[3][0]+24,1),R(t[3][2]+12,.5),R(t[3][1]+12,.5),R(t[3][0]+12,2)]],sequence:[0,1,2,3]};return{bpm:126,tracks:[r,n,o,i,s],reverb:{wet:.15,roomSize:.6,damp:.5},humanize:.05,sidechain:{depth:.55,beatsPerCycle:1},master:{lowCut:.35,presence:.2,air:.08}}}function ra(){let t=me("C4"),e=ut(Ke(t,"major",["IV7","iii7","ii7","I7"]).map(pn)),n=e.map(c=>c[0]-12),r={name:"rhodes",instrument:{...A.rhodes,volume:.42,lowpass:2600,fm:1.6},gain:.66,pan:-.1,patterns:e.map(c=>[R(c.map(m=>m),3.5,.75),G(.5)]),sequence:[0,1,2,3,0,1,2,3]},o={name:"bass",instrument:{...A.bass,lowpass:650,sub:.28},gain:.72,pan:.05,patterns:n.map(c=>[R(c,1.5,.9),G(.5),R(c+7,1,.7),R(c+5,1,.6)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"kick",instrument:{...A.kick,volume:.75},gain:.82,patterns:[[R("C2",1,.9),G(1),R("C2",.5,.6),G(.5),R("C2",.5,.4),G(.5)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...A.rimshot,volume:.24,lowpass:4e3},gain:.6,patterns:[[G(1),R("C4",1,.7),G(1),R("C4",1,.7)]],sequence:Array(8).fill(0)},a={name:"hat",instrument:{...A.hat,volume:.14,highpass:2500,lowpass:6e3},gain:.45,pan:.2,patterns:[[R("C6",.5,.5),R("C6",.5,.3)]],sequence:Array(16).fill(0)},l={name:"vinyl",instrument:{wave:"noise",attack:.5,release:.5,sustainLevel:1,volume:.022,lowpass:2800,highpass:400},gain:.3,patterns:[[R("C4",16,1)]],sequence:[0]},u={name:"keys",instrument:{...A.piano,volume:.3,lowpass:2800},gain:.48,pan:.15,patterns:[[R(e[0][2]+12,1,.7),G(1),R(e[0][1]+12,.5,.55),R(e[0][2]+12,.5,.5),G(1)],[G(.5),R(e[1][2]+12,1,.7),G(.5),R(e[1][1]+12,2,.55)],[R(e[2][2]+12,1.5,.7),R(e[2][1]+12,.5,.5),G(2)],[G(1),R(e[3][2]+12,1,.7),R(e[3][1]+12,1,.55),G(1)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:78,tracks:[l,r,o,i,s,a,u],swing:.75,humanize:.4,velBrightness:.7,reverb:{wet:.24,roomSize:.7,damp:.65},master:{lowCut:.26,presence:.22,air:.05}}}function oa(){let t=me("A3"),e=ut(Ke(t,"minor",["i","VI","III","VII"])),n=[a=>[R(a[0],1,.85),R(a[2],1,.55),G(2)],a=>[R(a[2],1.5,.8),G(.5),R(a[1],2,.5)],a=>[G(1),R(a[1]+12,1.5,.7),G(1.5)],a=>[R(a[0],2,.8),R(a[2],1,.55),G(1)]],r={name:"piano",instrument:{...A.piano,volume:.46},gain:.78,pan:-.05,patterns:e.map((a,l)=>n[l%n.length](a)),sequence:[0,1,2,3,0,1,2,3]},o={name:"strings",instrument:{...A.strings,attack:.4},gain:.5,pan:.1,patterns:e.map(a=>[R(a.map(l=>l-12),4,.65)]),sequence:[0,1,2,3,0,1,2,3]},i={name:"sub",instrument:{...A.subBass,volume:.4,attack:.03},gain:.55,patterns:e.map(a=>[R(a[0]-24,4,.6)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"melody",instrument:{...A.piano,volume:.4,lowpass:3e3},gain:.5,pan:.12,patterns:[[G(2),R(e[0][2]+12,1,.75),R(e[0][1]+12,1,.55)],[R(e[1][2]+12,2,.8),R(e[1][1]+12,1,.55),G(1)],[G(1.5),R(e[2][2]+12,1.5,.75),R(e[2][1]+12,1,.55)],[R(e[3][1]+12,1.5,.7),R(e[3][0]+12,2.5,.6)]],sequence:[0,1,2,3,0,1,2,3]};return{bpm:66,tracks:[i,o,r,s],humanize:.5,velBrightness:.75,reverb:{wet:.38,roomSize:.86,damp:.55},master:{lowCut:.4,presence:.28,air:.12}}}function ia(){let t=me("D3"),e=ut(Ke(t,"minor",["i","VI","III","VII","VI","VII","i","i"])),n=dn(me("D4"),"minor",3),r=m=>n[(m%n.length+n.length)%n.length],o={name:"strings",instrument:{...A.strings,volume:.24},gain:.7,pan:-.15,patterns:e.map(m=>no([m[0],m[1],m[2],m[0]+12],8,.5,.75)),sequence:[0,1,2,3,4,5,6,7]},i=[[R(r(0),2,.9),R(r(1),1,.8),R(r(2),1,.85)],[R(r(4),3,.95),R(r(2),1,.8)],[R(r(1),2,.85),R(r(0),1,.8),R(r(1),1,.8)],[R(r(4),2,.9),R(r(5),2,.95)],[R(r(5),2,.95),R(r(4),1,.85),R(r(2),1,.8)],[R(r(4),2,.9),R(r(6),2,.95)],[R(r(7),3,1),R(r(6),1,.85)],[R(r(7),4,1)]],s=[G(4)],a={name:"brass",instrument:{...A.brass,volume:.32},gain:.62,pan:.15,patterns:[s,...i],sequence:[0,0,1,2,3,4,5,6]},l={name:"choir",instrument:{...A.choir,volume:.18},gain:.5,pan:.05,patterns:e.map(m=>[R([m[2]+12,m[0]+24],4,.6)]),sequence:[0,1,2,3,4,5,6,7]},u={name:"timpani",instrument:{...A.kick,decay:.14,release:.25,slide:-12,volume:.85,sub:.5},gain:.82,patterns:[[R("D2",1,1),R("D2",1,.6),R("D2",.5,.85),R("D2",.5,.6),R("D2",1,.9)]],sequence:Array(8).fill(0)},c={name:"glocken",instrument:A.glocken,gain:.32,pan:.25,patterns:[s,...e.map(m=>[G(1),R(m[2]+24,1,.55),G(1),R(m[1]+24,1,.5)])],sequence:[0,0,3,4,5,6,7,8]};return{bpm:88,tracks:[u,o,a,l,c],humanize:.14,velBrightness:.5,reverb:{wet:.32,roomSize:.9,damp:.4},master:{lowCut:.4,presence:.32,air:.14}}}function sa(){let t=me("C4"),e=Ke(t,"major",["ii7","V7","I7","vi7"]),n=ut(e.map(pn)),r=e.map((c,m)=>{let d=e[(m+1)%e.length][0]-24,p=c[0]-24,h=c[1]-24,g=c[2]-24,x=d+(p<d?-1:1);return[R(p,1,.95),R(h,1,.75),R(g,1,.8),R(x,1,.7)]}),o={name:"bass",instrument:{...A.bass,lowpass:1e3,sub:.35,release:.12},gain:.74,patterns:r,sequence:[0,1,2,3,0,1,2,3]},i={name:"rhodes",instrument:{...A.rhodes,volume:.3},gain:.62,pan:-.15,patterns:n.map(c=>[G(.5),R(c.map(m=>m),.75,.7),G(.75),R(c.map(m=>m),.5,.55),G(1.5)]),sequence:[0,1,2,3,0,1,2,3]},s={name:"brass",instrument:{...A.brass,release:.1,volume:.24},gain:.55,pan:.2,patterns:[[G(2),R(n[0].map(c=>c+12),.5,.85),G(1.5)],[G(3),R(n[1].map(c=>c+12),.5,.85),G(.5)],[R(n[2].map(c=>c+12),.5,.8),G(3.5)],[G(2.5),R(n[3].map(c=>c+12),.5,.8),G(1)]],sequence:[0,1,2,3,0,1,2,3]},a={name:"ride",instrument:{...A.hat,volume:.13,highpass:3e3,lowpass:9e3,release:.08},gain:.5,pan:.1,patterns:[[R("C6",.5,.6),R("C6",.5,.35),R("C6",.5,.5),R("C6",.5,.35)]],sequence:Array(16).fill(0)},l={name:"snare",instrument:{...A.snare,volume:.28,highpass:900},gain:.5,patterns:[[G(1),R("D4",1,.6),G(1),R("D4",1,.7)]],sequence:Array(8).fill(0)},u={name:"kick",instrument:{...A.kick,volume:.55},gain:.62,patterns:[[R("C2",1,.85),G(1.5),R("C2",.5,.6),G(1)]],sequence:Array(8).fill(0)};return{bpm:116,tracks:[o,i,s,u,l,a],swing:.66,humanize:.35,velBrightness:.6,reverb:{wet:.16,roomSize:.55,damp:.5},master:{lowCut:.5,presence:.18,air:.07}}}var aa=[{id:"electronic",name:"Minimal Electronic",description:"Bass-driven four-on-the-floor in A minor \u2014 pulsing sidechained sub, offbeat hats, a synth hook.",make:na},{id:"lofi",name:"Lo-fi Beats",description:"Swung, dusty jazz sevenths on a Rhodes with warm bass, brushed drums and vinyl crackle.",make:ra},{id:"piano",name:"Melancholic Piano",description:"Slow, sad A-minor piano with space and rubato over a string bed in a big room.",make:oa},{id:"orchestral",name:"Epic Orchestral",description:"Uplifting D-minor with a soaring brass theme, arpeggiated strings, choir, timpani and glockenspiel.",make:ia},{id:"jazzfunk",name:"Jazz Funk",description:"Swung ii\u2013V\u2013I with a walking bass that chromatically approaches each chord, Rhodes comping and brass stabs.",make:sa}];function Pd(t){return aa.find(e=>e.id===t)}var b=(t,e,n=1)=>({pitch:t,beats:e,vel:n}),N=t=>({pitch:null,beats:t});function xn(t,e=2){return t.map((n,r)=>{let o=Ce(n,e),i=o[0],s=o[1]??i+3,a=o[2]??i+7,l=Ce(t[(r+1)%t.length],e)[0],u=l+(i<=l?-1:1);return[b(i,1,.92),b(s,1,.72),b(a,1,.78),b(u,1,.7)]})}function Ht(t,e=4,n="F4",r=.66){let o=me(n);return t.map((i,s)=>{let a=qt(Ce(i,e),o);return s%2===0?[b(a,1,r),N(.5),b(a,.5,r*.8),N(2)]:[N(1.5),b(a,.5,r*.85),N(1),b(a,.5,r*.7),N(.5)]})}function la(t,e=4,n="F4",r=.6){let o=me(n);return t.map(i=>[b(qt(Ce(i,e),o),4,r)])}var ua=()=>[b("C6",1,.55),b("C6",.5,.35),b("C6",.5,.5),b("C6",1,.55),b("C6",.5,.35),b("C6",.5,.5)],ca=()=>[N(1),b("C6",1,.5),N(1),b("C6",1,.5)];function pt(t=.42,e=8){return{name:"ride",instrument:A.ride,gain:t,pan:.12,patterns:[ua()],sequence:Array(e).fill(0)}}function vn(t=.4,e=8){return{name:"hat",instrument:{...A.hat,highpass:5e3,volume:.2},gain:t,pan:-.1,patterns:[ca()],sequence:Array(e).fill(0)}}function _t(t=.32,e=8){return{name:"vinyl",instrument:{wave:"noise",attack:.6,release:.6,sustainLevel:1,volume:.03,lowpass:3e3,highpass:380},gain:t,patterns:[[b("C4",e*4,1)]],sequence:[0]}}var jt=["F5","Gb5","Bb5","Ab5"];function ma(){let t=["Bbm9","Bbm9","Ebm9","Ab13","Dbmaj7","Gm7b5","C7alt","Fm7"],n={name:"bass",instrument:{...A.uprightBass,volume:.5},gain:.7,patterns:[[b("Bb1",.75,.95),b("Bb1",.25,.5),N(.5),b("Db2",.5,.7),b("F2",.5,.75),b("Ab1",.5,.6),b("Bb1",1,.7)],...xn(t.slice(2),2)],sequence:[0,0,1,2,3,4,5,6]},r={name:"rhodes",instrument:{...A.rhodes,volume:.32},gain:.6,pan:-.18,patterns:Ht(t,4,"Ab4",.62),sequence:[0,1,2,3,4,5,6,7]},o={name:"trumpet",instrument:{...A.mutedTrumpet,volume:.34},gain:.62,pan:.14,patterns:[[b(jt[0],.5,.85),b(jt[1],.5,.7),b(jt[2],1,.9),b(jt[3],.5,.75),N(1.5)],[b("F5",.5,.8),b("Db5",.5,.7),b("Bb4",1.5,.85),N(1.5)],[b("C5",.5,.85),b("Db5",.5,.72),b("F5",1,.9),b("Eb5",.5,.75),N(1.5)],[b("Db5",1,.8),b("C5",.5,.7),b("Bb4",.5,.7),b("Ab4",2,.72)],[b("Db5",.5,.8),b("F5",.5,.8),b("Ab5",1.5,.85),b("Gb5",1.5,.75)],[b("D5",1,.8),b("F5",1,.8),b("Ab5",1,.85),N(1)],[b("E5",.5,.85),b("Eb5",.5,.8),b("Db5",1,.8),b("C5",2,.78)],[b("F5",1,.85),b("Ab5",1,.8),b("C6",2,.9)]],sequence:[0,1,2,3,4,5,6,7]},i={name:"kick",instrument:{...A.kick,volume:.5},gain:.6,patterns:[[b("Bb1",1,.8),N(1.5),b("Bb1",.5,.55),N(1)]],sequence:Array(8).fill(0)},s={name:"snare",instrument:{...A.snare,volume:.3,highpass:1e3},gain:.5,patterns:[[N(1),b("D4",1,.7),N(1),b("D4",1,.75)]],sequence:Array(8).fill(0)};return{bpm:100,tracks:[n,r,o,i,s,pt(.42),vn(.35)],swing:.6,humanize:.32,velBrightness:.6,reverb:{wet:.17,roomSize:.6,damp:.5},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function da(){let t=["Ebmaj7","Cm7","Fm7","Bb13","Gm7","C7b9","Fm7","Bb7alt"],e={name:"bass",instrument:{...A.uprightBass,volume:.54,release:.2},gain:.74,patterns:t.map(i=>{let s=Ce(i,2)[0];return[b(s,2,.85),b(s+7,1,.6),b(s+12,1,.55)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...A.rhodes,volume:.34,release:.6},gain:.62,pan:-.15,patterns:la(t,4,"G4",.62),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...A.mutedTrumpet,volume:.36,attack:.05,vibrato:.11},gain:.62,pan:.12,patterns:[[N(1),b("G4",1.5,.7),b("Bb4",1,.75),b("G4",.5,.6)],[b("Eb4",2,.7),b("G4",1,.65),N(1)],[N(.5),b("Ab4",1.5,.72),b("C5",1,.75),b("Ab4",1,.62)],[b("D5",2.5,.78),b("Bb4",1.5,.65)],[b("Bb4",1.5,.7),b("G4",1,.65),b("D5",1.5,.72)],[b("Db5",2,.75),b("C5",1,.68),b("Bb4",1,.62)],[b("Ab4",2,.72),b("F4",1,.62),N(1)],[b("Ab4",1,.72),b("Db5",1,.7),b("D5",2,.72)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...A.snare,volume:.12,highpass:1500,release:.16},gain:.4,patterns:[[N(1),b("D4",1,.4),N(1),b("D4",1,.45)]],sequence:Array(8).fill(0)};return{bpm:62,tracks:[_t(.3),e,n,r,o,pt(.24)],swing:.5,humanize:.4,velBrightness:.6,reverb:{wet:.34,roomSize:.85,damp:.55},master:{lowCut:.24,presence:.16,air:.05,compress:.65}}}function pa(){let t=["Cm9","Cm9","Fm9","Dm7b5","G7alt","Cm9","Ab13","G7alt"],e={name:"bass",instrument:{...A.uprightBass,volume:.48},gain:.68,patterns:xn(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"vibes",instrument:{...A.vibraphone,volume:.34},gain:.6,pan:.1,patterns:[[b("G4",1,.7),N(1),b("Eb5",1,.65),N(1)],[N(2),b("D5",1,.68),b("C5",1,.6)],[b("Ab4",1,.7),N(1.5),b("F5",1.5,.6)],[b("F4",1,.7),b("Ab4",1,.6),N(2)],[N(1),b("B4",1,.72),b("Ab4",1,.6),b("F4",1,.55)],[b("Eb5",2,.68),b("C5",2,.6)],[b("C5",1,.7),b("Gb5",1,.68),N(2)],[b("B4",1,.7),b("Db5",1,.62),b("Ab4",2,.58)]],sequence:[0,1,2,3,4,5,6,7]},r={name:"guitar",instrument:{...A.jazzGuitar,volume:.22},gain:.5,pan:-.2,patterns:Ht(t,4,"Eb4",.5),sequence:[0,1,2,3,4,5,6,7]};return{bpm:96,tracks:[_t(.28),e,r,n,pt(.3),vn(.28)],swing:.62,humanize:.34,velBrightness:.6,reverb:{wet:.22,roomSize:.65,damp:.5},master:{lowCut:.24,presence:.13,air:.04,compress:.45}}}function ha(){let t={name:"bass",instrument:{...A.bass,volume:.52,lowpass:1e3,sub:.35},gain:.75,patterns:[[b("F1",.5,.95),b("F1",.5,.6),N(.5),b("F1",.5,.7),b("Ab1",.5,.7),b("C2",.5,.7),b("F1",.5,.65),b("Eb2",.5,.7)],[b("Bb1",.5,.9),b("Bb1",.5,.6),N(.5),b("Bb1",.5,.7),b("Db2",.5,.7),b("F2",.5,.7),b("Bb1",1,.65)],[b("C2",.5,.9),b("C2",.5,.6),b("Eb2",.5,.7),b("D2",.5,.7),b("C2",.5,.7),b("Bb1",.5,.7),b("G1",1,.7)]],sequence:[0,0,1,2]},e={name:"clav",instrument:{...A.clav,volume:.3,lowpass:2700},gain:.55,pan:-.16,patterns:[[b("F4",.25,.8),N(.25),b("Ab4",.25,.6),N(.25),b("F4",.25,.7),b("C5",.25,.6),N(.5),b("Eb5",.5,.7),N(1)],[b("Bb3",.25,.8),N(.25),b("Db4",.25,.6),N(.25),b("F4",.5,.7),N(.5),b("Bb4",.5,.65),N(1)],[b("C4",.25,.8),b("Eb4",.25,.6),b("G4",.5,.7),N(.5),b("C5",.5,.7),b("Bb4",.5,.65),N(1)]],sequence:[0,0,1,2]},n=a=>qt(Ce(a,4),me("C5")),r={name:"horns",instrument:{...A.horns,volume:.26},gain:.55,pan:.15,patterns:[[N(1.5),b(n("Fm7"),.5,.8),N(1.5),b(n("Fm7"),.5,.9)],[N(1.5),b(n("Fm7"),.5,.8),N(1.5),b(n("Bbm7"),.5,.9)],[N(2),b(n("Bbm7"),.5,.82),N(1),b(n("Bbm7"),.5,.88)],[b(n("C7#9"),.5,.92),N(1),b(n("C7#9"),.5,.82),N(1),b(n("C7#9"),.5,.9)]],sequence:[0,1,2,3]},o={name:"kick",instrument:A.kick,gain:.85,patterns:[[b("F1",1,.95),b("F1",.5,.6),N(.5),b("F1",.5,.7),N(.5),b("F1",1,.8)]],sequence:Array(4).fill(0)},i={name:"snare",instrument:{...A.snare,volume:.42},gain:.6,patterns:[[N(1),b("D4",1,.85),N(1),b("D4",1,.9)]],sequence:Array(4).fill(0)},s={name:"hat",instrument:{...A.hat,volume:.18,highpass:5e3,lowpass:9e3},gain:.38,pan:.1,patterns:[[b("C6",.5,.6),b("C6",.5,.35)]],sequence:Array(8).fill(0)};return{bpm:128,tracks:[o,t,e,r,i,s],humanize:.14,velBrightness:.55,sidechain:{depth:.5,beatsPerCycle:1},reverb:{wet:.12,roomSize:.5,damp:.5},master:{lowCut:.3,presence:.16,air:.05,compress:.4}}}function fa(){let t=["Abmaj7#11","Db9","Bbm7","Eb7alt","Cm7","F7b9","Bbm7","Eb13"],e={name:"bass",instrument:{...A.uprightBass,volume:.5,sub:.4},gain:.72,patterns:t.map((s,a)=>{let l=Ce(s,2)[0],u=Ce(t[(a+1)%t.length],2)[0],c=u+(l<=u?-1:1);return[b(l,1.5,.9),N(.5),b(l+7,1,.62),b(c,1,.62)]}),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...A.rhodes,volume:.28},gain:.55,pan:-.18,patterns:Ht(t,4,"Ab4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"vibes",instrument:{...A.vibraphone,volume:.3},gain:.55,pan:.18,patterns:[[N(1),b("C5",1,.7),b("D5",1,.65),b("Eb5",1,.62)],[b("F5",2,.7),b("Eb5",1,.62),b("C5",1,.58)],[b("Db5",1.5,.7),b("F5",1.5,.65),b("Ab5",1,.62)],[b("G5",1,.72),b("Gb5",1,.66),b("Db5",2,.6)],[N(1),b("Eb5",1.5,.68),b("G5",1.5,.62)],[b("Ab5",1,.72),b("Gb5",1,.66),b("F5",2,.6)],[b("Db5",2,.68),b("Bb4",2,.6)],[b("C5",1,.7),b("G5",1,.66),b("Eb5",2,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"kick",instrument:{...A.kick,volume:.55},gain:.62,patterns:[[b("Ab1",1,.85),N(2),b("Ab1",.5,.55),N(.5)]],sequence:Array(8).fill(0)},i={name:"snare",instrument:{...A.rimshot,volume:.22},gain:.5,patterns:[[N(2),b("D4",1,.7),N(1)]],sequence:Array(8).fill(0)};return{bpm:84,tracks:[_t(.32),e,n,r,o,i,pt(.28),vn(.24)],swing:.56,humanize:.3,velBrightness:.62,reverb:{wet:.26,roomSize:.72,damp:.55},master:{lowCut:.24,presence:.14,air:.04,compress:.45}}}function ba(){let t=["Dm7","G13","Cmaj9","A7b9","Dm7","G7","Cmaj9","Cmaj9"],e={name:"bass",instrument:{...A.uprightBass,volume:.5},gain:.66,patterns:xn(t,2),sequence:[0,1,2,3,4,5,6,7]},n={name:"rhodes",instrument:{...A.rhodes,volume:.32,release:.5},gain:.6,pan:-.14,patterns:Ht(t,4,"E4",.6),sequence:[0,1,2,3,4,5,6,7]},r={name:"trumpet",instrument:{...A.mutedTrumpet,volume:.36,vibrato:.1},gain:.62,pan:.12,patterns:[[N(1),b("A4",1,.72),b("C5",1,.75),b("D5",1,.7)],[b("B4",2,.75),b("G4",1,.65),b("F4",1,.6)],[b("E5",2,.78),b("G4",1,.62),b("E4",1,.6)],[b("C5",1,.72),b("Bb4",1,.68),b("A4",1,.65),b("D5",1,.62)],[b("G4",.5,.78),b("A4",.5,.72),b("C5",1,.82),b("B4",.5,.7),N(1.5)],[b("D5",1,.75),b("B4",1,.68),b("G4",2,.62)],[b("E5",2,.8),b("C5",2,.72)],[b("E4",4,.6)]],sequence:[0,1,2,3,4,5,6,7]},o={name:"brush",instrument:{...A.snare,volume:.12,highpass:1500,release:.15},gain:.42,patterns:[[N(1),b("D4",1,.42),N(1),b("D4",1,.46)]],sequence:Array(8).fill(0)};return{bpm:76,tracks:[_t(.3),e,n,r,o,pt(.26)],swing:.56,humanize:.36,velBrightness:.6,reverb:{wet:.3,roomSize:.8,damp:.5},master:{lowCut:.38,presence:.28,air:.09,compress:.65}}}var ga={title:"Neon Precinct",subtitle:"Original Soundtrack",concept:"The score to an imaginary neo-noir detective game. You work the night beat in a rain-slicked retro-future city \u2014 jazz-funk with a noir heart. Six cues, one motif, a long night.",tracks:[{id:"neon-precinct",title:"Neon Precinct",intent:"Main theme \u2014 swaggering medium funk, the city announcing itself.",make:ma},{id:"rain-avenue",title:"Rain on the Avenue",intent:"A smoky, slow torch ballad. Muted trumpet in the rain.",make:da},{id:"stakeout",title:"Stakeout",intent:"Minimal, nervous cool-jazz. Watching, waiting, unresolved.",make:pa},{id:"the-chase",title:"The Chase",intent:"Driving F-minor funk \u2014 clav, horn stabs, a hard pulse.",make:ha},{id:"smoke-mirrors",title:"Smoke & Mirrors",intent:"Slinky half-time noir; altered colours, nothing as it seems.",make:fa},{id:"last-call",title:"Last Call",intent:"The warm closer \u2014 a ii\u2013V\u2013I that finally lands, the motif resolved.",make:ba}]};function Nd(t){return ga.tracks.find(e=>e.id===t)}var Jt=null,ro="hayao-overlay-style",ya=`
6
+ .hy-scrim{position:absolute;inset:0;display:grid;place-items:center;z-index:50;font-family:var(--hy-serif,Georgia,serif)}
7
+ .hy-scrim.dim{background:rgba(30,24,14,.5);backdrop-filter:blur(2px)}
8
+ .hy-card{background:var(--hy-paper,#fbf6ea);color:var(--hy-ink,#3d3323);border:1px solid var(--hy-line,#d9ccae);border-radius:14px;box-shadow:0 14px 44px rgba(40,30,15,.3);padding:26px 30px;max-width:440px;text-align:center}
9
+ .hy-card h1{margin:0 0 6px;font-size:30px}
10
+ .hy-card .hy-body{color:var(--hy-ink-soft,#6f6047);font-size:15px;line-height:1.5;margin-bottom:18px}
11
+ .hy-menu{display:flex;flex-direction:column;gap:8px;align-items:stretch}
12
+ .hy-item{font:inherit;font-size:16px;padding:9px 16px;border-radius:9px;border:1px solid var(--hy-line,#d9ccae);background:transparent;color:inherit;cursor:pointer;transition:transform .1s,background .1s}
13
+ .hy-item:hover,.hy-item.sel{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent;transform:translateY(-1px)}
14
+ .hy-item.primary{background:var(--hy-accent,#a11d3a);color:#fdf3ee;border-color:transparent}
15
+ `;function xa(){if(typeof document>"u"||document.getElementById(ro))return;let t=document.createElement("style");t.id=ro,t.textContent=ya,document.head.appendChild(t)}var oo=null;function Ut(t){oo=t}var wn=null;function kn(t){wn=t}function io(t){if(typeof document>"u")return{close(){},element:null};xa(),Kt(),wn?.("show",t.title);let e=document.createElement("div");e.className=`hy-scrim${t.dim===!1?"":" dim"}${t.className?" "+t.className:""}`;let n=document.createElement("div");if(n.className="hy-card",t.title){let u=document.createElement("h1");u.textContent=t.title,n.appendChild(u)}if(t.body){let u=document.createElement("div");u.className="hy-body",u.innerHTML=t.body,n.appendChild(u)}let r=t.actions??[],o=Math.max(0,r.findIndex(u=>u.primary));o<0&&(o=0);let i=[];if(r.length){let u=document.createElement("div");u.className="hy-menu",r.forEach((c,m)=>{let d=document.createElement("button");d.className=`hy-item${c.primary?" primary":""}`,d.textContent=c.label,d.addEventListener("click",()=>c.onSelect()),d.addEventListener("mouseenter",()=>s(m)),u.appendChild(d),i.push(d)}),n.appendChild(u)}function s(u){o=(u+i.length)%i.length,i.forEach((c,m)=>c.classList.toggle("sel",m===o))}i.length&&s(o);let a=u=>{i.length&&(u.code==="ArrowDown"?(s(o+1),u.preventDefault()):u.code==="ArrowUp"?(s(o-1),u.preventDefault()):(u.code==="Enter"||u.code==="Space")&&(r[o]?.onSelect(),u.preventDefault()))};document.addEventListener("keydown",a),e.appendChild(n),(oo??document.body).appendChild(e);let l={element:e,close(){document.removeEventListener("keydown",a),e.remove(),Jt===l&&(Jt=null,wn?.("hide",t.title))}};return Jt=l,l}function Kt(){Jt?.close()}var so="hayao.settings.v1",ao={master:.7,music:.6,sfx:.8,muted:!1,colorblind:!1,reducedMotion:!1},Sn=class{state;subs=new Set;constructor(){this.state=this.load(),this.pushToAudio()}get(){return{...this.state}}set(e){this.state={...this.state,...e},this.save(),this.pushToAudio();for(let n of this.subs)n(this.get())}subscribe(e){return this.subs.add(e),()=>this.subs.delete(e)}pushToAudio(){Be.setVolumes({master:this.state.master,music:this.state.music,sfx:this.state.sfx,muted:this.state.muted})}load(){try{let e=typeof localStorage<"u"&&localStorage.getItem(so);if(e)return{...ao,...JSON.parse(e)}}catch{}return{...ao}}save(){try{localStorage.setItem(so,JSON.stringify(this.state))}catch{}}},Ne=new Sn;function lo(){if(typeof document>"u")return;let t=document,e=document.documentElement;document.fullscreenElement||t.webkitFullscreenElement?(document.exitFullscreen??t.webkitExitFullscreen)?.call(document):(e.requestFullscreen??e.webkitRequestFullscreen)?.call(e)}var Yt=class{paused=!1;opts;keyHandler;constructor(e={}){this.opts=e,this.keyHandler=n=>{n.code==="Escape"&&(n.preventDefault(),this.toggle())},typeof document<"u"&&document.addEventListener("keydown",this.keyHandler)}get isPaused(){return this.paused}toggle(){this.paused?this.resume():this.pause()}pause(){this.paused||(this.paused=!0,Be.blip(440),this.opts.onPause?.(!0),this.render())}resume(){this.paused&&(this.paused=!1,Kt(),this.opts.onPause?.(!1))}render(){let e=Ne.get(),n=(r,o)=>`${r}: ${Math.round(o*100)}`;io({title:this.opts.title??"Paused",body:`<div style="font-size:13px;text-align:left;line-height:1.9">${n("Master",e.master)} \xB7 ${n("Music",e.music)} \xB7 ${n("Sfx",e.sfx)}<br/><span style="opacity:.7">Use the menu, or keys: M mute \xB7 F fullscreen</span></div>`,actions:[{label:"Resume",primary:!0,onSelect:()=>this.resume()},{label:e.muted?"Unmute (M)":"Mute (M)",onSelect:()=>{Ne.set({muted:!Ne.get().muted}),this.render()}},{label:"Music \u2212/+",onSelect:()=>{let r=Math.min(1,Ne.get().music+.1)%1.05;Ne.set({music:r>1?0:r}),this.render()}},{label:"Fullscreen (F)",onSelect:()=>lo()},...this.opts.onRestart?[{label:"Restart",onSelect:()=>{this.resume(),this.opts.onRestart()}}]:[],...this.opts.onQuit?[{label:"Quit",onSelect:()=>{this.resume(),this.opts.onQuit()}}]:[]]})}dispose(){typeof document<"u"&&document.removeEventListener("keydown",this.keyHandler),Kt()}};var va=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5],wa=t=>t*t*(3-2*t),Mn=class extends j{type="ScreenTransition";kind;color;screenW;screenH;cell;coverage=0;queue=[];constructor(e={}){super(e),this.cosmetic=!0,this.kind=e.kind??"fade",this.color=e.color??"#1a1410",this.screenW=e.width??1280,this.screenH=e.height??720,this.cell=e.cell??28}get busy(){return this.queue.length>0}enqueue(e,n,r){this.queue.push({from:void 0,to:e,dur:Math.max(1e-4,n),elapsed:0,onEnd:r})}cover(e=.4,n){return this.enqueue(1,e,n),this}reveal(e=.4,n){return this.enqueue(0,e,n),this}hold(e,n){let r=this.queue.length?this.queue[this.queue.length-1].to:this.coverage;return this.enqueue(r,e,n),this}wipe(e={}){let n=e.cover??.4;return this.cover(n,()=>{this.emit("covered",void 0),e.onMidpoint?.()}),e.hold&&this.hold(e.hold),this.reveal(e.reveal??n,()=>{this.emit("done",void 0),e.onDone?.()}),this}get covered(){return this.signal("covered")}get done(){return this.signal("done")}onProcess(e){let n=this.queue[0];if(!n)return;n.from===void 0&&(n.from=this.coverage),n.elapsed+=e;let r=K(n.elapsed/n.dur,0,1);if(this.coverage=Ee(n.from,n.to,wa(r)),r>=1){this.coverage=n.to;let o=n.onEnd;this.queue.shift(),o?.()}}draw(e,n){let r=this.coverage;if(r<=0)return;let o=this.z;if(this.kind==="fade"){e.push({kind:"rect",x:0,y:0,w:this.screenW,h:this.screenH,fill:this.color,opacity:r,transform:le,z:o});return}if(this.kind==="circle"){let a=this.screenW/2,l=this.screenH/2,u=Math.sqrt(a*a+l*l);e.push({kind:"circle",cx:a,cy:l,radius:r*u,fill:this.color,transform:le,z:o});return}let i=Math.ceil(this.screenW/this.cell),s=Math.ceil(this.screenH/this.cell);for(let a=0;a<s;a++)for(let l=0;l<i;l++)(va[(l&3)+((a&3)<<2)]+.5)/16<r&&e.push({kind:"rect",x:l*this.cell,y:a*this.cell,w:this.cell,h:this.cell,fill:this.color,transform:le,z:o})}},uo=class extends j{type="CinematicPlayer";steps=[];index=-1;elapsed=0;running=!1;onFinish;constructor(e={}){super(e),this.cosmetic=!0}play(e,n){return this.steps=e,this.onFinish=n,this.index=-1,this.elapsed=0,this.running=e.length>0,this.advance(),this}get active(){return this.running}get step(){return this.index}get finished(){return this.signal("finished")}advance(){if(this.index++,this.elapsed=0,this.index>=this.steps.length){this.running=!1,this.index=-1,this.emit("finished",void 0),this.onFinish?.();return}this.steps[this.index].enter?.()}stop(){this.running=!1,this.index=-1,this.steps=[]}onProcess(e){if(!this.running)return;this.elapsed+=e;let n=this.steps[this.index],r=this.elapsed>=(n.duration??0),o=n.until?n.until():!0;r&&o&&this.advance()}};function jd(t,e={}){let n=new Mn({z:1e4,...e});return t.addChild(n)}function Hd(t,e={}){return{name:e.name??"wipe",enter:()=>t.wipe(e),until:()=>!t.busy}}var _d=(t,e)=>({x:0,y:0,w:t,h:e});function Ye(t,e={}){let n=e.maxDepth??60,r=e.nodeCap??1e6,o=t.initial(e.level);if(t.isWin(o))return{solvable:!0,path:[],depth:0,nodes:0,exhausted:!1};let i=[{state:o,path:[]}],s=new Set([t.key(o)]),a=0;for(let l=0;l<n&&i.length>0;l++){let u=[];for(let{state:c,path:m}of i)for(let d of t.moves(c)){if(a>=r)return{solvable:!1,nodes:a,exhausted:!0};a++;let p=t.apply(c,d);if(t.isDead?.(p))continue;if(t.isWin(p))return{solvable:!0,path:[...m,d],depth:l+1,nodes:a,exhausted:!1};let h=t.key(p);s.has(h)||(s.add(h),u.push({state:p,path:[...m,d]}))}i=u}return{solvable:!1,nodes:a,exhausted:i.length>0}}function Ud(t,e={}){let n=Ye(t,e);if(!n.solvable)throw new Error(`hayao: level ${e.level??0} is NOT winnable (expanded ${n.nodes} nodes${n.exhausted?", search capped \u2014 raise nodeCap/maxDepth":""}).`);return n}function co(t,e){let n=t(),r=[];for(let o=0;o<e.frames.length;o++)n.step(nt(e,o)),r.push(n.hash());return{finalHash:n.hash(),hashes:r}}function ka(t,e){let n=co(t,e),r=co(t,e),o=-1;for(let i=0;i<n.hashes.length;i++)if(n.hashes[i]!==r.hashes[i]){o=i;break}return{ok:o===-1&&n.finalHash===r.finalHash,frames:e.frames.length,divergedAt:o,finalHash:n.finalHash}}function Xd(t,e){let n=ka(t,e);if(!n.ok)throw new Error(`hayao: sim is NON-deterministic \u2014 runs diverged at frame ${n.divergedAt} of ${n.frames}. Check for Math.random/Date.now/Set-iteration/unordered-map in the sim.`);return n}function Qd(t,e,n){let r=t();for(let l=0;l<n;l++)r.step(nt(e,l));let o=r.snapshot(),i=t();i.restore(o);for(let l=n;l<e.frames.length;l++)r.step(nt(e,l)),i.step(nt(e,l));let s=r.hash(),a=i.hash();return{ok:s===a,hashA:s,hashB:a}}function ep(t,e){return{actions:t,frames:e}}function tp(t){return{actions:[],frames:t}}function np(t,e){let n=[],r=0;for(let o of e){for(let i=0;i<o.frames;i++)t.step(o.actions??[]);r+=o.frames,n.push(t.probe())}return{totalFrames:r,finalHash:t.hash(),probes:n}}function rp(t,e,n=[]){for(let r=0;r<e;r++)t.step(n)}function mo(){return typeof location<"u"&&new URLSearchParams(location.search).has("capture")}function po(t){let e={pump(n,r=[]){t.setPaused(!0);for(let o=0;o<n;o++)t.stepOnce(r);return t.world.probe()},probe:()=>t.world.probe(),hash:()=>t.world.hash(),shot:()=>t.renderSVG(),async save(n){let r=t.renderSVG();try{return(await fetch("/__shot",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:n,svg:r})})).ok}catch{return!1}},key(n,r){document.dispatchEvent(new KeyboardEvent(n,{code:r,bubbles:!0}))},get world(){return t.world}};return globalThis.__hayao=e,e}function Sa(t){let e=[];for(let n of t){let r=n.frames??1,o=n.hold??[];for(let i=0;i<r;i++)e.push(i===0&&n.press?[...o,...n.press]:[...o])}return e}function sp(t,e,n){let r=0;for(let o of Sa(e)){if(n&&n(t.probe()))return{frames:r,matched:!0};t.step(o),r++}return{frames:r,matched:n?n(t.probe()):!1}}function lp(t,e){let n=0,r=0,o={},s=a=>{let l=[],u=t[n];if(!u)return l;r++;let c={get frames(){return r},mem:o,next(){n++,r=0,o={}},retry(){r=0,o={}}},m=e[u.kind];if(!m)throw new Error(`plan bot: no executor for step kind "${u.kind}"`);return m(u,a,l,c),l};return s.stepIndex=()=>n,s.done=()=>n>=t.length,s}function up(t,e,n,r,o,i=8){t<n-i?o.push("right"):t>n+i&&o.push("left"),e<r-i?o.push("down"):e>r+i&&o.push("up")}var ft=t=>[...new Set(t)];function Ma(t,e={}){let n=e.minCoyote??.05,r=e.minBuffer??.05,o=e.requireCornerNudge??!0,i=[];return t.coyoteTime>=n||i.push(`coyote time ${t.coyoteTime}s is below the ${n}s floor \u2014 late jumps off a ledge will be dropped`),t.jumpBuffer>=r||i.push(`jump buffer ${t.jumpBuffer}s is below the ${r}s floor \u2014 early jumps before landing will be swallowed`),o&&!((t.jumpCornerNudge??0)>0)&&i.push("no jump corner nudge \u2014 clipping a ceiling edge kills upward momentum instead of slipping past"),i}function dp(t,e,n){let r=[];for(let o=0;o<=e;o++)n(o)||r.push(`${t}: input ${o} frame(s) into the window was refused \u2014 grace window is shorter than the specced ${e}`);return n(e+1)&&r.push(`${t}: input ${e+1} frame(s) in (past the window) was still accepted \u2014 grace window is longer than specced (unfair leniency)`),ft(r)}function Ca(t,e,n={}){let r=n.minChannels??2,[o,i]=n.shake??[0,1],[s,a]=n.hitstop??[0,12],l=[];for(let u of e){let c=t[u];if(!c){l.push(`event "${u}" has no feedback response \u2014 it happens silently`);continue}let m=new Set(c.channels).size;m<r&&l.push(`event "${u}" answers on ${m} channel(s) (${c.channels.join("+")||"none"}) \u2014 needs \u2265 ${r} (e.g. sfx + particles)`),c.shake!==void 0&&(c.shake<o||c.shake>i)&&l.push(`event "${u}" shake ${c.shake} is outside the [${o}, ${i}] envelope`),c.hitstopFrames!==void 0&&(c.hitstopFrames<s||c.hitstopFrames>a)&&l.push(`event "${u}" hit-stop ${c.hitstopFrames}f is outside the [${s}, ${a}]f envelope`)}return ft(l)}function Xt(t){let e=t.replace("#","");e.length===3&&(e=e.split("").map(o=>o+o).join(""));let n=parseInt(e,16),r=o=>{let i=o/255;return i<=.03928?i/12.92:Pe((i+.055)/1.055,2.4)};return .2126*r(n>>16&255)+.7152*r(n>>8&255)+.0722*r(n&255)}function ht(t,e){let n=Xt(t),r=Xt(e),o=Math.max(n,r),i=Math.min(n,r);return(o+.05)/(i+.05)}var Ta=t=>t.kind==="text"?void 0:t.fill;function Ra(t,e,n,r={}){let o=r.minBackgroundContrast??3,i=r.minSalienceFactor??1.15,s=[],a=ht(e,n);a<o&&s.push(`avatar (${e}) contrast vs background is ${a.toFixed(2)}:1 (needs \u2265 ${o}:1) \u2014 it sinks into the ground`);let l=[];for(let u of t){let c=Ta(u);c&&c!=="none"&&c!==e&&l.push(ht(c,n))}if(l.length){l.sort((c,m)=>c-m);let u=l[Math.floor(l.length/2)];a<u*i&&s.push(`avatar (${e}, ${a.toFixed(2)}:1) does not pop from the scenery (median ${u.toFixed(2)}:1) \u2014 it needs \u2265 ${i}\xD7 the median contrast`)}return ft(s)}function pp(t,e,n="threat"){let r=[],o=0;for(let i=0;i<t.length;i++){let s=t[i];s.active&&(i===0||!t[i-1].active)&&o<e&&r.push(`${n}: hitbox went live at frame ${i} after only ${o} telegraph frame(s) \u2014 needs \u2265 ${e} of wind-up`),o=s.active?0:s.telegraphing?o+1:0}return ft(r)}function Pa(t,e={}){let n=e.dt??.016666666666666666,r=e.maxSpeed??1800,o=e.maxAccel??9e4;if(t.length<3)return[];let i=[],s=[];for(let a=1;a<t.length;a++){let l=t[a].x-t[a-1].x,u=t[a].y-t[a-1].y,c=Z(l,u)/n;s.push(c),c>r&&i.push(`camera snapped at frame ${a}: ${Math.round(c)}px/s exceeds the ${r}px/s ceiling`)}for(let a=1;a<s.length;a++){let l=Math.abs(s[a]-s[a-1])/n;l>o&&i.push(`camera jerked at frame ${a+1}: ${Math.round(l)}px/s\xB2 exceeds the ${o}px/s\xB2 ceiling`)}return ft(i)}function Da(t,e,n=0){if(t.length<2||t.length!==e.length)return[];let r=t[t.length-1].x-t[0].x,o=e[e.length-1].x-e[0].x,i=t[t.length-1].y-t[0].y,s=e[e.length-1].y-e[0].y,a=[];return Math.abs(o)>n&&Math.sign(r)!==0&&Math.sign(r)!==Math.sign(o)&&a.push("camera drifts opposite the target on X \u2014 the view lags behind instead of leading"),Math.abs(s)>n&&Math.sign(i)!==0&&Math.sign(i)!==Math.sign(s)&&a.push("camera drifts opposite the target on Y \u2014 the view lags behind instead of leading"),a}function hp(t,e={}){let n=[],r=[],o=t.background??e.background??"#ffffff";if(t.forgiveness&&n.push({gate:"forgiveness",issues:Ma(t.forgiveness)}),t.feedback&&n.push({gate:"feedback",issues:Ca(t.feedback.contract,t.feedback.events)}),t.avatarFill&&(e.commands?n.push({gate:"salience",issues:Ra(e.commands,t.avatarFill,o)}):r.push("salience (no rendered frame)")),t.scrolls)if(e.camSamples&&e.camSamples.length>=3){let i=Pa(e.camSamples,{dt:e.dt});e.targetSamples&&i.push(...Da(e.camSamples,e.targetSamples)),n.push({gate:"camera",issues:i})}else r.push("camera (no sampled positions)");return{ok:n.every(i=>i.issues.length===0),sections:n,skipped:r}}function Ia(t){let e=t.text.length*t.size*.56,n=t.size*1.25,r=t.transform.e+t.x,o=t.transform.f+t.y,i=t.align==="center"?r-e/2:t.align==="right"?r-e:r;return{cmd:t,x:i,y:o-t.size,w:e,h:n}}function ho(t){let e=t.transform.e,n=t.transform.f;switch(t.kind){case"rect":return{x:e+t.x,y:n+t.y,w:t.w,h:t.h};case"circle":return{x:e+t.cx-t.radius,y:n+t.cy-t.radius,w:t.radius*2,h:t.radius*2};case"poly":{let r=1/0,o=1/0,i=-1/0,s=-1/0;for(let a=0;a<t.points.length;a+=2)r=Math.min(r,t.points[a]),i=Math.max(i,t.points[a]),o=Math.min(o,t.points[a+1]),s=Math.max(s,t.points[a+1]);return{x:e+r,y:n+o,w:i-r,h:s-o}}default:return null}}var fo=(t,e)=>t.x<e.x+e.w&&t.x+t.w>e.x&&t.y<e.y+e.h&&t.y+t.h>e.y,bo=(t,e,n=2)=>t.x-n<=e.x&&t.y-n<=e.y&&t.x+t.w+n>=e.x+e.w&&t.y+t.h+n>=e.y+e.h,Ea=t=>t.transient===!0,go=t=>{let e=t.fill;if(!(!e||e==="none")&&!t.gradient)return e};function gp(t,e={}){let n=e.backgroundZ??1,r=e.margin??0,o=e.background,i=e.minContrast??1.5,s=e.minTextContrast??4.5,a=[],l=e.includeTransient?t:t.filter(c=>!Ea(c)),u=[];for(let c of l)c.kind==="text"&&c.text.trim().length&&u.push(Ia(c));for(let c of u){let m=c.cmd.z??0,d={x:c.x-r,y:c.y-r,w:c.w+r*2,h:c.h+r*2},p=-1/0,h=o;for(let g of l){if(g.kind==="text")continue;let x=ho(g);if(!x||!bo(x,c))continue;let k=g.opacity===void 0||g.opacity>=.6,w=g.z??0;k&&w<=m&&w>=p&&(p=w,h=go(g)??h),w>m&&(g.opacity===void 0||g.opacity>=.9)&&a.push(`text "${bt(c.cmd.text)}" is hidden behind a ${g.kind} (z${w} > text z${m}) that fully covers it \u2014 give the text a higher z, or the shape a lower one`)}for(let g of l){if(g.kind==="text"||(g.z??0)<=n||(g.z??0)<=p||g.opacity!==void 0&&g.opacity<.25)continue;let x=ho(g);x&&fo(d,x)&&!bo(x,c)&&a.push(`text "${bt(c.cmd.text)}" collides with a ${g.kind} (z${g.z}) at ~(${Math.round(x.x)},${Math.round(x.y)}) \u2014 back it with a panel, or stay clear`)}if(o&&s>0){let g=c.cmd.fill;if(g&&g!=="none"&&(c.cmd.opacity===void 0||c.cmd.opacity>=.6)){let x=ht(g,h??o);x<s&&a.push(`text "${bt(c.cmd.text)}" (${g}) contrast is ${x.toFixed(2)}:1 on its backing (needs \u2265 ${s}:1) \u2014 barely readable`)}}}if(o)for(let c of l){if(c.kind==="text"||(c.z??0)<=n||c.opacity!==void 0&&c.opacity<.6)continue;let m=go(c);if(!m)continue;let d=ht(m,o);d<i&&a.push(`${c.kind} (${m}, z${c.z}) contrast is ${d.toFixed(2)}:1 vs background ${o} (needs \u2265 ${i}:1) \u2014 it vanishes into the ground`)}for(let c=0;c<u.length;c++)for(let m=c+1;m<u.length;m++)fo(u[c],u[m])&&a.push(`texts "${bt(u[c].cmd.text)}" and "${bt(u[m].cmd.text)}" overlap`);return yo(a)}var bt=t=>t.length>28?t.slice(0,25)+"\u2026":t,yo=t=>[...new Set(t)];function Fa(t){return t.startsWith("Digit")?[t.slice(5)]:t.startsWith("Key")?[t.slice(3).toLowerCase()]:t.startsWith("Arrow")?["arrow","\u2190","\u2192","\u2191","\u2193",t.slice(5).toLowerCase()]:t.startsWith("Shift")?["shift"]:t==="Space"?["space"]:t==="Enter"?["enter"]:t==="Period"?["."]:[t.toLowerCase()]}function yp(t,e){let n=t.render().filter(i=>i.kind==="text").map(i=>i.text.toLowerCase()).join(" \xB7 "),r=[],o=i=>i.length?i.length<=2&&/^[a-z0-9.]+$/.test(i)?new RegExp(`(^|[^a-z0-9])${i.replace(".","\\.")}($|[^a-z0-9])`).test(n):n.includes(i):!1;for(let[i,s]of Object.entries(e)){if(i==="restart")continue;[i.toLowerCase().replace(/-\d+$/,""),...s.flatMap(Fa)].some(o)||r.push(i)}return yo(r)}function vp(t,e){let n=[t.probe()];for(let r of e)t.step(r),n.push(t.probe());return n}function wp(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n;return-1}function kp(t,e){return t.map(n=>n[e])}function Sp(t,e){let n=[];for(let r=1;r<t.length;r++)t[r][e]!==t[r-1][e]&&n.push(r);return n}function Mp(t,e,n=0){for(let r=1;r<t.length;r++)if(e==="up"?t[r]<t[r-1]-n:t[r]>t[r-1]+n)return!1;return!0}function Cp(t){return t.length===0?0:t.filter(e=>e.length>0).length/t.length}function Tp(t,e){let n=[0,...t,e],r=0;for(let o=1;o<n.length;o++)r=Math.max(r,n[o]-n[o-1]);return r}var Na=t=>[...new Set(t)];function $a(t){let e=t.length;if(e===0)return{count:0,min:0,max:0,mean:0,distinct:0,maxJump:0,forwardFraction:1};let n=t[0],r=t[0],o=0,i=0,s=0;for(let a=0;a<e;a++){let l=t[a];if(l<n&&(n=l),l>r&&(r=l),o+=l,a>0){let u=l-t[a-1];u>i&&(i=u),u>=0&&s++}}return{count:e,min:n,max:r,mean:o/e,distinct:new Set(t).size,maxJump:i,forwardFraction:e>1?s/(e-1):1}}function Aa(t,e={}){let n=e.maxJumpFactor??3,r=e.minJumpAllowance??2,o=e.minForwardFraction??.6,i=e.minDistinct??3,s=e.finaleFraction??.8,a=[],l=t.length;if(l<2)return a.push(`ramp has ${l} level(s) \u2014 need at least 2 to form a curve`),a;let u=$a(t);t[l-1]<t[0]&&a.push(`curve descends overall: finale (${t[l-1]}) is easier than the opener (${t[0]}) \u2014 the game gets EASIER`),u.max>0&&t[l-1]<u.max*s&&a.push(`finale (${t[l-1]}) is well below the peak (${u.max}) \u2014 the hardest level is buried mid-campaign, so it ends on an anticlimax`);let c=0,m=0;for(let h=1;h<l;h++){let g=t[h]-t[h-1];g>0&&(c+=g,m++)}let d=m>0?c/m:0,p=Math.max(r,d*n);for(let h=1;h<l;h++){let g=t[h]-t[h-1];g>p&&a.push(`difficulty cliff at level ${h+1}: jumps ${t[h-1]}\u2192${t[h]} (+${g}), past the +${p.toFixed(1)} envelope \u2014 smooth it with an intermediate level`)}return u.forwardFraction<o&&a.push(`only ${(u.forwardFraction*100).toFixed(0)}% of steps make progress (need \u2265 ${(o*100).toFixed(0)}%) \u2014 the curve wanders/descends instead of building`),u.distinct<i&&a.push(`only ${u.distinct} distinct difficulty value(s) across ${l} levels (need \u2265 ${i}) \u2014 the curve is flat; levels don't actually differ in challenge`),Na(a)}function Pp(t,e={}){let n=Aa(t,e);if(n.length)throw new Error(`hayao: difficulty ramp is ill-shaped \u2014 ${n[0]}`)}function Ep(t,e,n){let r=Math.max(2,n.panels??12),o=Math.max(1,Math.ceil(e.length/(r-1))),i=[{frame:0,inner:qe(t.render(),"p0")}];for(let w=0;w<e.length;w++)t.step(e[w]),((w+1)%o===0||w===e.length-1)&&i.push({frame:w+1,inner:qe(t.render(),`p${i.length}`)});let s=Math.max(1,n.cols??4),a=n.panelWidth??320,l=Math.round(a*n.height/n.width),u=18,c=8,m=a+c,d=l+u+c,p=Math.ceil(i.length/s),h=s*m+c,g=p*d+c,x=n.background??"#ffffff",k=i.map((w,P)=>{let $=c+P%s*m,v=c+Math.floor(P/s)*d;return`<g transform="translate(${$} ${v})"><svg width="${a}" height="${l}" viewBox="0 0 ${n.width} ${n.height}"><rect x="0" y="0" width="${n.width}" height="${n.height}" fill="${x}"/>`+w.inner+`</svg><rect x="0" y="0" width="${a}" height="${l}" fill="none" stroke="#999" stroke-width="1"/><text x="${a/2}" y="${l+13}" font-size="11" font-family="monospace" text-anchor="middle" fill="#555">f ${w.frame} \xB7 ${(w.frame/60).toFixed(1)}s</text></g>`}).join("");return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${h} ${g}" width="${h}" height="${g}"><rect x="0" y="0" width="${h}" height="${g}" fill="#f4f4f2"/>`+k+"</svg>"}function Cn(t){let e=t.left.length,n=new Float32Array(e);for(let r=0;r<e;r++)n[r]=(t.left[r]+t.right[r])*.5;return n}function xo(t,e,n,r,o){let i=Math.max(1,Math.floor(t.length/e)),s=`M0 ${o}`,a="";for(let l=0;l<e;l++){let u=0,c=0,m=l*i;for(let p=0;p<i&&m+p<t.length;p++){let h=t[m+p];h>c&&(c=h),h<u&&(u=h)}let d=l/e*n;s+=` L${d.toFixed(1)} ${(o-c*(r/2)).toFixed(1)}`,a=` L${d.toFixed(1)} ${(o-u*(r/2)).toFixed(1)}`+a}return s+a+" Z"}function Lp(t,e={}){let n=e.width??900,r=e.timeBins??220,o=e.freqBands??64,i=16,s=n-i*2,a=70,l=200,u=84,c=i*5+a*2+l+u,m=dt(Cn(t)),d=xo(t.left,r,s,a,a/2),p=xo(t.right,r,s,a,a/2),h=Cn(t),g=2048,x=Math.max(1,Math.floor(h.length/r)),k=s/r,w=l/o,P="";for(let S=0;S<r;S++){let D=S*x;if(D+64>=h.length)break;let C=mt(h.subarray(D,Math.min(D+g,h.length)));if(C.length===0)continue;let y=Math.max(1,Math.floor(C.length/o));for(let T=0;T<o;T++){let E=0;for(let X=0;X<y;X++)E+=C[T*y+X]??0;let O=E>1e-6?20*St(E):-120,F=Math.max(0,Math.min(1,(O+60)/60));if(F<.03)continue;let J=i+S*k,Y=i*3+a*2+l-(T+1)*w,ne=La(F);P+=`<rect x="${J.toFixed(1)}" y="${Y.toFixed(1)}" width="${(k+.6).toFixed(1)}" height="${(w+.6).toFixed(1)}" fill="${ne}"/>`}}let $=za(m).map((S,D)=>`<text x="${i+4}" y="${c-u+20+D*18}" font-family="monospace" font-size="12" fill="#e8e4d8">${S}</text>`).join(""),v=i,f=i*2+a,M=(S,D)=>`<text x="${i}" y="${D-3}" font-family="monospace" font-size="10" fill="#8a8474">${S}</text>`;return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${c}" width="${n}" height="${c}"><rect width="${n}" height="${c}" fill="#1a1814"/>`+(e.title?`<text x="${i}" y="${i-3}" font-family="monospace" font-size="12" fill="#d8b25a">${Wa(e.title)}</text>`:"")+M("L",v)+`<g transform="translate(${i} ${v})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${d}" fill="#5a9ac4" opacity="0.9"/></g>`+M("R",f)+`<g transform="translate(${i} ${f})"><rect width="${s}" height="${a}" fill="#211e18"/><path d="${p}" fill="#5ac48f" opacity="0.9"/></g><rect x="${i}" y="${i*3+a*2}" width="${s}" height="${l}" fill="#0d0c0a"/>`+P+`<rect x="${i}" y="${c-u}" width="${s}" height="${u-i}" fill="#211e18"/>`+$+"</svg>"}function La(t){let e=Math.round(40+t*200),n=Math.round(20+t*t*150),r=Math.round(30+t*40);return`rgb(${e},${n},${r})`}function za(t){return[`dur ${t.durationSec.toFixed(2)}s peak ${t.peakDb.toFixed(1)} dBFS rms ${t.rms.toFixed(3)}`,`centroid ${Math.round(t.centroidHz)} Hz zcr ${Math.round(t.zcr)}/s`,`tempo ~${Math.round(t.tempoBpm)} bpm onsets ${t.onsetDensity.toFixed(1)}/s`]}function Wa(t){return t.replace(/[<>&]/g,e=>e==="<"?"&lt;":e===">"?"&gt;":"&amp;")}function zp(t,e){let n=dt(Cn(t)),r=[],o=(i,s)=>{i||r.push(s)};if(e.minDurationSec!==void 0&&o(n.durationSec>=e.minDurationSec,`duration ${n.durationSec.toFixed(2)}s < min ${e.minDurationSec}`),e.maxDurationSec!==void 0&&o(n.durationSec<=e.maxDurationSec,`duration ${n.durationSec.toFixed(2)}s > max ${e.maxDurationSec}`),e.maxPeakDb!==void 0&&o(n.peakDb<=e.maxPeakDb,`peak ${n.peakDb.toFixed(1)}dB > max ${e.maxPeakDb}`),e.minRms!==void 0&&o(n.rms>=e.minRms,`rms ${n.rms.toFixed(3)} < min ${e.minRms} (too quiet?)`),e.minCentroidHz!==void 0&&o(n.centroidHz>=e.minCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz < min ${e.minCentroidHz}`),e.maxCentroidHz!==void 0&&o(n.centroidHz<=e.maxCentroidHz,`centroid ${Math.round(n.centroidHz)}Hz > max ${e.maxCentroidHz}`),e.tempoBpm!==void 0){let i=e.tempoToleranceBpm??12;o(Math.abs(n.tempoBpm-e.tempoBpm)<=i,`tempo ${Math.round(n.tempoBpm)}bpm not within ${i} of ${e.tempoBpm}`)}return{ok:r.length===0,failures:r,features:n}}var Qt=class{rng;clock;input=new Nt;events=new Tt;resources=new Map;state={};width;height;root;activeCamera=null;seed;freeQueue=[];started=!1;tuningValues;constructor(e={}){this.seed=e.seed??1,this.rng=new ce(this.seed),this.clock=new Ct(e.clock),this.width=e.width??1280,this.height=e.height??720,this.tuningValues={...e.tuning??{}},this.root=new j({name:"root"})}tune(e){let n=this.tuningValues[e];if(n===void 0)throw new Error(`tune('${e}'): no such knob declared in the game's tuning spec`);return n}get time(){return this.clock.simTimeSec}get frame(){return this.clock.frame}setRoot(e){this.root&&this.root.exitTree(),this.root=e,this.started=!1}requestFree(e){this.freeQueue.push(e)}ensureStarted(){this.started||(this.root.enterTree(this),this.started=!0)}step(e=[]){this.ensureStarted(),this.input.beginFrame(e),this.root.updateTree(this.clock.dt),this.flushFree(),this.clock.tick()}advance(e,n=[]){let r=this.clock.advance(e);for(let o=0;o<r;o++)this.step(n);return r}runSteps(e,n){for(let r=0;r<e;r++)this.step(n?n(r):[])}flushFree(){if(this.freeQueue.length===0)return;let e=this.freeQueue;this.freeQueue=[];for(let n of e)n.exitTree(),n.parent?.removeChild(n),this.activeCamera===n&&(this.activeCamera=null)}viewTransform(){if(!this.activeCamera)return le;let e=this.activeCamera,n=e.worldTransform();return et(Mt({x:this.width/2,y:this.height/2},0,{x:e.zoom,y:e.zoom}),sn(n))}worldToScreen(e){return on(this.viewTransform(),e)}screenToWorld(e){return on(sn(this.viewTransform()),e)}render(){this.ensureStarted();let e=[];return this.root.collectDraw(e,this.viewTransform()),e}hash(){return Rt({seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:this.state,tree:this.root.serialize(),...Object.keys(this.tuningValues).length>0?{tuning:this.tuningValues}:{}})}snapshot(){return{seed:this.seed,rng:this.rng.getState(),clock:this.clock.getState(),input:this.input.getState(),state:structuredClone(this.state),tree:this.root.serialize(),tuning:{...this.tuningValues}}}restore(e){this.seed=e.seed,this.rng.setState(e.rng),this.clock.setState(e.clock),this.input.setState(e.input),this.state=structuredClone(e.state),e.tuning&&(this.tuningValues={...e.tuning}),Hn(1e6),this.setRoot(ln(e.tree)),this.ensureStarted()}probe(){return{frame:this.frame,time:this.time,hash:this.hash(),nodes:this.root.query("Sprite").length+this.root.query("Text").length}}};var Up={num(t,e){return{key:t,type:"number",...e}},color(t,e){return{key:t,type:"color",cosmetic:!0,...e}},enumOf(t,e){return{key:t,type:"enum",...e}}};function Zt(t,e){let n={};if(!t)return n;for(let r of t.knobs){n[r.key]=r.default;let o=e?.[r.key];if(o!==void 0)if(r.type==="number"){let i=typeof o=="number"?o:Number(o);if(!Number.isFinite(i))continue;let s=r.min??-1/0,a=r.max??1/0;n[r.key]=Math.min(a,Math.max(s,i))}else r.type==="enum"?typeof o=="string"&&(r.options??[]).includes(o)&&(n[r.key]=o):typeof o=="string"&&(n[r.key]=o)}return n}function Zp(t){return{width:1280,height:720,seed:1,background:"#f3ecdb",inputMap:un,...t}}function Re(t,e){let n=typeof e=="number"?{seed:e}:e??{},r=new Qt({seed:n.seed??t.seed??1,width:t.width??1280,height:t.height??720,clock:t.clock,tuning:Zt(t.tuning,n.tuning)});return r.setRoot(t.build(r)),t.probe&&(r.probe=()=>t.probe(r)),r}function eh(t){return t.inputMap??un}function th(t,e){let n=Re(t),r=e?.frames??[];for(let o of r)n.step(o);return{world:n,hash:n.hash(),steps:r.length}}function vo(t,e,n){let r=typeof n=="number"?{toFrame:n}:n??{},o=Re(t,{seed:e.seed,tuning:e.tuningValues});e.startSnapshot&&(o.restore(structuredClone(e.startSnapshot)),t.attach?.(o)),r.onWorld?.(o);let i=Math.min(r.toFrame??e.inputLog.frames.length,e.inputLog.frames.length),s=0,a=0,l={...e.tuningValues};for(let u=0;u<i;u++){for(;a<e.knobEvents.length&&e.knobEvents[a].frame===u;){let c=e.knobEvents[a++];l[c.key]=c.value;let m=o.snapshot();m.tuning={...l},o.restore(m),t.attach?.(o)}for(;s<e.axesLog.length&&e.axesLog[s][0]===u;){let[,c,m]=e.axesLog[s++];o.input.axes.set(c,m)}o.step(e.inputLog.frames[u]),r.onFrame?.(o,u)}return o}function wo(t){let{frame:e,time:n,hash:r,...o}=t;return JSON.stringify(o)}function Ba(t){let e=t.px??t.x,n=t.py??t.y;return typeof e=="number"&&typeof n=="number"?{x:e,y:n}:null}function Oa(t){let e=[],n=null;for(let o of t.wallClockMarks)o.kind==="visibility-hidden"&&n===null&&(n=o.frame),o.kind==="visibility-visible"&&n!==null&&(e.push([n,o.frame]),n=null);n!==null&&e.push([n,t.inputLog.frames.length]);let r=null;for(let o of t.screenEvents)(o.kind==="overlay-show"||o.kind==="pause")&&r===null&&(r=o.frame),(o.kind==="overlay-hide"||o.kind==="resume")&&r!==null&&(e.push([r,o.frame]),r=null);return e}var Ga=(t,e)=>e.some(([n,r])=>t>=n&&t<r);function sh(t,e,n={}){let r=n.hesitationFrames??45,o=n.futileWindow??30,i=n.quitWindow??300,s=n.clusterPx??64,a=e.inputLog.frames,l=Oa(e),u=new Set(e.axesLog.map(([y])=>y)),c=[],m=null;for(let y=0;y<=a.length;y++){let T=y<a.length&&a[y].length===0&&!u.has(y);if(T&&m===null&&(m=y),!T&&m!==null){let E=y-m;E>=r&&!Ga(m,l)&&c.push({startFrame:m,frames:E}),m=null}}let d=new Map;for(let y=0;y<a.length;y++){let T=y>0?a[y-1]:[];for(let E of a[y])T.includes(E)||(d.has(E)||d.set(E,[]),d.get(E).push(y))}let h=Object.keys(t.inputMap??{}).filter(y=>!d.has(y)),g=new Set;for(let y of c)g.add(y.startFrame);for(let y of e.annotations)g.add(Math.max(0,Math.min(y.frame,a.length-1)));for(let[,y]of d)for(let T of y)g.add(Math.max(0,T-1)),g.add(Math.min(a.length-1,T+o));a.length>0&&g.add(a.length-1);let x=new Map,k=[],w=!1,P=-1,$=vo(t,e,{onWorld:y=>{y.events.on("death",()=>k.push({frame:P+1,pos:Ba(y.probe())})),y.events.on("goal",()=>w=!0)},onFrame:(y,T)=>{P=T,g.has(T)&&x.set(T,y.probe())}}),v=a.length>0?x.get(a.length-1)??$.probe():$.probe();v.won===!0&&(w=!0);let f=c.map(y=>({...y,probe:x.get(y.startFrame)??{}})),M=new Map;for(let y of k){let T=y.pos?`${Math.round(y.pos.x/s)}:${Math.round(y.pos.y/s)}`:"unknown",E=M.get(T)??{x:y.pos?.x??0,y:y.pos?.y??0,count:0,frames:[]};E.count++,E.frames.push(y.frame),M.set(T,E)}let S=[];for(let[y,T]of d){let E=[];for(let O of T){let F=x.get(Math.max(0,O-1)),J=x.get(Math.min(a.length-1,O+o));F&&J&&wo(F)===wo(J)&&E.push(O)}E.length>0&&S.push({action:y,futilePresses:E.length,totalPresses:T.length,frames:E})}let D=e.annotations.map(y=>{let T=Math.max(0,Math.min(y.frame,a.length-1));return{frame:y.frame,tag:y.tag,...y.note!==void 0?{note:y.note}:{},probe:x.get(T)??{}}}),C={sessionId:e.id,game:e.game,buildRef:e.buildRef,seed:e.seed,variant:e.variant,frames:a.length,simSeconds:$.time,reachedGoal:w,deaths:k.length,hesitations:f,deathClusters:[...M.values()].sort((y,T)=>T.count-y.count),futileVerbs:S.sort((y,T)=>T.futilePresses-y.futilePresses),annotations:D,knobEvents:e.knobEvents,unusedActions:h};if(!w&&a.length>0){let y=Math.max(0,a.length-i);C.quit={frame:a.length-1,probe:v,recentDeaths:k.filter(T=>T.frame>=y).length,recentHesitations:f.filter(T=>T.startFrame>=y).length,endReason:e.endReason}}return C}var ko=class{constructor(e,n,r,o){this.states=e;this.transitions=n;this.ctx=o;this.current=r,this.states[r]?.onEnter?.(o)}states;transitions;ctx;current;update(e){for(let n of this.transitions)if((n.from==="*"||n.from===this.current)&&n.when(this.ctx)){this.go(n.to);break}this.states[this.current]?.onUpdate?.(this.ctx,e)}go(e){e!==this.current&&(this.states[this.current]?.onLeave?.(this.ctx),this.current=e,this.states[e]?.onEnter?.(this.ctx))}is(...e){return e.includes(this.current)}getState(){return this.current}setState(e){this.current=e}},So=class{constructor(e,n){this.defs=e;if(!e[n])throw new Error(`hayao: PhaseClock has no phase '${n}'`);this.phase=n}defs;phase;elapsed=0;get duration(){return this.defs[this.phase]?.duration??0}progress(e=n=>n){let n=this.duration,r=n>0?this.elapsed/n:1;return e(r<0?0:r>1?1:r)}get done(){return this.elapsed>=this.duration}update(e){this.elapsed+=e;let n=!1,r=0;for(;this.elapsed>=this.duration&&this.defs[this.phase]?.next!==void 0&&r++<1024;){let o=this.elapsed-this.duration;this.phase=this.defs[this.phase].next,this.elapsed=o,n=!0}return n}to(e){if(!this.defs[e])throw new Error(`hayao: PhaseClock has no phase '${e}'`);this.phase=e,this.elapsed=0}getState(){return{phase:this.phase,elapsed:this.elapsed}}setState(e){this.phase=e.phase,this.elapsed=e.elapsed}};function Va(t){let e=0;for(let n of t)e+=n>0?n:0;return e}function Co(t,e){let n=Va(e);if(n<=0)throw new Error("hayao: weightedIndex needs at least one positive weight");let r=t.float()*n;for(let o=0;o<e.length;o++){let i=e[o]>0?e[o]:0;if(r<i)return o;r-=i}for(let o=e.length-1;o>=0;o--)if(e[o]>0)return o;return e.length-1}function uh(t,e,n){if(e.length!==n.length)throw new Error("hayao: weightedPick items/weights length mismatch");return e[Co(t,n)]}function To(t,e){return e[Co(t,e.map(n=>n.weight))].value}var Mo=class{values;cumulative;total;constructor(e){if(e.length===0)throw new Error("hayao: LootTable needs at least one entry");let n=[],r=[],o=0;for(let i of e)o+=i.weight>0?i.weight:0,n.push(i.value),r.push(o);if(o<=0)throw new Error("hayao: LootTable needs at least one positive weight");this.values=n,this.cumulative=r,this.total=o}roll(e){let n=e.float()*this.total;for(let r=0;r<this.cumulative.length;r++)if(n<this.cumulative[r])return this.values[r];return this.values[this.values.length-1]}rollMany(e,n){let r=[];for(let o=0;o<n;o++)r.push(this.roll(e));return r}};function qa(t,e,n,r={}){let o=r.maxNodes??1e6,i=[],s=new Map,a=new Map,l=n(t);a.set(l,0);let u=[t];if(i.push(t),r.goal?.(t))return{order:i,cameFrom:s,dist:a};let c=0;for(;u.length>0&&c<o;){let m=[];for(let d of u){let p=a.get(n(d))??0;for(let h of e(d)){let g=n(h);if(!a.has(g)){if(a.set(g,p+1),s.set(g,d),i.push(h),c++,r.goal?.(h))return{order:i,cameFrom:s,dist:a};m.push(h)}}}u=m}return{order:i,cameFrom:s,dist:a}}function dh(t,e,n,r){let o=[r],i=r,s=e(n);for(;e(i)!==s;){let a=t.get(e(i));if(a===void 0)return[];i=a,o.push(i)}return o.reverse(),o}function ja(t,e,n,r,o={}){let i=o.heuristic??(()=>0),s=o.maxNodes??1e6,a=new Map,l=new Map,u=new Tn,c=r(t);l.set(c,0),u.push(t,i(t));let m=0;for(;u.size>0&&m<s;){let{item:d,priority:p}=u.pop(),h=r(d),g=l.get(h)??1/0;if(!(p>g+i(d)+1e-9)){if(e(d))return{path:Ha(a,r,d),cost:g};m++;for(let x of n(d)){let k=r(x.node),w=g+x.cost;w<(l.get(k)??1/0)&&(l.set(k,w),a.set(k,d),u.push(x.node,w+i(x.node)))}}}return null}function Ha(t,e,n){let r=[n],o=n,i=t.get(e(o));for(;i!==void 0;)o=i,r.push(o),i=t.get(e(o));return r.reverse(),r}var Tn=class{items=[];prio=[];seq=[];counter=0;get size(){return this.items.length}push(e,n){this.items.push(e),this.prio.push(n),this.seq.push(this.counter++),this.bubbleUp(this.items.length-1)}pop(){let e=this.items[0],n=this.prio[0],r=this.items.length-1;return this.swap(0,r),this.items.pop(),this.prio.pop(),this.seq.pop(),this.items.length>0&&this.bubbleDown(0),{item:e,priority:n}}less(e,n){return this.prio[e]<this.prio[n]||this.prio[e]===this.prio[n]&&this.seq[e]<this.seq[n]}bubbleUp(e){for(;e>0;){let n=e-1>>1;if(!this.less(e,n))break;this.swap(e,n),e=n}}bubbleDown(e){let n=this.items.length;for(;;){let r=2*e+1,o=2*e+2,i=e;if(r<n&&this.less(r,i)&&(i=r),o<n&&this.less(o,i)&&(i=o),i===e)break;this.swap(e,i),e=i}}swap(e,n){[this.items[e],this.items[n]]=[this.items[n],this.items[e]],[this.prio[e],this.prio[n]]=[this.prio[n],this.prio[e]],[this.seq[e],this.seq[n]]=[this.seq[n],this.seq[e]]}},en=[{x:0,y:-1},{x:1,y:0},{x:0,y:1},{x:-1,y:0}],Rn=[...en,{x:1,y:-1},{x:1,y:1},{x:-1,y:1},{x:-1,y:-1}],Ro=t=>`${t.x},${t.y}`;function _a(t,e,n,r){let o=r?Rn:en;return i=>{let s=[];for(let a of o){let l=i.x+a.x,u=i.y+a.y;l<0||u<0||l>=e||u>=n||t(l,u)&&s.push({x:l,y:u})}return s}}function Po(t,e,n){if(!e(t.x,t.y))return[];let r=_a(e,n.cols,n.rows,n.diagonal??!1);return qa(t,r,Ro).order}function ph(t,e,n,r=!1){let o=new Array(t*e).fill(-1),i=[],s=r?Rn:en;for(let a=0;a<e;a++)for(let l=0;l<t;l++){if(o[a*t+l]!==-1||!n(l,a))continue;let u=i.length,c=[],m=[{x:l,y:a}];for(o[a*t+l]=u;m.length>0;){let d=[];for(let p of m){c.push(p);for(let h of s){let g=p.x+h.x,x=p.y+h.y;if(g<0||x<0||g>=t||x>=e)continue;let k=x*t+g;o[k]!==-1||!n(g,x)||(o[k]=u,d.push({x:g,y:x}))}}m=d}i.push(c)}return{labels:o,cells:i}}function hh(t,e,n,r){let o=r.diagonal??!1,i=o?Rn:en,s=r.cost??(()=>1),a=1.4142135623730951,l=m=>{let d=[];for(let p of i){let h=m.x+p.x,g=m.y+p.y;if(h<0||g<0||h>=r.cols||g>=r.rows||!n(h,g))continue;let x=p.x!==0&&p.y!==0;d.push({node:{x:h,y:g},cost:s(h,g)*(x?a:1)})}return d},u=m=>{let d=Math.abs(m.x-e.x),p=Math.abs(m.y-e.y);if(!o)return d+p;let h=Math.min(d,p);return d+p-(2-a)*h};if(!n(e.x,e.y))return null;let c=ja(t,m=>m.x===e.x&&m.y===e.y,l,Ro,{heuristic:u,maxNodes:r.maxNodes});return c?c.path:null}function fh(t){return(e,n)=>fe(t,e,n)!==H.SOLID}function Ja(t){return structuredClone(t)}var Do=class{history=[];cursor=-1;limit;clone;constructor(e={}){this.limit=Math.max(1,e.limit??64),this.clone=e.clone??Ja}record(e){if(this.history.length=this.cursor+1,this.history.push(this.clone(e)),this.cursor=this.history.length-1,this.history.length>this.limit){let n=this.history.length-this.limit;this.history.splice(0,n),this.cursor-=n}}undo(){if(!(this.cursor<=0))return this.cursor--,this.clone(this.history[this.cursor])}redo(){if(!(this.cursor>=this.history.length-1))return this.cursor++,this.clone(this.history[this.cursor])}current(){return this.cursor>=0?this.clone(this.history[this.cursor]):void 0}get canUndo(){return this.cursor>0}get canRedo(){return this.cursor<this.history.length-1}get size(){return this.history.length}clear(){this.history.length=0,this.cursor=-1}},Io=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<1)throw new Error("hayao: RingBuffer capacity must be a positive integer");this.buf=new Array(e)}capacity;buf;start=0;count=0;push(e){let n=(this.start+this.count)%this.capacity;this.buf[n]=e,this.count<this.capacity?this.count++:this.start=(this.start+1)%this.capacity}get length(){return this.count}get isFull(){return this.count===this.capacity}at(e){if(!(e<0||e>=this.count))return this.buf[(this.start+e)%this.capacity]}latest(){return this.at(this.count-1)}toArray(){let e=[];for(let n=0;n<this.count;n++)e.push(this.buf[(this.start+n)%this.capacity]);return e}clear(){this.start=0,this.count=0,this.buf.fill(void 0)}};var Pn=class{map=new Map;get(e){return this.map.has(e)?this.map.get(e):null}set(e,n){this.map.set(e,n)}remove(e){this.map.delete(e)}keys(){return[...this.map.keys()]}},Eo=class{get(e){return null}set(e,n){}remove(e){}keys(){return[]}},Dn=class{constructor(e="hayao.save."){this.prefix=e}prefix;ls(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}get(e){try{return this.ls()?.getItem(this.prefix+e)??null}catch{return null}}set(e,n){try{this.ls()?.setItem(this.prefix+e,n)}catch{}}remove(e){try{this.ls()?.removeItem(this.prefix+e)}catch{}}keys(){let e=this.ls();if(!e)return[];let n=[];try{for(let r=0;r<e.length;r++){let o=e.key(r);o&&o.startsWith(this.prefix)&&n.push(o.slice(this.prefix.length))}}catch{}return n}};function Fo(t){try{if(typeof localStorage<"u"){let e="__hayao_probe__";return localStorage.setItem(e,"1"),localStorage.removeItem(e),new Dn(t)}}catch{}return new Pn}function xh(t){let e="",n=0;for(;n<t.length;){let r=t[n],o=1;for(;n+o<t.length&&t[n+o]===r;)o++;o>=4||r==="~"?e+="~"+r+o.toString(36)+"~":e+=r.repeat(o),n+=o}return e}function vh(t){let e="",n=0;for(;n<t.length;)if(t[n]==="~"){let r=t[n+1],o=t.indexOf("~",n+2);if(r===void 0||o<0)throw new Error("hayao: malformed RLE stream");let i=parseInt(t.slice(n+2,o),36);if(!Number.isFinite(i)||i<1)throw new Error("hayao: malformed RLE count");e+=r.repeat(i),n=o+1}else e+=t[n],n++;return e}var In="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",No={};for(let t=0;t<In.length;t++)No[In[t]]=t;function wh(t){let e="";for(let n of t){if(!Number.isInteger(n)||n<0)throw new Error(`hayao: packVarints expects non-negative integers, got ${n}`);let r=n;do{let o=r&31;r=Math.floor(r/32),r>0&&(o|=32),e+=In[o]}while(r>0)}return e}function kh(t){let e=[],n=0,r=1;for(let o of t){let i=No[o];if(i===void 0)throw new Error(`hayao: unpackVarints saw invalid char "${o}"`);n+=(i&31)*r,i&32?r*=32:(e.push(n),n=0,r=1)}if(r!==1)throw new Error("hayao: unpackVarints hit a truncated stream");return e}var Lo=1;function Ua(t){return JSON.stringify({v:Lo,snap:t})}function $o(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e;if(n.v!==Lo||!n.snap||typeof n.snap!="object")return null;let r=n.snap;return typeof r.seed!="number"||!r.rng||!r.clock||!r.input||!r.state||!r.tree?null:r}var Ao=class{constructor(e,n=Fo()){this.world=e;this.storage=n}world;storage;save(e="auto"){this.storage.set(e,Ua(this.world.snapshot()))}load(e="auto"){let n=$o(this.storage.get(e));return n?(this.world.restore(n),!0):!1}has(e="auto"){return $o(this.storage.get(e))!==null}delete(e="auto"){this.storage.remove(e)}slots(){return this.storage.keys()}};function Rh(t){return{next:t.map(e=>e.time)}}function Ph(t,e,n,r){let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e.next[i]??s.time;for(;a<=n;){let l;if(typeof s.spawn=="string")l=s.spawn;else{if(!r)throw new Error("hayao: pollDirector needs an Rng to roll a weighted wave");l=To(r,s.spawn)}if(o.push({spawn:l,count:s.count??1,wave:i}),s.every&&s.every>0){if(a+=s.every,s.end!==void 0&&a>=s.end){a=1/0;break}}else{a=1/0;break}}e.next[i]=a}return o}function Dh(t,e){let n=new Map;for(let o of e)n.set(o,(n.get(o)??0)+1);let r=o=>(n.get(o)??0)>0;return t.filter(o=>(n.get(o.id)??0)>=(o.maxStacks??1)?!1:(o.requires??[]).every(r))}var Ka=new Set(["#","-","^","."," "]),gt=t=>t===H.SOLID,Ya=t=>t===H.HAZARD,Xa=(t,e,n)=>({x:(t+.5)*n,y:(e+.5)*n});function Nh(t){let e=t.tileSize??32,n=t.legend??{},r=t.rows,o=Math.max(0,...r.map(l=>l.length)),i=null,s=null,a=[];if(r.forEach((l,u)=>{for(let c=0;c<l.length;c++){let m=l[c];if(m==="S")i={x:c,y:u};else if(m==="G")s={x:c,y:u};else if(m in n){let d=Xa(c,u,e);a.push({kind:n[m],tx:c,ty:u,x:d.x,y:d.y})}}}),!i)throw new Error(`level "${t.name}": no spawn marker 'S'`);if(!s)throw new Error(`level "${t.name}": no goal marker 'G'`);return{name:t.name,tileSize:e,rows:r,legend:n,cols:o,rowCount:r.length,spawn:i,goal:s,entities:a}}function $h(t){let e=[],n=En(t),r=o=>n.tiles[o.y*n.cols+o.x]??H.EMPTY;return t.rows.forEach((o,i)=>{for(let s=0;s<o.length;s++){let a=o[s];a==="S"||a==="G"||Ka.has(a)||a in t.legend||e.push(`unknown glyph '${a}' at (${s},${i}) \u2014 add it to the legend or use terrain '#/-/^/.'`)}}),gt(r(t.spawn))&&e.push(`spawn (${t.spawn.x},${t.spawn.y}) is inside a solid tile`),gt(r(t.goal))&&e.push(`goal (${t.goal.x},${t.goal.y}) is inside a solid tile`),[...new Set(e)]}function En(t){return ir(t.rows,t.tileSize)}function Ah(t,e={}){let n=En(t),r=(l,u)=>n.tiles[u*n.cols+l]??H.EMPTY,o=e.passable??((l,u)=>!gt(r(l,u))),i=Po(t.spawn,o,{cols:n.cols,rows:n.rows,diagonal:e.diagonal}),s=new Set(i.map(l=>`${l.x},${l.y}`)),a=[];s.has(`${t.goal.x},${t.goal.y}`)||a.push("goal");for(let l of t.entities)s.has(`${l.tx},${l.ty}`)||a.push(`entity@${l.tx},${l.ty}`);return{ok:a.length===0,unreachable:a,reached:i.length}}function Lh(t,e){let n=En(t),{cols:r,rows:o}=n,i=(w,P)=>w<0||P<0||w>=r||P>=o?H.SOLID:n.tiles[P*r+w],s=(w,P)=>{let $=i(w,P+1);return $===H.SOLID||$===H.ONEWAY},a=(w,P)=>!gt(i(w,P))&&!Ya(i(w,P))&&s(w,P),u=(w=>{for(let P=w.y;P<o;P++)if(a(w.x,P))return{x:w.x,y:P};return null})(t.spawn);if(!u)return{ok:!1,unreachable:["goal"],reached:0};let c=(w,P)=>Math.abs(P.x-w.x)<=e.runTiles&&w.y-P.y<=e.jumpTiles,m=[];for(let w=0;w<o;w++)for(let P=0;P<r;P++)a(P,w)&&m.push({x:P,y:w});let d=w=>`${w.x},${w.y}`,p=new Set([d(u)]),h=[u];for(;h.length;){let w=h.shift();for(let P of m){let $=d(P);!p.has($)&&c(w,P)&&(p.add($),h.push(P))}}let g=[...p].map(w=>{let[P,$]=w.split(",").map(Number);return{x:P,y:$}}),k=!gt(i(t.goal.x,t.goal.y))&&(p.has(d(t.goal))||g.some(w=>c(w,t.goal)))?[]:["goal"];return{ok:k.length===0,unreachable:k,reached:p.size}}function zh(t,e){let n=[],r=Math.max(t.rowCount,e.rowCount),o=Math.max(t.cols,e.cols),i=(u,c,m)=>u.rows[m]?.[c]??" ";for(let u=0;u<r;u++)for(let c=0;c<o;c++){let m=i(t,c,u),d=i(e,c,u);m!==d&&n.push({kind:"tile",detail:`(${c},${u}) '${m}' \u2192 '${d}'`})}let s=u=>`${u.kind}@${u.tx},${u.ty}`,a=new Set(t.entities.map(s)),l=new Set(e.entities.map(s));for(let u of e.entities)a.has(s(u))||n.push({kind:"entity+",detail:s(u)});for(let u of t.entities)l.has(s(u))||n.push({kind:"entity-",detail:s(u)});return(t.spawn.x!==e.spawn.x||t.spawn.y!==e.spawn.y)&&n.push({kind:"spawn",detail:`(${t.spawn.x},${t.spawn.y}) \u2192 (${e.spawn.x},${e.spawn.y})`}),(t.goal.x!==e.goal.x||t.goal.y!==e.goal.y)&&n.push({kind:"goal",detail:`(${t.goal.x},${t.goal.y}) \u2192 (${e.goal.x},${e.goal.y})`}),n}function Qa(t,e){return qn(`hayao/gen:${t>>>0}:${e}`)}var Za=(t,e,n)=>(n.minDepth===void 0||t>=n.minDepth)&&(n.maxDepth===void 0||t<=n.maxDepth)&&(n.minNodes===void 0||e>=n.minNodes)&&(n.maxNodes===void 0||e<=n.maxNodes);function el(t,e){let n=e.seed??1,r=e.maxAttempts??e.count*60,o=e.dedupeKey??(u=>u.key(u.initial())),i=[],s=new Set,a=0,l=0;for(let u=0;u<r&&i.length<e.count;u++){a++;let c=Qa(n,u),m=t(new ce(c)),d=Ye(m,e.solve);if(!d.solvable||d.exhausted||d.depth===void 0)continue;l++;let p={path:d.path??[],depth:d.depth,nodes:d.nodes};if(!Za(p.depth,p.nodes,e))continue;let h=o(m,p);s.has(h)||e.reject?.(m,p,c)||(s.add(h),i.push({...p,index:0,seed:c,puzzle:m}))}return i.sort((u,c)=>u.depth-c.depth||u.nodes-c.nodes||u.seed-c.seed),i.forEach((u,c)=>u.index=c),{levels:i,attempts:a,solvable:l,complete:i.length>=e.count,seeds:i.map(u=>u.seed)}}function zo(t,e){let n=el(t,e);if(!n.complete)throw new Error(`hayao: generator found only ${n.levels.length}/${e.count} in-band levels in ${n.attempts} attempts (${n.solvable} solvable). Widen the band [depth ${e.minDepth??0}..${e.maxDepth??"\u221E"}] or raise maxAttempts.`);return n.levels}function Gh(t,e){return t(new ce(e))}function jh(t){let e=t.seed??1,n=t.minutesPerLevel??1.5,r=[],o=[];return t.acts.forEach((i,s)=>{let a=i.factory??t.factory;if(!a)throw new Error(`hayao: act "${i.name}" has no factory and the campaign has no default`);let l=(e^(s+1)*2654435769)>>>0,u=zo(a,{count:i.count,seed:l,minDepth:i.minDepth,maxDepth:i.maxDepth,minNodes:i.minNodes,maxNodes:i.maxNodes,solve:i.solve??t.solve,maxAttempts:i.maxAttempts}),c=r.length;u.forEach((m,d)=>{r.push({...m,index:r.length,act:s,actName:i.name,actIndex:d})}),o.push({name:i.name,from:c,to:r.length-1})}),{levels:r,acts:o,difficulty:r.map(i=>i.depth),seeds:r.map(i=>i.seed),estMinutes:r.length*n}}function tl(t,e){let n=new Map(t.pickups.map(o=>[o.id,o.grants])),r=new Set;for(let o of e){let i=n.get(o);i&&r.add(i)}return r}function Wo(t,e){return(t.requires??[]).every(n=>e.has(n))}function Bo(t,e,n){let r=[];for(let o of t.edges)o.from===e&&Wo(o,n)?r.push(o.to):!o.oneWay&&o.to===e&&Wo(o,n)&&r.push(o.from);return r}function Fn(t,e="complete"){let n=o=>t.pickups.filter(i=>i.region===o),r=t.pickups.length;return{initial:()=>({region:t.start,taken:[]}),moves:o=>{let i=tl(t,o.taken),s=[];for(let l of n(o.region))o.taken.includes(l.id)||s.push({kind:"take",pickup:l.id});let a=new Set;for(let l of Bo(t,o.region,i))a.has(l)||(a.add(l),s.push({kind:"move",to:l}));return s},apply:(o,i)=>{if(i.kind==="move")return{region:i.to,taken:o.taken};let s=[...o.taken,i.pickup].sort();return{region:o.region,taken:s}},isWin:o=>o.region===t.goal&&(e==="complete"||o.taken.length===r),key:o=>`${o.region}|${o.taken.join(",")}`}}var Oo={maxDepth:2e3,nodeCap:5e6};function Jh(t){return Ye(Fn(t,"complete"),Oo)}function Uh(t){return Ye(Fn(t,"full"),Oo)}function nl(t,e){let n=new Set(e),r=new Set([t.start]),o=[t.start];for(;o.length;){let i=o.shift();for(let s of Bo(t,i,n))r.has(s)||(r.add(s),o.push(s))}return[...r]}function Kh(t,e="complete"){let n=Fn(t,e),r=n.initial(),o=n.key(r),i=new Map([[o,r]]),s=new Map,a=new Set,l=[r];for(n.isWin(r)&&a.add(o);l.length;){let p=l.shift(),h=n.key(p),g=[];for(let x of n.moves(p)){let k=n.apply(p,x),w=n.key(k);g.push(w),i.has(w)||(i.set(w,k),n.isWin(k)&&a.add(w),l.push(k))}s.set(h,g)}let u=new Map;for(let[p,h]of s)for(let g of h)(u.get(g)??u.set(g,[]).get(g)).push(p);let c=new Set(a),m=[...a];for(;m.length;){let p=m.shift();for(let h of u.get(p)??[])c.has(h)||(c.add(h),m.push(h))}let d=[...i.keys()].filter(p=>!c.has(p)).sort();return{ok:d.length===0,deadEnds:d,statesExplored:i.size}}function Yh(t){let e=[],n=new Set;for(let a of t.regions)n.has(a.id)&&e.push(`duplicate region id "${a.id}"`),n.add(a.id);let r=a=>n.has(a);r(t.start)||e.push(`start region "${t.start}" is not defined`),r(t.goal)||e.push(`goal region "${t.goal}" is not defined`);for(let a of t.edges)r(a.from)||e.push(`edge references unknown region "${a.from}"`),r(a.to)||e.push(`edge references unknown region "${a.to}"`);let o=new Set;for(let a of t.pickups)o.has(a.id)&&e.push(`duplicate pickup id "${a.id}"`),o.add(a.id),r(a.region)||e.push(`pickup "${a.id}" is in unknown region "${a.region}"`);let i=t.pickups.map(a=>a.grants),s=new Set(nl(t,i));for(let a of t.regions)s.has(a.id)||e.push(`region "${a.id}" is unreachable even with every ability`);return e}function Qh(t){let e=[];for(let n=1;n<=t;n++)e.push(`p${n}`);return e}var tn=(t,e)=>`${t}:${e}`;function yt(t,e){let n=[];for(let r of t){let o=e.get(r)??[];for(let i of o)n.push(tn(r,i))}return n.sort()}var Nn=class{constructor(e,n){this.world=e;this.player=n}world;player;isDown(e){return this.world.input.isDown(tn(this.player,e))}justPressed(e){return this.world.input.justPressed(tn(this.player,e))}justReleased(e){return this.world.input.justReleased(tn(this.player,e))}},Zh=(t,e)=>new Nn(t,e);var tf=1,Xe={mode:"lockstep",inputDelay:2,hashInterval:20,maxRollback:12,redundancy:3};function de(t){return JSON.stringify(t)}function $e(t){try{let e=JSON.parse(t);return!e||typeof e!="object"||e.v!==1||typeof e.t!="string"?null:e}catch{return null}}function pe(t){return{v:1,...t}}var Go=class{peers=[];queue=[];tickCount=0;seq=0;sent=0;delay;dropEvery;constructor(e={}){this.delay=e.delay??0,this.dropEvery=e.dropEvery??0}connect(){let e=new $n(this,this.peers.length);return this.peers.push(e),e}enqueue(e,n){this.sent++,!(this.dropEvery>0&&this.sent%this.dropEvery===0)&&this.queue.push({data:e,from:n,dueTick:this.tickCount+this.delay,seq:this.seq++})}tick(){let e=this.queue.filter(n=>n.dueTick<=this.tickCount).sort((n,r)=>n.seq-r.seq);this.queue=this.queue.filter(n=>n.dueTick>this.tickCount),this.tickCount++;for(let n of e)for(let r of this.peers)r.peerIndex!==n.from&&r.isOpen&&r.deliver(n.data)}flush(){for(;this.queue.length>0;)this.tick()}get pending(){return this.queue.length}},$n=class{constructor(e,n){this.hub=e;this.peerIndex=n}hub;peerIndex;listeners=[];closeListeners=[];open=!0;send(e){this.open&&this.hub.enqueue(e,this.peerIndex)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1;for(let e of this.closeListeners)e()}}get isOpen(){return this.open}deliver(e){for(let n of this.listeners)n(e)}},Vo=class{channel;listeners=[];closeListeners=[];open=!0;constructor(e){this.channel=new BroadcastChannel(`hayao-net:${e}`),this.channel.onmessage=n=>{if(typeof n.data=="string")for(let r of this.listeners)r(n.data)}}send(e){this.open&&this.channel.postMessage(e)}onMessage(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e)}}onClose(e){return this.closeListeners.push(e),()=>{this.closeListeners=this.closeListeners.filter(n=>n!==e)}}close(){if(this.open){this.open=!1,this.channel.close();for(let e of this.closeListeners)e()}}get isOpen(){return this.open}};function rf(t){return new Promise((e,n)=>{let r=new WebSocket(t),o=[],i=[],s=!1,a={send(l){s&&r.send(l)},onMessage(l){return o.push(l),()=>{let u=o.indexOf(l);u>=0&&o.splice(u,1)}},onClose(l){return i.push(l),()=>{let u=i.indexOf(l);u>=0&&i.splice(u,1)}},close(){s=!1,r.close()},get isOpen(){return s}};r.onopen=()=>{s=!0,e(a)},r.onmessage=l=>{if(typeof l.data=="string")for(let u of o)u(l.data)},r.onclose=()=>{let l=s;if(s=!1,l)for(let u of i)u()},r.onerror=()=>{s||n(new Error(`hayao-net: could not connect to ${t}`))}})}var Qe=class{frames=new Map;contiguous=new Map;addPlayer(e){this.frames.has(e)||(this.frames.set(e,new Map),this.contiguous.set(e,-1))}removePlayer(e){this.frames.delete(e),this.contiguous.delete(e)}players(){return[...this.frames.keys()]}set(e,n,r){let o=this.frames.get(e);if(!o||o.has(n))return!1;o.set(n,[...r].sort());let i=this.contiguous.get(e)??-1;for(;o.has(i+1);)i++;return this.contiguous.set(e,i),!0}has(e,n){return this.frames.get(e)?.has(n)??!1}get(e,n){return this.frames.get(e)?.get(n)}latestAt(e,n){let r=this.frames.get(e);if(!r)return[];for(let o=n;o>=0;o--){let i=r.get(o);if(i)return i}return[]}contiguousThrough(e){return this.contiguous.get(e)??-1}confirmedFrame(){let e=1/0;for(let n of this.contiguous.values())e=Math.min(e,n);return e===1/0?-1:e}clearFrom(e,n){let r=this.frames.get(e);if(!r)return;for(let i of r.keys())i>=n&&r.delete(i);let o=this.contiguous.get(e)??-1;o>=n&&(o=n-1),this.contiguous.set(e,o)}prune(e){for(let n of this.frames.values())for(let r of n.keys())r<e&&n.delete(r)}};var Ie=class{world;localPlayer;config;startFrame;transport;buffer=new Qe;roster=[];mergedLog=[];localHashes=new Map;pendingRemoteHashes=[];sentThrough;stallCount=0;desynced=!1;afterStepListeners=[];unsubscribe;onDesync;onStall;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.config={...Xe,...e.config,mode:"lockstep"},this.startFrame=e.startFrame??0,this.onDesync=e.onDesync,this.onStall=e.onStall;for(let n of e.players)if(this.roster.push({player:n,from:this.startFrame,until:1/0}),this.buffer.addPlayer(n),this.startFrame===0||n===this.localPlayer)for(let r=this.startFrame;r<this.startFrame+this.config.inputDelay;r++)this.buffer.set(n,r,[]);this.sentThrough=this.startFrame+this.config.inputDelay-1,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}activePlayers(e){return this.roster.filter(n=>n.from<=e&&e<n.until).map(n=>n.player)}addPlayer(e,n){if(!this.roster.some(r=>r.player===e&&r.until===1/0)){this.roster.push({player:e,from:n,until:1/0}),this.buffer.addPlayer(e);for(let r=n;r<n+this.config.inputDelay;r++)this.buffer.set(e,r,[])}}removePlayer(e,n){let r=this.roster.find(o=>o.player===e&&o.until===1/0);r&&(r.until=n),this.buffer.clearFrom(e,n)}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.activePlayers(this.world.frame))e=Math.min(e,this.buffer.contiguousThrough(n));return e===1/0?-1:e}get stalls(){return this.stallCount}tick(e=[]){if(this.desynced)return 0;let n=this.world.frame;this.scheduleLocal(e);let r=this.activePlayers(n);for(let s of r)if(!this.buffer.has(s,n))return this.stallCount++,this.onStall?.(s,n),0;let o=new Map;for(let s of r)o.set(s,this.buffer.get(s,n));let i=yt(r,o);return this.world.step(i),this.mergedLog.push(i),this.afterStep(this.world.frame),1}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let s=0;s<o&&this.tick(n)!==0;s++)r++;let i=0;for(;i++<8&&this.world.frame<this.remoteFrameEstimate()&&this.tick(n)===1;)r++;return r}inputLog(){return{frames:this.mergedLog.map(e=>e.slice())}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}onAfterStep(e){return this.afterStepListeners.push(e),()=>{this.afterStepListeners=this.afterStepListeners.filter(n=>n!==e)}}scheduleLocal(e){let n=this.world.frame+this.config.inputDelay;if(this.sentThrough>=n)return;for(;this.sentThrough<n;)this.sentThrough++,this.buffer.set(this.localPlayer,this.sentThrough,e);let r=Math.max(this.startFrame,n-this.config.redundancy+1),o=[];for(let i=r;i<=n;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(pe({t:"input",player:this.localPlayer,from:r,frames:o})))}afterStep(e){if(e%this.config.hashInterval===0){let n=this.world.hash();this.localHashes.set(e,n),this.transport.send(de(pe({t:"hash",player:this.localPlayer,frame:e,hash:n}))),this.checkPendingHashes()}if(e%64===0){this.buffer.prune(e-128);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}for(let n of this.afterStepListeners)n(e)}receive(e){let n=$e(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer)for(let r=0;r<n.frames.length;r++)this.buffer.set(n.player,n.from+r,n.frames[r]);else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.checkPendingHashes())}checkPendingHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.world.frame-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:this.startFrame}))}this.pendingRemoteHashes=e}remoteFrameEstimate(){let e=-1;for(let n of this.roster)n.player===this.localPlayer||n.until!==1/0||(e=Math.max(e,this.buffer.contiguousThrough(n.player)-this.config.inputDelay));return e}};var nn=class{world;localPlayer;config;transport;players;buffer=new Qe;attach;onDesync;onRollbackOverflow;ring;usedInputs=new Map;earliestBad=1/0;rollbackCount=0;resimulatedFrames=0;localHashes=new Map;dropped=new Map;pendingRemoteHashes=[];hashedThrough=-1;desynced=!1;overflowed=!1;unsubscribe;constructor(e){this.world=e.world,this.transport=e.transport,this.localPlayer=e.localPlayer,this.players=[...e.players],this.config={...Xe,mode:"rollback",inputDelay:0,...e.config},this.attach=e.attach,this.onDesync=e.onDesync,this.onRollbackOverflow=e.onRollbackOverflow,this.ring=new Array(this.config.maxRollback+1).fill(null);for(let n of this.players)this.buffer.addPlayer(n);this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get frame(){return this.world.frame}get confirmedFrame(){let e=1/0;for(let n of this.players){let r=this.dropped.get(n),o=this.buffer.contiguousThrough(n);r!==void 0&&o>=r-1&&(o=1/0),e=Math.min(e,o)}return e===1/0?-1:e}lastKnownFrame(e){return this.buffer.contiguousThrough(e)}removePlayer(e,n){if(!(e===this.localPlayer||this.dropped.has(e))){this.dropped.set(e,n),this.buffer.clearFrom(e,n);for(let r=n;r<this.world.frame;r++){let o=this.usedInputs.get(r)?.get(e);o!==void 0&&o!=="[]"&&(this.earliestBad=Math.min(this.earliestBad,r))}this.settleHashes()}}get stats(){return{rollbacks:this.rollbackCount,resimulatedFrames:this.resimulatedFrames}}tick(e=[]){if(this.desynced||this.overflowed)return 0;let n=this.world.frame;return n-(this.confirmedFrame+1)>=this.config.maxRollback||(this.publishLocal(n,e),!this.resolveCorrections())?0:(this.storeSnapshot(n),this.stepFrame(n),this.settleHashes(),n%64===0&&this.pruneOld(n),1)}advance(e,n=[]){let r=0,o=this.world.clock.advance(e);for(let i=0;i<o&&this.tick(n)!==0;i++)r++;return r}inputLog(){let e=[],n=this.confirmedFrame;for(let r=0;r<=n;r++){let o=new Map;for(let i of this.players)o.set(i,this.buffer.get(i,r)??[]);e.push(yt(this.players,o))}return{frames:e}}dispose(){this.unsubscribe()}deliver(e){this.receive(e)}publishLocal(e,n){if(!this.buffer.set(this.localPlayer,e,n))return;let r=Math.max(0,e-this.config.redundancy+1),o=[];for(let i=r;i<=e;i++)o.push(this.buffer.get(this.localPlayer,i)??[]);this.transport.send(de(pe({t:"input",player:this.localPlayer,from:r,frames:o})))}inputsFor(e){let n=new Map;for(let r of this.players){let o=this.dropped.get(r);o!==void 0&&e>=o?n.set(r,[]):n.set(r,this.buffer.get(r,e)??this.buffer.latestAt(r,e))}return n}stepFrame(e){let n=this.inputsFor(e),r=new Map;for(let o of this.players)r.set(o,JSON.stringify(n.get(o)));this.usedInputs.set(e,r),this.world.step(yt(this.players,n))}resolveCorrections(){if(this.earliestBad===1/0)return!0;let e=this.world.frame,n=this.earliestBad;this.earliestBad=1/0;let r=this.ring[n%this.ring.length];if(!r||r.frame!==n)return this.overflowed=!0,this.onRollbackOverflow?.(n),!1;this.rollbackCount++,this.world.restore(r.snap),this.attach?.(this.world);for(let o=n;o<e;o++)this.storeSnapshot(o),this.stepFrame(o),this.resimulatedFrames++;return!0}storeSnapshot(e){this.ring[e%this.ring.length]={frame:e,snap:this.world.snapshot()}}receive(e){let n=$e(e);if(n)if(n.t==="input"&&n.player!==this.localPlayer){let r=this.dropped.get(n.player);for(let o=0;o<n.frames.length;o++){let i=n.from+o;if(!(r!==void 0&&i>=r)&&this.buffer.set(n.player,i,n.frames[o])&&i<this.world.frame){let s=this.usedInputs.get(i)?.get(n.player),a=JSON.stringify([...n.frames[o]].sort());s!==void 0&&s!==a&&(this.earliestBad=Math.min(this.earliestBad,i))}}this.settleHashes()}else n.t==="hash"&&n.player!==this.localPlayer&&(this.pendingRemoteHashes.push({player:n.player,frame:n.frame,hash:n.hash}),this.compareHashes())}settleHashes(){let e=Math.min(this.confirmedFrame+1,this.world.frame,this.earliestBad===1/0?1/0:this.earliestBad),n=this.config.hashInterval,r=(Math.floor(this.hashedThrough/n)+1)*n;for(;r<=e;r+=n){let o=this.ring[r%this.ring.length];if(!o||o.frame!==r)continue;let i=Rt(o.snap);this.localHashes.set(r,i),this.hashedThrough=r,this.transport.send(de(pe({t:"hash",player:this.localPlayer,frame:r,hash:i})))}this.compareHashes()}compareHashes(){let e=[];for(let n of this.pendingRemoteHashes){let r=this.localHashes.get(n.frame);if(r===void 0){n.frame>this.hashedThrough-512&&e.push(n);continue}r!==n.hash&&!this.desynced&&(this.desynced=!0,this.onDesync?.({frame:n.frame,player:n.player,localHash:r,remoteHash:n.hash,log:this.inputLog(),startFrame:0}))}this.pendingRemoteHashes=e}pruneOld(e){this.buffer.prune(e-128);for(let n of this.usedInputs.keys())n<e-128&&this.usedInputs.delete(n);for(let n of this.localHashes.keys())n<e-512&&this.localHashes.delete(n)}};function rl(){return globalThis.crypto.randomUUID()}function qo(t,e,n,r,o,i,s,a,l){return t==="rollback"?new nn({world:e,transport:n,localPlayer:r,players:o,config:s,attach:a,onDesync:l.onDesync}):new Ie({world:e,transport:n,localPlayer:r,players:o,startFrame:i,config:s,onDesync:l.onDesync})}function jo(t,e,n,r,o){return{world:t,session:e,localPlayer:n,players:r,advance:(i,s=[])=>e.advance(i,s),dispose:()=>{e.dispose(),o?.()}}}var An=class{localPlayer="p1";seed;config;transport;makeWorld;maxPlayers;joinMargin;attach;callbacks;players=["p1"];uidToPlayer=new Map;nextPlayerIndex=2;started=!1;game=null;pendingSnapshots=[];unsubscribe;constructor(e){this.transport=e.transport,this.makeWorld=e.makeWorld,this.seed=e.seed??1,this.config={...Xe,...e.config},this.maxPlayers=e.maxPlayers??4,this.joinMargin=e.joinMargin??30,this.attach=e.attach,this.callbacks=e,this.unsubscribe=this.transport.onMessage(n=>this.receive(n))}get roster(){return[...this.players]}get isStarted(){return this.started}start(){if(this.game)return this.game;this.started=!0;let e=this.makeWorld(this.seed),n=qo(this.config.mode,e,this.transport,this.localPlayer,this.players,0,this.config,this.attach,this.callbacks);return n instanceof Ie&&n.onAfterStep(r=>this.serviceSnapshots(r,e)),this.transport.send(de(pe({t:"start",players:[...this.players]}))),this.game=jo(e,n,this.localPlayer,this.players,()=>this.unsubscribe()),this.game}dropPlayer(e){let n=this.game?.session;if(!n)return;let r=n instanceof Ie?Math.max(n.frame,n.confirmedFrame+1):n.lastKnownFrame(e)+1;this.transport.send(de(pe({t:"leave",player:e,atFrame:r}))),n.removePlayer(e,r),this.players=this.players.filter(o=>o!==e),this.callbacks.onPlayerLeave?.(e,r)}dispose(){this.unsubscribe(),this.game?.dispose()}receive(e){let n=$e(e);if(n){if(n.t==="hello")this.handleHello(n);else if(n.t==="bye"){let r=this.uidToPlayer.get(n.uid);r&&this.started?this.dropPlayer(r):r&&(this.players=this.players.filter(o=>o!==r),this.uidToPlayer.delete(n.uid))}}}handleHello(e){if(this.uidToPlayer.has(e.uid))return;if(this.players.length>=this.maxPlayers){this.transport.send(de(pe({t:"deny",to:e.uid,reason:"room full"})));return}if(this.started&&this.config.mode==="rollback"){this.transport.send(de(pe({t:"deny",to:e.uid,reason:"rollback rooms cannot be joined mid-game"})));return}let n=`p${this.nextPlayerIndex++}`;if(this.uidToPlayer.set(e.uid,n),this.players.push(n),!this.started){this.transport.send(de(pe({t:"welcome",to:e.uid,player:n,players:[...this.players],seed:this.seed,config:this.config,startFrame:0}))),this.callbacks.onPlayerJoin?.(n,0);return}let r=this.game.session,o=r.frame+this.joinMargin;this.transport.send(de(pe({t:"join",player:n,atFrame:o}))),r.addPlayer(n,o),this.pendingSnapshots.push({uid:e.uid,player:n,atFrame:o}),this.callbacks.onPlayerJoin?.(n,o)}serviceSnapshots(e,n){if(this.pendingSnapshots.length===0)return;let r=this.pendingSnapshots.filter(i=>i.atFrame===e);if(r.length===0)return;this.pendingSnapshots=this.pendingSnapshots.filter(i=>i.atFrame!==e);let o=n.snapshot();for(let i of r){let s=this.pendingSnapshots.filter(l=>l.player!==i.player),a=new Set(s.map(l=>l.player));this.transport.send(de(pe({t:"welcome",to:i.uid,player:i.player,players:this.players.filter(l=>!a.has(l)),seed:this.seed,config:this.config,startFrame:e,snapshot:o,joins:s.map(l=>({player:l.player,atFrame:l.atFrame}))})))}}};function Ho(t){let e=rl(),n=t.transport;return new Promise((r,o)=>{let i=null,s=!1,a=null,l=[],u=[],c=()=>{if(!i||!s)return;m();let d=a??i.players,p=t.makeWorld(i.seed);i.snapshot&&(p.restore(i.snapshot),t.attach?.(p));let h=qo(i.config.mode,p,n,i.player,d,i.startFrame,i.config,t.attach,t);if(i.joins&&h instanceof Ie)for(let k of i.joins)h.addPlayer(k.player,k.atFrame);for(let k of u)k.t==="join"&&h instanceof Ie&&h.addPlayer(k.player,k.atFrame),k.t==="leave"&&h.removePlayer(k.player,k.atFrame);let g=n.onMessage(k=>{let w=$e(k);w&&(w.t==="join"&&h instanceof Ie?(h.addPlayer(w.player,w.atFrame),t.onPlayerJoin?.(w.player,w.atFrame)):w.t==="leave"&&(h.removePlayer(w.player,w.atFrame),t.onPlayerLeave?.(w.player,w.atFrame)))}),x=jo(p,h,i.player,d,()=>{g(),n.send(de(pe({t:"bye",uid:e})))});for(let k of l)h.deliver(k);r(x)},m=n.onMessage(d=>{let p=$e(d);if(p)switch(p.t){case"welcome":p.to===e&&(i=p,(p.snapshot||p.startFrame>0)&&(s=!0),c());break;case"deny":p.to===e&&(m(),o(new Error(`hayao-net: join denied \u2014 ${p.reason}`)));break;case"start":s=!0,a=p.players,c();break;case"join":case"leave":u.push(p);break;case"input":case"hash":l.push(d);break}});n.send(de(pe({t:"hello",uid:e,name:t.name})))})}function _o(t){return new An(t)}function Tf(t,e,n){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=n.renderer==="canvas"?new He({width:r,height:o,background:i}):new je({width:r,height:o,background:i});e.style.position=e.style.position||"relative",s.mount?.(e),Ut(e);let a=new Ve(t.inputMap??{},document),l=g=>Re(t,g),u=null,c=null,m=0,d=!1,p=g=>x=>{!d&&u&&(u.advance(x-g,a.currentActions())>0&&a.clearPressed(),s.draw(u.world.render())),m=requestAnimationFrame(p(x))},h=g=>{u=g,n.onStatus?.(`playing as ${g.localPlayer} (${g.players.length} players)`),m=requestAnimationFrame(p(performance.now()))};return n.role==="host"?(c=_o({transport:n.transport,makeWorld:l,seed:n.seed??t.seed??1,config:n.config,maxPlayers:n.maxPlayers,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:(g,x)=>{n.onStatus?.(`${g} joined`),n.onPlayerJoin?.(g,x)},onPlayerLeave:n.onPlayerLeave}),n.onStatus?.("hosting \u2014 waiting for players")):(n.onStatus?.("joining\u2026"),Ho({transport:n.transport,makeWorld:l,attach:n.attach,onDesync:n.onDesync,onPlayerJoin:n.onPlayerJoin,onPlayerLeave:n.onPlayerLeave}).then(h).catch(g=>n.onStatus?.(g.message))),{start(){c&&!u&&h(c.start())},get game(){return u},get localPlayer(){return u?.localPlayer??(n.role==="host"?"p1":null)},get roster(){return c?.roster??u?.players??[]},input:a,stop(){d=!0,cancelAnimationFrame(m),u?.dispose(),c?.dispose(),a.dispose(),s.dispose?.()}}}function ol(t,e,n,r){let o=t.palette?.bg??"#141821",i=t.palette?.fg??(Xt(o)>.4?"#14171f":"#f4efe3"),s=t.title??e.title,a={a:1,b:0,c:0,d:1,e:0,f:0};return[{kind:"rect",x:0,y:0,w:n,h:r,fill:o,transform:a,z:0},{kind:"text",text:s,x:n/2,y:r/2,size:Math.round(r*.06),align:"center",weight:700,fill:i,transform:a,z:1},{kind:"text",text:"loading\u2026",x:n/2,y:r/2+r*.08,size:Math.round(r*.03),align:"center",fill:i,opacity:.7,transform:a,z:1}]}function Jo(t,e,n={}){let r=t.width??1280,o=t.height??720,i=t.background??"#f3ecdb",s=Re(t,n.world),a=n.renderer==="canvas"?new He({width:r,height:o,background:i}):new je({width:r,height:o,background:i});e.style.position=e.style.position||"relative",a.mount?.(e),Ut(e);let l=new Ve(t.inputMap??{},document),u=new $t(a),c=mo(),m=()=>{Be.start();let y=Ne.get();Be.setVolumes(y),window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",m)};window.addEventListener("pointerdown",m),window.addEventListener("keydown",m);let d=()=>a.draw(s.render()),p=()=>{s=Re(t,n.world),d()},h=n.shell===!1?null:new Yt({title:t.title,onRestart:n.onRestart??p,onPause:y=>n.onPause?.(y)}),g=t.splash===!1?null:t.splash??{},x=g&&!c?ol(g,t,r,o):null,k=!c,w=[],P,$=new Promise(y=>P=y),v=performance.now(),f=0,M=performance.now(),S=()=>{if(k){k=!1,M=performance.now(),d(),P();for(let y of w.splice(0))y()}},D=y=>{if(k){x&&a.draw(x),f=requestAnimationFrame(D);return}let T=y-M;if(M=y,!c&&!h?.isPaused&&!n.isHeld?.()){u.sample(s.input);let E=l.currentActions(),O=s.advance(T,E);O>0&&(l.clearPressed(),n.onAdvance?.(s,O,E))}d(),f=requestAnimationFrame(D)};if(f=requestAnimationFrame(D),k){let y=g?.minDurationMs??0,T=t.preload?Promise.resolve().then(()=>t.preload(s)):Promise.resolve(),E=new Promise(O=>setTimeout(O,Math.max(0,y-(performance.now()-v))));Promise.all([T,E]).then(S).catch(O=>{console.error("hayao: preload failed \u2014",O),S()})}else P();let C={get world(){return s},renderer:a,input:l,pointer:u,canvas:a.element,toDesign:(y,T)=>a.toDesign?.(y,T)??{x:y,y:T},ready:$,onReady(y){k?w.push(y):y()},stop(){cancelAnimationFrame(f),l.dispose(),u.dispose(),h?.dispose(),a.dispose?.()},restart:p};return c&&po({get world(){return s},stepOnce:(y=[])=>{s.step(y),d()},renderSVG:()=>Ot(s.render(),r,o,i),setPaused:()=>{}}),C}var il=0;function sl(t,e){return`${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"game"}-${e.replace(/[:.]/g,"-").toLowerCase()}-${(il++).toString(36)}`}var Ze=class{frames=[];axesLog=[];lastAxes=new Map;knobEvents=[];screenEvents=[];wallClockMarks=[];annotations=[];init;startedAt;id;buildRef;constructor(e){this.init=e,this.startedAt=e.startedAt??new Date().toISOString(),this.id=e.id??sl(e.game,this.startedAt),this.buildRef=e.buildRef??"unknown"}get frame(){return this.frames.length}get liveInputFrames(){return this.frames}get liveAxesLog(){return this.axesLog}get liveKnobEvents(){return this.knobEvents}step(e,n){if(n)for(let[r,o]of n)this.lastAxes.get(r)!==o&&(this.axesLog.push([this.frames.length,r,o]),this.lastAxes.set(r,o));this.frames.push([...e].sort())}knob(e,n){this.knobEvents.push({frame:this.frames.length,key:e,value:n}),this.screen("knob",`${e}=${n}`)}screen(e,n){this.screenEvents.push({frame:this.frames.length,kind:e,...n!==void 0?{detail:n}:{}})}mark(e,n){this.wallClockMarks.push({frame:this.frames.length,t:n,kind:e})}annotate(e,n){this.annotations.push({frame:this.frames.length,tag:e,...n!==void 0?{note:n}:{}})}truncate(e){if(!(e>=this.frames.length)){this.frames.length=e,this.axesLog=this.axesLog.filter(([n])=>n<e),this.lastAxes.clear();for(let[n,r,o]of this.axesLog)n<e&&this.lastAxes.set(r,o);this.knobEvents=this.knobEvents.filter(n=>n.frame<=e),this.screenEvents=this.screenEvents.filter(n=>n.frame<=e),this.wallClockMarks=this.wallClockMarks.filter(n=>n.frame<=e),this.annotations=this.annotations.filter(n=>n.frame<=e)}}toSession(e){return{id:this.id,game:this.init.game,startedAt:this.startedAt,buildRef:this.buildRef,seed:this.init.seed,variant:this.init.variant??{name:"dev",kind:"dev"},tuningValues:{...this.init.tuningValues},...this.init.startSnapshot?{startSnapshot:this.init.startSnapshot}:{},knobEvents:this.knobEvents.slice(),inputLog:{frames:this.frames.map(n=>n.slice())},axesLog:this.axesLog.slice(),screenEvents:this.screenEvents.slice(),wallClockMarks:this.wallClockMarks.slice(),annotations:this.annotations.slice(),endReason:e}}};var xt=class{constructor(e=30,n=240){this.stride=e;this.cap=n}stride;cap;entries=[];push(e,n){e%this.stride===0&&(this.entries.push({frame:e,snap:n.snapshot()}),this.entries.length>this.cap&&this.entries.shift())}nearest(e){let n=null;for(let r of this.entries)r.frame<=e&&(!n||r.frame>n.frame)&&(n=r);return n}get minFrame(){return this.entries.length>0?this.entries[0].frame:0}truncate(e){this.entries=this.entries.filter(n=>n.frame<=e)}clear(){this.entries=[]}};function Ln(t,e,n,r,o,i,s){let a=Math.max(n.minFrame,Math.min(s,r.length)),l=n.nearest(a);if(!l)return null;t.restore(structuredClone(l.snap)),e.attach?.(t),t.input.axes.clear();let u=new Map,c=0;for(;c<o.length&&o[c][0]<l.frame;){let[,d,p]=o[c++];u.set(d,p)}for(let[d,p]of u)t.input.axes.set(d,p);let m=i.findIndex(d=>d.frame>=l.frame);m<0&&(m=i.length);for(let d=l.frame;d<a;d++){for(;m<i.length&&i[m].frame===d;){let p=i[m++],h=t.snapshot();h.tuning={...h.tuning,[p.key]:p.value},t.restore(h),e.attach?.(t)}for(;c<o.length&&o[c][0]===d;){let[,p,h]=o[c++];t.input.axes.set(p,h)}t.step(r[d])}return a}function al(){if(typeof location>"u")return{};let t=new URLSearchParams(location.search),e={},n=t.get("seed");n!==null&&Number.isFinite(Number(n))&&(e.seed=Number(n));let r=t.get("tuning");if(r)try{let o=JSON.parse(atob(r));o&&typeof o=="object"&&(e.tuning=o)}catch{}return e}function Uf(t,e,n={}){let r=al(),o=typeof location<"u"?new URLSearchParams(location.search).get("variant"):null,i=o?n.variants?.[o]:void 0,s=i?.patch?i.patch(t):t,a=n.variant??(i&&o?{name:o,kind:"module"}:{name:"dev",kind:"dev"}),l=n.world?.seed??r.seed??s.seed??1,u={...i?.tuning,...r.tuning,...n.world?.tuning},c=Zt(s.tuning,u),m={...c},d=typeof performance<"u"?performance.now():0,p=new Ze({game:s.title,seed:l,tuningValues:c,variant:a}),h=!1,g=(I,z)=>{let B=JSON.stringify(I);if(z&&typeof navigator<"u"&&navigator.sendBeacon){navigator.sendBeacon("/__studio/session",new Blob([B],{type:"application/json"}));return}fetch("/__studio/session",{method:"POST",headers:{"content-type":"application/json"},body:B}).catch(()=>{})},x=(I="quit",z=!1)=>{w||p.frame===0&&h||(g(p.toSession(I),z),h=!0)},k=typeof location<"u"?new URLSearchParams(location.search).get("session"):null,w=null,P=null,$=new xt,v=!1,f=null,M=()=>{if(f===null||f>=p.frame){f=null;return}p.truncate(f),$.truncate(f),p.screen("scrub",`forked@${f}`),f=null},S=Jo(s,e,{...n,world:{seed:l,tuning:u},isHeld:()=>v||(n.isHeld?.()??!1),onAdvance:(I,z,B)=>{for(let W=0;W<z;W++)p.step(B,I.input.axes),$.push(p.frame,I);n.onAdvance?.(I,z,B)},onPause:I=>{p.screen(I?"pause":"resume"),n.onPause?.(I)},onRestart:()=>{x("restart"),p=new Ze({game:s.title,seed:l,tuningValues:{...m},variant:a,buildRef:p.buildRef}),(n.onRestart??S.restart)()}}),D=n.hot?.data.hayaoSnap;if(D){delete n.hot.data.hayaoSnap;let I=structuredClone(D);I.tuning={...m},S.world.restore(I),s.attach?.(S.world),p=new Ze({game:s.title,seed:l,tuningValues:{...m},variant:a,startSnapshot:I}),p.screen("hot-swap")}n.hot?.dispose(I=>{I.hayaoSnap=S.world.snapshot(),X("hot-swap")}),$.push(0,S.world);async function C(I,z){let B=await fetch(`/__studio/session/${encodeURIComponent(I)}`);if(!B.ok)return;let W=await B.json();v=!0;let V=S.world,re=Re(s,{seed:W.seed,tuning:W.tuningValues});V.restore(W.startSnapshot?structuredClone(W.startSnapshot):re.snapshot()),s.attach?.(V),V.input.axes.clear();let oe=W.inputLog.frames,te=Math.max(30,Math.ceil(oe.length/220/30)*30);$=new xt(te),$.push(0,V);let ie=0,ue=0;for(let ge=0;ge<oe.length;ge++){for(;ue<W.knobEvents.length&&W.knobEvents[ue].frame===ge;){let Ae=W.knobEvents[ue++],ke=V.snapshot();ke.tuning={...ke.tuning,[Ae.key]:Ae.value},V.restore(ke),s.attach?.(V)}for(;ie<W.axesLog.length&&W.axesLog[ie][0]===ge;){let[,Ae,ke]=W.axesLog[ie++];V.input.axes.set(Ae,ke)}V.step(oe[ge]),$.push(ge+1,V)}w={session:W,pos:oe.length},ae.scrub(Number.isFinite(z)?z:0)}function y(){if(!w||P!==null)return;let I=w.session,z=performance.now();P=window.setInterval(()=>{if(!w)return;let B=performance.now(),W=Math.min(120,Math.floor((B-z)/(1e3/60)));if(W<=0)return;z=B;let V=S.world;for(let re=0;re<W;re++){let oe=w.pos;if(oe>=I.inputLog.frames.length){T();return}for(let te of I.knobEvents)if(te.frame===oe){let ie=V.snapshot();ie.tuning={...ie.tuning,[te.key]:te.value},V.restore(ie),s.attach?.(V)}for(let[te,ie,ue]of I.axesLog)te===oe&&V.input.axes.set(ie,ue);V.step(I.inputLog.frames[oe]),w.pos=oe+1}},1e3/60)}function T(){P!==null&&(window.clearInterval(P),P=null)}k&&C(k,Number(new URLSearchParams(location.search).get("at")??"NaN")),fetch("/__studio/state").then(I=>I.ok?I.json():null).then(I=>{I?.buildRef&&(p.buildRef=I.buildRef)}).catch(()=>{}),kn((I,z)=>p.screen(I==="show"?"overlay-show":"overlay-hide",z));let E=()=>typeof performance<"u"?performance.now()-d:0,O=()=>p.mark(document.hidden?"visibility-hidden":"visibility-visible",E()),F=()=>p.mark("blur",E()),J=()=>p.mark("focus",E()),Y=()=>x("quit",!0);document.addEventListener("visibilitychange",O),window.addEventListener("blur",F),window.addEventListener("focus",J),window.addEventListener("pagehide",Y);let ne=window.setInterval(()=>x("idle"),1e4),X=I=>{T(),x(I,I==="hot-swap"),document.removeEventListener("visibilitychange",O),window.removeEventListener("blur",F),window.removeEventListener("focus",J),window.removeEventListener("pagehide",Y),window.clearInterval(ne),kn(null),S.stop()},ae={...S,get world(){return S.world},setKnob(I,z){if(w)return;M(),m[I]=z;let B=S.world.snapshot();B.tuning={...m},S.world.restore(B),s.attach?.(S.world),p.knob(I,z)},knobValues:()=>({...m}),tuningSpec:()=>s.tuning,variants:()=>Object.fromEntries(Object.entries(n.variants??{}).map(([I,z])=>[I,z.label])),activeVariant:()=>({...a}),title:()=>s.title,annotate:(I,z)=>{w||p.annotate(I,z)},setFrozen(I){if(w){I?T():y();return}if(I===v)return;if(I){v=!0;return}let z=f!==null;if(M(),z){let B=S.world.snapshot().tuning??{};for(let W of Object.keys(m))W in B&&(m[W]=B[W])}v=!1},frozen:()=>w?P===null:v,scrub(I){if(w){T();let B=w.session,W=Ln(S.world,s,$,B.inputLog.frames,B.axesLog,B.knobEvents,I);return W!==null&&(w.pos=W),W}v=!0;let z=Ln(S.world,s,$,p.liveInputFrames,p.liveAxesLog,p.liveKnobEvents,I);return z!==null&&(f=z<p.frame?z:null),z},timeline:()=>w?{min:$.minFrame,frame:w.pos,max:w.session.inputLog.frames.length}:{min:$.minFrame,frame:f??p.frame,max:p.frame},mode:()=>w?"replay":"live",flush:(I="idle")=>x(I),session:()=>p.toSession("idle"),stop:()=>X("navigate")};return window.__studio=ae,ae}var Yf="0.3.0";export{ga as ALBUM,Yl as AMBIENT_PRESETS,Qn as AmbientField,Ft as AnimationPlayer,gn as AudioBus,Tr as BitmapText,Vo as BroadcastChannelTransport,It as Camera2D,_n as CameraController,He as Canvas2DRenderer,uo as CinematicPlayer,Ct as Clock,un as DEFAULT_INPUT_MAP,rt as DEFAULT_PLATFORMER,Xe as DEFAULT_SESSION_CONFIG,or as DEFAULT_TILE_CHARS,Yi as DUSK,Yn as EASINGS,ee as Edge,Tt as EventBus,tu as FLOAT_PRESETS,Cr as FONT_5,er as FloatingText,ko as Fsm,aa as GENRES,Sd as GENRE_PROFILES,xr as HeadlessRenderer,le as IDENTITY,A as INSTRUMENTS,Qe as InputBuffer,nr as InputRecorder,Nt as InputState,L as KENTO,Ve as KeyboardSource,Dn as LocalStorageAdapter,Ie as LockstepSession,Go as LoopbackHub,$n as LoopbackTransport,Mo as LootTable,Ki as MEADOW,Pn as MemoryStorage,en as NEIGHBORS_4,Rn as NEIGHBORS_8,tf as NET_PROTOCOL_VERSION,j as Node,j as Node2D,Un as NodePool,Eo as NullStorage,xu as PAD_NEUTRAL,Ic as PALETTES,Rc as PANEL_PRESETS,Xi as PAPER,Kl as PARTICLE_PRESETS,Jn as ParallaxLayer,Xn as Particles,So as PhaseClock,st as PixelBuffer,Nn as PlayerInput,$t as PointerSource,Io as RingBuffer,ce as Rng,nn as RollbackSession,An as RoomHost,be as SAMPLE_RATE,Lo as SAVE_FORMAT_VERSION,Hr as SCALES,Ao as SaveManager,Mn as ScreenTransition,Ze as SessionRecorder,Zn as Shaker,Yt as Shell,tt as Signal,xt as SnapshotRing,Lt as SpatialHash,Pt as Sprite,je as SvgRenderer,se as TAU,H as TILE,Dt as Text,Sr as TextureSprite,Et as Timer,Do as UndoStack,Yf as VERSION,Je as WangFrame,Qt as World,tl as abilitiesOf,Fu as addBody,Vu as addDistanceJoint,qu as addRevoluteJoint,jd as addTransition,Nd as albumTrack,sh as analyzePlaytest,$u as applyImpulse,Ur as applyReverb,on as applyTransform,cu as asciiEntities,zp as assertAudio,Xd as assertDeterministic,Pp as assertRamp,Qd as assertSnapshotStable,Ud as assertSolvable,ja as astar,hh as astarGrid,Be as audio,sm as autotile4,am as autotileToCommands,Dh as availableUpgrades,eo as bandBalance,qa as bfs,Gc as blobPath,cn as bodyAABB,Vi as bodyContains,md as cadenceResolves,Pa as cameraIssues,yr as canvasGradient,Ue as cellFloat,bs as cellHash,pm as cellInt,Sp as changeFrames,ka as checkDeterministic,ad as chordChanges,Ce as chordNotes,K as clamp,Bt as clientToDesign,lr as collide,qe as commandsToSVGInner,jh as composeCampaign,et as composeTransform,rf as connectWebSocket,ph as connectedComponents,lm as contourToCommands,ht as contrastRatio,lp as createPlanBot,vu as createPlatformerState,Eu as createRigidWorld,Wr as createStereo,Re as createWorld,Zr as crestFactorDb,Su as dashJumpDistance,ci as datan,ll as datan2,yn as dbfs,Q as dcos,Jc as decode2bit,_c as decodeBits,$e as decodeMessage,Uc as decodeRLE,Fo as defaultStorage,Zp as defineGame,Nh as defineLevel,xl as deg2rad,ln as deserializeNode,Oe as dexp,he as dexp2,Z as dhypot,Ps as diatonicChord,zh as diffLevels,Qs as distanceGain,Bn as dlog,St as dlog10,rn as dlog2,Pe as dpow,sp as drive,cc as dropShadow,_ as dsin,vd as duckGain,de as encodeMessage,Kc as encodeRLE,Em as encodeWav,_s as estimateTempo,gd as evalCurve,Xs as featureDistance,dt as features,Ca as feedbackIssues,qs as fft,Kh as findSoftlocks,wp as firstFrame,Po as floodFill,Qr as fluxEnvelope,Ma as forgivenessIssues,Fr as fractalNoise,nt as frameActions,eh as gameInputMap,gm as generateCave,Cm as generateDungeon,zo as generateLevels,el as generateLevelsReport,Pd as genre,xe as getBody,ju as getJoint,uc as glow,dp as graceWindowIssues,Ac as gradient,fr as gradientDef,fs as gridAt,om as gridFromRows,Fe as gridSet,mm as gridToTilemap,wi as groundAt,qn as hashString,Rt as hashValue,Zi as hexToHsl,Kt as hideScreen,ep as hold,_o as hostRoom,Qi as hsl,Nc as hsv,Pu as inVisionCone,Rh as initDirector,Cp as inputDensity,po as installCapture,Gn as invLerp,sn as invertTransform,mo as isCaptureMode,km as isGround,Mp as isMonotonic,Ho as joinRoom,Si as jumpAirtime,Mi as jumpDistance,ku as jumpHeight,Fa as keyMentions,rr as keysToActions,Up as knob,xd as layerGains,gp as layoutIssues,ss as layoutText,Ee as lerp,Vl as lerpDamp,Gh as levelFromSeed,$h as levelIssues,Ah as levelReachable,En as levelToTilemap,Di as lineOfSight,ac as linearGradient,cd as lintSong,Tp as longestLull,Da as lookAheadIssues,mt as magnitudeSpectrum,lt as makeGrid,ql as makeReach,Mt as makeTransform,pu as mapHeight,du as mapWidth,ds as marchingSquaresCases,hs as marchingSquaresContours,Dr as mask4,im as mask8,pd as matchReport,at as measureLine,tm as measureText,yt as mergePlayerFrames,Rs as midiToFreq,Om as midiToName,yp as missingControlHints,Ec as mix,ts as mixLinear,Br as mixMono,At as moveRect,$c as mutateColor,pe as netMessage,Tc as nineSlice,Gr as normalize,me as noteToMidi,Hs as onsetDensity,pn as openVoicing,wh as packVarints,Zs as panFromOffset,ws as panGains,is as parseRich,$o as parseSnapshot,fh as passableFromTilemap,ks as peak,Xr as peakAmp,To as pickEntry,jr as pitchToFreq,rs as pixelsToCommands,Lh as platformerReachable,tn as playerAction,Qh as playerIds,Zh as playerInput,nc as pointQuery,Ph as pollDirector,Au as polygonBox,Ke as progression,Fn as progressionPuzzle,Jh as proveCompletable,Uh as proveFullCompletion,rp as pump,vl as rad2deg,lc as radialGradient,Aa as rampIssues,$a as rampStats,rc as rayCastRigid,Pi as raycastTiles,nl as reachableRegions,dh as reconstructPath,vp as recordTimeline,We as rectBlocked,wl as rectContains,kl as rectsOverlap,Ge as registerNode,Bc as regularPolygon,Xt as relLuminance,yl as remap,Nu as removeBody,Hu as removeJoint,Lp as renderAudioFilmstrip,Ep as renderFilmstrip,Yr as renderSong,Vt as renderSound,Ot as renderToSVGString,co as replay,vo as replaySession,Hn as resetNodeIds,Zt as resolveTuning,Qu as rigidStep,vh as rleDecode,xh as rleEncode,ct as rms,$r as roomCenter,qt as rootless,Jo as runBrowser,Tf as runBrowserNet,hp as runFeelGates,th as runHeadless,Uf as runStudio,Ra as salienceIssues,wr as sampleGradient,dn as scaleMidis,_r as scalePitchClasses,gs as scatter,hm as scatterCells,Md as scoreTrack,_d as screenRect,Sa as scriptToFrames,np as scriptedPlaythrough,Ln as scrubTo,Ua as serializeSnapshot,kp as series,Ut as setOverlayHost,kn as setScreenObserver,Ne as settings,br as shadowDef,gr as shapeBBox,ho as shapeBox,io as showScreen,Fm as signalHash,ns as smoothClosedPath,Vc as smoothOpenPath,Vn as smoothstep,zr as softClip,Or as softClipInPlace,Ir as solidNeighbours,Ye as solve,cr as solveJoint,Ls as songBeats,bn as songDuration,Wt as sortCommands,yd as spatialMix,js as spectralCentroid,yi as spring,xi as springStep,Oc as star,up as steer2D,wu as stepPlatformer,Im as stereoDuration,Dm as stereoFrames,ea as stereoWidth,Qa as subSeed,pp as telegraphIssues,Nr as terrainHeight,wm as terrainSlice,Ia as textBox,ls as textToCommands,fe as tileAt,mu as tileAtPoint,Xa as tileCenter,ir as tilemapFromAscii,lo as toggleFullscreen,Gm as transpose,as as typewriterCount,kh as unpackVarints,dl as vadd,Yh as validateWorld,ys as valueNoise,bl as vdist,fl as vdot,ml as vec2,fi as vlen,gl as vnorm,ut as voiceLead,hl as vscale,pl as vsub,tp as wait,ve as wakeBody,ms as wangTile,vi as weatherEnvelope,Co as weightedIndex,uh as weightedPick,Hd as wipeStep,Fc as withAlpha,Me as worldPoints,Gs as zcr};