@codexo/exojs 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +1 -3
- package/dist/esm/particles/emitters/ParticleOptions.d.ts +11 -0
- package/dist/esm/particles/emitters/ParticleOptions.js +11 -0
- package/dist/esm/particles/emitters/ParticleOptions.js.map +1 -1
- package/dist/esm/rendering/Container.d.ts +1 -1
- package/dist/esm/rendering/Container.js +5 -2
- package/dist/esm/rendering/Container.js.map +1 -1
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js +7 -0
- package/dist/esm/rendering/webgl2/WebGl2ShaderRuntime.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js +66 -43
- package/dist/esm/rendering/webgpu/WebGpuParticleRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.d.ts +2 -6
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js +160 -93
- package/dist/esm/rendering/webgpu/WebGpuPrimitiveRenderer.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js +50 -39
- package/dist/esm/rendering/webgpu/WebGpuRenderManager.js.map +1 -1
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js +75 -32
- package/dist/esm/rendering/webgpu/WebGpuSpriteRenderer.js.map +1 -1
- package/dist/exo.d.ts +14 -7
- package/dist/exo.esm.js +374 -209
- package/dist/exo.esm.js.map +1 -1
- package/dist/exo.esm.min.js +1 -1
- package/dist/exo.esm.min.js.map +1 -1
- package/dist/exo.global.js +374 -209
- package/dist/exo.global.js.map +1 -1
- package/dist/exo.global.min.js +1 -1
- package/dist/exo.global.min.js.map +1 -1
- package/package.json +3 -4
package/dist/exo.esm.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let t=null;class e{constructor(t=0,e=0){this._width=t,this._height=e}get width(){return this._width}set width(t){this._width=t}get height(){return this._height}set height(t){this._height=t}set(t,e=t){return this._width=t,this._height=e,this}add(t,e=t){return this._width+=t,this._height+=e,this}subtract(t,e=t){return this._width-=t,this._height-=e,this}scale(t,e=t){return this._width*=t,this._height*=e,this}divide(t,e=t){return this._width/=t,this._height/=e,this}copy(t){return this._width=t.width,this._height=t.height,this}clone(){return new e(this._width,this._height)}equals({width:t,height:e}={}){return!(void 0!==t&&this.width!==t||void 0!==e&&this.height!==e)}destroy(){}static get temp(){return null===t&&(t=new e),t}}e.zero=new e(0,0);class i{constructor(t=Date.now()){this._state=new Uint32Array(624),this._iteration=0,this._seed=0,this._value=0,this.setSeed(t),this._twist()}get seed(){return this._seed}get value(){return this._value}get iteration(){return this._iteration}setSeed(t){return this._seed=t,this.reset(),this}reset(){this._state[0]=this._seed;for(let t=1;t<624;t++){const e=this._state[t-1]^this._state[t-1]>>>30;this._state[t]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+t,this._state[t]|=0}return this._iteration=0,this}next(t=0,e=1){return this._iteration>=624&&this._twist(),this._value=this._state[this._iteration++],this._value^=this._value>>>11,this._value^=this._value<<7&2636928640,this._value^=this._value<<15&4022730752,this._value^=this._value>>>18,this._value=(this._value>>>0)/4294967295*(e-t)+t,this._value}destroy(){}_twist(){const t=this._state;for(let e=0;e<227;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e+397]^i>>>1^2567483615*(1&i)}for(let e=227;e<623;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e-227]^i>>>1^2567483615*(1&i)}const e=2147483648&t[623]|2147483647&t[0];t[623]=t[396]^e>>>1^2567483615*(1&e),this._iteration=0,this._value=0}}let s=null;class r{constructor(t=0,e=r.milliseconds){this._milliseconds=t*e}get milliseconds(){return this._milliseconds}set milliseconds(t){this._milliseconds=t}get seconds(){return this._milliseconds/r.seconds}set seconds(t){this._milliseconds=t*r.seconds}get minutes(){return this._milliseconds/r.minutes}set minutes(t){this._milliseconds=t*r.minutes}get hours(){return this._milliseconds/r.hours}set hours(t){this._milliseconds=t*r.hours}set(t=0,e=r.milliseconds){return this._milliseconds=t*e,this}setMilliseconds(t){return this.milliseconds=t,this}setSeconds(t){return this.seconds=t,this}setMinutes(t){return this.minutes=t,this}setHours(t){return this.hours=t,this}equals({milliseconds:t,seconds:e,minutes:i,hours:s}={}){return!(void 0!==t&&this.milliseconds!==t||void 0!==e&&this.seconds!==e||void 0!==i&&this.minutes!==i||void 0!==s&&this.hours!==s)}greaterThan(t){return this._milliseconds>t.milliseconds}lessThan(t){return this._milliseconds<t.milliseconds}clone(){return new r(this._milliseconds)}copy(t){return this._milliseconds=t.milliseconds,this}add(t=0,e=r.milliseconds){return this._milliseconds+=t*e,this}addTime(t){return this._milliseconds+=t.milliseconds,this}subtract(t=0,e=r.milliseconds){return this._milliseconds-=t*e,this}subtractTime(t){return this._milliseconds-=t.milliseconds,this}destroy(){}static get temp(){return null===s&&(s=new r),s}}r.milliseconds=1,r.seconds=1e3,r.minutes=6e4,r.hours=36e5,r.zero=new r(0),r.oneMillisecond=new r(1),r.oneSecond=new r(1,r.seconds),r.oneMinute=new r(1,r.minutes),r.oneHour=new r(1,r.hours);const n=/^no$/;let o=null,a=null,h=null,l=null,u=null;const c=()=>"undefined"!=typeof document,d=()=>"undefined"!=typeof window,_=()=>{if(!c())throw new Error("Canvas operations require a document context.");return null===a&&(a=document.createElement("canvas")),a},p=(t,e)=>(null===l&&(l=new i),l).next(t,e),f=()=>{},m=t=>{t.preventDefault(),t.stopImmediatePropagation()},g="undefined"!=typeof AudioContext,y="undefined"!=typeof indexedDB,x=d()&&"ontouchstart"in window,w="undefined"!=typeof PointerEvent,v=()=>{if(null!==u)return u;if(!d())return u=!1,u;let t=!1;try{window.addEventListener("test",f,{get passive(){return t=!0,!1}}),window.removeEventListener("test",f)}catch(t){}return u=t,u},b=()=>performance.now(),T=t=>new r(t,r.milliseconds),S=t=>new r(t,r.seconds),C=t=>new r(t,r.minutes),M=t=>new r(t,r.hours),P=new ArrayBuffer(0),B=(t,e,i)=>{if(e<t.length&&i>0){const s=e+i>t.length?t.length-e:i,r=t.length-s;for(let i=e;i<r;i++)t[i]=t[i+s];t.length=r}return t},E=(...t)=>t.some(t=>(()=>{if(!c())throw new Error("Audio codec detection requires a document context.");return null===o&&(o=document.createElement("audio")),o})().canPlayType(t).replace(n,"")),R=t=>{const i=t;return t instanceof HTMLImageElement?e.temp.set(t.naturalWidth,t.naturalHeight):t instanceof HTMLVideoElement?e.temp.set(t.videoWidth,t.videoHeight):t instanceof SVGElement?e.temp.copy(t.getBoundingClientRect()):"number"==typeof i.displayWidth&&"number"==typeof i.displayHeight?e.temp.set(i.displayWidth,i.displayHeight):"number"==typeof i.width&&"number"==typeof i.height?e.temp.set(i.width,i.height):e.zero},A=t=>null===t?e.zero:R(t),k=t=>{const{width:e,height:i}=R(t),s=_();return s.width=e,s.height=i,(()=>{if(null===h){const t=_().getContext("2d");if(!t)throw new Error("Could not create a 2D canvas context.");h=t}return h})().drawImage(t,0,0,e,i),s.toDataURL()};class L{constructor(t=r.zero,e=!1){this._elapsedTime=new r(0),this._running=!1,this._startTime=t.clone(),e&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const t=b();this._elapsedTime.add(t-this._startTime.milliseconds),this._startTime.milliseconds=t}return this._elapsedTime}get elapsedMilliseconds(){return this.elapsedTime.milliseconds}get elapsedSeconds(){return this.elapsedTime.seconds}get elapsedMinutes(){return this.elapsedTime.minutes}get elapsedHours(){return this.elapsedTime.hours}start(){return this._running||(this._running=!0,this._startTime.milliseconds=b()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(b()-this._startTime.milliseconds)),this}reset(){return this._running=!1,this._elapsedTime.setMilliseconds(0),this}restart(){return this.reset(),this.start(),this}destroy(){this._startTime.destroy(),this._elapsedTime.destroy()}}class F{constructor(){this._bindings=new Array}get bindings(){return this._bindings}has(t,e){return this._bindings.some(i=>i.handler===t&&i.context===e)}add(t,e){return this.has(t,e)||this._bindings.push({handler:t,context:e}),this}once(t,e){const i=(...s)=>{this.remove(i,e),t.call(e,...s)};return this.add(i,e),this}remove(t,e){const i=this._bindings.findIndex(i=>i.handler===t&&i.context===e);return-1!==i&&B(this._bindings,i,1),this}clearByContext(t){const e=this._bindings.filter(e=>e.context===t);for(const t of e)B(this._bindings,this._bindings.indexOf(t),1);return this}clear(){return this._bindings.length=0,this}dispatch(...t){if(this._bindings.length)for(const e of this._bindings)if(!1===e.handler.call(e.context,...t))break;return this}destroy(){this.clear()}}const D=2*Math.PI,I=Math.PI/180,N=180/Math.PI,U=t=>{const e=t%360;return e<0?e+360:e},V=t=>t*I,O=t=>t*N,G=(t,e,i)=>Math.min(i,Math.max(e,t)),z=t=>t&&(t<0?-1:1),W=(t,e,i)=>(1-i)*t+i*e,q=t=>0!==t&&!(t&t-1),H=(t,e,i)=>t>=Math.min(e,i)&&t<=Math.max(e,i),X=(t,e,i,s)=>{const r=t-i,n=e-s;return Math.sqrt(r*r+n*n)},j=(t,e,i,s,r,n,o,a,h=[],l=20)=>{h.push(t,e);for(let u=1,c=0,d=0,_=0,p=0,f=0,m=0;u<=l;u++)c=u/l,d=1-c,_=d*d,p=_*d,f=c*c,m=f*c,h.push(p*t+3*_*c*i+3*d*f*r+m*o,p*e+3*_*c*s+3*d*f*n+m*a);return h},Y=(t,e,i,s,r,n,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push(W(W(t,i,l),W(i,r,l),l),W(W(e,s,l),W(s,n,l),l))}return o},$=(t,e)=>{const i=e.dot(t.x,t.y);return i<0?-1:i>t.lengthSq?1:0};class K{constructor(t=0,e=0,i=0,s=1){this._rgba=null,this._array=null,this._r=255&t,this._g=255&e,this._b=255&i,this._a=G(s,0,1)}get r(){return this._r}set r(t){this._r=255&t,this._rgba=null}get g(){return this._g}set g(t){this._g=255&t,this._rgba=null}get b(){return this._b}set b(t){this._b=255&t,this._rgba=null}get a(){return this._a}set a(t){this._a=G(t,0,1),this._rgba=null}get red(){return this.r}set red(t){this.r=t}get green(){return this.g}set green(t){this.g=t}get blue(){return this.b}set blue(t){this.b=t}get alpha(){return this.a}set alpha(t){this.a=t}set(t=this._r,e=this._g,i=this._b,s=this._a){return this._r=255&t,this._g=255&e,this._b=255&i,this._a=G(s,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new K(this._r,this._g,this._b,this._a)}equals({r:t,g:e,b:i,a:s}={}){return!(void 0!==t&&this.r!==t||void 0!==e&&this.g!==e||void 0!==i&&this.b!==i||void 0!==s&&this.a!==s)}toArray(t=!1){return this._array||(this._array=new Float32Array(4)),t?(this._array[0]=this._r/255,this._array[1]=this._g/255,this._array[2]=this._b/255,this._array[3]=this._a):(this._array[0]=this._r,this._array[1]=this._g,this._array[2]=this._b,this._array[3]=this._a),this._array}toString(t=!0){return`${t?"#":""}${((1<<24)+(this._r<<16)+(this._g<<8)+this._b).toString(16).substr(1)}`}toRgba(){return null===this._rgba&&(this._rgba=this._a&&(255*this._a<<24)+(this._b<<16)+(this._g<<8)+this._r>>>0),this._rgba}destroy(){this._array&&(this._array=null)}}var Q,Z,J,tt,et,it,st;K.aliceBlue=new K(240,248,255,1),K.antiqueWhite=new K(250,235,215,1),K.aqua=new K(0,255,255,1),K.aquamarine=new K(127,255,212,1),K.azure=new K(240,255,255,1),K.beige=new K(245,245,220,1),K.bisque=new K(255,228,196,1),K.black=new K(0,0,0,1),K.blanchedAlmond=new K(255,235,205,1),K.blue=new K(0,0,255,1),K.blueViolet=new K(138,43,226,1),K.brown=new K(165,42,42,1),K.burlyWood=new K(222,184,135,1),K.cadetBlue=new K(95,158,160,1),K.chartreuse=new K(127,255,0,1),K.chocolate=new K(210,105,30,1),K.coral=new K(255,127,80,1),K.cornflowerBlue=new K(100,149,237,1),K.cornsilk=new K(255,248,220,1),K.crimson=new K(220,20,60,1),K.cyan=new K(0,255,255,1),K.darkBlue=new K(0,0,139,1),K.darkCyan=new K(0,139,139,1),K.darkGoldenrod=new K(184,134,11,1),K.darkGray=new K(169,169,169,1),K.darkGreen=new K(0,100,0,1),K.darkKhaki=new K(189,183,107,1),K.darkMagenta=new K(139,0,139,1),K.darkOliveGreen=new K(85,107,47,1),K.darkOrange=new K(255,140,0,1),K.darkOrchid=new K(153,50,204,1),K.darkRed=new K(139,0,0,1),K.darkSalmon=new K(233,150,122,1),K.darkSeaGreen=new K(143,188,139,1),K.darkSlateBlue=new K(72,61,139,1),K.darkSlateGray=new K(47,79,79,1),K.darkTurquoise=new K(0,206,209,1),K.darkViolet=new K(148,0,211,1),K.deepPink=new K(255,20,147,1),K.deepSkyBlue=new K(0,191,255,1),K.dimGray=new K(105,105,105,1),K.dodgerBlue=new K(30,144,255,1),K.firebrick=new K(178,34,34,1),K.floralWhite=new K(255,250,240,1),K.forestGreen=new K(34,139,34,1),K.fuchsia=new K(255,0,255,1),K.gainsboro=new K(220,220,220,1),K.ghostWhite=new K(248,248,255,1),K.gold=new K(255,215,0,1),K.goldenrod=new K(218,165,32,1),K.gray=new K(128,128,128,1),K.green=new K(0,128,0,1),K.greenYellow=new K(173,255,47,1),K.honeydew=new K(240,255,240,1),K.hotPink=new K(255,105,180,1),K.indianRed=new K(205,92,92,1),K.indigo=new K(75,0,130,1),K.ivory=new K(255,255,240,1),K.khaki=new K(240,230,140,1),K.lavender=new K(230,230,250,1),K.lavenderBlush=new K(255,240,245,1),K.lawnGreen=new K(124,252,0,1),K.lemonChiffon=new K(255,250,205,1),K.lightBlue=new K(173,216,230,1),K.lightCoral=new K(240,128,128,1),K.lightCyan=new K(224,255,255,1),K.lightGoldenrodYellow=new K(250,250,210,1),K.lightGray=new K(211,211,211,1),K.lightGreen=new K(144,238,144,1),K.lightPink=new K(255,182,193,1),K.lightSalmon=new K(255,160,122,1),K.lightSeaGreen=new K(32,178,170,1),K.lightSkyBlue=new K(135,206,250,1),K.lightSlateGray=new K(119,136,153,1),K.lightSteelBlue=new K(176,196,222,1),K.lightYellow=new K(255,255,224,1),K.lime=new K(0,255,0,1),K.limeGreen=new K(50,205,50,1),K.linen=new K(250,240,230,1),K.magenta=new K(255,0,255,1),K.maroon=new K(128,0,0,1),K.mediumAquamarine=new K(102,205,170,1),K.mediumBlue=new K(0,0,205,1),K.mediumOrchid=new K(186,85,211,1),K.mediumPurple=new K(147,112,219,1),K.mediumSeaGreen=new K(60,179,113,1),K.mediumSlateBlue=new K(123,104,238,1),K.mediumSpringGreen=new K(0,250,154,1),K.mediumTurquoise=new K(72,209,204,1),K.mediumVioletRed=new K(199,21,133,1),K.midnightBlue=new K(25,25,112,1),K.mintCream=new K(245,255,250,1),K.mistyRose=new K(255,228,225,1),K.moccasin=new K(255,228,181,1),K.navajoWhite=new K(255,222,173,1),K.navy=new K(0,0,128,1),K.oldLace=new K(253,245,230,1),K.olive=new K(128,128,0,1),K.oliveDrab=new K(107,142,35,1),K.orange=new K(255,165,0,1),K.orangeRed=new K(255,69,0,1),K.orchid=new K(218,112,214,1),K.paleGoldenrod=new K(238,232,170,1),K.paleGreen=new K(152,251,152,1),K.paleTurquoise=new K(175,238,238,1),K.paleVioletRed=new K(219,112,147,1),K.papayaWhip=new K(255,239,213,1),K.peachPuff=new K(255,218,185,1),K.peru=new K(205,133,63,1),K.pink=new K(255,192,203,1),K.plum=new K(221,160,221,1),K.powderBlue=new K(176,224,230,1),K.purple=new K(128,0,128,1),K.red=new K(255,0,0,1),K.rosyBrown=new K(188,143,143,1),K.royalBlue=new K(65,105,225,1),K.saddleBrown=new K(139,69,19,1),K.salmon=new K(250,128,114,1),K.sandyBrown=new K(244,164,96,1),K.seaGreen=new K(46,139,87,1),K.seaShell=new K(255,245,238,1),K.sienna=new K(160,82,45,1),K.silver=new K(192,192,192,1),K.skyBlue=new K(135,206,235,1),K.slateBlue=new K(106,90,205,1),K.slateGray=new K(112,128,144,1),K.snow=new K(255,250,250,1),K.springGreen=new K(0,255,127,1),K.steelBlue=new K(70,130,180,1),K.tan=new K(210,180,140,1),K.teal=new K(0,128,128,1),K.thistle=new K(216,191,216,1),K.tomato=new K(255,99,71,1),K.transparentBlack=new K(0,0,0,0),K.transparentWhite=new K(255,255,255,0),K.turquoise=new K(64,224,208,1),K.violet=new K(238,130,238,1),K.wheat=new K(245,222,179,1),K.white=new K(255,255,255,1),K.whiteSmoke=new K(245,245,245,1),K.yellow=new K(255,255,0,1),K.yellowGreen=new K(154,205,50,1),function(t){t[t.Normal=0]="Normal",t[t.Additive=1]="Additive",t[t.Subtract=2]="Subtract",t[t.Multiply=3]="Multiply",t[t.Screen=4]="Screen"}(Q||(Q={})),function(t){t[t.Nearest=9728]="Nearest",t[t.Linear=9729]="Linear",t[t.NearestMipmapNearest=9984]="NearestMipmapNearest",t[t.LinearMipmapNearest=9985]="LinearMipmapNearest",t[t.NearestMipmapLinear=9986]="NearestMipmapLinear",t[t.LinearMipmapLinear=9987]="LinearMipmapLinear"}(Z||(Z={})),function(t){t[t.Repeat=10497]="Repeat",t[t.ClampToEdge=33071]="ClampToEdge",t[t.MirroredRepeat=33648]="MirroredRepeat"}(J||(J={})),function(t){t[t.Points=0]="Points",t[t.Lines=1]="Lines",t[t.LineLoop=2]="LineLoop",t[t.LineStrip=3]="LineStrip",t[t.Triangles=4]="Triangles",t[t.TriangleStrip=5]="TriangleStrip",t[t.TriangleFan=6]="TriangleFan"}(tt||(tt={})),function(t){t[t.ArrayBuffer=34962]="ArrayBuffer",t[t.ElementArrayBuffer=34963]="ElementArrayBuffer",t[t.CopyReadBuffer=36662]="CopyReadBuffer",t[t.CopyWriteBuffer=36663]="CopyWriteBuffer",t[t.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",t[t.UniformBuffer=35345]="UniformBuffer",t[t.PixelPackBuffer=35051]="PixelPackBuffer",t[t.PixelUnpackBuffer=35052]="PixelUnpackBuffer"}(et||(et={})),function(t){t[t.StaticDraw=35044]="StaticDraw",t[t.StaticRead=35045]="StaticRead",t[t.StaticCopy=35046]="StaticCopy",t[t.DynamicDraw=35048]="DynamicDraw",t[t.DynamicRead=35049]="DynamicRead",t[t.DynamicCopy=35050]="DynamicCopy",t[t.StreamDraw=35040]="StreamDraw",t[t.StreamRead=35041]="StreamRead",t[t.StreamCopy=35042]="StreamCopy"}(it||(it={})),function(t){t[t.Int=5124]="Int",t[t.IntVec2=35667]="IntVec2",t[t.IntVec3=35668]="IntVec3",t[t.IntVec4=35669]="IntVec4",t[t.Float=5126]="Float",t[t.FloatVec2=35664]="FloatVec2",t[t.FloatVec3=35665]="FloatVec3",t[t.FloatVec4=35666]="FloatVec4",t[t.Bool=35670]="Bool",t[t.BoolVec2=35671]="BoolVec2",t[t.BoolVec3=35672]="BoolVec3",t[t.BoolVec4=35673]="BoolVec4",t[t.FloatMat2=35674]="FloatMat2",t[t.FloatMat3=35675]="FloatMat3",t[t.FloatMat4=35676]="FloatMat4",t[t.Sampler2D=35678]="Sampler2D"}(st||(st={}));class rt{get direction(){return Math.atan2(this.x,this.y)}set direction(t){const e=this.length;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get angle(){return this.direction}set angle(t){this.direction=t}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(t){const e=this.direction;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(t){this.length=Math.sqrt(t)}get magnitude(){return this.length}set magnitude(t){this.length=t}set(t,e=t){return this.x=t,this.y=e,this}equals({x:t,y:e}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e)}add(t,e=t){return this.x+=t,this.y+=e,this}subtract(t,e=t){return this.x-=t,this.y-=e,this}multiply(t,e=t){return this.x*=t,this.y*=e,this}divide(t,e=t){return 0!==t&&0!==e&&(this.x/=t,this.y/=e),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(t){return this.set(this.x*t.a+this.y*t.b+t.x,this.x*t.c+this.y*t.d+t.y)}transformInverse(t){const e=1/(t.a*t.d+t.c*-t.b);return this.set(this.x*t.d*e+this.y*-t.c*e+(t.y*t.c-t.x*t.d)*e,this.y*t.a*e+this.x*-t.b*e+(-t.y*t.a+t.x*t.b)*e)}perp(){return this.set(-this.y,this.x)}rperp(){return this.set(this.y,-this.x)}min(){return Math.min(this.x,this.y)}max(){return Math.max(this.x,this.y)}dot(t,e){return this.x*t+this.y*e}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){return X(this.x,this.y,t.x,t.y)}}class nt extends rt{constructor(t,e=0,i=0){super(),this._x=e,this._y=i,this._callback=t}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._callback?.())}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._callback?.())}set direction(t){const e=this.length;this.set(Math.cos(t)*e,Math.sin(t)*e)}set length(t){const e=this.direction;this.set(Math.cos(e)*t,Math.sin(e)*t)}set(t=this._x,e=this._y){return this._x===t&&this._y===e||(this._x=t,this._y=e,this._callback?.()),this}add(t,e=t){return this.set(this._x+t,this._y+e)}subtract(t,e=t){return this.set(this._x-t,this._y-e)}scale(t,e=t){return this.set(this._x*t,this._y*e)}divide(t,e=t){return 0!==t&&0!==e?this.set(this._x/t,this._y/e):this}clone(){return new nt(this._callback,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){}}let ot=null;class at{constructor(t=1,e=0,i=0,s=0,r=1,n=0,o=0,a=0,h=1){this._array=null,this.a=t,this.b=e,this.x=i,this.c=s,this.d=r,this.y=n,this.e=o,this.f=a,this.z=h}set(t=this.a,e=this.b,i=this.x,s=this.c,r=this.d,n=this.y,o=this.e,a=this.f,h=this.z){return this.a=t,this.b=e,this.x=i,this.c=s,this.d=r,this.y=n,this.e=o,this.f=a,this.z=h,this}copy(t){return this.a=t.a,this.b=t.b,this.x=t.x,this.c=t.c,this.d=t.d,this.y=t.y,this.e=t.e,this.f=t.f,this.z=t.z,this}clone(){return new at(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:t,b:e,x:i,c:s,d:r,y:n,e:o,f:a,z:h}={}){return!(void 0!==t&&this.a!==t||void 0!==e&&this.b!==e||void 0!==i&&this.x!==i||void 0!==s&&this.c!==s||void 0!==r&&this.d!==r||void 0!==n&&this.y!==n||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(t){return this.set(this.a*t.a+this.c*t.b+this.e*t.x,this.b*t.a+this.d*t.b+this.f*t.x,this.x*t.a+this.y*t.b+this.z*t.x,this.a*t.c+this.c*t.d+this.e*t.y,this.b*t.c+this.d*t.d+this.f*t.y,this.x*t.c+this.y*t.d+this.z*t.y,this.a*t.e+this.c*t.f+this.e*t.z,this.b*t.e+this.d*t.f+this.f*t.z,this.x*t.e+this.y*t.f+this.z*t.z)}getInverse(t=this){const e=this.a*(this.z*this.d-this.y*this.f)-this.b*(this.z*this.c-this.y*this.e)+this.x*(this.f*this.c-this.d*this.e);return 0===e?t.copy(at.identity):t.set((this.z*this.d-this.y*this.f)/e,(this.z*this.c-this.y*this.e)/-e,(this.f*this.c-this.d*this.e)/e,(this.z*this.b-this.x*this.f)/-e,(this.z*this.a-this.x*this.e)/e,(this.f*this.a-this.b*this.e)/-e,(this.y*this.b-this.x*this.d)/e,(this.y*this.a-this.x*this.c)/-e,(this.d*this.a-this.b*this.c)/e)}translate(t,e=t){return this.combine(at.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const s=V(t),r=Math.cos(s),n=Math.sin(s);return this.combine(at.temp.set(r,-n,e*(1-r)+i*n,n,r,i*(1-r)-e*n,0,0,1))}scale(t,e=t,i=0,s=i){return this.combine(at.temp.set(t,0,i*(1-t),0,e,s*(1-e),0,0,1))}toArray(t=!1){const e=this._array||(this._array=new Float32Array(9));return t?(e[0]=this.a,e[1]=this.b,e[2]=this.x,e[3]=this.c,e[4]=this.d,e[5]=this.y,e[6]=this.e,e[7]=this.f,e[8]=this.z):(e[0]=this.a,e[1]=this.c,e[2]=this.e,e[3]=this.b,e[4]=this.d,e[5]=this.f,e[6]=this.x,e[7]=this.y,e[8]=this.z),e}destroy(){this._array&&(this._array=null)}static get temp(){return null===ot&&(ot=new at),ot}}at.identity=new at(1,0,0,0,1,0,0,0,1);class ht{get value(){return this._value}constructor(...t){this._value=0,t.length&&this.push(...t)}push(...t){for(const e of t)this._value|=e;return this}pop(t){const e=this.has(t);return this.remove(t),e}remove(...t){for(const e of t)this._value&=~e;return this}has(...t){return t.some(t=>0!==(this._value&t))}clear(){return this._value=0,this}destroy(){this.clear()}}var lt;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse"}(lt||(lt={}));class ut{constructor(){this.flags=new ht(lt.Transform),this._transform=new at,this._position=new nt(this._setPositionDirty.bind(this),0,0),this._scale=new nt(this._setScalingDirty.bind(this),1,1),this._origin=new nt(this._setOriginDirty.bind(this),0,0),this._rotation=0,this._sin=0,this._cos=1}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get origin(){return this._origin}set origin(t){this._origin.copy(t)}setPosition(t,e=t){return this._position.set(t,e),this}setRotation(t){const e=U(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}setScale(t,e=t){return this._scale.set(t,e),this}setOrigin(t,e=t){return this._origin.set(t,e),this}move(t,e){return this.setPosition(this.x+t,this.y+e)}rotate(t){return this.setRotation(this._rotation+t)}getTransform(){return this.flags.has(lt.Transform)&&(this.updateTransform(),this.flags.remove(lt.Transform)),this._transform}updateTransform(){if(this.flags.has(lt.Rotation)){const t=V(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}if(this.flags.has(lt.Rotation|lt.Scaling)){const{x:t,y:e}=this._scale;this._transform.a=t*this._cos,this._transform.b=e*this._sin,this._transform.c=-t*this._sin,this._transform.d=e*this._cos}if(this._rotation){const{x:t,y:e}=this._origin;this._transform.x=t*-this._transform.a-e*this._transform.b+this._position.x,this._transform.y=t*-this._transform.c-e*this._transform.d+this._position.y}else this._transform.x=this._origin.x*-this._scale.x+this._position.x,this._transform.y=this._origin.y*-this._scale.y+this._position.y;return this}destroy(){this._transform.destroy(),this._position.destroy(),this._scale.destroy(),this._origin.destroy(),this.flags.destroy()}_setPositionDirty(){this.flags.push(lt.Translation)}_setRotationDirty(){this.flags.push(lt.Rotation)}_setScalingDirty(){this.flags.push(lt.Scaling)}_setOriginDirty(){this.flags.push(lt.Origin)}}let ct=null;class dt{constructor(t=0,e=t){this.min=t,this.max=e}set(t,e){return this.min=t,this.max=e,this}copy(t){return this.set(t.min,t.max)}clone(){return new dt(this.min,this.max)}containsInterval(t){return t.min>this.min&&t.max<this.max}includes(t){return t<=this.max&&t>=this.min}overlaps(t){return!(this.min>t.max||t.min>this.max)}getOverlap(t){return this.max<t.max?this.max-t.min:t.max-this.min}destroy(){}static get temp(){return null===ct&&(ct=new dt),ct}}dt.zero=new dt(0,0);const _t=1e-10,pt=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),ft=({x:t,y:e,rx:i,ry:s})=>{if(i<=0||s<=0)return[];const r=pt(i,s),n=2*Math.PI/r,o=[];for(let a=0;a<r;a++){const r=a*n;o.push({x:t+Math.cos(r)*i,y:e+Math.sin(r)*s})}return o},mt=({x:t,y:e},{x:i,y:s},{x:r,y:n})=>t<=Math.max(i,r)+_t&&t>=Math.min(i,r)-_t&&e<=Math.max(s,n)+_t&&e>=Math.min(s,n)-_t,gt=({x:t,y:e},{x:i,y:s},{x:r,y:n})=>{const o=(s-e)*(r-i)-(i-t)*(n-s);return Math.abs(o)<=_t?0:o>0?1:2},yt=(t,e,i,s)=>{const r=gt(t,e,i),n=gt(t,e,s),o=gt(i,s,t),a=gt(i,s,e);return r!==n&&o!==a||(!(0!==r||!mt(i,t,e))||(!(0!==n||!mt(s,t,e))||(!(0!==o||!mt(t,i,s))||!(0!==a||!mt(e,i,s)))))},xt=({x:t,y:e},i)=>{const s=i.length;if(s<3)return!1;let r=!1;for(let n=0,o=s-1;n<s;o=n++){const s=i[o],a=i[n];a.y>e!=s.y>e&&t<(s.x-a.x)*((e-a.y)/(s.y-a.y))+a.x&&(r=!r)}return r},wt=(t,e)=>{if(0===t.length||0===e.length)return!1;for(let i=0;i<t.length;i++){const s=t[i],r=t[(i+1)%t.length];for(let t=0;t<e.length;t++){const i=e[t],n=e[(t+1)%e.length];if(yt(s,r,i,n))return!0}}return xt(t[0],e)||xt(e[0],t)},vt=({x:t,y:e},{x:i,y:s},{x:r,y:n},o=.1)=>{const a=X(t,e,i,s),h=X(t,e,r,n),l=X(i,s,r,n);return a+h>=l-o&&a+h<=l+o},bt=(t,e,i,s)=>{const r=(e.x-t.x)*(s.y-i.y)-(s.x-i.x)*(e.y-t.y);if(Math.abs(r)<=_t)return!1;const n=((s.x-i.x)*(t.y-i.y)-(s.y-i.y)*(t.x-i.x))/r,o=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/r;return n>=0&&n<=1&&o>=0&&o<=1},Tt=(t,e)=>Math.sqrt(t*t+e*e),St=(t,e,i,s)=>{const r=i*t+s*e;const n=(o=t)*o+(a=e)*a;var o,a;return r<0?-1:r>n?1:0},Ct=(t,e)=>{const i=t.getNormals(),s=e.getNormals(),r=new dt,n=new dt;for(const s of i)if(t.project(s,r),e.project(s,n),!r.overlaps(n))return!1;for(const i of s)if(t.project(i,r),e.project(i,n),!r.overlaps(n))return!1;return!0},Mt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:s},r=0)=>X(t,e,i,s)<=r)(t,e,i),Pt=(t,e,i=.1)=>vt(t,e.fromPosition,e.toPosition,i),Bt=(t,e)=>(({x:t,y:e},{x:i,y:s,width:r,height:n})=>H(t,i,i+r)&&H(e,s,s+n))(t,e),Et=(t,e)=>(({x:t,y:e},{x:i,y:s,radius:r})=>r>0&&X(t,e,i,s)<=r)(t,e),Rt=(t,e)=>(({x:t,y:e},{x:i,y:s,rx:r,ry:n})=>{if(r<=0||n<=0)return!1;const o=(t-i)/r,a=(e-s)/n;return o*o+a*a<=1})(t,e),At=(t,e)=>((t,{points:e})=>xt(t,e))(t,e),kt=(t,e)=>bt(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),Lt=(t,e)=>{const{x:i,y:s,width:r,height:n}=e,o={x:i,y:s},a={x:i+r,y:s},h={x:i,y:s+n},l={x:i+r,y:s+n};return bt(t.fromPosition,t.toPosition,o,h)||bt(t.fromPosition,t.toPosition,a,l)||bt(t.fromPosition,t.toPosition,o,a)||bt(t.fromPosition,t.toPosition,h,l)},Ft=(t,e)=>{if(Et(t.fromPosition,e)||Et(t.toPosition,e))return!0;const{fromX:i,fromY:s,toX:r,toY:n}=t,{x:o,y:a,radius:h}=e,l=X(i,s,r,n);if(0===l)return!1;const u=((o-i)*(r-i)+(a-s)*(n-s))/(l*l),c=i+u*(r-i),d=s+u*(n-s);return!!vt({x:c,y:d},t.fromPosition,t.toPosition)&&X(c,d,o,a)<=h},Dt=(t,e)=>{const{x:i,y:s,rx:r,ry:n}=e;if(r<=0||n<=0)return!1;const o=(t.fromX-i)/r,a=(t.fromY-s)/n,h=(t.toX-i)/r-o,l=(t.toY-s)/n-a,u=h*h+l*l,c=2*(o*h+a*l),d=o*o+a*a-1;if(d<=0)return!0;if(u<=Number.EPSILON)return!1;const _=c*c-4*u*d;if(_<0)return!1;const p=Math.sqrt(_),f=(-c-p)/(2*u),m=(-c+p)/(2*u);return f>=0&&f<=1||m>=0&&m<=1},It=(t,e)=>{const{x:i,y:s,points:r}=e,n=r.length;for(let e=0;e<n;e++){const o=r[e],a=r[(e+1)%n];if(bt(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+s},{x:a.x+i,y:a.y+s}))return!0}return!1},Nt=(t,e)=>(({x:t,y:e,width:i,height:s},{x:r,y:n,width:o,height:a})=>!(r>t+i||n>e+s||t>r+o||e>n+a))(t,e),Ut=({x:t,y:e,width:i,height:s},{x:r,y:n,radius:o})=>{const a=G(r,t,t+i),h=G(n,e,e+s);return X(r,n,a,h)<=o},Vt=(t,e)=>wt((({x:t,y:e,width:i,height:s})=>[{x:t,y:e},{x:t+i,y:e},{x:t+i,y:e+s},{x:t,y:e+s}])(t),ft(e)),Ot=(t,e)=>Ct(t,e),Gt=({x:t,y:e,radius:i},{x:s,y:r,radius:n})=>X(t,e,s,r)<=i+n,zt=(t,e)=>wt((({x:t,y:e,radius:i})=>{if(i<=0)return[];const s=pt(i),r=2*Math.PI/s,n=[];for(let o=0;o<s;o++){const s=o*r;n.push({x:t+Math.cos(s)*i,y:e+Math.sin(s)*i})}return n})(t),ft(e)),Wt=(t,e,i,s,r,n,o,a,h)=>{if(-1!==St(a,h,r,n))return!1;return 1===St(s.x,s.y,t-i.x,e-i.y)&&Tt(r,n)>o},qt=(t,e,i,s,r,n,o,a,h)=>{if(1!==St(a,h,r,n))return!1;return-1===St(s.x,s.y,t-i.x,e-i.y)&&Tt(r,n)>o},Ht=(t,e,i,s,r)=>{const n=r,o=-s,a=Tt(n,o);if(0===a)return!1;const h=(t*n+e*o)/a;return h>0&&Math.abs(h)>i},Xt=({x:t,y:e,radius:i},{x:s,y:r,points:n,edges:o})=>{const a=s-t,h=r-e,l=n.length;for(let t=0;t<l;t++){const e=n[t],s=a-e.x,r=h-e.y,u=0===t?l-1:t-1,c=(t+1)%l,d=o[t];if(Wt(a,h,n[u],o[u],s,r,i,d.x,d.y))return!1;if(qt(a,h,n[c],o[c],s,r,i,d.x,d.y))return!1;if(Ht(s,r,i,d.x,d.y))return!1}return!0},jt=(t,e)=>wt(ft(t),ft(e)),Yt=(t,e)=>wt(ft(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:s})=>({x:i+t,y:s+e})))(e)),$t=(t,e)=>Ct(t,e),Kt=(t,e)=>{if(e.left>t.right||e.top>t.bottom)return null;if(t.left>e.right||t.top>e.bottom)return null;const i=t.position.clone().set(0,0),s=t.position.clone().set(0,0);return{shapeA:t,shapeB:e,overlap:0,shapeAinB:e.containsRect(t),shapeBinA:t.containsRect(e),projectionN:i,projectionV:s}},Qt=(t,e)=>{const i=e.position.clone().subtract(t.x,t.y),s=i.length,r=t.radius+e.radius-s;if(r<0)return i.destroy(),null;const n=i.clone().normalize(),o=i.multiply(r);return{shapeA:t,shapeB:e,overlap:r,shapeAinB:t.radius<=e.radius&&s<=e.radius-t.radius,shapeBinA:e.radius<=t.radius&&s<=t.radius-e.radius,projectionN:n,projectionV:o}},Zt=(t,e,i=!1)=>{const s=t.radius,r=e.width/2,n=e.height/2,o=X(t.x,t.y,e.x-r,e.y-n),a=s<=Math.min(r,n)&&o<=Math.min(r,n)-s,h=Math.max(r,n)<=s&&o<=s-Math.max(r,n);if(o>t.radius)return null;const l=t.position.clone().set(0,0),u=t.position.clone().set(0,0);return{shapeA:i?e:t,shapeB:i?t:e,overlap:s-o,shapeAinB:i?h:a,shapeBinA:i?a:h,projectionN:l,projectionV:u}},Jt=(t,e,i=!1)=>{const s=e.radius,r=t.points,n=e.x-t.x,o=e.y-t.y,a=e.position.clone().set(0,0),h=r.length;let l=!0,u=!0,c=1/0;for(let t=0;t<h;t++){const e=r[t],i=r[(t+1)%h],d=i.x-e.x,_=i.y-e.y,p=n-e.x,f=o-e.y,m=St(d,_,p,f),g=Tt(p,f);if(g>s&&(l=!1),-1===m){const i=r[0===t?h-1:t-1],l=e.x-i.x,d=e.y-i.y,_=n-i.x,m=o-i.y;if(1===St(l,d,_,m)){if(g>s)return a.destroy(),null;const t=s-g;Math.abs(t)<Math.abs(c)&&(c=t,a.set(p,f).normalize()),u=!1}}else if(1===m){const e=r[(t+2)%h],l=e.x-i.x,d=e.y-i.y,_=n-i.x,p=o-i.y,f=Tt(_,p);if(-1===St(l,d,_,p)){if(f>s)return a.destroy(),null;const t=s-f;Math.abs(t)<Math.abs(c)&&(c=t,a.set(_,p).normalize()),u=!1}}else{const t=_,e=-d,i=Tt(t,e),r=0===i?0:(p*t+f*e)/i;if(r>0&&Math.abs(r)>s)return a.destroy(),null;(r>=0||s-r<2*s)&&(u=!1);const n=s-r;Math.abs(n)<Math.abs(c)&&(c=n,a.set(t,e).normalize())}}const d=a.clone().multiply(c);return{shapeA:i?e:t,shapeB:i?t:e,overlap:c,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:d}},te=(t,e)=>{const i=t.getNormals(),s=e.getNormals(),r=(i[0]||s[0]).clone(),n=new dt,o=new dt;let a=1/0,h=!0,l=!0,u=!1,c=!1,d=0;for(const s of i){if(t.project(s,n),e.project(s,o),!n.overlaps(o))return r.destroy(),null;d=n.getOverlap(o),u=o.containsInterval(n),c=n.containsInterval(o),!u&&h&&(h=!1),!c&&l&&(l=!1),(u||c)&&(d+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),d<a&&(a=d,r.copy(s))}for(const i of s){if(t.project(i,n),e.project(i,o),!n.overlaps(o))return r.destroy(),null;d=n.getOverlap(o),u=o.containsInterval(n),c=n.containsInterval(o),!u&&h&&(h=!1),!c&&l&&(l=!1),(u||c)&&(d+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),d<a&&(a=d,r.copy(i))}const _=r.clone().multiply(a,a);return{shapeA:t,shapeB:e,overlap:a,shapeAinB:h,shapeBinA:l,projectionN:r,projectionV:_}};let ee=null;const ie=()=>{},se=new nt(ie);class re{constructor(t=0,i=t,s=0,r=s){this.collisionType=2,this._normals=null,this._normalsDirty=!1,this._position=new nt(()=>{this._normalsDirty=!0},t,i),this._size=new e(s,r)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get size(){return this._size}set size(t){this._size.copy(t),this._normalsDirty=!0}get width(){return this._size.width}set width(t){this._size.width=t,this._normalsDirty=!0}get height(){return this._size.height}set height(t){this._size.height=t,this._normalsDirty=!0}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}setPosition(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setSize(t,e){return this._size.set(t,e),this._normalsDirty=!0,this}set(t,e,i,s){return this.setPosition(t,e),this.setSize(i,s),this}copy(t){return this.position=t.position,this.size=t.size,this}clone(){return new re(this.x,this.y,this.width,this.height)}equals({x:t,y:e,width:i,height:s}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.width!==i||void 0!==s&&this.height!==s)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new nt(ie),new nt(ie),new nt(ie),new nt(ie)])),this._normalsDirty=!1),this._normals}project(t,e=new dt){const i=t.dot(this.left,this.top),s=t.dot(this.right,this.top),r=t.dot(this.right,this.bottom),n=t.dot(this.left,this.bottom);return e.set(Math.min(i,s,r,n),Math.max(i,s,r,n))}transform(t,e=this){const i=se.set(this.left,this.top).transform(t);let s=i.x,r=i.x,n=i.y,o=i.y;return i.set(this.left,this.bottom).transform(t),s=Math.min(s,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(t),s=Math.min(s,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(t),s=Math.min(s,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),e.set(s,n,r-s,o-n)}contains(t,e){return Bt(se.set(t,e),this)}containsRect(t){return H(t.left,this.left,this.right)&&H(t.right,this.left,this.right)&&H(t.top,this.top,this.bottom)&&H(t.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case 6:return t.isAlignedBox?Nt(this,t.getBounds()):Ct(this,t);case 2:return Nt(this,t);case 5:return Ot(this,t);case 3:return Ut(this,t);case 4:return Vt(this,t);case 1:return Lt(t,this);case 0:return Bt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:return t.isAlignedBox?Kt(this,t.getBounds()):te(this,t);case 2:return Kt(this,t);case 5:return te(this,t);case 3:return Zt(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(t){t[0].set(this.right-this.left,0).rperp().normalize(),t[1].set(0,this.bottom-this.top).rperp().normalize(),t[2].set(this.left-this.right,0).rperp().normalize(),t[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===ee&&(ee=new re),ee}}class ne{constructor(){this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this._rect=new re}get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(t,e){return this._minX=Math.min(this._minX,t),this._minY=Math.min(this._minY,e),this._maxX=Math.max(this._maxX,t),this._maxY=Math.max(this._maxY,e),this._dirty=!0,this}addRect(t,e){return e&&(t=t.transform(e,re.temp)),this.addCoords(t.left,t.top).addCoords(t.right,t.bottom)}getRect(){return this._dirty&&(this._rect.set(this._minX,this._minY,this._maxX-this._minX,this._maxY-this._minY),this._dirty=!1),this._rect}reset(){return this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this}destroy(){this._rect.destroy()}}class oe extends ut{constructor(){super(...arguments),this.collisionType=6,this._bounds=new ne,this._visible=!0,this._globalTransform=new at,this._localBounds=new re,this._anchor=new nt(this._updateOrigin.bind(this),0,0),this._parentNode=null,this._zIndex=0,this._childOrder=0,this._cullable=!0}get anchor(){return this._anchor}set anchor(t){this._anchor.copy(t)}get parent(){return this._parentNode}set parent(t){this._parentNode=t}get parentNode(){return this._parentNode}set parentNode(t){this._parentNode=t}get visible(){return this._visible}set visible(t){this._visible=t}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this._parentNode?.markSortDirty())}get childOrder(){return this._childOrder}get cullable(){return this._cullable}set cullable(t){this._cullable=t}get globalTransform(){return this.getGlobalTransform()}get localBounds(){return this.getLocalBounds()}get bounds(){return this.getBounds()}get isAlignedBox(){return this.rotation%90==0}setAnchor(t,e=t){return this._anchor.set(t,e),this}setChildOrder(t){return this._childOrder=t,this}setCullable(t){return this._cullable=t,this}getLocalBounds(){return this._localBounds}getBounds(){return this.updateParentTransform(),this.updateBounds(),this._bounds.getRect()}updateBounds(){return this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform()),this}updateParentTransform(){return this._parentNode&&this._parentNode.updateParentTransform(),this.updateTransform(),this}getGlobalTransform(){return this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this._globalTransform}getNormals(){return this.getBounds().getNormals()}project(t,e=new dt){return this.getBounds().project(t,e)}intersectsWith(t){if(this.isAlignedBox)return this.getBounds().intersectsWith(t);switch(t.collisionType){case 6:case 2:case 5:return Ct(this,t);case 3:return Ut(this.getBounds(),t);case 4:return Vt(this.getBounds(),t);case 1:return Lt(t,this.getBounds());case 0:return Bt(t,this.getBounds());default:return!1}}collidesWith(t){if(this.isAlignedBox)return this.getBounds().collidesWith(t);switch(t.collisionType){case 6:case 2:case 5:case 3:return te(this,t);default:return null}}contains(t,e){return this.getBounds().contains(t,e)}inView(t){return!this._cullable||t.getBounds().intersectsWith(this.getBounds())}render(t){return this}destroy(){super.destroy(),this._globalTransform.destroy(),this._localBounds.destroy(),this._bounds.destroy(),this._anchor.destroy()}_updateOrigin(){const{x:t,y:e}=this._anchor,{width:i,height:s}=this.getBounds();this.setOrigin(i*t,s*e)}}class ae extends e{constructor(t,e=0,i=0){super(e,i),this._callback=t}get width(){return this._width}set width(t){this._width!==t&&(this._width=t,this._callback())}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this._callback())}set(t=this._width,e=this._height){return this._width===t&&this._height===e||(this._width=t,this._height=e,this._callback()),this}add(t,e=t){return this.set(this._width+t,this._height+e)}subtract(t,e=t){return this.set(this._width-t,this._height-e)}scale(t,e=t){return this.set(this._width*t,this._height*e)}divide(t,e=t){return this.set(this._width/t,this._height/e)}copy(t){return this.set(t.width,t.height)}clone(){return new ae(this._callback,this._width,this._height)}}var he;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint"}(he||(he={}));class le{constructor(t,e,i,s){this._viewport=new re(0,0,1,1),this._transform=new at,this._inverseTransform=new at,this._bounds=new ne,this._flags=new ht,this._rotation=0,this._sin=0,this._cos=1,this._zoomLevel=1,this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this._boundsConstraint=null,this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakeFrequency=16,this._shakeDecay=!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._updateId=0,this._center=new nt(this._setPositionDirty.bind(this),t,e),this._size=new ae(this._setScalingDirty.bind(this),i,s),this._zoomBaseWidth=i,this._zoomBaseHeight=s,this._flags.push(he.Transform,he.TransformInverse,he.BoundingBox)}get center(){return this._center}set center(t){this._center.copy(t)}get size(){return this._size}set size(t){this._size.copy(t)}get width(){return this._size.width}set width(t){this._size.width=t}get height(){return this._size.height}set height(t){this._size.height=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get viewport(){return this._viewport}set viewport(t){this._viewport.equals(t)||(this._viewport.copy(t),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(t,e){return this._center.set(t,e),this}resize(t,e){return this._zoomBaseWidth=t,this._zoomBaseHeight=e,this._zoomLevel=1,this._size.set(t,e),this}setRotation(t){const e=U(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}move(t,e){return this.setCenter(this._center.x+t,this._center.y+e),this}zoom(t){return this.resize(this._size.width*t,this._size.height*t),this}setZoom(t){const e=Math.max(1e-4,t);return this._zoomLevel=e,this._size.set(this._zoomBaseWidth/e,this._zoomBaseHeight/e),this}zoomIn(t=.1){return this.setZoom(this._zoomLevel+t)}zoomOut(t=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-t))}follow(t,e={}){return this._followTarget=t,this._followLerp=G(e.lerp??1,0,1),this._followOffsetX=e.offsetX??0,this._followOffsetY=e.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(t){return null===t?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=t.clone():this._boundsConstraint.copy(t),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(t,e,i={}){return this._shakeIntensity=Math.max(0,t),this._shakeDurationMs=Math.max(0,e),this._shakeElapsedMs=0,this._shakeFrequency=Math.max(0,i.frequency??16),this._shakeDecay=i.decay??!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty(),this}stopShake(){return this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakePhase=0,0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()),this}update(t){return this._updateFollowTarget(),this._updateShake(t),this._applyBoundsConstraint(),this}rotate(t){return this.setRotation(this._rotation+t),this}reset(t,e,i,s){return this._zoomBaseWidth=i,this._zoomBaseHeight=s,this._zoomLevel=1,this._size.set(i,s),this._center.set(t,e),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(he.Transform),this}getTransform(){return this._flags.has(he.Transform)&&(this.updateTransform(),this._flags.remove(he.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=2/this.width,s=-2/this.height;if(this._flags.has(he.Rotation)){const t=V(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}return this._flags.has(he.Rotation|he.Scaling)&&(this._transform.a=i*this._cos,this._transform.b=i*this._sin,this._transform.c=-s*this._sin,this._transform.d=s*this._cos),this._transform.x=i*-this._transform.a-s*this._transform.b+-i*t,this._transform.y=i*-this._transform.c-s*this._transform.d+-s*e,this}getInverseTransform(){return this._flags.has(he.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(he.TransformInverse)),this._inverseTransform}getBounds(){return this._flags.has(he.BoundingBox)&&(this.updateBounds(),this._flags.remove(he.BoundingBox)),this._bounds.getRect()}updateBounds(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=this.width/2,s=this.height/2;return this._bounds.reset().addCoords(t-i,e-s).addCoords(t+i,e+s),this}destroy(){this.stopShake(),this.clearFollow(),this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this._center.destroy(),this._size.destroy(),this._viewport.destroy(),this._transform.destroy(),this._inverseTransform.destroy(),this._bounds.destroy(),this._flags.destroy()}_setDirty(){this._flags.push(he.TransformInverse,he.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(he.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(he.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(he.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;const t=this._followTarget.x+this._followOffsetX,e=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(t,e):this.setCenter(this._center.x+(t-this._center.x)*this._followLerp,this._center.y+(e-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const t=this._boundsConstraint,e=this.width/2,i=this.height/2,s=t.left+e,r=t.right-e,n=t.top+i,o=t.bottom-i,a=s>r?(t.left+t.right)/2:G(this._center.x,s,r),h=n>o?(t.top+t.bottom)/2:G(this._center.y,n,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(t){if(this._shakeDurationMs<=0||this._shakeIntensity<=0)return void(0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()));this._shakeElapsedMs=Math.min(this._shakeDurationMs,this._shakeElapsedMs+Math.max(0,t));const e=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-e):this._shakeIntensity;this._shakePhase+=Math.max(0,t)/1e3*this._shakeFrequency*Math.PI*2;const s=Math.sin(1.7*this._shakePhase)*i,r=Math.cos(1.3*this._shakePhase)*i;s===this._shakeOffsetX&&r===this._shakeOffsetY||(this._shakeOffsetX=s,this._shakeOffsetY=r,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}let ue=null;class ce extends rt{constructor(t=0,e=0){super(),this.collisionType=0,this.x=t,this.y=e}clone(){return new ce(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(t){switch(t.collisionType){case 6:return Bt(this,t.getBounds());case 2:return Bt(this,t);case 5:return At(this,t);case 3:return Et(this,t);case 4:return Rt(this,t);case 1:return Pt(this,t);case 0:return Mt(this,t);default:return!1}}collidesWith(t){return null}getBounds(){return re.temp.set(this.x,this.y,0,0)}contains(t,e){return Mt(ce.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new dt){return e}destroy(){}static get temp(){return null===ue&&(ue=new ce),ue}static add(t,e){return new ce(t.x+e.x,t.y+e.y)}static subtract(t,e){return new ce(t.x-e.x,t.y-e.y)}static multiply(t,e){return new ce(t.x*e.x,t.y*e.y)}static divide(t,e){return new ce(t.x/e.x,t.y/e.y)}}ce.zero=new ce(0,0),ce.one=new ce(1,1);class de{constructor(t,i,s=!1){this._destroyListeners=new Set,this._version=0,this._viewport=new re,this._size=new e(t,i),this._root=s,this._defaultView=new le(t/2,i/2,t,i),this._view=this._defaultView}get view(){return this._view}set view(t){this.setView(t)}get size(){return this._size}set size(t){this.resize(t.width,t.height)}get width(){return this._size.width}set width(t){this.resize(t,this.height)}get height(){return this._size.height}set height(t){this.resize(this.width,t)}get root(){return this._root}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setView(t){const e=t||this._defaultView;return this._view!==e&&(this._view=e,this._touch()),this}resize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}getViewport(t=this._view){const{x:e,y:i,width:s,height:r}=t.viewport;return this._viewport.set(Math.round(e*this.width),Math.round(i*this.height),Math.round(s*this.width),Math.round(r*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(t,e=this._view){const i=this.getViewport(e);return new ce(2*(t.x-i.left)/i.width-1,1-2*(t.y-i.top)/i.height).transform(e.getInverseTransform())}mapCoordsToPixel(t,e=this._view){const i=this.getViewport(e),s=t.clone().transform(e.getTransform());return s.set((s.x+1)/2*i.width+i.left|0,(1-s.y)/2*i.height+i.top|0)}destroy(){for(const t of Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}class _e extends de{constructor(t,e,i){super(t,e,!1),this._source=null,this._textureVersion=0;const{scaleMode:s,wrapMode:r,premultiplyAlpha:n,generateMipMap:o,flipY:a}={..._e.defaultSamplerOptions,...i};this._scaleMode=s,this._wrapMode=r,this._premultiplyAlpha=n,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(t){this.setSource(t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return q(this.width)&&q(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touchTexture()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touchTexture()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touchTexture()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._defaultView.resize(t,e),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}_e.defaultSamplerOptions={scaleMode:Z.Linear,wrapMode:J.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};class pe{constructor(t,e={}){this._callback=t,this._target=e.target??null,this._view=e.view??null,this._clearColor=e.clearColor??null}execute(t){const e=t.renderTarget,i=t.view;t.setRenderTarget(this._target),t.setView(this._view),null!==this._clearColor&&t.clear(this._clearColor);try{this._callback(t)}finally{t.setRenderTarget(e),t.setView(i)}}}const fe=t=>"destroy"in t&&"function"==typeof t.destroy;class me extends oe{constructor(){super(...arguments),this._filters=[],this._cacheBounds=new re,this._cacheSprite=null,this._captureView=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheDirty=!0,this._cacheTexture=null}get filters(){return this._filters}set filters(t){this.setFilters(t)}get mask(){return this._mask}set mask(t){this._mask!==t&&(this._mask=t,this.invalidateCache())}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(t){this.setCacheAsBitmap(t)}setFilters(t){return this._filters.length=0,this._filters.push(...t),this.invalidateCache()}addFilter(t){return this._filters.push(t),this.invalidateCache()}removeFilter(t){const e=this._filters.indexOf(t);return-1!==e&&(this._filters.splice(e,1),this.invalidateCache()),this}static setInternalSpriteFactory(t){me._spriteFactory=t}clearFilters(){return this._filters.length>0&&(this._filters.length=0,this.invalidateCache()),this}setCacheAsBitmap(t){return this._cacheAsBitmap!==t&&(this._cacheAsBitmap=t,this.invalidateCache(),t||this._destroyCacheTexture()),this}invalidateCache(){return this._cacheDirty=!0,this}renderVisualContent(t,e,i=Q.Normal){const s=this._filters.length>0,r=this._cacheAsBitmap;if(!s&&!r)return void this._withMask(t,e);const n=this.getBounds();if(n.width<=0||n.height<=0)return;const o=Math.floor(n.left),a=Math.floor(n.top),h=Math.max(1,Math.ceil(n.width)),l=Math.max(1,Math.ceil(n.height)),u=!this._cacheBounds.equals({x:o,y:a,width:h,height:l}),c=r&&(this._cacheDirty||null===this._cacheTexture||u);if(r&&!c&&null!==this._cacheTexture)return void this._withMask(t,()=>{this._drawTexture(t,this._cacheTexture,o,a,h,l,i)});const d=[],_=r?this._ensureCacheTexture(h,l):null;try{const n=r&&!s?_:t.acquireRenderTexture(h,l);n!==_&&d.push(n),this._renderContentToTexture(t,n,o,a,h,l,e);let u=n;if(s)for(let e=0;e<this._filters.length;e++){const i=e===this._filters.length-1&&r?_:t.acquireRenderTexture(h,l);i!==_&&d.push(i),this._filters[e].apply(t,u,i),u=i}r&&(this._cacheTexture=_,this._cacheBounds.set(o,a,h,l),this._cacheDirty=!1),this._withMask(t,()=>{this._drawTexture(t,u,o,a,h,l,i)})}finally{for(const e of d)t.releaseRenderTexture(e)}}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const t of this._filters)fe(t)&&t.destroy();this._filters.length=0,this._mask=null}_withMask(t,e){if(null===this._mask)return void e();const i=this._mask.getBounds();if(!(i.width<=0||i.height<=0)){t.pushMask(i);try{e()}finally{t.popMask()}}}_renderContentToTexture(t,e,i,s,r,n,o){null===this._captureView?this._captureView=new le(i+r/2,s+n/2,r,n):this._captureView.reset(i+r/2,s+n/2,r,n),t.execute(new pe(()=>{o()},{target:e,view:this._captureView,clearColor:K.transparentBlack}))}_drawTexture(t,e,i,s,r,n,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(K.white).setPosition(i,s).setRotation(0).setScale(1,1),a.width=r,a.height=n,a.render(t)}_ensureCacheTexture(t,e){return null===this._cacheTexture?this._cacheTexture=new _e(t,e):this._cacheTexture.width===t&&this._cacheTexture.height===e||this._cacheTexture.setSize(t,e),this._cacheTexture}_destroyCacheTexture(){null!==this._cacheTexture&&(this._cacheTexture.destroy(),this._cacheTexture=null),this._cacheDirty=!0}_getCacheSprite(){if(null===this._cacheSprite){if(null===me._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=me._spriteFactory()}return this._cacheSprite}}me._spriteFactory=null;class ge extends me{constructor(){super(...arguments),this._tint=K.white.clone(),this._blendMode=Q.Normal}get tint(){return this._tint}set tint(t){this.setTint(t)}get blendMode(){return this._blendMode}set blendMode(t){this.setBlendMode(t)}setTint(t){return t&&(this._tint.copy(t),this.invalidateCache()),this}setBlendMode(t){return this._blendMode!==t&&(this._blendMode=t,this.invalidateCache()),this}render(t){return this.visible?this.inView(t.view)?(this.renderVisualContent(t,()=>{t.draw(this)},this._blendMode),this):(t.stats.culledNodes++,this):this}destroy(){super.destroy(),this._tint.destroy()}}class ye extends ge{constructor(t,e,i=tt.Triangles){super(),this.geometry=t,this.color=e.clone(),this.drawMode=i}destroy(){super.destroy(),this.color.destroy()}}class xe{constructor({vertices:t=[],indices:e=[],points:i=[]}={}){this.vertices=new Float32Array(t),this.indices=new Uint16Array(e),this.points=i}destroy(){}}class we extends ye{render(t){return this.visible&&t.draw(this),this}}class ve{constructor(t){this._stack=[],this._transitionOverlay=new we(new xe({vertices:[0,0,1,0,0,1,1,1],indices:[0,1,2,3],points:[0,0,1,0,0,1,1,1]}),K.black,tt.TriangleStrip),this._transition=null,this.onChangeScene=new F,this.onStartScene=new F,this.onUpdateScene=new F,this.onStopScene=new F,this._handleKeyDown=t=>{this._dispatchInput({type:"keyDown",channel:t})},this._handleKeyUp=t=>{this._dispatchInput({type:"keyUp",channel:t})},this._handlePointerEnter=t=>{this._dispatchInput({type:"pointerEnter",pointer:t})},this._handlePointerLeave=t=>{this._dispatchInput({type:"pointerLeave",pointer:t})},this._handlePointerDown=t=>{this._dispatchInput({type:"pointerDown",pointer:t})},this._handlePointerMove=t=>{this._dispatchInput({type:"pointerMove",pointer:t})},this._handlePointerUp=t=>{this._dispatchInput({type:"pointerUp",pointer:t})},this._handlePointerTap=t=>{this._dispatchInput({type:"pointerTap",pointer:t})},this._handlePointerSwipe=t=>{this._dispatchInput({type:"pointerSwipe",pointer:t})},this._handlePointerCancel=t=>{this._dispatchInput({type:"pointerCancel",pointer:t})},this._handleMouseWheel=t=>{this._dispatchInput({type:"mouseWheel",wheel:t})},this._app=t,this._subscribeInputRouting()}get scene(){return this._stack.length>0?this._stack[this._stack.length-1].scene:null}set scene(t){this.setScene(t)}get scenes(){return this._stack.map(t=>t.scene)}async setScene(t,e={}){return await this._runWithTransition(async()=>{if(null===t)return await this._unloadAllScenes(),void this.onChangeScene.dispatch(null);if(this.scene===t)return void(this._stack.length>1&&await this._unloadCoveredScenes());if(this._stack.some(e=>e.scene===t))throw new Error("Cannot set a scene that is already present in the scene stack.");const e=this._resolveParticipationPolicy(t);await this._prepareScene(t),await this._unloadAllScenes(),this._stack.push({scene:t,policy:e}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async pushScene(t,e={}){return await this._runWithTransition(async()=>{if(this._stack.some(e=>e.scene===t))throw new Error("Cannot push a scene instance that is already present in the stack.");const i=this._resolveParticipationPolicy(t,e);await this._prepareScene(t),this._stack.push({scene:t,policy:i}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async popScene(t={}){return await this._runWithTransition(async()=>{if(0===this._stack.length)return;const t=this._stack[this._stack.length-1];await this._disposeScene(t.scene),this._stack.pop(),this.onChangeScene.dispatch(this.scene)},t.transition),this}update(t){this._advanceTransition(t.milliseconds);const{updateScenes:e,drawScenes:i}=this._resolveParticipants();for(const i of e)i.update(t);for(const t of i)t.draw(this._app.renderManager);const s=this._getTransitionAlpha();return s>0&&this._renderTransitionOverlay(s),null!==this.scene&&this.onUpdateScene.dispatch(this.scene),this}destroy(){if(this._unsubscribeInputRouting(),this._transition){const t=this._transition;this._transition=null,t.color.destroy(),t.reject(new Error("SceneManager was destroyed while a transition was active."))}this._unloadAllScenesOnDestroy(),this._transitionOverlay.destroy(),this.onChangeScene.destroy(),this.onStartScene.destroy(),this.onUpdateScene.destroy(),this.onStopScene.destroy()}async _prepareScene(t){t.app=this._app;try{await t.load(this._app.loader),await t.init(this._app.loader)}catch(e){let i=null;try{await t.unload(this._app.loader)}catch(t){i=t}if(t.destroy(),t.app=null,i){const t=e instanceof Error?e.message:String(e),s=i instanceof Error?i.message:String(i);throw new Error(`Failed to initialize scene: ${t}. Cleanup also failed: ${s}.`)}throw e}}async _disposeScene(t){this.onStopScene.dispatch(t),await t.unload(this._app.loader),t.destroy(),t.app=null}async _unloadAllScenes(){for(let t=this._stack.length-1;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0}async _unloadCoveredScenes(){if(this._stack.length<=1)return;const t=this._stack[this._stack.length-1];for(let t=this._stack.length-2;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0,this._stack.push(t)}async _unloadAllScenesOnDestroy(){for(let t=this._stack.length-1;t>=0;t--)try{await this._disposeScene(this._stack[t].scene)}catch(t){console.error("SceneManager.destroy() failed to unload the active scene.",t)}this._stack.length=0}_resolveParticipationPolicy(t,e={}){const i=t.getParticipationPolicy(),s=e.mode??i.mode??"overlay";return{mode:s,input:e.input??i.input??("overlay"===s?"passthrough":"capture")}}_resolveParticipants(){const t=new Array,e=new Array;let i=!0,s=!0;for(let r=this._stack.length-1;r>=0;r--){const n=this._stack[r];i&&t.push(n.scene),s&&e.push(n.scene),"opaque"===n.policy.mode?(i=!1,s=!1):"modal"===n.policy.mode&&(i=!1)}return t.reverse(),e.reverse(),{updateScenes:t,drawScenes:e}}_subscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.add?.(this._handleKeyDown),t?.onKeyUp?.add?.(this._handleKeyUp),t?.onPointerEnter?.add?.(this._handlePointerEnter),t?.onPointerLeave?.add?.(this._handlePointerLeave),t?.onPointerDown?.add?.(this._handlePointerDown),t?.onPointerMove?.add?.(this._handlePointerMove),t?.onPointerUp?.add?.(this._handlePointerUp),t?.onPointerTap?.add?.(this._handlePointerTap),t?.onPointerSwipe?.add?.(this._handlePointerSwipe),t?.onPointerCancel?.add?.(this._handlePointerCancel),t?.onMouseWheel?.add?.(this._handleMouseWheel)}_unsubscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.remove?.(this._handleKeyDown),t?.onKeyUp?.remove?.(this._handleKeyUp),t?.onPointerEnter?.remove?.(this._handlePointerEnter),t?.onPointerLeave?.remove?.(this._handlePointerLeave),t?.onPointerDown?.remove?.(this._handlePointerDown),t?.onPointerMove?.remove?.(this._handlePointerMove),t?.onPointerUp?.remove?.(this._handlePointerUp),t?.onPointerTap?.remove?.(this._handlePointerTap),t?.onPointerSwipe?.remove?.(this._handlePointerSwipe),t?.onPointerCancel?.remove?.(this._handlePointerCancel),t?.onMouseWheel?.remove?.(this._handleMouseWheel)}_dispatchInput(t){for(let e=this._stack.length-1;e>=0;e--){const i=this._stack[e];if("transparent"===i.policy.input)continue;if(!1===i.scene.handleInput(t)||"capture"===i.policy.input)break}}async _runWithTransition(t,e){if(!e||"fade"!==e.type)return void await t();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,e.duration??220);0!==i?await new Promise((s,r)=>{this._transition={type:"fade",durationMs:i,action:t,resolve:s,reject:r,color:(e.color??K.black).clone(),elapsedMs:0,phase:"out"}}):await t()}_advanceTransition(t){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),void(this._transition.elapsedMs>=this._transition.durationMs&&(this._transition.phase="switching",this._executeTransitionAction()))):void("in"===this._transition.phase&&(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const t=this._transition;if(t&&"switching"===t.phase){try{await t.action()}catch(e){return void(this._transition===t&&(this._transition=null,t.color.destroy(),t.reject(e)))}this._transition===t&&(t.phase="in",t.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const t=this._transition;this._transition=null,t.color.destroy(),t.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const t=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?t:1-t}_renderTransitionOverlay(t){const e=this._transition,i=e?e.color:K.black,s=this._app.renderManager,r=s.view.getBounds(),n=this._transitionOverlay.geometry.vertices;n[0]=r.left,n[1]=r.top,n[2]=r.right,n[3]=r.top,n[4]=r.left,n[5]=r.bottom,n[6]=r.right,n[7]=r.bottom,this._transitionOverlay.color.set(i.r,i.g,i.b,Math.max(0,Math.min(1,t))),this._transitionOverlay.render(s)}}const be=function(){var t=function(t){window.console&&window.console.error?window.console.error(t):function(t){window.console&&window.console.log&&window.console.log(t)}(t)},e={enable:{1:{0:!0}},disable:{1:{0:!0}},getParameter:{1:{0:!0}},drawArrays:{3:{0:!0}},drawElements:{4:{0:!0,2:!0}},createShader:{1:{0:!0}},getShaderParameter:{2:{1:!0}},getProgramParameter:{2:{1:!0}},getShaderPrecisionFormat:{2:{0:!0,1:!0}},getVertexAttrib:{2:{1:!0}},vertexAttribPointer:{6:{2:!0}},bindTexture:{2:{0:!0}},activeTexture:{1:{0:!0}},getTexParameter:{2:{0:!0,1:!0}},texParameterf:{3:{0:!0,1:!0}},texParameteri:{3:{0:!0,1:!0,2:!0}},copyTexImage2D:{8:{0:!0,2:!0}},copyTexSubImage2D:{8:{0:!0}},generateMipmap:{1:{0:!0}},bindBuffer:{2:{0:!0}},getBufferParameter:{2:{0:!0,1:!0}},pixelStorei:{2:{0:!0,1:!0}},bindRenderbuffer:{2:{0:!0}},bindFramebuffer:{2:{0:!0}},checkFramebufferStatus:{1:{0:!0}},framebufferRenderbuffer:{4:{0:!0,1:!0,2:!0}},framebufferTexture2D:{5:{0:!0,1:!0,2:!0}},getFramebufferAttachmentParameter:{3:{0:!0,1:!0,2:!0}},getRenderbufferParameter:{2:{0:!0,1:!0}},renderbufferStorage:{4:{0:!0,1:!0}},clear:{1:{0:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]}}},depthFunc:{1:{0:!0}},blendFunc:{2:{0:!0,1:!0}},blendFuncSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},blendEquation:{1:{0:!0}},blendEquationSeparate:{2:{0:!0,1:!0}},stencilFunc:{3:{0:!0}},stencilFuncSeparate:{4:{0:!0,1:!0}},stencilMaskSeparate:{2:{0:!0}},stencilOp:{3:{0:!0,1:!0,2:!0}},stencilOpSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},cullFace:{1:{0:!0}},frontFace:{1:{0:!0}},drawArraysInstancedANGLE:{4:{0:!0}},drawElementsInstancedANGLE:{5:{0:!0,2:!0}},blendEquationEXT:{1:{0:!0}},bufferData:{3:{0:!0,2:!0},4:{0:!0,2:!0},5:{0:!0,2:!0}},bufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},copyBufferSubData:{5:{0:!0,1:!0}},getBufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},blitFramebuffer:{10:{8:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]},9:!0}},framebufferTextureLayer:{5:{0:!0,1:!0}},invalidateFramebuffer:{2:{0:!0}},invalidateSubFramebuffer:{6:{0:!0}},readBuffer:{1:{0:!0}},getInternalformatParameter:{3:{0:!0,1:!0,2:!0}},renderbufferStorageMultisample:{5:{0:!0,2:!0}},texStorage2D:{5:{0:!0,2:!0}},texStorage3D:{6:{0:!0,2:!0}},texImage2D:{9:{0:!0,2:!0,6:!0,7:!0},6:{0:!0,2:!0,3:!0,4:!0},10:{0:!0,2:!0,6:!0,7:!0}},texImage3D:{10:{0:!0,2:!0,7:!0,8:!0},11:{0:!0,2:!0,7:!0,8:!0}},texSubImage2D:{9:{0:!0,6:!0,7:!0},7:{0:!0,4:!0,5:!0},10:{0:!0,6:!0,7:!0}},texSubImage3D:{11:{0:!0,8:!0,9:!0},12:{0:!0,8:!0,9:!0}},copyTexSubImage3D:{9:{0:!0}},compressedTexImage2D:{7:{0:!0,2:!0},8:{0:!0,2:!0},9:{0:!0,2:!0}},compressedTexImage3D:{8:{0:!0,2:!0},9:{0:!0,2:!0},10:{0:!0,2:!0}},compressedTexSubImage2D:{8:{0:!0,6:!0},9:{0:!0,6:!0},10:{0:!0,6:!0}},compressedTexSubImage3D:{10:{0:!0,8:!0},11:{0:!0,8:!0},12:{0:!0,8:!0}},vertexAttribIPointer:{5:{2:!0}},drawArraysInstanced:{4:{0:!0}},drawElementsInstanced:{5:{0:!0,2:!0}},drawRangeElements:{6:{0:!0,4:!0}},readPixels:{7:{4:!0,5:!0},8:{4:!0,5:!0}},clearBufferfv:{3:{0:!0},4:{0:!0}},clearBufferiv:{3:{0:!0},4:{0:!0}},clearBufferuiv:{3:{0:!0},4:{0:!0}},clearBufferfi:{4:{0:!0}},beginQuery:{2:{0:!0}},endQuery:{1:{0:!0}},getQuery:{2:{0:!0,1:!0}},getQueryParameter:{2:{1:!0}},samplerParameteri:{3:{1:!0,2:!0}},samplerParameterf:{3:{1:!0}},getSamplerParameter:{2:{1:!0}},fenceSync:{2:{0:!0,1:{enumBitwiseOr:[]}}},clientWaitSync:{3:{1:{enumBitwiseOr:["SYNC_FLUSH_COMMANDS_BIT"]}}},waitSync:{3:{1:{enumBitwiseOr:[]}}},getSyncParameter:{2:{1:!0}},bindTransformFeedback:{2:{0:!0}},beginTransformFeedback:{1:{0:!0}},transformFeedbackVaryings:{3:{2:!0}},bindBufferBase:{3:{0:!0}},bindBufferRange:{5:{0:!0}},getIndexedParameter:{2:{0:!0}},getActiveUniforms:{3:{2:!0}},getActiveUniformBlockParameter:{3:{2:!0}}},i=null,s=null;function r(t){if(null==i)for(var e in i={},s={},t)"number"==typeof t[e]&&(i[t[e]]=e,s[e]=t[e])}function n(){if(null==i)throw"WebGLDebugUtils.init(ctx) not called"}function o(t){n();var e=i[t];return void 0!==e?"gl."+e:"/*UNKNOWN WebGL ENUM*/ 0x"+t.toString(16)}function a(t,i,r,n){var a;if(void 0!==(a=e[t])&&(void 0!==(a=a[i])&&a[r])){if("object"==typeof a[r]&&void 0!==a[r].enumBitwiseOr){for(var h=a[r].enumBitwiseOr,l=0,u=[],c=0;c<h.length;++c){var d=s[h[c]];0!==(n&d)&&(l|=d,u.push(o(d)))}return l===n?u.join(" | "):o(n)}return o(n)}return null===n?"null":void 0===n?"undefined":n.toString()}function h(t,e,i){t.__defineGetter__(i,function(){return e[i]}),t.__defineSetter__(i,function(t){e[i]=t})}function l(t){var e=!!t.createTransformFeedback;e&&t.bindVertexArray(null);var i=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s);for(var r=0;r<i;++r)t.disableVertexAttribArray(r),t.vertexAttribPointer(r,4,t.FLOAT,!1,0,0),t.vertexAttrib1f(r,0),e&&t.vertexAttribDivisor(r,0);t.deleteBuffer(s);var n=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(r=0;r<n;++r)t.activeTexture(t.TEXTURE0+r),t.bindTexture(t.TEXTURE_CUBE_MAP,null),t.bindTexture(t.TEXTURE_2D,null),e&&(t.bindTexture(t.TEXTURE_2D_ARRAY,null),t.bindTexture(t.TEXTURE_3D,null),t.bindSampler(r,null));if(t.activeTexture(t.TEXTURE0),t.useProgram(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindRenderbuffer(t.RENDERBUFFER,null),t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.DITHER),t.disable(t.SCISSOR_TEST),t.blendColor(0,0,0,0),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.clearColor(0,0,0,0),t.clearDepth(1),t.clearStencil(-1),t.colorMask(!0,!0,!0,!0),t.cullFace(t.BACK),t.depthFunc(t.LESS),t.depthMask(!0),t.depthRange(0,1),t.frontFace(t.CCW),t.hint(t.GENERATE_MIPMAP_HINT,t.DONT_CARE),t.lineWidth(1),t.pixelStorei(t.PACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.UNPACK_COLORSPACE_CONVERSION_WEBGL&&t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.BROWSER_DEFAULT_WEBGL),t.polygonOffset(0,0),t.sampleCoverage(1,!1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilMask(4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),e){t.drawBuffers([t.BACK]),t.readBuffer(t.BACK),t.bindBuffer(t.COPY_READ_BUFFER,null),t.bindBuffer(t.COPY_WRITE_BUFFER,null),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.bindBuffer(t.PIXEL_UNPACK_BUFFER,null);var o=t.getParameter(t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);for(r=0;r<o;++r)t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,r,null);var a=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);for(r=0;r<a;++r)t.bindBufferBase(t.UNIFORM_BUFFER,r,null);t.disable(t.RASTERIZER_DISCARD),t.pixelStorei(t.UNPACK_IMAGE_HEIGHT,0),t.pixelStorei(t.UNPACK_SKIP_IMAGES,0),t.pixelStorei(t.UNPACK_ROW_LENGTH,0),t.pixelStorei(t.UNPACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_SKIP_PIXELS,0),t.pixelStorei(t.PACK_ROW_LENGTH,0),t.pixelStorei(t.PACK_SKIP_ROWS,0),t.pixelStorei(t.PACK_SKIP_PIXELS,0),t.hint(t.FRAGMENT_SHADER_DERIVATIVE_HINT,t.DONT_CARE)}for(;t.getError(););}return{init:r,mightBeEnum:function(t){return n(),void 0!==i[t]},glEnumToString:o,glFunctionArgToString:a,glFunctionArgsToString:function(t,e){for(var i="",s=e.length,r=0;r<s;++r)i+=(0==r?"":", ")+a(t,s,r,e[r]);return i},makeDebugContext:function e(i,s,n,l){l=l||i,r(i),s=s||function(e,i,s){for(var r="",n=s.length,h=0;h<n;++h)r+=(0==h?"":", ")+a(i,n,h,s[h]);t("WebGL error "+o(e)+" in "+i+"("+r+")")};var u={};function c(t,e){return function(){n&&n(e,arguments);var i=t[e].apply(t,arguments),r=l.getError();return 0!=r&&(u[r]=!0,s(r,e,arguments)),i}}var d={};for(var _ in i)if("function"==typeof i[_])if("getExtension"!=_)d[_]=c(i,_);else{var p=c(i,_);d[_]=function(){var t=p.apply(i,arguments);return t?e(t,s,n,l):null}}else h(d,i,_);return d.getError=function(){for(var t in u)if(u.hasOwnProperty(t)&&u[t])return u[t]=!1,t;return i.NO_ERROR},d},makeLostContextSimulatingCanvas:function(t){var e,i,s,r=[],n=[],o={},a=1,u=!1,c=[],d=0,_=0,p=!1,f=0,m={};function g(t){return"function"==typeof t?t:function(e){t.handleEvent(e)}}function y(){++_,u||d==_&&t.loseContext()}function x(t,e){var i=t[e];return function(){if(y(),!u)return i.apply(t,arguments)}}function w(t){return{statusMessage:t,preventDefault:function(){p=!0}}}return t.getContext=(s=t.getContext,function(){var r=s.apply(t,arguments);if(r instanceof WebGLRenderingContext||window.WebGL2RenderingContext&&r instanceof WebGL2RenderingContext){if(r!=e){if(e)throw"got different context";i=window.WebGL2RenderingContext&&r instanceof WebGL2RenderingContext,o=function(t){for(var s in t)"function"==typeof t[s]?o[s]=x(t,s):h(o,t,s);o.getError=function(){if(y(),!u)for(;t=e.getError();)m[t]=!0;for(var t in m)if(m[t])return delete m[t],t;return o.NO_ERROR};var r=["createBuffer","createFramebuffer","createProgram","createRenderbuffer","createShader","createTexture"];i&&r.push("createQuery","createSampler","fenceSync","createTransformFeedback","createVertexArray");for(var n=0;n<r.length;++n){var l=r[n];o[l]=function(e){return function(){if(y(),u)return null;var i=e.apply(t,arguments);return i.__webglDebugContextLostId__=a,c.push(i),i}}(t[l])}var d=["getActiveAttrib","getActiveUniform","getBufferParameter","getContextAttributes","getAttachedShaders","getFramebufferAttachmentParameter","getParameter","getProgramParameter","getProgramInfoLog","getRenderbufferParameter","getShaderParameter","getShaderInfoLog","getShaderSource","getTexParameter","getUniform","getUniformLocation","getVertexAttrib"];for(i&&d.push("getInternalformatParameter","getQuery","getQueryParameter","getSamplerParameter","getSyncParameter","getTransformFeedbackVarying","getIndexedParameter","getUniformIndices","getActiveUniforms","getActiveUniformBlockParameter","getActiveUniformBlockName"),n=0;n<d.length;++n)l=d[n],o[l]=function(e){return function(){return y(),u?null:e.apply(t,arguments)}}(o[l]);var _=["isBuffer","isEnabled","isFramebuffer","isProgram","isRenderbuffer","isShader","isTexture"];for(i&&_.push("isQuery","isSampler","isSync","isTransformFeedback","isVertexArray"),n=0;n<_.length;++n)l=_[n],o[l]=function(e){return function(){return y(),!u&&e.apply(t,arguments)}}(o[l]);return o.checkFramebufferStatus=function(e){return function(){return y(),u?o.FRAMEBUFFER_UNSUPPORTED:e.apply(t,arguments)}}(o.checkFramebufferStatus),o.getAttribLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getAttribLocation),o.getVertexAttribOffset=function(e){return function(){return y(),u?0:e.apply(t,arguments)}}(o.getVertexAttribOffset),o.isContextLost=function(){return u},i&&(o.getFragDataLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getFragDataLocation),o.clientWaitSync=function(e){return function(){return y(),u?o.WAIT_FAILED:e.apply(t,arguments)}}(o.clientWaitSync),o.getUniformBlockIndex=function(e){return function(){return y(),u?o.INVALID_INDEX:e.apply(t,arguments)}}(o.getUniformBlockIndex)),o}(e=r)}return o}return r}),function(t){var e=t.addEventListener;t.addEventListener=function(i,s,o){switch(i){case"webglcontextlost":!function(t){r.push(g(t))}(s);break;case"webglcontextrestored":!function(t){n.push(g(t))}(s);break;default:e.apply(t,arguments)}}}(t),t.loseContext=function(){if(!u){for(u=!0,d=0,++a;e.getError(););!function(){for(var t=Object.keys(m),e=0;e<t.length;++e)delete m[t[e]]}(),m[e.CONTEXT_LOST_WEBGL]=!0;var i=w("context lost"),s=r.slice();setTimeout(function(){for(var e=0;e<s.length;++e)s[e](i);f>=0&&setTimeout(function(){t.restoreContext()},f)},0)}},t.restoreContext=function(){u&&n.length&&setTimeout(function(){if(!p)throw"can not restore. webglcontestlost listener did not call event.preventDefault";!function(){for(var t=0;t<c.length;++t){var s=c[t];s instanceof WebGLBuffer?e.deleteBuffer(s):s instanceof WebGLFramebuffer?e.deleteFramebuffer(s):s instanceof WebGLProgram?e.deleteProgram(s):s instanceof WebGLRenderbuffer?e.deleteRenderbuffer(s):s instanceof WebGLShader?e.deleteShader(s):s instanceof WebGLTexture?e.deleteTexture(s):i&&(s instanceof WebGLQuery?e.deleteQuery(s):s instanceof WebGLSampler?e.deleteSampler(s):s instanceof WebGLSync?e.deleteSync(s):s instanceof WebGLTransformFeedback?e.deleteTransformFeedback(s):s instanceof WebGLVertexArrayObject&&e.deleteVertexArray(s))}}(),l(e),u=!1,_=0,p=!1;for(var t=n.slice(),s=w("context restored"),r=0;r<t.length;++r)t[r](s)},0)},t.loseContextInNCalls=function(t){if(u)throw"You can not ask a lost contet to be lost";d=_+t},t.getNumCalls=function(){return _},t.setRestoreTimeout=function(t){f=t},t},resetToInitialState:l}}();class Te{constructor(t=tt.Triangles){this._attributes=[],this._indexBuffer=null,this._runtime=null,this._version=0,this._drawMode=t}get attributes(){return this._attributes}get indexBuffer(){return this._indexBuffer}get drawMode(){return this._drawMode}get version(){return this._version}connect(t){return this._runtime=t,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(t,e,i=st.Float,s=!1,r=0,n=0){const{location:o,size:a}=e;return this._attributes.push({buffer:t,location:o,size:a,type:i,normalized:s,stride:r,start:n}),this._version++,this}addIndex(t){return this._indexBuffer=t,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(t,e,i=this._drawMode){return this._runtime?.draw(this,t,e,i),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}var Se;!function(t){t[t.WebGl2=0]="WebGl2",t[t.WebGpu=1]="WebGpu"}(Se||(Se={}));class Ce{constructor(){this.backendType=Se.WebGl2,this._runtime=null}connect(t){if(null===this._runtime){if(t.backendType!==Se.WebGl2)throw new Error(`${this.constructor.name} requires a WebGL2 runtime, but received backendType ${String(t.backendType)}.`);this._runtime=t,this.onConnect(t)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}class Me{constructor(t,e){this.attributes=new Map,this.uniforms=new Map,this._runtime=null,this._vertexSource=t,this._fragmentSource=e}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(t){return this._runtime=t,t.initialize(this),this}disconnect(){return this._runtime=null,this.attributes.clear(),this.uniforms.clear(),this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}sync(){return this._runtime?.sync(this),this}getAttribute(t){const e=this.attributes.get(t);if(!e)throw new Error(`Attribute "${t}" is not available.`);return e}getUniform(t){const e=this.uniforms.get(t);if(!e)throw new Error(`Uniform "${t}" is not available.`);return e}destroy(){this._runtime?.destroy(this),this._runtime=null,this.attributes.clear(),this.uniforms.clear()}}const Pe={[st.Float]:1,[st.FloatVec2]:2,[st.FloatVec3]:3,[st.FloatVec4]:4,[st.Int]:1,[st.IntVec2]:2,[st.IntVec3]:3,[st.IntVec4]:4,[st.Bool]:1,[st.BoolVec2]:2,[st.BoolVec3]:3,[st.BoolVec4]:4,[st.FloatMat2]:4,[st.FloatMat3]:9,[st.FloatMat4]:16,[st.Sampler2D]:1},Be={[st.Float]:Float32Array,[st.FloatVec2]:Float32Array,[st.FloatVec3]:Float32Array,[st.FloatVec4]:Float32Array,[st.Int]:Int32Array,[st.IntVec2]:Int32Array,[st.IntVec3]:Int32Array,[st.IntVec4]:Int32Array,[st.Bool]:Uint8Array,[st.BoolVec2]:Uint8Array,[st.BoolVec3]:Uint8Array,[st.BoolVec4]:Uint8Array,[st.FloatMat2]:Float32Array,[st.FloatMat3]:Float32Array,[st.FloatMat4]:Float32Array,[st.Sampler2D]:Uint8Array},Ee={[st.Float]:"FLOAT",[st.FloatVec2]:"FLOAT_VEC2",[st.FloatVec3]:"FLOAT_VEC3",[st.FloatVec4]:"FLOAT_VEC4",[st.Int]:"INT",[st.IntVec2]:"INT_VEC2",[st.IntVec3]:"INT_VEC3",[st.IntVec4]:"INT_VEC4",[st.Bool]:"BOOL",[st.BoolVec2]:"BOOL_VEC2",[st.BoolVec3]:"BOOL_VEC3",[st.BoolVec4]:"BOOL_VEC4",[st.FloatMat2]:"FLOAT_MAT2",[st.FloatMat3]:"FLOAT_MAT3",[st.FloatMat4]:"FLOAT_MAT4",[st.Sampler2D]:"SAMPLER_2D"};class Re{constructor(t,e,i){this.location=-1,this.index=t,this.name=e,this.type=i,this.size=Pe[i]}destroy(){}}class Ae{constructor(t,e,i,s,r){this._dirty=!0,this.name=s.replace(/\[.*?]/,""),this.index=t,this.type=e,this.size=i,this._value=r}get propName(){return this.name.substr(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(t){return this._value.set(t),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class ke{constructor(t,e,i){this._uniforms=new Map,this._context=t,this._program=e,this.index=i,this.name=t.getActiveUniformBlockName(e,i)||"",this.binding=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_BINDING),this.dataSize=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=t.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferData(t.UNIFORM_BUFFER,this._blockData,t.DYNAMIC_DRAW),t.bindBufferBase(t.UNIFORM_BUFFER,this.binding,this._uniformBuffer),t.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(t){if(!this._uniforms.has(t))throw new Error(`Uniform "${t}" is not available.`);return this._uniforms.get(t)}upload(){const t=this._context;t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferSubData(t.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const t of this._uniforms.values())t.destroy();this._uniforms.clear()}_extractUniforms(){const t=this._context,e=this._program,i=this._blockData,s=t.getActiveUniformBlockParameter(e,this.index,t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),r=t.getActiveUniforms(e,s,t.UNIFORM_OFFSET),n=s.length;for(let o=0;o<n;o++){const{type:n,size:a,name:h}=t.getActiveUniform(e,s[o]),l=new Be[n](i,r[o],Pe[n]*a),u=new Ae(s[o],n,a,h,l);this._uniforms.set(u.propName,u)}}}const Le={[st.Float]:(t,e,i)=>{t.uniform1f(e,i[0])},[st.FloatVec2]:(t,e,i)=>{t.uniform2fv(e,i)},[st.FloatVec3]:(t,e,i)=>{t.uniform3fv(e,i)},[st.FloatVec4]:(t,e,i)=>{t.uniform4fv(e,i)},[st.Int]:(t,e,i)=>{t.uniform1i(e,i[0])},[st.IntVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[st.IntVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[st.IntVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[st.Bool]:(t,e,i)=>{t.uniform1i(e,i[0])},[st.BoolVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[st.BoolVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[st.BoolVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[st.FloatMat2]:(t,e,i)=>{t.uniformMatrix2fv(e,!1,i)},[st.FloatMat3]:(t,e,i)=>{t.uniformMatrix3fv(e,!1,i)},[st.FloatMat4]:(t,e,i)=>{t.uniformMatrix4fv(e,!1,i)},[st.Sampler2D]:(t,e,i)=>{t.uniform1i(e,i[0])}};function Fe(t){let e=null,i=null,s=null;const r=[],n=[];function o(o){e||(i=De(t,t.VERTEX_SHADER,o.vertexSource),s=De(t,t.FRAGMENT_SHADER,o.fragmentSource),e=function(t,e,i){const s=t.createProgram();if(!s)throw new Error("Could not create shader program.");if(t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS)){const r=t.getProgramInfoLog(s);throw t.detachShader(s,e),t.detachShader(s,i),t.deleteProgram(s),new Error(`Shader program linking failed: ${r}`)}return s}(t,i,s),function(t,e,i){const s=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r<s;r++){const s=t.getActiveAttrib(e,r);if(!s)continue;const n=new Re(r,s.name,s.type);n.location=t.getAttribLocation(e,s.name),i.attributes.set(s.name,n)}}(t,e,o),function(t,e,i,s){const r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),n=new Uint8Array(r).map((t,e)=>e),o=t.getActiveUniforms(e,n,t.UNIFORM_BLOCK_INDEX),a=n.filter(t=>-1===o[t]);for(const r of a){const n=t.getActiveUniform(e,r);if(!n)continue;const o=new Be[n.type](Pe[n.type]*n.size),a=new Ae(r,n.type,n.size,n.name,o),h=t.getUniformLocation(e,a.name),l=Le[n.type];i.uniforms.set(a.name,a),h&&s.push({location:h,uploadFn:l,uniform:a})}}(t,e,o,r),function(t,e,i){const s=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<s;r++){const s=new ke(t,e,r);i.push(s)}}(t,e,n))}function a(){for(const e of r)e.uniform.dirty&&(e.uploadFn(t,e.location,e.uniform.value),e.uniform.markClean());for(const t of n)t.upload()}return{initialize:o,bind:i=>{o(i),t.useProgram(e),a()},unbind:()=>{t.useProgram(null)},sync:()=>{a()},destroy:o=>{t.deleteShader(i),t.deleteShader(s),t.deleteProgram(e);for(const t of n)t.destroy();i=null,s=null,e=null,r.length=0,n.length=0,o.disconnect()}}}function De(t,e,i){const s=t.createShader(e);if(!s)throw new Error("Could not create shader.");if(t.shaderSource(s,i),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(s);throw t.deleteShader(s),new Error(`Shader compilation failed: ${e}`)}return s}class Ie{constructor(t,e,i){this._runtime=null,this._data=P,this._version=0,this._type=t,this._usage=i,e&&this.upload(e)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(t){return this._runtime=t,this._data.byteLength>0&&t.upload(this,0),this}disconnect(){return this._runtime=null,this}upload(t,e=0){this._data=t,this._version++,this._runtime?.upload(this,e)}bind(){this._runtime?.bind(this)}destroy(){this._runtime?.destroy(this),this._runtime=null}}const Ne=(t={})=>{const{canvas:e,fillStyle:i,width:s,height:r}=t,n=e??document.createElement("canvas"),o=n.getContext("2d");return n.width=s??10,n.height=r??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,n.width,n.height),n},Ue=new Map;class Ve extends Ce{constructor(t,e,i,s){super(),this.batchIndex=0,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.vao=null,this.indexBuffer=null,this.vertexBuffer=null,this.connection=null,this.batchSize=t,this.attributeCount=e,this.vertexData=new ArrayBuffer(t*e*4),this.float32View=new Float32Array(this.vertexData),this.uint32View=new Uint32Array(this.vertexData),this.indexData=(t=>{const e=new Uint16Array(6*t),i=e.length;for(let t=0,s=0;t<i;t+=6,s+=4)e[t]=s,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s,e[t+4]=s+2,e[t+5]=s+3;return e})(t),this.shader=new Me(i,s)}flush(){const t=this.getRuntimeOrNull(),e=this.vertexBuffer,i=this.vao;if(0===this.batchIndex||null===t||null===e||null===i)return;const s=t.view;this.currentView===s&&this.currentViewId===s.updateId||(this.currentView=s,this.currentViewId=s.updateId,this.updateView(s)),this.shader.sync(),t.bindVertexArrayObject(i),e.upload(this.float32View.subarray(0,this.batchIndex*this.attributeCount)),i.draw(6*this.batchIndex,0),t.stats.batches++,t.stats.drawCalls++,this.batchIndex=0}destroy(){this.disconnect(),this.shader.destroy(),this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.connection=null}onConnect(t){const e=t.context;this.shader.connect(Fe(e)),this.connection=this.createConnection(e),this.indexBuffer=new Ie(et.ElementArrayBuffer,this.indexData,it.StaticDraw).connect(this.createBufferRuntime(this.connection)),this.vertexBuffer=new Ie(et.ArrayBuffer,this.vertexData,it.DynamicDraw).connect(this.createBufferRuntime(this.connection)),this.vao=this.createVao(e,this.indexBuffer,this.vertexBuffer).connect(this.createVaoRuntime(this.connection))}onDisconnect(){this.flush(),this.shader.disconnect(),this.indexBuffer?.destroy(),this.indexBuffer=null,this.vertexBuffer?.destroy(),this.vertexBuffer=null,this.vao?.destroy(),this.vao=null,this.connection=null,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.batchIndex=0}createConnection(t){const e=t.createVertexArray();if(null===e)throw new Error("Could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("Could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,s)=>{const r=t.gl,n=i.data,o=t.buffers.get(i);r.bindBuffer(i.type,e),o&&o.dataByteLength>=n.byteLength?(r.bufferSubData(i.type,s,n),o.dataByteLength=n.byteLength):(r.bufferData(i.type,n,i.usage),t.buffers.set(i,{handle:e,dataByteLength:n.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}createVaoRuntime(t){let e=-1;return{bind:i=>{const s=t.gl;if(s.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),s.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),s.enableVertexAttribArray(e.location);i.indexBuffer&&i.indexBuffer.bind(),e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,s,r)=>{const n=t.gl;e.indexBuffer?n.drawElements(r,i,n.UNSIGNED_SHORT,s):n.drawArrays(r,s,i)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}class Oe extends Ve{constructor(t){super(t,16,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,blendMode:i,tint:s,vertices:r,texCoords:n}=t,o=this.batchIndex>=this.batchSize,a=e!==this.currentTexture,h=i!==this.currentBlendMode,l=o||a||h,u=l?0:this.batchIndex*this.attributeCount,c=this.float32View,d=this.uint32View,_=this.getRuntime();return l&&(this.flush(),a&&(this.currentTexture=e),h&&(this.currentBlendMode=i,_.setBlendMode(i))),a&&e&&_.bindTexture(e),c[u+0]=r[0],c[u+1]=r[1],c[u+4]=r[2],c[u+5]=r[3],c[u+8]=r[4],c[u+9]=r[5],c[u+12]=r[6],c[u+13]=r[7],d[u+2]=n[0],d[u+6]=n[1],d[u+10]=n[2],d[u+14]=n[3],d[u+3]=d[u+7]=d[u+11]=d[u+15]=s.toRgba(),this.batchIndex++,this}createVao(t,e,i){return(new Te).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,12)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class Ge extends Ve{constructor(t){super(t,36,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec2 a_translation;\r\nlayout(location = 3) in vec2 a_scale;\r\nlayout(location = 4) in float a_rotation;\r\nlayout(location = 5) in vec4 a_color;\n\nuniform mat3 u_projection;\nuniform mat3 u_translation;\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\n vec2 rotation = vec2(sin(radians(a_rotation)), cos(radians(a_rotation)));\n vec3 position = vec3(\n (a_position.x * (a_scale.x * rotation.y)) + (a_position.y * (a_scale.y * rotation.x)) + a_translation.x,\n (a_position.x * (a_scale.x * -rotation.x)) + (a_position.y * (a_scale.y * rotation.y)) + a_translation.y,\n 1.0\n );\n\n gl_Position = vec4((u_projection * u_translation * position).xy, 0.0, 1.0);\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,vertices:i,texCoords:s,particles:r,blendMode:n}=t,o=e!==this.currentTexture,a=n!==this.currentBlendMode,h=this.float32View,l=this.uint32View,u=this.getRuntime();this.flush(),(o||a)&&(o&&(this.currentTexture=e),a&&(this.currentBlendMode=n,u.setBlendMode(n))),o&&u.bindTexture(e),this.shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));for(const t of r){this.batchIndex>=this.batchSize&&this.flush();const{position:e,scale:r,rotation:n,tint:o}=t,a=this.batchIndex*this.attributeCount;h[a+0]=h[a+27]=i[0],h[a+1]=h[a+10]=i[1],h[a+9]=h[a+18]=i[2],h[a+19]=h[a+28]=i[3],l[a+2]=s[0],l[a+11]=s[1],l[a+20]=s[2],l[a+29]=s[3],h[a+3]=h[a+12]=h[a+21]=h[a+30]=e.x,h[a+4]=h[a+13]=h[a+22]=h[a+31]=e.y,h[a+5]=h[a+14]=h[a+23]=h[a+32]=r.x,h[a+6]=h[a+15]=h[a+24]=h[a+33]=r.y,h[a+7]=h[a+16]=h[a+25]=h[a+34]=n,l[a+8]=l[a+17]=l[a+26]=l[a+35]=o.toRgba(),this.batchIndex++}return this}createVao(t,e,i){return(new Te).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_translation"),t.FLOAT,!1,this.attributeCount,12).addAttribute(i,this.shader.getAttribute("a_scale"),t.FLOAT,!1,this.attributeCount,20).addAttribute(i,this.shader.getAttribute("a_rotation"),t.FLOAT,!1,this.attributeCount,28).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,32)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class ze extends Ce{constructor(t){super(),this._shader=new Me("#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\nuniform mat3 u_translation;\r\n\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * u_translation * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nin vec4 v_color;\r\n\r\nvoid main(void) {\r\n fragColor = v_color;\r\n}\r\n"),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1,this._vertexCapacity=Math.max(4,t),this._indexCapacity=Math.max(6,3*this._vertexCapacity),this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._indexData=new Uint16Array(this._indexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}render(t){const e=this._connection;if(!e)throw new Error("Renderer not connected");const i=this.getRuntime(),{geometry:s,drawMode:r,color:n,blendMode:o}=t,a=s.vertices,h=s.indices,l=a.length/2,u=h.length>0?h.length:l;if(0===l||0===u)return;this._ensureVertexCapacity(l),this._ensureIndexCapacity(u),o!==this._currentBlendMode&&(this._currentBlendMode=o,i.setBlendMode(o));const c=i.view;this._currentView===c&&this._viewId===c.updateId||(this._currentView=c,this._viewId=c.updateId,this._shader.getUniform("u_projection").setValue(c.getTransform().toArray(!1))),this._shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));const d=n.toRgba();for(let t=0;t<l;t++){const e=2*t,i=3*t;this._float32View[i]=a[e],this._float32View[i+1]=a[e+1],this._uint32View[i+2]=d}if(h.length>0)this._indexData.set(h,0);else for(let t=0;t<l;t++)this._indexData[t]=t;this._shader.sync(),i.bindVertexArrayObject(e.vao),e.vertexBuffer.upload(this._float32View.subarray(0,3*l)),e.indexBuffer.upload(this._indexData.subarray(0,u)),e.vao.draw(u,0,r),i.stats.batches++,i.stats.drawCalls++}flush(){}destroy(){this.disconnect(),this._shader.destroy(),this._currentBlendMode=null,this._currentView=null}onConnect(t){const e=t.context,i=e.createVertexArray();if(this._shader.connect(Fe(e)),null===i)throw new Error("Could not create vertex array object.");const s=new Map,r=new Ie(et.ElementArrayBuffer,this._indexData,it.DynamicDraw).connect(this._createBufferRuntime(e,s)),n=new Ie(et.ArrayBuffer,this._vertexData,it.DynamicDraw).connect(this._createBufferRuntime(e,s)),o=(new Te).addIndex(r).addAttribute(n,this._shader.getAttribute("a_position"),e.FLOAT,!1,12,0).addAttribute(n,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,12,8).connect(this._createVaoRuntime(e,i));this._connection={gl:e,buffers:s,vaoHandle:i,vao:o,indexBuffer:r,vertexBuffer:n}}onDisconnect(){const t=this._connection;t&&(this._shader.disconnect(),t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1)}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(s,r)=>{const n=e.get(s),o=s.data;t.bindBuffer(s.type,i),n&&n.dataByteLength>=o.byteLength?(t.bufferSubData(s.type,r,o),n.dataByteLength=o.byteLength):(t.bufferData(s.type,o,s.usage),e.set(s,{handle:i,dataByteLength:o.byteLength}))},destroy:s=>{t.deleteBuffer(i),e.delete(s),s.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:s=>{if(t.bindVertexArray(e),i!==s.version){let e=null;for(const i of s.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);s.indexBuffer&&s.indexBuffer.bind(),i=s.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,r)=>{e.indexBuffer?t.drawElements(r,i,t.UNSIGNED_SHORT,s):t.drawArrays(r,s,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}var We;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint"}(We||(We={}));class qe extends ge{constructor(t){super(),this._texture=null,this._textureFrame=new re,this._vertices=new Float32Array(8),this._texCoords=new Uint32Array(4),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(t){this.scale.x=t/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(t){this.scale.y=t/this._textureFrame.height}get vertices(){const{left:t,top:e,right:i,bottom:s}=this.getLocalBounds(),{a:r,b:n,x:o,c:a,d:h,y:l}=this.getGlobalTransform();return this._vertices[0]=t*r+e*n+o,this._vertices[1]=t*a+e*h+l,this._vertices[2]=i*r+e*n+o,this._vertices[3]=i*a+e*h+l,this._vertices[4]=i*r+s*n+o,this._vertices[5]=i*a+s*h+l,this._vertices[6]=t*r+s*n+o,this._vertices[7]=t*a+s*h+l,this._vertices}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(We.TextureCoords)){const{width:t,height:e}=this._texture,{left:i,top:s,right:r,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(s/e*65535&65535)<<16,h=r/t*65535&65535,l=(n/e*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o)}return this._texCoords}setTexture(t){return this._texture!==t&&(this._texture=t,this.updateTexture(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,e=!0){const i=this.width,s=this.height;return this._textureFrame.copy(t),this.flags.push(We.TextureCoords),this.localBounds.set(0,0,t.width,t.height),e?(this.width=t.width,this.height=t.height):(this.width=i,this.height=s),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(re.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){const[t,e,i,s,r,n,o,a]=this.vertices;return[new ce(i-t,s-e).rperp().normalize(),new ce(r-i,n-s).rperp().normalize(),new ce(o-r,a-n).rperp().normalize(),new ce(t-o,e-a).rperp().normalize()]}project(t,e=new dt){const[i,s,r,n,o,a,h,l]=this.vertices,u=t.dot(i,s),c=t.dot(r,n),d=t.dot(o,a),_=t.dot(h,l);return e.set(Math.min(u,c,d,_),Math.max(u,c,d,_))}contains(t,e){if(this.rotation%90==0)return this.getBounds().contains(t,e);const[i,s,r,n,o,a]=this.vertices,h=ce.temp,l=h.set(r-i,n-s),u=l.dot(t-i,e-s),c=l.lengthSq,d=h.set(o-r,a-n),_=d.dot(t-r,e-n),p=d.lengthSq;return u>0&&u<=c&&_>0&&_<=p}destroy(){super.destroy(),this._textureFrame.destroy(),this._texture=null}}me.setInternalSpriteFactory(()=>new qe(null));class He{constructor(){this._totalLifetime=r.oneSecond.clone(),this._elapsedLifetime=r.zero.clone(),this._position=ce.zero.clone(),this._velocity=ce.zero.clone(),this._scale=ce.one.clone(),this._rotation=0,this._rotationSpeed=0,this._textureIndex=0,this._tint=K.white.clone()}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get tint(){return this._tint}set tint(t){this._tint.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=U(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get remainingLifetime(){return r.temp.set(this._totalLifetime.milliseconds-this._elapsedLifetime.milliseconds)}get elapsedRatio(){return this._elapsedLifetime.milliseconds/this._totalLifetime.milliseconds}get remainingRatio(){return this.remainingLifetime.milliseconds/this._totalLifetime.milliseconds}get expired(){return this._elapsedLifetime.greaterThan(this._totalLifetime)}applyOptions(t){const{totalLifetime:e,elapsedLifetime:i,position:s,velocity:r,scale:n,tint:o,rotation:a,rotationSpeed:h,textureIndex:l}=t;return this._totalLifetime.copy(e),this._elapsedLifetime.copy(i),this._position.copy(s),this._velocity.copy(r),this._scale.copy(n),this._tint.copy(o),this._rotation=a,this._rotationSpeed=h,this._textureIndex=l,this}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class Xe extends ge{constructor(t){super(),this._emitters=[],this._affectors=[],this._particles=[],this._graveyard=[],this._textureFrame=new re,this._vertices=new Float32Array(4),this._texCoords=new Uint32Array(4),this._updateTexCoords=!0,this._updateVertices=!0,this._texture=t,this.resetTextureFrame()}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get vertices(){if(this._updateVertices){const{x:t,y:e,width:i,height:s}=this._textureFrame,r=i/2,n=s/2;this._vertices[0]=t-r,this._vertices[1]=e-n,this._vertices[2]=i-r,this._vertices[3]=s-n,this._updateVertices=!1}return this._vertices}get texCoords(){if(this._updateTexCoords){const{width:t,height:e}=this._texture,{left:i,top:s,right:r,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(s/e*65535&65535)<<16,h=r/t*65535&65535,l=(n/e*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o),this._updateTexCoords=!1}return this._texCoords}get emitters(){return this._emitters}get affectors(){return this._affectors}get particles(){return this._particles}get graveyard(){return this._graveyard}setTexture(t){return this._texture!==t&&(this._texture=t,this.resetTextureFrame()),this}setTextureFrame(t){return this._textureFrame.copy(t),this._updateTexCoords=!0,this._updateVertices=!0,this.localBounds.set(0,0,t.width,t.height),this}resetTextureFrame(){return this.setTextureFrame(re.temp.set(0,0,this._texture.width,this._texture.height))}addEmitter(t){return this._emitters.push(t),this}clearEmitters(){for(const t of this._emitters)t.destroy();return this._emitters.length=0,this}addAffector(t){return this._affectors.push(t),this}clearAffectors(){for(const t of this._affectors)t.destroy();return this._affectors.length=0,this}requestParticle(){return this._graveyard.pop()||new He}emitParticle(t){return this._particles.push(t),this}updateParticle(t,e){const i=e.seconds;return t.elapsedLifetime.addTime(e),t.position.add(i*t.velocity.x,i*t.velocity.y),t.rotation+=i*t.rotationSpeed,this}clearParticles(){for(const t of this._particles)t.destroy();for(const t of this._graveyard)t.destroy();return this._particles.length=0,this._graveyard.length=0,this}update(t){const e=this._emitters,i=this._affectors,s=this._particles,r=this._graveyard,n=s.length;for(const i of e)i.apply(this,t);let o=0;for(let e=n-1;e>=0;e--)if(this.updateParticle(s[e],t),s[e].expired)r.push(s[e]),o++;else{o>0&&(s.splice(e+1,o),o=0);for(const r of i)r.apply(s[e],t)}return o>0&&s.splice(0,o),this}destroy(){super.destroy(),this.clearEmitters(),this.clearAffectors(),this.clearParticles(),this._textureFrame.destroy()}}class je{static get black(){return null===je._black&&(je._black=new je(Ne({fillStyle:"#000"}))),je._black}static get white(){return null===je._white&&(je._white=new je(Ne({fillStyle:"#fff"}))),je._white}constructor(t=null,i){this._version=0,this._source=null,this._size=new e(0,0),this._destroyListeners=new Set,this._premultiplyAlpha=!1,this._generateMipMap=!1,this._flipY=!1;const{scaleMode:s,wrapMode:r,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...je.defaultSamplerOptions,...i};this._scaleMode=s,this._wrapMode=r,this._premultiplyAlpha=n,this._generateMipMap=o,this._flipY=a,null!==t&&this.setSource(t)}get source(){return this._source}set source(t){this.setSource(t)}get size(){return this._size}set size(t){this.setSize(t.width,t.height)}get width(){return this._size.width}set width(t){this.setSize(t,this.height)}get height(){return this._size.height}set height(t){this.setSize(this.width,t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return q(this.width)&&q(this.height)}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touch()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touch()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touch()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){const{width:t,height:e}=A(this._source);return this.setSize(t,e),this._touch(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}destroy(){for(const t of Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}je._black=null,je._white=null,je.defaultSamplerOptions={scaleMode:Z.Linear,wrapMode:J.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1},je.empty=new je(null);class Ye{constructor(){this._renderers=new Map,this._runtime=null}registerRenderer(t,e){if(this._renderers.has(t))throw new Error(`A renderer is already registered for ${t.name}.`);this._renderers.set(t,e),null!==this._runtime&&e.connect(this._runtime)}resolve(t){let e,i=t.constructor;for(;null!==i&&!e;)if(e=this._renderers.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No renderer registered for ${t.constructor.name}. Register one with registry.registerRenderer() before the first draw call.`);return e}connect(t){this._runtime=t;for(const e of this._renderers.values())e.connect(t)}disconnect(){for(const t of this._renderers.values())t.disconnect();this._runtime=null}destroy(){this.disconnect();for(const t of this._renderers.values())"destroy"in t&&"function"==typeof t.destroy&&t.destroy();this._renderers.clear()}}const $e=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0}),Ke=t=>(t.frame++,t.submittedNodes=0,t.culledNodes=0,t.drawCalls=0,t.batches=0,t.renderPasses=0,t.renderTargetChanges=0,t.frameTimeMs=0,t),Qe=(t,e)=>{throw`${be.glEnumToString(t)} was caused by call to: ${e}`},Ze=(t,e)=>{((t,e)=>{console.log(`gl.${t}(${be.glFunctionArgsToString(t,e)})`)})(t,e),((t,e)=>{for(const i of e)void 0===i&&console.error(`undefined passed to gl.${t}(${be.glFunctionArgsToString(t,e)})`)})(t,e)};class Je{constructor(t){this.backendType=Se.WebGl2,this.rendererRegistry=new Ye,this._textureStates=new Map,this._renderTargetStates=new Map,this._textureDestroyHandlers=new Map,this._renderTargetDestroyHandlers=new Map,this._temporaryRenderTextures=[],this._maskStack=[],this._maskPixelStack=[],this._maskPointA=new ce,this._maskPointB=new ce,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._textureUnit=0,this._vao=null,this._clearColor=new K,this._boundFramebuffer=null,this._stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};const{width:e,height:i,clearColor:s,webglAttributes:r,debug:n,spriteRendererBatchSize:o,particleRendererBatchSize:a,primitiveRendererBatchSize:h}=t.options;this._canvas=t.canvas;const l=this._createContext(r);if(!l)throw new Error("This browser or hardware does not support WebGL.");this._context=n?be.makeDebugContext(l,Qe,Ze,l):l,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),s&&this.clearColor.copy(s),this._rootRenderTarget=new de(e,i,!0),this._renderTarget=this._rootRenderTarget,this._cursor=this._canvas.style.cursor,this._onContextLostHandler=this._onContextLost.bind(this),this._onContextRestoredHandler=this._onContextRestored.bind(this),this._setupContext(),this._addEvents(),this.rendererRegistry.registerRenderer(qe,new Oe(o)),this.rendererRegistry.registerRenderer(Xe,new Ge(a)),this.rendererRegistry.registerRenderer(ye,new ze(h)),this.rendererRegistry.connect(this),this._bindRenderTarget(this._renderTarget),this.setBlendMode(Q.Normal),this.resize(e,i)}get context(){return this._context}get renderTarget(){return this._renderTarget}get view(){return this._renderTarget.view}get clearColor(){return this._clearColor}get cursor(){return this._cursor}get stats(){return this._stats}async initialize(){return this}resetStats(){return Ke(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setRenderTarget(t){const e=t||this._rootRenderTarget;return this._renderTarget!==e&&(this._renderTarget=e,this._stats.renderTargetChanges++),this._bindRenderTarget(e),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,s=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(s),this._applyMaskState(),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this._applyMaskState(),this}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const s=this._temporaryRenderTextures[i];if(s.width===t&&s.height===e)return this._temporaryRenderTextures.splice(i,1),s}return new _e(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(t){return this._vao!==t&&(t&&t.bind(),this._vao&&this._vao.unbind(),this._vao=t),this}bindShader(t){return this._shader!==t&&(this._shader&&(this._shader.unbind(),this._shader=null),t&&t.bind(),this._shader=t),this}bindTexture(t,e){if(void 0!==e&&this._setTextureUnit(e),null===t)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(t);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=t,this}setBlendMode(t){if(t!==this._blendMode){const e=this._context;switch(this._blendMode=t,t){case Q.Additive:e.blendFunc(e.ONE,e.ONE);break;case Q.Subtract:e.blendFunc(e.ZERO,e.ONE_MINUS_SRC_COLOR);break;case Q.Multiply:e.blendFunc(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA);break;case Q.Screen:e.blendFunc(e.ONE,e.ONE_MINUS_SRC_COLOR);break;default:e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(t){if(this._textureUnit!==t){const e=this._context;this._textureUnit=t,e.activeTexture(e.TEXTURE0+t)}}setClearColor(t){if(!this._clearColor.equals(t)){const e=this._context;this._clearColor.copy(t),e.clearColor(t.r/255,t.g/255,t.b/255,t.a)}return this}setCursor(t){const e=t instanceof je?t.source:t;if(null===e)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof e?e:`url(${k(e)})`,this._canvas.style.cursor=this._cursor,this}clear(t){const e=this._context;return t&&this.setClearColor(t),this._bindRenderTarget(this._renderTarget),e.clear(e.COLOR_BUFFER_BIT),this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._bindRenderTarget(this._renderTarget),this}flush(){return this._flushActiveRenderer(),this}destroy(){this._removeEvents(),this.setRenderTarget(null),this._setActiveRenderer(null),this.bindVertexArrayObject(null),this.bindShader(null),this.bindTexture(null),this.rendererRegistry.destroy(),this._clearColor.destroy(),this._destroyManagedResources(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy(),this._rootRenderTarget.destroy(),this._vao=null,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._boundFramebuffer=null}_createContext(t){try{return this._canvas.getContext("webgl2",t)}catch(t){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const t=this._context,{r:e,g:i,b:s,a:r}=this._clearColor;t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.clearColor(e/255,i/255,s/255,r)}_addEvents(){this._canvas.addEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.addEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_removeEvents(){this._canvas.removeEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_onContextLost(){this._contextLost=!0,this._restoreContext()}_onContextRestored(){this._contextLost=!1}_createFramebuffer(){const t=this._context.createFramebuffer();if(null===t)throw new Error("Could not create framebuffer.");return t}_createTextureHandle(){const t=this._context.createTexture();if(null===t)throw new Error("Could not create texture.");return t}_destroyManagedResources(){for(const t of Array.from(this._renderTargetStates.keys()))this._evictRenderTarget(t,!1);for(const t of Array.from(this._textureStates.keys()))this._evictTexture(t,!1)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(t){let e=this._renderTargetStates.get(t);return e||(this._subscribeToDestroy(t,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(t,!0)}),e={framebuffer:t.root?null:this._createFramebuffer(),version:-1,attachedTexture:null},this._renderTargetStates.set(t,e)),e}_getTextureState(t){let e=this._textureStates.get(t);return e||(this._subscribeToDestroy(t,this._textureDestroyHandlers,()=>{this._evictTexture(t,!0)}),e={handle:this._createTextureHandle(),version:-1,width:0,height:0},this._textureStates.set(t,e)),e}_subscribeToDestroy(t,e,i){e.has(t)||(t.addDestroyListener(i),e.set(t,i))}_unsubscribeFromDestroy(t,e){const i=e.get(t);i&&(t.removeDestroyListener(i),e.delete(t))}_evictRenderTarget(t,e){const i=this._renderTargetStates.get(t);this._unsubscribeFromDestroy(t,this._renderTargetDestroyHandlers),t instanceof _e&&this._evictTexture(t,!1),i&&(this._boundFramebuffer===i.framebuffer&&(this._context.bindFramebuffer(this._context.FRAMEBUFFER,null),this._boundFramebuffer=null),null!==i.framebuffer&&this._context.deleteFramebuffer(i.framebuffer),this._renderTargetStates.delete(t)),this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget,e&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(t,e){const i=this._textureStates.get(t);this._unsubscribeFromDestroy(t,this._textureDestroyHandlers),i&&(this._texture===t&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this._context.deleteTexture(i.handle),this._textureStates.delete(t)),this._texture===t&&(this._texture=null),e&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(t){const e=this._prepareRenderTarget(t);if(this._boundFramebuffer!==e.framebuffer||e.version!==t.version){const i=this._context,{x:s,y:r,width:n,height:o}=t.getViewport();i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.viewport(s,r,n,o),this._boundFramebuffer=e.framebuffer,e.version=t.version}this._maskPixelStack.length>0&&this._applyMaskState()}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(t){const e=this._getRenderTargetState(t);if(t instanceof _e&&e.framebuffer){const i=this._boundFramebuffer,s=this._syncTexture(t);if(e.attachedTexture!==s.handle){const t=this._context;t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.handle,0),t.bindFramebuffer(t.FRAMEBUFFER,i),e.attachedTexture=s.handle}}return e}_syncTexture(t){const e=this._context,i=this._getTextureState(t),s=t instanceof _e?t.textureVersion:t.version;return e.bindTexture(e.TEXTURE_2D,i.handle),i.version!==s&&(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t.wrapMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t.wrapMode),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),t instanceof _e?-1===i.version||i.width!==t.width||i.height!==t.height||null===t.source?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.width,t.height,0,e.RGBA,e.UNSIGNED_BYTE,t.source):e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,t.source):t.source&&(-1===i.version||i.width!==t.width||i.height!==t.height?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source):e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,t.source)),t.generateMipMap&&(t instanceof _e||null!==t.source)&&e.generateMipmap(e.TEXTURE_2D),i.version=s,i.width=t.width,i.height=t.height),i}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),s=Math.min(e.x,i.x),r=Math.max(e.x,i.x),n=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(s))),u=Math.max(0,Math.min(a,Math.ceil(r))),c=Math.max(0,Math.min(h,Math.floor(n))),d=Math.max(0,Math.min(h,Math.ceil(o))),_=Math.max(0,u-l),p=Math.max(0,d-c);return{x:l,y:Math.max(0,h-d),width:_,height:p}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),s=Math.max(t.y,e.y),r=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:s,width:Math.max(0,r-i),height:Math.max(0,n-s)}}_applyMaskState(){const t=this._context;if(0===this._maskPixelStack.length)return void t.disable(t.SCISSOR_TEST);const e=this._maskPixelStack[this._maskPixelStack.length-1];t.enable(t.SCISSOR_TEST),t.scissor(e.x,e.y,e.width,e.height)}}class ti{constructor(){this.backendType=Se.WebGpu,this._runtime=null}connect(t){if(null===this._runtime){if(t.backendType!==Se.WebGpu)throw new Error(`${this.constructor.name} requires a WebGPU runtime, but received backendType ${String(t.backendType)}.`);this._runtime=t,this.onConnect(t)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}function ei(t){switch(t){case Q.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case Q.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case Q.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case Q.Screen:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}};default:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}}class ii extends ti{constructor(){super(...arguments),this._combinedTransform=new at,this._drawCalls=[],this._drawCallCount=0,this._transformData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT),this._pipelines=new Map,this._renderManager=null,this._device=null,this._shaderModule=null,this._bindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._bindGroup=null,this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._generatedIndexData=new Uint16Array(0),this._sequentialIndexData=new Uint16Array(0)}render(t){const e=this._renderManager;if(null===e)throw new Error("Renderer not connected");if(t.drawMode!==tt.Points&&t.drawMode!==tt.Lines&&t.drawMode!==tt.LineLoop&&t.drawMode!==tt.LineStrip&&t.drawMode!==tt.Triangles&&t.drawMode!==tt.TriangleFan&&t.drawMode!==tt.TriangleStrip)throw new Error(`WebGPU primitive renderer does not support draw mode "${t.drawMode}" yet.`);if(e.setBlendMode(t.blendMode),0===t.geometry.vertices.length)return;const i=this._drawCallCount++,s=this._drawCalls[i];s?(s.shape=t,s.blendMode=t.blendMode):this._drawCalls.push({shape:t,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._bindGroup,s=this._uniformBuffer;if(!(t&&e&&i&&s))return;if(0===this._drawCallCount&&!t.clearRequested)return;const r=e.createCommandEncoder(),n=r.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const o=t.getScissorRect(),a=null!==o&&(o.width<=0||o.height<=0);if(null===o||a||n.setScissorRect(o.x,o.y,o.width,o.height),!a)for(let r=0;r<this._drawCallCount;r++){const o=this._drawCalls[r],a=o.shape,h=a.geometry.vertices,l=this._resolveDrawCall(a);if(null===l)continue;const u=this._getPipeline({topology:l.topology,usesStripIndex:l.usesStripIndex,blendMode:o.blendMode,format:t.renderTargetFormat});this._ensureVertexCapacity(l.vertexCount),this._writeVertexData(h,a.color.toRgba()),this._writeTransformData(t,a),e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,12*l.vertexCount),e.queue.writeBuffer(s,0,this._transformData.buffer,this._transformData.byteOffset,this._transformData.byteLength),n.setPipeline(u),n.setBindGroup(0,i),n.setVertexBuffer(0,this._vertexBuffer),null!==l.indices&&l.indexCount>0?(this._ensureIndexCapacity(l.indexCount),e.queue.writeBuffer(this._indexBuffer,0,l.indices.buffer,l.indices.byteOffset,l.indexCount*Uint16Array.BYTES_PER_ELEMENT),n.setIndexBuffer(this._indexBuffer,"uint16"),n.drawIndexed(l.indexCount)):n.draw(l.vertexCount),t.stats.batches++,t.stats.drawCalls++}n.end(),t.submit(r.finish()),this._drawCallCount=0}destroy(){this.disconnect(),this._combinedTransform.destroy()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct TransformUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> uniforms: TransformUniforms;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = uniforms.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return input.color;\n}\n"}),this._bindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._bindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._bindGroup=this._device.createBindGroup({layout:this._bindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]})}onDisconnect(){this.flush(),this._destroyBuffers(),this._pipelines.clear(),this._uniformBuffer?.destroy(),this._uniformBuffer=null,this._bindGroup=null,this._bindGroupLayout=null,this._pipelineLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._drawCallCount=0}_writeTransformData(t,e){const i=this._combinedTransform.copy(t.view.getTransform()).combine(e.getGlobalTransform());this._transformData.set([i.a,i.c,0,0,i.b,i.d,0,0,0,0,1,0,i.x,i.y,0,i.z])}_writeVertexData(t,e){const i=t.length/2;for(let s=0;s<i;s++){const i=2*s,r=3*s;this._float32View[r]=t[i],this._float32View[r+1]=t[i+1],this._uint32View[r+2]=e}}_ensureVertexCapacity(t){const e=12*t;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?12:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(t),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,0===this._vertexBufferCapacity?12:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(t){const e=t*Uint16Array.BYTES_PER_ELEMENT;e>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(e,0===this._indexBufferCapacity?Uint16Array.BYTES_PER_ELEMENT:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_getPipeline(t){const e=`${t.topology}:${t.usesStripIndex?1:0}:${t.blendMode}:${t.format}`,i=this._pipelines.get(e);if(i)return i;const s=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:12,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t.format,blend:ei(t.blendMode),writeMask:GPUColorWrite.ALL}]},primitive:{topology:t.topology,stripIndexFormat:t.usesStripIndex?"uint16":void 0}});return this._pipelines.set(e,s),s}_getTopology(t){switch(t){case tt.Points:return"point-list";case tt.Lines:return"line-list";case tt.LineLoop:case tt.LineStrip:return"line-strip";case tt.Triangles:case tt.TriangleFan:return"triangle-list";case tt.TriangleStrip:return"triangle-strip";default:throw new Error(`WebGPU primitive renderer does not support draw mode "${t}" yet.`)}}_resolveDrawCall(t){const e=t.geometry.vertices.length/2;if(0===e)return null;switch(t.drawMode){case tt.LineLoop:return this._resolveLineLoopDrawCall(t.geometry.indices,e);case tt.TriangleFan:return this._resolveTriangleFanDrawCall(t.geometry.indices,e);default:{const i=t.geometry.indices,s=this._getTopology(t.drawMode),r=i.length,n=r>0&&(t.drawMode===tt.LineStrip||t.drawMode===tt.TriangleStrip);return r>0?{topology:s,usesStripIndex:n,vertexCount:e,indices:i,indexCount:r}:{topology:s,usesStripIndex:n,vertexCount:e,indices:null,indexCount:0}}}}_resolveLineLoopDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),s=i.length;if(s<2)return null;const r=s+1,n=this._ensureGeneratedIndexCapacity(r);return n.set(i.subarray(0,s),0),n[s]=i[0],{topology:"line-strip",usesStripIndex:!0,vertexCount:e,indices:n,indexCount:r}}_resolveTriangleFanDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),s=i.length;if(s<3)return null;const r=3*(s-2),n=this._ensureGeneratedIndexCapacity(r);let o=0;for(let t=1;t<s-1;t++)n[o++]=i[0],n[o++]=i[t],n[o++]=i[t+1];return{topology:"triangle-list",usesStripIndex:!1,vertexCount:e,indices:n,indexCount:r}}_getSequentialIndices(t){if(t>this._sequentialIndexData.length){let e=Math.max(1,this._sequentialIndexData.length);for(;e<t;)e*=2;this._sequentialIndexData=new Uint16Array(e)}for(let e=0;e<t;e++)this._sequentialIndexData[e]=e;return this._sequentialIndexData.subarray(0,t)}_ensureGeneratedIndexCapacity(t){if(t>this._generatedIndexData.length){let e=Math.max(1,this._generatedIndexData.length);for(;e<t;)e*=2;this._generatedIndexData=new Uint16Array(e)}return this._generatedIndexData.subarray(0,t)}_destroyBuffers(){this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0}}const si=28/Uint32Array.BYTES_PER_ELEMENT;class ri extends ti{constructor(){super(...arguments),this._drawCalls=[],this._drawCallCount=0,this._projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT),this._renderManager=null,this._device=null,this._shaderModule=null,this._uniformBindGroupLayout=null,this._textureBindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._vertexBuffer=null,this._indexBuffer=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._pipelines=new Map}onConnect(t){this._renderManager||(this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar spriteTexture0: texture_2d<f32>;\n@group(1) @binding(1)\nvar spriteTexture1: texture_2d<f32>;\n@group(1) @binding(2)\nvar spriteTexture2: texture_2d<f32>;\n@group(1) @binding(3)\nvar spriteTexture3: texture_2d<f32>;\n@group(1) @binding(4)\nvar spriteTexture4: texture_2d<f32>;\n@group(1) @binding(5)\nvar spriteTexture5: texture_2d<f32>;\n@group(1) @binding(6)\nvar spriteTexture6: texture_2d<f32>;\n@group(1) @binding(7)\nvar spriteTexture7: texture_2d<f32>;\n\n@group(1) @binding(8)\nvar spriteSampler0: sampler;\n@group(1) @binding(9)\nvar spriteSampler1: sampler;\n@group(1) @binding(10)\nvar spriteSampler2: sampler;\n@group(1) @binding(11)\nvar spriteSampler3: sampler;\n@group(1) @binding(12)\nvar spriteSampler4: sampler;\n@group(1) @binding(13)\nvar spriteSampler5: sampler;\n@group(1) @binding(14)\nvar spriteSampler6: sampler;\n@group(1) @binding(15)\nvar spriteSampler7: sampler;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n @location(3) premultiplySample: u32,\n @location(4) textureSlot: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n @location(3) @interpolate(flat) textureSlot: u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n output.premultiplySample = input.premultiplySample;\n output.textureSlot = input.textureSlot;\n\n return output;\n}\n\nfn sampleTexture(slot: u32, uv: vec2<f32>) -> vec4<f32> {\n switch slot {\n case 0u: {\n return textureSample(spriteTexture0, spriteSampler0, uv);\n }\n case 1u: {\n return textureSample(spriteTexture1, spriteSampler1, uv);\n }\n case 2u: {\n return textureSample(spriteTexture2, spriteSampler2, uv);\n }\n case 3u: {\n return textureSample(spriteTexture3, spriteSampler3, uv);\n }\n case 4u: {\n return textureSample(spriteTexture4, spriteSampler4, uv);\n }\n case 5u: {\n return textureSample(spriteTexture5, spriteSampler5, uv);\n }\n case 6u: {\n return textureSample(spriteTexture6, spriteSampler6, uv);\n }\n default: {\n return textureSample(spriteTexture7, spriteSampler7, uv);\n }\n }\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = sampleTexture(input.textureSlot, input.texcoord);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n\n return resolvedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[...Array.from({length:8},(t,e)=>({binding:e,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(t,e)=>({binding:8+e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}))]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._ensureBatchCapacity(32))}onDisconnect(){this.flush(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._vertexBuffer=null,this._indexBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._drawCallCount=0}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof je)&&!(i instanceof _e)||0===i.width||0===i.height||i instanceof je&&null===i.source)return;e.setBlendMode(t.blendMode);const s=this._drawCallCount++,r=this._drawCalls[s];r?(r.sprite=t,r.texture=i,r.color=t.tint.toRgba(),r.blendMode=t.blendMode):this._drawCalls.push({sprite:t,texture:i,color:t.tint.toRgba(),blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,s=this._uniformBindGroup,r=this._vertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&s&&r&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;const o=t.view.getTransform();this._projectionData.set([o.a,o.c,0,0,o.b,o.d,0,0,0,0,1,0,o.x,o.y,0,o.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const a=e.createCommandEncoder(),h=a.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const l=t.getScissorRect(),u=null!==l&&(l.width<=0||l.height<=0);if(null===l||u||h.setScissorRect(l.x,l.y,l.width,l.height),this._drawCallCount>0&&!u){h.setBindGroup(0,s),h.setVertexBuffer(0,this._vertexBuffer),h.setIndexBuffer(this._indexBuffer,"uint32");for(let i=0;i<this._drawCallCount;){const s=this._getBatchRange(i),r=this._getPipeline(s.blendMode,t.renderTargetFormat),n=s.end-s.start;this._ensureBatchCapacity(n),this._writeBatchVertexData(s),e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,4*n*28);const o=this._createTextureBindGroup(e,t,s.textures);h.setPipeline(r),h.setBindGroup(1,o),h.drawIndexed(6*s.spriteCount,1,0,0,0),t.stats.batches++,t.stats.drawCalls++,i=s.end}}h.end(),t.submit(a.finish()),this._drawCallCount=0}destroy(){this.disconnect()}_ensureBatchCapacity(t){if(!this._device||t<=this._vertexCapacity)return;let e=Math.max(this._vertexCapacity,32);for(;e<t;)e*=2;const i=new ArrayBuffer(4*e*28),s=this._device.createBuffer({size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),r=new Uint32Array(6*e),n=this._device.createBuffer({size:r.byteLength*Uint32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});for(let t=0;t<e;t++){const e=4*t,i=6*t;r[i]=e,r[i+1]=e+1,r[i+2]=e+2,r[i+3]=e,r[i+4]=e+2,r[i+5]=e+3}this._device.queue.writeBuffer(n,0,r.buffer,r.byteOffset,r.byteLength),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexCapacity=e,this._vertexData=i,this._float32View=new Float32Array(i),this._uint32View=new Uint32Array(i),this._vertexBuffer=s,this._indexBuffer=n}_writeBatchVertexData(t){const e=this._renderManager;if(!e)return;let i=0;for(let s=t.start;s<t.end;s++){const r=this._drawCalls[s],n=t.textureSlots.get(r.texture)??0,o=e.shouldPremultiplyTextureSample(r.texture)?1:0,a=r.sprite.vertices,h=r.sprite.texCoords;for(let t=0;t<4;t++){const e=2*t,s=h[t];this._float32View[i]=a[e],this._float32View[i+1]=a[e+1],this._float32View[i+2]=(65535&s)/65535,this._float32View[i+3]=(s>>>16&65535)/65535,this._uint32View[i+4]=r.color,this._uint32View[i+5]=o,this._uint32View[i+6]=n,i+=si}}}_getBatchRange(t){const e=this._drawCalls[t],i=new Map,s=new Array;let r=t+1;for(i.set(e.texture,0),s.push(e.texture);r<this._drawCallCount;){const t=this._drawCalls[r];if(t.blendMode!==e.blendMode)break;if(!i.has(t.texture)){if(s.length>=8)break;i.set(t.texture,s.length),s.push(t.texture)}if(i.size>8)break;r++}return{start:t,end:r,spriteCount:r-t,blendMode:e.blendMode,textures:s,textureSlots:i}}_createTextureBindGroup(t,e,i){const s=i[0],r=e.getTextureBinding(s),n=[],o=new Array(8);for(let t=0;t<8;t++){const n=i[t]??s,a=n===s?r:e.getTextureBinding(n);o[t]=a}for(let t=0;t<8;t++)n.push({binding:t,resource:o[t].view});for(let t=0;t<8;t++)n.push({binding:8+t,resource:o[t].sampler});return t.createBindGroup({layout:this._textureBindGroupLayout,entries:n})}_getPipeline(t,e){const i=`${t}:${e}`,s=this._pipelines.get(i);if(s)return s;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._renderManager))throw new Error("Renderer has to be connected first!");const r=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"},{shaderLocation:3,offset:20,format:"uint32"},{shaderLocation:4,offset:24,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:ei(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,r),r}}const ni=56,oi=new Float32Array([0,0,1,0,1,1,0,1]),ai=new Uint16Array([0,1,2,0,2,3]);class hi extends ti{constructor(){super(...arguments),this._drawCalls=[],this._drawCallCount=0,this._uniformData=new Float32Array(144/Float32Array.BYTES_PER_ELEMENT),this._renderManager=null,this._device=null,this._shaderModule=null,this._uniformBindGroupLayout=null,this._textureBindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._indexBuffer=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._pipelines=new Map}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof je)||null===i.source||0===i.width||0===i.height||0===t.particles.length)return;e.setBlendMode(t.blendMode);const s=this._drawCallCount++,r=this._drawCalls[s];r?(r.system=t,r.texture=i,r.blendMode=t.blendMode):this._drawCalls.push({system:t,texture:i,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,s=this._uniformBindGroup,r=this._staticVertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&s&&r&&this._instanceBuffer&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;const o=e.createCommandEncoder(),a=o.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const h=t.getScissorRect(),l=null!==h&&(h.width<=0||h.height<=0);if(null===h||l||a.setScissorRect(h.x,h.y,h.width,h.height),!l){a.setBindGroup(0,s);for(let s=0;s<this._drawCallCount;s++){const o=this._drawCalls[s],h=o.system,l=h.particles.length;if(0===l)continue;const u=this._getPipeline(o.blendMode,t.renderTargetFormat),c=t.getTextureBinding(o.texture),d=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:c.view},{binding:1,resource:c.sampler}]});this._ensureCapacity(l),this._writeInstanceData(h.vertices,h.texCoords,h.particles),this._writeUniformData(t,h,o.texture),e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,l*ni),e.queue.writeBuffer(i,0,this._uniformData.buffer,this._uniformData.byteOffset,this._uniformData.byteLength),a.setPipeline(u),a.setBindGroup(1,d),a.setVertexBuffer(0,r),a.setVertexBuffer(1,this._instanceBuffer),a.setIndexBuffer(n,"uint16"),a.drawIndexed(6,l,0,0,0),t.stats.batches++,t.stats.drawCalls++}}a.end(),t.submit(o.finish()),this._drawCallCount=0}destroy(){this.disconnect()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n projection: mat4x4<f32>,\n translation: mat4x4<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> uniforms: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar particleTexture: texture_2d<f32>;\n\n@group(1) @binding(1)\nvar particleSampler: sampler;\n\nstruct VertexInput {\n @location(0) unitPosition: vec2<f32>,\n @location(1) quadMin: vec2<f32>,\n @location(2) quadSize: vec2<f32>,\n @location(3) uvMin: vec2<f32>,\n @location(4) uvMax: vec2<f32>,\n @location(5) translation: vec2<f32>,\n @location(6) scale: vec2<f32>,\n @location(7) rotation: f32,\n @location(8) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let localPosition = input.quadMin + (input.unitPosition * input.quadSize);\n let radians = radians(input.rotation);\n let sinValue = sin(radians);\n let cosValue = cos(radians);\n let rotated = vec2<f32>(\n (localPosition.x * (input.scale.x * cosValue)) + (localPosition.y * (input.scale.y * sinValue)) + input.translation.x,\n (localPosition.x * (input.scale.x * -sinValue)) + (localPosition.y * (input.scale.y * cosValue)) + input.translation.y\n );\n\n var output: VertexOutput;\n\n output.position = uniforms.projection * uniforms.translation * vec4<f32>(rotated, 0.0, 1.0);\n output.texcoord = input.uvMin + ((input.uvMax - input.uvMin) * input.unitPosition);\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(particleTexture, particleSampler, input.texcoord);\n let premultipliedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), uniforms.flags.x > 0.5);\n\n return premultipliedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:144,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._staticVertexBuffer=this._device.createBuffer({size:oi.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._staticVertexBuffer,0,oi.buffer,oi.byteOffset,oi.byteLength),this._indexBuffer=this._device.createBuffer({size:ai.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,ai.buffer,ai.byteOffset,ai.byteLength),this._ensureCapacity(1)}onDisconnect(){this.flush(),this._staticVertexBuffer?.destroy(),this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._indexBuffer=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._drawCallCount=0}_ensureCapacity(t){const e=t*ni;if(e>this._instanceData.byteLength){let t=this._instanceData.byteLength;for(;t<e;)t*=2;this._instanceData=new ArrayBuffer(t),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData)}if(e>this._instanceBufferByteLength){let t=this._instanceBufferByteLength||ni;for(;t<e;)t*=2;this._instanceBuffer?.destroy(),this._instanceBuffer=this._device.createBuffer({size:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._instanceBufferByteLength=t}}_writeUniformData(t,e,i){const s=t.view.getTransform().toArray(!1),r=e.getGlobalTransform().toArray(!1),n=t.shouldPremultiplyTextureSample(i);this._uniformData.set([s[0],s[1],0,0,s[3],s[4],0,0,0,0,1,0,s[6],s[7],0,s[8],r[0],r[1],0,0,r[3],r[4],0,0,0,0,1,0,r[6],r[7],0,r[8],n?1:0,0,0,0])}_writeInstanceData(t,e,i){const s=t[0],r=t[1],n=t[2]-t[0],o=t[3]-t[1],a=(65535&e[0])/65535,h=(e[0]>>>16&65535)/65535,l=(65535&e[2])/65535,u=(e[2]>>>16&65535)/65535;for(let t=0;t<i.length;t++){const e=i[t],c=14*t;this._float32View[c]=s,this._float32View[c+1]=r,this._float32View[c+2]=n,this._float32View[c+3]=o,this._float32View[c+4]=a,this._float32View[c+5]=h,this._float32View[c+6]=l,this._float32View[c+7]=u,this._float32View[c+8]=e.position.x,this._float32View[c+9]=e.position.y,this._float32View[c+10]=e.scale.x,this._float32View[c+11]=e.scale.y,this._float32View[c+12]=e.rotation,this._uint32View[c+13]=e.tint.toRgba()}}_getPipeline(t,e){const i=`${t}:${e}`,s=this._pipelines.get(i);if(s)return s;const r=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:ni,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x2"},{shaderLocation:2,offset:8,format:"float32x2"},{shaderLocation:3,offset:16,format:"float32x2"},{shaderLocation:4,offset:24,format:"float32x2"},{shaderLocation:5,offset:32,format:"float32x2"},{shaderLocation:6,offset:40,format:"float32x2"},{shaderLocation:7,offset:48,format:"float32"},{shaderLocation:8,offset:52,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:ei(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,r),r}}const li="rgba8unorm";class ui{constructor(t){this.backendType=Se.WebGpu,this.rendererRegistry=new Ye,this._clearColor=new K,this._textureStates=new Map,this._textureDestroyHandlers=new Map,this._renderTargetDestroyHandlers=new Map,this._temporaryRenderTextures=[],this._maskStack=[],this._maskPixelStack=[],this._maskPointA=new ce,this._maskPointB=new ce,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._renderer=null,this._blendMode=null,this._texture=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};const{width:e,height:i,clearColor:s}=t.options;this._canvas=t.canvas,this._rootRenderTarget=new de(e,i,!0),this._renderTarget=this._rootRenderTarget,s&&this._clearColor.copy(s),this.rendererRegistry.registerRenderer(ye,new ii),this.rendererRegistry.registerRenderer(qe,new ri),this.rendererRegistry.registerRenderer(Xe,new hi),this.resize(e,i)}get view(){return this._renderTarget.view}get renderTarget(){return this._renderTarget}get device(){if(null===this._device)throw new Error("WebGPU device is not initialized yet.");return this._device}get context(){if(null===this._context)throw new Error("WebGPU canvas context is not initialized yet.");return this._context}get format(){if(null===this._format)throw new Error("WebGPU canvas format is not initialized yet.");return this._format}get renderTargetFormat(){return this._renderTarget===this._rootRenderTarget?this.format:li}get clearRequested(){return this._clearRequested}get stats(){return this._stats}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(t=>{throw this._initializePromise=null,t})),this._initializePromise}resetStats(){return Ke(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setShader(t){if(null!==t)throw new Error("WebGPU shaders are not implemented yet.");return this}setTexture(t,e){if(null===t)return this._texture=null,this;if(t instanceof de&&!(t instanceof _e))throw new Error("WebGPU render textures are not implemented yet.");return this._syncTexture(t),this._texture=t,this}setBlendMode(t){if(null===t)return this._blendMode=null,this;if(t!==Q.Normal&&t!==Q.Additive&&t!==Q.Subtract&&t!==Q.Multiply&&t!==Q.Screen)throw new Error(`WebGPU blend mode "${t}" is not implemented yet.`);return this._blendMode=t,this}setVao(t){if(null!==t)throw new Error("WebGPU vertex array objects are not implemented yet.");return this}setRenderTarget(t){const e=t??this._rootRenderTarget;if(!(e.root||e instanceof _e))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");return this._renderTarget!==e&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=e,this._stats.renderTargetChanges++,e!==this._rootRenderTarget&&this._subscribeRenderTarget(e)),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,s=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(s),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this}getScissorRect(){if(0===this._maskPixelStack.length)return null;const t=this._maskPixelStack[this._maskPixelStack.length-1];return{x:t.x,y:t.y,width:t.width,height:t.height}}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const s=this._temporaryRenderTextures[i];if(s.width===t&&s.height===e)return this._temporaryRenderTextures.splice(i,1),s}return new _e(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this}clear(t){return t&&this._clearColor.copy(t),this._clearRequested=!0,this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._hasPresentedFrame=!1,this}flush(){if(!this._device||!this._context)return this;if(this._renderer)this._flushActiveRenderer();else if(this._clearRequested){const t=this._device.createCommandEncoder();t.beginRenderPass({colorAttachments:[this.createColorAttachment()]}).end(),this._stats.renderPasses++,this.submit(t.finish())}return this}destroy(){this._setActiveRenderer(null),this.rendererRegistry.destroy(),this._destroyManagedTextures(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy();for(const t of Array.from(this._renderTargetDestroyHandlers.keys()))this._unsubscribeRenderTarget(t);this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._texture=null,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._renderTarget=this._rootRenderTarget,this._clearColor.destroy(),this._rootRenderTarget.destroy()}createColorAttachment(){const t=this._renderTarget;let e=null;if(t===this._rootRenderTarget)e={view:this.context.getCurrentTexture().createView(),shouldClear:this._clearRequested||!this._hasPresentedFrame};else{if(!(t instanceof _e))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");{const i=this._syncTexture(t);e={view:i.view,shouldClear:this._clearRequested||!i.hasContent}}}return this._clearRequested=!1,{view:e.view,clearValue:{r:this._clearColor.r/255,g:this._clearColor.g/255,b:this._clearColor.b/255,a:this._clearColor.a},loadOp:e.shouldClear?"clear":"load",storeOp:"store"}}submit(t){if(this.device.queue.submit([t]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof _e){const t=this._syncTexture(this._renderTarget);t.hasContent=!0,t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}}getTextureBinding(t){const e=this._syncTexture(t);return{view:e.view,sampler:e.sampler}}shouldPremultiplyTextureSample(t){return!(t instanceof _e)&&t.premultiplyAlpha}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer?.flush()}async _initialize(){const t=this._getGpuNavigator();if(null===t)throw new Error("This browser does not support WebGPU.");if("function"!=typeof t.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof t.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");const e=this._canvas.getContext("webgpu");if(null===e)throw new Error("Could not create WebGPU canvas context.");let i=null;try{i=await t.gpu.requestAdapter()}catch(t){throw this._createInitializationError("Failed to request a WebGPU adapter.",t)}if(null===i)throw new Error("Could not acquire a WebGPU adapter.");if("function"!=typeof i.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");let s=null;try{s=await i.requestDevice()}catch(t){throw this._createInitializationError("Failed to request a WebGPU device.",t)}if(null===s)throw new Error("Could not acquire a WebGPU device.");const r=t.gpu.getPreferredCanvasFormat();try{e.configure({device:s,format:r,alphaMode:"opaque"})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}return this._context=e,this._device=s,this._format=r,this._blendMode=Q.Normal,this._hasPresentedFrame=!1,this.rendererRegistry.connect(this),this.resize(this._canvas.width,this._canvas.height),this}_getGpuNavigator(){const t=navigator;return t.gpu?t:null}_createInitializationError(t,e){return e instanceof Error&&e.message.length>0?new Error(`${t} ${e.message}`):new Error(t)}_destroyManagedTextures(){for(const t of Array.from(this._textureStates.keys()))this._evictTexture(t)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getTextureState(t){let e=this._textureStates.get(t);if(!e){const i=this.device.createTexture({size:{width:Math.max(t.width,1),height:Math.max(t.height,1)},format:li,mipLevelCount:this._getMipLevelCount(t),usage:this._getTextureUsage(t)});e={texture:i,view:i.createView(),sampler:this._createSampler(t),version:-1,width:t.width,height:t.height,mipLevelCount:this._getMipLevelCount(t),hasContent:!1};const s=()=>{this._evictTexture(t)};t.addDestroyListener(s),this._textureDestroyHandlers.set(t,s),this._textureStates.set(t,e)}return e}_syncTexture(t){if(!(t instanceof _e||null!==t.source&&0!==t.width&&0!==t.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const e=this._getTextureState(t),i=t instanceof _e?t.textureVersion:t.version,s=this._getMipLevelCount(t);if(e.version!==i){if(e.width!==t.width||e.height!==t.height||e.mipLevelCount!==s){e.texture.destroy();const i=this.device.createTexture({size:{width:t.width,height:t.height},format:li,mipLevelCount:s,usage:this._getTextureUsage(t)});e.texture=i,e.view=i.createView(),e.width=t.width,e.height=t.height,e.mipLevelCount=s,e.hasContent=!1}if(e.sampler=this._createSampler(t),!(t instanceof _e)){const i=t.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:e.texture},{width:t.width,height:t.height}),e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}e.version=i}return e}_evictTexture(t){const e=this._textureStates.get(t),i=this._textureDestroyHandlers.get(t);i&&(t.removeDestroyListener(i),this._textureDestroyHandlers.delete(t)),e&&(e.texture.destroy(),this._textureStates.delete(t)),this._texture===t&&(this._texture=null)}_subscribeRenderTarget(t){if(!this._renderTargetDestroyHandlers.has(t)){const e=()=>{this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget),this._renderTargetDestroyHandlers.delete(t)};t.addDestroyListener(e),this._renderTargetDestroyHandlers.set(t,e)}}_unsubscribeRenderTarget(t){const e=this._renderTargetDestroyHandlers.get(t);e&&(t.removeDestroyListener(e),this._renderTargetDestroyHandlers.delete(t))}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),s=Math.min(e.x,i.x),r=Math.max(e.x,i.x),n=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(s))),u=Math.max(0,Math.min(a,Math.ceil(r))),c=Math.max(0,Math.min(h,Math.floor(n))),d=Math.max(0,Math.min(h,Math.ceil(o)));return{x:l,y:c,width:Math.max(0,u-l),height:Math.max(0,d-c)}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),s=Math.max(t.y,e.y),r=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:s,width:Math.max(0,r-i),height:Math.max(0,n-s)}}_createSampler(t){return this.device.createSampler({addressModeU:this._getAddressMode(t.wrapMode),addressModeV:this._getAddressMode(t.wrapMode),magFilter:this._getFilterMode(t.scaleMode),minFilter:this._getFilterMode(t.scaleMode),mipmapFilter:this._getMipmapFilterMode(t.scaleMode)})}_getTextureUsage(t){const e=this._getMipLevelCount(t)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return t instanceof _e?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|e:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|e}_getAddressMode(t){switch(t){case J.Repeat:return"repeat";case J.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case Z.Nearest:case Z.NearestMipmapNearest:case Z.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case Z.NearestMipmapLinear:case Z.LinearMipmapLinear:return"linear";default:return"nearest"}}_getMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_generateMipmaps(t,e){if(e<=1)return;const i=this._getMipmapResources(),s=this.device.createCommandEncoder();for(let r=1;r<e;r++){const e=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:t.createView({baseMipLevel:r-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),n=s.beginRenderPass({colorAttachments:[{view:t.createView({baseMipLevel:r,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});n.setPipeline(i.pipeline),n.setBindGroup(0,e),n.draw(3),n.end()}this.device.queue.submit([s.finish()])}_getMipmapResources(){return null!==this._mipmapShaderModule&&null!==this._mipmapBindGroupLayout&&null!==this._mipmapPipelineLayout&&null!==this._mipmapPipeline&&null!==this._mipmapSampler||(this._mipmapShaderModule=this.device.createShaderModule({code:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@group(0) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(0) @binding(1)\nvar sourceSampler: sampler;\n\n@vertex\nfn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0)\n );\n var texcoords = array<vec2<f32>, 3>(\n vec2<f32>(0.0, 0.0),\n vec2<f32>(2.0, 0.0),\n vec2<f32>(0.0, 2.0)\n );\n var output: VertexOutput;\n\n output.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);\n output.texcoord = texcoords[vertexIndex];\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(sourceTexture, sourceSampler, input.texcoord);\n}\n"}),this._mipmapBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._mipmapPipelineLayout=this.device.createPipelineLayout({bindGroupLayouts:[this._mipmapBindGroupLayout]}),this._mipmapPipeline=this.device.createRenderPipeline({layout:this._mipmapPipelineLayout,vertex:{module:this._mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this._mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:li,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}}),this._mipmapSampler=this.device.createSampler({minFilter:"linear",magFilter:"linear",mipmapFilter:"nearest"})),{bindGroupLayout:this._mipmapBindGroupLayout,pipeline:this._mipmapPipeline,sampler:this._mipmapSampler}}}var ci,di,_i,pi,fi,mi;!function(t){t[t.Container=768]="Container",t[t.Category=256]="Category",t[t.Gamepad=64]="Gamepad"}(ci||(ci={})),function(t){t[t.Backspace=8]="Backspace",t[t.Tab=9]="Tab",t[t.Clear=12]="Clear",t[t.Enter=13]="Enter",t[t.Shift=16]="Shift",t[t.Control=17]="Control",t[t.Alt=18]="Alt",t[t.Pause=19]="Pause",t[t.CapsLock=20]="CapsLock",t[t.Escape=27]="Escape",t[t.Space=32]="Space",t[t.PageUp=33]="PageUp",t[t.PageDown=34]="PageDown",t[t.End=35]="End",t[t.Home=36]="Home",t[t.Left=37]="Left",t[t.Up=38]="Up",t[t.Right=39]="Right",t[t.Down=40]="Down",t[t.Insert=45]="Insert",t[t.Delete=46]="Delete",t[t.Help=47]="Help",t[t.Zero=48]="Zero",t[t.One=49]="One",t[t.Two=50]="Two",t[t.Three=51]="Three",t[t.Four=52]="Four",t[t.Five=53]="Five",t[t.Six=54]="Six",t[t.Seven=55]="Seven",t[t.Eight=56]="Eight",t[t.Nine=57]="Nine",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.NumPad0=96]="NumPad0",t[t.NumPad1=97]="NumPad1",t[t.NumPad2=98]="NumPad2",t[t.NumPad3=99]="NumPad3",t[t.NumPad4=100]="NumPad4",t[t.NumPad5=101]="NumPad5",t[t.NumPad6=102]="NumPad6",t[t.NumPad7=103]="NumPad7",t[t.NumPad8=104]="NumPad8",t[t.NumPad9=105]="NumPad9",t[t.NumPadMultiply=106]="NumPadMultiply",t[t.NumPadAdd=107]="NumPadAdd",t[t.NumPadEnter=108]="NumPadEnter",t[t.NumPadSubtract=109]="NumPadSubtract",t[t.NumPadDecimal=110]="NumPadDecimal",t[t.NumPadDivide=111]="NumPadDivide",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NumLock=144]="NumLock",t[t.ScrollLock=145]="ScrollLock",t[t.Colon=186]="Colon",t[t.Equals=187]="Equals",t[t.Comma=188]="Comma",t[t.Dash=189]="Dash",t[t.Period=190]="Period",t[t.QuestionMark=191]="QuestionMark",t[t.Tilde=192]="Tilde",t[t.OpenBracket=219]="OpenBracket",t[t.BackwardSlash=220]="BackwardSlash",t[t.ClosedBracket=221]="ClosedBracket",t[t.Quotes=222]="Quotes"}(di||(di={}));class gi{constructor(t,e,i){this.onConnect=new F,this.onDisconnect=new F,this.onUpdate=new F,this.browserGamepad=null,this.info={name:"Generic Gamepad",label:"Generic Gamepad",vendorId:null,productId:null,productKey:null};const s="number"!=typeof t,r=s?t:null,n=s?t.index:t;if(this.indexValue=n,this.channelsValue=e,this.channelOffset=512+n*ci.Gamepad,this.mappingValue=r?i.mapping:i,r){const t=i;this.setInfo({name:t.name,label:t.descriptor.label,vendorId:t.descriptor.vendorId,productId:t.descriptor.productId,productKey:t.descriptor.productKey}),this.connect(r)}}get mapping(){return this.mappingValue}set mapping(t){this.mappingValue=t}get mappingFamily(){return this.mappingValue.family}get channels(){return this.channelsValue}get gamepad(){return this.browserGamepad}get index(){return this.indexValue}get connected(){return null!==this.browserGamepad}get name(){return this.info.name}get label(){return this.info.label}get vendorId(){return this.info.vendorId}get productId(){return this.info.productId}get productKey(){return this.info.productKey}setInfo(t){return this.info=t,this}connect(t){const e=this.connected;return this.browserGamepad=t,e||this.onConnect.dispatch(this),this}disconnect(){return this.connected&&(this.browserGamepad=null,this.clearMappedChannels(),this.onDisconnect.dispatch(this)),this}update(){if(null===this.browserGamepad)return this;const t=this.channelsValue,{buttons:e,axes:i}=this.browserGamepad;for(const i of this.mappingValue.buttons){const s=this.resolveChannelOffset(i.channel);if(i.index<e.length){const r=i.transformValue(e[i.index].value)||0;t[s]!==r&&(t[s]=r,this.onUpdate.dispatch(i.channel,r,this))}}for(const e of this.mappingValue.axes){const s=this.resolveChannelOffset(e.channel);if(e.index<i.length){const r=e.transformValue(i[e.index])||0;t[s]!==r&&(t[s]=r,this.onUpdate.dispatch(e.channel,r,this))}}return this}clearChannels(){return this.clearMappedChannels(),this}destroy(){this.disconnect(),this.clearMappedChannels(),this.onConnect.destroy(),this.onDisconnect.destroy(),this.onUpdate.destroy()}resolveChannelOffset(t){return this.channelOffset+(512^t)}static resolveChannelOffset(t,e){return 512+t*ci.Gamepad+(512^e)}clearMappedChannels(){for(const t of this.mappingValue.buttons)this.channelsValue[this.resolveChannelOffset(t.channel)]=0;for(const t of this.mappingValue.axes)this.channelsValue[this.resolveChannelOffset(t.channel)]=0}}!function(t){t[t.None=0]="None",t[t.Over=1]="Over",t[t.Leave=2]="Leave",t[t.Down=4]="Down",t[t.Move=8]="Move",t[t.Up=16]="Up",t[t.Cancel=32]="Cancel"}(_i||(_i={})),function(t){t[t.Unknown=0]="Unknown",t[t.InsideCanvas=1]="InsideCanvas",t[t.OutsideCanvas=2]="OutsideCanvas",t[t.Pressed=3]="Pressed",t[t.Moving=4]="Moving",t[t.Released=5]="Released",t[t.Cancelled=6]="Cancelled"}(pi||(pi={}));class yi{constructor(t,i){this.startPos=new ce(-1,-1),this.stateFlags=new ht,this._currentState=pi.Unknown;const{pointerId:s,pointerType:r,clientX:n,clientY:o,width:a,height:h,tiltX:l,tiltY:u,buttons:c,pressure:d,twist:_}=t,{left:p,top:f}=i.getBoundingClientRect();this._canvas=i,this.id=s,this.type=r,this.position=new ce(n-p,o-f),this.size=new e(a,h),this.tilt=new ce(l,u),this._buttons=c,this._pressure=d,this._rotation=_,this.stateFlags.push(_i.Over)}get x(){return this.position.x}get y(){return this.position.y}get width(){return this.size.width}get height(){return this.size.height}get buttons(){return this._buttons}get pressure(){return this._pressure}get rotation(){return this._rotation}get currentState(){return this._currentState}handleEnter(t){this.handleEvent(t),this._currentState=pi.InsideCanvas}handleLeave(t){this.handleEvent(t),this.stateFlags.push(_i.Leave),this._currentState=pi.OutsideCanvas}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(_i.Down),this._currentState=pi.Pressed}handleMove(t){this.handleEvent(t),this.stateFlags.push(_i.Move),this._currentState=pi.Moving}handleRelease(t){this.handleEvent(t),this.stateFlags.push(_i.Up),this._currentState=pi.Released}handleCancel(t){this.handleEvent(t),this.stateFlags.push(_i.Cancel),this._currentState=pi.Cancelled}destroy(){this.position.destroy(),this.startPos.destroy(),this.size.destroy(),this.tilt.destroy(),this._canvas=null}handleEvent(t){const{clientX:e,clientY:i,width:s,height:r,tiltX:n,tiltY:o,buttons:a,pressure:h,twist:l}=t,{left:u,top:c}=this._canvas.getBoundingClientRect();return this.position.set(e-u,i-c),this.size.set(s,r),this.tilt.set(n,o),this._buttons=a,this._pressure=h,this._rotation=l,this}}!function(t){t[t.ButtonSouth=512]="ButtonSouth",t[t.ButtonWest=513]="ButtonWest",t[t.ButtonEast=514]="ButtonEast",t[t.ButtonNorth=515]="ButtonNorth",t[t.LeftShoulder=516]="LeftShoulder",t[t.RightShoulder=517]="RightShoulder",t[t.LeftTrigger=518]="LeftTrigger",t[t.RightTrigger=519]="RightTrigger",t[t.Select=520]="Select",t[t.Start=521]="Start",t[t.LeftStick=522]="LeftStick",t[t.RightStick=523]="RightStick",t[t.DPadUp=524]="DPadUp",t[t.DPadDown=525]="DPadDown",t[t.DPadLeft=526]="DPadLeft",t[t.DPadRight=527]="DPadRight",t[t.Guide=528]="Guide",t[t.Share=529]="Share",t[t.Capture=530]="Capture",t[t.Touchpad=531]="Touchpad",t[t.Paddle1=532]="Paddle1",t[t.LeftStickLeft=533]="LeftStickLeft",t[t.LeftStickRight=534]="LeftStickRight",t[t.LeftStickUp=535]="LeftStickUp",t[t.LeftStickDown=536]="LeftStickDown",t[t.RightStickLeft=537]="RightStickLeft",t[t.RightStickRight=538]="RightStickRight",t[t.RightStickUp=539]="RightStickUp",t[t.RightStickDown=540]="RightStickDown",t[t.AuxiliaryAxis0Negative=541]="AuxiliaryAxis0Negative",t[t.AuxiliaryAxis0Positive=542]="AuxiliaryAxis0Positive",t[t.AuxiliaryAxis1Negative=543]="AuxiliaryAxis1Negative",t[t.AuxiliaryAxis1Positive=544]="AuxiliaryAxis1Positive",t[t.AuxiliaryAxis2Negative=545]="AuxiliaryAxis2Negative",t[t.AuxiliaryAxis2Positive=546]="AuxiliaryAxis2Positive",t[t.AuxiliaryAxis3Negative=547]="AuxiliaryAxis3Negative",t[t.AuxiliaryAxis3Positive=548]="AuxiliaryAxis3Positive"}(fi||(fi={}));class xi{constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=G(i.threshold??.2,0,1)}transformValue(t){let e=G(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),e>this.threshold?e:0}}!function(t){t.GenericDualAnalog="genericDualAnalog",t.Xbox="xbox",t.PlayStation="playStation",t.SwitchPro="switchPro",t.JoyConLeft="joyConLeft",t.JoyConRight="joyConRight",t.GameCube="gameCube",t.SteamController="steamController",t.ArcadeStick="arcadeStick"}(mi||(mi={}));class wi{constructor(t,e){this.buttons=t,this.axes=e}destroy(){this.buttons.length=0,this.axes.length=0}static createControls(t){return t.map(([t,e,i])=>new xi(t,e,i))}}const vi=[[0,fi.ButtonSouth],[1,fi.ButtonEast],[2,fi.ButtonWest],[3,fi.ButtonNorth],[4,fi.LeftShoulder],[5,fi.RightShoulder],[6,fi.LeftTrigger],[7,fi.RightTrigger],[8,fi.Select],[9,fi.Start],[12,fi.DPadUp],[13,fi.DPadDown],[14,fi.DPadLeft],[15,fi.DPadRight],[16,fi.Guide]];class bi extends wi{constructor(){super(wi.createControls(vi),[]),this.family=mi.ArcadeStick}}const Ti=[[0,fi.ButtonSouth],[1,fi.ButtonEast],[2,fi.ButtonWest],[3,fi.ButtonNorth],[4,fi.LeftShoulder],[5,fi.RightShoulder],[6,fi.LeftTrigger],[7,fi.RightTrigger],[8,fi.Select],[9,fi.Start],[10,fi.LeftStick],[11,fi.RightStick],[12,fi.DPadUp],[13,fi.DPadDown],[14,fi.DPadLeft],[15,fi.DPadRight],[16,fi.Guide],[17,fi.Share],[18,fi.Capture],[19,fi.Touchpad],[20,fi.Paddle1]],Si=[[0,fi.LeftStickLeft,{invert:!0}],[0,fi.LeftStickRight],[1,fi.LeftStickUp,{invert:!0}],[1,fi.LeftStickDown],[2,fi.RightStickLeft,{invert:!0}],[2,fi.RightStickRight],[3,fi.RightStickUp,{invert:!0}],[3,fi.RightStickDown],[4,fi.AuxiliaryAxis0Negative,{invert:!0}],[4,fi.AuxiliaryAxis0Positive],[5,fi.AuxiliaryAxis1Negative,{invert:!0}],[5,fi.AuxiliaryAxis1Positive],[6,fi.AuxiliaryAxis2Negative,{invert:!0}],[6,fi.AuxiliaryAxis2Positive],[7,fi.AuxiliaryAxis3Negative,{invert:!0}],[7,fi.AuxiliaryAxis3Positive]];class Ci extends wi{constructor(){super(wi.createControls(Ti),wi.createControls(Si)),this.family=mi.GenericDualAnalog}}class Mi extends Ci{constructor(){super(...arguments),this.family=mi.GameCube}}class Pi extends Ci{constructor(){super(...arguments),this.family=mi.JoyConLeft}}class Bi extends Ci{constructor(){super(...arguments),this.family=mi.JoyConRight}}class Ei extends Ci{constructor(){super(...arguments),this.family=mi.PlayStation}}class Ri extends Ci{constructor(){super(...arguments),this.family=mi.SteamController}}class Ai extends Ci{constructor(){super(...arguments),this.family=mi.SwitchPro}}class ki extends Ci{constructor(){super(...arguments),this.family=mi.Xbox}}const Li=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Fi=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,Di=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,Ii=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,Ni=(t,e,i)=>({ids:i,name:t,resolve:()=>({name:t,mapping:e()})}),Ui=t=>t.trim().toLowerCase(),Vi=t=>{const e=t.replace(Fi,"").replace(Li,"").replace(Ii,"").replace(Di,"").replace(/\s+/g," ").trim();return e.length>0?e:null},Oi=t=>{if(!t)return[];return(Array.isArray(t)?t:[t]).map(Ui)},Gi=(t,e)=>{if(!e)return!0;for(const i of Oi(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},zi=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=Fi.exec(t)||Li.exec(t)||Ii.exec(t)||Di.exec(t);return e?`${e[1].toLowerCase()}:${e[2].toLowerCase()}`:null})(e),s=i?.slice(0,4)??null,r=i?.slice(5)??null;return{id:t.id,index:t.index,label:e,vendorId:s,productId:r,productKey:i,name:Vi(e)}},Wi=(t,e)=>Gi(e,t.ids)?((t,e)=>{const i=t.resolve(e);return null==i?null:"mapping"in i?{descriptor:e,name:i.name??t.name??e.name??e.label,mapping:i.mapping}:{descriptor:e,name:t.name??e.name??e.label,mapping:i}})(t,e):null,qi=(t,e=Hi)=>{const i="connected"in t?zi(t):t;for(const t of e){const e=Wi(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new Ci}},Hi=[...[Ni("Xbox 360 Controller",()=>new ki,"045e:028e"),Ni("Xbox One Controller",()=>new ki,["045e:02d1","045e:02dd"]),Ni("Xbox Wireless Controller",()=>new ki,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),Ni("Xbox One Elite Controller",()=>new ki,"045e:02e3"),Ni("Xbox Elite Wireless Controller Series 2",()=>new ki,["045e:0b00","045e:0b05","045e:0b22"]),Ni("Xbox Series Controller",()=>new ki,["045e:0b12","045e:0b13"]),Ni("PlayStation 3 Controller",()=>new Ei,"054c:0268"),Ni("DualShock 4 Controller",()=>new Ei,["054c:05c4","054c:09cc","054c:0ba0"]),Ni("DualSense Controller",()=>new Ei,"054c:0ce6"),Ni("DualSense Edge Controller",()=>new Ei,"054c:0df2"),Ni("GameCube Controller Adapter",()=>new Mi,"057e:0337"),Ni("Joy-Con (L)",()=>new Pi,"057e:2006"),Ni("Joy-Con (R)",()=>new Bi,"057e:2007"),Ni("Joy-Con Charging Grip",()=>new Ai,"057e:200e"),Ni("Switch Pro Controller",()=>new Ai,"057e:2009"),Ni("Joy-Con 2 (L)",()=>new Pi,"057e:2066"),Ni("Joy-Con 2 (R)",()=>new Bi,"057e:2067"),Ni("Switch 2 Pro Controller",()=>new Ai,"057e:2069"),Ni("Switch 2 GameCube Controller",()=>new Mi,"057e:2073"),Ni("Steam Controller",()=>new Ri,["28de:1102","28de:1142"]),Ni("F310 Gamepad",()=>new Ci,"046d:c216"),Ni("F710 Gamepad",()=>new Ci,["046d:c219","046d:c21f"]),Ni("8BitDo P30 Controller",()=>new Ci,["2dc8:5107","2dc8:5108"]),Ni("8BitDo SF30 Pro Controller",()=>new Ai,["2dc8:3000","2dc8:6100","2dc8:6101"]),Ni("8BitDo SN30 Controller",()=>new Ai,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),Ni("8BitDo NES30 Controller",()=>new Ci,"2dc8:ab12"),Ni("PowerA Switch Controller",()=>new Ai,"20d6:a713"),Ni("PowerA OPS Pro Wireless Controller",()=>new Ci,"20d6:4033"),Ni("PowerA OPS Wireless Controller",()=>new Ci,"20d6:4026"),Ni("Nacon Revolution 3 Controller",()=>new Ei,"146b:0611"),Ni("Nacon Revolution Unlimited Pro Controller",()=>new Ei,"146b:0d08"),Ni("Nacon Revolution Infinity Controller",()=>new Ei,"146b:0d10"),Ni("Nacon Revolution 5 Pro Controller",()=>new Ei,["3285:0d17","3285:0d19"]),Ni("Razer Raiju Controller",()=>new Ei,"1532:1000"),Ni("Razer Raiju Mobile Controller",()=>new Ei,["1532:0705","1532:0707"]),Ni("Razer Raiju Tournament Edition Controller",()=>new Ei,["1532:1007","1532:100a"]),Ni("Razer Raiju Ultimate Controller",()=>new Ei,["1532:1004","1532:1009"]),Ni("Razer Raion Controller",()=>new bi,"1532:1100")],...[Ni("Microsoft Controller",()=>new ki,"045e"),Ni("Sony Controller",()=>new Ei,"054c")],Ni("Generic Gamepad",()=>new Ci)];var Xi;!function(t){t[t.None=0]="None",t[t.KeyDown=1]="KeyDown",t[t.KeyUp=2]="KeyUp",t[t.MouseWheel=4]="MouseWheel",t[t.PointerUpdate=8]="PointerUpdate"}(Xi||(Xi={}));class ji{constructor(t){this.channels=new Float32Array(ci.Container),this.inputs=new Set,this.pointers={},this.gamepadsValue=[],this.gamepadsByIndex=new Map,this.gamepadSlotsActive=new Uint8Array(ci.Category/ci.Gamepad),this.wheelOffset=new ce,this.flags=new ht,this.channelsPressed=[],this.channelsReleased=[],this.keyDownHandler=this.handleKeyDown.bind(this),this.keyUpHandler=this.handleKeyUp.bind(this),this.canvasFocusHandler=this.handleCanvasFocus.bind(this),this.canvasBlurHandler=this.handleCanvasBlur.bind(this),this.windowBlurHandler=this.handleWindowBlur.bind(this),this.mouseWheelHandler=this.handleMouseWheel.bind(this),this.pointerOverHandler=this.handlePointerOver.bind(this),this.pointerLeaveHandler=this.handlePointerLeave.bind(this),this.pointerDownHandler=this.handlePointerDown.bind(this),this.pointerMoveHandler=this.handlePointerMove.bind(this),this.pointerUpHandler=this.handlePointerUp.bind(this),this.pointerCancelHandler=this.handlePointerCancel.bind(this),this.onPointerEnter=new F,this.onPointerLeave=new F,this.onPointerDown=new F,this.onPointerMove=new F,this.onPointerUp=new F,this.onPointerTap=new F,this.onPointerSwipe=new F,this.onPointerCancel=new F,this.onMouseWheel=new F,this.onKeyDown=new F,this.onKeyUp=new F,this.onGamepadConnected=new F,this.onGamepadDisconnected=new F,this.onGamepadUpdated=new F;const{gamepadDefinitions:e=[],pointerDistanceThreshold:i}=t.options;this.canvas=t.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=i,this.gamepadDefinitions=[...e,...Hi],this.addEventListeners()}get pointersInCanvas(){return Object.values(this.pointers).some(t=>t.currentState!==pi.OutsideCanvas&&t.currentState!==pi.Cancelled)}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this.gamepadsValue}getGamepad(t){return this.gamepadsByIndex.get(t)??null}add(t){return Array.isArray(t)?(t.forEach(t=>this.add(t)),this):(this.inputs.add(t),this)}remove(t){return Array.isArray(t)?(t.forEach(t=>this.remove(t)),this):(this.inputs.delete(t),this)}clear(t=!1){if(t)for(const t of this.inputs)t.destroy();return this.inputs.clear(),this}update(){this.updateGamepads();for(const t of this.inputs)t.update(this.channels);return this.flags.value!==Xi.None&&this.updateEvents(),this}destroy(){this.removeEventListeners();for(const t of Object.values(this.pointers))t.destroy();for(const t of this.gamepadsValue)t.destroy();this.inputs.clear(),this.gamepadsByIndex.clear(),this.gamepadsValue.length=0,this.channelsPressed.length=0,this.channelsReleased.length=0,this.wheelOffset.destroy(),this.flags.destroy(),this.onPointerEnter.destroy(),this.onPointerLeave.destroy(),this.onPointerDown.destroy(),this.onPointerMove.destroy(),this.onPointerUp.destroy(),this.onPointerTap.destroy(),this.onPointerSwipe.destroy(),this.onPointerCancel.destroy(),this.onMouseWheel.destroy(),this.onKeyDown.destroy(),this.onKeyUp.destroy(),this.onGamepadConnected.destroy(),this.onGamepadDisconnected.destroy(),this.onGamepadUpdated.destroy()}handleKeyDown(t){const e=0+t.keyCode;this.channels[e]=1,this.channelsPressed.push(e),this.flags.push(Xi.KeyDown)}handleKeyUp(t){const e=0+t.keyCode;this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(Xi.KeyUp)}handlePointerOver(t){this.pointers[t.pointerId]=new yi(t,this.canvas),this.flags.push(Xi.PointerUpdate)}handlePointerLeave(t){this.pointers[t.pointerId].handleLeave(t),this.flags.push(Xi.PointerUpdate)}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0,this.pointers[t.pointerId].handlePress(t),this.flags.push(Xi.PointerUpdate),t.preventDefault()}handlePointerMove(t){this.pointers[t.pointerId].handleMove(t),this.flags.push(Xi.PointerUpdate)}handlePointerUp(t){this.pointers[t.pointerId].handleRelease(t),this.flags.push(Xi.PointerUpdate),t.preventDefault()}handlePointerCancel(t){this.pointers[t.pointerId].handleCancel(t),this.flags.push(Xi.PointerUpdate)}handleMouseWheel(t){this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(Xi.MouseWheel),this.canvasFocusedValue&&t.preventDefault()}handleCanvasFocus(){this.canvasFocusedValue=!0}handleCanvasBlur(){this.canvasFocusedValue=!1}handleWindowBlur(){this.canvasFocusedValue=!1}addEventListeners(){const t=window,e={capture:!0,passive:!1},i={capture:!0,passive:!0};t.addEventListener("keydown",this.keyDownHandler,!0),t.addEventListener("keyup",this.keyUpHandler,!0),t.addEventListener("blur",this.windowBlurHandler,!0),this.canvas.addEventListener("focus",this.canvasFocusHandler,!0),this.canvas.addEventListener("blur",this.canvasBlurHandler,!0),this.canvas.addEventListener("wheel",this.mouseWheelHandler,e),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,e),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",m,e),this.canvas.addEventListener("selectstart",m,e)}removeEventListeners(){const t={capture:!0,passive:!1},e={capture:!0,passive:!0};window.removeEventListener("keydown",this.keyDownHandler,!0),window.removeEventListener("keyup",this.keyUpHandler,!0),window.removeEventListener("blur",this.windowBlurHandler,!0),this.canvas.removeEventListener("focus",this.canvasFocusHandler,!0),this.canvas.removeEventListener("blur",this.canvasBlurHandler,!0),this.canvas.removeEventListener("wheel",this.mouseWheelHandler,t),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,e),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,e),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,e),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,t),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,e),this.canvas.removeEventListener("contextmenu",m,t),this.canvas.removeEventListener("selectstart",m,t)}updateGamepads(){const t=window.navigator.getGamepads();this.gamepadSlotsActive.fill(0);for(const e of t){if(!e)continue;const t=e.index;if(t<0||t>=this.gamepadSlotsActive.length)continue;this.gamepadSlotsActive[t]=1;let i=this.gamepadsByIndex.get(t);if(i)i.connect(e);else{const s=qi(e,this.gamepadDefinitions);i=new gi(e,this.channels,s),this.gamepadsByIndex.set(t,i),this.insertGamepadByIndex(i),this.onGamepadConnected.dispatch(i,this.gamepadsValue)}i.update(),this.onGamepadUpdated.dispatch(i,this.gamepadsValue)}for(let t=this.gamepadsValue.length-1;t>=0;t-=1){const e=this.gamepadsValue[t];0===this.gamepadSlotsActive[e.index]&&(e.disconnect(),this.gamepadsValue.splice(t,1),this.gamepadsByIndex.delete(e.index),this.onGamepadDisconnected.dispatch(e,this.gamepadsValue),e.destroy())}return this}insertGamepadByIndex(t){let e=0;for(;e<this.gamepadsValue.length&&this.gamepadsValue[e].index<t.index;)e+=1;this.gamepadsValue.splice(e,0,t)}updateEvents(){if(this.flags.pop(Xi.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(Xi.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(Xi.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(Xi.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of Object.values(this.pointers)){const{stateFlags:e}=t;if(e.value!==_i.None){if(e.pop(_i.Over)&&this.onPointerEnter.dispatch(t),e.pop(_i.Down)&&this.onPointerDown.dispatch(t),e.pop(_i.Move)&&this.onPointerMove.dispatch(t),e.pop(_i.Up)){const{x:e,y:i}=t.startPos;this.onPointerUp.dispatch(t),e>=0&&i>=0&&(X(e,i,t.x,t.y)<this.pointerDistanceThreshold?this.onPointerTap.dispatch(t):this.onPointerSwipe.dispatch(t)),t.startPos.set(-1,-1)}e.pop(_i.Cancel)&&this.onPointerCancel.dispatch(t),e.pop(_i.Leave)&&(this.onPointerLeave.dispatch(t),delete this.pointers[t.id])}}}}class Yi{get duration(){return this._duration}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}constructor(t){this.onStart=new F,this.onStop=new F;const{duration:e,volume:i,playbackRate:s,loop:r,muted:n}=t;this._duration=e,this._volume=i,this._playbackRate=s,this._loop=r,this._muted=n}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:s,time:r,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==s&&(this.playbackRate=s),void 0!==r&&(this.currentTime=r),void 0!==n&&(this.muted=n),this}destroy(){this.stop(),this.onStart.destroy(),this.onStop.destroy()}}const $i=["mousedown","touchstart","touchend"];let Ki=null,Qi=null,Zi=!1,Ji=!1,ts=!1;const es=()=>"undefined"!=typeof document,is=()=>Ki,ss=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===Ki&&(Ki=new AudioContext),Ki},rs=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===Qi){const t=ss();Qi=new OfflineAudioContext(1,2,t.sampleRate)}return Qi},ns=()=>{const t=is();t&&"running"===t.state&&!ts&&(ts=!0,(()=>{if(Zi&&es()){for(const t of $i)document.removeEventListener(t,hs,!1);Zi=!1}})(),ls.dispatch(t))},os=()=>{ns()},as=()=>{const t=ss();Ji||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",os),Ji=!0),ns(),ts||(()=>{if(!Zi&&es()){for(const t of $i)document.addEventListener(t,hs,!1);Zi=!0}})()},hs=()=>{const t=ss();"running"!==t.state?t.resume().then(()=>{ns()}):ns()};const ls=new class extends F{add(t,e){return super.add(t,e),as(),this}once(t,e){return super.once(t,e),as(),this}},us=()=>{const t=ss();return as(),t},cs=()=>{const t=is();return null!==t&&"running"===t.state},ds=()=>rs(),_s=async t=>rs().decodeAudioData(t);class ps extends Yi{constructor(t,e){super(t),this._audioSetup=null,this._audioElement=t,e&&this.applyOptions(e),cs()?this.setupWithAudioContext(us()):ls.once(this.setupWithAudioContext,this)}setVolume(t){const e=G(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._audioElement.loop=t),this}setPlaybackRate(t){const e=G(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._audioElement.playbackRate=e),this}getTime(){return this._audioElement.currentTime}setTime(t){return this._audioElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}get paused(){return this._audioElement.paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._audioElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._audioElement.pause(),this.onStop.dispatch()),this}destroy(){super.destroy(),ls.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._audioElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class fs extends Yi{get paused(){return this._paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}get poolSize(){return this._poolSize}set poolSize(t){this.setPoolSize(t)}constructor(t,e={}){super({duration:t.duration,volume:1,playbackRate:1,loop:!1,muted:!1}),this._pooledSources=[],this._queuedPooledPlays=[],this._sprites=new Map,this._audioSetup=null,this._paused=!0,this._startTime=0,this._currentTime=0,this._sourceNode=null,this._poolSize=1,this._audioBuffer=t;const{poolSize:i,sprites:s,...r}=e;this._poolSize=Math.max(1,Math.floor(i??1)),Object.keys(r).length>0&&this.applyOptions(r),s&&this.setSprites(s),cs()?this.setupWithAudioContext(us()):ls.once(this.setupWithAudioContext,this)}setVolume(t){const e=G(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop=t,this._sourceNode&&(this._sourceNode.loop=t,t&&(this._sourceNode.loopStart=0,this._sourceNode.loopEnd=this.duration)),this}setPlaybackRate(t){return this._playbackRate=G(t,.1,20),this._sourceNode&&(this._sourceNode.playbackRate.value=this._playbackRate),this}getTime(){return this._audioSetup&&!this._paused&&this._sourceNode?this._currentTime+(this._audioSetup.audioContext.currentTime-this._startTime)*this._playbackRate:this._currentTime}setTime(t){const e=Math.max(0,t);return this.paused||!this._audioSetup?(this._currentTime=e,this):(this.pause(),this._currentTime=e,this.play(),this)}setMuted(t){if(this._muted=t,this._audioSetup){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}setPoolSize(t){const e=Math.max(1,Math.floor(t));return this._poolSize===e||(this._poolSize=e,this._trimPooledSources()),this}setSprites(t){this._sprites.clear();for(const[e,i]of Object.entries(t))this.defineSprite(e,i);return this}defineSprite(t,e){if(0===t.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=e.start,s=e.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${t}" has an invalid start time (${i}).`);if(!Number.isFinite(s)||s<=i)throw new Error(`Sound sprite "${t}" has an invalid end time (${s}).`);if(s>this.duration)throw new Error(`Sound sprite "${t}" ends at ${s}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(t,{start:i,end:s,loop:e.loop??!1}),this}hasSprite(t){return this._sprites.has(t)}removeSprite(t){return this._sprites.delete(t),this}play(t){return t&&this.applyOptions(t),this._paused?(this._audioSetup&&this.createSourceNode(this._audioSetup),this._paused=!1,this.onStart.dispatch(),this):this}playPooled(t={}){const e=G(t.playbackRate??this._playbackRate,.1,20),i=Math.max(0,t.time??0),s=t.loop??!1;if(void 0!==t.volume&&this.setVolume(t.volume),void 0!==t.muted&&this.setMuted(t.muted),i>=this.duration)return this;const r=s?void 0:this.duration-i;return this._enqueuePooledPlay({offset:i,duration:r,loop:s,loopStart:0,loopEnd:this.duration,playbackRate:e}),this.onStart.dispatch(),this}playSprite(t,e={}){const i=this._sprites.get(t);if(!i)throw new Error(`Sound sprite "${t}" is not defined.`);const s=Math.max(0,e.time??0),r=i.start+s;if(r>=i.end)throw new Error(`Sound sprite "${t}" offset (${s}s) exceeds clip duration (${i.end-i.start}s).`);const n=e.loop??i.loop,o=G(e.playbackRate??this._playbackRate,.1,20);return void 0!==e.volume&&this.setVolume(e.volume),void 0!==e.muted&&this.setMuted(e.muted),this._enqueuePooledPlay({offset:r,duration:n?void 0:i.end-r,loop:n,loopStart:i.start,loopEnd:i.end,playbackRate:o}),this.onStart.dispatch(),this}stopPooled(){return this._pooledSources.length>0&&(this._stopPooledSources(),this.onStop.dispatch()),this._queuedPooledPlays.length=0,this}pause(t){if(t&&this.applyOptions(t),this._paused&&0===this._pooledSources.length)return this;if(!this._paused&&this._audioSetup){const t=this.duration,e=this.currentTime;this._currentTime=t>0?e%t:0}const e=this._pooledSources.length>0;this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0;const i=!this._paused||e;return this._paused=!0,i&&this.onStop.dispatch(),this}destroy(){super.destroy(),ls.clearByContext(this),this._audioSetup?.gainNode.disconnect(),this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0,this._sprites.clear()}createSourceNode(t){const{audioContext:e}=t;this._stopPrimarySource();const i=this._createBufferSourceNode(t,{offset:Math.min(Math.max(0,this._currentTime),Math.max(0,this.duration)),duration:void 0,loop:this._loop,loopStart:0,loopEnd:this.duration,playbackRate:this._playbackRate});i.onended=()=>{this._sourceNode===i&&(this._sourceNode=null,this._startTime=0,this._currentTime=0,this._paused||(this._paused=!0,this.onStop.dispatch()))},this._sourceNode=i,this._startTime=e.currentTime}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination),this._audioSetup={audioContext:t,gainNode:e},this._paused||this.createSourceNode(this._audioSetup),this._flushQueuedPooledPlays()}_enqueuePooledPlay(t){this._audioSetup?this._playPooledNow(t):this._queuedPooledPlays.push(t)}_flushQueuedPooledPlays(){if(!this._audioSetup||0===this._queuedPooledPlays.length)return;const t=[...this._queuedPooledPlays];this._queuedPooledPlays.length=0;for(const e of t)this._playPooledNow(e)}_playPooledNow(t){if(!this._audioSetup)return;const e=this._createBufferSourceNode(this._audioSetup,t);e.onended=()=>{const t=this._pooledSources.indexOf(e);-1!==t&&this._pooledSources.splice(t,1),e.disconnect()},this._pooledSources.push(e),this._trimPooledSources()}_trimPooledSources(){for(;this._pooledSources.length>this._poolSize;){const t=this._pooledSources.shift();t&&(t.onended=null,this._stopSourceNode(t))}}_stopPrimarySource(){this._sourceNode&&(this._sourceNode.onended=null,this._stopSourceNode(this._sourceNode),this._sourceNode=null,this._startTime=0)}_stopPooledSources(){for(const t of this._pooledSources)t.onended=null,this._stopSourceNode(t);this._pooledSources.length=0}_stopSourceNode(t){try{t.stop(0)}catch{}t.disconnect()}_createBufferSourceNode(t,e){const{gainNode:i}=t,s=t.audioContext.createBufferSource();s.buffer=this._audioBuffer,s.loop=e.loop,s.playbackRate.value=e.playbackRate,e.loop&&(s.loopStart=e.loopStart??0,s.loopEnd=e.loopEnd??this.duration),s.connect(i);const r=e.duration;return!e.loop&&void 0!==r&&r>0?s.start(0,e.offset,r):s.start(0,e.offset),s}}class ms extends qe{constructor(t,e,i){super(new je(t,i)),this.onStart=new F,this.onStop=new F,this._volume=1,this._playbackRate=1,this._loop=!1,this._muted=!1,this._audioSetup=null,this._textureDirty=!0,this._lastVideoTime=Number.NaN,this._videoFrameCallbackHandle=null;const{duration:s,volume:r,playbackRate:n,loop:o,muted:a}=t;this._videoElement=t,this._duration=s,this._volume=r,this._playbackRate=n,this._loop=o,this._muted=a,this._onMetadataHandler=this._onVideoMetadataUpdated.bind(this),this._onResizeHandler=this._onVideoMetadataUpdated.bind(this),this._onVideoFrameHandler=this._onVideoFrame.bind(this),0!==this._videoElement.videoWidth&&0!==this._videoElement.videoHeight||(this._videoElement.addEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.addEventListener("resize",this._onResizeHandler)),e&&this.applyOptions(e),cs()?this.setupWithAudioContext(us()):ls.once(this.setupWithAudioContext,this),this.updateTexture(),this._requestVideoFrameCallback()}get videoElement(){return this._videoElement}get duration(){return this._duration}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get paused(){return this._videoElement.paused}set paused(t){t?this.pause():this.play()}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:s,time:r,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==s&&(this.playbackRate=s),void 0!==r&&(this.currentTime=r),void 0!==n&&(this.muted=n),this}setVolume(t){const e=G(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._videoElement.loop=t),this}setPlaybackRate(t){const e=G(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._videoElement.playbackRate=e),this}getTime(){return this._videoElement.currentTime}setTime(t){return this._videoElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}render(t){return this.visible&&(this._markTextureDirtyIfPlaybackAdvanced(),this.updateTexture(),super.render(t)),this}updateTexture(){const t=this.texture;if(!t||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const e=this.textureFrame.width>0&&this.textureFrame.height>0;return t.updateSource(),t.width>0&&t.height>0&&this.setTextureFrame(re.temp.set(0,0,t.width,t.height),!e),this._textureDirty=!1,this}destroy(){super.destroy(),this.stop(),this._videoElement.removeEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.removeEventListener("resize",this._onResizeHandler),this._cancelVideoFrameCallback(),ls.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null),this.onStart.destroy(),this.onStop.destroy()}_onVideoMetadataUpdated(){this._textureDirty=!0,this.updateTexture()}_onVideoFrame(t,e){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyIfPlaybackAdvanced(){const t=this._videoElement.currentTime;this._lastVideoTime!==t&&(this._lastVideoTime=t,this._textureDirty=!0)}_requestVideoFrameCallback(){const t=this._videoElement;t.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=t.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const t=this._videoElement;t.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(t.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._videoElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class gs{}class ys{}class xs{}class ws{}class vs{constructor(){this._factories=new Map}register(t,e){this._factories.set(t,e)}resolve(t){let e,i=t;for(;null!==i&&!e;)if(e=this._factories.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No factory registered for ${t.name}. Register one with loader.register() before loading.`);return e}has(t){let e=t;for(;null!==e;){if(this._factories.has(e))return!0;const t=Object.getPrototypeOf(e.prototype);e=t?.constructor??null}return!1}destroy(){for(const t of this._factories.values())t.destroy();this._factories.clear()}}class bs{constructor(){this._objectUrls=[]}createObjectUrl(t){const e=URL.createObjectURL(t);return this._objectUrls.push(e),e}revokeObjectUrl(t){URL.revokeObjectURL(t);const e=this._objectUrls.indexOf(t);-1!==e&&this._objectUrls.splice(e,1)}destroy(){for(const t of this._objectUrls)URL.revokeObjectURL(t);this._objectUrls.length=0}}class Ts extends bs{constructor(){super(...arguments),this.storageName="font",this._addedFontFaces=[]}async process(t){return await t.arrayBuffer()}async create(t,e){if(!e?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:s,addToDocument:r}=e;if(t.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${t.byteLength}.`);const n=await new FontFace(i,t,s).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${t.byteLength} bytes).`)});return!1!==r&&(document.fonts.add(n),this._addedFontFaces.push(n)),n}destroy(){for(const t of this._addedFontFaces)document.fonts.delete(t);this._addedFontFaces.length=0,super.destroy()}}const Ss=[{mimeType:"image/x-icon",pattern:[0,0,1,0],mask:[255,255,255,255]},{mimeType:"image/x-icon",pattern:[0,0,2,0],mask:[255,255,255,255]},{mimeType:"image/bmp",pattern:[66,77],mask:[255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,55,97],mask:[255,255,255,255,255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,57,97],mask:[255,255,255,255,255,255]},{mimeType:"image/webp",pattern:[82,73,70,70,0,0,0,0,87,69,66,80,86,80],mask:[255,255,255,255,0,0,0,0,255,255,255,255,255,255]},{mimeType:"image/png",pattern:[137,80,78,71,13,10,26,10],mask:[255,255,255,255,255,255,255,255]},{mimeType:"image/jpeg",pattern:[255,216,255],mask:[255,255,255]},{mimeType:"audio/basic",pattern:[46,115,110,100],mask:[255,255,255,255]},{mimeType:"audio/mpeg",pattern:[73,68,51],mask:[255,255,255]},{mimeType:"audio/wave",pattern:[82,73,70,70,0,0,0,0,87,65,86,69],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"audio/midi",pattern:[77,84,104,100,0,0,0,6],mask:[255,255,255,255,255,255,255,255]},{mimeType:"audio/aiff",pattern:[70,79,82,77,0,0,0,0,65,73,70,70],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"video/avi",pattern:[82,73,70,70,0,0,0,0,65,86,73,32],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"application/ogg",pattern:[79,103,103,83,0],mask:[255,255,255,255,255]}],Cs=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of Ss)if(!(e.length<t.pattern.length)&&t.pattern.every((i,s)=>(e[s]&t.mask[s])===i))return t.mimeType;return(t=>{const e=new Uint8Array(t),i=new DataView(t).getUint32(0,!1);return!(e.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...e.subarray(4,11))})(t)?"video/mp4":(t=>{const e=new Uint8Array(t),i=[26,69,223,163].every((t,i)=>t===e[i]),s=e.subarray(4,4100),r=s.findIndex((t,e,i)=>66===i[e]&&130===i[e+1]);return!(!i||-1===r)&&"webm"===String.fromCharCode(...s.subarray(r+3,r+7))})(t)?"video/webm":(t=>{if(t.byteLength<12)return!1;const e=new Uint8Array(t);if("ftyp"!==String.fromCharCode(e[4],e[5],e[6],e[7]))return!1;const i=String.fromCharCode(e[8],e[9],e[10],e[11]);return"avif"===i||"avis"===i})(t)?"image/avif":"text/plain"};class Ms extends bs{constructor(){super(...arguments),this.storageName="image"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??Cs(t)}),s=this.createObjectUrl(i);return new Promise((t,e)=>{const i=new Image,r=()=>{this.revokeObjectUrl(s)};i.addEventListener("load",()=>{r(),t(i)},{once:!0}),i.addEventListener("error",()=>{r(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),e(Error("Image loading was canceled."))},{once:!0}),i.src=s})}}class Ps extends bs{constructor(){super(...arguments),this.storageName="json"}async process(t){return await t.json()}async create(t){return t}}const Bs={once:!0};class Es extends bs{constructor(){super(...arguments),this.storageName="music",this._audioElements=[]}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:s,playbackOptions:r}=e,n=new Blob([t],{type:i??Cs(t)});return new Promise((t,e)=>{const i=document.createElement("audio");this._audioElements.push(i),i.addEventListener("error",()=>e(Error("Error loading audio source.")),Bs),i.addEventListener("abort",()=>e(Error("Audio loading was canceled.")),Bs),i.addEventListener(s??"canplaythrough",()=>t(new ps(i,r)),Bs),i.preload="auto",i.src=this.createObjectUrl(n)})}destroy(){for(const t of this._audioElements)t.pause(),t.src="",t.load();this._audioElements.length=0,super.destroy()}}class Rs extends bs{constructor(){super(...arguments),this.storageName="sound"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=await _s(t);return new fs(i,{...e.playbackOptions,poolSize:e.poolSize,sprites:e.sprites})}}class As extends bs{constructor(){super(...arguments),this.storageName="text"}async process(t){return await t.text()}async create(t){return t}}class ks extends bs{constructor(){super(...arguments),this.storageName="texture"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,samplerOptions:s}=e,r=new Blob([t],{type:i??Cs(t)}),n=this.createObjectUrl(r);return new Promise((t,e)=>{const i=new Image,r=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{r(),t(new je(i,s))},{once:!0}),i.addEventListener("error",()=>{r(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),e(Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const Ls={once:!0};class Fs extends bs{constructor(){super(...arguments),this.storageName="video",this._videoElements=[]}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:s,playbackOptions:r,samplerOptions:n}=e,o=new Blob([t],{type:i??Cs(t)});return new Promise((t,e)=>{const i=document.createElement("video");this._videoElements.push(i),i.addEventListener("error",()=>e(Error("Video loading error.")),Ls),i.addEventListener("abort",()=>e(Error("Video loading error: cancelled.")),Ls),i.addEventListener("emptied",()=>e(Error("Video loading error: emptied.")),Ls),i.addEventListener(s??"canplaythrough",()=>t(new ms(i,r,n)),Ls),i.preload="auto",i.src=this.createObjectUrl(o)})}destroy(){for(const t of this._videoElements)t.pause(),t.src="",t.load();this._videoElements.length=0,super.destroy()}}class Ds extends bs{constructor(){super(...arguments),this.storageName="svg"}async process(t){return await t.text()}async create(t){const e=new Blob([t],{type:"image/svg+xml"}),i=this.createObjectUrl(e);return new Promise((t,e)=>{const s=new Image,r=()=>{this.revokeObjectUrl(i)};s.addEventListener("load",()=>{r(),t(s)},{once:!0}),s.addEventListener("error",()=>{r(),e(Error("Error loading image source."))},{once:!0}),s.addEventListener("abort",()=>{r(),e(Error("Image loading was canceled."))},{once:!0}),s.src=i})}}class Is extends bs{constructor(){super(...arguments),this.storageName="binary"}async process(t){return t.arrayBuffer()}async create(t){return t}}class Ns extends bs{constructor(){super(...arguments),this.storageName="wasm"}async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}const Us=t=>{const e=t.split(":");let i=0;return i=3===e.length?3600*Number(e[0])+60*Number(e[1])+Number(e[2]):2===e.length?60*Number(e[0])+Number(e[1]):Number(e[0]),i};class Vs extends bs{constructor(){super(...arguments),this.storageName="vtt"}async process(t){return t.text()}async create(t){const e=[],i=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n");let s=0;for(;s<i.length&&!i[s].includes("--\x3e");)s++;for(;s<i.length;){const t=i[s].trim();if(t.includes("--\x3e")){const r=t.indexOf("--\x3e"),n=t.slice(0,r).trim(),o=t.slice(r+3).trim().split(/\s+/)[0],a=Us(n),h=Us(o);s++;const l=[];for(;s<i.length&&""!==i[s].trim();)l.push(i[s]),s++;e.push(new VTTCue(a,h,l.join("\n")))}else s++}return e}}class Os extends Error{constructor(t,e){super(`Failed to load bundle "${t}" (${e.length} failure${1===e.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=t,this.failures=e}}function Gs(t){return function(t){if(!zs(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!zs(t.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[e,i]of Object.entries(t.bundles)){if(0===e.trim().length)throw new Error("Invalid asset manifest: bundle names must be non-empty strings.");if(!Array.isArray(i))throw new Error(`Invalid asset manifest: bundle "${e}" must be an array of entries.`);const t=new Map;i.forEach((i,s)=>{const r=`bundle "${e}" entry[${s}]`;if(!zs(i))throw new Error(`Invalid asset manifest: ${r} must be an object.`);if("function"!=typeof i.type)throw new Error(`Invalid asset manifest: ${r} has an invalid "type" token.`);Ws(i.alias,`${r} has an invalid "alias".`),Ws(i.path,`${r} has an invalid "path".`);const n=i.type,o=i.alias;t.has(n)||t.set(n,new Set);const a=t.get(n);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${qs(n)}, "${o}") in bundle "${e}".`);a.add(o)})}}(t),t}function zs(t){return"object"==typeof t&&null!==t}function Ws(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function qs(t){return t.name.length>0?t.name:"(anonymous type)"}class Hs{constructor(t={}){this._registry=new vs,this._resources=new Map,this._manifest=new Map,this._bundles=new Map,this._inFlight=new Map,this._typeIds=new WeakMap,this._preventStoreKeys=new Set,this._nextTypeId=1,this._backgroundQueue=[],this._backgroundActive=0,this._backgroundTotal=0,this._backgroundLoaded=0,this._backgroundResolve=null,this.onProgress=new F,this.onBundleProgress=new F,this.onLoaded=new F,this.onError=new F,this._resourcePath=t.resourcePath??"",this._requestOptions=t.requestOptions??{},this._concurrency=t.concurrency??6,this._stores=t.cache?Array.isArray(t.cache)?t.cache:[t.cache]:[],this._registerBuiltinFactories()}register(t,e){return this._registry.register(t,e),this}add(t,e){const i=t;if("string"==typeof e)this._addManifestEntry(i,e,e);else if(Array.isArray(e))for(const t of e)this._addManifestEntry(i,t,t);else for(const[t,s]of Object.entries(e))this._addManifestEntry(i,t,s);return this}registerManifest(t){const e=Gs(t),i=new Map,s=new Array;for(const[t,r]of Object.entries(e.bundles)){if(this._bundles.has(t))throw new Error(`Bundle "${t}" is already registered.`);const e=new Array;for(const s of r){const r=s.type,n=this._key(r,s.alias),o=i.get(n)??this._getManifestEntry(r,s.alias);if(o&&!this._isManifestDefinitionEquivalent(o,s.path,s.options))throw new Error(`Conflicting asset definition for (${this._describeType(r)}, "${s.alias}") while registering bundle "${t}".`);i.set(n,{path:s.path,options:s.options}),e.push({type:r,alias:s.alias,path:s.path,options:s.options})}s.push([t,e])}for(const[t,e]of s){for(const t of e)this._addManifestEntry(t.type,t.alias,t.path,t.options);this._bundles.set(t,e)}return this}async loadBundle(t,e={}){const i=this._bundles.get(t);if(!i)throw new Error(`Unknown bundle "${t}".`);const s=i.length;let r=0;const n=new Array;if(0!==s){if(await Promise.all(i.map(async i=>{try{e.background?await this._loadSingleBackground(i.type,i.alias,i.path,i.options):await this._loadSingle(i.type,i.alias,i.options,i.path)}catch(t){n.push({type:i.type,alias:i.alias,error:this._normalizeError(t)})}finally{r++,this._emitBundleProgress(t,r,s,e.onProgress)}})),n.length>0)throw new Os(t,n)}else this._emitBundleProgress(t,0,0,e.onProgress)}hasBundle(t){const e=this._bundles.get(t);return!!e&&e.every(t=>this._hasResource(t.type,t.alias))}async load(t,e,i){const s=t;if("string"==typeof e)return this._loadSingle(s,e,i);if(Array.isArray(e))return Promise.all(e.map(t=>this._loadSingle(s,t,i)));const r=Object.entries(e),n={};return await Promise.all(r.map(async([t,e])=>{n[t]=await this._loadSingle(s,t,i,e)})),n}backgroundLoad(){for(const[t,e]of this._manifest)for(const[i,s]of e){if(this._hasResource(t,i))continue;const e=this._key(t,i);this._inFlight.has(e)||this._backgroundQueue.push({type:t,alias:i,path:s.path,options:s.options})}this._backgroundTotal=this._backgroundQueue.length,this._backgroundLoaded=0,this._drainBackground()}loadAll(){return new Promise(t=>{this._backgroundResolve=t,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,t())})}setConcurrency(t){return this._concurrency=t,this}get(t,e){const i=t,s=this._resources.get(i);if(!s?.has(e))throw new Error(`Missing resource "${e}" for type ${i.name}.`);return s.get(e)}peek(t,e){const i=t;return this._resources.get(i)?.get(e)??null}has(t,e){const i=t;return this._resources.get(i)?.has(e)??!1}unload(t,e){const i=t,s=this._key(i,e);return this._resources.get(i)?.delete(e),this._inFlight.has(s)&&this._preventStoreKeys.add(s),this}unloadAll(t){if(t)this._resources.get(t)?.clear();else for(const t of this._resources.values())t.clear();return this}get resourcePath(){return this._resourcePath}set resourcePath(t){this._resourcePath=t}get requestOptions(){return this._requestOptions}set requestOptions(t){this._requestOptions=t}destroy(){this._registry.destroy();for(const t of this._stores)t.destroy();this._resources.clear(),this._manifest.clear(),this._bundles.clear(),this._inFlight.clear(),this._preventStoreKeys.clear(),this._backgroundQueue.length=0,this.onProgress.destroy(),this.onBundleProgress.destroy(),this.onLoaded.destroy(),this.onError.destroy()}async _loadSingle(t,e,i,s){if(this._hasResource(t,e))return this._resources.get(t).get(e);const r=this._key(t,e);if(this._inFlight.has(r))return this._inFlight.get(r);if(this._boostFromQueue(t,e),this._inFlight.has(r))return this._inFlight.get(r);const n=this._getManifestEntry(t,e),o=s??n?.path??e,a=i??n?.options;return this._trackInFlight(r,this._fetch(t,e,o,a))}_loadSingleBackground(t,e,i,s){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const r=this._key(t,e),n=this._inFlight.get(r);if(n)return n;this._isQueuedInBackground(t,e)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:t,alias:e,path:i,options:s}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(r);return o||this._waitForBackgroundEntry(t,e)}async _fetch(t,e,i,s){const r=this._registry.resolve(t),n=this._resolveUrl(i);let o=null;for(const i of this._stores)if(o=await i.load(r.storageName,e),null!=o)try{const i=await r.create(o,s);return this._storeResource(t,e,i),i}catch{await i.delete(r.storageName,e),o=null}const a=await fetch(n,this._requestOptions);if(!a.ok)throw new Error(`Failed to fetch "${e}" from "${n}" (${a.status} ${a.statusText}).`);o=await r.process(a);const h=await r.create(o,s).catch(t=>{const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to create "${e}" from "${n}": ${i}`)});for(const t of this._stores)try{await t.save(r.storageName,e,o)}catch{}return this._storeResource(t,e,h),h}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const t=this._backgroundQueue.shift(),e=this._key(t.type,t.alias);this._hasResource(t.type,t.alias)||this._inFlight.has(e)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(t)}}_boostFromQueue(t,e){const i=this._backgroundQueue.findIndex(i=>i.type===t&&i.alias===e);if(-1===i)return;const[s]=this._backgroundQueue.splice(i,1);this._startBackgroundEntry(s)}_isQueuedInBackground(t,e){return this._backgroundQueue.some(i=>i.type===t&&i.alias===e)}_waitForBackgroundEntry(t,e){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const i=this._key(t,e),s=this._inFlight.get(i);return s||new Promise((s,r)=>{const n=(i,r,n)=>{i===t&&r===e&&(a(),s(n))},o=(i,s,n)=>{i===t&&s===e&&(a(),r(n))},a=()=>{this.onLoaded.remove(n),this.onError.remove(o)};this.onLoaded.add(n),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(s,r);this._hasResource(t,e)&&(a(),s(this._resources.get(t).get(e)))})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const t=this._backgroundResolve;this._backgroundResolve=null,t()}}_startBackgroundEntry(t){const e=this._key(t.type,t.alias);this._backgroundActive++,this._trackInFlight(e,this._fetch(t.type,t.alias,t.path,t.options)).catch(e=>{const i=e instanceof Error?e:new Error(String(e));this.onError.dispatch(t.type,t.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(t,e){const i=e.finally(()=>{this._inFlight.delete(t),this._preventStoreKeys.delete(t)});return this._inFlight.set(t,i),i}_emitBundleProgress(t,e,i,s){this.onBundleProgress.dispatch(t,e,i),s&&s(e,i)}_addManifestEntry(t,e,i,s){this._manifest.has(t)||this._manifest.set(t,new Map),this._manifest.get(t).set(e,{path:i,options:s})}_getManifestEntry(t,e){return this._manifest.get(t)?.get(e)}_isManifestDefinitionEquivalent(t,e,i){return t.path===e&&this._areOptionsEquivalent(t.options,i)}_areOptionsEquivalent(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this._areOptionsEquivalent(t[i],e[i]))return!1;return!0}const i=Object.getPrototypeOf(t);if(i!==Object.getPrototypeOf(e))return!1;if(i!==Object.prototype&&null!==i)return!1;const s=t,r=e,n=Object.keys(s),o=Object.keys(r);if(n.length!==o.length)return!1;for(const t of n){if(!Object.prototype.hasOwnProperty.call(r,t))return!1;if(!this._areOptionsEquivalent(s[t],r[t]))return!1}return!0}_normalizeError(t){return t instanceof Error?t:new Error(String(t))}_describeType(t){return t.name.length>0?t.name:"(anonymous type)"}_hasResource(t,e){return this._resources.get(t)?.has(e)??!1}_storeResource(t,e,i){const s=this._key(t,e);this._preventStoreKeys.delete(s)||(this._resources.has(t)||this._resources.set(t,new Map),this._resources.get(t).set(e,i),this.onLoaded.dispatch(t,e,i))}_key(t,e){let i=this._typeIds.get(t);return void 0===i&&(i=this._nextTypeId++,this._typeIds.set(t,i)),`${i}:${e}`}_resolveUrl(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?t:`${this._resourcePath}${t}`}_registerBuiltinFactories(){this._registry.register(je,new ks),this._registry.register(fs,new Rs),this._registry.register(ps,new Es),this._registry.register(ms,new Fs),this._registry.register(gs,new Ps),this._registry.register(ys,new As),this._registry.register(xs,new Ds),this._registry.register(ws,new Vs),this._registry.register(ArrayBuffer,new Is),"undefined"!=typeof FontFace&&this._registry.register(FontFace,new Ts),"undefined"!=typeof HTMLImageElement&&this._registry.register(HTMLImageElement,new Ms),"undefined"!=typeof WebAssembly&&this._registry.register(WebAssembly.Module,new Ns)}}var Xs;!function(t){t[t.Loading=1]="Loading",t[t.Running=2]="Running",t[t.Halting=3]="Halting",t[t.Stopped=4]="Stopped"}(Xs||(Xs={}));const js={type:"auto"},Ys={width:800,height:600,clearColor:K.cornflowerBlue,debug:!1,spriteRendererBatchSize:4096,particleRendererBatchSize:8192,primitiveRendererBatchSize:65536,gamepadDefinitions:[],pointerDistanceThreshold:10,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1},resourcePath:"",requestOptions:{method:"GET",mode:"cors",cache:"default"},cache:void 0,backend:js};class $s{constructor(t){this.onResize=new F,this._startupClock=new L,this._activeClock=new L,this._frameClock=new L,this._status=Xs.Stopped,this._frameCount=0,this._frameRequest=0,this.options={canvas:t?.canvas??document.createElement("canvas"),...Ys,...t,backend:t?.backend??js},this.canvas=this.options.canvas,this.canvas.hasAttribute("tabindex")||this.canvas.setAttribute("tabindex","-1"),this.loader=new Hs({resourcePath:this.options.resourcePath,requestOptions:this.options.requestOptions,cache:this.options.cache}),this._backendType=this.resolveInitialBackendType(),this._renderManager=this.createRenderManager(this._backendType),this.inputManager=new ji(this),this.sceneManager=new ve(this),this._updateHandler=this.update.bind(this),this._startupClock.start()}get status(){return this._status}get startupTime(){return this._startupClock.elapsedTime}get activeTime(){return this._activeClock.elapsedTime}get frameTime(){return this._frameClock.elapsedTime}get frameCount(){return this._frameCount}get renderManager(){return this._renderManager}async start(t){if(this._status===Xs.Stopped){this._status=Xs.Loading;try{await this.initializeRenderManager(),await this.sceneManager.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._activeClock.start(),this._status=Xs.Running}catch(t){throw this._status=Xs.Stopped,t}}return this}update(){if(this._status===Xs.Running){const t=this._frameClock.elapsedTime,e=performance.now();this.renderManager.resetStats(),this.inputManager.update();const i=this.renderManager.view;i&&"function"==typeof i.update&&i.update(t.milliseconds),this.sceneManager.update(t),this.renderManager.flush(),this.renderManager.stats.frameTimeMs=performance.now()-e,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===Xs.Running&&(this._status=Xs.Halting,cancelAnimationFrame(this._frameRequest),this.sceneManager.setScene(null).catch(t=>{console.error("Application.stop() failed to unload the active scene.",t)}),this._activeClock.stop(),this._frameClock.stop(),this._status=Xs.Stopped),this}resize(t,e){return this.renderManager.resize(t,e),this.onResize.dispatch(t,e,this),this}destroy(){this.stop(),this.loader.destroy(),this.inputManager.destroy(),this._renderManager.destroy(),this.sceneManager.destroy(),this._startupClock.destroy(),this._activeClock.destroy(),this._frameClock.destroy(),this.onResize.destroy()}resolveInitialBackendType(){const t=this.options.backend?.type;return"webgl2"===t?"webgl2":"webgpu"===t||this.canUseWebGpu()?"webgpu":"webgl2"}createRenderManager(t){return"webgpu"===t?new ui(this):new Je(this)}async initializeRenderManager(){try{await this._renderManager.initialize()}catch(t){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw t;this._renderManager.destroy(),this._backendType="webgl2",this._renderManager=this.createRenderManager(this._backendType),await this._renderManager.initialize()}}canUseWebGpu(){return!!navigator.gpu}}class Ks{constructor(t,e=0){this._quadTrees=new Map,this._sceneNodes=new Set,this._bounds=t.clone(),this.level=e}addSceneNode(t){const e=this._getQuadTree(t);return e?(e.addSceneNode(t),this):(this._sceneNodes.add(t),this._sceneNodes.size>Ks.maxSceneNodes&&this.level<Ks.maxLevel&&this._split(),this)}getRelatedChildren(t){const e=this._getQuadTree(t);return null===e?[...this._sceneNodes]:[...e.getRelatedChildren(t),...this._sceneNodes]}getBounds(){return this._bounds}clear(){if(this._quadTrees.size>0){for(const t of this._quadTrees.values())t.destroy();this._quadTrees.clear()}return this._sceneNodes.clear(),this}destroy(){this.clear(),this._bounds.destroy()}_getQuadTree(t){if(this._quadTrees.size>0){const e=t.getBounds();for(const t of this._quadTrees.values())if(t.getBounds().containsRect(e))return t}return null}_split(){if(0===this._quadTrees.size){const{top:t,left:e,width:i,height:s}=this.getBounds(),r=i/2|0,n=s/2|0,o=this.level+1;this._quadTrees.set(0,new Ks(re.temp.set(e,t,r,n),o)),this._quadTrees.set(1,new Ks(re.temp.set(e+r,t,r,n),o)),this._quadTrees.set(2,new Ks(re.temp.set(e,t+n,r,n),o)),this._quadTrees.set(3,new Ks(re.temp.set(e+r,t+n,r,n),o))}this._passSceneNodesToQuadTrees()}_passSceneNodesToQuadTrees(){for(const t of this._sceneNodes){const e=this._getQuadTree(t);e&&(this._sceneNodes.delete(t),e.addSceneNode(t))}}}Ks.maxSceneNodes=50,Ks.maxLevel=5;class Qs extends me{constructor(){super(...arguments),this._children=[],this._sortableChildren=!1,this._sortDirty=!1,this._nextChildOrder=0}get children(){return this._children}get sortableChildren(){return this._sortableChildren}set sortableChildren(t){this._sortableChildren!==t&&(this._sortableChildren=t,this._sortDirty=t)}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this.scale.x=t/this.bounds.width}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this.scale.y=t/this.bounds.height}get left(){return this.x-this.width*this.origin.x}get top(){return this.y-this.height*this.origin.y}get right(){return this.x+this.width-this.origin.x}get bottom(){return this.y+this.height-this.origin.y}addChild(t){return this.addChildAt(t,this._children.length)}addChildAt(t,e){if(e<0||e>this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return t===this||(t.parentNode&&t.parentNode.removeChild(t),t.parentNode=this,t.setChildOrder(this._nextChildOrder++),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache()),this}swapChildren(t,e){if(t!==e){const i=this.getChildIndex(t),s=this.getChildIndex(e);this._children[i]=e,this._children[s]=t,this.markSortDirty(),this.invalidateCache()}return this}getChildIndex(t){const e=this._children.indexOf(t);if(-1===e)throw new Error("Drawable is not a child of the container.");return e}setChildIndex(t,e){if(e<0||e>=this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return B(this._children,this.getChildIndex(t),1),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache(),this}getChildAt(t){if(t<0||t>=this._children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this._children[t]}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&this.removeChildAt(e),this}removeChildAt(t){const e=this._children[t];return B(this._children,t,1),e&&e.parentNode===this&&(e.parentNode=null),this.markSortDirty(),this.invalidateCache(),this}removeChildren(t=0,e=this._children.length){const i=e-t;if(i<0||i>e)throw new Error("Values are outside the acceptable range.");for(let i=t;i<e;i++){const t=this._children[i];t&&t.parentNode===this&&(t.parentNode=null)}return B(this._children,t,i),this.markSortDirty(),this.invalidateCache(),this}render(t){return this.visible&&0!==this._children.length?this.inView(t.view)?(this.renderVisualContent(t,()=>{this._sortChildrenIfNeeded();for(const e of this._children)e.render(t)}),this):(t.stats.culledNodes++,this):this}contains(t,e){return this._children.some(i=>i.contains(t,e))}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const t of this._children)t.visible&&this._bounds.addRect(t.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}markSortDirty(){return this._sortableChildren&&(this._sortDirty=!0),this}sortChildren(){return!this._sortableChildren||!this._sortDirty||this._children.length<=1?(this._sortDirty=!1,this):(this._children.sort((t,e)=>t.zIndex===e.zIndex?t.childOrder-e.childOrder:t.zIndex-e.zIndex),this._sortDirty=!1,this.invalidateCache(),this)}_sortChildrenIfNeeded(){this._sortableChildren&&this._sortDirty&&this.sortChildren()}}class Zs{static create(t){return Object.assign(new Zs,t)}constructor(){this._app=null,this._root=new Qs,this._stackMode="overlay",this._inputMode="capture"}get app(){return this._app}set app(t){this._app=t}get root(){return this._root}get stackMode(){return this._stackMode}set stackMode(t){this._stackMode=t}get inputMode(){return this._inputMode}set inputMode(t){this._inputMode=t}addChild(t){return this._root.addChild(t),this}removeChild(t){return this._root.removeChild(t),this}setParticipationPolicy(t){return t.mode&&(this._stackMode=t.mode),t.input&&(this._inputMode=t.input),this}getParticipationPolicy(){return{mode:this._stackMode,input:this._inputMode}}load(t){}init(t){}update(t){}draw(t){}handleInput(t){}unload(t){}destroy(){this._root.destroy(),this._app=null}}class Js extends L{constructor(t,e=!1){super(),this._limit=t.clone(),e&&this.restart()}set limit(t){this._limit.copy(t)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/r.seconds}get remainingMinutes(){return this.remainingMilliseconds/r.minutes}get remainingHours(){return this.remainingMilliseconds/r.hours}}class tr{constructor(t,e={}){this._analyser=null,this._audioContext=null,this._analyserTarget=null;const{fftSize:i,minDecibels:s,maxDecibels:r,smoothingTimeConstant:n}=e;this._media=t,this._fftSize=i??2048,this._minDecibels=s??-100,this._maxDecibels=r??-30,this._smoothingTimeConstant=n??.8,this._frequencyBinCount=this._fftSize/2,this._timeDomainData=new Uint8Array(this._frequencyBinCount),this._frequencyData=new Uint8Array(this._frequencyBinCount),this._preciseTimeDomainData=new Float32Array(this._frequencyBinCount),this._preciseFrequencyData=new Float32Array(this._frequencyBinCount),cs()?this.setupWithAudioContext(us()):ls.once(this.setupWithAudioContext,this)}connect(){if(!this._analyser||null!==this._analyserTarget)return this;const t=this._media.analyserTarget;if(!t)throw new Error("No AudioNode on property analyserTarget.");return this._analyserTarget=t,t.connect(this._analyser),this}get timeDomainData(){return this._analyser&&(this.connect(),this._analyser.getByteTimeDomainData(this._timeDomainData)),this._timeDomainData}get frequencyData(){return this._analyser&&(this.connect(),this._analyser.getByteFrequencyData(this._frequencyData)),this._frequencyData}get preciseTimeDomainData(){return this._analyser&&(this.connect(),this._analyser.getFloatTimeDomainData(this._preciseTimeDomainData)),this._preciseTimeDomainData}get preciseFrequencyData(){return this._analyser&&(this.connect(),this._analyser.getFloatFrequencyData(this._preciseFrequencyData)),this._preciseFrequencyData}destroy(){ls.clearByContext(this),this._analyserTarget?.disconnect(),this._analyser?.disconnect()}setupWithAudioContext(t){this._audioContext=t,this._analyser=t.createAnalyser(),this._analyser.fftSize=this._fftSize,this._analyser.minDecibels=this._minDecibels,this._analyser.maxDecibels=this._maxDecibels,this._analyser.smoothingTimeConstant=this._smoothingTimeConstant}}const er=new Map([["DPad",[.22,.58]],["DPadUp",[.22,.5]],["DPadDown",[.22,.66]],["DPadLeft",[.14,.58]],["DPadRight",[.3,.58]],["ButtonNorth",[.78,.5]],["ButtonWest",[.7,.58]],["ButtonEast",[.86,.58]],["ButtonSouth",[.78,.66]],["LeftShoulder",[.28,.28]],["RightShoulder",[.72,.28]],["LeftTrigger",[.2,.16]],["RightTrigger",[.8,.16]],["Select",[.46,.5]],["Start",[.54,.5]],["LeftStick",[.38,.66]],["RightStick",[.62,.66]]]),ir=new Map([["ButtonNorth",fi.ButtonNorth],["ButtonWest",fi.ButtonWest],["ButtonEast",fi.ButtonEast],["ButtonSouth",fi.ButtonSouth],["LeftShoulder",fi.LeftShoulder],["RightShoulder",fi.RightShoulder],["LeftTrigger",fi.LeftTrigger],["RightTrigger",fi.RightTrigger],["Select",fi.Select],["Start",fi.Start],["LeftStick",fi.LeftStick],["RightStick",fi.RightStick],["DPadUp",fi.DPadUp],["DPadDown",fi.DPadDown],["DPadLeft",fi.DPadLeft],["DPadRight",fi.DPadRight]]),sr=new Map([["ButtonNorth","North"],["ButtonWest","West"],["ButtonEast","East"],["ButtonSouth","South"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Select"],["Start","Start"],["LeftStick","L3"],["RightStick","R3"]]),rr=new Map([["ButtonNorth","Y"],["ButtonWest","X"],["ButtonEast","B"],["ButtonSouth","A"],["LeftShoulder","LB"],["RightShoulder","RB"],["LeftTrigger","LT"],["RightTrigger","RT"],["Select","View"],["Start","Menu"],["LeftStick","L3"],["RightStick","R3"]]),nr=new Map([["ButtonNorth","Triangle"],["ButtonWest","Square"],["ButtonEast","Circle"],["ButtonSouth","Cross"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Create"],["Start","Options"],["LeftStick","L3"],["RightStick","R3"]]),or=new Map([["ButtonNorth","X"],["ButtonWest","Y"],["ButtonEast","A"],["ButtonSouth","B"],["LeftShoulder","L"],["RightShoulder","R"],["LeftTrigger","ZL"],["RightTrigger","ZR"],["Select","Minus"],["Start","Plus"],["LeftStick","L3"],["RightStick","R3"]]),ar=new Map([[mi.GenericDualAnalog,sr],[mi.Xbox,rr],[mi.PlayStation,nr],[mi.SwitchPro,or],[mi.JoyConLeft,or],[mi.JoyConRight,or],[mi.GameCube,sr],[mi.SteamController,sr],[mi.ArcadeStick,sr]]);class hr{static getControlPosition(t){return er.get(t)??[.5,.5]}static getControlLabels(t){return ar.get(t)??sr}static buildControlChannelMap(){return ir}}hr.controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];class lr{constructor(t,{onStart:e,onStop:i,onActive:s,onTrigger:r,context:n,threshold:o}={}){this.channels=new Set,this.valueState=0,this.onStart=new F,this.onStop=new F,this.onActive=new F,this.onTrigger=new F,this.channels=new Set(Array.isArray(t)?t:[t]),this.triggerTimer=new Js(T(o??lr.triggerThreshold)),e&&this.onStart.add(e,n),i&&this.onStop.add(i,n),s&&this.onActive.add(s,n),r&&this.onTrigger.add(r,n)}get activeChannels(){return this.channels}get value(){return this.valueState}update(t){this.valueState=0;for(const e of this.channels)this.valueState=Math.max(t[e],this.valueState);return this.valueState?(this.triggerTimer.running||(this.triggerTimer.restart(),this.onStart.dispatch(this.valueState)),this.onActive.dispatch(this.valueState)):this.triggerTimer.running&&(this.onStop.dispatch(this.valueState),this.triggerTimer.expired||this.onTrigger.dispatch(this.valueState),this.triggerTimer.stop()),this}destroy(){this.channels.clear(),this.triggerTimer.destroy(),this.onStart.destroy(),this.onStop.destroy(),this.onActive.destroy(),this.onTrigger.destroy()}}function ur(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}lr.triggerThreshold=300;var cr,dr={exports:{}};var _r=function(){if(cr)return dr.exports;function t(t,i,r){r=r||2;var n,o,a,u,c,_,p,f=i&&i.length,m=f?i[0]*r:t.length,g=e(t,0,m,r,!0),y=[];if(!g||g.next===g.prev)return y;if(f&&(g=function(t,i,s,r){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*r,n<o-1?i[n+1]*r:t.length,r,!1))===a.next&&(a.steiner=!0),u.push(d(a));for(u.sort(h),n=0;n<u.length;n++)s=l(u[n],s);return s}(t,i,g,r)),t.length>80*r){n=a=t[0],o=u=t[1];for(var x=r;x<m;x+=r)(c=t[x])<n&&(n=c),(_=t[x+1])<o&&(o=_),c>a&&(a=c),_>u&&(u=_);p=0!==(p=Math.max(a-n,u-o))?32767/p:0}return s(g,y,r,n,o,p,0),y}function e(t,e,i,s,r){var n,o;if(r===C(t,e,i,s)>0)for(n=e;n<i;n+=s)o=b(n,t[n],t[n+1],o);else for(n=i-s;n>=e;n-=s)o=b(n,t[n],t[n+1],o);return o&&m(o,o.next)&&(T(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!m(s,s.next)&&0!==f(s.prev,s,s.next))s=s.next;else{if(T(s),(s=e=s.prev)===s.next)break;i=!0}}while(i||s!==e);return e}function s(t,e,h,l,u,d,_){if(t){!_&&d&&function(t,e,i,s){var r=t;do{0===r.z&&(r.z=c(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){var e,i,s,r,n,o,a,h,l=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,s=i,a=0,e=0;e<l&&(a++,s=s.nextZ);e++);for(h=l;a>0||h>0&&s;)0!==a&&(0===h||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,h--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;i=s}n.nextZ=null,l*=2}while(o>1)}(r)}(t,l,u,d);for(var p,f,m=t;t.prev!==t.next;)if(p=t.prev,f=t.next,d?n(t,l,u,d):r(t))e.push(p.i/h|0),e.push(t.i/h|0),e.push(f.i/h|0),T(t),t=f.next,m=f.next;else if((t=f)===m){_?1===_?s(t=o(i(t),e,h),e,h,l,u,d,2):2===_&&a(t,e,h,l,u,d):s(i(t),e,h,l,u,d,1);break}}}function r(t){var e=t.prev,i=t,s=t.next;if(f(e,i,s)>=0)return!1;for(var r=e.x,n=i.x,o=s.x,a=e.y,h=i.y,l=s.y,u=r<n?r<o?r:o:n<o?n:o,c=a<h?a<l?a:l:h<l?h:l,d=r>n?r>o?r:o:n>o?n:o,p=a>h?a>l?a:l:h>l?h:l,m=s.next;m!==e;){if(m.x>=u&&m.x<=d&&m.y>=c&&m.y<=p&&_(r,a,n,h,o,l,m.x,m.y)&&f(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function n(t,e,i,s){var r=t.prev,n=t,o=t.next;if(f(r,n,o)>=0)return!1;for(var a=r.x,h=n.x,l=o.x,u=r.y,d=n.y,p=o.y,m=a<h?a<l?a:l:h<l?h:l,g=u<d?u<p?u:p:d<p?d:p,y=a>h?a>l?a:l:h>l?h:l,x=u>d?u>p?u:p:d>p?d:p,w=c(m,g,e,i,s),v=c(y,x,e,i,s),b=t.prevZ,T=t.nextZ;b&&b.z>=w&&T&&T.z<=v;){if(b.x>=m&&b.x<=y&&b.y>=g&&b.y<=x&&b!==r&&b!==o&&_(a,u,h,d,l,p,b.x,b.y)&&f(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,T.x>=m&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&_(a,u,h,d,l,p,T.x,T.y)&&f(T.prev,T,T.next)>=0)return!1;T=T.nextZ}for(;b&&b.z>=w;){if(b.x>=m&&b.x<=y&&b.y>=g&&b.y<=x&&b!==r&&b!==o&&_(a,u,h,d,l,p,b.x,b.y)&&f(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;T&&T.z<=v;){if(T.x>=m&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&_(a,u,h,d,l,p,T.x,T.y)&&f(T.prev,T,T.next)>=0)return!1;T=T.nextZ}return!0}function o(t,e,s){var r=t;do{var n=r.prev,o=r.next.next;!m(n,o)&&g(n,r,r.next,o)&&w(n,o)&&w(o,n)&&(e.push(n.i/s|0),e.push(r.i/s|0),e.push(o.i/s|0),T(r),T(r.next),r=t=o),r=r.next}while(r!==t);return i(r)}function a(t,e,r,n,o,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&p(h,l)){var u=v(h,l);return h=i(h,h.next),u=i(u,u.next),s(h,e,r,n,o,a,0),void s(u,e,r,n,o,a,0)}l=l.next}h=h.next}while(h!==t)}function h(t,e){return t.x-e.x}function l(t,e){var s=function(t,e){var i,s=e,r=t.x,n=t.y,o=-1/0;do{if(n<=s.y&&n>=s.next.y&&s.next.y!==s.y){var a=s.x+(n-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>o&&(o=a,i=s.x<s.next.x?s:s.next,a===r))return i}s=s.next}while(s!==e);if(!i)return null;var h,l=i,c=i.x,d=i.y,p=1/0;s=i;do{r>=s.x&&s.x>=c&&r!==s.x&&_(n<d?r:o,n,c,d,n<d?o:r,n,s.x,s.y)&&(h=Math.abs(n-s.y)/(r-s.x),w(s,t)&&(h<p||h===p&&(s.x>i.x||s.x===i.x&&u(i,s)))&&(i=s,p=h)),s=s.next}while(s!==l);return i}(t,e);if(!s)return e;var r=v(s,t);return i(r,r.next),i(s,s.next)}function u(t,e){return f(t.prev,t,e.prev)<0&&f(e.next,t,t.next)<0}function c(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function _(t,e,i,s,r,n,o,a){return(r-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(s-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(r-o)*(s-a)}function p(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&g(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(w(t,e)&&w(e,t)&&function(t,e){var i=t,s=!1,r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(f(t.prev,t,e.prev)||f(t,e.prev,e))||m(t,e)&&f(t.prev,t,t.next)>0&&f(e.prev,e,e.next)>0)}function f(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function m(t,e){return t.x===e.x&&t.y===e.y}function g(t,e,i,s){var r=x(f(t,e,i)),n=x(f(t,e,s)),o=x(f(i,s,t)),a=x(f(i,s,e));return r!==n&&o!==a||(!(0!==r||!y(t,i,e))||(!(0!==n||!y(t,s,e))||(!(0!==o||!y(i,t,s))||!(0!==a||!y(i,e,s)))))}function y(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function w(t,e){return f(t.prev,t,t.next)<0?f(t,e,t.next)>=0&&f(t,t.prev,e)>=0:f(t,e,t.prev)<0||f(t,t.next,e)<0}function v(t,e){var i=new S(t.i,t.x,t.y),s=new S(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function b(t,e,i,s){var r=new S(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function T(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function S(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function C(t,e,i,s){for(var r=0,n=e,o=i-s;n<i;n+=s)r+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return r}return cr=1,dr.exports=t,dr.exports.default=t,t.deviation=function(t,e,i,s){var r=e&&e.length,n=r?e[0]*i:t.length,o=Math.abs(C(t,0,n,i));if(r)for(var a=0,h=e.length;a<h;a++){var l=e[a]*i,u=a<h-1?e[a+1]*i:t.length;o-=Math.abs(C(t,l,u,i))}var c=0;for(a=0;a<s.length;a+=3){var d=s[a]*i,_=s[a+1]*i,p=s[a+2]*i;c+=Math.abs((t[d]-t[p])*(t[_+1]-t[d+1])-(t[d]-t[_])*(t[p+1]-t[d+1]))}return 0===o&&0===c?0:Math.abs((c-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},s=0,r=0;r<t.length;r++){for(var n=0;n<t[r].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[r][n][o]);r>0&&(s+=t[r-1].length,i.holes.push(s))}return i},dr.exports}(),pr=ur(_r);const fr=(t,e,i,s,r,n=[],o=[])=>{const a=[t,e,i,s],h=r/2,l=n.length/6,u=new ce(t-i,e-s).perp().normalize().multiply(h),c=new ce(i-t,s-e).perp().normalize().multiply(h);return n.push(t-u.x,e-u.y),n.push(t+u.x,e+u.y),n.push(i-c.x,s-c.y),n.push(i+c.x,s+c.y),o.push(l,l,l+1,l+2,l+3,l+3),new xe({vertices:n,indices:o,points:a})},mr=(t,e,i=[],s=[])=>{if(t.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const r=e/2,n=new ce(t[0],t[1]),o=new ce(t[t.length-2],t[t.length-1]);if(n.x===o.x&&n.y===o.y){(t=t.slice()).pop(),t.pop(),o.set(t[t.length-2],t[t.length-1]);const e=o.x+.5*(n.x-o.x),i=o.y+.5*(n.y-o.y);t.unshift(e,i),t.push(e,i)}const a=t.length/2;let h=t.length,l=i.length/6,u=t[0],c=t[1],d=t[2],_=t[3],p=0,f=0,m=-(c-_),g=u-d,y=0,x=0,w=0,v=0,b=Math.sqrt(m*m+g*g);m/=b,g/=b,m*=r,g*=r,i.push(u-m,c-g),i.push(u+m,c+g);for(let e=1;e<a-1;e++){u=t[2*(e-1)],c=t[2*(e-1)+1],d=t[2*e],_=t[2*e+1],p=t[2*(e+1)],f=t[2*(e+1)+1],m=-(c-_),g=u-d,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=r,g*=r,y=-(_-f),x=d-p,b=Math.sqrt(y*y+x*x),y/=b,x/=b,y*=r,x*=r;const s=-g+c-(-g+_),n=-m+d-(-m+u),o=(-m+u)*(-g+_)-(-m+d)*(-g+c),a=-x+f-(-x+_),l=-y+d-(-y+p),T=(-y+p)*(-x+_)-(-y+d)*(-x+f);let S=s*l-a*n;if(Math.abs(S)<.1){S+=10.1,i.push(d-m,_-g),i.push(d+m,_+g);continue}const C=(n*T-l*o)/S,M=(a*o-s*T)/S;(C-d)*(C-d)+(M-_)*(M-_)>196*r*r?(w=m-y,v=g-x,b=Math.sqrt(w*w+v*v),w/=b,v/=b,w*=r,v*=r,i.push(d-w,_-v),i.push(d+w,_+v),i.push(d-w,_-v),h++):(i.push(C,M),i.push(d-(C-d),_-(M-_)))}u=t[2*(a-2)],c=t[2*(a-2)+1],d=t[2*(a-1)],_=t[2*(a-1)+1],m=-(c-_),g=u-d,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=r,g*=r,i.push(d-m,_-g),i.push(d+m,_+g),s.push(l);for(let t=0;t<h;t++)s.push(l++);return s.push(l-1),new xe({vertices:i,indices:s,points:t})},gr=(t,e,i,s=[],r=[])=>{const n=Math.floor(15*Math.sqrt(i+i)),o=2*Math.PI/n,a=[];let h=s.length/6;r.push(h);for(let l=0;l<n+1;l++){const n=t+Math.sin(o*l)*i,u=e+Math.cos(o*l)*i;a.push(n,u),s.push(t,e),s.push(n,u),r.push(h++,h++)}return r.push(h-1),new xe({vertices:s,indices:r,points:a})},yr=(t,e,i,s,r=[],n=[])=>{const o=Math.floor(15*Math.sqrt(i+s)),a=2*Math.PI/o,h=[];let l=r.length/6;n.push(l);for(let u=0;u<o+1;u++){const o=t+Math.sin(a*u)*i,c=e+Math.cos(a*u)*s;h.push(o,c),r.push(t,e),r.push(o,c),n.push(l++,l++)}return n.push(l-1),new xe({vertices:r,indices:n,points:h})},xr=(t,e=[],i=[])=>{if(t.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const s=e.length/6,r=t.length/2,n=pr(t,[],2);if(n){for(let t=0;t<n.length;t+=3)i.push(n[t]+s),i.push(n[t]+s),i.push(n[t+1]+s),i.push(n[t+2]+s),i.push(n[t+2]+s);for(let i=0;i<r;i++)e.push(t[2*i],t[2*i+1])}return new xe({vertices:e,indices:i,points:t})},wr=(t,e,i,s,r=[],n=[])=>{const o=[t,e,t+i,e,t,e+s,t+i,e+s],a=r.length/6;return r.push(...o),n.push(a,a,a+1,a+2,a+3,a+3),new xe({vertices:r,indices:n,points:o})},vr=(t,e,i,s,r=s/2,n=0)=>{const o=Math.PI/-2+n,a=2*i,h=D/a,l=[];for(let i=0;i<a;i++){const n=o+i*h,a=i%2?r:s;l.push(t+a*Math.cos(n),e+a*Math.sin(n))}return xr(l)};let br=null;class Tr{constructor(t=0,e=0,i=0,s=0){this.collisionType=1,this._fromPosition=new ce(t,e),this._toPosition=new ce(i,s)}get fromPosition(){return this._fromPosition}set fromPosition(t){this._fromPosition.copy(t)}get fromX(){return this._fromPosition.x}set fromX(t){this._fromPosition.x=t}get fromY(){return this._fromPosition.y}set fromY(t){this._fromPosition.y=t}get toPosition(){return this._toPosition}set toPosition(t){this._toPosition.copy(t)}get toX(){return this._toPosition.x}set toX(t){this._toPosition.x=t}get toY(){return this._toPosition.y}set toY(t){this._toPosition.y=t}set(t,e,i,s){return this._fromPosition.set(t,e),this._toPosition.set(i,s),this}copy(t){return this._fromPosition.copy(t.fromPosition),this.toPosition.copy(t.toPosition),this}clone(){return new Tr(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:t,fromY:e,toX:i,toY:s}=this,r=Math.min(t,i),n=Math.min(e,s);return new re(r,n,Math.max(t,i)-r,Math.max(e,s)-n)}getNormals(){return[]}project(t,e=new dt){return e}intersectsWith(t){switch(t.collisionType){case 6:return Lt(this,t.getBounds());case 2:return Lt(this,t);case 5:return It(this,t);case 3:return Ft(this,t);case 4:return Dt(this,t);case 1:return kt(this,t);case 0:return Pt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return Pt(ce.temp.set(t,e),this,i)}equals({fromX:t,fromY:e,toX:i,toY:s}={}){return!(void 0!==t&&this.fromX!==t||void 0!==e&&this.fromY!==e||void 0!==i&&this.toX!==i||void 0!==s&&this.toY!==s)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===br&&(br=new Tr),br}}let Sr=null;class Cr{constructor(t=0,e=0,i=0){this.collisionType=3,this._collisionVertices=null,this._position=new ce(t,e),this._radius=i}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t){return this._radius=t,this}set(t,e,i){return this._position.set(t,e),this._radius=i,this}copy(t){return this._position.copy(t.position),this._radius=t.radius,this}clone(){return new Cr(this.x,this.y,this.radius)}equals({x:t,y:e,radius:i}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.radius!==i)}getBounds(){return new re(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){return this.getCollisionVertices().map((t,e,i)=>i[(e+1)%i.length].clone().subtract(t.x,t.y).rperp().normalize())}project(t,e=new dt){const i=t.dot(this.x,this.y),s=this.radius*t.length;return e.set(i-s,i+s)}contains(t,e){return Et(ce.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case 6:return Ut(t.getBounds(),this);case 2:return Ut(t,this);case 5:return Xt(this,t);case 3:return Gt(this,t);case 4:return zt(this,t);case 1:return Ft(t,this);case 0:return Et(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:return Zt(this,t.getBounds());case 2:return Zt(this,t);case 5:return Jt(t,this,!0);case 3:return Qt(this,t);default:return null}}destroy(){this._position.destroy()}getCollisionVertices(){if(null===this._collisionVertices){this._collisionVertices=[];for(let t=0;t<Cr.collisionSegments;t++)this._collisionVertices.push(this.getCollisionVertex(t))}return this._collisionVertices}getCollisionVertex(t){const e=2*t*Math.PI/Cr.collisionSegments-Math.PI/2,i=Math.cos(e)*this._radius,s=Math.sin(e)*this._radius;return new ce(this._radius+i,this._radius+s)}static get temp(){return null===Sr&&(Sr=new Cr),Sr}}Cr.collisionSegments=32;class Mr{constructor(t=0,e=0,i=0,s=i){this.collisionType=4,this._position=new ce(t,e),this._radius=new ce(i,s)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius.copy(t)}get rx(){return this._radius.x}set rx(t){this._radius.x=t}get ry(){return this._radius.y}set ry(t){this._radius.y=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t,e=t){return this._radius.set(t,e),this}set(t,e,i,s){return this._position.set(t,e),this._radius.set(i,s),this}copy(t){return this._position.copy(t.position),this._radius.copy(t.radius),this}clone(){return new Mr(this.x,this.y,this.rx,this.ry)}getBounds(){return new re(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new dt){return e}intersectsWith(t){switch(t.collisionType){case 6:return Vt(t.getBounds(),this);case 2:return Vt(t,this);case 5:return Yt(this,t);case 3:return zt(t,this);case 4:return jt(this,t);case 1:return Dt(t,this);case 0:return Rt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e){return Rt(ce.temp.set(t,e),this)}equals({x:t,y:e,rx:i,ry:s}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.rx!==i||void 0!==s&&this.ry!==s)}destroy(){this._position.destroy(),this._radius.destroy()}}let Pr=null;class Br{constructor(t=[],e=0,i=0){this.collisionType=5,this._points=[],this._edges=[],this._normals=[],this._position=new ce(e,i),this.setPoints(t)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get points(){return this._points}set points(t){this.setPoints(t)}get edges(){return this._edges}get normals(){return this._normals}setPosition(t,e){return this._position.set(t,e),this}setPoints(t){const e=this._points.length,i=t.length,s=e-i,r=Math.min(e,i);for(let e=0;e<r;e++)this._points[e].copy(t[e]);if(s>0)this._points.splice(i).forEach(t=>t.destroy()),this._edges.splice(i).forEach(t=>t.destroy()),this._normals.splice(i).forEach(t=>t.destroy());else if(s<0)for(let s=e;s<i;s++)this._points.push(t[s].clone()),this._edges.push(t[s].clone()),this._normals.push(t[s].clone());for(let t=0;t<i;t++){const e=this._points[t],s=this._points[(t+1)%i];this._edges[t].set(s.x-e.x,s.y-e.y),this._normals[t].copy(this._edges[t]).rperp().normalize()}return this}set(t,e,i){return this._position.set(t,e),this.setPoints(i),this}copy(t){return this._position.copy(t.position),this.setPoints(t.points),this}clone(){return new Br(this.points,this.x,this.y)}equals({x:t,y:e,points:i}={}){return(void 0===t||this.x===t)&&(void 0===e||this.y===e)&&(void 0===i||this.points.length===i.length&&this.points.every((t,e)=>t.equals(i[e])))}getBounds(){let t=1/0,e=1/0,i=-1/0,s=-1/0;for(const r of this._points)t=Math.min(r.x,t),e=Math.min(r.y,e),i=Math.max(r.x,i),s=Math.max(r.y,s);return new re(this.x+t,this.y+e,i-t,s-e)}getNormals(){return this._normals}project(t,e=new dt){const i=t.clone().normalize(),s=this._points.map(t=>i.dot(t.x,t.y));return e.set(Math.min(...s),Math.max(...s))}contains(t,e){return At(ce.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case 6:return Ot(t.getBounds(),this);case 2:return Ot(t,this);case 5:return $t(this,t);case 3:return Xt(t,this);case 4:return Yt(t,this);case 1:return It(t,this);case 0:return At(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:case 2:case 5:return te(this,t);case 3:return Jt(this,t);default:return null}}destroy(){for(const t of this._points)t.destroy();this._position.destroy(),this._points.length=0}static get temp(){return null===Pr&&(Pr=new Br),Pr}}let Er=null;class Rr{constructor(t=0,e=0,i=0,s=0){this._startPoint=new ce(t,e),this._endPoint=new ce(i,s)}get startPoint(){return this._startPoint}set startPoint(t){this._startPoint.copy(t)}get startX(){return this._startPoint.x}set startX(t){this._startPoint.x=t}get startY(){return this._startPoint.y}set startY(t){this._startPoint.y=t}get endPoint(){return this._endPoint}set endPoint(t){this._endPoint.copy(t)}get endX(){return this._endPoint.x}set endX(t){this._endPoint.x=t}get endY(){return this._endPoint.y}set endY(t){this._endPoint.y=t}set(t,e,i,s){return this._startPoint.set(t,e),this._endPoint.set(i,s),this}copy(t){return this._startPoint.copy(t.startPoint),this._endPoint.copy(t.endPoint),this}clone(){return new Rr(this.startX,this.startY,this.endX,this.endY)}equals({startX:t,startY:e,endX:i,endY:s}={}){return!(void 0!==t&&this.startX!==t||void 0!==e&&this.startY!==e||void 0!==i&&this.endX!==i||void 0!==s&&this.endY!==s)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===Er&&(Er=new Rr),Er}}class Ar{constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new Ar(t.length,0)}toVector(){return ce.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}class kr{constructor(t,e){this._fromColor=t.clone(),this._toColor=e.clone()}get fromColor(){return this._fromColor}set fromColor(t){this.setFromColor(t)}get toColor(){return this._toColor}set toColor(t){this.setToColor(t)}setFromColor(t){return this._fromColor.copy(t),this}setToColor(t){return this._toColor.copy(t),this}apply(t,e){const i=t.elapsedRatio,{r:s,g:r,b:n,a:o}=this._fromColor,{r:a,g:h,b:l,a:u}=this._toColor;return t.tint.set((a-s)*i+s,(h-r)*i+r,(l-n)*i+n,(u-o)*i+o),this}destroy(){this._fromColor.destroy(),this._toColor.destroy()}}class Lr{constructor(t,e){this._acceleration=new ce(t,e)}get acceleration(){return this._acceleration}set acceleration(t){this.setAcceleration(t)}setAcceleration(t){return this._acceleration.copy(t),this}apply(t,e){return t.velocity.add(e.seconds*this._acceleration.x,e.seconds*this._acceleration.y),this}destroy(){this._acceleration.destroy()}}class Fr{constructor(t,e){this._scaleFactor=new ce(t,e)}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this.setScaleFactor(t)}setScaleFactor(t){return this._scaleFactor.copy(t),this}apply(t,e){return t.scale.add(e.seconds*this._scaleFactor.x,e.seconds*this._scaleFactor.y),this}destroy(){this._scaleFactor.destroy()}}class Dr{constructor(t){this._angularAcceleration=t}get angularAcceleration(){return this._angularAcceleration}set angularAcceleration(t){this.setAngularAcceleration(t)}setAngularAcceleration(t){return this._angularAcceleration=t,this}apply(t,e){return t.rotationSpeed+=e.seconds*this._angularAcceleration,this}destroy(){}}class Ir{constructor(t={}){const{totalLifetime:e,elapsedLifetime:i,position:s,velocity:n,scale:o,rotation:a,rotationSpeed:h,textureIndex:l,tint:u}=t;this._totalLifetime=(e??r.oneSecond).clone(),this._elapsedLifetime=(i??r.zero).clone(),this._position=(s??ce.zero).clone(),this._velocity=(n??ce.zero).clone(),this._scale=(o??ce.one).clone(),this._tint=(u??K.white).clone(),this._rotation=a??0,this._rotationSpeed=h??0,this._textureIndex=l??0}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=U(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get tint(){return this._tint}set tint(t){this._tint.copy(t)}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class Nr{constructor(t,e){this._emissionDelta=0,this._emissionRate=t,this._particleOptions=e??new Ir}get emissionRate(){return this._emissionRate}set emissionRate(t){this._emissionRate=t}get particleOptions(){return this._particleOptions}set particleOptions(t){this._particleOptions=t}computeParticleCount(t){const e=this._emissionRate*t.seconds+this._emissionDelta,i=0|e;return this._emissionDelta=e-i,i}apply(t,e){const i=this.computeParticleCount(e),s=this._particleOptions;for(let e=0;e<i;e++){const e=t.requestParticle();e.applyOptions(s),t.emitParticle(e)}return this}destroy(){this._particleOptions.destroy()}}class Ur extends xe{constructor(t,e,i){const s=Math.floor(15*Math.sqrt(i+i)),r=2*Math.PI/s,n=[],o=[],a=[];let h=n.length/6;o.push(h);for(let l=0;l<s+1;l++){const s=t+Math.sin(r*l)*i,u=e+Math.cos(r*l)*i;a.push(s,u),n.push(t,e),n.push(s,u),o.push(h++,h++)}o.push(h-1),super({vertices:n,indices:o,points:a})}}class Vr extends Qs{constructor(){super(...arguments),this._lineWidth=0,this._lineColor=new K,this._fillColor=new K,this._currentPoint=new ce(0,0)}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t}get lineColor(){return this._lineColor}set lineColor(t){this._lineColor.copy(t)}get fillColor(){return this._fillColor}set fillColor(t){this._fillColor.copy(t)}get currentPoint(){return this._currentPoint}getChildAt(t){return super.getChildAt(t)}addChild(t){if(!(t instanceof ye))throw new Error("Graphics can only contain DrawableShape children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof ye))throw new Error("Graphics can only contain DrawableShape children.");return super.addChildAt(t,e)}moveTo(t,e){return this._currentPoint.set(t,e),this}lineTo(t,e){const{x:i,y:s}=this._currentPoint;return this.drawPath([i,s,t,e]),this.moveTo(t,e),this}quadraticCurveTo(t,e,i,s){const{x:r,y:n}=this._currentPoint;return this.drawPath(Y(r,n,t,e,i,s)),this.moveTo(i,s),this}bezierCurveTo(t,e,i,s,r,n){const{x:o,y:a}=this._currentPoint;return this.drawPath(j(o,a,t,e,i,s,r,n)),this.moveTo(r,n),this}arcTo(t,e,i,s,r){const{x:n,y:o}=this._currentPoint,a=Math.abs(r);if(0===a||n===t&&o===e||t===i&&e===s)return this.lineTo(t,e);const h=t-n,l=e-o,u=i-t,c=s-e,d=Math.hypot(h,l),_=Math.hypot(u,c);if(0===d||0===_)return this.lineTo(t,e);const p=h/d,f=l/d,m=u/_,g=c/_,y=G(p*m+f*g,-1,1),x=Math.acos(y);if(0===x||x===Math.PI)return this.lineTo(t,e);const w=a/Math.tan(x/2);if(!Number.isFinite(w)||w>d||w>_)return this.lineTo(t,e);const v=t-p*w,b=e-f*w,T=t+m*w,S=e+g*w,C=p*g-f*m>0,M=v+(C?-f:f)*a,P=b+(C?p:-p)*a,B=Math.atan2(b-P,v-M),E=Math.atan2(S-P,T-M);return this.lineTo(v,b),this.drawArc(M,P,a,B,E,C)}drawArc(t,e,i,s,r,n=!1){const o=Math.abs(i);if(0===o)return this;let a=r-s;if(!n&&a<0?a+=D:n&&a>0&&(a-=D),0===a)return this;const h=Math.max(2,Math.ceil(Math.abs(a)/(Math.PI/16))),l=[];for(let i=0;i<=h;i++){const r=s+a*(i/h);l.push(t+Math.cos(r)*o,e+Math.sin(r)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(t,e,i,s){return this.addChild(new ye(fr(t,e,i,s,this._lineWidth),this._lineColor,tt.TriangleStrip)),this}drawPath(t){return this.addChild(new ye(mr(t,this._lineWidth),this._lineColor,tt.TriangleStrip)),this}drawPolygon(t){const e=xr(t);return this.addChild(new ye(e,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(e.points),this}drawCircle(t,e,i){const s=new Ur(t,e,i);return this.addChild(new ye(s,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(s.points),this}drawEllipse(t,e,i,s){const r=yr(t,e,i,s);return this.addChild(new ye(r,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(r.points),this}drawRectangle(t,e,i,s){const r=wr(t,e,i,s);return this.addChild(new ye(r,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(r.points),this}drawStar(t,e,i,s,r=s/2,n=0){const o=vr(t,e,i,s,r,n);return this.addChild(new ye(o,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._lineColor.copy(K.black),this._fillColor.copy(K.black),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}}class Or{constructor(t,e){this.frames=new Map,this.sprites=new Map,this.animations=new Map,this.texture=t,this.parse(e)}parse(t,e=!1){e||this.clear();for(const[e,i]of Object.entries(t.frames))this.addFrame(e,i);if(t.animations)for(const[e,i]of Object.entries(t.animations))this.defineAnimation(e,i)}addFrame(t,e){const{x:i,y:s,w:r,h:n}=e.frame,o=new re(i,s,r,n),a=new qe(this.texture);a.setTextureFrame(o),this.frames.set(t,o),this.sprites.set(t,a)}defineAnimation(t,e){if(0===t.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(!Array.isArray(e)||0===e.length)throw new Error(`Spritesheet animation "${t}" must reference at least one frame.`);for(const i of e)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${t}" references missing frame "${i}".`);return this.animations.set(t,[...e]),this}getFrame(t){const e=this.frames.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}getAnimationFrameNames(t){const e=this.animations.get(t);if(!e)throw new Error(`Spritesheet animation named ${t} is not available!`);return e}getFrameSprite(t){const e=this.sprites.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}clear(){for(const t of this.frames.values())t.destroy();this.frames.clear();for(const t of this.sprites.values())t.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}}class Gr extends qe{constructor(t,e){super(t),this._clips=new Map,this._currentClipName=null,this._currentFrameIndex=0,this._playing=!1,this._loopOverride=null,this._elapsedFrameTimeMs=0,this.onComplete=new F,this.onFrame=new F,e&&this.setClips(e)}get currentClip(){return this._currentClipName}get currentFrame(){return this._currentFrameIndex}get playing(){return this._playing}get loop(){return null!==this._loopOverride?this._loopOverride:!!this._currentClipName&&(this._clips.get(this._currentClipName)?.loop??!1)}set loop(t){this._loopOverride=t}setClips(t){this._clips.clear();for(const[e,i]of Object.entries(t))this.defineClip(e,i);return this}defineClip(t,e){if(0===t.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");if(!Array.isArray(e.frames)||0===e.frames.length)throw new Error(`AnimatedSprite clip "${t}" must define at least one frame.`);const i=e.fps??12;if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid fps value (${i}).`);return this._clips.set(t,{frames:e.frames.map(t=>t.clone()),frameDurationMs:1e3/i,loop:e.loop??!0}),this}removeClip(t){return this._currentClipName===t&&this.stop(),this._clips.delete(t),this}play(t,e={}){const i=this._clips.get(t);if(!i)throw new Error(`AnimatedSprite clip "${t}" is not defined.`);const s=this._currentClipName===t,r=e.restart??!0;return s&&!r||(this._currentClipName=t,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._applyFrame(i.frames[0]),this.onFrame.dispatch(t,0)),this._loopOverride=e.loop??this._loopOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const t=this._clips.get(this._currentClipName);return t&&t.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(t.frames[0]),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(t){if(!this._playing||null===this._currentClipName)return this;const e=this._clips.get(this._currentClipName);if(!e||e.frames.length<=1)return this;const i="number"==typeof t?t:t.milliseconds;if(i<=0)return this;for(this._elapsedFrameTimeMs+=i;this._elapsedFrameTimeMs>=e.frameDurationMs;){this._elapsedFrameTimeMs-=e.frameDurationMs;const t=this._currentFrameIndex+1;if(t>=e.frames.length){if(this.loop){this._currentFrameIndex=0,this._applyFrame(e.frames[0]),this.onFrame.dispatch(this._currentClipName,0);continue}this._currentFrameIndex=e.frames.length-1,this._applyFrame(e.frames[this._currentFrameIndex]),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=t,this._applyFrame(e.frames[this._currentFrameIndex]),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex)}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const t of this._clips.values())for(const e of t.frames)e.destroy();this._clips.clear()}static fromSpritesheet(t){const e={};for(const[i,s]of t.animations)e[i]={frames:s.map(e=>t.getFrame(e)),loop:!0};return new Gr(t.texture,e)}_applyFrame(t){this.setTextureFrame(t,!1)}}class zr{constructor(t={}){this._dirty=!0,this._align=t.align??"left",this._fill=t.fill??"black",this._stroke=t.stroke??"black",this._strokeThickness=t.strokeThickness??1,this._fontSize=t.fontSize??20,this._fontWeight=t.fontWeight??"bold",this._fontFamily=t.fontFamily??"Arial",this._wordWrap=t.wordWrap??!1,this._wordWrapWidth=t.wordWrapWidth??100,this._baseline=t.baseline??"alphabetic",this._lineJoin=t.lineJoin??"miter",this._miterLimit=t.miterLimit??10,this._padding=t.padding??0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this._dirty=!0)}get fill(){return this._fill}set fill(t){this._fill!==t&&(this._fill=t,this._dirty=!0)}get stroke(){return this._stroke}set stroke(t){this._stroke!==t&&(this._stroke=t,this._dirty=!0)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this._dirty=!0)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this._dirty=!0)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this._dirty=!0)}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this._dirty=!0)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this._dirty=!0)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this._dirty=!0)}get baseline(){return this._baseline}set baseline(t){this._baseline!==t&&(this._baseline=t,this._dirty=!0)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this._dirty=!0)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this._dirty=!0)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this._dirty=!0)}get dirty(){return this._dirty}set dirty(t){this._dirty=t}get font(){return`${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}apply(t){return t.font=this.font,t.fillStyle=this.fill,t.strokeStyle=this.stroke,t.lineWidth=this.strokeThickness,t.textBaseline=this.baseline,t.lineJoin=this.lineJoin,t.miterLimit=this.miterLimit,this}copy(t){return t!==this&&(this.align=t.align,this.fill=t.fill,this.stroke=t.stroke,this.strokeThickness=t.strokeThickness,this.fontSize=t.fontSize,this.fontWeight=t.fontWeight,this.fontFamily=t.fontFamily,this.wordWrap=t.wordWrap,this.wordWrapWidth=t.wordWrapWidth,this.baseline=t.baseline,this.lineJoin=t.lineJoin,this.miterLimit=t.miterLimit,this.padding=t.padding,this.dirty=t.dirty),this}clone(){return(new zr).copy(this)}}const Wr=/(?:\r\n|\r|\n)/;class qr extends qe{constructor(t,e,i,s=document.createElement("canvas")){super(new je(s,i)),this._dirty=!0,this._text=t,this._style=e&&e instanceof zr?e:new zr(e),this._canvas=s,this._context=s.getContext("2d"),this.updateTexture()}get text(){return this._text}set text(t){this.setText(t)}get style(){return this._style}set style(t){this.setStyle(t)}get canvas(){return this._canvas}set canvas(t){this.setCanvas(t)}setText(t){return this._text!==t&&(this._text=t,this._dirty=!0),this}setStyle(t){return this._style=t instanceof zr?t:new zr(t),this._dirty=!0,this}setCanvas(t){return this._canvas!==t&&(this._canvas=t,this._context=this._getContext(t),this._dirty=!0,this.texture.setSource.call(this.texture,t),this.setTextureFrame(re.temp.set(0,0,t.width,t.height))),this}updateTexture(){if(this._style&&(this._dirty||this._style.dirty)){const t=this._canvas,e=this._context,i=this._style.apply(e),s=i.wordWrap?this.getWordWrappedText():this._text,r=(t=>{if(!Ue.has(t)){const e=document.body,i=document.createElement("div");i.appendChild(document.createTextNode("M")),i.setAttribute("style",`font: ${t};position:absolute;top:0;left:0`),e.appendChild(i),Ue.set(t,i.offsetHeight),e.removeChild(i)}return Ue.get(t)})(e.font)+i.strokeThickness,n=s.split(Wr),o=n.map(t=>e.measureText(t)),a=o.reduce((t,e)=>Math.max(t,e.width),0),h=Math.ceil(a+i.strokeThickness+2*i.padding),l=Math.ceil(r*n.length+2*i.padding);h!==t.width||l!==t.height?(t.width=h,t.height=l,this.setTextureFrame(re.temp.set(0,0,h,l))):e.clearRect(0,0,h,l),i.apply(e);for(let t=0;t<n.length;t++){const s=o[t],h=a-s.width,l="right"===i.align?h:h/2,u=i.padding+i.strokeThickness/2,c=s.actualBoundingBoxLeft+("left"===i.align?0:l)+u,d=s.actualBoundingBoxAscent+r*t+u;i.stroke&&i.strokeThickness&&e.strokeText(n[t],c,d),i.fill&&e.fillText(n[t],c,d)}this.texture.updateSource(),this._dirty=!1,this._style.dirty=!1}return this}getWordWrappedText(){const t=this._context,e=this._style.wordWrapWidth,i=this._text.split("\n"),s=t.measureText(" ").width;let r=e,n="";for(let o=0;o<i.length;o++){const a=i[o].split(" ");o>0&&(n+="\n");for(let i=0;i<a.length;i++){const o=a[i],h=t.measureText(o).width+s;h>r?(i>0&&(n+="\n"),r=e):r-=h,n+=`${o} `}}return n}render(t){return this.visible&&(this.updateTexture(),super.render(t)),this}_getContext(t){const e=t.getContext("2d");if(null===e)throw new Error("Could not create a 2D canvas context.");return e}}class Hr{constructor(t,e){const{scaleMode:i,wrapMode:s,premultiplyAlpha:r,generateMipMap:n,flipY:o}=e;this._context=t,this._sampler=t.createSampler(),this._scaleMode=i,this._wrapMode=s,this._premultiplyAlpha=r,this._generateMipMap=n,this._flipY=o,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this.updateScaleModeParameters()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this.updateWrapModeParameters()),this}bind(t){return this._context.bindSampler(t,this._sampler),this}destroy(){this._context.deleteSampler(this._sampler)}updateScaleModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_MAG_FILTER,this._scaleMode),t.samplerParameteri(this._sampler,t.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_S,this._wrapMode),t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_T,this._wrapMode)}}class Xr{constructor(t){this._callback=t}execute(t){this._callback(t)}}class jr{}class Yr extends jr{constructor(t={}){super(),this._sprite=new qe(null),this._sampleTint=K.white.clone(),this._radius=2,this._quality=1,this._radius=Math.max(0,t.radius??2),this._quality=Math.max(1,Math.floor(t.quality??1))}get radius(){return this._radius}set radius(t){this._radius=Math.max(0,t)}get quality(){return this._quality}set quality(t){this._quality=Math.max(1,Math.floor(t))}apply(t,e,i){const s=this._radius,r=this._quality,n=Math.max(1,2*r+1),o=1/(s<=0?1:2*n);this._sampleTint.set(255,255,255,o),this._sprite.setTexture(e).setBlendMode(Q.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new pe(()=>{if(s<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<n;e++){const i=(2*(1===n?0:e/(n-1))-1)*s;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:i,view:i.view,clearColor:K.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}}class $r extends jr{constructor(t=K.white){super(),this._sprite=new qe(null),this._color=t.clone()}get color(){return this._color}apply(t,e,i){this._sprite.setTexture(e).setBlendMode(Q.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new pe(()=>{this._sprite.render(t)},{target:i,view:i.view,clearColor:K.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}}class Kr{async resolve(t,e){const{storageName:i,key:s,url:r,requestOptions:n,factory:o}=t;for(const t of e){const e=await t.load(i,s);if(null!=e)try{return await o.create(e),e}catch{await t.delete(i,s)}}const a=await fetch(r,n);if(!a.ok)throw new Error(`Failed to fetch "${r}" (${a.status} ${a.statusText}).`);const h=await o.process(a);for(const t of e)try{await t.save(i,s,h)}catch{}return h}}class Qr{async resolve(t,e){const i=await fetch(t.url,t.requestOptions);if(!i.ok)throw new Error(`Failed to fetch "${t.url}" (${i.status} ${i.statusText}).`);return t.factory.process(i)}}const Zr=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"];class Jr{get connected(){return this._connected}constructor(t,e=1,i=Zr,s){if(this._onCloseHandler=this.disconnect.bind(this),this._connected=!1,this._database=null,!y)throw new Error("This browser does not support indexedDB!");this.name=t,this.version=e,this._storeNames=i,this._migrations=s}async getObjectStore(t,e="readonly"){return await this.connect(),this._database.transaction([t],e).objectStore(t)}async connect(){return!(!this._connected||!this._database)||new Promise((t,e)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",t=>{const s=i.result,r=i.transaction,n=[...r.objectStoreNames],{oldVersion:o,newVersion:a}=t;if(s.addEventListener("error",()=>e(Error("An error occurred while opening the database."))),s.addEventListener("abort",()=>e(Error("The database opening was aborted."))),this._migrations){const t=Object.keys(this._migrations).map(Number).filter(t=>t>o&&t<=(a??this.version)).sort((t,e)=>t-e);for(const e of t){if(!this._migrations[e](s,r))return void r.abort()}}else{for(const t of n)this._storeNames.includes(t)||s.deleteObjectStore(t);for(const t of this._storeNames)n.includes(t)||s.createObjectStore(t,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,t(!0)}),i.addEventListener("error",()=>e(Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>e(Error("The request for the database connection has been blocked.")))})}async disconnect(){return this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close(),this._database=null,this._connected=!1),!0}async load(t,e){const i=await this.getObjectStore(t);return new Promise((t,s)=>{const r=i.get(e);r.addEventListener("success",()=>t(r.result?.data??null)),r.addEventListener("error",()=>s(Error("An error occurred while loading an item.")))})}async save(t,e,i){const s=await this.getObjectStore(t,"readwrite");return new Promise((t,r)=>{const n=s.put({name:e,data:i});n.addEventListener("success",()=>t()),n.addEventListener("error",()=>r(Error("An error occurred while saving an item.")))})}async delete(t,e){const i=await this.getObjectStore(t,"readwrite");return new Promise((t,s)=>{const r=i.delete(e);r.addEventListener("success",()=>t(!0)),r.addEventListener("error",()=>s(Error("An error occurred while deleting an item.")))})}async clearStorage(t){const e=await this.getObjectStore(t,"readwrite");return new Promise((t,i)=>{const s=e.clear();s.addEventListener("success",()=>t(!0)),s.addEventListener("error",()=>i(Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((t,e)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>t(!0)),i.addEventListener("error",()=>e(Error("An error occurred while deleting a storage.")))})}destroy(){this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close()),this._database=null,this._connected=!1}}class tn{constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new Jr(e.name,e.version??1,e.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"],e.migrations)}async load(t,e){return this._db.load(t,e)}async save(t,e,i){return this._db.save(t,e,i)}async delete(t,e){return this._db.delete(t,e)}async clear(t){return this._db.clearStorage(t)}destroy(){this._db.destroy()}}const en="@dimforge/rapier2d-compat",sn=65535,rn=1/60,nn={lineWidth:1,solidLineColor:new K(64,196,255,1),solidFillColor:new K(64,196,255,.12),triggerLineColor:new K(255,180,48,1),triggerFillColor:new K(255,180,48,.08)},on=async()=>await import(en),an=(t,e)=>{if(!Number.isFinite(t))throw new Error(`${e} must be a finite number.`)},hn=(t,e)=>{if(an(t,e),t<=0)throw new Error(`${e} must be greater than zero.`)},ln=(t,e)=>{if(!Number.isInteger(t)||t<0||t>15)throw new Error(`${e} must be an integer between 0 and 15.`)},un=(t,e)=>void 0===t?e:"number"==typeof t?(ln(t,"collision group"),1<<t):0===t.length?0:t.reduce((t,e,i)=>(ln(e,`collision groups[${i}]`),t|1<<e),0),cn=t=>{const e=un(t?.membership,1),i=un(t?.collidesWith,sn);return(e&sn)<<16|i&sn},dn=t=>({x:t.offsetX??0,y:t.offsetY??0}),_n=(t,e,i)=>{const s=Math.cos(i),r=Math.sin(i);return{x:t*s-e*r,y:t*r+e*s}},pn=t=>{(t=>{if("box"===t.type)return hn(t.width,"Box width"),hn(t.height,"Box height"),an(t.offsetX??0,"Box offsetX"),an(t.offsetY??0,"Box offsetY"),void an(t.offsetRotation??0,"Box offsetRotation");hn(t.radius,"Circle radius"),an(t.offsetX??0,"Circle offsetX"),an(t.offsetY??0,"Circle offsetY")})(t.shape),an(t.friction??0,"friction"),an(t.restitution??0,"restitution"),an(t.density??0,"density"),an(t.gravityScale??1,"gravityScale"),an(t.linearDamping??0,"linearDamping"),an(t.angularDamping??0,"angularDamping"),cn(t.collisionFilter)};class fn{constructor(t,e,i,s,r){this._world=t,this.node=e,this._body=i,this._collider=s,this.bodyType=r.type??"dynamic",this.shape=r.shape,this.trigger=r.trigger??!1,this._syncMode=r.syncMode??"physicsToNode"}get bodyHandle(){return this._body.handle}get colliderHandle(){return this._collider.handle}getBody(){return this._body}get syncMode(){return this._syncMode}set syncMode(t){this._syncMode=t}get x(){return this._body.translation().x}get y(){return this._body.translation().y}get rotation(){return this._body.rotation()}setSyncMode(t){return this._syncMode=t,this}teleport(t,e,i=this.node.rotation){return this._world.writeBodyTransform(this._body,t,e,i,!0),this.node.setPosition(t,e),this.node.setRotation(i),this}syncBodyFromNode(t=!0){return this._world.writeBodyTransform(this._body,this.node.x,this.node.y,this.node.rotation,t),this}syncNodeFromBody(){const t=this._body.translation();return this.node.setPosition(t.x,t.y),this.node.setRotation(this._body.rotation()),this}setCollisionFilter(t){const e=cn(t);return this._collider.setCollisionGroups(e),this._collider.setSolverGroups(e),this}destroy(){this._world.removeBinding(this)}}class mn{constructor(t,e,i){this.onCollisionEnter=new F,this.onCollisionExit=new F,this.onTriggerEnter=new F,this.onTriggerExit=new F,this._bindings=new Set,this._nodeBindings=new Map,this._colliderBindings=new Map,this._rapier=t,this._world=e,this._eventQueue=i}static async create(t={}){const e=t.moduleLoader??on;let i=null;try{i=await e()}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Rapier physics module is unavailable. Install "${en}" or provide a custom module loader. Original error: ${e}`)}const s=(t=>{const e=t,i=e.Vector2,s=e.World,r=e.EventQueue,n=e.RigidBodyDesc,o=e.ColliderDesc;if("function"!=typeof i||"function"!=typeof s||"function"!=typeof r)throw new Error("Invalid Rapier module loader result. Expected Vector2, World, and EventQueue exports.");if("object"!=typeof n||null===n||"object"!=typeof o||null===o)throw new Error("Invalid Rapier module loader result. Expected RigidBodyDesc and ColliderDesc exports.");const a=e.ActiveEvents,h="number"==typeof a?.COLLISION_EVENTS?a.COLLISION_EVENTS:void 0;return{init:"function"==typeof e.init?e.init:void 0,vector2:i,worldConstructor:s,eventQueueConstructor:r,rigidBodyDescFactory:n,colliderDescFactory:o,activeCollisionEvents:h}})(i);"function"==typeof s.init&&await s.init();const r=t.gravityX??0,n=t.gravityY??9.81;an(r,"gravityX"),an(n,"gravityY");const o=new s.worldConstructor(new s.vector2(r,n)),a=new s.eventQueueConstructor(!0);return new mn(s,o,a)}get gravity(){return{x:this._world.gravity.x,y:this._world.gravity.y}}setGravity(t,e){return an(t,"gravityX"),an(e,"gravityY"),this._world.gravity.x=t,this._world.gravity.y=e,this}hasNode(t){return this._nodeBindings.has(t)}getBinding(t){return this._nodeBindings.get(t)??null}attachNode(t,e){if(this._nodeBindings.has(t))throw new Error("This SceneNode is already attached to a physics body.");pn(e);const i=this.createBodyDescriptor(t,e),s=this._world.createRigidBody(i),r=this.createColliderDescriptor(e),n=this._world.createCollider(r,s),o=new fn(this,t,s,n,e);return this._bindings.add(o),this._nodeBindings.set(t,o),this._colliderBindings.set(n.handle,o),o}detachNode(t){const e=this._nodeBindings.get(t);return e&&this.removeBinding(e),this}step(t=rn){if(an(t,"deltaSeconds"),t<0)throw new Error("deltaSeconds must be zero or greater.");return this.applyStepDelta(t),this._world.step(this._eventQueue),this.drainCollisionEvents(),this.syncNodeTransforms(),this}syncNodeTransforms(){for(const t of this._bindings)"physicsToNode"===t.syncMode&&t.syncNodeFromBody();return this}createDebugGraphics(t={}){const e=new Vr;return e.setCullable(!1),this.updateDebugGraphics(e,t),e}updateDebugGraphics(t,e={}){const i=e.lineWidth??nn.lineWidth,s=e.solidLineColor??nn.solidLineColor,r=e.solidFillColor??nn.solidFillColor,n=e.triggerLineColor??nn.triggerLineColor,o=e.triggerFillColor??nn.triggerFillColor;t.clear(),t.lineWidth=i;for(const e of this._bindings){const i={x:e.x,y:e.y},a=e.rotation,h=e.trigger?n:s,l=e.trigger?o:r;if(t.lineColor=h,t.fillColor=l,"box"===e.shape.type){const s=this.buildBoxPath(e.shape,i.x,i.y,a);t.drawPolygon(s)}else{const s=dn(e.shape),r=_n(s.x,s.y,a);t.drawCircle(i.x+r.x,i.y+r.y,e.shape.radius)}}return t}destroy(){for(const t of Array.from(this._bindings))this.removeBinding(t);this.onCollisionEnter.destroy(),this.onCollisionExit.destroy(),this.onTriggerEnter.destroy(),this.onTriggerExit.destroy()}writeBodyTransform(t,e,i,s,r){t.setTranslation(new this._rapier.vector2(e,i),r),t.setRotation(s,r)}removeBinding(t){this._bindings.has(t)&&(this._bindings.delete(t),this._nodeBindings.delete(t.node),this._colliderBindings.delete(t.colliderHandle),this._world.removeRigidBody(t.getBody()))}createBodyDescriptor(t,e){const i=e.type??"dynamic";let s=this._rapier.rigidBodyDescFactory.dynamic();switch(i){case"static":s=this._rapier.rigidBodyDescFactory.fixed();break;case"kinematic":if("function"==typeof this._rapier.rigidBodyDescFactory.kinematicPositionBased)s=this._rapier.rigidBodyDescFactory.kinematicPositionBased();else{if("function"!=typeof this._rapier.rigidBodyDescFactory.kinematicVelocityBased)throw new Error("Rapier module does not expose a kinematic rigid-body descriptor.");s=this._rapier.rigidBodyDescFactory.kinematicVelocityBased()}break;default:s=this._rapier.rigidBodyDescFactory.dynamic()}return s.setTranslation(t.x,t.y).setRotation(t.rotation).setLinearDamping(e.linearDamping??0).setAngularDamping(e.angularDamping??0).setGravityScale(e.gravityScale??1).lockRotations(e.lockRotation??!1),s}createColliderDescriptor(t){const e=t.shape,i="box"===e.type?this._rapier.colliderDescFactory.cuboid(e.width/2,e.height/2):this._rapier.colliderDescFactory.ball(e.radius),s=dn(e),r=cn(t.collisionFilter);i.setTranslation(s.x,s.y).setRotation("box"===e.type?e.offsetRotation??0:0).setSensor(t.trigger??!1).setFriction(t.friction??.5).setRestitution(t.restitution??0).setDensity(t.density??1).setCollisionGroups(r).setSolverGroups(r);const n=this._rapier.activeCollisionEvents;return"number"==typeof n&&i.setActiveEvents(n),i}applyStepDelta(t){const e=this._world;"number"==typeof e.timestep&&(e.timestep=t),e.integrationParameters&&"number"==typeof e.integrationParameters.dt&&(e.integrationParameters.dt=t)}drainCollisionEvents(){this._eventQueue.drainCollisionEvents((t,e,i)=>{const s=this._colliderBindings.get(t),r=this._colliderBindings.get(e);if(!s||!r)return;const n=s.trigger||r.trigger,o={started:i,trigger:n,first:s,second:r};n?i?this.onTriggerEnter.dispatch(o):this.onTriggerExit.dispatch(o):i?this.onCollisionEnter.dispatch(o):this.onCollisionExit.dispatch(o)})}buildBoxPath(t,e,i,s){const r=t.width/2,n=t.height/2,o=[{x:-r,y:-n},{x:r,y:-n},{x:r,y:n},{x:-r,y:n}],a=dn(t),h=t.offsetRotation??0,l=[];for(const t of o){const r=_n(t.x,t.y,h),n={x:r.x+a.x,y:r.y+a.y},o=_n(n.x,n.y,s);l.push(e+o.x,i+o.y)}return l}}const gn=async(t={})=>await mn.create(t);export{bs as AbstractAssetFactory,Yi as AbstractMedia,Ve as AbstractWebGl2BatchedRenderer,Ce as AbstractWebGl2Renderer,ti as AbstractWebGpuRenderer,Gr as AnimatedSprite,$s as Application,Xs as ApplicationStatus,bi as ArcadeStickGamepadMapping,tr as AudioAnalyser,Is as BinaryFactory,Q as BlendModes,Yr as BlurFilter,ne as Bounds,et as BufferTypes,it as BufferUsage,Os as BundleLoadError,Kr as CacheFirstStrategy,Xr as CallbackRenderPass,ci as ChannelSize,Cr as Circle,Ur as CircleGeometry,L as Clock,K as Color,kr as ColorAffector,$r as ColorFilter,Qs as Container,ge as Drawable,ye as DrawableShape,Mr as Ellipse,vs as FactoryRegistry,jr as Filter,ht as Flags,Ts as FontFactory,Lr as ForceAffector,Mi as GameCubeGamepadMapping,gi as Gamepad,fi as GamepadChannel,xi as GamepadControl,wi as GamepadMapping,mi as GamepadMappingFamily,hr as GamepadPromptLayouts,Ci as GenericDualAnalogGamepadMapping,xe as Geometry,Vr as Graphics,Ms as ImageFactory,Jr as IndexedDbDatabase,tn as IndexedDbStore,lr as Input,ji as InputManager,dt as Interval,Pi as JoyConLeftGamepadMapping,Bi as JoyConRightGamepadMapping,gs as Json,Ps as JsonFactory,di as Keyboard,Tr as Line,Hs as Loader,at as Matrix,ps as Music,Es as MusicFactory,Qr as NetworkOnlyStrategy,ae as ObservableSize,nt as ObservableVector,He as Particle,Ir as ParticleOptions,Xe as ParticleSystem,Ei as PlayStationGamepadMapping,yi as Pointer,pi as PointerState,_i as PointerStateFlag,Ar as PolarVector,Br as Polygon,Ks as Quadtree,i as Random,fn as RapierPhysicsBinding,mn as RapierPhysicsWorld,re as Rectangle,Se as RenderBackendType,me as RenderNode,de as RenderTarget,pe as RenderTargetPass,_e as RenderTexture,Ye as RendererRegistry,tt as RenderingPrimitives,Hr as Sampler,Fr as ScaleAffector,Z as ScaleModes,Zs as Scene,ve as SceneManager,oe as SceneNode,Rr as Segment,Me as Shader,Re as ShaderAttribute,st as ShaderPrimitives,Ae as ShaderUniform,F as Signal,e as Size,fs as Sound,Rs as SoundFactory,qe as Sprite,We as SpriteFlags,Or as Spritesheet,Ri as SteamControllerGamepadMapping,xs as SvgAsset,Ds as SvgFactory,Ai as SwitchProGamepadMapping,qr as Text,ys as TextAsset,As as TextFactory,zr as TextStyle,je as Texture,ks as TextureFactory,r as Time,Js as Timer,Dr as TorqueAffector,ut as Transformable,lt as TransformableFlags,Nr as UniversalEmitter,ce as Vector,ms as Video,Fs as VideoFactory,le as View,he as ViewFlags,ws as VttAsset,Vs as VttFactory,Ns as WasmFactory,Ge as WebGl2ParticleRenderer,ze as WebGl2PrimitiveRenderer,Ie as WebGl2RenderBuffer,Je as WebGl2RenderManager,ke as WebGl2ShaderBlock,Oe as WebGl2SpriteRenderer,Te as WebGl2VertexArrayObject,hi as WebGpuParticleRenderer,ii as WebGpuPrimitiveRenderer,ui as WebGpuRenderManager,ri as WebGpuSpriteRenderer,J as WrapModes,ki as XboxGamepadMapping,j as bezierCurveTo,gr as buildCircle,yr as buildEllipse,fr as buildLine,mr as buildPath,xr as buildPolygon,wr as buildRectangle,vr as buildStar,Hi as builtInGamepadDefinitions,k as canvasSourceToDataUrl,G as clamp,gn as createRapierPhysicsWorld,$e as createRenderStats,Fe as createWebGl2ShaderRuntime,_s as decodeAudioData,Gs as defineAssetManifest,N as degreesPerRadian,V as degreesToRadians,Cs as determineMimeType,P as emptyArrayBuffer,us as getAudioContext,R as getCanvasSourceSize,Qt as getCollisionCircleCircle,Zt as getCollisionCircleRectangle,Jt as getCollisionPolygonCircle,Kt as getCollisionRectangleRectangle,te as getCollisionSat,X as getDistance,ds as getOfflineAudioContext,b as getPreciseTime,A as getTextureSourceSize,$ as getVoronoiRegion,ei as getWebGpuBlendState,M as hours,H as inRange,Gt as intersectionCircleCircle,zt as intersectionCircleEllipse,Xt as intersectionCirclePoly,jt as intersectionEllipseEllipse,Yt as intersectionEllipsePoly,Ft as intersectionLineCircle,Dt as intersectionLineEllipse,kt as intersectionLineLine,It as intersectionLinePoly,Lt as intersectionLineRect,Et as intersectionPointCircle,Rt as intersectionPointEllipse,Pt as intersectionPointLine,Mt as intersectionPointPoint,At as intersectionPointPoly,Bt as intersectionPointRect,$t as intersectionPolyPoly,Ut as intersectionRectCircle,Vt as intersectionRectEllipse,Ot as intersectionRectPoly,Nt as intersectionRectRect,Ct as intersectionSat,cs as isAudioContextReady,q as isPowerOfTwo,W as lerp,Gi as matchesIds,T as milliseconds,C as minutes,f as noop,Oi as normalizeIds,ls as onAudioContextReady,zi as parseGamepadDescriptor,Y as quadraticCurveTo,I as radiansPerDegree,O as radiansToDegrees,p as rand,B as removeArrayItems,Ke as resetRenderStats,Wi as resolveDefinition,qi as resolveGamepadDefinition,S as seconds,z as sign,m as stopEvent,E as supportsCodec,v as supportsEventOptions,y as supportsIndexedDb,w as supportsPointerEvents,x as supportsTouchEvents,g as supportsWebAudio,D as tau,U as trimRotation,Be as webGl2PrimitiveArrayConstructors,Pe as webGl2PrimitiveByteSizeMapping,Ee as webGl2PrimitiveTypeNames};
|
|
1
|
+
let t=null;class e{constructor(t=0,e=0){this._width=t,this._height=e}get width(){return this._width}set width(t){this._width=t}get height(){return this._height}set height(t){this._height=t}set(t,e=t){return this._width=t,this._height=e,this}add(t,e=t){return this._width+=t,this._height+=e,this}subtract(t,e=t){return this._width-=t,this._height-=e,this}scale(t,e=t){return this._width*=t,this._height*=e,this}divide(t,e=t){return this._width/=t,this._height/=e,this}copy(t){return this._width=t.width,this._height=t.height,this}clone(){return new e(this._width,this._height)}equals({width:t,height:e}={}){return!(void 0!==t&&this.width!==t||void 0!==e&&this.height!==e)}destroy(){}static get temp(){return null===t&&(t=new e),t}}e.zero=new e(0,0);class i{constructor(t=Date.now()){this._state=new Uint32Array(624),this._iteration=0,this._seed=0,this._value=0,this.setSeed(t),this._twist()}get seed(){return this._seed}get value(){return this._value}get iteration(){return this._iteration}setSeed(t){return this._seed=t,this.reset(),this}reset(){this._state[0]=this._seed;for(let t=1;t<624;t++){const e=this._state[t-1]^this._state[t-1]>>>30;this._state[t]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+t,this._state[t]|=0}return this._iteration=0,this}next(t=0,e=1){return this._iteration>=624&&this._twist(),this._value=this._state[this._iteration++],this._value^=this._value>>>11,this._value^=this._value<<7&2636928640,this._value^=this._value<<15&4022730752,this._value^=this._value>>>18,this._value=(this._value>>>0)/4294967295*(e-t)+t,this._value}destroy(){}_twist(){const t=this._state;for(let e=0;e<227;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e+397]^i>>>1^2567483615*(1&i)}for(let e=227;e<623;e++){const i=2147483648&t[e]|2147483647&t[e+1];t[e]=t[e-227]^i>>>1^2567483615*(1&i)}const e=2147483648&t[623]|2147483647&t[0];t[623]=t[396]^e>>>1^2567483615*(1&e),this._iteration=0,this._value=0}}let s=null;class r{constructor(t=0,e=r.milliseconds){this._milliseconds=t*e}get milliseconds(){return this._milliseconds}set milliseconds(t){this._milliseconds=t}get seconds(){return this._milliseconds/r.seconds}set seconds(t){this._milliseconds=t*r.seconds}get minutes(){return this._milliseconds/r.minutes}set minutes(t){this._milliseconds=t*r.minutes}get hours(){return this._milliseconds/r.hours}set hours(t){this._milliseconds=t*r.hours}set(t=0,e=r.milliseconds){return this._milliseconds=t*e,this}setMilliseconds(t){return this.milliseconds=t,this}setSeconds(t){return this.seconds=t,this}setMinutes(t){return this.minutes=t,this}setHours(t){return this.hours=t,this}equals({milliseconds:t,seconds:e,minutes:i,hours:s}={}){return!(void 0!==t&&this.milliseconds!==t||void 0!==e&&this.seconds!==e||void 0!==i&&this.minutes!==i||void 0!==s&&this.hours!==s)}greaterThan(t){return this._milliseconds>t.milliseconds}lessThan(t){return this._milliseconds<t.milliseconds}clone(){return new r(this._milliseconds)}copy(t){return this._milliseconds=t.milliseconds,this}add(t=0,e=r.milliseconds){return this._milliseconds+=t*e,this}addTime(t){return this._milliseconds+=t.milliseconds,this}subtract(t=0,e=r.milliseconds){return this._milliseconds-=t*e,this}subtractTime(t){return this._milliseconds-=t.milliseconds,this}destroy(){}static get temp(){return null===s&&(s=new r),s}}r.milliseconds=1,r.seconds=1e3,r.minutes=6e4,r.hours=36e5,r.zero=new r(0),r.oneMillisecond=new r(1),r.oneSecond=new r(1,r.seconds),r.oneMinute=new r(1,r.minutes),r.oneHour=new r(1,r.hours);const n=/^no$/;let o=null,a=null,h=null,l=null,u=null;const d=()=>"undefined"!=typeof document,c=()=>"undefined"!=typeof window,p=()=>{if(!d())throw new Error("Canvas operations require a document context.");return null===a&&(a=document.createElement("canvas")),a},_=(t,e)=>(null===l&&(l=new i),l).next(t,e),f=()=>{},m=t=>{t.preventDefault(),t.stopImmediatePropagation()},g="undefined"!=typeof AudioContext,y="undefined"!=typeof indexedDB,x=c()&&"ontouchstart"in window,w="undefined"!=typeof PointerEvent,v=()=>{if(null!==u)return u;if(!c())return u=!1,u;let t=!1;try{window.addEventListener("test",f,{get passive(){return t=!0,!1}}),window.removeEventListener("test",f)}catch(t){}return u=t,u},b=()=>performance.now(),T=t=>new r(t,r.milliseconds),S=t=>new r(t,r.seconds),C=t=>new r(t,r.minutes),M=t=>new r(t,r.hours),P=new ArrayBuffer(0),B=(t,e,i)=>{if(e<t.length&&i>0){const s=e+i>t.length?t.length-e:i,r=t.length-s;for(let i=e;i<r;i++)t[i]=t[i+s];t.length=r}return t},E=(...t)=>t.some(t=>(()=>{if(!d())throw new Error("Audio codec detection requires a document context.");return null===o&&(o=document.createElement("audio")),o})().canPlayType(t).replace(n,"")),R=t=>{const i=t;return t instanceof HTMLImageElement?e.temp.set(t.naturalWidth,t.naturalHeight):t instanceof HTMLVideoElement?e.temp.set(t.videoWidth,t.videoHeight):t instanceof SVGElement?e.temp.copy(t.getBoundingClientRect()):"number"==typeof i.displayWidth&&"number"==typeof i.displayHeight?e.temp.set(i.displayWidth,i.displayHeight):"number"==typeof i.width&&"number"==typeof i.height?e.temp.set(i.width,i.height):e.zero},A=t=>null===t?e.zero:R(t),k=t=>{const{width:e,height:i}=R(t),s=p();return s.width=e,s.height=i,(()=>{if(null===h){const t=p().getContext("2d");if(!t)throw new Error("Could not create a 2D canvas context.");h=t}return h})().drawImage(t,0,0,e,i),s.toDataURL()};class L{constructor(t=r.zero,e=!1){this._elapsedTime=new r(0),this._running=!1,this._startTime=t.clone(),e&&this.start()}get running(){return this._running}get elapsedTime(){if(this._running){const t=b();this._elapsedTime.add(t-this._startTime.milliseconds),this._startTime.milliseconds=t}return this._elapsedTime}get elapsedMilliseconds(){return this.elapsedTime.milliseconds}get elapsedSeconds(){return this.elapsedTime.seconds}get elapsedMinutes(){return this.elapsedTime.minutes}get elapsedHours(){return this.elapsedTime.hours}start(){return this._running||(this._running=!0,this._startTime.milliseconds=b()),this}stop(){return this._running&&(this._running=!1,this._elapsedTime.add(b()-this._startTime.milliseconds)),this}reset(){return this._running=!1,this._elapsedTime.setMilliseconds(0),this}restart(){return this.reset(),this.start(),this}destroy(){this._startTime.destroy(),this._elapsedTime.destroy()}}class F{constructor(){this._bindings=new Array}get bindings(){return this._bindings}has(t,e){return this._bindings.some(i=>i.handler===t&&i.context===e)}add(t,e){return this.has(t,e)||this._bindings.push({handler:t,context:e}),this}once(t,e){const i=(...s)=>{this.remove(i,e),t.call(e,...s)};return this.add(i,e),this}remove(t,e){const i=this._bindings.findIndex(i=>i.handler===t&&i.context===e);return-1!==i&&B(this._bindings,i,1),this}clearByContext(t){const e=this._bindings.filter(e=>e.context===t);for(const t of e)B(this._bindings,this._bindings.indexOf(t),1);return this}clear(){return this._bindings.length=0,this}dispatch(...t){if(this._bindings.length)for(const e of this._bindings)if(!1===e.handler.call(e.context,...t))break;return this}destroy(){this.clear()}}const D=2*Math.PI,I=Math.PI/180,N=180/Math.PI,U=t=>{const e=t%360;return e<0?e+360:e},V=t=>t*I,O=t=>t*N,G=(t,e,i)=>Math.min(i,Math.max(e,t)),z=t=>t&&(t<0?-1:1),W=(t,e,i)=>(1-i)*t+i*e,q=t=>0!==t&&!(t&t-1),H=(t,e,i)=>t>=Math.min(e,i)&&t<=Math.max(e,i),X=(t,e,i,s)=>{const r=t-i,n=e-s;return Math.sqrt(r*r+n*n)},Y=(t,e,i,s,r,n,o,a,h=[],l=20)=>{h.push(t,e);for(let u=1,d=0,c=0,p=0,_=0,f=0,m=0;u<=l;u++)d=u/l,c=1-d,p=c*c,_=p*c,f=d*d,m=f*d,h.push(_*t+3*p*d*i+3*c*f*r+m*o,_*e+3*p*d*s+3*c*f*n+m*a);return h},j=(t,e,i,s,r,n,o=[],a=20)=>{for(let h=0;h<=a;h++){const l=h/a;o.push(W(W(t,i,l),W(i,r,l),l),W(W(e,s,l),W(s,n,l),l))}return o},$=(t,e)=>{const i=e.dot(t.x,t.y);return i<0?-1:i>t.lengthSq?1:0};class K{constructor(t=0,e=0,i=0,s=1){this._rgba=null,this._array=null,this._r=255&t,this._g=255&e,this._b=255&i,this._a=G(s,0,1)}get r(){return this._r}set r(t){this._r=255&t,this._rgba=null}get g(){return this._g}set g(t){this._g=255&t,this._rgba=null}get b(){return this._b}set b(t){this._b=255&t,this._rgba=null}get a(){return this._a}set a(t){this._a=G(t,0,1),this._rgba=null}get red(){return this.r}set red(t){this.r=t}get green(){return this.g}set green(t){this.g=t}get blue(){return this.b}set blue(t){this.b=t}get alpha(){return this.a}set alpha(t){this.a=t}set(t=this._r,e=this._g,i=this._b,s=this._a){return this._r=255&t,this._g=255&e,this._b=255&i,this._a=G(s,0,1),this._rgba=null,this}copy(t){return this.set(t.r,t.g,t.b,t.a)}clone(){return new K(this._r,this._g,this._b,this._a)}equals({r:t,g:e,b:i,a:s}={}){return!(void 0!==t&&this.r!==t||void 0!==e&&this.g!==e||void 0!==i&&this.b!==i||void 0!==s&&this.a!==s)}toArray(t=!1){return this._array||(this._array=new Float32Array(4)),t?(this._array[0]=this._r/255,this._array[1]=this._g/255,this._array[2]=this._b/255,this._array[3]=this._a):(this._array[0]=this._r,this._array[1]=this._g,this._array[2]=this._b,this._array[3]=this._a),this._array}toString(t=!0){return`${t?"#":""}${((1<<24)+(this._r<<16)+(this._g<<8)+this._b).toString(16).substr(1)}`}toRgba(){return null===this._rgba&&(this._rgba=this._a&&(255*this._a<<24)+(this._b<<16)+(this._g<<8)+this._r>>>0),this._rgba}destroy(){this._array&&(this._array=null)}}var Q,Z,J,tt,et,it,st;K.aliceBlue=new K(240,248,255,1),K.antiqueWhite=new K(250,235,215,1),K.aqua=new K(0,255,255,1),K.aquamarine=new K(127,255,212,1),K.azure=new K(240,255,255,1),K.beige=new K(245,245,220,1),K.bisque=new K(255,228,196,1),K.black=new K(0,0,0,1),K.blanchedAlmond=new K(255,235,205,1),K.blue=new K(0,0,255,1),K.blueViolet=new K(138,43,226,1),K.brown=new K(165,42,42,1),K.burlyWood=new K(222,184,135,1),K.cadetBlue=new K(95,158,160,1),K.chartreuse=new K(127,255,0,1),K.chocolate=new K(210,105,30,1),K.coral=new K(255,127,80,1),K.cornflowerBlue=new K(100,149,237,1),K.cornsilk=new K(255,248,220,1),K.crimson=new K(220,20,60,1),K.cyan=new K(0,255,255,1),K.darkBlue=new K(0,0,139,1),K.darkCyan=new K(0,139,139,1),K.darkGoldenrod=new K(184,134,11,1),K.darkGray=new K(169,169,169,1),K.darkGreen=new K(0,100,0,1),K.darkKhaki=new K(189,183,107,1),K.darkMagenta=new K(139,0,139,1),K.darkOliveGreen=new K(85,107,47,1),K.darkOrange=new K(255,140,0,1),K.darkOrchid=new K(153,50,204,1),K.darkRed=new K(139,0,0,1),K.darkSalmon=new K(233,150,122,1),K.darkSeaGreen=new K(143,188,139,1),K.darkSlateBlue=new K(72,61,139,1),K.darkSlateGray=new K(47,79,79,1),K.darkTurquoise=new K(0,206,209,1),K.darkViolet=new K(148,0,211,1),K.deepPink=new K(255,20,147,1),K.deepSkyBlue=new K(0,191,255,1),K.dimGray=new K(105,105,105,1),K.dodgerBlue=new K(30,144,255,1),K.firebrick=new K(178,34,34,1),K.floralWhite=new K(255,250,240,1),K.forestGreen=new K(34,139,34,1),K.fuchsia=new K(255,0,255,1),K.gainsboro=new K(220,220,220,1),K.ghostWhite=new K(248,248,255,1),K.gold=new K(255,215,0,1),K.goldenrod=new K(218,165,32,1),K.gray=new K(128,128,128,1),K.green=new K(0,128,0,1),K.greenYellow=new K(173,255,47,1),K.honeydew=new K(240,255,240,1),K.hotPink=new K(255,105,180,1),K.indianRed=new K(205,92,92,1),K.indigo=new K(75,0,130,1),K.ivory=new K(255,255,240,1),K.khaki=new K(240,230,140,1),K.lavender=new K(230,230,250,1),K.lavenderBlush=new K(255,240,245,1),K.lawnGreen=new K(124,252,0,1),K.lemonChiffon=new K(255,250,205,1),K.lightBlue=new K(173,216,230,1),K.lightCoral=new K(240,128,128,1),K.lightCyan=new K(224,255,255,1),K.lightGoldenrodYellow=new K(250,250,210,1),K.lightGray=new K(211,211,211,1),K.lightGreen=new K(144,238,144,1),K.lightPink=new K(255,182,193,1),K.lightSalmon=new K(255,160,122,1),K.lightSeaGreen=new K(32,178,170,1),K.lightSkyBlue=new K(135,206,250,1),K.lightSlateGray=new K(119,136,153,1),K.lightSteelBlue=new K(176,196,222,1),K.lightYellow=new K(255,255,224,1),K.lime=new K(0,255,0,1),K.limeGreen=new K(50,205,50,1),K.linen=new K(250,240,230,1),K.magenta=new K(255,0,255,1),K.maroon=new K(128,0,0,1),K.mediumAquamarine=new K(102,205,170,1),K.mediumBlue=new K(0,0,205,1),K.mediumOrchid=new K(186,85,211,1),K.mediumPurple=new K(147,112,219,1),K.mediumSeaGreen=new K(60,179,113,1),K.mediumSlateBlue=new K(123,104,238,1),K.mediumSpringGreen=new K(0,250,154,1),K.mediumTurquoise=new K(72,209,204,1),K.mediumVioletRed=new K(199,21,133,1),K.midnightBlue=new K(25,25,112,1),K.mintCream=new K(245,255,250,1),K.mistyRose=new K(255,228,225,1),K.moccasin=new K(255,228,181,1),K.navajoWhite=new K(255,222,173,1),K.navy=new K(0,0,128,1),K.oldLace=new K(253,245,230,1),K.olive=new K(128,128,0,1),K.oliveDrab=new K(107,142,35,1),K.orange=new K(255,165,0,1),K.orangeRed=new K(255,69,0,1),K.orchid=new K(218,112,214,1),K.paleGoldenrod=new K(238,232,170,1),K.paleGreen=new K(152,251,152,1),K.paleTurquoise=new K(175,238,238,1),K.paleVioletRed=new K(219,112,147,1),K.papayaWhip=new K(255,239,213,1),K.peachPuff=new K(255,218,185,1),K.peru=new K(205,133,63,1),K.pink=new K(255,192,203,1),K.plum=new K(221,160,221,1),K.powderBlue=new K(176,224,230,1),K.purple=new K(128,0,128,1),K.red=new K(255,0,0,1),K.rosyBrown=new K(188,143,143,1),K.royalBlue=new K(65,105,225,1),K.saddleBrown=new K(139,69,19,1),K.salmon=new K(250,128,114,1),K.sandyBrown=new K(244,164,96,1),K.seaGreen=new K(46,139,87,1),K.seaShell=new K(255,245,238,1),K.sienna=new K(160,82,45,1),K.silver=new K(192,192,192,1),K.skyBlue=new K(135,206,235,1),K.slateBlue=new K(106,90,205,1),K.slateGray=new K(112,128,144,1),K.snow=new K(255,250,250,1),K.springGreen=new K(0,255,127,1),K.steelBlue=new K(70,130,180,1),K.tan=new K(210,180,140,1),K.teal=new K(0,128,128,1),K.thistle=new K(216,191,216,1),K.tomato=new K(255,99,71,1),K.transparentBlack=new K(0,0,0,0),K.transparentWhite=new K(255,255,255,0),K.turquoise=new K(64,224,208,1),K.violet=new K(238,130,238,1),K.wheat=new K(245,222,179,1),K.white=new K(255,255,255,1),K.whiteSmoke=new K(245,245,245,1),K.yellow=new K(255,255,0,1),K.yellowGreen=new K(154,205,50,1),function(t){t[t.Normal=0]="Normal",t[t.Additive=1]="Additive",t[t.Subtract=2]="Subtract",t[t.Multiply=3]="Multiply",t[t.Screen=4]="Screen"}(Q||(Q={})),function(t){t[t.Nearest=9728]="Nearest",t[t.Linear=9729]="Linear",t[t.NearestMipmapNearest=9984]="NearestMipmapNearest",t[t.LinearMipmapNearest=9985]="LinearMipmapNearest",t[t.NearestMipmapLinear=9986]="NearestMipmapLinear",t[t.LinearMipmapLinear=9987]="LinearMipmapLinear"}(Z||(Z={})),function(t){t[t.Repeat=10497]="Repeat",t[t.ClampToEdge=33071]="ClampToEdge",t[t.MirroredRepeat=33648]="MirroredRepeat"}(J||(J={})),function(t){t[t.Points=0]="Points",t[t.Lines=1]="Lines",t[t.LineLoop=2]="LineLoop",t[t.LineStrip=3]="LineStrip",t[t.Triangles=4]="Triangles",t[t.TriangleStrip=5]="TriangleStrip",t[t.TriangleFan=6]="TriangleFan"}(tt||(tt={})),function(t){t[t.ArrayBuffer=34962]="ArrayBuffer",t[t.ElementArrayBuffer=34963]="ElementArrayBuffer",t[t.CopyReadBuffer=36662]="CopyReadBuffer",t[t.CopyWriteBuffer=36663]="CopyWriteBuffer",t[t.TransformFeedbackBuffer=35982]="TransformFeedbackBuffer",t[t.UniformBuffer=35345]="UniformBuffer",t[t.PixelPackBuffer=35051]="PixelPackBuffer",t[t.PixelUnpackBuffer=35052]="PixelUnpackBuffer"}(et||(et={})),function(t){t[t.StaticDraw=35044]="StaticDraw",t[t.StaticRead=35045]="StaticRead",t[t.StaticCopy=35046]="StaticCopy",t[t.DynamicDraw=35048]="DynamicDraw",t[t.DynamicRead=35049]="DynamicRead",t[t.DynamicCopy=35050]="DynamicCopy",t[t.StreamDraw=35040]="StreamDraw",t[t.StreamRead=35041]="StreamRead",t[t.StreamCopy=35042]="StreamCopy"}(it||(it={})),function(t){t[t.Int=5124]="Int",t[t.IntVec2=35667]="IntVec2",t[t.IntVec3=35668]="IntVec3",t[t.IntVec4=35669]="IntVec4",t[t.Float=5126]="Float",t[t.FloatVec2=35664]="FloatVec2",t[t.FloatVec3=35665]="FloatVec3",t[t.FloatVec4=35666]="FloatVec4",t[t.Bool=35670]="Bool",t[t.BoolVec2=35671]="BoolVec2",t[t.BoolVec3=35672]="BoolVec3",t[t.BoolVec4=35673]="BoolVec4",t[t.FloatMat2=35674]="FloatMat2",t[t.FloatMat3=35675]="FloatMat3",t[t.FloatMat4=35676]="FloatMat4",t[t.Sampler2D=35678]="Sampler2D"}(st||(st={}));class rt{get direction(){return Math.atan2(this.x,this.y)}set direction(t){const e=this.length;this.x=Math.cos(t)*e,this.y=Math.sin(t)*e}get angle(){return this.direction}set angle(t){this.direction=t}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}set length(t){const e=this.direction;this.x=Math.cos(e)*t,this.y=Math.sin(e)*t}get lengthSq(){return this.x*this.x+this.y*this.y}set lengthSq(t){this.length=Math.sqrt(t)}get magnitude(){return this.length}set magnitude(t){this.length=t}set(t,e=t){return this.x=t,this.y=e,this}equals({x:t,y:e}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e)}add(t,e=t){return this.x+=t,this.y+=e,this}subtract(t,e=t){return this.x-=t,this.y-=e,this}multiply(t,e=t){return this.x*=t,this.y*=e,this}divide(t,e=t){return 0!==t&&0!==e&&(this.x/=t,this.y/=e),this}normalize(){return this.divide(this.length)}invert(){return this.multiply(-1,-1)}transform(t){return this.set(this.x*t.a+this.y*t.b+t.x,this.x*t.c+this.y*t.d+t.y)}transformInverse(t){const e=1/(t.a*t.d+t.c*-t.b);return this.set(this.x*t.d*e+this.y*-t.c*e+(t.y*t.c-t.x*t.d)*e,this.y*t.a*e+this.x*-t.b*e+(-t.y*t.a+t.x*t.b)*e)}perp(){return this.set(-this.y,this.x)}rperp(){return this.set(this.y,-this.x)}min(){return Math.min(this.x,this.y)}max(){return Math.max(this.x,this.y)}dot(t,e){return this.x*t+this.y*e}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){return X(this.x,this.y,t.x,t.y)}}class nt extends rt{constructor(t,e=0,i=0){super(),this._x=e,this._y=i,this._callback=t}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._callback?.())}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._callback?.())}set direction(t){const e=this.length;this.set(Math.cos(t)*e,Math.sin(t)*e)}set length(t){const e=this.direction;this.set(Math.cos(e)*t,Math.sin(e)*t)}set(t=this._x,e=this._y){return this._x===t&&this._y===e||(this._x=t,this._y=e,this._callback?.()),this}add(t,e=t){return this.set(this._x+t,this._y+e)}subtract(t,e=t){return this.set(this._x-t,this._y-e)}scale(t,e=t){return this.set(this._x*t,this._y*e)}divide(t,e=t){return 0!==t&&0!==e?this.set(this._x/t,this._y/e):this}clone(){return new nt(this._callback,this._x,this._y)}copy(t){return this.set(t.x,t.y)}destroy(){}}let ot=null;class at{constructor(t=1,e=0,i=0,s=0,r=1,n=0,o=0,a=0,h=1){this._array=null,this.a=t,this.b=e,this.x=i,this.c=s,this.d=r,this.y=n,this.e=o,this.f=a,this.z=h}set(t=this.a,e=this.b,i=this.x,s=this.c,r=this.d,n=this.y,o=this.e,a=this.f,h=this.z){return this.a=t,this.b=e,this.x=i,this.c=s,this.d=r,this.y=n,this.e=o,this.f=a,this.z=h,this}copy(t){return this.a=t.a,this.b=t.b,this.x=t.x,this.c=t.c,this.d=t.d,this.y=t.y,this.e=t.e,this.f=t.f,this.z=t.z,this}clone(){return new at(this.a,this.b,this.x,this.c,this.d,this.y,this.e,this.f,this.z)}equals({a:t,b:e,x:i,c:s,d:r,y:n,e:o,f:a,z:h}={}){return!(void 0!==t&&this.a!==t||void 0!==e&&this.b!==e||void 0!==i&&this.x!==i||void 0!==s&&this.c!==s||void 0!==r&&this.d!==r||void 0!==n&&this.y!==n||void 0!==o&&this.e!==o||void 0!==a&&this.f!==a||void 0!==h&&this.z!==h)}combine(t){return this.set(this.a*t.a+this.c*t.b+this.e*t.x,this.b*t.a+this.d*t.b+this.f*t.x,this.x*t.a+this.y*t.b+this.z*t.x,this.a*t.c+this.c*t.d+this.e*t.y,this.b*t.c+this.d*t.d+this.f*t.y,this.x*t.c+this.y*t.d+this.z*t.y,this.a*t.e+this.c*t.f+this.e*t.z,this.b*t.e+this.d*t.f+this.f*t.z,this.x*t.e+this.y*t.f+this.z*t.z)}getInverse(t=this){const e=this.a*(this.z*this.d-this.y*this.f)-this.b*(this.z*this.c-this.y*this.e)+this.x*(this.f*this.c-this.d*this.e);return 0===e?t.copy(at.identity):t.set((this.z*this.d-this.y*this.f)/e,(this.z*this.c-this.y*this.e)/-e,(this.f*this.c-this.d*this.e)/e,(this.z*this.b-this.x*this.f)/-e,(this.z*this.a-this.x*this.e)/e,(this.f*this.a-this.b*this.e)/-e,(this.y*this.b-this.x*this.d)/e,(this.y*this.a-this.x*this.c)/-e,(this.d*this.a-this.b*this.c)/e)}translate(t,e=t){return this.combine(at.temp.set(1,0,t,0,1,e,0,0,1))}rotate(t,e=0,i=e){const s=V(t),r=Math.cos(s),n=Math.sin(s);return this.combine(at.temp.set(r,-n,e*(1-r)+i*n,n,r,i*(1-r)-e*n,0,0,1))}scale(t,e=t,i=0,s=i){return this.combine(at.temp.set(t,0,i*(1-t),0,e,s*(1-e),0,0,1))}toArray(t=!1){const e=this._array||(this._array=new Float32Array(9));return t?(e[0]=this.a,e[1]=this.b,e[2]=this.x,e[3]=this.c,e[4]=this.d,e[5]=this.y,e[6]=this.e,e[7]=this.f,e[8]=this.z):(e[0]=this.a,e[1]=this.c,e[2]=this.e,e[3]=this.b,e[4]=this.d,e[5]=this.f,e[6]=this.x,e[7]=this.y,e[8]=this.z),e}destroy(){this._array&&(this._array=null)}static get temp(){return null===ot&&(ot=new at),ot}}at.identity=new at(1,0,0,0,1,0,0,0,1);class ht{get value(){return this._value}constructor(...t){this._value=0,t.length&&this.push(...t)}push(...t){for(const e of t)this._value|=e;return this}pop(t){const e=this.has(t);return this.remove(t),e}remove(...t){for(const e of t)this._value&=~e;return this}has(...t){return t.some(t=>0!==(this._value&t))}clear(){return this._value=0,this}destroy(){this.clear()}}var lt;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse"}(lt||(lt={}));class ut{constructor(){this.flags=new ht(lt.Transform),this._transform=new at,this._position=new nt(this._setPositionDirty.bind(this),0,0),this._scale=new nt(this._setScalingDirty.bind(this),1,1),this._origin=new nt(this._setOriginDirty.bind(this),0,0),this._rotation=0,this._sin=0,this._cos=1}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get origin(){return this._origin}set origin(t){this._origin.copy(t)}setPosition(t,e=t){return this._position.set(t,e),this}setRotation(t){const e=U(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}setScale(t,e=t){return this._scale.set(t,e),this}setOrigin(t,e=t){return this._origin.set(t,e),this}move(t,e){return this.setPosition(this.x+t,this.y+e)}rotate(t){return this.setRotation(this._rotation+t)}getTransform(){return this.flags.has(lt.Transform)&&(this.updateTransform(),this.flags.remove(lt.Transform)),this._transform}updateTransform(){if(this.flags.has(lt.Rotation)){const t=V(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}if(this.flags.has(lt.Rotation|lt.Scaling)){const{x:t,y:e}=this._scale;this._transform.a=t*this._cos,this._transform.b=e*this._sin,this._transform.c=-t*this._sin,this._transform.d=e*this._cos}if(this._rotation){const{x:t,y:e}=this._origin;this._transform.x=t*-this._transform.a-e*this._transform.b+this._position.x,this._transform.y=t*-this._transform.c-e*this._transform.d+this._position.y}else this._transform.x=this._origin.x*-this._scale.x+this._position.x,this._transform.y=this._origin.y*-this._scale.y+this._position.y;return this}destroy(){this._transform.destroy(),this._position.destroy(),this._scale.destroy(),this._origin.destroy(),this.flags.destroy()}_setPositionDirty(){this.flags.push(lt.Translation)}_setRotationDirty(){this.flags.push(lt.Rotation)}_setScalingDirty(){this.flags.push(lt.Scaling)}_setOriginDirty(){this.flags.push(lt.Origin)}}let dt=null;class ct{constructor(t=0,e=t){this.min=t,this.max=e}set(t,e){return this.min=t,this.max=e,this}copy(t){return this.set(t.min,t.max)}clone(){return new ct(this.min,this.max)}containsInterval(t){return t.min>this.min&&t.max<this.max}includes(t){return t<=this.max&&t>=this.min}overlaps(t){return!(this.min>t.max||t.min>this.max)}getOverlap(t){return this.max<t.max?this.max-t.min:t.max-this.min}destroy(){}static get temp(){return null===dt&&(dt=new ct),dt}}ct.zero=new ct(0,0);const pt=1e-10,_t=(t,e=t)=>Math.max(16,Math.ceil(8*Math.sqrt(Math.max(t,e)))),ft=({x:t,y:e,rx:i,ry:s})=>{if(i<=0||s<=0)return[];const r=_t(i,s),n=2*Math.PI/r,o=[];for(let a=0;a<r;a++){const r=a*n;o.push({x:t+Math.cos(r)*i,y:e+Math.sin(r)*s})}return o},mt=({x:t,y:e},{x:i,y:s},{x:r,y:n})=>t<=Math.max(i,r)+pt&&t>=Math.min(i,r)-pt&&e<=Math.max(s,n)+pt&&e>=Math.min(s,n)-pt,gt=({x:t,y:e},{x:i,y:s},{x:r,y:n})=>{const o=(s-e)*(r-i)-(i-t)*(n-s);return Math.abs(o)<=pt?0:o>0?1:2},yt=(t,e,i,s)=>{const r=gt(t,e,i),n=gt(t,e,s),o=gt(i,s,t),a=gt(i,s,e);return r!==n&&o!==a||(!(0!==r||!mt(i,t,e))||(!(0!==n||!mt(s,t,e))||(!(0!==o||!mt(t,i,s))||!(0!==a||!mt(e,i,s)))))},xt=({x:t,y:e},i)=>{const s=i.length;if(s<3)return!1;let r=!1;for(let n=0,o=s-1;n<s;o=n++){const s=i[o],a=i[n];a.y>e!=s.y>e&&t<(s.x-a.x)*((e-a.y)/(s.y-a.y))+a.x&&(r=!r)}return r},wt=(t,e)=>{if(0===t.length||0===e.length)return!1;for(let i=0;i<t.length;i++){const s=t[i],r=t[(i+1)%t.length];for(let t=0;t<e.length;t++){const i=e[t],n=e[(t+1)%e.length];if(yt(s,r,i,n))return!0}}return xt(t[0],e)||xt(e[0],t)},vt=({x:t,y:e},{x:i,y:s},{x:r,y:n},o=.1)=>{const a=X(t,e,i,s),h=X(t,e,r,n),l=X(i,s,r,n);return a+h>=l-o&&a+h<=l+o},bt=(t,e,i,s)=>{const r=(e.x-t.x)*(s.y-i.y)-(s.x-i.x)*(e.y-t.y);if(Math.abs(r)<=pt)return!1;const n=((s.x-i.x)*(t.y-i.y)-(s.y-i.y)*(t.x-i.x))/r,o=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/r;return n>=0&&n<=1&&o>=0&&o<=1},Tt=(t,e)=>Math.sqrt(t*t+e*e),St=(t,e,i,s)=>{const r=i*t+s*e;const n=(o=t)*o+(a=e)*a;var o,a;return r<0?-1:r>n?1:0},Ct=(t,e)=>{const i=t.getNormals(),s=e.getNormals(),r=new ct,n=new ct;for(const s of i)if(t.project(s,r),e.project(s,n),!r.overlaps(n))return!1;for(const i of s)if(t.project(i,r),e.project(i,n),!r.overlaps(n))return!1;return!0},Mt=(t,e,i=0)=>(({x:t,y:e},{x:i,y:s},r=0)=>X(t,e,i,s)<=r)(t,e,i),Pt=(t,e,i=.1)=>vt(t,e.fromPosition,e.toPosition,i),Bt=(t,e)=>(({x:t,y:e},{x:i,y:s,width:r,height:n})=>H(t,i,i+r)&&H(e,s,s+n))(t,e),Et=(t,e)=>(({x:t,y:e},{x:i,y:s,radius:r})=>r>0&&X(t,e,i,s)<=r)(t,e),Rt=(t,e)=>(({x:t,y:e},{x:i,y:s,rx:r,ry:n})=>{if(r<=0||n<=0)return!1;const o=(t-i)/r,a=(e-s)/n;return o*o+a*a<=1})(t,e),At=(t,e)=>((t,{points:e})=>xt(t,e))(t,e),kt=(t,e)=>bt(t.fromPosition,t.toPosition,e.fromPosition,e.toPosition),Lt=(t,e)=>{const{x:i,y:s,width:r,height:n}=e,o={x:i,y:s},a={x:i+r,y:s},h={x:i,y:s+n},l={x:i+r,y:s+n};return bt(t.fromPosition,t.toPosition,o,h)||bt(t.fromPosition,t.toPosition,a,l)||bt(t.fromPosition,t.toPosition,o,a)||bt(t.fromPosition,t.toPosition,h,l)},Ft=(t,e)=>{if(Et(t.fromPosition,e)||Et(t.toPosition,e))return!0;const{fromX:i,fromY:s,toX:r,toY:n}=t,{x:o,y:a,radius:h}=e,l=X(i,s,r,n);if(0===l)return!1;const u=((o-i)*(r-i)+(a-s)*(n-s))/(l*l),d=i+u*(r-i),c=s+u*(n-s);return!!vt({x:d,y:c},t.fromPosition,t.toPosition)&&X(d,c,o,a)<=h},Dt=(t,e)=>{const{x:i,y:s,rx:r,ry:n}=e;if(r<=0||n<=0)return!1;const o=(t.fromX-i)/r,a=(t.fromY-s)/n,h=(t.toX-i)/r-o,l=(t.toY-s)/n-a,u=h*h+l*l,d=2*(o*h+a*l),c=o*o+a*a-1;if(c<=0)return!0;if(u<=Number.EPSILON)return!1;const p=d*d-4*u*c;if(p<0)return!1;const _=Math.sqrt(p),f=(-d-_)/(2*u),m=(-d+_)/(2*u);return f>=0&&f<=1||m>=0&&m<=1},It=(t,e)=>{const{x:i,y:s,points:r}=e,n=r.length;for(let e=0;e<n;e++){const o=r[e],a=r[(e+1)%n];if(bt(t.fromPosition,t.toPosition,{x:o.x+i,y:o.y+s},{x:a.x+i,y:a.y+s}))return!0}return!1},Nt=(t,e)=>(({x:t,y:e,width:i,height:s},{x:r,y:n,width:o,height:a})=>!(r>t+i||n>e+s||t>r+o||e>n+a))(t,e),Ut=({x:t,y:e,width:i,height:s},{x:r,y:n,radius:o})=>{const a=G(r,t,t+i),h=G(n,e,e+s);return X(r,n,a,h)<=o},Vt=(t,e)=>wt((({x:t,y:e,width:i,height:s})=>[{x:t,y:e},{x:t+i,y:e},{x:t+i,y:e+s},{x:t,y:e+s}])(t),ft(e)),Ot=(t,e)=>Ct(t,e),Gt=({x:t,y:e,radius:i},{x:s,y:r,radius:n})=>X(t,e,s,r)<=i+n,zt=(t,e)=>wt((({x:t,y:e,radius:i})=>{if(i<=0)return[];const s=_t(i),r=2*Math.PI/s,n=[];for(let o=0;o<s;o++){const s=o*r;n.push({x:t+Math.cos(s)*i,y:e+Math.sin(s)*i})}return n})(t),ft(e)),Wt=(t,e,i,s,r,n,o,a,h)=>{if(-1!==St(a,h,r,n))return!1;return 1===St(s.x,s.y,t-i.x,e-i.y)&&Tt(r,n)>o},qt=(t,e,i,s,r,n,o,a,h)=>{if(1!==St(a,h,r,n))return!1;return-1===St(s.x,s.y,t-i.x,e-i.y)&&Tt(r,n)>o},Ht=(t,e,i,s,r)=>{const n=r,o=-s,a=Tt(n,o);if(0===a)return!1;const h=(t*n+e*o)/a;return h>0&&Math.abs(h)>i},Xt=({x:t,y:e,radius:i},{x:s,y:r,points:n,edges:o})=>{const a=s-t,h=r-e,l=n.length;for(let t=0;t<l;t++){const e=n[t],s=a-e.x,r=h-e.y,u=0===t?l-1:t-1,d=(t+1)%l,c=o[t];if(Wt(a,h,n[u],o[u],s,r,i,c.x,c.y))return!1;if(qt(a,h,n[d],o[d],s,r,i,c.x,c.y))return!1;if(Ht(s,r,i,c.x,c.y))return!1}return!0},Yt=(t,e)=>wt(ft(t),ft(e)),jt=(t,e)=>wt(ft(t),(({x:t,y:e,points:i})=>i.map(({x:i,y:s})=>({x:i+t,y:s+e})))(e)),$t=(t,e)=>Ct(t,e),Kt=(t,e)=>{if(e.left>t.right||e.top>t.bottom)return null;if(t.left>e.right||t.top>e.bottom)return null;const i=t.position.clone().set(0,0),s=t.position.clone().set(0,0);return{shapeA:t,shapeB:e,overlap:0,shapeAinB:e.containsRect(t),shapeBinA:t.containsRect(e),projectionN:i,projectionV:s}},Qt=(t,e)=>{const i=e.position.clone().subtract(t.x,t.y),s=i.length,r=t.radius+e.radius-s;if(r<0)return i.destroy(),null;const n=i.clone().normalize(),o=i.multiply(r);return{shapeA:t,shapeB:e,overlap:r,shapeAinB:t.radius<=e.radius&&s<=e.radius-t.radius,shapeBinA:e.radius<=t.radius&&s<=t.radius-e.radius,projectionN:n,projectionV:o}},Zt=(t,e,i=!1)=>{const s=t.radius,r=e.width/2,n=e.height/2,o=X(t.x,t.y,e.x-r,e.y-n),a=s<=Math.min(r,n)&&o<=Math.min(r,n)-s,h=Math.max(r,n)<=s&&o<=s-Math.max(r,n);if(o>t.radius)return null;const l=t.position.clone().set(0,0),u=t.position.clone().set(0,0);return{shapeA:i?e:t,shapeB:i?t:e,overlap:s-o,shapeAinB:i?h:a,shapeBinA:i?a:h,projectionN:l,projectionV:u}},Jt=(t,e,i=!1)=>{const s=e.radius,r=t.points,n=e.x-t.x,o=e.y-t.y,a=e.position.clone().set(0,0),h=r.length;let l=!0,u=!0,d=1/0;for(let t=0;t<h;t++){const e=r[t],i=r[(t+1)%h],c=i.x-e.x,p=i.y-e.y,_=n-e.x,f=o-e.y,m=St(c,p,_,f),g=Tt(_,f);if(g>s&&(l=!1),-1===m){const i=r[0===t?h-1:t-1],l=e.x-i.x,c=e.y-i.y,p=n-i.x,m=o-i.y;if(1===St(l,c,p,m)){if(g>s)return a.destroy(),null;const t=s-g;Math.abs(t)<Math.abs(d)&&(d=t,a.set(_,f).normalize()),u=!1}}else if(1===m){const e=r[(t+2)%h],l=e.x-i.x,c=e.y-i.y,p=n-i.x,_=o-i.y,f=Tt(p,_);if(-1===St(l,c,p,_)){if(f>s)return a.destroy(),null;const t=s-f;Math.abs(t)<Math.abs(d)&&(d=t,a.set(p,_).normalize()),u=!1}}else{const t=p,e=-c,i=Tt(t,e),r=0===i?0:(_*t+f*e)/i;if(r>0&&Math.abs(r)>s)return a.destroy(),null;(r>=0||s-r<2*s)&&(u=!1);const n=s-r;Math.abs(n)<Math.abs(d)&&(d=n,a.set(t,e).normalize())}}const c=a.clone().multiply(d);return{shapeA:i?e:t,shapeB:i?t:e,overlap:d,shapeAinB:i?u:l,shapeBinA:i?l:u,projectionN:a,projectionV:c}},te=(t,e)=>{const i=t.getNormals(),s=e.getNormals(),r=(i[0]||s[0]).clone(),n=new ct,o=new ct;let a=1/0,h=!0,l=!0,u=!1,d=!1,c=0;for(const s of i){if(t.project(s,n),e.project(s,o),!n.overlaps(o))return r.destroy(),null;c=n.getOverlap(o),u=o.containsInterval(n),d=n.containsInterval(o),!u&&h&&(h=!1),!d&&l&&(l=!1),(u||d)&&(c+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),c<a&&(a=c,r.copy(s))}for(const i of s){if(t.project(i,n),e.project(i,o),!n.overlaps(o))return r.destroy(),null;c=n.getOverlap(o),u=o.containsInterval(n),d=n.containsInterval(o),!u&&h&&(h=!1),!d&&l&&(l=!1),(u||d)&&(c+=Math.min(Math.abs(n.min-o.min),Math.abs(n.max-o.max))),c<a&&(a=c,r.copy(i))}const p=r.clone().multiply(a,a);return{shapeA:t,shapeB:e,overlap:a,shapeAinB:h,shapeBinA:l,projectionN:r,projectionV:p}};let ee=null;const ie=()=>{},se=new nt(ie);class re{constructor(t=0,i=t,s=0,r=s){this.collisionType=2,this._normals=null,this._normalsDirty=!1,this._position=new nt(()=>{this._normalsDirty=!0},t,i),this._size=new e(s,r)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t,this._normalsDirty=!0}get y(){return this._position.y}set y(t){this._position.y=t,this._normalsDirty=!0}get size(){return this._size}set size(t){this._size.copy(t),this._normalsDirty=!0}get width(){return this._size.width}set width(t){this._size.width=t,this._normalsDirty=!0}get height(){return this._size.height}set height(t){this._size.height=t,this._normalsDirty=!0}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}setPosition(t,e){return this._position.set(t,e),this._normalsDirty=!0,this}setSize(t,e){return this._size.set(t,e),this._normalsDirty=!0,this}set(t,e,i,s){return this.setPosition(t,e),this.setSize(i,s),this}copy(t){return this.position=t.position,this.size=t.size,this}clone(){return new re(this.x,this.y,this.width,this.height)}equals({x:t,y:e,width:i,height:s}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.width!==i||void 0!==s&&this.height!==s)}getBounds(){return this.clone()}getNormals(){return(this._normalsDirty||null===this._normals)&&(this._updateNormals(this._normals||(this._normals=[new nt(ie),new nt(ie),new nt(ie),new nt(ie)])),this._normalsDirty=!1),this._normals}project(t,e=new ct){const i=t.dot(this.left,this.top),s=t.dot(this.right,this.top),r=t.dot(this.right,this.bottom),n=t.dot(this.left,this.bottom);return e.set(Math.min(i,s,r,n),Math.max(i,s,r,n))}transform(t,e=this){const i=se.set(this.left,this.top).transform(t);let s=i.x,r=i.x,n=i.y,o=i.y;return i.set(this.left,this.bottom).transform(t),s=Math.min(s,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.top).transform(t),s=Math.min(s,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),i.set(this.right,this.bottom).transform(t),s=Math.min(s,i.x),n=Math.min(n,i.y),r=Math.max(r,i.x),o=Math.max(o,i.y),e.set(s,n,r-s,o-n)}contains(t,e){return Bt(se.set(t,e),this)}containsRect(t){return H(t.left,this.left,this.right)&&H(t.right,this.left,this.right)&&H(t.top,this.top,this.bottom)&&H(t.bottom,this.top,this.bottom)}intersectsWith(t){switch(t.collisionType){case 6:return t.isAlignedBox?Nt(this,t.getBounds()):Ct(this,t);case 2:return Nt(this,t);case 5:return Ot(this,t);case 3:return Ut(this,t);case 4:return Vt(this,t);case 1:return Lt(t,this);case 0:return Bt(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:return t.isAlignedBox?Kt(this,t.getBounds()):te(this,t);case 2:return Kt(this,t);case 5:return te(this,t);case 3:return Zt(t,this,!0);default:return null}}destroy(){this._position.destroy(),this._size.destroy(),this._normals&&(this._normals=null)}_updateNormals(t){t[0].set(this.right-this.left,0).rperp().normalize(),t[1].set(0,this.bottom-this.top).rperp().normalize(),t[2].set(this.left-this.right,0).rperp().normalize(),t[3].set(0,this.top-this.bottom).rperp().normalize()}static get temp(){return null===ee&&(ee=new re),ee}}class ne{constructor(){this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this._rect=new re}get minX(){return this._minX}get minY(){return this._minY}get maxX(){return this._maxX}get maxY(){return this._maxY}addCoords(t,e){return this._minX=Math.min(this._minX,t),this._minY=Math.min(this._minY,e),this._maxX=Math.max(this._maxX,t),this._maxY=Math.max(this._maxY,e),this._dirty=!0,this}addRect(t,e){return e&&(t=t.transform(e,re.temp)),this.addCoords(t.left,t.top).addCoords(t.right,t.bottom)}getRect(){return this._dirty&&(this._rect.set(this._minX,this._minY,this._maxX-this._minX,this._maxY-this._minY),this._dirty=!1),this._rect}reset(){return this._minX=1/0,this._minY=1/0,this._maxX=-1/0,this._maxY=-1/0,this._dirty=!0,this}destroy(){this._rect.destroy()}}class oe extends ut{constructor(){super(...arguments),this.collisionType=6,this._bounds=new ne,this._visible=!0,this._globalTransform=new at,this._localBounds=new re,this._anchor=new nt(this._updateOrigin.bind(this),0,0),this._parentNode=null,this._zIndex=0,this._childOrder=0,this._cullable=!0}get anchor(){return this._anchor}set anchor(t){this._anchor.copy(t)}get parent(){return this._parentNode}set parent(t){this._parentNode=t}get parentNode(){return this._parentNode}set parentNode(t){this._parentNode=t}get visible(){return this._visible}set visible(t){this._visible=t}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this._parentNode?.markSortDirty())}get childOrder(){return this._childOrder}get cullable(){return this._cullable}set cullable(t){this._cullable=t}get globalTransform(){return this.getGlobalTransform()}get localBounds(){return this.getLocalBounds()}get bounds(){return this.getBounds()}get isAlignedBox(){return this.rotation%90==0}setAnchor(t,e=t){return this._anchor.set(t,e),this}setChildOrder(t){return this._childOrder=t,this}setCullable(t){return this._cullable=t,this}getLocalBounds(){return this._localBounds}getBounds(){return this.updateParentTransform(),this.updateBounds(),this._bounds.getRect()}updateBounds(){return this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform()),this}updateParentTransform(){return this._parentNode&&this._parentNode.updateParentTransform(),this.updateTransform(),this}getGlobalTransform(){return this._globalTransform.copy(this.getTransform()),this._parentNode&&this._globalTransform.combine(this._parentNode.getGlobalTransform()),this._globalTransform}getNormals(){return this.getBounds().getNormals()}project(t,e=new ct){return this.getBounds().project(t,e)}intersectsWith(t){if(this.isAlignedBox)return this.getBounds().intersectsWith(t);switch(t.collisionType){case 6:case 2:case 5:return Ct(this,t);case 3:return Ut(this.getBounds(),t);case 4:return Vt(this.getBounds(),t);case 1:return Lt(t,this.getBounds());case 0:return Bt(t,this.getBounds());default:return!1}}collidesWith(t){if(this.isAlignedBox)return this.getBounds().collidesWith(t);switch(t.collisionType){case 6:case 2:case 5:case 3:return te(this,t);default:return null}}contains(t,e){return this.getBounds().contains(t,e)}inView(t){return!this._cullable||t.getBounds().intersectsWith(this.getBounds())}render(t){return this}destroy(){super.destroy(),this._globalTransform.destroy(),this._localBounds.destroy(),this._bounds.destroy(),this._anchor.destroy()}_updateOrigin(){const{x:t,y:e}=this._anchor,{width:i,height:s}=this.getBounds();this.setOrigin(i*t,s*e)}}class ae extends e{constructor(t,e=0,i=0){super(e,i),this._callback=t}get width(){return this._width}set width(t){this._width!==t&&(this._width=t,this._callback())}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this._callback())}set(t=this._width,e=this._height){return this._width===t&&this._height===e||(this._width=t,this._height=e,this._callback()),this}add(t,e=t){return this.set(this._width+t,this._height+e)}subtract(t,e=t){return this.set(this._width-t,this._height-e)}scale(t,e=t){return this.set(this._width*t,this._height*e)}divide(t,e=t){return this.set(this._width/t,this._height/e)}copy(t){return this.set(t.width,t.height)}clone(){return new ae(this._callback,this._width,this._height)}}var he;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint"}(he||(he={}));class le{constructor(t,e,i,s){this._viewport=new re(0,0,1,1),this._transform=new at,this._inverseTransform=new at,this._bounds=new ne,this._flags=new ht,this._rotation=0,this._sin=0,this._cos=1,this._zoomLevel=1,this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this._boundsConstraint=null,this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakeFrequency=16,this._shakeDecay=!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._updateId=0,this._center=new nt(this._setPositionDirty.bind(this),t,e),this._size=new ae(this._setScalingDirty.bind(this),i,s),this._zoomBaseWidth=i,this._zoomBaseHeight=s,this._flags.push(he.Transform,he.TransformInverse,he.BoundingBox)}get center(){return this._center}set center(t){this._center.copy(t)}get size(){return this._size}set size(t){this._size.copy(t)}get width(){return this._size.width}set width(t){this._size.width=t}get height(){return this._size.height}set height(t){this._size.height=t}get rotation(){return this._rotation}set rotation(t){this.setRotation(t)}get viewport(){return this._viewport}set viewport(t){this._viewport.equals(t)||(this._viewport.copy(t),this._setDirty())}get updateId(){return this._updateId}get zoomLevel(){return this._zoomLevel}setCenter(t,e){return this._center.set(t,e),this}resize(t,e){return this._zoomBaseWidth=t,this._zoomBaseHeight=e,this._zoomLevel=1,this._size.set(t,e),this}setRotation(t){const e=U(t);return this._rotation!==e&&(this._rotation=e,this._setRotationDirty()),this}move(t,e){return this.setCenter(this._center.x+t,this._center.y+e),this}zoom(t){return this.resize(this._size.width*t,this._size.height*t),this}setZoom(t){const e=Math.max(1e-4,t);return this._zoomLevel=e,this._size.set(this._zoomBaseWidth/e,this._zoomBaseHeight/e),this}zoomIn(t=.1){return this.setZoom(this._zoomLevel+t)}zoomOut(t=.1){return this.setZoom(Math.max(1e-4,this._zoomLevel-t))}follow(t,e={}){return this._followTarget=t,this._followLerp=G(e.lerp??1,0,1),this._followOffsetX=e.offsetX??0,this._followOffsetY=e.offsetY??0,this}clearFollow(){return this._followTarget=null,this._followLerp=1,this._followOffsetX=0,this._followOffsetY=0,this}setBounds(t){return null===t?(this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this):(null===this._boundsConstraint?this._boundsConstraint=t.clone():this._boundsConstraint.copy(t),this._applyBoundsConstraint(),this)}clearBounds(){return this.setBounds(null)}shake(t,e,i={}){return this._shakeIntensity=Math.max(0,t),this._shakeDurationMs=Math.max(0,e),this._shakeElapsedMs=0,this._shakeFrequency=Math.max(0,i.frequency??16),this._shakeDecay=i.decay??!0,this._shakePhase=0,this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty(),this}stopShake(){return this._shakeIntensity=0,this._shakeDurationMs=0,this._shakeElapsedMs=0,this._shakePhase=0,0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()),this}update(t){return this._updateFollowTarget(),this._updateShake(t),this._applyBoundsConstraint(),this}rotate(t){return this.setRotation(this._rotation+t),this}reset(t,e,i,s){return this._zoomBaseWidth=i,this._zoomBaseHeight=s,this._zoomLevel=1,this._size.set(i,s),this._center.set(t,e),this._viewport.set(0,0,1,1),this._rotation=0,this._sin=0,this._cos=1,this._flags.push(he.Transform),this}getTransform(){return this._flags.has(he.Transform)&&(this.updateTransform(),this._flags.remove(he.Transform)),this._transform}updateTransform(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=2/this.width,s=-2/this.height;if(this._flags.has(he.Rotation)){const t=V(this._rotation);this._cos=Math.cos(t),this._sin=Math.sin(t)}return this._flags.has(he.Rotation|he.Scaling)&&(this._transform.a=i*this._cos,this._transform.b=i*this._sin,this._transform.c=-s*this._sin,this._transform.d=s*this._cos),this._transform.x=i*-this._transform.a-s*this._transform.b+-i*t,this._transform.y=i*-this._transform.c-s*this._transform.d+-s*e,this}getInverseTransform(){return this._flags.has(he.TransformInverse)&&(this.getTransform().getInverse(this._inverseTransform),this._flags.remove(he.TransformInverse)),this._inverseTransform}getBounds(){return this._flags.has(he.BoundingBox)&&(this.updateBounds(),this._flags.remove(he.BoundingBox)),this._bounds.getRect()}updateBounds(){const t=this._center.x+this._shakeOffsetX,e=this._center.y+this._shakeOffsetY,i=this.width/2,s=this.height/2;return this._bounds.reset().addCoords(t-i,e-s).addCoords(t+i,e+s),this}destroy(){this.stopShake(),this.clearFollow(),this._boundsConstraint&&(this._boundsConstraint.destroy(),this._boundsConstraint=null),this._center.destroy(),this._size.destroy(),this._viewport.destroy(),this._transform.destroy(),this._inverseTransform.destroy(),this._bounds.destroy(),this._flags.destroy()}_setDirty(){this._flags.push(he.TransformInverse,he.BoundingBox),this._updateId++}_setPositionDirty(){this._flags.push(he.Translation),this._setDirty()}_setRotationDirty(){this._flags.push(he.Rotation),this._setDirty()}_setScalingDirty(){this._flags.push(he.Scaling),this._setDirty()}_updateFollowTarget(){if(!this._followTarget)return;const t=this._followTarget.x+this._followOffsetX,e=this._followTarget.y+this._followOffsetY;this._followLerp>=1?this.setCenter(t,e):this.setCenter(this._center.x+(t-this._center.x)*this._followLerp,this._center.y+(e-this._center.y)*this._followLerp)}_applyBoundsConstraint(){if(!this._boundsConstraint)return;const t=this._boundsConstraint,e=this.width/2,i=this.height/2,s=t.left+e,r=t.right-e,n=t.top+i,o=t.bottom-i,a=s>r?(t.left+t.right)/2:G(this._center.x,s,r),h=n>o?(t.top+t.bottom)/2:G(this._center.y,n,o);a===this._center.x&&h===this._center.y||this.setCenter(a,h)}_updateShake(t){if(this._shakeDurationMs<=0||this._shakeIntensity<=0)return void(0===this._shakeOffsetX&&0===this._shakeOffsetY||(this._shakeOffsetX=0,this._shakeOffsetY=0,this._setPositionDirty()));this._shakeElapsedMs=Math.min(this._shakeDurationMs,this._shakeElapsedMs+Math.max(0,t));const e=this._shakeDurationMs>0?this._shakeElapsedMs/this._shakeDurationMs:1,i=this._shakeDecay?this._shakeIntensity*(1-e):this._shakeIntensity;this._shakePhase+=Math.max(0,t)/1e3*this._shakeFrequency*Math.PI*2;const s=Math.sin(1.7*this._shakePhase)*i,r=Math.cos(1.3*this._shakePhase)*i;s===this._shakeOffsetX&&r===this._shakeOffsetY||(this._shakeOffsetX=s,this._shakeOffsetY=r,this._setPositionDirty()),this._shakeElapsedMs>=this._shakeDurationMs&&this.stopShake()}}let ue=null;class de extends rt{constructor(t=0,e=0){super(),this.collisionType=0,this.x=t,this.y=e}clone(){return new de(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}intersectsWith(t){switch(t.collisionType){case 6:return Bt(this,t.getBounds());case 2:return Bt(this,t);case 5:return At(this,t);case 3:return Et(this,t);case 4:return Rt(this,t);case 1:return Pt(this,t);case 0:return Mt(this,t);default:return!1}}collidesWith(t){return null}getBounds(){return re.temp.set(this.x,this.y,0,0)}contains(t,e){return Mt(de.temp.set(t,e),this)}getNormals(){return[this.clone().rperp().normalize()]}project(t,e=new ct){return e}destroy(){}static get temp(){return null===ue&&(ue=new de),ue}static add(t,e){return new de(t.x+e.x,t.y+e.y)}static subtract(t,e){return new de(t.x-e.x,t.y-e.y)}static multiply(t,e){return new de(t.x*e.x,t.y*e.y)}static divide(t,e){return new de(t.x/e.x,t.y/e.y)}}de.zero=new de(0,0),de.one=new de(1,1);class ce{constructor(t,i,s=!1){this._destroyListeners=new Set,this._version=0,this._viewport=new re,this._size=new e(t,i),this._root=s,this._defaultView=new le(t/2,i/2,t,i),this._view=this._defaultView}get view(){return this._view}set view(t){this.setView(t)}get size(){return this._size}set size(t){this.resize(t.width,t.height)}get width(){return this._size.width}set width(t){this.resize(t,this.height)}get height(){return this._size.height}set height(t){this.resize(this.width,t)}get root(){return this._root}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setView(t){const e=t||this._defaultView;return this._view!==e&&(this._view=e,this._touch()),this}resize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}getViewport(t=this._view){const{x:e,y:i,width:s,height:r}=t.viewport;return this._viewport.set(Math.round(e*this.width),Math.round(i*this.height),Math.round(s*this.width),Math.round(r*this.height))}updateViewport(){return this._touch(),this}mapPixelToCoords(t,e=this._view){const i=this.getViewport(e);return new de(2*(t.x-i.left)/i.width-1,1-2*(t.y-i.top)/i.height).transform(e.getInverseTransform())}mapCoordsToPixel(t,e=this._view){const i=this.getViewport(e),s=t.clone().transform(e.getTransform());return s.set((s.x+1)/2*i.width+i.left|0,(1-s.y)/2*i.height+i.top|0)}destroy(){for(const t of Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._view!==this._defaultView&&this._view.destroy(),this._defaultView.destroy(),this._viewport.destroy(),this._size.destroy()}_touch(){this._version++}}class pe extends ce{constructor(t,e,i){super(t,e,!1),this._source=null,this._textureVersion=0;const{scaleMode:s,wrapMode:r,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...pe.defaultSamplerOptions,...i};this._scaleMode=s,this._wrapMode=r,this._premultiplyAlpha=n,this._generateMipMap=o,this._flipY=a,this._touchTexture()}get source(){return this._source}set source(t){this.setSource(t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return q(this.width)&&q(this.height)}get textureVersion(){return this._textureVersion}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touchTexture()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touchTexture()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touchTexture()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){return this._touchTexture(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._defaultView.resize(t,e),this.updateViewport(),this._touchTexture()),this}destroy(){super.destroy(),this._source=null}_touchTexture(){this._textureVersion++}}pe.defaultSamplerOptions={scaleMode:Z.Linear,wrapMode:J.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!1,flipY:!0};class _e{constructor(t,e={}){this._callback=t,this._target=e.target??null,this._view=e.view??null,this._clearColor=e.clearColor??null}execute(t){const e=t.renderTarget,i=t.view;t.setRenderTarget(this._target),t.setView(this._view),null!==this._clearColor&&t.clear(this._clearColor);try{this._callback(t)}finally{t.setRenderTarget(e),t.setView(i)}}}const fe=t=>"destroy"in t&&"function"==typeof t.destroy;class me extends oe{constructor(){super(...arguments),this._filters=[],this._cacheBounds=new re,this._cacheSprite=null,this._captureView=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheDirty=!0,this._cacheTexture=null}get filters(){return this._filters}set filters(t){this.setFilters(t)}get mask(){return this._mask}set mask(t){this._mask!==t&&(this._mask=t,this.invalidateCache())}get cacheAsBitmap(){return this._cacheAsBitmap}set cacheAsBitmap(t){this.setCacheAsBitmap(t)}setFilters(t){return this._filters.length=0,this._filters.push(...t),this.invalidateCache()}addFilter(t){return this._filters.push(t),this.invalidateCache()}removeFilter(t){const e=this._filters.indexOf(t);return-1!==e&&(this._filters.splice(e,1),this.invalidateCache()),this}static setInternalSpriteFactory(t){me._spriteFactory=t}clearFilters(){return this._filters.length>0&&(this._filters.length=0,this.invalidateCache()),this}setCacheAsBitmap(t){return this._cacheAsBitmap!==t&&(this._cacheAsBitmap=t,this.invalidateCache(),t||this._destroyCacheTexture()),this}invalidateCache(){return this._cacheDirty=!0,this}renderVisualContent(t,e,i=Q.Normal){const s=this._filters.length>0,r=this._cacheAsBitmap;if(!s&&!r)return void this._withMask(t,e);const n=this.getBounds();if(n.width<=0||n.height<=0)return;const o=Math.floor(n.left),a=Math.floor(n.top),h=Math.max(1,Math.ceil(n.width)),l=Math.max(1,Math.ceil(n.height)),u=!this._cacheBounds.equals({x:o,y:a,width:h,height:l}),d=r&&(this._cacheDirty||null===this._cacheTexture||u);if(r&&!d&&null!==this._cacheTexture)return void this._withMask(t,()=>{this._drawTexture(t,this._cacheTexture,o,a,h,l,i)});const c=[],p=r?this._ensureCacheTexture(h,l):null;try{const n=r&&!s?p:t.acquireRenderTexture(h,l);n!==p&&c.push(n),this._renderContentToTexture(t,n,o,a,h,l,e);let u=n;if(s)for(let e=0;e<this._filters.length;e++){const i=e===this._filters.length-1&&r?p:t.acquireRenderTexture(h,l);i!==p&&c.push(i),this._filters[e].apply(t,u,i),u=i}r&&(this._cacheTexture=p,this._cacheBounds.set(o,a,h,l),this._cacheDirty=!1),this._withMask(t,()=>{this._drawTexture(t,u,o,a,h,l,i)})}finally{for(const e of c)t.releaseRenderTexture(e)}}destroy(){super.destroy(),this._destroyCacheTexture(),this._cacheBounds.destroy(),this._cacheSprite?.destroy(),this._cacheSprite=null,this._captureView?.destroy(),this._captureView=null;for(const t of this._filters)fe(t)&&t.destroy();this._filters.length=0,this._mask=null}_withMask(t,e){if(null===this._mask)return void e();const i=this._mask.getBounds();if(!(i.width<=0||i.height<=0)){t.pushMask(i);try{e()}finally{t.popMask()}}}_renderContentToTexture(t,e,i,s,r,n,o){null===this._captureView?this._captureView=new le(i+r/2,s+n/2,r,n):this._captureView.reset(i+r/2,s+n/2,r,n),t.execute(new _e(()=>{o()},{target:e,view:this._captureView,clearColor:K.transparentBlack}))}_drawTexture(t,e,i,s,r,n,o){const a=this._getCacheSprite();a.setTexture(e).setBlendMode(o).setTint(K.white).setPosition(i,s).setRotation(0).setScale(1,1),a.width=r,a.height=n,a.render(t)}_ensureCacheTexture(t,e){return null===this._cacheTexture?this._cacheTexture=new pe(t,e):this._cacheTexture.width===t&&this._cacheTexture.height===e||this._cacheTexture.setSize(t,e),this._cacheTexture}_destroyCacheTexture(){null!==this._cacheTexture&&(this._cacheTexture.destroy(),this._cacheTexture=null),this._cacheDirty=!0}_getCacheSprite(){if(null===this._cacheSprite){if(null===me._spriteFactory)throw new Error("RenderNode sprite factory is not initialized.");this._cacheSprite=me._spriteFactory()}return this._cacheSprite}}me._spriteFactory=null;class ge extends me{constructor(){super(...arguments),this._tint=K.white.clone(),this._blendMode=Q.Normal}get tint(){return this._tint}set tint(t){this.setTint(t)}get blendMode(){return this._blendMode}set blendMode(t){this.setBlendMode(t)}setTint(t){return t&&(this._tint.copy(t),this.invalidateCache()),this}setBlendMode(t){return this._blendMode!==t&&(this._blendMode=t,this.invalidateCache()),this}render(t){return this.visible?this.inView(t.view)?(this.renderVisualContent(t,()=>{t.draw(this)},this._blendMode),this):(t.stats.culledNodes++,this):this}destroy(){super.destroy(),this._tint.destroy()}}class ye extends ge{constructor(t,e,i=tt.Triangles){super(),this.geometry=t,this.color=e.clone(),this.drawMode=i}destroy(){super.destroy(),this.color.destroy()}}class xe{constructor({vertices:t=[],indices:e=[],points:i=[]}={}){this.vertices=new Float32Array(t),this.indices=new Uint16Array(e),this.points=i}destroy(){}}class we extends ye{render(t){return this.visible&&t.draw(this),this}}class ve{constructor(t){this._stack=[],this._transitionOverlay=new we(new xe({vertices:[0,0,1,0,0,1,1,1],indices:[0,1,2,3],points:[0,0,1,0,0,1,1,1]}),K.black,tt.TriangleStrip),this._transition=null,this.onChangeScene=new F,this.onStartScene=new F,this.onUpdateScene=new F,this.onStopScene=new F,this._handleKeyDown=t=>{this._dispatchInput({type:"keyDown",channel:t})},this._handleKeyUp=t=>{this._dispatchInput({type:"keyUp",channel:t})},this._handlePointerEnter=t=>{this._dispatchInput({type:"pointerEnter",pointer:t})},this._handlePointerLeave=t=>{this._dispatchInput({type:"pointerLeave",pointer:t})},this._handlePointerDown=t=>{this._dispatchInput({type:"pointerDown",pointer:t})},this._handlePointerMove=t=>{this._dispatchInput({type:"pointerMove",pointer:t})},this._handlePointerUp=t=>{this._dispatchInput({type:"pointerUp",pointer:t})},this._handlePointerTap=t=>{this._dispatchInput({type:"pointerTap",pointer:t})},this._handlePointerSwipe=t=>{this._dispatchInput({type:"pointerSwipe",pointer:t})},this._handlePointerCancel=t=>{this._dispatchInput({type:"pointerCancel",pointer:t})},this._handleMouseWheel=t=>{this._dispatchInput({type:"mouseWheel",wheel:t})},this._app=t,this._subscribeInputRouting()}get scene(){return this._stack.length>0?this._stack[this._stack.length-1].scene:null}set scene(t){this.setScene(t)}get scenes(){return this._stack.map(t=>t.scene)}async setScene(t,e={}){return await this._runWithTransition(async()=>{if(null===t)return await this._unloadAllScenes(),void this.onChangeScene.dispatch(null);if(this.scene===t)return void(this._stack.length>1&&await this._unloadCoveredScenes());if(this._stack.some(e=>e.scene===t))throw new Error("Cannot set a scene that is already present in the scene stack.");const e=this._resolveParticipationPolicy(t);await this._prepareScene(t),await this._unloadAllScenes(),this._stack.push({scene:t,policy:e}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async pushScene(t,e={}){return await this._runWithTransition(async()=>{if(this._stack.some(e=>e.scene===t))throw new Error("Cannot push a scene instance that is already present in the stack.");const i=this._resolveParticipationPolicy(t,e);await this._prepareScene(t),this._stack.push({scene:t,policy:i}),this.onChangeScene.dispatch(t),this.onStartScene.dispatch(t)},e.transition),this}async popScene(t={}){return await this._runWithTransition(async()=>{if(0===this._stack.length)return;const t=this._stack[this._stack.length-1];await this._disposeScene(t.scene),this._stack.pop(),this.onChangeScene.dispatch(this.scene)},t.transition),this}update(t){this._advanceTransition(t.milliseconds);const{updateScenes:e,drawScenes:i}=this._resolveParticipants();for(const i of e)i.update(t);for(const t of i)t.draw(this._app.renderManager);const s=this._getTransitionAlpha();return s>0&&this._renderTransitionOverlay(s),null!==this.scene&&this.onUpdateScene.dispatch(this.scene),this}destroy(){if(this._unsubscribeInputRouting(),this._transition){const t=this._transition;this._transition=null,t.color.destroy(),t.reject(new Error("SceneManager was destroyed while a transition was active."))}this._unloadAllScenesOnDestroy(),this._transitionOverlay.destroy(),this.onChangeScene.destroy(),this.onStartScene.destroy(),this.onUpdateScene.destroy(),this.onStopScene.destroy()}async _prepareScene(t){t.app=this._app;try{await t.load(this._app.loader),await t.init(this._app.loader)}catch(e){let i=null;try{await t.unload(this._app.loader)}catch(t){i=t}if(t.destroy(),t.app=null,i){const t=e instanceof Error?e.message:String(e),s=i instanceof Error?i.message:String(i);throw new Error(`Failed to initialize scene: ${t}. Cleanup also failed: ${s}.`)}throw e}}async _disposeScene(t){this.onStopScene.dispatch(t),await t.unload(this._app.loader),t.destroy(),t.app=null}async _unloadAllScenes(){for(let t=this._stack.length-1;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0}async _unloadCoveredScenes(){if(this._stack.length<=1)return;const t=this._stack[this._stack.length-1];for(let t=this._stack.length-2;t>=0;t--)await this._disposeScene(this._stack[t].scene);this._stack.length=0,this._stack.push(t)}async _unloadAllScenesOnDestroy(){for(let t=this._stack.length-1;t>=0;t--)try{await this._disposeScene(this._stack[t].scene)}catch(t){console.error("SceneManager.destroy() failed to unload the active scene.",t)}this._stack.length=0}_resolveParticipationPolicy(t,e={}){const i=t.getParticipationPolicy(),s=e.mode??i.mode??"overlay";return{mode:s,input:e.input??i.input??("overlay"===s?"passthrough":"capture")}}_resolveParticipants(){const t=new Array,e=new Array;let i=!0,s=!0;for(let r=this._stack.length-1;r>=0;r--){const n=this._stack[r];i&&t.push(n.scene),s&&e.push(n.scene),"opaque"===n.policy.mode?(i=!1,s=!1):"modal"===n.policy.mode&&(i=!1)}return t.reverse(),e.reverse(),{updateScenes:t,drawScenes:e}}_subscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.add?.(this._handleKeyDown),t?.onKeyUp?.add?.(this._handleKeyUp),t?.onPointerEnter?.add?.(this._handlePointerEnter),t?.onPointerLeave?.add?.(this._handlePointerLeave),t?.onPointerDown?.add?.(this._handlePointerDown),t?.onPointerMove?.add?.(this._handlePointerMove),t?.onPointerUp?.add?.(this._handlePointerUp),t?.onPointerTap?.add?.(this._handlePointerTap),t?.onPointerSwipe?.add?.(this._handlePointerSwipe),t?.onPointerCancel?.add?.(this._handlePointerCancel),t?.onMouseWheel?.add?.(this._handleMouseWheel)}_unsubscribeInputRouting(){const t=this._app.inputManager;t?.onKeyDown?.remove?.(this._handleKeyDown),t?.onKeyUp?.remove?.(this._handleKeyUp),t?.onPointerEnter?.remove?.(this._handlePointerEnter),t?.onPointerLeave?.remove?.(this._handlePointerLeave),t?.onPointerDown?.remove?.(this._handlePointerDown),t?.onPointerMove?.remove?.(this._handlePointerMove),t?.onPointerUp?.remove?.(this._handlePointerUp),t?.onPointerTap?.remove?.(this._handlePointerTap),t?.onPointerSwipe?.remove?.(this._handlePointerSwipe),t?.onPointerCancel?.remove?.(this._handlePointerCancel),t?.onMouseWheel?.remove?.(this._handleMouseWheel)}_dispatchInput(t){for(let e=this._stack.length-1;e>=0;e--){const i=this._stack[e];if("transparent"===i.policy.input)continue;if(!1===i.scene.handleInput(t)||"capture"===i.policy.input)break}}async _runWithTransition(t,e){if(!e||"fade"!==e.type)return void await t();if(this._transition)throw new Error("Scene transition is already in progress.");const i=Math.max(0,e.duration??220);0!==i?await new Promise((s,r)=>{this._transition={type:"fade",durationMs:i,action:t,resolve:s,reject:r,color:(e.color??K.black).clone(),elapsedMs:0,phase:"out"}}):await t()}_advanceTransition(t){if(this._transition)return"out"===this._transition.phase?(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),void(this._transition.elapsedMs>=this._transition.durationMs&&(this._transition.phase="switching",this._executeTransitionAction()))):void("in"===this._transition.phase&&(this._transition.elapsedMs=Math.min(this._transition.durationMs,this._transition.elapsedMs+Math.max(0,t)),this._transition.elapsedMs>=this._transition.durationMs&&this._finishTransition()))}async _executeTransitionAction(){const t=this._transition;if(t&&"switching"===t.phase){try{await t.action()}catch(e){return void(this._transition===t&&(this._transition=null,t.color.destroy(),t.reject(e)))}this._transition===t&&(t.phase="in",t.elapsedMs=0)}}_finishTransition(){if(!this._transition)return;const t=this._transition;this._transition=null,t.color.destroy(),t.resolve()}_getTransitionAlpha(){if(!this._transition)return 0;if("switching"===this._transition.phase)return 1;const t=this._transition.durationMs>0?this._transition.elapsedMs/this._transition.durationMs:1;return"out"===this._transition.phase?t:1-t}_renderTransitionOverlay(t){const e=this._transition,i=e?e.color:K.black,s=this._app.renderManager,r=s.view.getBounds(),n=this._transitionOverlay.geometry.vertices;n[0]=r.left,n[1]=r.top,n[2]=r.right,n[3]=r.top,n[4]=r.left,n[5]=r.bottom,n[6]=r.right,n[7]=r.bottom,this._transitionOverlay.color.set(i.r,i.g,i.b,Math.max(0,Math.min(1,t))),this._transitionOverlay.render(s)}}const be=function(){var t=function(t){window.console&&window.console.error?window.console.error(t):function(t){window.console&&window.console.log&&window.console.log(t)}(t)},e={enable:{1:{0:!0}},disable:{1:{0:!0}},getParameter:{1:{0:!0}},drawArrays:{3:{0:!0}},drawElements:{4:{0:!0,2:!0}},createShader:{1:{0:!0}},getShaderParameter:{2:{1:!0}},getProgramParameter:{2:{1:!0}},getShaderPrecisionFormat:{2:{0:!0,1:!0}},getVertexAttrib:{2:{1:!0}},vertexAttribPointer:{6:{2:!0}},bindTexture:{2:{0:!0}},activeTexture:{1:{0:!0}},getTexParameter:{2:{0:!0,1:!0}},texParameterf:{3:{0:!0,1:!0}},texParameteri:{3:{0:!0,1:!0,2:!0}},copyTexImage2D:{8:{0:!0,2:!0}},copyTexSubImage2D:{8:{0:!0}},generateMipmap:{1:{0:!0}},bindBuffer:{2:{0:!0}},getBufferParameter:{2:{0:!0,1:!0}},pixelStorei:{2:{0:!0,1:!0}},bindRenderbuffer:{2:{0:!0}},bindFramebuffer:{2:{0:!0}},checkFramebufferStatus:{1:{0:!0}},framebufferRenderbuffer:{4:{0:!0,1:!0,2:!0}},framebufferTexture2D:{5:{0:!0,1:!0,2:!0}},getFramebufferAttachmentParameter:{3:{0:!0,1:!0,2:!0}},getRenderbufferParameter:{2:{0:!0,1:!0}},renderbufferStorage:{4:{0:!0,1:!0}},clear:{1:{0:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]}}},depthFunc:{1:{0:!0}},blendFunc:{2:{0:!0,1:!0}},blendFuncSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},blendEquation:{1:{0:!0}},blendEquationSeparate:{2:{0:!0,1:!0}},stencilFunc:{3:{0:!0}},stencilFuncSeparate:{4:{0:!0,1:!0}},stencilMaskSeparate:{2:{0:!0}},stencilOp:{3:{0:!0,1:!0,2:!0}},stencilOpSeparate:{4:{0:!0,1:!0,2:!0,3:!0}},cullFace:{1:{0:!0}},frontFace:{1:{0:!0}},drawArraysInstancedANGLE:{4:{0:!0}},drawElementsInstancedANGLE:{5:{0:!0,2:!0}},blendEquationEXT:{1:{0:!0}},bufferData:{3:{0:!0,2:!0},4:{0:!0,2:!0},5:{0:!0,2:!0}},bufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},copyBufferSubData:{5:{0:!0,1:!0}},getBufferSubData:{3:{0:!0},4:{0:!0},5:{0:!0}},blitFramebuffer:{10:{8:{enumBitwiseOr:["COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT"]},9:!0}},framebufferTextureLayer:{5:{0:!0,1:!0}},invalidateFramebuffer:{2:{0:!0}},invalidateSubFramebuffer:{6:{0:!0}},readBuffer:{1:{0:!0}},getInternalformatParameter:{3:{0:!0,1:!0,2:!0}},renderbufferStorageMultisample:{5:{0:!0,2:!0}},texStorage2D:{5:{0:!0,2:!0}},texStorage3D:{6:{0:!0,2:!0}},texImage2D:{9:{0:!0,2:!0,6:!0,7:!0},6:{0:!0,2:!0,3:!0,4:!0},10:{0:!0,2:!0,6:!0,7:!0}},texImage3D:{10:{0:!0,2:!0,7:!0,8:!0},11:{0:!0,2:!0,7:!0,8:!0}},texSubImage2D:{9:{0:!0,6:!0,7:!0},7:{0:!0,4:!0,5:!0},10:{0:!0,6:!0,7:!0}},texSubImage3D:{11:{0:!0,8:!0,9:!0},12:{0:!0,8:!0,9:!0}},copyTexSubImage3D:{9:{0:!0}},compressedTexImage2D:{7:{0:!0,2:!0},8:{0:!0,2:!0},9:{0:!0,2:!0}},compressedTexImage3D:{8:{0:!0,2:!0},9:{0:!0,2:!0},10:{0:!0,2:!0}},compressedTexSubImage2D:{8:{0:!0,6:!0},9:{0:!0,6:!0},10:{0:!0,6:!0}},compressedTexSubImage3D:{10:{0:!0,8:!0},11:{0:!0,8:!0},12:{0:!0,8:!0}},vertexAttribIPointer:{5:{2:!0}},drawArraysInstanced:{4:{0:!0}},drawElementsInstanced:{5:{0:!0,2:!0}},drawRangeElements:{6:{0:!0,4:!0}},readPixels:{7:{4:!0,5:!0},8:{4:!0,5:!0}},clearBufferfv:{3:{0:!0},4:{0:!0}},clearBufferiv:{3:{0:!0},4:{0:!0}},clearBufferuiv:{3:{0:!0},4:{0:!0}},clearBufferfi:{4:{0:!0}},beginQuery:{2:{0:!0}},endQuery:{1:{0:!0}},getQuery:{2:{0:!0,1:!0}},getQueryParameter:{2:{1:!0}},samplerParameteri:{3:{1:!0,2:!0}},samplerParameterf:{3:{1:!0}},getSamplerParameter:{2:{1:!0}},fenceSync:{2:{0:!0,1:{enumBitwiseOr:[]}}},clientWaitSync:{3:{1:{enumBitwiseOr:["SYNC_FLUSH_COMMANDS_BIT"]}}},waitSync:{3:{1:{enumBitwiseOr:[]}}},getSyncParameter:{2:{1:!0}},bindTransformFeedback:{2:{0:!0}},beginTransformFeedback:{1:{0:!0}},transformFeedbackVaryings:{3:{2:!0}},bindBufferBase:{3:{0:!0}},bindBufferRange:{5:{0:!0}},getIndexedParameter:{2:{0:!0}},getActiveUniforms:{3:{2:!0}},getActiveUniformBlockParameter:{3:{2:!0}}},i=null,s=null;function r(t){if(null==i)for(var e in i={},s={},t)"number"==typeof t[e]&&(i[t[e]]=e,s[e]=t[e])}function n(){if(null==i)throw"WebGLDebugUtils.init(ctx) not called"}function o(t){n();var e=i[t];return void 0!==e?"gl."+e:"/*UNKNOWN WebGL ENUM*/ 0x"+t.toString(16)}function a(t,i,r,n){var a;if(void 0!==(a=e[t])&&(void 0!==(a=a[i])&&a[r])){if("object"==typeof a[r]&&void 0!==a[r].enumBitwiseOr){for(var h=a[r].enumBitwiseOr,l=0,u=[],d=0;d<h.length;++d){var c=s[h[d]];0!==(n&c)&&(l|=c,u.push(o(c)))}return l===n?u.join(" | "):o(n)}return o(n)}return null===n?"null":void 0===n?"undefined":n.toString()}function h(t,e,i){t.__defineGetter__(i,function(){return e[i]}),t.__defineSetter__(i,function(t){e[i]=t})}function l(t){var e=!!t.createTransformFeedback;e&&t.bindVertexArray(null);var i=t.getParameter(t.MAX_VERTEX_ATTRIBS),s=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,s);for(var r=0;r<i;++r)t.disableVertexAttribArray(r),t.vertexAttribPointer(r,4,t.FLOAT,!1,0,0),t.vertexAttrib1f(r,0),e&&t.vertexAttribDivisor(r,0);t.deleteBuffer(s);var n=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);for(r=0;r<n;++r)t.activeTexture(t.TEXTURE0+r),t.bindTexture(t.TEXTURE_CUBE_MAP,null),t.bindTexture(t.TEXTURE_2D,null),e&&(t.bindTexture(t.TEXTURE_2D_ARRAY,null),t.bindTexture(t.TEXTURE_3D,null),t.bindSampler(r,null));if(t.activeTexture(t.TEXTURE0),t.useProgram(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindRenderbuffer(t.RENDERBUFFER,null),t.disable(t.BLEND),t.disable(t.CULL_FACE),t.disable(t.DEPTH_TEST),t.disable(t.DITHER),t.disable(t.SCISSOR_TEST),t.blendColor(0,0,0,0),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ZERO),t.clearColor(0,0,0,0),t.clearDepth(1),t.clearStencil(-1),t.colorMask(!0,!0,!0,!0),t.cullFace(t.BACK),t.depthFunc(t.LESS),t.depthMask(!0),t.depthRange(0,1),t.frontFace(t.CCW),t.hint(t.GENERATE_MIPMAP_HINT,t.DONT_CARE),t.lineWidth(1),t.pixelStorei(t.PACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_ALIGNMENT,4),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,!1),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.UNPACK_COLORSPACE_CONVERSION_WEBGL&&t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.BROWSER_DEFAULT_WEBGL),t.polygonOffset(0,0),t.sampleCoverage(1,!1),t.scissor(0,0,t.canvas.width,t.canvas.height),t.stencilFunc(t.ALWAYS,0,4294967295),t.stencilMask(4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT|t.STENCIL_BUFFER_BIT),e){t.drawBuffers([t.BACK]),t.readBuffer(t.BACK),t.bindBuffer(t.COPY_READ_BUFFER,null),t.bindBuffer(t.COPY_WRITE_BUFFER,null),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),t.bindBuffer(t.PIXEL_UNPACK_BUFFER,null);var o=t.getParameter(t.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS);for(r=0;r<o;++r)t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,r,null);var a=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);for(r=0;r<a;++r)t.bindBufferBase(t.UNIFORM_BUFFER,r,null);t.disable(t.RASTERIZER_DISCARD),t.pixelStorei(t.UNPACK_IMAGE_HEIGHT,0),t.pixelStorei(t.UNPACK_SKIP_IMAGES,0),t.pixelStorei(t.UNPACK_ROW_LENGTH,0),t.pixelStorei(t.UNPACK_SKIP_ROWS,0),t.pixelStorei(t.UNPACK_SKIP_PIXELS,0),t.pixelStorei(t.PACK_ROW_LENGTH,0),t.pixelStorei(t.PACK_SKIP_ROWS,0),t.pixelStorei(t.PACK_SKIP_PIXELS,0),t.hint(t.FRAGMENT_SHADER_DERIVATIVE_HINT,t.DONT_CARE)}for(;t.getError(););}return{init:r,mightBeEnum:function(t){return n(),void 0!==i[t]},glEnumToString:o,glFunctionArgToString:a,glFunctionArgsToString:function(t,e){for(var i="",s=e.length,r=0;r<s;++r)i+=(0==r?"":", ")+a(t,s,r,e[r]);return i},makeDebugContext:function e(i,s,n,l){l=l||i,r(i),s=s||function(e,i,s){for(var r="",n=s.length,h=0;h<n;++h)r+=(0==h?"":", ")+a(i,n,h,s[h]);t("WebGL error "+o(e)+" in "+i+"("+r+")")};var u={};function d(t,e){return function(){n&&n(e,arguments);var i=t[e].apply(t,arguments),r=l.getError();return 0!=r&&(u[r]=!0,s(r,e,arguments)),i}}var c={};for(var p in i)if("function"==typeof i[p])if("getExtension"!=p)c[p]=d(i,p);else{var _=d(i,p);c[p]=function(){var t=_.apply(i,arguments);return t?e(t,s,n,l):null}}else h(c,i,p);return c.getError=function(){for(var t in u)if(u.hasOwnProperty(t)&&u[t])return u[t]=!1,t;return i.NO_ERROR},c},makeLostContextSimulatingCanvas:function(t){var e,i,s,r=[],n=[],o={},a=1,u=!1,d=[],c=0,p=0,_=!1,f=0,m={};function g(t){return"function"==typeof t?t:function(e){t.handleEvent(e)}}function y(){++p,u||c==p&&t.loseContext()}function x(t,e){var i=t[e];return function(){if(y(),!u)return i.apply(t,arguments)}}function w(t){return{statusMessage:t,preventDefault:function(){_=!0}}}return t.getContext=(s=t.getContext,function(){var r=s.apply(t,arguments);if(r instanceof WebGLRenderingContext||window.WebGL2RenderingContext&&r instanceof WebGL2RenderingContext){if(r!=e){if(e)throw"got different context";i=window.WebGL2RenderingContext&&r instanceof WebGL2RenderingContext,o=function(t){for(var s in t)"function"==typeof t[s]?o[s]=x(t,s):h(o,t,s);o.getError=function(){if(y(),!u)for(;t=e.getError();)m[t]=!0;for(var t in m)if(m[t])return delete m[t],t;return o.NO_ERROR};var r=["createBuffer","createFramebuffer","createProgram","createRenderbuffer","createShader","createTexture"];i&&r.push("createQuery","createSampler","fenceSync","createTransformFeedback","createVertexArray");for(var n=0;n<r.length;++n){var l=r[n];o[l]=function(e){return function(){if(y(),u)return null;var i=e.apply(t,arguments);return i.__webglDebugContextLostId__=a,d.push(i),i}}(t[l])}var c=["getActiveAttrib","getActiveUniform","getBufferParameter","getContextAttributes","getAttachedShaders","getFramebufferAttachmentParameter","getParameter","getProgramParameter","getProgramInfoLog","getRenderbufferParameter","getShaderParameter","getShaderInfoLog","getShaderSource","getTexParameter","getUniform","getUniformLocation","getVertexAttrib"];for(i&&c.push("getInternalformatParameter","getQuery","getQueryParameter","getSamplerParameter","getSyncParameter","getTransformFeedbackVarying","getIndexedParameter","getUniformIndices","getActiveUniforms","getActiveUniformBlockParameter","getActiveUniformBlockName"),n=0;n<c.length;++n)l=c[n],o[l]=function(e){return function(){return y(),u?null:e.apply(t,arguments)}}(o[l]);var p=["isBuffer","isEnabled","isFramebuffer","isProgram","isRenderbuffer","isShader","isTexture"];for(i&&p.push("isQuery","isSampler","isSync","isTransformFeedback","isVertexArray"),n=0;n<p.length;++n)l=p[n],o[l]=function(e){return function(){return y(),!u&&e.apply(t,arguments)}}(o[l]);return o.checkFramebufferStatus=function(e){return function(){return y(),u?o.FRAMEBUFFER_UNSUPPORTED:e.apply(t,arguments)}}(o.checkFramebufferStatus),o.getAttribLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getAttribLocation),o.getVertexAttribOffset=function(e){return function(){return y(),u?0:e.apply(t,arguments)}}(o.getVertexAttribOffset),o.isContextLost=function(){return u},i&&(o.getFragDataLocation=function(e){return function(){return y(),u?-1:e.apply(t,arguments)}}(o.getFragDataLocation),o.clientWaitSync=function(e){return function(){return y(),u?o.WAIT_FAILED:e.apply(t,arguments)}}(o.clientWaitSync),o.getUniformBlockIndex=function(e){return function(){return y(),u?o.INVALID_INDEX:e.apply(t,arguments)}}(o.getUniformBlockIndex)),o}(e=r)}return o}return r}),function(t){var e=t.addEventListener;t.addEventListener=function(i,s,o){switch(i){case"webglcontextlost":!function(t){r.push(g(t))}(s);break;case"webglcontextrestored":!function(t){n.push(g(t))}(s);break;default:e.apply(t,arguments)}}}(t),t.loseContext=function(){if(!u){for(u=!0,c=0,++a;e.getError(););!function(){for(var t=Object.keys(m),e=0;e<t.length;++e)delete m[t[e]]}(),m[e.CONTEXT_LOST_WEBGL]=!0;var i=w("context lost"),s=r.slice();setTimeout(function(){for(var e=0;e<s.length;++e)s[e](i);f>=0&&setTimeout(function(){t.restoreContext()},f)},0)}},t.restoreContext=function(){u&&n.length&&setTimeout(function(){if(!_)throw"can not restore. webglcontestlost listener did not call event.preventDefault";!function(){for(var t=0;t<d.length;++t){var s=d[t];s instanceof WebGLBuffer?e.deleteBuffer(s):s instanceof WebGLFramebuffer?e.deleteFramebuffer(s):s instanceof WebGLProgram?e.deleteProgram(s):s instanceof WebGLRenderbuffer?e.deleteRenderbuffer(s):s instanceof WebGLShader?e.deleteShader(s):s instanceof WebGLTexture?e.deleteTexture(s):i&&(s instanceof WebGLQuery?e.deleteQuery(s):s instanceof WebGLSampler?e.deleteSampler(s):s instanceof WebGLSync?e.deleteSync(s):s instanceof WebGLTransformFeedback?e.deleteTransformFeedback(s):s instanceof WebGLVertexArrayObject&&e.deleteVertexArray(s))}}(),l(e),u=!1,p=0,_=!1;for(var t=n.slice(),s=w("context restored"),r=0;r<t.length;++r)t[r](s)},0)},t.loseContextInNCalls=function(t){if(u)throw"You can not ask a lost contet to be lost";c=p+t},t.getNumCalls=function(){return p},t.setRestoreTimeout=function(t){f=t},t},resetToInitialState:l}}();class Te{constructor(t=tt.Triangles){this._attributes=[],this._indexBuffer=null,this._runtime=null,this._version=0,this._drawMode=t}get attributes(){return this._attributes}get indexBuffer(){return this._indexBuffer}get drawMode(){return this._drawMode}get version(){return this._version}connect(t){return this._runtime=t,this}disconnect(){return this._runtime=null,this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}addAttribute(t,e,i=st.Float,s=!1,r=0,n=0){const{location:o,size:a}=e;return this._attributes.push({buffer:t,location:o,size:a,type:i,normalized:s,stride:r,start:n}),this._version++,this}addIndex(t){return this._indexBuffer=t,this._version++,this}clear(){return this._attributes.length=0,this._indexBuffer=null,this._version++,this}draw(t,e,i=this._drawMode){return this._runtime?.draw(this,t,e,i),this}destroy(){this._runtime?.destroy(this),this._runtime=null,this._indexBuffer=null}}var Se;!function(t){t[t.WebGl2=0]="WebGl2",t[t.WebGpu=1]="WebGpu"}(Se||(Se={}));class Ce{constructor(){this.backendType=Se.WebGl2,this._runtime=null}connect(t){if(null===this._runtime){if(t.backendType!==Se.WebGl2)throw new Error(`${this.constructor.name} requires a WebGL2 runtime, but received backendType ${String(t.backendType)}.`);this._runtime=t,this.onConnect(t)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}class Me{constructor(t,e){this.attributes=new Map,this.uniforms=new Map,this._runtime=null,this._vertexSource=t,this._fragmentSource=e}get vertexSource(){return this._vertexSource}get fragmentSource(){return this._fragmentSource}connect(t){return this._runtime=t,t.initialize(this),this}disconnect(){return this._runtime=null,this.attributes.clear(),this.uniforms.clear(),this}bind(){return this._runtime?.bind(this),this}unbind(){return this._runtime?.unbind(this),this}sync(){return this._runtime?.sync(this),this}getAttribute(t){const e=this.attributes.get(t);if(!e)throw new Error(`Attribute "${t}" is not available.`);return e}getUniform(t){const e=this.uniforms.get(t);if(!e)throw new Error(`Uniform "${t}" is not available.`);return e}destroy(){this._runtime?.destroy(this),this._runtime=null,this.attributes.clear(),this.uniforms.clear()}}const Pe={[st.Float]:1,[st.FloatVec2]:2,[st.FloatVec3]:3,[st.FloatVec4]:4,[st.Int]:1,[st.IntVec2]:2,[st.IntVec3]:3,[st.IntVec4]:4,[st.Bool]:1,[st.BoolVec2]:2,[st.BoolVec3]:3,[st.BoolVec4]:4,[st.FloatMat2]:4,[st.FloatMat3]:9,[st.FloatMat4]:16,[st.Sampler2D]:1},Be={[st.Float]:Float32Array,[st.FloatVec2]:Float32Array,[st.FloatVec3]:Float32Array,[st.FloatVec4]:Float32Array,[st.Int]:Int32Array,[st.IntVec2]:Int32Array,[st.IntVec3]:Int32Array,[st.IntVec4]:Int32Array,[st.Bool]:Uint8Array,[st.BoolVec2]:Uint8Array,[st.BoolVec3]:Uint8Array,[st.BoolVec4]:Uint8Array,[st.FloatMat2]:Float32Array,[st.FloatMat3]:Float32Array,[st.FloatMat4]:Float32Array,[st.Sampler2D]:Uint8Array},Ee={[st.Float]:"FLOAT",[st.FloatVec2]:"FLOAT_VEC2",[st.FloatVec3]:"FLOAT_VEC3",[st.FloatVec4]:"FLOAT_VEC4",[st.Int]:"INT",[st.IntVec2]:"INT_VEC2",[st.IntVec3]:"INT_VEC3",[st.IntVec4]:"INT_VEC4",[st.Bool]:"BOOL",[st.BoolVec2]:"BOOL_VEC2",[st.BoolVec3]:"BOOL_VEC3",[st.BoolVec4]:"BOOL_VEC4",[st.FloatMat2]:"FLOAT_MAT2",[st.FloatMat3]:"FLOAT_MAT3",[st.FloatMat4]:"FLOAT_MAT4",[st.Sampler2D]:"SAMPLER_2D"};class Re{constructor(t,e,i){this.location=-1,this.index=t,this.name=e,this.type=i,this.size=Pe[i]}destroy(){}}class Ae{constructor(t,e,i,s,r){this._dirty=!0,this.name=s.replace(/\[.*?]/,""),this.index=t,this.type=e,this.size=i,this._value=r}get propName(){return this.name.substr(this.name.lastIndexOf(".")+1)}get value(){return this._value}get dirty(){return this._dirty}setValue(t){return this._value.set(t),this._dirty=!0,this}markClean(){this._dirty=!1}destroy(){}}class ke{constructor(t,e,i){this._uniforms=new Map,this._context=t,this._program=e,this.index=i,this.name=t.getActiveUniformBlockName(e,i)||"",this.binding=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_BINDING),this.dataSize=t.getActiveUniformBlockParameter(e,i,t.UNIFORM_BLOCK_DATA_SIZE),this._uniformBuffer=t.createBuffer(),this._blockData=new ArrayBuffer(this.dataSize),this._extractUniforms(),t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferData(t.UNIFORM_BUFFER,this._blockData,t.DYNAMIC_DRAW),t.bindBufferBase(t.UNIFORM_BUFFER,this.binding,this._uniformBuffer),t.uniformBlockBinding(this._program,this.index,this.binding)}getUniform(t){if(!this._uniforms.has(t))throw new Error(`Uniform "${t}" is not available.`);return this._uniforms.get(t)}upload(){const t=this._context;t.bindBuffer(t.UNIFORM_BUFFER,this._uniformBuffer),t.bufferSubData(t.UNIFORM_BUFFER,0,this._blockData)}destroy(){for(const t of this._uniforms.values())t.destroy();this._uniforms.clear()}_extractUniforms(){const t=this._context,e=this._program,i=this._blockData,s=t.getActiveUniformBlockParameter(e,this.index,t.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES),r=t.getActiveUniforms(e,s,t.UNIFORM_OFFSET),n=s.length;for(let o=0;o<n;o++){const{type:n,size:a,name:h}=t.getActiveUniform(e,s[o]),l=new Be[n](i,r[o],Pe[n]*a),u=new Ae(s[o],n,a,h,l);this._uniforms.set(u.propName,u)}}}const Le={[st.Float]:(t,e,i)=>{t.uniform1f(e,i[0])},[st.FloatVec2]:(t,e,i)=>{t.uniform2fv(e,i)},[st.FloatVec3]:(t,e,i)=>{t.uniform3fv(e,i)},[st.FloatVec4]:(t,e,i)=>{t.uniform4fv(e,i)},[st.Int]:(t,e,i)=>{t.uniform1i(e,i[0])},[st.IntVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[st.IntVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[st.IntVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[st.Bool]:(t,e,i)=>{t.uniform1i(e,i[0])},[st.BoolVec2]:(t,e,i)=>{t.uniform2iv(e,i)},[st.BoolVec3]:(t,e,i)=>{t.uniform3iv(e,i)},[st.BoolVec4]:(t,e,i)=>{t.uniform4iv(e,i)},[st.FloatMat2]:(t,e,i)=>{t.uniformMatrix2fv(e,!1,i)},[st.FloatMat3]:(t,e,i)=>{t.uniformMatrix3fv(e,!1,i)},[st.FloatMat4]:(t,e,i)=>{t.uniformMatrix4fv(e,!1,i)},[st.Sampler2D]:(t,e,i)=>{t.uniform1i(e,i[0])}};function Fe(t){let e=null,i=null,s=null;const r=[],n=[];function o(o){e||(i=De(t,t.VERTEX_SHADER,o.vertexSource),s=De(t,t.FRAGMENT_SHADER,o.fragmentSource),e=function(t,e,i){const s=t.createProgram();if(!s)throw new Error("Could not create shader program.");if(t.attachShader(s,e),t.attachShader(s,i),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS)){const r=t.getProgramInfoLog(s);throw t.detachShader(s,e),t.detachShader(s,i),t.deleteProgram(s),new Error(`Shader program linking failed: ${r}`)}return s}(t,i,s),function(t,e,i){const s=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r<s;r++){const s=t.getActiveAttrib(e,r);if(!s)continue;const n=new Re(r,s.name,s.type);n.location=t.getAttribLocation(e,s.name),i.attributes.set(s.name,n)}}(t,e,o),function(t,e,i,s){const r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),n=new Uint8Array(r).map((t,e)=>e),o=t.getActiveUniforms(e,n,t.UNIFORM_BLOCK_INDEX),a=n.filter(t=>-1===o[t]);for(const r of a){const n=t.getActiveUniform(e,r);if(!n)continue;const o=new Be[n.type](Pe[n.type]*n.size),a=new Ae(r,n.type,n.size,n.name,o),h=t.getUniformLocation(e,a.name),l=Le[n.type];i.uniforms.set(a.name,a),h&&s.push({location:h,uploadFn:l,uniform:a})}}(t,e,o,r),function(t,e,i){const s=t.getProgramParameter(e,t.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<s;r++){const s=new ke(t,e,r);i.push(s)}}(t,e,n))}function a(){for(const e of r)e.uniform.dirty&&(e.uploadFn(t,e.location,e.uniform.value),e.uniform.markClean());for(const t of n)t.upload()}return{initialize:o,bind:i=>{o(i),t.useProgram(e),a()},unbind:()=>{t.useProgram(null)},sync:()=>{t.useProgram(e),a()},destroy:o=>{t.deleteShader(i),t.deleteShader(s),t.deleteProgram(e);for(const t of n)t.destroy();i=null,s=null,e=null,r.length=0,n.length=0,o.disconnect()}}}function De(t,e,i){const s=t.createShader(e);if(!s)throw new Error("Could not create shader.");if(t.shaderSource(s,i),t.compileShader(s),!t.getShaderParameter(s,t.COMPILE_STATUS)){const e=t.getShaderInfoLog(s);throw t.deleteShader(s),new Error(`Shader compilation failed: ${e}`)}return s}class Ie{constructor(t,e,i){this._runtime=null,this._data=P,this._version=0,this._type=t,this._usage=i,e&&this.upload(e)}get type(){return this._type}get usage(){return this._usage}get data(){return this._data}get version(){return this._version}connect(t){return this._runtime=t,this._data.byteLength>0&&t.upload(this,0),this}disconnect(){return this._runtime=null,this}upload(t,e=0){this._data=t,this._version++,this._runtime?.upload(this,e)}bind(){this._runtime?.bind(this)}destroy(){this._runtime?.destroy(this),this._runtime=null}}const Ne=(t={})=>{const{canvas:e,fillStyle:i,width:s,height:r}=t,n=e??document.createElement("canvas"),o=n.getContext("2d");return n.width=s??10,n.height=r??10,o.fillStyle=i??"#6495ed",o.fillRect(0,0,n.width,n.height),n},Ue=new Map;class Ve extends Ce{constructor(t,e,i,s){super(),this.batchIndex=0,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.vao=null,this.indexBuffer=null,this.vertexBuffer=null,this.connection=null,this.batchSize=t,this.attributeCount=e,this.vertexData=new ArrayBuffer(t*e*4),this.float32View=new Float32Array(this.vertexData),this.uint32View=new Uint32Array(this.vertexData),this.indexData=(t=>{const e=new Uint16Array(6*t),i=e.length;for(let t=0,s=0;t<i;t+=6,s+=4)e[t]=s,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s,e[t+4]=s+2,e[t+5]=s+3;return e})(t),this.shader=new Me(i,s)}flush(){const t=this.getRuntimeOrNull(),e=this.vertexBuffer,i=this.vao;if(0===this.batchIndex||null===t||null===e||null===i)return;const s=t.view;this.currentView===s&&this.currentViewId===s.updateId||(this.currentView=s,this.currentViewId=s.updateId,this.updateView(s)),this.shader.sync(),t.bindVertexArrayObject(i),e.upload(this.float32View.subarray(0,this.batchIndex*this.attributeCount)),i.draw(6*this.batchIndex,0),t.stats.batches++,t.stats.drawCalls++,this.batchIndex=0}destroy(){this.disconnect(),this.shader.destroy(),this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.connection=null}onConnect(t){const e=t.context;this.shader.connect(Fe(e)),this.connection=this.createConnection(e),this.indexBuffer=new Ie(et.ElementArrayBuffer,this.indexData,it.StaticDraw).connect(this.createBufferRuntime(this.connection)),this.vertexBuffer=new Ie(et.ArrayBuffer,this.vertexData,it.DynamicDraw).connect(this.createBufferRuntime(this.connection)),this.vao=this.createVao(e,this.indexBuffer,this.vertexBuffer).connect(this.createVaoRuntime(this.connection))}onDisconnect(){this.flush(),this.shader.disconnect(),this.indexBuffer?.destroy(),this.indexBuffer=null,this.vertexBuffer?.destroy(),this.vertexBuffer=null,this.vao?.destroy(),this.vao=null,this.connection=null,this.currentTexture=null,this.currentBlendMode=null,this.currentView=null,this.currentViewId=-1,this.batchIndex=0}createConnection(t){const e=t.createVertexArray();if(null===e)throw new Error("Could not create vertex array object.");return{gl:t,buffers:new Map,vaoHandle:e}}createBufferRuntime(t){const e=t.gl.createBuffer();if(null===e)throw new Error("Could not create render buffer.");return{bind:i=>{t.gl.bindBuffer(i.type,e)},upload:(i,s)=>{const r=t.gl,n=i.data,o=t.buffers.get(i);r.bindBuffer(i.type,e),o&&o.dataByteLength>=n.byteLength?(r.bufferSubData(i.type,s,n),o.dataByteLength=n.byteLength):(r.bufferData(i.type,n,i.usage),t.buffers.set(i,{handle:e,dataByteLength:n.byteLength}))},destroy:i=>{t.gl.deleteBuffer(e),t.buffers.delete(i),i.disconnect()}}}createVaoRuntime(t){let e=-1;return{bind:i=>{const s=t.gl;if(s.bindVertexArray(t.vaoHandle),e!==i.version){let t=null;for(const e of i.attributes)t!==e.buffer&&(e.buffer.bind(),t=e.buffer),s.vertexAttribPointer(e.location,e.size,e.type,e.normalized,e.stride,e.start),s.enableVertexAttribArray(e.location);i.indexBuffer&&i.indexBuffer.bind(),e=i.version}},unbind:()=>{t.gl.bindVertexArray(null)},draw:(e,i,s,r)=>{const n=t.gl;e.indexBuffer?n.drawElements(r,i,n.UNSIGNED_SHORT,s):n.drawArrays(r,s,i)},destroy:e=>{t.gl.deleteVertexArray(t.vaoHandle),e.disconnect()}}}}class Oe extends Ve{constructor(t){super(t,16,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,blendMode:i,tint:s,vertices:r,texCoords:n}=t,o=this.batchIndex>=this.batchSize,a=e!==this.currentTexture,h=i!==this.currentBlendMode,l=o||a||h,u=l?0:this.batchIndex*this.attributeCount,d=this.float32View,c=this.uint32View,p=this.getRuntime();return l&&(this.flush(),a&&(this.currentTexture=e),h&&(this.currentBlendMode=i,p.setBlendMode(i))),a&&e&&p.bindTexture(e),d[u+0]=r[0],d[u+1]=r[1],d[u+4]=r[2],d[u+5]=r[3],d[u+8]=r[4],d[u+9]=r[5],d[u+12]=r[6],d[u+13]=r[7],c[u+2]=n[0],c[u+6]=n[1],c[u+10]=n[2],c[u+14]=n[3],c[u+3]=c[u+7]=c[u+11]=c[u+15]=s.toRgba(),this.batchIndex++,this}createVao(t,e,i){return(new Te).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,12)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class Ge extends Ve{constructor(t){super(t,36,"#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec2 a_texcoord;\r\nlayout(location = 2) in vec2 a_translation;\r\nlayout(location = 3) in vec2 a_scale;\r\nlayout(location = 4) in float a_rotation;\r\nlayout(location = 5) in vec4 a_color;\n\nuniform mat3 u_projection;\nuniform mat3 u_translation;\n\r\nout vec2 v_texcoord;\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\n vec2 rotation = vec2(sin(radians(a_rotation)), cos(radians(a_rotation)));\n vec3 position = vec3(\n (a_position.x * (a_scale.x * rotation.y)) + (a_position.y * (a_scale.y * rotation.x)) + a_translation.x,\n (a_position.x * (a_scale.x * -rotation.x)) + (a_position.y * (a_scale.y * rotation.y)) + a_translation.y,\n 1.0\n );\n\n gl_Position = vec4((u_projection * u_translation * position).xy, 0.0, 1.0);\n\r\n v_texcoord = a_texcoord;\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nuniform sampler2D u_texture;\r\n\r\nin vec2 v_texcoord;\r\nin vec4 v_color;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nvoid main(void) {\r\n fragColor = texture(u_texture, v_texcoord) * v_color;\r\n}\r\n")}render(t){const{texture:e,vertices:i,texCoords:s,particles:r,blendMode:n}=t,o=e!==this.currentTexture,a=n!==this.currentBlendMode,h=this.float32View,l=this.uint32View,u=this.getRuntime();this.flush(),(o||a)&&(o&&(this.currentTexture=e),a&&(this.currentBlendMode=n,u.setBlendMode(n))),o&&u.bindTexture(e),this.shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));for(const t of r){this.batchIndex>=this.batchSize&&this.flush();const{position:e,scale:r,rotation:n,tint:o}=t,a=this.batchIndex*this.attributeCount;h[a+0]=h[a+27]=i[0],h[a+1]=h[a+10]=i[1],h[a+9]=h[a+18]=i[2],h[a+19]=h[a+28]=i[3],l[a+2]=s[0],l[a+11]=s[1],l[a+20]=s[2],l[a+29]=s[3],h[a+3]=h[a+12]=h[a+21]=h[a+30]=e.x,h[a+4]=h[a+13]=h[a+22]=h[a+31]=e.y,h[a+5]=h[a+14]=h[a+23]=h[a+32]=r.x,h[a+6]=h[a+15]=h[a+24]=h[a+33]=r.y,h[a+7]=h[a+16]=h[a+25]=h[a+34]=n,l[a+8]=l[a+17]=l[a+26]=l[a+35]=o.toRgba(),this.batchIndex++}return this}createVao(t,e,i){return(new Te).addIndex(e).addAttribute(i,this.shader.getAttribute("a_position"),t.FLOAT,!1,this.attributeCount,0).addAttribute(i,this.shader.getAttribute("a_texcoord"),t.UNSIGNED_SHORT,!0,this.attributeCount,8).addAttribute(i,this.shader.getAttribute("a_translation"),t.FLOAT,!1,this.attributeCount,12).addAttribute(i,this.shader.getAttribute("a_scale"),t.FLOAT,!1,this.attributeCount,20).addAttribute(i,this.shader.getAttribute("a_rotation"),t.FLOAT,!1,this.attributeCount,28).addAttribute(i,this.shader.getAttribute("a_color"),t.UNSIGNED_BYTE,!0,this.attributeCount,32)}updateView(t){return this.shader.getUniform("u_projection").setValue(t.getTransform().toArray(!1)),this}}class ze extends Ce{constructor(t){super(),this._shader=new Me("#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) in vec2 a_position;\r\nlayout(location = 1) in vec4 a_color;\r\n\r\nuniform mat3 u_projection;\r\nuniform mat3 u_translation;\r\n\r\nout vec4 v_color;\r\n\r\nvoid main(void) {\r\n gl_Position = vec4((u_projection * u_translation * vec3(a_position, 1.0)).xy, 0.0, 1.0);\r\n v_color = vec4(a_color.rgb * a_color.a, a_color.a);\r\n}\r\n","#version 300 es\r\nprecision lowp float;\r\n\r\nlayout(location = 0) out vec4 fragColor;\r\n\r\nin vec4 v_color;\r\n\r\nvoid main(void) {\r\n fragColor = v_color;\r\n}\r\n"),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1,this._vertexCapacity=Math.max(4,t),this._indexCapacity=Math.max(6,3*this._vertexCapacity),this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._indexData=new Uint16Array(this._indexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}render(t){const e=this._connection;if(!e)throw new Error("Renderer not connected");const i=this.getRuntime(),{geometry:s,drawMode:r,color:n,blendMode:o}=t,a=s.vertices,h=s.indices,l=a.length/2,u=h.length>0?h.length:l;if(0===l||0===u)return;this._ensureVertexCapacity(l),this._ensureIndexCapacity(u),o!==this._currentBlendMode&&(this._currentBlendMode=o,i.setBlendMode(o));const d=i.view;this._currentView===d&&this._viewId===d.updateId||(this._currentView=d,this._viewId=d.updateId,this._shader.getUniform("u_projection").setValue(d.getTransform().toArray(!1))),this._shader.getUniform("u_translation").setValue(t.getGlobalTransform().toArray(!1));const c=n.toRgba();for(let t=0;t<l;t++){const e=2*t,i=3*t;this._float32View[i]=a[e],this._float32View[i+1]=a[e+1],this._uint32View[i+2]=c}if(h.length>0)this._indexData.set(h,0);else for(let t=0;t<l;t++)this._indexData[t]=t;this._shader.sync(),i.bindVertexArrayObject(e.vao),e.vertexBuffer.upload(this._float32View.subarray(0,3*l)),e.indexBuffer.upload(this._indexData.subarray(0,u)),e.vao.draw(u,0,r),i.stats.batches++,i.stats.drawCalls++}flush(){}destroy(){this.disconnect(),this._shader.destroy(),this._currentBlendMode=null,this._currentView=null}onConnect(t){const e=t.context,i=e.createVertexArray();if(this._shader.connect(Fe(e)),null===i)throw new Error("Could not create vertex array object.");const s=new Map,r=new Ie(et.ElementArrayBuffer,this._indexData,it.DynamicDraw).connect(this._createBufferRuntime(e,s)),n=new Ie(et.ArrayBuffer,this._vertexData,it.DynamicDraw).connect(this._createBufferRuntime(e,s)),o=(new Te).addIndex(r).addAttribute(n,this._shader.getAttribute("a_position"),e.FLOAT,!1,12,0).addAttribute(n,this._shader.getAttribute("a_color"),e.UNSIGNED_BYTE,!0,12,8).connect(this._createVaoRuntime(e,i));this._connection={gl:e,buffers:s,vaoHandle:i,vao:o,indexBuffer:r,vertexBuffer:n}}onDisconnect(){const t=this._connection;t&&(this._shader.disconnect(),t.indexBuffer.destroy(),t.vertexBuffer.destroy(),t.vao.destroy(),this._connection=null,this._currentBlendMode=null,this._currentView=null,this._viewId=-1)}_ensureVertexCapacity(t){if(!(t<=this._vertexCapacity)){for(;this._vertexCapacity<t;)this._vertexCapacity*=2;this._vertexData=new ArrayBuffer(12*this._vertexCapacity),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}}_ensureIndexCapacity(t){if(!(t<=this._indexCapacity)){for(;this._indexCapacity<t;)this._indexCapacity*=2;this._indexData=new Uint16Array(this._indexCapacity)}}_createBufferRuntime(t,e){const i=t.createBuffer();if(null===i)throw new Error("Could not create render buffer.");return{bind:e=>{t.bindBuffer(e.type,i)},upload:(s,r)=>{const n=e.get(s),o=s.data;t.bindBuffer(s.type,i),n&&n.dataByteLength>=o.byteLength?(t.bufferSubData(s.type,r,o),n.dataByteLength=o.byteLength):(t.bufferData(s.type,o,s.usage),e.set(s,{handle:i,dataByteLength:o.byteLength}))},destroy:s=>{t.deleteBuffer(i),e.delete(s),s.disconnect()}}}_createVaoRuntime(t,e){let i=-1;return{bind:s=>{if(t.bindVertexArray(e),i!==s.version){let e=null;for(const i of s.attributes)e!==i.buffer&&(i.buffer.bind(),e=i.buffer),t.vertexAttribPointer(i.location,i.size,i.type,i.normalized,i.stride,i.start),t.enableVertexAttribArray(i.location);s.indexBuffer&&s.indexBuffer.bind(),i=s.version}},unbind:()=>{t.bindVertexArray(null)},draw:(e,i,s,r)=>{e.indexBuffer?t.drawElements(r,i,t.UNSIGNED_SHORT,s):t.drawArrays(r,s,i)},destroy:i=>{t.deleteVertexArray(e),i.disconnect()}}}}var We;!function(t){t[t.None=0]="None",t[t.Translation=1]="Translation",t[t.Rotation=2]="Rotation",t[t.Scaling=4]="Scaling",t[t.Origin=8]="Origin",t[t.Transform=15]="Transform",t[t.TransformInverse=16]="TransformInverse",t[t.BoundingBox=32]="BoundingBox",t[t.TextureCoords=64]="TextureCoords",t[t.VertexTint=128]="VertexTint"}(We||(We={}));class qe extends ge{constructor(t){super(),this._texture=null,this._textureFrame=new re,this._vertices=new Float32Array(8),this._texCoords=new Uint32Array(4),null!==t&&this.setTexture(t)}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get width(){return Math.abs(this.scale.x)*this._textureFrame.width}set width(t){this.scale.x=t/this._textureFrame.width}get height(){return Math.abs(this.scale.y)*this._textureFrame.height}set height(t){this.scale.y=t/this._textureFrame.height}get vertices(){const{left:t,top:e,right:i,bottom:s}=this.getLocalBounds(),{a:r,b:n,x:o,c:a,d:h,y:l}=this.getGlobalTransform();return this._vertices[0]=t*r+e*n+o,this._vertices[1]=t*a+e*h+l,this._vertices[2]=i*r+e*n+o,this._vertices[3]=i*a+e*h+l,this._vertices[4]=i*r+s*n+o,this._vertices[5]=i*a+s*h+l,this._vertices[6]=t*r+s*n+o,this._vertices[7]=t*a+s*h+l,this._vertices}get texCoords(){if(null===this._texture)throw new Error("texCoords can only be calculated when the sprite has a texture");if(this.flags.pop(We.TextureCoords)){const{width:t,height:e}=this._texture,{left:i,top:s,right:r,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(s/e*65535&65535)<<16,h=r/t*65535&65535,l=(n/e*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o)}return this._texCoords}setTexture(t){return this._texture!==t&&(this._texture=t,this.updateTexture(),this.invalidateCache()),this}updateTexture(){return this._texture&&(this._texture.updateSource(),this.resetTextureFrame(),this.invalidateCache()),this}setTextureFrame(t,e=!0){const i=this.width,s=this.height;return this._textureFrame.copy(t),this.flags.push(We.TextureCoords),this.localBounds.set(0,0,t.width,t.height),e?(this.width=t.width,this.height=t.height):(this.width=i,this.height=s),this.invalidateCache(),this}resetTextureFrame(){if(!this._texture)throw new Error("Cannot reset texture frame when no texture was set");return this.setTextureFrame(re.temp.set(0,0,this._texture.width,this._texture.height))}getNormals(){const[t,e,i,s,r,n,o,a]=this.vertices;return[new de(i-t,s-e).rperp().normalize(),new de(r-i,n-s).rperp().normalize(),new de(o-r,a-n).rperp().normalize(),new de(t-o,e-a).rperp().normalize()]}project(t,e=new ct){const[i,s,r,n,o,a,h,l]=this.vertices,u=t.dot(i,s),d=t.dot(r,n),c=t.dot(o,a),p=t.dot(h,l);return e.set(Math.min(u,d,c,p),Math.max(u,d,c,p))}contains(t,e){if(this.rotation%90==0)return this.getBounds().contains(t,e);const[i,s,r,n,o,a]=this.vertices,h=de.temp,l=h.set(r-i,n-s),u=l.dot(t-i,e-s),d=l.lengthSq,c=h.set(o-r,a-n),p=c.dot(t-r,e-n),_=c.lengthSq;return u>0&&u<=d&&p>0&&p<=_}destroy(){super.destroy(),this._textureFrame.destroy(),this._texture=null}}me.setInternalSpriteFactory(()=>new qe(null));class He{constructor(){this._totalLifetime=r.oneSecond.clone(),this._elapsedLifetime=r.zero.clone(),this._position=de.zero.clone(),this._velocity=de.zero.clone(),this._scale=de.one.clone(),this._rotation=0,this._rotationSpeed=0,this._textureIndex=0,this._tint=K.white.clone()}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get tint(){return this._tint}set tint(t){this._tint.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=U(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get remainingLifetime(){return r.temp.set(this._totalLifetime.milliseconds-this._elapsedLifetime.milliseconds)}get elapsedRatio(){return this._elapsedLifetime.milliseconds/this._totalLifetime.milliseconds}get remainingRatio(){return this.remainingLifetime.milliseconds/this._totalLifetime.milliseconds}get expired(){return this._elapsedLifetime.greaterThan(this._totalLifetime)}applyOptions(t){const{totalLifetime:e,elapsedLifetime:i,position:s,velocity:r,scale:n,tint:o,rotation:a,rotationSpeed:h,textureIndex:l}=t;return this._totalLifetime.copy(e),this._elapsedLifetime.copy(i),this._position.copy(s),this._velocity.copy(r),this._scale.copy(n),this._tint.copy(o),this._rotation=a,this._rotationSpeed=h,this._textureIndex=l,this}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class Xe extends ge{constructor(t){super(),this._emitters=[],this._affectors=[],this._particles=[],this._graveyard=[],this._textureFrame=new re,this._vertices=new Float32Array(4),this._texCoords=new Uint32Array(4),this._updateTexCoords=!0,this._updateVertices=!0,this._texture=t,this.resetTextureFrame()}get texture(){return this._texture}set texture(t){this.setTexture(t)}get textureFrame(){return this._textureFrame}set textureFrame(t){this.setTextureFrame(t)}get vertices(){if(this._updateVertices){const{x:t,y:e,width:i,height:s}=this._textureFrame,r=i/2,n=s/2;this._vertices[0]=t-r,this._vertices[1]=e-n,this._vertices[2]=i-r,this._vertices[3]=s-n,this._updateVertices=!1}return this._vertices}get texCoords(){if(this._updateTexCoords){const{width:t,height:e}=this._texture,{left:i,top:s,right:r,bottom:n}=this._textureFrame,o=i/t*65535&65535,a=(s/e*65535&65535)<<16,h=r/t*65535&65535,l=(n/e*65535&65535)<<16;this._texture.flipY?(this._texCoords[0]=l|o,this._texCoords[1]=l|h,this._texCoords[2]=a|h,this._texCoords[3]=a|o):(this._texCoords[0]=a|o,this._texCoords[1]=a|h,this._texCoords[2]=l|h,this._texCoords[3]=l|o),this._updateTexCoords=!1}return this._texCoords}get emitters(){return this._emitters}get affectors(){return this._affectors}get particles(){return this._particles}get graveyard(){return this._graveyard}setTexture(t){return this._texture!==t&&(this._texture=t,this.resetTextureFrame()),this}setTextureFrame(t){return this._textureFrame.copy(t),this._updateTexCoords=!0,this._updateVertices=!0,this.localBounds.set(0,0,t.width,t.height),this}resetTextureFrame(){return this.setTextureFrame(re.temp.set(0,0,this._texture.width,this._texture.height))}addEmitter(t){return this._emitters.push(t),this}clearEmitters(){for(const t of this._emitters)t.destroy();return this._emitters.length=0,this}addAffector(t){return this._affectors.push(t),this}clearAffectors(){for(const t of this._affectors)t.destroy();return this._affectors.length=0,this}requestParticle(){return this._graveyard.pop()||new He}emitParticle(t){return this._particles.push(t),this}updateParticle(t,e){const i=e.seconds;return t.elapsedLifetime.addTime(e),t.position.add(i*t.velocity.x,i*t.velocity.y),t.rotation+=i*t.rotationSpeed,this}clearParticles(){for(const t of this._particles)t.destroy();for(const t of this._graveyard)t.destroy();return this._particles.length=0,this._graveyard.length=0,this}update(t){const e=this._emitters,i=this._affectors,s=this._particles,r=this._graveyard,n=s.length;for(const i of e)i.apply(this,t);let o=0;for(let e=n-1;e>=0;e--)if(this.updateParticle(s[e],t),s[e].expired)r.push(s[e]),o++;else{o>0&&(s.splice(e+1,o),o=0);for(const r of i)r.apply(s[e],t)}return o>0&&s.splice(0,o),this}destroy(){super.destroy(),this.clearEmitters(),this.clearAffectors(),this.clearParticles(),this._textureFrame.destroy()}}class Ye{static get black(){return null===Ye._black&&(Ye._black=new Ye(Ne({fillStyle:"#000"}))),Ye._black}static get white(){return null===Ye._white&&(Ye._white=new Ye(Ne({fillStyle:"#fff"}))),Ye._white}constructor(t=null,i){this._version=0,this._source=null,this._size=new e(0,0),this._destroyListeners=new Set,this._premultiplyAlpha=!1,this._generateMipMap=!1,this._flipY=!1;const{scaleMode:s,wrapMode:r,premultiplyAlpha:n,generateMipMap:o,flipY:a}={...Ye.defaultSamplerOptions,...i};this._scaleMode=s,this._wrapMode=r,this._premultiplyAlpha=n,this._generateMipMap=o,this._flipY=a,null!==t&&this.setSource(t)}get source(){return this._source}set source(t){this.setSource(t)}get size(){return this._size}set size(t){this.setSize(t.width,t.height)}get width(){return this._size.width}set width(t){this.setSize(t,this.height)}get height(){return this._size.height}set height(t){this.setSize(this.width,t)}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}get premultiplyAlpha(){return this._premultiplyAlpha}set premultiplyAlpha(t){this.setPremultiplyAlpha(t)}get generateMipMap(){return this._generateMipMap}set generateMipMap(t){this._generateMipMap=t}get flipY(){return this._flipY}set flipY(t){this._flipY=t}get powerOfTwo(){return q(this.width)&&q(this.height)}get version(){return this._version}addDestroyListener(t){return this._destroyListeners.add(t),this}removeDestroyListener(t){return this._destroyListeners.delete(t),this}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this._touch()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this._touch()),this}setPremultiplyAlpha(t){return this._premultiplyAlpha!==t&&(this._premultiplyAlpha=t,this._touch()),this}setSource(t){return this._source!==t&&(this._source=t,this.updateSource()),this}updateSource(){const{width:t,height:e}=A(this._source);return this.setSize(t,e),this._touch(),this}setSize(t,e){return this._size.equals({width:t,height:e})||(this._size.set(t,e),this._touch()),this}destroy(){for(const t of Array.from(this._destroyListeners))t();this._destroyListeners.clear(),this._size.destroy(),this._source=null}_touch(){this._version++}}Ye._black=null,Ye._white=null,Ye.defaultSamplerOptions={scaleMode:Z.Linear,wrapMode:J.ClampToEdge,premultiplyAlpha:!0,generateMipMap:!0,flipY:!1},Ye.empty=new Ye(null);class je{constructor(){this._renderers=new Map,this._runtime=null}registerRenderer(t,e){if(this._renderers.has(t))throw new Error(`A renderer is already registered for ${t.name}.`);this._renderers.set(t,e),null!==this._runtime&&e.connect(this._runtime)}resolve(t){let e,i=t.constructor;for(;null!==i&&!e;)if(e=this._renderers.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No renderer registered for ${t.constructor.name}. Register one with registry.registerRenderer() before the first draw call.`);return e}connect(t){this._runtime=t;for(const e of this._renderers.values())e.connect(t)}disconnect(){for(const t of this._renderers.values())t.disconnect();this._runtime=null}destroy(){this.disconnect();for(const t of this._renderers.values())"destroy"in t&&"function"==typeof t.destroy&&t.destroy();this._renderers.clear()}}const $e=()=>({frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0}),Ke=t=>(t.frame++,t.submittedNodes=0,t.culledNodes=0,t.drawCalls=0,t.batches=0,t.renderPasses=0,t.renderTargetChanges=0,t.frameTimeMs=0,t),Qe=(t,e)=>{throw`${be.glEnumToString(t)} was caused by call to: ${e}`},Ze=(t,e)=>{((t,e)=>{console.log(`gl.${t}(${be.glFunctionArgsToString(t,e)})`)})(t,e),((t,e)=>{for(const i of e)void 0===i&&console.error(`undefined passed to gl.${t}(${be.glFunctionArgsToString(t,e)})`)})(t,e)};class Je{constructor(t){this.backendType=Se.WebGl2,this.rendererRegistry=new je,this._textureStates=new Map,this._renderTargetStates=new Map,this._textureDestroyHandlers=new Map,this._renderTargetDestroyHandlers=new Map,this._temporaryRenderTextures=[],this._maskStack=[],this._maskPixelStack=[],this._maskPointA=new de,this._maskPointB=new de,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._textureUnit=0,this._vao=null,this._clearColor=new K,this._boundFramebuffer=null,this._stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};const{width:e,height:i,clearColor:s,webglAttributes:r,debug:n,spriteRendererBatchSize:o,particleRendererBatchSize:a,primitiveRendererBatchSize:h}=t.options;this._canvas=t.canvas;const l=this._createContext(r);if(!l)throw new Error("This browser or hardware does not support WebGL.");this._context=n?be.makeDebugContext(l,Qe,Ze,l):l,this._contextLost=this._context.isContextLost(),this._contextLost&&this._restoreContext(),s&&this.clearColor.copy(s),this._rootRenderTarget=new ce(e,i,!0),this._renderTarget=this._rootRenderTarget,this._cursor=this._canvas.style.cursor,this._onContextLostHandler=this._onContextLost.bind(this),this._onContextRestoredHandler=this._onContextRestored.bind(this),this._setupContext(),this._addEvents(),this.rendererRegistry.registerRenderer(qe,new Oe(o)),this.rendererRegistry.registerRenderer(Xe,new Ge(a)),this.rendererRegistry.registerRenderer(ye,new ze(h)),this.rendererRegistry.connect(this),this._bindRenderTarget(this._renderTarget),this.setBlendMode(Q.Normal),this.resize(e,i)}get context(){return this._context}get renderTarget(){return this._renderTarget}get view(){return this._renderTarget.view}get clearColor(){return this._clearColor}get cursor(){return this._cursor}get stats(){return this._stats}async initialize(){return this}resetStats(){return Ke(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setRenderTarget(t){const e=t||this._rootRenderTarget;return this._renderTarget!==e&&(this._renderTarget=e,this._stats.renderTargetChanges++),this._bindRenderTarget(e),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,s=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(s),this._applyMaskState(),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this._applyMaskState(),this}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const s=this._temporaryRenderTextures[i];if(s.width===t&&s.height===e)return this._temporaryRenderTextures.splice(i,1),s}return new pe(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this._bindRenderTarget(this._renderTarget),this}bindVertexArrayObject(t){return this._vao!==t&&(t&&t.bind(),this._vao&&this._vao.unbind(),this._vao=t),this}bindShader(t){return this._shader!==t&&(this._shader&&(this._shader.unbind(),this._shader=null),t&&t.bind(),this._shader=t),this}bindTexture(t,e){if(void 0!==e&&this._setTextureUnit(e),null===t)return null!==this._texture&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this;const i=this._syncTexture(t);return this._context.bindTexture(this._context.TEXTURE_2D,i.handle),this._texture=t,this}setBlendMode(t){if(t!==this._blendMode){const e=this._context;switch(this._blendMode=t,t){case Q.Additive:e.blendFunc(e.ONE,e.ONE);break;case Q.Subtract:e.blendFunc(e.ZERO,e.ONE_MINUS_SRC_COLOR);break;case Q.Multiply:e.blendFunc(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA);break;case Q.Screen:e.blendFunc(e.ONE,e.ONE_MINUS_SRC_COLOR);break;default:e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA)}}return this}_setTextureUnit(t){if(this._textureUnit!==t){const e=this._context;this._textureUnit=t,e.activeTexture(e.TEXTURE0+t)}}setClearColor(t){if(!this._clearColor.equals(t)){const e=this._context;this._clearColor.copy(t),e.clearColor(t.r/255,t.g/255,t.b/255,t.a)}return this}setCursor(t){const e=t instanceof Ye?t.source:t;if(null===e)throw new Error("Provided Texture has no source.");return this._cursor="string"==typeof e?e:`url(${k(e)})`,this._canvas.style.cursor=this._cursor,this}clear(t){const e=this._context;return t&&this.setClearColor(t),this._bindRenderTarget(this._renderTarget),e.clear(e.COLOR_BUFFER_BIT),this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._bindRenderTarget(this._renderTarget),this}flush(){return this._flushActiveRenderer(),this}destroy(){this._removeEvents(),this.setRenderTarget(null),this._setActiveRenderer(null),this.bindVertexArrayObject(null),this.bindShader(null),this.bindTexture(null),this.rendererRegistry.destroy(),this._clearColor.destroy(),this._destroyManagedResources(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy(),this._rootRenderTarget.destroy(),this._vao=null,this._renderer=null,this._shader=null,this._blendMode=null,this._texture=null,this._boundFramebuffer=null}_createContext(t){try{return this._canvas.getContext("webgl2",t)}catch(t){return null}}_restoreContext(){this._context.getExtension("WEBGL_lose_context")?.restoreContext()}_setupContext(){const t=this._context,{r:e,g:i,b:s,a:r}=this._clearColor;t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.clearColor(e/255,i/255,s/255,r)}_addEvents(){this._canvas.addEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.addEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_removeEvents(){this._canvas.removeEventListener("webglcontextlost",this._onContextLostHandler,!1),this._canvas.removeEventListener("webglcontextrestored",this._onContextRestoredHandler,!1)}_onContextLost(){this._contextLost=!0,this._restoreContext()}_onContextRestored(){this._contextLost=!1}_createFramebuffer(){const t=this._context.createFramebuffer();if(null===t)throw new Error("Could not create framebuffer.");return t}_createTextureHandle(){const t=this._context.createTexture();if(null===t)throw new Error("Could not create texture.");return t}_destroyManagedResources(){for(const t of Array.from(this._renderTargetStates.keys()))this._evictRenderTarget(t,!1);for(const t of Array.from(this._textureStates.keys()))this._evictTexture(t,!1)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getRenderTargetState(t){let e=this._renderTargetStates.get(t);return e||(this._subscribeToDestroy(t,this._renderTargetDestroyHandlers,()=>{this._evictRenderTarget(t,!0)}),e={framebuffer:t.root?null:this._createFramebuffer(),version:-1,attachedTexture:null},this._renderTargetStates.set(t,e)),e}_getTextureState(t){let e=this._textureStates.get(t);return e||(this._subscribeToDestroy(t,this._textureDestroyHandlers,()=>{this._evictTexture(t,!0)}),e={handle:this._createTextureHandle(),version:-1,width:0,height:0},this._textureStates.set(t,e)),e}_subscribeToDestroy(t,e,i){e.has(t)||(t.addDestroyListener(i),e.set(t,i))}_unsubscribeFromDestroy(t,e){const i=e.get(t);i&&(t.removeDestroyListener(i),e.delete(t))}_evictRenderTarget(t,e){const i=this._renderTargetStates.get(t);this._unsubscribeFromDestroy(t,this._renderTargetDestroyHandlers),t instanceof pe&&this._evictTexture(t,!1),i&&(this._boundFramebuffer===i.framebuffer&&(this._context.bindFramebuffer(this._context.FRAMEBUFFER,null),this._boundFramebuffer=null),null!==i.framebuffer&&this._context.deleteFramebuffer(i.framebuffer),this._renderTargetStates.delete(t)),this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget,e&&this._bindRenderTarget(this._rootRenderTarget))}_evictTexture(t,e){const i=this._textureStates.get(t);this._unsubscribeFromDestroy(t,this._textureDestroyHandlers),i&&(this._texture===t&&(this._context.bindTexture(this._context.TEXTURE_2D,null),this._texture=null),this._context.deleteTexture(i.handle),this._textureStates.delete(t)),this._texture===t&&(this._texture=null),e&&null!==this._texture&&this.bindTexture(this._texture)}_bindRenderTarget(t){const e=this._prepareRenderTarget(t);if(this._boundFramebuffer!==e.framebuffer||e.version!==t.version){const i=this._context,{x:s,y:r,width:n,height:o}=t.getViewport();i.bindFramebuffer(i.FRAMEBUFFER,e.framebuffer),i.viewport(s,r,n,o),this._boundFramebuffer=e.framebuffer,e.version=t.version}this._maskPixelStack.length>0&&this._applyMaskState()}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer&&!this._contextLost&&(this._bindRenderTarget(this._renderTarget),this._renderer.flush())}_prepareRenderTarget(t){const e=this._getRenderTargetState(t);if(t instanceof pe&&e.framebuffer){const i=this._boundFramebuffer,s=this._syncTexture(t);if(e.attachedTexture!==s.handle){const t=this._context;t.bindFramebuffer(t.FRAMEBUFFER,e.framebuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s.handle,0),t.bindFramebuffer(t.FRAMEBUFFER,i),e.attachedTexture=s.handle}}return e}_syncTexture(t){const e=this._context,i=this._getTextureState(t),s=t instanceof pe?t.textureVersion:t.version;return e.bindTexture(e.TEXTURE_2D,i.handle),i.version!==s&&(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t.wrapMode),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t.wrapMode),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),t instanceof pe?-1===i.version||i.width!==t.width||i.height!==t.height||null===t.source?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.width,t.height,0,e.RGBA,e.UNSIGNED_BYTE,t.source):e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.width,t.height,e.RGBA,e.UNSIGNED_BYTE,t.source):t.source&&(-1===i.version||i.width!==t.width||i.height!==t.height?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source):e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,t.source)),t.generateMipMap&&(t instanceof pe||null!==t.source)&&e.generateMipmap(e.TEXTURE_2D),i.version=s,i.width=t.width,i.height=t.height),i}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),s=Math.min(e.x,i.x),r=Math.max(e.x,i.x),n=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(s))),u=Math.max(0,Math.min(a,Math.ceil(r))),d=Math.max(0,Math.min(h,Math.floor(n))),c=Math.max(0,Math.min(h,Math.ceil(o))),p=Math.max(0,u-l),_=Math.max(0,c-d);return{x:l,y:Math.max(0,h-c),width:p,height:_}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),s=Math.max(t.y,e.y),r=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:s,width:Math.max(0,r-i),height:Math.max(0,n-s)}}_applyMaskState(){const t=this._context;if(0===this._maskPixelStack.length)return void t.disable(t.SCISSOR_TEST);const e=this._maskPixelStack[this._maskPixelStack.length-1];t.enable(t.SCISSOR_TEST),t.scissor(e.x,e.y,e.width,e.height)}}class ti{constructor(){this.backendType=Se.WebGpu,this._runtime=null}connect(t){if(null===this._runtime){if(t.backendType!==Se.WebGpu)throw new Error(`${this.constructor.name} requires a WebGPU runtime, but received backendType ${String(t.backendType)}.`);this._runtime=t,this.onConnect(t)}}disconnect(){null!==this._runtime&&(this.flush(),this.onDisconnect(),this._runtime=null)}getRuntime(){if(null===this._runtime)throw new Error(`${this.constructor.name} is not connected to a runtime.`);return this._runtime}getRuntimeOrNull(){return this._runtime}}function ei(t){switch(t){case Q.Additive:return{color:{operation:"add",srcFactor:"one",dstFactor:"one"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one"}};case Q.Subtract:return{color:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"zero",dstFactor:"one-minus-src-alpha"}};case Q.Multiply:return{color:{operation:"add",srcFactor:"dst",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"dst-alpha",dstFactor:"one-minus-src-alpha"}};case Q.Screen:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}};default:return{color:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"},alpha:{operation:"add",srcFactor:"one",dstFactor:"one-minus-src-alpha"}}}}const ii=20,si=ii/Uint32Array.BYTES_PER_ELEMENT;class ri extends ti{constructor(){super(...arguments),this._combinedTransform=new at,this._drawCalls=[],this._drawCallCount=0,this._pipelines=new Map,this._renderManager=null,this._device=null,this._shaderModule=null,this._pipelineLayout=null,this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._packedIndexData=new Uint16Array(0),this._generatedIndexData=new Uint16Array(0),this._sequentialIndexData=new Uint16Array(0)}render(t){const e=this._renderManager;if(null===e)throw new Error("Renderer not connected");if(t.drawMode!==tt.Points&&t.drawMode!==tt.Lines&&t.drawMode!==tt.LineLoop&&t.drawMode!==tt.LineStrip&&t.drawMode!==tt.Triangles&&t.drawMode!==tt.TriangleFan&&t.drawMode!==tt.TriangleStrip)throw new Error(`WebGPU primitive renderer does not support draw mode "${t.drawMode}" yet.`);if(e.setBlendMode(t.blendMode),0===t.geometry.vertices.length)return;const i=this._drawCallCount++,s=this._drawCalls[i];s?(s.shape=t,s.blendMode=t.blendMode):this._drawCalls.push({shape:t,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device;if(!t||!e)return;if(0===this._drawCallCount&&!t.clearRequested)return;const i=t.getScissorRect(),s=null!==i&&(i.width<=0||i.height<=0),r=[],n=[];let o=0,a=0;if(this._drawCallCount>0&&!s)for(let e=0;e<this._drawCallCount;e++){const i=this._drawCalls[e],s=i.shape,h=this._resolveDrawCall(s);if(n.push(h),null===h)continue;const l=this._getPipeline({topology:h.topology,usesStripIndex:h.usesStripIndex,blendMode:i.blendMode,format:t.renderTargetFormat});r.push({pipeline:l,vertexByteOffset:o*ii,vertexCount:h.vertexCount,indexByteOffset:a*Uint16Array.BYTES_PER_ELEMENT,indexCount:h.indexCount}),o+=h.vertexCount,a+=h.indexCount}if(0===r.length){if(t.clearRequested){const i=e.createCommandEncoder(),s=i.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,s.end(),t.submit(i.finish())}return void(this._drawCallCount=0)}this._ensureVertexCapacity(o),a>0&&(this._ensureIndexCapacity(a),this._packedIndexData.length<a&&(this._packedIndexData=new Uint16Array(Math.max(a,0===this._packedIndexData.length?1:2*this._packedIndexData.length))));{let e=0,i=0;for(let s=0;s<this._drawCallCount;s++){const r=n[s];if(null===r)continue;const o=this._drawCalls[s].shape;this._writeShapeVertices(t,o,e),null!==r.indices&&r.indexCount>0&&(this._packedIndexData.set(r.indices.subarray(0,r.indexCount),i),i+=r.indexCount),e+=r.vertexCount}}e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,o*ii),a>0&&e.queue.writeBuffer(this._indexBuffer,0,this._packedIndexData.buffer,this._packedIndexData.byteOffset,a*Uint16Array.BYTES_PER_ELEMENT);const h=e.createCommandEncoder(),l=h.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,null!==i&&l.setScissorRect(i.x,i.y,i.width,i.height);for(const e of r)l.setPipeline(e.pipeline),l.setVertexBuffer(0,this._vertexBuffer,e.vertexByteOffset),e.indexCount>0?(l.setIndexBuffer(this._indexBuffer,"uint16",e.indexByteOffset),l.drawIndexed(e.indexCount)):l.draw(e.vertexCount),t.stats.batches++,t.stats.drawCalls++;l.end(),t.submit(h.finish()),this._drawCallCount=0}destroy(){this.disconnect(),this._combinedTransform.destroy()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct VertexInput {\n @location(0) position: vec4<f32>,\n @location(1) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = input.position;\n output.color = vec4<f32>(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return input.color;\n}\n"}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[]})}onDisconnect(){this.flush(),this._destroyBuffers(),this._pipelines.clear(),this._pipelineLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._drawCallCount=0}_writeShapeVertices(t,e,i){const s=this._combinedTransform.copy(e.getGlobalTransform()).combine(t.view.getTransform()),r=s.a,n=s.b,o=s.c,a=s.d,h=s.x,l=s.y,u=s.z,d=e.color.toRgba(),c=e.geometry.vertices,p=c.length/2;for(let t=0;t<p;t++){const e=2*t,s=(i+t)*si,p=c[e],_=c[e+1];this._float32View[s+0]=r*p+n*_+h,this._float32View[s+1]=o*p+a*_+l,this._float32View[s+2]=0,this._float32View[s+3]=u,this._uint32View[s+4]=d}}_ensureVertexCapacity(t){const e=t*ii;if(e>this._vertexData.byteLength){const t=Math.max(e,0===this._vertexData.byteLength?ii:2*this._vertexData.byteLength);this._vertexData=new ArrayBuffer(t),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData)}e>this._vertexBufferCapacity&&(this._vertexBuffer?.destroy(),this._vertexBufferCapacity=Math.max(e,0===this._vertexBufferCapacity?ii:2*this._vertexBufferCapacity),this._vertexBuffer=this._device.createBuffer({size:this._vertexBufferCapacity,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}))}_ensureIndexCapacity(t){const e=t*Uint16Array.BYTES_PER_ELEMENT;e>this._indexBufferCapacity&&(this._indexBuffer?.destroy(),this._indexBufferCapacity=Math.max(e,0===this._indexBufferCapacity?Uint16Array.BYTES_PER_ELEMENT:2*this._indexBufferCapacity),this._indexBuffer=this._device.createBuffer({size:this._indexBufferCapacity,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}))}_getPipeline(t){const e=`${t.topology}:${t.usesStripIndex?1:0}:${t.blendMode}:${t.format}`,i=this._pipelines.get(e);if(i)return i;const s=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:ii,attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:1,offset:16,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:t.format,blend:ei(t.blendMode),writeMask:GPUColorWrite.ALL}]},primitive:{topology:t.topology,stripIndexFormat:t.usesStripIndex?"uint16":void 0}});return this._pipelines.set(e,s),s}_getTopology(t){switch(t){case tt.Points:return"point-list";case tt.Lines:return"line-list";case tt.LineLoop:case tt.LineStrip:return"line-strip";case tt.Triangles:case tt.TriangleFan:return"triangle-list";case tt.TriangleStrip:return"triangle-strip";default:throw new Error(`WebGPU primitive renderer does not support draw mode "${t}" yet.`)}}_resolveDrawCall(t){const e=t.geometry.vertices.length/2;if(0===e)return null;switch(t.drawMode){case tt.LineLoop:return this._resolveLineLoopDrawCall(t.geometry.indices,e);case tt.TriangleFan:return this._resolveTriangleFanDrawCall(t.geometry.indices,e);default:{const i=t.geometry.indices,s=this._getTopology(t.drawMode),r=i.length,n=r>0&&(t.drawMode===tt.LineStrip||t.drawMode===tt.TriangleStrip);return r>0?{topology:s,usesStripIndex:n,vertexCount:e,indices:i,indexCount:r}:{topology:s,usesStripIndex:n,vertexCount:e,indices:null,indexCount:0}}}}_resolveLineLoopDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),s=i.length;if(s<2)return null;const r=s+1,n=this._ensureGeneratedIndexCapacity(r);return n.set(i.subarray(0,s),0),n[s]=i[0],{topology:"line-strip",usesStripIndex:!0,vertexCount:e,indices:n,indexCount:r}}_resolveTriangleFanDrawCall(t,e){const i=t.length>0?t:this._getSequentialIndices(e),s=i.length;if(s<3)return null;const r=3*(s-2),n=this._ensureGeneratedIndexCapacity(r);let o=0;for(let t=1;t<s-1;t++)n[o++]=i[0],n[o++]=i[t],n[o++]=i[t+1];return{topology:"triangle-list",usesStripIndex:!1,vertexCount:e,indices:n,indexCount:r}}_getSequentialIndices(t){if(t>this._sequentialIndexData.length){let e=Math.max(1,this._sequentialIndexData.length);for(;e<t;)e*=2;this._sequentialIndexData=new Uint16Array(e)}for(let e=0;e<t;e++)this._sequentialIndexData[e]=e;return this._sequentialIndexData.subarray(0,t)}_ensureGeneratedIndexCapacity(t){if(t>this._generatedIndexData.length){let e=Math.max(1,this._generatedIndexData.length);for(;e<t;)e*=2;this._generatedIndexData=new Uint16Array(e)}return this._generatedIndexData.subarray(0,t)}_destroyBuffers(){this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexBuffer=null,this._indexBuffer=null,this._vertexBufferCapacity=0,this._indexBufferCapacity=0}}const ni=28/Uint32Array.BYTES_PER_ELEMENT;class oi extends ti{constructor(){super(...arguments),this._drawCalls=[],this._drawCallCount=0,this._projectionData=new Float32Array(64/Float32Array.BYTES_PER_ELEMENT),this._renderManager=null,this._device=null,this._shaderModule=null,this._uniformBindGroupLayout=null,this._textureBindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._vertexBuffer=null,this._indexBuffer=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._pipelines=new Map}onConnect(t){this._renderManager||(this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n matrix: mat4x4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> projection: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar spriteTexture0: texture_2d<f32>;\n@group(1) @binding(1)\nvar spriteTexture1: texture_2d<f32>;\n@group(1) @binding(2)\nvar spriteTexture2: texture_2d<f32>;\n@group(1) @binding(3)\nvar spriteTexture3: texture_2d<f32>;\n@group(1) @binding(4)\nvar spriteTexture4: texture_2d<f32>;\n@group(1) @binding(5)\nvar spriteTexture5: texture_2d<f32>;\n@group(1) @binding(6)\nvar spriteTexture6: texture_2d<f32>;\n@group(1) @binding(7)\nvar spriteTexture7: texture_2d<f32>;\n\n@group(1) @binding(8)\nvar spriteSampler0: sampler;\n@group(1) @binding(9)\nvar spriteSampler1: sampler;\n@group(1) @binding(10)\nvar spriteSampler2: sampler;\n@group(1) @binding(11)\nvar spriteSampler3: sampler;\n@group(1) @binding(12)\nvar spriteSampler4: sampler;\n@group(1) @binding(13)\nvar spriteSampler5: sampler;\n@group(1) @binding(14)\nvar spriteSampler6: sampler;\n@group(1) @binding(15)\nvar spriteSampler7: sampler;\n\nstruct VertexInput {\n @location(0) position: vec2<f32>,\n @location(1) texcoord: vec2<f32>,\n @location(2) color: vec4<f32>,\n @location(3) premultiplySample: u32,\n @location(4) textureSlot: u32,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n @location(2) @interpolate(flat) premultiplySample: u32,\n @location(3) @interpolate(flat) textureSlot: u32,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n var output: VertexOutput;\n\n output.position = projection.matrix * vec4<f32>(input.position, 0.0, 1.0);\n output.texcoord = input.texcoord;\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n output.premultiplySample = input.premultiplySample;\n output.textureSlot = input.textureSlot;\n\n return output;\n}\n\nfn sampleTexture(slot: u32, uv: vec2<f32>, ddx: vec2<f32>, ddy: vec2<f32>) -> vec4<f32> {\n switch slot {\n case 0u: {\n return textureSampleGrad(spriteTexture0, spriteSampler0, uv, ddx, ddy);\n }\n case 1u: {\n return textureSampleGrad(spriteTexture1, spriteSampler1, uv, ddx, ddy);\n }\n case 2u: {\n return textureSampleGrad(spriteTexture2, spriteSampler2, uv, ddx, ddy);\n }\n case 3u: {\n return textureSampleGrad(spriteTexture3, spriteSampler3, uv, ddx, ddy);\n }\n case 4u: {\n return textureSampleGrad(spriteTexture4, spriteSampler4, uv, ddx, ddy);\n }\n case 5u: {\n return textureSampleGrad(spriteTexture5, spriteSampler5, uv, ddx, ddy);\n }\n case 6u: {\n return textureSampleGrad(spriteTexture6, spriteSampler6, uv, ddx, ddy);\n }\n default: {\n return textureSampleGrad(spriteTexture7, spriteSampler7, uv, ddx, ddy);\n }\n }\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n // Compute screen-space derivatives in uniform control flow before the\n // per-slot switch. WGSL requires textureSample (implicit LOD) to run in\n // uniform control flow, which multi-texture batching breaks because the\n // slot varies per fragment. textureSampleGrad takes explicit derivatives\n // and is valid regardless of control-flow uniformity, while preserving\n // mipmap-correct LOD when sprites use mipmapped textures.\n let ddx = dpdx(input.texcoord);\n let ddy = dpdy(input.texcoord);\n let sample = sampleTexture(input.textureSlot, input.texcoord, ddx, ddy);\n let resolvedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), input.premultiplySample == 1u);\n\n return resolvedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[...Array.from({length:8},(t,e)=>({binding:e,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}})),...Array.from({length:8},(t,e)=>({binding:8+e,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}))]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._ensureBatchCapacity(32))}onDisconnect(){this.flush(),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._vertexBuffer=null,this._indexBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._vertexCapacity=0,this._vertexData=new ArrayBuffer(0),this._float32View=new Float32Array(this._vertexData),this._uint32View=new Uint32Array(this._vertexData),this._drawCallCount=0}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof Ye)&&!(i instanceof pe)||0===i.width||0===i.height||i instanceof Ye&&null===i.source)return;e.setBlendMode(t.blendMode);const s=this._drawCallCount++,r=this._drawCalls[s];r?(r.sprite=t,r.texture=i,r.color=t.tint.toRgba(),r.blendMode=t.blendMode):this._drawCalls.push({sprite:t,texture:i,color:t.tint.toRgba(),blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,s=this._uniformBindGroup,r=this._vertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&s&&r&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;this._drawCallCount>0&&this._ensureBatchCapacity(this._drawCallCount);const o=[];let a=0;for(let t=0;t<this._drawCallCount;){const e=this._getBatchRange(t),i=e.end-e.start;this._writeBatchVertexData(e,a),o.push({firstSprite:a,spriteCount:i,blendMode:e.blendMode,textures:e.textures}),a+=i,t=e.end}const h=t.view.getTransform();this._projectionData.set([h.a,h.c,0,0,h.b,h.d,0,0,0,0,1,0,h.x,h.y,0,h.z]),e.queue.writeBuffer(i,0,this._projectionData.buffer,this._projectionData.byteOffset,this._projectionData.byteLength);const l=e.createCommandEncoder(),u=l.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++;const d=t.getScissorRect(),c=null!==d&&(d.width<=0||d.height<=0);if(null===d||c||u.setScissorRect(d.x,d.y,d.width,d.height),this._drawCallCount>0&&!c){e.queue.writeBuffer(this._vertexBuffer,0,this._vertexData,0,4*a*28),u.setBindGroup(0,s),u.setVertexBuffer(0,this._vertexBuffer),u.setIndexBuffer(this._indexBuffer,"uint32");for(const i of o){const s=this._getPipeline(i.blendMode,t.renderTargetFormat),r=this._createTextureBindGroup(e,t,i.textures);u.setPipeline(s),u.setBindGroup(1,r),u.drawIndexed(6*i.spriteCount,1,6*i.firstSprite,0,0),t.stats.batches++,t.stats.drawCalls++}}u.end(),t.submit(l.finish()),this._drawCallCount=0}destroy(){this.disconnect()}_ensureBatchCapacity(t){if(!this._device||t<=this._vertexCapacity)return;let e=Math.max(this._vertexCapacity,32);for(;e<t;)e*=2;const i=new ArrayBuffer(4*e*28),s=this._device.createBuffer({size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),r=new Uint32Array(6*e),n=this._device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});for(let t=0;t<e;t++){const e=4*t,i=6*t;r[i]=e,r[i+1]=e+1,r[i+2]=e+2,r[i+3]=e,r[i+4]=e+2,r[i+5]=e+3}this._device.queue.writeBuffer(n,0,r.buffer,r.byteOffset,r.byteLength),this._vertexBuffer?.destroy(),this._indexBuffer?.destroy(),this._vertexCapacity=e,this._vertexData=i,this._float32View=new Float32Array(i),this._uint32View=new Uint32Array(i),this._vertexBuffer=s,this._indexBuffer=n}_writeBatchVertexData(t,e){const i=this._renderManager;if(!i)return;let s=4*e*ni;for(let e=t.start;e<t.end;e++){const r=this._drawCalls[e],n=t.textureSlots.get(r.texture)??0,o=i.shouldPremultiplyTextureSample(r.texture)?1:0,a=r.sprite.vertices,h=r.sprite.texCoords;for(let t=0;t<4;t++){const e=2*t,i=h[t];this._float32View[s]=a[e],this._float32View[s+1]=a[e+1],this._float32View[s+2]=(65535&i)/65535,this._float32View[s+3]=(i>>>16&65535)/65535,this._uint32View[s+4]=r.color,this._uint32View[s+5]=o,this._uint32View[s+6]=n,s+=ni}}}_getBatchRange(t){const e=this._drawCalls[t],i=new Map,s=new Array;let r=t+1;for(i.set(e.texture,0),s.push(e.texture);r<this._drawCallCount;){const t=this._drawCalls[r];if(t.blendMode!==e.blendMode)break;if(!i.has(t.texture)){if(s.length>=8)break;i.set(t.texture,s.length),s.push(t.texture)}if(i.size>8)break;r++}return{start:t,end:r,spriteCount:r-t,blendMode:e.blendMode,textures:s,textureSlots:i}}_createTextureBindGroup(t,e,i){const s=i[0],r=e.getTextureBinding(s),n=[],o=new Array(8);for(let t=0;t<8;t++){const n=i[t]??s,a=n===s?r:e.getTextureBinding(n);o[t]=a}for(let t=0;t<8;t++)n.push({binding:t,resource:o[t].view});for(let t=0;t<8;t++)n.push({binding:8+t,resource:o[t].sampler});return t.createBindGroup({layout:this._textureBindGroupLayout,entries:n})}_getPipeline(t,e){const i=`${t}:${e}`,s=this._pipelines.get(i);if(s)return s;if(!(this._device&&this._shaderModule&&this._pipelineLayout&&this._renderManager))throw new Error("Renderer has to be connected first!");const r=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:28,attributes:[{shaderLocation:0,offset:0,format:"float32x2"},{shaderLocation:1,offset:8,format:"float32x2"},{shaderLocation:2,offset:16,format:"unorm8x4"},{shaderLocation:3,offset:20,format:"uint32"},{shaderLocation:4,offset:24,format:"uint32"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:ei(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,r),r}}const ai=56,hi=new Float32Array([0,0,1,0,1,1,0,1]),li=new Uint16Array([0,1,2,0,2,3]);class ui extends ti{constructor(){super(...arguments),this._drawCalls=[],this._drawCallCount=0,this._uniformData=new Float32Array(144/Float32Array.BYTES_PER_ELEMENT),this._renderManager=null,this._device=null,this._shaderModule=null,this._uniformBindGroupLayout=null,this._textureBindGroupLayout=null,this._pipelineLayout=null,this._uniformBuffer=null,this._uniformBindGroup=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._indexBuffer=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._pipelines=new Map}render(t){const e=this._renderManager,i=t.texture;if(null===e||!(i instanceof Ye)||null===i.source||0===i.width||0===i.height||0===t.particles.length)return;e.setBlendMode(t.blendMode);const s=this._drawCallCount++,r=this._drawCalls[s];r?(r.system=t,r.texture=i,r.blendMode=t.blendMode):this._drawCalls.push({system:t,texture:i,blendMode:t.blendMode})}flush(){const t=this._renderManager,e=this._device,i=this._uniformBuffer,s=this._uniformBindGroup,r=this._staticVertexBuffer,n=this._indexBuffer;if(!(t&&e&&i&&s&&r&&this._instanceBuffer&&n))return;if(0===this._drawCallCount&&!t.clearRequested)return;const o=t.getScissorRect(),a=null!==o&&(o.width<=0||o.height<=0);if(0===this._drawCallCount||a){if(t.clearRequested){const i=e.createCommandEncoder(),s=i.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,s.end(),t.submit(i.finish())}this._drawCallCount=0}else{for(let a=0;a<this._drawCallCount;a++){const h=this._drawCalls[a],l=h.system,u=l.particles.length;if(0===u)continue;const d=this._getPipeline(h.blendMode,t.renderTargetFormat),c=t.getTextureBinding(h.texture),p=e.createBindGroup({layout:this._textureBindGroupLayout,entries:[{binding:0,resource:c.view},{binding:1,resource:c.sampler}]});this._ensureCapacity(u),this._writeInstanceData(l.vertices,l.texCoords,l.particles),this._writeUniformData(t,l,h.texture),e.queue.writeBuffer(this._instanceBuffer,0,this._instanceData,0,u*ai),e.queue.writeBuffer(i,0,this._uniformData.buffer,this._uniformData.byteOffset,this._uniformData.byteLength);const _=e.createCommandEncoder(),f=_.beginRenderPass({colorAttachments:[t.createColorAttachment()]});t.stats.renderPasses++,null!==o&&f.setScissorRect(o.x,o.y,o.width,o.height),f.setBindGroup(0,s),f.setPipeline(d),f.setBindGroup(1,p),f.setVertexBuffer(0,r),f.setVertexBuffer(1,this._instanceBuffer),f.setIndexBuffer(n,"uint16"),f.drawIndexed(6,u,0,0,0),t.stats.batches++,t.stats.drawCalls++,f.end(),t.submit(_.finish())}this._drawCallCount=0}}destroy(){this.disconnect()}onConnect(t){this._renderManager=t,this._device=this._renderManager.device,this._shaderModule=this._device.createShaderModule({code:"\nstruct ProjectionUniforms {\n projection: mat4x4<f32>,\n translation: mat4x4<f32>,\n flags: vec4<f32>,\n};\n\n@group(0) @binding(0)\nvar<uniform> uniforms: ProjectionUniforms;\n\n@group(1) @binding(0)\nvar particleTexture: texture_2d<f32>;\n\n@group(1) @binding(1)\nvar particleSampler: sampler;\n\nstruct VertexInput {\n @location(0) unitPosition: vec2<f32>,\n @location(1) quadMin: vec2<f32>,\n @location(2) quadSize: vec2<f32>,\n @location(3) uvMin: vec2<f32>,\n @location(4) uvMax: vec2<f32>,\n @location(5) translation: vec2<f32>,\n @location(6) scale: vec2<f32>,\n @location(7) rotation: f32,\n @location(8) color: vec4<f32>,\n};\n\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n @location(1) color: vec4<f32>,\n};\n\n@vertex\nfn vertexMain(input: VertexInput) -> VertexOutput {\n let localPosition = input.quadMin + (input.unitPosition * input.quadSize);\n let radians = radians(input.rotation);\n let sinValue = sin(radians);\n let cosValue = cos(radians);\n let rotated = vec2<f32>(\n (localPosition.x * (input.scale.x * cosValue)) + (localPosition.y * (input.scale.y * sinValue)) + input.translation.x,\n (localPosition.x * (input.scale.x * -sinValue)) + (localPosition.y * (input.scale.y * cosValue)) + input.translation.y\n );\n\n var output: VertexOutput;\n\n output.position = uniforms.projection * uniforms.translation * vec4<f32>(rotated, 0.0, 1.0);\n output.texcoord = input.uvMin + ((input.uvMax - input.uvMin) * input.unitPosition);\n output.color = vec4(input.color.rgb * input.color.a, input.color.a);\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n let sample = textureSample(particleTexture, particleSampler, input.texcoord);\n let premultipliedSample = select(sample, vec4(sample.rgb * sample.a, sample.a), uniforms.flags.x > 0.5);\n\n return premultipliedSample * input.color;\n}\n"}),this._uniformBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.VERTEX|GPUShaderStage.FRAGMENT,buffer:{type:"uniform"}}]}),this._textureBindGroupLayout=this._device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._pipelineLayout=this._device.createPipelineLayout({bindGroupLayouts:[this._uniformBindGroupLayout,this._textureBindGroupLayout]}),this._uniformBuffer=this._device.createBuffer({size:144,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._uniformBindGroup=this._device.createBindGroup({layout:this._uniformBindGroupLayout,entries:[{binding:0,resource:{buffer:this._uniformBuffer}}]}),this._staticVertexBuffer=this._device.createBuffer({size:hi.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._staticVertexBuffer,0,hi.buffer,hi.byteOffset,hi.byteLength),this._indexBuffer=this._device.createBuffer({size:li.byteLength,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST}),this._device.queue.writeBuffer(this._indexBuffer,0,li.buffer,li.byteOffset,li.byteLength),this._ensureCapacity(1)}onDisconnect(){this.flush(),this._staticVertexBuffer?.destroy(),this._instanceBuffer?.destroy(),this._indexBuffer?.destroy(),this._uniformBuffer?.destroy(),this._pipelines.clear(),this._indexBuffer=null,this._staticVertexBuffer=null,this._instanceBuffer=null,this._uniformBindGroup=null,this._uniformBuffer=null,this._pipelineLayout=null,this._textureBindGroupLayout=null,this._uniformBindGroupLayout=null,this._shaderModule=null,this._device=null,this._renderManager=null,this._instanceBufferByteLength=0,this._instanceData=new ArrayBuffer(56),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData),this._drawCallCount=0}_ensureCapacity(t){const e=t*ai;if(e>this._instanceData.byteLength){let t=this._instanceData.byteLength;for(;t<e;)t*=2;this._instanceData=new ArrayBuffer(t),this._float32View=new Float32Array(this._instanceData),this._uint32View=new Uint32Array(this._instanceData)}if(e>this._instanceBufferByteLength){let t=this._instanceBufferByteLength||ai;for(;t<e;)t*=2;this._instanceBuffer?.destroy(),this._instanceBuffer=this._device.createBuffer({size:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),this._instanceBufferByteLength=t}}_writeUniformData(t,e,i){const s=t.view.getTransform().toArray(!1),r=e.getGlobalTransform().toArray(!1),n=t.shouldPremultiplyTextureSample(i);this._uniformData.set([s[0],s[1],0,0,s[3],s[4],0,0,0,0,1,0,s[6],s[7],0,s[8],r[0],r[1],0,0,r[3],r[4],0,0,0,0,1,0,r[6],r[7],0,r[8],n?1:0,0,0,0])}_writeInstanceData(t,e,i){const s=t[0],r=t[1],n=t[2]-t[0],o=t[3]-t[1],a=(65535&e[0])/65535,h=(e[0]>>>16&65535)/65535,l=(65535&e[2])/65535,u=(e[2]>>>16&65535)/65535;for(let t=0;t<i.length;t++){const e=i[t],d=14*t;this._float32View[d]=s,this._float32View[d+1]=r,this._float32View[d+2]=n,this._float32View[d+3]=o,this._float32View[d+4]=a,this._float32View[d+5]=h,this._float32View[d+6]=l,this._float32View[d+7]=u,this._float32View[d+8]=e.position.x,this._float32View[d+9]=e.position.y,this._float32View[d+10]=e.scale.x,this._float32View[d+11]=e.scale.y,this._float32View[d+12]=e.rotation,this._uint32View[d+13]=e.tint.toRgba()}}_getPipeline(t,e){const i=`${t}:${e}`,s=this._pipelines.get(i);if(s)return s;const r=this._device.createRenderPipeline({layout:this._pipelineLayout,vertex:{module:this._shaderModule,entryPoint:"vertexMain",buffers:[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:ai,stepMode:"instance",attributes:[{shaderLocation:1,offset:0,format:"float32x2"},{shaderLocation:2,offset:8,format:"float32x2"},{shaderLocation:3,offset:16,format:"float32x2"},{shaderLocation:4,offset:24,format:"float32x2"},{shaderLocation:5,offset:32,format:"float32x2"},{shaderLocation:6,offset:40,format:"float32x2"},{shaderLocation:7,offset:48,format:"float32"},{shaderLocation:8,offset:52,format:"unorm8x4"}]}]},fragment:{module:this._shaderModule,entryPoint:"fragmentMain",targets:[{format:e,blend:ei(t),writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}});return this._pipelines.set(i,r),r}}const di="rgba8unorm";class ci{constructor(t){this.backendType=Se.WebGpu,this.rendererRegistry=new je,this._clearColor=new K,this._textureStates=new Map,this._textureDestroyHandlers=new Map,this._renderTargetDestroyHandlers=new Map,this._temporaryRenderTextures=[],this._maskStack=[],this._maskPixelStack=[],this._maskPointA=new de,this._maskPointB=new de,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._renderer=null,this._blendMode=null,this._texture=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._stats={frame:0,submittedNodes:0,culledNodes:0,drawCalls:0,batches:0,renderPasses:0,renderTargetChanges:0,frameTimeMs:0};const{width:e,height:i,clearColor:s}=t.options;this._canvas=t.canvas,this._rootRenderTarget=new ce(e,i,!0),this._renderTarget=this._rootRenderTarget,s&&this._clearColor.copy(s),this.rendererRegistry.registerRenderer(ye,new ri),this.rendererRegistry.registerRenderer(qe,new oi),this.rendererRegistry.registerRenderer(Xe,new ui),this.resize(e,i)}get view(){return this._renderTarget.view}get renderTarget(){return this._renderTarget}get device(){if(null===this._device)throw new Error("WebGPU device is not initialized yet.");return this._device}get context(){if(null===this._context)throw new Error("WebGPU canvas context is not initialized yet.");return this._context}get format(){if(null===this._format)throw new Error("WebGPU canvas format is not initialized yet.");return this._format}get renderTargetFormat(){return this._renderTarget===this._rootRenderTarget?this.format:di}get clearRequested(){return this._clearRequested}get stats(){return this._stats}initialize(){return this._initializePromise||(this._initializePromise=this._initialize().catch(t=>{throw this._initializePromise=null,t})),this._initializePromise}resetStats(){return Ke(this._stats),this}draw(t){const e=this.rendererRegistry.resolve(t);return this._setActiveRenderer(e),e.render(t),this._stats.submittedNodes++,this}execute(t){return this._flushActiveRenderer(),this._stats.renderPasses++,t.execute(this),this}setShader(t){if(null!==t)throw new Error("WebGPU shaders are not implemented yet.");return this}setTexture(t,e){if(null===t)return this._texture=null,this;if(t instanceof ce&&!(t instanceof pe))throw new Error("WebGPU render textures are not implemented yet.");return this._syncTexture(t),this._texture=t,this}setBlendMode(t){if(null===t)return this._blendMode=null,this;if(t!==Q.Normal&&t!==Q.Additive&&t!==Q.Subtract&&t!==Q.Multiply&&t!==Q.Screen)throw new Error(`WebGPU blend mode "${t}" is not implemented yet.`);return this._blendMode=t,this}setVao(t){if(null!==t)throw new Error("WebGPU vertex array objects are not implemented yet.");return this}setRenderTarget(t){const e=t??this._rootRenderTarget;if(!(e.root||e instanceof pe))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");return this._renderTarget!==e&&(this._flushActiveRenderer(),this._renderTarget!==this._rootRenderTarget&&this._unsubscribeRenderTarget(this._renderTarget),this._renderTarget=e,this._stats.renderTargetChanges++,e!==this._rootRenderTarget&&this._subscribeRenderTarget(e)),this}pushMask(t){this._flushActiveRenderer(),this._maskStack.push(t.clone());const e=this._toMaskPixels(t),i=this._maskPixelStack.length>0?this._maskPixelStack[this._maskPixelStack.length-1]:null,s=i?this._intersectMasks(i,e):e;return this._maskPixelStack.push(s),this}popMask(){if(0===this._maskStack.length)return this;this._flushActiveRenderer();const t=this._maskStack.pop();return t&&t.destroy(),this._maskPixelStack.pop(),this}getScissorRect(){if(0===this._maskPixelStack.length)return null;const t=this._maskPixelStack[this._maskPixelStack.length-1];return{x:t.x,y:t.y,width:t.width,height:t.height}}acquireRenderTexture(t,e){for(let i=0;i<this._temporaryRenderTextures.length;i++){const s=this._temporaryRenderTextures[i];if(s.width===t&&s.height===e)return this._temporaryRenderTextures.splice(i,1),s}return new pe(t,e)}releaseRenderTexture(t){return this._temporaryRenderTextures.includes(t)||(t.setView(null),this._temporaryRenderTextures.push(t)),this}setView(t){return this._flushActiveRenderer(),this._renderTarget.setView(t),this}clear(t){return t&&this._clearColor.copy(t),this._clearRequested=!0,this}resize(t,e){return this._canvas.width=t,this._canvas.height=e,this._rootRenderTarget.resize(t,e),this._hasPresentedFrame=!1,this}flush(){if(!this._device||!this._context)return this;if(this._renderer)this._flushActiveRenderer();else if(this._clearRequested){const t=this._device.createCommandEncoder();t.beginRenderPass({colorAttachments:[this.createColorAttachment()]}).end(),this._stats.renderPasses++,this.submit(t.finish())}return this}destroy(){this._setActiveRenderer(null),this.rendererRegistry.destroy(),this._destroyManagedTextures(),this._destroyTemporaryRenderTextures();for(const t of this._maskStack)t.destroy();this._maskStack.length=0,this._maskPixelStack.length=0,this._maskPointA.destroy(),this._maskPointB.destroy();for(const t of Array.from(this._renderTargetDestroyHandlers.keys()))this._unsubscribeRenderTarget(t);this._context?.unconfigure(),this._context=null,this._device=null,this._format=null,this._initializePromise=null,this._clearRequested=!1,this._hasPresentedFrame=!1,this._texture=null,this._mipmapShaderModule=null,this._mipmapBindGroupLayout=null,this._mipmapPipelineLayout=null,this._mipmapPipeline=null,this._mipmapSampler=null,this._renderTarget=this._rootRenderTarget,this._clearColor.destroy(),this._rootRenderTarget.destroy()}createColorAttachment(){const t=this._renderTarget;let e=null;if(t===this._rootRenderTarget)e={view:this.context.getCurrentTexture().createView(),shouldClear:this._clearRequested||!this._hasPresentedFrame};else{if(!(t instanceof pe))throw new Error("WebGPU currently supports only root targets and RenderTexture targets.");{const i=this._syncTexture(t);e={view:i.view,shouldClear:this._clearRequested||!i.hasContent}}}return this._clearRequested=!1,{view:e.view,clearValue:{r:this._clearColor.r/255,g:this._clearColor.g/255,b:this._clearColor.b/255,a:this._clearColor.a},loadOp:e.shouldClear?"clear":"load",storeOp:"store"}}submit(t){if(this.device.queue.submit([t]),this._renderTarget===this._rootRenderTarget)this._hasPresentedFrame=!0;else if(this._renderTarget instanceof pe){const t=this._syncTexture(this._renderTarget);t.hasContent=!0,t.mipLevelCount>1&&this._generateMipmaps(t.texture,t.mipLevelCount)}}getTextureBinding(t){const e=this._syncTexture(t);return{view:e.view,sampler:e.sampler}}shouldPremultiplyTextureSample(t){return!(t instanceof pe)&&t.premultiplyAlpha}_setActiveRenderer(t){this._renderer!==t&&(this._flushActiveRenderer(),this._renderer=t)}_flushActiveRenderer(){this._renderer?.flush()}async _initialize(){const t=this._getGpuNavigator();if(null===t)throw new Error("This browser does not support WebGPU.");if("function"!=typeof t.gpu.requestAdapter)throw new Error("WebGPU is available, but navigator.gpu.requestAdapter is not implemented.");if("function"!=typeof t.gpu.getPreferredCanvasFormat)throw new Error("WebGPU is available, but navigator.gpu.getPreferredCanvasFormat is not implemented.");let e=null;try{e=await t.gpu.requestAdapter()}catch(t){throw this._createInitializationError("Failed to request a WebGPU adapter.",t)}if(null===e)throw new Error("Could not acquire a WebGPU adapter.");const i=this._canvas.getContext("webgpu");if(null===i)throw new Error("Could not create WebGPU canvas context.");if("function"!=typeof e.requestDevice)throw new Error("WebGPU adapter does not expose requestDevice().");let s=null;try{s=await e.requestDevice()}catch(t){throw this._createInitializationError("Failed to request a WebGPU device.",t)}if(null===s)throw new Error("Could not acquire a WebGPU device.");const r=t.gpu.getPreferredCanvasFormat();try{i.configure({device:s,format:r,alphaMode:"opaque"})}catch(t){throw this._createInitializationError("Failed to configure the WebGPU canvas context.",t)}return this._context=i,this._device=s,this._format=r,this._blendMode=Q.Normal,this._hasPresentedFrame=!1,this.rendererRegistry.connect(this),this.resize(this._canvas.width,this._canvas.height),this}_getGpuNavigator(){const t=navigator;return t.gpu?t:null}_createInitializationError(t,e){return e instanceof Error&&e.message.length>0?new Error(`${t} ${e.message}`):new Error(t)}_destroyManagedTextures(){for(const t of Array.from(this._textureStates.keys()))this._evictTexture(t)}_destroyTemporaryRenderTextures(){for(const t of this._temporaryRenderTextures)t.destroy();this._temporaryRenderTextures.length=0}_getTextureState(t){let e=this._textureStates.get(t);if(!e){const i=this.device.createTexture({size:{width:Math.max(t.width,1),height:Math.max(t.height,1)},format:di,mipLevelCount:this._getMipLevelCount(t),usage:this._getTextureUsage(t)});e={texture:i,view:i.createView(),sampler:this._createSampler(t),version:-1,width:t.width,height:t.height,mipLevelCount:this._getMipLevelCount(t),hasContent:!1};const s=()=>{this._evictTexture(t)};t.addDestroyListener(s),this._textureDestroyHandlers.set(t,s),this._textureStates.set(t,e)}return e}_syncTexture(t){if(!(t instanceof pe||null!==t.source&&0!==t.width&&0!==t.height))throw new Error("WebGPU sprite rendering requires a texture with a valid source and non-zero dimensions.");const e=this._getTextureState(t),i=t instanceof pe?t.textureVersion:t.version,s=this._getMipLevelCount(t);if(e.version!==i){if(e.width!==t.width||e.height!==t.height||e.mipLevelCount!==s){e.texture.destroy();const i=this.device.createTexture({size:{width:t.width,height:t.height},format:di,mipLevelCount:s,usage:this._getTextureUsage(t)});e.texture=i,e.view=i.createView(),e.width=t.width,e.height=t.height,e.mipLevelCount=s,e.hasContent=!1}if(e.sampler=this._createSampler(t),!(t instanceof pe)){const i=t.source;this.device.queue.copyExternalImageToTexture({source:i,flipY:!1},{texture:e.texture},{width:t.width,height:t.height}),e.mipLevelCount>1&&this._generateMipmaps(e.texture,e.mipLevelCount)}e.version=i}return e}_evictTexture(t){const e=this._textureStates.get(t),i=this._textureDestroyHandlers.get(t);i&&(t.removeDestroyListener(i),this._textureDestroyHandlers.delete(t)),e&&(e.texture.destroy(),this._textureStates.delete(t)),this._texture===t&&(this._texture=null)}_subscribeRenderTarget(t){if(!this._renderTargetDestroyHandlers.has(t)){const e=()=>{this._renderTarget===t&&(this._renderTarget=this._rootRenderTarget),this._renderTargetDestroyHandlers.delete(t)};t.addDestroyListener(e),this._renderTargetDestroyHandlers.set(t,e)}}_unsubscribeRenderTarget(t){const e=this._renderTargetDestroyHandlers.get(t);e&&(t.removeDestroyListener(e),this._renderTargetDestroyHandlers.delete(t))}_toMaskPixels(t){const e=this._renderTarget.mapCoordsToPixel(this._maskPointA.set(t.left,t.top)),i=this._renderTarget.mapCoordsToPixel(this._maskPointB.set(t.right,t.bottom)),s=Math.min(e.x,i.x),r=Math.max(e.x,i.x),n=Math.min(e.y,i.y),o=Math.max(e.y,i.y),a=this._renderTarget.width,h=this._renderTarget.height,l=Math.max(0,Math.min(a,Math.floor(s))),u=Math.max(0,Math.min(a,Math.ceil(r))),d=Math.max(0,Math.min(h,Math.floor(n))),c=Math.max(0,Math.min(h,Math.ceil(o)));return{x:l,y:d,width:Math.max(0,u-l),height:Math.max(0,c-d)}}_intersectMasks(t,e){const i=Math.max(t.x,e.x),s=Math.max(t.y,e.y),r=Math.min(t.x+t.width,e.x+e.width),n=Math.min(t.y+t.height,e.y+e.height);return{x:i,y:s,width:Math.max(0,r-i),height:Math.max(0,n-s)}}_createSampler(t){return this.device.createSampler({addressModeU:this._getAddressMode(t.wrapMode),addressModeV:this._getAddressMode(t.wrapMode),magFilter:this._getFilterMode(t.scaleMode),minFilter:this._getFilterMode(t.scaleMode),mipmapFilter:this._getMipmapFilterMode(t.scaleMode)})}_getTextureUsage(t){const e=this._getMipLevelCount(t)>1?GPUTextureUsage.RENDER_ATTACHMENT:0;return t instanceof pe?GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT|e:GPUTextureUsage.COPY_DST|GPUTextureUsage.TEXTURE_BINDING|e}_getAddressMode(t){switch(t){case J.Repeat:return"repeat";case J.MirroredRepeat:return"mirror-repeat";default:return"clamp-to-edge"}}_getFilterMode(t){switch(t){case Z.Nearest:case Z.NearestMipmapNearest:case Z.NearestMipmapLinear:return"nearest";default:return"linear"}}_getMipmapFilterMode(t){switch(t){case Z.NearestMipmapLinear:case Z.LinearMipmapLinear:return"linear";default:return"nearest"}}_getMipLevelCount(t){if(!t.generateMipMap)return 1;const e=Math.max(t.width,t.height);return e<=1?1:Math.floor(Math.log2(e))+1}_generateMipmaps(t,e){if(e<=1)return;const i=this._getMipmapResources(),s=this.device.createCommandEncoder();for(let r=1;r<e;r++){const e=this.device.createBindGroup({layout:i.bindGroupLayout,entries:[{binding:0,resource:t.createView({baseMipLevel:r-1,mipLevelCount:1})},{binding:1,resource:i.sampler}]}),n=s.beginRenderPass({colorAttachments:[{view:t.createView({baseMipLevel:r,mipLevelCount:1}),clearValue:{r:0,g:0,b:0,a:0},loadOp:"clear",storeOp:"store"}]});n.setPipeline(i.pipeline),n.setBindGroup(0,e),n.draw(3),n.end()}this.device.queue.submit([s.finish()])}_getMipmapResources(){return null!==this._mipmapShaderModule&&null!==this._mipmapBindGroupLayout&&null!==this._mipmapPipelineLayout&&null!==this._mipmapPipeline&&null!==this._mipmapSampler||(this._mipmapShaderModule=this.device.createShaderModule({code:"\nstruct VertexOutput {\n @builtin(position) position: vec4<f32>,\n @location(0) texcoord: vec2<f32>,\n};\n\n@group(0) @binding(0)\nvar sourceTexture: texture_2d<f32>;\n@group(0) @binding(1)\nvar sourceSampler: sampler;\n\n@vertex\nfn vertexMain(@builtin(vertex_index) vertexIndex: u32) -> VertexOutput {\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(3.0, -1.0),\n vec2<f32>(-1.0, 3.0)\n );\n // Y is flipped vs the position array: NDC Y points up, but texture UV\n // Y points down (UV (0,0) is the top-left of the source). Matching the\n // two ensures that the output texture's top-left pixel samples from the\n // source's top-left, so every mip level has the same orientation as the\n // level above it. Prior to this, odd mip levels were rendered upside\n // down, producing visible texture flips at view-size doublings.\n var texcoords = array<vec2<f32>, 3>(\n vec2<f32>(0.0, 1.0),\n vec2<f32>(2.0, 1.0),\n vec2<f32>(0.0, -1.0)\n );\n var output: VertexOutput;\n\n output.position = vec4<f32>(positions[vertexIndex], 0.0, 1.0);\n output.texcoord = texcoords[vertexIndex];\n\n return output;\n}\n\n@fragment\nfn fragmentMain(input: VertexOutput) -> @location(0) vec4<f32> {\n return textureSample(sourceTexture, sourceSampler, input.texcoord);\n}\n"}),this._mipmapBindGroupLayout=this.device.createBindGroupLayout({entries:[{binding:0,visibility:GPUShaderStage.FRAGMENT,texture:{sampleType:"float"}},{binding:1,visibility:GPUShaderStage.FRAGMENT,sampler:{type:"filtering"}}]}),this._mipmapPipelineLayout=this.device.createPipelineLayout({bindGroupLayouts:[this._mipmapBindGroupLayout]}),this._mipmapPipeline=this.device.createRenderPipeline({layout:this._mipmapPipelineLayout,vertex:{module:this._mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this._mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:di,writeMask:GPUColorWrite.ALL}]},primitive:{topology:"triangle-list"}}),this._mipmapSampler=this.device.createSampler({minFilter:"linear",magFilter:"linear",mipmapFilter:"nearest"})),{bindGroupLayout:this._mipmapBindGroupLayout,pipeline:this._mipmapPipeline,sampler:this._mipmapSampler}}}var pi,_i,fi,mi,gi,yi;!function(t){t[t.Container=768]="Container",t[t.Category=256]="Category",t[t.Gamepad=64]="Gamepad"}(pi||(pi={})),function(t){t[t.Backspace=8]="Backspace",t[t.Tab=9]="Tab",t[t.Clear=12]="Clear",t[t.Enter=13]="Enter",t[t.Shift=16]="Shift",t[t.Control=17]="Control",t[t.Alt=18]="Alt",t[t.Pause=19]="Pause",t[t.CapsLock=20]="CapsLock",t[t.Escape=27]="Escape",t[t.Space=32]="Space",t[t.PageUp=33]="PageUp",t[t.PageDown=34]="PageDown",t[t.End=35]="End",t[t.Home=36]="Home",t[t.Left=37]="Left",t[t.Up=38]="Up",t[t.Right=39]="Right",t[t.Down=40]="Down",t[t.Insert=45]="Insert",t[t.Delete=46]="Delete",t[t.Help=47]="Help",t[t.Zero=48]="Zero",t[t.One=49]="One",t[t.Two=50]="Two",t[t.Three=51]="Three",t[t.Four=52]="Four",t[t.Five=53]="Five",t[t.Six=54]="Six",t[t.Seven=55]="Seven",t[t.Eight=56]="Eight",t[t.Nine=57]="Nine",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.NumPad0=96]="NumPad0",t[t.NumPad1=97]="NumPad1",t[t.NumPad2=98]="NumPad2",t[t.NumPad3=99]="NumPad3",t[t.NumPad4=100]="NumPad4",t[t.NumPad5=101]="NumPad5",t[t.NumPad6=102]="NumPad6",t[t.NumPad7=103]="NumPad7",t[t.NumPad8=104]="NumPad8",t[t.NumPad9=105]="NumPad9",t[t.NumPadMultiply=106]="NumPadMultiply",t[t.NumPadAdd=107]="NumPadAdd",t[t.NumPadEnter=108]="NumPadEnter",t[t.NumPadSubtract=109]="NumPadSubtract",t[t.NumPadDecimal=110]="NumPadDecimal",t[t.NumPadDivide=111]="NumPadDivide",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NumLock=144]="NumLock",t[t.ScrollLock=145]="ScrollLock",t[t.Colon=186]="Colon",t[t.Equals=187]="Equals",t[t.Comma=188]="Comma",t[t.Dash=189]="Dash",t[t.Period=190]="Period",t[t.QuestionMark=191]="QuestionMark",t[t.Tilde=192]="Tilde",t[t.OpenBracket=219]="OpenBracket",t[t.BackwardSlash=220]="BackwardSlash",t[t.ClosedBracket=221]="ClosedBracket",t[t.Quotes=222]="Quotes"}(_i||(_i={}));class xi{constructor(t,e,i){this.onConnect=new F,this.onDisconnect=new F,this.onUpdate=new F,this.browserGamepad=null,this.info={name:"Generic Gamepad",label:"Generic Gamepad",vendorId:null,productId:null,productKey:null};const s="number"!=typeof t,r=s?t:null,n=s?t.index:t;if(this.indexValue=n,this.channelsValue=e,this.channelOffset=512+n*pi.Gamepad,this.mappingValue=r?i.mapping:i,r){const t=i;this.setInfo({name:t.name,label:t.descriptor.label,vendorId:t.descriptor.vendorId,productId:t.descriptor.productId,productKey:t.descriptor.productKey}),this.connect(r)}}get mapping(){return this.mappingValue}set mapping(t){this.mappingValue=t}get mappingFamily(){return this.mappingValue.family}get channels(){return this.channelsValue}get gamepad(){return this.browserGamepad}get index(){return this.indexValue}get connected(){return null!==this.browserGamepad}get name(){return this.info.name}get label(){return this.info.label}get vendorId(){return this.info.vendorId}get productId(){return this.info.productId}get productKey(){return this.info.productKey}setInfo(t){return this.info=t,this}connect(t){const e=this.connected;return this.browserGamepad=t,e||this.onConnect.dispatch(this),this}disconnect(){return this.connected&&(this.browserGamepad=null,this.clearMappedChannels(),this.onDisconnect.dispatch(this)),this}update(){if(null===this.browserGamepad)return this;const t=this.channelsValue,{buttons:e,axes:i}=this.browserGamepad;for(const i of this.mappingValue.buttons){const s=this.resolveChannelOffset(i.channel);if(i.index<e.length){const r=i.transformValue(e[i.index].value)||0;t[s]!==r&&(t[s]=r,this.onUpdate.dispatch(i.channel,r,this))}}for(const e of this.mappingValue.axes){const s=this.resolveChannelOffset(e.channel);if(e.index<i.length){const r=e.transformValue(i[e.index])||0;t[s]!==r&&(t[s]=r,this.onUpdate.dispatch(e.channel,r,this))}}return this}clearChannels(){return this.clearMappedChannels(),this}destroy(){this.disconnect(),this.clearMappedChannels(),this.onConnect.destroy(),this.onDisconnect.destroy(),this.onUpdate.destroy()}resolveChannelOffset(t){return this.channelOffset+(512^t)}static resolveChannelOffset(t,e){return 512+t*pi.Gamepad+(512^e)}clearMappedChannels(){for(const t of this.mappingValue.buttons)this.channelsValue[this.resolveChannelOffset(t.channel)]=0;for(const t of this.mappingValue.axes)this.channelsValue[this.resolveChannelOffset(t.channel)]=0}}!function(t){t[t.None=0]="None",t[t.Over=1]="Over",t[t.Leave=2]="Leave",t[t.Down=4]="Down",t[t.Move=8]="Move",t[t.Up=16]="Up",t[t.Cancel=32]="Cancel"}(fi||(fi={})),function(t){t[t.Unknown=0]="Unknown",t[t.InsideCanvas=1]="InsideCanvas",t[t.OutsideCanvas=2]="OutsideCanvas",t[t.Pressed=3]="Pressed",t[t.Moving=4]="Moving",t[t.Released=5]="Released",t[t.Cancelled=6]="Cancelled"}(mi||(mi={}));class wi{constructor(t,i){this.startPos=new de(-1,-1),this.stateFlags=new ht,this._currentState=mi.Unknown;const{pointerId:s,pointerType:r,clientX:n,clientY:o,width:a,height:h,tiltX:l,tiltY:u,buttons:d,pressure:c,twist:p}=t,{left:_,top:f}=i.getBoundingClientRect();this._canvas=i,this.id=s,this.type=r,this.position=new de(n-_,o-f),this.size=new e(a,h),this.tilt=new de(l,u),this._buttons=d,this._pressure=c,this._rotation=p,this.stateFlags.push(fi.Over)}get x(){return this.position.x}get y(){return this.position.y}get width(){return this.size.width}get height(){return this.size.height}get buttons(){return this._buttons}get pressure(){return this._pressure}get rotation(){return this._rotation}get currentState(){return this._currentState}handleEnter(t){this.handleEvent(t),this._currentState=mi.InsideCanvas}handleLeave(t){this.handleEvent(t),this.stateFlags.push(fi.Leave),this._currentState=mi.OutsideCanvas}handlePress(t){this.handleEvent(t),this.startPos.copy(this.position),this.stateFlags.push(fi.Down),this._currentState=mi.Pressed}handleMove(t){this.handleEvent(t),this.stateFlags.push(fi.Move),this._currentState=mi.Moving}handleRelease(t){this.handleEvent(t),this.stateFlags.push(fi.Up),this._currentState=mi.Released}handleCancel(t){this.handleEvent(t),this.stateFlags.push(fi.Cancel),this._currentState=mi.Cancelled}destroy(){this.position.destroy(),this.startPos.destroy(),this.size.destroy(),this.tilt.destroy(),this._canvas=null}handleEvent(t){const{clientX:e,clientY:i,width:s,height:r,tiltX:n,tiltY:o,buttons:a,pressure:h,twist:l}=t,{left:u,top:d}=this._canvas.getBoundingClientRect();return this.position.set(e-u,i-d),this.size.set(s,r),this.tilt.set(n,o),this._buttons=a,this._pressure=h,this._rotation=l,this}}!function(t){t[t.ButtonSouth=512]="ButtonSouth",t[t.ButtonWest=513]="ButtonWest",t[t.ButtonEast=514]="ButtonEast",t[t.ButtonNorth=515]="ButtonNorth",t[t.LeftShoulder=516]="LeftShoulder",t[t.RightShoulder=517]="RightShoulder",t[t.LeftTrigger=518]="LeftTrigger",t[t.RightTrigger=519]="RightTrigger",t[t.Select=520]="Select",t[t.Start=521]="Start",t[t.LeftStick=522]="LeftStick",t[t.RightStick=523]="RightStick",t[t.DPadUp=524]="DPadUp",t[t.DPadDown=525]="DPadDown",t[t.DPadLeft=526]="DPadLeft",t[t.DPadRight=527]="DPadRight",t[t.Guide=528]="Guide",t[t.Share=529]="Share",t[t.Capture=530]="Capture",t[t.Touchpad=531]="Touchpad",t[t.Paddle1=532]="Paddle1",t[t.LeftStickLeft=533]="LeftStickLeft",t[t.LeftStickRight=534]="LeftStickRight",t[t.LeftStickUp=535]="LeftStickUp",t[t.LeftStickDown=536]="LeftStickDown",t[t.RightStickLeft=537]="RightStickLeft",t[t.RightStickRight=538]="RightStickRight",t[t.RightStickUp=539]="RightStickUp",t[t.RightStickDown=540]="RightStickDown",t[t.AuxiliaryAxis0Negative=541]="AuxiliaryAxis0Negative",t[t.AuxiliaryAxis0Positive=542]="AuxiliaryAxis0Positive",t[t.AuxiliaryAxis1Negative=543]="AuxiliaryAxis1Negative",t[t.AuxiliaryAxis1Positive=544]="AuxiliaryAxis1Positive",t[t.AuxiliaryAxis2Negative=545]="AuxiliaryAxis2Negative",t[t.AuxiliaryAxis2Positive=546]="AuxiliaryAxis2Positive",t[t.AuxiliaryAxis3Negative=547]="AuxiliaryAxis3Negative",t[t.AuxiliaryAxis3Positive=548]="AuxiliaryAxis3Positive"}(gi||(gi={}));class vi{constructor(t,e,i={}){this.index=t,this.channel=e,this.invert=i.invert??!1,this.normalize=i.normalize??!1,this.threshold=G(i.threshold??.2,0,1)}transformValue(t){let e=G(t,-1,1);return this.invert&&(e*=-1),this.normalize&&(e=(e+1)/2),e>this.threshold?e:0}}!function(t){t.GenericDualAnalog="genericDualAnalog",t.Xbox="xbox",t.PlayStation="playStation",t.SwitchPro="switchPro",t.JoyConLeft="joyConLeft",t.JoyConRight="joyConRight",t.GameCube="gameCube",t.SteamController="steamController",t.ArcadeStick="arcadeStick"}(yi||(yi={}));class bi{constructor(t,e){this.buttons=t,this.axes=e}destroy(){this.buttons.length=0,this.axes.length=0}static createControls(t){return t.map(([t,e,i])=>new vi(t,e,i))}}const Ti=[[0,gi.ButtonSouth],[1,gi.ButtonEast],[2,gi.ButtonWest],[3,gi.ButtonNorth],[4,gi.LeftShoulder],[5,gi.RightShoulder],[6,gi.LeftTrigger],[7,gi.RightTrigger],[8,gi.Select],[9,gi.Start],[12,gi.DPadUp],[13,gi.DPadDown],[14,gi.DPadLeft],[15,gi.DPadRight],[16,gi.Guide]];class Si extends bi{constructor(){super(bi.createControls(Ti),[]),this.family=yi.ArcadeStick}}const Ci=[[0,gi.ButtonSouth],[1,gi.ButtonEast],[2,gi.ButtonWest],[3,gi.ButtonNorth],[4,gi.LeftShoulder],[5,gi.RightShoulder],[6,gi.LeftTrigger],[7,gi.RightTrigger],[8,gi.Select],[9,gi.Start],[10,gi.LeftStick],[11,gi.RightStick],[12,gi.DPadUp],[13,gi.DPadDown],[14,gi.DPadLeft],[15,gi.DPadRight],[16,gi.Guide],[17,gi.Share],[18,gi.Capture],[19,gi.Touchpad],[20,gi.Paddle1]],Mi=[[0,gi.LeftStickLeft,{invert:!0}],[0,gi.LeftStickRight],[1,gi.LeftStickUp,{invert:!0}],[1,gi.LeftStickDown],[2,gi.RightStickLeft,{invert:!0}],[2,gi.RightStickRight],[3,gi.RightStickUp,{invert:!0}],[3,gi.RightStickDown],[4,gi.AuxiliaryAxis0Negative,{invert:!0}],[4,gi.AuxiliaryAxis0Positive],[5,gi.AuxiliaryAxis1Negative,{invert:!0}],[5,gi.AuxiliaryAxis1Positive],[6,gi.AuxiliaryAxis2Negative,{invert:!0}],[6,gi.AuxiliaryAxis2Positive],[7,gi.AuxiliaryAxis3Negative,{invert:!0}],[7,gi.AuxiliaryAxis3Positive]];class Pi extends bi{constructor(){super(bi.createControls(Ci),bi.createControls(Mi)),this.family=yi.GenericDualAnalog}}class Bi extends Pi{constructor(){super(...arguments),this.family=yi.GameCube}}class Ei extends Pi{constructor(){super(...arguments),this.family=yi.JoyConLeft}}class Ri extends Pi{constructor(){super(...arguments),this.family=yi.JoyConRight}}class Ai extends Pi{constructor(){super(...arguments),this.family=yi.PlayStation}}class ki extends Pi{constructor(){super(...arguments),this.family=yi.SteamController}}class Li extends Pi{constructor(){super(...arguments),this.family=yi.SwitchPro}}class Fi extends Pi{constructor(){super(...arguments),this.family=yi.Xbox}}const Di=/vendor[:\s]*([0-9a-f]{4})\s*product[:\s]*([0-9a-f]{4})/i,Ii=/vendor[:\s]*0x([0-9a-f]{4})\s*product[:\s]*0x([0-9a-f]{4})/i,Ni=/\b([0-9a-f]{4})[-: ]([0-9a-f]{4})\b/i,Ui=/vid[_:\s]*([0-9a-f]{4}).{0,8}pid[_:\s]*([0-9a-f]{4})/i,Vi=(t,e,i)=>({ids:i,name:t,resolve:()=>({name:t,mapping:e()})}),Oi=t=>t.trim().toLowerCase(),Gi=t=>{const e=t.replace(Ii,"").replace(Di,"").replace(Ui,"").replace(Ni,"").replace(/\s+/g," ").trim();return e.length>0?e:null},zi=t=>{if(!t)return[];return(Array.isArray(t)?t:[t]).map(Oi)},Wi=(t,e)=>{if(!e)return!0;for(const i of zi(e))if(i.includes(":")){if(t.productKey===i)return!0}else if(t.vendorId===i)return!0;return!1},qi=t=>{const e=t.id.trim()||`Gamepad ${t.index}`,i=(t=>{const e=Ii.exec(t)||Di.exec(t)||Ui.exec(t)||Ni.exec(t);return e?`${e[1].toLowerCase()}:${e[2].toLowerCase()}`:null})(e),s=i?.slice(0,4)??null,r=i?.slice(5)??null;return{id:t.id,index:t.index,label:e,vendorId:s,productId:r,productKey:i,name:Gi(e)}},Hi=(t,e)=>Wi(e,t.ids)?((t,e)=>{const i=t.resolve(e);return null==i?null:"mapping"in i?{descriptor:e,name:i.name??t.name??e.name??e.label,mapping:i.mapping}:{descriptor:e,name:t.name??e.name??e.label,mapping:i}})(t,e):null,Xi=(t,e=Yi)=>{const i="connected"in t?qi(t):t;for(const t of e){const e=Hi(t,i);if(e)return e}return{descriptor:i,name:i.name??i.label,mapping:new Pi}},Yi=[...[Vi("Xbox 360 Controller",()=>new Fi,"045e:028e"),Vi("Xbox One Controller",()=>new Fi,["045e:02d1","045e:02dd"]),Vi("Xbox Wireless Controller",()=>new Fi,["045e:02e0","045e:02ea","045e:02fd","045e:0b20"]),Vi("Xbox One Elite Controller",()=>new Fi,"045e:02e3"),Vi("Xbox Elite Wireless Controller Series 2",()=>new Fi,["045e:0b00","045e:0b05","045e:0b22"]),Vi("Xbox Series Controller",()=>new Fi,["045e:0b12","045e:0b13"]),Vi("PlayStation 3 Controller",()=>new Ai,"054c:0268"),Vi("DualShock 4 Controller",()=>new Ai,["054c:05c4","054c:09cc","054c:0ba0"]),Vi("DualSense Controller",()=>new Ai,"054c:0ce6"),Vi("DualSense Edge Controller",()=>new Ai,"054c:0df2"),Vi("GameCube Controller Adapter",()=>new Bi,"057e:0337"),Vi("Joy-Con (L)",()=>new Ei,"057e:2006"),Vi("Joy-Con (R)",()=>new Ri,"057e:2007"),Vi("Joy-Con Charging Grip",()=>new Li,"057e:200e"),Vi("Switch Pro Controller",()=>new Li,"057e:2009"),Vi("Joy-Con 2 (L)",()=>new Ei,"057e:2066"),Vi("Joy-Con 2 (R)",()=>new Ri,"057e:2067"),Vi("Switch 2 Pro Controller",()=>new Li,"057e:2069"),Vi("Switch 2 GameCube Controller",()=>new Bi,"057e:2073"),Vi("Steam Controller",()=>new ki,["28de:1102","28de:1142"]),Vi("F310 Gamepad",()=>new Pi,"046d:c216"),Vi("F710 Gamepad",()=>new Pi,["046d:c219","046d:c21f"]),Vi("8BitDo P30 Controller",()=>new Pi,["2dc8:5107","2dc8:5108"]),Vi("8BitDo SF30 Pro Controller",()=>new Li,["2dc8:3000","2dc8:6100","2dc8:6101"]),Vi("8BitDo SN30 Controller",()=>new Li,["2dc8:3001","2dc8:5103","2dc8:9020","2dc8:ab20","2dc8:2840","2dc8:2862"]),Vi("8BitDo NES30 Controller",()=>new Pi,"2dc8:ab12"),Vi("PowerA Switch Controller",()=>new Li,"20d6:a713"),Vi("PowerA OPS Pro Wireless Controller",()=>new Pi,"20d6:4033"),Vi("PowerA OPS Wireless Controller",()=>new Pi,"20d6:4026"),Vi("Nacon Revolution 3 Controller",()=>new Ai,"146b:0611"),Vi("Nacon Revolution Unlimited Pro Controller",()=>new Ai,"146b:0d08"),Vi("Nacon Revolution Infinity Controller",()=>new Ai,"146b:0d10"),Vi("Nacon Revolution 5 Pro Controller",()=>new Ai,["3285:0d17","3285:0d19"]),Vi("Razer Raiju Controller",()=>new Ai,"1532:1000"),Vi("Razer Raiju Mobile Controller",()=>new Ai,["1532:0705","1532:0707"]),Vi("Razer Raiju Tournament Edition Controller",()=>new Ai,["1532:1007","1532:100a"]),Vi("Razer Raiju Ultimate Controller",()=>new Ai,["1532:1004","1532:1009"]),Vi("Razer Raion Controller",()=>new Si,"1532:1100")],...[Vi("Microsoft Controller",()=>new Fi,"045e"),Vi("Sony Controller",()=>new Ai,"054c")],Vi("Generic Gamepad",()=>new Pi)];var ji;!function(t){t[t.None=0]="None",t[t.KeyDown=1]="KeyDown",t[t.KeyUp=2]="KeyUp",t[t.MouseWheel=4]="MouseWheel",t[t.PointerUpdate=8]="PointerUpdate"}(ji||(ji={}));class $i{constructor(t){this.channels=new Float32Array(pi.Container),this.inputs=new Set,this.pointers={},this.gamepadsValue=[],this.gamepadsByIndex=new Map,this.gamepadSlotsActive=new Uint8Array(pi.Category/pi.Gamepad),this.wheelOffset=new de,this.flags=new ht,this.channelsPressed=[],this.channelsReleased=[],this.keyDownHandler=this.handleKeyDown.bind(this),this.keyUpHandler=this.handleKeyUp.bind(this),this.canvasFocusHandler=this.handleCanvasFocus.bind(this),this.canvasBlurHandler=this.handleCanvasBlur.bind(this),this.windowBlurHandler=this.handleWindowBlur.bind(this),this.mouseWheelHandler=this.handleMouseWheel.bind(this),this.pointerOverHandler=this.handlePointerOver.bind(this),this.pointerLeaveHandler=this.handlePointerLeave.bind(this),this.pointerDownHandler=this.handlePointerDown.bind(this),this.pointerMoveHandler=this.handlePointerMove.bind(this),this.pointerUpHandler=this.handlePointerUp.bind(this),this.pointerCancelHandler=this.handlePointerCancel.bind(this),this.onPointerEnter=new F,this.onPointerLeave=new F,this.onPointerDown=new F,this.onPointerMove=new F,this.onPointerUp=new F,this.onPointerTap=new F,this.onPointerSwipe=new F,this.onPointerCancel=new F,this.onMouseWheel=new F,this.onKeyDown=new F,this.onKeyUp=new F,this.onGamepadConnected=new F,this.onGamepadDisconnected=new F,this.onGamepadUpdated=new F;const{gamepadDefinitions:e=[],pointerDistanceThreshold:i}=t.options;this.canvas=t.canvas,this.canvasFocusedValue=document.activeElement===this.canvas,this.pointerDistanceThreshold=i,this.gamepadDefinitions=[...e,...Yi],this.addEventListeners()}get pointersInCanvas(){return Object.values(this.pointers).some(t=>t.currentState!==mi.OutsideCanvas&&t.currentState!==mi.Cancelled)}get canvasFocused(){return this.canvasFocusedValue}get gamepads(){return this.gamepadsValue}getGamepad(t){return this.gamepadsByIndex.get(t)??null}add(t){return Array.isArray(t)?(t.forEach(t=>this.add(t)),this):(this.inputs.add(t),this)}remove(t){return Array.isArray(t)?(t.forEach(t=>this.remove(t)),this):(this.inputs.delete(t),this)}clear(t=!1){if(t)for(const t of this.inputs)t.destroy();return this.inputs.clear(),this}update(){this.updateGamepads();for(const t of this.inputs)t.update(this.channels);return this.flags.value!==ji.None&&this.updateEvents(),this}destroy(){this.removeEventListeners();for(const t of Object.values(this.pointers))t.destroy();for(const t of this.gamepadsValue)t.destroy();this.inputs.clear(),this.gamepadsByIndex.clear(),this.gamepadsValue.length=0,this.channelsPressed.length=0,this.channelsReleased.length=0,this.wheelOffset.destroy(),this.flags.destroy(),this.onPointerEnter.destroy(),this.onPointerLeave.destroy(),this.onPointerDown.destroy(),this.onPointerMove.destroy(),this.onPointerUp.destroy(),this.onPointerTap.destroy(),this.onPointerSwipe.destroy(),this.onPointerCancel.destroy(),this.onMouseWheel.destroy(),this.onKeyDown.destroy(),this.onKeyUp.destroy(),this.onGamepadConnected.destroy(),this.onGamepadDisconnected.destroy(),this.onGamepadUpdated.destroy()}handleKeyDown(t){const e=0+t.keyCode;this.channels[e]=1,this.channelsPressed.push(e),this.flags.push(ji.KeyDown)}handleKeyUp(t){const e=0+t.keyCode;this.channels[e]=0,this.channelsReleased.push(e),this.flags.push(ji.KeyUp)}handlePointerOver(t){this.pointers[t.pointerId]=new wi(t,this.canvas),this.flags.push(ji.PointerUpdate)}handlePointerLeave(t){this.pointers[t.pointerId].handleLeave(t),this.flags.push(ji.PointerUpdate)}handlePointerDown(t){this.canvas.focus(),this.canvasFocusedValue=!0,this.pointers[t.pointerId].handlePress(t),this.flags.push(ji.PointerUpdate),t.preventDefault()}handlePointerMove(t){this.pointers[t.pointerId].handleMove(t),this.flags.push(ji.PointerUpdate)}handlePointerUp(t){this.pointers[t.pointerId].handleRelease(t),this.flags.push(ji.PointerUpdate),t.preventDefault()}handlePointerCancel(t){this.pointers[t.pointerId].handleCancel(t),this.flags.push(ji.PointerUpdate)}handleMouseWheel(t){this.wheelOffset.set(t.deltaX,t.deltaY),this.flags.push(ji.MouseWheel),this.canvasFocusedValue&&t.preventDefault()}handleCanvasFocus(){this.canvasFocusedValue=!0}handleCanvasBlur(){this.canvasFocusedValue=!1}handleWindowBlur(){this.canvasFocusedValue=!1}addEventListeners(){const t=window,e={capture:!0,passive:!1},i={capture:!0,passive:!0};t.addEventListener("keydown",this.keyDownHandler,!0),t.addEventListener("keyup",this.keyUpHandler,!0),t.addEventListener("blur",this.windowBlurHandler,!0),this.canvas.addEventListener("focus",this.canvasFocusHandler,!0),this.canvas.addEventListener("blur",this.canvasBlurHandler,!0),this.canvas.addEventListener("wheel",this.mouseWheelHandler,e),this.canvas.addEventListener("pointerover",this.pointerOverHandler,i),this.canvas.addEventListener("pointerleave",this.pointerLeaveHandler,i),this.canvas.addEventListener("pointerdown",this.pointerDownHandler,e),this.canvas.addEventListener("pointermove",this.pointerMoveHandler,i),this.canvas.addEventListener("pointerup",this.pointerUpHandler,e),this.canvas.addEventListener("pointercancel",this.pointerCancelHandler,i),this.canvas.addEventListener("contextmenu",m,e),this.canvas.addEventListener("selectstart",m,e)}removeEventListeners(){const t={capture:!0,passive:!1},e={capture:!0,passive:!0};window.removeEventListener("keydown",this.keyDownHandler,!0),window.removeEventListener("keyup",this.keyUpHandler,!0),window.removeEventListener("blur",this.windowBlurHandler,!0),this.canvas.removeEventListener("focus",this.canvasFocusHandler,!0),this.canvas.removeEventListener("blur",this.canvasBlurHandler,!0),this.canvas.removeEventListener("wheel",this.mouseWheelHandler,t),this.canvas.removeEventListener("pointerover",this.pointerOverHandler,e),this.canvas.removeEventListener("pointerleave",this.pointerLeaveHandler,e),this.canvas.removeEventListener("pointerdown",this.pointerDownHandler,t),this.canvas.removeEventListener("pointermove",this.pointerMoveHandler,e),this.canvas.removeEventListener("pointerup",this.pointerUpHandler,t),this.canvas.removeEventListener("pointercancel",this.pointerCancelHandler,e),this.canvas.removeEventListener("contextmenu",m,t),this.canvas.removeEventListener("selectstart",m,t)}updateGamepads(){const t=window.navigator.getGamepads();this.gamepadSlotsActive.fill(0);for(const e of t){if(!e)continue;const t=e.index;if(t<0||t>=this.gamepadSlotsActive.length)continue;this.gamepadSlotsActive[t]=1;let i=this.gamepadsByIndex.get(t);if(i)i.connect(e);else{const s=Xi(e,this.gamepadDefinitions);i=new xi(e,this.channels,s),this.gamepadsByIndex.set(t,i),this.insertGamepadByIndex(i),this.onGamepadConnected.dispatch(i,this.gamepadsValue)}i.update(),this.onGamepadUpdated.dispatch(i,this.gamepadsValue)}for(let t=this.gamepadsValue.length-1;t>=0;t-=1){const e=this.gamepadsValue[t];0===this.gamepadSlotsActive[e.index]&&(e.disconnect(),this.gamepadsValue.splice(t,1),this.gamepadsByIndex.delete(e.index),this.onGamepadDisconnected.dispatch(e,this.gamepadsValue),e.destroy())}return this}insertGamepadByIndex(t){let e=0;for(;e<this.gamepadsValue.length&&this.gamepadsValue[e].index<t.index;)e+=1;this.gamepadsValue.splice(e,0,t)}updateEvents(){if(this.flags.pop(ji.KeyDown)){for(const t of this.channelsPressed)this.onKeyDown.dispatch(t);this.channelsPressed.length=0}if(this.flags.pop(ji.KeyUp)){for(const t of this.channelsReleased)this.onKeyUp.dispatch(t);this.channelsReleased.length=0}return this.flags.pop(ji.MouseWheel)&&(this.onMouseWheel.dispatch(this.wheelOffset),this.wheelOffset.set(0,0)),this.flags.pop(ji.PointerUpdate)&&this.updatePointerEvents(),this}updatePointerEvents(){for(const t of Object.values(this.pointers)){const{stateFlags:e}=t;if(e.value!==fi.None){if(e.pop(fi.Over)&&this.onPointerEnter.dispatch(t),e.pop(fi.Down)&&this.onPointerDown.dispatch(t),e.pop(fi.Move)&&this.onPointerMove.dispatch(t),e.pop(fi.Up)){const{x:e,y:i}=t.startPos;this.onPointerUp.dispatch(t),e>=0&&i>=0&&(X(e,i,t.x,t.y)<this.pointerDistanceThreshold?this.onPointerTap.dispatch(t):this.onPointerSwipe.dispatch(t)),t.startPos.set(-1,-1)}e.pop(fi.Cancel)&&this.onPointerCancel.dispatch(t),e.pop(fi.Leave)&&(this.onPointerLeave.dispatch(t),delete this.pointers[t.id])}}}}class Ki{get duration(){return this._duration}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}constructor(t){this.onStart=new F,this.onStop=new F;const{duration:e,volume:i,playbackRate:s,loop:r,muted:n}=t;this._duration=e,this._volume=i,this._playbackRate=s,this._loop=r,this._muted=n}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:s,time:r,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==s&&(this.playbackRate=s),void 0!==r&&(this.currentTime=r),void 0!==n&&(this.muted=n),this}destroy(){this.stop(),this.onStart.destroy(),this.onStop.destroy()}}const Qi=["mousedown","touchstart","touchend"];let Zi=null,Ji=null,ts=!1,es=!1,is=!1;const ss=()=>"undefined"!=typeof document,rs=()=>Zi,ns=()=>{if("undefined"==typeof AudioContext)throw new Error("This environment does not support AudioContext.");return null===Zi&&(Zi=new AudioContext),Zi},os=()=>{if("undefined"==typeof OfflineAudioContext)throw new Error("This environment does not support OfflineAudioContext.");if(null===Ji){const t=ns();Ji=new OfflineAudioContext(1,2,t.sampleRate)}return Ji},as=()=>{const t=rs();t&&"running"===t.state&&!is&&(is=!0,(()=>{if(ts&&ss()){for(const t of Qi)document.removeEventListener(t,us,!1);ts=!1}})(),ds.dispatch(t))},hs=()=>{as()},ls=()=>{const t=ns();es||"function"!=typeof t.addEventListener||(t.addEventListener("statechange",hs),es=!0),as(),is||(()=>{if(!ts&&ss()){for(const t of Qi)document.addEventListener(t,us,!1);ts=!0}})()},us=()=>{const t=ns();"running"!==t.state?t.resume().then(()=>{as()}):as()};const ds=new class extends F{add(t,e){return super.add(t,e),ls(),this}once(t,e){return super.once(t,e),ls(),this}},cs=()=>{const t=ns();return ls(),t},ps=()=>{const t=rs();return null!==t&&"running"===t.state},_s=()=>os(),fs=async t=>os().decodeAudioData(t);class ms extends Ki{constructor(t,e){super(t),this._audioSetup=null,this._audioElement=t,e&&this.applyOptions(e),ps()?this.setupWithAudioContext(cs()):ds.once(this.setupWithAudioContext,this)}setVolume(t){const e=G(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._audioElement.loop=t),this}setPlaybackRate(t){const e=G(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._audioElement.playbackRate=e),this}getTime(){return this._audioElement.currentTime}setTime(t){return this._audioElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}get paused(){return this._audioElement.paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._audioElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._audioElement.pause(),this.onStop.dispatch()),this}destroy(){super.destroy(),ds.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._audioElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class gs extends Ki{get paused(){return this._paused}set paused(t){t?this.pause():this.play()}get analyserTarget(){return this._audioSetup?.gainNode??null}get poolSize(){return this._poolSize}set poolSize(t){this.setPoolSize(t)}constructor(t,e={}){super({duration:t.duration,volume:1,playbackRate:1,loop:!1,muted:!1}),this._pooledSources=[],this._queuedPooledPlays=[],this._sprites=new Map,this._audioSetup=null,this._paused=!0,this._startTime=0,this._currentTime=0,this._sourceNode=null,this._poolSize=1,this._audioBuffer=t;const{poolSize:i,sprites:s,...r}=e;this._poolSize=Math.max(1,Math.floor(i??1)),Object.keys(r).length>0&&this.applyOptions(r),s&&this.setSprites(s),ps()?this.setupWithAudioContext(cs()):ds.once(this.setupWithAudioContext,this)}setVolume(t){const e=G(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop=t,this._sourceNode&&(this._sourceNode.loop=t,t&&(this._sourceNode.loopStart=0,this._sourceNode.loopEnd=this.duration)),this}setPlaybackRate(t){return this._playbackRate=G(t,.1,20),this._sourceNode&&(this._sourceNode.playbackRate.value=this._playbackRate),this}getTime(){return this._audioSetup&&!this._paused&&this._sourceNode?this._currentTime+(this._audioSetup.audioContext.currentTime-this._startTime)*this._playbackRate:this._currentTime}setTime(t){const e=Math.max(0,t);return this.paused||!this._audioSetup?(this._currentTime=e,this):(this.pause(),this._currentTime=e,this.play(),this)}setMuted(t){if(this._muted=t,this._audioSetup){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}setPoolSize(t){const e=Math.max(1,Math.floor(t));return this._poolSize===e||(this._poolSize=e,this._trimPooledSources()),this}setSprites(t){this._sprites.clear();for(const[e,i]of Object.entries(t))this.defineSprite(e,i);return this}defineSprite(t,e){if(0===t.trim().length)throw new Error("Sound sprite names must be non-empty strings.");const i=e.start,s=e.end;if(!Number.isFinite(i)||i<0)throw new Error(`Sound sprite "${t}" has an invalid start time (${i}).`);if(!Number.isFinite(s)||s<=i)throw new Error(`Sound sprite "${t}" has an invalid end time (${s}).`);if(s>this.duration)throw new Error(`Sound sprite "${t}" ends at ${s}s, which exceeds sound duration ${this.duration}s.`);return this._sprites.set(t,{start:i,end:s,loop:e.loop??!1}),this}hasSprite(t){return this._sprites.has(t)}removeSprite(t){return this._sprites.delete(t),this}play(t){return t&&this.applyOptions(t),this._paused?(this._audioSetup&&this.createSourceNode(this._audioSetup),this._paused=!1,this.onStart.dispatch(),this):this}playPooled(t={}){const e=G(t.playbackRate??this._playbackRate,.1,20),i=Math.max(0,t.time??0),s=t.loop??!1;if(void 0!==t.volume&&this.setVolume(t.volume),void 0!==t.muted&&this.setMuted(t.muted),i>=this.duration)return this;const r=s?void 0:this.duration-i;return this._enqueuePooledPlay({offset:i,duration:r,loop:s,loopStart:0,loopEnd:this.duration,playbackRate:e}),this.onStart.dispatch(),this}playSprite(t,e={}){const i=this._sprites.get(t);if(!i)throw new Error(`Sound sprite "${t}" is not defined.`);const s=Math.max(0,e.time??0),r=i.start+s;if(r>=i.end)throw new Error(`Sound sprite "${t}" offset (${s}s) exceeds clip duration (${i.end-i.start}s).`);const n=e.loop??i.loop,o=G(e.playbackRate??this._playbackRate,.1,20);return void 0!==e.volume&&this.setVolume(e.volume),void 0!==e.muted&&this.setMuted(e.muted),this._enqueuePooledPlay({offset:r,duration:n?void 0:i.end-r,loop:n,loopStart:i.start,loopEnd:i.end,playbackRate:o}),this.onStart.dispatch(),this}stopPooled(){return this._pooledSources.length>0&&(this._stopPooledSources(),this.onStop.dispatch()),this._queuedPooledPlays.length=0,this}pause(t){if(t&&this.applyOptions(t),this._paused&&0===this._pooledSources.length)return this;if(!this._paused&&this._audioSetup){const t=this.duration,e=this.currentTime;this._currentTime=t>0?e%t:0}const e=this._pooledSources.length>0;this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0;const i=!this._paused||e;return this._paused=!0,i&&this.onStop.dispatch(),this}destroy(){super.destroy(),ds.clearByContext(this),this._audioSetup?.gainNode.disconnect(),this._stopPrimarySource(),this._stopPooledSources(),this._queuedPooledPlays.length=0,this._sprites.clear()}createSourceNode(t){const{audioContext:e}=t;this._stopPrimarySource();const i=this._createBufferSourceNode(t,{offset:Math.min(Math.max(0,this._currentTime),Math.max(0,this.duration)),duration:void 0,loop:this._loop,loopStart:0,loopEnd:this.duration,playbackRate:this._playbackRate});i.onended=()=>{this._sourceNode===i&&(this._sourceNode=null,this._startTime=0,this._currentTime=0,this._paused||(this._paused=!0,this.onStop.dispatch()))},this._sourceNode=i,this._startTime=e.currentTime}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination),this._audioSetup={audioContext:t,gainNode:e},this._paused||this.createSourceNode(this._audioSetup),this._flushQueuedPooledPlays()}_enqueuePooledPlay(t){this._audioSetup?this._playPooledNow(t):this._queuedPooledPlays.push(t)}_flushQueuedPooledPlays(){if(!this._audioSetup||0===this._queuedPooledPlays.length)return;const t=[...this._queuedPooledPlays];this._queuedPooledPlays.length=0;for(const e of t)this._playPooledNow(e)}_playPooledNow(t){if(!this._audioSetup)return;const e=this._createBufferSourceNode(this._audioSetup,t);e.onended=()=>{const t=this._pooledSources.indexOf(e);-1!==t&&this._pooledSources.splice(t,1),e.disconnect()},this._pooledSources.push(e),this._trimPooledSources()}_trimPooledSources(){for(;this._pooledSources.length>this._poolSize;){const t=this._pooledSources.shift();t&&(t.onended=null,this._stopSourceNode(t))}}_stopPrimarySource(){this._sourceNode&&(this._sourceNode.onended=null,this._stopSourceNode(this._sourceNode),this._sourceNode=null,this._startTime=0)}_stopPooledSources(){for(const t of this._pooledSources)t.onended=null,this._stopSourceNode(t);this._pooledSources.length=0}_stopSourceNode(t){try{t.stop(0)}catch{}t.disconnect()}_createBufferSourceNode(t,e){const{gainNode:i}=t,s=t.audioContext.createBufferSource();s.buffer=this._audioBuffer,s.loop=e.loop,s.playbackRate.value=e.playbackRate,e.loop&&(s.loopStart=e.loopStart??0,s.loopEnd=e.loopEnd??this.duration),s.connect(i);const r=e.duration;return!e.loop&&void 0!==r&&r>0?s.start(0,e.offset,r):s.start(0,e.offset),s}}class ys extends qe{constructor(t,e,i){super(new Ye(t,i)),this.onStart=new F,this.onStop=new F,this._volume=1,this._playbackRate=1,this._loop=!1,this._muted=!1,this._audioSetup=null,this._textureDirty=!0,this._lastVideoTime=Number.NaN,this._videoFrameCallbackHandle=null;const{duration:s,volume:r,playbackRate:n,loop:o,muted:a}=t;this._videoElement=t,this._duration=s,this._volume=r,this._playbackRate=n,this._loop=o,this._muted=a,this._onMetadataHandler=this._onVideoMetadataUpdated.bind(this),this._onResizeHandler=this._onVideoMetadataUpdated.bind(this),this._onVideoFrameHandler=this._onVideoFrame.bind(this),0!==this._videoElement.videoWidth&&0!==this._videoElement.videoHeight||(this._videoElement.addEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.addEventListener("resize",this._onResizeHandler)),e&&this.applyOptions(e),ps()?this.setupWithAudioContext(cs()):ds.once(this.setupWithAudioContext,this),this.updateTexture(),this._requestVideoFrameCallback()}get videoElement(){return this._videoElement}get duration(){return this._duration}get progress(){const t=this.currentTime,e=this.duration;return t%e/e}get volume(){return this._volume}set volume(t){this.setVolume(t)}get loop(){return this._loop}set loop(t){this.setLoop(t)}get playbackRate(){return this._playbackRate}set playbackRate(t){this.setPlaybackRate(t)}get currentTime(){return this.getTime()}set currentTime(t){this.setTime(t)}get muted(){return this._muted}set muted(t){this.setMuted(t)}get paused(){return this._videoElement.paused}set paused(t){t?this.pause():this.play()}get playing(){return!this.paused}set playing(t){t?this.play():this.pause()}get analyserTarget(){return this._audioSetup?.gainNode??null}play(t){return t&&this.applyOptions(t),this.paused&&(this._videoElement.play(),this.onStart.dispatch()),this}pause(t){return t&&this.applyOptions(t),this.playing&&(this._videoElement.pause(),this.onStop.dispatch()),this}stop(t){return this.pause(t),this.currentTime=0,this}toggle(t){return this.paused?this.play(t):this.pause(t)}applyOptions(t={}){const{volume:e,loop:i,playbackRate:s,time:r,muted:n}=t;return void 0!==e&&(this.volume=e),void 0!==i&&(this.loop=i),void 0!==s&&(this.playbackRate=s),void 0!==r&&(this.currentTime=r),void 0!==n&&(this.muted=n),this}setVolume(t){const e=G(t,0,2);if(this._volume===e)return this;if(this._volume=e,this._audioSetup){const{gainNode:t,audioContext:i}=this._audioSetup;t.gain.setTargetAtTime(this.muted?0:e,i.currentTime,10)}return this}setLoop(t){return this._loop!==t&&(this._loop=t,this._videoElement.loop=t),this}setPlaybackRate(t){const e=G(t,.1,20);return this._playbackRate!==e&&(this._playbackRate=e,this._videoElement.playbackRate=e),this}getTime(){return this._videoElement.currentTime}setTime(t){return this._videoElement.currentTime=Math.max(0,t),this}setMuted(t){if(this._muted!==t&&(this._muted=t,this._audioSetup)){const{gainNode:e,audioContext:i}=this._audioSetup;e.gain.setTargetAtTime(t?0:this.volume,i.currentTime,10)}return this}render(t){return this.visible&&(this._markTextureDirtyIfPlaybackAdvanced(),this.updateTexture(),super.render(t)),this}updateTexture(){const t=this.texture;if(!t||!this._videoElement)return this;if(0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return this;if(!this._textureDirty)return this;const e=this.textureFrame.width>0&&this.textureFrame.height>0;return t.updateSource(),t.width>0&&t.height>0&&this.setTextureFrame(re.temp.set(0,0,t.width,t.height),!e),this._textureDirty=!1,this}destroy(){super.destroy(),this.stop(),this._videoElement.removeEventListener("loadedmetadata",this._onMetadataHandler),this._videoElement.removeEventListener("resize",this._onResizeHandler),this._cancelVideoFrameCallback(),ds.clearByContext(this),this._audioSetup&&(this._audioSetup.sourceNode.disconnect(),this._audioSetup.gainNode.disconnect(),this._audioSetup=null),this.onStart.destroy(),this.onStop.destroy()}_onVideoMetadataUpdated(){this._textureDirty=!0,this.updateTexture()}_onVideoFrame(t,e){this._videoFrameCallbackHandle=null,this._textureDirty=!0,this._requestVideoFrameCallback()}_markTextureDirtyIfPlaybackAdvanced(){const t=this._videoElement.currentTime;this._lastVideoTime!==t&&(this._lastVideoTime=t,this._textureDirty=!0)}_requestVideoFrameCallback(){const t=this._videoElement;t.requestVideoFrameCallback&&null===this._videoFrameCallbackHandle&&(this._videoFrameCallbackHandle=t.requestVideoFrameCallback(this._onVideoFrameHandler))}_cancelVideoFrameCallback(){const t=this._videoElement;t.cancelVideoFrameCallback&&null!==this._videoFrameCallbackHandle&&(t.cancelVideoFrameCallback(this._videoFrameCallbackHandle),this._videoFrameCallbackHandle=null)}setupWithAudioContext(t){const e=t.createGain();e.gain.setTargetAtTime(this.muted?0:this.volume,t.currentTime,10),e.connect(t.destination);const i=t.createMediaElementSource(this._videoElement);i.connect(e),this._audioSetup={audioContext:t,gainNode:e,sourceNode:i}}}class xs{}class ws{}class vs{}class bs{}class Ts{constructor(){this._factories=new Map}register(t,e){this._factories.set(t,e)}resolve(t){let e,i=t;for(;null!==i&&!e;)if(e=this._factories.get(i),!e){const t=Object.getPrototypeOf(i.prototype);i=t?.constructor??null}if(!e)throw new Error(`No factory registered for ${t.name}. Register one with loader.register() before loading.`);return e}has(t){let e=t;for(;null!==e;){if(this._factories.has(e))return!0;const t=Object.getPrototypeOf(e.prototype);e=t?.constructor??null}return!1}destroy(){for(const t of this._factories.values())t.destroy();this._factories.clear()}}class Ss{constructor(){this._objectUrls=[]}createObjectUrl(t){const e=URL.createObjectURL(t);return this._objectUrls.push(e),e}revokeObjectUrl(t){URL.revokeObjectURL(t);const e=this._objectUrls.indexOf(t);-1!==e&&this._objectUrls.splice(e,1)}destroy(){for(const t of this._objectUrls)URL.revokeObjectURL(t);this._objectUrls.length=0}}class Cs extends Ss{constructor(){super(...arguments),this.storageName="font",this._addedFontFaces=[]}async process(t){return await t.arrayBuffer()}async create(t,e){if(!e?.family)throw new Error('FontFactory.create requires options with a "family" property.');const{family:i,descriptors:s,addToDocument:r}=e;if(t.byteLength<4)throw new SyntaxError(`Invalid font data: expected at least 4 bytes, received ${t.byteLength}.`);const n=await new FontFace(i,t,s).load().catch(()=>{throw new SyntaxError(`Invalid font data in ArrayBuffer (${t.byteLength} bytes).`)});return!1!==r&&(document.fonts.add(n),this._addedFontFaces.push(n)),n}destroy(){for(const t of this._addedFontFaces)document.fonts.delete(t);this._addedFontFaces.length=0,super.destroy()}}const Ms=[{mimeType:"image/x-icon",pattern:[0,0,1,0],mask:[255,255,255,255]},{mimeType:"image/x-icon",pattern:[0,0,2,0],mask:[255,255,255,255]},{mimeType:"image/bmp",pattern:[66,77],mask:[255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,55,97],mask:[255,255,255,255,255,255]},{mimeType:"image/gif",pattern:[71,73,70,56,57,97],mask:[255,255,255,255,255,255]},{mimeType:"image/webp",pattern:[82,73,70,70,0,0,0,0,87,69,66,80,86,80],mask:[255,255,255,255,0,0,0,0,255,255,255,255,255,255]},{mimeType:"image/png",pattern:[137,80,78,71,13,10,26,10],mask:[255,255,255,255,255,255,255,255]},{mimeType:"image/jpeg",pattern:[255,216,255],mask:[255,255,255]},{mimeType:"audio/basic",pattern:[46,115,110,100],mask:[255,255,255,255]},{mimeType:"audio/mpeg",pattern:[73,68,51],mask:[255,255,255]},{mimeType:"audio/wave",pattern:[82,73,70,70,0,0,0,0,87,65,86,69],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"audio/midi",pattern:[77,84,104,100,0,0,0,6],mask:[255,255,255,255,255,255,255,255]},{mimeType:"audio/aiff",pattern:[70,79,82,77,0,0,0,0,65,73,70,70],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"video/avi",pattern:[82,73,70,70,0,0,0,0,65,86,73,32],mask:[255,255,255,255,0,0,0,0,255,255,255,255]},{mimeType:"application/ogg",pattern:[79,103,103,83,0],mask:[255,255,255,255,255]}],Ps=t=>{const e=new Uint8Array(t);if(!e.length)throw new Error("Cannot determine mime type: No data.");for(const t of Ms)if(!(e.length<t.pattern.length)&&t.pattern.every((i,s)=>(e[s]&t.mask[s])===i))return t.mimeType;return(t=>{const e=new Uint8Array(t),i=new DataView(t).getUint32(0,!1);return!(e.length<Math.max(12,i)||i%4!=0)&&"ftypmp4"===String.fromCharCode(...e.subarray(4,11))})(t)?"video/mp4":(t=>{const e=new Uint8Array(t),i=[26,69,223,163].every((t,i)=>t===e[i]),s=e.subarray(4,4100),r=s.findIndex((t,e,i)=>66===i[e]&&130===i[e+1]);return!(!i||-1===r)&&"webm"===String.fromCharCode(...s.subarray(r+3,r+7))})(t)?"video/webm":(t=>{if(t.byteLength<12)return!1;const e=new Uint8Array(t);if("ftyp"!==String.fromCharCode(e[4],e[5],e[6],e[7]))return!1;const i=String.fromCharCode(e[8],e[9],e[10],e[11]);return"avif"===i||"avis"===i})(t)?"image/avif":"text/plain"};class Bs extends Ss{constructor(){super(...arguments),this.storageName="image"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=new Blob([t],{type:e.mimeType??Ps(t)}),s=this.createObjectUrl(i);return new Promise((t,e)=>{const i=new Image,r=()=>{this.revokeObjectUrl(s)};i.addEventListener("load",()=>{r(),t(i)},{once:!0}),i.addEventListener("error",()=>{r(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),e(Error("Image loading was canceled."))},{once:!0}),i.src=s})}}class Es extends Ss{constructor(){super(...arguments),this.storageName="json"}async process(t){return await t.json()}async create(t){return t}}const Rs={once:!0};class As extends Ss{constructor(){super(...arguments),this.storageName="music",this._audioElements=[]}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:s,playbackOptions:r}=e,n=new Blob([t],{type:i??Ps(t)});return new Promise((t,e)=>{const i=document.createElement("audio");this._audioElements.push(i),i.addEventListener("error",()=>e(Error("Error loading audio source.")),Rs),i.addEventListener("abort",()=>e(Error("Audio loading was canceled.")),Rs),i.addEventListener(s??"canplaythrough",()=>t(new ms(i,r)),Rs),i.preload="auto",i.src=this.createObjectUrl(n)})}destroy(){for(const t of this._audioElements)t.pause(),t.src="",t.load();this._audioElements.length=0,super.destroy()}}class ks extends Ss{constructor(){super(...arguments),this.storageName="sound"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const i=await fs(t);return new gs(i,{...e.playbackOptions,poolSize:e.poolSize,sprites:e.sprites})}}class Ls extends Ss{constructor(){super(...arguments),this.storageName="text"}async process(t){return await t.text()}async create(t){return t}}class Fs extends Ss{constructor(){super(...arguments),this.storageName="texture"}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,samplerOptions:s}=e,r=new Blob([t],{type:i??Ps(t)}),n=this.createObjectUrl(r);return new Promise((t,e)=>{const i=new Image,r=()=>{this.revokeObjectUrl(n)};i.addEventListener("load",()=>{r(),t(new Ye(i,s))},{once:!0}),i.addEventListener("error",()=>{r(),e(Error("Error loading image source."))},{once:!0}),i.addEventListener("abort",()=>{r(),e(Error("Image loading was canceled."))},{once:!0}),i.src=n})}}const Ds={once:!0};class Is extends Ss{constructor(){super(...arguments),this.storageName="video",this._videoElements=[]}async process(t){return await t.arrayBuffer()}async create(t,e={}){const{mimeType:i,loadEvent:s,playbackOptions:r,samplerOptions:n}=e,o=new Blob([t],{type:i??Ps(t)});return new Promise((t,e)=>{const i=document.createElement("video");this._videoElements.push(i),i.addEventListener("error",()=>e(Error("Video loading error.")),Ds),i.addEventListener("abort",()=>e(Error("Video loading error: cancelled.")),Ds),i.addEventListener("emptied",()=>e(Error("Video loading error: emptied.")),Ds),i.addEventListener(s??"canplaythrough",()=>t(new ys(i,r,n)),Ds),i.preload="auto",i.src=this.createObjectUrl(o)})}destroy(){for(const t of this._videoElements)t.pause(),t.src="",t.load();this._videoElements.length=0,super.destroy()}}class Ns extends Ss{constructor(){super(...arguments),this.storageName="svg"}async process(t){return await t.text()}async create(t){const e=new Blob([t],{type:"image/svg+xml"}),i=this.createObjectUrl(e);return new Promise((t,e)=>{const s=new Image,r=()=>{this.revokeObjectUrl(i)};s.addEventListener("load",()=>{r(),t(s)},{once:!0}),s.addEventListener("error",()=>{r(),e(Error("Error loading image source."))},{once:!0}),s.addEventListener("abort",()=>{r(),e(Error("Image loading was canceled."))},{once:!0}),s.src=i})}}class Us extends Ss{constructor(){super(...arguments),this.storageName="binary"}async process(t){return t.arrayBuffer()}async create(t){return t}}class Vs extends Ss{constructor(){super(...arguments),this.storageName="wasm"}async process(t){return t.arrayBuffer()}async create(t){return WebAssembly.compile(t)}}const Os=t=>{const e=t.split(":");let i=0;return i=3===e.length?3600*Number(e[0])+60*Number(e[1])+Number(e[2]):2===e.length?60*Number(e[0])+Number(e[1]):Number(e[0]),i};class Gs extends Ss{constructor(){super(...arguments),this.storageName="vtt"}async process(t){return t.text()}async create(t){const e=[],i=t.replace(/\r\n/g,"\n").replace(/\r/g,"\n").split("\n");let s=0;for(;s<i.length&&!i[s].includes("--\x3e");)s++;for(;s<i.length;){const t=i[s].trim();if(t.includes("--\x3e")){const r=t.indexOf("--\x3e"),n=t.slice(0,r).trim(),o=t.slice(r+3).trim().split(/\s+/)[0],a=Os(n),h=Os(o);s++;const l=[];for(;s<i.length&&""!==i[s].trim();)l.push(i[s]),s++;e.push(new VTTCue(a,h,l.join("\n")))}else s++}return e}}class zs extends Error{constructor(t,e){super(`Failed to load bundle "${t}" (${e.length} failure${1===e.length?"":"s"}).`),this.name="BundleLoadError",this.bundle=t,this.failures=e}}function Ws(t){return function(t){if(!qs(t))throw new Error("Invalid asset manifest: manifest must be an object.");if(!qs(t.bundles))throw new Error("Invalid asset manifest: manifest.bundles must be an object.");for(const[e,i]of Object.entries(t.bundles)){if(0===e.trim().length)throw new Error("Invalid asset manifest: bundle names must be non-empty strings.");if(!Array.isArray(i))throw new Error(`Invalid asset manifest: bundle "${e}" must be an array of entries.`);const t=new Map;i.forEach((i,s)=>{const r=`bundle "${e}" entry[${s}]`;if(!qs(i))throw new Error(`Invalid asset manifest: ${r} must be an object.`);if("function"!=typeof i.type)throw new Error(`Invalid asset manifest: ${r} has an invalid "type" token.`);Hs(i.alias,`${r} has an invalid "alias".`),Hs(i.path,`${r} has an invalid "path".`);const n=i.type,o=i.alias;t.has(n)||t.set(n,new Set);const a=t.get(n);if(a.has(o))throw new Error(`Invalid asset manifest: duplicate (${Xs(n)}, "${o}") in bundle "${e}".`);a.add(o)})}}(t),t}function qs(t){return"object"==typeof t&&null!==t}function Hs(t,e){if("string"!=typeof t||0===t.trim().length)throw new Error(`Invalid asset manifest: ${e}`)}function Xs(t){return t.name.length>0?t.name:"(anonymous type)"}class Ys{constructor(t={}){this._registry=new Ts,this._resources=new Map,this._manifest=new Map,this._bundles=new Map,this._inFlight=new Map,this._typeIds=new WeakMap,this._preventStoreKeys=new Set,this._nextTypeId=1,this._backgroundQueue=[],this._backgroundActive=0,this._backgroundTotal=0,this._backgroundLoaded=0,this._backgroundResolve=null,this.onProgress=new F,this.onBundleProgress=new F,this.onLoaded=new F,this.onError=new F,this._resourcePath=t.resourcePath??"",this._requestOptions=t.requestOptions??{},this._concurrency=t.concurrency??6,this._stores=t.cache?Array.isArray(t.cache)?t.cache:[t.cache]:[],this._registerBuiltinFactories()}register(t,e){return this._registry.register(t,e),this}add(t,e){const i=t;if("string"==typeof e)this._addManifestEntry(i,e,e);else if(Array.isArray(e))for(const t of e)this._addManifestEntry(i,t,t);else for(const[t,s]of Object.entries(e))this._addManifestEntry(i,t,s);return this}registerManifest(t){const e=Ws(t),i=new Map,s=new Array;for(const[t,r]of Object.entries(e.bundles)){if(this._bundles.has(t))throw new Error(`Bundle "${t}" is already registered.`);const e=new Array;for(const s of r){const r=s.type,n=this._key(r,s.alias),o=i.get(n)??this._getManifestEntry(r,s.alias);if(o&&!this._isManifestDefinitionEquivalent(o,s.path,s.options))throw new Error(`Conflicting asset definition for (${this._describeType(r)}, "${s.alias}") while registering bundle "${t}".`);i.set(n,{path:s.path,options:s.options}),e.push({type:r,alias:s.alias,path:s.path,options:s.options})}s.push([t,e])}for(const[t,e]of s){for(const t of e)this._addManifestEntry(t.type,t.alias,t.path,t.options);this._bundles.set(t,e)}return this}async loadBundle(t,e={}){const i=this._bundles.get(t);if(!i)throw new Error(`Unknown bundle "${t}".`);const s=i.length;let r=0;const n=new Array;if(0!==s){if(await Promise.all(i.map(async i=>{try{e.background?await this._loadSingleBackground(i.type,i.alias,i.path,i.options):await this._loadSingle(i.type,i.alias,i.options,i.path)}catch(t){n.push({type:i.type,alias:i.alias,error:this._normalizeError(t)})}finally{r++,this._emitBundleProgress(t,r,s,e.onProgress)}})),n.length>0)throw new zs(t,n)}else this._emitBundleProgress(t,0,0,e.onProgress)}hasBundle(t){const e=this._bundles.get(t);return!!e&&e.every(t=>this._hasResource(t.type,t.alias))}async load(t,e,i){const s=t;if("string"==typeof e)return this._loadSingle(s,e,i);if(Array.isArray(e))return Promise.all(e.map(t=>this._loadSingle(s,t,i)));const r=Object.entries(e),n={};return await Promise.all(r.map(async([t,e])=>{n[t]=await this._loadSingle(s,t,i,e)})),n}backgroundLoad(){for(const[t,e]of this._manifest)for(const[i,s]of e){if(this._hasResource(t,i))continue;const e=this._key(t,i);this._inFlight.has(e)||this._backgroundQueue.push({type:t,alias:i,path:s.path,options:s.options})}this._backgroundTotal=this._backgroundQueue.length,this._backgroundLoaded=0,this._drainBackground()}loadAll(){return new Promise(t=>{this._backgroundResolve=t,this.backgroundLoad(),0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundResolve=null,t())})}setConcurrency(t){return this._concurrency=t,this}get(t,e){const i=t,s=this._resources.get(i);if(!s?.has(e))throw new Error(`Missing resource "${e}" for type ${i.name}.`);return s.get(e)}peek(t,e){const i=t;return this._resources.get(i)?.get(e)??null}has(t,e){const i=t;return this._resources.get(i)?.has(e)??!1}unload(t,e){const i=t,s=this._key(i,e);return this._resources.get(i)?.delete(e),this._inFlight.has(s)&&this._preventStoreKeys.add(s),this}unloadAll(t){if(t)this._resources.get(t)?.clear();else for(const t of this._resources.values())t.clear();return this}get resourcePath(){return this._resourcePath}set resourcePath(t){this._resourcePath=t}get requestOptions(){return this._requestOptions}set requestOptions(t){this._requestOptions=t}destroy(){this._registry.destroy();for(const t of this._stores)t.destroy();this._resources.clear(),this._manifest.clear(),this._bundles.clear(),this._inFlight.clear(),this._preventStoreKeys.clear(),this._backgroundQueue.length=0,this.onProgress.destroy(),this.onBundleProgress.destroy(),this.onLoaded.destroy(),this.onError.destroy()}async _loadSingle(t,e,i,s){if(this._hasResource(t,e))return this._resources.get(t).get(e);const r=this._key(t,e);if(this._inFlight.has(r))return this._inFlight.get(r);if(this._boostFromQueue(t,e),this._inFlight.has(r))return this._inFlight.get(r);const n=this._getManifestEntry(t,e),o=s??n?.path??e,a=i??n?.options;return this._trackInFlight(r,this._fetch(t,e,o,a))}_loadSingleBackground(t,e,i,s){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const r=this._key(t,e),n=this._inFlight.get(r);if(n)return n;this._isQueuedInBackground(t,e)||(0===this._backgroundQueue.length&&0===this._backgroundActive&&(this._backgroundLoaded=0,this._backgroundTotal=0),this._backgroundQueue.push({type:t,alias:e,path:i,options:s}),this._backgroundTotal++),this._drainBackground();const o=this._inFlight.get(r);return o||this._waitForBackgroundEntry(t,e)}async _fetch(t,e,i,s){const r=this._registry.resolve(t),n=this._resolveUrl(i);let o=null;for(const i of this._stores)if(o=await i.load(r.storageName,e),null!=o)try{const i=await r.create(o,s);return this._storeResource(t,e,i),i}catch{await i.delete(r.storageName,e),o=null}const a=await fetch(n,this._requestOptions);if(!a.ok)throw new Error(`Failed to fetch "${e}" from "${n}" (${a.status} ${a.statusText}).`);o=await r.process(a);const h=await r.create(o,s).catch(t=>{const i=t instanceof Error?t.message:String(t);throw new Error(`Failed to create "${e}" from "${n}": ${i}`)});for(const t of this._stores)try{await t.save(r.storageName,e,o)}catch{}return this._storeResource(t,e,h),h}_drainBackground(){for(;this._backgroundActive<this._concurrency&&this._backgroundQueue.length>0;){const t=this._backgroundQueue.shift(),e=this._key(t.type,t.alias);this._hasResource(t.type,t.alias)||this._inFlight.has(e)?(this._backgroundLoaded++,this._onBackgroundItemDone()):this._startBackgroundEntry(t)}}_boostFromQueue(t,e){const i=this._backgroundQueue.findIndex(i=>i.type===t&&i.alias===e);if(-1===i)return;const[s]=this._backgroundQueue.splice(i,1);this._startBackgroundEntry(s)}_isQueuedInBackground(t,e){return this._backgroundQueue.some(i=>i.type===t&&i.alias===e)}_waitForBackgroundEntry(t,e){if(this._hasResource(t,e))return Promise.resolve(this._resources.get(t).get(e));const i=this._key(t,e),s=this._inFlight.get(i);return s||new Promise((s,r)=>{const n=(i,r,n)=>{i===t&&r===e&&(a(),s(n))},o=(i,s,n)=>{i===t&&s===e&&(a(),r(n))},a=()=>{this.onLoaded.remove(n),this.onError.remove(o)};this.onLoaded.add(n),this.onError.add(o);const h=this._inFlight.get(i);if(h)return a(),void h.then(s,r);this._hasResource(t,e)&&(a(),s(this._resources.get(t).get(e)))})}_onBackgroundItemDone(){if(this.onProgress.dispatch(this._backgroundLoaded,this._backgroundTotal),this._backgroundResolve&&0===this._backgroundQueue.length&&0===this._backgroundActive){const t=this._backgroundResolve;this._backgroundResolve=null,t()}}_startBackgroundEntry(t){const e=this._key(t.type,t.alias);this._backgroundActive++,this._trackInFlight(e,this._fetch(t.type,t.alias,t.path,t.options)).catch(e=>{const i=e instanceof Error?e:new Error(String(e));this.onError.dispatch(t.type,t.alias,i)}).finally(()=>{this._backgroundActive--,this._backgroundLoaded++,this._onBackgroundItemDone(),this._drainBackground()})}_trackInFlight(t,e){const i=e.finally(()=>{this._inFlight.delete(t),this._preventStoreKeys.delete(t)});return this._inFlight.set(t,i),i}_emitBundleProgress(t,e,i,s){this.onBundleProgress.dispatch(t,e,i),s&&s(e,i)}_addManifestEntry(t,e,i,s){this._manifest.has(t)||this._manifest.set(t,new Map),this._manifest.get(t).set(e,{path:i,options:s})}_getManifestEntry(t,e){return this._manifest.get(t)?.get(e)}_isManifestDefinitionEquivalent(t,e,i){return t.path===e&&this._areOptionsEquivalent(t.options,i)}_areOptionsEquivalent(t,e){if(Object.is(t,e))return!0;if(typeof t!=typeof e)return!1;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this._areOptionsEquivalent(t[i],e[i]))return!1;return!0}const i=Object.getPrototypeOf(t);if(i!==Object.getPrototypeOf(e))return!1;if(i!==Object.prototype&&null!==i)return!1;const s=t,r=e,n=Object.keys(s),o=Object.keys(r);if(n.length!==o.length)return!1;for(const t of n){if(!Object.prototype.hasOwnProperty.call(r,t))return!1;if(!this._areOptionsEquivalent(s[t],r[t]))return!1}return!0}_normalizeError(t){return t instanceof Error?t:new Error(String(t))}_describeType(t){return t.name.length>0?t.name:"(anonymous type)"}_hasResource(t,e){return this._resources.get(t)?.has(e)??!1}_storeResource(t,e,i){const s=this._key(t,e);this._preventStoreKeys.delete(s)||(this._resources.has(t)||this._resources.set(t,new Map),this._resources.get(t).set(e,i),this.onLoaded.dispatch(t,e,i))}_key(t,e){let i=this._typeIds.get(t);return void 0===i&&(i=this._nextTypeId++,this._typeIds.set(t,i)),`${i}:${e}`}_resolveUrl(t){return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("//")?t:`${this._resourcePath}${t}`}_registerBuiltinFactories(){this._registry.register(Ye,new Fs),this._registry.register(gs,new ks),this._registry.register(ms,new As),this._registry.register(ys,new Is),this._registry.register(xs,new Es),this._registry.register(ws,new Ls),this._registry.register(vs,new Ns),this._registry.register(bs,new Gs),this._registry.register(ArrayBuffer,new Us),"undefined"!=typeof FontFace&&this._registry.register(FontFace,new Cs),"undefined"!=typeof HTMLImageElement&&this._registry.register(HTMLImageElement,new Bs),"undefined"!=typeof WebAssembly&&this._registry.register(WebAssembly.Module,new Vs)}}var js;!function(t){t[t.Loading=1]="Loading",t[t.Running=2]="Running",t[t.Halting=3]="Halting",t[t.Stopped=4]="Stopped"}(js||(js={}));const $s={type:"auto"},Ks={width:800,height:600,clearColor:K.cornflowerBlue,debug:!1,spriteRendererBatchSize:4096,particleRendererBatchSize:8192,primitiveRendererBatchSize:65536,gamepadDefinitions:[],pointerDistanceThreshold:10,webglAttributes:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,stencil:!1,depth:!1},resourcePath:"",requestOptions:{method:"GET",mode:"cors",cache:"default"},cache:void 0,backend:$s};class Qs{constructor(t){this.onResize=new F,this._startupClock=new L,this._activeClock=new L,this._frameClock=new L,this._status=js.Stopped,this._frameCount=0,this._frameRequest=0,this.options={canvas:t?.canvas??document.createElement("canvas"),...Ks,...t,backend:t?.backend??$s},this.canvas=this.options.canvas,this.canvas.hasAttribute("tabindex")||this.canvas.setAttribute("tabindex","-1"),this.loader=new Ys({resourcePath:this.options.resourcePath,requestOptions:this.options.requestOptions,cache:this.options.cache}),this._backendType=this.resolveInitialBackendType(),this._renderManager=this.createRenderManager(this._backendType),this.inputManager=new $i(this),this.sceneManager=new ve(this),this._updateHandler=this.update.bind(this),this._startupClock.start()}get status(){return this._status}get startupTime(){return this._startupClock.elapsedTime}get activeTime(){return this._activeClock.elapsedTime}get frameTime(){return this._frameClock.elapsedTime}get frameCount(){return this._frameCount}get renderManager(){return this._renderManager}async start(t){if(this._status===js.Stopped){this._status=js.Loading;try{await this.initializeRenderManager(),await this.sceneManager.setScene(t),this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._activeClock.start(),this._status=js.Running}catch(t){throw this._status=js.Stopped,t}}return this}update(){if(this._status===js.Running){const t=this._frameClock.elapsedTime,e=performance.now();this.renderManager.resetStats(),this.inputManager.update();const i=this.renderManager.view;i&&"function"==typeof i.update&&i.update(t.milliseconds),this.sceneManager.update(t),this.renderManager.flush(),this.renderManager.stats.frameTimeMs=performance.now()-e,this._frameRequest=requestAnimationFrame(this._updateHandler),this._frameClock.restart(),this._frameCount++}return this}stop(){return this._status===js.Running&&(this._status=js.Halting,cancelAnimationFrame(this._frameRequest),this.sceneManager.setScene(null).catch(t=>{console.error("Application.stop() failed to unload the active scene.",t)}),this._activeClock.stop(),this._frameClock.stop(),this._status=js.Stopped),this}resize(t,e){return this.renderManager.resize(t,e),this.onResize.dispatch(t,e,this),this}destroy(){this.stop(),this.loader.destroy(),this.inputManager.destroy(),this._renderManager.destroy(),this.sceneManager.destroy(),this._startupClock.destroy(),this._activeClock.destroy(),this._frameClock.destroy(),this.onResize.destroy()}resolveInitialBackendType(){const t=this.options.backend?.type;return"webgl2"===t?"webgl2":"webgpu"===t||this.canUseWebGpu()?"webgpu":"webgl2"}createRenderManager(t){return"webgpu"===t?new ci(this):new Je(this)}async initializeRenderManager(){try{await this._renderManager.initialize()}catch(t){if("auto"!==this.options.backend?.type||"webgpu"!==this._backendType)throw t;this._renderManager.destroy(),this._backendType="webgl2",this._renderManager=this.createRenderManager(this._backendType),await this._renderManager.initialize()}}canUseWebGpu(){return!!navigator.gpu}}class Zs{constructor(t,e=0){this._quadTrees=new Map,this._sceneNodes=new Set,this._bounds=t.clone(),this.level=e}addSceneNode(t){const e=this._getQuadTree(t);return e?(e.addSceneNode(t),this):(this._sceneNodes.add(t),this._sceneNodes.size>Zs.maxSceneNodes&&this.level<Zs.maxLevel&&this._split(),this)}getRelatedChildren(t){const e=this._getQuadTree(t);return null===e?[...this._sceneNodes]:[...e.getRelatedChildren(t),...this._sceneNodes]}getBounds(){return this._bounds}clear(){if(this._quadTrees.size>0){for(const t of this._quadTrees.values())t.destroy();this._quadTrees.clear()}return this._sceneNodes.clear(),this}destroy(){this.clear(),this._bounds.destroy()}_getQuadTree(t){if(this._quadTrees.size>0){const e=t.getBounds();for(const t of this._quadTrees.values())if(t.getBounds().containsRect(e))return t}return null}_split(){if(0===this._quadTrees.size){const{top:t,left:e,width:i,height:s}=this.getBounds(),r=i/2|0,n=s/2|0,o=this.level+1;this._quadTrees.set(0,new Zs(re.temp.set(e,t,r,n),o)),this._quadTrees.set(1,new Zs(re.temp.set(e+r,t,r,n),o)),this._quadTrees.set(2,new Zs(re.temp.set(e,t+n,r,n),o)),this._quadTrees.set(3,new Zs(re.temp.set(e+r,t+n,r,n),o))}this._passSceneNodesToQuadTrees()}_passSceneNodesToQuadTrees(){for(const t of this._sceneNodes){const e=this._getQuadTree(t);e&&(this._sceneNodes.delete(t),e.addSceneNode(t))}}}Zs.maxSceneNodes=50,Zs.maxLevel=5;class Js extends me{constructor(){super(...arguments),this._children=[],this._sortableChildren=!1,this._sortDirty=!1,this._nextChildOrder=0}get children(){return this._children}get sortableChildren(){return this._sortableChildren}set sortableChildren(t){this._sortableChildren!==t&&(this._sortableChildren=t,this._sortDirty=t)}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this.scale.x=t/this.bounds.width}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this.scale.y=t/this.bounds.height}get left(){return this.x-this.width*this.origin.x}get top(){return this.y-this.height*this.origin.y}get right(){return this.x+this.width-this.origin.x}get bottom(){return this.y+this.height-this.origin.y}addChild(...t){for(const e of t)this.addChildAt(e,this._children.length);return this}addChildAt(t,e){if(e<0||e>this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return t===this||(t.parentNode&&t.parentNode.removeChild(t),t.parentNode=this,t.setChildOrder(this._nextChildOrder++),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache()),this}swapChildren(t,e){if(t!==e){const i=this.getChildIndex(t),s=this.getChildIndex(e);this._children[i]=e,this._children[s]=t,this.markSortDirty(),this.invalidateCache()}return this}getChildIndex(t){const e=this._children.indexOf(t);if(-1===e)throw new Error("Drawable is not a child of the container.");return e}setChildIndex(t,e){if(e<0||e>=this._children.length)throw new Error(`The index ${e} is out of bounds ${this._children.length}`);return B(this._children,this.getChildIndex(t),1),this._children.splice(e,0,t),this.markSortDirty(),this.invalidateCache(),this}getChildAt(t){if(t<0||t>=this._children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this._children[t]}removeChild(t){const e=this._children.indexOf(t);return-1!==e&&this.removeChildAt(e),this}removeChildAt(t){const e=this._children[t];return B(this._children,t,1),e&&e.parentNode===this&&(e.parentNode=null),this.markSortDirty(),this.invalidateCache(),this}removeChildren(t=0,e=this._children.length){const i=e-t;if(i<0||i>e)throw new Error("Values are outside the acceptable range.");for(let i=t;i<e;i++){const t=this._children[i];t&&t.parentNode===this&&(t.parentNode=null)}return B(this._children,t,i),this.markSortDirty(),this.invalidateCache(),this}render(t){return this.visible&&0!==this._children.length?this.inView(t.view)?(this.renderVisualContent(t,()=>{this._sortChildrenIfNeeded();for(const e of this._children)e.render(t)}),this):(t.stats.culledNodes++,this):this}contains(t,e){return this._children.some(i=>i.contains(t,e))}updateBounds(){this._bounds.reset().addRect(this.getLocalBounds(),this.getGlobalTransform());for(const t of this._children)t.visible&&this._bounds.addRect(t.getBounds());return this}destroy(){this.removeChildren(),super.destroy()}markSortDirty(){return this._sortableChildren&&(this._sortDirty=!0),this}sortChildren(){return!this._sortableChildren||!this._sortDirty||this._children.length<=1?(this._sortDirty=!1,this):(this._children.sort((t,e)=>t.zIndex===e.zIndex?t.childOrder-e.childOrder:t.zIndex-e.zIndex),this._sortDirty=!1,this.invalidateCache(),this)}_sortChildrenIfNeeded(){this._sortableChildren&&this._sortDirty&&this.sortChildren()}}class tr{static create(t){return Object.assign(new tr,t)}constructor(){this._app=null,this._root=new Js,this._stackMode="overlay",this._inputMode="capture"}get app(){return this._app}set app(t){this._app=t}get root(){return this._root}get stackMode(){return this._stackMode}set stackMode(t){this._stackMode=t}get inputMode(){return this._inputMode}set inputMode(t){this._inputMode=t}addChild(t){return this._root.addChild(t),this}removeChild(t){return this._root.removeChild(t),this}setParticipationPolicy(t){return t.mode&&(this._stackMode=t.mode),t.input&&(this._inputMode=t.input),this}getParticipationPolicy(){return{mode:this._stackMode,input:this._inputMode}}load(t){}init(t){}update(t){}draw(t){}handleInput(t){}unload(t){}destroy(){this._root.destroy(),this._app=null}}class er extends L{constructor(t,e=!1){super(),this._limit=t.clone(),e&&this.restart()}set limit(t){this._limit.copy(t)}get expired(){return this.elapsedMilliseconds>=this._limit.milliseconds}get remainingMilliseconds(){return Math.max(0,this._limit.milliseconds-this.elapsedMilliseconds)}get remainingSeconds(){return this.remainingMilliseconds/r.seconds}get remainingMinutes(){return this.remainingMilliseconds/r.minutes}get remainingHours(){return this.remainingMilliseconds/r.hours}}class ir{constructor(t,e={}){this._analyser=null,this._audioContext=null,this._analyserTarget=null;const{fftSize:i,minDecibels:s,maxDecibels:r,smoothingTimeConstant:n}=e;this._media=t,this._fftSize=i??2048,this._minDecibels=s??-100,this._maxDecibels=r??-30,this._smoothingTimeConstant=n??.8,this._frequencyBinCount=this._fftSize/2,this._timeDomainData=new Uint8Array(this._frequencyBinCount),this._frequencyData=new Uint8Array(this._frequencyBinCount),this._preciseTimeDomainData=new Float32Array(this._frequencyBinCount),this._preciseFrequencyData=new Float32Array(this._frequencyBinCount),ps()?this.setupWithAudioContext(cs()):ds.once(this.setupWithAudioContext,this)}connect(){if(!this._analyser||null!==this._analyserTarget)return this;const t=this._media.analyserTarget;if(!t)throw new Error("No AudioNode on property analyserTarget.");return this._analyserTarget=t,t.connect(this._analyser),this}get timeDomainData(){return this._analyser&&(this.connect(),this._analyser.getByteTimeDomainData(this._timeDomainData)),this._timeDomainData}get frequencyData(){return this._analyser&&(this.connect(),this._analyser.getByteFrequencyData(this._frequencyData)),this._frequencyData}get preciseTimeDomainData(){return this._analyser&&(this.connect(),this._analyser.getFloatTimeDomainData(this._preciseTimeDomainData)),this._preciseTimeDomainData}get preciseFrequencyData(){return this._analyser&&(this.connect(),this._analyser.getFloatFrequencyData(this._preciseFrequencyData)),this._preciseFrequencyData}destroy(){ds.clearByContext(this),this._analyserTarget?.disconnect(),this._analyser?.disconnect()}setupWithAudioContext(t){this._audioContext=t,this._analyser=t.createAnalyser(),this._analyser.fftSize=this._fftSize,this._analyser.minDecibels=this._minDecibels,this._analyser.maxDecibels=this._maxDecibels,this._analyser.smoothingTimeConstant=this._smoothingTimeConstant}}const sr=new Map([["DPad",[.22,.58]],["DPadUp",[.22,.5]],["DPadDown",[.22,.66]],["DPadLeft",[.14,.58]],["DPadRight",[.3,.58]],["ButtonNorth",[.78,.5]],["ButtonWest",[.7,.58]],["ButtonEast",[.86,.58]],["ButtonSouth",[.78,.66]],["LeftShoulder",[.28,.28]],["RightShoulder",[.72,.28]],["LeftTrigger",[.2,.16]],["RightTrigger",[.8,.16]],["Select",[.46,.5]],["Start",[.54,.5]],["LeftStick",[.38,.66]],["RightStick",[.62,.66]]]),rr=new Map([["ButtonNorth",gi.ButtonNorth],["ButtonWest",gi.ButtonWest],["ButtonEast",gi.ButtonEast],["ButtonSouth",gi.ButtonSouth],["LeftShoulder",gi.LeftShoulder],["RightShoulder",gi.RightShoulder],["LeftTrigger",gi.LeftTrigger],["RightTrigger",gi.RightTrigger],["Select",gi.Select],["Start",gi.Start],["LeftStick",gi.LeftStick],["RightStick",gi.RightStick],["DPadUp",gi.DPadUp],["DPadDown",gi.DPadDown],["DPadLeft",gi.DPadLeft],["DPadRight",gi.DPadRight]]),nr=new Map([["ButtonNorth","North"],["ButtonWest","West"],["ButtonEast","East"],["ButtonSouth","South"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Select"],["Start","Start"],["LeftStick","L3"],["RightStick","R3"]]),or=new Map([["ButtonNorth","Y"],["ButtonWest","X"],["ButtonEast","B"],["ButtonSouth","A"],["LeftShoulder","LB"],["RightShoulder","RB"],["LeftTrigger","LT"],["RightTrigger","RT"],["Select","View"],["Start","Menu"],["LeftStick","L3"],["RightStick","R3"]]),ar=new Map([["ButtonNorth","Triangle"],["ButtonWest","Square"],["ButtonEast","Circle"],["ButtonSouth","Cross"],["LeftShoulder","L1"],["RightShoulder","R1"],["LeftTrigger","L2"],["RightTrigger","R2"],["Select","Create"],["Start","Options"],["LeftStick","L3"],["RightStick","R3"]]),hr=new Map([["ButtonNorth","X"],["ButtonWest","Y"],["ButtonEast","A"],["ButtonSouth","B"],["LeftShoulder","L"],["RightShoulder","R"],["LeftTrigger","ZL"],["RightTrigger","ZR"],["Select","Minus"],["Start","Plus"],["LeftStick","L3"],["RightStick","R3"]]),lr=new Map([[yi.GenericDualAnalog,nr],[yi.Xbox,or],[yi.PlayStation,ar],[yi.SwitchPro,hr],[yi.JoyConLeft,hr],[yi.JoyConRight,hr],[yi.GameCube,nr],[yi.SteamController,nr],[yi.ArcadeStick,nr]]);class ur{static getControlPosition(t){return sr.get(t)??[.5,.5]}static getControlLabels(t){return lr.get(t)??nr}static buildControlChannelMap(){return rr}}ur.controls=["DPad","DPadUp","DPadDown","DPadLeft","DPadRight","ButtonNorth","ButtonWest","ButtonEast","ButtonSouth","LeftShoulder","RightShoulder","LeftTrigger","RightTrigger","Select","Start","LeftStick","RightStick"];class dr{constructor(t,{onStart:e,onStop:i,onActive:s,onTrigger:r,context:n,threshold:o}={}){this.channels=new Set,this.valueState=0,this.onStart=new F,this.onStop=new F,this.onActive=new F,this.onTrigger=new F,this.channels=new Set(Array.isArray(t)?t:[t]),this.triggerTimer=new er(T(o??dr.triggerThreshold)),e&&this.onStart.add(e,n),i&&this.onStop.add(i,n),s&&this.onActive.add(s,n),r&&this.onTrigger.add(r,n)}get activeChannels(){return this.channels}get value(){return this.valueState}update(t){this.valueState=0;for(const e of this.channels)this.valueState=Math.max(t[e],this.valueState);return this.valueState?(this.triggerTimer.running||(this.triggerTimer.restart(),this.onStart.dispatch(this.valueState)),this.onActive.dispatch(this.valueState)):this.triggerTimer.running&&(this.onStop.dispatch(this.valueState),this.triggerTimer.expired||this.onTrigger.dispatch(this.valueState),this.triggerTimer.stop()),this}destroy(){this.channels.clear(),this.triggerTimer.destroy(),this.onStart.destroy(),this.onStop.destroy(),this.onActive.destroy(),this.onTrigger.destroy()}}function cr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}dr.triggerThreshold=300;var pr,_r={exports:{}};var fr=function(){if(pr)return _r.exports;function t(t,i,r){r=r||2;var n,o,a,u,d,p,_,f=i&&i.length,m=f?i[0]*r:t.length,g=e(t,0,m,r,!0),y=[];if(!g||g.next===g.prev)return y;if(f&&(g=function(t,i,s,r){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*r,n<o-1?i[n+1]*r:t.length,r,!1))===a.next&&(a.steiner=!0),u.push(c(a));for(u.sort(h),n=0;n<u.length;n++)s=l(u[n],s);return s}(t,i,g,r)),t.length>80*r){n=a=t[0],o=u=t[1];for(var x=r;x<m;x+=r)(d=t[x])<n&&(n=d),(p=t[x+1])<o&&(o=p),d>a&&(a=d),p>u&&(u=p);_=0!==(_=Math.max(a-n,u-o))?32767/_:0}return s(g,y,r,n,o,_,0),y}function e(t,e,i,s,r){var n,o;if(r===C(t,e,i,s)>0)for(n=e;n<i;n+=s)o=b(n,t[n],t[n+1],o);else for(n=i-s;n>=e;n-=s)o=b(n,t[n],t[n+1],o);return o&&m(o,o.next)&&(T(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!m(s,s.next)&&0!==f(s.prev,s,s.next))s=s.next;else{if(T(s),(s=e=s.prev)===s.next)break;i=!0}}while(i||s!==e);return e}function s(t,e,h,l,u,c,p){if(t){!p&&c&&function(t,e,i,s){var r=t;do{0===r.z&&(r.z=d(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){var e,i,s,r,n,o,a,h,l=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,s=i,a=0,e=0;e<l&&(a++,s=s.nextZ);e++);for(h=l;a>0||h>0&&s;)0!==a&&(0===h||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,h--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;i=s}n.nextZ=null,l*=2}while(o>1)}(r)}(t,l,u,c);for(var _,f,m=t;t.prev!==t.next;)if(_=t.prev,f=t.next,c?n(t,l,u,c):r(t))e.push(_.i/h|0),e.push(t.i/h|0),e.push(f.i/h|0),T(t),t=f.next,m=f.next;else if((t=f)===m){p?1===p?s(t=o(i(t),e,h),e,h,l,u,c,2):2===p&&a(t,e,h,l,u,c):s(i(t),e,h,l,u,c,1);break}}}function r(t){var e=t.prev,i=t,s=t.next;if(f(e,i,s)>=0)return!1;for(var r=e.x,n=i.x,o=s.x,a=e.y,h=i.y,l=s.y,u=r<n?r<o?r:o:n<o?n:o,d=a<h?a<l?a:l:h<l?h:l,c=r>n?r>o?r:o:n>o?n:o,_=a>h?a>l?a:l:h>l?h:l,m=s.next;m!==e;){if(m.x>=u&&m.x<=c&&m.y>=d&&m.y<=_&&p(r,a,n,h,o,l,m.x,m.y)&&f(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function n(t,e,i,s){var r=t.prev,n=t,o=t.next;if(f(r,n,o)>=0)return!1;for(var a=r.x,h=n.x,l=o.x,u=r.y,c=n.y,_=o.y,m=a<h?a<l?a:l:h<l?h:l,g=u<c?u<_?u:_:c<_?c:_,y=a>h?a>l?a:l:h>l?h:l,x=u>c?u>_?u:_:c>_?c:_,w=d(m,g,e,i,s),v=d(y,x,e,i,s),b=t.prevZ,T=t.nextZ;b&&b.z>=w&&T&&T.z<=v;){if(b.x>=m&&b.x<=y&&b.y>=g&&b.y<=x&&b!==r&&b!==o&&p(a,u,h,c,l,_,b.x,b.y)&&f(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,T.x>=m&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&p(a,u,h,c,l,_,T.x,T.y)&&f(T.prev,T,T.next)>=0)return!1;T=T.nextZ}for(;b&&b.z>=w;){if(b.x>=m&&b.x<=y&&b.y>=g&&b.y<=x&&b!==r&&b!==o&&p(a,u,h,c,l,_,b.x,b.y)&&f(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;T&&T.z<=v;){if(T.x>=m&&T.x<=y&&T.y>=g&&T.y<=x&&T!==r&&T!==o&&p(a,u,h,c,l,_,T.x,T.y)&&f(T.prev,T,T.next)>=0)return!1;T=T.nextZ}return!0}function o(t,e,s){var r=t;do{var n=r.prev,o=r.next.next;!m(n,o)&&g(n,r,r.next,o)&&w(n,o)&&w(o,n)&&(e.push(n.i/s|0),e.push(r.i/s|0),e.push(o.i/s|0),T(r),T(r.next),r=t=o),r=r.next}while(r!==t);return i(r)}function a(t,e,r,n,o,a){var h=t;do{for(var l=h.next.next;l!==h.prev;){if(h.i!==l.i&&_(h,l)){var u=v(h,l);return h=i(h,h.next),u=i(u,u.next),s(h,e,r,n,o,a,0),void s(u,e,r,n,o,a,0)}l=l.next}h=h.next}while(h!==t)}function h(t,e){return t.x-e.x}function l(t,e){var s=function(t,e){var i,s=e,r=t.x,n=t.y,o=-1/0;do{if(n<=s.y&&n>=s.next.y&&s.next.y!==s.y){var a=s.x+(n-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>o&&(o=a,i=s.x<s.next.x?s:s.next,a===r))return i}s=s.next}while(s!==e);if(!i)return null;var h,l=i,d=i.x,c=i.y,_=1/0;s=i;do{r>=s.x&&s.x>=d&&r!==s.x&&p(n<c?r:o,n,d,c,n<c?o:r,n,s.x,s.y)&&(h=Math.abs(n-s.y)/(r-s.x),w(s,t)&&(h<_||h===_&&(s.x>i.x||s.x===i.x&&u(i,s)))&&(i=s,_=h)),s=s.next}while(s!==l);return i}(t,e);if(!s)return e;var r=v(s,t);return i(r,r.next),i(s,s.next)}function u(t,e){return f(t.prev,t,e.prev)<0&&f(e.next,t,t.next)<0}function d(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function c(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function p(t,e,i,s,r,n,o,a){return(r-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(s-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(r-o)*(s-a)}function _(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&g(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(w(t,e)&&w(e,t)&&function(t,e){var i=t,s=!1,r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(f(t.prev,t,e.prev)||f(t,e.prev,e))||m(t,e)&&f(t.prev,t,t.next)>0&&f(e.prev,e,e.next)>0)}function f(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function m(t,e){return t.x===e.x&&t.y===e.y}function g(t,e,i,s){var r=x(f(t,e,i)),n=x(f(t,e,s)),o=x(f(i,s,t)),a=x(f(i,s,e));return r!==n&&o!==a||(!(0!==r||!y(t,i,e))||(!(0!==n||!y(t,s,e))||(!(0!==o||!y(i,t,s))||!(0!==a||!y(i,e,s)))))}function y(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function w(t,e){return f(t.prev,t,t.next)<0?f(t,e,t.next)>=0&&f(t,t.prev,e)>=0:f(t,e,t.prev)<0||f(t,t.next,e)<0}function v(t,e){var i=new S(t.i,t.x,t.y),s=new S(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function b(t,e,i,s){var r=new S(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function T(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function S(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function C(t,e,i,s){for(var r=0,n=e,o=i-s;n<i;n+=s)r+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return r}return pr=1,_r.exports=t,_r.exports.default=t,t.deviation=function(t,e,i,s){var r=e&&e.length,n=r?e[0]*i:t.length,o=Math.abs(C(t,0,n,i));if(r)for(var a=0,h=e.length;a<h;a++){var l=e[a]*i,u=a<h-1?e[a+1]*i:t.length;o-=Math.abs(C(t,l,u,i))}var d=0;for(a=0;a<s.length;a+=3){var c=s[a]*i,p=s[a+1]*i,_=s[a+2]*i;d+=Math.abs((t[c]-t[_])*(t[p+1]-t[c+1])-(t[c]-t[p])*(t[_+1]-t[c+1]))}return 0===o&&0===d?0:Math.abs((d-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},s=0,r=0;r<t.length;r++){for(var n=0;n<t[r].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[r][n][o]);r>0&&(s+=t[r-1].length,i.holes.push(s))}return i},_r.exports}(),mr=cr(fr);const gr=(t,e,i,s,r,n=[],o=[])=>{const a=[t,e,i,s],h=r/2,l=n.length/6,u=new de(t-i,e-s).perp().normalize().multiply(h),d=new de(i-t,s-e).perp().normalize().multiply(h);return n.push(t-u.x,e-u.y),n.push(t+u.x,e+u.y),n.push(i-d.x,s-d.y),n.push(i+d.x,s+d.y),o.push(l,l,l+1,l+2,l+3,l+3),new xe({vertices:n,indices:o,points:a})},yr=(t,e,i=[],s=[])=>{if(t.length<4)throw new Error("At least two X/Y pairs are required to build a line.");const r=e/2,n=new de(t[0],t[1]),o=new de(t[t.length-2],t[t.length-1]);if(n.x===o.x&&n.y===o.y){(t=t.slice()).pop(),t.pop(),o.set(t[t.length-2],t[t.length-1]);const e=o.x+.5*(n.x-o.x),i=o.y+.5*(n.y-o.y);t.unshift(e,i),t.push(e,i)}const a=t.length/2;let h=t.length,l=i.length/6,u=t[0],d=t[1],c=t[2],p=t[3],_=0,f=0,m=-(d-p),g=u-c,y=0,x=0,w=0,v=0,b=Math.sqrt(m*m+g*g);m/=b,g/=b,m*=r,g*=r,i.push(u-m,d-g),i.push(u+m,d+g);for(let e=1;e<a-1;e++){u=t[2*(e-1)],d=t[2*(e-1)+1],c=t[2*e],p=t[2*e+1],_=t[2*(e+1)],f=t[2*(e+1)+1],m=-(d-p),g=u-c,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=r,g*=r,y=-(p-f),x=c-_,b=Math.sqrt(y*y+x*x),y/=b,x/=b,y*=r,x*=r;const s=-g+d-(-g+p),n=-m+c-(-m+u),o=(-m+u)*(-g+p)-(-m+c)*(-g+d),a=-x+f-(-x+p),l=-y+c-(-y+_),T=(-y+_)*(-x+p)-(-y+c)*(-x+f);let S=s*l-a*n;if(Math.abs(S)<.1){S+=10.1,i.push(c-m,p-g),i.push(c+m,p+g);continue}const C=(n*T-l*o)/S,M=(a*o-s*T)/S;(C-c)*(C-c)+(M-p)*(M-p)>196*r*r?(w=m-y,v=g-x,b=Math.sqrt(w*w+v*v),w/=b,v/=b,w*=r,v*=r,i.push(c-w,p-v),i.push(c+w,p+v),i.push(c-w,p-v),h++):(i.push(C,M),i.push(c-(C-c),p-(M-p)))}u=t[2*(a-2)],d=t[2*(a-2)+1],c=t[2*(a-1)],p=t[2*(a-1)+1],m=-(d-p),g=u-c,b=Math.sqrt(m*m+g*g),m/=b,g/=b,m*=r,g*=r,i.push(c-m,p-g),i.push(c+m,p+g),s.push(l);for(let t=0;t<h;t++)s.push(l++);return s.push(l-1),new xe({vertices:i,indices:s,points:t})},xr=(t,e,i,s=[],r=[])=>{const n=Math.floor(15*Math.sqrt(i+i)),o=2*Math.PI/n,a=[];let h=s.length/6;r.push(h);for(let l=0;l<n+1;l++){const n=t+Math.sin(o*l)*i,u=e+Math.cos(o*l)*i;a.push(n,u),s.push(t,e),s.push(n,u),r.push(h++,h++)}return r.push(h-1),new xe({vertices:s,indices:r,points:a})},wr=(t,e,i,s,r=[],n=[])=>{const o=Math.floor(15*Math.sqrt(i+s)),a=2*Math.PI/o,h=[];let l=r.length/6;n.push(l);for(let u=0;u<o+1;u++){const o=t+Math.sin(a*u)*i,d=e+Math.cos(a*u)*s;h.push(o,d),r.push(t,e),r.push(o,d),n.push(l++,l++)}return n.push(l-1),new xe({vertices:r,indices:n,points:h})},vr=(t,e=[],i=[])=>{if(t.length<6)throw new Error("At least three X/Y pairs are required to build a polygon.");const s=e.length/6,r=t.length/2,n=mr(t,[],2);if(n){for(let t=0;t<n.length;t+=3)i.push(n[t]+s),i.push(n[t]+s),i.push(n[t+1]+s),i.push(n[t+2]+s),i.push(n[t+2]+s);for(let i=0;i<r;i++)e.push(t[2*i],t[2*i+1])}return new xe({vertices:e,indices:i,points:t})},br=(t,e,i,s,r=[],n=[])=>{const o=[t,e,t+i,e,t,e+s,t+i,e+s],a=r.length/6;return r.push(...o),n.push(a,a,a+1,a+2,a+3,a+3),new xe({vertices:r,indices:n,points:o})},Tr=(t,e,i,s,r=s/2,n=0)=>{const o=Math.PI/-2+n,a=2*i,h=D/a,l=[];for(let i=0;i<a;i++){const n=o+i*h,a=i%2?r:s;l.push(t+a*Math.cos(n),e+a*Math.sin(n))}return vr(l)};let Sr=null;class Cr{constructor(t=0,e=0,i=0,s=0){this.collisionType=1,this._fromPosition=new de(t,e),this._toPosition=new de(i,s)}get fromPosition(){return this._fromPosition}set fromPosition(t){this._fromPosition.copy(t)}get fromX(){return this._fromPosition.x}set fromX(t){this._fromPosition.x=t}get fromY(){return this._fromPosition.y}set fromY(t){this._fromPosition.y=t}get toPosition(){return this._toPosition}set toPosition(t){this._toPosition.copy(t)}get toX(){return this._toPosition.x}set toX(t){this._toPosition.x=t}get toY(){return this._toPosition.y}set toY(t){this._toPosition.y=t}set(t,e,i,s){return this._fromPosition.set(t,e),this._toPosition.set(i,s),this}copy(t){return this._fromPosition.copy(t.fromPosition),this.toPosition.copy(t.toPosition),this}clone(){return new Cr(this.fromX,this.fromY,this.toX,this.toY)}getBounds(){const{fromX:t,fromY:e,toX:i,toY:s}=this,r=Math.min(t,i),n=Math.min(e,s);return new re(r,n,Math.max(t,i)-r,Math.max(e,s)-n)}getNormals(){return[]}project(t,e=new ct){return e}intersectsWith(t){switch(t.collisionType){case 6:return Lt(this,t.getBounds());case 2:return Lt(this,t);case 5:return It(this,t);case 3:return Ft(this,t);case 4:return Dt(this,t);case 1:return kt(this,t);case 0:return Pt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e,i=.1){return Pt(de.temp.set(t,e),this,i)}equals({fromX:t,fromY:e,toX:i,toY:s}={}){return!(void 0!==t&&this.fromX!==t||void 0!==e&&this.fromY!==e||void 0!==i&&this.toX!==i||void 0!==s&&this.toY!==s)}destroy(){this._fromPosition.destroy(),this._toPosition.destroy()}static get temp(){return null===Sr&&(Sr=new Cr),Sr}}let Mr=null;class Pr{constructor(t=0,e=0,i=0){this.collisionType=3,this._collisionVertices=null,this._position=new de(t,e),this._radius=i}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t){return this._radius=t,this}set(t,e,i){return this._position.set(t,e),this._radius=i,this}copy(t){return this._position.copy(t.position),this._radius=t.radius,this}clone(){return new Pr(this.x,this.y,this.radius)}equals({x:t,y:e,radius:i}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.radius!==i)}getBounds(){return new re(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}getNormals(){return this.getCollisionVertices().map((t,e,i)=>i[(e+1)%i.length].clone().subtract(t.x,t.y).rperp().normalize())}project(t,e=new ct){const i=t.dot(this.x,this.y),s=this.radius*t.length;return e.set(i-s,i+s)}contains(t,e){return Et(de.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case 6:return Ut(t.getBounds(),this);case 2:return Ut(t,this);case 5:return Xt(this,t);case 3:return Gt(this,t);case 4:return zt(this,t);case 1:return Ft(t,this);case 0:return Et(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:return Zt(this,t.getBounds());case 2:return Zt(this,t);case 5:return Jt(t,this,!0);case 3:return Qt(this,t);default:return null}}destroy(){this._position.destroy()}getCollisionVertices(){if(null===this._collisionVertices){this._collisionVertices=[];for(let t=0;t<Pr.collisionSegments;t++)this._collisionVertices.push(this.getCollisionVertex(t))}return this._collisionVertices}getCollisionVertex(t){const e=2*t*Math.PI/Pr.collisionSegments-Math.PI/2,i=Math.cos(e)*this._radius,s=Math.sin(e)*this._radius;return new de(this._radius+i,this._radius+s)}static get temp(){return null===Mr&&(Mr=new Pr),Mr}}Pr.collisionSegments=32;class Br{constructor(t=0,e=0,i=0,s=i){this.collisionType=4,this._position=new de(t,e),this._radius=new de(i,s)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get radius(){return this._radius}set radius(t){this._radius.copy(t)}get rx(){return this._radius.x}set rx(t){this._radius.x=t}get ry(){return this._radius.y}set ry(t){this._radius.y=t}setPosition(t,e){return this._position.set(t,e),this}setRadius(t,e=t){return this._radius.set(t,e),this}set(t,e,i,s){return this._position.set(t,e),this._radius.set(i,s),this}copy(t){return this._position.copy(t.position),this._radius.copy(t.radius),this}clone(){return new Br(this.x,this.y,this.rx,this.ry)}getBounds(){return new re(this.x-this.rx,this.y-this.ry,2*this.rx,2*this.ry)}getNormals(){return[]}project(t,e=new ct){return e}intersectsWith(t){switch(t.collisionType){case 6:return Vt(t.getBounds(),this);case 2:return Vt(t,this);case 5:return jt(this,t);case 3:return zt(t,this);case 4:return Yt(this,t);case 1:return Dt(t,this);case 0:return Rt(t,this);default:return!1}}collidesWith(t){return null}contains(t,e){return Rt(de.temp.set(t,e),this)}equals({x:t,y:e,rx:i,ry:s}={}){return!(void 0!==t&&this.x!==t||void 0!==e&&this.y!==e||void 0!==i&&this.rx!==i||void 0!==s&&this.ry!==s)}destroy(){this._position.destroy(),this._radius.destroy()}}let Er=null;class Rr{constructor(t=[],e=0,i=0){this.collisionType=5,this._points=[],this._edges=[],this._normals=[],this._position=new de(e,i),this.setPoints(t)}get position(){return this._position}set position(t){this._position.copy(t)}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get points(){return this._points}set points(t){this.setPoints(t)}get edges(){return this._edges}get normals(){return this._normals}setPosition(t,e){return this._position.set(t,e),this}setPoints(t){const e=this._points.length,i=t.length,s=e-i,r=Math.min(e,i);for(let e=0;e<r;e++)this._points[e].copy(t[e]);if(s>0)this._points.splice(i).forEach(t=>t.destroy()),this._edges.splice(i).forEach(t=>t.destroy()),this._normals.splice(i).forEach(t=>t.destroy());else if(s<0)for(let s=e;s<i;s++)this._points.push(t[s].clone()),this._edges.push(t[s].clone()),this._normals.push(t[s].clone());for(let t=0;t<i;t++){const e=this._points[t],s=this._points[(t+1)%i];this._edges[t].set(s.x-e.x,s.y-e.y),this._normals[t].copy(this._edges[t]).rperp().normalize()}return this}set(t,e,i){return this._position.set(t,e),this.setPoints(i),this}copy(t){return this._position.copy(t.position),this.setPoints(t.points),this}clone(){return new Rr(this.points,this.x,this.y)}equals({x:t,y:e,points:i}={}){return(void 0===t||this.x===t)&&(void 0===e||this.y===e)&&(void 0===i||this.points.length===i.length&&this.points.every((t,e)=>t.equals(i[e])))}getBounds(){let t=1/0,e=1/0,i=-1/0,s=-1/0;for(const r of this._points)t=Math.min(r.x,t),e=Math.min(r.y,e),i=Math.max(r.x,i),s=Math.max(r.y,s);return new re(this.x+t,this.y+e,i-t,s-e)}getNormals(){return this._normals}project(t,e=new ct){const i=t.clone().normalize(),s=this._points.map(t=>i.dot(t.x,t.y));return e.set(Math.min(...s),Math.max(...s))}contains(t,e){return At(de.temp.set(t,e),this)}intersectsWith(t){switch(t.collisionType){case 6:return Ot(t.getBounds(),this);case 2:return Ot(t,this);case 5:return $t(this,t);case 3:return Xt(t,this);case 4:return jt(t,this);case 1:return It(t,this);case 0:return At(t,this);default:return!1}}collidesWith(t){switch(t.collisionType){case 6:case 2:case 5:return te(this,t);case 3:return Jt(this,t);default:return null}}destroy(){for(const t of this._points)t.destroy();this._position.destroy(),this._points.length=0}static get temp(){return null===Er&&(Er=new Rr),Er}}let Ar=null;class kr{constructor(t=0,e=0,i=0,s=0){this._startPoint=new de(t,e),this._endPoint=new de(i,s)}get startPoint(){return this._startPoint}set startPoint(t){this._startPoint.copy(t)}get startX(){return this._startPoint.x}set startX(t){this._startPoint.x=t}get startY(){return this._startPoint.y}set startY(t){this._startPoint.y=t}get endPoint(){return this._endPoint}set endPoint(t){this._endPoint.copy(t)}get endX(){return this._endPoint.x}set endX(t){this._endPoint.x=t}get endY(){return this._endPoint.y}set endY(t){this._endPoint.y=t}set(t,e,i,s){return this._startPoint.set(t,e),this._endPoint.set(i,s),this}copy(t){return this._startPoint.copy(t.startPoint),this._endPoint.copy(t.endPoint),this}clone(){return new kr(this.startX,this.startY,this.endX,this.endY)}equals({startX:t,startY:e,endX:i,endY:s}={}){return!(void 0!==t&&this.startX!==t||void 0!==e&&this.startY!==e||void 0!==i&&this.endX!==i||void 0!==s&&this.endY!==s)}destroy(){this._startPoint.destroy(),this._endPoint.destroy()}static get temp(){return null===Ar&&(Ar=new kr),Ar}}class Lr{constructor(t=0,e=0){this.radius=t,this.phi=e}static fromVector(t){return new Lr(t.length,0)}toVector(){return de.temp.set(this.radius*Math.cos(this.phi),this.radius*Math.sin(this.phi))}}class Fr{constructor(t,e){this._fromColor=t.clone(),this._toColor=e.clone()}get fromColor(){return this._fromColor}set fromColor(t){this.setFromColor(t)}get toColor(){return this._toColor}set toColor(t){this.setToColor(t)}setFromColor(t){return this._fromColor.copy(t),this}setToColor(t){return this._toColor.copy(t),this}apply(t,e){const i=t.elapsedRatio,{r:s,g:r,b:n,a:o}=this._fromColor,{r:a,g:h,b:l,a:u}=this._toColor;return t.tint.set((a-s)*i+s,(h-r)*i+r,(l-n)*i+n,(u-o)*i+o),this}destroy(){this._fromColor.destroy(),this._toColor.destroy()}}class Dr{constructor(t,e){this._acceleration=new de(t,e)}get acceleration(){return this._acceleration}set acceleration(t){this.setAcceleration(t)}setAcceleration(t){return this._acceleration.copy(t),this}apply(t,e){return t.velocity.add(e.seconds*this._acceleration.x,e.seconds*this._acceleration.y),this}destroy(){this._acceleration.destroy()}}class Ir{constructor(t,e){this._scaleFactor=new de(t,e)}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this.setScaleFactor(t)}setScaleFactor(t){return this._scaleFactor.copy(t),this}apply(t,e){return t.scale.add(e.seconds*this._scaleFactor.x,e.seconds*this._scaleFactor.y),this}destroy(){this._scaleFactor.destroy()}}class Nr{constructor(t){this._angularAcceleration=t}get angularAcceleration(){return this._angularAcceleration}set angularAcceleration(t){this.setAngularAcceleration(t)}setAngularAcceleration(t){return this._angularAcceleration=t,this}apply(t,e){return t.rotationSpeed+=e.seconds*this._angularAcceleration,this}destroy(){}}class Ur{constructor(t={}){const{totalLifetime:e,elapsedLifetime:i,position:s,velocity:n,scale:o,rotation:a,rotationSpeed:h,textureIndex:l,tint:u}=t;this._totalLifetime=(e??r.oneSecond).clone(),this._elapsedLifetime=(i??r.zero).clone(),this._position=(s??de.zero).clone(),this._velocity=(n??de.zero).clone(),this._scale=(o??de.one).clone(),this._tint=(u??K.white).clone(),this._rotation=a??0,this._rotationSpeed=h??0,this._textureIndex=l??0}get totalLifetime(){return this._totalLifetime}set totalLifetime(t){this._totalLifetime.copy(t)}get elapsedLifetime(){return this._elapsedLifetime}set elapsedLifetime(t){this._elapsedLifetime.copy(t)}get position(){return this._position}set position(t){this._position.copy(t)}get velocity(){return this._velocity}set velocity(t){this._velocity.copy(t)}get scale(){return this._scale}set scale(t){this._scale.copy(t)}get rotation(){return this._rotation}set rotation(t){this._rotation=U(t)}get rotationSpeed(){return this._rotationSpeed}set rotationSpeed(t){this._rotationSpeed=t}get textureIndex(){return this._textureIndex}set textureIndex(t){this._textureIndex=t}get tint(){return this._tint}set tint(t){this._tint.copy(t)}destroy(){this._totalLifetime.destroy(),this._elapsedLifetime.destroy(),this._position.destroy(),this._velocity.destroy(),this._scale.destroy(),this._tint.destroy()}}class Vr{constructor(t,e){this._emissionDelta=0,this._emissionRate=t,this._particleOptions=e??new Ur}get emissionRate(){return this._emissionRate}set emissionRate(t){this._emissionRate=t}get particleOptions(){return this._particleOptions}set particleOptions(t){this._particleOptions=t}computeParticleCount(t){const e=this._emissionRate*t.seconds+this._emissionDelta,i=0|e;return this._emissionDelta=e-i,i}apply(t,e){const i=this.computeParticleCount(e),s=this._particleOptions;for(let e=0;e<i;e++){const e=t.requestParticle();e.applyOptions(s),t.emitParticle(e)}return this}destroy(){this._particleOptions.destroy()}}class Or extends xe{constructor(t,e,i){const s=Math.floor(15*Math.sqrt(i+i)),r=2*Math.PI/s,n=[],o=[],a=[];let h=n.length/6;o.push(h);for(let l=0;l<s+1;l++){const s=t+Math.sin(r*l)*i,u=e+Math.cos(r*l)*i;a.push(s,u),n.push(t,e),n.push(s,u),o.push(h++,h++)}o.push(h-1),super({vertices:n,indices:o,points:a})}}class Gr extends Js{constructor(){super(...arguments),this._lineWidth=0,this._lineColor=new K,this._fillColor=new K,this._currentPoint=new de(0,0)}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t}get lineColor(){return this._lineColor}set lineColor(t){this._lineColor.copy(t)}get fillColor(){return this._fillColor}set fillColor(t){this._fillColor.copy(t)}get currentPoint(){return this._currentPoint}getChildAt(t){return super.getChildAt(t)}addChild(t){if(!(t instanceof ye))throw new Error("Graphics can only contain DrawableShape children.");return super.addChild(t)}addChildAt(t,e){if(!(t instanceof ye))throw new Error("Graphics can only contain DrawableShape children.");return super.addChildAt(t,e)}moveTo(t,e){return this._currentPoint.set(t,e),this}lineTo(t,e){const{x:i,y:s}=this._currentPoint;return this.drawPath([i,s,t,e]),this.moveTo(t,e),this}quadraticCurveTo(t,e,i,s){const{x:r,y:n}=this._currentPoint;return this.drawPath(j(r,n,t,e,i,s)),this.moveTo(i,s),this}bezierCurveTo(t,e,i,s,r,n){const{x:o,y:a}=this._currentPoint;return this.drawPath(Y(o,a,t,e,i,s,r,n)),this.moveTo(r,n),this}arcTo(t,e,i,s,r){const{x:n,y:o}=this._currentPoint,a=Math.abs(r);if(0===a||n===t&&o===e||t===i&&e===s)return this.lineTo(t,e);const h=t-n,l=e-o,u=i-t,d=s-e,c=Math.hypot(h,l),p=Math.hypot(u,d);if(0===c||0===p)return this.lineTo(t,e);const _=h/c,f=l/c,m=u/p,g=d/p,y=G(_*m+f*g,-1,1),x=Math.acos(y);if(0===x||x===Math.PI)return this.lineTo(t,e);const w=a/Math.tan(x/2);if(!Number.isFinite(w)||w>c||w>p)return this.lineTo(t,e);const v=t-_*w,b=e-f*w,T=t+m*w,S=e+g*w,C=_*g-f*m>0,M=v+(C?-f:f)*a,P=b+(C?_:-_)*a,B=Math.atan2(b-P,v-M),E=Math.atan2(S-P,T-M);return this.lineTo(v,b),this.drawArc(M,P,a,B,E,C)}drawArc(t,e,i,s,r,n=!1){const o=Math.abs(i);if(0===o)return this;let a=r-s;if(!n&&a<0?a+=D:n&&a>0&&(a-=D),0===a)return this;const h=Math.max(2,Math.ceil(Math.abs(a)/(Math.PI/16))),l=[];for(let i=0;i<=h;i++){const r=s+a*(i/h);l.push(t+Math.cos(r)*o,e+Math.sin(r)*o)}return this.drawPath(l),this.moveTo(l[l.length-2],l[l.length-1]),this}drawLine(t,e,i,s){return this.addChild(new ye(gr(t,e,i,s,this._lineWidth),this._lineColor,tt.TriangleStrip)),this}drawPath(t){return this.addChild(new ye(yr(t,this._lineWidth),this._lineColor,tt.TriangleStrip)),this}drawPolygon(t){const e=vr(t);return this.addChild(new ye(e,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(e.points),this}drawCircle(t,e,i){const s=new Or(t,e,i);return this.addChild(new ye(s,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(s.points),this}drawEllipse(t,e,i,s){const r=wr(t,e,i,s);return this.addChild(new ye(r,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(r.points),this}drawRectangle(t,e,i,s){const r=br(t,e,i,s);return this.addChild(new ye(r,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(r.points),this}drawStar(t,e,i,s,r=s/2,n=0){const o=Tr(t,e,i,s,r,n);return this.addChild(new ye(o,this._fillColor,tt.TriangleStrip)),this._lineWidth>0&&this.drawPath(o.points),this}clear(){return this.removeChildren(),this._lineWidth=0,this._lineColor.copy(K.black),this._fillColor.copy(K.black),this._currentPoint.set(0,0),this}destroy(){super.destroy(),this.clear(),this._lineColor.destroy(),this._fillColor.destroy(),this._currentPoint.destroy()}}class zr{constructor(t,e){this.frames=new Map,this.sprites=new Map,this.animations=new Map,this.texture=t,this.parse(e)}parse(t,e=!1){e||this.clear();for(const[e,i]of Object.entries(t.frames))this.addFrame(e,i);if(t.animations)for(const[e,i]of Object.entries(t.animations))this.defineAnimation(e,i)}addFrame(t,e){const{x:i,y:s,w:r,h:n}=e.frame,o=new re(i,s,r,n),a=new qe(this.texture);a.setTextureFrame(o),this.frames.set(t,o),this.sprites.set(t,a)}defineAnimation(t,e){if(0===t.trim().length)throw new Error("Spritesheet animation names must be non-empty strings.");if(!Array.isArray(e)||0===e.length)throw new Error(`Spritesheet animation "${t}" must reference at least one frame.`);for(const i of e)if(!this.frames.has(i))throw new Error(`Spritesheet animation "${t}" references missing frame "${i}".`);return this.animations.set(t,[...e]),this}getFrame(t){const e=this.frames.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}getAnimationFrameNames(t){const e=this.animations.get(t);if(!e)throw new Error(`Spritesheet animation named ${t} is not available!`);return e}getFrameSprite(t){const e=this.sprites.get(t);if(!e)throw new Error(`Spritesheet frame named ${t} is not available!`);return e}clear(){for(const t of this.frames.values())t.destroy();this.frames.clear();for(const t of this.sprites.values())t.destroy();return this.sprites.clear(),this.animations.clear(),this}destroy(){this.clear()}}class Wr extends qe{constructor(t,e){super(t),this._clips=new Map,this._currentClipName=null,this._currentFrameIndex=0,this._playing=!1,this._loopOverride=null,this._elapsedFrameTimeMs=0,this.onComplete=new F,this.onFrame=new F,e&&this.setClips(e)}get currentClip(){return this._currentClipName}get currentFrame(){return this._currentFrameIndex}get playing(){return this._playing}get loop(){return null!==this._loopOverride?this._loopOverride:!!this._currentClipName&&(this._clips.get(this._currentClipName)?.loop??!1)}set loop(t){this._loopOverride=t}setClips(t){this._clips.clear();for(const[e,i]of Object.entries(t))this.defineClip(e,i);return this}defineClip(t,e){if(0===t.trim().length)throw new Error("AnimatedSprite clip names must be non-empty strings.");if(!Array.isArray(e.frames)||0===e.frames.length)throw new Error(`AnimatedSprite clip "${t}" must define at least one frame.`);const i=e.fps??12;if(!Number.isFinite(i)||i<=0)throw new Error(`AnimatedSprite clip "${t}" has an invalid fps value (${i}).`);return this._clips.set(t,{frames:e.frames.map(t=>t.clone()),frameDurationMs:1e3/i,loop:e.loop??!0}),this}removeClip(t){return this._currentClipName===t&&this.stop(),this._clips.delete(t),this}play(t,e={}){const i=this._clips.get(t);if(!i)throw new Error(`AnimatedSprite clip "${t}" is not defined.`);const s=this._currentClipName===t,r=e.restart??!0;return s&&!r||(this._currentClipName=t,this._currentFrameIndex=0,this._elapsedFrameTimeMs=0,this._applyFrame(i.frames[0]),this.onFrame.dispatch(t,0)),this._loopOverride=e.loop??this._loopOverride,this._playing=!0,this}stop(){if(this._playing=!1,this._elapsedFrameTimeMs=0,!this._currentClipName)return this;const t=this._clips.get(this._currentClipName);return t&&t.frames.length>0&&(this._currentFrameIndex=0,this._applyFrame(t.frames[0]),this.onFrame.dispatch(this._currentClipName,0)),this}pause(){return this._playing=!1,this}resume(){return null!==this._currentClipName&&(this._playing=!0),this}update(t){if(!this._playing||null===this._currentClipName)return this;const e=this._clips.get(this._currentClipName);if(!e||e.frames.length<=1)return this;const i="number"==typeof t?t:t.milliseconds;if(i<=0)return this;for(this._elapsedFrameTimeMs+=i;this._elapsedFrameTimeMs>=e.frameDurationMs;){this._elapsedFrameTimeMs-=e.frameDurationMs;const t=this._currentFrameIndex+1;if(t>=e.frames.length){if(this.loop){this._currentFrameIndex=0,this._applyFrame(e.frames[0]),this.onFrame.dispatch(this._currentClipName,0);continue}this._currentFrameIndex=e.frames.length-1,this._applyFrame(e.frames[this._currentFrameIndex]),this._playing=!1,this.onComplete.dispatch(this._currentClipName);break}this._currentFrameIndex=t,this._applyFrame(e.frames[this._currentFrameIndex]),this.onFrame.dispatch(this._currentClipName,this._currentFrameIndex)}return this}destroy(){super.destroy(),this.onComplete.destroy(),this.onFrame.destroy();for(const t of this._clips.values())for(const e of t.frames)e.destroy();this._clips.clear()}static fromSpritesheet(t){const e={};for(const[i,s]of t.animations)e[i]={frames:s.map(e=>t.getFrame(e)),loop:!0};return new Wr(t.texture,e)}_applyFrame(t){this.setTextureFrame(t,!1)}}class qr{constructor(t={}){this._dirty=!0,this._align=t.align??"left",this._fill=t.fill??"black",this._stroke=t.stroke??"black",this._strokeThickness=t.strokeThickness??1,this._fontSize=t.fontSize??20,this._fontWeight=t.fontWeight??"bold",this._fontFamily=t.fontFamily??"Arial",this._wordWrap=t.wordWrap??!1,this._wordWrapWidth=t.wordWrapWidth??100,this._baseline=t.baseline??"alphabetic",this._lineJoin=t.lineJoin??"miter",this._miterLimit=t.miterLimit??10,this._padding=t.padding??0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this._dirty=!0)}get fill(){return this._fill}set fill(t){this._fill!==t&&(this._fill=t,this._dirty=!0)}get stroke(){return this._stroke}set stroke(t){this._stroke!==t&&(this._stroke=t,this._dirty=!0)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this._dirty=!0)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this._dirty=!0)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this._dirty=!0)}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this._dirty=!0)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this._dirty=!0)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this._dirty=!0)}get baseline(){return this._baseline}set baseline(t){this._baseline!==t&&(this._baseline=t,this._dirty=!0)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this._dirty=!0)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this._dirty=!0)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this._dirty=!0)}get dirty(){return this._dirty}set dirty(t){this._dirty=t}get font(){return`${this._fontWeight} ${this._fontSize}px ${this._fontFamily}`}apply(t){return t.font=this.font,t.fillStyle=this.fill,t.strokeStyle=this.stroke,t.lineWidth=this.strokeThickness,t.textBaseline=this.baseline,t.lineJoin=this.lineJoin,t.miterLimit=this.miterLimit,this}copy(t){return t!==this&&(this.align=t.align,this.fill=t.fill,this.stroke=t.stroke,this.strokeThickness=t.strokeThickness,this.fontSize=t.fontSize,this.fontWeight=t.fontWeight,this.fontFamily=t.fontFamily,this.wordWrap=t.wordWrap,this.wordWrapWidth=t.wordWrapWidth,this.baseline=t.baseline,this.lineJoin=t.lineJoin,this.miterLimit=t.miterLimit,this.padding=t.padding,this.dirty=t.dirty),this}clone(){return(new qr).copy(this)}}const Hr=/(?:\r\n|\r|\n)/;class Xr extends qe{constructor(t,e,i,s=document.createElement("canvas")){super(new Ye(s,i)),this._dirty=!0,this._text=t,this._style=e&&e instanceof qr?e:new qr(e),this._canvas=s,this._context=s.getContext("2d"),this.updateTexture()}get text(){return this._text}set text(t){this.setText(t)}get style(){return this._style}set style(t){this.setStyle(t)}get canvas(){return this._canvas}set canvas(t){this.setCanvas(t)}setText(t){return this._text!==t&&(this._text=t,this._dirty=!0),this}setStyle(t){return this._style=t instanceof qr?t:new qr(t),this._dirty=!0,this}setCanvas(t){return this._canvas!==t&&(this._canvas=t,this._context=this._getContext(t),this._dirty=!0,this.texture.setSource.call(this.texture,t),this.setTextureFrame(re.temp.set(0,0,t.width,t.height))),this}updateTexture(){if(this._style&&(this._dirty||this._style.dirty)){const t=this._canvas,e=this._context,i=this._style.apply(e),s=i.wordWrap?this.getWordWrappedText():this._text,r=(t=>{if(!Ue.has(t)){const e=document.body,i=document.createElement("div");i.appendChild(document.createTextNode("M")),i.setAttribute("style",`font: ${t};position:absolute;top:0;left:0`),e.appendChild(i),Ue.set(t,i.offsetHeight),e.removeChild(i)}return Ue.get(t)})(e.font)+i.strokeThickness,n=s.split(Hr),o=n.map(t=>e.measureText(t)),a=o.reduce((t,e)=>Math.max(t,e.width),0),h=Math.ceil(a+i.strokeThickness+2*i.padding),l=Math.ceil(r*n.length+2*i.padding);h!==t.width||l!==t.height?(t.width=h,t.height=l,this.setTextureFrame(re.temp.set(0,0,h,l))):e.clearRect(0,0,h,l),i.apply(e);for(let t=0;t<n.length;t++){const s=o[t],h=a-s.width,l="right"===i.align?h:h/2,u=i.padding+i.strokeThickness/2,d=s.actualBoundingBoxLeft+("left"===i.align?0:l)+u,c=s.actualBoundingBoxAscent+r*t+u;i.stroke&&i.strokeThickness&&e.strokeText(n[t],d,c),i.fill&&e.fillText(n[t],d,c)}this.texture.updateSource(),this._dirty=!1,this._style.dirty=!1}return this}getWordWrappedText(){const t=this._context,e=this._style.wordWrapWidth,i=this._text.split("\n"),s=t.measureText(" ").width;let r=e,n="";for(let o=0;o<i.length;o++){const a=i[o].split(" ");o>0&&(n+="\n");for(let i=0;i<a.length;i++){const o=a[i],h=t.measureText(o).width+s;h>r?(i>0&&(n+="\n"),r=e):r-=h,n+=`${o} `}}return n}render(t){return this.visible&&(this.updateTexture(),super.render(t)),this}_getContext(t){const e=t.getContext("2d");if(null===e)throw new Error("Could not create a 2D canvas context.");return e}}class Yr{constructor(t,e){const{scaleMode:i,wrapMode:s,premultiplyAlpha:r,generateMipMap:n,flipY:o}=e;this._context=t,this._sampler=t.createSampler(),this._scaleMode=i,this._wrapMode=s,this._premultiplyAlpha=r,this._generateMipMap=n,this._flipY=o,this.updateWrapModeParameters(),this.updateScaleModeParameters()}get sampler(){return this._sampler}get scaleMode(){return this._scaleMode}set scaleMode(t){this.setScaleMode(t)}get wrapMode(){return this._wrapMode}set wrapMode(t){this.setWrapMode(t)}setScaleMode(t){return this._scaleMode!==t&&(this._scaleMode=t,this.updateScaleModeParameters()),this}setWrapMode(t){return this._wrapMode!==t&&(this._wrapMode=t,this.updateWrapModeParameters()),this}bind(t){return this._context.bindSampler(t,this._sampler),this}destroy(){this._context.deleteSampler(this._sampler)}updateScaleModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_MAG_FILTER,this._scaleMode),t.samplerParameteri(this._sampler,t.TEXTURE_MIN_FILTER,this._scaleMode)}updateWrapModeParameters(){if(null===this._sampler)throw new Error("Sampler is null. Could not update sampler parameters.");const t=this._context;t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_S,this._wrapMode),t.samplerParameteri(this._sampler,t.TEXTURE_WRAP_T,this._wrapMode)}}class jr{constructor(t){this._callback=t}execute(t){this._callback(t)}}class $r{}class Kr extends $r{constructor(t={}){super(),this._sprite=new qe(null),this._sampleTint=K.white.clone(),this._radius=2,this._quality=1,this._radius=Math.max(0,t.radius??2),this._quality=Math.max(1,Math.floor(t.quality??1))}get radius(){return this._radius}set radius(t){this._radius=Math.max(0,t)}get quality(){return this._quality}set quality(t){this._quality=Math.max(1,Math.floor(t))}apply(t,e,i){const s=this._radius,r=this._quality,n=Math.max(1,2*r+1),o=1/(s<=0?1:2*n);this._sampleTint.set(255,255,255,o),this._sprite.setTexture(e).setBlendMode(Q.Additive).setTint(this._sampleTint).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new _e(()=>{if(s<=0)this._sprite.setPosition(0,0).render(t);else for(let e=0;e<n;e++){const i=(2*(1===n?0:e/(n-1))-1)*s;this._sprite.setPosition(i,0).render(t),this._sprite.setPosition(0,i).render(t)}},{target:i,view:i.view,clearColor:K.transparentBlack}))}destroy(){this._sampleTint.destroy(),this._sprite.destroy()}}class Qr extends $r{constructor(t=K.white){super(),this._sprite=new qe(null),this._color=t.clone()}get color(){return this._color}apply(t,e,i){this._sprite.setTexture(e).setBlendMode(Q.Normal).setTint(this._color).setPosition(0,0).setRotation(0).setScale(1,1),this._sprite.width=i.width,this._sprite.height=i.height,t.execute(new _e(()=>{this._sprite.render(t)},{target:i,view:i.view,clearColor:K.transparentBlack}))}destroy(){this._sprite.destroy(),this._color.destroy()}}class Zr{async resolve(t,e){const{storageName:i,key:s,url:r,requestOptions:n,factory:o}=t;for(const t of e){const e=await t.load(i,s);if(null!=e)try{return await o.create(e),e}catch{await t.delete(i,s)}}const a=await fetch(r,n);if(!a.ok)throw new Error(`Failed to fetch "${r}" (${a.status} ${a.statusText}).`);const h=await o.process(a);for(const t of e)try{await t.save(i,s,h)}catch{}return h}}class Jr{async resolve(t,e){const i=await fetch(t.url,t.requestOptions);if(!i.ok)throw new Error(`Failed to fetch "${t.url}" (${i.status} ${i.statusText}).`);return t.factory.process(i)}}const tn=["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"];class en{get connected(){return this._connected}constructor(t,e=1,i=tn,s){if(this._onCloseHandler=this.disconnect.bind(this),this._connected=!1,this._database=null,!y)throw new Error("This browser does not support indexedDB!");this.name=t,this.version=e,this._storeNames=i,this._migrations=s}async getObjectStore(t,e="readonly"){return await this.connect(),this._database.transaction([t],e).objectStore(t)}async connect(){return!(!this._connected||!this._database)||new Promise((t,e)=>{const i=indexedDB.open(this.name,this.version);i.addEventListener("upgradeneeded",t=>{const s=i.result,r=i.transaction,n=[...r.objectStoreNames],{oldVersion:o,newVersion:a}=t;if(s.addEventListener("error",()=>e(Error("An error occurred while opening the database."))),s.addEventListener("abort",()=>e(Error("The database opening was aborted."))),this._migrations){const t=Object.keys(this._migrations).map(Number).filter(t=>t>o&&t<=(a??this.version)).sort((t,e)=>t-e);for(const e of t){if(!this._migrations[e](s,r))return void r.abort()}}else{for(const t of n)this._storeNames.includes(t)||s.deleteObjectStore(t);for(const t of this._storeNames)n.includes(t)||s.createObjectStore(t,{keyPath:"name"})}}),i.addEventListener("success",()=>{this._database=i.result,this._database.addEventListener("close",this._onCloseHandler),this._database.addEventListener("versionchange",this._onCloseHandler),this._connected=!0,t(!0)}),i.addEventListener("error",()=>e(Error("An error occurred while requesting the database connection."))),i.addEventListener("blocked",()=>e(Error("The request for the database connection has been blocked.")))})}async disconnect(){return this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close(),this._database=null,this._connected=!1),!0}async load(t,e){const i=await this.getObjectStore(t);return new Promise((t,s)=>{const r=i.get(e);r.addEventListener("success",()=>t(r.result?.data??null)),r.addEventListener("error",()=>s(Error("An error occurred while loading an item.")))})}async save(t,e,i){const s=await this.getObjectStore(t,"readwrite");return new Promise((t,r)=>{const n=s.put({name:e,data:i});n.addEventListener("success",()=>t()),n.addEventListener("error",()=>r(Error("An error occurred while saving an item.")))})}async delete(t,e){const i=await this.getObjectStore(t,"readwrite");return new Promise((t,s)=>{const r=i.delete(e);r.addEventListener("success",()=>t(!0)),r.addEventListener("error",()=>s(Error("An error occurred while deleting an item.")))})}async clearStorage(t){const e=await this.getObjectStore(t,"readwrite");return new Promise((t,i)=>{const s=e.clear();s.addEventListener("success",()=>t(!0)),s.addEventListener("error",()=>i(Error("An error occurred while clearing a storage.")))})}async deleteStorage(){return await this.disconnect(),new Promise((t,e)=>{const i=indexedDB.deleteDatabase(this.name);i.addEventListener("success",()=>t(!0)),i.addEventListener("error",()=>e(Error("An error occurred while deleting a storage.")))})}destroy(){this._database&&(this._database.removeEventListener("close",this._onCloseHandler),this._database.removeEventListener("versionchange",this._onCloseHandler),this._database.close()),this._database=null,this._connected=!1}}class sn{constructor(t){const e="string"==typeof t?{name:t}:t;this._db=new en(e.name,e.version??1,e.storeNames??["font","video","music","sound","image","texture","text","svg","json","binary","wasm","vtt"],e.migrations)}async load(t,e){return this._db.load(t,e)}async save(t,e,i){return this._db.save(t,e,i)}async delete(t,e){return this._db.delete(t,e)}async clear(t){return this._db.clearStorage(t)}destroy(){this._db.destroy()}}const rn="@dimforge/rapier2d-compat",nn=65535,on=1/60,an={lineWidth:1,solidLineColor:new K(64,196,255,1),solidFillColor:new K(64,196,255,.12),triggerLineColor:new K(255,180,48,1),triggerFillColor:new K(255,180,48,.08)},hn=async()=>await import(rn),ln=(t,e)=>{if(!Number.isFinite(t))throw new Error(`${e} must be a finite number.`)},un=(t,e)=>{if(ln(t,e),t<=0)throw new Error(`${e} must be greater than zero.`)},dn=(t,e)=>{if(!Number.isInteger(t)||t<0||t>15)throw new Error(`${e} must be an integer between 0 and 15.`)},cn=(t,e)=>void 0===t?e:"number"==typeof t?(dn(t,"collision group"),1<<t):0===t.length?0:t.reduce((t,e,i)=>(dn(e,`collision groups[${i}]`),t|1<<e),0),pn=t=>{const e=cn(t?.membership,1),i=cn(t?.collidesWith,nn);return(e&nn)<<16|i&nn},_n=t=>({x:t.offsetX??0,y:t.offsetY??0}),fn=(t,e,i)=>{const s=Math.cos(i),r=Math.sin(i);return{x:t*s-e*r,y:t*r+e*s}},mn=t=>{(t=>{if("box"===t.type)return un(t.width,"Box width"),un(t.height,"Box height"),ln(t.offsetX??0,"Box offsetX"),ln(t.offsetY??0,"Box offsetY"),void ln(t.offsetRotation??0,"Box offsetRotation");un(t.radius,"Circle radius"),ln(t.offsetX??0,"Circle offsetX"),ln(t.offsetY??0,"Circle offsetY")})(t.shape),ln(t.friction??0,"friction"),ln(t.restitution??0,"restitution"),ln(t.density??0,"density"),ln(t.gravityScale??1,"gravityScale"),ln(t.linearDamping??0,"linearDamping"),ln(t.angularDamping??0,"angularDamping"),pn(t.collisionFilter)};class gn{constructor(t,e,i,s,r){this._world=t,this.node=e,this._body=i,this._collider=s,this.bodyType=r.type??"dynamic",this.shape=r.shape,this.trigger=r.trigger??!1,this._syncMode=r.syncMode??"physicsToNode"}get bodyHandle(){return this._body.handle}get colliderHandle(){return this._collider.handle}getBody(){return this._body}get syncMode(){return this._syncMode}set syncMode(t){this._syncMode=t}get x(){return this._body.translation().x}get y(){return this._body.translation().y}get rotation(){return this._body.rotation()}setSyncMode(t){return this._syncMode=t,this}teleport(t,e,i=this.node.rotation){return this._world.writeBodyTransform(this._body,t,e,i,!0),this.node.setPosition(t,e),this.node.setRotation(i),this}syncBodyFromNode(t=!0){return this._world.writeBodyTransform(this._body,this.node.x,this.node.y,this.node.rotation,t),this}syncNodeFromBody(){const t=this._body.translation();return this.node.setPosition(t.x,t.y),this.node.setRotation(this._body.rotation()),this}setCollisionFilter(t){const e=pn(t);return this._collider.setCollisionGroups(e),this._collider.setSolverGroups(e),this}destroy(){this._world.removeBinding(this)}}class yn{constructor(t,e,i){this.onCollisionEnter=new F,this.onCollisionExit=new F,this.onTriggerEnter=new F,this.onTriggerExit=new F,this._bindings=new Set,this._nodeBindings=new Map,this._colliderBindings=new Map,this._rapier=t,this._world=e,this._eventQueue=i}static async create(t={}){const e=t.moduleLoader??hn;let i=null;try{i=await e()}catch(t){const e=t instanceof Error?t.message:String(t);throw new Error(`Rapier physics module is unavailable. Install "${rn}" or provide a custom module loader. Original error: ${e}`)}const s=(t=>{const e=t,i=e.Vector2,s=e.World,r=e.EventQueue,n=e.RigidBodyDesc,o=e.ColliderDesc;if("function"!=typeof i||"function"!=typeof s||"function"!=typeof r)throw new Error("Invalid Rapier module loader result. Expected Vector2, World, and EventQueue exports.");if("object"!=typeof n||null===n||"object"!=typeof o||null===o)throw new Error("Invalid Rapier module loader result. Expected RigidBodyDesc and ColliderDesc exports.");const a=e.ActiveEvents,h="number"==typeof a?.COLLISION_EVENTS?a.COLLISION_EVENTS:void 0;return{init:"function"==typeof e.init?e.init:void 0,vector2:i,worldConstructor:s,eventQueueConstructor:r,rigidBodyDescFactory:n,colliderDescFactory:o,activeCollisionEvents:h}})(i);"function"==typeof s.init&&await s.init();const r=t.gravityX??0,n=t.gravityY??9.81;ln(r,"gravityX"),ln(n,"gravityY");const o=new s.worldConstructor(new s.vector2(r,n)),a=new s.eventQueueConstructor(!0);return new yn(s,o,a)}get gravity(){return{x:this._world.gravity.x,y:this._world.gravity.y}}setGravity(t,e){return ln(t,"gravityX"),ln(e,"gravityY"),this._world.gravity.x=t,this._world.gravity.y=e,this}hasNode(t){return this._nodeBindings.has(t)}getBinding(t){return this._nodeBindings.get(t)??null}attachNode(t,e){if(this._nodeBindings.has(t))throw new Error("This SceneNode is already attached to a physics body.");mn(e);const i=this.createBodyDescriptor(t,e),s=this._world.createRigidBody(i),r=this.createColliderDescriptor(e),n=this._world.createCollider(r,s),o=new gn(this,t,s,n,e);return this._bindings.add(o),this._nodeBindings.set(t,o),this._colliderBindings.set(n.handle,o),o}detachNode(t){const e=this._nodeBindings.get(t);return e&&this.removeBinding(e),this}step(t=on){if(ln(t,"deltaSeconds"),t<0)throw new Error("deltaSeconds must be zero or greater.");return this.applyStepDelta(t),this._world.step(this._eventQueue),this.drainCollisionEvents(),this.syncNodeTransforms(),this}syncNodeTransforms(){for(const t of this._bindings)"physicsToNode"===t.syncMode&&t.syncNodeFromBody();return this}createDebugGraphics(t={}){const e=new Gr;return e.setCullable(!1),this.updateDebugGraphics(e,t),e}updateDebugGraphics(t,e={}){const i=e.lineWidth??an.lineWidth,s=e.solidLineColor??an.solidLineColor,r=e.solidFillColor??an.solidFillColor,n=e.triggerLineColor??an.triggerLineColor,o=e.triggerFillColor??an.triggerFillColor;t.clear(),t.lineWidth=i;for(const e of this._bindings){const i={x:e.x,y:e.y},a=e.rotation,h=e.trigger?n:s,l=e.trigger?o:r;if(t.lineColor=h,t.fillColor=l,"box"===e.shape.type){const s=this.buildBoxPath(e.shape,i.x,i.y,a);t.drawPolygon(s)}else{const s=_n(e.shape),r=fn(s.x,s.y,a);t.drawCircle(i.x+r.x,i.y+r.y,e.shape.radius)}}return t}destroy(){for(const t of Array.from(this._bindings))this.removeBinding(t);this.onCollisionEnter.destroy(),this.onCollisionExit.destroy(),this.onTriggerEnter.destroy(),this.onTriggerExit.destroy()}writeBodyTransform(t,e,i,s,r){t.setTranslation(new this._rapier.vector2(e,i),r),t.setRotation(s,r)}removeBinding(t){this._bindings.has(t)&&(this._bindings.delete(t),this._nodeBindings.delete(t.node),this._colliderBindings.delete(t.colliderHandle),this._world.removeRigidBody(t.getBody()))}createBodyDescriptor(t,e){const i=e.type??"dynamic";let s=this._rapier.rigidBodyDescFactory.dynamic();switch(i){case"static":s=this._rapier.rigidBodyDescFactory.fixed();break;case"kinematic":if("function"==typeof this._rapier.rigidBodyDescFactory.kinematicPositionBased)s=this._rapier.rigidBodyDescFactory.kinematicPositionBased();else{if("function"!=typeof this._rapier.rigidBodyDescFactory.kinematicVelocityBased)throw new Error("Rapier module does not expose a kinematic rigid-body descriptor.");s=this._rapier.rigidBodyDescFactory.kinematicVelocityBased()}break;default:s=this._rapier.rigidBodyDescFactory.dynamic()}return s.setTranslation(t.x,t.y).setRotation(t.rotation).setLinearDamping(e.linearDamping??0).setAngularDamping(e.angularDamping??0).setGravityScale(e.gravityScale??1).lockRotations(e.lockRotation??!1),s}createColliderDescriptor(t){const e=t.shape,i="box"===e.type?this._rapier.colliderDescFactory.cuboid(e.width/2,e.height/2):this._rapier.colliderDescFactory.ball(e.radius),s=_n(e),r=pn(t.collisionFilter);i.setTranslation(s.x,s.y).setRotation("box"===e.type?e.offsetRotation??0:0).setSensor(t.trigger??!1).setFriction(t.friction??.5).setRestitution(t.restitution??0).setDensity(t.density??1).setCollisionGroups(r).setSolverGroups(r);const n=this._rapier.activeCollisionEvents;return"number"==typeof n&&i.setActiveEvents(n),i}applyStepDelta(t){const e=this._world;"number"==typeof e.timestep&&(e.timestep=t),e.integrationParameters&&"number"==typeof e.integrationParameters.dt&&(e.integrationParameters.dt=t)}drainCollisionEvents(){this._eventQueue.drainCollisionEvents((t,e,i)=>{const s=this._colliderBindings.get(t),r=this._colliderBindings.get(e);if(!s||!r)return;const n=s.trigger||r.trigger,o={started:i,trigger:n,first:s,second:r};n?i?this.onTriggerEnter.dispatch(o):this.onTriggerExit.dispatch(o):i?this.onCollisionEnter.dispatch(o):this.onCollisionExit.dispatch(o)})}buildBoxPath(t,e,i,s){const r=t.width/2,n=t.height/2,o=[{x:-r,y:-n},{x:r,y:-n},{x:r,y:n},{x:-r,y:n}],a=_n(t),h=t.offsetRotation??0,l=[];for(const t of o){const r=fn(t.x,t.y,h),n={x:r.x+a.x,y:r.y+a.y},o=fn(n.x,n.y,s);l.push(e+o.x,i+o.y)}return l}}const xn=async(t={})=>await yn.create(t);export{Ss as AbstractAssetFactory,Ki as AbstractMedia,Ve as AbstractWebGl2BatchedRenderer,Ce as AbstractWebGl2Renderer,ti as AbstractWebGpuRenderer,Wr as AnimatedSprite,Qs as Application,js as ApplicationStatus,Si as ArcadeStickGamepadMapping,ir as AudioAnalyser,Us as BinaryFactory,Q as BlendModes,Kr as BlurFilter,ne as Bounds,et as BufferTypes,it as BufferUsage,zs as BundleLoadError,Zr as CacheFirstStrategy,jr as CallbackRenderPass,pi as ChannelSize,Pr as Circle,Or as CircleGeometry,L as Clock,K as Color,Fr as ColorAffector,Qr as ColorFilter,Js as Container,ge as Drawable,ye as DrawableShape,Br as Ellipse,Ts as FactoryRegistry,$r as Filter,ht as Flags,Cs as FontFactory,Dr as ForceAffector,Bi as GameCubeGamepadMapping,xi as Gamepad,gi as GamepadChannel,vi as GamepadControl,bi as GamepadMapping,yi as GamepadMappingFamily,ur as GamepadPromptLayouts,Pi as GenericDualAnalogGamepadMapping,xe as Geometry,Gr as Graphics,Bs as ImageFactory,en as IndexedDbDatabase,sn as IndexedDbStore,dr as Input,$i as InputManager,ct as Interval,Ei as JoyConLeftGamepadMapping,Ri as JoyConRightGamepadMapping,xs as Json,Es as JsonFactory,_i as Keyboard,Cr as Line,Ys as Loader,at as Matrix,ms as Music,As as MusicFactory,Jr as NetworkOnlyStrategy,ae as ObservableSize,nt as ObservableVector,He as Particle,Ur as ParticleOptions,Xe as ParticleSystem,Ai as PlayStationGamepadMapping,wi as Pointer,mi as PointerState,fi as PointerStateFlag,Lr as PolarVector,Rr as Polygon,Zs as Quadtree,i as Random,gn as RapierPhysicsBinding,yn as RapierPhysicsWorld,re as Rectangle,Se as RenderBackendType,me as RenderNode,ce as RenderTarget,_e as RenderTargetPass,pe as RenderTexture,je as RendererRegistry,tt as RenderingPrimitives,Yr as Sampler,Ir as ScaleAffector,Z as ScaleModes,tr as Scene,ve as SceneManager,oe as SceneNode,kr as Segment,Me as Shader,Re as ShaderAttribute,st as ShaderPrimitives,Ae as ShaderUniform,F as Signal,e as Size,gs as Sound,ks as SoundFactory,qe as Sprite,We as SpriteFlags,zr as Spritesheet,ki as SteamControllerGamepadMapping,vs as SvgAsset,Ns as SvgFactory,Li as SwitchProGamepadMapping,Xr as Text,ws as TextAsset,Ls as TextFactory,qr as TextStyle,Ye as Texture,Fs as TextureFactory,r as Time,er as Timer,Nr as TorqueAffector,ut as Transformable,lt as TransformableFlags,Vr as UniversalEmitter,de as Vector,ys as Video,Is as VideoFactory,le as View,he as ViewFlags,bs as VttAsset,Gs as VttFactory,Vs as WasmFactory,Ge as WebGl2ParticleRenderer,ze as WebGl2PrimitiveRenderer,Ie as WebGl2RenderBuffer,Je as WebGl2RenderManager,ke as WebGl2ShaderBlock,Oe as WebGl2SpriteRenderer,Te as WebGl2VertexArrayObject,ui as WebGpuParticleRenderer,ri as WebGpuPrimitiveRenderer,ci as WebGpuRenderManager,oi as WebGpuSpriteRenderer,J as WrapModes,Fi as XboxGamepadMapping,Y as bezierCurveTo,xr as buildCircle,wr as buildEllipse,gr as buildLine,yr as buildPath,vr as buildPolygon,br as buildRectangle,Tr as buildStar,Yi as builtInGamepadDefinitions,k as canvasSourceToDataUrl,G as clamp,xn as createRapierPhysicsWorld,$e as createRenderStats,Fe as createWebGl2ShaderRuntime,fs as decodeAudioData,Ws as defineAssetManifest,N as degreesPerRadian,V as degreesToRadians,Ps as determineMimeType,P as emptyArrayBuffer,cs as getAudioContext,R as getCanvasSourceSize,Qt as getCollisionCircleCircle,Zt as getCollisionCircleRectangle,Jt as getCollisionPolygonCircle,Kt as getCollisionRectangleRectangle,te as getCollisionSat,X as getDistance,_s as getOfflineAudioContext,b as getPreciseTime,A as getTextureSourceSize,$ as getVoronoiRegion,ei as getWebGpuBlendState,M as hours,H as inRange,Gt as intersectionCircleCircle,zt as intersectionCircleEllipse,Xt as intersectionCirclePoly,Yt as intersectionEllipseEllipse,jt as intersectionEllipsePoly,Ft as intersectionLineCircle,Dt as intersectionLineEllipse,kt as intersectionLineLine,It as intersectionLinePoly,Lt as intersectionLineRect,Et as intersectionPointCircle,Rt as intersectionPointEllipse,Pt as intersectionPointLine,Mt as intersectionPointPoint,At as intersectionPointPoly,Bt as intersectionPointRect,$t as intersectionPolyPoly,Ut as intersectionRectCircle,Vt as intersectionRectEllipse,Ot as intersectionRectPoly,Nt as intersectionRectRect,Ct as intersectionSat,ps as isAudioContextReady,q as isPowerOfTwo,W as lerp,Wi as matchesIds,T as milliseconds,C as minutes,f as noop,zi as normalizeIds,ds as onAudioContextReady,qi as parseGamepadDescriptor,j as quadraticCurveTo,I as radiansPerDegree,O as radiansToDegrees,_ as rand,B as removeArrayItems,Ke as resetRenderStats,Hi as resolveDefinition,Xi as resolveGamepadDefinition,S as seconds,z as sign,m as stopEvent,E as supportsCodec,v as supportsEventOptions,y as supportsIndexedDb,w as supportsPointerEvents,x as supportsTouchEvents,g as supportsWebAudio,D as tau,U as trimRotation,Be as webGl2PrimitiveArrayConstructors,Pe as webGl2PrimitiveByteSizeMapping,Ee as webGl2PrimitiveTypeNames};
|
|
2
2
|
//# sourceMappingURL=exo.esm.min.js.map
|