excalibur 0.32.0-alpha.1570 → 0.32.0-alpha.1572
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 +27 -1
- package/build/dist/Collision/BoundingBox.d.ts +9 -3
- package/build/dist/Debug/DebugConfig.d.ts +14 -1
- package/build/dist/Graphics/Context/ExcaliburGraphicsContext.d.ts +13 -0
- package/build/dist/Graphics/Context/ExcaliburGraphicsContext2DCanvas.d.ts +2 -1
- package/build/dist/Graphics/Context/ExcaliburGraphicsContextWebGL.d.ts +20 -3
- package/build/dist/Graphics/Context/debug-circle-renderer/debug-circle-renderer.d.ts +23 -0
- package/build/dist/Graphics/Context/{line-renderer/line-renderer.d.ts → debug-line-renderer/debug-line-renderer.d.ts} +5 -7
- package/build/dist/Graphics/Context/{point-renderer/point-renderer.d.ts → debug-point-renderer/debug-point-renderer.d.ts} +2 -2
- package/build/dist/Graphics/Context/debug-text.d.ts +5 -1
- package/build/dist/Graphics/Debug.d.ts +5 -5
- package/build/dist/excalibur.development.js +504 -164
- package/build/dist/excalibur.js +504 -164
- package/build/dist/excalibur.min.development.js +158 -47
- package/build/dist/excalibur.min.js +158 -47
- package/build/esm/excalibur.development.js +504 -164
- package/build/esm/excalibur.js +504 -164
- package/build/esm/excalibur.min.development.js +2869 -2610
- package/build/esm/excalibur.min.js +2869 -2610
- package/package.json +1 -1
|
@@ -1,46 +1,48 @@
|
|
|
1
|
-
/*! excalibur - 0.32.0-alpha.
|
|
1
|
+
/*! excalibur - 0.32.0-alpha.1572+72a3430 - 2025-11-28
|
|
2
2
|
https://github.com/excaliburjs/Excalibur
|
|
3
3
|
Copyright (c) 2025 Excalibur.js <https://github.com/excaliburjs/Excalibur/graphs/contributors>
|
|
4
4
|
Licensed BSD-2-Clause
|
|
5
5
|
@preserve */
|
|
6
|
-
(function(d,Me){typeof exports=="object"&&typeof module!="undefined"?Me(exports):typeof define=="function"&&define.amd?define(["exports"],Me):(d=typeof globalThis!="undefined"?globalThis:d||self,Me(d.ex={}))})(this,function(d){"use strict";function Me(){if(typeof window=="undefined"&&(window={audioContext:function(){}}),typeof window!="undefined"&&!window.requestAnimationFrame&&(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(r){window.setInterval(r,1e3/60)}),typeof window!="undefined"&&!window.cancelAnimationFrame&&(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),typeof window!="undefined"&&!window.AudioContext){if(window.webkitAudioContext){const t=window.webkitAudioContext.prototype.decodeAudioData;window.webkitAudioContext.prototype.decodeAudioData=function(e){return new Promise((i,s)=>{t.call(this,e,i,s)})}}window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext}typeof window!="undefined"&&!window.devicePixelRatio&&(window.devicePixelRatio=window.devicePixelRatio||1),typeof window!="undefined"&&!window.requestIdleCallback&&(window.requestIdleCallback=window.requestIdleCallback||function(r){const t=Date.now();return setTimeout(function(){r({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})},1)},window.cancelIdleCallback=window.cancelIdleCallback||function(r){clearTimeout(r)})}const _s=class jt{static useCanvasGraphicsContext(){jt.enable("use-canvas-context")}static useLegacyImageRenderer(){jt.enable("use-legacy-image-renderer")}static freeze(){jt._FROZEN=!0}static _reset(){jt._FROZEN=!1,jt._FLAGS={}}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");jt._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");jt._FLAGS[t]=!1}static isEnabled(t){return!!jt._FLAGS[t]}static show(){return Object.keys(jt._FLAGS)}};_s._FROZEN=!1,_s._FLAGS={};let De=_s;function _e(r,t){return{type:r,value:t}}class wt{constructor(){this._isCompleted=!1,this.promise=new Promise((t,e)=>{this._resolver=t,this._rejecter=e})}get isCompleted(){return this._isCompleted}resolve(t){this._isCompleted||(this._isCompleted=!0,this._resolver(t))}reject(t){this._isCompleted||(this._isCompleted=!0,this._rejecter(t))}}class X{constructor(){this._paused=!1,this._empty=!0,this._listeners={},this._listenersOnce={},this._pipes=[]}clear(){this._listeners={},this._listenersOnce={},this._pipes.length=0,this._empty=!0}on(t,e){var i;return this._empty=!1,this._listeners[t]=(i=this._listeners[t])!=null?i:[],this._listeners[t].push(e),{close:()=>this.off(t,e)}}once(t,e){var i;return this._empty=!1,this._listenersOnce[t]=(i=this._listenersOnce[t])!=null?i:[],this._listenersOnce[t].push(e),{close:()=>this.off(t,e)}}off(t,e){var i,s;if(e){const n=(i=this._listeners[t])==null?void 0:i.filter(a=>a!==e);this._listeners[t]=n;const o=(s=this._listenersOnce[t])==null?void 0:s.filter(a=>a!==e);this._listenersOnce[t]=o}else delete this._listeners[t]}emit(t,e){if(this._empty||this._paused)return;const i=this._listeners[t];if(i)for(let n=0;n<i.length;n++)i[n](e);const s=this._listenersOnce[t];if(this._listenersOnce[t]=[],s)for(let n=0;n<s.length;n++)s[n](e);for(let n=0;n<this._pipes.length;n++)this._pipes[n].emit(t,e)}pipe(t){if(this===t)throw Error("Cannot pipe to self");return this._empty=!1,this._pipes.push(t),{close:()=>{const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}}}unpipe(t){const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}pause(){this._paused=!0}unpause(){this._paused=!1}}var Fe=(r=>(r.Canvas="Canvas",r.Document="Document",r))(Fe||{}),Z=(r=>(r.ShortestPath="shortest-path",r.LongestPath="longest-path",r.Clockwise="clockwise",r.CounterClockwise="counter-clockwise",r))(Z||{});const fs=4294967295,Oa=Date.now();let Ha=0;class ie{constructor(t){this._lowerMask=2147483647,this._upperMask=2147483648,this._w=32,this._n=624,this._m=397,this._a=2567483615,this._u=11,this._s=7,this._b=2636928640,this._t=15,this._c=4022730752,this._l=18,this._f=1812433253,this._mt=new Array(this._n),this._mt[0]=(t||Oa+Ha++)>>>0,this._seed=this._mt[0];for(let e=1;e<this._n;e++){const i=this._mt[e-1]^this._mt[e-1]>>>this._w-2;this._mt[e]=(this._f*((i&4294901760)>>>16)<<16)+this._f*(i&65535)+e>>>0}this._index=this._n}_twist(){const t=[0,this._a];let e=0,i=0;for(;i<this._n-this._m;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+this._m]^e>>>1^t[e&1]&fs;for(;i<this._n-1;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+(this._m-this._n)]^e>>>1^t[e&1]&fs;e=this._mt[this._n-1]&this._upperMask|this._mt[0]&this._lowerMask,this._mt[this._n-1]=this._mt[this._m-1]^e>>>1^t[e&1]&fs,this._index=0}nextInt(){this._index>=this._n&&this._twist();let t=this._mt[this._index++];return t^=t>>>this._u,t^=t<<this._s&this._b,t^=t<<this._t&this._c,t^=t>>>this._l,t>>>0}next(){return this.nextInt()*(1/4294967296)}floating(t,e){return(e-t)*this.next()+t}integer(t,e){return Math.floor((e-t+1)*this.next()+t)}bool(t=.5){return this.next()<=t}pickOne(t){return t[this.integer(0,t.length-1)]}pickSet(t,e,i=!1){return i?this._pickSetWithDuplicates(t,e):this._pickSetWithoutDuplicates(t,e)}_pickSetWithoutDuplicates(t,e){if(e>t.length||e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 < n <= length");if(e===t.length)return t;const i=new Array(e);let s=0;const n=t.slice(0);for(;s<e;){const o=this.integer(0,n.length-1);i[s++]=n[o],n.splice(o,1)}return i}_pickSetWithDuplicates(t,e){if(e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT");const i=new Array(e);for(let s=0;s<e;s++)i[s]=this.pickOne(t);return i}shuffle(t){const e=t.slice(0);let i;for(let s=0;s<e.length-2;s++){const n=this.integer(s,e.length-1);i=e[s],e[s]=e[n],e[n]=i}return e}range(t,e,i){const s=new Array(t);for(let n=0;n<t;n++)s[n]=this.integer(e,i);return s}d4(){return this.integer(1,4)}d6(){return this.integer(1,6)}d8(){return this.integer(1,8)}d10(){return this.integer(1,10)}d12(){return this.integer(1,12)}d20(){return this.integer(1,20)}get seed(){return this._seed}}const et=Math.PI*2;function Na(r){return r>=0?r-Math.floor(r):r-Math.ceil(r)}function V(r){return r===0?0:r<0?-1:1}function F(r,t,e){return Math.min(Math.max(t,r),e)}function ar(r,t,e){return Math.abs(r-t)<e}function Zt(r){let t=r;if(r>=et)for(;t>=et;)t-=et;if(r<0)for(;t<0;)t+=et;return t}function hr(r){return 180/Math.PI*r}function Wa(r){return r/180*Math.PI}const Ga=(r,t)=>Array.from(new Array(t-r+1),(e,i)=>i+r);function Ot(r,t,e=new ie){return e?e.floating(r,t):r+Math.random()*(t-r)}function Va(r,t,e=new ie){return e?e.integer(r,t):Math.round(Ot(r,t))}const lr=class q{constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}static get Zero(){return new q(0,0)}static get One(){return new q(1,1)}static get Half(){return new q(.5,.5)}static get Up(){return new q(0,-1)}static get Down(){return new q(0,1)}static get Left(){return new q(-1,0)}static get Right(){return new q(1,0)}static fromAngle(t){return new q(Math.cos(t),Math.sin(t))}static isValid(t){return!(t==null||isNaN(t.x)||isNaN(t.y)||t.x===1/0||t.y===1/0||t.x===-1/0||t.y===-1/0)}static distance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}static min(t,e){return new q(Math.min(t.x,e.x),Math.min(t.y,e.y))}static max(t,e){return new q(Math.max(t.x,e.x),Math.max(t.y,e.y))}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}setTo(t,e){this.x=t,this.y=e}equals(t,e=q.EQUALS_EPSILON){return Math.abs(this.x-t.x)<=e&&Math.abs(this.y-t.y)<=e}distance(t){if(!t)return Math.sqrt(this.x*this.x+this.y*this.y);const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}squareDistance(t){t||(t=q.Zero);const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}clampMagnitude(t){const e=this.magnitude,i=F(e,0,t);return this.magnitude=i,this}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}get magnitude(){return this.distance()}set magnitude(t){this.normalize().scale(t,this)}normalize(){const t=this.distance();return t===0?q.Zero:new q(this.x/t,this.y/t)}average(t){return this.add(t).scale(.5)}scale(t,e){const i=e||new q(0,0);return t instanceof q?(i.x=this.x*t.x,i.y=this.y*t.y):(i.x=this.x*t,i.y=this.y*t),i}add(t,e){return e?(e.x=this.x+t.x,e.y=this.y+t.y,e):new q(this.x+t.x,this.y+t.y)}sub(t,e){const i=e||new q(0,0),s=this.x-t.x,n=this.y-t.y;return i.x=s,i.y=n,i}addEqual(t){return this.setTo(this.x+t.x,this.y+t.y),this}subEqual(t){return this.setTo(this.x-t.x,this.y-t.y),this}scaleEqual(t){return this.setTo(this.x*t,this.y*t),this}dot(t){return this.x*t.x+this.y*t.y}cross(t){if(t instanceof q)return this.x*t.y-this.y*t.x;if(typeof t=="number")return new q(t*this.y,-t*this.x)}static cross(t,e){return new q(-t*e.y,t*e.x)}perpendicular(){return new q(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Zt(Math.atan2(this.y,this.x))}angleBetween(t,e){const i=this.toAngle(),s=Zt(t);let n=0,o=0;switch(s>i?n=s-i:n=(et-i+s)%et,o=(n-et)%et,e){case Z.ShortestPath:return Math.abs(n)<Math.abs(o)?n:o;case Z.LongestPath:return Math.abs(n)>Math.abs(o)?n:o;case Z.Clockwise:return n;case Z.CounterClockwise:return o}}rotate(t,e,i){const s=i||new q(0,0);e||(e=new q(0,0));const n=Math.sin(t),o=Math.cos(t),a=o*(this.x-e.x)-n*(this.y-e.y)+e.x,h=n*(this.x-e.x)+o*(this.y-e.y)+e.y;return s.x=a,s.y=h,s}clone(t){const e=t!=null?t:new q(0,0);return e.x=this.x,e.y=this.y,e}toString(t){return t?`(${this.x.toFixed(t)}, ${this.y.toFixed(t)})`:`(${this.x}, ${this.y})`}lerp(t,e){e=F(e,0,1);const i=new q(0,0);return i.x=this.x+(t.x-this.x)*e,i.y=this.y+(t.y-this.y)*e,i}};lr.EQUALS_EPSILON=.001;let v=lr;function x(r,t){return new v(r,t)}class gs extends v{constructor(t){super(0,0),this._getX=t.getX,this._getY=t.getY,this._setX=t.setX,this._setY=t.setY}get x(){return this._x=this._getX()}set x(t){this._setX(t),this._x=t}get y(){return this._y=this._getY()}set y(t){this._setY(t),this._y=t}}var cr=(r=>(r[r.X=12]="X",r[r.Y=13]="Y",r))(cr||{});class yt{constructor(){this.data=new Float32Array(16),this._scaleX=1,this._scaleSignX=1,this._scaleY=1,this._scaleSignY=1}static ortho(t,e,i,s,n,o){const a=new yt;return a.data[0]=2/(e-t),a.data[1]=0,a.data[2]=0,a.data[3]=0,a.data[4]=0,a.data[5]=2/(s-i),a.data[6]=0,a.data[7]=0,a.data[8]=0,a.data[9]=0,a.data[10]=-2/(o-n),a.data[11]=0,a.data[12]=-(e+t)/(e-t),a.data[13]=-(s+i)/(s-i),a.data[14]=-(o+n)/(o-n),a.data[15]=1,a}clone(t){const e=t||new yt;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e.data[6]=this.data[6],e.data[7]=this.data[7],e.data[8]=this.data[8],e.data[9]=this.data[9],e.data[10]=this.data[10],e.data[11]=this.data[11],e.data[12]=this.data[12],e.data[13]=this.data[13],e.data[14]=this.data[14],e.data[15]=this.data[15],e}toDOMMatrix(){return new DOMMatrix([...this.data])}static fromFloat32Array(t){const e=new yt;return e.data=t,e}static identity(){const t=new yt;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}static translation(t,e){const i=yt.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=yt.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=yt.identity();return e.data[0]=Math.cos(t),e.data[4]=-Math.sin(t),e.data[1]=Math.sin(t),e.data[5]=Math.cos(t),e}multiply(t,e){if(t instanceof v){const i=e||new v(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[4]+this.data[12],o=s.x*this.data[1]+s.y*this.data[5]+this.data[13];return i.x=n,i.y=o,i}else{const i=e||new yt,s=t,n=this.data[0],o=this.data[1],a=this.data[2],h=this.data[3],l=this.data[4],c=this.data[5],u=this.data[6],_=this.data[7],f=this.data[8],p=this.data[9],g=this.data[10],w=this.data[11],m=this.data[12],b=this.data[13],T=this.data[14],C=this.data[15],S=s.data[0],I=s.data[1],y=s.data[2],k=s.data[3],U=s.data[4],z=s.data[5],Y=s.data[6],ht=s.data[7],$=s.data[8],G=s.data[9],ct=s.data[10],ft=s.data[11],E=s.data[12],Ee=s.data[13],Ie=s.data[14],Re=s.data[15];i.data[0]=n*S+l*I+f*y+m*k,i.data[1]=o*S+c*I+p*y+b*k,i.data[2]=a*S+u*I+g*y+T*k,i.data[3]=h*S+_*I+w*y+C*k,i.data[4]=n*U+l*z+f*Y+m*ht,i.data[5]=o*U+c*z+p*Y+b*ht,i.data[6]=a*U+u*z+g*Y+T*ht,i.data[7]=h*U+_*z+w*Y+C*ht,i.data[8]=n*$+l*G+f*ct+m*ft,i.data[9]=o*$+c*G+p*ct+b*ft,i.data[10]=a*$+u*G+g*ct+T*ft,i.data[11]=h*$+_*G+w*ct+C*ft,i.data[12]=n*E+l*Ee+f*Ie+m*Re,i.data[13]=o*E+c*Ee+p*Ie+b*Re,i.data[14]=a*E+u*Ee+g*Ie+T*Re,i.data[15]=h*E+_*Ee+w*Ie+C*Re;const yi=this.getScale();return i._scaleSignX=V(yi.x)*V(i._scaleSignX),i._scaleSignY=V(yi.y)*V(i._scaleSignY),i}}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5],l=this.data[6],c=this.data[7],u=this.data[8],_=this.data[9],f=this.data[10],p=this.data[11],g=this.data[12],w=this.data[13],m=this.data[14],b=this.data[15],T=0,C=1;return this.data[12]=i*t+a*e+u*T+g*C,this.data[13]=s*t+h*e+_*T+w*C,this.data[14]=n*t+l*e+f*T+m*C,this.data[15]=o*t+c*e+p*T+b*C,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return x(this.data[12],this.data[13])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=Math.sin(t),u=Math.cos(t);return this.data[0]=u*e+c*o,this.data[1]=u*i+c*a,this.data[2]=u*s+c*h,this.data[3]=u*n+c*l,this.data[4]=u*o-c*e,this.data[5]=u*a-c*i,this.data[6]=u*h-c*s,this.data[7]=u*l-c*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5],l=this.data[6],c=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=o*t,this.data[4]=a*e,this.data[5]=h*e,this.data[6]=l*e,this.data[7]=c*e,this}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[4]=-i*e.x,this.data[5]=s*e.y}getRotation(){const t=Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX());return Zt(t)}getScaleX(){const t=x(this.data[0],this.data[4]).magnitude;return this._scaleSignX*t}getScaleY(){const t=x(this.data[1],this.data[5]).magnitude;return this._scaleSignY*t}getScale(){return x(this.getScaleX(),this.getScaleY())}setScaleX(t){if(this._scaleX===t)return;this._scaleSignX=V(t);const e=x(this.data[0]*this._scaleSignX,this.data[4]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[4]=e.y*t,this._scaleX=t}setScaleY(t){if(this._scaleY===t)return;this._scaleSignY=V(t);const e=x(this.data[1]*this._scaleSignY,this.data[5]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[5]=e.y*t,this._scaleY=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}getBasisDeterminant(){return this.data[0]*this.data[5]-this.data[1]*this.data[4]}getAffineInverse(t){const i=1/this.getBasisDeterminant(),s=this.data[0],n=this.data[4],o=this.data[1],a=this.data[5],h=t||yt.identity();h.data[0]=a*i,h.data[1]=-o*i,h.data[4]=-n*i,h.data[5]=s*i;const l=this.data[12],c=this.data[13];return h.data[12]=-(l*h.data[0]+c*h.data[4]),h.data[13]=-(l*h.data[1]+c*h.data[5]),h}isIdentity(){return this.data[0]===1&&this.data[1]===0&&this.data[2]===0&&this.data[3]===0&&this.data[4]===0&&this.data[5]===1&&this.data[6]===0&&this.data[7]===0&&this.data[8]===0&&this.data[9]===0&&this.data[10]===1&&this.data[11]===0&&this.data[12]===0&&this.data[13]===0&&this.data[14]===0&&this.data[15]===1}toString(){return`
|
|
6
|
+
(function(d,Fe){typeof exports=="object"&&typeof module!="undefined"?Fe(exports):typeof define=="function"&&define.amd?define(["exports"],Fe):(d=typeof globalThis!="undefined"?globalThis:d||self,Fe(d.ex={}))})(this,function(d){"use strict";function Fe(){if(typeof window=="undefined"&&(window={audioContext:function(){}}),typeof window!="undefined"&&!window.requestAnimationFrame&&(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(r){window.setInterval(r,1e3/60)}),typeof window!="undefined"&&!window.cancelAnimationFrame&&(window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||function(){}),typeof window!="undefined"&&!window.AudioContext){if(window.webkitAudioContext){const t=window.webkitAudioContext.prototype.decodeAudioData;window.webkitAudioContext.prototype.decodeAudioData=function(e){return new Promise((i,s)=>{t.call(this,e,i,s)})}}window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext}typeof window!="undefined"&&!window.devicePixelRatio&&(window.devicePixelRatio=window.devicePixelRatio||1),typeof window!="undefined"&&!window.requestIdleCallback&&(window.requestIdleCallback=window.requestIdleCallback||function(r){const t=Date.now();return setTimeout(function(){r({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})},1)},window.cancelIdleCallback=window.cancelIdleCallback||function(r){clearTimeout(r)})}const gs=class Qt{static useCanvasGraphicsContext(){Qt.enable("use-canvas-context")}static useLegacyImageRenderer(){Qt.enable("use-legacy-image-renderer")}static freeze(){Qt._FROZEN=!0}static _reset(){Qt._FROZEN=!1,Qt._FLAGS={}}static enable(t){if(this._FROZEN)throw Error("Feature flags can only be enabled before Engine constructor time");Qt._FLAGS[t]=!0}static disable(t){if(this._FROZEN)throw Error("Feature flags can only be disabled before Engine constructor time");Qt._FLAGS[t]=!1}static isEnabled(t){return!!Qt._FLAGS[t]}static show(){return Object.keys(Qt._FLAGS)}};gs._FROZEN=!1,gs._FLAGS={};let De=gs;function fe(r,t){return{type:r,value:t}}class wt{constructor(){this._isCompleted=!1,this.promise=new Promise((t,e)=>{this._resolver=t,this._rejecter=e})}get isCompleted(){return this._isCompleted}resolve(t){this._isCompleted||(this._isCompleted=!0,this._resolver(t))}reject(t){this._isCompleted||(this._isCompleted=!0,this._rejecter(t))}}class X{constructor(){this._paused=!1,this._empty=!0,this._listeners={},this._listenersOnce={},this._pipes=[]}clear(){this._listeners={},this._listenersOnce={},this._pipes.length=0,this._empty=!0}on(t,e){var i;return this._empty=!1,this._listeners[t]=(i=this._listeners[t])!=null?i:[],this._listeners[t].push(e),{close:()=>this.off(t,e)}}once(t,e){var i;return this._empty=!1,this._listenersOnce[t]=(i=this._listenersOnce[t])!=null?i:[],this._listenersOnce[t].push(e),{close:()=>this.off(t,e)}}off(t,e){var i,s;if(e){const n=(i=this._listeners[t])==null?void 0:i.filter(a=>a!==e);this._listeners[t]=n;const o=(s=this._listenersOnce[t])==null?void 0:s.filter(a=>a!==e);this._listenersOnce[t]=o}else delete this._listeners[t]}emit(t,e){if(this._empty||this._paused)return;const i=this._listeners[t];if(i)for(let n=0;n<i.length;n++)i[n](e);const s=this._listenersOnce[t];if(this._listenersOnce[t]=[],s)for(let n=0;n<s.length;n++)s[n](e);for(let n=0;n<this._pipes.length;n++)this._pipes[n].emit(t,e)}pipe(t){if(this===t)throw Error("Cannot pipe to self");return this._empty=!1,this._pipes.push(t),{close:()=>{const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}}}unpipe(t){const e=this._pipes.indexOf(t);e>-1&&this._pipes.splice(e,1)}pause(){this._paused=!0}unpause(){this._paused=!1}}var Be=(r=>(r.Canvas="Canvas",r.Document="Document",r))(Be||{}),j=(r=>(r.ShortestPath="shortest-path",r.LongestPath="longest-path",r.Clockwise="clockwise",r.CounterClockwise="counter-clockwise",r))(j||{});const ps=4294967295,Oa=Date.now();let Ha=0;class se{constructor(t){this._lowerMask=2147483647,this._upperMask=2147483648,this._w=32,this._n=624,this._m=397,this._a=2567483615,this._u=11,this._s=7,this._b=2636928640,this._t=15,this._c=4022730752,this._l=18,this._f=1812433253,this._mt=new Array(this._n),this._mt[0]=(t||Oa+Ha++)>>>0,this._seed=this._mt[0];for(let e=1;e<this._n;e++){const i=this._mt[e-1]^this._mt[e-1]>>>this._w-2;this._mt[e]=(this._f*((i&4294901760)>>>16)<<16)+this._f*(i&65535)+e>>>0}this._index=this._n}_twist(){const t=[0,this._a];let e=0,i=0;for(;i<this._n-this._m;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+this._m]^e>>>1^t[e&1]&ps;for(;i<this._n-1;i++)e=this._mt[i]&this._upperMask|this._mt[i+1]&this._lowerMask,this._mt[i]=this._mt[i+(this._m-this._n)]^e>>>1^t[e&1]&ps;e=this._mt[this._n-1]&this._upperMask|this._mt[0]&this._lowerMask,this._mt[this._n-1]=this._mt[this._m-1]^e>>>1^t[e&1]&ps,this._index=0}nextInt(){this._index>=this._n&&this._twist();let t=this._mt[this._index++];return t^=t>>>this._u,t^=t<<this._s&this._b,t^=t<<this._t&this._c,t^=t>>>this._l,t>>>0}next(){return this.nextInt()*(1/4294967296)}floating(t,e){return(e-t)*this.next()+t}integer(t,e){return Math.floor((e-t+1)*this.next()+t)}bool(t=.5){return this.next()<=t}pickOne(t){return t[this.integer(0,t.length-1)]}pickSet(t,e,i=!1){return i?this._pickSetWithDuplicates(t,e):this._pickSetWithoutDuplicates(t,e)}_pickSetWithoutDuplicates(t,e){if(e>t.length||e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 < n <= length");if(e===t.length)return t;const i=new Array(e);let s=0;const n=t.slice(0);for(;s<e;){const o=this.integer(0,n.length-1);i[s++]=n[o],n.splice(o,1)}return i}_pickSetWithDuplicates(t,e){if(e<0)throw new Error("Invalid number of elements to pick, must pick a value 0 <= n < MAX_INT");const i=new Array(e);for(let s=0;s<e;s++)i[s]=this.pickOne(t);return i}shuffle(t){const e=t.slice(0);let i;for(let s=0;s<e.length-2;s++){const n=this.integer(s,e.length-1);i=e[s],e[s]=e[n],e[n]=i}return e}range(t,e,i){const s=new Array(t);for(let n=0;n<t;n++)s[n]=this.integer(e,i);return s}d4(){return this.integer(1,4)}d6(){return this.integer(1,6)}d8(){return this.integer(1,8)}d10(){return this.integer(1,10)}d12(){return this.integer(1,12)}d20(){return this.integer(1,20)}get seed(){return this._seed}}const it=Math.PI*2;function Na(r){return r>=0?r-Math.floor(r):r-Math.ceil(r)}function V(r){return r===0?0:r<0?-1:1}function B(r,t,e){return Math.min(Math.max(t,r),e)}function ar(r,t,e){return Math.abs(r-t)<e}function Jt(r){let t=r;if(r>=it)for(;t>=it;)t-=it;if(r<0)for(;t<0;)t+=it;return t}function hr(r){return 180/Math.PI*r}function Wa(r){return r/180*Math.PI}const Ga=(r,t)=>Array.from(new Array(t-r+1),(e,i)=>i+r);function Nt(r,t,e=new se){return e?e.floating(r,t):r+Math.random()*(t-r)}function Va(r,t,e=new se){return e?e.integer(r,t):Math.round(Nt(r,t))}const lr=class q{constructor(t,e){this._x=0,this._y=0,this._x=t,this._y=e}static get Zero(){return new q(0,0)}static get One(){return new q(1,1)}static get Half(){return new q(.5,.5)}static get Up(){return new q(0,-1)}static get Down(){return new q(0,1)}static get Left(){return new q(-1,0)}static get Right(){return new q(1,0)}static fromAngle(t){return new q(Math.cos(t),Math.sin(t))}static isValid(t){return!(t==null||isNaN(t.x)||isNaN(t.y)||t.x===1/0||t.y===1/0||t.x===-1/0||t.y===-1/0)}static distance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}static min(t,e){return new q(Math.min(t.x,e.x),Math.min(t.y,e.y))}static max(t,e){return new q(Math.max(t.x,e.x),Math.max(t.y,e.y))}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}setTo(t,e){this.x=t,this.y=e}equals(t,e=q.EQUALS_EPSILON){return Math.abs(this.x-t.x)<=e&&Math.abs(this.y-t.y)<=e}distance(t){if(!t)return Math.sqrt(this.x*this.x+this.y*this.y);const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}squareDistance(t){t||(t=q.Zero);const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}clampMagnitude(t){const e=this.magnitude,i=B(e,0,t);return this.magnitude=i,this}get size(){return this.distance()}set size(t){const e=this.normalize().scale(t);this.setTo(e.x,e.y)}get magnitude(){return this.distance()}set magnitude(t){this.normalize().scale(t,this)}normalize(){const t=this.distance();return t===0?q.Zero:new q(this.x/t,this.y/t)}average(t){return this.add(t).scale(.5)}scale(t,e){const i=e||new q(0,0);return t instanceof q?(i.x=this.x*t.x,i.y=this.y*t.y):(i.x=this.x*t,i.y=this.y*t),i}add(t,e){return e?(e.x=this.x+t.x,e.y=this.y+t.y,e):new q(this.x+t.x,this.y+t.y)}sub(t,e){const i=e||new q(0,0),s=this.x-t.x,n=this.y-t.y;return i.x=s,i.y=n,i}addEqual(t){return this.setTo(this.x+t.x,this.y+t.y),this}subEqual(t){return this.setTo(this.x-t.x,this.y-t.y),this}scaleEqual(t){return this.setTo(this.x*t,this.y*t),this}dot(t){return this.x*t.x+this.y*t.y}cross(t){if(t instanceof q)return this.x*t.y-this.y*t.x;if(typeof t=="number")return new q(t*this.y,-t*this.x)}static cross(t,e){return new q(-t*e.y,t*e.x)}perpendicular(){return new q(this.y,-this.x)}normal(){return this.perpendicular().normalize()}negate(){return this.scale(-1)}toAngle(){return Jt(Math.atan2(this.y,this.x))}angleBetween(t,e){const i=this.toAngle(),s=Jt(t);let n=0,o=0;switch(s>i?n=s-i:n=(it-i+s)%it,o=(n-it)%it,e){case j.ShortestPath:return Math.abs(n)<Math.abs(o)?n:o;case j.LongestPath:return Math.abs(n)>Math.abs(o)?n:o;case j.Clockwise:return n;case j.CounterClockwise:return o}}rotate(t,e,i){const s=i||new q(0,0);e||(e=new q(0,0));const n=Math.sin(t),o=Math.cos(t),a=o*(this.x-e.x)-n*(this.y-e.y)+e.x,h=n*(this.x-e.x)+o*(this.y-e.y)+e.y;return s.x=a,s.y=h,s}clone(t){const e=t!=null?t:new q(0,0);return e.x=this.x,e.y=this.y,e}toString(t){return t?`(${this.x.toFixed(t)}, ${this.y.toFixed(t)})`:`(${this.x}, ${this.y})`}lerp(t,e){e=B(e,0,1);const i=new q(0,0);return i.x=this.x+(t.x-this.x)*e,i.y=this.y+(t.y-this.y)*e,i}};lr.EQUALS_EPSILON=.001;let w=lr;function b(r,t){return new w(r,t)}class ms extends w{constructor(t){super(0,0),this._getX=t.getX,this._getY=t.getY,this._setX=t.setX,this._setY=t.setY}get x(){return this._x=this._getX()}set x(t){this._setX(t),this._x=t}get y(){return this._y=this._getY()}set y(t){this._setY(t),this._y=t}}var cr=(r=>(r[r.X=12]="X",r[r.Y=13]="Y",r))(cr||{});class Ct{constructor(){this.data=new Float32Array(16),this._scaleX=1,this._scaleSignX=1,this._scaleY=1,this._scaleSignY=1}static ortho(t,e,i,s,n,o){const a=new Ct;return a.data[0]=2/(e-t),a.data[1]=0,a.data[2]=0,a.data[3]=0,a.data[4]=0,a.data[5]=2/(s-i),a.data[6]=0,a.data[7]=0,a.data[8]=0,a.data[9]=0,a.data[10]=-2/(o-n),a.data[11]=0,a.data[12]=-(e+t)/(e-t),a.data[13]=-(s+i)/(s-i),a.data[14]=-(o+n)/(o-n),a.data[15]=1,a}clone(t){const e=t||new Ct;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e.data[6]=this.data[6],e.data[7]=this.data[7],e.data[8]=this.data[8],e.data[9]=this.data[9],e.data[10]=this.data[10],e.data[11]=this.data[11],e.data[12]=this.data[12],e.data[13]=this.data[13],e.data[14]=this.data[14],e.data[15]=this.data[15],e}toDOMMatrix(){return new DOMMatrix([...this.data])}static fromFloat32Array(t){const e=new Ct;return e.data=t,e}static identity(){const t=new Ct;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=0,t.data[4]=0,t.data[5]=1,t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=0,t.data[13]=0,t.data[14]=0,t.data[15]=1,t}static translation(t,e){const i=Ct.identity();return i.data[12]=t,i.data[13]=e,i}static scale(t,e){const i=Ct.identity();return i.data[0]=t,i.data[5]=e,i.data[10]=1,i.data[15]=1,i}static rotation(t){const e=Ct.identity();return e.data[0]=Math.cos(t),e.data[4]=-Math.sin(t),e.data[1]=Math.sin(t),e.data[5]=Math.cos(t),e}multiply(t,e){if(t instanceof w){const i=e||new w(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[4]+this.data[12],o=s.x*this.data[1]+s.y*this.data[5]+this.data[13];return i.x=n,i.y=o,i}else{const i=e||new Ct,s=t,n=this.data[0],o=this.data[1],a=this.data[2],h=this.data[3],l=this.data[4],c=this.data[5],u=this.data[6],_=this.data[7],f=this.data[8],m=this.data[9],p=this.data[10],x=this.data[11],v=this.data[12],g=this.data[13],y=this.data[14],S=this.data[15],A=s.data[0],I=s.data[1],C=s.data[2],L=s.data[3],U=s.data[4],G=s.data[5],et=s.data[6],ht=s.data[7],$=s.data[8],W=s.data[9],ct=s.data[10],ft=s.data[11],E=s.data[12],Ie=s.data[13],Re=s.data[14],Me=s.data[15];i.data[0]=n*A+l*I+f*C+v*L,i.data[1]=o*A+c*I+m*C+g*L,i.data[2]=a*A+u*I+p*C+y*L,i.data[3]=h*A+_*I+x*C+S*L,i.data[4]=n*U+l*G+f*et+v*ht,i.data[5]=o*U+c*G+m*et+g*ht,i.data[6]=a*U+u*G+p*et+y*ht,i.data[7]=h*U+_*G+x*et+S*ht,i.data[8]=n*$+l*W+f*ct+v*ft,i.data[9]=o*$+c*W+m*ct+g*ft,i.data[10]=a*$+u*W+p*ct+y*ft,i.data[11]=h*$+_*W+x*ct+S*ft,i.data[12]=n*E+l*Ie+f*Re+v*Me,i.data[13]=o*E+c*Ie+m*Re+g*Me,i.data[14]=a*E+u*Ie+p*Re+y*Me,i.data[15]=h*E+_*Ie+x*Re+S*Me;const Ci=this.getScale();return i._scaleSignX=V(Ci.x)*V(i._scaleSignX),i._scaleSignY=V(Ci.y)*V(i._scaleSignY),i}}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5],l=this.data[6],c=this.data[7],u=this.data[8],_=this.data[9],f=this.data[10],m=this.data[11],p=this.data[12],x=this.data[13],v=this.data[14],g=this.data[15],y=0,S=1;return this.data[12]=i*t+a*e+u*y+p*S,this.data[13]=s*t+h*e+_*y+x*S,this.data[14]=n*t+l*e+f*y+v*S,this.data[15]=o*t+c*e+m*y+g*S,this}setPosition(t,e){this.data[12]=t,this.data[13]=e}getPosition(){return b(this.data[12],this.data[13])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],o=this.data[4],a=this.data[5],h=this.data[6],l=this.data[7],c=Math.sin(t),u=Math.cos(t);return this.data[0]=u*e+c*o,this.data[1]=u*i+c*a,this.data[2]=u*s+c*h,this.data[3]=u*n+c*l,this.data[4]=u*o-c*e,this.data[5]=u*a-c*i,this.data[6]=u*h-c*s,this.data[7]=u*l-c*n,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5],l=this.data[6],c=this.data[7];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*t,this.data[3]=o*t,this.data[4]=a*e,this.data[5]=h*e,this.data[6]=l*e,this.data[7]=c*e,this}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[4]=-i*e.x,this.data[5]=s*e.y}getRotation(){const t=Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX());return Jt(t)}getScaleX(){const t=b(this.data[0],this.data[4]).magnitude;return this._scaleSignX*t}getScaleY(){const t=b(this.data[1],this.data[5]).magnitude;return this._scaleSignY*t}getScale(){return b(this.getScaleX(),this.getScaleY())}setScaleX(t){if(this._scaleX===t)return;this._scaleSignX=V(t);const e=b(this.data[0]*this._scaleSignX,this.data[4]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[4]=e.y*t,this._scaleX=t}setScaleY(t){if(this._scaleY===t)return;this._scaleSignY=V(t);const e=b(this.data[1]*this._scaleSignY,this.data[5]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[5]=e.y*t,this._scaleY=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}getBasisDeterminant(){return this.data[0]*this.data[5]-this.data[1]*this.data[4]}getAffineInverse(t){const i=1/this.getBasisDeterminant(),s=this.data[0],n=this.data[4],o=this.data[1],a=this.data[5],h=t||Ct.identity();h.data[0]=a*i,h.data[1]=-o*i,h.data[4]=-n*i,h.data[5]=s*i;const l=this.data[12],c=this.data[13];return h.data[12]=-(l*h.data[0]+c*h.data[4]),h.data[13]=-(l*h.data[1]+c*h.data[5]),h}isIdentity(){return this.data[0]===1&&this.data[1]===0&&this.data[2]===0&&this.data[3]===0&&this.data[4]===0&&this.data[5]===1&&this.data[6]===0&&this.data[7]===0&&this.data[8]===0&&this.data[9]===0&&this.data[10]===1&&this.data[11]===0&&this.data[12]===0&&this.data[13]===0&&this.data[14]===0&&this.data[15]===1}toString(){return`
|
|
7
7
|
[${this.data[0]} ${this.data[4]} ${this.data[8]} ${this.data[12]}]
|
|
8
8
|
[${this.data[1]} ${this.data[5]} ${this.data[9]} ${this.data[13]}]
|
|
9
9
|
[${this.data[2]} ${this.data[6]} ${this.data[10]} ${this.data[14]}]
|
|
10
10
|
[${this.data[3]} ${this.data[7]} ${this.data[11]} ${this.data[15]}]
|
|
11
|
-
`}}class
|
|
11
|
+
`}}class Z{constructor(){this.data=new Float64Array(6),this._scale=new Float64Array([1,1]),this._scaleSignX=1,this._scaleSignY=1}toDOMMatrix(){return new DOMMatrix([...this.data])}static identity(){const t=new Z;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=1,t.data[4]=0,t.data[5]=0,t}static translation(t,e){const i=Z.identity();return i.data[4]=t,i.data[5]=e,i}static scale(t,e){const i=Z.identity();return i.data[0]=t,i.data[3]=e,i._scale[0]=t,i._scale[1]=e,i}static rotation(t){const e=Z.identity();return e.data[0]=Math.cos(t),e.data[1]=Math.sin(t),e.data[2]=-Math.sin(t),e.data[3]=Math.cos(t),e}setPosition(t,e){this.data[4]=t,this.data[5]=e}getPosition(){return b(this.data[4],this.data[5])}rotate(t){const e=this.data[0],i=this.data[1],s=this.data[2],n=this.data[3],o=Math.sin(t),a=Math.cos(t);return this.data[0]=a*e+o*s,this.data[1]=a*i+o*n,this.data[2]=a*s-o*e,this.data[3]=a*n-o*i,this}translate(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3],a=this.data[4],h=this.data[5];return this.data[4]=i*t+n*e+a,this.data[5]=s*t+o*e+h,this}scale(t,e){const i=this.data[0],s=this.data[1],n=this.data[2],o=this.data[3];return this.data[0]=i*t,this.data[1]=s*t,this.data[2]=n*e,this.data[3]=o*e,this._scale[0]=t,this._scale[1]=e,this._scaleSignX=V(t),this._scaleSignY=V(e),this}determinant(){return this.data[0]*this.data[3]-this.data[1]*this.data[2]}inverse(t){const e=this.determinant();let i=e;e!==0&&(i=1/e);const s=this.data[0],n=this.data[2],o=this.data[1],a=this.data[3],h=t||Z.identity();h.data[0]=a*i,h.data[1]=-o*i,h.data[2]=-n*i,h.data[3]=s*i;const l=this.data[4],c=this.data[5];return h.data[4]=-(l*h.data[0]+c*h.data[2]),h.data[5]=-(l*h.data[1]+c*h.data[3]),h}multiply(t,e){if(t instanceof w){const i=e||new w(0,0),s=t,n=s.x*this.data[0]+s.y*this.data[2]+this.data[4],o=s.x*this.data[1]+s.y*this.data[3]+this.data[5];return i.x=n,i.y=o,i}else{const i=e||new Z,s=t,n=this.data[0],o=this.data[1],a=this.data[2],h=this.data[3],l=this.data[4],c=this.data[5],u=s.data[0],_=s.data[1],f=s.data[2],m=s.data[3],p=s.data[4],x=s.data[5];i.data[0]=n*u+a*_,i.data[1]=o*u+h*_,i.data[2]=n*f+a*m,i.data[3]=o*f+h*m,i.data[4]=n*p+a*x+l,i.data[5]=o*p+h*x+c;const v=this._scaleSignX,g=this._scaleSignY;return i._scaleSignX=v*V(i._scaleSignX),i._scaleSignY=g*V(i._scaleSignY),i}}multiplyQuadInPlace(t){const e=t[0]*this.data[0]+t[1]*this.data[2]+this.data[4],i=t[0]*this.data[1]+t[1]*this.data[3]+this.data[5];t[0]=e,t[1]=i;const s=t[2]*this.data[0]+t[3]*this.data[2]+this.data[4],n=t[2]*this.data[1]+t[3]*this.data[3]+this.data[5];t[2]=s,t[3]=n;const o=t[4]*this.data[0]+t[5]*this.data[2]+this.data[4],a=t[4]*this.data[1]+t[5]*this.data[3]+this.data[5];t[4]=o,t[5]=a;const h=t[6]*this.data[0]+t[7]*this.data[2]+this.data[4],l=t[6]*this.data[1]+t[7]*this.data[3]+this.data[5];t[6]=h,t[7]=l}to4x4(){const t=new Ct;return t.data[0]=this.data[0],t.data[1]=this.data[1],t.data[2]=0,t.data[3]=0,t.data[4]=this.data[2],t.data[5]=this.data[3],t.data[6]=0,t.data[7]=0,t.data[8]=0,t.data[9]=0,t.data[10]=1,t.data[11]=0,t.data[12]=this.data[4],t.data[13]=this.data[5],t.data[14]=0,t.data[15]=1,t}setRotation(t){const e=this.getScale(),i=Math.sin(t),s=Math.cos(t);this.data[0]=s*e.x,this.data[1]=i*e.y,this.data[2]=-i*e.x,this.data[3]=s*e.y}getRotation(){const t=Math.atan2(this.data[1]/this.getScaleY(),this.data[0]/this.getScaleX());return Jt(t)}getScaleX(){const t=this.data[0]*this.data[0]+this.data[2]*this.data[2];return t===1?this._scaleSignX:this._scaleSignX*Math.sqrt(t)}getScaleY(){const t=this.data[1]*this.data[1]+this.data[3]*this.data[3];return t===1?this._scaleSignY:this._scaleSignY*Math.sqrt(t)}getScale(){return b(this.getScaleX(),this.getScaleY())}setScaleX(t){if(t===this._scale[0])return;this._scaleSignX=V(t);const e=b(this.data[0]*this._scaleSignX,this.data[2]*this._scaleSignX).normalize();this.data[0]=e.x*t,this.data[2]=e.y*t,this._scale[0]=t}setScaleY(t){if(t===this._scale[1])return;this._scaleSignY=V(t);const e=b(this.data[1]*this._scaleSignY,this.data[3]*this._scaleSignY).normalize();this.data[1]=e.x*t,this.data[3]=e.y*t,this._scale[1]=t}setScale(t){this.setScaleX(t.x),this.setScaleY(t.y)}isIdentity(){return this.data[0]===1&&this.data[1]===0&&this.data[2]===0&&this.data[3]===1&&this.data[4]===0&&this.data[5]===0}reset(){const t=this;return t.data[0]=1,t.data[1]=0,t.data[2]=0,t.data[3]=1,t.data[4]=0,t.data[5]=0,t}clone(t){const e=t||new Z;return e.data[0]=this.data[0],e.data[1]=this.data[1],e.data[2]=this.data[2],e.data[3]=this.data[3],e.data[4]=this.data[4],e.data[5]=this.data[5],e._scaleSignX=this._scaleSignX,e._scaleSignY=this._scaleSignY,e}toString(){return`
|
|
12
12
|
[${this.data[0]} ${this.data[2]} ${this.data[4]}]
|
|
13
13
|
[${this.data[1]} ${this.data[3]} ${this.data[5]}]
|
|
14
14
|
[0 0 1]
|
|
15
|
-
`}}class se extends v{constructor(t,e){super(t.x,t.y),this.original=t,this.change=e}get x(){return this._x=this.original.x}set x(t){t!==this._x&&(this.change(t,this._y),this._x=this.original.x=t)}get y(){return this._y=this.original.y}set y(t){t!==this._y&&(this.change(this._x,t),this._y=this.original.y=t)}setTo(t,e){this.x=t,this.y=e}}class Qt{constructor(){this._parent=null,this._children=[],this._pos=new se(x(0,0),()=>{this.flagDirty()}),this._globalPos=new gs({getX:()=>this.matrix.data[4],getY:()=>this.matrix.data[5],setX:t=>{if(this.parent){const{x:e}=this.parent.inverse.multiply(x(t,this.pos.y));this.pos.x=e}else this.pos.x=t;t!==this.matrix.data[4]&&this.flagDirty()},setY:t=>{if(this.parent){const{y:e}=this.parent.inverse.multiply(x(this.pos.x,t));this.pos.y=e}else this.pos.y=t;t!==this.matrix.data[5]&&this.flagDirty()}}),this._rotation=0,this._scale=new se(x(1,1),()=>{this.flagDirty()}),this._globalScale=new gs({getX:()=>this.parent?this.matrix.getScaleX():this.scale.x,getY:()=>this.parent?this.matrix.getScaleY():this.scale.y,setX:t=>{if(this.parent){const e=this.parent.globalScale.x;this.scale.x=t/e}else this.scale.x=t},setY:t=>{if(this.parent){const e=this.parent.globalScale.y;this.scale.y=t/e}else this.scale.y=t}}),this._z=0,this._isDirty=!1,this._isInverseDirty=!1,this._matrix=Q.identity(),this._inverse=Q.identity(),this._scratch=Q.identity()}get parent(){return this._parent}set parent(t){if(this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._parent=t,this._parent&&this._parent._children.push(this),this.flagDirty()}get children(){return this._children}set pos(t){this._pos.x=t.x,this._pos.y=t.y}get pos(){return this._pos}set globalPos(t){let e=t.clone();this.parent&&(e=this.parent.inverse.multiply(t)),e.equals(this._pos)||(this._pos=e,this.flagDirty())}get globalPos(){return this._globalPos}set rotation(t){const e=Zt(t);e!==this._rotation&&this.flagDirty(),this._rotation=e}get rotation(){return this._rotation}set globalRotation(t){let e=0;this.parent&&(e=this.parent.globalRotation);const i=Zt(t+e);i!==this._rotation&&this.flagDirty(),this._rotation=i}get globalRotation(){return this.parent?this.matrix.getRotation():this.rotation}set scale(t){this._scale.x=t.x,this._scale.y=t.y}get scale(){return this._scale}set globalScale(t){let e=x(1,1);this.parent&&(e=this.parent.globalScale),this.scale=t.scale(x(1/e.x,1/e.y))}get globalScale(){return this._globalScale}set z(t){this._z=t,this.flagDirty()}get z(){return this._z}set globalZ(t){this.parent?this.z=t-this.parent.globalZ:this.z=t}get globalZ(){return this.parent?this.z+this.parent.globalZ:this.z}get matrix(){return this._isDirty&&(this.parent===null?this._calculateMatrix().clone(this._matrix):this.parent.matrix.multiply(this._calculateMatrix()).clone(this._matrix),this._isDirty=!1),this._matrix}get inverse(){return this._isInverseDirty&&(this.matrix.inverse(this._inverse),this._isInverseDirty=!1),this._inverse}_calculateMatrix(){return this._scratch.data[0]=Math.cos(this._rotation),this._scratch.data[1]=Math.sin(this._rotation),this._scratch.data[2]=-Math.sin(this._rotation),this._scratch.data[3]=Math.cos(this.rotation),this._scratch.data[4]=this._pos.x,this._scratch.data[5]=this._pos.y,this._scratch.scale(this._scale.x,this._scale.y),this._scratch}flagDirty(){this._isDirty=!0,this._isInverseDirty=!0;for(let t=0;t<this._children.length;t++)this._children[t].flagDirty()}apply(t){return this.matrix.multiply(t)}applyInverse(t){return this.inverse.multiply(t)}setTransform(t,e,i){this._pos.x=t.x,this._pos.y=t.y,this._rotation=Zt(e),this._scale.x=i.x,this._scale.y=i.y,this.flagDirty()}isMirrored(){const t=V(this.scale.x)>>>31,e=V(this.scale.y)>>>31;return!!(t^e)}clone(t){const e=t!=null?t:new Qt;return this._pos.clone(e._pos),e._z=this._z,e._rotation=this._rotation,this._scale.clone(e._scale),e.flagDirty(),e}cloneWithParent(t){const e=t!=null?t:new Qt;return this._pos.clone(e._pos),e._z=this._z,e._rotation=this._rotation,this._scale.clone(e._scale),e.parent=this.parent,e.flagDirty(),e}toString(){return this.matrix.toString()}}var rt=(r=>(r.World="world",r.Screen="screen",r))(rt||{});class Be{constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}static fromPagePosition(t,e,i){let s,n,o,a;arguments.length===3?(s=t,n=e,o=new v(s,n),a=i):(o=t,s=o.x,n=o.y,a=e);const h=a.screen.pageToScreenCoordinates(o),l=a.screen.screenToWorldCoordinates(h);return new Be(l,o,h)}}class J{constructor(t,e){this.begin=t,this.end=e}clone(t){const e=t||new J(this.begin.clone(),this.end.clone());return e.begin=this.begin.clone(e.begin),e.end=this.end.clone(e.end),e}transform(t,e){const i=e||new J(v.Zero,v.Zero);return i.begin=t.multiply(this.begin,i.begin),i.end=t.multiply(this.end,i.end),i}get slope(){return(this.end.y-this.begin.y)/(this.end.x-this.begin.x)}get intercept(){return this.begin.y-this.slope*this.begin.x}normal(){return this._normal?this._normal:this._normal=this.end.sub(this.begin).normal()}dir(){return this._dir?this._dir:this._dir=this.end.sub(this.begin)}getPoints(){return[this.begin,this.end]}getSlope(){if(this._slope)return this._slope;const t=this.begin,e=this.end,i=t.distance(e);return this._slope=e.sub(t).scale(1/i)}getEdge(){const t=this.begin;return this.end.sub(t)}getLength(){const t=this.begin,e=this.end;return t.distance(e)}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new J(this.end,this.begin)}below(t){return(this.end.x-this.begin.x)*(t.y-this.begin.y)-(this.end.y-this.begin.y)*(t.x-this.begin.x)>=0}clip(t,e,i=!0){let s=t;i&&(s=s.normalize());const n=s.dot(this.begin)-e,o=s.dot(this.end)-e,a=[];if(n<=0&&a.push(this.begin),o<=0&&a.push(this.end),n*o<0){const h=n/(n-o);a.push(this.begin.add(this.end.sub(this.begin).scale(h)))}return a.length!==2?null:new J(a[0],a[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),o=this.end.y-this.begin.y,a=this.end.x-this.begin.x,h=(o*i-a*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?h:Math.abs(h)}findVectorToPoint(t){const e=this.begin.sub(t),i=this.getSlope();return e.sub(i.scale(e.dot(i)))}findPoint(t=null,e=null){const i=this.slope,s=this.intercept;if(t!==null)return new v(t,i*t+s);if(e!==null)return new v((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if(typeof arguments[0]=="number"&&typeof arguments[1]=="number")t=new v(arguments[0],arguments[1]),e=arguments[2]||0;else if(arguments[0]instanceof v)t=arguments[0],e=arguments[1]||0;else throw"Could not determine the arguments for Vector.hasPoint";const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,o=this.end.y-this.begin.y,a=i*o-s*n;return Math.abs(a)>e?!1:Math.abs(n)>=Math.abs(o)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:o>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y}}class Ke{constructor(t,e){this.min=t,this.max=e}overlaps(t){return this.max>t.min&&t.max>this.min}getOverlap(t){return this.overlaps(t)?this.max>t.max?t.max-this.min:this.max-t.min:0}}class fe{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(this.dir.cross(t.getSlope())===0&&e.cross(this.dir)!==0)return-1;const i=this.dir.cross(t.getSlope());if(i===0)return-1;const s=e.cross(t.getSlope())/i;if(s>=0){const n=e.cross(this.dir)/i/t.getLength();if(n>=0&&n<=1)return s}return-1}intersectPoint(t){const e=this.intersect(t);return e<0?null:this.getPoint(e)}getPoint(t){return this.pos.add(this.dir.scale(t))}}function ot(r,t,e){return(1-e)*r+t*e}function ps(r,t,e,i){const s=(r-t+et)%et>=Math.PI,n=Math.abs(t-r),o=et-n;let a=0,h=0;n>o?(a=o,h=n):(a=n,h=o);let l=0,c=1;switch(e){case Z.ShortestPath:l=a,c=s?1:-1;break;case Z.LongestPath:l=h,c=s?-1:1;break;case Z.Clockwise:c=1,l=s?a:h;break;case Z.CounterClockwise:c=-1,l=s?h:a;break}return r+c*(l*i)}function ti(r,t,e){return r.scale(1-e).add(t.scale(e))}function dr(r,t,e){return(e-r)/(t-r)}function ur(r,t,e){const i=e.sub(r),s=t.sub(r),n=i.x/s.x,o=i.y/s.y;return Math.min(n,o)}function Ht(r,t,e,i,s){const n=dr(r,t,s);return ot(e,i,n)}function qa(r,t,e,i,s){const n=ur(r,t,s);return ti(e,i,n)}class ei{constructor(t){this._distLookup=[],this.quality=4;var e;if(t.controlPoints.length!==4)throw new Error("Only cubic bezier curves are supported");this._controlPoints=[...t.controlPoints],this.quality=(e=t.quality)!=null?e:this.quality,this._calculateLookup()}get arcLength(){return this._arcLength}get controlPoints(){return this._controlPoints}set controlPoints(t){this._controlPoints=[...t],this._calculateLookup()}setControlPoint(t,e){this._controlPoints[t]=e,this._calculateLookup()}_calculateLookup(){let t=0;this._distLookup.length=0;let e=this.controlPoints[0];const i=this.controlPoints.length*this.quality;for(let s=0;s<i;s++){const n=s/(i-1),o=this.getPoint(n),a=e.distance(o);t+=a,this._distLookup.push(t),e=o}this._arcLength=t}_getTimeGivenDistance(t){const e=this._distLookup.length,i=this.arcLength;if(t>=0&&t<i){for(let s=0;s<e-1;s++)if(this._distLookup[s]<=t&&t<this._distLookup[s+1])return Ht(this._distLookup[s],this._distLookup[s+1],s/(e-1),(s+1)/(e-1),t)}return t/i}getPoint(t){const e=[...this.controlPoints];for(let i=1;i<e.length;i++)for(let s=0;s<e.length-i;s++)e[s]=ti(e[s],e[s+1],t);return e[0]}getTangent(t){const e=t*t,i=this.controlPoints[0],s=this.controlPoints[1],n=this.controlPoints[2],o=this.controlPoints[3];return i.scale(-3*e+6*t-3).add(s.scale(9*e-12*t+3).add(n.scale(-9*e+6*t).add(o.scale(3*e)))).normalize()}getUniformTangent(t){const e=t*this.arcLength,i=this._getTimeGivenDistance(e);return this.getTangent(i)}getNormal(t){return this.getTangent(t).normal()}getUniformNormal(t){return this.getUniformTangent(t).normal()}getUniformPoint(t){const e=t*this.arcLength,i=this._getTimeGivenDistance(e);return this.getPoint(i)}clone(){return new ei({controlPoints:[...this.controlPoints],quality:this.quality})}}class ms{constructor(){this.id=ws.generateUUID(),this._nodes=new Map,this._edges=new Set,this.adjacencyList=new Map}addNode(t,e){let i;return e?i=new _r(t,e):i=new Si(t),this._nodes.set(i.id,i),this.adjacencyList.set(i.id,new Set),i}addNodes(t){for(const e of t){const i=new Si(e);this._nodes.set(i.id,i),this.adjacencyList.set(i.id,new Set)}return this._nodes}deleteNode(t){const e=t.edges;for(const i of e)this.deleteEdge(i);return this.adjacencyList.forEach((i,s)=>{i.delete(t.id)}),this._nodes.delete(t.id),this.adjacencyList.delete(t.id),this._nodes}addEdge(t,e,i){var s,n;if(Array.from(this._edges).find(l=>l.source.id===t.id&&l.target.id===e.id))return[];let a;i?a="directed"in i?i.directed:!1:a=!1;const h=new vs(t,e,i);if(this._edges.add(h),t.registerNewEdge(h),e.registerNewEdge(h),(s=this.adjacencyList.get(t.id))==null||s.add(e.id),!a){const l=new vs(e,t,i);return(n=this.adjacencyList.get(e.id))==null||n.add(t.id),this._edges.add(l),e.registerNewEdge(l),t.registerNewEdge(l),h.linkWithPartner(l),l.linkWithPartner(h),[h,l]}return[h]}deleteEdge(t){t.source.breakEdge(t),t.target.breakEdge(t),this._edges.delete(t);const e=t.partnerEdge;e&&(e.source.breakEdge(e),e.target.breakEdge(e),this._edges.delete(e))}get nodes(){return this._nodes}getNode(t){return this._nodes.get(t)}get edges(){return this._edges}getNeighbors(t){var e;return Array.from((e=this.adjacencyList.get(t.id))!=null?e:[]).map(i=>this.nodes.get(i))}areNodesConnected(t,e){var i,s;return(s=(i=this.adjacencyList.get(t.id))==null?void 0:i.has(e.id))!=null?s:!1}bfs(t){if(!this._nodes.has(t.id))return[];const e=[t.id],i=new Set([t.id]);for(;e.length>0;){const s=e.shift(),n=this.adjacencyList.get(s)||new Set;for(const o of n)i.has(o)||(i.add(o),e.push(o))}return Array.from(i)}dfs(t,e=new Set){var i;const s=t.id;if(!this._nodes.has(s))return[];e.add(s);let n=[s];for(const o of(i=this.adjacencyList.get(s))!=null?i:[])e.has(o)||(n=n.concat(this.dfs(this._nodes.get(o),e)));return n}static createGraphFromNodes(t){const e=new ms;return e.addNodes(t),e}dijkstra(t){const e=[],i=[],s=[];this.nodes.forEach(l=>i.push(l)),this.nodes.forEach(l=>s.push({node:l,distance:1/0,previous:null}));const n=s.findIndex(l=>l.node===t);if(n===-1)return[];s[n].distance=0,e.push(t),i.splice(i.indexOf(t),1);let o=t;const a=o.edges,h=Array.from(a).filter(l=>l.target!==o);for(const l of h){const c=s.findIndex(u=>u.node===l.target);if(c===-1)return[];s[c].distance=l.weight,s[c].previous=o}for(;i.length>0;){let l=[],c=[];c=s.filter(p=>i.includes(p.node)),l=c.map(p=>p.node);let u=1/0,_=-1;if(l.length>0)for(let p=0;p<l.length;p++){const g=l[p],w=s.findIndex(m=>m.node===g);s[w].distance<u&&(u=s[w].distance,_=w)}else{u=1/0,_=-1;for(let p=0;p<i.length;p++){const g=i[p],w=s.findIndex(m=>m.node===g);s[w].distance<u&&(u=s[w].distance,_=w)}}if(_===-1)return[];o=s[_].node;let f=Array.from(o.edges);f=f.filter(p=>!e.includes(p.source)&&!e.includes(p.target)&&p.target!==o),e.push(o),i.splice(i.indexOf(o),1);for(let p=0;p<f.length;p++){const g=f[p],w=s.findIndex(C=>C.node===g.target),m=s.findIndex(C=>C.node===g.source),T=s[m].distance+g.weight;T<s[w].distance&&(s[w].distance=T,s[w].previous=o)}}return s}shortestPathDijkstra(t,e){var i,s;const n=this.dijkstra(t);if(n.length===0)return{path:[],distance:1/0};const o=[];let a=e;const h=(i=n.find(l=>l.node===e))==null?void 0:i.distance;for(;a!=null&&(o.push(a),a=(s=n.find(l=>l.node===a))==null?void 0:s.previous,a!=null););return o.reverse(),{path:o,distance:h}}aStar(t,e){if(!("pos"in t)||!("pos"in e))throw new Error("A* algorithm requires PositionNode with position vectors");const i=new Set([t.id]),s=new Set,n=new Set,o=new Map,a=new Map,h=new Map,l=new Map,c=new Map;for(const[u,_]of this._nodes)"pos"in _?c.set(u,_):n.add(u);for(const[u]of c)o.set(u,this._euclideanDistance(c.get(u),t)),a.set(u,this._euclideanDistance(c.get(u),e)),h.set(u,o.get(u)+a.get(u)),l.set(u,null);for(;i.size>0;){let u=null,_=1/0;for(const g of i){const w=h.get(g)||1/0;w<_&&(_=w,u=g)}if(u===null)break;if(u===e.id){const g=[];let w=e.id;for(;w!==null;){const m=this._nodes.get(w);g.unshift(m),w=l.get(w)}return{path:g,pathSteps:g.length-1,distance:o.get(e.id)||1/0,skippedNodes:n}}i.delete(u),s.add(u);const f=this._nodes.get(u),p=this.getNeighbors(f);for(const g of p){const w=g.id;s.has(w)||!("pos"in g)||!Array.from(f.edges).find(T=>T.source.id===u&&T.target.id===w)||(l.set(w,u),i.has(w)||i.add(w))}}return{path:[],pathSteps:0,distance:1/0,skippedNodes:n}}_euclideanDistance(t,e){const i=t.pos,s=e.pos;return Math.sqrt((s.x-i.x)**2+(s.y-i.y)**2)}}class vs{constructor(t,e,i){this._id=ws.generateUUID(),this._weight=0,this._partnerEdge=null,this._source=t,this._target=e,i&&i.weight?this._weight=i.weight:i&&i.useEuclidean?this._weight=t.pos.distance(e.pos):this._weight=0}linkWithPartner(t){this._partnerEdge=t}get id(){return this._id}get source(){return this._source}get target(){return this._target}get weight(){return this._weight}get partnerEdge(){return this._partnerEdge}}class Si{constructor(t){this._id=ws.generateUUID(),this._data=t,this._edges=new Set}get id(){return this._id}get data(){return this._data}get edges(){return this._edges}registerNewEdge(t){this._edges.add(t)}breakEdge(t){this._edges.delete(t)}getConnectedNodes(){return Array.from(this._edges).map(t=>t.target)}}class _r extends Si{constructor(t,e){super(t),this.pos=e}}const fr=class Fa{static generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){const s=Fa.rng.next()*16|0;return(i==="x"?s:s&3|8).toString(16)})}};fr.rng=new ie;let ws=fr;function Ti(r){return r}function Xa(r,t,e){return r=F((r-t)/(e-t),0,1),r*r*(3-2*r)}function Ya(r,t,e){return r=F((r-t)/(e-t),0,1),r*r*r*(r*(6*r-15)+10)}function $a(r){return-1*Math.cos(r*(Math.PI/2))+1}function ja(r){return Math.sin(r*(Math.PI/2))}function Za(r){return-.5*(Math.cos(Math.PI*r)-1)}function Qa(r){return r*r}function Ja(r){return r*(2-r)}function Ka(r){return r<.5?2*r*r:-1+(4-2*r)*r}function th(r){return r*r*r}function eh(r){const t=r-1;return t*t*t+1}function xs(r){return r<.5?4*r*r*r:(r-1)*(2*r-2)*(2*r-2)+1}function ih(r){return r*r*r*r}function sh(r){const t=r-1;return 1-t*t*t*t}function nh(r){const t=r-1;return r<.5?8*r*r*r*r:1-8*t*t*t*t}function rh(r){return r*r*r*r*r}function oh(r){const t=r-1;return 1+t*t*t*t*t}function ah(r){const t=r-1;return r<.5?16*r*r*r*r*r:1+16*t*t*t*t*t}function hh(r){return r===0?0:Math.pow(2,10*(r-1))}function lh(r){return r===1?1:-Math.pow(2,-10*r)+1}function ch(r){if(r===0||r===1)return r;const t=r*2,e=t-1;return t<1?.5*Math.pow(2,10*e):.5*(-Math.pow(2,-10*e)+2)}function dh(r){const t=r/1;return-1*(Math.sqrt(1-t*r)-1)}function uh(r){const t=r-1;return Math.sqrt(1-t*t)}function _h(r){const t=r*2,e=t-2;return t<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-e*e)+1)}function fh(r,t=1.70158){return r*r*((t+1)*r-t)}function gh(r,t=1.70158){const e=r/1-1;return e*e*((t+1)*e+t)+1}function ph(r,t=1.70158){const e=r*2,i=e-2,s=t*1.525;return e<1?.5*e*e*((s+1)*e-s):.5*(i*i*((s+1)*i+s)+2)}function mh(r,t=.7){if(r===0||r===1)return r;const i=r/1-1,s=1-t,n=s/(2*Math.PI)*Math.asin(1);return-(Math.pow(2,10*i)*Math.sin((i-n)*(2*Math.PI)/s))}function vh(r,t=.7){if(r===0||r===1)return r;const e=1-t,i=r*2,s=e/(2*Math.PI)*Math.asin(1);return Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}function wh(r,t=.65){if(r===0||r===1)return r;const e=1-t,i=r*2,s=i-1,n=e/(2*Math.PI)*Math.asin(1);return i<1?-.5*(Math.pow(2,10*s)*Math.sin((s-n)*(2*Math.PI)/e)):Math.pow(2,-10*s)*Math.sin((s-n)*(2*Math.PI)/e)*.5+1}function bs(r){const t=r/1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const e=t-.5454545454545454;return 7.5625*e*e+.75}else if(t<2.5/2.75){const e=t-.8181818181818182;return 7.5625*e*e+.9375}else{const e=t-.9545454545454546;return 7.5625*e*e+.984375}}function gr(r){return 1-bs(1-r)}function xh(r){return r<.5?gr(r*2)*.5:bs(r*2-1)*.5+.5}class P{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=s!=null?s:1}static fromRGB(t,e,i,s){return new P(t,e,i,s)}static fromRGBString(t){const e=/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i;let i=null;if(i=t.match(e)){const s=parseInt(i[1],10),n=parseInt(i[2],10),o=parseInt(i[3],10);let a=1;return i[4]&&(a=parseFloat(i[4])),new P(s,n,o,a)}else throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){const e=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;let i=null;if(i=t.match(e)){const s=parseInt(i[1],16),n=parseInt(i[2],16),o=parseInt(i[3],16);let a=1;return i[4]&&(a=parseInt(i[4],16)/255),new P(s,n,o,a)}else throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new xt(t,e,i,s).toRGBA()}lighten(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.s-=e.s*t,e.toRGBA()}multiply(t){const e=t.r/255*this.r/255*255,i=t.g/255*this.g/255*255,s=t.b/255*this.b/255*255,n=t.a*this.a;return new P(e,i,s,n)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new P(255-this.r,255-this.g,255-this.b,1-this.a)}average(t){const e=(t.r+this.r)/2,i=(t.g+this.g)/2,s=(t.b+this.b)/2,n=(t.a+this.a)/2;return new P(e,i,s,n)}equal(t){return this.toString()===t.toString()}toString(t="rgb"){switch(t){case"rgb":return this.toRGBA();case"hsl":return this.toHSLA();case"hex":return this.toHex();default:throw new Error("Invalid Color format")}}_componentToHex(t){const e=Math.max(Math.round(t),0).toString(16);return e.length===1?"0"+e:e}toHex(){let t="#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b);return this.a!==1&&(t+=this._componentToHex(this.a*255)),t}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return this.a!==void 0||this.a!==null?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return xt.fromRGBA(this.r,this.g,this.b,this.a).toString()}fillStyle(){return this.toString()}clone(t){const e=t||new P(this.r,this.g,this.b,this.a);return e.r=this.r,e.g=this.g,e.b=this.b,e.a=this.a,e}static lerp(t,e,i){const s=xt.fromRGBA(t.r,t.g,t.b,t.a),n=xt.fromRGBA(e.r,e.g,e.b,e.a);return xt.lerp(s,n,i).toRGBA()}static random(t){const e=t!=null?t:new ie;return new P(e.integer(0,255),e.integer(0,255),e.integer(0,255))}static get Black(){return P.fromHex("#000000")}static get White(){return P.fromHex("#FFFFFF")}static get Gray(){return P.fromHex("#808080")}static get LightGray(){return P.fromHex("#D3D3D3")}static get DarkGray(){return P.fromHex("#A9A9A9")}static get Yellow(){return P.fromHex("#FFFF00")}static get Orange(){return P.fromHex("#FFA500")}static get Red(){return P.fromHex("#FF0000")}static get Vermilion(){return P.fromHex("#FF5B31")}static get Rose(){return P.fromHex("#FF007F")}static get Pink(){return P.fromHex("#FFC0CB")}static get Magenta(){return P.fromHex("#FF00FF")}static get Violet(){return P.fromHex("#7F00FF")}static get Purple(){return P.fromHex("#800080")}static get Blue(){return P.fromHex("#0000FF")}static get Azure(){return P.fromHex("#007FFF")}static get Cyan(){return P.fromHex("#00FFFF")}static get Viridian(){return P.fromHex("#59978F")}static get Teal(){return P.fromHex("#008080")}static get Green(){return P.fromHex("#00FF00")}static get Chartreuse(){return P.fromHex("#7FFF00")}static get Transparent(){return P.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return P.fromHex("#176BAA")}static get Brown(){return P.fromHex("#964B00")}}class xt{constructor(t,e,i,s){this.h=t,this.s=e,this.l=i,this.a=s}static hue2rgb(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}static fromRGBA(t,e,i,s){t/=255,e/=255,i/=255;const n=Math.max(t,e,i),o=Math.min(t,e,i);let a,h;const l=(n+o)/2;if(n===o)a=h=0;else{const c=n-o;switch(h=l>.5?c/(2-n-o):c/(n+o),n){case t:a=(e-i)/c+(e<i?6:0);break;case e:a=(i-t)/c+2;break;case i:a=(t-e)/c+4;break}a/=6}return new xt(a,h,l,s)}toRGBA(){let t,e,i;if(this.s===0)t=e=i=this.l;else{const s=this.l<.5?this.l*(1+this.s):this.l+this.s-this.l*this.s,n=2*this.l-s;t=xt.hue2rgb(n,s,this.h+1/3),e=xt.hue2rgb(n,s,this.h),i=xt.hue2rgb(n,s,this.h-1/3)}return new P(t*255,e*255,i*255,this.a)}toString(){const t=this.h.toFixed(0),e=this.s.toFixed(0),i=this.l.toFixed(0),s=this.a.toFixed(0);return`hsla(${t}, ${e}, ${i}, ${s})`}static lerp(t,e,i){i=Math.max(0,Math.min(1,i));let s=e.h-t.h;s>.5?s-=1:s<-.5&&(s+=1);const n=(t.h+s*i+1)%1,o=t.s+(e.s-t.s)*i,a=t.l+(e.l-t.l)*i,h=t.a+(e.a-t.a)*i;return new xt(n,o,a,h)}}var Le=(r=>(r[r.Debug=0]="Debug",r[r.Info=1]="Info",r[r.Warn=2]="Warn",r[r.Error=3]="Error",r[r.Fatal=4]="Fatal",r))(Le||{});const pr=class te{constructor(){if(this._appenders=[],this.defaultLevel=1,this._logOnceSet=new Set,te._INSTANCE)throw new Error("Logger is a singleton");return te._INSTANCE=this,te._INSTANCE.addAppender(new ys),te._INSTANCE}static getInstance(){return te._INSTANCE==null&&(te._INSTANCE=new te),te._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){t==null&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}_logOnce(t,e){const i=t+e.join("+");this._logOnceSet.has(i)||(this._logOnceSet.add(i),this._log(t,e))}debug(...t){this._log(0,t)}debugOnce(...t){this._logOnce(0,t)}info(...t){this._log(1,t)}infoOnce(...t){this._logOnce(1,t)}warn(...t){this._log(2,t)}warnOnce(...t){this._logOnce(2,t)}error(...t){this._log(3,t)}errorOnce(...t){this._logOnce(3,t)}fatal(...t){this._log(4,t)}fatalOnce(...t){this._logOnce(4,t)}};pr._INSTANCE=null;let R=pr;class ys{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+Le[t]+"] : "),t<2?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<3?console.warn.apply?console.warn.apply(console,i):console.warn(i.join(" ")):console.error.apply?console.error.apply(console,i):console.error(i.join(" "))}}class mr{constructor(t){this._messages=[],this._pos=10,this._color=P.Black;var e,i;this._options=t,this.canvas=document.createElement("canvas"),this._ctx=this.canvas.getContext("2d"),this.canvas.style.position="absolute",this.canvas.style.zIndex=(i=(e=t.zIndex)==null?void 0:e.toString())!=null?i:"99",this.canvas.style.pointerEvents="none",this.canvas.style.userSelect="none",document.body.appendChild(this.canvas),this._positionScreenAppenderCanvas(),t.engine.screen.events.on("resize",()=>{this._positionScreenAppenderCanvas()})}_positionScreenAppenderCanvas(){var t,e,i,s;const n=this._options;this.canvas.width=(t=n.width)!=null?t:n.engine.screen.resolution.width,this.canvas.height=(e=n.height)!=null?e:n.engine.screen.resolution.height,this.canvas.style.position="absolute";const o=n.engine.screen.screenToPageCoordinates(x(0,0));this.canvas.style.left=o.x+"px",this.canvas.style.top=o.y+"px",this._pos=(i=n.xPos)!=null?i:this._pos,this._color=(s=n.color)!=null?s:this._color}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this._messages.unshift("["+Le[t]+"] : "+i);let s=10;this._messages=this._messages.slice(0,1e3);for(let n=0;n<this._messages.length;n++)this._ctx.fillStyle=this._color.toRGBA(),this._ctx.fillText(this._messages[n],this._pos,s),s+=10}}var M=(r=>(r.PreventCollision="PreventCollision",r.Passive="Passive",r.Active="Active",r.Fixed="Fixed",r))(M||{});function vr(r){return!!r&&!!r.prototype&&!!r.prototype.constructor}function bh(r){return!!(r!=null&&r.clone)}class Dt{constructor(){this.owner=void 0}clone(){const t=new this.constructor;for(const e in this)if(this.hasOwnProperty(e)){const i=this[e];bh(i)&&e!=="owner"&&e!=="clone"?t[e]=i.clone():t[e]=i}return t}}class gt{constructor(){this.observers=[],this.subscriptions=[]}register(t){this.observers.push(t)}subscribe(t){this.subscriptions.push(t)}unregister(t){const e=this.observers.indexOf(t);e!==-1&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);e!==-1&&this.subscriptions.splice(e,1)}notifyAll(t){const e=this.observers.length;for(let s=0;s<e;s++)this.observers[s].notify(t);const i=this.subscriptions.length;for(let s=0;s<i;s++)this.subscriptions[s](t)}clear(){this.observers.length=0,this.subscriptions.length=0}}class A extends Dt{constructor(){super(...arguments),this._logger=R.getInstance(),this._parentComponent=null,this._transform=new Qt,this._addChildTransform=t=>{const e=t.get(A);e&&(e._transform.parent=this._transform,e._parentComponent=this)},this.zIndexChanged$=new gt,this._coordPlane=rt.World}get(){return this._transform}onAdd(t){for(const e of t.children)this._addChildTransform(e);t.childrenAdded$.subscribe(e=>this._addChildTransform(e)),t.childrenRemoved$.subscribe(e=>{const i=e.get(A);i&&(i._transform.parent=null,i._parentComponent=null)})}onRemove(t){this._transform.parent=null,this._parentComponent=null}get z(){return this._transform.z}set z(t){const e=this._transform.z;this._transform.z=t,e!==t&&this.zIndexChanged$.notifyAll(t)}get globalZ(){return this._transform.globalZ}set globalZ(t){this._transform.globalZ=t}get coordPlane(){return this._parentComponent?this._parentComponent.coordPlane:this._coordPlane}set coordPlane(t){var e;this._parentComponent?this._logger.warn(`Cannot set coordinate plane on child entity ${(e=this.owner)==null?void 0:e.name}, children inherit their coordinate plane from their parents.`):this._coordPlane=t}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get globalPos(){return this._transform.globalPos}set globalPos(t){this._transform.globalPos=t}get rotation(){return this._transform.rotation}set rotation(t){this._transform.rotation=t}get globalRotation(){return this._transform.globalRotation}set globalRotation(t){this._transform.globalRotation=t}get scale(){return this._transform.scale}set scale(t){this._transform.scale=t}get globalScale(){return this._transform.globalScale}set globalScale(t){this._transform.globalScale=t}applyInverse(t){return this._transform.applyInverse(t)}apply(t){return this._transform.apply(t)}clone(){const t=new A;return t._transform=this._transform.clone(),t}}class H extends Dt{constructor(){super(...arguments),this.vel=v.Zero,this.maxVel=v.One.scaleEqual(1/0),this.acc=v.Zero,this.scaleFactor=v.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1,this.integration={onScreenOnly:!1}}}const ge=class{static create(t,e){if(this._CURRENT_GROUP>this._MAX_GROUPS)throw new Error(`Cannot have more than ${this._MAX_GROUPS} collision groups`);if(this._GROUPS.get(t)){const s=this._GROUPS.get(t);if(s.mask===e)return s;throw new Error(`Collision group ${t} already exists with a different mask!`)}const i=new pe(t,this._CURRENT_BIT,e!==void 0?e:~this._CURRENT_BIT);return this._CURRENT_BIT=this._CURRENT_BIT<<1|0,this._CURRENT_GROUP++,this._GROUPS.set(t,i),i}static get groups(){return Array.from(this._GROUPS.values())}static groupByName(t){return this._GROUPS.get(t)}static reset(){this._GROUPS=new Map,this._CURRENT_BIT=this._STARTING_BIT,this._CURRENT_GROUP=1}};ge._STARTING_BIT=1,ge._MAX_GROUPS=32,ge._CURRENT_GROUP=1,ge._CURRENT_BIT=ge._STARTING_BIT,ge._GROUPS=new Map;let Pi=ge;const Cs=class{constructor(t,e,i){this._name=t,this._category=e,this._mask=i}get name(){return this._name}get category(){return this._category}get mask(){return this._mask}canCollide(t){const e=this.category&t.mask,i=this.mask&t.category;return e!==0&&i!==0}invert(){const t=Pi.create("~("+this.name+")",~this.mask|0);return t._category=~this.category,t}static combine(t){const e=t.map(n=>n.name).join("+"),s=~t.reduce((n,o)=>o.category|n,0);return Pi.create(e,s)}static collidesWith(t){const e=`collidesWith(${t.map(s=>s.name).join("+")})`,i=t.reduce((s,n)=>n.category|s,0);return Pi.create(e,i)}toString(){return`
|
|
15
|
+
`}}class ne extends w{constructor(t,e){super(t.x,t.y),this.original=t,this.change=e}get x(){return this._x=this.original.x}set x(t){t!==this._x&&(this.change(t,this._y),this._x=this.original.x=t)}get y(){return this._y=this.original.y}set y(t){t!==this._y&&(this.change(this._x,t),this._y=this.original.y=t)}setTo(t,e){this.x=t,this.y=e}}class Kt{constructor(){this._parent=null,this._children=[],this._pos=new ne(b(0,0),()=>{this.flagDirty()}),this._globalPos=new ms({getX:()=>this.matrix.data[4],getY:()=>this.matrix.data[5],setX:t=>{if(this.parent){const{x:e}=this.parent.inverse.multiply(b(t,this.pos.y));this.pos.x=e}else this.pos.x=t;t!==this.matrix.data[4]&&this.flagDirty()},setY:t=>{if(this.parent){const{y:e}=this.parent.inverse.multiply(b(this.pos.x,t));this.pos.y=e}else this.pos.y=t;t!==this.matrix.data[5]&&this.flagDirty()}}),this._rotation=0,this._scale=new ne(b(1,1),()=>{this.flagDirty()}),this._globalScale=new ms({getX:()=>this.parent?this.matrix.getScaleX():this.scale.x,getY:()=>this.parent?this.matrix.getScaleY():this.scale.y,setX:t=>{if(this.parent){const e=this.parent.globalScale.x;this.scale.x=t/e}else this.scale.x=t},setY:t=>{if(this.parent){const e=this.parent.globalScale.y;this.scale.y=t/e}else this.scale.y=t}}),this._z=0,this._isDirty=!1,this._isInverseDirty=!1,this._matrix=Z.identity(),this._inverse=Z.identity(),this._scratch=Z.identity()}get parent(){return this._parent}set parent(t){if(this._parent){const e=this._parent._children.indexOf(this);e>-1&&this._parent._children.splice(e,1)}this._parent=t,this._parent&&this._parent._children.push(this),this.flagDirty()}get children(){return this._children}set pos(t){this._pos.x=t.x,this._pos.y=t.y}get pos(){return this._pos}set globalPos(t){let e=t.clone();this.parent&&(e=this.parent.inverse.multiply(t)),e.equals(this._pos)||(this._pos=e,this.flagDirty())}get globalPos(){return this._globalPos}set rotation(t){const e=Jt(t);e!==this._rotation&&this.flagDirty(),this._rotation=e}get rotation(){return this._rotation}set globalRotation(t){let e=0;this.parent&&(e=this.parent.globalRotation);const i=Jt(t+e);i!==this._rotation&&this.flagDirty(),this._rotation=i}get globalRotation(){return this.parent?this.matrix.getRotation():this.rotation}set scale(t){this._scale.x=t.x,this._scale.y=t.y}get scale(){return this._scale}set globalScale(t){let e=b(1,1);this.parent&&(e=this.parent.globalScale),this.scale=t.scale(b(1/e.x,1/e.y))}get globalScale(){return this._globalScale}set z(t){this._z=t,this.flagDirty()}get z(){return this._z}set globalZ(t){this.parent?this.z=t-this.parent.globalZ:this.z=t}get globalZ(){return this.parent?this.z+this.parent.globalZ:this.z}get matrix(){return this._isDirty&&(this.parent===null?this._calculateMatrix().clone(this._matrix):this.parent.matrix.multiply(this._calculateMatrix()).clone(this._matrix),this._isDirty=!1),this._matrix}get inverse(){return this._isInverseDirty&&(this.matrix.inverse(this._inverse),this._isInverseDirty=!1),this._inverse}_calculateMatrix(){return this._scratch.data[0]=Math.cos(this._rotation),this._scratch.data[1]=Math.sin(this._rotation),this._scratch.data[2]=-Math.sin(this._rotation),this._scratch.data[3]=Math.cos(this.rotation),this._scratch.data[4]=this._pos.x,this._scratch.data[5]=this._pos.y,this._scratch.scale(this._scale.x,this._scale.y),this._scratch}flagDirty(){this._isDirty=!0,this._isInverseDirty=!0;for(let t=0;t<this._children.length;t++)this._children[t].flagDirty()}apply(t){return this.matrix.multiply(t)}applyInverse(t){return this.inverse.multiply(t)}setTransform(t,e,i){this._pos.x=t.x,this._pos.y=t.y,this._rotation=Jt(e),this._scale.x=i.x,this._scale.y=i.y,this.flagDirty()}isMirrored(){const t=V(this.scale.x)>>>31,e=V(this.scale.y)>>>31;return!!(t^e)}clone(t){const e=t!=null?t:new Kt;return this._pos.clone(e._pos),e._z=this._z,e._rotation=this._rotation,this._scale.clone(e._scale),e.flagDirty(),e}cloneWithParent(t){const e=t!=null?t:new Kt;return this._pos.clone(e._pos),e._z=this._z,e._rotation=this._rotation,this._scale.clone(e._scale),e.parent=this.parent,e.flagDirty(),e}toString(){return this.matrix.toString()}}var rt=(r=>(r.World="world",r.Screen="screen",r))(rt||{});class ke{constructor(t,e,i){this.worldPos=t,this.pagePos=e,this.screenPos=i}static fromPagePosition(t,e,i){let s,n,o,a;arguments.length===3?(s=t,n=e,o=new w(s,n),a=i):(o=t,s=o.x,n=o.y,a=e);const h=a.screen.pageToScreenCoordinates(o),l=a.screen.screenToWorldCoordinates(h);return new ke(l,o,h)}}class Q{constructor(t,e){this.begin=t,this.end=e}clone(t){const e=t||new Q(this.begin.clone(),this.end.clone());return e.begin=this.begin.clone(e.begin),e.end=this.end.clone(e.end),e}transform(t,e){const i=e||new Q(w.Zero,w.Zero);return i.begin=t.multiply(this.begin,i.begin),i.end=t.multiply(this.end,i.end),i}get slope(){return(this.end.y-this.begin.y)/(this.end.x-this.begin.x)}get intercept(){return this.begin.y-this.slope*this.begin.x}normal(){return this._normal?this._normal:this._normal=this.end.sub(this.begin).normal()}dir(){return this._dir?this._dir:this._dir=this.end.sub(this.begin)}getPoints(){return[this.begin,this.end]}getSlope(){if(this._slope)return this._slope;const t=this.begin,e=this.end,i=t.distance(e);return this._slope=e.sub(t).scale(1/i)}getEdge(){const t=this.begin;return this.end.sub(t)}getLength(){const t=this.begin,e=this.end;return t.distance(e)}get midpoint(){return this.begin.add(this.end).scale(.5)}flip(){return new Q(this.end,this.begin)}below(t){return(this.end.x-this.begin.x)*(t.y-this.begin.y)-(this.end.y-this.begin.y)*(t.x-this.begin.x)>=0}clip(t,e,i=!0){let s=t;i&&(s=s.normalize());const n=s.dot(this.begin)-e,o=s.dot(this.end)-e,a=[];if(n<=0&&a.push(this.begin),o<=0&&a.push(this.end),n*o<0){const h=n/(n-o);a.push(this.begin.add(this.end.sub(this.begin).scale(h)))}return a.length!==2?null:new Q(a[0],a[1])}distanceToPoint(t,e=!1){const i=t.x,s=t.y,n=this.getLength(),o=this.end.y-this.begin.y,a=this.end.x-this.begin.x,h=(o*i-a*s+this.end.x*this.begin.y-this.end.y*this.begin.x)/n;return e?h:Math.abs(h)}findVectorToPoint(t){const e=this.begin.sub(t),i=this.getSlope();return e.sub(i.scale(e.dot(i)))}findPoint(t=null,e=null){const i=this.slope,s=this.intercept;if(t!==null)return new w(t,i*t+s);if(e!==null)return new w((e-s)/i,e);throw new Error("You must provide an X or a Y value")}hasPoint(){let t,e=0;if(typeof arguments[0]=="number"&&typeof arguments[1]=="number")t=new w(arguments[0],arguments[1]),e=arguments[2]||0;else if(arguments[0]instanceof w)t=arguments[0],e=arguments[1]||0;else throw"Could not determine the arguments for Vector.hasPoint";const i=t.x-this.begin.x,s=t.y-this.begin.y,n=this.end.x-this.begin.x,o=this.end.y-this.begin.y,a=i*o-s*n;return Math.abs(a)>e?!1:Math.abs(n)>=Math.abs(o)?n>0?this.begin.x<=t.x&&t.x<=this.end.x:this.end.x<=t.x&&t.x<=this.begin.x:o>0?this.begin.y<=t.y&&t.y<=this.end.y:this.end.y<=t.y&&t.y<=this.begin.y}}class ei{constructor(t,e){this.min=t,this.max=e}overlaps(t){return this.max>t.min&&t.max>this.min}getOverlap(t){return this.overlaps(t)?this.max>t.max?t.max-this.min:this.max-t.min:0}}class ge{constructor(t,e){this.pos=t,this.dir=e.normalize()}intersect(t){const e=t.begin.sub(this.pos);if(this.dir.cross(t.getSlope())===0&&e.cross(this.dir)!==0)return-1;const i=this.dir.cross(t.getSlope());if(i===0)return-1;const s=e.cross(t.getSlope())/i;if(s>=0){const n=e.cross(this.dir)/i/t.getLength();if(n>=0&&n<=1)return s}return-1}intersectPoint(t){const e=this.intersect(t);return e<0?null:this.getPoint(e)}getPoint(t){return this.pos.add(this.dir.scale(t))}}function ot(r,t,e){return(1-e)*r+t*e}function vs(r,t,e,i){const s=(r-t+it)%it>=Math.PI,n=Math.abs(t-r),o=it-n;let a=0,h=0;n>o?(a=o,h=n):(a=n,h=o);let l=0,c=1;switch(e){case j.ShortestPath:l=a,c=s?1:-1;break;case j.LongestPath:l=h,c=s?-1:1;break;case j.Clockwise:c=1,l=s?a:h;break;case j.CounterClockwise:c=-1,l=s?h:a;break}return r+c*(l*i)}function ii(r,t,e){return r.scale(1-e).add(t.scale(e))}function dr(r,t,e){return(e-r)/(t-r)}function ur(r,t,e){const i=e.sub(r),s=t.sub(r),n=i.x/s.x,o=i.y/s.y;return Math.min(n,o)}function Wt(r,t,e,i,s){const n=dr(r,t,s);return ot(e,i,n)}function qa(r,t,e,i,s){const n=ur(r,t,s);return ii(e,i,n)}class si{constructor(t){this._distLookup=[],this.quality=4;var e;if(t.controlPoints.length!==4)throw new Error("Only cubic bezier curves are supported");this._controlPoints=[...t.controlPoints],this.quality=(e=t.quality)!=null?e:this.quality,this._calculateLookup()}get arcLength(){return this._arcLength}get controlPoints(){return this._controlPoints}set controlPoints(t){this._controlPoints=[...t],this._calculateLookup()}setControlPoint(t,e){this._controlPoints[t]=e,this._calculateLookup()}_calculateLookup(){let t=0;this._distLookup.length=0;let e=this.controlPoints[0];const i=this.controlPoints.length*this.quality;for(let s=0;s<i;s++){const n=s/(i-1),o=this.getPoint(n),a=e.distance(o);t+=a,this._distLookup.push(t),e=o}this._arcLength=t}_getTimeGivenDistance(t){const e=this._distLookup.length,i=this.arcLength;if(t>=0&&t<i){for(let s=0;s<e-1;s++)if(this._distLookup[s]<=t&&t<this._distLookup[s+1])return Wt(this._distLookup[s],this._distLookup[s+1],s/(e-1),(s+1)/(e-1),t)}return t/i}getPoint(t){const e=[...this.controlPoints];for(let i=1;i<e.length;i++)for(let s=0;s<e.length-i;s++)e[s]=ii(e[s],e[s+1],t);return e[0]}getTangent(t){const e=t*t,i=this.controlPoints[0],s=this.controlPoints[1],n=this.controlPoints[2],o=this.controlPoints[3];return i.scale(-3*e+6*t-3).add(s.scale(9*e-12*t+3).add(n.scale(-9*e+6*t).add(o.scale(3*e)))).normalize()}getUniformTangent(t){const e=t*this.arcLength,i=this._getTimeGivenDistance(e);return this.getTangent(i)}getNormal(t){return this.getTangent(t).normal()}getUniformNormal(t){return this.getUniformTangent(t).normal()}getUniformPoint(t){const e=t*this.arcLength,i=this._getTimeGivenDistance(e);return this.getPoint(i)}clone(){return new si({controlPoints:[...this.controlPoints],quality:this.quality})}}class ws{constructor(){this.id=bs.generateUUID(),this._nodes=new Map,this._edges=new Set,this.adjacencyList=new Map}addNode(t,e){let i;return e?i=new _r(t,e):i=new Ti(t),this._nodes.set(i.id,i),this.adjacencyList.set(i.id,new Set),i}addNodes(t){for(const e of t){const i=new Ti(e);this._nodes.set(i.id,i),this.adjacencyList.set(i.id,new Set)}return this._nodes}deleteNode(t){const e=t.edges;for(const i of e)this.deleteEdge(i);return this.adjacencyList.forEach((i,s)=>{i.delete(t.id)}),this._nodes.delete(t.id),this.adjacencyList.delete(t.id),this._nodes}addEdge(t,e,i){var s,n;if(Array.from(this._edges).find(l=>l.source.id===t.id&&l.target.id===e.id))return[];let a;i?a="directed"in i?i.directed:!1:a=!1;const h=new xs(t,e,i);if(this._edges.add(h),t.registerNewEdge(h),e.registerNewEdge(h),(s=this.adjacencyList.get(t.id))==null||s.add(e.id),!a){const l=new xs(e,t,i);return(n=this.adjacencyList.get(e.id))==null||n.add(t.id),this._edges.add(l),e.registerNewEdge(l),t.registerNewEdge(l),h.linkWithPartner(l),l.linkWithPartner(h),[h,l]}return[h]}deleteEdge(t){t.source.breakEdge(t),t.target.breakEdge(t),this._edges.delete(t);const e=t.partnerEdge;e&&(e.source.breakEdge(e),e.target.breakEdge(e),this._edges.delete(e))}get nodes(){return this._nodes}getNode(t){return this._nodes.get(t)}get edges(){return this._edges}getNeighbors(t){var e;return Array.from((e=this.adjacencyList.get(t.id))!=null?e:[]).map(i=>this.nodes.get(i))}areNodesConnected(t,e){var i,s;return(s=(i=this.adjacencyList.get(t.id))==null?void 0:i.has(e.id))!=null?s:!1}bfs(t){if(!this._nodes.has(t.id))return[];const e=[t.id],i=new Set([t.id]);for(;e.length>0;){const s=e.shift(),n=this.adjacencyList.get(s)||new Set;for(const o of n)i.has(o)||(i.add(o),e.push(o))}return Array.from(i)}dfs(t,e=new Set){var i;const s=t.id;if(!this._nodes.has(s))return[];e.add(s);let n=[s];for(const o of(i=this.adjacencyList.get(s))!=null?i:[])e.has(o)||(n=n.concat(this.dfs(this._nodes.get(o),e)));return n}static createGraphFromNodes(t){const e=new ws;return e.addNodes(t),e}dijkstra(t){const e=[],i=[],s=[];this.nodes.forEach(l=>i.push(l)),this.nodes.forEach(l=>s.push({node:l,distance:1/0,previous:null}));const n=s.findIndex(l=>l.node===t);if(n===-1)return[];s[n].distance=0,e.push(t),i.splice(i.indexOf(t),1);let o=t;const a=o.edges,h=Array.from(a).filter(l=>l.target!==o);for(const l of h){const c=s.findIndex(u=>u.node===l.target);if(c===-1)return[];s[c].distance=l.weight,s[c].previous=o}for(;i.length>0;){let l=[],c=[];c=s.filter(m=>i.includes(m.node)),l=c.map(m=>m.node);let u=1/0,_=-1;if(l.length>0)for(let m=0;m<l.length;m++){const p=l[m],x=s.findIndex(v=>v.node===p);s[x].distance<u&&(u=s[x].distance,_=x)}else{u=1/0,_=-1;for(let m=0;m<i.length;m++){const p=i[m],x=s.findIndex(v=>v.node===p);s[x].distance<u&&(u=s[x].distance,_=x)}}if(_===-1)return[];o=s[_].node;let f=Array.from(o.edges);f=f.filter(m=>!e.includes(m.source)&&!e.includes(m.target)&&m.target!==o),e.push(o),i.splice(i.indexOf(o),1);for(let m=0;m<f.length;m++){const p=f[m],x=s.findIndex(S=>S.node===p.target),v=s.findIndex(S=>S.node===p.source),y=s[v].distance+p.weight;y<s[x].distance&&(s[x].distance=y,s[x].previous=o)}}return s}shortestPathDijkstra(t,e){var i,s;const n=this.dijkstra(t);if(n.length===0)return{path:[],distance:1/0};const o=[];let a=e;const h=(i=n.find(l=>l.node===e))==null?void 0:i.distance;for(;a!=null&&(o.push(a),a=(s=n.find(l=>l.node===a))==null?void 0:s.previous,a!=null););return o.reverse(),{path:o,distance:h}}aStar(t,e){if(!("pos"in t)||!("pos"in e))throw new Error("A* algorithm requires PositionNode with position vectors");const i=new Set([t.id]),s=new Set,n=new Set,o=new Map,a=new Map,h=new Map,l=new Map,c=new Map;for(const[u,_]of this._nodes)"pos"in _?c.set(u,_):n.add(u);for(const[u]of c)o.set(u,this._euclideanDistance(c.get(u),t)),a.set(u,this._euclideanDistance(c.get(u),e)),h.set(u,o.get(u)+a.get(u)),l.set(u,null);for(;i.size>0;){let u=null,_=1/0;for(const p of i){const x=h.get(p)||1/0;x<_&&(_=x,u=p)}if(u===null)break;if(u===e.id){const p=[];let x=e.id;for(;x!==null;){const v=this._nodes.get(x);p.unshift(v),x=l.get(x)}return{path:p,pathSteps:p.length-1,distance:o.get(e.id)||1/0,skippedNodes:n}}i.delete(u),s.add(u);const f=this._nodes.get(u),m=this.getNeighbors(f);for(const p of m){const x=p.id;s.has(x)||!("pos"in p)||!Array.from(f.edges).find(y=>y.source.id===u&&y.target.id===x)||(l.set(x,u),i.has(x)||i.add(x))}}return{path:[],pathSteps:0,distance:1/0,skippedNodes:n}}_euclideanDistance(t,e){const i=t.pos,s=e.pos;return Math.sqrt((s.x-i.x)**2+(s.y-i.y)**2)}}class xs{constructor(t,e,i){this._id=bs.generateUUID(),this._weight=0,this._partnerEdge=null,this._source=t,this._target=e,i&&i.weight?this._weight=i.weight:i&&i.useEuclidean?this._weight=t.pos.distance(e.pos):this._weight=0}linkWithPartner(t){this._partnerEdge=t}get id(){return this._id}get source(){return this._source}get target(){return this._target}get weight(){return this._weight}get partnerEdge(){return this._partnerEdge}}class Ti{constructor(t){this._id=bs.generateUUID(),this._data=t,this._edges=new Set}get id(){return this._id}get data(){return this._data}get edges(){return this._edges}registerNewEdge(t){this._edges.add(t)}breakEdge(t){this._edges.delete(t)}getConnectedNodes(){return Array.from(this._edges).map(t=>t.target)}}class _r extends Ti{constructor(t,e){super(t),this.pos=e}}const fr=class Da{static generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){const s=Da.rng.next()*16|0;return(i==="x"?s:s&3|8).toString(16)})}};fr.rng=new se;let bs=fr;function Ai(r){return r}function Xa(r,t,e){return r=B((r-t)/(e-t),0,1),r*r*(3-2*r)}function Ya(r,t,e){return r=B((r-t)/(e-t),0,1),r*r*r*(r*(6*r-15)+10)}function $a(r){return-1*Math.cos(r*(Math.PI/2))+1}function Za(r){return Math.sin(r*(Math.PI/2))}function ja(r){return-.5*(Math.cos(Math.PI*r)-1)}function Qa(r){return r*r}function Ja(r){return r*(2-r)}function Ka(r){return r<.5?2*r*r:-1+(4-2*r)*r}function th(r){return r*r*r}function eh(r){const t=r-1;return t*t*t+1}function ys(r){return r<.5?4*r*r*r:(r-1)*(2*r-2)*(2*r-2)+1}function ih(r){return r*r*r*r}function sh(r){const t=r-1;return 1-t*t*t*t}function nh(r){const t=r-1;return r<.5?8*r*r*r*r:1-8*t*t*t*t}function rh(r){return r*r*r*r*r}function oh(r){const t=r-1;return 1+t*t*t*t*t}function ah(r){const t=r-1;return r<.5?16*r*r*r*r*r:1+16*t*t*t*t*t}function hh(r){return r===0?0:Math.pow(2,10*(r-1))}function lh(r){return r===1?1:-Math.pow(2,-10*r)+1}function ch(r){if(r===0||r===1)return r;const t=r*2,e=t-1;return t<1?.5*Math.pow(2,10*e):.5*(-Math.pow(2,-10*e)+2)}function dh(r){const t=r/1;return-1*(Math.sqrt(1-t*r)-1)}function uh(r){const t=r-1;return Math.sqrt(1-t*t)}function _h(r){const t=r*2,e=t-2;return t<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-e*e)+1)}function fh(r,t=1.70158){return r*r*((t+1)*r-t)}function gh(r,t=1.70158){const e=r/1-1;return e*e*((t+1)*e+t)+1}function ph(r,t=1.70158){const e=r*2,i=e-2,s=t*1.525;return e<1?.5*e*e*((s+1)*e-s):.5*(i*i*((s+1)*i+s)+2)}function mh(r,t=.7){if(r===0||r===1)return r;const i=r/1-1,s=1-t,n=s/(2*Math.PI)*Math.asin(1);return-(Math.pow(2,10*i)*Math.sin((i-n)*(2*Math.PI)/s))}function vh(r,t=.7){if(r===0||r===1)return r;const e=1-t,i=r*2,s=e/(2*Math.PI)*Math.asin(1);return Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}function wh(r,t=.65){if(r===0||r===1)return r;const e=1-t,i=r*2,s=i-1,n=e/(2*Math.PI)*Math.asin(1);return i<1?-.5*(Math.pow(2,10*s)*Math.sin((s-n)*(2*Math.PI)/e)):Math.pow(2,-10*s)*Math.sin((s-n)*(2*Math.PI)/e)*.5+1}function Cs(r){const t=r/1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const e=t-.5454545454545454;return 7.5625*e*e+.75}else if(t<2.5/2.75){const e=t-.8181818181818182;return 7.5625*e*e+.9375}else{const e=t-.9545454545454546;return 7.5625*e*e+.984375}}function gr(r){return 1-Cs(1-r)}function xh(r){return r<.5?gr(r*2)*.5:Cs(r*2-1)*.5+.5}class T{constructor(t,e,i,s){this.r=t,this.g=e,this.b=i,this.a=s!=null?s:1}static fromRGB(t,e,i,s){return new T(t,e,i,s)}static fromRGBString(t){const e=/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i;let i=null;if(i=t.match(e)){const s=parseInt(i[1],10),n=parseInt(i[2],10),o=parseInt(i[3],10);let a=1;return i[4]&&(a=parseFloat(i[4])),new T(s,n,o,a)}else throw new Error("Invalid rgb/a string: "+t)}static fromHex(t){const e=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i;let i=null;if(i=t.match(e)){const s=parseInt(i[1],16),n=parseInt(i[2],16),o=parseInt(i[3],16);let a=1;return i[4]&&(a=parseInt(i[4],16)/255),new T(s,n,o,a)}else throw new Error("Invalid hex string: "+t)}static fromHSL(t,e,i,s=1){return new xt(t,e,i,s).toRGBA()}lighten(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.l+=(1-e.l)*t,e.toRGBA()}darken(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.l-=e.l*t,e.toRGBA()}saturate(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.s+=e.s*t,e.toRGBA()}desaturate(t=.1){const e=xt.fromRGBA(this.r,this.g,this.b,this.a);return e.s-=e.s*t,e.toRGBA()}multiply(t){const e=t.r/255*this.r/255*255,i=t.g/255*this.g/255*255,s=t.b/255*this.b/255*255,n=t.a*this.a;return new T(e,i,s,n)}screen(t){const e=t.invert(),i=t.invert();return e.multiply(i).invert()}invert(){return new T(255-this.r,255-this.g,255-this.b,1-this.a)}average(t){const e=(t.r+this.r)/2,i=(t.g+this.g)/2,s=(t.b+this.b)/2,n=(t.a+this.a)/2;return new T(e,i,s,n)}equal(t){return this.toString()===t.toString()}toString(t="rgb"){switch(t){case"rgb":return this.toRGBA();case"hsl":return this.toHSLA();case"hex":return this.toHex();default:throw new Error("Invalid Color format")}}_componentToHex(t){const e=Math.max(Math.round(t),0).toString(16);return e.length===1?"0"+e:e}toHex(){let t="#"+this._componentToHex(this.r)+this._componentToHex(this.g)+this._componentToHex(this.b);return this.a!==1&&(t+=this._componentToHex(this.a*255)),t}toRGBA(){const t=String(this.r.toFixed(0))+", "+String(this.g.toFixed(0))+", "+String(this.b.toFixed(0));return this.a!==void 0||this.a!==null?"rgba("+t+", "+String(this.a)+")":"rgb("+t+")"}toHSLA(){return xt.fromRGBA(this.r,this.g,this.b,this.a).toString()}fillStyle(){return this.toString()}clone(t){const e=t||new T(this.r,this.g,this.b,this.a);return e.r=this.r,e.g=this.g,e.b=this.b,e.a=this.a,e}static lerp(t,e,i){const s=xt.fromRGBA(t.r,t.g,t.b,t.a),n=xt.fromRGBA(e.r,e.g,e.b,e.a);return xt.lerp(s,n,i).toRGBA()}static random(t){const e=t!=null?t:new se;return new T(e.integer(0,255),e.integer(0,255),e.integer(0,255))}static get Black(){return T.fromHex("#000000")}static get White(){return T.fromHex("#FFFFFF")}static get Gray(){return T.fromHex("#808080")}static get LightGray(){return T.fromHex("#D3D3D3")}static get DarkGray(){return T.fromHex("#A9A9A9")}static get Yellow(){return T.fromHex("#FFFF00")}static get Orange(){return T.fromHex("#FFA500")}static get Red(){return T.fromHex("#FF0000")}static get Vermilion(){return T.fromHex("#FF5B31")}static get Rose(){return T.fromHex("#FF007F")}static get Pink(){return T.fromHex("#FFC0CB")}static get Magenta(){return T.fromHex("#FF00FF")}static get Violet(){return T.fromHex("#7F00FF")}static get Purple(){return T.fromHex("#800080")}static get Blue(){return T.fromHex("#0000FF")}static get Azure(){return T.fromHex("#007FFF")}static get Cyan(){return T.fromHex("#00FFFF")}static get Viridian(){return T.fromHex("#59978F")}static get Teal(){return T.fromHex("#008080")}static get Green(){return T.fromHex("#00FF00")}static get Chartreuse(){return T.fromHex("#7FFF00")}static get Transparent(){return T.fromHex("#FFFFFF00")}static get ExcaliburBlue(){return T.fromHex("#176BAA")}static get Brown(){return T.fromHex("#964B00")}}class xt{constructor(t,e,i,s){this.h=t,this.s=e,this.l=i,this.a=s}static hue2rgb(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}static fromRGBA(t,e,i,s){t/=255,e/=255,i/=255;const n=Math.max(t,e,i),o=Math.min(t,e,i);let a,h;const l=(n+o)/2;if(n===o)a=h=0;else{const c=n-o;switch(h=l>.5?c/(2-n-o):c/(n+o),n){case t:a=(e-i)/c+(e<i?6:0);break;case e:a=(i-t)/c+2;break;case i:a=(t-e)/c+4;break}a/=6}return new xt(a,h,l,s)}toRGBA(){let t,e,i;if(this.s===0)t=e=i=this.l;else{const s=this.l<.5?this.l*(1+this.s):this.l+this.s-this.l*this.s,n=2*this.l-s;t=xt.hue2rgb(n,s,this.h+1/3),e=xt.hue2rgb(n,s,this.h),i=xt.hue2rgb(n,s,this.h-1/3)}return new T(t*255,e*255,i*255,this.a)}toString(){const t=this.h.toFixed(0),e=this.s.toFixed(0),i=this.l.toFixed(0),s=this.a.toFixed(0);return`hsla(${t}, ${e}, ${i}, ${s})`}static lerp(t,e,i){i=Math.max(0,Math.min(1,i));let s=e.h-t.h;s>.5?s-=1:s<-.5&&(s+=1);const n=(t.h+s*i+1)%1,o=t.s+(e.s-t.s)*i,a=t.l+(e.l-t.l)*i,h=t.a+(e.a-t.a)*i;return new xt(n,o,a,h)}}var Le=(r=>(r[r.Debug=0]="Debug",r[r.Info=1]="Info",r[r.Warn=2]="Warn",r[r.Error=3]="Error",r[r.Fatal=4]="Fatal",r))(Le||{});const pr=class ee{constructor(){if(this._appenders=[],this.defaultLevel=1,this._logOnceSet=new Set,ee._INSTANCE)throw new Error("Logger is a singleton");return ee._INSTANCE=this,ee._INSTANCE.addAppender(new Ss),ee._INSTANCE}static getInstance(){return ee._INSTANCE==null&&(ee._INSTANCE=new ee),ee._INSTANCE}addAppender(t){this._appenders.push(t)}clearAppenders(){this._appenders.length=0}_log(t,e){t==null&&(t=this.defaultLevel);const i=this._appenders.length;for(let s=0;s<i;s++)t>=this.defaultLevel&&this._appenders[s].log(t,e)}_logOnce(t,e){const i=t+e.join("+");this._logOnceSet.has(i)||(this._logOnceSet.add(i),this._log(t,e))}debug(...t){this._log(0,t)}debugOnce(...t){this._logOnce(0,t)}info(...t){this._log(1,t)}infoOnce(...t){this._logOnce(1,t)}warn(...t){this._log(2,t)}warnOnce(...t){this._logOnce(2,t)}error(...t){this._log(3,t)}errorOnce(...t){this._logOnce(3,t)}fatal(...t){this._log(4,t)}fatalOnce(...t){this._logOnce(4,t)}};pr._INSTANCE=null;let R=pr;class Ss{log(t,e){if(!console&&!console.log&&console.warn&&console.error)return;const i=[];i.unshift.apply(i,e),i.unshift("["+Le[t]+"] : "),t<2?console.log.apply?console.log.apply(console,i):console.log(i.join(" ")):t<3?console.warn.apply?console.warn.apply(console,i):console.warn(i.join(" ")):console.error.apply?console.error.apply(console,i):console.error(i.join(" "))}}class mr{constructor(t){this._messages=[],this._pos=10,this._color=T.Black;var e,i;this._options=t,this.canvas=document.createElement("canvas"),this._ctx=this.canvas.getContext("2d"),this.canvas.style.position="absolute",this.canvas.style.zIndex=(i=(e=t.zIndex)==null?void 0:e.toString())!=null?i:"99",this.canvas.style.pointerEvents="none",this.canvas.style.userSelect="none",document.body.appendChild(this.canvas),this._positionScreenAppenderCanvas(),t.engine.screen.events.on("resize",()=>{this._positionScreenAppenderCanvas()})}_positionScreenAppenderCanvas(){var t,e,i,s;const n=this._options;this.canvas.width=(t=n.width)!=null?t:n.engine.screen.resolution.width,this.canvas.height=(e=n.height)!=null?e:n.engine.screen.resolution.height,this.canvas.style.position="absolute";const o=n.engine.screen.screenToPageCoordinates(b(0,0));this.canvas.style.left=o.x+"px",this.canvas.style.top=o.y+"px",this._pos=(i=n.xPos)!=null?i:this._pos,this._color=(s=n.color)!=null?s:this._color}log(t,e){const i=e.join(",");this._ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this._messages.unshift("["+Le[t]+"] : "+i);let s=10;this._messages=this._messages.slice(0,1e3);for(let n=0;n<this._messages.length;n++)this._ctx.fillStyle=this._color.toRGBA(),this._ctx.fillText(this._messages[n],this._pos,s),s+=10}}var M=(r=>(r.PreventCollision="PreventCollision",r.Passive="Passive",r.Active="Active",r.Fixed="Fixed",r))(M||{});function vr(r){return!!r&&!!r.prototype&&!!r.prototype.constructor}function bh(r){return!!(r!=null&&r.clone)}class Dt{constructor(){this.owner=void 0}clone(){const t=new this.constructor;for(const e in this)if(this.hasOwnProperty(e)){const i=this[e];bh(i)&&e!=="owner"&&e!=="clone"?t[e]=i.clone():t[e]=i}return t}}class gt{constructor(){this.observers=[],this.subscriptions=[]}register(t){this.observers.push(t)}subscribe(t){this.subscriptions.push(t)}unregister(t){const e=this.observers.indexOf(t);e!==-1&&this.observers.splice(e,1)}unsubscribe(t){const e=this.subscriptions.indexOf(t);e!==-1&&this.subscriptions.splice(e,1)}notifyAll(t){const e=this.observers.length;for(let s=0;s<e;s++)this.observers[s].notify(t);const i=this.subscriptions.length;for(let s=0;s<i;s++)this.subscriptions[s](t)}clear(){this.observers.length=0,this.subscriptions.length=0}}class P extends Dt{constructor(){super(...arguments),this._logger=R.getInstance(),this._parentComponent=null,this._transform=new Kt,this._addChildTransform=t=>{const e=t.get(P);e&&(e._transform.parent=this._transform,e._parentComponent=this)},this.zIndexChanged$=new gt,this._coordPlane=rt.World}get(){return this._transform}onAdd(t){for(const e of t.children)this._addChildTransform(e);t.childrenAdded$.subscribe(e=>this._addChildTransform(e)),t.childrenRemoved$.subscribe(e=>{const i=e.get(P);i&&(i._transform.parent=null,i._parentComponent=null)})}onRemove(t){this._transform.parent=null,this._parentComponent=null}get z(){return this._transform.z}set z(t){const e=this._transform.z;this._transform.z=t,e!==t&&this.zIndexChanged$.notifyAll(t)}get globalZ(){return this._transform.globalZ}set globalZ(t){this._transform.globalZ=t}get coordPlane(){return this._parentComponent?this._parentComponent.coordPlane:this._coordPlane}set coordPlane(t){var e;this._parentComponent?this._logger.warn(`Cannot set coordinate plane on child entity ${(e=this.owner)==null?void 0:e.name}, children inherit their coordinate plane from their parents.`):this._coordPlane=t}get pos(){return this._transform.pos}set pos(t){this._transform.pos=t}get globalPos(){return this._transform.globalPos}set globalPos(t){this._transform.globalPos=t}get rotation(){return this._transform.rotation}set rotation(t){this._transform.rotation=t}get globalRotation(){return this._transform.globalRotation}set globalRotation(t){this._transform.globalRotation=t}get scale(){return this._transform.scale}set scale(t){this._transform.scale=t}get globalScale(){return this._transform.globalScale}set globalScale(t){this._transform.globalScale=t}applyInverse(t){return this._transform.applyInverse(t)}apply(t){return this._transform.apply(t)}clone(){const t=new P;return t._transform=this._transform.clone(),t}}class O extends Dt{constructor(){super(...arguments),this.vel=w.Zero,this.maxVel=w.One.scaleEqual(1/0),this.acc=w.Zero,this.scaleFactor=w.Zero,this.angularVelocity=0,this.torque=0,this.inertia=1,this.integration={onScreenOnly:!1}}}const pe=class{static create(t,e){if(this._CURRENT_GROUP>this._MAX_GROUPS)throw new Error(`Cannot have more than ${this._MAX_GROUPS} collision groups`);if(this._GROUPS.get(t)){const s=this._GROUPS.get(t);if(s.mask===e)return s;throw new Error(`Collision group ${t} already exists with a different mask!`)}const i=new me(t,this._CURRENT_BIT,e!==void 0?e:~this._CURRENT_BIT);return this._CURRENT_BIT=this._CURRENT_BIT<<1|0,this._CURRENT_GROUP++,this._GROUPS.set(t,i),i}static get groups(){return Array.from(this._GROUPS.values())}static groupByName(t){return this._GROUPS.get(t)}static reset(){this._GROUPS=new Map,this._CURRENT_BIT=this._STARTING_BIT,this._CURRENT_GROUP=1}};pe._STARTING_BIT=1,pe._MAX_GROUPS=32,pe._CURRENT_GROUP=1,pe._CURRENT_BIT=pe._STARTING_BIT,pe._GROUPS=new Map;let Pi=pe;const Ts=class{constructor(t,e,i){this._name=t,this._category=e,this._mask=i}get name(){return this._name}get category(){return this._category}get mask(){return this._mask}canCollide(t){const e=this.category&t.mask,i=this.mask&t.category;return e!==0&&i!==0}invert(){const t=Pi.create("~("+this.name+")",~this.mask|0);return t._category=~this.category,t}static combine(t){const e=t.map(n=>n.name).join("+"),s=~t.reduce((n,o)=>o.category|n,0);return Pi.create(e,s)}static collidesWith(t){const e=`collidesWith(${t.map(s=>s.name).join("+")})`,i=t.reduce((s,n)=>n.category|s,0);return Pi.create(e,i)}toString(){return`
|
|
16
16
|
category: ${this.category.toString(2).padStart(32,"0")}
|
|
17
17
|
mask: ${(this.mask>>>0).toString(2).padStart(32,"0")}
|
|
18
|
-
`}};Cs.All=new Cs("Collide with all groups",-1,-1);let pe=Cs;var Ss=(r=>(r.Kill="kill",r.PreKill="prekill",r.PostKill="postkill",r.PreDraw="predraw",r.PostDraw="postdraw",r.PreDebugDraw="predebugdraw",r.PostDebugDraw="postdebugdraw",r.PreUpdate="preupdate",r.PostUpdate="postupdate",r.PreFrame="preframe",r.PostFrame="postframe",r.PreCollision="precollision",r.CollisionStart="collisionstart",r.CollisionEnd="collisionend",r.PostCollision="postcollision",r.Initialize="initialize",r.Activate="activate",r.Deactivate="deactivate",r.ExitViewport="exitviewport",r.EnterViewport="enterviewport",r.ExitTrigger="exit",r.EnterTrigger="enter",r.Connect="connect",r.Disconnect="disconnect",r.Button="button",r.Axis="axis",r.Visible="visible",r.Hidden="hidden",r.Start="start",r.Stop="stop",r.PointerUp="pointerup",r.PointerDown="pointerdown",r.PointerMove="pointermove",r.PointerEnter="pointerenter",r.PointerLeave="pointerleave",r.PointerCancel="pointercancel",r.PointerWheel="pointerwheel",r.Up="up",r.Down="down",r.Move="move",r.Enter="enter",r.Leave="leave",r.Cancel="cancel",r.Wheel="wheel",r.Press="press",r.Release="release",r.Hold="hold",r.PointerDragStart="pointerdragstart",r.PointerDragEnd="pointerdragend",r.PointerDragEnter="pointerdragenter",r.PointerDragLeave="pointerdragleave",r.PointerDragMove="pointerdragmove",r.ActionStart="actionstart",r.ActionComplete="actioncomplete",r.Add="add",r.Remove="remove",r))(Ss||{});class L{constructor(){this.other=null,this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class Ai extends L{constructor(t){super(),this.self=t,this.target=t}}class Ts extends L{constructor(t){super(),this.self=t,this.target=t}}class Ps extends L{constructor(t){super(),this.self=t,this.target=t}}class As extends L{constructor(t){super(),this.self=t,this.target=t}}class Es extends L{constructor(t){super(),this.self=t,this.target=t}}class ke extends L{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Ue extends L{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Is extends L{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Rs extends L{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Ms extends L{constructor(t,e){super(),this.ctx=t,this.self=e,this.target=e}}class Ds extends L{constructor(t,e){super(),this.ctx=t,this.self=e,this.target=e}}class ne extends L{constructor(t,e,i){super(),this.engine=t,this.elapsed=e,this.self=i,this.target=i}}class re extends L{constructor(t,e,i){super(),this.engine=t,this.elapsed=e,this.self=i,this.target=i}}class Fs extends L{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class Bs extends L{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class Ls extends L{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class ks extends L{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Us extends L{constructor(t,e,i,s){super(),this.button=t,this.index=e,this.value=i,this.self=s,this.target=s}}class zs extends L{constructor(t,e,i){super(),this.axis=t,this.value=e,this.self=i,this.target=i}}class Os extends L{constructor(t){super(),this.self=t,this.target=t}}class Hs extends L{constructor(t){super(),this.self=t,this.target=t}}class me extends L{constructor(t,e,i,s,n){super(),this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n,this.target=t}}class ve extends L{constructor(t,e,i,s,n){super(),this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n,this.target=t}}class Ei{constructor(t,e,i,s){this.self=t,this.other=e,this.side=i,this.contact=s}}class Ii{constructor(t,e,i,s){this.self=t,this.other=e,this.side=i,this.lastContact=s}}class Ri{constructor(t,e,i,s,n){this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class Mi{constructor(t,e,i,s,n){this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class ii extends L{constructor(t,e,i,s){super(),this.self=t,this.other=e,this.side=i,this.contact=s,this.target=t}}class si extends L{constructor(t,e,i,s){super(),this.self=t,this.other=e,this.side=i,this.lastContact=s,this.target=t}}class ze extends L{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class Ns extends L{constructor(t,e){super(),this.context=t,this.self=e,this.target=e}}class Ws extends L{constructor(t,e){super(),this.context=t,this.self=e,this.target=e}}class Gs extends L{constructor(t){super(),this.self=t,this.target=t}}class Vs extends L{constructor(t){super(),this.self=t,this.target=t}}class qs extends L{constructor(t,e){super(),this.self=t,this.entity=e,this.target=t}}class Xs extends L{constructor(t,e){super(),this.self=t,this.entity=e,this.target=t}}class Ys extends L{constructor(t,e){super(),this.action=t,this.self=e,this.target=e}}class $s extends L{constructor(t,e){super(),this.action=t,this.self=e,this.target=e}}class js extends L{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class Zs extends L{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}const yh=Object.freeze(Object.defineProperty({__proto__:null,ActionCompleteEvent:$s,ActionStartEvent:Ys,ActivateEvent:Ns,AddEvent:js,CollisionEndEvent:si,CollisionPostSolveEvent:Mi,CollisionPreSolveEvent:Ri,CollisionStartEvent:ii,ContactEndEvent:Ii,ContactStartEvent:Ei,DeactivateEvent:Ws,EnterTriggerEvent:qs,EnterViewPortEvent:Vs,EventTypes:Ss,ExitTriggerEvent:Xs,ExitViewPortEvent:Gs,GameEvent:L,GameStartEvent:As,GameStopEvent:Es,GamepadAxisEvent:zs,GamepadButtonEvent:Us,GamepadConnectEvent:Ls,GamepadDisconnectEvent:ks,HiddenEvent:Hs,InitializeEvent:ze,KillEvent:Ai,PostCollisionEvent:ve,PostDebugDrawEvent:Ds,PostDrawEvent:Ue,PostFrameEvent:Bs,PostKillEvent:Ps,PostTransformDrawEvent:Rs,PostUpdateEvent:re,PreCollisionEvent:me,PreDebugDrawEvent:Ms,PreDrawEvent:ke,PreFrameEvent:Fs,PreKillEvent:Ts,PreTransformDrawEvent:Is,PreUpdateEvent:ne,RemoveEvent:Zs,VisibleEvent:Os},Symbol.toStringTag,{value:"Module"}));function wr(r){if(r.length===0)throw new Error("Cannot find minIndex of array.length == 0");let t=r[0],e=0;for(let i=1;i<r.length;i++)r[i]<t&&(t=r[i],e=i);return e}function ni(r){if(r&&r.getBoundingClientRect){const t=r.getBoundingClientRect();return x(t.x+window.scrollX,t.y+window.scrollY)}return v.Zero}function Ch(r,t){return t.indexOf(r)===-1?(t.push(r),!0):!1}function Oe(r,t){let e=-1;return(e=t.indexOf(r))>-1?(t.splice(e,1),!0):!1}function xr(r,t){for(let e=0;e<r.length;e++)if(r[e]===t)return!0;return!1}function br(r){throw new Error(r)}function Di(r,t){var e;const i=new wt;return((e=t==null?void 0:t.schedule.bind(t))!=null?e:setTimeout)(()=>{i.resolve()},r),i.promise}function yr(r,t){const e={};for(const i in r)t.includes(i)||(e[i]=r[i]);return e}function Fi(r){return r&&typeof r=="object"&&!Array.isArray(r)}function Bi(r,...t){if(!t.length)return r;const e=t.shift();if(Fi(r)&&Fi(e))for(const i in e)Fi(e[i])?(r[i]||Object.assign(r,{[i]:{}}),Bi(r[i],e[i])):Object.assign(r,{[i]:e[i]});return Bi(r,...t)}class Sh{constructor(t){this.data=t,this.type="Component Added"}}function Th(r){return!!r&&r.type==="Component Added"}class Ph{constructor(t){this.data=t,this.type="Component Removed"}}function Ah(r){return!!r&&r.type==="Component Removed"}const Eh={Add:"add",Remove:"remove",Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate",Kill:"kill"},Cr=class sr{constructor(t,e){this.id=sr._ID++,this.name=`Entity#${this.id}`,this.events=new X,this._tags=new Set,this.componentAdded$=new gt,this.componentRemoved$=new gt,this.tagAdded$=new gt,this.tagRemoved$=new gt,this.components=new Map,this.componentValues=[],this._componentsToRemove=[],this.scene=null,this.isActive=!0,this._parent=null,this.childrenAdded$=new gt,this.childrenRemoved$=new gt,this._children=[],this._isInitialized=!1,this._isAdded=!1;let i,s;if(Array.isArray(t))i=t,s=e;else if(t&&typeof t=="object"){const{components:n,name:o}=t;i=n!=null?n:[],s=o}if(s&&(this.name=s),i)for(const n of i)this.addComponent(n)}get active(){return this.isActive}set active(t){this.isActive=t}kill(){this.isActive&&(this.isActive=!1,this.unparent()),this.emit("kill",new Ai(this))}isKilled(){return!this.isActive}get tags(){return this._tags}hasTag(t){return this._tags.has(t)}addTag(t){return this._tags.add(t),this.tagAdded$.notifyAll(t),this}removeTag(t){return this._tags.delete(t),this.tagRemoved$.notifyAll(t),this}get types(){return Array.from(this.components.keys())}getComponents(){return Array.from(this.components.values())}hasAll(t){for(let e=0;e<t.length;e++)if(!this.components.has(t[e]))return!1;return!0}hasAllTags(t){for(let e=0;e<t.length;e++)if(!this.tags.has(t[e]))return!1;return!0}get(t){return this.components.get(t)}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}hasChild(t,e=!1){if(!e)return t.parent===this;for(const i of this.children)if(i===t||e&&i.hasChild(t,!0))return!0;return!1}addChild(t){if(t.parent===null){if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t)}else throw new Error("Entity already has a parent, cannot add without unparenting");return this}removeChild(t){return t.parent===this&&(Oe(t,this._children),t._parent=null,this.childrenRemoved$.notifyAll(t)),this}removeAllChildren(){for(let t=this.children.length-1;t>=0;t--)this.removeChild(this.children[t]);return this}getAncestors(){const t=[this];let e=this.parent;for(;e;)t.push(e),e=e.parent;return t.reverse()}getDescendants(){let t=[this],e=[this];for(;e.length>0;){const i=e.pop();i&&(e=e.concat(i.children),t=t.concat(i.children))}return t}clone(){const t=new sr;for(const e of this.types){const i=this.get(e);i&&t.addComponent(i.clone())}for(const e of this.children)t.addChild(e.clone());return t}addTemplate(t,e=!1){for(const i of t.getComponents())this.addComponent(i.clone(),e);for(const i of t.children)this.addChild(i.clone().addTemplate(i));return this}_getClassHierarchyRoot(t){var e,i;let s=t,n=(e=Object.getPrototypeOf(s.prototype))==null?void 0:e.constructor;for(;n&&n!==Object&&n!==Dt;)s=n,n=(i=Object.getPrototypeOf(s.prototype))==null?void 0:i.constructor;return s}addComponent(t,e=!1){if(this.has(t.constructor))if(e)this.removeComponent(t.constructor,!0);else return this;if(t.dependencies&&t.dependencies.length)for(const s of t.dependencies)this.addComponent(new s);t.owner=this;const i=this._getClassHierarchyRoot(t.constructor);return this.components.set(i,t),this.components.set(t.constructor,t),this.componentValues.push(t),t.onAdd&&t.onAdd(this),this.componentAdded$.notifyAll(t),this}removeComponent(t,e=!1){let i;if(vr(t)?i=t:i=t.constructor,e){const s=this.components.get(i);if(s){this.componentRemoved$.notifyAll(s),s.owner=void 0,s.onRemove&&s.onRemove(this);const o=this.componentValues.indexOf(s);o>-1&&this.componentValues.splice(o,1)}const n=this._getClassHierarchyRoot(i);this.components.delete(n),this.components.delete(i)}else this._componentsToRemove.push(i);return this}clearComponents(){const t=this.types;for(const e of t)this.removeComponent(e)}processComponentRemoval(){for(const t of this._componentsToRemove)this.removeComponent(t,!0);this._componentsToRemove.length=0}has(t){return this.components.has(t)}get isInitialized(){return this._isInitialized}get isAdded(){return this._isAdded}_initialize(t){this.isInitialized||(this.onInitialize(t),this.events.emit("initialize",new ze(t,this)),this._isInitialized=!0)}_add(t){!this.isAdded&&this.isActive&&(this.onAdd(t),this.events.emit("add",new js(t,this)),this._isAdded=!0)}_remove(t){this.isAdded&&!this.isActive&&(this.onRemove(t),this.events.emit("remove",new Zs(t,this)),this._isAdded=!1)}_preupdate(t,e){this.events.emit("preupdate",new ne(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new re(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onAdd(t){}onRemove(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._add(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e),this._remove(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){e?this.events.off(t,e):this.events.off(t)}};Cr._ID=0;let Tt=Cr;class Sr{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._childAddedHandlerMap=new Map,this._childRemovedHandlerMap=new Map,this._createChildAddedHandler=()=>e=>{this.addEntity(e)},this._createChildRemovedHandler=()=>e=>{this.removeEntity(e,!1)},this._entitiesToRemove=[]}updateEntities(t,e){for(let i=0;i<this.entities.length;i++){const s=this.entities[i];s.update(t.engine,e),s.isActive||this.removeEntity(s)}}findEntitiesForRemoval(){for(let t=0;t<this.entities.length;t++){const e=this.entities[t];e.isActive||this.removeEntity(e)}}addEntity(t){if(t.isActive=!0,t.scene=this._world.scene,t&&!this._entityIndex[t.id]){this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.children.forEach(s=>{s.scene=t.scene,this.addEntity(s)});const e=this._createChildAddedHandler();this._childAddedHandlerMap.set(t,e);const i=this._createChildRemovedHandler();this._childRemovedHandlerMap.set(t,i),t.childrenAdded$.subscribe(e),t.childrenRemoved$.subscribe(i)}}removeEntity(t,e=!0){var i,s;let n=0;t instanceof Tt?n=t.id:n=t;const o=this._entityIndex[n];if(o&&o.isActive&&(o.isActive=!1),o&&e){this._entitiesToRemove.push(o);return}if(delete this._entityIndex[n],o){o.scene=null,Oe(o,this.entities),this._world.queryManager.removeEntity(o),o.children.forEach(l=>{l.scene=null,this.removeEntity(l,e)});const a=this._childAddedHandlerMap.get(o);a&&(o.childrenAdded$.unsubscribe(a),this._childAddedHandlerMap.delete(o));const h=this._childRemovedHandlerMap.get(o);h&&(o.childrenRemoved$.unsubscribe(h),this._childRemovedHandlerMap.delete(o)),(s=(i=this._world)==null?void 0:i.scene)!=null&&s.engine&&this._world.scene.engine.stats.currFrame.actors.killed++}}processEntityRemovals(){for(let t=0;t<this._entitiesToRemove.length;t++){const e=this._entitiesToRemove[t];e.isActive||this.removeEntity(e,!1)}this._entitiesToRemove.length=0}processComponentRemovals(){for(let t=0;t<this.entities.length;t++)this.entities[t].processComponentRemoval()}getById(t){return this._entityIndex[t]}getByName(t){return this.entities.filter(e=>e.name===t)}clear(){for(let t=this.entities.length-1;t>=0;t--)this.removeEntity(this.entities[t])}}class Bt{constructor(t){this._entities=[],this.entitiesSet=new Set,this.entityAdded$=new gt,this.entityRemoved$=new gt,this.filter={components:{all:new Set,any:new Set,not:new Set},tags:{all:new Set,any:new Set,not:new Set}},this._dirty=!1;var e,i,s,n,o,a,h,l,c,u,_,f;Array.isArray(t)&&(t={components:{all:t}}),this.filter.components.all=new Set((i=(e=t.components)==null?void 0:e.all)!=null?i:[]),this.filter.components.any=new Set((n=(s=t.components)==null?void 0:s.any)!=null?n:[]),this.filter.components.not=new Set((a=(o=t.components)==null?void 0:o.not)!=null?a:[]),this.filter.tags.all=new Set((l=(h=t.tags)==null?void 0:h.all)!=null?l:[]),this.filter.tags.any=new Set((u=(c=t.tags)==null?void 0:c.any)!=null?u:[]),this.filter.tags.not=new Set((f=(_=t.tags)==null?void 0:_.not)!=null?f:[]),this.id=Bt.createId(t)}get entities(){return this._dirty&&(this._entities=Array.from(this.entitiesSet),this._dirty=!1),this._entities}static createId(t){var e,i,s,n,o,a,h,l,c,u,_,f;Array.isArray(t)&&(t={components:{all:t}});const p=(e=t.components)!=null&&e.any?`any_${Bt.hashComponents(new Set((i=t.components)==null?void 0:i.any))}`:"",g=(s=t.components)!=null&&s.all?`all_${Bt.hashComponents(new Set((n=t.components)==null?void 0:n.all))}`:"",w=(o=t.components)!=null&&o.not?`not_${Bt.hashComponents(new Set((a=t.components)==null?void 0:a.not))}`:"",m=(h=t.tags)!=null&&h.any?`any_${Bt.hashTags(new Set((l=t.tags)==null?void 0:l.any))}`:"",b=(c=t.tags)!=null&&c.all?`all_${Bt.hashTags(new Set((u=t.tags)==null?void 0:u.all))}`:"",T=(_=t.tags)!=null&&_.not?`not_${Bt.hashTags(new Set((f=t.tags)==null?void 0:f.not))}`:"";return[p,g,w,m,b,T].filter(Boolean).join("-")}static hashTags(t){return Array.from(t).map(e=>`t_${e}`).sort().join("-")}static hashComponents(t){return Array.from(t).map(e=>`c_${e.name}`).sort().join("-")}matchesNotFilter(t,e){for(const i of this.filter.components.not)if(e!==i&&t.has(i))return!0;for(const i of this.filter.tags.not)if(t.hasTag(i))return!0;return!1}matches(t,e){for(const i of this.filter.components.not)if(e!==i&&t.has(i))return!1;for(const i of this.filter.tags.not)if(t.hasTag(i))return!1;for(const i of this.filter.components.all)if(i===e||!t.has(i))return!1;for(const i of this.filter.tags.all)if(!t.hasTag(i))return!1;if(this.filter.components.any.size>0){let i=!1;for(const s of this.filter.components.any)if(t.has(s)){i=!0;break}if(!i)return!1}if(this.filter.tags.any.size>0){let i=!1;for(const s of this.filter.tags.any)if(t.hasTag(s)){i=!0;break}if(!i)return!1}return!0}checkAndModify(t,e){const i=this.entitiesSet.has(t);if(i&&this.matchesNotFilter(t,e))return this.removeEntity(t),!1;const s=this.matches(t,e);return i&&!s?(this.removeEntity(t),!1):!i&&s?(this._dirty=!0,this.entitiesSet.add(t),this.entityAdded$.notifyAll(t),!0):!1}removeEntity(t){this.entitiesSet.delete(t)&&(this._dirty=!0,this.entityRemoved$.notifyAll(t))}getEntities(t){return t&&this.entities.sort(t),this.entities}}class Qs{constructor(t){if(this.requiredTags=t,this.tags=new Set,this.entities=[],this.entityAdded$=new gt,this.entityRemoved$=new gt,t.length===0)throw new Error("Cannot create tag query without tags");for(const e of t)this.tags.add(e);this.id=Qs.createId(t)}static createId(t){return t.slice().sort().join("-")}checkAndAdd(t){return!this.entities.includes(t)&&t.hasAllTags(Array.from(this.tags))?(this.entities.push(t),this.entityAdded$.notifyAll(t),!0):!1}removeEntity(t){const e=this.entities.indexOf(t);e>-1&&(this.entities.splice(e,1),this.entityRemoved$.notifyAll(t))}getEntities(t){return t&&this.entities.sort(t),this.entities}}class Tr{constructor(t){this._world=t,this._queries=new Map,this._addComponentHandlers=new Map,this._removeComponentHandlers=new Map,this._componentToQueriesIndex=new Map,this._tagToQueriesIndex=new Map,this._addTagHandlers=new Map,this._removeTagHandlers=new Map,this._createAddComponentHandler=e=>i=>{this.addComponent(e,i)},this._createRemoveComponentHandler=e=>i=>{this.removeComponent(e,i)},this._createAddTagHandler=e=>i=>{this.addTag(e,i)},this._createRemoveTagHandler=e=>i=>{this.removeTag(e,i)}}createQuery(t){const e=Bt.createId(t);if(this._queries.has(e))return this._queries.get(e);const i=new Bt(t);this._queries.set(i.id,i);for(const s of[...i.filter.components.all,...i.filter.components.any,...i.filter.components.not]){const n=this._componentToQueriesIndex.get(s);n?n.push(i):this._componentToQueriesIndex.set(s,[i])}for(const s of[...i.filter.tags.all,...i.filter.tags.any,...i.filter.tags.not]){const n=this._tagToQueriesIndex.get(s);n?n.push(i):this._tagToQueriesIndex.set(s,[i])}for(const s of this._world.entities)this.addEntity(s);return i}addEntity(t){const e=this._addComponentHandlers.get(t),i=this._removeComponentHandlers.get(t),s=e!=null?e:this._createAddComponentHandler(t),n=i!=null?i:this._createRemoveComponentHandler(t);this._addComponentHandlers.set(t,s),this._removeComponentHandlers.set(t,n);const o=this._addTagHandlers.get(t),a=this._removeTagHandlers.get(t),h=o!=null?o:this._createAddTagHandler(t),l=a!=null?a:this._createRemoveTagHandler(t);this._addTagHandlers.set(t,h),this._removeTagHandlers.set(t,l);for(const c of this._queries.values())c.checkAndModify(t);t.componentAdded$.subscribe(s),t.componentRemoved$.subscribe(n),t.tagAdded$.subscribe(h),t.tagRemoved$.subscribe(l)}removeEntity(t){const e=this._addComponentHandlers.get(t),i=this._removeComponentHandlers.get(t);for(const o of this._queries.values())o.removeEntity(t);e&&(t.componentAdded$.unsubscribe(e),this._addComponentHandlers.delete(t)),i&&(t.componentRemoved$.unsubscribe(i),this._removeComponentHandlers.delete(t));const s=this._addTagHandlers.get(t),n=this._removeTagHandlers.get(t);s&&(t.tagAdded$.unsubscribe(s),this._addTagHandlers.delete(t)),n&&(t.tagRemoved$.unsubscribe(n),this._removeTagHandlers.delete(t))}addComponent(t,e){var i;const s=(i=this._componentToQueriesIndex.get(e.constructor))!=null?i:[];for(const n of s)n.checkAndModify(t)}removeComponent(t,e){var i;const s=(i=this._componentToQueriesIndex.get(e.constructor))!=null?i:[];for(const n of s)n.checkAndModify(t,e.constructor)}addTag(t,e){var i;const s=(i=this._tagToQueriesIndex.get(e))!=null?i:[];for(const n of s)n.checkAndModify(t)}removeTag(t,e){var i;const s=(i=this._tagToQueriesIndex.get(e))!=null?i:[];for(const n of s)n.removeEntity(t),n.checkAndModify(t)}}const Nt={Highest:-1/0,Higher:-5,Average:0,Lower:5,Lowest:1/0};var Pt=(r=>(r.Update="update",r.Draw="draw",r))(Pt||{});class At{}At.priority=Nt.Average;function Pr(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Ar{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find(e=>e instanceof t)}addSystem(t){let e;t instanceof At?e=t:e=new t(this._world),this.systems.push(e),this.systems.sort((i,s)=>i.constructor.priority-s.constructor.priority),this.initialized&&e.initialize&&e.initialize(this._world,this._world.scene)}removeSystem(t){Oe(t,this.systems)}initialize(){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world,this._world.scene)}}updateSystems(t,e,i){const s=this.systems.filter(n=>n.systemType===t);for(const n of s)n.preupdate&&n.preupdate(e,i);for(const n of s)n.update(i);for(const n of s)n.postupdate&&n.postupdate(e,i)}clear(){for(let t=this.systems.length-1;t>=0;t--)this.removeSystem(this.systems[t])}}class Er{constructor(t){this.scene=t,this._logger=R.getInstance(),this.queryManager=new Tr(this),this.entityManager=new Sr(this),this.systemManager=new Ar(this)}query(t){return this.queryManager.createQuery(t)}queryTags(t){return this.queryManager.createQuery({tags:{all:t}})}update(t,e){t===Pt.Update&&this.entityManager.updateEntities(this.scene,e),this.systemManager.updateSystems(t,this.scene,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){if(t instanceof Tt){this.entityManager.addEntity(t);return}if(t instanceof At||Pr(t)){this.systemManager.addSystem(t);return}this._logger.warn(`Could not add entity/system ${t.constructor.name} to Excalibur!
|
|
18
|
+
`}};Ts.All=new Ts("Collide with all groups",-1,-1);let me=Ts;var As=(r=>(r.Kill="kill",r.PreKill="prekill",r.PostKill="postkill",r.PreDraw="predraw",r.PostDraw="postdraw",r.PreDebugDraw="predebugdraw",r.PostDebugDraw="postdebugdraw",r.PreUpdate="preupdate",r.PostUpdate="postupdate",r.PreFrame="preframe",r.PostFrame="postframe",r.PreCollision="precollision",r.CollisionStart="collisionstart",r.CollisionEnd="collisionend",r.PostCollision="postcollision",r.Initialize="initialize",r.Activate="activate",r.Deactivate="deactivate",r.ExitViewport="exitviewport",r.EnterViewport="enterviewport",r.ExitTrigger="exit",r.EnterTrigger="enter",r.Connect="connect",r.Disconnect="disconnect",r.Button="button",r.Axis="axis",r.Visible="visible",r.Hidden="hidden",r.Start="start",r.Stop="stop",r.PointerUp="pointerup",r.PointerDown="pointerdown",r.PointerMove="pointermove",r.PointerEnter="pointerenter",r.PointerLeave="pointerleave",r.PointerCancel="pointercancel",r.PointerWheel="pointerwheel",r.Up="up",r.Down="down",r.Move="move",r.Enter="enter",r.Leave="leave",r.Cancel="cancel",r.Wheel="wheel",r.Press="press",r.Release="release",r.Hold="hold",r.PointerDragStart="pointerdragstart",r.PointerDragEnd="pointerdragend",r.PointerDragEnter="pointerdragenter",r.PointerDragLeave="pointerdragleave",r.PointerDragMove="pointerdragmove",r.ActionStart="actionstart",r.ActionComplete="actioncomplete",r.Add="add",r.Remove="remove",r))(As||{});class k{constructor(){this.other=null,this._bubbles=!0}get bubbles(){return this._bubbles}set bubbles(t){this._bubbles=t}stopPropagation(){this.bubbles=!1}}class Ei extends k{constructor(t){super(),this.self=t,this.target=t}}class Ps extends k{constructor(t){super(),this.self=t,this.target=t}}class Es extends k{constructor(t){super(),this.self=t,this.target=t}}class Is extends k{constructor(t){super(),this.self=t,this.target=t}}class Rs extends k{constructor(t){super(),this.self=t,this.target=t}}class Ue extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class ze extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Ms extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Fs extends k{constructor(t,e,i){super(),this.ctx=t,this.elapsed=e,this.self=i,this.target=i}}class Ds extends k{constructor(t,e){super(),this.ctx=t,this.self=e,this.target=e}}class Bs extends k{constructor(t,e){super(),this.ctx=t,this.self=e,this.target=e}}class re extends k{constructor(t,e,i){super(),this.engine=t,this.elapsed=e,this.self=i,this.target=i}}class oe extends k{constructor(t,e,i){super(),this.engine=t,this.elapsed=e,this.self=i,this.target=i}}class ks extends k{constructor(t,e){super(),this.engine=t,this.prevStats=e,this.target=t}}class Ls extends k{constructor(t,e){super(),this.engine=t,this.stats=e,this.target=t}}class Us extends k{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class zs extends k{constructor(t,e){super(),this.index=t,this.gamepad=e,this.target=e}}class Os extends k{constructor(t,e,i,s){super(),this.button=t,this.index=e,this.value=i,this.self=s,this.target=s}}class Hs extends k{constructor(t,e,i){super(),this.axis=t,this.value=e,this.self=i,this.target=i}}class Ns extends k{constructor(t){super(),this.self=t,this.target=t}}class Ws extends k{constructor(t){super(),this.self=t,this.target=t}}class ve extends k{constructor(t,e,i,s,n){super(),this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n,this.target=t}}class we extends k{constructor(t,e,i,s,n){super(),this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n,this.target=t}}class Ii{constructor(t,e,i,s){this.self=t,this.other=e,this.side=i,this.contact=s}}class Ri{constructor(t,e,i,s){this.self=t,this.other=e,this.side=i,this.lastContact=s}}class Mi{constructor(t,e,i,s,n){this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class Fi{constructor(t,e,i,s,n){this.self=t,this.other=e,this.side=i,this.intersection=s,this.contact=n}}class ni extends k{constructor(t,e,i,s){super(),this.self=t,this.other=e,this.side=i,this.contact=s,this.target=t}}class ri extends k{constructor(t,e,i,s){super(),this.self=t,this.other=e,this.side=i,this.lastContact=s,this.target=t}}class Oe extends k{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class Gs extends k{constructor(t,e){super(),this.context=t,this.self=e,this.target=e}}class Vs extends k{constructor(t,e){super(),this.context=t,this.self=e,this.target=e}}class qs extends k{constructor(t){super(),this.self=t,this.target=t}}class Xs extends k{constructor(t){super(),this.self=t,this.target=t}}class Ys extends k{constructor(t,e){super(),this.self=t,this.entity=e,this.target=t}}class $s extends k{constructor(t,e){super(),this.self=t,this.entity=e,this.target=t}}class Zs extends k{constructor(t,e){super(),this.action=t,this.self=e,this.target=e}}class js extends k{constructor(t,e){super(),this.action=t,this.self=e,this.target=e}}class Qs extends k{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}class Js extends k{constructor(t,e){super(),this.engine=t,this.self=e,this.target=e}}const yh=Object.freeze(Object.defineProperty({__proto__:null,ActionCompleteEvent:js,ActionStartEvent:Zs,ActivateEvent:Gs,AddEvent:Qs,CollisionEndEvent:ri,CollisionPostSolveEvent:Fi,CollisionPreSolveEvent:Mi,CollisionStartEvent:ni,ContactEndEvent:Ri,ContactStartEvent:Ii,DeactivateEvent:Vs,EnterTriggerEvent:Ys,EnterViewPortEvent:Xs,EventTypes:As,ExitTriggerEvent:$s,ExitViewPortEvent:qs,GameEvent:k,GameStartEvent:Is,GameStopEvent:Rs,GamepadAxisEvent:Hs,GamepadButtonEvent:Os,GamepadConnectEvent:Us,GamepadDisconnectEvent:zs,HiddenEvent:Ws,InitializeEvent:Oe,KillEvent:Ei,PostCollisionEvent:we,PostDebugDrawEvent:Bs,PostDrawEvent:ze,PostFrameEvent:Ls,PostKillEvent:Es,PostTransformDrawEvent:Fs,PostUpdateEvent:oe,PreCollisionEvent:ve,PreDebugDrawEvent:Ds,PreDrawEvent:Ue,PreFrameEvent:ks,PreKillEvent:Ps,PreTransformDrawEvent:Ms,PreUpdateEvent:re,RemoveEvent:Js,VisibleEvent:Ns},Symbol.toStringTag,{value:"Module"}));function wr(r){if(r.length===0)throw new Error("Cannot find minIndex of array.length == 0");let t=r[0],e=0;for(let i=1;i<r.length;i++)r[i]<t&&(t=r[i],e=i);return e}function oi(r){if(r&&r.getBoundingClientRect){const t=r.getBoundingClientRect();return b(t.x+window.scrollX,t.y+window.scrollY)}return w.Zero}function Ch(r,t){return t.indexOf(r)===-1?(t.push(r),!0):!1}function He(r,t){let e=-1;return(e=t.indexOf(r))>-1?(t.splice(e,1),!0):!1}function xr(r,t){for(let e=0;e<r.length;e++)if(r[e]===t)return!0;return!1}function br(r){throw new Error(r)}function Di(r,t){var e;const i=new wt;return((e=t==null?void 0:t.schedule.bind(t))!=null?e:setTimeout)(()=>{i.resolve()},r),i.promise}function yr(r,t){const e={};for(const i in r)t.includes(i)||(e[i]=r[i]);return e}function Bi(r){return r&&typeof r=="object"&&!Array.isArray(r)}function ki(r,...t){if(!t.length)return r;const e=t.shift();if(Bi(r)&&Bi(e))for(const i in e)Bi(e[i])?(r[i]||Object.assign(r,{[i]:{}}),ki(r[i],e[i])):Object.assign(r,{[i]:e[i]});return ki(r,...t)}class Sh{constructor(t){this.data=t,this.type="Component Added"}}function Th(r){return!!r&&r.type==="Component Added"}class Ah{constructor(t){this.data=t,this.type="Component Removed"}}function Ph(r){return!!r&&r.type==="Component Removed"}const Eh={Add:"add",Remove:"remove",Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate",Kill:"kill"},Cr=class sr{constructor(t,e){this.id=sr._ID++,this.name=`Entity#${this.id}`,this.events=new X,this._tags=new Set,this.componentAdded$=new gt,this.componentRemoved$=new gt,this.tagAdded$=new gt,this.tagRemoved$=new gt,this.components=new Map,this.componentValues=[],this._componentsToRemove=[],this.scene=null,this.isActive=!0,this._parent=null,this.childrenAdded$=new gt,this.childrenRemoved$=new gt,this._children=[],this._isInitialized=!1,this._isAdded=!1;let i,s;if(Array.isArray(t))i=t,s=e;else if(t&&typeof t=="object"){const{components:n,name:o}=t;i=n!=null?n:[],s=o}if(s&&(this.name=s),i)for(const n of i)this.addComponent(n)}get active(){return this.isActive}set active(t){this.isActive=t}kill(){this.isActive&&(this.isActive=!1,this.unparent()),this.emit("kill",new Ei(this))}isKilled(){return!this.isActive}get tags(){return this._tags}hasTag(t){return this._tags.has(t)}addTag(t){return this._tags.add(t),this.tagAdded$.notifyAll(t),this}removeTag(t){return this._tags.delete(t),this.tagRemoved$.notifyAll(t),this}get types(){return Array.from(this.components.keys())}getComponents(){return Array.from(this.components.values())}hasAll(t){for(let e=0;e<t.length;e++)if(!this.components.has(t[e]))return!1;return!0}hasAllTags(t){for(let e=0;e<t.length;e++)if(!this.tags.has(t[e]))return!1;return!0}get(t){return this.components.get(t)}get parent(){return this._parent}get children(){return this._children}unparent(){this._parent&&(this._parent.removeChild(this),this._parent=null)}hasChild(t,e=!1){if(!e)return t.parent===this;for(const i of this.children)if(i===t||e&&i.hasChild(t,!0))return!0;return!1}addChild(t){if(t.parent===null){if(this.getAncestors().includes(t))throw new Error("Cycle detected, cannot add entity");this._children.push(t),t._parent=this,this.childrenAdded$.notifyAll(t)}else throw new Error("Entity already has a parent, cannot add without unparenting");return this}removeChild(t){return t.parent===this&&(He(t,this._children),t._parent=null,this.childrenRemoved$.notifyAll(t)),this}removeAllChildren(){for(let t=this.children.length-1;t>=0;t--)this.removeChild(this.children[t]);return this}getAncestors(){const t=[this];let e=this.parent;for(;e;)t.push(e),e=e.parent;return t.reverse()}getDescendants(){let t=[this],e=[this];for(;e.length>0;){const i=e.pop();i&&(e=e.concat(i.children),t=t.concat(i.children))}return t}clone(){const t=new sr;for(const e of this.types){const i=this.get(e);i&&t.addComponent(i.clone())}for(const e of this.children)t.addChild(e.clone());return t}addTemplate(t,e=!1){for(const i of t.getComponents())this.addComponent(i.clone(),e);for(const i of t.children)this.addChild(i.clone().addTemplate(i));return this}_getClassHierarchyRoot(t){var e,i;let s=t,n=(e=Object.getPrototypeOf(s.prototype))==null?void 0:e.constructor;for(;n&&n!==Object&&n!==Dt;)s=n,n=(i=Object.getPrototypeOf(s.prototype))==null?void 0:i.constructor;return s}addComponent(t,e=!1){if(this.has(t.constructor))if(e)this.removeComponent(t.constructor,!0);else return this;if(t.dependencies&&t.dependencies.length)for(const s of t.dependencies)this.addComponent(new s);t.owner=this;const i=this._getClassHierarchyRoot(t.constructor);return this.components.set(i,t),this.components.set(t.constructor,t),this.componentValues.push(t),t.onAdd&&t.onAdd(this),this.componentAdded$.notifyAll(t),this}removeComponent(t,e=!1){let i;if(vr(t)?i=t:i=t.constructor,e){const s=this.components.get(i);if(s){this.componentRemoved$.notifyAll(s),s.owner=void 0,s.onRemove&&s.onRemove(this);const o=this.componentValues.indexOf(s);o>-1&&this.componentValues.splice(o,1)}const n=this._getClassHierarchyRoot(i);this.components.delete(n),this.components.delete(i)}else this._componentsToRemove.push(i);return this}clearComponents(){const t=this.types;for(const e of t)this.removeComponent(e)}processComponentRemoval(){for(const t of this._componentsToRemove)this.removeComponent(t,!0);this._componentsToRemove.length=0}has(t){return this.components.has(t)}get isInitialized(){return this._isInitialized}get isAdded(){return this._isAdded}_initialize(t){this.isInitialized||(this.onInitialize(t),this.events.emit("initialize",new Oe(t,this)),this._isInitialized=!0)}_add(t){!this.isAdded&&this.isActive&&(this.onAdd(t),this.events.emit("add",new Qs(t,this)),this._isAdded=!0)}_remove(t){this.isAdded&&!this.isActive&&(this.onRemove(t),this.events.emit("remove",new Js(t,this)),this._isAdded=!1)}_preupdate(t,e){this.events.emit("preupdate",new re(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new oe(t,e,this)),this.onPostUpdate(t,e)}onInitialize(t){}onAdd(t){}onRemove(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}update(t,e){this._initialize(t),this._add(t),this._preupdate(t,e);for(const i of this.children)i.update(t,e);this._postupdate(t,e),this._remove(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){e?this.events.off(t,e):this.events.off(t)}};Cr._ID=0;let At=Cr;class Sr{constructor(t){this._world=t,this.entities=[],this._entityIndex={},this._childAddedHandlerMap=new Map,this._childRemovedHandlerMap=new Map,this._createChildAddedHandler=()=>e=>{this.addEntity(e)},this._createChildRemovedHandler=()=>e=>{this.removeEntity(e,!1)},this._entitiesToRemove=[]}updateEntities(t,e){for(let i=0;i<this.entities.length;i++){const s=this.entities[i];s.update(t.engine,e),s.isActive||this.removeEntity(s)}}findEntitiesForRemoval(){for(let t=0;t<this.entities.length;t++){const e=this.entities[t];e.isActive||this.removeEntity(e)}}addEntity(t){if(t.isActive=!0,t.scene=this._world.scene,t&&!this._entityIndex[t.id]){this._entityIndex[t.id]=t,this.entities.push(t),this._world.queryManager.addEntity(t),t.children.forEach(s=>{s.scene=t.scene,this.addEntity(s)});const e=this._createChildAddedHandler();this._childAddedHandlerMap.set(t,e);const i=this._createChildRemovedHandler();this._childRemovedHandlerMap.set(t,i),t.childrenAdded$.subscribe(e),t.childrenRemoved$.subscribe(i)}}removeEntity(t,e=!0){var i,s;let n=0;t instanceof At?n=t.id:n=t;const o=this._entityIndex[n];if(o&&o.isActive&&(o.isActive=!1),o&&e){this._entitiesToRemove.push(o);return}if(delete this._entityIndex[n],o){o.scene=null,He(o,this.entities),this._world.queryManager.removeEntity(o),o.children.forEach(l=>{l.scene=null,this.removeEntity(l,e)});const a=this._childAddedHandlerMap.get(o);a&&(o.childrenAdded$.unsubscribe(a),this._childAddedHandlerMap.delete(o));const h=this._childRemovedHandlerMap.get(o);h&&(o.childrenRemoved$.unsubscribe(h),this._childRemovedHandlerMap.delete(o)),(s=(i=this._world)==null?void 0:i.scene)!=null&&s.engine&&this._world.scene.engine.stats.currFrame.actors.killed++}}processEntityRemovals(){for(let t=0;t<this._entitiesToRemove.length;t++){const e=this._entitiesToRemove[t];e.isActive||this.removeEntity(e,!1)}this._entitiesToRemove.length=0}processComponentRemovals(){for(let t=0;t<this.entities.length;t++)this.entities[t].processComponentRemoval()}getById(t){return this._entityIndex[t]}getByName(t){return this.entities.filter(e=>e.name===t)}clear(){for(let t=this.entities.length-1;t>=0;t--)this.removeEntity(this.entities[t])}}class Lt{constructor(t){this._entities=[],this.entitiesSet=new Set,this.entityAdded$=new gt,this.entityRemoved$=new gt,this.filter={components:{all:new Set,any:new Set,not:new Set},tags:{all:new Set,any:new Set,not:new Set}},this._dirty=!1;var e,i,s,n,o,a,h,l,c,u,_,f;Array.isArray(t)&&(t={components:{all:t}}),this.filter.components.all=new Set((i=(e=t.components)==null?void 0:e.all)!=null?i:[]),this.filter.components.any=new Set((n=(s=t.components)==null?void 0:s.any)!=null?n:[]),this.filter.components.not=new Set((a=(o=t.components)==null?void 0:o.not)!=null?a:[]),this.filter.tags.all=new Set((l=(h=t.tags)==null?void 0:h.all)!=null?l:[]),this.filter.tags.any=new Set((u=(c=t.tags)==null?void 0:c.any)!=null?u:[]),this.filter.tags.not=new Set((f=(_=t.tags)==null?void 0:_.not)!=null?f:[]),this.id=Lt.createId(t)}get entities(){return this._dirty&&(this._entities=Array.from(this.entitiesSet),this._dirty=!1),this._entities}static createId(t){var e,i,s,n,o,a,h,l,c,u,_,f;Array.isArray(t)&&(t={components:{all:t}});const m=(e=t.components)!=null&&e.any?`any_${Lt.hashComponents(new Set((i=t.components)==null?void 0:i.any))}`:"",p=(s=t.components)!=null&&s.all?`all_${Lt.hashComponents(new Set((n=t.components)==null?void 0:n.all))}`:"",x=(o=t.components)!=null&&o.not?`not_${Lt.hashComponents(new Set((a=t.components)==null?void 0:a.not))}`:"",v=(h=t.tags)!=null&&h.any?`any_${Lt.hashTags(new Set((l=t.tags)==null?void 0:l.any))}`:"",g=(c=t.tags)!=null&&c.all?`all_${Lt.hashTags(new Set((u=t.tags)==null?void 0:u.all))}`:"",y=(_=t.tags)!=null&&_.not?`not_${Lt.hashTags(new Set((f=t.tags)==null?void 0:f.not))}`:"";return[m,p,x,v,g,y].filter(Boolean).join("-")}static hashTags(t){return Array.from(t).map(e=>`t_${e}`).sort().join("-")}static hashComponents(t){return Array.from(t).map(e=>`c_${e.name}`).sort().join("-")}matchesNotFilter(t,e){for(const i of this.filter.components.not)if(e!==i&&t.has(i))return!0;for(const i of this.filter.tags.not)if(t.hasTag(i))return!0;return!1}matches(t,e){for(const i of this.filter.components.not)if(e!==i&&t.has(i))return!1;for(const i of this.filter.tags.not)if(t.hasTag(i))return!1;for(const i of this.filter.components.all)if(i===e||!t.has(i))return!1;for(const i of this.filter.tags.all)if(!t.hasTag(i))return!1;if(this.filter.components.any.size>0){let i=!1;for(const s of this.filter.components.any)if(t.has(s)){i=!0;break}if(!i)return!1}if(this.filter.tags.any.size>0){let i=!1;for(const s of this.filter.tags.any)if(t.hasTag(s)){i=!0;break}if(!i)return!1}return!0}checkAndModify(t,e){const i=this.entitiesSet.has(t);if(i&&this.matchesNotFilter(t,e))return this.removeEntity(t),!1;const s=this.matches(t,e);return i&&!s?(this.removeEntity(t),!1):!i&&s?(this._dirty=!0,this.entitiesSet.add(t),this.entityAdded$.notifyAll(t),!0):!1}removeEntity(t){this.entitiesSet.delete(t)&&(this._dirty=!0,this.entityRemoved$.notifyAll(t))}getEntities(t){return t&&this.entities.sort(t),this.entities}}class Ks{constructor(t){if(this.requiredTags=t,this.tags=new Set,this.entities=[],this.entityAdded$=new gt,this.entityRemoved$=new gt,t.length===0)throw new Error("Cannot create tag query without tags");for(const e of t)this.tags.add(e);this.id=Ks.createId(t)}static createId(t){return t.slice().sort().join("-")}checkAndAdd(t){return!this.entities.includes(t)&&t.hasAllTags(Array.from(this.tags))?(this.entities.push(t),this.entityAdded$.notifyAll(t),!0):!1}removeEntity(t){const e=this.entities.indexOf(t);e>-1&&(this.entities.splice(e,1),this.entityRemoved$.notifyAll(t))}getEntities(t){return t&&this.entities.sort(t),this.entities}}class Tr{constructor(t){this._world=t,this._queries=new Map,this._addComponentHandlers=new Map,this._removeComponentHandlers=new Map,this._componentToQueriesIndex=new Map,this._tagToQueriesIndex=new Map,this._addTagHandlers=new Map,this._removeTagHandlers=new Map,this._createAddComponentHandler=e=>i=>{this.addComponent(e,i)},this._createRemoveComponentHandler=e=>i=>{this.removeComponent(e,i)},this._createAddTagHandler=e=>i=>{this.addTag(e,i)},this._createRemoveTagHandler=e=>i=>{this.removeTag(e,i)}}createQuery(t){const e=Lt.createId(t);if(this._queries.has(e))return this._queries.get(e);const i=new Lt(t);this._queries.set(i.id,i);for(const s of[...i.filter.components.all,...i.filter.components.any,...i.filter.components.not]){const n=this._componentToQueriesIndex.get(s);n?n.push(i):this._componentToQueriesIndex.set(s,[i])}for(const s of[...i.filter.tags.all,...i.filter.tags.any,...i.filter.tags.not]){const n=this._tagToQueriesIndex.get(s);n?n.push(i):this._tagToQueriesIndex.set(s,[i])}for(const s of this._world.entities)this.addEntity(s);return i}addEntity(t){const e=this._addComponentHandlers.get(t),i=this._removeComponentHandlers.get(t),s=e!=null?e:this._createAddComponentHandler(t),n=i!=null?i:this._createRemoveComponentHandler(t);this._addComponentHandlers.set(t,s),this._removeComponentHandlers.set(t,n);const o=this._addTagHandlers.get(t),a=this._removeTagHandlers.get(t),h=o!=null?o:this._createAddTagHandler(t),l=a!=null?a:this._createRemoveTagHandler(t);this._addTagHandlers.set(t,h),this._removeTagHandlers.set(t,l);for(const c of this._queries.values())c.checkAndModify(t);t.componentAdded$.subscribe(s),t.componentRemoved$.subscribe(n),t.tagAdded$.subscribe(h),t.tagRemoved$.subscribe(l)}removeEntity(t){const e=this._addComponentHandlers.get(t),i=this._removeComponentHandlers.get(t);for(const o of this._queries.values())o.removeEntity(t);e&&(t.componentAdded$.unsubscribe(e),this._addComponentHandlers.delete(t)),i&&(t.componentRemoved$.unsubscribe(i),this._removeComponentHandlers.delete(t));const s=this._addTagHandlers.get(t),n=this._removeTagHandlers.get(t);s&&(t.tagAdded$.unsubscribe(s),this._addTagHandlers.delete(t)),n&&(t.tagRemoved$.unsubscribe(n),this._removeTagHandlers.delete(t))}addComponent(t,e){var i;const s=(i=this._componentToQueriesIndex.get(e.constructor))!=null?i:[];for(const n of s)n.checkAndModify(t)}removeComponent(t,e){var i;const s=(i=this._componentToQueriesIndex.get(e.constructor))!=null?i:[];for(const n of s)n.checkAndModify(t,e.constructor)}addTag(t,e){var i;const s=(i=this._tagToQueriesIndex.get(e))!=null?i:[];for(const n of s)n.checkAndModify(t)}removeTag(t,e){var i;const s=(i=this._tagToQueriesIndex.get(e))!=null?i:[];for(const n of s)n.removeEntity(t),n.checkAndModify(t)}}const Gt={Highest:-1/0,Higher:-5,Average:0,Lower:5,Lowest:1/0};var Pt=(r=>(r.Update="update",r.Draw="draw",r))(Pt||{});class Et{}Et.priority=Gt.Average;function Ar(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Pr{constructor(t){this._world=t,this.systems=[],this.initialized=!1}get(t){return this.systems.find(e=>e instanceof t)}addSystem(t){let e;t instanceof Et?e=t:e=new t(this._world),this.systems.push(e),this.systems.sort((i,s)=>i.constructor.priority-s.constructor.priority),this.initialized&&e.initialize&&e.initialize(this._world,this._world.scene)}removeSystem(t){He(t,this.systems)}initialize(){if(!this.initialized){this.initialized=!0;for(const t of this.systems)t.initialize&&t.initialize(this._world,this._world.scene)}}updateSystems(t,e,i){const s=this.systems.filter(n=>n.systemType===t);for(const n of s)n.preupdate&&n.preupdate(e,i);for(const n of s)n.update(i);for(const n of s)n.postupdate&&n.postupdate(e,i)}clear(){for(let t=this.systems.length-1;t>=0;t--)this.removeSystem(this.systems[t])}}class Er{constructor(t){this.scene=t,this._logger=R.getInstance(),this.queryManager=new Tr(this),this.entityManager=new Sr(this),this.systemManager=new Pr(this)}query(t){return this.queryManager.createQuery(t)}queryTags(t){return this.queryManager.createQuery({tags:{all:t}})}update(t,e){t===Pt.Update&&this.entityManager.updateEntities(this.scene,e),this.systemManager.updateSystems(t,this.scene,e),this.entityManager.findEntitiesForRemoval(),this.entityManager.processComponentRemovals(),this.entityManager.processEntityRemovals()}add(t){if(t instanceof At){this.entityManager.addEntity(t);return}if(t instanceof Et||Ar(t)){this.systemManager.addSystem(t);return}this._logger.warn(`Could not add entity/system ${t.constructor.name} to Excalibur!
|
|
19
19
|
|
|
20
20
|
If this looks like an Excalibur type, this can be caused by 2 versions of excalibur being included on the page.
|
|
21
21
|
|
|
22
|
-
Check your bundler settings to make sure this is not the case! Excalibur has ESM & UMD bundles be sure one 1 is loaded.`)}get(t){return this.systemManager.get(t)}remove(t,e=!0){if(t instanceof
|
|
22
|
+
Check your bundler settings to make sure this is not the case! Excalibur has ESM & UMD bundles be sure one 1 is loaded.`)}get(t){return this.systemManager.get(t)}remove(t,e=!0){if(t instanceof At){this.entityManager.removeEntity(t,e);return}if(t instanceof Et){this.systemManager.removeSystem(t);return}this._logger.warn(`Could not remove entity/system ${t.constructor.name} to Excalibur!
|
|
23
23
|
|
|
24
24
|
If this looks like an Excalibur type, this can be caused by 2 versions of excalibur being included on the page.
|
|
25
25
|
|
|
26
|
-
Check your bundler settings to make sure this is not the case! Excalibur has ESM & UMD bundles be sure one 1 is loaded.`)}get entities(){return this.entityManager.entities}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}d.Side=(r=>(r.None="None",r.Top="Top",r.Bottom="Bottom",r.Left="Left",r.Right="Right",r))(d.Side||{}),(r=>{function t(i){return i==="Top"?"Bottom":i==="Bottom"?"Top":i==="Left"?"Right":i==="Right"?"Left":"None"}r.getOpposite=t;function e(i){return Math.abs(i.x)>=Math.abs(i.y)?i.x<=0?"Left":"Right":i.y<=0?"Top":"Bottom"}r.fromDirection=e})(d.Side||(d.Side={}));const Ir=class vt{constructor(t=0,e=0,i=0,s=0){this._points=[],typeof t=="object"?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):typeof t=="number"&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}clone(t){const e=t||new vt(0,0,0,0);return e.left=this.left,e.right=this.right,e.top=this.top,e.bottom=this.bottom,e}reset(){this.left=0,this.top=0,this.bottom=0,this.right=0}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?d.Side.Right:d.Side.Left:t.y<0?d.Side.Bottom:d.Side.Top:d.Side.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let o=0;o<t.length;o++)t[o].x<e&&(e=t[o].x),t[o].x>s&&(s=t[o].x),t[o].y<i&&(i=t[o].y),t[o].y>n&&(n=t[o].y);return new vt(e,i,s,n)}static fromDimension(t,e,i=v.Half,s=v.Zero){return new vt(-t*i.x+s.x,-e*i.y+s.y,t-t*i.x+s.x,e-e*i.y+s.y)}get width(){return this.right-this.left}get height(){return this.bottom-this.top}hasZeroDimensions(){return this.width===0||this.height===0}get center(){return new v((this.left+this.right)/2,(this.top+this.bottom)/2)}get topLeft(){return new v(this.left,this.top)}get bottomRight(){return new v(this.right,this.bottom)}get topRight(){return new v(this.right,this.top)}get bottomLeft(){return new v(this.left,this.bottom)}translate(t){return new vt(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=v.Zero){const i=this.getPoints().map(s=>s.rotate(t,e));return vt.fromPoints(i)}scale(t,e=v.Zero){const i=this.translate(e);return new vt(i.left*t.x,i.top*t.y,i.right*t.x,i.bottom*t.y)}transform(t){const e=t.data[0]*this.left,i=t.data[1]*this.left,s=t.data[0]*this.right,n=t.data[1]*this.right,o=t.data[2]*this.top,a=t.data[3]*this.top,h=t.data[2]*this.bottom,l=t.data[3]*this.bottom,c=t.getPosition(),u=Math.min(e,s)+Math.min(o,h)+c.x,_=Math.min(i,n)+Math.min(a,l)+c.y,f=Math.max(e,s)+Math.max(o,h)+c.x,p=Math.max(i,n)+Math.max(a,l)+c.y;return new vt({left:u,top:_,right:f,bottom:p})}getPerimeter(){const t=this.width,e=this.height;return 2*(t+e)}getPoints(){return(this._left!==this.left||this._right!==this.right||this._top!==this.top||this._bottom!==this.bottom)&&(this._points.length=0,this._points.push(new v(this.left,this.top)),this._points.push(new v(this.right,this.top)),this._points.push(new v(this.right,this.bottom)),this._points.push(new v(this.left,this.bottom)),this._left=this.left,this._right=this.right,this._top=this.top,this._bottom=this.bottom),this._points}rayCast(t,e=1/0){let i,s;const n=t.dir.x===0?Number.MAX_VALUE:1/t.dir.x,o=t.dir.y===0?Number.MAX_VALUE:1/t.dir.y,a=(this.left-t.pos.x)*n,h=(this.right-t.pos.x)*n;s=Math.min(a,h),i=Math.max(a,h);const l=(this.top-t.pos.y)*o,c=(this.bottom-t.pos.y)*o;return s=Math.max(s,Math.min(l,c)),i=Math.min(i,Math.max(l,c)),i>=0&&i>=s&&s<e}rayCastTime(t,e=1/0){let i,s;const n=t.dir.x===0?Number.MAX_VALUE:1/t.dir.x,o=t.dir.y===0?Number.MAX_VALUE:1/t.dir.y,a=(this.left-t.pos.x)*n,h=(this.right-t.pos.x)*n;s=Math.min(a,h),i=Math.max(a,h);const l=(this.top-t.pos.y)*o,c=(this.bottom-t.pos.y)*o;return s=Math.max(s,Math.min(l,c)),i=Math.min(i,Math.max(l,c)),i>=0&&i>=s&&s<e?s:-1}contains(t){return t instanceof v?this.left<=t.x&&this.top<=t.y&&t.y<=this.bottom&&t.x<=this.right:t instanceof vt?this.left<=t.left&&this.top<=t.top&&t.bottom<=this.bottom&&t.right<=this.right:!1}combine(t,e){const i=e||new vt(0,0,0,0),s=Math.min(this.left,t.left),n=Math.min(this.top,t.top),o=Math.max(this.right,t.right),a=Math.max(this.bottom,t.bottom);return i.left=s,i.top=n,i.right=o,i.bottom=a,i}get dimensions(){return new v(this.width,this.height)}overlaps(t,e){const i=e||0;if(t.hasZeroDimensions())return this.contains(t);if(this.hasZeroDimensions())return t.contains(this);const s=this.combine(t);return s.width+i<t.width+this.width&&s.height+i<t.height+this.height}intersect(t){if(this.bottom<=t.top||t.bottom<=this.top||this.right<=t.left||t.right<=this.left)return null;const e=this.bottom-t.top;vt._SCRATCH_INTERSECT[0]=e;const i=t.bottom-this.top;vt._SCRATCH_INTERSECT[1]=i;const s=this.right-t.left;vt._SCRATCH_INTERSECT[2]=s;const n=t.right-this.left;vt._SCRATCH_INTERSECT[3]=n;const o=wr(vt._SCRATCH_INTERSECT);switch(o){case 0:return new v(0,-e);case 1:return new v(0,i);case 2:return new v(-s,0);case 3:return new v(n,0);default:const a=o;throw new Error(`Unreachable index: [${a}] on bounding box intersection!`)}}intersectWithSide(t){const e=this.intersect(t);return vt.getSideFromIntersection(e)}draw(t,e=P.Yellow){t.debug.drawRect(this.left,this.top,this.width,this.height,{color:e})}};Ir._SCRATCH_INTERSECT=[0,0,0,0];let D=Ir;class pt{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=pt.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;if(t.id===e.id||t.owner&&e.owner&&t.owner.id===e.owner.id||t.localBounds.hasZeroDimensions()||e.localBounds.hasZeroDimensions())return!1;const n=(i=t==null?void 0:t.owner)==null?void 0:i.get(W),o=(s=e==null?void 0:e.owner)==null?void 0:s.get(W);return!(!n||!o||!n.group.canCollide(o.group)||n.collisionType===M.Fixed&&o.collisionType===M.Fixed||o.collisionType===M.PreventCollision||n.collisionType===M.PreventCollision||!n.isActive||!o.isActive)}get canCollide(){const t=this.colliderA,e=this.colliderB;return pt.canCollide(t,e)}collide(){return this.colliderA.collide(this.colliderB)}hasCollider(t){return t===this.colliderA||t===this.colliderB}static calculatePairHash(t,e){return t.value<e.value?`#${t.value}+${e.value}`:`#${e.value}+${t.value}`}}class Js{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new D,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class Ks{constructor(t,e=new D(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this._config=t,this.worldBounds=e,this.root=null,this.nodes={}}_insert(t){if(this.root===null){this.root=t,this.root.parent=null;return}const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const a=i.left,h=i.right,l=i.bounds.getPerimeter(),u=i.bounds.combine(e).getPerimeter(),_=2*u,f=2*(u-l);let p=0;const g=e.combine(a.bounds);let w,m;a.isLeaf()?p=g.getPerimeter()+f:(m=a.bounds.getPerimeter(),w=g.getPerimeter(),p=w-m+f);let b=0;const T=e.combine(h.bounds);if(h.isLeaf()?b=T.getPerimeter()+f:(m=h.bounds.getPerimeter(),w=T.getPerimeter(),b=w-m+f),_<p&&_<b)break;p<b?i=a:i=h}const s=i.parent,n=new Js(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,s!==null?(s.left===i?s.left=n:s.right=n,n.left=i,n.right=t,i.parent=n,t.parent=n):(n.left=i,n.right=t,i.parent=n,t.parent=n,this.root=n);let o=t.parent;for(;o;){if(o=this._balance(o),!o.left)throw new Error("Parent of current leaf cannot have a null left child"+o);if(!o.right)throw new Error("Parent of current leaf cannot have a null right child"+o);o.height=1+Math.max(o.left.height,o.right.height),o.bounds=o.left.bounds.combine(o.right.bounds),o=o.parent}}_remove(t){if(t===this.root){this.root=null;return}const e=t.parent,i=e.parent;let s;if(e.left===t?s=e.right:s=e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let n=i;for(;n;)n=this._balance(n),n.bounds=n.left.bounds.combine(n.right.bounds),n.height=1+Math.max(n.left.height,n.right.height),n=n.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new Js;e.data=t,e.bounds=t.bounds,e.bounds.left-=2,e.bounds.top-=2,e.bounds.right+=2,e.bounds.bottom+=2,this.nodes[t.id.value]=e,this._insert(e)}updateCollider(t){var e;const i=this.nodes[t.id.value];if(!i)return!1;const s=t.bounds;if(!this.worldBounds.contains(s))return R.getInstance().warn("Collider with id "+t.id.value+" is outside the world bounds and will no longer be tracked for physics"),this.untrackCollider(t),!1;if(i.bounds.contains(s))return!1;if(this._remove(i),s.left-=this._config.boundsPadding,s.top-=this._config.boundsPadding,s.right+=this._config.boundsPadding,s.bottom+=this._config.boundsPadding,t.owner){const n=(e=t.owner)==null?void 0:e.get(W);if(n){const o=n.vel.x*32/1e3*this._config.velocityMultiplier,a=n.vel.y*32/1e3*this._config.velocityMultiplier;o<0?s.left+=o:s.right+=o,a<0?s.top+=a:s.bottom+=a}}return i.bounds=s,this._insert(i),!0}untrackCollider(t){const e=this.nodes[t.id.value];e&&(this._remove(e),this.nodes[t.id.value]=null,delete this.nodes[t.id.value])}_balance(t){if(t===null)throw new Error("Cannot balance at null node");if(t.isLeaf()||t.height<2)return t;const e=t.left,i=t.right,s=t,n=e,o=i,a=e.left,h=e.right,l=i.left,c=i.right,u=o.height-n.height;if(u>1)return o.left=s,o.parent=s.parent,s.parent=o,o.parent?o.parent.left===s?o.parent.left=o:o.parent.right=o:this.root=o,l.height>c.height?(o.right=l,s.right=c,c.parent=s,s.bounds=n.bounds.combine(c.bounds),o.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,c.height),o.height=1+Math.max(s.height,l.height)):(o.right=c,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),o.bounds=s.bounds.combine(c.bounds),s.height=1+Math.max(n.height,l.height),o.height=1+Math.max(s.height,c.height)),o;if(u<-1){if(n.left=s,n.parent=s.parent,s.parent=n,n.parent)if(n.parent.left===s)n.parent.left=n;else{if(n.parent.right!==s)throw"Error rotating Dynamic Tree";n.parent.right=n}else this.root=n;return a.height>h.height?(n.right=a,s.left=h,h.parent=s,s.bounds=o.bounds.combine(h.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(o.height,h.height),n.height=1+Math.max(s.height,a.height)):(n.right=h,s.left=a,a.parent=s,s.bounds=o.bounds.combine(a.bounds),n.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(o.height,a.height),n.height=1+Math.max(s.height,h.height)),n}return t}getHeight(){return this.root===null?0:this.root.height}query(t,e){const i=t.bounds,s=n=>{if(n&&n.bounds.overlaps(i))if(n.isLeaf()&&n.data!==t){if(e.call(t,n.data))return!0}else return s(n.left)||s(n.right);return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e))if(n.isLeaf()){if(i.call(t,n.data))return!0}else return s(n.left)||s(n.right);return!1};s(this.root)}getNodes(){const t=e=>e?[e].concat(t(e.left),t(e.right)):[];return t(this.root)}debug(t){const e=i=>{i&&(i.isLeaf()?i.bounds.draw(t,P.Green):i.bounds.draw(t,P.White),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class Li{constructor(t){this._config=t,this._pairs=new Set,this._collisionPairCache=[],this._colliders=[],this._dynamicCollisionTree=new Ks(t.dynamicTree)}getColliders(){return this._colliders}query(t){const e=[];return t instanceof D?this._dynamicCollisionTree.query({id:_e("collider",-1),owner:null,bounds:t},i=>(e.push(i),!1)):this._dynamicCollisionTree.query({id:_e("collider",-1),owner:null,bounds:new D(t.x,t.y,t.x,t.y)},i=>(e.push(i),!1)),e}rayCast(t,e){var i,s,n;const o=[],a=(i=e==null?void 0:e.maxDistance)!=null?i:1/0,h=e==null?void 0:e.collisionGroup,l=h?h.category:(s=e==null?void 0:e.collisionMask)!=null?s:pe.All.category,c=(n=e==null?void 0:e.searchAllColliders)!=null?n:!1;return this._dynamicCollisionTree.rayCastQuery(t,a,u=>{const f=u.owner.get(W);if(e!=null&&e.ignoreCollisionGroupAll&&f.group===pe.All)return!1;const p=(l&f.group.category)!==0;if(f!=null&&f.group&&!p)return!1;const g=u.rayCast(t,a);if(g){if(e!=null&&e.filter){if(e.filter(g)&&(o.push(g),!c))return!0}else if(o.push(g),!c)return!0}return!1}),o}track(t){if(!t){R.getInstance().warn("Cannot track null collider");return}if(t instanceof at){const e=t.getColliders();for(const i of e)i.owner=t.owner,this._colliders.push(i),this._dynamicCollisionTree.trackCollider(i)}else this._colliders.push(t),this._dynamicCollisionTree.trackCollider(t)}untrack(t){if(!t){R.getInstance().warn("Cannot untrack a null collider");return}if(t instanceof at){const e=t.getColliders();for(const i of e){const s=this._colliders.indexOf(i);s!==-1&&this._colliders.splice(s,1),this._dynamicCollisionTree.untrackCollider(i)}}else{const e=this._colliders.indexOf(t);e!==-1&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}_pairExists(t,e){const i=pt.calculatePairHash(t.id,e.id);return this._pairs.has(i)}broadphase(t,e,i){const s=e/1e3,n=t.filter(a=>{var h,l;const c=(h=a.owner)==null?void 0:h.get(W);return((l=a.owner)==null?void 0:l.isActive)&&c.collisionType!==M.PreventCollision});this._collisionPairCache=[],this._pairs.clear();let o;for(let a=0,h=n.length;a<h;a++)o=n[a],this._dynamicCollisionTree.query(o,l=>{if(!this._pairExists(o,l)&&pt.canCollide(o,l)){const c=new pt(o,l);this._pairs.add(c.id),this._collisionPairCache.push(c)}return!1});if(i&&(i.physics.pairs=this._collisionPairCache.length),this._config.continuous.checkForFastBodies)for(const a of n){const h=a.owner.get(W);if((h==null?void 0:h.collisionType)!==M.Active)continue;const l=h.vel.magnitude*s+h.acc.magnitude*.5*s*s,c=Math.min(a.bounds.height,a.bounds.width);if(this._config.continuous.disableMinimumSpeedForFastBody||l>c/2){i&&i.physics.fastBodies++;const u=h.globalPos.sub(h.oldPos),_=a.center,f=a.getFurthestPoint(h.vel),p=f.sub(u),g=new fe(p,h.vel);g.pos=g.pos.add(g.dir.scale(-2*this._config.continuous.surfaceEpsilon));let w,m=new v(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(g,l+this._config.continuous.surfaceEpsilon*2,b=>{if(!this._pairExists(a,b)&&pt.canCollide(a,b)){const T=b.rayCast(g,l+this._config.continuous.surfaceEpsilon*10);if(T){const C=T.point.sub(p);C.magnitude<m.magnitude&&(m=C,w=b)}}return!1}),w&&v.isValid(m)){const b=new pt(a,w);this._pairs.has(b.id)||(this._pairs.add(b.id),this._collisionPairCache.push(b));const T=_.sub(f);h.globalPos=p.add(T).add(m).add(g.dir.scale(10*this._config.continuous.surfaceEpsilon)),a.update(h.transform.get()),i&&i.physics.fastBodyCollisions++}}}return this._collisionPairCache}narrowphase(t,e){let i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();if(i=i.concat(n),e&&n.length>0)for(const o of n)e.physics.contacts.set(o.id,o)}return e&&(e.physics.collisions+=i.length),i}update(t){let e=0;const i=t.length;for(let s=0;s<i;s++)this._dynamicCollisionTree.updateCollider(t[s])&&e++;return e}debug(t){this._dynamicCollisionTree.debug(t)}}const Rr=class Ba{constructor(){this.id=_e("collider",Ba._ID++),this.composite=null,this.events=new X,this.offset=v.Zero}touching(t){const e=this.collide(t);return!!(e&&e.length>0)}};Rr._ID=0;let ri=Rr;var ki=(r=>(r.Arcade="arcade",r.Realistic="realistic",r))(ki||{}),oe=(r=>(r.None="none",r.VerticalFirst="vertical-first",r.HorizontalFirst="horizontal-first",r))(oe||{});const tn={vertical:1,horizontal:2},en={horizontal:1,vertical:2},sn={horizontal:0,vertical:0};var oi=(r=>(r.DynamicTree="dynamic-tree",r.SparseHashGrid="sparse-hash-grid",r))(oi||{});const Jt=()=>({enabled:!0,integration:{onScreenOnly:!1},gravity:x(0,0).clone(),solver:ki.Arcade,substep:1,colliders:{compositeStrategy:"together"},continuous:{checkForFastBodies:!0,disableMinimumSpeedForFastBody:!1,surfaceEpsilon:.1},bodies:{canSleepByDefault:!1,sleepEpsilon:.07,wakeThreshold:.07*3,sleepBias:.9,defaultMass:10},spatialPartition:oi.SparseHashGrid,sparseHashGrid:{size:100},dynamicTree:{boundsPadding:5,velocityMultiplier:2},arcade:{contactSolveBias:oe.None},realistic:{contactSolveBias:oe.None,positionIterations:3,velocityIterations:8,slop:1,steeringFactor:.2,warmStart:!0}});class at extends ri{constructor(t){super(),this._collisionProcessor=new Li({...Jt()}),this._dynamicAABBTree=new Ks({boundsPadding:5,velocityMultiplier:2}),this._colliders=[];for(const e of t)this.addCollider(e)}set compositeStrategy(t){this._compositeStrategy=t}get compositeStrategy(){return this._compositeStrategy}clearColliders(){this._colliders=[]}addCollider(t){let e;t instanceof at?(e=t.getColliders(),e.forEach(i=>i.offset.addEqual(t.offset))):e=[t];for(const i of e)i.events.pipe(this.events),i.composite=this,this._colliders.push(i),this._collisionProcessor.track(i),this._dynamicAABBTree.trackCollider(i)}removeCollider(t){t.events.pipe(this.events),t.composite=null,Oe(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return((e=(t=this._transform)==null?void 0:t.pos)!=null?e:v.Zero).add(this.offset)}get center(){var t,e;return((e=(t=this._transform)==null?void 0:t.pos)!=null?e:v.Zero).add(this.offset)}get bounds(){var t,e;const i=this.getColliders();return i.reduce((n,o)=>n.combine(o.bounds),(e=(t=i[0])==null?void 0:t.bounds)!=null?e:new D().translate(this.worldPos)).translate(this.offset)}get localBounds(){var t,e;const i=this.getColliders();return i.reduce((n,o)=>n.combine(o.localBounds),(e=(t=i[0])==null?void 0:t.localBounds)!=null?e:new D)}get axes(){const t=this.getColliders();let e=[];for(const i of t)e=e.concat(i.axes);return e}getFurthestPoint(t){const e=this.getColliders(),i=[];for(const o of e)i.push(o.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const o of i){const a=o.dot(t);a>n&&(s=o,n=a)}return s}getInertia(t){const e=this.getColliders();let i=0;for(const s of e)i+=s.getInertia(t);return i}collide(t){let e=[t];t instanceof at&&(e=t.getColliders());const i=[];for(const n of e)this._dynamicAABBTree.query(n,o=>(i.push(new pt(n,o)),!1));let s=[];for(const n of i)s=s.concat(n.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof at){const s=t.getColliders();for(const n of e)for(const o of s){const a=n.getClosestLineBetween(o);a&&i.push(a)}}else for(const s of e){const n=t.getClosestLineBetween(s);n&&i.push(n)}if(i.length){let s=i[0].getLength(),n=i[0];for(const o of i){const a=o.getLength();a<s&&(s=a,n=o)}return n}return null}contains(t){const e=this.getColliders();for(const i of e)if(i.contains(t))return!0;return!1}rayCast(t,e){const i=this.getColliders(),s=[];for(const n of i){const o=n.rayCast(t,e);o&&s.push(o)}if(s.length){let n=s[0],o=n.point.dot(t.dir);for(const a of s){const h=t.dir.dot(a.point);h<o&&(n=a,o=h)}return n}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const n=s.project(t);n&&i.push(n)}if(i.length){const s=new Ke(i[0].min,i[0].max);for(const n of i)s.min=Math.min(n.min,s.min),s.max=Math.max(n.max,s.max);return s}return null}update(t){if(t){const e=this.getColliders();for(const i of e)i.owner=this.owner,i.update(t)}}debug(t,e,i){const s=this.getColliders();t.save(),t.translate(this.offset.x,this.offset.y);for(const n of s)n.debug(t,e,i);t.restore()}clone(){const t=new at(this._colliders.map(e=>e.clone()));return t.offset=this.offset.clone(),t}}function nn(r,t){const i=r.dir(),s=t.dir(),n=i.dot(i),o=s.dot(s);if(n<1e-9&&o<1e-9)return new J(r.begin,t.begin);if(n<1e-9){const w=F(s.dot(r.begin.sub(t.begin))/o,0,1),m=t.begin.add(s.scale(w));return new J(r.begin,m)}if(o<1e-9){const w=F(i.dot(t.begin.sub(r.begin))/n,0,1),m=r.begin.add(i.scale(w));return new J(m,t.begin)}const a=r.begin.sub(t.begin),h=n,l=o,c=s.dot(a),u=h*l-Math.pow(i.dot(s),2);let _=0,f=0;Math.abs(u)>1e-9?_=F((i.dot(s)*c-l*i.dot(a))/u,0,1):_=F(i.dot(a)/h,0,1),Math.abs(l)>1e-9?f=F((i.dot(s)*_+c)/l,0,1):f=0;const p=r.begin.add(i.scale(_)),g=t.begin.add(s.scale(f));return new J(p,g)}const Wt={PolygonPolygonClosestLine(r,t){const e=r.getSides(),i=t.getSides();let s=Number.MAX_VALUE,n=null;for(let o=0;o<e.length;o++)for(let a=0;a<i.length;a++){const h=nn(e[o],i[a]),l=h.getLength();l<s&&(s=l,n=h)}return n},PolygonEdgeClosestLine(r,t){const i=t.worldPos.sub(r.worldPos),s=new fe(r.worldPos,i),n=r.rayCast(s).point.add(s.dir.scale(.1)),o=r.getClosestFace(n),a=t.asLine();return nn(o.face,a)},PolygonCircleClosestLine(r,t){const e=t.worldPos,i=e.sub(r.worldPos),s=new fe(r.worldPos,i.normalize()),n=r.rayCast(s).point.add(s.dir.scale(.1)),o=r.getClosestFace(n),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(e.x-a.x)+h.y*(e.y-a.y))/(h.x*h.x+h.y*h.y);l>1?l=1:l<0&&(l=0);const c=Math.sqrt(Math.pow(a.x+h.x*l-e.x,2)+Math.pow(a.y+h.y*l-e.y,2))-t.radius,u=(a.x+h.x*l-e.x)*t.radius/(t.radius+c),_=(a.y+h.y*l-e.y)*t.radius/(t.radius+c);return new J(h.scale(l).add(a),new v(e.x+u,e.y+_))},CircleCircleClosestLine(r,t){const i=t.worldPos.sub(r.worldPos),n=r.worldPos.sub(t.worldPos),o=new fe(r.worldPos,i),a=new fe(t.worldPos,n),h=r.rayCast(o),l=t.rayCast(a);return new J(h.point,l.point)},CircleEdgeClosestLine(r,t){const e=r.worldPos,i=t.asLine(),s=i.begin,n=i.getEdge(),o=s,a=n;let h=(a.x*(e.x-o.x)+a.y*(e.y-o.y))/(a.x*a.x+a.y*a.y);h>1?h=1:h<0&&(h=0);const l=Math.sqrt(Math.pow(o.x+a.x*h-e.x,2)+Math.pow(o.y+a.y*h-e.y,2))-r.radius,c=(o.x+a.x*h-e.x)*r.radius/(r.radius+l),u=(o.y+a.y*h-e.y)*r.radius/(r.radius+l);return new J(a.scale(h).add(o),new v(e.x+c,e.y+u))},EdgeEdgeClosestLine(r,t){const e=r.asLine(),i=t.asLine();return nn(e,i)}};class dt extends ri{constructor(t){super(),this.offset=v.Zero,this._globalMatrix=Q.identity(),this._localBoundsDirty=!0,this.offset=t.offset||v.Zero,this.radius=t.radius||0,this._globalMatrix.translate(this.offset.x,this.offset.y)}get worldPos(){return this._globalMatrix.getPosition()}get radius(){var t;if(this._radius)return this._radius;const e=this._transform,i=(t=e==null?void 0:e.globalScale)!=null?t:v.One;return this._radius=this._naturalRadius*Math.min(i.x,i.y)}set radius(t){var e;const i=this._transform,s=(e=i==null?void 0:i.globalScale)!=null?e:v.One;this._naturalRadius=t/Math.min(s.x,s.y),this._localBoundsDirty=!0,this._radius=t}clone(){return new dt({offset:this.offset.clone(),radius:this.radius})}get center(){return this._globalMatrix.getPosition()}contains(t){var e,i;return((i=(e=this._transform)==null?void 0:e.pos)!=null?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){var i,s;const n=this.center,o=t.dir,a=t.pos,h=n.sub(a),l=o.scale(h.dot(o)),u=h.sub(l).magnitude;if(u>this.radius)return null;{let _=0;if(ar(u,this.radius,1e-4)){if(_=-o.dot(a.sub(n)),_>0&&_<e){const f=t.getPoint(_);return{point:f,normal:f.sub(n).normalize(),collider:this,body:(i=this.owner)==null?void 0:i.get(W),distance:_}}return null}else{const f=Math.sqrt(Math.pow(o.dot(a.sub(n)),2)-Math.pow(a.sub(n).distance(),2)+Math.pow(this.radius,2)),p=-o.dot(a.sub(n))+f,g=-o.dot(a.sub(n))-f,w=[];p>=0&&w.push(p),g>=0&&w.push(g);const m=Math.min(...w);if(m<=e){const b=t.getPoint(m);return{point:b,normal:b.sub(n).normalize(),collider:this,body:(s=this.owner)==null?void 0:s.get(W),distance:m}}return null}}}getClosestLineBetween(t){if(t instanceof dt)return Wt.CircleCircleClosestLine(this,t);if(t instanceof lt)return Wt.PolygonCircleClosestLine(t,this).flip();if(t instanceof Ct)return Wt.CircleEdgeClosestLine(this,t).flip();throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Lt.CollideCircleCircle(this,t);if(t instanceof lt)return Lt.CollideCirclePolygon(this,t);if(t instanceof Ct)return Lt.CollideCircleEdge(this,t);throw new Error(`Circle could not collide with unknown CollisionShape ${typeof t}`)}getFurthestPoint(t){return this.center.add(t.normalize().scale(this.radius))}getFurthestLocalPoint(t){return t.normalize().scale(this.radius)}get bounds(){return this.localBounds.transform(this._globalMatrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=new D(-this._naturalRadius,-this._naturalRadius,+this._naturalRadius,+this._naturalRadius),this._localBoundsDirty=!1),this._localBounds}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){var e;this._transform=t,((e=t.matrix)!=null?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y),this._radius=void 0}project(t){const e=[],s=this.center.dot(t);return e.push(s),e.push(s+this.radius),e.push(s-this.radius),new Ke(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e,i){var s,n,o,a;const{lineWidth:h}={lineWidth:1,...i},l=this._transform,c=(s=l==null?void 0:l.globalScale)!=null?s:v.One,u=(n=l==null?void 0:l.globalRotation)!=null?n:0,_=(o=l==null?void 0:l.globalPos)!=null?o:v.Zero;t.save(),t.translate(_.x,_.y),t.rotate(u),t.scale(c.x,c.y),t.drawCircle((a=this.offset)!=null?a:v.Zero,this._naturalRadius,P.Transparent,e,h),t.restore()}}class we{constructor(t,e,i,s,n,o,a,h){this._canceled=!1,this.bodyA=null,this.bodyB=null;var l,c,u,_,f,p;if(this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=o,this.localPoints=a,this.info=h,this.id=pt.calculatePairHash(t.id,e.id),t.composite||e.composite){const g=((l=t.composite)==null?void 0:l.compositeStrategy)==="separate"?t.id:(u=(c=t.composite)==null?void 0:c.id)!=null?u:t.id,w=((_=e.composite)==null?void 0:_.compositeStrategy)==="separate"?e.id:(p=(f=e.composite)==null?void 0:f.id)!=null?p:e.id;this.id+="|"+pt.calculatePairHash(g,w)}this.colliderA.owner&&(this.bodyA=this.colliderA.owner.get(W)),this.colliderB.owner&&(this.bodyB=this.colliderB.owner.get(W))}matchAwake(){const t=this.bodyA,e=this.bodyB;t&&e&&t.isSleeping!==e.isSleeping&&(t.isSleeping&&t.collisionType!==M.Fixed&&e.sleepMotion>=t.wakeThreshold&&(t.isSleeping=!1),e.isSleeping&&e.collisionType!==M.Fixed&&t.sleepMotion>=e.wakeThreshold&&(e.isSleeping=!1))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}bias(t){if(t!==this.colliderA&&t!==this.colliderB)throw new Error("Collider must be either colliderA or colliderB from this contact");if(t===this.colliderA)return this;const e=this.colliderA,i=this.colliderB;return this.colliderB=e,this.colliderA=i,this.mtv=this.mtv.negate(),this.normal=this.normal.negate(),this.tangent=this.tangent.negate(),this}}class Ui{constructor(t,e,i=100){this.builder=t,this.recycler=e,this.maxObjects=i,this.totalAllocations=0,this.index=0,this.objects=[],this.disableWarnings=!1,this._logger=R.getInstance()}dispose(){this.objects.length=0}preallocate(){for(let t=0;t<this.maxObjects;t++)this.objects[t]=this.builder()}using(t){const e=t(this);return e?this.done(...e):this.done()}borrow(t){const e=this.get();t(e),this.index--}get(){return this.index===this.maxObjects&&(this.disableWarnings||this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=this.maxObjects*2),this.objects[this.index]?this.recycler?this.recycler(this.objects[this.index++]):this.objects[this.index++]:(this.totalAllocations++,this.objects[this.index++]=this.builder())}done(...t){this.index=0;for(const e of t){const i=this.objects.indexOf(e);this.objects[i]=this.builder(),this.totalAllocations++}return t}}class Mr{constructor(){this.axis=x(0,0),this.localAxis=x(0,0),this.side=new J(x(0,0),x(0,0)),this.localSide=new J(x(0,0),x(0,0)),this.point=x(0,0),this.localPoint=x(0,0)}}const xe=class ee{static findPolygonPolygonSeparation(t,e){if(e.transform.matrix.determinant()===0)return ee.findPolygonPolygonSeparationDegenerate(t,e);let i=-Number.MAX_VALUE,s=-1,n;const o=e.transform.inverse.multiply(t.transform.matrix,ee._SCRATCH_MATRIX),a=o.getRotation(),h=t.normals,l=t.points,c=e.points;for(let f=0;f<l.length;f++){const p=h[f].rotate(a,ee._ZERO,ee._SCRATCH_NORMAL),g=o.multiply(l[f],ee._SCRATCH_POINT);let w=Number.MAX_VALUE,m;for(let b=0;b<c.length;b++){const T=p.dot(c[b].sub(g,ee._SCRATCH_SUB_POINT));T<w&&(w=T,m=c[b])}w>i&&(i=w,s=f,n=m)}const u=(s+1)%l.length,_=ee.SeparationPool.get();return _.collider=t,_.separation=i,i>0||(h[s].clone(_.localAxis),h[s].rotate(t.transform.rotation,ee._ZERO,_.axis),t.transform.matrix.multiply(l[s],_.side.begin),t.transform.matrix.multiply(l[u],_.side.end),e.transform.matrix.multiply(n,_.point),_.sideId=s,n.clone(_.localPoint),l[s].clone(_.localSide.begin),l[u].clone(_.localSide.end)),_}static findCirclePolygonSeparation(t,e){const i=e.axes,n=e.center.sub(t.worldPos),o=e.getFurthestPoint(n.negate());i.push(o.sub(t.worldPos).normalize());let a=Number.MAX_VALUE,h=null,l=-1;for(let c=0;c<i.length;c++){const u=e.project(i[c]),_=t.project(i[c]),f=u.getOverlap(_);if(f<=0)return null;f<a&&(a=f,h=i[c],l=c)}return l<0?null:h.normalize().scale(a)}static findPolygonPolygonSeparationDegenerate(t,e){let i=-Number.MAX_VALUE,s=null,n=null,o=-1,a=null;const h=t.getSides(),l=t.getLocalSides();for(let c=0;c<h.length;c++){const u=h[c],_=u.normal(),f=e.getFurthestPoint(_.negate()),p=u.distanceToPoint(f,!0);p>i&&(i=p,s=u,n=_,o=c,a=f)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:l[o],sideId:o,point:a,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}};xe.SeparationPool=new Ui(()=>new Mr,r=>r,500),xe._ZERO=x(0,0),xe._SCRATCH_POINT=x(0,0),xe._SCRATCH_SUB_POINT=x(0,0),xe._SCRATCH_NORMAL=x(0,0),xe._SCRATCH_MATRIX=Q.identity();let He=xe;He.SeparationPool.disableWarnings=!0;const Ih=v.Zero,Rh=v.Zero,Mh=Q.identity(),Lt={CollideCircleCircle(r,t){const e=r.worldPos,i=t.worldPos,s=r.radius+t.radius,n=e.distance(i);if(n>s)return[];const o=s-n,a=i.sub(e).normalize(),h=a.perpendicular(),l=a.scale(o),c=r.getFurthestPoint(a),u=r.getFurthestLocalPoint(a),_={collider:r,separation:o,axis:a,point:c};return[new we(r,t,l,a,h,[c],[u],_)]},CollideCirclePolygon(r,t){var e,i;let s=He.findCirclePolygonSeparation(r,t);if(!s)return[];s=s.dot(t.center.sub(r.center))<0?s.negate():s;const o=r.getFurthestPoint(s),h=((i=(e=r.owner)==null?void 0:e.get(A))!=null?i:new A).applyInverse(o),l=s.normalize(),c={collider:r,separation:-s.magnitude,axis:l,point:o,localPoint:h,side:t.findSide(l.negate()),localSide:t.findLocalSide(l.negate())};return[new we(r,t,s,l,l.perpendicular(),[o],[h],c)]},CollideCircleEdge(r,t){const e=r.center,i=t.asLine(),s=i.end.sub(i.begin),n=s.dot(i.end.sub(e)),o=s.dot(e.sub(i.begin)),a=t.asLine(),h=t.asLocalLine();if(o<=0){const m=i.begin.sub(e),b=m.dot(m);if(b>r.radius*r.radius)return[];const T=m.normalize(),C=r.radius-Math.sqrt(b),S={collider:r,separation:C,axis:T,point:a.begin,side:a,localSide:h};return[new we(r,t,T.scale(C),T,T.perpendicular(),[a.begin],[h.begin],S)]}if(n<=0){const m=i.end.sub(e),b=m.dot(m);if(b>r.radius*r.radius)return[];const T=m.normalize(),C=r.radius-Math.sqrt(b),S={collider:r,separation:C,axis:T,point:a.end,side:a,localSide:h};return[new we(r,t,T.scale(C),T,T.perpendicular(),[a.end],[h.end],S)]}const l=s.dot(s),c=i.begin.scale(n).add(i.end.scale(o)).scale(1/l),u=e.sub(c),_=u.dot(u);if(_>r.radius*r.radius)return[];let f=s.perpendicular();f.dot(e.sub(i.begin))<0&&(f.x=-f.x,f.y=-f.y),f=f.normalize();const p=r.radius-Math.sqrt(_),g=f.scale(p),w={collider:r,separation:p,axis:f,point:c,side:a,localSide:h};return[new we(r,t,g,f.negate(),f.negate().perpendicular(),[c],[c.sub(t.worldPos)],w)]},CollideEdgeEdge(){return[]},CollidePolygonEdge(r,t){var e;const i=r.center,n=t.center.sub(i).normalize(),o=new lt({points:[t.begin,t.end,t.end.add(n.scale(100)),t.begin.add(n.scale(100))],offset:t.offset});o.owner=t.owner,((e=t.owner)==null?void 0:e.get(A))&&o.update(t.owner.get(A).get());const h=this.CollidePolygonPolygon(r,o);return h.length&&(h[0].colliderB=t,h[0].id=pt.calculatePairHash(r.id,t.id)),h},CollidePolygonPolygon(r,t){const e=He.findPolygonPolygonSeparation(r,t);if(e.separation>0)return[];const i=He.findPolygonPolygonSeparation(t,r);if(i.separation>0)return[];const s=e.separation>i.separation?e:i,n=s.collider===r?t:r,o=s.collider===r?r:t,a=n.transform.inverse.multiply(o.transform.matrix,Mh),h=a.getRotation(),l=o.normals[s.sideId].rotate(h,Ih,Rh);let c=Number.MAX_VALUE,u=0;for(let m=0;m<n.normals.length;m++){const b=l.dot(n.normals[m]);b<c&&(c=b,u=m)}if(!s.localSide||!s.localAxis||!s.axis)return[];const _=s.localSide.transform(a),f=s.localAxis.perpendicular().negate().rotate(h),g=new J(n.points[u],n.points[(u+1)%n.points.length]).clip(f.negate(),-f.dot(_.begin),!1);let w=null;if(g&&(w=g.clip(f,f.dot(_.end),!1)),w){const m=[],b=[],T=w.getPoints();for(let I=0;I<T.length;I++){const y=T[I];_.below(y)&&(m.push(y),b.push(n.transform.apply(y)))}let C=s.axis,S=C.perpendicular();return t.center.sub(r.center).dot(C)<0&&(C=C.negate(),S=C.perpendicular()),[new we(r,t,C.scale(-s.separation),C,S,b,m,s)]}return[]},FindContactSeparation(r,t){var e,i,s,n;const o=r.colliderA,a=(i=(e=r.bodyA)==null?void 0:e.transform)!=null?i:new A,h=r.colliderB,l=(n=(s=r.bodyB)==null?void 0:s.transform)!=null?n:new A;if(o instanceof dt&&h instanceof dt){const c=o.radius+h.radius,u=a.pos.distance(l.pos);return-(c-u)}if(o instanceof lt&&h instanceof lt&&r.info.localSide){let c,u;return r.info.collider===o?(c=new J(a.apply(r.info.localSide.begin).add(o.offset),a.apply(r.info.localSide.end).add(o.offset)),u=l.apply(t).add(h.offset)):(c=new J(l.apply(r.info.localSide.begin).add(h.offset),l.apply(r.info.localSide.end).add(h.offset)),u=a.apply(t).add(o.offset)),c.distanceToPoint(u,!0)}if(o instanceof lt&&h instanceof dt||h instanceof lt&&o instanceof dt){const c=a.apply(t);if(r.info.side)return r.info.side.distanceToPoint(c,!0)}if(o instanceof Ct&&h instanceof lt||h instanceof Ct&&o instanceof lt){let c;if(r.info.collider===o?c=l.apply(t):c=a.apply(t),r.info.side)return r.info.side.distanceToPoint(c,!0)}if(o instanceof dt&&h instanceof Ct||h instanceof dt&&o instanceof Ct){const c=l.apply(t);let u;o instanceof dt&&(u=o.getFurthestPoint(r.normal));const _=c.distance(u);if(r.info.side)return _>0?-_:0}return 0}};class Ct extends ri{constructor(t){var e;super(),this._globalMatrix=Q.identity(),this.begin=t.begin||v.Zero,this.end=t.end||v.Zero,this.offset=(e=t.offset)!=null?e:v.Zero}clone(){return new Ct({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return(t=e==null?void 0:e.globalPos.add(this.offset))!=null?t:this.offset}get center(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.average(e)}_getTransformedBegin(){return this._globalMatrix.multiply(this.begin)}_getTransformedEnd(){return this._globalMatrix.multiply(this.end)}getSlope(){const t=this._getTransformedBegin(),e=this._getTransformedEnd(),i=t.distance(e);return e.sub(t).scale(1/i)}getLength(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.distance(e)}contains(){return!1}rayCast(t,e=1/0){var i;const s=this._getTransformedBegin().sub(t.pos);if(t.dir.cross(this.getSlope())===0&&s.cross(t.dir)!==0)return null;const n=t.dir.cross(this.getSlope());if(n===0)return null;const o=s.cross(this.getSlope())/n;if(o>=0&&o<=e){const a=s.cross(t.dir)/n/this.getLength();if(a>=0&&a<=1)return{distance:o,normal:this.asLine().normal(),collider:this,body:(i=this.owner)==null?void 0:i.get(W),point:t.getPoint(o)}}return null}getClosestLineBetween(t){if(t instanceof dt)return Wt.CircleEdgeClosestLine(t,this);if(t instanceof lt)return Wt.PolygonEdgeClosestLine(t,this).flip();if(t instanceof Ct)return Wt.EdgeEdgeClosestLine(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Lt.CollideCircleEdge(t,this);if(t instanceof lt)return Lt.CollidePolygonEdge(t,this);if(t instanceof Ct)return Lt.CollideEdgeEdge();throw new Error(`Edge could not collide with unknown CollisionShape ${typeof t}`)}getFurthestPoint(t){const e=this._getTransformedBegin(),i=this._getTransformedEnd();return t.dot(e)>0?e:i}_boundsFromBeginEnd(t,e,i=10){return new D(Math.min(t.x,e.x)-i,Math.min(t.y,e.y)-i,Math.max(t.x,e.x)+i,Math.max(t.y,e.y)+i)}get bounds(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return this._boundsFromBeginEnd(t,e)}get localBounds(){return this._boundsFromBeginEnd(this.begin,this.end)}asLine(){return new J(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new J(this.begin,this.end)}get axes(){const e=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),i=[];return i.push(e),i.push(e.negate()),i.push(e.normal()),i.push(e.normal().negate()),i}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){var e;this._transform=t,((e=t.matrix)!=null?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}project(t){const e=[],i=[this._getTransformedBegin(),this._getTransformedEnd()],s=i.length;for(let n=0;n<s;n++)e.push(i[n].dot(t));return new Ke(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.drawLine(i,s,e,2),t.drawCircle(i,2,e),t.drawCircle(s,2,e)}}class lt extends ri{constructor(t){var e;super(),this._logger=R.getInstance(),this._transform=new Qt,this._transformedPoints=[],this._sides=[],this._localSides=[],this._transformedPointsDirty=!0,this._sidesDirty=!0,this._localSidesDirty=!0,this._localBoundsDirty=!0,this.offset=(e=t.offset)!=null?e:v.Zero,this._transform.pos.x+=this.offset.x,this._transform.pos.y+=this.offset.y,this.points=t.points,this.isConvex()||t.suppressConvexWarning||this._logger.warn("Excalibur only supports convex polygon colliders and will not behave properly.Call PolygonCollider.triangulate() to build a new collider composed of smaller convex triangles"),this._calculateTransformation()}flagDirty(){this._localBoundsDirty=!0,this._localSidesDirty=!0,this._transformedPointsDirty=!0,this._sidesDirty=!0}get normals(){return this._normals}set points(t){if(t.length<3)throw new Error("PolygonCollider cannot be created with less that 3 points");this._points=t,this._checkAndUpdateWinding(this._points),this._calculateNormals(),this.flagDirty()}_calculateNormals(){const t=[];for(let e=0;e<this._points.length;e++)t.push(this._points[(e+1)%this._points.length].sub(this._points[e]).normal());this._normals=t}get points(){return this._points}get transform(){return this._transform}_checkAndUpdateWinding(t){this._isCounterClockwiseWinding(t)||t.reverse()}_isCounterClockwiseWinding(t){let e=0;for(let i=0;i<t.length;i++)e+=(t[(i+1)%t.length].x-t[i].x)*(t[(i+1)%t.length].y+t[i].y);return e<0}isConvex(){if(this.points.length<3)return!1;let t=this.points[this.points.length-2],e=this.points[this.points.length-1],i=Math.atan2(e.y-t.y,e.x-t.x),s=0,n=0,o=0;for(const[a,h]of this.points.entries()){if(t=e,s=i,e=h,i=Math.atan2(e.y-t.y,e.x-t.x),t.equals(e))return!1;let l=i-s;if(l<=-Math.PI?l+=Math.PI*2:l>Math.PI&&(l-=Math.PI*2),a===0){if(l===0)return!1;n=l>0?1:-1}else if(n*l<=0)return!1;o+=l}return Math.abs(Math.round(o/(Math.PI*2)))===1}tessellate(){const t=[];for(let e=1;e<this.points.length-2;e++)t.push([this.points[0],this.points[e+1],this.points[e+2]]);return t.push([this.points[0],this.points[1],this.points[2]]),new at(t.map(e=>ut.Polygon(e)))}triangulate(){if(this.points.length<3)throw Error("Invalid polygon");const t=[],e=[...this.points].reverse();let i=e.length;function s(u){return u===0?i-1:u-1}function n(u){return u===i-1?0:u+1}function o(u){const _=s(u),f=n(u),p=e[_],g=e[u],w=e[f],m=p.sub(g),b=w.sub(g);return!(m.cross(b)<0)}const a=e.map((u,_)=>o(_));function h(u,_,f,p){const g=f.sub(_),w=p.sub(f),m=_.sub(p),b=u.sub(_),T=u.sub(f),C=u.sub(p),S=g.cross(b),I=w.cross(T),y=m.cross(C);return!(S>0||I>0||y>0)}function l(){for(let u=0;u<i;u++)if(a[u]){const _=s(u),f=n(u),p=e[_],g=e[u],w=e[f];let m=!0;for(let b=0;b<i;b++){if(b===u||b===_||b===f)continue;const T=e[b];if(h(T,p,g,w)){m=!1;break}}if(m)return u}for(let u=0;u<i;u++)if(a[u])return u;return 0}function c(u){const _=s(u),f=n(u),p=e[_],g=e[u],w=e[f];t.push([p,g,w]),e.splice(u,1),a.splice(u,1),i--}for(;i>3;){const u=l();c(u);for(let _=0;_<i;_++)a[_]=o(_)}return t.push([e[0],e[1],e[2]]),new at(t.map(u=>ut.Polygon(u,v.Zero,!0)))}clone(){return new lt({offset:this.offset.clone(),points:this.points.map(t=>t.clone())})}get worldPos(){return this._transform.pos}get center(){return this.bounds.center}_calculateTransformation(){const t=this.points,e=t.length;this._transformedPoints.length=0;for(let i=0;i<e;i++)this._transformedPoints[i]=this._transform.apply(t[i].clone())}getTransformedPoints(){return this._transformedPointsDirty&&(this._calculateTransformation(),this._transformedPointsDirty=!1),this._transformedPoints}getSides(){if(this._sidesDirty){const t=[],e=this.getTransformedPoints(),i=e.length;for(let s=0;s<i;s++)t.push(new J(e[s],e[(s+1)%i]));this._sides=t,this._sidesDirty=!1}return this._sides}getLocalSides(){if(this._localSidesDirty){const t=[],e=this.points,i=e.length;for(let s=0;s<i;s++)t.push(new J(e[s],e[(s+1)%i]));this._localSides=t,this._localSidesDirty=!1}return this._localSides}findSide(t){const e=this.getSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=e[n],h=o.normal().dot(t);h>s&&(i=o,s=h)}return i}findLocalSide(t){const e=this.getLocalSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=e[n],h=o.normal().dot(t);h>s&&(i=o,s=h)}return i}get axes(){const t=[],e=this.getSides();for(let i=0;i<e.length;i++)t.push(e[i].normal());return t}update(t){t&&(t.cloneWithParent(this._transform),this._transformedPointsDirty=!0,this._sidesDirty=!0,(this.offset.x!==0||this.offset.y!==0)&&(this._transform.pos.x+=this.offset.x,this._transform.pos.y+=this.offset.y),this._transform.isMirrored()&&(this.points=this.points.map(e=>x(e.x*V(this._transform.scale.x),e.y*V(this._transform.scale.y))),this._transform.scale.x=Math.abs(this._transform.scale.x),this._transform.scale.y=Math.abs(this._transform.scale.y)))}contains(t){const e=this._transform.applyInverse(t),i=new fe(e,new v(1,0));let s=0;const n=this.getLocalSides();for(let o=0;o<n.length;o++){const a=n[o];i.intersect(a)>=0&&s++}return s%2!==0}getClosestLineBetween(t){if(t instanceof dt)return Wt.PolygonCircleClosestLine(this,t);if(t instanceof lt)return Wt.PolygonPolygonClosestLine(this,t);if(t instanceof Ct)return Wt.PolygonEdgeClosestLine(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Lt.CollideCirclePolygon(t,this);if(t instanceof lt)return Lt.CollidePolygonPolygon(this,t);if(t instanceof Ct)return Lt.CollidePolygonEdge(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}getFurthestPoint(t){const e=this.getTransformedPoints();let i=null,s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=t.dot(e[n]);o>s&&(s=o,i=e[n])}return i}getFurthestLocalPoint(t){const e=this.points;let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=t.dot(e[n]);o>s&&(s=o,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let o=0;o<e.length;o++){const a=e[o].distanceToPoint(t);a<i&&(i=a,s=o,n=a)}return s!==-1?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){return this.localBounds.transform(this._transform.matrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=D.fromPoints(this.points),this._localBoundsDirty=!1),this._localBounds}getInertia(t){if(this._cachedMass===t&&this._cachedInertia)return this._cachedInertia;let e=0,i=0;const s=this.points;for(let n=0;n<s.length;n++){const o=(n+1)%s.length,a=s[o].cross(s[n]);e+=a*(s[n].dot(s[n])+s[n].dot(s[o])+s[o].dot(s[o])),i+=a}return this._cachedMass=t,this._cachedInertia=t/6*(e/i)}rayCast(t,e=1/0){var i;const s=this.getSides(),n=s.length;let o=Number.MAX_VALUE,a,h=-1;for(let l=0;l<n;l++){const c=t.intersect(s[l]);c>=0&&c<o&&c<=e&&(o=c,a=s[l],h=l)}return h>=0?{collider:this,distance:o,body:(i=this.owner)==null?void 0:i.get(W),point:t.getPoint(o),normal:a.normal()}:null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let o=0;o<i;o++){const a=e[o].dot(t);s=Math.min(s,a),n=Math.max(n,a)}return new Ke(s,n)}debug(t,e,i){const s=this.getTransformedPoints();Cn.drawPolygon(s,{color:e})}}class ut{static Box(t,e,i=v.Half,s=v.Zero){return new lt({points:new D(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints().slice(),offset:s})}static Polygon(t,e=v.Zero,i=!1){return new lt({points:t,offset:e,suppressConvexWarning:i})}static Circle(t,e=v.Zero){return new dt({radius:t,offset:e})}static Edge(t,e){return new Ct({begin:t,end:e})}static Capsule(t,e,i=v.Zero){const s=R.getInstance();if(t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider"),e>=t){const o=new at([ut.Circle(t/2,x(0,-e/2+t/2).add(i)),ut.Box(t,e-t,v.Half,i),ut.Circle(t/2,x(0,e/2-t/2).add(i))]);return o.compositeStrategy="together",o}else{const o=new at([ut.Circle(e/2,x(-t/2+e/2,0).add(i)),ut.Box(t-e,e,v.Half,i),ut.Circle(e/2,x(t/2-e/2,0).add(i))]);return o.compositeStrategy="together",o}}}function Et(r,t){return r&&(r.__isProxy===void 0?new Proxy(r,{set:(e,i,s)=>(e[i]!==s&&(e[i]=s,typeof i=="string"&&i[0]!=="_"&&t(e)),!0),get:(e,i)=>i!=="__isProxy"?e[i]:!0}):r)}const Dr=(r=[],t,e)=>({get:(i,s)=>s==="__isProxy"?!0:typeof i[s]=="object"&&i[s]!=null?new Proxy(i[s],Dr([...r,s],t,e)):i[s],set:(i,s,n)=>(typeof s=="string"&&s[0]!=="_"&&t(e),i[s]=n,!0)});function Dh(r,t){return r&&(r.__isProxy===void 0?new Proxy(r,Dr([],t,r)):r)}const Fr=class La{constructor(t){this.id=La._ID++,this.transform=Q.identity(),this._transformStale=!0,this.showDebug=!1,this._flipHorizontal=!1,this._flipVertical=!1,this._rotation=0,this.opacity=1,this._scale=v.One,this._width=0,this._height=0;var e,i,s,n,o,a,h;t&&(this.origin=(e=t.origin)!=null?e:this.origin,this.flipHorizontal=(i=t.flipHorizontal)!=null?i:this.flipHorizontal,this.flipVertical=(s=t.flipVertical)!=null?s:this.flipVertical,this.rotation=(n=t.rotation)!=null?n:this.rotation,this.opacity=(o=t.opacity)!=null?o:this.opacity,this.scale=(a=t.scale)!=null?a:this.scale,this.tint=(h=t.tint)!=null?h:this.tint,t.width&&(this._width=t.width),t.height&&(this._height=t.height))}isStale(){return this._transformStale}get flipHorizontal(){return this._flipHorizontal}set flipHorizontal(t){this._flipHorizontal=t,this._transformStale=!0}get flipVertical(){return this._flipVertical}set flipVertical(t){this._flipVertical=t,this._transformStale=!0}get rotation(){return this._rotation}set rotation(t){this._rotation=t,this._transformStale=!0}get scale(){return this._scale}set scale(t){this._scale=Et(t,()=>{this._transformStale=!0}),this._transformStale=!0}get origin(){return this._origin}set origin(t){t&&(this._origin=Et(t,()=>{this._transformStale=!0})),this._transformStale=!0}cloneGraphicOptions(){return{width:this.width/this.scale.x,height:this.height/this.scale.y,origin:this.origin?this.origin.clone():void 0,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():void 0,tint:this.tint?this.tint.clone():void 0}}get width(){return Math.abs(this._width*this.scale.x)}get height(){return Math.abs(this._height*this.scale.y)}set width(t){this._width=t,this._transformStale=!0}set height(t){this._height=t,this._transformStale=!0}get localBounds(){return D.fromDimension(this.width,this.height,v.Zero)}draw(t,e,i){this._preDraw(t,e,i),this._drawImage(t,0,0),this._postDraw(t)}_preDraw(t,e,i){t.save(),t.translate(e,i),this._transformStale&&(this.transform.reset(),this.transform.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this._rotate(this.transform),this._flip(this.transform),this._transformStale=!1),t.multiply(this.transform),t.opacity=t.opacity*this.opacity,this.tint&&(t.tint=this.tint)}_rotate(t){var e;const i=this.scale.x>0?1:-1,s=this.scale.y>0?1:-1,n=(e=this.origin)!=null?e:x(this.width/2,this.height/2);t.translate(n.x,n.y),t.rotate(this.rotation),t.scale(i,s),t.translate(-n.x,-n.y)}_flip(t){this.flipHorizontal&&(t.translate(this.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,this.height/this.scale.y),t.scale(1,-1))}_postDraw(t){this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}};Fr._ID=0;let it=Fr;var Br=(r=>(r.Forward="forward",r.Backward="backward",r))(Br||{}),Lr=(r=>(r.End="end",r.Loop="loop",r.PingPong="pingpong",r.Freeze="freeze",r))(Lr||{});const Fh={Frame:"frame",Loop:"loop",End:"end"},kr=class nr extends it{constructor(t){var e,i,s;super(t),this.events=new X,this.frames=[],this.strategy="loop",this.frameDuration=100,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._pingPongDirection=1,this._done=!1,this._playing=!0,this._speed=1,this._wasResetDuringFrameCalc=!1,this._reversed=!1,this.frames=t.frames,this.speed=(e=t.speed)!=null?e:this.speed,this.strategy=(i=t.strategy)!=null?i:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:(s=t.frameDuration)!=null?s:this.frameDuration,this.data=t.data?new Map(Object.entries(t.data)):new Map,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){const t=this.constructor;return new t({frames:this.frames.map(e=>({...e})),frameDuration:this.frameDuration,speed:this.speed,reverse:this._reversed,strategy:this.strategy,...this.cloneGraphicOptions()})}get width(){const t=this.currentFrame;return t&&t.graphic?Math.abs(t.graphic.width*this.scale.x):0}get height(){const t=this.currentFrame;return t&&t.graphic?Math.abs(t.graphic.height*this.scale.y):0}static fromSpriteSheet(t,e,i,s="loop",n){const o=t.sprites.length-1,a=e.filter(h=>h<0||h>o);return a.length&&nr._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: ${a.join(",")} no frame will be shown`),new this({frames:t.sprites.filter((h,l)=>e.indexOf(l)>-1).map(h=>({graphic:h,duration:i})),strategy:s,data:n})}static fromSpriteSheetCoordinates(t){var e;const{spriteSheet:i,frameCoordinates:s,durationPerFrame:n,durationPerFrameMs:o,speed:a,strategy:h,reverse:l,data:c}=t,u=(e=n!=null?n:o)!=null?e:100,_=[];for(const f of s){const{x:p,y:g,duration:w,options:m}=f,b=i.getSprite(p,g,m);b?_.push({graphic:b,duration:w!=null?w:u}):nr._LOGGER.warn(`Skipping frame! SpriteSheet does not have coordinate (${p}, ${g}), please check your SpriteSheet to confirm that sprite exists`)}return new this({frames:_,strategy:h,speed:a,reverse:l,data:c})}get speed(){return this._speed}set speed(t){this._speed=F(Math.abs(t),0,1/0)}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get currentFrameTimeLeft(){return this._timeLeftInFrame}get isPlaying(){return this._playing}get isReversed(){return this._reversed}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!!(this._reversed&&this._pingPongDirection===1)?"backward":"forward"}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._wasResetDuringFrameCalc=!0,this._done=!1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=this.frameDuration;const t=this.frames[this._currentFrame];t&&(this._timeLeftInFrame=(t==null?void 0:t.duration)||this.frameDuration)}get canFinish(){switch(this.strategy){case"end":case"freeze":return!0;default:return!1}}get done(){return this._done}goToFrame(t,e){this._currentFrame=t,this._timeLeftInFrame=e!=null?e:this.frameDuration;const i=this.frames[this._currentFrame];i&&!this._done&&(this._timeLeftInFrame=e!=null?e:(i==null?void 0:i.duration)||this.frameDuration,this.events.emit("frame",{...i,frameIndex:this.currentFrameIndex}))}_nextFrame(){this._wasResetDuringFrameCalc=!1;const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case"loop":{e=(t+1)%this.frames.length,e===0&&this.events.emit("loop",this);break}case"end":{e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break}case"freeze":{e=F(t+1,0,this.frames.length-1),t+1>=this.frames.length&&(this._done=!0,this.events.emit("end",this));break}case"pingpong":{t+this._pingPongDirection>=this.frames.length&&(this._pingPongDirection=-1,this.events.emit("loop",this)),t+this._pingPongDirection<0&&(this._pingPongDirection=1,this.events.emit("loop",this)),e=t+this._pingPongDirection%this.frames.length;break}}return this._wasResetDuringFrameCalc?(this._wasResetDuringFrameCalc=!1,this._currentFrame):e}tick(t,e=0){this._idempotencyToken!==e&&(this._idempotencyToken=e,this._playing&&(this._firstTick&&(this._firstTick=!1,this.events.emit("frame",{...this.currentFrame,frameIndex:this.currentFrameIndex})),this._timeLeftInFrame-=t*this._speed,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame())))}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic&&this.currentFrame.graphic.draw(t,e,i)}};kr._LOGGER=R.getInstance();let zi=kr;class Ne extends it{constructor(t){var e;super(t),this._logger=R.getInstance(),this.useAnchor=!0,this.members=[],this.members=t.members,this.useAnchor=(e=t.useAnchor)!=null?e:this.useAnchor,this._updateDimensions()}clone(){return new Ne({members:[...this.members],...this.cloneGraphicOptions()})}_updateDimensions(){const t=this.localBounds;return this.width=t.width,this.height=t.height,t}get localBounds(){const t=new D;for(const e of this.members)if(e instanceof it)e.localBounds.combine(t,t);else{const{graphic:i,offset:s,useBounds:n}=e;i?(n===void 0?!0:n)&&i.localBounds.translate(s).combine(t,t):this._logger.warnOnce(`Graphics group member has an null or undefined graphic, member definition: ${JSON.stringify(e)}.`)}return t}_isAnimationOrGroup(t){return t instanceof zi||t instanceof Ne}tick(t,e){for(const i of this.members){let s;i instanceof it?s=i:s=i.graphic,this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){let e;t instanceof it?e=t:e=t.graphic,this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,this.useAnchor?e:0,this.useAnchor?i:0)}_drawImage(t,e,i){const s=v.Zero;for(const n of this.members){let o;n instanceof it?o=n:(o=n.graphic,n.offset.clone(s)),o&&(t.save(),t.translate(e,i),o.draw(t,s.x,s.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore())}}}class We extends it{constructor(t){var e,i,s,n,o,a,h,l,c,u;super(yr({...t},["width","height"])),this.lineCap="butt",this.quality=1,this._dirty=!0,this._smoothing=!1,this._color=Et(P.Black,()=>this.flagDirty()),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.quality=(e=t.quality)!=null?e:this.quality,this.color=(i=t.color)!=null?i:P.Black,this.strokeColor=t==null?void 0:t.strokeColor,this.smoothing=(s=t.smoothing)!=null?s:this.smoothing,this.lineWidth=(n=t.lineWidth)!=null?n:this.lineWidth,this.lineDash=(o=t.lineDash)!=null?o:this.lineDash,this.lineCap=(a=t.lineCap)!=null?a:this.lineCap,this.padding=(h=t.padding)!=null?h:this.padding,this.filtering=(l=t.filtering)!=null?l:this.filtering),this._bitmap=document.createElement("canvas");const _=(c=t==null?void 0:t.width)!=null?c:this._bitmap.width,f=(u=t==null?void 0:t.height)!=null?u:this._bitmap.height;this.width=_,this.height=f;const p=this._bitmap.getContext("2d");if(p)this._ctx=p;else throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic")}cloneRasterOptions(){return{color:this.color?this.color.clone():void 0,strokeColor:this.strokeColor?this.strokeColor.clone():void 0,smoothing:this.smoothing,lineWidth:this.lineWidth,lineDash:this.lineDash,lineCap:this.lineCap,quality:this.quality,padding:this.padding}}get dirty(){return this._dirty}flagDirty(){this._dirty=!0}get width(){return Math.abs(this._getTotalWidth()*this.scale.x)}set width(t){t/=Math.abs(this.scale.x),this._bitmap.width=t,this._originalWidth=t,this.flagDirty()}get height(){return Math.abs(this._getTotalHeight()*this.scale.y)}set height(t){t/=Math.abs(this.scale.y),this._bitmap.height=t,this._originalHeight=t,this.flagDirty()}_getTotalWidth(){var t;return(((t=this._originalWidth)!=null?t:this._bitmap.width)+this.padding*2)*1}_getTotalHeight(){var t;return(((t=this._originalHeight)!=null?t:this._bitmap.height)+this.padding*2)*1}get localBounds(){return D.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,v.Zero)}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this.flagDirty()}get color(){return this._color}set color(t){this.flagDirty(),this._color=Et(t,()=>this.flagDirty())}get strokeColor(){return this._strokeColor}set strokeColor(t){this.flagDirty(),t&&(this._strokeColor=Et(t,()=>this.flagDirty()))}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t,this.flagDirty()}get lineDash(){return this._lineDash}set lineDash(t){this._lineDash=t,this.flagDirty()}get padding(){return this._padding}set padding(t){this._padding=t,this.flagDirty()}rasterize(){this._dirty=!1,this._ctx.clearRect(0,0,this._getTotalWidth(),this._getTotalHeight()),this._ctx.save(),this._applyRasterProperties(this._ctx),this.execute(this._ctx),this._ctx.restore()}_applyRasterProperties(t){var e,i,s,n;this._bitmap.width=this._getTotalWidth()*this.quality,this._bitmap.height=this._getTotalHeight()*this.quality,this._bitmap.setAttribute("filtering",this.filtering),this._bitmap.setAttribute("forceUpload","true"),t.scale(this.quality,this.quality),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash((e=this.lineDash)!=null?e:t.getLineDash()),t.lineCap=this.lineCap,t.strokeStyle=(s=(i=this.strokeColor)==null?void 0:i.toString())!=null?s:"",t.fillStyle=(n=this.color)==null?void 0:n.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.scale(1/this.quality,1/this.quality),t.drawImage(this._bitmap,e,i)}}var rn=(r=>(r.Em="em",r.Rem="rem",r.Px="px",r.Pt="pt",r.Percent="%",r))(rn||{}),on=(r=>(r.Left="left",r.Right="right",r.Center="center",r.Start="start",r.End="end",r))(on||{}),an=(r=>(r.Top="top",r.Hanging="hanging",r.Middle="middle",r.Alphabetic="alphabetic",r.Ideographic="ideographic",r.Bottom="bottom",r))(an||{}),hn=(r=>(r.Normal="normal",r.Italic="italic",r.Oblique="oblique",r))(hn||{}),ln=(r=>(r.LeftToRight="ltr",r.RightToLeft="rtl",r))(ln||{}),mt=(r=>(r.Pixel="Pixel",r.Blended="Blended",r))(mt||{});function Ge(r){switch(r){case"Pixel":return"Pixel";case"Blended":return"Blended";default:return}}function cn(r,t=P.Red,e,i,s,n,o=1,a="butt"){r.save(),r.beginPath(),r.lineWidth=o,r.lineCap=a,r.strokeStyle=t.toString(),r.moveTo(e,i),r.lineTo(s,n),r.closePath(),r.stroke(),r.restore()}function Bh(r,t=P.Red,e){r.beginPath(),r.strokeStyle=t.toString(),r.arc(e.x,e.y,5,0,Math.PI*2),r.closePath(),r.stroke()}function Lh(r,t,e,i,s=1){const n=t?t.toString():"blue",o=i.scale(s);r.beginPath(),r.strokeStyle=n,r.moveTo(e.x,e.y),r.lineTo(e.x+o.x,e.y+o.y),r.closePath(),r.stroke()}function dn(r,t,e,i,s,n=5,o=P.White,a=null){let h;if(typeof n=="number")h={tl:n,tr:n,br:n,bl:n};else{const l={tl:0,tr:0,br:0,bl:0};for(const c in l)if(l.hasOwnProperty(c)){const u=c;h[u]=n[u]||l[u]}}r.beginPath(),r.moveTo(t+h.tl,e),r.lineTo(t+i-h.tr,e),r.quadraticCurveTo(t+i,e,t+i,e+h.tr),r.lineTo(t+i,e+s-h.br),r.quadraticCurveTo(t+i,e+s,t+i-h.br,e+s),r.lineTo(t+h.bl,e+s),r.quadraticCurveTo(t,e+s,t,e+s-h.bl),r.lineTo(t,e+h.tl),r.quadraticCurveTo(t,e,t+h.tl,e),r.closePath(),a&&(r.fillStyle=a.toString(),r.fill()),o&&(r.strokeStyle=o.toString(),r.stroke())}function kh(r,t,e,i,s=P.White,n=null){r.beginPath(),r.arc(t,e,i,0,Math.PI*2),r.closePath(),n&&(r.fillStyle=n.toString(),r.fill()),s&&(r.strokeStyle=s.toString(),r.stroke())}const Uh=Object.freeze(Object.defineProperty({__proto__:null,circle:kh,line:cn,point:Bh,roundRect:dn,vector:Lh},Symbol.toStringTag,{value:"Module"}));class Ve{constructor(t,e,i=1){this.builder=t,this.cleaner=e,this._pool=[],this._size=0,this.grow(i)}grow(t){if(t>0){this._size+=t;for(let e=0;e<t;e++)this._pool.push(this.builder())}}rent(t=!1){return this._pool.length===0&&this.grow(this._size),t?this.cleaner(this._pool.pop()):this._pool.pop()}return(t){this._pool.push(t)}}class zh{constructor(){this._pool=new Ve(()=>Q.identity(),t=>t.reset(),100),this._transforms=[],this._currentTransform=this._pool.rent(!0)}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone(this._pool.rent())}restore(){this._pool.return(this._currentTransform),this._currentTransform=this._transforms.pop()}translate(t,e){return this._currentTransform.translate(t,e)}rotate(t){return this._currentTransform.rotate(t)}scale(t,e){return this._currentTransform.scale(t,e)}reset(){this._currentTransform.reset()}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class Oh{constructor(){this.opacity=1,this.z=0,this.tint=P.White,this.material=null}}class Ur{constructor(){this._pool=new Ve(()=>new Oh,t=>(t.opacity=1,t.z=0,t.tint=P.White,t.material=null,t),100),this.current=this._pool.rent(!0),this._states=[]}_cloneState(t){var e;return t.opacity=this.current.opacity,t.z=this.current.z,t.tint=(e=this.current.tint)==null?void 0:e.clone(),t.material=this.current.material,t}save(){this._states.push(this.current),this.current=this._cloneState(this._pool.rent())}restore(){this._pool.return(this.current),this.current=this._states.pop()}}const Hh={Complete:"complete",Load:"load",LoadStart:"loadstart",Progress:"progress",Error:"error"};class ai{constructor(t,e,i=!1){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=R.getInstance(),this.events=new X}isLoaded(){return this.data!==null}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise((t,e)=>{if(this.data!==null){this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),t(this.data);return}const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",s=>this.events.emit("loadstart",s)),i.addEventListener("progress",s=>this.events.emit("progress",s)),i.addEventListener("error",s=>this.events.emit("error",s)),i.addEventListener("load",s=>this.events.emit("load",s)),i.addEventListener("load",()=>{if(i.status!==0&&i.status!==200){this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),e(new Error(i.statusText));return}if(i.response instanceof Blob&&i.response.type==="text/html"){const s=`Expected blob (usually image) data from the server when loading ${this.path}, but got HTML content instead!
|
|
26
|
+
Check your bundler settings to make sure this is not the case! Excalibur has ESM & UMD bundles be sure one 1 is loaded.`)}get entities(){return this.entityManager.entities}clearEntities(){this.entityManager.clear()}clearSystems(){this.systemManager.clear()}}d.Side=(r=>(r.None="None",r.Top="Top",r.Bottom="Bottom",r.Left="Left",r.Right="Right",r))(d.Side||{}),(r=>{function t(i){return i==="Top"?"Bottom":i==="Bottom"?"Top":i==="Left"?"Right":i==="Right"?"Left":"None"}r.getOpposite=t;function e(i){return Math.abs(i.x)>=Math.abs(i.y)?i.x<=0?"Left":"Right":i.y<=0?"Top":"Bottom"}r.fromDirection=e})(d.Side||(d.Side={}));const Ir=class vt{constructor(t=0,e=0,i=0,s=0){this._points=[],typeof t=="object"?(this.left=t.left,this.top=t.top,this.right=t.right,this.bottom=t.bottom):typeof t=="number"&&(this.left=t,this.top=e,this.right=i,this.bottom=s)}clone(t){const e=t||new vt(0,0,0,0);return e.left=this.left,e.right=this.right,e.top=this.top,e.bottom=this.bottom,e}reset(){this.left=0,this.top=0,this.bottom=0,this.right=0}static getSideFromIntersection(t){return t&&t?Math.abs(t.x)>Math.abs(t.y)?t.x<0?d.Side.Right:d.Side.Left:t.y<0?d.Side.Bottom:d.Side.Top:d.Side.None}static fromPoints(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;for(let o=0;o<t.length;o++)t[o].x<e&&(e=t[o].x),t[o].x>s&&(s=t[o].x),t[o].y<i&&(i=t[o].y),t[o].y>n&&(n=t[o].y);return new vt(e,i,s,n)}static fromDimension(t,e,i=w.Half,s=w.Zero){return new vt(-t*i.x+s.x,-e*i.y+s.y,t-t*i.x+s.x,e-e*i.y+s.y)}get width(){return this.right-this.left}get height(){return this.bottom-this.top}hasZeroDimensions(){return this.width===0||this.height===0}get center(){return new w((this.left+this.right)/2,(this.top+this.bottom)/2)}get topLeft(){return new w(this.left,this.top)}get bottomRight(){return new w(this.right,this.bottom)}get topRight(){return new w(this.right,this.top)}get bottomLeft(){return new w(this.left,this.bottom)}translate(t){return new vt(this.left+t.x,this.top+t.y,this.right+t.x,this.bottom+t.y)}rotate(t,e=w.Zero){const i=this.getPoints().map(s=>s.rotate(t,e));return vt.fromPoints(i)}scale(t,e=w.Zero){const i=this.translate(e);return new vt(i.left*t.x,i.top*t.y,i.right*t.x,i.bottom*t.y)}transform(t){const e=t.data[0]*this.left,i=t.data[1]*this.left,s=t.data[0]*this.right,n=t.data[1]*this.right,o=t.data[2]*this.top,a=t.data[3]*this.top,h=t.data[2]*this.bottom,l=t.data[3]*this.bottom,c=t.getPosition(),u=Math.min(e,s)+Math.min(o,h)+c.x,_=Math.min(i,n)+Math.min(a,l)+c.y,f=Math.max(e,s)+Math.max(o,h)+c.x,m=Math.max(i,n)+Math.max(a,l)+c.y;return new vt({left:u,top:_,right:f,bottom:m})}getPerimeter(){const t=this.width,e=this.height;return 2*(t+e)}getPoints(){return(this._left!==this.left||this._right!==this.right||this._top!==this.top||this._bottom!==this.bottom)&&(this._points.length=0,this._points.push(new w(this.left,this.top)),this._points.push(new w(this.right,this.top)),this._points.push(new w(this.right,this.bottom)),this._points.push(new w(this.left,this.bottom)),this._left=this.left,this._right=this.right,this._top=this.top,this._bottom=this.bottom),this._points}rayCast(t,e=1/0){let i,s;const n=t.dir.x===0?Number.MAX_VALUE:1/t.dir.x,o=t.dir.y===0?Number.MAX_VALUE:1/t.dir.y,a=(this.left-t.pos.x)*n,h=(this.right-t.pos.x)*n;s=Math.min(a,h),i=Math.max(a,h);const l=(this.top-t.pos.y)*o,c=(this.bottom-t.pos.y)*o;return s=Math.max(s,Math.min(l,c)),i=Math.min(i,Math.max(l,c)),i>=0&&i>=s&&s<e}rayCastTime(t,e=1/0){let i,s;const n=t.dir.x===0?Number.MAX_VALUE:1/t.dir.x,o=t.dir.y===0?Number.MAX_VALUE:1/t.dir.y,a=(this.left-t.pos.x)*n,h=(this.right-t.pos.x)*n;s=Math.min(a,h),i=Math.max(a,h);const l=(this.top-t.pos.y)*o,c=(this.bottom-t.pos.y)*o;return s=Math.max(s,Math.min(l,c)),i=Math.min(i,Math.max(l,c)),i>=0&&i>=s&&s<e?s:-1}contains(t){return t instanceof w?this.left<=t.x&&this.top<=t.y&&t.y<=this.bottom&&t.x<=this.right:t instanceof vt?this.left<=t.left&&this.top<=t.top&&t.bottom<=this.bottom&&t.right<=this.right:!1}combine(t,e){const i=e||new vt(0,0,0,0),s=Math.min(this.left,t.left),n=Math.min(this.top,t.top),o=Math.max(this.right,t.right),a=Math.max(this.bottom,t.bottom);return i.left=s,i.top=n,i.right=o,i.bottom=a,i}get dimensions(){return new w(this.width,this.height)}overlaps(t,e){const i=e||0;if(t.hasZeroDimensions())return this.contains(t);if(this.hasZeroDimensions())return t.contains(this);const s=this.combine(t);return s.width+i<t.width+this.width&&s.height+i<t.height+this.height}intersect(t){if(this.bottom<=t.top||t.bottom<=this.top||this.right<=t.left||t.right<=this.left)return null;const e=this.bottom-t.top;vt._SCRATCH_INTERSECT[0]=e;const i=t.bottom-this.top;vt._SCRATCH_INTERSECT[1]=i;const s=this.right-t.left;vt._SCRATCH_INTERSECT[2]=s;const n=t.right-this.left;vt._SCRATCH_INTERSECT[3]=n;const o=wr(vt._SCRATCH_INTERSECT);switch(o){case 0:return new w(0,-e);case 1:return new w(0,i);case 2:return new w(-s,0);case 3:return new w(n,0);default:const a=o;throw new Error(`Unreachable index: [${a}] on bounding box intersection!`)}}intersectWithSide(t){const e=this.intersect(t);return vt.getSideFromIntersection(e)}draw(t,e={color:T.Yellow}){t.debug.drawRect(this.left,this.top,this.width,this.height,e)}debug(t,e={color:T.Yellow}){t.debug.drawRect(this.left,this.top,this.width,this.height,e)}};Ir._SCRATCH_INTERSECT=[0,0,0,0];let F=Ir;class pt{constructor(t,e){this.colliderA=t,this.colliderB=e,this.id=null,this.id=pt.calculatePairHash(t.id,e.id)}static canCollide(t,e){var i,s;if(t.id===e.id||t.owner&&e.owner&&t.owner.id===e.owner.id||t.localBounds.hasZeroDimensions()||e.localBounds.hasZeroDimensions())return!1;const n=(i=t==null?void 0:t.owner)==null?void 0:i.get(N),o=(s=e==null?void 0:e.owner)==null?void 0:s.get(N);return!(!n||!o||!n.group.canCollide(o.group)||n.collisionType===M.Fixed&&o.collisionType===M.Fixed||o.collisionType===M.PreventCollision||n.collisionType===M.PreventCollision||!n.isActive||!o.isActive)}get canCollide(){const t=this.colliderA,e=this.colliderB;return pt.canCollide(t,e)}collide(){return this.colliderA.collide(this.colliderB)}hasCollider(t){return t===this.colliderA||t===this.colliderB}static calculatePairHash(t,e){return t.value<e.value?`#${t.value}+${e.value}`:`#${e.value}+${t.value}`}}class tn{constructor(t){this.parent=t,this.parent=t||null,this.data=null,this.bounds=new F,this.left=null,this.right=null,this.height=0}isLeaf(){return!this.left&&!this.right}}class en{constructor(t,e=new F(-Number.MAX_VALUE,-Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)){this._config=t,this.worldBounds=e,this.root=null,this.nodes={}}_insert(t){if(this.root===null){this.root=t,this.root.parent=null;return}const e=t.bounds;let i=this.root;for(;!i.isLeaf();){const a=i.left,h=i.right,l=i.bounds.getPerimeter(),u=i.bounds.combine(e).getPerimeter(),_=2*u,f=2*(u-l);let m=0;const p=e.combine(a.bounds);let x,v;a.isLeaf()?m=p.getPerimeter()+f:(v=a.bounds.getPerimeter(),x=p.getPerimeter(),m=x-v+f);let g=0;const y=e.combine(h.bounds);if(h.isLeaf()?g=y.getPerimeter()+f:(v=h.bounds.getPerimeter(),x=y.getPerimeter(),g=x-v+f),_<m&&_<g)break;m<g?i=a:i=h}const s=i.parent,n=new tn(s);n.bounds=e.combine(i.bounds),n.height=i.height+1,s!==null?(s.left===i?s.left=n:s.right=n,n.left=i,n.right=t,i.parent=n,t.parent=n):(n.left=i,n.right=t,i.parent=n,t.parent=n,this.root=n);let o=t.parent;for(;o;){if(o=this._balance(o),!o.left)throw new Error("Parent of current leaf cannot have a null left child"+o);if(!o.right)throw new Error("Parent of current leaf cannot have a null right child"+o);o.height=1+Math.max(o.left.height,o.right.height),o.bounds=o.left.bounds.combine(o.right.bounds),o=o.parent}}_remove(t){if(t===this.root){this.root=null;return}const e=t.parent,i=e.parent;let s;if(e.left===t?s=e.right:s=e.left,i){i.left===e?i.left=s:i.right=s,s.parent=i;let n=i;for(;n;)n=this._balance(n),n.bounds=n.left.bounds.combine(n.right.bounds),n.height=1+Math.max(n.left.height,n.right.height),n=n.parent}else this.root=s,s.parent=null}trackCollider(t){const e=new tn;e.data=t,e.bounds=t.bounds,e.bounds.left-=2,e.bounds.top-=2,e.bounds.right+=2,e.bounds.bottom+=2,this.nodes[t.id.value]=e,this._insert(e)}updateCollider(t){var e;const i=this.nodes[t.id.value];if(!i)return!1;const s=t.bounds;if(!this.worldBounds.contains(s))return R.getInstance().warn("Collider with id "+t.id.value+" is outside the world bounds and will no longer be tracked for physics"),this.untrackCollider(t),!1;if(i.bounds.contains(s))return!1;if(this._remove(i),s.left-=this._config.boundsPadding,s.top-=this._config.boundsPadding,s.right+=this._config.boundsPadding,s.bottom+=this._config.boundsPadding,t.owner){const n=(e=t.owner)==null?void 0:e.get(N);if(n){const o=n.vel.x*32/1e3*this._config.velocityMultiplier,a=n.vel.y*32/1e3*this._config.velocityMultiplier;o<0?s.left+=o:s.right+=o,a<0?s.top+=a:s.bottom+=a}}return i.bounds=s,this._insert(i),!0}untrackCollider(t){const e=this.nodes[t.id.value];e&&(this._remove(e),this.nodes[t.id.value]=null,delete this.nodes[t.id.value])}_balance(t){if(t===null)throw new Error("Cannot balance at null node");if(t.isLeaf()||t.height<2)return t;const e=t.left,i=t.right,s=t,n=e,o=i,a=e.left,h=e.right,l=i.left,c=i.right,u=o.height-n.height;if(u>1)return o.left=s,o.parent=s.parent,s.parent=o,o.parent?o.parent.left===s?o.parent.left=o:o.parent.right=o:this.root=o,l.height>c.height?(o.right=l,s.right=c,c.parent=s,s.bounds=n.bounds.combine(c.bounds),o.bounds=s.bounds.combine(l.bounds),s.height=1+Math.max(n.height,c.height),o.height=1+Math.max(s.height,l.height)):(o.right=c,s.right=l,l.parent=s,s.bounds=n.bounds.combine(l.bounds),o.bounds=s.bounds.combine(c.bounds),s.height=1+Math.max(n.height,l.height),o.height=1+Math.max(s.height,c.height)),o;if(u<-1){if(n.left=s,n.parent=s.parent,s.parent=n,n.parent)if(n.parent.left===s)n.parent.left=n;else{if(n.parent.right!==s)throw"Error rotating Dynamic Tree";n.parent.right=n}else this.root=n;return a.height>h.height?(n.right=a,s.left=h,h.parent=s,s.bounds=o.bounds.combine(h.bounds),n.bounds=s.bounds.combine(a.bounds),s.height=1+Math.max(o.height,h.height),n.height=1+Math.max(s.height,a.height)):(n.right=h,s.left=a,a.parent=s,s.bounds=o.bounds.combine(a.bounds),n.bounds=s.bounds.combine(h.bounds),s.height=1+Math.max(o.height,a.height),n.height=1+Math.max(s.height,h.height)),n}return t}getHeight(){return this.root===null?0:this.root.height}query(t,e){const i=t.bounds,s=n=>{if(n&&n.bounds.overlaps(i))if(n.isLeaf()&&n.data!==t){if(e.call(t,n.data))return!0}else return s(n.left)||s(n.right);return!1};s(this.root)}rayCastQuery(t,e=1/0,i){const s=n=>{if(n&&n.bounds.rayCast(t,e))if(n.isLeaf()){if(i.call(t,n.data))return!0}else return s(n.left)||s(n.right);return!1};s(this.root)}getNodes(){const t=e=>e?[e].concat(t(e.left),t(e.right)):[];return t(this.root)}debug(t){const e=i=>{i&&(i.isLeaf()?i.bounds.debug(t,{color:T.Green}):i.bounds.debug(t,{color:T.White}),i.left&&e(i.left),i.right&&e(i.right))};e(this.root)}}class Li{constructor(t){this._config=t,this._pairs=new Set,this._collisionPairCache=[],this._colliders=[],this._dynamicCollisionTree=new en(t.dynamicTree)}getColliders(){return this._colliders}query(t){const e=[];return t instanceof F?this._dynamicCollisionTree.query({id:fe("collider",-1),owner:null,bounds:t},i=>(e.push(i),!1)):this._dynamicCollisionTree.query({id:fe("collider",-1),owner:null,bounds:new F(t.x,t.y,t.x,t.y)},i=>(e.push(i),!1)),e}rayCast(t,e){var i,s,n;const o=[],a=(i=e==null?void 0:e.maxDistance)!=null?i:1/0,h=e==null?void 0:e.collisionGroup,l=h?h.category:(s=e==null?void 0:e.collisionMask)!=null?s:me.All.category,c=(n=e==null?void 0:e.searchAllColliders)!=null?n:!1;return this._dynamicCollisionTree.rayCastQuery(t,a,u=>{const f=u.owner.get(N);if(e!=null&&e.ignoreCollisionGroupAll&&f.group===me.All)return!1;const m=(l&f.group.category)!==0;if(f!=null&&f.group&&!m)return!1;const p=u.rayCast(t,a);if(p){if(e!=null&&e.filter){if(e.filter(p)&&(o.push(p),!c))return!0}else if(o.push(p),!c)return!0}return!1}),o}track(t){if(!t){R.getInstance().warn("Cannot track null collider");return}if(t instanceof at){const e=t.getColliders();for(const i of e)i.owner=t.owner,this._colliders.push(i),this._dynamicCollisionTree.trackCollider(i)}else this._colliders.push(t),this._dynamicCollisionTree.trackCollider(t)}untrack(t){if(!t){R.getInstance().warn("Cannot untrack a null collider");return}if(t instanceof at){const e=t.getColliders();for(const i of e){const s=this._colliders.indexOf(i);s!==-1&&this._colliders.splice(s,1),this._dynamicCollisionTree.untrackCollider(i)}}else{const e=this._colliders.indexOf(t);e!==-1&&this._colliders.splice(e,1),this._dynamicCollisionTree.untrackCollider(t)}}_pairExists(t,e){const i=pt.calculatePairHash(t.id,e.id);return this._pairs.has(i)}broadphase(t,e,i){const s=e/1e3,n=t.filter(a=>{var h,l;const c=(h=a.owner)==null?void 0:h.get(N);return((l=a.owner)==null?void 0:l.isActive)&&c.collisionType!==M.PreventCollision});this._collisionPairCache=[],this._pairs.clear();let o;for(let a=0,h=n.length;a<h;a++)o=n[a],this._dynamicCollisionTree.query(o,l=>{if(!this._pairExists(o,l)&&pt.canCollide(o,l)){const c=new pt(o,l);this._pairs.add(c.id),this._collisionPairCache.push(c)}return!1});if(i&&(i.physics.pairs=this._collisionPairCache.length),this._config.continuous.checkForFastBodies)for(const a of n){const h=a.owner.get(N);if((h==null?void 0:h.collisionType)!==M.Active)continue;const l=h.vel.magnitude*s+h.acc.magnitude*.5*s*s,c=Math.min(a.bounds.height,a.bounds.width);if(this._config.continuous.disableMinimumSpeedForFastBody||l>c/2){i&&i.physics.fastBodies++;const u=h.globalPos.sub(h.oldPos),_=a.center,f=a.getFurthestPoint(h.vel),m=f.sub(u),p=new ge(m,h.vel);p.pos=p.pos.add(p.dir.scale(-2*this._config.continuous.surfaceEpsilon));let x,v=new w(1/0,1/0);if(this._dynamicCollisionTree.rayCastQuery(p,l+this._config.continuous.surfaceEpsilon*2,g=>{if(!this._pairExists(a,g)&&pt.canCollide(a,g)){const y=g.rayCast(p,l+this._config.continuous.surfaceEpsilon*10);if(y){const S=y.point.sub(m);S.magnitude<v.magnitude&&(v=S,x=g)}}return!1}),x&&w.isValid(v)){const g=new pt(a,x);this._pairs.has(g.id)||(this._pairs.add(g.id),this._collisionPairCache.push(g));const y=_.sub(f);h.globalPos=m.add(y).add(v).add(p.dir.scale(10*this._config.continuous.surfaceEpsilon)),a.update(h.transform.get()),i&&i.physics.fastBodyCollisions++}}}return this._collisionPairCache}narrowphase(t,e){let i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();if(i=i.concat(n),e&&n.length>0)for(const o of n)e.physics.contacts.set(o.id,o)}return e&&(e.physics.collisions+=i.length),i}update(t){let e=0;const i=t.length;for(let s=0;s<i;s++)this._dynamicCollisionTree.updateCollider(t[s])&&e++;return e}debug(t){this._dynamicCollisionTree.debug(t)}}const Rr=class Ba{constructor(){this.id=fe("collider",Ba._ID++),this.composite=null,this.events=new X,this.offset=w.Zero}touching(t){const e=this.collide(t);return!!(e&&e.length>0)}};Rr._ID=0;let ai=Rr;var Ui=(r=>(r.Arcade="arcade",r.Realistic="realistic",r))(Ui||{}),ae=(r=>(r.None="none",r.VerticalFirst="vertical-first",r.HorizontalFirst="horizontal-first",r))(ae||{});const sn={vertical:1,horizontal:2},nn={horizontal:1,vertical:2},rn={horizontal:0,vertical:0};var hi=(r=>(r.DynamicTree="dynamic-tree",r.SparseHashGrid="sparse-hash-grid",r))(hi||{});const te=()=>({enabled:!0,integration:{onScreenOnly:!1},gravity:b(0,0).clone(),solver:Ui.Arcade,substep:1,colliders:{compositeStrategy:"together"},continuous:{checkForFastBodies:!0,disableMinimumSpeedForFastBody:!1,surfaceEpsilon:.1},bodies:{canSleepByDefault:!1,sleepEpsilon:.07,wakeThreshold:.07*3,sleepBias:.9,defaultMass:10},spatialPartition:hi.SparseHashGrid,sparseHashGrid:{size:100},dynamicTree:{boundsPadding:5,velocityMultiplier:2},arcade:{contactSolveBias:ae.None},realistic:{contactSolveBias:ae.None,positionIterations:3,velocityIterations:8,slop:1,steeringFactor:.2,warmStart:!0}});class at extends ai{constructor(t){super(),this._collisionProcessor=new Li({...te()}),this._dynamicAABBTree=new en({boundsPadding:5,velocityMultiplier:2}),this._colliders=[];for(const e of t)this.addCollider(e)}set compositeStrategy(t){this._compositeStrategy=t}get compositeStrategy(){return this._compositeStrategy}clearColliders(){this._colliders=[]}addCollider(t){let e;t instanceof at?(e=t.getColliders(),e.forEach(i=>i.offset.addEqual(t.offset))):e=[t];for(const i of e)i.events.pipe(this.events),i.composite=this,this._colliders.push(i),this._collisionProcessor.track(i),this._dynamicAABBTree.trackCollider(i)}removeCollider(t){t.events.pipe(this.events),t.composite=null,He(t,this._colliders),this._collisionProcessor.untrack(t),this._dynamicAABBTree.untrackCollider(t)}getColliders(){return this._colliders}get worldPos(){var t,e;return((e=(t=this._transform)==null?void 0:t.pos)!=null?e:w.Zero).add(this.offset)}get center(){var t,e;return((e=(t=this._transform)==null?void 0:t.pos)!=null?e:w.Zero).add(this.offset)}get bounds(){var t,e;const i=this.getColliders();return i.reduce((n,o)=>n.combine(o.bounds),(e=(t=i[0])==null?void 0:t.bounds)!=null?e:new F().translate(this.worldPos)).translate(this.offset)}get localBounds(){var t,e;const i=this.getColliders();return i.reduce((n,o)=>n.combine(o.localBounds),(e=(t=i[0])==null?void 0:t.localBounds)!=null?e:new F)}get axes(){const t=this.getColliders();let e=[];for(const i of t)e=e.concat(i.axes);return e}getFurthestPoint(t){const e=this.getColliders(),i=[];for(const o of e)i.push(o.getFurthestPoint(t));let s=i[0],n=-Number.MAX_VALUE;for(const o of i){const a=o.dot(t);a>n&&(s=o,n=a)}return s}getInertia(t){const e=this.getColliders();let i=0;for(const s of e)i+=s.getInertia(t);return i}collide(t){let e=[t];t instanceof at&&(e=t.getColliders());const i=[];for(const n of e)this._dynamicAABBTree.query(n,o=>(i.push(new pt(n,o)),!1));let s=[];for(const n of i)s=s.concat(n.collide());return s}getClosestLineBetween(t){const e=this.getColliders(),i=[];if(t instanceof at){const s=t.getColliders();for(const n of e)for(const o of s){const a=n.getClosestLineBetween(o);a&&i.push(a)}}else for(const s of e){const n=t.getClosestLineBetween(s);n&&i.push(n)}if(i.length){let s=i[0].getLength(),n=i[0];for(const o of i){const a=o.getLength();a<s&&(s=a,n=o)}return n}return null}contains(t){const e=this.getColliders();for(const i of e)if(i.contains(t))return!0;return!1}rayCast(t,e){const i=this.getColliders(),s=[];for(const n of i){const o=n.rayCast(t,e);o&&s.push(o)}if(s.length){let n=s[0],o=n.point.dot(t.dir);for(const a of s){const h=t.dir.dot(a.point);h<o&&(n=a,o=h)}return n}return null}project(t){const e=this.getColliders(),i=[];for(const s of e){const n=s.project(t);n&&i.push(n)}if(i.length){const s=new ei(i[0].min,i[0].max);for(const n of i)s.min=Math.min(n.min,s.min),s.max=Math.max(n.max,s.max);return s}return null}update(t){if(t){const e=this.getColliders();for(const i of e)i.owner=this.owner,i.update(t)}}debug(t,e,i){const s=this.getColliders();t.save(),t.translate(this.offset.x,this.offset.y);for(const n of s)n.debug(t,e,i);t.restore()}clone(){const t=new at(this._colliders.map(e=>e.clone()));return t.offset=this.offset.clone(),t}}function on(r,t){const i=r.dir(),s=t.dir(),n=i.dot(i),o=s.dot(s);if(n<1e-9&&o<1e-9)return new Q(r.begin,t.begin);if(n<1e-9){const x=B(s.dot(r.begin.sub(t.begin))/o,0,1),v=t.begin.add(s.scale(x));return new Q(r.begin,v)}if(o<1e-9){const x=B(i.dot(t.begin.sub(r.begin))/n,0,1),v=r.begin.add(i.scale(x));return new Q(v,t.begin)}const a=r.begin.sub(t.begin),h=n,l=o,c=s.dot(a),u=h*l-Math.pow(i.dot(s),2);let _=0,f=0;Math.abs(u)>1e-9?_=B((i.dot(s)*c-l*i.dot(a))/u,0,1):_=B(i.dot(a)/h,0,1),Math.abs(l)>1e-9?f=B((i.dot(s)*_+c)/l,0,1):f=0;const m=r.begin.add(i.scale(_)),p=t.begin.add(s.scale(f));return new Q(m,p)}const Vt={PolygonPolygonClosestLine(r,t){const e=r.getSides(),i=t.getSides();let s=Number.MAX_VALUE,n=null;for(let o=0;o<e.length;o++)for(let a=0;a<i.length;a++){const h=on(e[o],i[a]),l=h.getLength();l<s&&(s=l,n=h)}return n},PolygonEdgeClosestLine(r,t){const i=t.worldPos.sub(r.worldPos),s=new ge(r.worldPos,i),n=r.rayCast(s).point.add(s.dir.scale(.1)),o=r.getClosestFace(n),a=t.asLine();return on(o.face,a)},PolygonCircleClosestLine(r,t){const e=t.worldPos,i=e.sub(r.worldPos),s=new ge(r.worldPos,i.normalize()),n=r.rayCast(s).point.add(s.dir.scale(.1)),o=r.getClosestFace(n),a=o.face.begin,h=o.face.getEdge();let l=(h.x*(e.x-a.x)+h.y*(e.y-a.y))/(h.x*h.x+h.y*h.y);l>1?l=1:l<0&&(l=0);const c=Math.sqrt(Math.pow(a.x+h.x*l-e.x,2)+Math.pow(a.y+h.y*l-e.y,2))-t.radius,u=(a.x+h.x*l-e.x)*t.radius/(t.radius+c),_=(a.y+h.y*l-e.y)*t.radius/(t.radius+c);return new Q(h.scale(l).add(a),new w(e.x+u,e.y+_))},CircleCircleClosestLine(r,t){const i=t.worldPos.sub(r.worldPos),n=r.worldPos.sub(t.worldPos),o=new ge(r.worldPos,i),a=new ge(t.worldPos,n),h=r.rayCast(o),l=t.rayCast(a);return new Q(h.point,l.point)},CircleEdgeClosestLine(r,t){const e=r.worldPos,i=t.asLine(),s=i.begin,n=i.getEdge(),o=s,a=n;let h=(a.x*(e.x-o.x)+a.y*(e.y-o.y))/(a.x*a.x+a.y*a.y);h>1?h=1:h<0&&(h=0);const l=Math.sqrt(Math.pow(o.x+a.x*h-e.x,2)+Math.pow(o.y+a.y*h-e.y,2))-r.radius,c=(o.x+a.x*h-e.x)*r.radius/(r.radius+l),u=(o.y+a.y*h-e.y)*r.radius/(r.radius+l);return new Q(a.scale(h).add(o),new w(e.x+c,e.y+u))},EdgeEdgeClosestLine(r,t){const e=r.asLine(),i=t.asLine();return on(e,i)}};class dt extends ai{constructor(t){super(),this.offset=w.Zero,this._globalMatrix=Z.identity(),this._localBoundsDirty=!0,this.offset=t.offset||w.Zero,this.radius=t.radius||0,this._globalMatrix.translate(this.offset.x,this.offset.y)}get worldPos(){return this._globalMatrix.getPosition()}get radius(){var t;if(this._radius)return this._radius;const e=this._transform,i=(t=e==null?void 0:e.globalScale)!=null?t:w.One;return this._radius=this._naturalRadius*Math.min(i.x,i.y)}set radius(t){var e;const i=this._transform,s=(e=i==null?void 0:i.globalScale)!=null?e:w.One;this._naturalRadius=t/Math.min(s.x,s.y),this._localBoundsDirty=!0,this._radius=t}clone(){return new dt({offset:this.offset.clone(),radius:this.radius})}get center(){return this._globalMatrix.getPosition()}contains(t){var e,i;return((i=(e=this._transform)==null?void 0:e.pos)!=null?i:this.offset).distance(t)<=this.radius}rayCast(t,e=1/0){var i,s;const n=this.center,o=t.dir,a=t.pos,h=n.sub(a),l=o.scale(h.dot(o)),u=h.sub(l).magnitude;if(u>this.radius)return null;{let _=0;if(ar(u,this.radius,1e-4)){if(_=-o.dot(a.sub(n)),_>0&&_<e){const f=t.getPoint(_);return{point:f,normal:f.sub(n).normalize(),collider:this,body:(i=this.owner)==null?void 0:i.get(N),distance:_}}return null}else{const f=Math.sqrt(Math.pow(o.dot(a.sub(n)),2)-Math.pow(a.sub(n).distance(),2)+Math.pow(this.radius,2)),m=-o.dot(a.sub(n))+f,p=-o.dot(a.sub(n))-f,x=[];m>=0&&x.push(m),p>=0&&x.push(p);const v=Math.min(...x);if(v<=e){const g=t.getPoint(v);return{point:g,normal:g.sub(n).normalize(),collider:this,body:(s=this.owner)==null?void 0:s.get(N),distance:v}}return null}}}getClosestLineBetween(t){if(t instanceof dt)return Vt.CircleCircleClosestLine(this,t);if(t instanceof lt)return Vt.PolygonCircleClosestLine(t,this).flip();if(t instanceof St)return Vt.CircleEdgeClosestLine(this,t).flip();throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Ut.CollideCircleCircle(this,t);if(t instanceof lt)return Ut.CollideCirclePolygon(this,t);if(t instanceof St)return Ut.CollideCircleEdge(this,t);throw new Error(`Circle could not collide with unknown CollisionShape ${typeof t}`)}getFurthestPoint(t){return this.center.add(t.normalize().scale(this.radius))}getFurthestLocalPoint(t){return t.normalize().scale(this.radius)}get bounds(){return this.localBounds.transform(this._globalMatrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=new F(-this._naturalRadius,-this._naturalRadius,+this._naturalRadius,+this._naturalRadius),this._localBoundsDirty=!1),this._localBounds}get axes(){return[]}getInertia(t){return t*this.radius*this.radius/2}update(t){var e;this._transform=t,((e=t.matrix)!=null?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y),this._radius=void 0}project(t){const e=[],s=this.center.dot(t);return e.push(s),e.push(s+this.radius),e.push(s-this.radius),new ei(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e,i){var s,n,o,a;const{lineWidth:h}={lineWidth:1,...i},l=this._transform,c=(s=l==null?void 0:l.globalScale)!=null?s:w.One,u=(n=l==null?void 0:l.globalRotation)!=null?n:0,_=(o=l==null?void 0:l.globalPos)!=null?o:w.Zero;t.save(),t.translate(_.x,_.y),t.rotate(u),t.scale(c.x,c.y),t.debug.drawCircle((a=this.offset)!=null?a:w.Zero,this._naturalRadius,T.Transparent,e,h),t.restore()}}class xe{constructor(t,e,i,s,n,o,a,h){this._canceled=!1,this.bodyA=null,this.bodyB=null;var l,c,u,_,f,m;if(this.colliderA=t,this.colliderB=e,this.mtv=i,this.normal=s,this.tangent=n,this.points=o,this.localPoints=a,this.info=h,this.id=pt.calculatePairHash(t.id,e.id),t.composite||e.composite){const p=((l=t.composite)==null?void 0:l.compositeStrategy)==="separate"?t.id:(u=(c=t.composite)==null?void 0:c.id)!=null?u:t.id,x=((_=e.composite)==null?void 0:_.compositeStrategy)==="separate"?e.id:(m=(f=e.composite)==null?void 0:f.id)!=null?m:e.id;this.id+="|"+pt.calculatePairHash(p,x)}this.colliderA.owner&&(this.bodyA=this.colliderA.owner.get(N)),this.colliderB.owner&&(this.bodyB=this.colliderB.owner.get(N))}matchAwake(){const t=this.bodyA,e=this.bodyB;t&&e&&t.isSleeping!==e.isSleeping&&(t.isSleeping&&t.collisionType!==M.Fixed&&e.sleepMotion>=t.wakeThreshold&&(t.isSleeping=!1),e.isSleeping&&e.collisionType!==M.Fixed&&t.sleepMotion>=e.wakeThreshold&&(e.isSleeping=!1))}isCanceled(){return this._canceled}cancel(){this._canceled=!0}bias(t){if(t!==this.colliderA&&t!==this.colliderB)throw new Error("Collider must be either colliderA or colliderB from this contact");if(t===this.colliderA)return this;const e=this.colliderA,i=this.colliderB;return this.colliderB=e,this.colliderA=i,this.mtv=this.mtv.negate(),this.normal=this.normal.negate(),this.tangent=this.tangent.negate(),this}}class zi{constructor(t,e,i=100){this.builder=t,this.recycler=e,this.maxObjects=i,this.totalAllocations=0,this.index=0,this.objects=[],this.disableWarnings=!1,this._logger=R.getInstance()}dispose(){this.objects.length=0}preallocate(){for(let t=0;t<this.maxObjects;t++)this.objects[t]=this.builder()}using(t){const e=t(this);return e?this.done(...e):this.done()}borrow(t){const e=this.get();t(e),this.index--}get(){return this.index===this.maxObjects&&(this.disableWarnings||this._logger.warn("Max pooled objects reached, possible memory leak? Doubling"),this.maxObjects=this.maxObjects*2),this.objects[this.index]?this.recycler?this.recycler(this.objects[this.index++]):this.objects[this.index++]:(this.totalAllocations++,this.objects[this.index++]=this.builder())}done(...t){this.index=0;for(const e of t){const i=this.objects.indexOf(e);this.objects[i]=this.builder(),this.totalAllocations++}return t}}class Mr{constructor(){this.axis=b(0,0),this.localAxis=b(0,0),this.side=new Q(b(0,0),b(0,0)),this.localSide=new Q(b(0,0),b(0,0)),this.point=b(0,0),this.localPoint=b(0,0)}}const be=class ie{static findPolygonPolygonSeparation(t,e){if(e.transform.matrix.determinant()===0)return ie.findPolygonPolygonSeparationDegenerate(t,e);let i=-Number.MAX_VALUE,s=-1,n;const o=e.transform.inverse.multiply(t.transform.matrix,ie._SCRATCH_MATRIX),a=o.getRotation(),h=t.normals,l=t.points,c=e.points;for(let f=0;f<l.length;f++){const m=h[f].rotate(a,ie._ZERO,ie._SCRATCH_NORMAL),p=o.multiply(l[f],ie._SCRATCH_POINT);let x=Number.MAX_VALUE,v;for(let g=0;g<c.length;g++){const y=m.dot(c[g].sub(p,ie._SCRATCH_SUB_POINT));y<x&&(x=y,v=c[g])}x>i&&(i=x,s=f,n=v)}const u=(s+1)%l.length,_=ie.SeparationPool.get();return _.collider=t,_.separation=i,i>0||(h[s].clone(_.localAxis),h[s].rotate(t.transform.rotation,ie._ZERO,_.axis),t.transform.matrix.multiply(l[s],_.side.begin),t.transform.matrix.multiply(l[u],_.side.end),e.transform.matrix.multiply(n,_.point),_.sideId=s,n.clone(_.localPoint),l[s].clone(_.localSide.begin),l[u].clone(_.localSide.end)),_}static findCirclePolygonSeparation(t,e){const i=e.axes,n=e.center.sub(t.worldPos),o=e.getFurthestPoint(n.negate());i.push(o.sub(t.worldPos).normalize());let a=Number.MAX_VALUE,h=null,l=-1;for(let c=0;c<i.length;c++){const u=e.project(i[c]),_=t.project(i[c]),f=u.getOverlap(_);if(f<=0)return null;f<a&&(a=f,h=i[c],l=c)}return l<0?null:h.normalize().scale(a)}static findPolygonPolygonSeparationDegenerate(t,e){let i=-Number.MAX_VALUE,s=null,n=null,o=-1,a=null;const h=t.getSides(),l=t.getLocalSides();for(let c=0;c<h.length;c++){const u=h[c],_=u.normal(),f=e.getFurthestPoint(_.negate()),m=u.distanceToPoint(f,!0);m>i&&(i=m,s=u,n=_,o=c,a=f)}return{collider:t,separation:n?i:99,axis:n,side:s,localSide:l[o],sideId:o,point:a,localPoint:n?e.getFurthestLocalPoint(n.negate()):null}}};be.SeparationPool=new zi(()=>new Mr,r=>r,500),be._ZERO=b(0,0),be._SCRATCH_POINT=b(0,0),be._SCRATCH_SUB_POINT=b(0,0),be._SCRATCH_NORMAL=b(0,0),be._SCRATCH_MATRIX=Z.identity();let Ne=be;Ne.SeparationPool.disableWarnings=!0;const Ih=w.Zero,Rh=w.Zero,Mh=Z.identity(),Ut={CollideCircleCircle(r,t){const e=r.worldPos,i=t.worldPos,s=r.radius+t.radius,n=e.distance(i);if(n>s)return[];const o=s-n,a=i.sub(e).normalize(),h=a.perpendicular(),l=a.scale(o),c=r.getFurthestPoint(a),u=r.getFurthestLocalPoint(a),_={collider:r,separation:o,axis:a,point:c};return[new xe(r,t,l,a,h,[c],[u],_)]},CollideCirclePolygon(r,t){var e,i;let s=Ne.findCirclePolygonSeparation(r,t);if(!s)return[];s=s.dot(t.center.sub(r.center))<0?s.negate():s;const o=r.getFurthestPoint(s),h=((i=(e=r.owner)==null?void 0:e.get(P))!=null?i:new P).applyInverse(o),l=s.normalize(),c={collider:r,separation:-s.magnitude,axis:l,point:o,localPoint:h,side:t.findSide(l.negate()),localSide:t.findLocalSide(l.negate())};return[new xe(r,t,s,l,l.perpendicular(),[o],[h],c)]},CollideCircleEdge(r,t){const e=r.center,i=t.asLine(),s=i.end.sub(i.begin),n=s.dot(i.end.sub(e)),o=s.dot(e.sub(i.begin)),a=t.asLine(),h=t.asLocalLine();if(o<=0){const v=i.begin.sub(e),g=v.dot(v);if(g>r.radius*r.radius)return[];const y=v.normalize(),S=r.radius-Math.sqrt(g),A={collider:r,separation:S,axis:y,point:a.begin,side:a,localSide:h};return[new xe(r,t,y.scale(S),y,y.perpendicular(),[a.begin],[h.begin],A)]}if(n<=0){const v=i.end.sub(e),g=v.dot(v);if(g>r.radius*r.radius)return[];const y=v.normalize(),S=r.radius-Math.sqrt(g),A={collider:r,separation:S,axis:y,point:a.end,side:a,localSide:h};return[new xe(r,t,y.scale(S),y,y.perpendicular(),[a.end],[h.end],A)]}const l=s.dot(s),c=i.begin.scale(n).add(i.end.scale(o)).scale(1/l),u=e.sub(c),_=u.dot(u);if(_>r.radius*r.radius)return[];let f=s.perpendicular();f.dot(e.sub(i.begin))<0&&(f.x=-f.x,f.y=-f.y),f=f.normalize();const m=r.radius-Math.sqrt(_),p=f.scale(m),x={collider:r,separation:m,axis:f,point:c,side:a,localSide:h};return[new xe(r,t,p,f.negate(),f.negate().perpendicular(),[c],[c.sub(t.worldPos)],x)]},CollideEdgeEdge(){return[]},CollidePolygonEdge(r,t){var e;const i=r.center,n=t.center.sub(i).normalize(),o=new lt({points:[t.begin,t.end,t.end.add(n.scale(100)),t.begin.add(n.scale(100))],offset:t.offset});o.owner=t.owner,((e=t.owner)==null?void 0:e.get(P))&&o.update(t.owner.get(P).get());const h=this.CollidePolygonPolygon(r,o);return h.length&&(h[0].colliderB=t,h[0].id=pt.calculatePairHash(r.id,t.id)),h},CollidePolygonPolygon(r,t){const e=Ne.findPolygonPolygonSeparation(r,t);if(e.separation>0)return[];const i=Ne.findPolygonPolygonSeparation(t,r);if(i.separation>0)return[];const s=e.separation>i.separation?e:i,n=s.collider===r?t:r,o=s.collider===r?r:t,a=n.transform.inverse.multiply(o.transform.matrix,Mh),h=a.getRotation(),l=o.normals[s.sideId].rotate(h,Ih,Rh);let c=Number.MAX_VALUE,u=0;for(let v=0;v<n.normals.length;v++){const g=l.dot(n.normals[v]);g<c&&(c=g,u=v)}if(!s.localSide||!s.localAxis||!s.axis)return[];const _=s.localSide.transform(a),f=s.localAxis.perpendicular().negate().rotate(h),p=new Q(n.points[u],n.points[(u+1)%n.points.length]).clip(f.negate(),-f.dot(_.begin),!1);let x=null;if(p&&(x=p.clip(f,f.dot(_.end),!1)),x){const v=[],g=[],y=x.getPoints();for(let I=0;I<y.length;I++){const C=y[I];_.below(C)&&(v.push(C),g.push(n.transform.apply(C)))}let S=s.axis,A=S.perpendicular();return t.center.sub(r.center).dot(S)<0&&(S=S.negate(),A=S.perpendicular()),[new xe(r,t,S.scale(-s.separation),S,A,g,v,s)]}return[]},FindContactSeparation(r,t){var e,i,s,n;const o=r.colliderA,a=(i=(e=r.bodyA)==null?void 0:e.transform)!=null?i:new P,h=r.colliderB,l=(n=(s=r.bodyB)==null?void 0:s.transform)!=null?n:new P;if(o instanceof dt&&h instanceof dt){const c=o.radius+h.radius,u=a.pos.distance(l.pos);return-(c-u)}if(o instanceof lt&&h instanceof lt&&r.info.localSide){let c,u;return r.info.collider===o?(c=new Q(a.apply(r.info.localSide.begin).add(o.offset),a.apply(r.info.localSide.end).add(o.offset)),u=l.apply(t).add(h.offset)):(c=new Q(l.apply(r.info.localSide.begin).add(h.offset),l.apply(r.info.localSide.end).add(h.offset)),u=a.apply(t).add(o.offset)),c.distanceToPoint(u,!0)}if(o instanceof lt&&h instanceof dt||h instanceof lt&&o instanceof dt){const c=a.apply(t);if(r.info.side)return r.info.side.distanceToPoint(c,!0)}if(o instanceof St&&h instanceof lt||h instanceof St&&o instanceof lt){let c;if(r.info.collider===o?c=l.apply(t):c=a.apply(t),r.info.side)return r.info.side.distanceToPoint(c,!0)}if(o instanceof dt&&h instanceof St||h instanceof dt&&o instanceof St){const c=l.apply(t);let u;o instanceof dt&&(u=o.getFurthestPoint(r.normal));const _=c.distance(u);if(r.info.side)return _>0?-_:0}return 0}};class St extends ai{constructor(t){var e;super(),this._globalMatrix=Z.identity(),this.begin=t.begin||w.Zero,this.end=t.end||w.Zero,this.offset=(e=t.offset)!=null?e:w.Zero}clone(){return new St({begin:this.begin.clone(),end:this.end.clone()})}get worldPos(){var t;const e=this._transform;return(t=e==null?void 0:e.globalPos.add(this.offset))!=null?t:this.offset}get center(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.average(e)}_getTransformedBegin(){return this._globalMatrix.multiply(this.begin)}_getTransformedEnd(){return this._globalMatrix.multiply(this.end)}getSlope(){const t=this._getTransformedBegin(),e=this._getTransformedEnd(),i=t.distance(e);return e.sub(t).scale(1/i)}getLength(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return t.distance(e)}contains(){return!1}rayCast(t,e=1/0){var i;const s=this._getTransformedBegin().sub(t.pos);if(t.dir.cross(this.getSlope())===0&&s.cross(t.dir)!==0)return null;const n=t.dir.cross(this.getSlope());if(n===0)return null;const o=s.cross(this.getSlope())/n;if(o>=0&&o<=e){const a=s.cross(t.dir)/n/this.getLength();if(a>=0&&a<=1)return{distance:o,normal:this.asLine().normal(),collider:this,body:(i=this.owner)==null?void 0:i.get(N),point:t.getPoint(o)}}return null}getClosestLineBetween(t){if(t instanceof dt)return Vt.CircleEdgeClosestLine(t,this);if(t instanceof lt)return Vt.PolygonEdgeClosestLine(t,this).flip();if(t instanceof St)return Vt.EdgeEdgeClosestLine(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Ut.CollideCircleEdge(t,this);if(t instanceof lt)return Ut.CollidePolygonEdge(t,this);if(t instanceof St)return Ut.CollideEdgeEdge();throw new Error(`Edge could not collide with unknown CollisionShape ${typeof t}`)}getFurthestPoint(t){const e=this._getTransformedBegin(),i=this._getTransformedEnd();return t.dot(e)>0?e:i}_boundsFromBeginEnd(t,e,i=10){return new F(Math.min(t.x,e.x)-i,Math.min(t.y,e.y)-i,Math.max(t.x,e.x)+i,Math.max(t.y,e.y)+i)}get bounds(){const t=this._getTransformedBegin(),e=this._getTransformedEnd();return this._boundsFromBeginEnd(t,e)}get localBounds(){return this._boundsFromBeginEnd(this.begin,this.end)}asLine(){return new Q(this._getTransformedBegin(),this._getTransformedEnd())}asLocalLine(){return new Q(this.begin,this.end)}get axes(){const e=this._getTransformedEnd().sub(this._getTransformedBegin()).normal(),i=[];return i.push(e),i.push(e.negate()),i.push(e.normal()),i.push(e.normal().negate()),i}getInertia(t){const e=this.end.sub(this.begin).distance()/2;return t*e*e}update(t){var e;this._transform=t,((e=t.matrix)!=null?e:this._globalMatrix).clone(this._globalMatrix),this._globalMatrix.translate(this.offset.x,this.offset.y)}project(t){const e=[],i=[this._getTransformedBegin(),this._getTransformedEnd()],s=i.length;for(let n=0;n<s;n++)e.push(i[n].dot(t));return new ei(Math.min.apply(Math,e),Math.max.apply(Math,e))}debug(t,e){const i=this._getTransformedBegin(),s=this._getTransformedEnd();t.debug.drawLine(i,s,{color:e,lineWidth:2}),t.debug.drawCircle(i,2,e),t.debug.drawCircle(s,2,e)}}class lt extends ai{constructor(t){var e;super(),this._logger=R.getInstance(),this._transform=new Kt,this._transformedPoints=[],this._sides=[],this._localSides=[],this._transformedPointsDirty=!0,this._sidesDirty=!0,this._localSidesDirty=!0,this._localBoundsDirty=!0,this.offset=(e=t.offset)!=null?e:w.Zero,this._transform.pos.x+=this.offset.x,this._transform.pos.y+=this.offset.y,this.points=t.points,this.isConvex()||t.suppressConvexWarning||this._logger.warn("Excalibur only supports convex polygon colliders and will not behave properly.Call PolygonCollider.triangulate() to build a new collider composed of smaller convex triangles"),this._calculateTransformation()}flagDirty(){this._localBoundsDirty=!0,this._localSidesDirty=!0,this._transformedPointsDirty=!0,this._sidesDirty=!0}get normals(){return this._normals}set points(t){if(t.length<3)throw new Error("PolygonCollider cannot be created with less that 3 points");this._points=t,this._checkAndUpdateWinding(this._points),this._calculateNormals(),this.flagDirty()}_calculateNormals(){const t=[];for(let e=0;e<this._points.length;e++)t.push(this._points[(e+1)%this._points.length].sub(this._points[e]).normal());this._normals=t}get points(){return this._points}get transform(){return this._transform}_checkAndUpdateWinding(t){this._isCounterClockwiseWinding(t)||t.reverse()}_isCounterClockwiseWinding(t){let e=0;for(let i=0;i<t.length;i++)e+=(t[(i+1)%t.length].x-t[i].x)*(t[(i+1)%t.length].y+t[i].y);return e<0}isConvex(){if(this.points.length<3)return!1;let t=this.points[this.points.length-2],e=this.points[this.points.length-1],i=Math.atan2(e.y-t.y,e.x-t.x),s=0,n=0,o=0;for(const[a,h]of this.points.entries()){if(t=e,s=i,e=h,i=Math.atan2(e.y-t.y,e.x-t.x),t.equals(e))return!1;let l=i-s;if(l<=-Math.PI?l+=Math.PI*2:l>Math.PI&&(l-=Math.PI*2),a===0){if(l===0)return!1;n=l>0?1:-1}else if(n*l<=0)return!1;o+=l}return Math.abs(Math.round(o/(Math.PI*2)))===1}tessellate(){const t=[];for(let e=1;e<this.points.length-2;e++)t.push([this.points[0],this.points[e+1],this.points[e+2]]);return t.push([this.points[0],this.points[1],this.points[2]]),new at(t.map(e=>ut.Polygon(e)))}triangulate(){if(this.points.length<3)throw Error("Invalid polygon");const t=[],e=[...this.points].reverse();let i=e.length;function s(u){return u===0?i-1:u-1}function n(u){return u===i-1?0:u+1}function o(u){const _=s(u),f=n(u),m=e[_],p=e[u],x=e[f],v=m.sub(p),g=x.sub(p);return!(v.cross(g)<0)}const a=e.map((u,_)=>o(_));function h(u,_,f,m){const p=f.sub(_),x=m.sub(f),v=_.sub(m),g=u.sub(_),y=u.sub(f),S=u.sub(m),A=p.cross(g),I=x.cross(y),C=v.cross(S);return!(A>0||I>0||C>0)}function l(){for(let u=0;u<i;u++)if(a[u]){const _=s(u),f=n(u),m=e[_],p=e[u],x=e[f];let v=!0;for(let g=0;g<i;g++){if(g===u||g===_||g===f)continue;const y=e[g];if(h(y,m,p,x)){v=!1;break}}if(v)return u}for(let u=0;u<i;u++)if(a[u])return u;return 0}function c(u){const _=s(u),f=n(u),m=e[_],p=e[u],x=e[f];t.push([m,p,x]),e.splice(u,1),a.splice(u,1),i--}for(;i>3;){const u=l();c(u);for(let _=0;_<i;_++)a[_]=o(_)}return t.push([e[0],e[1],e[2]]),new at(t.map(u=>ut.Polygon(u,w.Zero,!0)))}clone(){return new lt({offset:this.offset.clone(),points:this.points.map(t=>t.clone())})}get worldPos(){return this._transform.pos}get center(){return this.bounds.center}_calculateTransformation(){const t=this.points,e=t.length;this._transformedPoints.length=0;for(let i=0;i<e;i++)this._transformedPoints[i]=this._transform.apply(t[i].clone())}getTransformedPoints(){return this._transformedPointsDirty&&(this._calculateTransformation(),this._transformedPointsDirty=!1),this._transformedPoints}getSides(){if(this._sidesDirty){const t=[],e=this.getTransformedPoints(),i=e.length;for(let s=0;s<i;s++)t.push(new Q(e[s],e[(s+1)%i]));this._sides=t,this._sidesDirty=!1}return this._sides}getLocalSides(){if(this._localSidesDirty){const t=[],e=this.points,i=e.length;for(let s=0;s<i;s++)t.push(new Q(e[s],e[(s+1)%i]));this._localSides=t,this._localSidesDirty=!1}return this._localSides}findSide(t){const e=this.getSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=e[n],h=o.normal().dot(t);h>s&&(i=o,s=h)}return i}findLocalSide(t){const e=this.getLocalSides();let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=e[n],h=o.normal().dot(t);h>s&&(i=o,s=h)}return i}get axes(){const t=[],e=this.getSides();for(let i=0;i<e.length;i++)t.push(e[i].normal());return t}update(t){t&&(t.cloneWithParent(this._transform),this._transformedPointsDirty=!0,this._sidesDirty=!0,(this.offset.x!==0||this.offset.y!==0)&&(this._transform.pos.x+=this.offset.x,this._transform.pos.y+=this.offset.y),this._transform.isMirrored()&&(this.points=this.points.map(e=>b(e.x*V(this._transform.scale.x),e.y*V(this._transform.scale.y))),this._transform.scale.x=Math.abs(this._transform.scale.x),this._transform.scale.y=Math.abs(this._transform.scale.y)))}contains(t){const e=this._transform.applyInverse(t),i=new ge(e,new w(1,0));let s=0;const n=this.getLocalSides();for(let o=0;o<n.length;o++){const a=n[o];i.intersect(a)>=0&&s++}return s%2!==0}getClosestLineBetween(t){if(t instanceof dt)return Vt.PolygonCircleClosestLine(this,t);if(t instanceof lt)return Vt.PolygonPolygonClosestLine(this,t);if(t instanceof St)return Vt.PolygonEdgeClosestLine(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}collide(t){if(t instanceof dt)return Ut.CollideCirclePolygon(t,this);if(t instanceof lt)return Ut.CollidePolygonPolygon(this,t);if(t instanceof St)return Ut.CollidePolygonEdge(this,t);throw new Error(`Polygon could not collide with unknown CollisionShape ${typeof t}`)}getFurthestPoint(t){const e=this.getTransformedPoints();let i=null,s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=t.dot(e[n]);o>s&&(s=o,i=e[n])}return i}getFurthestLocalPoint(t){const e=this.points;let i=e[0],s=-Number.MAX_VALUE;for(let n=0;n<e.length;n++){const o=t.dot(e[n]);o>s&&(s=o,i=e[n])}return i}getClosestFace(t){const e=this.getSides();let i=Number.POSITIVE_INFINITY,s=-1,n=-1;for(let o=0;o<e.length;o++){const a=e[o].distanceToPoint(t);a<i&&(i=a,s=o,n=a)}return s!==-1?{distance:e[s].normal().scale(n),face:e[s]}:null}get bounds(){return this.localBounds.transform(this._transform.matrix)}get localBounds(){return this._localBoundsDirty&&(this._localBounds=F.fromPoints(this.points),this._localBoundsDirty=!1),this._localBounds}getInertia(t){if(this._cachedMass===t&&this._cachedInertia)return this._cachedInertia;let e=0,i=0;const s=this.points;for(let n=0;n<s.length;n++){const o=(n+1)%s.length,a=s[o].cross(s[n]);e+=a*(s[n].dot(s[n])+s[n].dot(s[o])+s[o].dot(s[o])),i+=a}return this._cachedMass=t,this._cachedInertia=t/6*(e/i)}rayCast(t,e=1/0){var i;const s=this.getSides(),n=s.length;let o=Number.MAX_VALUE,a,h=-1;for(let l=0;l<n;l++){const c=t.intersect(s[l]);c>=0&&c<o&&c<=e&&(o=c,a=s[l],h=l)}return h>=0?{collider:this,distance:o,body:(i=this.owner)==null?void 0:i.get(N),point:t.getPoint(o),normal:a.normal()}:null}project(t){const e=this.getTransformedPoints(),i=e.length;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;for(let o=0;o<i;o++){const a=e[o].dot(t);s=Math.min(s,a),n=Math.max(n,a)}return new ei(s,n)}debug(t,e,i){const s=this.getTransformedPoints();Tt.drawPolygon(s,{color:e})}}class ut{static Box(t,e,i=w.Half,s=w.Zero){return new lt({points:new F(-t*i.x,-e*i.y,t-t*i.x,e-e*i.y).getPoints().slice(),offset:s})}static Polygon(t,e=w.Zero,i=!1){return new lt({points:t,offset:e,suppressConvexWarning:i})}static Circle(t,e=w.Zero){return new dt({radius:t,offset:e})}static Edge(t,e){return new St({begin:t,end:e})}static Capsule(t,e,i=w.Zero){const s=R.getInstance();if(t===e&&s.warn("A capsule collider with equal width and height is a circle, consider using a ex.Shape.Circle or ex.CircleCollider"),e>=t){const o=new at([ut.Circle(t/2,b(0,-e/2+t/2).add(i)),ut.Box(t,e-t,w.Half,i),ut.Circle(t/2,b(0,e/2-t/2).add(i))]);return o.compositeStrategy="together",o}else{const o=new at([ut.Circle(e/2,b(-t/2+e/2,0).add(i)),ut.Box(t-e,e,w.Half,i),ut.Circle(e/2,b(t/2-e/2,0).add(i))]);return o.compositeStrategy="together",o}}}function It(r,t){return r&&(r.__isProxy===void 0?new Proxy(r,{set:(e,i,s)=>(e[i]!==s&&(e[i]=s,typeof i=="string"&&i[0]!=="_"&&t(e)),!0),get:(e,i)=>i!=="__isProxy"?e[i]:!0}):r)}const Fr=(r=[],t,e)=>({get:(i,s)=>s==="__isProxy"?!0:typeof i[s]=="object"&&i[s]!=null?new Proxy(i[s],Fr([...r,s],t,e)):i[s],set:(i,s,n)=>(typeof s=="string"&&s[0]!=="_"&&t(e),i[s]=n,!0)});function Fh(r,t){return r&&(r.__isProxy===void 0?new Proxy(r,Fr([],t,r)):r)}const Dr=class ka{constructor(t){this.id=ka._ID++,this.transform=Z.identity(),this._transformStale=!0,this.showDebug=!1,this._flipHorizontal=!1,this._flipVertical=!1,this._rotation=0,this.opacity=1,this._scale=w.One,this._width=0,this._height=0;var e,i,s,n,o,a,h;t&&(this.origin=(e=t.origin)!=null?e:this.origin,this.flipHorizontal=(i=t.flipHorizontal)!=null?i:this.flipHorizontal,this.flipVertical=(s=t.flipVertical)!=null?s:this.flipVertical,this.rotation=(n=t.rotation)!=null?n:this.rotation,this.opacity=(o=t.opacity)!=null?o:this.opacity,this.scale=(a=t.scale)!=null?a:this.scale,this.tint=(h=t.tint)!=null?h:this.tint,t.width&&(this._width=t.width),t.height&&(this._height=t.height))}isStale(){return this._transformStale}get flipHorizontal(){return this._flipHorizontal}set flipHorizontal(t){this._flipHorizontal=t,this._transformStale=!0}get flipVertical(){return this._flipVertical}set flipVertical(t){this._flipVertical=t,this._transformStale=!0}get rotation(){return this._rotation}set rotation(t){this._rotation=t,this._transformStale=!0}get scale(){return this._scale}set scale(t){this._scale=It(t,()=>{this._transformStale=!0}),this._transformStale=!0}get origin(){return this._origin}set origin(t){t&&(this._origin=It(t,()=>{this._transformStale=!0})),this._transformStale=!0}cloneGraphicOptions(){return{width:this.width/this.scale.x,height:this.height/this.scale.y,origin:this.origin?this.origin.clone():void 0,flipHorizontal:this.flipHorizontal,flipVertical:this.flipVertical,rotation:this.rotation,opacity:this.opacity,scale:this.scale?this.scale.clone():void 0,tint:this.tint?this.tint.clone():void 0}}get width(){return Math.abs(this._width*this.scale.x)}get height(){return Math.abs(this._height*this.scale.y)}set width(t){this._width=t,this._transformStale=!0}set height(t){this._height=t,this._transformStale=!0}get localBounds(){return F.fromDimension(this.width,this.height,w.Zero)}draw(t,e,i){this._preDraw(t,e,i),this._drawImage(t,0,0),this._postDraw(t)}_preDraw(t,e,i){t.save(),t.translate(e,i),this._transformStale&&(this.transform.reset(),this.transform.scale(Math.abs(this.scale.x),Math.abs(this.scale.y)),this._rotate(this.transform),this._flip(this.transform),this._transformStale=!1),t.multiply(this.transform),t.opacity=t.opacity*this.opacity,this.tint&&(t.tint=this.tint)}_rotate(t){var e;const i=this.scale.x>0?1:-1,s=this.scale.y>0?1:-1,n=(e=this.origin)!=null?e:b(this.width/2,this.height/2);t.translate(n.x,n.y),t.rotate(this.rotation),t.scale(i,s),t.translate(-n.x,-n.y)}_flip(t){this.flipHorizontal&&(t.translate(this.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,this.height/this.scale.y),t.scale(1,-1))}_postDraw(t){this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore()}};Dr._ID=0;let st=Dr;var Br=(r=>(r.Forward="forward",r.Backward="backward",r))(Br||{}),kr=(r=>(r.End="end",r.Loop="loop",r.PingPong="pingpong",r.Freeze="freeze",r))(kr||{});const Dh={Frame:"frame",Loop:"loop",End:"end"},Lr=class nr extends st{constructor(t){var e,i,s;super(t),this.events=new X,this.frames=[],this.strategy="loop",this.frameDuration=100,this._idempotencyToken=-1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=0,this._pingPongDirection=1,this._done=!1,this._playing=!0,this._speed=1,this._wasResetDuringFrameCalc=!1,this._reversed=!1,this.frames=t.frames,this.speed=(e=t.speed)!=null?e:this.speed,this.strategy=(i=t.strategy)!=null?i:this.strategy,this.frameDuration=t.totalDuration?t.totalDuration/this.frames.length:(s=t.frameDuration)!=null?s:this.frameDuration,this.data=t.data?new Map(Object.entries(t.data)):new Map,t.reverse&&this.reverse(),this.goToFrame(0)}clone(){const t=this.constructor;return new t({frames:this.frames.map(e=>({...e})),frameDuration:this.frameDuration,speed:this.speed,reverse:this._reversed,strategy:this.strategy,...this.cloneGraphicOptions()})}get width(){const t=this.currentFrame;return t&&t.graphic?Math.abs(t.graphic.width*this.scale.x):0}get height(){const t=this.currentFrame;return t&&t.graphic?Math.abs(t.graphic.height*this.scale.y):0}static fromSpriteSheet(t,e,i,s="loop",n){const o=t.sprites.length-1,a=e.filter(h=>h<0||h>o);return a.length&&nr._LOGGER.warn(`Indices into SpriteSheet were provided that don't exist: ${a.join(",")} no frame will be shown`),new this({frames:t.sprites.filter((h,l)=>e.indexOf(l)>-1).map(h=>({graphic:h,duration:i})),strategy:s,data:n})}static fromSpriteSheetCoordinates(t){var e;const{spriteSheet:i,frameCoordinates:s,durationPerFrame:n,durationPerFrameMs:o,speed:a,strategy:h,reverse:l,data:c}=t,u=(e=n!=null?n:o)!=null?e:100,_=[];for(const f of s){const{x:m,y:p,duration:x,options:v}=f,g=i.getSprite(m,p,v);g?_.push({graphic:g,duration:x!=null?x:u}):nr._LOGGER.warn(`Skipping frame! SpriteSheet does not have coordinate (${m}, ${p}), please check your SpriteSheet to confirm that sprite exists`)}return new this({frames:_,strategy:h,speed:a,reverse:l,data:c})}get speed(){return this._speed}set speed(t){this._speed=B(Math.abs(t),0,1/0)}get currentFrame(){return this._currentFrame>=0&&this._currentFrame<this.frames.length?this.frames[this._currentFrame]:null}get currentFrameIndex(){return this._currentFrame}get currentFrameTimeLeft(){return this._timeLeftInFrame}get isPlaying(){return this._playing}get isReversed(){return this._reversed}reverse(){this.frames=this.frames.slice().reverse(),this._reversed=!this._reversed}get direction(){return!!(this._reversed&&this._pingPongDirection===1)?"backward":"forward"}play(){this._playing=!0}pause(){this._playing=!1,this._firstTick=!0}reset(){this._wasResetDuringFrameCalc=!0,this._done=!1,this._firstTick=!0,this._currentFrame=0,this._timeLeftInFrame=this.frameDuration;const t=this.frames[this._currentFrame];t&&(this._timeLeftInFrame=(t==null?void 0:t.duration)||this.frameDuration)}get canFinish(){switch(this.strategy){case"end":case"freeze":return!0;default:return!1}}get done(){return this._done}goToFrame(t,e){this._currentFrame=t,this._timeLeftInFrame=e!=null?e:this.frameDuration;const i=this.frames[this._currentFrame];i&&!this._done&&(this._timeLeftInFrame=e!=null?e:(i==null?void 0:i.duration)||this.frameDuration,this.events.emit("frame",{...i,frameIndex:this.currentFrameIndex}))}_nextFrame(){this._wasResetDuringFrameCalc=!1;const t=this._currentFrame;if(this._done)return t;let e=-1;switch(this.strategy){case"loop":{e=(t+1)%this.frames.length,e===0&&this.events.emit("loop",this);break}case"end":{e=t+1,e>=this.frames.length&&(this._done=!0,this._currentFrame=this.frames.length,this.events.emit("end",this));break}case"freeze":{e=B(t+1,0,this.frames.length-1),t+1>=this.frames.length&&(this._done=!0,this.events.emit("end",this));break}case"pingpong":{t+this._pingPongDirection>=this.frames.length&&(this._pingPongDirection=-1,this.events.emit("loop",this)),t+this._pingPongDirection<0&&(this._pingPongDirection=1,this.events.emit("loop",this)),e=t+this._pingPongDirection%this.frames.length;break}}return this._wasResetDuringFrameCalc?(this._wasResetDuringFrameCalc=!1,this._currentFrame):e}tick(t,e=0){this._idempotencyToken!==e&&(this._idempotencyToken=e,this._playing&&(this._firstTick&&(this._firstTick=!1,this.events.emit("frame",{...this.currentFrame,frameIndex:this.currentFrameIndex})),this._timeLeftInFrame-=t*this._speed,this._timeLeftInFrame<=0&&this.goToFrame(this._nextFrame())))}_drawImage(t,e,i){this.currentFrame&&this.currentFrame.graphic&&this.currentFrame.graphic.draw(t,e,i)}};Lr._LOGGER=R.getInstance();let Oi=Lr;class We extends st{constructor(t){var e;super(t),this._logger=R.getInstance(),this.useAnchor=!0,this.members=[],this.members=t.members,this.useAnchor=(e=t.useAnchor)!=null?e:this.useAnchor,this._updateDimensions()}clone(){return new We({members:[...this.members],...this.cloneGraphicOptions()})}_updateDimensions(){const t=this.localBounds;return this.width=t.width,this.height=t.height,t}get localBounds(){const t=new F;for(const e of this.members)if(e instanceof st)e.localBounds.combine(t,t);else{const{graphic:i,offset:s,useBounds:n}=e;i?(n===void 0?!0:n)&&i.localBounds.translate(s).combine(t,t):this._logger.warnOnce(`Graphics group member has an null or undefined graphic, member definition: ${JSON.stringify(e)}.`)}return t}_isAnimationOrGroup(t){return t instanceof Oi||t instanceof We}tick(t,e){for(const i of this.members){let s;i instanceof st?s=i:s=i.graphic,this._isAnimationOrGroup(s)&&s.tick(t,e)}}reset(){for(const t of this.members){let e;t instanceof st?e=t:e=t.graphic,this._isAnimationOrGroup(e)&&e.reset()}}_preDraw(t,e,i){this._updateDimensions(),super._preDraw(t,this.useAnchor?e:0,this.useAnchor?i:0)}_drawImage(t,e,i){const s=w.Zero;for(const n of this.members){let o;n instanceof st?o=n:(o=n.graphic,n.offset.clone(s)),o&&(t.save(),t.translate(e,i),o.draw(t,s.x,s.y),this.showDebug&&t.debug.drawRect(0,0,this.width,this.height),t.restore())}}}class Ge extends st{constructor(t){var e,i,s,n,o,a,h,l,c,u;super(yr({...t},["width","height"])),this.lineCap="butt",this.quality=1,this._dirty=!0,this._smoothing=!1,this._color=It(T.Black,()=>this.flagDirty()),this._lineWidth=1,this._lineDash=[],this._padding=0,t&&(this.quality=(e=t.quality)!=null?e:this.quality,this.color=(i=t.color)!=null?i:T.Black,this.strokeColor=t==null?void 0:t.strokeColor,this.smoothing=(s=t.smoothing)!=null?s:this.smoothing,this.lineWidth=(n=t.lineWidth)!=null?n:this.lineWidth,this.lineDash=(o=t.lineDash)!=null?o:this.lineDash,this.lineCap=(a=t.lineCap)!=null?a:this.lineCap,this.padding=(h=t.padding)!=null?h:this.padding,this.filtering=(l=t.filtering)!=null?l:this.filtering),this._bitmap=document.createElement("canvas");const _=(c=t==null?void 0:t.width)!=null?c:this._bitmap.width,f=(u=t==null?void 0:t.height)!=null?u:this._bitmap.height;this.width=_,this.height=f;const m=this._bitmap.getContext("2d");if(m)this._ctx=m;else throw new Error("Browser does not support 2d canvas drawing, cannot create Raster graphic")}cloneRasterOptions(){return{color:this.color?this.color.clone():void 0,strokeColor:this.strokeColor?this.strokeColor.clone():void 0,smoothing:this.smoothing,lineWidth:this.lineWidth,lineDash:this.lineDash,lineCap:this.lineCap,quality:this.quality,padding:this.padding}}get dirty(){return this._dirty}flagDirty(){this._dirty=!0}get width(){return Math.abs(this._getTotalWidth()*this.scale.x)}set width(t){t/=Math.abs(this.scale.x),this._bitmap.width=t,this._originalWidth=t,this.flagDirty()}get height(){return Math.abs(this._getTotalHeight()*this.scale.y)}set height(t){t/=Math.abs(this.scale.y),this._bitmap.height=t,this._originalHeight=t,this.flagDirty()}_getTotalWidth(){var t;return(((t=this._originalWidth)!=null?t:this._bitmap.width)+this.padding*2)*1}_getTotalHeight(){var t;return(((t=this._originalHeight)!=null?t:this._bitmap.height)+this.padding*2)*1}get localBounds(){return F.fromDimension(this._getTotalWidth()*this.scale.x,this._getTotalHeight()*this.scale.y,w.Zero)}get smoothing(){return this._smoothing}set smoothing(t){this._smoothing=t,this.flagDirty()}get color(){return this._color}set color(t){this.flagDirty(),this._color=It(t,()=>this.flagDirty())}get strokeColor(){return this._strokeColor}set strokeColor(t){this.flagDirty(),t&&(this._strokeColor=It(t,()=>this.flagDirty()))}get lineWidth(){return this._lineWidth}set lineWidth(t){this._lineWidth=t,this.flagDirty()}get lineDash(){return this._lineDash}set lineDash(t){this._lineDash=t,this.flagDirty()}get padding(){return this._padding}set padding(t){this._padding=t,this.flagDirty()}rasterize(){this._dirty=!1,this._ctx.clearRect(0,0,this._getTotalWidth(),this._getTotalHeight()),this._ctx.save(),this._applyRasterProperties(this._ctx),this.execute(this._ctx),this._ctx.restore()}_applyRasterProperties(t){var e,i,s,n;this._bitmap.width=this._getTotalWidth()*this.quality,this._bitmap.height=this._getTotalHeight()*this.quality,this._bitmap.setAttribute("filtering",this.filtering),this._bitmap.setAttribute("forceUpload","true"),t.scale(this.quality,this.quality),t.translate(this.padding,this.padding),t.imageSmoothingEnabled=this.smoothing,t.lineWidth=this.lineWidth,t.setLineDash((e=this.lineDash)!=null?e:t.getLineDash()),t.lineCap=this.lineCap,t.strokeStyle=(s=(i=this.strokeColor)==null?void 0:i.toString())!=null?s:"",t.fillStyle=(n=this.color)==null?void 0:n.toString()}_drawImage(t,e,i){this._dirty&&this.rasterize(),t.scale(1/this.quality,1/this.quality),t.drawImage(this._bitmap,e,i)}}var an=(r=>(r.Em="em",r.Rem="rem",r.Px="px",r.Pt="pt",r.Percent="%",r))(an||{}),hn=(r=>(r.Left="left",r.Right="right",r.Center="center",r.Start="start",r.End="end",r))(hn||{}),ln=(r=>(r.Top="top",r.Hanging="hanging",r.Middle="middle",r.Alphabetic="alphabetic",r.Ideographic="ideographic",r.Bottom="bottom",r))(ln||{}),cn=(r=>(r.Normal="normal",r.Italic="italic",r.Oblique="oblique",r))(cn||{}),dn=(r=>(r.LeftToRight="ltr",r.RightToLeft="rtl",r))(dn||{}),mt=(r=>(r.Pixel="Pixel",r.Blended="Blended",r))(mt||{});function Ve(r){switch(r){case"Pixel":return"Pixel";case"Blended":return"Blended";default:return}}function un(r,t=T.Red,e,i,s,n,o=1,a="butt"){r.save(),r.beginPath(),r.lineWidth=o,r.lineCap=a,r.strokeStyle=t.toString(),r.moveTo(e,i),r.lineTo(s,n),r.closePath(),r.stroke(),r.restore()}function Bh(r,t=T.Red,e){r.beginPath(),r.strokeStyle=t.toString(),r.arc(e.x,e.y,5,0,Math.PI*2),r.closePath(),r.stroke()}function kh(r,t,e,i,s=1){const n=t?t.toString():"blue",o=i.scale(s);r.beginPath(),r.strokeStyle=n,r.moveTo(e.x,e.y),r.lineTo(e.x+o.x,e.y+o.y),r.closePath(),r.stroke()}function _n(r,t,e,i,s,n=5,o=T.White,a=null){let h;if(typeof n=="number")h={tl:n,tr:n,br:n,bl:n};else{const l={tl:0,tr:0,br:0,bl:0};for(const c in l)if(l.hasOwnProperty(c)){const u=c;h[u]=n[u]||l[u]}}r.beginPath(),r.moveTo(t+h.tl,e),r.lineTo(t+i-h.tr,e),r.quadraticCurveTo(t+i,e,t+i,e+h.tr),r.lineTo(t+i,e+s-h.br),r.quadraticCurveTo(t+i,e+s,t+i-h.br,e+s),r.lineTo(t+h.bl,e+s),r.quadraticCurveTo(t,e+s,t,e+s-h.bl),r.lineTo(t,e+h.tl),r.quadraticCurveTo(t,e,t+h.tl,e),r.closePath(),a&&(r.fillStyle=a.toString(),r.fill()),o&&(r.strokeStyle=o.toString(),r.stroke())}function Lh(r,t,e,i,s=T.White,n=null){r.beginPath(),r.arc(t,e,i,0,Math.PI*2),r.closePath(),n&&(r.fillStyle=n.toString(),r.fill()),s&&(r.strokeStyle=s.toString(),r.stroke())}const Uh=Object.freeze(Object.defineProperty({__proto__:null,circle:Lh,line:un,point:Bh,roundRect:_n,vector:kh},Symbol.toStringTag,{value:"Module"}));class qe{constructor(t,e,i=1){this.builder=t,this.cleaner=e,this._pool=[],this._size=0,this.grow(i)}grow(t){if(t>0){this._size+=t;for(let e=0;e<t;e++)this._pool.push(this.builder())}}rent(t=!1){return this._pool.length===0&&this.grow(this._size),t?this.cleaner(this._pool.pop()):this._pool.pop()}return(t){this._pool.push(t)}}class zh{constructor(){this._pool=new qe(()=>Z.identity(),t=>t.reset(),100),this._transforms=[],this._currentTransform=this._pool.rent(!0)}save(){this._transforms.push(this._currentTransform),this._currentTransform=this._currentTransform.clone(this._pool.rent())}restore(){this._pool.return(this._currentTransform),this._currentTransform=this._transforms.pop()}translate(t,e){return this._currentTransform.translate(t,e)}rotate(t){return this._currentTransform.rotate(t)}scale(t,e){return this._currentTransform.scale(t,e)}reset(){this._currentTransform.reset()}set current(t){this._currentTransform=t}get current(){return this._currentTransform}}class Oh{constructor(){this.opacity=1,this.z=0,this.tint=T.White,this.material=null}}class Ur{constructor(){this._pool=new qe(()=>new Oh,t=>(t.opacity=1,t.z=0,t.tint=T.White,t.material=null,t),100),this.current=this._pool.rent(!0),this._states=[]}_cloneState(t){var e;return t.opacity=this.current.opacity,t.z=this.current.z,t.tint=(e=this.current.tint)==null?void 0:e.clone(),t.material=this.current.material,t}save(){this._states.push(this.current),this.current=this._cloneState(this._pool.rent())}restore(){this._pool.return(this.current),this.current=this._states.pop()}}const Hh={Complete:"complete",Load:"load",LoadStart:"loadstart",Progress:"progress",Error:"error"};class li{constructor(t,e,i=!1){this.path=t,this.responseType=e,this.bustCache=i,this.data=null,this.logger=R.getInstance(),this.events=new X}isLoaded(){return this.data!==null}_cacheBust(t){return/\?\w*=\w*/.test(t)?t+="&__="+Date.now():t+="?__="+Date.now(),t}load(){return new Promise((t,e)=>{if(this.data!==null){this.logger.debug("Already have data for resource",this.path),this.events.emit("complete",this.data),t(this.data);return}const i=new XMLHttpRequest;i.open("GET",this.bustCache?this._cacheBust(this.path):this.path,!0),i.responseType=this.responseType,i.addEventListener("loadstart",s=>this.events.emit("loadstart",s)),i.addEventListener("progress",s=>this.events.emit("progress",s)),i.addEventListener("error",s=>this.events.emit("error",s)),i.addEventListener("load",s=>this.events.emit("load",s)),i.addEventListener("load",()=>{if(i.status!==0&&i.status!==200){this.logger.error("Failed to load resource ",this.path," server responded with error code",i.status),this.events.emit("error",i.response),e(new Error(i.statusText));return}if(i.response instanceof Blob&&i.response.type==="text/html"){const s=`Expected blob (usually image) data from the server when loading ${this.path}, but got HTML content instead!
|
|
27
27
|
|
|
28
|
-
Check your server configuration, for example Vite serves static files from the /public folder`;this.events.emit("error",i.response),e(new Error(s));return}this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)}),i.send()})}}class
|
|
28
|
+
Check your server configuration, for example Vite serves static files from the /public folder`;this.events.emit("error",i.response),e(new Error(s));return}this.data=i.response,this.events.emit("complete",this.data),this.logger.debug("Completed loading resource",this.path),t(this.data)}),i.send()})}}class zt extends st{constructor(t){var e,i;super(t),this._logger=R.getInstance(),this._dirty=!0,this.image=t.image;const{width:s,height:n}=t;this.sourceView=(e=t.sourceView)!=null?e:{x:0,y:0,width:s!=null?s:0,height:n!=null?n:0},this.destSize=(i=t.destSize)!=null?i:{width:s!=null?s:0,height:n!=null?n:0},this._updateSpriteDimensions(),this.image.ready.then(()=>{this._updateSpriteDimensions()})}static from(t,e){return new zt({image:t,...e})}get width(){return Math.abs(this.destSize.width*this.scale.x)}get height(){return Math.abs(this.destSize.height*this.scale.y)}set width(t){t/=Math.abs(this.scale.x),this.destSize.width=t,super.width=Math.ceil(this.destSize.width)}set height(t){t/=Math.abs(this.scale.y),this.destSize.height=t,super.height=Math.ceil(this.destSize.height)}_updateSpriteDimensions(){var t,e,i,s,n,o;const{width:a,height:h}=this.image;this.sourceView.width=((t=this.sourceView)==null?void 0:t.width)||a,this.sourceView.height=((e=this.sourceView)==null?void 0:e.height)||h,this.destSize.width=((i=this.destSize)==null?void 0:i.width)||((s=this.sourceView)==null?void 0:s.width)||a,this.destSize.height=((n=this.destSize)==null?void 0:n.height)||((o=this.sourceView)==null?void 0:o.height)||h,this.width=Math.ceil(this.destSize.width)*this.scale.x,this.height=Math.ceil(this.destSize.height)*this.scale.y}_preDraw(t,e,i){this.image.isLoaded()&&this._dirty&&(this._dirty=!1,this._updateSpriteDimensions()),super._preDraw(t,e,i)}_drawImage(t,e,i){this.image.isLoaded()?t.drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,e,i,this.destSize.width,this.destSize.height):this._logger.warnOnce(`ImageSource ${this.image.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.
|
|
29
29
|
|
|
30
|
-
Read https://excaliburjs.com/docs/imagesource for more information.`)}clone(){return new
|
|
30
|
+
Read https://excaliburjs.com/docs/imagesource for more information.`)}clone(){return new zt({image:this.image,sourceView:{...this.sourceView},destSize:{...this.destSize},...this.cloneGraphicOptions()})}}var _t=(r=>(r.Clamp="Clamp",r.Repeat="Repeat",r.Mirror="Mirror",r))(_t||{});function Ot(r){switch(r){case"Clamp":return"Clamp";case"Repeat":return"Repeat";case"Mirror":return"Mirror";default:return"Clamp"}}const ci=class Ft{constructor(t,e){this._garbageCollector=e,this._textureMap=new Map,this._collect=s=>{var n;if(this._gl){const o=(n=s.dataset.originalSrc)!=null?n:s.constructor.name;return Ft._LOGGER.debug(`WebGL Texture for ${o} collected`),this.delete(s),!0}return!1};var i;this._gl=t,Ft._MAX_TEXTURE_SIZE=t.getParameter(t.MAX_TEXTURE_SIZE),this._garbageCollector&&(Ft._LOGGER.debug("WebGL Texture collection interval:",this._garbageCollector.collectionInterval),(i=this._garbageCollector.garbageCollector)==null||i.registerCollector("texture",this._garbageCollector.collectionInterval,this._collect))}dispose(){for(const[t]of this._textureMap)this.delete(t);this._textureMap.clear(),this._gl=null}get(t){return this._textureMap.get(t)}has(t){return this._textureMap.has(t)}load(t,e,i=!1){var s,n;const o=this._gl;if(!o)return null;const{filtering:a,wrapping:h}={...e};let l=null;if(this.has(t)&&(l=this.get(t)),l)return i&&(o.bindTexture(o.TEXTURE_2D,l),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,t)),(s=this._garbageCollector)==null||s.garbageCollector.touch(t),l;l=o.createTexture(),Ft.checkImageSizeSupportedAndLog(t),o.bindTexture(o.TEXTURE_2D,l),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0);let c;h&&(typeof h=="string"?c={x:h,y:h}:c={x:h.x,y:h.y});const{x:u,y:_}=c!=null?c:Ft.wrapping;switch(u){case _t.Clamp:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE);break;case _t.Repeat:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.REPEAT);break;case _t.Mirror:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.MIRRORED_REPEAT);break;default:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE)}switch(_){case _t.Clamp:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE);break;case _t.Repeat:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.REPEAT);break;case _t.Mirror:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.MIRRORED_REPEAT);break;default:o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE)}const f=a!=null?a:Ft.filtering;return o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,f===mt.Pixel?o.NEAREST:o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,f===mt.Pixel?o.NEAREST:o.LINEAR),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,t),this._textureMap.set(t,l),(n=this._garbageCollector)==null||n.garbageCollector.addCollectableResource("texture",t),l}delete(t){const e=this._gl;if(e&&this.has(t)){const i=this.get(t);i&&(this._textureMap.delete(t),e.deleteTexture(i))}}static checkImageSizeSupportedAndLog(t){var e;const i=(e=t.dataset.originalSrc)!=null?e:"internal canvas bitmap";return t.width>Ft._MAX_TEXTURE_SIZE||t.height>Ft._MAX_TEXTURE_SIZE?(Ft._LOGGER.error(`The image [${i}] provided to Excalibur is too large for the device's maximum texture size of (${Ft._MAX_TEXTURE_SIZE}x${Ft._MAX_TEXTURE_SIZE}) please resize to an image for excalibur to render properly.
|
|
31
31
|
|
|
32
32
|
Images will likely render as black rectangles.
|
|
33
33
|
|
|
34
|
-
Read more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!1):((t.width>4096||t.height>4096)&&
|
|
34
|
+
Read more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!1):((t.width>4096||t.height>4096)&&Ft._LOGGER.warn(`The image [${i}] provided to excalibur is too large may not work on all mobile devices, it is recommended you resize images to a maximum (4096x4096).
|
|
35
35
|
|
|
36
36
|
Images will likely render as black rectangles on some mobile platforms.
|
|
37
37
|
|
|
38
|
-
Read more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!0)}};
|
|
39
|
-
`);if(e==null)return s;for(let n=0;n<s.length;n++){let o=s[n],a="";if(this.measureText(o).width>e){for(;this.measureText(o).width>e;)a=o[o.length-1]+a,o=o.slice(0,-1);s[n]=o,s[n+1]=a}}return this._cachedText=t,this._cachedLines=s,this._cachedRenderWidth=e,s}}class li extends kt{constructor(t){super({image:t.image,sourceView:t.sourceView,destSize:{width:t.width,height:t.height},flipHorizontal:t.flipHorizontal,flipVertical:t.flipVertical,rotation:t.rotation,scale:t.scale,opacity:t.opacity,tint:t.tint,origin:t.origin}),this._ready=new wt,this.ready=this._ready.promise,this._options=t,this.image.isLoaded()?this._applyTiling():this.image.ready.then(()=>this._applyTiling())}static fromSprite(t,e){return new li({sourceView:{...t.sourceView},width:t.width,height:t.height,...e,image:t.image})}_applyTiling(){const{width:t,height:e,filtering:i,wrapping:s}={...this._options},n=document.createElement("canvas");n.width=this.sourceView.width,n.height=this.sourceView.height,n.getContext("2d").drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,0,0,this.sourceView.width,this.sourceView.height);const a=Gt.fromHtmlCanvasElement(n,{wrapping:s!=null?s:_t.Repeat,filtering:i});t&&(this.destSize.width=t,this.sourceView.width=t),e&&(this.destSize.height=e,this.sourceView.height=e),this.sourceView.x=0,this.sourceView.y=0,this.image=a,this.image.ready.then(()=>this._ready.resolve())}}class be{constructor(t){this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=i!=null?i:1,this.columns=s!=null?s:this.sprites.length}getSprite(t,e,i){var s,n,o,a,h,l,c,u,_;if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const f=t+e*this.columns,p=this.sprites[f];if(p){if(i){const g=p.clone();return g.flipHorizontal=(s=i.flipHorizontal)!=null?s:g.flipHorizontal,g.flipVertical=(n=i.flipVertical)!=null?n:g.flipVertical,g.width=(o=i.width)!=null?o:g.width,g.height=(a=i.height)!=null?a:g.height,g.rotation=(h=i.rotation)!=null?h:g.rotation,g.scale=(l=i.scale)!=null?l:g.scale,g.opacity=(c=i.opacity)!=null?c:g.opacity,g.tint=(u=i.tint)!=null?u:g.tint,g.origin=(_=i.origin)!=null?_:g.origin,g}return p}throw Error(`Invalid sprite coordinates (${t}, ${e})`)}getTiledSprite(t,e,i){if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const s=t+e*this.columns,n=this.sprites[s];if(n)return li.fromSprite(n,i);throw Error(`Invalid sprite coordinates (${t}, ${e})`)}static fromImageSourceWithSourceViews(t){const e=t.sourceViews.map(i=>new kt({image:t.image,sourceView:i}));return new be({sprites:e})}static fromImageSource(t){var e;const i=[];t.spacing=(e=t.spacing)!=null?e:{};const{image:s,grid:{rows:n,columns:o,spriteWidth:a,spriteHeight:h},spacing:{originOffset:l,margin:c}}=t;let u,_;l instanceof v?_={x:l.x,y:l.y}:l&&(_={x:l.x,y:l.y}),c instanceof v?u={x:c.x,y:c.y}:c&&(u={x:c.x,y:c.y});const f={x:0,y:0,..._},p={x:0,y:0,...u};for(let g=0;g<o;g++)for(let w=0;w<n;w++)i[g+w*o]=new kt({image:s,sourceView:{x:g*a+p.x*g+f.x,y:w*h+p.y*w+f.y,width:a,height:h},destSize:{height:h,width:a}});return new be({sprites:i,rows:n,columns:o})}clone(){return new be({sprites:this.sprites.map(t=>t.clone()),rows:this.rows,columns:this.columns})}}const Nh="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAABACAYAAAD1Xam+AAAAAXNSR0IArs4c6QAABlFJREFUeJztndmy4yoMRcWt/v9fdr8EWoDAaDD4JntVpeqcxBrMIGQDNhEAAAAAAAAAAAAAAOCrSbMfr+u6yoEpTY+906GV57YtPkjyXj9WZZ+wHWHfo2N3/bU6Tte9Rv6ptruqRyMvKvvIX/zY3I/vjLeqsg6l/CWdp0KHKO/1Y1H2EdsR9j06Ntdfp+N03SvkH2u7i3pu5XkQ+DNTkgNJSok+/183xpcdWZHjgUzpQ2pGD67vaf//KRAGAq3tdhCy2tcMQKPyXyz7iPqrdBjbX5h9g7xbtvWf4ZJvM4D/BKG24Sd+IkQ0TC9aW5NM5FbO2HgrPVzW2vmN50DZNv/QWtl5bfPy85SBtdy9dFmjsf2F2SehTBVE+u+tkE5+lAGcJlFwGuodwRRU2Qe3rx0FhPNflc3HWC7BEh8EDGVR5IMCiLnDONtPp87qhxVH/S/LvzUAuDs/kyGimA5oSONKR1w8vsLpv+v+S9vhmS71JRiX1xB5CWZNw7m6rMrllMag/RJyWb67BEgpDVMWSydc+K47pr35w05kWd7ReEq6116KaG4CsbJ7OmV9PdZLEKkONiC1/7ZONVgDsajLIJPYp2OUAXRpnPcGmnIE6eSK4nv5YQqqSYO52JqnYfYj/PdQXQIY7XszuMofMgZRT/1LdeC5h2I5/0EdWDMY2Yb05WDE1RodVdpSA5r85slArAVnSf+89iP896St0f5bZKVA7Gk/3ja8q+152/+wrLqBWZTem3IBADbRBoDuHgAA4HdAAADgh0EAAOCHQQAA4IdBAADgh0EAAOCHuVsKbJ3P9M7jjuxHzGfv8j9iDt47Dx7hP8cjq5F/o/0T62Aer//ZOgDrajBp6aNlOWTEajKLjgj/Pcs/vfZD/a++3Pc8hNfZ966EVeh5vP75luDRJUAl0KzJfnopaqbaTuzZiulc2BS5lltFXntu3dcQsXadl59Wn1H+dfYNtrt2d6D/LDF9HkCQw6eXFbr8P9X5W/un5Ol8gz1t39p5pWOPn0vLynbgdnfe8maEQw+UIPJdfxdOd/4oTtVD0IYg8wDywGas0I04T5O3P8/qf2UWwPpkn1PbOT1bN2tFe59EM7TvKf+TRFw+erZ2ey4hpS3hp9qBkqq/tjsSU1OYqucBWB1yynt5QxC42Mdk30pAEIio//zRG3feBzLUX+TTjCKwlH83aI/KbpQBVEHgUGF0j/SitcLofHem8q6AyH0wBhFv4WszuOjy0yK2vc/oRWQoP2X9ve78jfaLnpncbBqQSC6s0HnIRT0a2yNZjfxT8+ir8t+yDsDTWaS6X70GP33+d77stp+I5HtBdwEAAPBl8ECApcAA/DBvfSowAGAB7/05ZAAA/DAIAADMMU3fOuS2ggAAwBjrorKoxWiPBxHMAgAg490Ts0VeePdA+ZfJDKcCh7sBqY88mmjklZeOt9iXPrvx2I2QPRnN2/qzyJ84h4gNcbtfasq5mM1rZr+bBWh2A+bIIX13Z9wqL+nQvFno7v3oq4tJItCed7isUT6C/I7BUn9KP95wDicYBYpcjncrO2c/dmW4tBtw4RiRld1IDxDyYsoXMHxF1w3dyz0Nne8033AOFsT6VgRCafl89fenTZUfbm8CGhrgdDcS7anAsvnkkP0IeCfQ+JzYunky6jhNYj5bl7++4fJvN9WDSKS/292A0wyANyKDI91bfkm3kcH7ckaP/SKW/VHKRZAcI14pP3beu0fPyn/DuZQbWMogNnsc16sziE96f7H/iai7uTf0/3N8lwFz/e13T00Djt4OrInCnkeChXT+qOcKOLA21tJpsv/G8/COnGnw97J9QwbTvd6djYSv7fxEVTuV/LzNhj7nOawv6bfbAGCYEpQ6HxFtuxs6sq9tzOYHobQ6Nje+6vo5BwFrPZ4OgMayS4PPt1NlzdLfbRCYBoBc+NaO4JWPwLEf33oN3unY3InKPQBW6Z7nEZzEmrl4iZjC804lqgePPEOguQcwWghUphxm343wyt/pWpWR0OrR+jvyxavHajfb9pTjbt9bH07Z5/expM4TLWfwb7QQqMoC+UDWXZo/4RgA38LOgUvLJAAQ1Td9y9//0ylxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB+g79apuVUsS5ZmwAAAABJRU5ErkJggg==";class un{constructor(){this.fontSheet=Nh,this.size=16,this.load()}load(){return this._imageSource=new Gt(this.fontSheet),this._imageSource.load().then(()=>{this._spriteSheet=be.fromImageSource({image:this._imageSource,grid:{rows:4,columns:16,spriteWidth:16,spriteHeight:16}}),this._spriteFont=new Oi({alphabet:`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,!'&."?-()+# `,caseInsensitive:!0,spriteSheet:this._spriteSheet,spacing:-6})})}write(t,e,i){this._imageSource.isLoaded()&&this._spriteFont.render(t,e,null,i.x,i.y)}}class Wh{constructor(t,e){this._gl=t,this._texture=e}use(){const t=this._gl;t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._texture)}disable(){const t=this._gl;t.bindTexture(t.TEXTURE_2D,null)}}class Hi{constructor(t){this.antialias=!1,this.samples=1;var e,i;this._gl=t.gl,this.width=t.width,this.height=t.height,this.transparency=t.transparency,this.antialias=(e=t.antialias)!=null?e:this.antialias,this.samples=(i=t.samples)!=null?i:this._gl.getParameter(this._gl.MAX_SAMPLES);const s=this._gl;s.drawingBufferFormat?this.bufferFormat=s.drawingBufferFormat:this.transparency?this.bufferFormat=s.RGBA8:this.bufferFormat=s.RGB8,this._setupRenderBuffer(),this._setupFramebuffer()}setResolution(t,e){const i=this._gl;this.width=t,this.height=e,i.bindTexture(i.TEXTURE_2D,this._frameTexture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),this._renderBuffer&&(i.bindRenderbuffer(i.RENDERBUFFER,this._renderBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,Math.min(this.samples,i.getParameter(i.MAX_SAMPLES)),this.bufferFormat,this.width,this.height))}get renderBuffer(){return this._renderBuffer}get renderFrameBuffer(){return this._renderFrameBuffer}get frameBuffer(){return this._frameBuffer}get frameTexture(){return this._frameTexture}_setupRenderBuffer(){if(this.antialias){const t=this._gl;this._renderBuffer=t.createRenderbuffer(),this._renderFrameBuffer=t.createFramebuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this._renderBuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,Math.min(this.samples,t.getParameter(t.MAX_SAMPLES)),this.bufferFormat,this.width,this.height),t.bindFramebuffer(t.FRAMEBUFFER,this._renderFrameBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,this._renderBuffer)}}_setupFramebuffer(){const t=this._gl;this._frameTexture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this._frameTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);const e=t.COLOR_ATTACHMENT0;this._frameBuffer=t.createFramebuffer(),t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,e,t.TEXTURE_2D,this._frameTexture,0),this.disable()}toRenderSource(){return this.renderBuffer&&this.blitRenderBufferToFrameBuffer(),new Wh(this._gl,this._frameTexture)}blitToScreen(){const t=this._gl;this._renderBuffer?(t.bindFramebuffer(t.READ_FRAMEBUFFER,this.renderFrameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR)):(t.bindFramebuffer(t.READ_FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR))}blitRenderBufferToFrameBuffer(){if(this._renderBuffer){const t=this._gl;t.bindFramebuffer(t.READ_FRAMEBUFFER,this.renderFrameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,this.frameBuffer),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR)}}copyToTexture(t){const e=this._gl;this._renderBuffer&&this.blitRenderBufferToFrameBuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.bindTexture(e.TEXTURE_2D,t),e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,this.width,this.height,0)}use(){const t=this._gl;this.antialias?t.bindFramebuffer(t.FRAMEBUFFER,this._renderFrameBuffer):t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.viewport(0,0,this.width,this.height)}disable(){const t=this._gl;t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindTexture(t.TEXTURE_2D,null)}}const Gh=`#version 300 es
|
|
38
|
+
Read more here: https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#understand_system_limits`),!0)}};ci._LOGGER=R.getInstance(),ci.filtering=mt.Blended,ci.wrapping={x:_t.Clamp,y:_t.Clamp},ci._MAX_TEXTURE_SIZE=4096;let Xe=ci;const z={Filtering:"filtering",WrappingX:"wrapping-x",WrappingY:"wrapping-y"};class qt{constructor(t,e,i){this._logger=R.getInstance(),this.data=new Image,this._readyFuture=new wt,this.ready=this._readyFuture.promise,this.path=t;let s=!1,n;typeof e=="boolean"?s=e:{filtering:i,wrapping:n,bustCache:s}={...e},this._resource=new li(t,"blob",s),this.filtering=i!=null?i:this.filtering,typeof n=="string"?this.wrapping={x:n,y:n}:this.wrapping=n!=null?n:this.wrapping,t.endsWith(".gif")&&this._logger.warn(`Use the ex.Gif type to load gifs, you may have mixed results with ${t} in ex.ImageSource. Fully supported: svg, jpg, bmp, and png`)}get width(){return this.image.naturalWidth}get height(){return this.image.naturalHeight}isLoaded(){return this._src||(this._src=this.data.src),!!this._src}get image(){return this.data}static fromHtmlImageElement(t,e){const i=new qt("");if(i._src="image-element",i.data=t,i.data.setAttribute("data-original-src","image-element"),e!=null&&e.filtering?i.data.setAttribute(z.Filtering,e==null?void 0:e.filtering):i.data.setAttribute(z.Filtering,mt.Blended),e!=null&&e.wrapping){let s;typeof e.wrapping=="string"?s={x:e.wrapping,y:e.wrapping}:s={x:e.wrapping.x,y:e.wrapping.y},i.data.setAttribute(z.WrappingX,s.x),i.data.setAttribute(z.WrappingY,s.y)}else i.data.setAttribute(z.WrappingX,_t.Clamp),i.data.setAttribute(z.WrappingY,_t.Clamp);return Xe.checkImageSizeSupportedAndLog(t),i._readyFuture.resolve(t),i}static fromHtmlCanvasElement(t,e){const i=new qt("");if(i._src="canvas-element-blob",i.data.setAttribute("data-original-src","canvas-element-blob"),e!=null&&e.filtering?i.data.setAttribute(z.Filtering,e==null?void 0:e.filtering):i.data.setAttribute(z.Filtering,mt.Blended),e!=null&&e.wrapping){let s;typeof e.wrapping=="string"?s={x:e.wrapping,y:e.wrapping}:s={x:e.wrapping.x,y:e.wrapping.y},i.data.setAttribute(z.WrappingX,s.x),i.data.setAttribute(z.WrappingY,s.y)}else i.data.setAttribute(z.WrappingX,_t.Clamp),i.data.setAttribute(z.WrappingY,_t.Clamp);return Xe.checkImageSizeSupportedAndLog(t),t.toBlob(s=>{const n=URL.createObjectURL(s);i.image.onload=()=>{URL.revokeObjectURL(n),i.data=i.image,i._readyFuture.resolve(i.image)},i.image.src=n}),i}static fromSvgString(t,e){const i=new Blob([t],{type:"image/svg+xml"}),s=URL.createObjectURL(i);return new qt(s,e)}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){var t,e,i,s;if(this.isLoaded())return this.data;try{let n;if(this.path.includes("data:image/"))n=this.path;else{const h=await this._resource.load();n=URL.createObjectURL(h)}const o=new Image,a=new wt;o.onload=()=>a.resolve(),o.src=n,o.setAttribute("data-original-src",this.path),await a.promise,this.data=o,Xe.checkImageSizeSupportedAndLog(this.data)}catch(n){throw`Error loading ImageSource from path '${this.path}' with error [${n.message}]`}return this.data.setAttribute(z.Filtering,this.filtering),this.data.setAttribute(z.WrappingX,(e=(t=this.wrapping)==null?void 0:t.x)!=null?e:_t.Clamp),this.data.setAttribute(z.WrappingY,(s=(i=this.wrapping)==null?void 0:i.y)!=null?s:_t.Clamp),this._readyFuture.resolve(this.data),this.data}toSprite(t){return zt.from(this,t)}unload(){this.data=new Image}}class Hi extends st{constructor(t){super(t),this._text="",this.alphabet="",this.shadow=void 0,this.caseInsensitive=!1,this.spacing=0,this.lineHeight=void 0,this._logger=R.getInstance();const{alphabet:e,spriteSheet:i,caseInsensitive:s,spacing:n,shadow:o,lineHeight:a}=t;this.alphabet=e,this.spriteSheet=i,this.caseInsensitive=s!=null?s:this.caseInsensitive,this.spacing=n!=null?n:this.spacing,this.shadow=o!=null?o:this.shadow,this.lineHeight=a!=null?a:this.lineHeight}_getCharacterSprites(t){const e=[],i=this.caseInsensitive?t.toLocaleLowerCase():t,s=this.caseInsensitive?this.alphabet.toLocaleLowerCase():this.alphabet;for(let n=0;n<i.length;n++){const o=i[n];let a=s.indexOf(o);a===-1&&(a=0,this._logger.warnOnce(`SpriteFont - Cannot find letter '${o}' in configured alphabet '${s}'.`),this._logger.warnOnce("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."));const h=this.spriteSheet.sprites[a];h?e.push(h):(this._logger.warnOnce(`SpriteFont - Cannot find sprite for '${o}' at index '${a}' in configured SpriteSheet`),this._logger.warnOnce("There maybe be more issues in the SpriteFont configuration. No additional warnings will be logged."))}return e}measureText(t,e){const i=this._getLinesFromText(t,e),s=i.reduce((h,l)=>h.length>l.length?h:l),n=this._getCharacterSprites(s);let o=0,a=0;for(const h of n)o+=h.width+this.spacing,a=Math.max(a,h.height);return F.fromDimension(o*this.scale.x,a*i.length*this.scale.y,w.Zero)}_drawImage(t,e,i,s){var n;let o=0,a=0,h=0;const l=this._getLinesFromText(this._text,s);for(const c of l){for(const u of this._getCharacterSprites(c))u.draw(t,e+o,i+a),o+=u.width+this.spacing,h=Math.max(h,u.height);o=0,a+=(n=this.lineHeight)!=null?n:h}}render(t,e,i,s,n,o){this._text=e;const a=this.measureText(e,o);this.width=a.width,this.height=a.height,this.shadow&&(t.save(),t.translate(this.shadow.offset.x,this.shadow.offset.y),this._preDraw(t,s,n),this._drawImage(t,0,0,o),this._postDraw(t),t.restore()),this._preDraw(t,s,n),this._drawImage(t,0,0,o),this._postDraw(t)}clone(){return new Hi({alphabet:this.alphabet,spriteSheet:this.spriteSheet,spacing:this.spacing})}_getLinesFromText(t,e){var i;if(this._cachedText===t&&this._cachedRenderWidth===e&&((i=this._cachedLines)!=null&&i.length))return this._cachedLines;const s=t.split(`
|
|
39
|
+
`);if(e==null)return s;for(let n=0;n<s.length;n++){let o=s[n],a="";if(this.measureText(o).width>e){for(;this.measureText(o).width>e;)a=o[o.length-1]+a,o=o.slice(0,-1);s[n]=o,s[n+1]=a}}return this._cachedText=t,this._cachedLines=s,this._cachedRenderWidth=e,s}}class di extends zt{constructor(t){super({image:t.image,sourceView:t.sourceView,destSize:{width:t.width,height:t.height},flipHorizontal:t.flipHorizontal,flipVertical:t.flipVertical,rotation:t.rotation,scale:t.scale,opacity:t.opacity,tint:t.tint,origin:t.origin}),this._ready=new wt,this.ready=this._ready.promise,this._options=t,this.image.isLoaded()?this._applyTiling():this.image.ready.then(()=>this._applyTiling())}static fromSprite(t,e){return new di({sourceView:{...t.sourceView},width:t.width,height:t.height,...e,image:t.image})}_applyTiling(){const{width:t,height:e,filtering:i,wrapping:s}={...this._options},n=document.createElement("canvas");n.width=this.sourceView.width,n.height=this.sourceView.height,n.getContext("2d").drawImage(this.image.image,this.sourceView.x,this.sourceView.y,this.sourceView.width,this.sourceView.height,0,0,this.sourceView.width,this.sourceView.height);const a=qt.fromHtmlCanvasElement(n,{wrapping:s!=null?s:_t.Repeat,filtering:i});t&&(this.destSize.width=t,this.sourceView.width=t),e&&(this.destSize.height=e,this.sourceView.height=e),this.sourceView.x=0,this.sourceView.y=0,this.image=a,this.image.ready.then(()=>this._ready.resolve())}}class ye{constructor(t){this.sprites=[];const{sprites:e,rows:i,columns:s}=t;this.sprites=e,this.rows=i!=null?i:1,this.columns=s!=null?s:this.sprites.length}getSprite(t,e,i){var s,n,o,a,h,l,c,u,_;if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const f=t+e*this.columns,m=this.sprites[f];if(m){if(i){const p=m.clone();return p.flipHorizontal=(s=i.flipHorizontal)!=null?s:p.flipHorizontal,p.flipVertical=(n=i.flipVertical)!=null?n:p.flipVertical,p.width=(o=i.width)!=null?o:p.width,p.height=(a=i.height)!=null?a:p.height,p.rotation=(h=i.rotation)!=null?h:p.rotation,p.scale=(l=i.scale)!=null?l:p.scale,p.opacity=(c=i.opacity)!=null?c:p.opacity,p.tint=(u=i.tint)!=null?u:p.tint,p.origin=(_=i.origin)!=null?_:p.origin,p}return m}throw Error(`Invalid sprite coordinates (${t}, ${e})`)}getTiledSprite(t,e,i){if(t>=this.columns||t<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), x: ${t} should be between 0 and ${this.columns-1} columns`);if(e>=this.rows||e<0)throw Error(`No sprite exists in the SpriteSheet at (${t}, ${e}), y: ${e} should be between 0 and ${this.rows-1} rows`);const s=t+e*this.columns,n=this.sprites[s];if(n)return di.fromSprite(n,i);throw Error(`Invalid sprite coordinates (${t}, ${e})`)}static fromImageSourceWithSourceViews(t){const e=t.sourceViews.map(i=>new zt({image:t.image,sourceView:i}));return new ye({sprites:e})}static fromImageSource(t){var e;const i=[];t.spacing=(e=t.spacing)!=null?e:{};const{image:s,grid:{rows:n,columns:o,spriteWidth:a,spriteHeight:h},spacing:{originOffset:l,margin:c}}=t;let u,_;l instanceof w?_={x:l.x,y:l.y}:l&&(_={x:l.x,y:l.y}),c instanceof w?u={x:c.x,y:c.y}:c&&(u={x:c.x,y:c.y});const f={x:0,y:0,..._},m={x:0,y:0,...u};for(let p=0;p<o;p++)for(let x=0;x<n;x++)i[p+x*o]=new zt({image:s,sourceView:{x:p*a+m.x*p+f.x,y:x*h+m.y*x+f.y,width:a,height:h},destSize:{height:h,width:a}});return new ye({sprites:i,rows:n,columns:o})}clone(){return new ye({sprites:this.sprites.map(t=>t.clone()),rows:this.rows,columns:this.columns})}}const Nh="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADACAYAAABS3GwHAAAAAXNSR0IB2cksfwAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB+kLGhIwLEfXSw4AAAaVSURBVHja7d3BduQoDIVhas68/ytnNtOz6DPVBiEBtr9/l8RxMBVzQUiX1gAAAAC8iU/WjX5+fn5aa+3z+XxGruv9vez2RH/+6/v/dWBnu6PPOfsc+HO//qUr8Gb+vsub2qsYv4/Q0RF7VBFWK9jvzzPajurr7wIFAAU4eeS/+vrbCHg1Yr1tTm0t8f/PSQHQRIEWzllXrwF65/6jUayrOfnq/pxt/1W0K/t5q+/f2z8UANYAj5K0wTVBdP/ibnPn0TVT9XOu6q+rdlMAUIAT3+hoFChr5H5aVKR3P+H0NWH250cBQAFOfONH5/Kr5qzfdpZXPX9Wv1df3+wEA0B7X5Zlb4yfAgAAAAAAAAAAAABtUUXYroqqrAqv3uzPaEVSdUVVdf+0l/r/fOsfO8FoskETndKy8rdX5etX+eKMKuHq/lnlC5Tty5Q1I+EMB/TUA/S6IGS7JWR7aGatSZAzUo+ukUY9Wns/PwqAJgqU4LRW5X7c+8Zn+8yMRo2y5tJZUaDT3BdO+fuc4YA/rQFWvcmzUZUrH5vonDOqINVRmd5a6OznzaqZznaGy4oKUQBQgJVzxlkntqfMWXe3v2ofoDdas3o/gTMckJkLNDqHW5UbE/X2rM69OSVX6q0nxFgDAMDTfX4aXyAAAAAAAAAAAAAgwRcoK3do9f1Py2WKukJUV8BluVTscgnhCwS0CV+gX9/PeiOr3/is61fV/kazK3edWJ/9d6LKltX/FAAUYOWbeerJ9Nq/px7gyoWkuh0UABTgJLfe09szW4GVFZ26+8gf/fyjUScKAIwoQO/cf3TEqnZ7rp6LZ0dtshzgqkby7BG32oeIAgCZa4BRH5hVc9m7uxS0m0atnqYEFAAUoOdNyt75u7p/tD2nuCtX9+dVnPybE9tse66U4BS36t7npQAAAAAAAAAAAAAAAKA9+KT4U3x7Vp1ZVuVScer1VefyRrNEo6c/qggD2sJzgk/3Bdrlk/MUF4psp7mqfP5ZRzoKAOx0heALFPPHuaqXqPLoPKVibLQfKAAQUYC7V4S9rfZ298i/SgmitekUAMiIAlXP3bPcnk+Zo0fbmx3l2O30dno0jgKAArQXuRHvfo5R1+OskXS3896pnycFAAU40ffm1PtHozTZnpbZUbjRHePqqOCq+1IANNmghW+eXBycDAUAAAAAAAAA8DZ+/kVPoNkHANo7d4Lvmoe+K4cl68yvXdmeWbXFd8sAoABoskFfVHNbpSS7FS4rO7ZtPrmdAgB3qggbzS/ffe5vlQtG1jnEs897F2/OrH6Z/f+hAKAAFVGH6EhW7ZY82v5vc9tZt+TZ/smae896c+5yxMv6f6AAoADtxd6g2ecKtIdGvZ4aHaQAoABPise/3WW6WmmfpoAUABRg5c5flTt09CysXb5DVWuX6jn76LkFuxS3tx0UAMDz6y6u/t5b60AoANQDYL0X5+66CNEwCgAAAAAAAAAAzQ4rgv2bfV2zDwA09QB41rnNuyvtKAAoQIXvSm/Vf/b9s10bql0qVl9/9wq5bGc+CgAKUOm7En2DR9/ou7s2jPrjZNU+jyrJ6ufvVbRo+ygAKMAJfj6n1paujqKsUrK7tafXIY4CAE/aB9g9N101R89aC51+Us8uxf32NQUABajw7Vl97sDo2iHa/t6ReVQxen12ou2/2icZ7denKBIFACqy8mRlyoptXCEAUSDw+aEAAAAAAAAAANDOOh9gNEfjbVmGszXTu/vp6Z9X7y64fQBQAMRPTL/6/resz1NOinn7jjEFQJMLtGENcMr1WXnxV3POqE9P1ogePVd4tH6htz+z/X0oAJBZEVZd/T86AkVHntXPs6smePTnUT+gbJ+iq0q3amc7CgAKcOJIOTqnjo6s2b452ddFPVNno0yjI3S1x2d0LUcBgJ59gFmPyNmoS+8aYPS6rJ3a2X2AqDuEeL0oELBuJziau3JKnP609qzKBdq9ZqAAAAAAAAAAAAAAAAAA7dhcoOocmuzrs3JjsnKMTsthyvocRnOfstpVla0sFwhNRVggDz16umL0ZPCseoRo9uPo/UfrFaL9H72+Jbs+RGuIe38vek7zVU05BQAFyKgZrXIkm53j3sWfKOoC8dSTIGfPK3ZSPHDSKZGzc/TomiFrTbL6xPRVrhS7vUmj/lCzUSdrAGBmH6C6Nnb1PsDTPVB3nYeQve8RjS5ZAwDOB0A79NyFLOe3UV8pCgAKAJx6hlfWzr9cIAAAAAAAAAAv5R8sG/KSRHx9UQAAAABJRU5ErkJggg==",Ni=class yt{static registerDebugConfig(t){yt.config=t}static draw(t){this._drawCalls.push(t)}static drawPoint(t,e){yt.draw(i=>{i.debug.drawPoint(t,e)})}static drawLine(t,e,i){yt.draw(s=>{s.debug.drawLine(t,e,i)})}static drawLines(t,e){t.length>1&&yt.draw(i=>{for(let s=0;s<t.length-1;s++)i.debug.drawLine(t[s],t[s+1],e)})}static drawText(t,e){yt.draw(i=>{i.debug.drawText(t,e)})}static drawPolygon(t,e){t.length>1&&yt.draw(i=>{const s=t[0],n=[...t,s];for(let o=0;o<n.length-1;o++)i.debug.drawLine(n[o],n[o+1],e)})}static drawCircle(t,e,i){const{color:s,strokeColor:n,width:o}={color:T.Black,strokeColor:void 0,width:void 0,...i};yt.draw(a=>{a.debug.drawCircle(t,e,s,n,o)})}static drawBounds(t,e){yt.draw(i=>{i.debug.drawRect(t.left,t.top,t.width,t.height,e)})}static drawRay(t,e){const{distance:i,color:s}={color:T.Blue,distance:10,...e};yt.draw(n=>{n.z=yt.config.settings.z.ray;const o=t.pos,a=t.pos.add(t.dir.scale(i));n.debug.drawLine(o,a,{color:s})})}static flush(t){t.save(),t.z=yt.z;for(const e of yt._drawCalls)e(t);t.restore(),yt.clear()}static clear(){yt._drawCalls.length=0}};Ni._drawCalls=[],Ni.z=1/0,Ni.config={settings:{text:{foreground:T.Black,background:T.Transparent,border:T.Transparent},z:{text:Number.POSITIVE_INFINITY,point:Number.MAX_SAFE_INTEGER-1,ray:Number.MAX_SAFE_INTEGER-1,dashed:Number.MAX_SAFE_INTEGER-2,solid:Number.MAX_SAFE_INTEGER-3}}};let Tt=Ni;class fn{constructor(){this.fontSheet=Nh,this.size=16,this.foregroundColor=Tt.config.settings.text.foreground,this.backgroundColor=Tt.config.settings.text.background,this.borderColor=Tt.config.settings.text.border,this.load()}load(){return this._imageSource=new qt(this.fontSheet),this._imageSource.load().then(()=>{this._spriteSheet=ye.fromImageSource({image:this._imageSource,grid:{rows:8,columns:16,spriteWidth:10,spriteHeight:24},spacing:{originOffset:{x:2,y:0},margin:{x:2,y:0}}}),this._spriteFont=new Hi({alphabet:" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~?",caseInsensitive:!1,spriteSheet:this._spriteSheet,spacing:2})})}write(t,e,i,s,n){if(this._imageSource.isLoaded()){const o=t.getTransform().getPosition();t.save(),t.resetTransform(),t.z=Tt.config.settings.z.text,t.translate(o.x,o.y);const a=this._spriteFont.measureText(e),h=s!=null?s:this.foregroundColor,l=n!=null?n:this.backgroundColor;t.save(),t.z=Tt.config.settings.z.solid,t.drawRectangle(i,a.width,a.height,l,this.borderColor,1),t.restore(),t.tint=h,this._spriteFont.render(t,e,null,i.x,i.y),t.restore()}}}class Wh{constructor(t,e){this._gl=t,this._texture=e}use(){const t=this._gl;t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this._texture)}disable(){const t=this._gl;t.bindTexture(t.TEXTURE_2D,null)}}class Wi{constructor(t){this.antialias=!1,this.samples=1;var e,i;this._gl=t.gl,this.width=t.width,this.height=t.height,this.transparency=t.transparency,this.antialias=(e=t.antialias)!=null?e:this.antialias,this.samples=(i=t.samples)!=null?i:this._gl.getParameter(this._gl.MAX_SAMPLES);const s=this._gl;s.drawingBufferFormat?this.bufferFormat=s.drawingBufferFormat:this.transparency?this.bufferFormat=s.RGBA8:this.bufferFormat=s.RGB8,this._setupRenderBuffer(),this._setupFramebuffer()}setResolution(t,e){const i=this._gl;this.width=t,this.height=e,i.bindTexture(i.TEXTURE_2D,this._frameTexture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),this._renderBuffer&&(i.bindRenderbuffer(i.RENDERBUFFER,this._renderBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,Math.min(this.samples,i.getParameter(i.MAX_SAMPLES)),this.bufferFormat,this.width,this.height))}get renderBuffer(){return this._renderBuffer}get renderFrameBuffer(){return this._renderFrameBuffer}get frameBuffer(){return this._frameBuffer}get frameTexture(){return this._frameTexture}_setupRenderBuffer(){if(this.antialias){const t=this._gl;this._renderBuffer=t.createRenderbuffer(),this._renderFrameBuffer=t.createFramebuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this._renderBuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,Math.min(this.samples,t.getParameter(t.MAX_SAMPLES)),this.bufferFormat,this.width,this.height),t.bindFramebuffer(t.FRAMEBUFFER,this._renderFrameBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,this._renderBuffer)}}_setupFramebuffer(){const t=this._gl;this._frameTexture=t.createTexture(),t.bindTexture(t.TEXTURE_2D,this._frameTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);const e=t.COLOR_ATTACHMENT0;this._frameBuffer=t.createFramebuffer(),t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,e,t.TEXTURE_2D,this._frameTexture,0),this.disable()}toRenderSource(){return this.renderBuffer&&this.blitRenderBufferToFrameBuffer(),new Wh(this._gl,this._frameTexture)}blitToScreen(){const t=this._gl;this._renderBuffer?(t.bindFramebuffer(t.READ_FRAMEBUFFER,this.renderFrameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR)):(t.bindFramebuffer(t.READ_FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR))}blitRenderBufferToFrameBuffer(){if(this._renderBuffer){const t=this._gl;t.bindFramebuffer(t.READ_FRAMEBUFFER,this.renderFrameBuffer),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,this.frameBuffer),t.clearBufferfv(t.COLOR,0,[0,0,1,1]),t.blitFramebuffer(0,0,this.width,this.height,0,0,this.width,this.height,t.COLOR_BUFFER_BIT,t.LINEAR)}}copyToTexture(t){const e=this._gl;this._renderBuffer&&this.blitRenderBufferToFrameBuffer(),e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.bindTexture(e.TEXTURE_2D,t),e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,this.width,this.height,0)}use(){const t=this._gl;this.antialias?t.bindFramebuffer(t.FRAMEBUFFER,this._renderFrameBuffer):t.bindFramebuffer(t.FRAMEBUFFER,this._frameBuffer),t.viewport(0,0,this.width,this.height)}disable(){const t=this._gl;t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindTexture(t.TEXTURE_2D,null)}}const Gh=`#version 300 es
|
|
40
40
|
in vec2 a_position;
|
|
41
41
|
in vec4 a_color;
|
|
42
|
+
in float a_lengthSoFar;
|
|
42
43
|
|
|
43
44
|
out lowp vec4 v_color;
|
|
45
|
+
out float v_lengthSoFar;
|
|
44
46
|
|
|
45
47
|
uniform mat4 u_matrix;
|
|
46
48
|
|
|
@@ -50,19 +52,31 @@ void main() {
|
|
|
50
52
|
|
|
51
53
|
// Passthrough the color
|
|
52
54
|
v_color = a_color;
|
|
53
|
-
|
|
55
|
+
|
|
56
|
+
// Passthrough the line length so far
|
|
57
|
+
v_lengthSoFar = a_lengthSoFar;
|
|
58
|
+
}
|
|
59
|
+
`,Vh=`#version 300 es
|
|
54
60
|
precision mediump float;
|
|
55
61
|
|
|
56
62
|
// Color
|
|
57
63
|
in lowp vec4 v_color;
|
|
64
|
+
in float v_lengthSoFar;
|
|
58
65
|
|
|
59
66
|
out vec4 fragColor;
|
|
60
67
|
|
|
68
|
+
uniform bool u_dashed;
|
|
69
|
+
|
|
61
70
|
void main() {
|
|
62
71
|
fragColor = v_color;
|
|
63
|
-
}`;class _n extends it{constructor(t){super(),this.color=P.Black,this.thickness=1;const{start:e,end:i,color:s,thickness:n}=t;this.start=e,this.end=i,this.color=s!=null?s:this.color,this.thickness=n!=null?n:this.thickness,this._localBounds=this._calculateBounds();const{width:o,height:a}=this._localBounds;this.width=o,this.height=a}get localBounds(){return this._localBounds}_calculateBounds(){const t=this.end.sub(this.start).normal(),e=this.thickness/2,i=[this.start.add(t.scale(e)),this.end.add(t.scale(e)),this.end.add(t.scale(-e)),this.start.add(t.scale(-e))];return D.fromPoints(i)}_drawImage(t,e,i){t.drawLine(this.start,this.end,this.color,this.thickness)}clone(){return new _n({start:this.start,end:this.end,color:this.color,thickness:this.thickness})}}class Ni extends Dt{constructor(t,e=!0){super(),this.draw=t,this.useTransform=e}}class Wi extends Dt{constructor(t){super(),this.parallaxFactor=x(1,1),this.parallaxFactor=t!=null?t:this.parallaxFactor}}const Xe=class nt{static measureText(t,e,i){const s=$e.getHashCode(e,t);if(nt._MEASURE_CACHE.has(s))return nt._MEASURE_CACHE.get(s);nt._LOGGER.debug("Font text measurement cache miss");const n=e.measureTextWithoutCache(t,i);return nt._MEASURE_CACHE.set(s,n),n}static getTextInstance(t,e,i){const s=$e.getHashCode(e,t,i);let n=nt._TEXT_CACHE.get(s);return n||(n=new $e(e,t,i),nt._TEXT_CACHE.set(s,n),nt._LOGGER.debug("Font text instance cache miss")),nt._TEXT_USAGE.set(n,performance.now()),n}static checkAndClearCache(){const t=[],e=new Set;for(const[s,n]of nt._TEXT_USAGE.entries())if(n+nt.FONT_TIMEOUT<performance.now())nt._LOGGER.debug(`Text cache entry timed out ${s.text}`),t.push(s),s.dispose();else{const o=s.getHashCode(!1);e.add(o)}t.forEach(s=>{nt._TEXT_USAGE.delete(s)}),this._TEXT_CACHE.clear();for(const[s]of this._TEXT_USAGE.entries())this._TEXT_CACHE.set(s.getHashCode(),s);const i=new Map;for(const s of e)nt._MEASURE_CACHE.has(s)&&i.set(s,nt._MEASURE_CACHE.get(s));this._MEASURE_CACHE.clear(),this._MEASURE_CACHE=i}static get cacheSize(){return nt._TEXT_USAGE.size}static clearCache(){for(const[t]of nt._TEXT_USAGE.entries())t.dispose();nt._TEXT_USAGE.clear(),nt._TEXT_CACHE.clear(),nt._MEASURE_CACHE.clear()}};Xe.FONT_TIMEOUT=500,Xe._LOGGER=R.getInstance(),Xe._TEXT_USAGE=new Map,Xe._TEXT_CACHE=new Map,Xe._MEASURE_CACHE=new Map;let Gi=Xe;function qh(r,t,e,i){if(r.parent!==t.parent){const c=r.clone(),u=r.globalPos.clone(),_=r.globalScale.clone(),f=r.globalRotation;c.parent=t.parent,c.globalPos=u,c.globalScale=_,c.globalRotation=f,r=c}let s=t.pos,n=t.scale,o=t.rotation;s=t.pos.scale(e).add(r.pos.scale(1-e)),n=t.scale.scale(e).add(r.scale.scale(1-e));const a=(1-e)*Math.cos(r.rotation)+e*Math.cos(t.rotation),h=(1-e)*Math.sin(r.rotation)+e*Math.sin(t.rotation);o=Math.atan2(h,a);const l=i!=null?i:new Qt;return l.setTransform(s,o,n),l}class fn extends At{constructor(t){super(),this.world=t,this.systemType=Pt.Draw,this._token=0,this._sortedTransforms=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0},this._targetInterpolationTransform=new Qt,this.query=this.world.query([A,j]),this.query.entityAdded$.subscribe(e=>{const i=e.get(A);this._sortedTransforms.push(i),i.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}),this.query.entityRemoved$.subscribe(e=>{const i=e.get(A);i.zIndexChanged$.unsubscribe(this._zIndexUpdate);const s=this._sortedTransforms.indexOf(i);s>-1&&this._sortedTransforms.splice(s,1)})}get sortedTransforms(){return this._sortedTransforms}initialize(t,e){this._camera=e.camera,this._engine=e.engine}preupdate(){this._graphicsContext=this._engine.graphicsContext,this._zHasChanged&&(this._sortedTransforms.sort((t,e)=>t.globalZ-e.globalZ),this._zHasChanged=!1)}update(t){this._token++;let e;Gi.checkAndClearCache(),this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext);for(let i=0;i<this._sortedTransforms.length;i++){const s=this._sortedTransforms[i],n=s.owner;if(n.hasTag("ex.offscreen")||(e=n.get(j),!e.isVisible))continue;e.onPreTransformDraw&&e.onPreTransformDraw(this._graphicsContext,t),n.events.emit("pretransformdraw",new Is(this._graphicsContext,t,n)),s.coordPlane===rt.Screen&&this._graphicsContext.restore(),this._graphicsContext.save(),s.coordPlane===rt.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),e.update(t,this._token);const o=n.get(Wi);if(o){const a=v.One.sub(o.parallaxFactor),h=this._camera.drawPos.scale(a);this._graphicsContext.translate(h.x,h.y)}this._applyTransform(n),e.material&&(this._graphicsContext.material=e.material),e.onPreDraw&&e.onPreDraw(this._graphicsContext,t),n.events.emit("predraw",new ke(this._graphicsContext,t,n)),this._applyOpacity(n),this._drawGraphicsComponent(e,s),e.onPostDraw&&e.onPostDraw(this._graphicsContext,t),n.events.emit("postdraw",new Ue(this._graphicsContext,t,n)),this._graphicsContext.restore(),s.coordPlane===rt.Screen&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext)),e.onPostTransformDraw&&e.onPostTransformDraw(this._graphicsContext,t),n.events.emit("posttransformdraw",new Rs(this._graphicsContext,t,n))}this._graphicsContext.restore()}_drawGraphicsComponent(t,e){var i,s;if(t.isVisible){const n=t.flipHorizontal,o=t.flipVertical,a=t.current,h=(i=t.currentOptions)!=null?i:{};if(a){let l=t.anchor,c=t.offset,u=1,_=1;h!=null&&h.anchor&&(l=h.anchor),h!=null&&h.offset&&(c=h.offset);const f=e.globalScale;u*=a.scale.x*f.x,_*=a.scale.y*f.y;const p=-a.width*l.x+c.x*u,g=-a.height*l.y+c.y*_,w=a.flipHorizontal,m=a.flipVertical;if((n||o)&&(a.flipHorizontal=n?!w:w,a.flipVertical=o?!m:m),a==null||a.draw(this._graphicsContext,p,g),(n||o)&&(a.flipHorizontal=w,a.flipVertical=m),(s=this._engine)!=null&&s.isDebug&&this._engine.debug.graphics.showBounds){const b=x(p,g);if(a instanceof Ne)for(const T of a.members){let C,S=v.Zero;T instanceof it?C=T:(C=T.graphic,S=T.offset),a.useAnchor?C==null||C.localBounds.translate(b.add(S)).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor):C==null||C.localBounds.translate(S).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor)}else a==null||a.localBounds.translate(b).draw(this._graphicsContext,this._engine.debug.graphics.boundsColor)}}}}_applyTransform(t){const e=t.getAncestors();for(let i=0;i<e.length;i++){const s=e[i],n=s==null?void 0:s.get(A),o=s==null?void 0:s.get(W);if(n){let a=n.get();if(o&&this._engine.fixedUpdateTimestep&&o.__oldTransformCaptured&&o.enableFixedUpdateInterpolate){const h=this._engine.currentFrameLagMs/this._engine.fixedUpdateTimestep;a=qh(o.oldTransform,n.get(),h,this._targetInterpolationTransform)}this._graphicsContext.z=n.globalZ,this._graphicsContext.translate(a.pos.x,a.pos.y),this._graphicsContext.scale(a.scale.x,a.scale.y),this._graphicsContext.rotate(a.rotation)}}}_applyOpacity(t){var e;const i=t.getAncestors();for(let s=0;s<i.length;s++){const n=i[s],o=n==null?void 0:n.get(j);this._graphicsContext.opacity*=(e=o==null?void 0:o.opacity)!=null?e:1}}}fn.priority=Nt.Average;class gn extends At{constructor(t){super(),this.world=t,this.systemType=Pt.Draw,this.query=this.world.query([A,j])}initialize(t,e){this._camera=e.camera,this._screen=e.engine.screen}update(){this._worldBounds=this._screen.getWorldBounds();let t,e,i;for(let s=0;s<this.query.entities.length;s++){const n=this.query.entities[s];e=n.get(j),t=n.get(A),i=n.get(Wi);let o;if(i){const h=v.One.sub(i.parallaxFactor);o=this._camera.pos.scale(h)}const a=this._isOffscreen(t,e,o);a&&!n.hasTag("ex.offscreen")&&(n.events.emit("exitviewport",new Gs(n)),n.addTag("ex.offscreen")),!a&&n.hasTag("ex.offscreen")&&(n.events.emit("enterviewport",new Vs(n)),n.removeTag("ex.offscreen"))}}_isOffscreen(t,e,i){if(e.forceOnScreen)return!1;if(t.coordPlane===rt.World){let s=e.localBounds;i&&(s=s.translate(i));const n=s.transform(t.get().matrix);return!this._worldBounds.overlaps(n)}else return!1}}gn.priority=Nt.Higher;class Vi extends We{constructor(t){var e,i,s;super(t),this._radius=0;const n=(e=t.lineWidth)!=null?e:t.strokeColor?1:0;this.padding=(i=t.padding)!=null?i:2+n/2,this.radius=t.radius,this.filtering=(s=t.filtering)!=null?s:mt.Blended,this.rasterize()}get radius(){return this._radius}set radius(t){this._radius=t,this.width=this._radius*2,this.height=this._radius*2,this.flagDirty()}clone(){return new Vi({radius:this.radius,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.radius>0&&(t.beginPath(),t.arc(this.radius,this.radius,this.radius,0,Math.PI*2),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class ci extends We{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new ci({width:this.width,height:this.height,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.color&&t.fillRect(0,0,this.width,this.height),this.strokeColor&&t.strokeRect(0,0,this.width,this.height)}}class pn extends We{constructor(t){super(t),this._points=[],this.points=t.points,this.filtering=mt.Blended,this.rasterize()}get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce((i,s)=>Math.max(s.x,i),0)-e.x,this.height=this._points.reduce((i,s)=>Math.max(s.y,i),0)-e.y,this.flagDirty()}get minPoint(){const t=this._points.reduce((i,s)=>Math.min(s.x,i),1/0),e=this._points.reduce((i,s)=>Math.min(s.y,i),1/0);return x(t,e)}clone(){return new pn({points:this.points.map(t=>t.clone()),...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){if(this.points&&this.points.length){t.beginPath();const e=this.minPoint.negate(),i=this.points[0].add(e);t.moveTo(i.x,i.y),this.points.forEach(s=>{t.lineTo(s.x+e.x,s.y+e.y)}),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}class qi extends We{constructor(t={}){super(t),this._options=t}get ctx(){return this._ctx}clone(){return new qi({...this._options,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){var e,i;(e=this._options)!=null&&e.draw&&((i=this._options)==null||i.draw(t)),this._options.cache||this.flagDirty()}}var zr=(r=>(r.Stretch="stretch",r.Tile="tile",r.TileFit="tile-fit",r))(zr||{});class mn extends it{constructor(t){super(t),this._logger=R.getInstance(),this._config=t,this._imgSource=t.source,this._canvasA=document.createElement("canvas"),this._canvasB=document.createElement("canvas"),this._canvasC=document.createElement("canvas"),this._canvasD=document.createElement("canvas"),this._canvasE=document.createElement("canvas"),this._canvasF=document.createElement("canvas"),this._canvasG=document.createElement("canvas"),this._canvasH=document.createElement("canvas"),this._canvasI=document.createElement("canvas"),this._initialize(),this._imgSource.ready.then(()=>{this._initialize()})}setTargetWidth(t,e=!1){this._config.width=t,e&&this._initialize()}setTargetHeight(t,e=!1){this._config.height=t,e&&this._initialize()}setMargins(t,e,i,s,n=!1){this._config.sourceConfig.leftMargin=t,this._config.sourceConfig.topMargin=e,this._config.sourceConfig.rightMargin=i,this._config.sourceConfig.bottomMargin=s,n&&this._initialize()}setStretch(t,e,i=!1){t==="horizontal"?this._config.destinationConfig.horizontalStretch=e:t==="vertical"?this._config.destinationConfig.verticalStretch=e:(this._config.destinationConfig.horizontalStretch=e,this._config.destinationConfig.verticalStretch=e),i&&this._initialize()}getConfig(){return this._config}_drawTile(t,e,i,s,n,o,a){const h=o||0,l=a||0;let c,u,_,f;const p=this._getNumberOfTiles(e.width,i.x,s),g=this._getNumberOfTiles(e.height,i.y,n);for(let w=0;w<p;w++)for(let m=0;m<g;m++){let{tempSize:b,tempPosition:T}=this._calculateParams(w,p,e.width,i.x,this._config.destinationConfig.horizontalStretch);c=b,u=T,{tempSize:b,tempPosition:T}=this._calculateParams(m,g,e.height,i.y,this._config.destinationConfig.verticalStretch),_=b,f=T,t.drawImage(e,0,0,e.width,e.height,h+u,l+f,c,_)}}_drawImage(t,e,i){this._imgSource.isLoaded()?(this._drawTile(t,this._canvasA,new v(this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch),this._drawTile(t,this._canvasB,new v(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,0),this._drawTile(t,this._canvasC,new v(this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,0),this._drawTile(t,this._canvasD,new v(this._config.sourceConfig.leftMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,0,this._config.sourceConfig.topMargin),this._config.destinationConfig.drawCenter&&this._drawTile(t,this._canvasE,new v(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin),this._drawTile(t,this._canvasF,new v(this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._drawTile(t,this._canvasG,new v(this._config.sourceConfig.leftMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,0,this._config.height-this._config.sourceConfig.bottomMargin),this._drawTile(t,this._canvasH,new v(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,this._config.height-this._config.sourceConfig.bottomMargin),this._drawTile(t,this._canvasI,new v(this._config.sourceConfig.rightMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin)):this._logger.warnOnce(`NineSlice ImageSource ${this._imgSource.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.
|
|
72
|
+
if (u_dashed) {
|
|
73
|
+
fragColor.a = smoothstep(0.5, 0.55, fract(v_lengthSoFar / 10.0)); // 10 pixel dashes
|
|
74
|
+
fragColor.rgb *= fragColor.a;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
`;class gn extends st{constructor(t){super(),this.color=T.Black,this.thickness=1;const{start:e,end:i,color:s,thickness:n}=t;this.start=e,this.end=i,this.color=s!=null?s:this.color,this.thickness=n!=null?n:this.thickness,this._localBounds=this._calculateBounds();const{width:o,height:a}=this._localBounds;this.width=o,this.height=a}get localBounds(){return this._localBounds}_calculateBounds(){const t=this.end.sub(this.start).normal(),e=this.thickness/2,i=[this.start.add(t.scale(e)),this.end.add(t.scale(e)),this.end.add(t.scale(-e)),this.start.add(t.scale(-e))];return F.fromPoints(i)}_drawImage(t,e,i){t.drawLine(this.start,this.end,this.color,this.thickness)}clone(){return new gn({start:this.start,end:this.end,color:this.color,thickness:this.thickness})}}class Gi extends Dt{constructor(t,e=!0){super(),this.draw=t,this.useTransform=e}}class Vi extends Dt{constructor(t){super(),this.parallaxFactor=b(1,1),this.parallaxFactor=t!=null?t:this.parallaxFactor}}const Ye=class nt{static measureText(t,e,i){const s=je.getHashCode(e,t);if(nt._MEASURE_CACHE.has(s))return nt._MEASURE_CACHE.get(s);nt._LOGGER.debug("Font text measurement cache miss");const n=e.measureTextWithoutCache(t,i);return nt._MEASURE_CACHE.set(s,n),n}static getTextInstance(t,e,i){const s=je.getHashCode(e,t,i);let n=nt._TEXT_CACHE.get(s);return n||(n=new je(e,t,i),nt._TEXT_CACHE.set(s,n),nt._LOGGER.debug("Font text instance cache miss")),nt._TEXT_USAGE.set(n,performance.now()),n}static checkAndClearCache(){const t=[],e=new Set;for(const[s,n]of nt._TEXT_USAGE.entries())if(n+nt.FONT_TIMEOUT<performance.now())nt._LOGGER.debug(`Text cache entry timed out ${s.text}`),t.push(s),s.dispose();else{const o=s.getHashCode(!1);e.add(o)}t.forEach(s=>{nt._TEXT_USAGE.delete(s)}),this._TEXT_CACHE.clear();for(const[s]of this._TEXT_USAGE.entries())this._TEXT_CACHE.set(s.getHashCode(),s);const i=new Map;for(const s of e)nt._MEASURE_CACHE.has(s)&&i.set(s,nt._MEASURE_CACHE.get(s));this._MEASURE_CACHE.clear(),this._MEASURE_CACHE=i}static get cacheSize(){return nt._TEXT_USAGE.size}static clearCache(){for(const[t]of nt._TEXT_USAGE.entries())t.dispose();nt._TEXT_USAGE.clear(),nt._TEXT_CACHE.clear(),nt._MEASURE_CACHE.clear()}};Ye.FONT_TIMEOUT=500,Ye._LOGGER=R.getInstance(),Ye._TEXT_USAGE=new Map,Ye._TEXT_CACHE=new Map,Ye._MEASURE_CACHE=new Map;let qi=Ye;function qh(r,t,e,i){if(r.parent!==t.parent){const c=r.clone(),u=r.globalPos.clone(),_=r.globalScale.clone(),f=r.globalRotation;c.parent=t.parent,c.globalPos=u,c.globalScale=_,c.globalRotation=f,r=c}let s=t.pos,n=t.scale,o=t.rotation;s=t.pos.scale(e).add(r.pos.scale(1-e)),n=t.scale.scale(e).add(r.scale.scale(1-e));const a=(1-e)*Math.cos(r.rotation)+e*Math.cos(t.rotation),h=(1-e)*Math.sin(r.rotation)+e*Math.sin(t.rotation);o=Math.atan2(h,a);const l=i!=null?i:new Kt;return l.setTransform(s,o,n),l}class pn extends Et{constructor(t){super(),this.world=t,this.systemType=Pt.Draw,this._token=0,this._sortedTransforms=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0},this._targetInterpolationTransform=new Kt,this.query=this.world.query([P,K]),this.query.entityAdded$.subscribe(e=>{const i=e.get(P);this._sortedTransforms.push(i),i.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}),this.query.entityRemoved$.subscribe(e=>{const i=e.get(P);i.zIndexChanged$.unsubscribe(this._zIndexUpdate);const s=this._sortedTransforms.indexOf(i);s>-1&&this._sortedTransforms.splice(s,1)})}get sortedTransforms(){return this._sortedTransforms}initialize(t,e){this._camera=e.camera,this._engine=e.engine}preupdate(){this._graphicsContext=this._engine.graphicsContext,this._zHasChanged&&(this._sortedTransforms.sort((t,e)=>t.globalZ-e.globalZ),this._zHasChanged=!1)}update(t){this._token++;let e;qi.checkAndClearCache(),this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext);for(let i=0;i<this._sortedTransforms.length;i++){const s=this._sortedTransforms[i],n=s.owner;if(n.hasTag("ex.offscreen")||(e=n.get(K),!e.isVisible))continue;e.onPreTransformDraw&&e.onPreTransformDraw(this._graphicsContext,t),n.events.emit("pretransformdraw",new Ms(this._graphicsContext,t,n)),s.coordPlane===rt.Screen&&this._graphicsContext.restore(),this._graphicsContext.save(),s.coordPlane===rt.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),e.update(t,this._token);const o=n.get(Vi);if(o){const a=w.One.sub(o.parallaxFactor),h=this._camera.drawPos.scale(a);this._graphicsContext.translate(h.x,h.y)}this._applyTransform(n),e.material&&(this._graphicsContext.material=e.material),e.onPreDraw&&e.onPreDraw(this._graphicsContext,t),n.events.emit("predraw",new Ue(this._graphicsContext,t,n)),this._applyOpacity(n),this._drawGraphicsComponent(e,s),e.onPostDraw&&e.onPostDraw(this._graphicsContext,t),n.events.emit("postdraw",new ze(this._graphicsContext,t,n)),this._graphicsContext.restore(),s.coordPlane===rt.Screen&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext)),e.onPostTransformDraw&&e.onPostTransformDraw(this._graphicsContext,t),n.events.emit("posttransformdraw",new Fs(this._graphicsContext,t,n))}this._graphicsContext.restore()}_drawGraphicsComponent(t,e){var i,s;if(t.isVisible){const n=t.flipHorizontal,o=t.flipVertical,a=t.current,h=(i=t.currentOptions)!=null?i:{};if(a){let l=t.anchor,c=t.offset,u=1,_=1;h!=null&&h.anchor&&(l=h.anchor),h!=null&&h.offset&&(c=h.offset);const f=e.globalScale;u*=a.scale.x*f.x,_*=a.scale.y*f.y;const m=-a.width*l.x+c.x*u,p=-a.height*l.y+c.y*_,x=a.flipHorizontal,v=a.flipVertical;if((n||o)&&(a.flipHorizontal=n?!x:x,a.flipVertical=o?!v:v),a==null||a.draw(this._graphicsContext,m,p),(n||o)&&(a.flipHorizontal=x,a.flipVertical=v),(s=this._engine)!=null&&s.isDebug&&this._engine.debug.graphics.showBounds){this._graphicsContext.save();const g=b(m,p);if(a instanceof We)for(const y of a.members){let S,A=w.Zero;y instanceof st?S=y:(S=y.graphic,A=y.offset),a.useAnchor?S==null||S.localBounds.translate(g.add(A)).debug(this._graphicsContext,{color:this._engine.debug.graphics.boundsColor,dashed:!0}):S==null||S.localBounds.translate(A).debug(this._graphicsContext,{color:this._engine.debug.graphics.boundsColor,dashed:!0})}else a==null||a.localBounds.translate(g).debug(this._graphicsContext,{color:this._engine.debug.graphics.boundsColor,dashed:!0});this._graphicsContext.restore()}}}}_applyTransform(t){const e=t.getAncestors();for(let i=0;i<e.length;i++){const s=e[i],n=s==null?void 0:s.get(P),o=s==null?void 0:s.get(N);if(n){let a=n.get();if(o&&this._engine.fixedUpdateTimestep&&o.__oldTransformCaptured&&o.enableFixedUpdateInterpolate){const h=this._engine.currentFrameLagMs/this._engine.fixedUpdateTimestep;a=qh(o.oldTransform,n.get(),h,this._targetInterpolationTransform)}this._graphicsContext.z=n.globalZ,this._graphicsContext.translate(a.pos.x,a.pos.y),this._graphicsContext.scale(a.scale.x,a.scale.y),this._graphicsContext.rotate(a.rotation)}}}_applyOpacity(t){var e;const i=t.getAncestors();for(let s=0;s<i.length;s++){const n=i[s],o=n==null?void 0:n.get(K);this._graphicsContext.opacity*=(e=o==null?void 0:o.opacity)!=null?e:1}}}pn.priority=Gt.Average;class mn extends Et{constructor(t){super(),this.world=t,this.systemType=Pt.Draw,this.query=this.world.query([P,K])}initialize(t,e){this._camera=e.camera,this._screen=e.engine.screen}update(){this._worldBounds=this._screen.getWorldBounds();let t,e,i;for(let s=0;s<this.query.entities.length;s++){const n=this.query.entities[s];e=n.get(K),t=n.get(P),i=n.get(Vi);let o;if(i){const h=w.One.sub(i.parallaxFactor);o=this._camera.pos.scale(h)}const a=this._isOffscreen(t,e,o);a&&!n.hasTag("ex.offscreen")&&(n.events.emit("exitviewport",new qs(n)),n.addTag("ex.offscreen")),!a&&n.hasTag("ex.offscreen")&&(n.events.emit("enterviewport",new Xs(n)),n.removeTag("ex.offscreen"))}}_isOffscreen(t,e,i){if(e.forceOnScreen)return!1;if(t.coordPlane===rt.World){let s=e.localBounds;i&&(s=s.translate(i));const n=s.transform(t.get().matrix);return!this._worldBounds.overlaps(n)}else return!1}}mn.priority=Gt.Higher;class Xi extends Ge{constructor(t){var e,i,s;super(t),this._radius=0;const n=(e=t.lineWidth)!=null?e:t.strokeColor?1:0;this.padding=(i=t.padding)!=null?i:2+n/2,this.radius=t.radius,this.filtering=(s=t.filtering)!=null?s:mt.Blended,this.rasterize()}get radius(){return this._radius}set radius(t){this._radius=t,this.width=this._radius*2,this.height=this._radius*2,this.flagDirty()}clone(){return new Xi({radius:this.radius,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.radius>0&&(t.beginPath(),t.arc(this.radius,this.radius,this.radius,0,Math.PI*2),this.color&&t.fill(),this.strokeColor&&t.stroke())}}class ui extends Ge{constructor(t){super(t),this.width=t.width,this.height=t.height,this.rasterize()}clone(){return new ui({width:this.width,height:this.height,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){this.color&&t.fillRect(0,0,this.width,this.height),this.strokeColor&&t.strokeRect(0,0,this.width,this.height)}}class vn extends Ge{constructor(t){super(t),this._points=[],this.points=t.points,this.filtering=mt.Blended,this.rasterize()}get points(){return this._points}set points(t){this._points=t;const e=this.minPoint;this.width=this._points.reduce((i,s)=>Math.max(s.x,i),0)-e.x,this.height=this._points.reduce((i,s)=>Math.max(s.y,i),0)-e.y,this.flagDirty()}get minPoint(){const t=this._points.reduce((i,s)=>Math.min(s.x,i),1/0),e=this._points.reduce((i,s)=>Math.min(s.y,i),1/0);return b(t,e)}clone(){return new vn({points:this.points.map(t=>t.clone()),...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){if(this.points&&this.points.length){t.beginPath();const e=this.minPoint.negate(),i=this.points[0].add(e);t.moveTo(i.x,i.y),this.points.forEach(s=>{t.lineTo(s.x+e.x,s.y+e.y)}),t.lineTo(i.x,i.y),t.closePath(),this.color&&t.fill(),this.strokeColor&&t.stroke()}}}class Yi extends Ge{constructor(t={}){super(t),this._options=t}get ctx(){return this._ctx}clone(){return new Yi({...this._options,...this.cloneGraphicOptions(),...this.cloneRasterOptions()})}execute(t){var e,i;(e=this._options)!=null&&e.draw&&((i=this._options)==null||i.draw(t)),this._options.cache||this.flagDirty()}}var zr=(r=>(r.Stretch="stretch",r.Tile="tile",r.TileFit="tile-fit",r))(zr||{});class wn extends st{constructor(t){super(t),this._logger=R.getInstance(),this._config=t,this._imgSource=t.source,this._canvasA=document.createElement("canvas"),this._canvasB=document.createElement("canvas"),this._canvasC=document.createElement("canvas"),this._canvasD=document.createElement("canvas"),this._canvasE=document.createElement("canvas"),this._canvasF=document.createElement("canvas"),this._canvasG=document.createElement("canvas"),this._canvasH=document.createElement("canvas"),this._canvasI=document.createElement("canvas"),this._initialize(),this._imgSource.ready.then(()=>{this._initialize()})}setTargetWidth(t,e=!1){this._config.width=t,e&&this._initialize()}setTargetHeight(t,e=!1){this._config.height=t,e&&this._initialize()}setMargins(t,e,i,s,n=!1){this._config.sourceConfig.leftMargin=t,this._config.sourceConfig.topMargin=e,this._config.sourceConfig.rightMargin=i,this._config.sourceConfig.bottomMargin=s,n&&this._initialize()}setStretch(t,e,i=!1){t==="horizontal"?this._config.destinationConfig.horizontalStretch=e:t==="vertical"?this._config.destinationConfig.verticalStretch=e:(this._config.destinationConfig.horizontalStretch=e,this._config.destinationConfig.verticalStretch=e),i&&this._initialize()}getConfig(){return this._config}_drawTile(t,e,i,s,n,o,a){const h=o||0,l=a||0;let c,u,_,f;const m=this._getNumberOfTiles(e.width,i.x,s),p=this._getNumberOfTiles(e.height,i.y,n);for(let x=0;x<m;x++)for(let v=0;v<p;v++){let{tempSize:g,tempPosition:y}=this._calculateParams(x,m,e.width,i.x,this._config.destinationConfig.horizontalStretch);c=g,u=y,{tempSize:g,tempPosition:y}=this._calculateParams(v,p,e.height,i.y,this._config.destinationConfig.verticalStretch),_=g,f=y,t.drawImage(e,0,0,e.width,e.height,h+u,l+f,c,_)}}_drawImage(t,e,i){this._imgSource.isLoaded()?(this._drawTile(t,this._canvasA,new w(this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch),this._drawTile(t,this._canvasB,new w(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,0),this._drawTile(t,this._canvasC,new w(this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,0),this._drawTile(t,this._canvasD,new w(this._config.sourceConfig.leftMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,0,this._config.sourceConfig.topMargin),this._config.destinationConfig.drawCenter&&this._drawTile(t,this._canvasE,new w(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin),this._drawTile(t,this._canvasF,new w(this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin-this._config.sourceConfig.topMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin),this._drawTile(t,this._canvasG,new w(this._config.sourceConfig.leftMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,0,this._config.height-this._config.sourceConfig.bottomMargin),this._drawTile(t,this._canvasH,new w(this._config.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.sourceConfig.leftMargin,this._config.height-this._config.sourceConfig.bottomMargin),this._drawTile(t,this._canvasI,new w(this._config.sourceConfig.rightMargin,this._config.sourceConfig.bottomMargin),this._config.destinationConfig.horizontalStretch,this._config.destinationConfig.verticalStretch,this._config.width-this._config.sourceConfig.rightMargin,this._config.height-this._config.sourceConfig.bottomMargin)):this._logger.warnOnce(`NineSlice ImageSource ${this._imgSource.path} is not yet loaded and won't be drawn. Please call .load() or include in a Loader.
|
|
64
78
|
|
|
65
|
-
Read https://excaliburjs.com/docs/imagesource for more information.`)}_initialize(){this._sourceSprite=this._imgSource.image,this._canvasA.width=this._config.sourceConfig.leftMargin,this._canvasA.height=this._config.sourceConfig.topMargin;const t=this._canvasA.getContext("2d");t==null||t.drawImage(this._sourceSprite,0,0,this._canvasA.width,this._canvasA.height,0,0,this._canvasA.width,this._canvasA.height),this._canvasB.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasB.height=this._config.sourceConfig.topMargin;const e=this._canvasB.getContext("2d");e==null||e.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,0,this._canvasB.width,this._canvasB.height,0,0,this._canvasB.width,this._canvasB.height),this._canvasC.width=this._config.sourceConfig.rightMargin,this._canvasC.height=this._config.sourceConfig.topMargin;const i=this._canvasC.getContext("2d");i==null||i.drawImage(this._sourceSprite,this._sourceSprite.width-this._config.sourceConfig.rightMargin,0,this._canvasC.width,this._canvasC.height,0,0,this._canvasC.width,this._canvasC.height),this._canvasD.width=this._config.sourceConfig.leftMargin,this._canvasD.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const s=this._canvasD.getContext("2d");s==null||s.drawImage(this._sourceSprite,0,this._config.sourceConfig.topMargin,this._canvasD.width,this._canvasD.height,0,0,this._canvasD.width,this._canvasD.height),this._canvasE.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasE.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const n=this._canvasE.getContext("2d");n==null||n.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin,this._canvasE.width,this._canvasE.height,0,0,this._canvasE.width,this._canvasE.height),this._canvasF.width=this._config.sourceConfig.rightMargin,this._canvasF.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const o=this._canvasF.getContext("2d");o==null||o.drawImage(this._sourceSprite,this._config.sourceConfig.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin,this._canvasF.width,this._canvasF.height,0,0,this._canvasF.width,this._canvasF.height),this._canvasG.width=this._config.sourceConfig.leftMargin,this._canvasG.height=this._config.sourceConfig.bottomMargin;const a=this._canvasG.getContext("2d");a==null||a.drawImage(this._sourceSprite,0,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasG.width,this._canvasG.height,0,0,this._canvasG.width,this._canvasG.height),this._canvasH.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasH.height=this._config.sourceConfig.bottomMargin;const h=this._canvasH.getContext("2d");h==null||h.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasH.width,this._canvasH.height,0,0,this._canvasH.width,this._canvasH.height),this._canvasI.width=this._config.sourceConfig.rightMargin,this._canvasI.height=this._config.sourceConfig.bottomMargin;const l=this._canvasI.getContext("2d");l==null||l.drawImage(this._sourceSprite,this._sourceSprite.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasI.width,this._canvasI.height,0,0,this._canvasI.width,this._canvasI.height)}clone(){return new mn(this._config)}_getNumberOfTiles(t,e,i){switch(i){case"stretch":return 1;case"tile":return Math.ceil(e/t);case"tile-fit":return Math.ceil(e/t)}}_calculateParams(t,e,i,s,n){switch(n){case"stretch":return{tempPosition:0,tempSize:s};case"tile":return t===e-1?{tempPosition:t*i,tempSize:i-(e*i-s)}:{tempPosition:t*i,tempSize:i};case"tile-fit":const o=s/e;return{tempPosition:t*o,tempSize:o}}}}class vn extends zi{constructor(t){super({...t,frames:t.animation.frames.slice(),strategy:t.animation.strategy,frameDuration:t.animation.frameDuration,speed:t.animation.speed,reverse:t.animation.isReversed}),this._ready=new wt,this.ready=this._ready.promise,this._tiledWidth=0,this._tiledHeight=0,this._sourceView={},this._sourceView={...t.sourceView},this._tiledWidth=t.width,this._tiledHeight=t.height;const e=[];for(let i=0;i<this.frames.length;i++){const s=this.frames[i].graphic;if(s&&s instanceof kt){const n=new li({image:s.image,width:t.width,height:t.height,sourceView:{...s.sourceView},wrapping:t.wrapping,filtering:t.filtering});this.frames[i].graphic=n,n.ready.then(()=>{n.sourceView={...n.sourceView,...this._sourceView}}),e.push(n.ready)}}Promise.all(e).then(()=>this._ready.resolve())}static fromAnimation(t,e){return new vn({width:t.width,height:t.height,...e,animation:t})}_updateSourceView(){for(let t=0;t<this.frames.length;t++){const e=this.frames[t].graphic;e&&e instanceof kt&&(e.sourceView={...e.sourceView,...this._sourceView})}}get sourceView(){return Et(this._sourceView,()=>this._updateSourceView())}set sourceView(t){this._sourceView=Et(t,()=>this._updateSourceView()),this._updateSourceView()}_updateWidthHeight(){for(let t=0;t<this.frames.length;t++){const e=this.frames[t].graphic;e&&e instanceof kt&&(e.sourceView.height=this._tiledHeight||e.height,e.destSize.height=this._tiledHeight||e.height,e.sourceView.width=this._tiledWidth||e.width,e.destSize.width=this._tiledWidth||e.width)}}get width(){return this._tiledWidth}get height(){return this._tiledHeight}set width(t){this._tiledWidth=t,this._updateWidthHeight()}set height(t){this._tiledHeight=t,this._updateWidthHeight()}}const Or={pixelArtSampler:!1,nativeContextAntialiasing:!1,multiSampleAntialiasing:!0,filtering:mt.Blended,canvasImageRendering:"auto"},Hr={pixelArtSampler:!0,nativeContextAntialiasing:!1,multiSampleAntialiasing:!0,filtering:mt.Blended,canvasImageRendering:"auto"},wn=class rr{static clear(){rr.DrawCallCount=0,rr.DrawnImagesCount=0}};wn.DrawCallCount=0,wn.DrawnImagesCount=0;let st=wn;const K=1e-4;class Xh{constructor(t){this._ex=t,this._debugText=new un}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~(t+K):t,this._ex.snapToPixel?~~(e+K):e,this._ex.snapToPixel?~~(i+K):i,this._ex.snapToPixel?~~(s+K):s),this._ex.__ctx.restore()}drawLine(t,e,i={color:P.Black}){var s,n;this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=(n=(s=i.color)==null?void 0:s.toString())!=null?n:"",this._ex.__ctx.moveTo(this._ex.snapToPixel?~~(t.x+K):t.x,this._ex.snapToPixel?~~(t.y+K):t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~(e.x+K):e.x,this._ex.snapToPixel?~~(e.y+K):e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:P.Black,size:5}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.fillStyle=e.color.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~(t.x+K):t.x,this._ex.snapToPixel?~~(t.y+K):t.y,e.size,0,Math.PI*2),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class Xi{constructor(t){this.useDrawSorting=!1,this.z=0,this.backgroundColor=P.ExcaliburBlue,this._state=new Ur,this.snapToPixel=!1,this.debug=new Xh(this);const{canvasElement:e,context:i,enableTransparency:s,snapToPixel:n,antialiasing:o,backgroundColor:a}=t;if(this.__ctx=i!=null?i:e.getContext("2d",{alpha:s!=null?s:!0}),!this.__ctx)throw new Error("Cannot build new ExcaliburGraphicsContext2D for some reason!");this.backgroundColor=a!=null?a:this.backgroundColor,this.snapToPixel=n!=null?n:this.snapToPixel,this.smoothing=o!=null?o:this.smoothing}get width(){return this.__ctx.canvas.width}get height(){return this.__ctx.canvas.height}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get smoothing(){return this.__ctx.imageSmoothingEnabled}set smoothing(t){this.__ctx.imageSmoothingEnabled=t}resetTransform(){this.__ctx.resetTransform()}updateViewport(t){}drawImage(t,e,i,s,n,o,a,h,l){if(s===0||n===0)return;if(h===0||l===0)return;if(t.width===0||t.height===0)return;this.__ctx.globalAlpha=this.opacity;const c=[t,e,i,s,n,o,a,h,l].filter(u=>u!==void 0).map(u=>typeof u=="number"&&this.snapToPixel?~~u:u);this.__ctx.drawImage.apply(this.__ctx,c),st.DrawCallCount++,st.DrawnImagesCount=1}drawLine(t,e,i,s=1){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.strokeStyle=i.toString(),this.__ctx.moveTo(this.snapToPixel?~~(t.x+K):t.x,this.snapToPixel?~~(t.y+K):t.y),this.__ctx.lineTo(this.snapToPixel?~~(e.x+K):e.x,this.snapToPixel?~~(e.y+K):e.y),this.__ctx.lineWidth=s,this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}drawRectangle(t,e,i,s){this.__ctx.save(),this.__ctx.fillStyle=s.toString(),this.__ctx.fillRect(this.snapToPixel?~~(t.x+K):t.x,this.snapToPixel?~~(t.y+K):t.y,this.snapToPixel?~~(e+K):e,this.snapToPixel?~~(i+K):i),this.__ctx.restore()}drawCircle(t,e,i,s,n){this.__ctx.save(),this.__ctx.beginPath(),s&&(this.__ctx.strokeStyle=s.toString()),n&&(this.__ctx.lineWidth=n),this.__ctx.fillStyle=i.toString(),this.__ctx.arc(this.snapToPixel?~~(t.x+K):t.x,this.snapToPixel?~~(t.y+K):t.y,e,0,Math.PI*2),this.__ctx.fill(),s&&this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}save(){this.__ctx.save(),this._state.save()}restore(){this.__ctx.restore(),this._state.restore()}translate(t,e){this.__ctx.translate(this.snapToPixel?~~(t+K):t,this.snapToPixel?~~(e+K):e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}getTransform(){throw new Error("Not implemented")}multiply(t){this.__ctx.setTransform(this.__ctx.getTransform().multiply(t.toDOMMatrix()))}addPostProcessor(t){}removePostProcessor(t){}clearPostProcessors(){}updatePostProcessors(t){}beginDrawLifecycle(){}endDrawLifecycle(){}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){return null}clear(){this.__ctx.clearRect(0,0,this.width,this.height),this.__ctx.fillStyle=this.backgroundColor.toString(),this.__ctx.fillRect(0,0,this.width,this.height),st.clear()}flush(){}dispose(){this.__ctx=void 0}}class Nr{constructor(t){this.type="static";const{gl:e,size:i,type:s,data:n}=t;if(this._gl=e,this.buffer=e.createBuffer(),this._maxFloats=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)/32,!n&&!i)throw Error("Must either provide data or a size to the UniformBuffer");if(n?this.bufferData=n:this.bufferData=new Float32Array(i),this.bufferData.length>this._maxFloats)throw Error(`UniformBuffer exceeds browsers allowed number of floats ${this._maxFloats}`);this.type=s!=null?s:this.type,e.bindBuffer(e.UNIFORM_BUFFER,this.buffer),e.bufferData(e.UNIFORM_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.UNIFORM_BUFFER,this.buffer)}unbind(){const t=this._gl;t.bindBuffer(t.UNIFORM_BUFFER,null)}upload(t){const e=this._gl;e.bindBuffer(e.UNIFORM_BUFFER,this.buffer),t?e.bufferSubData(e.UNIFORM_BUFFER,0,this.bufferData,0,t):e.bufferData(e.UNIFORM_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}function xn(r,t){switch(t){case r.INT:case r.UNSIGNED_INT:case r.FLOAT:return 4;case r.SHORT:return 2;case r.UNSIGNED_SHORT:return 2;case r.BYTE:return 1;case r.UNSIGNED_BYTE:return 1;default:return 1}}function Wr(r,t){const e=`(?<type>[a-z0-9]+)\\s+${t};`,s=new RegExp(e,"g").exec(r);return(s==null?void 0:s.length)>0}function Gr(r,t,e){var i;const s=`(?<type>[a-z0-9]+)\\s+${e};`,o=new RegExp(s,"g").exec(t);switch((i=o==null?void 0:o.groups)==null?void 0:i.type){case"float":case"vec2":case"vec3":case"vec4":return r.FLOAT;case"int":case"ivec2":case"ivec3":case"ivec4":return r.INT;case"uint":case"uvec2":case"uvec3":case"uvec4":return r.UNSIGNED_INT;case"bool":case"bvec2":case"bvec3":case"bvec4":return r.BOOL;case"short":return r.SHORT;case"ushort":return r.UNSIGNED_SHORT;case"ubyte":return r.UNSIGNED_BYTE;case"byte":return r.BYTE;default:return r.FLOAT}}function Vr(r,t){switch(t){case r.LOW_FLOAT:case r.HIGH_FLOAT:case r.FLOAT:return 1;case r.FLOAT_VEC2:return 2;case r.FLOAT_VEC3:return 3;case r.FLOAT_VEC4:return 4;case r.BYTE:return 1;case r.UNSIGNED_BYTE:return 1;case r.UNSIGNED_SHORT:case r.SHORT:return 1;default:return 1}}function qr(r,t){switch(t){case r.LOW_FLOAT:case r.HIGH_FLOAT:case r.FLOAT:case r.FLOAT_VEC2:case r.FLOAT_VEC3:case r.FLOAT_VEC4:return r.FLOAT;case r.BYTE:return r.BYTE;case r.UNSIGNED_BYTE:return r.UNSIGNED_BYTE;case r.SHORT:return r.SHORT;case r.UNSIGNED_SHORT:return r.UNSIGNED_SHORT;default:return r.FLOAT}}function bn(r,t){const e=s=>{const n=`#version 300 es
|
|
79
|
+
Read https://excaliburjs.com/docs/imagesource for more information.`)}_initialize(){this._sourceSprite=this._imgSource.image,this._canvasA.width=this._config.sourceConfig.leftMargin,this._canvasA.height=this._config.sourceConfig.topMargin;const t=this._canvasA.getContext("2d");t==null||t.drawImage(this._sourceSprite,0,0,this._canvasA.width,this._canvasA.height,0,0,this._canvasA.width,this._canvasA.height),this._canvasB.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasB.height=this._config.sourceConfig.topMargin;const e=this._canvasB.getContext("2d");e==null||e.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,0,this._canvasB.width,this._canvasB.height,0,0,this._canvasB.width,this._canvasB.height),this._canvasC.width=this._config.sourceConfig.rightMargin,this._canvasC.height=this._config.sourceConfig.topMargin;const i=this._canvasC.getContext("2d");i==null||i.drawImage(this._sourceSprite,this._sourceSprite.width-this._config.sourceConfig.rightMargin,0,this._canvasC.width,this._canvasC.height,0,0,this._canvasC.width,this._canvasC.height),this._canvasD.width=this._config.sourceConfig.leftMargin,this._canvasD.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const s=this._canvasD.getContext("2d");s==null||s.drawImage(this._sourceSprite,0,this._config.sourceConfig.topMargin,this._canvasD.width,this._canvasD.height,0,0,this._canvasD.width,this._canvasD.height),this._canvasE.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasE.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const n=this._canvasE.getContext("2d");n==null||n.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,this._config.sourceConfig.topMargin,this._canvasE.width,this._canvasE.height,0,0,this._canvasE.width,this._canvasE.height),this._canvasF.width=this._config.sourceConfig.rightMargin,this._canvasF.height=this._config.sourceConfig.height-this._config.sourceConfig.topMargin-this._config.sourceConfig.bottomMargin;const o=this._canvasF.getContext("2d");o==null||o.drawImage(this._sourceSprite,this._config.sourceConfig.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.topMargin,this._canvasF.width,this._canvasF.height,0,0,this._canvasF.width,this._canvasF.height),this._canvasG.width=this._config.sourceConfig.leftMargin,this._canvasG.height=this._config.sourceConfig.bottomMargin;const a=this._canvasG.getContext("2d");a==null||a.drawImage(this._sourceSprite,0,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasG.width,this._canvasG.height,0,0,this._canvasG.width,this._canvasG.height),this._canvasH.width=this._config.sourceConfig.width-this._config.sourceConfig.leftMargin-this._config.sourceConfig.rightMargin,this._canvasH.height=this._config.sourceConfig.bottomMargin;const h=this._canvasH.getContext("2d");h==null||h.drawImage(this._sourceSprite,this._config.sourceConfig.leftMargin,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasH.width,this._canvasH.height,0,0,this._canvasH.width,this._canvasH.height),this._canvasI.width=this._config.sourceConfig.rightMargin,this._canvasI.height=this._config.sourceConfig.bottomMargin;const l=this._canvasI.getContext("2d");l==null||l.drawImage(this._sourceSprite,this._sourceSprite.width-this._config.sourceConfig.rightMargin,this._config.sourceConfig.height-this._config.sourceConfig.bottomMargin,this._canvasI.width,this._canvasI.height,0,0,this._canvasI.width,this._canvasI.height)}clone(){return new wn(this._config)}_getNumberOfTiles(t,e,i){switch(i){case"stretch":return 1;case"tile":return Math.ceil(e/t);case"tile-fit":return Math.ceil(e/t)}}_calculateParams(t,e,i,s,n){switch(n){case"stretch":return{tempPosition:0,tempSize:s};case"tile":return t===e-1?{tempPosition:t*i,tempSize:i-(e*i-s)}:{tempPosition:t*i,tempSize:i};case"tile-fit":const o=s/e;return{tempPosition:t*o,tempSize:o}}}}class xn extends Oi{constructor(t){super({...t,frames:t.animation.frames.slice(),strategy:t.animation.strategy,frameDuration:t.animation.frameDuration,speed:t.animation.speed,reverse:t.animation.isReversed}),this._ready=new wt,this.ready=this._ready.promise,this._tiledWidth=0,this._tiledHeight=0,this._sourceView={},this._sourceView={...t.sourceView},this._tiledWidth=t.width,this._tiledHeight=t.height;const e=[];for(let i=0;i<this.frames.length;i++){const s=this.frames[i].graphic;if(s&&s instanceof zt){const n=new di({image:s.image,width:t.width,height:t.height,sourceView:{...s.sourceView},wrapping:t.wrapping,filtering:t.filtering});this.frames[i].graphic=n,n.ready.then(()=>{n.sourceView={...n.sourceView,...this._sourceView}}),e.push(n.ready)}}Promise.all(e).then(()=>this._ready.resolve())}static fromAnimation(t,e){return new xn({width:t.width,height:t.height,...e,animation:t})}_updateSourceView(){for(let t=0;t<this.frames.length;t++){const e=this.frames[t].graphic;e&&e instanceof zt&&(e.sourceView={...e.sourceView,...this._sourceView})}}get sourceView(){return It(this._sourceView,()=>this._updateSourceView())}set sourceView(t){this._sourceView=It(t,()=>this._updateSourceView()),this._updateSourceView()}_updateWidthHeight(){for(let t=0;t<this.frames.length;t++){const e=this.frames[t].graphic;e&&e instanceof zt&&(e.sourceView.height=this._tiledHeight||e.height,e.destSize.height=this._tiledHeight||e.height,e.sourceView.width=this._tiledWidth||e.width,e.destSize.width=this._tiledWidth||e.width)}}get width(){return this._tiledWidth}get height(){return this._tiledHeight}set width(t){this._tiledWidth=t,this._updateWidthHeight()}set height(t){this._tiledHeight=t,this._updateWidthHeight()}}const Or={pixelArtSampler:!1,nativeContextAntialiasing:!1,multiSampleAntialiasing:!0,filtering:mt.Blended,canvasImageRendering:"auto"},Hr={pixelArtSampler:!0,nativeContextAntialiasing:!1,multiSampleAntialiasing:!0,filtering:mt.Blended,canvasImageRendering:"auto"},bn=class rr{static clear(){rr.DrawCallCount=0,rr.DrawnImagesCount=0}};bn.DrawCallCount=0,bn.DrawnImagesCount=0;let J=bn;const Y=1e-4;class Xh{constructor(t){this._ex=t,this._debugText=new fn}drawRect(t,e,i,s){this._ex.__ctx.save(),this._ex.__ctx.strokeStyle="red",this._ex.__ctx.strokeRect(this._ex.snapToPixel?~~(t+Y):t,this._ex.snapToPixel?~~(e+Y):e,this._ex.snapToPixel?~~(i+Y):i,this._ex.snapToPixel?~~(s+Y):s),this._ex.__ctx.restore()}drawLine(t,e,i={color:T.Black}){var s,n;this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.strokeStyle=(n=(s=i.color)==null?void 0:s.toString())!=null?n:"",this._ex.__ctx.moveTo(this._ex.snapToPixel?~~(t.x+Y):t.x,this._ex.snapToPixel?~~(t.y+Y):t.y),this._ex.__ctx.lineTo(this._ex.snapToPixel?~~(e.x+Y):e.x,this._ex.snapToPixel?~~(e.y+Y):e.y),this._ex.__ctx.lineWidth=2,this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawPoint(t,e={color:T.Black,size:5}){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),this._ex.__ctx.fillStyle=e.color.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~(t.x+Y):t.x,this._ex.snapToPixel?~~(t.y+Y):t.y,e.size,0,Math.PI*2),this._ex.__ctx.fill(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawCircle(t,e,i,s,n){this._ex.__ctx.save(),this._ex.__ctx.beginPath(),s&&(this._ex.__ctx.strokeStyle=s.toString()),n&&(this._ex.__ctx.lineWidth=n),this._ex.__ctx.fillStyle=i.toString(),this._ex.__ctx.arc(this._ex.snapToPixel?~~(t.x+Y):t.x,this._ex.snapToPixel?~~(t.y+Y):t.y,e,0,Math.PI*2),this._ex.__ctx.fill(),s&&this._ex.__ctx.stroke(),this._ex.__ctx.closePath(),this._ex.__ctx.restore()}drawText(t,e){this._debugText.write(this._ex,t,e)}}class $i{constructor(t){this.useDrawSorting=!1,this.z=0,this.backgroundColor=T.ExcaliburBlue,this._state=new Ur,this.snapToPixel=!1,this.debug=new Xh(this);const{canvasElement:e,context:i,enableTransparency:s,snapToPixel:n,antialiasing:o,backgroundColor:a}=t;if(this.__ctx=i!=null?i:e.getContext("2d",{alpha:s!=null?s:!0}),!this.__ctx)throw new Error("Cannot build new ExcaliburGraphicsContext2D for some reason!");this.backgroundColor=a!=null?a:this.backgroundColor,this.snapToPixel=n!=null?n:this.snapToPixel,this.smoothing=o!=null?o:this.smoothing}get width(){return this.__ctx.canvas.width}get height(){return this.__ctx.canvas.height}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get smoothing(){return this.__ctx.imageSmoothingEnabled}set smoothing(t){this.__ctx.imageSmoothingEnabled=t}resetTransform(){this.__ctx.resetTransform()}updateViewport(t){}drawImage(t,e,i,s,n,o,a,h,l){if(s===0||n===0)return;if(h===0||l===0)return;if(t.width===0||t.height===0)return;this.__ctx.globalAlpha=this.opacity;const c=[t,e,i,s,n,o,a,h,l].filter(u=>u!==void 0).map(u=>typeof u=="number"&&this.snapToPixel?~~u:u);this.__ctx.drawImage.apply(this.__ctx,c),J.DrawCallCount++,J.DrawnImagesCount=1}drawLine(t,e,i,s=1){this.__ctx.save(),this.__ctx.beginPath(),this.__ctx.strokeStyle=i.toString(),this.__ctx.moveTo(this.snapToPixel?~~(t.x+Y):t.x,this.snapToPixel?~~(t.y+Y):t.y),this.__ctx.lineTo(this.snapToPixel?~~(e.x+Y):e.x,this.snapToPixel?~~(e.y+Y):e.y),this.__ctx.lineWidth=s,this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}drawRectangle(t,e,i,s){this.__ctx.save(),this.__ctx.fillStyle=s.toString(),this.__ctx.fillRect(this.snapToPixel?~~(t.x+Y):t.x,this.snapToPixel?~~(t.y+Y):t.y,this.snapToPixel?~~(e+Y):e,this.snapToPixel?~~(i+Y):i),this.__ctx.restore()}drawCircle(t,e,i,s,n){this.__ctx.save(),this.__ctx.beginPath(),s&&(this.__ctx.strokeStyle=s.toString()),n&&(this.__ctx.lineWidth=n),this.__ctx.fillStyle=i.toString(),this.__ctx.arc(this.snapToPixel?~~(t.x+Y):t.x,this.snapToPixel?~~(t.y+Y):t.y,e,0,Math.PI*2),this.__ctx.fill(),s&&this.__ctx.stroke(),this.__ctx.closePath(),this.__ctx.restore()}save(){this.__ctx.save(),this._state.save()}restore(){this.__ctx.restore(),this._state.restore()}translate(t,e){this.__ctx.translate(this.snapToPixel?~~(t+Y):t,this.snapToPixel?~~(e+Y):e)}rotate(t){this.__ctx.rotate(t)}scale(t,e){this.__ctx.scale(t,e)}getTransform(){const t=this.__ctx.getTransform(),e=new Z;return e.data[0]=t.a,e.data[1]=t.b,e.data[2]=t.c,e.data[3]=t.d,e.data[4]=t.e,e.data[5]=t.f,e}multiply(t){this.__ctx.setTransform(this.__ctx.getTransform().multiply(t.toDOMMatrix()))}addPostProcessor(t){}removePostProcessor(t){}clearPostProcessors(){}updatePostProcessors(t){}beginDrawLifecycle(){}endDrawLifecycle(){}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){return null}clear(){this.__ctx.clearRect(0,0,this.width,this.height),this.__ctx.fillStyle=this.backgroundColor.toString(),this.__ctx.fillRect(0,0,this.width,this.height),J.clear()}flush(){}dispose(){this.__ctx=void 0}}class Nr{constructor(t){this.type="static";const{gl:e,size:i,type:s,data:n}=t;if(this._gl=e,this.buffer=e.createBuffer(),this._maxFloats=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE)/32,!n&&!i)throw Error("Must either provide data or a size to the UniformBuffer");if(n?this.bufferData=n:this.bufferData=new Float32Array(i),this.bufferData.length>this._maxFloats)throw Error(`UniformBuffer exceeds browsers allowed number of floats ${this._maxFloats}`);this.type=s!=null?s:this.type,e.bindBuffer(e.UNIFORM_BUFFER,this.buffer),e.bufferData(e.UNIFORM_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.UNIFORM_BUFFER,this.buffer)}unbind(){const t=this._gl;t.bindBuffer(t.UNIFORM_BUFFER,null)}upload(t){const e=this._gl;e.bindBuffer(e.UNIFORM_BUFFER,this.buffer),t?e.bufferSubData(e.UNIFORM_BUFFER,0,this.bufferData,0,t):e.bufferData(e.UNIFORM_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}function yn(r,t){switch(t){case r.INT:case r.UNSIGNED_INT:case r.FLOAT:return 4;case r.SHORT:return 2;case r.UNSIGNED_SHORT:return 2;case r.BYTE:return 1;case r.UNSIGNED_BYTE:return 1;default:return 1}}function Wr(r,t){const e=`(?<type>[a-z0-9]+)\\s+${t};`,s=new RegExp(e,"g").exec(r);return(s==null?void 0:s.length)>0}function Gr(r,t,e){var i;const s=`(?<type>[a-z0-9]+)\\s+${e};`,o=new RegExp(s,"g").exec(t);switch((i=o==null?void 0:o.groups)==null?void 0:i.type){case"float":case"vec2":case"vec3":case"vec4":return r.FLOAT;case"int":case"ivec2":case"ivec3":case"ivec4":return r.INT;case"uint":case"uvec2":case"uvec3":case"uvec4":return r.UNSIGNED_INT;case"bool":case"bvec2":case"bvec3":case"bvec4":return r.BOOL;case"short":return r.SHORT;case"ushort":return r.UNSIGNED_SHORT;case"ubyte":return r.UNSIGNED_BYTE;case"byte":return r.BYTE;default:return r.FLOAT}}function Vr(r,t){switch(t){case r.LOW_FLOAT:case r.HIGH_FLOAT:case r.FLOAT:return 1;case r.FLOAT_VEC2:return 2;case r.FLOAT_VEC3:return 3;case r.FLOAT_VEC4:return 4;case r.BYTE:return 1;case r.UNSIGNED_BYTE:return 1;case r.UNSIGNED_SHORT:case r.SHORT:return 1;default:return 1}}function qr(r,t){switch(t){case r.LOW_FLOAT:case r.HIGH_FLOAT:case r.FLOAT:case r.FLOAT_VEC2:case r.FLOAT_VEC3:case r.FLOAT_VEC4:return r.FLOAT;case r.BYTE:return r.BYTE;case r.UNSIGNED_BYTE:return r.UNSIGNED_BYTE;case r.SHORT:return r.SHORT;case r.UNSIGNED_SHORT:return r.UNSIGNED_SHORT;default:return r.FLOAT}}function Cn(r,t){const e=s=>{const n=`#version 300 es
|
|
66
80
|
precision mediump float;
|
|
67
81
|
out vec4 fragColor;
|
|
68
82
|
void main() {
|
|
@@ -72,14 +86,14 @@ Read https://excaliburjs.com/docs/imagesource for more information.`)}_initializ
|
|
|
72
86
|
`:o+=` else if (index <= ${a}.5) {
|
|
73
87
|
`,o+=` fragColor = vec4(1.0);
|
|
74
88
|
`,o+=` }
|
|
75
|
-
`;return n.replace("%%complexity%%",o)};let i=!1;do{const s=e(t),n=r.createShader(r.FRAGMENT_SHADER);r.shaderSource(n,s),r.compileShader(n),i=r.getShaderParameter(n,r.COMPILE_STATUS),i||(t=t/2|0)}while(!i);return t}const Yh=Object.freeze(Object.defineProperty({__proto__:null,getAttributeComponentSize:Vr,getAttributePointerType:qr,getGLTypeFromSource:Gr,getGlTypeSizeBytes:xn,getMaxShaderComplexity:bn,isAttributeInSource:Wr},Symbol.toStringTag,{value:"Module"}));function Xr(r,t){switch(t){case r.FLOAT:return"uniform1f";case r.FLOAT_VEC2:return"uniform2f";case r.FLOAT_VEC3:return"uniform3f";case r.FLOAT_VEC4:return"uniform4f";case r.INT:return"uniform1i";case r.INT_VEC2:return"uniform2i";case r.INT_VEC3:return"uniform3i";case r.INT_VEC4:return"uniform4i";case r.BOOL:return"uniform1i";case r.BOOL_VEC2:return"uniform2i";case r.BOOL_VEC3:return"uniform3i";case r.BOOL_VEC4:return"uniform4i";case r.FLOAT_MAT2:return"uniform1f";case r.FLOAT_MAT3:return"uniform1f";case r.FLOAT_MAT4:return"uniform1f";case r.SAMPLER_2D:return"uniform1f";case r.SAMPLER_CUBE:return"uniform1f";case r.UNSIGNED_INT:return"uniform1ui";case r.UNSIGNED_INT_VEC2:return"uniform2ui";case r.UNSIGNED_INT_VEC3:return"uniform3ui";case r.UNSIGNED_INT_VEC4:return"uniform4ui";case r.FLOAT_MAT2x3:return"uniformMatrix2x3fv";case r.FLOAT_MAT2x4:return"uniformMatrix2x4fv";case r.FLOAT_MAT3x2:return"uniformMatrix3x2fv";case r.FLOAT_MAT3x4:return"uniformMatrix3x4fv";case r.FLOAT_MAT4x2:return"uniformMatrix4x2fv";case r.FLOAT_MAT4x3:return"uniformMatrix4x3fv";case r.SAMPLER_2D_ARRAY:return"uniform1fv";case r.SAMPLER_2D_ARRAY_SHADOW:return"uniform1f";case r.SAMPLER_CUBE_SHADOW:return"uniform1f";case r.INT_SAMPLER_2D:return"uniform1f";case r.INT_SAMPLER_3D:return"uniform1f";case r.INT_SAMPLER_CUBE:return"uniform1f";case r.INT_SAMPLER_2D_ARRAY:return"uniform1f";case r.UNSIGNED_INT_SAMPLER_2D:return"uniform1ui";default:throw new Error(`Unknown uniform type: ${t}`)}}const Yr=class Ci{constructor(t){this.name="anonymous shader",this._logger=R.getInstance(),this._textures=new Map,this.attributes={},this._uniforms={},this._uniformBuffers={},this._compiled=!1,this._dirtyUniforms=!0,this._startingTextureSlot=0,this.uniforms=Et({},()=>this.flagUniformsDirty()),this.images={};const{name:e,graphicsContext:i,vertexSource:s,fragmentSource:n,onPreLink:o,onPostCompile:a,uniforms:h,images:l,startingTextureSlot:c}=t;if(this.name=e!=null?e:this.name,!(i instanceof Xt))throw new Error(`ExcaliburGraphicsContext provided to a shader ${this.name} must be WebGL`);this._gl=i.__gl,this._startingTextureSlot=c!=null?c:this._startingTextureSlot,this._maxTextureSlots=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS)-this._startingTextureSlot,this.vertexSource=s,this.fragmentSource=n,this.uniforms=Et(h!=null?h:this.uniforms,()=>this.flagUniformsDirty()),this.images=l!=null?l:this.images,Object.keys(this.images).length>=this._maxTextureSlots&&this._logger.warn(`Max number texture slots ${this._maxTextureSlots} have been reached for material "${this.name}", no more textures will be uploaded due to hardware constraints.`),this._textureLoader=i.textureLoader,this._onPreLink=o,this._onPostCompile=a}flagUniformsDirty(){this._dirtyUniforms=!0}get compiled(){return this._compiled}dispose(){this._gl.deleteProgram(this.program),this._gl=null}use(){this._gl.useProgram(this.program),Ci._ACTIVE_SHADER_INSTANCE=this,this._dirtyUniforms&&(this._setUniforms(),this._dirtyUniforms=!1),this._setImages()}unuse(){const t=this._gl;Ci._ACTIVE_SHADER_INSTANCE=null,t.useProgram(null)}isCurrentlyBound(){return Ci._ACTIVE_SHADER_INSTANCE===this}_setUniforms(){const t=this._gl,e=Object.entries(this.uniforms);if(e.length){const i=this.getUniformDefinitions();for(const[s,n]of e)if(n instanceof Float32Array)this.setUniformBuffer(s,n);else if(Array.isArray(n)&&n[0]instanceof Float32Array&&typeof n[1]=="number")this.setUniformBuffer(s,n[0],n[1]);else if(typeof n=="number")this.trySetUniformFloat(s,n);else if(typeof n=="boolean")this.trySetUniformBoolean(s,n);else if(n instanceof v)this.trySetUniformFloatVector(s,n);else if(n instanceof P)this.trySetUniformFloatColor(s,n);else if(n instanceof Q)this.setUniformAffineMatrix(s,n);else{const o=i.find(a=>a.name===s);if(o){const a=Xr(t,o.glType);this.trySetUniform(a,s,n)}else this._logger.warnOnce(`Could not locate uniform named ${s}, this can happen if the uniform is unused in the shader code some GPUs will remove this as an optimization.`)}}}_loadImageSource(t){const e=t.image,i=e.getAttribute(O.Filtering),s=i?Ge(i):void 0,n=Ut(e.getAttribute(O.WrappingX)),o=Ut(e.getAttribute(O.WrappingY)),a=e.getAttribute("forceUpload")==="true",h=this._textureLoader.load(e,{filtering:s,wrapping:{x:n,y:o}},a);return e.removeAttribute("forceUpload"),this._textures.has(t)||this._textures.set(t,h),h}_setImages(t=!1){const e=this._gl;let i=this._startingTextureSlot;for(const[s,n]of Object.entries(this.images)){if(!n.isLoaded()){t||this._logger.warnOnce(`Image named ${s} in not loaded, nothing will be uploaded to the shader. Did you forget to add this to a loader? https://excaliburjs.com/docs/loaders/`);continue}const o=this._loadImageSource(n);o||t||this._logger.warnOnce(`Image ${s} (${n.image.src}) could not be loaded for some reason in shader ${this.name}`),e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,o),this.trySetUniformInt(s,i),i++}}compile(){if(this._compiled)return this.program;const t=this._gl,e=this._compileShader(t,this.vertexSource,t.VERTEX_SHADER),i=this._compileShader(t,this.fragmentSource,t.FRAGMENT_SHADER);this.program=this._createProgram(t,e,i);const s=this.getAttributeDefinitions();for(const o of s)this.attributes[o.name]=o;const n=this.getUniformDefinitions();for(const o of n)this._uniforms[o.name]=o;return this._compiled=!0,this._onPostCompile&&this._onPostCompile(this),t.useProgram(this.program),Ci._ACTIVE_SHADER_INSTANCE=this,this._dirtyUniforms&&(this._setUniforms(),this._dirtyUniforms=!1),this._setImages(!0),this.unuse(),this.program}getUniformDefinitions(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_UNIFORMS),i=[];for(let s=0;s<e;s++){const n=t.getActiveUniform(this.program,s),o=t.getUniformLocation(this.program,n.name);i.push({name:n.name,glType:n.type,location:o})}return i}getAttributeDefinitions(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_ATTRIBUTES),i=[];for(let s=0;s<e;s++){const n=t.getActiveAttrib(this.program,s),o=t.getAttribLocation(this.program,n.name);i.push({name:n.name,glType:qr(t,n.type),size:Vr(t,n.type),location:o,normalized:!1})}return i}addImageSource(t,e){Object.keys(this.images).length<this._maxTextureSlots?this.images[t]=e:this._logger.warn(`Max number texture slots ${this._maxTextureSlots} have been reached for material "${this.name}", no more textures will be uploaded due to hardware constraints.`)}removeImageSource(t){const e=this.images[t];e&&(this._textureLoader.delete(e.image),delete this.images[t])}setTexture(t,e){const i=this._gl;i.activeTexture(i.TEXTURE0+t),i.bindTexture(i.TEXTURE_2D,e)}setUniformBuffer(t,e,i=0){const s=this._gl,n=s.getUniformBlockIndex(this.program,t);n===s.INVALID_INDEX&&this._logger.warnOnce(`Invalid block name ${t}`);let o;this._uniformBuffers[t]?(o=this._uniformBuffers[t],o.bufferData.set(e),o.upload()):(o=new Nr({gl:s,data:e}),this._uniformBuffers[t]=o),s.uniformBlockBinding(this.program,n,i),s.bindBufferBase(s.UNIFORM_BUFFER,i,o.buffer)}trySetUniformBuffer(t,e,i=0){return this._compiled?this.isCurrentlyBound()?this._gl.getUniformBlockIndex(this.program,t)?(this.setUniformBuffer(t,e,i),!0):!1:(this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1):(this._logger.warn(`Must compile shader before setting a uniform block ${t} at binding point ${i}`),!1)}setUniformInt(t,e){this.setUniform("uniform1i",t,~~e)}trySetUniformInt(t,e){return this.trySetUniform("uniform1i",t,~~e)}setUniformIntArray(t,e){this.setUniform("uniform1iv",t,e)}trySetUniformIntArray(t,e){return this.trySetUniform("uniform1iv",t,e)}setUniformBoolean(t,e){this.setUniform("uniform1i",t,e?1:0)}trySetUniformBoolean(t,e){return this.trySetUniform("uniform1i",t,e?1:0)}setUniformFloat(t,e){this.setUniform("uniform1f",t,e)}trySetUniformFloat(t,e){return this.trySetUniform("uniform1f",t,e)}setUniformFloatArray(t,e){this.setUniform("uniform1fv",t,e)}trySetUniformFloatArray(t,e){return this.trySetUniform("uniform1fv",t,e)}setUniformFloatVector(t,e){this.setUniform("uniform2f",t,e.x,e.y)}trySetUniformFloatVector(t,e){return this.trySetUniform("uniform2f",t,e.x,e.y)}setUniformFloatColor(t,e){this.setUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}trySetUniformFloatColor(t,e){return this.trySetUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}setUniformMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,e.data)}setUniformAffineMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,[e.data[0],e.data[1],0,0,e.data[2],e.data[3],0,0,0,0,1,0,e.data[4],e.data[5],0,1])}trySetUniformMatrix(t,e){return this.trySetUniform("uniformMatrix4fv",t,!1,e.data)}setUniform(t,e,...i){if(!this._compiled)throw Error(`Must compile shader before setting a uniform ${t}:${e}`);if(!this.isCurrentlyBound())throw Error("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms");const n=this._gl.getUniformLocation(this.program,e);if(n){const o=[n,...i];this._gl[t].apply(this._gl,o)}else throw Error(`Uniform ${t}:${e} doesn't exist or is not used in the shader source code, unused uniforms are optimized away by most browsers`)}trySetUniform(t,e,...i){if(!this._compiled)return this._logger.warn(`Must compile shader before setting a uniform ${t}:${e}`),!1;if(!this.isCurrentlyBound())return this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1;const n=this._gl.getUniformLocation(this.program,e);if(n){const o=[n,...i];this._gl[t].apply(this._gl,o)}else return!1;return!0}_createProgram(t,e,i){const s=t.createProgram();if(s===null)throw Error("Could not create graphics shader program");if(t.attachShader(s,e),t.attachShader(s,i),this._onPreLink&&this._onPreLink(s),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw Error(`Could not link the program: [${t.getProgramInfoLog(s)}]`);return s}_compileShader(t,e,i){const s=t.VERTEX_SHADER===i?"vertex":"fragment",n=t.createShader(i);if(n===null)throw Error(`Could not build shader: [${e}]`);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const a=t.getShaderInfoLog(n);throw Error(`Could not compile ${s} shader:
|
|
89
|
+
`;return n.replace("%%complexity%%",o)};let i=!1;do{const s=e(t),n=r.createShader(r.FRAGMENT_SHADER);r.shaderSource(n,s),r.compileShader(n),i=r.getShaderParameter(n,r.COMPILE_STATUS),i||(t=t/2|0)}while(!i);return t}const Yh=Object.freeze(Object.defineProperty({__proto__:null,getAttributeComponentSize:Vr,getAttributePointerType:qr,getGLTypeFromSource:Gr,getGlTypeSizeBytes:yn,getMaxShaderComplexity:Cn,isAttributeInSource:Wr},Symbol.toStringTag,{value:"Module"}));function Xr(r,t){switch(t){case r.FLOAT:return"uniform1f";case r.FLOAT_VEC2:return"uniform2f";case r.FLOAT_VEC3:return"uniform3f";case r.FLOAT_VEC4:return"uniform4f";case r.INT:return"uniform1i";case r.INT_VEC2:return"uniform2i";case r.INT_VEC3:return"uniform3i";case r.INT_VEC4:return"uniform4i";case r.BOOL:return"uniform1i";case r.BOOL_VEC2:return"uniform2i";case r.BOOL_VEC3:return"uniform3i";case r.BOOL_VEC4:return"uniform4i";case r.FLOAT_MAT2:return"uniform1f";case r.FLOAT_MAT3:return"uniform1f";case r.FLOAT_MAT4:return"uniform1f";case r.SAMPLER_2D:return"uniform1f";case r.SAMPLER_CUBE:return"uniform1f";case r.UNSIGNED_INT:return"uniform1ui";case r.UNSIGNED_INT_VEC2:return"uniform2ui";case r.UNSIGNED_INT_VEC3:return"uniform3ui";case r.UNSIGNED_INT_VEC4:return"uniform4ui";case r.FLOAT_MAT2x3:return"uniformMatrix2x3fv";case r.FLOAT_MAT2x4:return"uniformMatrix2x4fv";case r.FLOAT_MAT3x2:return"uniformMatrix3x2fv";case r.FLOAT_MAT3x4:return"uniformMatrix3x4fv";case r.FLOAT_MAT4x2:return"uniformMatrix4x2fv";case r.FLOAT_MAT4x3:return"uniformMatrix4x3fv";case r.SAMPLER_2D_ARRAY:return"uniform1fv";case r.SAMPLER_2D_ARRAY_SHADOW:return"uniform1f";case r.SAMPLER_CUBE_SHADOW:return"uniform1f";case r.INT_SAMPLER_2D:return"uniform1f";case r.INT_SAMPLER_3D:return"uniform1f";case r.INT_SAMPLER_CUBE:return"uniform1f";case r.INT_SAMPLER_2D_ARRAY:return"uniform1f";case r.UNSIGNED_INT_SAMPLER_2D:return"uniform1ui";default:throw new Error(`Unknown uniform type: ${t}`)}}const Yr=class Si{constructor(t){this.name="anonymous shader",this._logger=R.getInstance(),this._textures=new Map,this.attributes={},this._uniforms={},this._uniformBuffers={},this._compiled=!1,this._dirtyUniforms=!0,this._startingTextureSlot=0,this.uniforms=It({},()=>this.flagUniformsDirty()),this.images={};const{name:e,graphicsContext:i,vertexSource:s,fragmentSource:n,onPreLink:o,onPostCompile:a,uniforms:h,images:l,startingTextureSlot:c}=t;if(this.name=e!=null?e:this.name,!(i instanceof $t))throw new Error(`ExcaliburGraphicsContext provided to a shader ${this.name} must be WebGL`);this._gl=i.__gl,this._startingTextureSlot=c!=null?c:this._startingTextureSlot,this._maxTextureSlots=this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS)-this._startingTextureSlot,this.vertexSource=s,this.fragmentSource=n,this.uniforms=It(h!=null?h:this.uniforms,()=>this.flagUniformsDirty()),this.images=l!=null?l:this.images,Object.keys(this.images).length>=this._maxTextureSlots&&this._logger.warn(`Max number texture slots ${this._maxTextureSlots} have been reached for material "${this.name}", no more textures will be uploaded due to hardware constraints.`),this._textureLoader=i.textureLoader,this._onPreLink=o,this._onPostCompile=a}flagUniformsDirty(){this._dirtyUniforms=!0}get compiled(){return this._compiled}dispose(){this._gl.deleteProgram(this.program),this._gl=null}use(){this._gl.useProgram(this.program),Si._ACTIVE_SHADER_INSTANCE=this,this._dirtyUniforms&&(this._setUniforms(),this._dirtyUniforms=!1),this._setImages()}unuse(){const t=this._gl;Si._ACTIVE_SHADER_INSTANCE=null,t.useProgram(null)}isCurrentlyBound(){return Si._ACTIVE_SHADER_INSTANCE===this}_setUniforms(){const t=this._gl,e=Object.entries(this.uniforms);if(e.length){const i=this.getUniformDefinitions();for(const[s,n]of e)if(n instanceof Float32Array)this.setUniformBuffer(s,n);else if(Array.isArray(n)&&n[0]instanceof Float32Array&&typeof n[1]=="number")this.setUniformBuffer(s,n[0],n[1]);else if(typeof n=="number")this.trySetUniformFloat(s,n);else if(typeof n=="boolean")this.trySetUniformBoolean(s,n);else if(n instanceof w)this.trySetUniformFloatVector(s,n);else if(n instanceof T)this.trySetUniformFloatColor(s,n);else if(n instanceof Z)this.setUniformAffineMatrix(s,n);else{const o=i.find(a=>a.name===s);if(o){const a=Xr(t,o.glType);this.trySetUniform(a,s,n)}else this._logger.warnOnce(`Could not locate uniform named ${s}, this can happen if the uniform is unused in the shader code some GPUs will remove this as an optimization.`)}}}_loadImageSource(t){const e=t.image,i=e.getAttribute(z.Filtering),s=i?Ve(i):void 0,n=Ot(e.getAttribute(z.WrappingX)),o=Ot(e.getAttribute(z.WrappingY)),a=e.getAttribute("forceUpload")==="true",h=this._textureLoader.load(e,{filtering:s,wrapping:{x:n,y:o}},a);return e.removeAttribute("forceUpload"),this._textures.has(t)||this._textures.set(t,h),h}_setImages(t=!1){const e=this._gl;let i=this._startingTextureSlot;for(const[s,n]of Object.entries(this.images)){if(!n.isLoaded()){t||this._logger.warnOnce(`Image named ${s} in not loaded, nothing will be uploaded to the shader. Did you forget to add this to a loader? https://excaliburjs.com/docs/loaders/`);continue}const o=this._loadImageSource(n);o||t||this._logger.warnOnce(`Image ${s} (${n.image.src}) could not be loaded for some reason in shader ${this.name}`),e.activeTexture(e.TEXTURE0+i),e.bindTexture(e.TEXTURE_2D,o),this.trySetUniformInt(s,i),i++}}compile(){if(this._compiled)return this.program;const t=this._gl,e=this._compileShader(t,this.vertexSource,t.VERTEX_SHADER),i=this._compileShader(t,this.fragmentSource,t.FRAGMENT_SHADER);this.program=this._createProgram(t,e,i);const s=this.getAttributeDefinitions();for(const o of s)this.attributes[o.name]=o;const n=this.getUniformDefinitions();for(const o of n)this._uniforms[o.name]=o;return this._compiled=!0,this._onPostCompile&&this._onPostCompile(this),t.useProgram(this.program),Si._ACTIVE_SHADER_INSTANCE=this,this._dirtyUniforms&&(this._setUniforms(),this._dirtyUniforms=!1),this._setImages(!0),this.unuse(),this.program}getUniformDefinitions(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_UNIFORMS),i=[];for(let s=0;s<e;s++){const n=t.getActiveUniform(this.program,s),o=t.getUniformLocation(this.program,n.name);i.push({name:n.name,glType:n.type,location:o})}return i}getAttributeDefinitions(){const t=this._gl,e=t.getProgramParameter(this.program,t.ACTIVE_ATTRIBUTES),i=[];for(let s=0;s<e;s++){const n=t.getActiveAttrib(this.program,s),o=t.getAttribLocation(this.program,n.name);i.push({name:n.name,glType:qr(t,n.type),size:Vr(t,n.type),location:o,normalized:!1})}return i}addImageSource(t,e){Object.keys(this.images).length<this._maxTextureSlots?this.images[t]=e:this._logger.warn(`Max number texture slots ${this._maxTextureSlots} have been reached for material "${this.name}", no more textures will be uploaded due to hardware constraints.`)}removeImageSource(t){const e=this.images[t];e&&(this._textureLoader.delete(e.image),delete this.images[t])}setTexture(t,e){const i=this._gl;i.activeTexture(i.TEXTURE0+t),i.bindTexture(i.TEXTURE_2D,e)}setUniformBuffer(t,e,i=0){const s=this._gl,n=s.getUniformBlockIndex(this.program,t);n===s.INVALID_INDEX&&this._logger.warnOnce(`Invalid block name ${t}`);let o;this._uniformBuffers[t]?(o=this._uniformBuffers[t],o.bufferData.set(e),o.upload()):(o=new Nr({gl:s,data:e}),this._uniformBuffers[t]=o),s.uniformBlockBinding(this.program,n,i),s.bindBufferBase(s.UNIFORM_BUFFER,i,o.buffer)}trySetUniformBuffer(t,e,i=0){return this._compiled?this.isCurrentlyBound()?this._gl.getUniformBlockIndex(this.program,t)?(this.setUniformBuffer(t,e,i),!0):!1:(this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1):(this._logger.warn(`Must compile shader before setting a uniform block ${t} at binding point ${i}`),!1)}setUniformInt(t,e){this.setUniform("uniform1i",t,~~e)}trySetUniformInt(t,e){return this.trySetUniform("uniform1i",t,~~e)}setUniformIntArray(t,e){this.setUniform("uniform1iv",t,e)}trySetUniformIntArray(t,e){return this.trySetUniform("uniform1iv",t,e)}setUniformBoolean(t,e){this.setUniform("uniform1i",t,e?1:0)}trySetUniformBoolean(t,e){return this.trySetUniform("uniform1i",t,e?1:0)}setUniformFloat(t,e){this.setUniform("uniform1f",t,e)}trySetUniformFloat(t,e){return this.trySetUniform("uniform1f",t,e)}setUniformFloatArray(t,e){this.setUniform("uniform1fv",t,e)}trySetUniformFloatArray(t,e){return this.trySetUniform("uniform1fv",t,e)}setUniformFloatVector(t,e){this.setUniform("uniform2f",t,e.x,e.y)}trySetUniformFloatVector(t,e){return this.trySetUniform("uniform2f",t,e.x,e.y)}setUniformFloatColor(t,e){this.setUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}trySetUniformFloatColor(t,e){return this.trySetUniform("uniform4f",t,e.r/255,e.g/255,e.b/255,e.a)}setUniformMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,e.data)}setUniformAffineMatrix(t,e){this.setUniform("uniformMatrix4fv",t,!1,[e.data[0],e.data[1],0,0,e.data[2],e.data[3],0,0,0,0,1,0,e.data[4],e.data[5],0,1])}trySetUniformMatrix(t,e){return this.trySetUniform("uniformMatrix4fv",t,!1,e.data)}setUniform(t,e,...i){if(!this._compiled)throw Error(`Must compile shader before setting a uniform ${t}:${e}`);if(!this.isCurrentlyBound())throw Error("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms");const n=this._gl.getUniformLocation(this.program,e);if(n){const o=[n,...i];this._gl[t].apply(this._gl,o)}else throw Error(`Uniform ${t}:${e} doesn't exist or is not used in the shader source code, unused uniforms are optimized away by most browsers`)}trySetUniform(t,e,...i){if(!this._compiled)return this._logger.warn(`Must compile shader before setting a uniform ${t}:${e}`),!1;if(!this.isCurrentlyBound())return this._logger.warn("Currently accessed shader instance is not the current active shader in WebGL, must call `shader.use()` before setting uniforms"),!1;const n=this._gl.getUniformLocation(this.program,e);if(n){const o=[n,...i];this._gl[t].apply(this._gl,o)}else return!1;return!0}_createProgram(t,e,i){const s=t.createProgram();if(s===null)throw Error("Could not create graphics shader program");if(t.attachShader(s,e),t.attachShader(s,i),this._onPreLink&&this._onPreLink(s),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw Error(`Could not link the program: [${t.getProgramInfoLog(s)}]`);return s}_compileShader(t,e,i){const s=t.VERTEX_SHADER===i?"vertex":"fragment",n=t.createShader(i);if(n===null)throw Error(`Could not build shader: [${e}]`);if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const a=t.getShaderInfoLog(n);throw Error(`Could not compile ${s} shader:
|
|
76
90
|
|
|
77
91
|
${a}${this._processSourceForError(e,a)}`)}return n}_processSourceForError(t,e){if(!t)return e;const i=t.split(`
|
|
78
92
|
`),s=e.search(/\d:\d/),n=e.indexOf(" ",s),[o,a]=e.slice(s,n).split(":").map(h=>Number(h));for(let h=0;h<i.length;h++)i[h]=`${h+1}: ${i[h]}${a===h+1?" <----- ERROR!":""}`;return`
|
|
79
93
|
|
|
80
94
|
Source:
|
|
81
95
|
`+i.join(`
|
|
82
|
-
`)}};Yr._ACTIVE_SHADER_INSTANCE=null;let
|
|
96
|
+
`)}};Yr._ACTIVE_SHADER_INSTANCE=null;let Bt=Yr;const $h=`#version 300 es
|
|
83
97
|
precision mediump float;
|
|
84
98
|
|
|
85
99
|
uniform float deltaMs;
|
|
@@ -135,7 +149,7 @@ void main(){
|
|
|
135
149
|
float scale = sqrt(u_transform[0][0] * u_transform[0][0] + u_transform[1][1] * u_transform[1][1]);
|
|
136
150
|
gl_Position = vec4(transformedPos, 1.0 - lifePercent, 1.); // use life percent to sort z
|
|
137
151
|
gl_PointSize = mix(startSize, endSize, 1.0 - lifePercent) * scale;
|
|
138
|
-
}`,
|
|
152
|
+
}`,Zh=`#version 300 es
|
|
139
153
|
precision mediump float;
|
|
140
154
|
|
|
141
155
|
uniform sampler2D graphic;
|
|
@@ -177,11 +191,11 @@ void main(){
|
|
|
177
191
|
fragColor.a = startOpacity * circle * (fade ? lifePct : 1.0);// * mix(beginColor.a, endColor.a, 1.0 - lifePct);
|
|
178
192
|
fragColor.rgb *= fragColor.a;
|
|
179
193
|
}
|
|
180
|
-
}`,
|
|
194
|
+
}`,Ce=class ue{static integrate(t,e,i,s){const n=s/1e3;e.vel.addEqual(i.scale(n,ue._ACC)),e.vel.setTo(B(e.vel.x,-e.maxVel.x,e.maxVel.x),B(e.vel.y,-e.maxVel.y,e.maxVel.y)),t.pos.add(e.vel.scale(n,ue._VEL),ue._POS).addEqual(i.scale(.5*n*n,ue._VEL_ACC)),e.angularVelocity+=e.torque*(1/e.inertia)*n;const o=t.rotation+e.angularVelocity*n;t.scale.add(e.scaleFactor.scale(n,this._SCALE_FACTOR),ue._SCALE),t.get().setTransform(ue._POS,o,ue._SCALE)}};Ce._POS=new w(0,0),Ce._SCALE=new w(1,1),Ce._ACC=new w(0,0),Ce._VEL=new w(0,0),Ce._VEL_ACC=new w(0,0),Ce._SCALE_FACTOR=new w(0,0);let $r=Ce;class Zi extends At{constructor(t){super(),this.beginColor=T.White,this.endColor=T.White,this.life=300,this.fade=!1,this._rRate=1,this._gRate=1,this._bRate=1,this._aRate=0,this._currentColor=T.White,this.size=5,this.sizeRate=0,this.visible=!0,this.isOffscreen=!1,this.particleTransform="global",this.name=`Particle#${this.id}`,this.addComponent(this.transform=new P),this.addComponent(this.motion=new O),this.addComponent(this.graphics=new K),this.configure(t)}registerEmitter(t){if(this._emitter=t,this.particleTransform==="global"){const e=this._emitter.transform.globalPos;this.transform.pos=this.transform.pos.add(e),this.motion.vel=this.motion.vel.rotate(this._emitter.transform.globalRotation)}}configure(t){var e,i,s,n,o,a,h,l,c,u,_,f,m,p,x;this.particleTransform=(e=t.transform)!=null?e:this.particleTransform,this.life=(i=t.life)!=null?i:this.life,this.fade=(s=t.fade)!=null?s:this.fade,this.size=(n=t.size)!=null?n:this.size,this.endColor=(o=t.endColor)!=null?o:this.endColor.clone(),this.beginColor=(a=t.beginColor)!=null?a:this.beginColor.clone(),this._currentColor=this.beginColor.clone(),this.graphic=t.graphic,this.graphics.opacity=(h=t.opacity)!=null?h:this.graphics.opacity,this.transform.pos=(l=t.pos)!=null?l:this.transform.pos,this.transform.rotation=(c=t.rotation)!=null?c:0,this.transform.scale=b(1,1),this.transform.z=(u=t.z)!=null?u:0,this.motion.vel=(_=t.vel)!=null?_:this.motion.vel,this.motion.angularVelocity=(f=t.angularVelocity)!=null?f:0,this.motion.acc=(m=t.acc)!=null?m:this.motion.acc,this._rRate=(this.endColor.r-this.beginColor.r)/this.life,this._gRate=(this.endColor.g-this.beginColor.g)/this.life,this._bRate=(this.endColor.b-this.beginColor.b)/this.life,this._aRate=this.graphics.opacity/this.life,this.startSize=(p=t.startSize)!=null?p:0,this.endSize=(x=t.endSize)!=null?x:0,this.endSize>0&&this.startSize>0&&(this.sizeRate=(this.endSize-this.startSize)/this.life,this.size=this.startSize),this.graphic?(this.graphics.use(this.graphic),this.graphics.onPostDraw=void 0):(this.graphics.localBounds=F.fromDimension(this.size,this.size,w.Half),this.graphics.onPostDraw=v=>{v.save(),v.debug.drawPoint(b(0,0),{color:this._currentColor,size:this.size}),v.restore()})}kill(){var t;(t=this._emitter)!=null&&t.isActive?this._emitter.removeParticle(this):super.kill()}update(t,e){this.life=this.life-e,this.life<0&&this.kill(),this.fade&&(this.graphics.opacity=B(this._aRate*this.life,1e-4,1)),this.startSize&&this.endSize&&this.startSize>0&&this.endSize>0&&(this.size=B(this.sizeRate*e+this.size,Math.min(this.startSize,this.endSize),Math.max(this.startSize,this.endSize))),this._currentColor.r=B(this._currentColor.r+this._rRate*e,0,255),this._currentColor.g=B(this._currentColor.g+this._gRate*e,0,255),this._currentColor.b=B(this._currentColor.b+this._bRate*e,0,255),this._currentColor.a=this.graphics.opacity;let i=this.motion.acc;this.focus&&(i=this.focus.sub(this.transform.pos).normalize().scale(this.focusAccel||0).scale(e/1e3)),$r.integrate(this.transform,this.motion,i,e)}}Zi.DefaultConfig={beginColor:T.White,endColor:T.White,life:300,fade:!1,size:5,graphic:void 0,startSize:void 0,endSize:void 0};var Xt=(r=>(r.Global="global",r.Local="local",r))(Xt||{});class Zr{constructor(){this.type="ex.particle",this.priority=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Bt({graphicsContext:e,vertexSource:$h,fragmentSource:Zh,onPreLink:i=>{t.transformFeedbackVaryings(i,["finalPosition","finalVelocity","finalRotation","finalAngularVelocity","finalLifeMs"],t.INTERLEAVED_ATTRIBS)}}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho)}_getTexture(t){const e=t.getAttribute(z.Filtering),i=e?Ve(e):void 0,s=Ot(t.getAttribute(z.WrappingX)),n=Ot(t.getAttribute(z.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);return t.removeAttribute("forceUpload"),a}draw(t,e){var i,s,n,o,a,h,l,c,u;const _=this._gl;this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho);const f=t.particle.transform===Xt.Local?this._context.getTransform():this._context.getTransform().multiply(t.emitter.transform.get().inverse);this._shader.setUniformAffineMatrix("u_transform",f),this._shader.setUniformBoolean("fade",!!t.particle.fade),this._shader.setUniformBoolean("useTexture",!!t.particle.graphic),this._shader.setUniformFloat("maxLifeMs",(i=t.particle.life)!=null?i:2e3),this._shader.setUniformFloat("deltaMs",e),this._shader.setUniformFloatVector("gravity",(s=t.particle.acc)!=null?s:b(0,0)),this._shader.setUniformFloatColor("beginColor",(n=t.particle.beginColor)!=null?n:T.Transparent),this._shader.setUniformFloatColor("endColor",(o=t.particle.endColor)!=null?o:T.Transparent);let m=(a=t.particle.startSize)!=null?a:0,p=(h=t.particle.endSize)!=null?h:0;const x=(l=t.particle.size)!=null?l:0;if(x>0&&(m=x,p=x),this._shader.setUniformFloat("startSize",m!=null?m:10),this._shader.setUniformFloat("endSize",p!=null?p:10),this._shader.setUniformFloat("startOpacity",(c=t.particle.opacity)!=null?c:1),t.particle.focus&&(this._shader.setUniformFloatVector("focus",t.particle.focus),this._shader.setUniformFloat("focusAccel",(u=t.particle.focusAccel)!=null?u:0)),t.particle.graphic){const v=t.particle.graphic,g=this._getTexture(v.image.image);_.activeTexture(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g),this._shader.setUniformInt("graphic",0)}t.draw(_)}hasPendingDraws(){return!1}flush(){}dispose(){}}class Ht{constructor(t){this.type="dynamic";const{gl:e,size:i,type:s,data:n}=t;if(this._gl=e,this.buffer=this._gl.createBuffer(),!n&&!i)throw Error("Must either provide data or a size to the VertexBuffer");n?this.bufferData=n:this.bufferData=new Float32Array(i),this.type=s!=null?s:this.type,e.bindBuffer(e.ARRAY_BUFFER,this.buffer),e.bufferData(e.ARRAY_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,this.buffer)}unbind(){const t=this._gl;t.bindBuffer(t.ARRAY_BUFFER,null)}upload(t){const e=this._gl;e.bindBuffer(e.ARRAY_BUFFER,this.buffer),t?e.bufferSubData(e.ARRAY_BUFFER,0,this.bufferData,0,t):e.bufferData(e.ARRAY_BUFFER,this.bufferData,this.type==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}class Yt{constructor(t){this._logger=R.getInstance(),this._suppressWarnings=!1,this._layout=[],this._attributes=[],this._vertexTotalSizeBytes=0,this._initialized=!1;const{gl:e,shader:i,vertexBuffer:s,attributes:n,suppressWarnings:o}=t;this._gl=e,this._vertexBuffer=s,this._attributes=n,this._shader=i,this._suppressWarnings=o,i&&this.initialize()}get vertexBuffer(){return this._vertexBuffer}get attributes(){return this._attributes}get totalVertexSizeBytes(){return this._vertexTotalSizeBytes}set shader(t){t&&this._shader!==t&&(this._shader=t,this.initialize())}get shader(){return this._shader}initialize(){if(this._initialized||!this._shader)return;if(!this._shader.compiled)throw Error("Shader not compiled, shader must be compiled before defining a vertex layout");this._vertexTotalSizeBytes=0,this._layout.length=0;const t=this._shader.attributes;for(const n of this._attributes){const o=t[n[0]];if(!o){if(!Wr(this._shader.vertexSource,n[0]))throw Error(`The attribute named: ${n[0]} size ${n[1]} not found in the shader source code:
|
|
181
195
|
${this._shader.vertexSource}`);this._suppressWarnings||this._logger.warn(`The attribute named: ${n[0]} size ${n[1]} not found in the compiled shader. This is possibly a bug:
|
|
182
196
|
1. Not a bug, but should remove unused code - attribute "${n[0]}" is unused in vertex/fragment and has been automatically removed by glsl compiler.
|
|
183
197
|
2. Definitely a bug, attribute "${n[0]}" in layout has been mistyped or is missing in shader, check vertex/fragment source.`);const a=Gr(this._gl,this._shader.vertexSource,n[0]);this._layout.push({name:n[0],glType:a,size:n[1],location:-1,normalized:!1})}if(o){if(o.size!==n[1])throw Error(`VertexLayout size definition for attribute: [${n[0]}, ${n[1]}], doesn't match shader source size ${o.size}:
|
|
184
|
-
${this._shader.vertexSource}`);this._layout.push(o)}}let e=0;for(const n of this._layout){const o=
|
|
198
|
+
${this._shader.vertexSource}`);this._layout.push(o)}}let e=0;for(const n of this._layout){const o=yn(this._gl,n.glType);this._vertexTotalSizeBytes+=o*n.size,e+=n.size}this._vertexBuffer.bufferData.length%e!==0&&this._logger.warn(`The vertex component size (${e}) does NOT divide evenly into the specified vertex buffer (${this._vertexBuffer.bufferData.length})`);const i=this._gl;this._vao=i.createVertexArray(),i.bindVertexArray(this._vao),this._vertexBuffer.bind();let s=0;for(const n of this._layout)n.location!==-1&&(n.glType===i.INT?i.vertexAttribIPointer(n.location,n.size,n.glType,this.totalVertexSizeBytes,s):i.vertexAttribPointer(n.location,n.size,n.glType,n.normalized,this.totalVertexSizeBytes,s),i.enableVertexAttribArray(n.location)),s+=yn(i,n.glType)*n.size;i.bindVertexArray(null),this._vertexBuffer.unbind(),this._initialized=!0}use(t=!1,e){if(!this._shader)throw Error("No shader is associated with this vertex layout, a shader must be set");const i=this._gl;if(!this._shader.isCurrentlyBound())throw Error("Shader associated with this vertex layout is not active! Call shader.use() before layout.use()");this._vertexBuffer.bind(),t&&this._vertexBuffer.upload(e),i.bindVertexArray(this._vao)}}class jr{constructor(t,e){e.includes("v_texcoord")&&R.getInstance().warn(`ScreenShader: "v_texcoord" is deprecated in postprocessing fragment shaders will be removed in v1.0, use "v_uv" instead. Source [${e}]`);const i=t.__gl;this._shader=new Bt({graphicsContext:t,vertexSource:`#version 300 es
|
|
185
199
|
in vec2 a_position;
|
|
186
200
|
in vec2 a_uv;
|
|
187
201
|
out vec2 v_texcoord;
|
|
@@ -192,7 +206,7 @@ void main(){
|
|
|
192
206
|
// Pass the texcoord to the fragment shader.
|
|
193
207
|
v_texcoord = a_uv;
|
|
194
208
|
v_uv = a_uv;
|
|
195
|
-
}`,fragmentSource:e}),this._shader.compile(),this._buffer=new
|
|
209
|
+
}`,fragmentSource:e}),this._shader.compile(),this._buffer=new Ht({gl:i,type:"static",data:new Float32Array([-1,-1,0,0,-1,1,0,1,1,-1,1,0,1,-1,1,0,-1,1,0,1,1,1,1,1])}),this._layout=new Yt({gl:i,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2]]}),this._buffer.upload()}getShader(){return this._shader}getLayout(){return this._layout}}var $e=(r=>(r.Protanope="Protanope",r.Deuteranope="Deuteranope",r.Tritanope="Tritanope",r))($e||{});const jh=`#version 300 es
|
|
196
210
|
precision mediump float;
|
|
197
211
|
// our texture
|
|
198
212
|
uniform sampler2D u_image;
|
|
@@ -256,7 +270,7 @@ void main() {
|
|
|
256
270
|
} else {
|
|
257
271
|
fragColor = correction.rgba;
|
|
258
272
|
}
|
|
259
|
-
}`;class Qr{constructor(t,e=!1){this._colorBlindnessMode=t,this._simulate=!1,this._simulate=e}initialize(t){this._shader=new
|
|
273
|
+
}`;class Qr{constructor(t,e=!1){this._colorBlindnessMode=t,this._simulate=!1,this._simulate=e}initialize(t){this._shader=new jr(t,jh),this.simulate=this._simulate,this.colorBlindnessMode=this._colorBlindnessMode}getShader(){return this._shader.getShader()}getLayout(){return this._shader.getLayout()}set colorBlindnessMode(t){if(this._colorBlindnessMode=t,this._shader){const e=this._shader.getShader();e.use(),this._colorBlindnessMode===$e.Protanope?e.setUniformInt("u_type",0):this._colorBlindnessMode===$e.Deuteranope?e.setUniformInt("u_type",1):this._colorBlindnessMode===$e.Tritanope&&e.setUniformInt("u_type",2)}}get colorBlindnessMode(){return this._colorBlindnessMode}set simulate(t){if(this._simulate=t,this._shader){const e=this._shader.getShader();e.use(),e.setUniformBoolean("u_simulate",t)}}get simulate(){return this._simulate}}class Ze{constructor(t,e,i){this._logger=R.getInstance(),this._gl=t,this.buffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer);const s=e*6;if(!i)this.bufferData=new Uint32Array(s);else{const a=Math.floor(16383.5);this.bufferGlType=t.UNSIGNED_SHORT,this.bufferData=new Uint16Array(s),e>a&&this._logger.warn(`Total quads exceeds hardware index buffer limit (uint16), max(${a}) requested quads(${e})`)}let n=0;for(let o=0;o<s;o+=6)this.bufferData[o+0]=n+0,this.bufferData[o+1]=n+1,this.bufferData[o+2]=n+2,this.bufferData[o+3]=n+2,this.bufferData[o+4]=n+1,this.bufferData[o+5]=n+3,n+=4;t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.bufferData,t.STATIC_DRAW)}get size(){return this.bufferData.length}upload(){const t=this._gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.bufferData,t.STATIC_DRAW)}bind(){const t=this._gl;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.buffer)}dispose(){this._gl.deleteBuffer(this.buffer),this._gl=null}}const Qh=`#version 300 es
|
|
260
274
|
in vec2 a_position;
|
|
261
275
|
|
|
262
276
|
in vec2 a_uv;
|
|
@@ -276,7 +290,7 @@ void main() {
|
|
|
276
290
|
v_uv = a_uv;
|
|
277
291
|
v_screenuv = a_screenuv;
|
|
278
292
|
}
|
|
279
|
-
`,Jr=class
|
|
293
|
+
`,Jr=class La{constructor(t){this._logger=R.getInstance(),this._color=T.Transparent,this._initialized=!1,this._images={},this._uniforms={};const{color:e,name:i,vertexSource:s,fragmentSource:n,graphicsContext:o,images:a,uniforms:h}=t;if(this._name=i!=null?i:"anonymous material",this._vertexSource=s!=null?s:Qh,this._fragmentSource=n,this._color=e!=null?e:this._color,this._uniforms=h!=null?h:this._uniforms,this._images=a!=null?a:this._images,!o)throw Error(`Material ${i} must be provided an excalibur webgl graphics context`);o instanceof $t?this._initialize(o):this._logger.warn(`Material ${i} was created in 2D Canvas mode, currently only WebGL is supported`);{this.images.u_graphic&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_graphic, is this on purpose? If so ignore this warning.`),this.images.u_screen_texture&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_screen_texture, is this on purpose? If so ignore this warning.`);for(const l of Object.keys(this._uniforms))La.BuiltInUniforms.includes(l)&&this._logger.warn(`Material named "${this.name}" is overriding built in uniform ${l}, is this on purpose? If so ignore this warning.`)}}_initialize(t){this._initialized||(this._shader=t.createShader({name:this._name,vertexSource:this._vertexSource,fragmentSource:this._fragmentSource,uniforms:this._uniforms,images:this._images,startingTextureSlot:this.isUsingScreenTexture?2:1}),this._initialized=!0)}get uniforms(){return this._shader.uniforms}get images(){return this._shader.images}get color(){return this._color}set color(t){this._color=t}get name(){return this._name}get isUsingScreenTexture(){return this._fragmentSource.includes("u_screen_texture")}get isOverridingGraphic(){return!!this._images.u_graphic}update(t){this._shader&&(this._shader.use(),t(this._shader))}getShader(){return this._shader}addImageSource(t,e){this._shader.addImageSource(t,e),this.images.u_graphic&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_graphic, is this on purpose? If so ignore this warning.`),this.images.u_screen_texture&&this._logger.warn(`Material named "${this.name}" is overriding built in image u_screen_texture, is this on purpose? If so ignore this warning.`)}removeImageSource(t){this._shader.removeImageSource(t)}use(){if(this._initialized)this._shader.use(),this._shader.trySetUniformFloatColor("u_color",this._color);else throw Error(`Material ${this.name} not yet initialized, use the ExcaliburGraphicsContext.createMaterial() to work around this.`)}};Jr.BuiltInUniforms=["u_time_ms","u_opacity","u_resolution","u_graphic_resolution","u_size","u_matrix","u_transform","u_graphic","u_screen_texture"];let Kr=Jr;class Jh{constructor(){this.type="ex.debug-line",this.priority=0,this._maxLines=10922,this._vertexIndex=0,this._lineCount=0,this._startScratch=b(0,0),this._endScratch=b(0,0),this._lengthSoFar=0,this._currentlyDashed=!1}initialize(t,e){this._gl=t,this._context=e,this._shader=new Bt({graphicsContext:e,vertexSource:Gh,fragmentSource:Vh}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._vertexBuffer=new Ht({gl:t,size:42*this._maxLines,type:"dynamic"}),this._layout=new Yt({gl:t,vertexBuffer:this._vertexBuffer,shader:this._shader,attributes:[["a_position",2],["a_color",4],["a_lengthSoFar",1]]})}dispose(){this._vertexBuffer.dispose(),this._shader.dispose(),this._context=null,this._gl=null}draw(t,e,i,s=2,n=!1){(this._isFull()||this._currentlyDashed!==n)&&(this._currentlyDashed=n,this.flush()),this._lineCount++;const o=this._context.getTransform(),a=o.multiply(t,this._startScratch),h=o.multiply(e,this._endScratch),l=h.sub(a),c=a.distance(h),u=l.normal(),_=s/2,f=this._vertexBuffer.bufferData;f[this._vertexIndex++]=a.x-u.x*_,f[this._vertexIndex++]=a.y-u.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar,f[this._vertexIndex++]=a.x+u.x*_,f[this._vertexIndex++]=a.y+u.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar,f[this._vertexIndex++]=h.x-u.x*_,f[this._vertexIndex++]=h.y-u.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar+c,f[this._vertexIndex++]=h.x-u.x*_,f[this._vertexIndex++]=h.y-u.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar+c,f[this._vertexIndex++]=a.x+u.x*_,f[this._vertexIndex++]=a.y+u.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar,f[this._vertexIndex++]=h.x+u.x*_,f[this._vertexIndex++]=h.y+u.y*_,f[this._vertexIndex++]=i.r/255,f[this._vertexIndex++]=i.g/255,f[this._vertexIndex++]=i.b/255,f[this._vertexIndex++]=i.a,f[this._vertexIndex++]=this._lengthSoFar+c}_isFull(){return this._lineCount>=this._maxLines}hasPendingDraws(){return this._lineCount!==0}flush(){if(this._lineCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_dashed",this._currentlyDashed),t.drawArrays(t.TRIANGLES,0,this._lineCount*6),J.DrawnImagesCount+=this._lineCount,J.DrawCallCount++,this._vertexIndex=0,this._lineCount=0,this._lengthSoFar=0}}const Kh=`#version 300 es
|
|
280
294
|
in vec2 a_position;
|
|
281
295
|
in vec4 a_color;
|
|
282
296
|
in float a_size;
|
|
@@ -306,7 +320,104 @@ void main() {
|
|
|
306
320
|
color.a = color.a * alpha;
|
|
307
321
|
color.rgb = color.rgb * color.a;
|
|
308
322
|
fragColor = color;
|
|
309
|
-
}`;class el{constructor(){this.type="ex.point",this.priority=0,this._maxPoints=10922,this._pointCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new
|
|
323
|
+
}`;class el{constructor(){this.type="ex.debug-point",this.priority=0,this._maxPoints=10922,this._pointCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Bt({graphicsContext:e,vertexSource:Kh,fragmentSource:tl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._buffer=new Ht({gl:t,size:7*this._maxPoints,type:"dynamic"}),this._layout=new Yt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_color",4],["a_size",1]]})}dispose(){this._buffer.dispose(),this._shader.dispose(),this._context=null,this._gl=null}draw(t,e,i){this._isFull()&&this.flush(),this._pointCount++;const s=this._context.getTransform(),n=this._context.opacity,o=this._context.snapToPixel,a=s.multiply(t);o&&(a.x=~~(a.x+D),a.y=~~(a.y+D));const h=this._buffer.bufferData;h[this._vertexIndex++]=a.x,h[this._vertexIndex++]=a.y,h[this._vertexIndex++]=e.r/255,h[this._vertexIndex++]=e.g/255,h[this._vertexIndex++]=e.b/255,h[this._vertexIndex++]=e.a*n,h[this._vertexIndex++]=i}_isFull(){return this._pointCount>=this._maxPoints}hasPendingDraws(){return this._pointCount!==0}flush(){if(this._pointCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),t.drawArrays(t.POINTS,0,this._pointCount),J.DrawnImagesCount+=this._pointCount,J.DrawCallCount++,this._pointCount=0,this._vertexIndex=0}}const il=`#version 300 es
|
|
324
|
+
precision highp float;
|
|
325
|
+
|
|
326
|
+
// UV coord
|
|
327
|
+
in vec2 v_uv;
|
|
328
|
+
|
|
329
|
+
// Color coord to blend with image
|
|
330
|
+
in lowp vec4 v_color;
|
|
331
|
+
|
|
332
|
+
// Stroke color if used
|
|
333
|
+
in lowp vec4 v_strokeColor;
|
|
334
|
+
|
|
335
|
+
// Stroke thickness if used
|
|
336
|
+
in lowp float v_strokeThickness;
|
|
337
|
+
|
|
338
|
+
in float v_radius;
|
|
339
|
+
|
|
340
|
+
// Opacity
|
|
341
|
+
in float v_opacity;
|
|
342
|
+
|
|
343
|
+
out vec4 fragColor;
|
|
344
|
+
|
|
345
|
+
void main() {
|
|
346
|
+
// make (0, 0) the center the uv
|
|
347
|
+
vec2 uv = v_uv * 2.0 - 1.0;
|
|
348
|
+
|
|
349
|
+
vec4 color = v_color;
|
|
350
|
+
vec4 strokeColor = v_strokeColor;
|
|
351
|
+
|
|
352
|
+
float dist = 1.0 - length(uv);
|
|
353
|
+
float radius = dist * v_radius; // 0 is the edge
|
|
354
|
+
|
|
355
|
+
// Fade based on fwidth
|
|
356
|
+
float fade = fwidth(dot(uv, uv)) / 2.0;
|
|
357
|
+
|
|
358
|
+
float fill = smoothstep(-fade, fade, radius);
|
|
359
|
+
|
|
360
|
+
float stroke =
|
|
361
|
+
smoothstep(0.0, fade, radius) -
|
|
362
|
+
smoothstep(v_strokeThickness, v_strokeThickness + fade, radius);
|
|
363
|
+
|
|
364
|
+
strokeColor.a = stroke;
|
|
365
|
+
strokeColor.rgb *= strokeColor.a;
|
|
366
|
+
|
|
367
|
+
// vec4 finalColor = strokeColor;
|
|
368
|
+
|
|
369
|
+
color.a *= fill * (1.0 - stroke);
|
|
370
|
+
color.rgb *= color.a;
|
|
371
|
+
|
|
372
|
+
vec4 finalColor = mix(vec4(0.0), (color + strokeColor), fill);
|
|
373
|
+
finalColor.rgb = finalColor.rgb * v_opacity;
|
|
374
|
+
finalColor.a = finalColor.a * v_opacity;
|
|
375
|
+
|
|
376
|
+
fragColor = finalColor;
|
|
377
|
+
}
|
|
378
|
+
`,sl=`#version 300 es
|
|
379
|
+
in vec2 a_position;
|
|
380
|
+
|
|
381
|
+
// UV coordinate
|
|
382
|
+
in vec2 a_uv;
|
|
383
|
+
out vec2 v_uv;
|
|
384
|
+
|
|
385
|
+
// Opacity
|
|
386
|
+
in float a_opacity;
|
|
387
|
+
out float v_opacity;
|
|
388
|
+
|
|
389
|
+
in vec4 a_color;
|
|
390
|
+
out vec4 v_color;
|
|
391
|
+
|
|
392
|
+
in vec4 a_strokeColor;
|
|
393
|
+
out vec4 v_strokeColor;
|
|
394
|
+
|
|
395
|
+
in float a_strokeThickness;
|
|
396
|
+
out float v_strokeThickness;
|
|
397
|
+
|
|
398
|
+
in float a_radius;
|
|
399
|
+
out float v_radius;
|
|
400
|
+
|
|
401
|
+
uniform mat4 u_matrix;
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
void main() {
|
|
405
|
+
// Set the vertex position using the ortho transform matrix
|
|
406
|
+
gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);
|
|
407
|
+
|
|
408
|
+
// Pass through UV coords
|
|
409
|
+
v_uv = a_uv;
|
|
410
|
+
// Pass through the Opacity to the fragment shader
|
|
411
|
+
v_opacity = a_opacity;
|
|
412
|
+
// Pass through the color to the fragment shader
|
|
413
|
+
v_color = a_color;
|
|
414
|
+
// Pass through the stroke color to the fragment shader
|
|
415
|
+
v_strokeColor = a_strokeColor;
|
|
416
|
+
// Pass through the stroke thickenss to the fragment shader
|
|
417
|
+
v_strokeThickness = a_strokeThickness;
|
|
418
|
+
v_radius = a_radius;
|
|
419
|
+
}
|
|
420
|
+
`;class nl{constructor(){this.type="ex.debug-circle",this.priority=0,this._maxCircles=10922,this._circleCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Bt({graphicsContext:e,fragmentSource:il,vertexSource:sl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new Ht({gl:t,size:60*this._maxCircles,type:"dynamic"}),this._layout=new Yt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1],["a_radius",1]]}),this._quads=new Ze(t,this._maxCircles,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._context=null,this._gl=null}_isFull(){return this._circleCount>=this._maxCircles}draw(t,e,i,s=T.Transparent,n=0){this._isFull()&&this.flush(),this._circleCount++;const o=this._context.getTransform(),a=o.getScaleX(),h=this._context.opacity,l=this._context.snapToPixel,c=o.multiply(t.add(b(-e,-e))),u=o.multiply(t.add(b(e,-e))),_=o.multiply(t.add(b(e,e))),f=o.multiply(t.add(b(-e,e)));l&&(c.x=~~(c.x+D),c.y=~~(c.y+D),u.x=~~(u.x+D),u.y=~~(u.y+D),f.x=~~(f.x+D),f.y=~~(f.y+D),_.x=~~(_.x+D),_.y=~~(_.y+D));const m=0,p=0,x=1,v=1,g=this._layout.vertexBuffer.bufferData;g[this._vertexIndex++]=c.x,g[this._vertexIndex++]=c.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=p,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a,g[this._vertexIndex++]=f.x,g[this._vertexIndex++]=f.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=v,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a,g[this._vertexIndex++]=u.x,g[this._vertexIndex++]=u.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=p,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a,g[this._vertexIndex++]=_.x,g[this._vertexIndex++]=_.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=v,g[this._vertexIndex++]=h,g[this._vertexIndex++]=i.r/255,g[this._vertexIndex++]=i.g/255,g[this._vertexIndex++]=i.b/255,g[this._vertexIndex++]=i.a,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n,g[this._vertexIndex++]=e*a}hasPendingDraws(){return this._circleCount!==0}flush(){if(this._circleCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,this._circleCount*6,this._quads.bufferGlType,0),J.DrawnImagesCount+=this._circleCount,J.DrawCallCount++,this._circleCount=0,this._vertexIndex=0}}const rl=`#version 300 es
|
|
310
421
|
in vec2 a_position;
|
|
311
422
|
|
|
312
423
|
in vec2 a_texcoord;
|
|
@@ -317,7 +428,7 @@ void main() {
|
|
|
317
428
|
|
|
318
429
|
// Pass the texcoord to the fragment shader.
|
|
319
430
|
v_texcoord = a_texcoord;
|
|
320
|
-
}`,
|
|
431
|
+
}`,ol=`#version 300 es
|
|
321
432
|
precision mediump float;
|
|
322
433
|
|
|
323
434
|
// Passed in from the vertex shader.
|
|
@@ -330,7 +441,7 @@ out vec4 fragColor;
|
|
|
330
441
|
|
|
331
442
|
void main() {
|
|
332
443
|
fragColor = texture(u_texture, v_texcoord);
|
|
333
|
-
}`;class
|
|
444
|
+
}`;class al{constructor(t){const e=t.__gl;this._gl=e,this._shader=new Bt({graphicsContext:t,vertexSource:rl,fragmentSource:ol}),this._shader.compile(),this._buffer=new Ht({gl:e,type:"static",data:new Float32Array([-1,-1,0,0,-1,1,0,1,1,-1,1,0,1,-1,1,0,-1,1,0,1,1,1,1,1])}),this._layout=new Yt({gl:e,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_texcoord",2]]}),this._buffer.upload()}renderWithPostProcessor(t){const e=this._gl,i=t.getShader();i.use(),t.getLayout().use(),e.activeTexture(e.TEXTURE0),i.trySetUniformInt("u_image",0),t.onDraw&&t.onDraw(),e.drawArrays(e.TRIANGLES,0,6)}renderToScreen(){const t=this._gl;this._shader.use(),this._layout.use(),t.drawArrays(t.TRIANGLES,0,6)}}const hl=`#version 300 es
|
|
334
445
|
precision mediump float;
|
|
335
446
|
|
|
336
447
|
// UV coord
|
|
@@ -377,7 +488,7 @@ void main(){
|
|
|
377
488
|
color.rgb=color.rgb*v_opacity;
|
|
378
489
|
color.a=color.a*v_opacity;
|
|
379
490
|
fragColor=color*v_tint;
|
|
380
|
-
}`,
|
|
491
|
+
}`,ll=`#version 300 es
|
|
381
492
|
in vec2 a_position;
|
|
382
493
|
|
|
383
494
|
// Opacity
|
|
@@ -416,12 +527,12 @@ void main(){
|
|
|
416
527
|
v_textureIndex=a_textureIndex;
|
|
417
528
|
// Pass through the tint
|
|
418
529
|
v_tint=a_tint;
|
|
419
|
-
}`;class
|
|
530
|
+
}`;class cl{constructor(t){this.type="ex.image",this.priority=0,this._maxImages=10922,this._maxTextures=0,this._imageCount=0,this._textures=[],this._textureIndex=0,this._textureToIndex=new Map,this._images=new Set,this._vertexIndex=0,this._imageToWidth=new Map,this._imageToHeight=new Map,this._view=[0,0,0,0],this._dest=[0,0],this._quad=[0,0,0,0,0,0,0,0],this._defaultTint=T.White,this.pixelArtSampler=t.pixelArtSampler,this.uvPadding=t.uvPadding}initialize(t,e){this._gl=t,this._context=e;const i=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),s=Cn(t,i);this._maxTextures=Math.min(i,s);const n=this._transformFragmentSource(hl,this._maxTextures);this._shader=new Bt({graphicsContext:e,fragmentSource:n,vertexSource:ll}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._shader.setUniformIntArray("u_textures",[...Array(this._maxTextures)].map((o,a)=>a)),this._buffer=new Ht({gl:t,size:48*this._maxImages,type:"dynamic"}),this._layout=new Yt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_opacity",1],["a_res",2],["a_texcoord",2],["a_textureIndex",1],["a_tint",4]]}),this._quads=new Ze(t,this._maxImages,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._textures.length=0,this._context=null,this._gl=null}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let n=0;n<e;n++)n===0?s+=`if (v_textureIndex <= ${n}.5) {
|
|
420
531
|
`:s+=` else if (v_textureIndex <= ${n}.5) {
|
|
421
532
|
`,s+=` vec2 uv = u_pixelart ? uv_iq(v_texcoord, v_res) : v_texcoord;
|
|
422
533
|
`,s+=` color = texture(u_textures[${n}], uv);
|
|
423
534
|
`,s+=` }
|
|
424
|
-
`;return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){if(this._images.has(t))return;const e=t.getAttribute(
|
|
535
|
+
`;return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){if(this._images.has(t))return;const e=t.getAttribute(z.Filtering),i=e?Ve(e):void 0,s=Ot(t.getAttribute(z.WrappingX)),n=Ot(t.getAttribute(z.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&(this._textures.push(a),this._textureToIndex.set(a,this._textureIndex++),this._images.add(t))}_bindTextures(t){for(let e=0;e<this._maxTextures;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,this._textures[e]||this._textures[0])}_getTextureIdForImage(t){var e;if(t){const i=this._context.textureLoader.get(t);return(e=this._textureToIndex.get(i))!=null?e:-1}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}draw(t,e,i,s,n,o,a,h,l){var c,u,_,f;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);const m=this._getImageWidth(t),p=this._getImageHeight(t);let x=m||s||0,v=p||n||0;this._view[0]=0,this._view[1]=0,this._view[2]=(c=s!=null?s:m)!=null?c:0,this._view[3]=(u=n!=null?n:p)!=null?u:0,this._dest[0]=e!=null?e:1,this._dest[1]=i!=null?i:1,o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(this._view[0]=e!=null?e:1,this._view[1]=i!=null?i:1,this._view[2]=(_=s!=null?s:m)!=null?_:0,this._view[3]=(f=n!=null?n:p)!=null?f:0,this._dest[0]=o,this._dest[1]=a,x=h,v=l),e=this._view[0],i=this._view[1];const g=this._view[2],y=this._view[3],S=this._context.getTransform(),A=this._context.opacity,I=this._context.snapToPixel;this._quad[0]=this._dest[0],this._quad[1]=this._dest[1],this._quad[2]=this._dest[0]+x,this._quad[3]=this._dest[1],this._quad[4]=this._dest[0],this._quad[5]=this._dest[1]+v,this._quad[6]=this._dest[0]+x,this._quad[7]=this._dest[1]+v,S.multiplyQuadInPlace(this._quad),I&&(this._quad[0]=~~(this._quad[0]+V(this._quad[0])*D),this._quad[1]=~~(this._quad[1]+V(this._quad[1])*D),this._quad[2]=~~(this._quad[2]+V(this._quad[2])*D),this._quad[3]=~~(this._quad[3]+V(this._quad[3])*D),this._quad[4]=~~(this._quad[4]+V(this._quad[4])*D),this._quad[5]=~~(this._quad[5]+V(this._quad[5])*D),this._quad[6]=~~(this._quad[6]+V(this._quad[6])*D),this._quad[7]=~~(this._quad[7]+V(this._quad[7])*D));const C=this._context.tint||this._defaultTint,L=this._getTextureIdForImage(t),U=m||x,G=p||v,et=(e+this.uvPadding)/U,ht=(i+this.uvPadding)/G,$=(e+g-this.uvPadding)/U,W=(i+y-this.uvPadding)/G,ct=m,ft=p,E=this._layout.vertexBuffer.bufferData;E[this._vertexIndex++]=this._quad[0],E[this._vertexIndex++]=this._quad[1],E[this._vertexIndex++]=A,E[this._vertexIndex++]=ct,E[this._vertexIndex++]=ft,E[this._vertexIndex++]=et,E[this._vertexIndex++]=ht,E[this._vertexIndex++]=L,E[this._vertexIndex++]=C.r/255,E[this._vertexIndex++]=C.g/255,E[this._vertexIndex++]=C.b/255,E[this._vertexIndex++]=C.a,E[this._vertexIndex++]=this._quad[4],E[this._vertexIndex++]=this._quad[5],E[this._vertexIndex++]=A,E[this._vertexIndex++]=ct,E[this._vertexIndex++]=ft,E[this._vertexIndex++]=et,E[this._vertexIndex++]=W,E[this._vertexIndex++]=L,E[this._vertexIndex++]=C.r/255,E[this._vertexIndex++]=C.g/255,E[this._vertexIndex++]=C.b/255,E[this._vertexIndex++]=C.a,E[this._vertexIndex++]=this._quad[2],E[this._vertexIndex++]=this._quad[3],E[this._vertexIndex++]=A,E[this._vertexIndex++]=ct,E[this._vertexIndex++]=ft,E[this._vertexIndex++]=$,E[this._vertexIndex++]=ht,E[this._vertexIndex++]=L,E[this._vertexIndex++]=C.r/255,E[this._vertexIndex++]=C.g/255,E[this._vertexIndex++]=C.b/255,E[this._vertexIndex++]=C.a,E[this._vertexIndex++]=this._quad[6],E[this._vertexIndex++]=this._quad[7],E[this._vertexIndex++]=A,E[this._vertexIndex++]=ct,E[this._vertexIndex++]=ft,E[this._vertexIndex++]=$,E[this._vertexIndex++]=W,E[this._vertexIndex++]=L,E[this._vertexIndex++]=C.r/255,E[this._vertexIndex++]=C.g/255,E[this._vertexIndex++]=C.b/255,E[this._vertexIndex++]=C.a}hasPendingDraws(){return this._imageCount!==0}flush(){if(this._imageCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0,48*this._imageCount),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_pixelart",this.pixelArtSampler),this._bindTextures(t),this._quads.bind(),t.drawElements(t.TRIANGLES,this._imageCount*6,this._quads.bufferGlType,0),J.DrawnImagesCount+=this._imageCount,J.DrawCallCount++,this._imageCount=0,this._vertexIndex=0,this._textures.length=0,this._textureIndex=0,this._textureToIndex.clear(),this._images.clear(),this._imageToWidth.clear(),this._imageToHeight.clear()}}const dl=`#version 300 es
|
|
425
536
|
|
|
426
537
|
precision mediump float;
|
|
427
538
|
|
|
@@ -506,7 +617,7 @@ void main() {
|
|
|
506
617
|
|
|
507
618
|
// vec4 finalColor = mix(v4FromColor, v4ToColor, mixPct);
|
|
508
619
|
// gl_FragColor = finalColor;
|
|
509
|
-
}`,
|
|
620
|
+
}`,ul=`#version 300 es
|
|
510
621
|
in vec2 a_position;
|
|
511
622
|
|
|
512
623
|
// UV coordinate
|
|
@@ -548,7 +659,7 @@ void main() {
|
|
|
548
659
|
v_strokeColor = a_strokeColor;
|
|
549
660
|
// Pass through the stroke thickenss to the fragment shader
|
|
550
661
|
v_strokeThickness = a_strokeThickness;
|
|
551
|
-
}`;class
|
|
662
|
+
}`;class _l{constructor(){this.type="ex.rectangle",this.priority=0,this._maxRectangles=10922,this._rectangleCount=0,this._vertexIndex=0,this._transparent=T.Transparent,this._scratch1=b(0,0),this._scratch2=b(0,0),this._scratch3=b(0,0),this._scratch4=b(0,0)}initialize(t,e){this._gl=t,this._context=e,this._shader=new Bt({graphicsContext:e,fragmentSource:dl,vertexSource:ul}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new Ht({gl:t,size:64*this._maxRectangles,type:"dynamic"}),this._layout=new Yt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_size",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1]]}),this._quads=new Ze(t,this._maxRectangles,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._context=null,this._gl=null}_isFull(){return this._rectangleCount>=this._maxRectangles}draw(...t){t[0]instanceof w&&t[1]instanceof w?this.drawLine.apply(this,t):this.drawRectangle.apply(this,t)}drawLine(t,e,i,s=1){this._isFull()&&this.flush(),this._rectangleCount++;const n=this._context.getTransform(),o=this._context.opacity,a=this._context.snapToPixel,h=e.sub(t),l=h.magnitude,c=h.normalize().perpendicular(),u=s/2,_=n.multiply(c.scale(u,this._scratch1).add(t,this._scratch1),this._scratch1),f=n.multiply(c.scale(-u,this._scratch2).add(t,this._scratch2),this._scratch2),m=n.multiply(c.scale(u,this._scratch3).add(e,this._scratch3),this._scratch3),p=n.multiply(c.scale(-u,this._scratch4).add(e,this._scratch4),this._scratch4);a&&(_.x=~~(_.x+D),_.y=~~(_.y+D),m.x=~~(m.x+D),m.y=~~(m.y+D),f.x=~~(f.x+D),f.y=~~(f.y+D),p.x=~~(p.x+D),p.y=~~(p.y+D));const x=0,v=0,g=1,y=1,S=this._transparent,A=0,I=1,C=this._layout.vertexBuffer.bufferData;C[this._vertexIndex++]=_.x,C[this._vertexIndex++]=_.y,C[this._vertexIndex++]=x,C[this._vertexIndex++]=v,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/I,C[this._vertexIndex++]=f.x,C[this._vertexIndex++]=f.y,C[this._vertexIndex++]=x,C[this._vertexIndex++]=y,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/I,C[this._vertexIndex++]=m.x,C[this._vertexIndex++]=m.y,C[this._vertexIndex++]=g,C[this._vertexIndex++]=v,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/I,C[this._vertexIndex++]=p.x,C[this._vertexIndex++]=p.y,C[this._vertexIndex++]=g,C[this._vertexIndex++]=y,C[this._vertexIndex++]=l,C[this._vertexIndex++]=s,C[this._vertexIndex++]=o,C[this._vertexIndex++]=i.r/255,C[this._vertexIndex++]=i.g/255,C[this._vertexIndex++]=i.b/255,C[this._vertexIndex++]=i.a,C[this._vertexIndex++]=S.r/255,C[this._vertexIndex++]=S.g/255,C[this._vertexIndex++]=S.b/255,C[this._vertexIndex++]=S.a,C[this._vertexIndex++]=A/I}drawRectangle(t,e,i,s,n=T.Transparent,o=0){this._isFull()&&this.flush(),this._rectangleCount++;const a=this._context.getTransform(),h=this._context.opacity,l=this._context.snapToPixel,c=a.multiply(t.add(b(0,0))),u=a.multiply(t.add(b(e,0))),_=a.multiply(t.add(b(e,i))),f=a.multiply(t.add(b(0,i)));l&&(c.x=~~(c.x+D),c.y=~~(c.y+D),u.x=~~(u.x+D),u.y=~~(u.y+D),f.x=~~(f.x+D),f.y=~~(f.y+D),_.x=~~(_.x+D),_.y=~~(_.y+D));const m=0,p=0,x=1,v=1,g=this._layout.vertexBuffer.bufferData;g[this._vertexIndex++]=c.x,g[this._vertexIndex++]=c.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=p,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o,g[this._vertexIndex++]=f.x,g[this._vertexIndex++]=f.y,g[this._vertexIndex++]=m,g[this._vertexIndex++]=v,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o,g[this._vertexIndex++]=u.x,g[this._vertexIndex++]=u.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=p,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o,g[this._vertexIndex++]=_.x,g[this._vertexIndex++]=_.y,g[this._vertexIndex++]=x,g[this._vertexIndex++]=v,g[this._vertexIndex++]=e,g[this._vertexIndex++]=i,g[this._vertexIndex++]=h,g[this._vertexIndex++]=s.r/255,g[this._vertexIndex++]=s.g/255,g[this._vertexIndex++]=s.b/255,g[this._vertexIndex++]=s.a,g[this._vertexIndex++]=n.r/255,g[this._vertexIndex++]=n.g/255,g[this._vertexIndex++]=n.b/255,g[this._vertexIndex++]=n.a,g[this._vertexIndex++]=o}hasPendingDraws(){return this._rectangleCount!==0}flush(){if(this._rectangleCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,this._rectangleCount*6,this._quads.bufferGlType,0),J.DrawnImagesCount+=this._rectangleCount,J.DrawCallCount++,this._rectangleCount=0,this._vertexIndex=0}}const fl=`#version 300 es
|
|
552
663
|
precision highp float;
|
|
553
664
|
|
|
554
665
|
// UV coord
|
|
@@ -600,7 +711,7 @@ void main() {
|
|
|
600
711
|
finalColor.rgb = finalColor.rgb * v_opacity;
|
|
601
712
|
finalColor.a = finalColor.a * v_opacity;
|
|
602
713
|
fragColor = finalColor;
|
|
603
|
-
}`,
|
|
714
|
+
}`,gl=`#version 300 es
|
|
604
715
|
in vec2 a_position;
|
|
605
716
|
|
|
606
717
|
// UV coordinate
|
|
@@ -637,7 +748,7 @@ void main() {
|
|
|
637
748
|
v_strokeColor = a_strokeColor;
|
|
638
749
|
// Pass through the stroke thickenss to the fragment shader
|
|
639
750
|
v_strokeThickness = a_strokeThickness;
|
|
640
|
-
}`;class
|
|
751
|
+
}`;class pl{constructor(){this.type="ex.circle",this.priority=0,this._maxCircles=10922,this._circleCount=0,this._vertexIndex=0}initialize(t,e){this._gl=t,this._context=e,this._shader=new Bt({graphicsContext:e,fragmentSource:fl,vertexSource:gl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._buffer=new Ht({gl:t,size:56*this._maxCircles,type:"dynamic"}),this._layout=new Yt({gl:t,shader:this._shader,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_opacity",1],["a_color",4],["a_strokeColor",4],["a_strokeThickness",1]]}),this._quads=new Ze(t,this._maxCircles,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._shader.dispose(),this._context=null,this._gl=null}_isFull(){return this._circleCount>=this._maxCircles}draw(t,e,i,s=T.Transparent,n=0){this._isFull()&&this.flush(),this._circleCount++;const o=this._context.getTransform(),a=this._context.opacity,h=this._context.snapToPixel,l=o.multiply(t.add(b(-e,-e))),c=o.multiply(t.add(b(e,-e))),u=o.multiply(t.add(b(e,e))),_=o.multiply(t.add(b(-e,e)));h&&(l.x=~~(l.x+D),l.y=~~(l.y+D),c.x=~~(c.x+D),c.y=~~(c.y+D),_.x=~~(_.x+D),_.y=~~(_.y+D),u.x=~~(u.x+D),u.y=~~(u.y+D));const f=0,m=0,p=1,x=1,v=this._layout.vertexBuffer.bufferData;v[this._vertexIndex++]=l.x,v[this._vertexIndex++]=l.y,v[this._vertexIndex++]=f,v[this._vertexIndex++]=m,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e,v[this._vertexIndex++]=_.x,v[this._vertexIndex++]=_.y,v[this._vertexIndex++]=f,v[this._vertexIndex++]=x,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e,v[this._vertexIndex++]=c.x,v[this._vertexIndex++]=c.y,v[this._vertexIndex++]=p,v[this._vertexIndex++]=m,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e,v[this._vertexIndex++]=u.x,v[this._vertexIndex++]=u.y,v[this._vertexIndex++]=p,v[this._vertexIndex++]=x,v[this._vertexIndex++]=a,v[this._vertexIndex++]=i.r/255,v[this._vertexIndex++]=i.g/255,v[this._vertexIndex++]=i.b/255,v[this._vertexIndex++]=i.a,v[this._vertexIndex++]=s.r/255,v[this._vertexIndex++]=s.g/255,v[this._vertexIndex++]=s.b/255,v[this._vertexIndex++]=s.a,v[this._vertexIndex++]=n/e}hasPendingDraws(){return this._circleCount!==0}flush(){if(this._circleCount===0)return;const t=this._gl;this._shader.use(),this._layout.use(!0),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._quads.bind(),t.drawElements(t.TRIANGLES,this._circleCount*6,this._quads.bufferGlType,0),J.DrawnImagesCount+=this._circleCount,J.DrawCallCount++,this._circleCount=0,this._vertexIndex=0}}class ml{constructor(){this.z=0,this.priority=0,this.renderer="",this.transform=Z.identity(),this.state={z:0,opacity:1,tint:T.White,material:null},this.args=new Array(10)}}class to{constructor(){this.type="ex.material",this.priority=0,this._textures=[]}initialize(t,e){this._gl=t,this._context=e,this._buffer=new Ht({gl:t,size:24,type:"dynamic"}),this._layout=new Yt({gl:t,vertexBuffer:this._buffer,attributes:[["a_position",2],["a_uv",2],["a_screenuv",2]],suppressWarnings:!0}),this._quads=new Ze(t,1,!0)}dispose(){this._buffer.dispose(),this._quads.dispose(),this._textures.length=0,this._context=null,this._gl=null}draw(t,e,i,s,n,o,a,h,l){var c,u,_,f,m;const p=this._gl,x=this._context.material;if(!x)return;const v=this._context.getTransform(),g=this._context.opacity,y=x.getShader(),S=this._layout.vertexBuffer.bufferData;let A=0,I=(t==null?void 0:t.width)||s||0,C=(t==null?void 0:t.height)||n||0,L=[0,0,(c=s!=null?s:t==null?void 0:t.width)!=null?c:0,(u=n!=null?n:t==null?void 0:t.height)!=null?u:0],U=[e!=null?e:1,i!=null?i:1];o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(L=[e!=null?e:1,i!=null?i:1,(_=s!=null?s:t==null?void 0:t.width)!=null?_:0,(f=n!=null?n:t==null?void 0:t.height)!=null?f:0],U=[o,a],I=h,C=l),e=L[0],i=L[1];const G=L[2],et=L[3],ht=b(U[0],U[1]),$=b(U[0]+I,U[1]),W=b(U[0],U[1]+C),ct=b(U[0]+I,U[1]+C),ft=t.width||I,E=t.height||C,Ie=e/ft,Re=i/E,Me=(e+G-.01)/ft,Ci=(i+et-.01)/E,ir=v.getPosition(),Pa=ir.add(ct),Ea=ir.x/this._context.width,Ia=ir.y/this._context.height,Ra=Pa.x/this._context.width,Ma=Pa.y/this._context.height;S[A++]=ht.x,S[A++]=ht.y,S[A++]=Ie,S[A++]=Re,S[A++]=Ea,S[A++]=Ia,S[A++]=W.x,S[A++]=W.y,S[A++]=Ie,S[A++]=Ci,S[A++]=Ea,S[A++]=Ma,S[A++]=$.x,S[A++]=$.y,S[A++]=Me,S[A++]=Re,S[A++]=Ra,S[A++]=Ia,S[A++]=ct.x,S[A++]=ct.y,S[A++]=Me,S[A++]=Ci,S[A++]=Ra,S[A++]=Ma;let Fa=this._addImageAsTexture(t);x.use(),this._layout.shader=y,this._layout.use(!0),y.trySetUniformFloat("u_time_ms",performance.now()),y.trySetUniformFloat("u_opacity",g),y.trySetUniformFloatVector("u_resolution",b(this._context.width,this._context.height)),y.trySetUniformFloatVector("u_graphic_resolution",b(ft,E)),y.trySetUniformFloatVector("u_size",b(G,et)),y.trySetUniformMatrix("u_matrix",this._context.ortho),y.trySetUniformMatrix("u_transform",v.to4x4()),x.isOverridingGraphic&&(m=x.images.u_graphic)!=null&&m.image&&(Fa=this._addImageAsTexture(x.images.u_graphic.image)),p.activeTexture(p.TEXTURE0+0),p.bindTexture(p.TEXTURE_2D,Fa),y.trySetUniformInt("u_graphic",0),x.isUsingScreenTexture&&(p.activeTexture(p.TEXTURE0+1),p.bindTexture(p.TEXTURE_2D,this._context.materialScreenTexture),y.trySetUniformInt("u_screen_texture",1)),this._quads.bind(),p.drawElements(p.TRIANGLES,6,this._quads.bufferGlType,0),J.DrawnImagesCount++,J.DrawCallCount++}_addImageAsTexture(t){const e=t.getAttribute(z.Filtering),i=e?Ve(e):void 0,s=Ot(t.getAttribute(z.WrappingX)),n=Ot(t.getAttribute(z.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);return t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&this._textures.push(a),a}hasPendingDraws(){return!1}flush(){}}const vl=`#version 300 es
|
|
641
752
|
precision mediump float;
|
|
642
753
|
|
|
643
754
|
// UV coord
|
|
@@ -705,7 +816,7 @@ void main(){
|
|
|
705
816
|
color.rgb = color.rgb * v_opacity;
|
|
706
817
|
color.a = color.a * v_opacity;
|
|
707
818
|
fragColor = color * v_tint;
|
|
708
|
-
}`,
|
|
819
|
+
}`,wl=`#version 300 es
|
|
709
820
|
layout(location=0) in vec2 pos;
|
|
710
821
|
layout(location=1) in vec2 a_texcoord;
|
|
711
822
|
out vec2 v_texcoord;
|
|
@@ -759,14 +870,14 @@ void main(){
|
|
|
759
870
|
v_size = a_size;
|
|
760
871
|
v_texture_index = a_texture_index;
|
|
761
872
|
v_tint = a_tint;
|
|
762
|
-
}`;class
|
|
873
|
+
}`;class xl{constructor(t){this.type="ex.image-v2",this.priority=0,this._maxImages=2e4,this._maxTextures=0,this._components=22,this._imageCount=0,this._textures=[],this._textureIndex=0,this._textureToIndex=new Map,this._images=new Set,this._vertexIndex=0,this._imageToWidth=new Map,this._imageToHeight=new Map,this._view=[0,0,0,0],this._dest=[0,0],this._defaultTint=T.White,this.pixelArtSampler=t.pixelArtSampler,this.uvPadding=t.uvPadding}initialize(t,e){this._gl=t,this._context=e;const i=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),s=Cn(t,i);this._maxTextures=Math.min(i,s);const n=this._transformFragmentSource(vl,this._maxTextures);this._shader=new Bt({graphicsContext:e,fragmentSource:n,vertexSource:wl}),this._shader.compile(),this._shader.use(),this._shader.setUniformMatrix("u_matrix",e.ortho),this._shader.setUniformIntArray("u_textures",[...Array(this._maxTextures)].map((u,_)=>_)),this._vao=t.createVertexArray(),t.bindVertexArray(this._vao),this._quadMesh=new Float32Array([0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,0,1,0,1,1,1,1,1]),this._meshBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._meshBuffer),t.bufferData(t.ARRAY_BUFFER,this._quadMesh,t.STATIC_DRAW),t.vertexAttribPointer(0,2,t.FLOAT,!1,16,0),t.enableVertexAttribArray(0),t.vertexAttribPointer(1,2,t.FLOAT,!1,16,8),t.enableVertexAttribArray(1),t.bindBuffer(t.ARRAY_BUFFER,null);const o=this._components;this._transformData=new Ht({gl:t,size:o*this._maxImages,type:"dynamic"}),this._transformData.bind();let a=0,h=2;const l=4,c=o*4;t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(2),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(3),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(4),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(5),a+=2*l,t.vertexAttribPointer(h++,1,t.FLOAT,!1,c,a),t.enableVertexAttribArray(6),a+=1*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(7),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(8),a+=2*l,t.vertexAttribPointer(h++,1,t.FLOAT,!1,c,a),t.enableVertexAttribArray(9),a+=1*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(10),a+=2*l,t.vertexAttribPointer(h++,2,t.FLOAT,!1,c,a),t.enableVertexAttribArray(11),a+=2*l,t.vertexAttribPointer(h++,4,t.FLOAT,!1,c,a),t.enableVertexAttribArray(12),a+=4*l,t.vertexAttribDivisor(2,1),t.vertexAttribDivisor(3,1),t.vertexAttribDivisor(4,1),t.vertexAttribDivisor(5,1),t.vertexAttribDivisor(6,1),t.vertexAttribDivisor(7,1),t.vertexAttribDivisor(8,1),t.vertexAttribDivisor(9,1),t.vertexAttribDivisor(10,1),t.vertexAttribDivisor(11,1),t.vertexAttribDivisor(12,1),t.bindVertexArray(null)}_bindData(t){const e=this._components;this._transformData.bind(),this._transformData.upload(e*this._imageCount),t.bindVertexArray(this._vao)}dispose(){this._transformData.dispose(),this._shader.dispose(),this._textures.length=0,this._context=null,this._gl=null}_transformFragmentSource(t,e){let i=t.replace("%%count%%",e.toString()),s="";for(let n=0;n<e;n++)n===0?s+=`if (v_texture_index <= ${n}.5) {
|
|
763
874
|
`:s+=` else if (v_texture_index <= ${n}.5) {
|
|
764
875
|
`,s+=` color = texture(u_textures[${n}], uv);
|
|
765
876
|
`,s+=` }
|
|
766
|
-
`;return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){if(this._images.has(t))return;const e=t.getAttribute(O.Filtering),i=e?Ge(e):void 0,s=Ut(t.getAttribute(O.WrappingX)),n=Ut(t.getAttribute(O.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&(this._textures.push(a),this._textureToIndex.set(a,this._textureIndex++),this._images.add(t))}_bindTextures(t){const e=Math.min(this._textureIndex,this._maxTextures);for(let i=0;i<e;i++)t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,this._textures[i]||this._textures[0])}_getTextureIdForImage(t){var e;if(t){const i=this._context.textureLoader.get(t);return(e=this._textureToIndex.get(i))!=null?e:-1}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}draw(t,e,i,s,n,o,a,h,l){var c,u,_,f;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);const p=this._getImageWidth(t),g=this._getImageHeight(t);let w=p||s||0,m=g||n||0;this._view[0]=0,this._view[1]=0,this._view[2]=(c=s!=null?s:p)!=null?c:0,this._view[3]=(u=n!=null?n:g)!=null?u:0,this._dest[0]=e!=null?e:1,this._dest[1]=i!=null?i:1,o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(this._view[0]=e!=null?e:1,this._view[1]=i!=null?i:1,this._view[2]=(_=s!=null?s:p)!=null?_:0,this._view[3]=(f=n!=null?n:g)!=null?f:0,this._dest[0]=o,this._dest[1]=a,w=h,m=l),e=this._view[0],i=this._view[1];const b=this._view[2],T=this._view[3],C=this._context.getTransform(),S=this._context.opacity;this._context.snapToPixel&&(this._dest[0]=~~(this._dest[0]+B),this._dest[1]=~~(this._dest[1]+B));const y=this._context.tint||this._defaultTint,k=this._getTextureIdForImage(t),U=p||w,z=g||m,Y=(e+this.uvPadding)/U,ht=(i+this.uvPadding)/z,$=(e+b-this.uvPadding)/U,G=(i+T-this.uvPadding)/z,ct=p,ft=g,E=this._transformData.bufferData;E[this._vertexIndex++]=this._dest[0],E[this._vertexIndex++]=this._dest[1],E[this._vertexIndex++]=C.data[0],E[this._vertexIndex++]=C.data[1],E[this._vertexIndex++]=C.data[2],E[this._vertexIndex++]=C.data[3],E[this._vertexIndex++]=C.data[4],E[this._vertexIndex++]=C.data[5],E[this._vertexIndex++]=S,E[this._vertexIndex++]=w,E[this._vertexIndex++]=m,E[this._vertexIndex++]=ct,E[this._vertexIndex++]=ft,E[this._vertexIndex++]=k,E[this._vertexIndex++]=Y,E[this._vertexIndex++]=ht,E[this._vertexIndex++]=$,E[this._vertexIndex++]=G,E[this._vertexIndex++]=y.r/255,E[this._vertexIndex++]=y.g/255,E[this._vertexIndex++]=y.b/255,E[this._vertexIndex++]=y.a}hasPendingDraws(){return this._imageCount!==0}flush(){if(this._imageCount===0)return;const t=this._gl;this._shader.use(),this._bindData(t),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_pixelart",this.pixelArtSampler),this._bindTextures(t),t.drawArraysInstanced(t.TRIANGLES,0,6,this._imageCount),st.DrawnImagesCount+=this._imageCount,st.DrawCallCount++,t.bindVertexArray(null),this._imageCount=0,this._vertexIndex=0,this._textures.length=0,this._textureIndex=0,this._textureToIndex.clear(),this._images.clear(),this._imageToWidth.clear(),this._imageToHeight.clear()}}const B=1e-4;class vl{constructor(t){this._webglCtx=t,this._debugText=new un}drawRect(t,e,i,s,n={color:P.Black}){this.drawLine(x(t,e),x(t+i,e),{...n}),this.drawLine(x(t+i,e),x(t+i,e+s),{...n}),this.drawLine(x(t+i,e+s),x(t,e+s),{...n}),this.drawLine(x(t,e+s),x(t,e),{...n})}drawLine(t,e,i){var s;this._webglCtx.draw("ex.line",t,e,(s=i==null?void 0:i.color)!=null?s:P.Black)}drawPoint(t,e={color:P.Black,size:5}){this._webglCtx.draw("ex.point",t,e.color,e.size)}drawText(t,e){this._debugText.write(this._webglCtx,t,e)}}class Xt{constructor(t){this._logger=R.getInstance(),this._renderers=new Map,this._lazyRenderersFactory=new Map,this.imageRenderer=De.isEnabled("use-legacy-image-renderer")?"ex.image":"ex.image-v2",this._isDrawLifecycle=!1,this.useDrawSorting=!0,this._drawCallPool=new Ui(()=>new fl,void 0,4e3),this._drawCallIndex=0,this._drawCalls=new Array(4e3).fill(null),this._postProcessTargets=[],this._postprocessors=[],this._transform=new zh,this._state=new Ur,this.snapToPixel=!1,this.smoothing=!1,this.pixelArtSampler=!1,this.uvPadding=.01,this.backgroundColor=P.ExcaliburBlue,this.multiSampleAntialiasing=!0,this.transparency=!0,this._isContextLost=!1,this._disposed=!1,this._imageToWidth=new Map,this._imageToHeight=new Map,this.debug=new vl(this),this._totalPostProcessorTime=0;const{canvasElement:e,context:i,enableTransparency:s,antialiasing:n,uvPadding:o,multiSampleAntialiasing:a,pixelArtSampler:h,powerPreference:l,snapToPixel:c,backgroundColor:u,useDrawSorting:_,garbageCollector:f,handleContextLost:p,handleContextRestored:g}=t;if(this.__gl=i!=null?i:e.getContext("webgl2",{antialias:n!=null?n:this.smoothing,premultipliedAlpha:!1,alpha:s!=null?s:this.transparency,depth:!1,powerPreference:l!=null?l:"high-performance"}),!this.__gl)throw Error("Failed to retrieve webgl context from browser");p&&this.__gl.canvas.addEventListener("webglcontextlost",p,!1),g&&this.__gl.canvas.addEventListener("webglcontextrestored",g,!1),this.__gl.canvas.addEventListener("webglcontextlost",()=>{this._isContextLost=!0}),this.__gl.canvas.addEventListener("webglcontextrestored",()=>{this._isContextLost=!1}),this.textureLoader=new qe(this.__gl,f),this.snapToPixel=c!=null?c:this.snapToPixel,this.smoothing=n!=null?n:this.smoothing,this.transparency=s!=null?s:this.transparency,this.pixelArtSampler=h!=null?h:this.pixelArtSampler,this.uvPadding=o!=null?o:this.uvPadding,this.multiSampleAntialiasing=typeof a=="boolean"?a:this.multiSampleAntialiasing,this.samples=typeof a=="object"?a.samples:void 0,this.backgroundColor=u!=null?u:this.backgroundColor,this.useDrawSorting=_!=null?_:this.useDrawSorting,this._drawCallPool.disableWarnings=!0,this._drawCallPool.preallocate(),this._init()}get z(){return this._state.current.z}set z(t){this._state.current.z=t}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get width(){return this.__gl.canvas.width}get height(){return this.__gl.canvas.height}get ortho(){return this._ortho}checkIfResolutionSupported(t){let e=!0;return(t.width>4096||t.height>4096)&&(e=!1),e}dispose(){if(!this._disposed){this._disposed=!0,this.textureLoader.dispose();for(const t of this._renderers.values())t.dispose();this._renderers.clear(),this._drawCallPool.dispose(),this._drawCalls.length=0,this.__gl=null}}_init(){const t=this.__gl;if(this._ortho=yt.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.blendEquationSeparate(t.FUNC_ADD,t.FUNC_ADD),t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA),t.depthMask(!1),this.register(new al({uvPadding:this.uvPadding,pixelArtSampler:this.pixelArtSampler})),this.register(new to),this.register(new cl),this.register(new _l),this.register(new el),this.register(new Jh),this.lazyRegister("ex.particle",()=>new jr),this.register(new ml({uvPadding:this.uvPadding,pixelArtSampler:this.pixelArtSampler})),this.materialScreenTexture=t.createTexture(),!this.materialScreenTexture)throw new Error("Could not create screen texture!");t.bindTexture(t.TEXTURE_2D,this.materialScreenTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT),t.bindTexture(t.TEXTURE_2D,null),this._screenRenderer=new nl(this),this._renderTarget=new Hi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height}),this._postProcessTargets=[new Hi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height}),new Hi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height})],this._msaaTarget=new Hi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height,antialias:this.multiSampleAntialiasing,samples:this.samples})}register(t){this._renderers.set(t.type,t),t.initialize(this.__gl,this)}lazyRegister(t,e){this._lazyRenderersFactory.set(t,e)}get(t){let e=this._renderers.get(t);if(!e){const i=this._lazyRenderersFactory.get(t);i&&(this._logger.debug("lazy init renderer:",t),e=i(),this.register(e))}return e}_isCurrentRenderer(t){return!this._currentRenderer||this._currentRenderer===t}beginDrawLifecycle(){this._isDrawLifecycle=!0}endDrawLifecycle(){this._isDrawLifecycle=!1}draw(t,...e){if(e.length>9)throw new Error("Only 10 or less renderer arguments are supported!;");if(this._isDrawLifecycle||this._logger.warnOnce(`Attempting to draw outside the the drawing lifecycle (preDraw/postDraw) is not supported and is a source of bugs/errors.
|
|
767
|
-
If you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPostDraw handler.`),this._isContextLost){this._logger.errorOnce(`Unable to draw ${t}, the webgl context is lost`);return}const i=this.get(t);if(i)if(this.useDrawSorting){const s=this._drawCallPool.get();s.z=this._state.current.z,s.priority=i.priority,s.renderer=t,this.getTransform().clone(s.transform),s.state.z=this._state.current.z,s.state.opacity=this._state.current.opacity,s.state.tint=this._state.current.tint,s.state.material=this._state.current.material,s.args[0]=e[0],s.args[1]=e[1],s.args[2]=e[2],s.args[3]=e[3],s.args[4]=e[4],s.args[5]=e[5],s.args[6]=e[6],s.args[7]=e[7],s.args[8]=e[8],s.args[9]=e[9],this._drawCalls[this._drawCallIndex++]=s}else this._currentRenderer||(this._currentRenderer=i),this._isCurrentRenderer(i)||this._currentRenderer.flush(),i.draw(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9]),this._currentRenderer=i;else throw Error(`No renderer with name ${t} has been registered`)}resetTransform(){this._transform.reset()}updateViewport(t){const e=this.__gl;this._ortho=this._ortho=
|
|
768
|
-
`);const s=i.reduce((_,f)=>_.length>f.length?_:f);this._applyFont(this.ctx);const n=this.ctx.measureText(s);let o=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);const a=o*i.length;o=a;const h=a-Math.abs(n.actualBoundingBoxAscent),l=0,c=0;return new
|
|
769
|
-
`);if(e==null)return s;for(let n=0;n<s.length;n++){let o=s[n],a="";if(this.measureText(o).width>e){for(;this.measureText(o).width>e;)a=o[o.length-1]+a,o=o.slice(0,-1);s[n]=o,s[n+1]=a}}return this._cachedText=t,this._cachedLines=s,this._cachedRenderWidth=e,s}}class Ce extends it{constructor(t={}){var e,i,s,n,o,a,h,l,c,u,_,f,p,g,w,m,b,T,C,S;super(t),this.filtering=mt.Blended,this.quality=2,this.padding=2,this.smoothing=!1,this.lineWidth=1,this.lineDash=[],this.color=P.Black,this.family="sans-serif",this.style=hn.Normal,this.bold=!1,this.unit=rn.Px,this.textAlign=on.Left,this.baseAlign=an.Top,this.direction=ln.LeftToRight,this.lineHeight=void 0,this.size=10,this._textBounds=new D,this.smoothing=(e=t==null?void 0:t.smoothing)!=null?e:this.smoothing,this.padding=(i=t==null?void 0:t.padding)!=null?i:this.padding,this.color=(s=t==null?void 0:t.color)!=null?s:this.color,this.strokeColor=(n=t==null?void 0:t.strokeColor)!=null?n:this.strokeColor,this.lineDash=(o=t==null?void 0:t.lineDash)!=null?o:this.lineDash,this.lineWidth=(a=t==null?void 0:t.lineWidth)!=null?a:this.lineWidth,this.filtering=(h=t==null?void 0:t.filtering)!=null?h:this.filtering,this.family=(l=t==null?void 0:t.family)!=null?l:this.family,this.style=(c=t==null?void 0:t.style)!=null?c:this.style,this.bold=(u=t==null?void 0:t.bold)!=null?u:this.bold,this.size=(_=t==null?void 0:t.size)!=null?_:this.size,this.unit=(f=t==null?void 0:t.unit)!=null?f:this.unit,this.textAlign=(p=t==null?void 0:t.textAlign)!=null?p:this.textAlign,this.baseAlign=(g=t==null?void 0:t.baseAlign)!=null?g:this.baseAlign,this.direction=(w=t==null?void 0:t.direction)!=null?w:this.direction,this.lineHeight=(m=t==null?void 0:t.lineHeight)!=null?m:this.lineHeight,this.quality=(b=t==null?void 0:t.quality)!=null?b:this.quality,t!=null&&t.shadow&&(this.shadow={},this.shadow.blur=(T=t.shadow.blur)!=null?T:this.shadow.blur,this.shadow.offset=(C=t.shadow.offset)!=null?C:this.shadow.offset,this.shadow.color=(S=t.shadow.color)!=null?S:this.shadow.color),this._textMeasurement=new $e(this,"",P.Black)}clone(){return new Ce({...this.cloneGraphicOptions(),size:this.size,unit:this.unit,family:this.family,style:this.style,bold:this.bold,textAlign:this.textAlign,baseAlign:this.baseAlign,direction:this.direction,shadow:this.shadow?{blur:this.shadow.blur,offset:this.shadow.offset,color:this.shadow.color}:void 0})}get fontString(){return`${this.style} ${this.bold?"bold":""} ${this.size}${this.unit} ${this.family}`}get localBounds(){return this._textBounds}_drawImage(t,e,i){}_rotate(t){var e;const i=(e=this.origin)!=null?e:this._textBounds.center;t.translate(i.x,i.y),t.rotate(this.rotation),t.translate(-i.x,-i.y)}_flip(t){this.flipHorizontal&&(t.translate(this._textBounds.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,-this._textBounds.height/2/this.scale.y),t.scale(1,-1))}measureTextWithoutCache(t,e){return this._textMeasurement.measureText(t,e)}measureText(t,e){return Gi.measureText(t,this,e)}_postDraw(t){t.restore()}render(t,e,i,s,n,o){const a=Gi.getTextInstance(e,this,i);this._textBounds=a.dimensions,this._preDraw(t,s,n),a.render(t,s,n,o),this._postDraw(t)}}class ui extends it{constructor(t){var e,i;super(t),this._text="",this._textWidth=0,this._textHeight=0,this.font=(e=t.font)!=null?e:new Ce,this.color=(i=t.color)!=null?i:this.color,this.text=t.text,this.maxWidth=t.maxWidth}clone(){var t,e;return new ui({text:this.text.slice(),color:(e=(t=this.color)==null?void 0:t.clone())!=null?e:P.Black,font:this.font.clone(),maxWidth:this.maxWidth})}get text(){return this._text}set text(t){this._text=t,this._calculateDimension()}get font(){return this._font}set font(t){this._font=t}get width(){return this._textWidth===0&&this._calculateDimension(),this._textWidth*this.scale.x}get height(){return this._textHeight===0&&this._calculateDimension(),this._textHeight*this.scale.y}_calculateDimension(){const{width:t,height:e}=this.font.measureText(this._text,this.maxWidth);this._textWidth=t,this._textHeight=e}get localBounds(){return this.font.measureText(this._text,this.maxWidth).scale(this.scale)}_rotate(t){}_flip(t){}_preDraw(t,e,i){(this.isStale()||this.font.isStale())&&(this.font.flipHorizontal=this.flipHorizontal,this.font.flipVertical=this.flipVertical,this.font.rotation=this.rotation,this.font.origin=this.origin,this.font.opacity=this.opacity),this.font.tint=this.tint,super._preDraw(t,e,i)}_drawImage(t,e,i){var s;let n=P.Black;this.font instanceof Ce&&(n=(s=this.color)!=null?s:this.font.color);const{width:o,height:a}=this.font.measureText(this._text,this.maxWidth);this._textWidth=o,this._textHeight=a,this.font.render(t,this._text,n,e,i,this.maxWidth),this.font.showDebug&&(t.debug.drawRect(e-o,i-a,o*2,a*2),this.maxWidth!=null&&t.debug.drawRect(e,i,this.maxWidth,this.height,{color:P.Yellow}))}}function Sn(r){return!!r.tick}class j extends Dt{constructor(t){super(),this._logger=R.getInstance(),this._current="default",this._graphics={},this._options={},this.material=null,this.isVisible=!0,this.forceOnScreen=!1,this.opacity=1,this._offset=new se(v.Zero,()=>this.recalculateBounds()),this._anchor=new se(v.Half,()=>this.recalculateBounds()),this.flipHorizontal=!1,this.flipVertical=!1,this.copyGraphics=!1,t={visible:this.isVisible,graphics:{},...t};const{current:e,anchor:i,color:s,opacity:n,visible:o,graphics:a,offset:h,copyGraphics:l,onPreDraw:c,onPostDraw:u,onPreTransformDraw:_,onPostTransformDraw:f}=t;for(const[p,g]of Object.entries(a))g instanceof it?this._graphics[p]=g:(this._graphics[p]=g.graphic,this._options[p]=g.options);this.offset=h!=null?h:this.offset,this.opacity=n!=null?n:this.opacity,this.anchor=i!=null?i:this.anchor,this.color=s!=null?s:this.color,this.copyGraphics=l!=null?l:this.copyGraphics,this.onPreDraw=c!=null?c:this.onPreDraw,this.onPostDraw=u!=null?u:this.onPostDraw,this.onPreDraw=_!=null?_:this.onPreTransformDraw,this.onPostTransformDraw=f!=null?f:this.onPostTransformDraw,this.isVisible=!!o,this._current=e!=null?e:this._current,e&&this._graphics[e]&&this.use(e)}get visible(){return this.isVisible}set visible(t){this.isVisible=t}get offset(){return this._offset}set offset(t){this._offset=new se(t,()=>this.recalculateBounds()),this.recalculateBounds()}get anchor(){return this._anchor}set anchor(t){this._anchor=new se(t,()=>this.recalculateBounds()),this.recalculateBounds()}get color(){return this._color}set color(t){if(t){this._color=t.clone();const e=this.current;(e instanceof We||e instanceof ui)&&(e.color=this._color)}}getGraphic(t){return this._graphics[t]}getOptions(t){return this._options[t]}getNames(){return Object.keys(this._graphics)}get current(){return this._graphics[this._current]}get currentOptions(){return this._options[this._current]}get graphics(){return this._graphics}get options(){return this._options}add(t,e,i){let s="default",n=null,o;if(typeof t=="string"&&e instanceof it&&(s=t,n=e,o=i),t instanceof it&&!(e instanceof it)&&(n=t,o=e),!n)throw new Error("Need to provide a graphic or valid graphic string");return this._graphics[s]=this.copyGraphics?n.clone():n,this._options[s]=this.copyGraphics?{...o}:o,s==="default"&&this.use("default"),n}remove(t){delete this._graphics[t],delete this._options[t],this._current===t&&(this._current="default",this.recalculateBounds())}use(t,e){var i;if(t instanceof it){let s=t;this.copyGraphics&&(s=t.clone()),this._current="default",this._graphics[this._current]=s,this._options[this._current]=e}else this._current=t,this._options[this._current]=e,this._current in this._graphics||this._logger.warn(`Graphic ${this._current} is not registered with the graphics component owned by ${(i=this.owner)==null?void 0:i.name}. Nothing will be drawn.`);return this.recalculateBounds(),this.current}hide(){this._current="ex.none"}set localBounds(t){this._localBounds=t}recalculateBounds(){let t=new D;const e=this._graphics[this._current],i=this._options[this._current];if(!e){this._localBounds=t;return}let s=this.anchor,n=this.offset;i!=null&&i.anchor&&(s=i.anchor),i!=null&&i.offset&&(n=i.offset);const o=e.localBounds,a=-o.width*s.x+n.x,h=-o.height*s.y+n.y;e instanceof Ne&&!e.useAnchor?t=e==null?void 0:e.localBounds.combine(t):t=e==null?void 0:e.localBounds.translate(x(a,h)).combine(t),this._localBounds=t}get localBounds(){return(!this._localBounds||this._localBounds.hasZeroDimensions())&&this.recalculateBounds(),this._localBounds}get bounds(){let t=this.localBounds;if(this.owner){const e=this.owner.get(A);e&&(t=t.transform(e.get().matrix))}return t}update(t,e=0){const i=this.current;i&&Sn(i)&&i.tick(t,e)}clone(){const t=new j;return t._graphics={...this._graphics},t._options={...this._options},t.offset=this.offset.clone(),this.color&&(t.color=this.color.clone()),t.opacity=this.opacity,t.anchor=this.anchor.clone(),t.copyGraphics=this.copyGraphics,t.onPreDraw=this.onPreDraw,t.onPostDraw=this.onPostDraw,t.isVisible=this.isVisible,t}}class ae extends Dt{constructor(t){var e,i;super(),this.useColliderShape=!0,this.useGraphicsBounds=!0,this.useColliderShape=(e=t==null?void 0:t.useColliderShape)!=null?e:this.useColliderShape,this.useGraphicsBounds=(i=t==null?void 0:t.useGraphicsBounds)!=null?i:this.useGraphicsBounds,this.localBounds=t==null?void 0:t.localBounds}}function Se(r){return!!r&&r.length===4}const bt=class{static CreateReversibleEasingFunction(t){return(e,i,s,n)=>s<i?i-(t(e,s,i,n)-s):t(e,i,s,n)}static CreateVectorEasingFunction(t){return(e,i,s,n)=>new v(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}};bt.Linear=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,e*r/i+t)),bt.EaseInQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,e*r*r+t)),bt.EaseOutQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,-e*r*(r-2)+t)),bt.EaseInOutQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i/2,r<1?e/2*r*r+t:(r--,-e/2*(r*(r-2)-1)+t))),bt.EaseInCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,e*r*r*r+t)),bt.EaseOutCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,r--,e*(r*r*r+1)+t)),bt.EaseInOutCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i/2,r<1?e/2*r*r*r+t:(r-=2,e/2*(r*r*r+2)+t)));let It=bt;class eo{constructor(t){this._actions=[],this._currentAction=null,this._completedActions=[],this._entity=t}add(t){this._actions.push(t)}remove(t){const e=this._actions.indexOf(t);this._actions.splice(e,1)}clearActions(){this._actions.length=0,this._completedActions.length=0,this._currentAction&&this._currentAction.stop()}getActions(){return this._actions.concat(this._completedActions)}getIncompleteActions(){return this._actions}getCurrentAction(){return this._currentAction}hasNext(){return this._actions.length>0}isComplete(){return this._actions.length===0}reset(){this._actions=this.getActions();const t=this._actions.length;for(let e=0;e<t;e++)this._actions[e].reset();this._completedActions=[]}update(t){if(this._actions.length>0&&(this._currentAction!==this._actions[0]&&(this._currentAction=this._actions[0],this._entity.emit("actionstart",new Ys(this._currentAction,this._entity))),this._currentAction.update(t),this._currentAction.isComplete(this._entity))){this._entity.emit("actioncomplete",new $s(this._currentAction,this._entity));const e=this._actions.shift();e&&this._completedActions.push(e)}}}let wl=0;function N(){return wl++}class io{constructor(t,e,i){this.id=N(),this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new _i(t),this._actionQueue=this._repeatContext.getQueue(),this._repeat=i,this._originalRepeat=i,this._repeatBuilder(this._repeatContext),this._repeat--}update(t){this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext),this._repeat--),this._actionQueue.update(t)}isComplete(){return this._stopped||this._repeat<=0&&this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._repeat=this._originalRepeat}}class so{constructor(t,e){this.id=N(),this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new _i(t),this._actionQueue=this._repeatContext.getQueue(),this._repeatBuilder(this._repeatContext)}update(t){this._stopped||(this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext)),this._actionQueue.update(t))}isComplete(){return this._stopped}stop(){this._stopped=!0,this._actionQueue.clearActions()}reset(){}}function no(r){return r.offset instanceof v&&typeof r.duration=="number"}class ro{constructor(t,e){this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._legacyEasing=It.Linear,this._easing=Ti,this._useLegacyEasing=!1;var i;if(this._offset=e.offset,this._easing=(i=e.easing)!=null?i:this._easing,Se(e.easing)&&(this._legacyEasing=e.easing,this._useLegacyEasing=!0),this._tx=t.get(A),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only MoveBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._start=this._tx.pos.clone(),this._end=this._start.add(this._offset),this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=this._tx.pos;let s=0,n=0;this._useLegacyEasing?(s=this._legacyEasing(e,this._start.x,this._end.x,1),n=this._legacyEasing(e,this._start.y,this._end.y,1)):(s=ot(this._start.x,this._end.x,this._easing(e)),n=ot(this._start.y,this._end.y,this._easing(e)));const o=t/1e3,a=o===0?0:(s-i.x)/o,h=o===0?0:(n-i.y)/o;this._motion.vel.x=a,this._motion.vel.y=h,this.isComplete(this.entity)&&(this._tx.pos=x(this._end.x,this._end.y),this._motion.vel=x(0,0))}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.vel=x(0,0),this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class Tn{constructor(t,e,i,s){if(this.id=N(),this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(A),this._motion=t.get(H),this._speed=s,this._offset=new v(e,i),s<=0)throw R.getInstance().error("Attempted to moveBy with speed less than or equal to zero : "+s),new Error("Speed must be greater than 0 pixels per second")}update(t){this._started||(this._started=!0,this._start=new v(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.magnitude,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=x(this._end.x,this._end.y),this._motion.vel=x(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(A);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=x(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function oo(r){return r.pos instanceof v&&typeof r.duration=="number"}class ao{constructor(t,e){this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._easing=Ti,this._legacyEasing=It.Linear,this._useLegacyEasing=!1;var i;if(this._end=e.pos,this._easing=(i=e.easing)!=null?i:this._easing,Se(e.easing)&&(this._legacyEasing=e.easing,this._useLegacyEasing=!0),this._tx=t.get(A),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only moveTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._start=this._tx.pos.clone(),this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=this._tx.pos;let s=0,n=0;this._useLegacyEasing?(s=this._legacyEasing(e,this._start.x,this._end.x,1),n=this._legacyEasing(e,this._start.y,this._end.y,1)):(s=ot(this._start.x,this._end.x,this._easing(e)),n=ot(this._start.y,this._end.y,this._easing(e)));const o=t/1e3,a=o===0?0:(s-i.x)/o,h=o===0?0:(n-i.y)/o;this._motion.vel.x=a,this._motion.vel.y=h,this.isComplete(this.entity)&&(this._tx.pos=x(this._end.x,this._end.y),this._motion.vel=x(0,0))}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.vel=x(0,0),this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class Pn{constructor(t,e,i,s){this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._end=new v(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new v(this._tx.pos.x,this._tx.pos.y),this._distance=this._start.distance(this._end),this._dir=this._end.sub(this._start).normalize());const e=this._dir.scale(this._speed);this._motion.vel=x(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=x(this._end.x,this._end.y),this._motion.vel=x(0,0))}isComplete(t){const e=t.get(A);return this._stopped||new v(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=x(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function xl(r){return typeof r.angle=="number"&&typeof r.duration=="number"}class ho{constructor(t,e){this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._endAngle=0,this._startAngle=0;var i;if(this._endAngle=e.angle,this._tx=t.get(A),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only RotateTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._rotationType=(i=e.rotationType)!=null?i:Z.ShortestPath,this._currentMs=this._durationMs}update(t){this._started||(this._startAngle=this._tx.rotation,this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=ps(this._startAngle,this._endAngle,this._rotationType,e),s=this._tx.rotation,n=t/1e3,o=n===0?0:(i-s)/n;this._motion.angularVelocity=o,this.isComplete(this.entity)&&(this._tx.rotation=this._endAngle,this._motion.angularVelocity=0)}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.angularVelocity=0,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class lo{constructor(t,e,i,s){this.id=N(),this._started=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._end=e,this._speed=i,this._rotationType=s||Z.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const e=Math.abs(this._end-this._start),i=et-e;switch(e>i?(this._shortDistance=i,this._longDistance=e):(this._shortDistance=e,this._longDistance=i),this._shortestPathIsPositive=(this._start-this._end+et)%et>=Math.PI,this._rotationType){case Z.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case Z.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case Z.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case Z.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance;break}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function bl(r){return typeof r.angleRadiansOffset=="number"&&typeof r.duration=="number"}class co{constructor(t,e){this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._offset=0,this._startAngle=0,this._endAngle=0;var i;if(this._offset=e.angleRadiansOffset,this._tx=t.get(A),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only RotateBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._rotationType=(i=e.rotationType)!=null?i:Z.ShortestPath,this._currentMs=this._durationMs}update(t){this._started||(this._startAngle=this._tx.rotation,this._endAngle=Zt(this._startAngle+this._offset),this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=ps(this._startAngle,this._endAngle,this._rotationType,e),s=this._tx.rotation,n=t/1e3,o=n===0?0:(i-s)/n;this._motion.angularVelocity=o,this.isComplete()&&(this._tx.rotation=this._endAngle,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.angularVelocity=0,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class uo{constructor(t,e,i,s){this.id=N(),this._started=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._speed=i,this._offset=e,this._rotationType=s||Z.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation,this._end=this._start+this._offset;const e=Math.abs(this._end-this._start),i=et-e;switch(e>i?(this._shortDistance=i,this._longDistance=e):(this._shortDistance=e,this._longDistance=i),this._shortestPathIsPositive=(this._start-this._end+et)%et>=Math.PI,this._rotationType){case Z.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case Z.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case Z.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case Z.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance;break}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._start=void 0,this._currentNonCannonAngle=void 0,this._distance=void 0}}function _o(r){return typeof r.scale=="object"&&typeof r.duration=="number"}class fo{constructor(t,e){if(this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._endScale=x(1,1),this._startScale=x(1,1),this._endScale=e.scale,this._tx=t.get(A),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only ScaleTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._startScale=this._tx.scale,this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=ti(this._startScale,this._endScale,e),s=this._tx.scale,n=t/1e3,o=i.sub(s).scale(n===0?0:1/n);this._motion.scaleFactor=o,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.scaleFactor=v.Zero,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class go{constructor(t,e,i,s,n){this.id=N(),this._started=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._endX=e,this._endY=i,this._speedX=s,this._speedY=n}update(t){if(this._started||(this._started=!0,this._startX=this._tx.scale.x,this._startY=this._tx.scale.y,this._distanceX=Math.abs(this._endX-this._startX),this._distanceY=Math.abs(this._endY-this._startY)),Math.abs(this._tx.scale.x-this._startX)>=this._distanceX)this._motion.scaleFactor.x=0;else{const e=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*e}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const e=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*e}this.isComplete()&&(this._tx.scale=x(this._endX,this._endY),this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startX)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startY)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function po(r){return typeof r.scaleOffset=="object"&&typeof r.duration=="number"}class mo{constructor(t,e){if(this.entity=t,this.id=N(),this._started=!1,this._stopped=!1,this._endScale=x(1,1),this._scaleOffset=x(0,0),this._startScale=x(1,1),this._scaleOffset=e.scaleOffset,this._tx=t.get(A),this._motion=t.get(H),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only ScaleBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._startScale=this._tx.scale,this._endScale=this._startScale.add(this._scaleOffset),this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=ti(this._startScale,this._endScale,e),s=this._tx.scale,n=t/1e3,o=i.sub(s).scale(n===0?0:1/n);this._motion.scaleFactor=o,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.scaleFactor=v.Zero,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class vo{constructor(t,e,i,s){this.id=N(),this._started=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._offset=new v(e,i),this._speedX=this._speedY=s}update(t){this._started||(this._started=!0,this._startScale=this._tx.scale.clone(),this._endScale=this._startScale.add(this._offset),this._distanceX=Math.abs(this._endScale.x-this._startScale.x),this._distanceY=Math.abs(this._endScale.y-this._startScale.y),this._directionX=this._endScale.x<this._startScale.x?-1:1,this._directionY=this._endScale.y<this._startScale.y?-1:1),this._motion.scaleFactor.x=this._speedX*this._directionX,this._motion.scaleFactor.y=this._speedY*this._directionY,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startScale.x)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startScale.y)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class wo{constructor(t){this.id=N(),this._hasBeenCalled=!1,this._method=t}update(t){this._method(),this._hasBeenCalled=!0}isComplete(){return this._hasBeenCalled}reset(){this._hasBeenCalled=!1}stop(){this._hasBeenCalled=!0}}class xo{constructor(t,e,i,s,n){this.easingFcn=n,this.id=N(),this._currentLerpTime=0,this._lerpDuration=1*1e3,this._lerpStart=new v(0,0),this._lerpEnd=new v(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._lerpDuration=s,this._lerpEnd=new v(e,i)}_initialize(){this._lerpStart=new v(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;if(this._currentLerpTime<this._lerpDuration){this._lerpEnd.x<this._lerpStart.x?e=this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):e=this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),this._lerpEnd.y<this._lerpStart.y?i=this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):i=this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration);const s=t/1e3;this._motion.vel=x(s===0?0:(e-this._tx.pos.x)/s,s===0?0:(i-this._tx.pos.y)/s)}else this._tx.pos=x(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=v.Zero}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=x(0,0),this._stopped=!0}}class bo{constructor(t,e,i,s,n){this.easingFcn=n,this.id=N(),this._currentLerpTime=0,this._lerpDuration=1*1e3,this._lerpStart=new v(0,0),this._lerpEnd=new v(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._lerpDuration=s,this._offset=new v(e,i)}_initialize(){this._lerpStart=new v(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0,this._lerpEnd=this._lerpStart.add(this._offset)}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;if(this._currentLerpTime<this._lerpDuration){this._lerpEnd.x<this._lerpStart.x?e=this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):e=this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),this._lerpEnd.y<this._lerpStart.y?i=this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):i=this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration);const s=t/1e3;this._motion.vel=x(s===0?0:(e-this._tx.pos.x)/s,s===0?0:(i-this._tx.pos.y)/s)}else this._tx.pos=x(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=v.Zero}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=x(0,0),this._stopped=!0}}class yo{constructor(t,e,i,s=1){this.id=N(),this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(j),this._timeVisible=e,this._timeNotVisible=i,this._duration=(e+i)*s}update(t){this._started||(this._started=!0,this._elapsedTime=0,this._totalTime=0),this._graphics&&(this._elapsedTime+=t,this._totalTime+=t,this._graphics.isVisible&&this._elapsedTime>=this._timeVisible&&(this._graphics.isVisible=!1,this._elapsedTime=0),!this._graphics.isVisible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.isVisible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.isVisible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.isVisible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._elapsedTime=0,this._totalTime=0}}class Co{constructor(t,e,i){this.id=N(),this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(j),this._endOpacity=e,this._remainingTime=this._originalTime=i}update(t){this._graphics&&(this._started||(this._started=!0,this._remainingTime=this._originalTime,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._remainingTime>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._remainingTime),this._remainingTime-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),R.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||this._remainingTime<=0}stop(){this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._remainingTime=this._originalTime}}class So{constructor(t){this.id=N(),this._elapsedTime=0,this._started=!1,this._stopped=!1,this._delay=t}update(t){this._started||(this._started=!0),this._elapsedTime+=t}isComplete(){return this._stopped||this._elapsedTime>=this._delay}stop(){this._stopped=!0}reset(){this._elapsedTime=0,this._started=!1,this._stopped=!1}}class To{constructor(t){this.id=N(),this._stopped=!1,this._entity=t}update(t){this._entity.get(je).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class An{constructor(t,e,i){this.id=N(),this._started=!1,this._stopped=!1,this._tx=t.get(A),this._motion=t.get(H),this._followTx=e.get(A),this._followMotion=e.get(H),this._current=new v(this._tx.pos.x,this._tx.pos.y),this._end=new v(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=i!==void 0?i:this._current.distance(this._end),this._speed=0}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._followMotion.vel.x,2)+Math.pow(this._followMotion.vel.y,2));if(e!==0&&(this._speed=e),this._current=x(this._tx.pos.x,this._tx.pos.y),this._end=x(this._followTx.pos.x,this._followTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize(),this._distanceBetween>=this._maximumDistance){const i=this._dir.scale(this._speed);this._motion.vel=x(i.x,i.y)}else this._motion.vel=x(0,0);this.isComplete()&&(this._tx.pos=x(this._end.x,this._end.y),this._motion.vel=x(0,0))}stop(){this._motion.vel=x(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1,this._stopped=!1}}class $i{constructor(t,e,i,s){this.id=N(),this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tolerance=1,this._tx=t.get(A),this._motion=t.get(H),this._meetTx=e.get(A),this._meetMotion=e.get(H),this._current=new v(this._tx.pos.x,this._tx.pos.y),this._end=new v(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,i!==void 0&&(this._speedWasSpecified=!0),s!==void 0&&(this._tolerance=s)}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._meetMotion.vel.x,2)+Math.pow(this._meetMotion.vel.y,2));e!==0&&!this._speedWasSpecified&&(this._speed=e),this._current=x(this._tx.pos.x,this._tx.pos.y),this._end=x(this._meetTx.pos.x,this._meetTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize();const i=this._dir.scale(this._speed);this._motion.vel=x(i.x,i.y),this.isComplete()&&(this._tx.pos=x(this._end.x,this._end.y),this._motion.vel=x(0,0))}isComplete(){return this._stopped||this._distanceBetween<=this._tolerance}stop(){this._motion.vel=x(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._distanceBetween=1/0}}class Po{constructor(t,e,i=1e3){this.id=N(),this._stopped=!1,this._started=!1,this._total=0,this._currentDuration=0;var s;this._graphics=t.get(j),this._duration=i,this._entity=t,this._material=(s=t.scene)==null?void 0:s.engine.graphicsContext.createMaterial({name:"flash-material",color:e,fragmentSource:`#version 300 es
|
|
877
|
+
`;return i=i.replace("%%texture_picker%%",s),i}_addImageAsTexture(t){if(this._images.has(t))return;const e=t.getAttribute(z.Filtering),i=e?Ve(e):void 0,s=Ot(t.getAttribute(z.WrappingX)),n=Ot(t.getAttribute(z.WrappingY)),o=t.getAttribute("forceUpload")==="true",a=this._context.textureLoader.load(t,{filtering:i,wrapping:{x:s,y:n}},o);t.removeAttribute("forceUpload"),this._textures.indexOf(a)===-1&&(this._textures.push(a),this._textureToIndex.set(a,this._textureIndex++),this._images.add(t))}_bindTextures(t){const e=Math.min(this._textureIndex,this._maxTextures);for(let i=0;i<e;i++)t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,this._textures[i]||this._textures[0])}_getTextureIdForImage(t){var e;if(t){const i=this._context.textureLoader.get(t);return(e=this._textureToIndex.get(i))!=null?e:-1}return-1}_isFull(){return this._imageCount>=this._maxImages||this._textures.length>=this._maxTextures}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}draw(t,e,i,s,n,o,a,h,l){var c,u,_,f;this._isFull()&&this.flush(),this._imageCount++,this._addImageAsTexture(t);const m=this._getImageWidth(t),p=this._getImageHeight(t);let x=m||s||0,v=p||n||0;this._view[0]=0,this._view[1]=0,this._view[2]=(c=s!=null?s:m)!=null?c:0,this._view[3]=(u=n!=null?n:p)!=null?u:0,this._dest[0]=e!=null?e:1,this._dest[1]=i!=null?i:1,o!==void 0&&a!==void 0&&h!==void 0&&l!==void 0&&(this._view[0]=e!=null?e:1,this._view[1]=i!=null?i:1,this._view[2]=(_=s!=null?s:m)!=null?_:0,this._view[3]=(f=n!=null?n:p)!=null?f:0,this._dest[0]=o,this._dest[1]=a,x=h,v=l),e=this._view[0],i=this._view[1];const g=this._view[2],y=this._view[3],S=this._context.getTransform(),A=this._context.opacity;this._context.snapToPixel&&(this._dest[0]=~~(this._dest[0]+D),this._dest[1]=~~(this._dest[1]+D));const C=this._context.tint||this._defaultTint,L=this._getTextureIdForImage(t),U=m||x,G=p||v,et=(e+this.uvPadding)/U,ht=(i+this.uvPadding)/G,$=(e+g-this.uvPadding)/U,W=(i+y-this.uvPadding)/G,ct=m,ft=p,E=this._transformData.bufferData;E[this._vertexIndex++]=this._dest[0],E[this._vertexIndex++]=this._dest[1],E[this._vertexIndex++]=S.data[0],E[this._vertexIndex++]=S.data[1],E[this._vertexIndex++]=S.data[2],E[this._vertexIndex++]=S.data[3],E[this._vertexIndex++]=S.data[4],E[this._vertexIndex++]=S.data[5],E[this._vertexIndex++]=A,E[this._vertexIndex++]=x,E[this._vertexIndex++]=v,E[this._vertexIndex++]=ct,E[this._vertexIndex++]=ft,E[this._vertexIndex++]=L,E[this._vertexIndex++]=et,E[this._vertexIndex++]=ht,E[this._vertexIndex++]=$,E[this._vertexIndex++]=W,E[this._vertexIndex++]=C.r/255,E[this._vertexIndex++]=C.g/255,E[this._vertexIndex++]=C.b/255,E[this._vertexIndex++]=C.a}hasPendingDraws(){return this._imageCount!==0}flush(){if(this._imageCount===0)return;const t=this._gl;this._shader.use(),this._bindData(t),this._shader.setUniformMatrix("u_matrix",this._context.ortho),this._shader.setUniformBoolean("u_pixelart",this.pixelArtSampler),this._bindTextures(t),t.drawArraysInstanced(t.TRIANGLES,0,6,this._imageCount),J.DrawnImagesCount+=this._imageCount,J.DrawCallCount++,t.bindVertexArray(null),this._imageCount=0,this._vertexIndex=0,this._textures.length=0,this._textureIndex=0,this._textureToIndex.clear(),this._images.clear(),this._imageToWidth.clear(),this._imageToHeight.clear()}}const D=1e-4;class bl{constructor(t){this._webglCtx=t,this._debugText=new fn}drawRect(t,e,i,s,n={color:T.Black}){this.drawLine(b(t,e),b(t+i,e),{...n}),this.drawLine(b(t+i,e),b(t+i,e+s),{...n}),this.drawLine(b(t+i,e+s),b(t,e+s),{...n}),this.drawLine(b(t,e+s),b(t,e),{...n})}drawLine(t,e,i){var s;this._webglCtx.save(),this._webglCtx.z=i!=null&&i.dashed?Tt.config.settings.z.dashed:Tt.config.settings.z.solid,this._webglCtx.draw("ex.debug-line",t,e,(s=i==null?void 0:i.color)!=null?s:T.Black,i==null?void 0:i.lineWidth,i==null?void 0:i.dashed),this._webglCtx.restore()}drawPoint(t,e={color:T.Black,size:5}){this._webglCtx.save(),this._webglCtx.z=Tt.config.settings.z.point,this._webglCtx.draw("ex.debug-point",t,e.color,e.size),this._webglCtx.restore()}drawCircle(t,e,i,s,n){this._webglCtx.save(),this._webglCtx.z=Tt.config.settings.z.solid,this._webglCtx.draw("ex.debug-circle",t,e,i,s,n),this._webglCtx.restore()}drawText(t,e){this._webglCtx.save(),this._webglCtx.z=Tt.config.settings.z.text,this._debugText.write(this._webglCtx,t,e),this._webglCtx.restore()}}class $t{constructor(t){this._logger=R.getInstance(),this._renderers=new Map,this._lazyRenderersFactory=new Map,this.imageRenderer=De.isEnabled("use-legacy-image-renderer")?"ex.image":"ex.image-v2",this._isDrawLifecycle=!1,this.useDrawSorting=!0,this._drawCallPool=new zi(()=>new ml,void 0,4e3),this._drawCallIndex=0,this._drawCalls=new Array(4e3).fill(null),this._postProcessTargets=[],this._postprocessors=[],this._transform=new zh,this._state=new Ur,this.snapToPixel=!1,this.smoothing=!1,this.pixelArtSampler=!1,this.uvPadding=.01,this.backgroundColor=T.ExcaliburBlue,this.multiSampleAntialiasing=!0,this.transparency=!0,this._isContextLost=!1,this._disposed=!1,this._imageToWidth=new Map,this._imageToHeight=new Map,this._totalPostProcessorTime=0;const{canvasElement:e,context:i,enableTransparency:s,antialiasing:n,uvPadding:o,multiSampleAntialiasing:a,pixelArtSampler:h,powerPreference:l,snapToPixel:c,backgroundColor:u,useDrawSorting:_,garbageCollector:f,handleContextLost:m,handleContextRestored:p}=t;if(this.__gl=i!=null?i:e.getContext("webgl2",{antialias:n!=null?n:this.smoothing,premultipliedAlpha:!1,alpha:s!=null?s:this.transparency,depth:!1,powerPreference:l!=null?l:"high-performance"}),!this.__gl)throw Error("Failed to retrieve webgl context from browser");m&&this.__gl.canvas.addEventListener("webglcontextlost",m,!1),p&&this.__gl.canvas.addEventListener("webglcontextrestored",p,!1),this.__gl.canvas.addEventListener("webglcontextlost",()=>{this._isContextLost=!0}),this.__gl.canvas.addEventListener("webglcontextrestored",()=>{this._isContextLost=!1}),this.textureLoader=new Xe(this.__gl,f),this.snapToPixel=c!=null?c:this.snapToPixel,this.smoothing=n!=null?n:this.smoothing,this.transparency=s!=null?s:this.transparency,this.pixelArtSampler=h!=null?h:this.pixelArtSampler,this.uvPadding=o!=null?o:this.uvPadding,this.multiSampleAntialiasing=typeof a=="boolean"?a:this.multiSampleAntialiasing,this.samples=typeof a=="object"?a.samples:void 0,this.backgroundColor=u!=null?u:this.backgroundColor,this.useDrawSorting=_!=null?_:this.useDrawSorting,this._drawCallPool.disableWarnings=!0,this._drawCallPool.preallocate(),this._init()}get z(){return this._state.current.z}set z(t){this._state.current.z=t}get opacity(){return this._state.current.opacity}set opacity(t){this._state.current.opacity=t}get tint(){return this._state.current.tint}set tint(t){this._state.current.tint=t}get width(){return this.__gl.canvas.width}get height(){return this.__gl.canvas.height}get ortho(){return this._ortho}checkIfResolutionSupported(t){let e=!0;return(t.width>4096||t.height>4096)&&(e=!1),e}dispose(){if(!this._disposed){this._disposed=!0,this.textureLoader.dispose();for(const t of this._renderers.values())t.dispose();this._renderers.clear(),this._drawCallPool.dispose(),this._drawCalls.length=0,this.__gl=null}}_init(){const t=this.__gl;if(this._ortho=Ct.ortho(0,t.canvas.width,t.canvas.height,0,400,-400),t.viewport(0,0,t.canvas.width,t.canvas.height),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.blendEquationSeparate(t.FUNC_ADD,t.FUNC_ADD),t.blendFuncSeparate(t.ONE,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA),t.depthMask(!1),this.register(new cl({uvPadding:this.uvPadding,pixelArtSampler:this.pixelArtSampler})),this.register(new to),this.register(new _l),this.register(new pl),this.lazyRegister("ex.debug-circle",()=>new nl),this.lazyRegister("ex.debug-point",()=>new el),this.lazyRegister("ex.debug-line",()=>new Jh),this.lazyRegister("ex.particle",()=>new Zr),this.register(new xl({uvPadding:this.uvPadding,pixelArtSampler:this.pixelArtSampler})),this.materialScreenTexture=t.createTexture(),!this.materialScreenTexture)throw new Error("Could not create screen texture!");t.bindTexture(t.TEXTURE_2D,this.materialScreenTexture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,this.width,this.height,0,t.RGBA,t.UNSIGNED_BYTE,null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT),t.bindTexture(t.TEXTURE_2D,null),this._screenRenderer=new al(this),this._renderTarget=new Wi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height}),this._postProcessTargets=[new Wi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height}),new Wi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height})],this._msaaTarget=new Wi({gl:t,transparency:this.transparency,width:t.canvas.width,height:t.canvas.height,antialias:this.multiSampleAntialiasing,samples:this.samples}),this.debug=new bl(this)}register(t){this._renderers.set(t.type,t),t.initialize(this.__gl,this)}lazyRegister(t,e){this._lazyRenderersFactory.set(t,e)}get(t){let e=this._renderers.get(t);if(!e){const i=this._lazyRenderersFactory.get(t);i&&(this._logger.debug("lazy init renderer:",t),e=i(),this.register(e))}return e}_isCurrentRenderer(t){return!this._currentRenderer||this._currentRenderer===t}beginDrawLifecycle(){this._isDrawLifecycle=!0}endDrawLifecycle(){this._isDrawLifecycle=!1}draw(t,...e){if(e.length>9)throw new Error("Only 10 or less renderer arguments are supported!;");if(this._isDrawLifecycle||this._logger.warnOnce(`Attempting to draw outside the the drawing lifecycle (preDraw/postDraw) is not supported and is a source of bugs/errors.
|
|
878
|
+
If you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPostDraw handler.`),this._isContextLost){this._logger.errorOnce(`Unable to draw ${t}, the webgl context is lost`);return}const i=this.get(t);if(i)if(this.useDrawSorting){const s=this._drawCallPool.get();s.z=this._state.current.z,s.priority=i.priority,s.renderer=t,this.getTransform().clone(s.transform),s.state.z=this._state.current.z,s.state.opacity=this._state.current.opacity,s.state.tint=this._state.current.tint,s.state.material=this._state.current.material,s.args[0]=e[0],s.args[1]=e[1],s.args[2]=e[2],s.args[3]=e[3],s.args[4]=e[4],s.args[5]=e[5],s.args[6]=e[6],s.args[7]=e[7],s.args[8]=e[8],s.args[9]=e[9],this._drawCalls[this._drawCallIndex++]=s}else this._currentRenderer||(this._currentRenderer=i),this._isCurrentRenderer(i)||this._currentRenderer.flush(),i.draw(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9]),this._currentRenderer=i;else throw Error(`No renderer with name ${t} has been registered`)}resetTransform(){this._transform.reset()}updateViewport(t){const e=this.__gl;this._ortho=this._ortho=Ct.ortho(0,t.width,t.height,0,400,-400),this._renderTarget.setResolution(e.canvas.width,e.canvas.height),this._msaaTarget.setResolution(e.canvas.width,e.canvas.height),this._postProcessTargets[0].setResolution(e.canvas.width,e.canvas.height),this._postProcessTargets[1].setResolution(e.canvas.width,e.canvas.height)}_getImageWidth(t){let e=this._imageToWidth.get(t);return e===void 0&&(e=t.width,this._imageToWidth.set(t,e)),e}_getImageHeight(t){let e=this._imageToHeight.get(t);return e===void 0&&(e=t.height,this._imageToHeight.set(t,e)),e}drawImage(t,e,i,s,n,o,a,h,l){if(!(s===0||n===0)){{if(h===0||l===0)return;if(this._getImageWidth(t)===0||this._getImageHeight(t)===0)return}if(!t){R.getInstance().warn("Cannot draw a null or undefined image"),console.trace&&console.trace();return}this._state.current.material?this.draw("ex.material",t,e,i,s,n,o,a,h,l):this.imageRenderer==="ex.image"?this.draw(this.imageRenderer,t,e,i,s,n,o,a,h,l):this.draw(this.imageRenderer,t,e,i,s,n,o,a,h,l)}}drawLine(t,e,i,s=1){this.draw("ex.rectangle",t,e,i,s)}drawRectangle(t,e,i,s,n,o){this.draw("ex.rectangle",t,e,i,s,n,o)}drawCircle(t,e,i,s,n){this.draw("ex.circle",t,e,i,s,n)}save(){this._transform.save(),this._state.save()}restore(){this._transform.restore(),this._state.restore()}translate(t,e){this._transform.translate(this.snapToPixel?~~(t+D):t,this.snapToPixel?~~(e+D):e)}rotate(t){this._transform.rotate(t)}scale(t,e){this._transform.scale(t,e)}transform(t){this._transform.current=t}getTransform(){return this._transform.current}multiply(t){this._transform.current.multiply(t,this._transform.current)}addPostProcessor(t){this._postprocessors.push(t),t.initialize(this)}removePostProcessor(t){const e=this._postprocessors.indexOf(t);e!==-1&&this._postprocessors.splice(e,1)}clearPostProcessors(){this._postprocessors.length=0}updatePostProcessors(t){for(const e of this._postprocessors){const i=e.getShader();i.use();const s=i.getUniformDefinitions();this._totalPostProcessorTime+=t,s.find(n=>n.name==="u_time_ms")&&i.setUniformFloat("u_time_ms",this._totalPostProcessorTime),s.find(n=>n.name==="u_elapsed_ms")&&i.setUniformFloat("u_elapsed_ms",t),s.find(n=>n.name==="u_resolution")&&i.setUniformFloatVector("u_resolution",b(this.width,this.height)),e.onUpdate&&e.onUpdate(t)}}set material(t){this._state.current.material=t}get material(){return this._state.current.material}createMaterial(t){return new Kr({...t,graphicsContext:this})}createShader(t){const{name:e,vertexSource:i,fragmentSource:s,uniforms:n,images:o,startingTextureSlot:a}=t,h=new Bt({name:e,graphicsContext:this,vertexSource:i,fragmentSource:s,uniforms:n,images:o,startingTextureSlot:a});return h.compile(),h}clear(){const t=this.__gl;(this.multiSampleAntialiasing?this._msaaTarget:this._renderTarget).use(),t.clearColor(this.backgroundColor.r/255,this.backgroundColor.g/255,this.backgroundColor.b/255,this.backgroundColor.a),t.clear(t.COLOR_BUFFER_BIT)}flush(){var t;if(this._isContextLost){this._logger.errorOnce("Unable to flush the webgl context is lost");return}let e=this.multiSampleAntialiasing?this._msaaTarget:this._renderTarget;if(e.use(),this.useDrawSorting){for(let o=this._drawCallIndex;o<this._drawCalls.length;o++)this._drawCalls[o]=null;const i=new Map;for(const[o]of this._renderers){let a=0;for(a=0;a<this._drawCallIndex&&this._drawCalls[a].renderer!==o;a++);i.set(o,a)}this._drawCalls.sort((o,a)=>{if(o===null||a===null)return 0;const h=o.z-a.z,l=i.get(o.renderer)-i.get(a.renderer),c=o.priority-a.priority;return h===0?c===0?l:c:h});const s=this._transform.current,n=this._state.current;if(this._drawCalls.length&&this._drawCallIndex){let o=this._drawCalls[0].renderer,a=this.get(o);for(let h=0;h<this._drawCallIndex;h++)this._transform.current=this._drawCalls[h].transform,this._state.current=this._drawCalls[h].state,this._drawCalls[h].renderer!==o&&(a.flush(),o=this._drawCalls[h].renderer,a=this.get(o)),a instanceof to&&((t=this.material)!=null&&t.isUsingScreenTexture)&&(e.copyToTexture(this.materialScreenTexture),e.use()),a.draw(...this._drawCalls[h].args);a.hasPendingDraws()&&a.flush()}this._transform.current=s,this._state.current=n,this._drawCallPool.done(),this._drawCallIndex=0,this._imageToHeight.clear(),this._imageToWidth.clear()}else for(const i of this._renderers.values())i.hasPendingDraws()&&i.flush();e.disable(),this._postprocessors.length>0&&e.toRenderSource().use();for(let i=0;i<this._postprocessors.length;i++)e=this._postProcessTargets[i%2],this._postProcessTargets[i%2].use(),this._screenRenderer.renderWithPostProcessor(this._postprocessors[i]),this._postProcessTargets[i%2].toRenderSource().use();e.blitToScreen()}}class je{constructor(t,e,i,s){this.font=t,this.text=e,this.color=i,this.maxWidth=s,this._textFragments=[],this.disposed=!1,this._dirty=!0,this.canvas=document.createElement("canvas");const n=this.canvas.getContext("2d");if(!n)throw new Error("Unable to create FontTextInstance, internal canvas failed to create");this.ctx=n,this.dimensions=this.measureText(e),this._setDimension(this.dimensions,this.ctx),this._lastHashCode=this.getHashCode()}measureText(t,e){if(this.disposed)throw Error("Accessing disposed text instance! "+this.text);let i=null;e!=null?i=this._getLinesFromText(t,e):i=t.split(`
|
|
879
|
+
`);const s=i.reduce((_,f)=>_.length>f.length?_:f);this._applyFont(this.ctx);const n=this.ctx.measureText(s);let o=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);const a=o*i.length;o=a;const h=a-Math.abs(n.actualBoundingBoxAscent),l=0,c=0;return new F({left:l-Math.abs(n.actualBoundingBoxLeft)-this.font.padding,top:c-Math.abs(n.actualBoundingBoxAscent)-this.font.padding,bottom:c+h+this.font.padding,right:l+Math.abs(n.actualBoundingBoxRight)+this.font.padding})}_setDimension(t,e){let i=1;this.font.lineHeight&&(i=this.font.lineHeight/this.font.size),e.canvas.width=(t.width+this.font.padding*2)*2*this.font.quality,e.canvas.height=(t.height+this.font.padding*2)*2*this.font.quality*i}static getHashCode(t,e,i){var s;return e+"__hashcode__"+t.fontString+t.showDebug+t.textAlign+t.baseAlign+t.direction+t.lineHeight+JSON.stringify(t.shadow)+(t.padding.toString()+t.smoothing.toString()+t.lineWidth.toString()+t.lineDash.toString()+((s=t.strokeColor)==null?void 0:s.toString())+(i?i.toString():t.color.toString()))}getHashCode(t=!0){return je.getHashCode(this.font,this.text,t?this.color:void 0)}_applyRasterProperties(t){var e,i,s;t.translate(this.font.padding,this.font.padding),t.imageSmoothingEnabled=this.font.smoothing,t.lineWidth=this.font.lineWidth,t.setLineDash((e=this.font.lineDash)!=null?e:t.getLineDash()),t.strokeStyle=(s=(i=this.font.strokeColor)==null?void 0:i.toString())!=null?s:"",t.fillStyle=this.color.toString()}_applyFont(t){t.resetTransform(),t.translate(this.font.padding+t.canvas.width/2,this.font.padding+t.canvas.height/2),t.scale(this.font.quality,this.font.quality),t.textAlign=this.font.textAlign,t.textBaseline=this.font.baseAlign,t.font=this.font.fontString,t.direction=this.font.direction,this.font.shadow&&(this.font.shadow.color&&(t.shadowColor=this.font.shadow.color.toString()),this.font.shadow.blur&&(t.shadowBlur=this.font.shadow.blur),this.font.shadow.offset&&(t.shadowOffsetX=this.font.shadow.offset.x,t.shadowOffsetY=this.font.shadow.offset.y))}_drawText(t,e,i){this._applyRasterProperties(t),this._applyFont(t);for(let s=0;s<e.length;s++){const n=e[s];this.color&&t.fillText(n,0,s*i),this.font.strokeColor&&t.strokeText(n,0,s*i)}this.font.showDebug&&(un(t,T.Green,-t.canvas.width/2,0,t.canvas.width/2,0,2),un(t,T.Red,0,-t.canvas.height/2,0,t.canvas.height/2,2))}_splitTextBitmap(t){const e=[];let i=0,s=0;const n=Math.min(4096,t.canvas.width),o=Math.min(4096,t.canvas.height);for(;i<t.canvas.width;){for(;s<t.canvas.height;){const a=document.createElement("canvas");a.width=n,a.height=o;const h=a.getContext("2d");if(!h)throw new Error("Unable to split internal FontTextInstance bitmap, failed to create internal canvas");h.drawImage(t.canvas,i,s,n,o,0,0,n,o),e.push({x:i,y:s,canvas:a}),s+=o}i+=n,s=0}return e}flagDirty(){this._dirty=!0}render(t,e,i,s){var n;if(this.disposed)throw Error("Accessing disposed text instance! "+this.text);this._ex=t;const o=this.getHashCode();if(this._lastHashCode!==o&&(this._dirty=!0),this._dirty){this.dimensions=this.measureText(this.text,s),this._setDimension(this.dimensions,this.ctx);const a=this._getLinesFromText(this.text,s),h=(n=this.font.lineHeight)!=null?n:this.dimensions.height/a.length;if(this._drawText(this.ctx,a,h),t instanceof $t)for(const l of this._textFragments)t.textureLoader.delete(l.canvas);if(this._textFragments=this._splitTextBitmap(this.ctx),t instanceof $t)for(const l of this._textFragments)t.textureLoader.load(l.canvas,{filtering:this.font.filtering},!0);this._lastHashCode=o,this._dirty=!1}for(const a of this._textFragments)t.drawImage(a.canvas,0,0,a.canvas.width,a.canvas.height,a.x/this.font.quality+e-this.ctx.canvas.width/this.font.quality/2,a.y/this.font.quality+i-this.ctx.canvas.height/this.font.quality/2,a.canvas.width/this.font.quality,a.canvas.height/this.font.quality)}dispose(){if(this.disposed=!0,this.dimensions=void 0,this.canvas=void 0,this.ctx=void 0,this._ex instanceof $t)for(const t of this._textFragments)this._ex.textureLoader.delete(t.canvas);this._textFragments.length=0}_getLinesFromText(t,e){var i;if(this._cachedText===t&&this._cachedRenderWidth===e&&((i=this._cachedLines)!=null&&i.length))return this._cachedLines;const s=t.split(`
|
|
880
|
+
`);if(e==null)return s;for(let n=0;n<s.length;n++){let o=s[n],a="";if(this.measureText(o).width>e){for(;this.measureText(o).width>e;)a=o[o.length-1]+a,o=o.slice(0,-1);s[n]=o,s[n+1]=a}}return this._cachedText=t,this._cachedLines=s,this._cachedRenderWidth=e,s}}class Se extends st{constructor(t={}){var e,i,s,n,o,a,h,l,c,u,_,f,m,p,x,v,g,y,S,A;super(t),this.filtering=mt.Blended,this.quality=2,this.padding=2,this.smoothing=!1,this.lineWidth=1,this.lineDash=[],this.color=T.Black,this.family="sans-serif",this.style=cn.Normal,this.bold=!1,this.unit=an.Px,this.textAlign=hn.Left,this.baseAlign=ln.Top,this.direction=dn.LeftToRight,this.lineHeight=void 0,this.size=10,this._textBounds=new F,this.smoothing=(e=t==null?void 0:t.smoothing)!=null?e:this.smoothing,this.padding=(i=t==null?void 0:t.padding)!=null?i:this.padding,this.color=(s=t==null?void 0:t.color)!=null?s:this.color,this.strokeColor=(n=t==null?void 0:t.strokeColor)!=null?n:this.strokeColor,this.lineDash=(o=t==null?void 0:t.lineDash)!=null?o:this.lineDash,this.lineWidth=(a=t==null?void 0:t.lineWidth)!=null?a:this.lineWidth,this.filtering=(h=t==null?void 0:t.filtering)!=null?h:this.filtering,this.family=(l=t==null?void 0:t.family)!=null?l:this.family,this.style=(c=t==null?void 0:t.style)!=null?c:this.style,this.bold=(u=t==null?void 0:t.bold)!=null?u:this.bold,this.size=(_=t==null?void 0:t.size)!=null?_:this.size,this.unit=(f=t==null?void 0:t.unit)!=null?f:this.unit,this.textAlign=(m=t==null?void 0:t.textAlign)!=null?m:this.textAlign,this.baseAlign=(p=t==null?void 0:t.baseAlign)!=null?p:this.baseAlign,this.direction=(x=t==null?void 0:t.direction)!=null?x:this.direction,this.lineHeight=(v=t==null?void 0:t.lineHeight)!=null?v:this.lineHeight,this.quality=(g=t==null?void 0:t.quality)!=null?g:this.quality,t!=null&&t.shadow&&(this.shadow={},this.shadow.blur=(y=t.shadow.blur)!=null?y:this.shadow.blur,this.shadow.offset=(S=t.shadow.offset)!=null?S:this.shadow.offset,this.shadow.color=(A=t.shadow.color)!=null?A:this.shadow.color),this._textMeasurement=new je(this,"",T.Black)}clone(){return new Se({...this.cloneGraphicOptions(),size:this.size,unit:this.unit,family:this.family,style:this.style,bold:this.bold,textAlign:this.textAlign,baseAlign:this.baseAlign,direction:this.direction,shadow:this.shadow?{blur:this.shadow.blur,offset:this.shadow.offset,color:this.shadow.color}:void 0})}get fontString(){return`${this.style} ${this.bold?"bold":""} ${this.size}${this.unit} ${this.family}`}get localBounds(){return this._textBounds}_drawImage(t,e,i){}_rotate(t){var e;const i=(e=this.origin)!=null?e:this._textBounds.center;t.translate(i.x,i.y),t.rotate(this.rotation),t.translate(-i.x,-i.y)}_flip(t){this.flipHorizontal&&(t.translate(this._textBounds.width/this.scale.x,0),t.scale(-1,1)),this.flipVertical&&(t.translate(0,-this._textBounds.height/2/this.scale.y),t.scale(1,-1))}measureTextWithoutCache(t,e){return this._textMeasurement.measureText(t,e)}measureText(t,e){return qi.measureText(t,this,e)}_postDraw(t){t.restore()}render(t,e,i,s,n,o){const a=qi.getTextInstance(e,this,i);this._textBounds=a.dimensions,this._preDraw(t,s,n),a.render(t,s,n,o),this._postDraw(t)}}class _i extends st{constructor(t){var e,i;super(t),this._text="",this._textWidth=0,this._textHeight=0,this.font=(e=t.font)!=null?e:new Se,this.color=(i=t.color)!=null?i:this.color,this.text=t.text,this.maxWidth=t.maxWidth}clone(){var t,e;return new _i({text:this.text.slice(),color:(e=(t=this.color)==null?void 0:t.clone())!=null?e:T.Black,font:this.font.clone(),maxWidth:this.maxWidth})}get text(){return this._text}set text(t){this._text=t,this._calculateDimension()}get font(){return this._font}set font(t){this._font=t}get width(){return this._textWidth===0&&this._calculateDimension(),this._textWidth*this.scale.x}get height(){return this._textHeight===0&&this._calculateDimension(),this._textHeight*this.scale.y}_calculateDimension(){const{width:t,height:e}=this.font.measureText(this._text,this.maxWidth);this._textWidth=t,this._textHeight=e}get localBounds(){return this.font.measureText(this._text,this.maxWidth).scale(this.scale)}_rotate(t){}_flip(t){}_preDraw(t,e,i){(this.isStale()||this.font.isStale())&&(this.font.flipHorizontal=this.flipHorizontal,this.font.flipVertical=this.flipVertical,this.font.rotation=this.rotation,this.font.origin=this.origin,this.font.opacity=this.opacity),this.font.tint=this.tint,super._preDraw(t,e,i)}_drawImage(t,e,i){var s;let n=T.Black;this.font instanceof Se&&(n=(s=this.color)!=null?s:this.font.color);const{width:o,height:a}=this.font.measureText(this._text,this.maxWidth);this._textWidth=o,this._textHeight=a,this.font.render(t,this._text,n,e,i,this.maxWidth),this.font.showDebug&&(t.debug.drawRect(e-o,i-a,o*2,a*2),this.maxWidth!=null&&t.debug.drawRect(e,i,this.maxWidth,this.height,{color:T.Yellow}))}}function Sn(r){return!!r.tick}class K extends Dt{constructor(t){super(),this._logger=R.getInstance(),this._current="default",this._graphics={},this._options={},this.material=null,this.isVisible=!0,this.forceOnScreen=!1,this.opacity=1,this._offset=new ne(w.Zero,()=>this.recalculateBounds()),this._anchor=new ne(w.Half,()=>this.recalculateBounds()),this.flipHorizontal=!1,this.flipVertical=!1,this.copyGraphics=!1,t={visible:this.isVisible,graphics:{},...t};const{current:e,anchor:i,color:s,opacity:n,visible:o,graphics:a,offset:h,copyGraphics:l,onPreDraw:c,onPostDraw:u,onPreTransformDraw:_,onPostTransformDraw:f}=t;for(const[m,p]of Object.entries(a))p instanceof st?this._graphics[m]=p:(this._graphics[m]=p.graphic,this._options[m]=p.options);this.offset=h!=null?h:this.offset,this.opacity=n!=null?n:this.opacity,this.anchor=i!=null?i:this.anchor,this.color=s!=null?s:this.color,this.copyGraphics=l!=null?l:this.copyGraphics,this.onPreDraw=c!=null?c:this.onPreDraw,this.onPostDraw=u!=null?u:this.onPostDraw,this.onPreDraw=_!=null?_:this.onPreTransformDraw,this.onPostTransformDraw=f!=null?f:this.onPostTransformDraw,this.isVisible=!!o,this._current=e!=null?e:this._current,e&&this._graphics[e]&&this.use(e)}get visible(){return this.isVisible}set visible(t){this.isVisible=t}get offset(){return this._offset}set offset(t){this._offset=new ne(t,()=>this.recalculateBounds()),this.recalculateBounds()}get anchor(){return this._anchor}set anchor(t){this._anchor=new ne(t,()=>this.recalculateBounds()),this.recalculateBounds()}get color(){return this._color}set color(t){if(t){this._color=t.clone();const e=this.current;(e instanceof Ge||e instanceof _i)&&(e.color=this._color)}}getGraphic(t){return this._graphics[t]}getOptions(t){return this._options[t]}getNames(){return Object.keys(this._graphics)}get current(){return this._graphics[this._current]}get currentOptions(){return this._options[this._current]}get graphics(){return this._graphics}get options(){return this._options}add(t,e,i){let s="default",n=null,o;if(typeof t=="string"&&e instanceof st&&(s=t,n=e,o=i),t instanceof st&&!(e instanceof st)&&(n=t,o=e),!n)throw new Error("Need to provide a graphic or valid graphic string");return this._graphics[s]=this.copyGraphics?n.clone():n,this._options[s]=this.copyGraphics?{...o}:o,s==="default"&&this.use("default"),n}remove(t){delete this._graphics[t],delete this._options[t],this._current===t&&(this._current="default",this.recalculateBounds())}use(t,e){var i;if(t instanceof st){let s=t;this.copyGraphics&&(s=t.clone()),this._current="default",this._graphics[this._current]=s,this._options[this._current]=e}else this._current=t,this._options[this._current]=e,this._current in this._graphics||this._logger.warn(`Graphic ${this._current} is not registered with the graphics component owned by ${(i=this.owner)==null?void 0:i.name}. Nothing will be drawn.`);return this.recalculateBounds(),this.current}hide(){this._current="ex.none"}set localBounds(t){this._localBounds=t}recalculateBounds(){let t=new F;const e=this._graphics[this._current],i=this._options[this._current];if(!e){this._localBounds=t;return}let s=this.anchor,n=this.offset;i!=null&&i.anchor&&(s=i.anchor),i!=null&&i.offset&&(n=i.offset);const o=e.localBounds,a=-o.width*s.x+n.x,h=-o.height*s.y+n.y;e instanceof We&&!e.useAnchor?t=e==null?void 0:e.localBounds.combine(t):t=e==null?void 0:e.localBounds.translate(b(a,h)).combine(t),this._localBounds=t}get localBounds(){return(!this._localBounds||this._localBounds.hasZeroDimensions())&&this.recalculateBounds(),this._localBounds}get bounds(){let t=this.localBounds;if(this.owner){const e=this.owner.get(P);e&&(t=t.transform(e.get().matrix))}return t}update(t,e=0){const i=this.current;i&&Sn(i)&&i.tick(t,e)}clone(){const t=new K;return t._graphics={...this._graphics},t._options={...this._options},t.offset=this.offset.clone(),this.color&&(t.color=this.color.clone()),t.opacity=this.opacity,t.anchor=this.anchor.clone(),t.copyGraphics=this.copyGraphics,t.onPreDraw=this.onPreDraw,t.onPostDraw=this.onPostDraw,t.isVisible=this.isVisible,t}}class he extends Dt{constructor(t){var e,i;super(),this.useColliderShape=!0,this.useGraphicsBounds=!0,this.useColliderShape=(e=t==null?void 0:t.useColliderShape)!=null?e:this.useColliderShape,this.useGraphicsBounds=(i=t==null?void 0:t.useGraphicsBounds)!=null?i:this.useGraphicsBounds,this.localBounds=t==null?void 0:t.localBounds}}function Te(r){return!!r&&r.length===4}const bt=class{static CreateReversibleEasingFunction(t){return(e,i,s,n)=>s<i?i-(t(e,s,i,n)-s):t(e,i,s,n)}static CreateVectorEasingFunction(t){return(e,i,s,n)=>new w(t(e,i.x,s.x,n),t(e,i.y,s.y,n))}};bt.Linear=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,e*r/i+t)),bt.EaseInQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,e*r*r+t)),bt.EaseOutQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,-e*r*(r-2)+t)),bt.EaseInOutQuad=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i/2,r<1?e/2*r*r+t:(r--,-e/2*(r*(r-2)-1)+t))),bt.EaseInCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,e*r*r*r+t)),bt.EaseOutCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i,r--,e*(r*r*r+1)+t)),bt.EaseInOutCubic=bt.CreateReversibleEasingFunction((r,t,e,i)=>(e=e-t,r/=i/2,r<1?e/2*r*r*r+t:(r-=2,e/2*(r*r*r+2)+t)));let Rt=bt;class eo{constructor(t){this._actions=[],this._currentAction=null,this._completedActions=[],this._entity=t}add(t){this._actions.push(t)}remove(t){const e=this._actions.indexOf(t);this._actions.splice(e,1)}clearActions(){this._actions.length=0,this._completedActions.length=0,this._currentAction&&this._currentAction.stop()}getActions(){return this._actions.concat(this._completedActions)}getIncompleteActions(){return this._actions}getCurrentAction(){return this._currentAction}hasNext(){return this._actions.length>0}isComplete(){return this._actions.length===0}reset(){this._actions=this.getActions();const t=this._actions.length;for(let e=0;e<t;e++)this._actions[e].reset();this._completedActions=[]}update(t){if(this._actions.length>0&&(this._currentAction!==this._actions[0]&&(this._currentAction=this._actions[0],this._entity.emit("actionstart",new Zs(this._currentAction,this._entity))),this._currentAction.update(t),this._currentAction.isComplete(this._entity))){this._entity.emit("actioncomplete",new js(this._currentAction,this._entity));const e=this._actions.shift();e&&this._completedActions.push(e)}}}let yl=0;function H(){return yl++}class io{constructor(t,e,i){this.id=H(),this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new fi(t),this._actionQueue=this._repeatContext.getQueue(),this._repeat=i,this._originalRepeat=i,this._repeatBuilder(this._repeatContext),this._repeat--}update(t){this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext),this._repeat--),this._actionQueue.update(t)}isComplete(){return this._stopped||this._repeat<=0&&this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._repeat=this._originalRepeat}}class so{constructor(t,e){this.id=H(),this._stopped=!1,this._repeatBuilder=e,this._repeatContext=new fi(t),this._actionQueue=this._repeatContext.getQueue(),this._repeatBuilder(this._repeatContext)}update(t){this._stopped||(this._actionQueue.isComplete()&&(this._actionQueue.clearActions(),this._repeatBuilder(this._repeatContext)),this._actionQueue.update(t))}isComplete(){return this._stopped}stop(){this._stopped=!0,this._actionQueue.clearActions()}reset(){}}function no(r){return r.offset instanceof w&&typeof r.duration=="number"}class ro{constructor(t,e){this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._legacyEasing=Rt.Linear,this._easing=Ai,this._useLegacyEasing=!1;var i;if(this._offset=e.offset,this._easing=(i=e.easing)!=null?i:this._easing,Te(e.easing)&&(this._legacyEasing=e.easing,this._useLegacyEasing=!0),this._tx=t.get(P),this._motion=t.get(O),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only MoveBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._start=this._tx.pos.clone(),this._end=this._start.add(this._offset),this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=this._tx.pos;let s=0,n=0;this._useLegacyEasing?(s=this._legacyEasing(e,this._start.x,this._end.x,1),n=this._legacyEasing(e,this._start.y,this._end.y,1)):(s=ot(this._start.x,this._end.x,this._easing(e)),n=ot(this._start.y,this._end.y,this._easing(e)));const o=t/1e3,a=o===0?0:(s-i.x)/o,h=o===0?0:(n-i.y)/o;this._motion.vel.x=a,this._motion.vel.y=h,this.isComplete(this.entity)&&(this._tx.pos=b(this._end.x,this._end.y),this._motion.vel=b(0,0))}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.vel=b(0,0),this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class Tn{constructor(t,e,i,s){if(this.id=H(),this._started=!1,this._stopped=!1,this._entity=t,this._tx=t.get(P),this._motion=t.get(O),this._speed=s,this._offset=new w(e,i),s<=0)throw R.getInstance().error("Attempted to moveBy with speed less than or equal to zero : "+s),new Error("Speed must be greater than 0 pixels per second")}update(t){this._started||(this._started=!0,this._start=new w(this._tx.pos.x,this._tx.pos.y),this._end=this._start.add(this._offset),this._distance=this._offset.magnitude,this._dir=this._end.sub(this._start).normalize()),this.isComplete(this._entity)?(this._tx.pos=b(this._end.x,this._end.y),this._motion.vel=b(0,0)):this._motion.vel=this._dir.scale(this._speed)}isComplete(t){const e=t.get(P);return this._stopped||e.pos.distance(this._start)>=this._distance}stop(){this._motion.vel=b(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function oo(r){return r.pos instanceof w&&typeof r.duration=="number"}class ao{constructor(t,e){this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._easing=Ai,this._legacyEasing=Rt.Linear,this._useLegacyEasing=!1;var i;if(this._end=e.pos,this._easing=(i=e.easing)!=null?i:this._easing,Te(e.easing)&&(this._legacyEasing=e.easing,this._useLegacyEasing=!0),this._tx=t.get(P),this._motion=t.get(O),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only moveTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._start=this._tx.pos.clone(),this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=this._tx.pos;let s=0,n=0;this._useLegacyEasing?(s=this._legacyEasing(e,this._start.x,this._end.x,1),n=this._legacyEasing(e,this._start.y,this._end.y,1)):(s=ot(this._start.x,this._end.x,this._easing(e)),n=ot(this._start.y,this._end.y,this._easing(e)));const o=t/1e3,a=o===0?0:(s-i.x)/o,h=o===0?0:(n-i.y)/o;this._motion.vel.x=a,this._motion.vel.y=h,this.isComplete(this.entity)&&(this._tx.pos=b(this._end.x,this._end.y),this._motion.vel=b(0,0))}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.vel=b(0,0),this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class An{constructor(t,e,i,s){this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._end=new w(e,i),this._speed=s}update(t){this._started||(this._started=!0,this._start=new w(this._tx.pos.x,this._tx.pos.y),this._distance=this._start.distance(this._end),this._dir=this._end.sub(this._start).normalize());const e=this._dir.scale(this._speed);this._motion.vel=b(e.x,e.y),this.isComplete(this.entity)&&(this._tx.pos=b(this._end.x,this._end.y),this._motion.vel=b(0,0))}isComplete(t){const e=t.get(P);return this._stopped||new w(e.pos.x,e.pos.y).distance(this._start)>=this._distance}stop(){this._motion.vel=b(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function Cl(r){return typeof r.angle=="number"&&typeof r.duration=="number"}class ho{constructor(t,e){this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._endAngle=0,this._startAngle=0;var i;if(this._endAngle=e.angle,this._tx=t.get(P),this._motion=t.get(O),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only RotateTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._rotationType=(i=e.rotationType)!=null?i:j.ShortestPath,this._currentMs=this._durationMs}update(t){this._started||(this._startAngle=this._tx.rotation,this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=vs(this._startAngle,this._endAngle,this._rotationType,e),s=this._tx.rotation,n=t/1e3,o=n===0?0:(i-s)/n;this._motion.angularVelocity=o,this.isComplete(this.entity)&&(this._tx.rotation=this._endAngle,this._motion.angularVelocity=0)}isComplete(t){return this._stopped||this._currentMs<0}stop(){this._motion.angularVelocity=0,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class lo{constructor(t,e,i,s){this.id=H(),this._started=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._end=e,this._speed=i,this._rotationType=s||j.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation;const e=Math.abs(this._end-this._start),i=it-e;switch(e>i?(this._shortDistance=i,this._longDistance=e):(this._shortDistance=e,this._longDistance=i),this._shortestPathIsPositive=(this._start-this._end+it)%it>=Math.PI,this._rotationType){case j.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case j.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case j.Clockwise:this._direction=1,this._shortestPathIsPositive?this._distance=this._shortDistance:this._distance=this._longDistance;break;case j.CounterClockwise:this._direction=-1,this._shortestPathIsPositive?this._distance=this._longDistance:this._distance=this._shortDistance;break}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function Sl(r){return typeof r.angleRadiansOffset=="number"&&typeof r.duration=="number"}class co{constructor(t,e){this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._offset=0,this._startAngle=0,this._endAngle=0;var i;if(this._offset=e.angleRadiansOffset,this._tx=t.get(P),this._motion=t.get(O),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only RotateBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._rotationType=(i=e.rotationType)!=null?i:j.ShortestPath,this._currentMs=this._durationMs}update(t){this._started||(this._startAngle=this._tx.rotation,this._endAngle=Jt(this._startAngle+this._offset),this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=vs(this._startAngle,this._endAngle,this._rotationType,e),s=this._tx.rotation,n=t/1e3,o=n===0?0:(i-s)/n;this._motion.angularVelocity=o,this.isComplete()&&(this._tx.rotation=this._endAngle,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.angularVelocity=0,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class uo{constructor(t,e,i,s){this.id=H(),this._started=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._speed=i,this._offset=e,this._rotationType=s||j.ShortestPath}update(t){if(!this._started){this._started=!0,this._start=this._tx.rotation,this._currentNonCannonAngle=this._tx.rotation,this._end=this._start+this._offset;const e=Math.abs(this._end-this._start),i=it-e;switch(e>i?(this._shortDistance=i,this._longDistance=e):(this._shortDistance=e,this._longDistance=i),this._shortestPathIsPositive=(this._start-this._end+it)%it>=Math.PI,this._rotationType){case j.ShortestPath:this._distance=this._shortDistance,this._shortestPathIsPositive?this._direction=1:this._direction=-1;break;case j.LongestPath:this._distance=this._longDistance,this._shortestPathIsPositive?this._direction=-1:this._direction=1;break;case j.Clockwise:this._direction=1,this._shortDistance>=0?this._distance=this._shortDistance:this._distance=this._longDistance;break;case j.CounterClockwise:this._direction=-1,this._shortDistance<=0?this._distance=this._shortDistance:this._distance=this._longDistance;break}}this._motion.angularVelocity=this._direction*this._speed,this._currentNonCannonAngle+=this._direction*this._speed*(t/1e3),this.isComplete()&&(this._tx.rotation=this._end,this._motion.angularVelocity=0,this._stopped=!0)}isComplete(){const t=Math.abs(this._currentNonCannonAngle-this._start);return this._stopped||t>=Math.abs(this._distance)}stop(){this._motion.angularVelocity=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._start=void 0,this._currentNonCannonAngle=void 0,this._distance=void 0}}function _o(r){return typeof r.scale=="object"&&typeof r.duration=="number"}class fo{constructor(t,e){if(this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._endScale=b(1,1),this._startScale=b(1,1),this._endScale=e.scale,this._tx=t.get(P),this._motion=t.get(O),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only ScaleTo on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._startScale=this._tx.scale,this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=ii(this._startScale,this._endScale,e),s=this._tx.scale,n=t/1e3,o=i.sub(s).scale(n===0?0:1/n);this._motion.scaleFactor=o,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.scaleFactor=w.Zero,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class go{constructor(t,e,i,s,n){this.id=H(),this._started=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._endX=e,this._endY=i,this._speedX=s,this._speedY=n}update(t){if(this._started||(this._started=!0,this._startX=this._tx.scale.x,this._startY=this._tx.scale.y,this._distanceX=Math.abs(this._endX-this._startX),this._distanceY=Math.abs(this._endY-this._startY)),Math.abs(this._tx.scale.x-this._startX)>=this._distanceX)this._motion.scaleFactor.x=0;else{const e=this._endY<this._startY?-1:1;this._motion.scaleFactor.x=this._speedX*e}if(Math.abs(this._tx.scale.y-this._startY)>=this._distanceY)this._motion.scaleFactor.y=0;else{const e=this._endY<this._startY?-1:1;this._motion.scaleFactor.y=this._speedY*e}this.isComplete()&&(this._tx.scale=b(this._endX,this._endY),this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startX)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startY)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}function po(r){return typeof r.scaleOffset=="object"&&typeof r.duration=="number"}class mo{constructor(t,e){if(this.entity=t,this.id=H(),this._started=!1,this._stopped=!1,this._endScale=b(1,1),this._scaleOffset=b(0,0),this._startScale=b(1,1),this._scaleOffset=e.scaleOffset,this._tx=t.get(P),this._motion=t.get(O),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only ScaleBy on Entities with TransformComponents.`);this._durationMs=e.duration,this._currentMs=this._durationMs}update(t){this._started||(this._startScale=this._tx.scale,this._endScale=this._startScale.add(this._scaleOffset),this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1),i=ii(this._startScale,this._endScale,e),s=this._tx.scale,n=t/1e3,o=i.sub(s).scale(n===0?0:1/n);this._motion.scaleFactor=o,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.angularVelocity=0)}isComplete(){return this._stopped||this._currentMs<0}stop(){this._motion.scaleFactor=w.Zero,this._stopped=!0,this._currentMs=0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}}class vo{constructor(t,e,i,s){this.id=H(),this._started=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._offset=new w(e,i),this._speedX=this._speedY=s}update(t){this._started||(this._started=!0,this._startScale=this._tx.scale.clone(),this._endScale=this._startScale.add(this._offset),this._distanceX=Math.abs(this._endScale.x-this._startScale.x),this._distanceY=Math.abs(this._endScale.y-this._startScale.y),this._directionX=this._endScale.x<this._startScale.x?-1:1,this._directionY=this._endScale.y<this._startScale.y?-1:1),this._motion.scaleFactor.x=this._speedX*this._directionX,this._motion.scaleFactor.y=this._speedY*this._directionY,this.isComplete()&&(this._tx.scale=this._endScale,this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0)}isComplete(){return this._stopped||Math.abs(this._tx.scale.x-this._startScale.x)>=this._distanceX-.01&&Math.abs(this._tx.scale.y-this._startScale.y)>=this._distanceY-.01}stop(){this._motion.scaleFactor.x=0,this._motion.scaleFactor.y=0,this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class wo{constructor(t){this.id=H(),this._hasBeenCalled=!1,this._method=t}update(t){this._method(),this._hasBeenCalled=!0}isComplete(){return this._hasBeenCalled}reset(){this._hasBeenCalled=!1}stop(){this._hasBeenCalled=!0}}class xo{constructor(t,e,i,s,n){this.easingFcn=n,this.id=H(),this._currentLerpTime=0,this._lerpDuration=1*1e3,this._lerpStart=new w(0,0),this._lerpEnd=new w(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._lerpDuration=s,this._lerpEnd=new w(e,i)}_initialize(){this._lerpStart=new w(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;if(this._currentLerpTime<this._lerpDuration){this._lerpEnd.x<this._lerpStart.x?e=this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):e=this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),this._lerpEnd.y<this._lerpStart.y?i=this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):i=this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration);const s=t/1e3;this._motion.vel=b(s===0?0:(e-this._tx.pos.x)/s,s===0?0:(i-this._tx.pos.y)/s)}else this._tx.pos=b(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=w.Zero}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=b(0,0),this._stopped=!0}}class bo{constructor(t,e,i,s,n){this.easingFcn=n,this.id=H(),this._currentLerpTime=0,this._lerpDuration=1*1e3,this._lerpStart=new w(0,0),this._lerpEnd=new w(0,0),this._initialized=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._lerpDuration=s,this._offset=new w(e,i)}_initialize(){this._lerpStart=new w(this._tx.pos.x,this._tx.pos.y),this._currentLerpTime=0,this._lerpEnd=this._lerpStart.add(this._offset)}update(t){this._initialized||(this._initialize(),this._initialized=!0),this._currentLerpTime+=t;let e=this._tx.pos.x,i=this._tx.pos.y;if(this._currentLerpTime<this._lerpDuration){this._lerpEnd.x<this._lerpStart.x?e=this._lerpStart.x-(this.easingFcn(this._currentLerpTime,this._lerpEnd.x,this._lerpStart.x,this._lerpDuration)-this._lerpEnd.x):e=this.easingFcn(this._currentLerpTime,this._lerpStart.x,this._lerpEnd.x,this._lerpDuration),this._lerpEnd.y<this._lerpStart.y?i=this._lerpStart.y-(this.easingFcn(this._currentLerpTime,this._lerpEnd.y,this._lerpStart.y,this._lerpDuration)-this._lerpEnd.y):i=this.easingFcn(this._currentLerpTime,this._lerpStart.y,this._lerpEnd.y,this._lerpDuration);const s=t/1e3;this._motion.vel=b(s===0?0:(e-this._tx.pos.x)/s,s===0?0:(i-this._tx.pos.y)/s)}else this._tx.pos=b(this._lerpEnd.x,this._lerpEnd.y),this._motion.vel=w.Zero}isComplete(){return this._stopped||this._currentLerpTime>=this._lerpDuration}reset(){this._initialized=!1,this._stopped=!1,this._currentLerpTime=0}stop(){this._motion.vel=b(0,0),this._stopped=!0}}class yo{constructor(t,e,i,s=1){this.id=H(),this._timeVisible=0,this._timeNotVisible=0,this._elapsedTime=0,this._totalTime=0,this._stopped=!1,this._started=!1,this._graphics=t.get(K),this._timeVisible=e,this._timeNotVisible=i,this._duration=(e+i)*s}update(t){this._started||(this._started=!0,this._elapsedTime=0,this._totalTime=0),this._graphics&&(this._elapsedTime+=t,this._totalTime+=t,this._graphics.isVisible&&this._elapsedTime>=this._timeVisible&&(this._graphics.isVisible=!1,this._elapsedTime=0),!this._graphics.isVisible&&this._elapsedTime>=this._timeNotVisible&&(this._graphics.isVisible=!0,this._elapsedTime=0),this.isComplete()&&(this._graphics.isVisible=!0))}isComplete(){return this._stopped||this._totalTime>=this._duration}stop(){this._graphics&&(this._graphics.isVisible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._elapsedTime=0,this._totalTime=0}}class Co{constructor(t,e,i){this.id=H(),this._multiplier=1,this._started=!1,this._stopped=!1,this._graphics=t.get(K),this._endOpacity=e,this._remainingTime=this._originalTime=i}update(t){this._graphics&&(this._started||(this._started=!0,this._remainingTime=this._originalTime,this._endOpacity<this._graphics.opacity?this._multiplier=-1:this._multiplier=1),this._remainingTime>0&&(this._graphics.opacity+=this._multiplier*(Math.abs(this._graphics.opacity-this._endOpacity)*t)/this._remainingTime),this._remainingTime-=t,this.isComplete()&&(this._graphics.opacity=this._endOpacity),R.getInstance().debug("[Action fade] Actor opacity:",this._graphics.opacity))}isComplete(){return this._stopped||this._remainingTime<=0}stop(){this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._remainingTime=this._originalTime}}class So{constructor(t){this.id=H(),this._elapsedTime=0,this._started=!1,this._stopped=!1,this._delay=t}update(t){this._started||(this._started=!0),this._elapsedTime+=t}isComplete(){return this._stopped||this._elapsedTime>=this._delay}stop(){this._stopped=!0}reset(){this._elapsedTime=0,this._started=!1,this._stopped=!1}}class To{constructor(t){this.id=H(),this._stopped=!1,this._entity=t}update(t){this._entity.get(Qe).clearActions(),this._entity.kill(),this._stopped=!0}isComplete(){return this._stopped}stop(){}reset(){}}class Pn{constructor(t,e,i){this.id=H(),this._started=!1,this._stopped=!1,this._tx=t.get(P),this._motion=t.get(O),this._followTx=e.get(P),this._followMotion=e.get(O),this._current=new w(this._tx.pos.x,this._tx.pos.y),this._end=new w(this._followTx.pos.x,this._followTx.pos.y),this._maximumDistance=i!==void 0?i:this._current.distance(this._end),this._speed=0}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._followMotion.vel.x,2)+Math.pow(this._followMotion.vel.y,2));if(e!==0&&(this._speed=e),this._current=b(this._tx.pos.x,this._tx.pos.y),this._end=b(this._followTx.pos.x,this._followTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize(),this._distanceBetween>=this._maximumDistance){const i=this._dir.scale(this._speed);this._motion.vel=b(i.x,i.y)}else this._motion.vel=b(0,0);this.isComplete()&&(this._tx.pos=b(this._end.x,this._end.y),this._motion.vel=b(0,0))}stop(){this._motion.vel=b(0,0),this._stopped=!0}isComplete(){return this._stopped}reset(){this._started=!1,this._stopped=!1}}class ji{constructor(t,e,i,s){this.id=H(),this._started=!1,this._stopped=!1,this._speedWasSpecified=!1,this._tolerance=1,this._tx=t.get(P),this._motion=t.get(O),this._meetTx=e.get(P),this._meetMotion=e.get(O),this._current=new w(this._tx.pos.x,this._tx.pos.y),this._end=new w(this._meetTx.pos.x,this._meetTx.pos.y),this._speed=i||0,i!==void 0&&(this._speedWasSpecified=!0),s!==void 0&&(this._tolerance=s)}update(t){this._started||(this._started=!0,this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize());const e=Math.sqrt(Math.pow(this._meetMotion.vel.x,2)+Math.pow(this._meetMotion.vel.y,2));e!==0&&!this._speedWasSpecified&&(this._speed=e),this._current=b(this._tx.pos.x,this._tx.pos.y),this._end=b(this._meetTx.pos.x,this._meetTx.pos.y),this._distanceBetween=this._current.distance(this._end),this._dir=this._end.sub(this._current).normalize();const i=this._dir.scale(this._speed);this._motion.vel=b(i.x,i.y),this.isComplete()&&(this._tx.pos=b(this._end.x,this._end.y),this._motion.vel=b(0,0))}isComplete(){return this._stopped||this._distanceBetween<=this._tolerance}stop(){this._motion.vel=b(0,0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1,this._distanceBetween=1/0}}class Ao{constructor(t,e,i=1e3){this.id=H(),this._stopped=!1,this._started=!1,this._total=0,this._currentDuration=0;var s;this._graphics=t.get(K),this._duration=i,this._entity=t,this._material=(s=t.scene)==null?void 0:s.engine.graphicsContext.createMaterial({name:"flash-material",color:e,fragmentSource:`#version 300 es
|
|
770
881
|
|
|
771
882
|
precision mediump float;
|
|
772
883
|
uniform float u_blend;
|
|
@@ -780,10 +891,10 @@ If you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPost
|
|
|
780
891
|
vec4 textureColor = texture(u_graphic, v_uv);
|
|
781
892
|
color = mix(textureColor, u_color, u_blend * textureColor.a);
|
|
782
893
|
color.rgb = color.rgb * color.a;
|
|
783
|
-
}`}),this._total=i}update(t){var e;this._started||(this._started=!0,this._total=this._duration,this._currentDuration=this._duration,this._entity.graphics.material=this._material),this._graphics&&(this._currentDuration-=t,this._graphics&&((e=this._material)==null||e.update(i=>{i.trySetUniformFloat("u_blend",this._currentDuration/this._total)})),this.isComplete()&&(this._entity.graphics.material=null))}isComplete(){return this._stopped||this._currentDuration<=0}stop(){this._graphics&&(this._graphics.isVisible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class Ao{constructor(t,e){this.id=N(),this._started=!1,this._stopped=!1,this._mode="dynamic";var i;if(this._entity=t,this._tx=this._entity.get(A),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only curveTo on Entities with TransformComponents.`);this._curve=new ei({controlPoints:[x(0,0),...e.controlPoints],quality:e.quality}),this._durationMs=e.duration,this._mode=(i=e.mode)!=null?i:this._mode,this._currentMs=this._durationMs}update(t){this._started||(this._curve.setControlPoint(0,this._tx.globalPos.clone()),this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1);this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(e):this._tx.pos=this._curve.getUniformPoint(e),this.isComplete(this._entity)&&(this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(1):this._tx.pos=this._curve.getUniformPoint(1))}isComplete(t){return this._stopped||this._currentMs<0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}stop(){this._stopped=!0,this._currentMs=0}}class Eo{constructor(t,e){this.id=N(),this._started=!1,this._stopped=!1,this._mode="dynamic";var i;if(this._entity=t,this._tx=this._entity.get(A),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only curveTo on Entities with TransformComponents.`);this._curve=this._curve=new ei({controlPoints:[x(0,0),...e.controlPoints],quality:e.quality}),this._durationMs=e.duration,this._mode=(i=e.mode)!=null?i:this._mode,this._currentMs=this._durationMs}update(t){this._started||(this._curve.setControlPoint(0,this._tx.globalPos),this._curve.setControlPoint(1,this._curve.controlPoints[1].add(this._tx.globalPos)),this._curve.setControlPoint(2,this._curve.controlPoints[2].add(this._tx.globalPos)),this._curve.setControlPoint(3,this._curve.controlPoints[3].add(this._tx.globalPos)),this._started=!0),this._currentMs-=t;const e=F(Ht(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1);this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(e):this._tx.pos=this._curve.getUniformPoint(e),this.isComplete(this._entity)&&(this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(1):this._tx.pos=this._curve.getUniformPoint(1))}isComplete(t){return this._stopped||this._currentMs<0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}stop(){this._stopped=!0}}class _i{constructor(t){this._entity=t,this._queue=new eo(t)}getQueue(){return this._queue}update(t){this._queue.update(t)}clearActions(){this._queue.clearActions()}runAction(t){return t.reset(),this._queue.add(t),this}curveBy(t){return this._queue.add(new Eo(this._entity,t)),this}curveTo(t){return this._queue.add(new Ao(this._entity,t)),this}easeTo(...t){var e,i;let s=0,n=0,o=0,a=It.Linear;return t[0]instanceof v?(s=t[0].x,n=t[0].y,o=t[1],a=(e=t[2])!=null?e:a):(s=t[0],n=t[1],o=t[2],a=(i=t[3])!=null?i:a),this._queue.add(new xo(this._entity,s,n,o,a)),this}easeBy(...t){var e,i;let s=0,n=0,o=0,a=It.Linear;return t[0]instanceof v?(s=t[0].x,n=t[0].y,o=t[1],a=(e=t[2])!=null?e:a):(s=t[0],n=t[1],o=t[2],a=(i=t[3])!=null?i:a),this._queue.add(new bo(this._entity,s,n,o,a)),this}moveTo(t,e,i){let s=0,n=0,o=0;return t instanceof v?(s=t.x,n=t.y,o=+(e!=null?e:0),this._queue.add(new Pn(this._entity,s,n,o))):typeof t=="number"&&typeof e=="number"&&typeof i=="number"?(s=t,n=e,o=i,this._queue.add(new Pn(this._entity,s,n,o))):oo(t)&&this._queue.add(new ao(this._entity,t)),this}moveBy(t,e,i){let s=0,n=0,o=0;return t instanceof v&&typeof e=="number"?(s=t.x,n=t.y,o=e,this._queue.add(new Tn(this._entity,s,n,o))):typeof t=="number"&&typeof e=="number"&&typeof i=="number"?(s=t,n=e,o=i,this._queue.add(new Tn(this._entity,s,n,o))):no(t)&&this._queue.add(new ro(this._entity,t)),this}rotateTo(t,e,i){return typeof t=="number"&&typeof e=="number"?this._queue.add(new lo(this._entity,t,e,i)):typeof t=="object"&&this._queue.add(new ho(this._entity,t)),this}rotateBy(t,e,i){return typeof t=="object"?this._queue.add(new co(this._entity,t)):this._queue.add(new uo(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,o=1,a=0,h=0;return _o(t)?(this._queue.add(new fo(this._entity,t)),this):(t instanceof v&&e instanceof v&&(n=t.x,o=t.y,a=e.x,h=e.y),typeof t=="number"&&typeof e=="number"&&(n=t,o=e,a=i,h=s),this._queue.add(new go(this._entity,n,o,a,h)),this)}scaleBy(t,e,i){if(po(t))return this._queue.add(new mo(this._entity,t)),this;let s=1,n=1;return t instanceof v&&(s=t.x,n=t.y,i=e),typeof t=="number"&&typeof e=="number"&&(s=t,n=e),this._queue.add(new vo(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new yo(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new Co(this._entity,t,e)),this}flash(t,e=1e3){return this._queue.add(new Po(this._entity,t,e)),this}delay(t){return this._queue.add(new So(t)),this}die(){return this._queue.add(new To(this._entity)),this}callMethod(t){return this._queue.add(new wo(t)),this}repeat(t,e){return e?(this._queue.add(new io(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new so(this._entity,t)),this}follow(t,e){return e===void 0?this._queue.add(new An(this._entity,t)):this._queue.add(new An(this._entity,t,e)),this}meet(t,e,i){return e===void 0&&i===void 0?this._queue.add(new $i(this._entity,t)):i===void 0?this._queue.add(new $i(this._entity,t,e)):this._queue.add(new $i(this._entity,t,e,i)),this}toPromise(){return new Promise(e=>{this._queue.add(new wo(()=>{e()}))})}}class je extends Dt{constructor(){super(...arguments),this.dependencies=[A,H],this._ctx=null}onAdd(t){this._ctx=new _i(t)}onRemove(){this._ctx=null}_getCtx(){if(!this._ctx)throw new Error("Actions component not attached to an entity, no context available");return this._ctx}getQueue(){if(!this._ctx)throw new Error("Actions component not attached to an entity, no queue available");return this._ctx.getQueue()}runAction(t){if(!this._ctx)throw new Error("Actions component not attached to an entity, cannot run action");return this._ctx.runAction(t)}update(t){var e;return(e=this._ctx)==null?void 0:e.update(t)}clearActions(){var t;(t=this._ctx)==null||t.clearActions()}curveBy(t){return this._getCtx().curveBy.apply(this._ctx,[t])}curveTo(t){return this._getCtx().curveTo.apply(this._ctx,[t])}easeTo(...t){return this._getCtx().easeTo.apply(this._ctx,t)}easeBy(...t){return this._getCtx().easeBy.apply(this._ctx,t)}moveTo(t,e,i){return this._getCtx().moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._getCtx().moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._getCtx().rotateTo.apply(this._ctx,[t,e,i])}rotateBy(t,e,i){return this._getCtx().rotateBy.apply(this._ctx,[t,e,i])}scaleTo(t,e,i,s){return this._getCtx().scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._getCtx().scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._getCtx().blink(t,e,i)}fade(t,e){return this._getCtx().fade(t,e)}flash(t,e=1e3){return this._getCtx().flash(t,e)}delay(t){return this._getCtx().delay(t)}die(){return this._getCtx().die()}callMethod(t){return this._getCtx().callMethod(t)}repeat(t,e){return this._getCtx().repeat(t,e)}repeatForever(t){return this._getCtx().repeatForever(t)}follow(t,e){return this._getCtx().follow(t,e)}meet(t,e){return this._getCtx().meet(t,e)}toPromise(){return this._getCtx().toPromise()}}function yl(r){return r instanceof Ft}const Cl={CollisionStart:"collisionstart",CollisionEnd:"collisionend",PreCollision:"precollision",PostCollision:"postcollision",Kill:"kill",PreKill:"prekill",PostKill:"postkill",PreDraw:"predraw",PostDraw:"postdraw",PreTransformDraw:"pretransformdraw",PostTransformDraw:"posttransformdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw",PointerUp:"pointerup",PointerDown:"pointerdown",PointerEnter:"pointerenter",PointerLeave:"pointerleave",PointerMove:"pointermove",PointerCancel:"pointercancel",Wheel:"pointerwheel",PointerDrag:"pointerdragstart",PointerDragEnd:"pointerdragend",PointerDragEnter:"pointerdragenter",PointerDragLeave:"pointerdragleave",PointerDragMove:"pointerdragmove",EnterViewPort:"enterviewport",ExitViewPort:"exitviewport",ActionStart:"actionstart",ActionComplete:"actioncomplete"},Io=class or extends Tt{constructor(t){super(),this.events=new X,this._anchor=Et(v.Half,z=>this._handleAnchorChange(z)),this._offset=Et(v.Zero,z=>this._handleOffsetChange(z)),this.logger=R.getInstance(),this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=z=>{this._dragging&&(this.pos=z.worldPos)},this._pointerDragLeaveHandler=z=>{this._dragging&&(this.pos=z.worldPos)};const{name:e,x:i,y:s,pos:n,coordPlane:o,scale:a,width:h,height:l,radius:c,collider:u,vel:_,acc:f,rotation:p,angularVelocity:g,z:w,color:m,visible:b,opacity:T,anchor:C,offset:S,collisionType:I,collisionGroup:y,graphic:k,material:U}={...t};this.name=e!=null?e:this.name,this.anchor=C!=null?C:or.defaults.anchor.clone(),this.offset=S!=null?S:v.Zero,this.transform=new A,this.addComponent(this.transform),this.pos=n!=null?n:x(i!=null?i:0,s!=null?s:0),this.rotation=p!=null?p:0,this.scale=a!=null?a:x(1,1),this.z=w!=null?w:0,this.transform.coordPlane=o!=null?o:rt.World,this.pointer=new ae,this.addComponent(this.pointer),this.graphics=new j({anchor:this.anchor,offset:this.offset,opacity:T}),this.addComponent(this.graphics),this.motion=new H,this.addComponent(this.motion),this.vel=_!=null?_:v.Zero,this.acc=f!=null?f:v.Zero,this.angularVelocity=g!=null?g:0,this.actions=new je,this.addComponent(this.actions),this.body=new W,this.addComponent(this.body),this.body.collisionType=I!=null?I:M.Passive,y&&(this.body.group=y),m&&(this.color=m),u?(this.collider=new tt(u),this.addComponent(this.collider)):c?(this.collider=new tt(ut.Circle(c)),this.addComponent(this.collider),m&&this.graphics.add(new Vi({color:m,radius:c}))):h>0&&l>0?(this.collider=new tt(ut.Box(h,l,this.anchor)),this.addComponent(this.collider),m&&h&&l&&this.graphics.add(new ci({color:m,width:h,height:l}))):(this.collider=new tt,this.addComponent(this.collider)),this.graphics.isVisible=b!=null?b:!0,k&&this.graphics.use(k),U&&(this.graphics.material=U)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}get oldGlobalPos(){return this.body.oldGlobalPos}set oldPos(t){this.body.oldPos.setTo(t.x,t.y)}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t.clone()}get oldVel(){return this.body.oldVel}set oldVel(t){this.body.oldVel.setTo(t.x,t.y)}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t.clone()}set oldAcc(t){this.body.oldAcc.setTo(t.x,t.y)}get oldAcc(){return this.body.oldAcc}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}get scale(){return this.get(A).scale}set scale(t){this.get(A).scale=t}get anchor(){return this._anchor}set anchor(t){this._anchor=Et(t,e=>this._handleAnchorChange(e)),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get offset(){return this._offset}set offset(t){this._offset=Et(t,e=>this._handleOffsetChange(e)),this._handleOffsetChange(t)}_handleOffsetChange(t){this.graphics&&(this.graphics.offset=t)}get isOffScreen(){return this.hasTag("ex.offscreen")}get draggable(){return this._draggable}set draggable(t){t&&(t&&!this._draggable?(this.events.on("pointerdragstart",this._pointerDragStartHandler),this.events.on("pointerdragend",this._pointerDragEndHandler),this.events.on("pointerdragmove",this._pointerDragMoveHandler),this.events.on("pointerdragleave",this._pointerDragLeaveHandler)):!t&&this._draggable&&(this.events.off("pointerdragstart",this._pointerDragStartHandler),this.events.off("pointerdragend",this._pointerDragEndHandler),this.events.off("pointerdragmove",this._pointerDragMoveHandler),this.events.off("pointerdragleave",this._pointerDragLeaveHandler)),this._draggable=t)}get color(){return this.graphics.color}set color(t){this.graphics.color=t}clone(){const t=new or({color:this.color.clone(),anchor:this.anchor.clone(),offset:this.offset.clone()});t.clearComponents(),t.processComponentRemoval(),t.addComponent(t.transform=this.transform.clone(),!0),t.addComponent(t.pointer=this.pointer.clone(),!0),t.addComponent(t.graphics=this.graphics.clone(),!0),t.addComponent(t.motion=this.motion.clone(),!0),t.addComponent(t.actions=this.actions.clone(),!0),t.addComponent(t.body=this.body.clone(),!0),this.collider.get()&&t.addComponent(t.collider=this.collider.clone(),!0);const e=[this.transform,this.pointer,this.graphics,this.motion,this.actions,this.body,this.collider],i=this.getComponents();for(const s of i)e.includes(s)||t.addComponent(s.clone(),!0);return t}onInitialize(t){}_initialize(t){super._initialize(t);for(const e of this.children)e._initialize(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_prekill(t){this.events.emit("prekill",new Ts(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){this.events.emit("postkill",new Ps(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),this.events.emit("kill",new Ai(this)),super.kill(),this._postkill(this.scene)):this.logger.warn(`Cannot kill actor named "${this.name}", it was never added to the Scene`)}unkill(){this.isActive=!0}isKilled(){return!this.isActive}get z(){return this.get(A).z}set z(t){this.get(A).z=t}get center(){const t=this.getGlobalPos();return new v(t.x+this.width/2-this.anchor.x*this.width,t.y+this.height/2-this.anchor.y*this.height)}get localCenter(){return new v(this.pos.x+this.width/2-this.anchor.x*this.width,this.pos.y+this.height/2-this.anchor.y*this.height)}get width(){return this.collider.localBounds.width*this.getGlobalScale().x}get height(){return this.collider.localBounds.height*this.getGlobalScale().y}getGlobalRotation(){return this.get(A).globalRotation}get globalRotation(){return this.get(A).globalRotation}getGlobalPos(){return this.get(A).globalPos}get globalPos(){return this.get(A).globalPos}getGlobalScale(){return this.get(A).globalScale}get globalScale(){return this.get(A).globalScale}get globalZ(){return this.get(A).globalZ}contains(t,e,i=!1){const s=x(t,e),n=this.get(tt);n.update();const o=n.get();if(!o)return!1;const a=o.contains(s);return i?a||this.children.some(h=>h.contains(t,e,!0)):a}within(t,e){const i=this.get(tt),s=t.get(tt),n=i.get(),o=s.get();return n&&o?n.getClosestLineBetween(o).getLength()<=e:!1}update(t,e){this._initialize(t),this._add(t),this._preupdate(t,e),this._postupdate(t,e),this._remove(t)}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreCollisionResolve(t,e,i,s){}onPostCollisionResolve(t,e,i,s){}onCollisionStart(t,e,i,s){}onCollisionEnd(t,e,i,s){}_preupdate(t,e){this.events.emit("preupdate",new ne(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new re(t,e,this)),this.onPostUpdate(t,e)}};Io.defaults={anchor:v.Half};let Ft=Io;class tt extends Dt{constructor(t){super(),this.events=new X,this.$colliderAdded=new gt,this.$colliderRemoved=new gt,this._collidersToRemove=[],this.set(t)}get(){return this._collider}set(t){return this.clear(),t&&(this._collider=t,this._collider.owner=this.owner,t.events.pipe(this.events),this.$colliderAdded.notifyAll(t),this.update()),t}clear(){this._collider&&(this._collidersToRemove.push(this._collider),this._collider=null)}processColliderRemoval(){for(const t of this._collidersToRemove)t.events.unpipe(this.events),this.$colliderRemoved.notifyAll(t),t.owner=null}clone(){return new tt(this._collider.clone())}get bounds(){var t,e;return(e=(t=this._collider)==null?void 0:t.bounds)!=null?e:new D}get localBounds(){var t,e;return(e=(t=this._collider)==null?void 0:t.localBounds)!=null?e:new D}update(){var t;const e=(t=this.owner)==null?void 0:t.get(A);this._collider&&(this._collider.owner=this.owner,e&&this._collider.update(e.get()))}collide(t){let e=this._collider,i=t._collider;if(!e||!i)return[];let s=!1;if(i instanceof at&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach(o=>{o.mtv=o.mtv.negate(),o.normal=o.normal.negate(),o.tangent=o.normal.perpendicular(),o.colliderA=this._collider,o.colliderB=t._collider}),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",e=>{const i=e;t.events.emit("precollision",new me(i.self,i.other,i.side,i.intersection,i.contact)),t instanceof Ft&&t.onPreCollisionResolve(i.self,i.other,i.side,i.contact)}),this.events.on("postcollision",e=>{const i=e;t.events.emit("postcollision",new ve(i.self,i.other,i.side,i.intersection,i.contact)),t instanceof Ft&&t.onPostCollisionResolve(i.self,i.other,i.side,i.contact)}),this.events.on("collisionstart",e=>{const i=e;t.events.emit("collisionstart",new ii(i.self,i.other,i.side,i.contact)),t instanceof Ft&&t.onCollisionStart(i.self,i.other,i.side,i.contact)}),this.events.on("collisionend",e=>{const i=e;t.events.emit("collisionend",new si(i.self,i.other,i.side,i.lastContact)),t instanceof Ft&&t.onCollisionEnd(i.self,i.other,i.side,i.lastContact)})}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=v.Half,s=v.Zero){const n=ut.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=v.Zero){const i=ut.Polygon(t,e);return this.set(i)}useCircleCollider(t,e=v.Zero){const i=ut.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=ut.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new at(t))}}var he=(r=>(r.Rotation="rotation",r.X="x",r.Y="y",r))(he||{});const En=class ds extends Dt{constructor(t){var e,i,s;super(),this.dependencies=[A,H],this.id=_e("body",ds._ID++),this.events=new X,this.oldTransform=new Qt,this.__oldTransformCaptured=!1,this.enableFixedUpdateInterpolate=!0,this.collisionType=M.PreventCollision,this.group=pe.All,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this._oldGlobalPos=v.Zero,this.oldVel=new v(0,0),this.oldAcc=v.Zero,this._impulseScratch=x(0,0),this._distanceFromCenterScratch=x(0,0),t?(this.collisionType=(e=t.type)!=null?e:this.collisionType,this.group=(i=t.group)!=null?i:this.group,this.useGravity=(s=t.useGravity)!=null?s:this.useGravity,this._bodyConfig={...Jt().bodies,...t.config}):this._bodyConfig={...Jt().bodies},this.updatePhysicsConfig(this._bodyConfig),this._mass=ds._DEFAULT_CONFIG.defaultMass}get matrix(){return this.transform.get().matrix}updatePhysicsConfig(t){this._bodyConfig={...Jt().bodies,...t},this.canSleep=this._bodyConfig.canSleepByDefault,this.sleepMotion=this._bodyConfig.sleepEpsilon*5,this.wakeThreshold=this._bodyConfig.wakeThreshold}static updateDefaultPhysicsConfig(t){ds._DEFAULT_CONFIG=t}get mass(){return this._mass}set mass(t){this._mass=t,this._cachedInertia=void 0,this._cachedInverseInertia=void 0}get inverseMass(){return this.collisionType===M.Fixed?0:1/this.mass}get sleeping(){return this.isSleeping}get isSleeping(){return this._sleeping}setSleeping(t){this.isSleeping=t}set isSleeping(t){this._sleeping=t,t?(this.vel=v.Zero,this.acc=v.Zero,this.angularVelocity=0,this.sleepMotion=0):this.sleepMotion=this._bodyConfig.sleepEpsilon*5}updateMotion(){this._sleeping&&(this.isSleeping=!0);const t=this.vel.magnitude*this.vel.magnitude+Math.abs(this.angularVelocity*this.angularVelocity),e=this._bodyConfig.sleepBias;this.sleepMotion=e*this.sleepMotion+(1-e)*t,this.sleepMotion=F(this.sleepMotion,0,10*this._bodyConfig.sleepEpsilon),this.canSleep&&this.sleepMotion<this._bodyConfig.sleepEpsilon&&(this.isSleeping=!0)}get inertia(){if(this._cachedInertia)return this._cachedInertia;const t=this.owner.get(tt);if(t){t.$colliderAdded.subscribe(()=>{this._cachedInertia=null}),t.$colliderRemoved.subscribe(()=>{this._cachedInertia=null});const e=t.get();if(e)return this._cachedInertia=e.getInertia(this.mass)}return 0}get inverseInertia(){return this._cachedInverseInertia?this._cachedInverseInertia:this._cachedInverseInertia=this.collisionType===M.Fixed?0:1/this.inertia}get active(){var t;return!!((t=this.owner)!=null&&t.isActive)}get isActive(){var t;return!!((t=this.owner)!=null&&t.isActive)}get center(){return this.globalPos}onAdd(t){var e,i;this.transform=(e=this.owner)==null?void 0:e.get(A),this.motion=(i=this.owner)==null?void 0:i.get(H)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get globalPos(){return this.transform.globalPos}set globalPos(t){this.transform.globalPos=t}get oldPos(){return this.oldTransform.pos}get oldGlobalPos(){return this._oldGlobalPos}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t}get torque(){return this.motion.torque}set torque(t){this.motion.torque=t}get oldRotation(){return this.oldTransform.rotation}get rotation(){return this.transform.globalRotation}set rotation(t){this.transform.globalRotation=t}get scale(){return this.transform.globalScale}set scale(t){this.transform.globalScale=t}get oldScale(){return this.oldTransform.scale}get scaleFactor(){return this.motion.scaleFactor}set scaleFactor(t){this.motion.scaleFactor=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}applyImpulse(t,e){if(this.collisionType!==M.Active)return;const i=e.scale(this.inverseMass,this._impulseScratch);if(this.limitDegreeOfFreedom.indexOf("x")>-1&&(i.x=0),this.limitDegreeOfFreedom.indexOf("y")>-1&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes("rotation")){const s=t.sub(this.globalPos,this._distanceFromCenterScratch);this.angularVelocity+=this.inverseInertia*s.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==M.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes("x")&&(e.x=0),this.limitDegreeOfFreedom.includes("y")&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===M.Active&&!this.limitDegreeOfFreedom.includes("rotation")){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.__oldTransformCaptured=!0;const t=this.transform.get();t.clone(this.oldTransform),this.oldTransform.parent=t.parent,this.oldVel.setTo(this.vel.x,this.vel.y),this.oldAcc.setTo(this.acc.x,this.acc.y),this.oldGlobalPos.setTo(this.globalPos.x,this.globalPos.y)}clone(){return super.clone()}};En._ID=0,En._DEFAULT_CONFIG={...Jt().bodies};let W=En;class In{constructor(t,e){this.object=t,this.id=-1,this.cells=[],this.hasZeroBounds=!1,this.gridSize=e,this.bounds=t.bounds,this.hasZeroBounds=this.bounds.hasZeroDimensions(),this.leftX=Math.floor(this.bounds.left/this.gridSize),this.rightX=Math.floor(this.bounds.right/this.gridSize),this.bottomY=Math.floor(this.bounds.bottom/this.gridSize),this.topY=Math.floor(this.bounds.top/this.gridSize)}hasChanged(){const t=this.object.bounds,e=Math.floor(t.left/this.gridSize),i=Math.floor(t.right/this.gridSize),s=Math.floor(t.bottom/this.gridSize),n=Math.floor(t.top/this.gridSize);return this.leftX!==e||this.rightX!==i||this.bottomY!==s||this.topY!==n}clear(){for(const t of this.cells){const e=t.proxies.indexOf(this);e>-1&&t.proxies.splice(e,1)}}updateBounds(){this.bounds=this.object.bounds}update(){this.bounds=this.object.bounds,this.leftX=Math.floor(this.bounds.left/this.gridSize),this.rightX=Math.floor(this.bounds.right/this.gridSize),this.bottomY=Math.floor(this.bounds.bottom/this.gridSize),this.topY=Math.floor(this.bounds.top/this.gridSize),this.hasZeroBounds=this.object.bounds.hasZeroDimensions()}}class Yt{constructor(){this.proxies=[]}configure(t,e){this.x=t,this.y=e,this.key=Yt.calculateHashKey(t,e)}static calculateHashKey(t,e){return`${t}+${e}`}}class Rn{constructor(t){this.bounds=new D,this._hashGridCellPool=new Ve(()=>new Yt,e=>(e.configure(0,0),e.proxies.length=0,e),1e3),this.gridSize=t.size,this.sparseHashGrid=new Map,this.objectToProxy=new Map,t.proxyFactory?this._buildProxy=e=>t.proxyFactory(e,this.gridSize):this._buildProxy=e=>new In(e,this.gridSize)}query(t){const e=new Set;if(t instanceof D){const i=t,s=Math.floor(i.left/this.gridSize),n=Math.floor(i.right/this.gridSize),o=Math.floor(i.bottom/this.gridSize),a=Math.floor(i.top/this.gridSize);for(let h=s;h<=n;h++)for(let l=a;l<=o;l++){const c=Yt.calculateHashKey(h,l),u=this.sparseHashGrid.get(c);if(u)for(let _=0;_<u.proxies.length;_++)u.proxies[_].updateBounds(),u.proxies[_].bounds.intersect(i)&&e.add(u.proxies[_].object)}}else{const i=t,s=Yt.calculateHashKey(Math.floor(i.x/this.gridSize),Math.floor(i.y/this.gridSize)),n=this.sparseHashGrid.get(s);if(n)for(let o=0;o<n.proxies.length;o++)n.proxies[o].updateBounds(),n.proxies[o].bounds.contains(i)&&e.add(n.proxies[o].object)}return Array.from(e)}get(t,e){const i=Yt.calculateHashKey(t,e);return this.sparseHashGrid.get(i)}_insert(t,e,i){const s=Yt.calculateHashKey(t,e);let n=this.sparseHashGrid.get(s);n||(n=this._hashGridCellPool.rent(),n.configure(t,e),this.sparseHashGrid.set(n.key,n)),n.proxies.push(i),i.cells.push(n),this.bounds.combine(i.bounds,this.bounds)}_remove(t,e,i){const s=Yt.calculateHashKey(t,e),n=this.sparseHashGrid.get(s);if(n){const o=n.proxies.indexOf(i);o>-1&&n.proxies.splice(o,1);const a=i.cells.indexOf(n);a>-1&&i.cells.splice(a,1),n.proxies.length===0&&(this._hashGridCellPool.return(n),this.sparseHashGrid.delete(s))}}track(t){const e=this._buildProxy(t);this.objectToProxy.set(t,e);for(let i=e.leftX;i<=e.rightX;i++)for(let s=e.topY;s<=e.bottomY;s++)this._insert(i,s,e)}untrack(t){const e=this.objectToProxy.get(t);e&&(e.clear(),this.objectToProxy.delete(t))}update(t){let e=0;for(const i of t){const s=this.objectToProxy.get(i);if(s&&s.hasChanged()){for(let n=s.leftX;n<=s.rightX;n++)for(let o=s.topY;o<=s.bottomY;o++)this._remove(n,o,s);s.update();for(let n=s.leftX;n<=s.rightX;n++)for(let o=s.topY;o<=s.bottomY;o++)this._insert(n,o,s);e++}}return e}debug(t,e){const i=P.Transparent,s=P.White;for(const n of this.sparseHashGrid.values())t.drawRectangle(x(n.x*this.gridSize,n.y*this.gridSize),this.gridSize,this.gridSize,i,s,2)}}class Ro extends In{constructor(t,e){var i,s,n;super(t,e),this.collider=t,this.id=-1,this.hasZeroBounds=!1,this.cells=[],this.gridSize=e;const o=t.bounds;this.hasZeroBounds=o.hasZeroDimensions(),this.leftX=Math.floor(o.left/this.gridSize),this.rightX=Math.floor(o.right/this.gridSize),this.bottomY=Math.floor(o.bottom/this.gridSize),this.topY=Math.floor(o.top/this.gridSize),this.owner=t.owner,this.body=(i=this.owner)==null?void 0:i.get(W),this.collisionType=(n=(s=this.body)==null?void 0:s.collisionType)!=null?n:M.PreventCollision}update(){var t,e,i;super.update(),this.body=(t=this.owner)==null?void 0:t.get(W),this.collisionType=(i=(e=this.body)==null?void 0:e.collisionType)!=null?i:M.PreventCollision,this.hasZeroBounds=this.collider.localBounds.hasZeroDimensions()}}class Mn{constructor(t){this._pairs=new Set,this._nonPairs=new Set,this._pairPool=new Ui(()=>new pt({id:_e("collider",0)},{id:_e("collider",0)}),e=>(e.colliderA=null,e.colliderB=null,e),200),this.gridSize=t.size,this.hashGrid=new Rn({size:this.gridSize,proxyFactory:(e,i)=>new Ro(e,i)}),this._pairPool.disableWarnings=!0}getColliders(){return Array.from(this.hashGrid.objectToProxy.keys())}query(t){return this.hashGrid.query(t)}rayCast(t,e){var i,s,n;const o=[],a=(i=e==null?void 0:e.maxDistance)!=null?i:1/0,h=e==null?void 0:e.collisionGroup,l=h?h.category:(s=e==null?void 0:e.collisionMask)!=null?s:pe.All.category,c=(n=e==null?void 0:e.searchAllColliders)!=null?n:!1,u=t.dir.normalize(),_=u.y/u.x,f=u.x/u.y,p=Math.sqrt(1+_*_)*this.gridSize,g=Math.sqrt(1+f*f)*this.gridSize,w=t.pos.x/this.gridSize,m=t.pos.y/this.gridSize,b=x(1,1);let T=~~w,C=~~m,S=0,I=0;u.x<0?(b.x=-1,S=(w-T)*p):(b.x=1,S=(T+1-w)*p),u.y<0?(b.y=-1,I=(m-C)*g):(b.y=1,I=(C+1-m)*g);const y=new Set;let k=!1,U=9999;for(;!k&&U>0&&(U--,!!this.hashGrid.bounds.contains(x(T*this.gridSize,C*this.gridSize)));){const z=Yt.calculateHashKey(T,C),Y=this.hashGrid.sparseHashGrid.get(z);if(Y){const ht=[];for(let $=0;$<Y.proxies.length;$++){const G=Y.proxies[$];if(!y.has(G.collider.id.value)){if(y.add(G.collider.id.value),G.body){if(e!=null&&e.ignoreCollisionGroupAll&&G.body.group===pe.All)continue;const ft=(l&G.body.group.category)!==0;if(G.body.group&&!ft)continue}const ct=G.collider.rayCast(t,a);ct&&ht.push(ct)}}ht.sort(($,G)=>$.distance-G.distance);for(let $=0;$<ht.length;$++){const G=ht[$];if(e!=null&&e.filter){if(e.filter(G)&&(o.push(G),!c)){k=!0;break}}else if(o.push(G),!c){k=!0;break}}}S<I?(T+=b.x,S+=p):(C+=b.y,I+=g)}return o.sort((z,Y)=>z.distance-Y.distance),!c&&o.length?[o[0]]:o}track(t){let e=[t];if(t instanceof at){const i=t.getColliders();for(const s of i)s.owner=t.owner;e=i}for(const i of e)this.hashGrid.track(i)}untrack(t){let e=[t];t instanceof at&&(e=t.getColliders());for(const i of e)this.hashGrid.untrack(i)}_canCollide(t,e){return!(t.collider.id===e.collider.id||t.owner&&e.owner&&t.owner.id===e.owner.id||t.hasZeroBounds||e.hasZeroBounds||t.body&&e.body&&!t.body.group.canCollide(e.body.group)||t.collisionType===M.Fixed&&e.collisionType===M.Fixed||t.collisionType===M.PreventCollision||e.collisionType===M.PreventCollision||!t.owner.isActive||!e.owner.isActive)}broadphase(t,e){const i=[];this._pairs.clear(),this._nonPairs.clear();let s=0;for(const n of this.hashGrid.objectToProxy.values())if(n.id=s++,!(!n.owner.isActive||n.collisionType===M.PreventCollision))for(let o=0;o<n.cells.length;o++){const a=n.cells[o];for(let h=0;h<a.proxies.length;h++){const l=a.proxies[h];if(l.id===n.id)continue;const c=pt.calculatePairHash(n.collider.id,l.collider.id);if(!this._nonPairs.has(c))if(!this._pairs.has(c)&&this._canCollide(n,l)&&n.object.bounds.overlaps(l.object.bounds)){const u=this._pairPool.get();u.colliderA=n.collider,u.colliderB=l.collider,u.id=c,this._pairs.add(c),i.push(u)}else this._nonPairs.add(c)}}return i}narrowphase(t,e){const i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();for(let o=0;o<n.length;o++){const a=n[o];i.push(a),e&&e.physics.contacts.set(a.id,a)}}return this._pairPool.done(),e&&(e.physics.collisions+=i.length),i}update(t,e){return this.hashGrid.update(t)}debug(t,e){this.hashGrid.debug(t,e)}}class Ze{constructor(t,e){this.bounds=t,this.options=e,this._defaultOptions={maxDepth:10,capacity:10,level:0},this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null,this.options={...this._defaultOptions,...e},this.halfWidth=t.width/2,this.halfHeight=t.height/2}_split(){this._isDivided=!0;const t={maxDepth:this.options.maxDepth,capacity:this.options.capacity,level:this.options.level+1};this.topLeft=new Ze(new D({left:this.bounds.left,top:this.bounds.top,right:this.bounds.left+this.halfWidth,bottom:this.bounds.top+this.halfHeight}),t),this.topRight=new Ze(new D({left:this.bounds.left+this.halfWidth,top:this.bounds.top,right:this.bounds.right,bottom:this.bounds.top+this.halfHeight}),t),this.bottomLeft=new Ze(new D({left:this.bounds.left,top:this.bounds.top+this.halfHeight,right:this.bounds.left+this.halfWidth,bottom:this.bounds.bottom}),t),this.bottomRight=new Ze(new D({left:this.bounds.left+this.halfWidth,top:this.bounds.top+this.halfHeight,right:this.bounds.right,bottom:this.bounds.bottom}),t)}_insertIntoSubNodes(t){var e,i,s,n;(e=this.topLeft)!=null&&e.bounds.overlaps(t.bounds)&&this.topLeft.insert(t),(i=this.topRight)!=null&&i.bounds.overlaps(t.bounds)&&this.topRight.insert(t),(s=this.bottomLeft)!=null&&s.bounds.overlaps(t.bounds)&&this.bottomLeft.insert(t),(n=this.bottomRight)!=null&&n.bounds.overlaps(t.bounds)&&this.bottomRight.insert(t)}insert(t){if(this._isDivided){this._insertIntoSubNodes(t);return}if(this.items.push(t),this.items.length>this.options.capacity&&this.options.level<this.options.maxDepth){this._isDivided||this._split();for(const e of this.items)this._insertIntoSubNodes(e);this.items.length=0}}remove(t){var e,i,s,n;if(this.bounds.overlaps(t.bounds)){if(!this._isDivided){const o=this.items.indexOf(t);o>-1&&this.items.splice(o,1);return}(e=this.topLeft)!=null&&e.bounds.overlaps(t.bounds)&&this.topLeft.remove(t),(i=this.topRight)!=null&&i.bounds.overlaps(t.bounds)&&this.topRight.remove(t),(s=this.bottomLeft)!=null&&s.bounds.overlaps(t.bounds)&&this.bottomLeft.remove(t),(n=this.bottomRight)!=null&&n.bounds.overlaps(t.bounds)&&this.bottomRight.remove(t)}}query(t){let e=this.items;return this._isDivided&&(this.topLeft.bounds.overlaps(t)&&(e=e.concat(this.topLeft.query(t))),this.topRight.bounds.overlaps(t)&&(e=e.concat(this.topRight.query(t))),this.bottomLeft.bounds.overlaps(t)&&(e=e.concat(this.bottomLeft.query(t))),this.bottomRight.bounds.overlaps(t)&&(e=e.concat(this.bottomRight.query(t)))),e=e.filter((i,s)=>e.indexOf(i)>=s),e}clear(){this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null}getAllItems(){let t=this.items;return this._isDivided&&(t=t.concat(this.topLeft.getAllItems()),t=t.concat(this.topRight.getAllItems()),t=t.concat(this.bottomLeft.getAllItems()),t=t.concat(this.bottomRight.getAllItems())),t=t.filter((e,i)=>t.indexOf(e)>=i),t}getTreeDepth(){return this._isDivided?1+Math.max(this.topLeft.getTreeDepth(),this.topRight.getTreeDepth(),this.bottomLeft.getTreeDepth(),this.bottomRight.getTreeDepth()):0}debug(t){this.bounds.draw(t,P.Yellow),this._isDivided&&(this.topLeft.bounds.draw(t,P.Yellow),this.topRight.bounds.draw(t,P.Yellow),this.bottomLeft.bounds.draw(t,P.Yellow),this.bottomRight.bounds.draw(t,P.Yellow))}}class Dn{constructor(t){this.config=t,this.directionMap=new Map,this.distanceMap=new Map,this._compositeContactsIds=new Set}solve(t){this.preSolve(t),t=t.filter(i=>!i.isCanceled());let e;switch(this.config.contactSolveBias){case oe.HorizontalFirst:{e=en;break}case oe.VerticalFirst:{e=tn;break}default:e=sn}t.sort((i,s)=>{const n=this.directionMap.get(i.id),o=this.directionMap.get(s.id),a=this.distanceMap.get(i.id),h=this.distanceMap.get(s.id);return e[n]-e[o]||a-h});for(const i of t)this.solvePosition(i),this.solveVelocity(i);return this.postSolve(t),t}preSolve(t){for(let i=0;i<t.length;i++){const s=t[i],n=s.id.indexOf("|");if(n>0){const l=s.id.substring(n+1);if(this._compositeContactsIds.has(l)){s.cancel();continue}this._compositeContactsIds.add(l)}if(Math.abs(s.mtv.x)<1e-4&&Math.abs(s.mtv.y)<1e-4){s.cancel();continue}const o=d.Side.fromDirection(s.mtv),a=s.mtv.negate(),h=Math.abs(s.info.separation);this.distanceMap.set(s.id,h),this.directionMap.set(s.id,o===d.Side.Left||o===d.Side.Right?"horizontal":"vertical"),s.colliderA.events.emit("precollision",new me(s.colliderA,s.colliderB,o,a,s)),s.colliderB.events.emit("precollision",new me(s.colliderB,s.colliderA,d.Side.getOpposite(o),a.negate(),s))}this._compositeContactsIds.clear()}postSolve(t){var e,i;for(let s=0;s<t.length;s++){const n=t[s];if(n.isCanceled())continue;const o=n.colliderA,a=n.colliderB,h=(e=o.owner)==null?void 0:e.get(W),l=(i=a.owner)==null?void 0:i.get(W);if(h&&l&&(h.collisionType===M.Passive||l.collisionType===M.Passive))continue;const c=d.Side.fromDirection(n.mtv),u=n.mtv.negate();n.colliderA.events.emit("postcollision",new ve(n.colliderA,n.colliderB,c,u,n)),n.colliderB.events.emit("postcollision",new ve(n.colliderB,n.colliderA,d.Side.getOpposite(c),u.negate(),n))}}solvePosition(t){var e,i;if(!t.colliderA.bounds.overlaps(t.colliderB.bounds,1e-4)){t.cancel();return}if(Math.abs(t.mtv.x)<1e-4&&Math.abs(t.mtv.y)<1e-4){t.cancel();return}let n=t.mtv;const o=t.colliderA,a=t.colliderB,h=(e=o.owner)==null?void 0:e.get(W),l=(i=a.owner)==null?void 0:i.get(W);if(h&&l){if(h.collisionType===M.Passive||l.collisionType===M.Passive)return;h.collisionType===M.Active&&l.collisionType===M.Active&&(n=n.scale(.5)),h.collisionType===M.Active&&(h.globalPos.x-=n.x,h.globalPos.y-=n.y,o.update(h.transform.get())),l.collisionType===M.Active&&(l.globalPos.x+=n.x,l.globalPos.y+=n.y,a.update(l.transform.get()))}}solveVelocity(t){var e,i;if(t.isCanceled())return;const s=t.colliderA,n=t.colliderB,o=(e=s.owner)==null?void 0:e.get(W),a=(i=n.owner)==null?void 0:i.get(W);if(o&&a){if(o.collisionType===M.Passive||a.collisionType===M.Passive)return;const h=t.normal,l=h.negate();if(o.collisionType===M.Active&&o.vel.normalize().dot(l)<0){const c=h.scale(h.dot(o.vel.negate()));o.vel=o.vel.add(c)}if(a.collisionType===M.Active&&a.vel.normalize().dot(h)<0){const c=l.scale(l.dot(a.vel.negate()));a.vel=a.vel.add(c)}}}}class Mo{constructor(t,e,i){this.point=t,this.local=e,this.contact=i,this.normalImpulse=0,this.tangentImpulse=0,this.normalMass=0,this.tangentMass=0,this.aToContact=new v(0,0),this.bToContact=new v(0,0),this.originalVelocityAndRestitution=0,this.update()}update(){const t=this.contact.bodyA,e=this.contact.colliderA,i=this.contact.bodyB,s=this.contact.colliderB;if(t&&i){const n=this.contact.normal,o=this.contact.tangent;this.aToContact=this.point.sub(e.center),this.bToContact=this.point.sub(s.center);const a=this.aToContact.cross(n),h=this.bToContact.cross(n);this.normalMass=t.inverseMass+i.inverseMass+t.inverseInertia*a*a+i.inverseInertia*h*h;const l=this.aToContact.cross(o),c=this.bToContact.cross(o);this.tangentMass=t.inverseMass+i.inverseMass+t.inverseInertia*l*l+i.inverseInertia*c*c}return this}getRelativeVelocity(){const t=this.contact.bodyA,e=this.contact.bodyB;if(t&&e){const i=t.vel.add(v.cross(t.angularVelocity,this.aToContact));return e.vel.add(v.cross(e.angularVelocity,this.bToContact)).sub(i)}return v.Zero}}class Fn{constructor(t){this.config=t,this.directionMap=new Map,this.distanceMap=new Map,this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return(e=this.idToContactConstraint.get(t))!=null?e:[]}solve(t){this.preSolve(t),t=t.filter(i=>!i.isCanceled());let e;switch(this.config.contactSolveBias){case oe.HorizontalFirst:{e=en;break}case oe.VerticalFirst:{e=tn;break}default:e=sn}return t.sort((i,s)=>{const n=this.directionMap.get(i.id),o=this.directionMap.get(s.id),a=this.distanceMap.get(i.id),h=this.distanceMap.get(s.id);return e[n]-e[o]||a-h}),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}preSolve(t){var e,i,s,n;for(let h=0;h<t.length;h++){const l=t[h];if(Math.abs(l.mtv.x)<1e-4&&Math.abs(l.mtv.y)<1e-4){l.cancel();continue}const c=d.Side.fromDirection(l.mtv),u=Math.abs(((e=l==null?void 0:l.info)==null?void 0:e.separation)||0);this.distanceMap.set(l.id,u),this.directionMap.set(l.id,c===d.Side.Left||c===d.Side.Right?"horizontal":"vertical"),l.colliderA.events.emit("precollision",new me(l.colliderA,l.colliderB,c,l.mtv,l)),l.colliderA.events.emit("beforecollisionresolve",new Ri(l.colliderA,l.colliderB,c,l.mtv,l)),l.colliderB.events.emit("precollision",new me(l.colliderB,l.colliderA,d.Side.getOpposite(c),l.mtv.negate(),l)),l.colliderB.events.emit("beforecollisionresolve",new Ri(l.colliderB,l.colliderA,d.Side.getOpposite(c),l.mtv.negate(),l)),l.matchAwake()}const a=Array.from(this.idToContactConstraint.keys());for(let h=0;h<t.length;h++){const l=t[h],c=a.indexOf(l.id);c>-1&&a.splice(c,1);const u=(i=this.idToContactConstraint.get(l.id))!=null?i:[];let _=0;const f=l.bodyA,p=l.colliderA,g=l.bodyB,w=l.colliderB;if(f&&g)for(let m=0;m<l.points.length;m++){const b=l.points[m],T=l.normal,C=l.tangent,S=b.sub(p.center),I=b.sub(w.center),y=S.cross(T),k=I.cross(T),U=f.inverseMass+g.inverseMass+f.inverseInertia*y*y+g.inverseInertia*k*k,z=S.cross(C),Y=I.cross(C),ht=f.inverseMass+g.inverseMass+f.inverseInertia*z*z+g.inverseInertia*Y*Y;u[_]&&((n=(s=u[_])==null?void 0:s.point)==null?void 0:n.squareDistance(b))<4?(u[_].point=b,u[_].local=l.localPoints[_]):u[_]=new Mo(b,l.localPoints[_],l),u[_].aToContact=S,u[_].bToContact=I,u[_].normalMass=1/U,u[_].tangentMass=1/ht;const $=f.bounciness>g.bounciness?f.bounciness:g.bounciness,G=l.normal.dot(u[_].getRelativeVelocity());u[_].originalVelocityAndRestitution=0,G<-.1&&(u[_].originalVelocityAndRestitution=-$*G),_++}this.idToContactConstraint.set(l.id,u)}for(const h of a)this.idToContactConstraint.delete(h);if(this.config.warmStart)this.warmStart(t);else for(let h=0;h<t.length;h++){const l=t[h],c=this.getContactConstraints(l.id);for(const u of c)u.normalImpulse=0,u.tangentImpulse=0}}postSolve(t){for(let e=0;e<t.length;e++){const i=t[e],s=i.bodyA,n=i.bodyB;if(s&&n){if(s.collisionType===M.Passive||n.collisionType===M.Passive)continue;s.updateMotion(),n.updateMotion()}const o=d.Side.fromDirection(i.mtv);i.colliderA.events.emit("postcollision",new ve(i.colliderA,i.colliderB,o,i.mtv,i)),i.colliderA.events.emit("aftercollisionresolve",new Mi(i.colliderA,i.colliderB,o,i.mtv,i)),i.colliderB.events.emit("postcollision",new ve(i.colliderB,i.colliderA,d.Side.getOpposite(o),i.mtv.negate(),i)),i.colliderB.events.emit("aftercollisionresolve",new Mi(i.colliderB,i.colliderA,d.Side.getOpposite(o),i.mtv.negate(),i))}this.lastFrameContacts.clear();for(let e=0;e<t.length;e++){const i=t[e];this.lastFrameContacts.set(i.id,i)}}warmStart(t){var e;for(let i=0;i<t.length;i++){const s=t[i],n=s.bodyA,o=s.bodyB;if(n&&o){const a=(e=this.idToContactConstraint.get(s.id))!=null?e:[];for(const h of a)if(this.config.warmStart){const l=s.normal.scale(h.normalImpulse),c=s.tangent.scale(h.tangentImpulse),u=l.add(c);n.applyImpulse(h.point,u.negate()),o.applyImpulse(h.point,u)}else h.normalImpulse=0,h.tangentImpulse=0}}}solvePosition(t){var e;for(let i=0;i<this.config.positionIterations;i++)for(let s=0;s<t.length;s++){const n=t[s],o=n.bodyA,a=n.bodyB;if(o&&a){if(o.collisionType===M.Passive||a.collisionType===M.Passive)continue;const h=(e=this.idToContactConstraint.get(n.id))!=null?e:[];for(const l of h){const c=n.normal,u=Lt.FindContactSeparation(n,l.local),_=this.config.steeringFactor,f=-5,p=this.config.slop,g=F(_*(u+p),f,0),w=c.scale(-g*l.normalMass);if(o.collisionType===M.Active){const m=w.negate().scale(o.inverseMass);o.limitDegreeOfFreedom.includes(he.X)&&(m.x=0),o.limitDegreeOfFreedom.includes(he.Y)&&(m.y=0),o.globalPos=o.globalPos.add(m),o.limitDegreeOfFreedom.includes(he.Rotation)||(o.rotation-=l.aToContact.cross(w)*o.inverseInertia)}if(a.collisionType===M.Active){const m=w.scale(a.inverseMass);a.limitDegreeOfFreedom.includes(he.X)&&(m.x=0),a.limitDegreeOfFreedom.includes(he.Y)&&(m.y=0),a.globalPos=a.globalPos.add(m),a.limitDegreeOfFreedom.includes(he.Rotation)||(a.rotation+=l.bToContact.cross(w)*a.inverseInertia)}}}}}solveVelocity(t){var e;for(let i=0;i<this.config.velocityIterations;i++)for(let s=0;s<t.length;s++){const n=t[s],o=n.bodyA,a=n.bodyB;if(o&&a){if(o.collisionType===M.Passive||a.collisionType===M.Passive)continue;const h=Math.min(o.friction,a.friction),l=(e=this.idToContactConstraint.get(n.id))!=null?e:[];for(const c of l){let f=-c.getRelativeVelocity().dot(n.tangent)*c.tangentMass;const p=h*c.normalImpulse,g=F(c.tangentImpulse+f,-p,p);f=g-c.tangentImpulse,c.tangentImpulse=g;const w=n.tangent.scale(f);o.applyImpulse(c.point,w.negate()),a.applyImpulse(c.point,w)}for(const c of l){const _=c.getRelativeVelocity().dot(n.normal);let f=-c.normalMass*(_-c.originalVelocityAndRestitution);const p=Math.max(c.normalImpulse+f,0);f=p-c.normalImpulse,c.normalImpulse=p;const g=n.normal.scale(f);o.applyImpulse(c.point,g.negate()),a.applyImpulse(c.point,g)}}}}}class ji extends At{constructor(t,e){super(),this.world=t,this.physics=e,this.systemType=Pt.Update,this._physicsConfigDirty=!1,this.query=this.world.query({components:{all:[A,H]},tags:{not:this.physics.config.integration.onScreenOnly?["ex.offscreen"]:[]}}),e.$configUpdate.subscribe(()=>{this._physicsConfigDirty=!0})}update(t){let e,i;const s=this.query.entities,o=this.physics.config.substep;for(let a=0;a<s.length;a++){if(e=s[a].get(A),i=s[a].get(H),i.integration.onScreenOnly&&s[a].hasTag("ex.offscreen"))continue;const h=s[a].get(W);if(this._physicsConfigDirty&&h&&h.updatePhysicsConfig(this.physics.config.bodies),h!=null&&h.isSleeping)continue;const l=i.acc.clone();(h==null?void 0:h.collisionType)===M.Active&&(h!=null&&h.useGravity)&&l.addEqual(this.physics.config.gravity),s[a].parent||this.captureOldTransformWithChildren(s[a]),$r.integrate(e,i,l,t/o)}this._physicsConfigDirty&&(this._physicsConfigDirty=!1,this.query=this.world.query({components:{all:[A,H]},tags:{not:this.physics.config.integration.onScreenOnly?["ex.offscreen"]:[]}}))}captureOldTransformWithChildren(t){var e;(e=t.get(W))==null||e.captureOldTransform();for(let i=0;i<t.children.length;i++)this.captureOldTransformWithChildren(t.children[i])}}ji.priority=Nt.Higher;class Zi extends At{constructor(t,e){super(),this._physics=e,this.systemType=Pt.Update,this._configDirty=!1,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._arcadeSolver=new Dn(e.config.arcade),this._realisticSolver=new Fn(e.config.realistic),this._physics.$configUpdate.subscribe(()=>this._configDirty=!0),this._trackCollider=i=>this._processor.track(i),this._untrackCollider=i=>this._processor.untrack(i),this.query=t.query([A,tt]),this.query.entityAdded$.subscribe(i=>{const s=i.get(tt);s.$colliderAdded.subscribe(this._trackCollider),s.$colliderRemoved.subscribe(this._untrackCollider);const n=s.get();n&&this._processor.track(n)}),this.query.entityRemoved$.subscribe(i=>{const s=i.get(tt),n=s.get();s&&n&&this._processor.untrack(n)}),this._motionSystem=t.get(ji)}get _processor(){return this._physics.collisionProcessor}initialize(t,e){this._engine=e.engine}update(t){var e,i,s,n;if(!this._physics.config.enabled)return;let o=[];for(let u=0;u<this.query.entities.length;u++){const f=this.query.entities[u].get(tt),p=f==null?void 0:f.get();if(f&&((e=f.owner)!=null&&e.isActive)&&p)if(f.update(),p instanceof at){const g=p.getColliders();p.compositeStrategy||(p.compositeStrategy=this._physics.config.colliders.compositeStrategy),o=o.concat(g)}else o.push(p)}this._processor.update(o,t);let a=this._processor.broadphase(o,t);this._currentFrameContacts.clear();let h=[];const l=this.getSolver(),c=this._physics.config.substep;for(let u=0;u<c;u++)if(u>0&&this._motionSystem.update(t),h.length&&(a=h.map(_=>new pt(_.colliderA,_.colliderB))),a.length){h=this._processor.narrowphase(a,(n=(s=(i=this._engine)==null?void 0:i.debug)==null?void 0:s.stats)==null?void 0:n.currFrame),h=l.solve(h);for(const _ of h){if(_.isCanceled())continue;const f=_.id.indexOf("|");if(f>0){const p=_.id.substring(f+1);this._currentFrameContacts.set(p,_)}else this._currentFrameContacts.set(_.id,_)}}this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts);for(const u of this.query.entities){const _=u.get(tt);_&&_.processColliderRemoval()}}postupdate(){He.SeparationPool.done()}getSolver(){return this._configDirty&&(this._configDirty=!1,this._arcadeSolver=new Dn(this._physics.config.arcade),this._realisticSolver=new Fn(this._physics.config.realistic)),this._physics.config.solver===ki.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t,0)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const i=e.colliderA,s=e.colliderB,n=d.Side.fromDirection(e.mtv),o=d.Side.getOpposite(n);i.events.emit("collisionstart",new ii(i,s,n,e)),i.events.emit("contactstart",new Ei(i,s,n,e)),s.events.emit("collisionstart",new ii(s,i,o,e)),s.events.emit("contactstart",new Ei(s,i,o,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const i=e.colliderA,s=e.colliderB,n=d.Side.fromDirection(e.mtv),o=d.Side.getOpposite(n);i.events.emit("collisionend",new si(i,s,n,e)),i.events.emit("contactend",new Ii(i,s,n,e)),s.events.emit("collisionend",new si(s,i,o,e)),s.events.emit("contactend",new Ii(s,i,o,e))}}}Zi.priority=Nt.Higher;class Do{constructor(t){this.$configUpdate=new gt,this._configDirty=!1,this.config=t,this.$configUpdate.subscribe(e=>{this._configDirty=!0,W.updateDefaultPhysicsConfig(e.bodies)}),this._config.spatialPartition===oi.SparseHashGrid?this._collisionProcessor=new Mn(this._config.sparseHashGrid):this._collisionProcessor=new Li(this._config)}get config(){return Dh(this._config,t=>{this.$configUpdate.notifyAll(t)})}set config(t){this._config=t,this.$configUpdate.notifyAll(t)}get collisionProcessor(){if(this._configDirty){this._configDirty=!1;const t=this._collisionProcessor.getColliders();this._config.spatialPartition===oi.SparseHashGrid?this._collisionProcessor=new Mn(this._config.sparseHashGrid):this._collisionProcessor=new Li(this._config);for(const e of t)this._collisionProcessor.track(e)}return this._collisionProcessor}rayCast(t,e){return this.collisionProcessor.rayCast(t,e)}query(t){return this._collisionProcessor.query(t)}}var fi=(r=>(r.Fixed="Fixed",r.FitContainerAndFill="FitContainerAndFill",r.FitScreenAndFill="FitScreenAndFill",r.FitContainerAndZoom="FitContainerAndZoom",r.FitScreenAndZoom="FitScreenAndZoom",r.FitScreen="FitScreen",r.FillScreen="FillScreen",r.FitContainer="FitContainer",r.FillContainer="FillContainer",r))(fi||{});class Bn{static get SVGA(){return{width:800,height:600}}static get Standard(){return{width:1920,height:1080}}static get Atari2600(){return{width:160,height:192}}static get GameBoy(){return{width:160,height:144}}static get GameBoyAdvance(){return{width:240,height:160}}static get NintendoDS(){return{width:256,height:192}}static get NES(){return{width:256,height:224}}static get SNES(){return{width:256,height:244}}}const Sl={ScreenResize:"resize",PixelRatioChange:"pixelratio",FullScreenChange:"fullscreen"};class Ln{constructor(t){this.events=new X,this._antialiasing=!0,this._canvasImageRendering="auto",this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullscreen=!1,this._isDisposed=!1,this._logger=R.getInstance(),this._fullscreenChangeHandler=()=>{this._isDisposed||(this._isFullscreen=!this._isFullscreen,this._logger.debug("Fullscreen Change",this._isFullscreen),this.events.emit("fullscreen",{fullscreen:this.isFullscreen}))},this._pixelRatioChangeHandler=()=>{this._isDisposed||(this._logger.debug("Pixel Ratio Change",window.devicePixelRatio),this._listenForPixelRatio(),this._devicePixelRatio=this._calculateDevicePixelRatio(),this.applyResolutionAndViewport(),this.events.emit("pixelratio",{pixelRatio:this.pixelRatio}))},this._resizeHandler=()=>{if(this._isDisposed)return;const o=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(o),this.applyResolutionAndViewport(),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._contentArea=new D,this._unsafeArea=new D;var e,i,s,n;this.viewport=t.viewport,this.resolution=(e=t.resolution)!=null?e:{...this.viewport},this._contentResolution=this.resolution,this._displayMode=(i=t.displayMode)!=null?i:"Fixed",this._canvas=t.canvas,this.graphicsContext=t.context,this._antialiasing=(s=t.antialiasing)!=null?s:this._antialiasing,this._canvasImageRendering=(n=t.canvasImageRendering)!=null?n:this._canvasImageRendering,this._browser=t.browser,this._pixelRatioOverride=t.pixelRatio,this._applyDisplayMode(),this._listenForPixelRatio(),this._canvas.addEventListener("fullscreenchange",this._fullscreenChangeHandler),this.applyResolutionAndViewport()}_listenForPixelRatio(){this._mediaQueryList&&!this._mediaQueryList.addEventListener&&this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._mediaQueryList=this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._mediaQueryList.addEventListener?this._mediaQueryList.addEventListener("change",this._pixelRatioChangeHandler,{once:!0}):this._mediaQueryList.addListener(this._pixelRatioChangeHandler)}dispose(){this._isDisposed||(this._isDisposed=!0,this.events.clear(),this._browser.window.off("resize",this._resizeHandler),this._browser.window.clear(),this._resizeObserver&&this._resizeObserver.disconnect(),this.parent.removeEventListener("resize",this._resizeHandler),this._mediaQueryList.removeEventListener?this._mediaQueryList.removeEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._canvas.removeEventListener("fullscreenchange",this._fullscreenChangeHandler),this._canvas=null)}_calculateDevicePixelRatio(){return window.devicePixelRatio<1?1:window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get worldToPagePixelRatio(){if(this._canvas){const t=this.worldToPageCoordinates(v.Zero);return this.worldToPageCoordinates(x(1,0)).sub(t).x}else return 1}get pixelRatioOverride(){return this._pixelRatioOverride}set pixelRatioOverride(t){this._pixelRatioOverride=t}get isHiDpi(){return this.pixelRatio!==1}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){switch(this.displayMode){case"FillContainer":case"FitContainer":case"FitContainerAndFill":case"FitContainerAndZoom":return this.canvas.parentElement||document.body;default:return window}}get resolution(){return this._resolution}set resolution(t){this._resolution=t}get viewport(){return this._viewport?this._viewport:this._resolution}set viewport(t){this._viewport=t}get aspectRatio(){return this._resolution.width/this._resolution.height}get scaledWidth(){return this._resolution.width*this.pixelRatio}get scaledHeight(){return this._resolution.height*this.pixelRatio}setCurrentCamera(t){this._camera=t}pushResolutionAndViewport(){this._resolutionStack.push(this.resolution),this._viewportStack.push(this.viewport),this.resolution={...this.resolution},this.viewport={...this.viewport}}peekViewport(){return this._viewportStack[this._viewportStack.length-1]}peekResolution(){return this._resolutionStack[this._resolutionStack.length-1]}popResolutionAndViewport(){this._resolutionStack.length&&this._viewportStack.length&&(this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop())}applyResolutionAndViewport(){if(this.graphicsContext instanceof Xt&&!this.graphicsContext.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})&&(this._logger.warnOnce(`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) and pixel ratio (${this.pixelRatio}) are too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly. Try reducing the resolution or disabling Hi DPI scaling to avoid this (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`),!this.pixelRatioOverride)){let s=Math.max(1,this.pixelRatio-.5),n=!1;for(;s>1&&!n;){s=Math.max(1,s-.5);const o=this._resolution.width*s,a=this._resolution.height*s;n=this.graphicsContext.checkIfResolutionSupported({width:o,height:a})}this.pixelRatioOverride=s,this._logger.warnOnce(`Scaled resolution too big attempted recovery! Pixel ratio was automatically reduced to (${this.pixelRatio}) to avoid 4k texture limit. Setting \`ex.Engine({pixelRatio: ...}) will override any automatic recalculation, do so at your own risk.\` (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`)}this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this._canvasImageRendering==="auto"?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",this._canvas.style.imageRendering===""&&(this._canvas.style.imageRendering="crisp-edges"));const t=this.viewport.widthUnit==="percent"?"%":"px",e=this.viewport.heightUnit==="percent"?"%":"px";this._canvas.style.width=this.viewport.width+t,this._canvas.style.height=this.viewport.height+e,this.graphicsContext.updateViewport(this.resolution),this.graphicsContext.resetTransform(),this.graphicsContext.smoothing=this._antialiasing,this.graphicsContext instanceof Xi&&this.graphicsContext.scale(this.pixelRatio,this.pixelRatio),document.documentElement.style.setProperty("--ex-pixel-ratio",this.worldToPagePixelRatio.toString())}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this.graphicsContext.smoothing=this._antialiasing}get isFullScreen(){return this._isFullscreen}get isFullscreen(){return this._isFullscreen}goFullScreen(t){return this.enterFullscreen(t)}enterFullscreen(t){var e,i,s,n,o,a;if(t){const h=document.getElementById(t);if(h!=null&&h.requestFullscreen||h!=null&&h.webkitRequestFullscreen){if(h.getAttribute("ex-fullscreen-listener")||(h.setAttribute("ex-fullscreen-listener","true"),h.addEventListener("fullscreenchange",this._fullscreenChangeHandler)),h.requestFullscreen)return(e=h.requestFullscreen())!=null?e:Promise.resolve();if(h.webkitRequestFullscreen)return(i=h.webkitRequestFullscreen())!=null?i:Promise.resolve()}}return(s=this._canvas)!=null&&s.requestFullscreen?(o=(n=this._canvas)==null?void 0:n.requestFullscreen())!=null?o:Promise.resolve():this._canvas.webkitRequestFullscreen?(a=this._canvas.webkitRequestFullscreen())!=null?a:Promise.resolve():(this._logger.warnOnce("Could not go fullscreen, is this an iPhone? Currently Apple does not support fullscreen on iPhones"),Promise.resolve())}exitFullScreen(){return this.exitFullscreen()}exitFullscreen(){return document.exitFullscreen()}_viewportToPixels(t){return{width:t.widthUnit==="percent"?this.canvas.offsetWidth:t.width,height:t.heightUnit==="percent"?this.canvas.offsetHeight:t.height}}pageToScreenCoordinates(t){let e=t.x,i=t.y;this._isFullscreen||(e-=ni(this._canvas).x,i-=ni(this._canvas).y);const s=this._viewportToPixels(this.viewport);if(this._isFullscreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const n=window.innerWidth/this.aspectRatio,o=(window.innerHeight-n)/2;i=(i-o)/n*s.height,e=e/window.innerWidth*s.width}else{const n=window.innerHeight*this.aspectRatio,o=(window.innerWidth-n)/2;e=(e-o)/n*s.width,i=i/window.innerHeight*s.height}return e=e/s.width*this.resolution.width,i=i/s.height*this.resolution.height,e=e-this.contentArea.left,i=i-this.contentArea.top,new v(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;const s=this._viewportToPixels(this.viewport);if(e=e/this.resolution.width*s.width,i=i/this.resolution.height*s.height,this._isFullscreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const n=window.innerWidth/this.aspectRatio,o=(window.innerHeight-n)/2;i=i/s.height*n+o,e=e/s.width*window.innerWidth}else{const n=window.innerHeight*this.aspectRatio,o=(window.innerWidth-n)/2;e=e/s.width*n+o,i=i/s.height*window.innerHeight}return this._isFullscreen||(e+=ni(this._canvas).x,i+=ni(this._canvas).y),new v(e,i)}screenToWorldCoordinates(t){return t=t.add(x(this.contentArea.left,this.contentArea.top)),this._camera?this._camera.inverse.multiply(t):t.sub(x(this.resolution.width/2,this.resolution.height/2))}worldToScreenCoordinates(t){return this._camera?this._camera.transform.multiply(t):t.add(x(this.resolution.width/2,this.resolution.height/2))}pageToWorldCoordinates(t){const e=this.pageToScreenCoordinates(t);return this.screenToWorldCoordinates(e)}worldToPageCoordinates(t){const e=this.worldToScreenCoordinates(t);return this.screenToPageCoordinates(e)}getWorldBounds(){return D.fromDimension(this.resolution.width,this.resolution.height,v.Half).scale(x(1/this._camera.zoom,1/this._camera.zoom)).rotate(this._camera.rotation).translate(this._camera.drawPos)}getScreenBounds(){return D.fromDimension(this.resolution.width,this.resolution.height,v.Zero,v.Zero)}get canvasWidth(){return this.canvas.width}get halfCanvasWidth(){return this.canvas.width/2}get canvasHeight(){return this.canvas.height}get halfCanvasHeight(){return this.canvas.height/2}get drawWidth(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get width(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get halfDrawWidth(){return this.drawWidth/2}get drawHeight(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get height(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return x(this.halfDrawWidth,this.halfDrawHeight)}get contentArea(){return this._contentArea}get unsafeArea(){return this._unsafeArea}_computeFit(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.aspectRatio;let e=0,i=0;window.innerWidth/t<window.innerHeight?(e=window.innerWidth,i=window.innerWidth/t):(e=window.innerHeight*t,i=window.innerHeight),this.viewport={width:e,height:i},this._contentArea=D.fromDimension(this.resolution.width,this.resolution.height,v.Zero),this._unsafeArea=D.fromDimension(this.resolution.width,this.resolution.height,v.Zero),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitScreenAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndFill(t,e),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitContainerAndFill(){this.canvas.style.width="100%",this.canvas.style.height="100%",this._computeFitAndFill(this.canvas.offsetWidth,this.canvas.offsetHeight,{width:100,widthUnit:"percent",height:100,heightUnit:"percent"}),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitAndFill(t,e,i){if(this.viewport=i!=null?i:{width:t,height:e},t/e<=this._contentResolution.width/this._contentResolution.height){this.resolution={width:t*this._contentResolution.width/t,height:t*this._contentResolution.width/t*e/t};const s=(this.resolution.height-this._contentResolution.height)/2;this._contentArea=new D({top:s,left:0,right:this._contentResolution.width,bottom:this.resolution.height-s}),this._unsafeArea=new D({top:-s,left:0,right:this._contentResolution.width,bottom:this.resolution.height+s})}else{this.resolution={width:e*this._contentResolution.height/e*t/e,height:e*this._contentResolution.height/e};const s=(this.resolution.width-this._contentResolution.width)/2;this._contentArea=new D({top:0,left:s,right:this.resolution.width-s,bottom:this._contentResolution.height}),this._unsafeArea=new D({top:0,left:-s,right:this.resolution.width+s,bottom:this._contentResolution.height})}}_computeFitScreenAndZoom(){document.body.style.margin="0px",document.body.style.overflow="hidden",this.canvas.style.position="absolute";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndZoom(t,e),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitContainerAndZoom(){this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.position="relative";const t=this.canvas.parentElement;t.style.overflow="hidden";const{offsetWidth:e,offsetHeight:i}=this.canvas;this._computeFitAndZoom(e,i),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitAndZoom(t,e){const i=this.aspectRatio;let s=0,n=0;t/i<e?(s=t,n=t/i):(s=e*i,n=e);const o=t/s,a=e/n,h=Math.max(o,a),l=s*h,c=n*h;l>t?this.canvas.style.left=-(l-t)/2+"px":this.canvas.style.left="",c>e?this.canvas.style.top=-(c-e)/2+"px":this.canvas.style.top="",this.viewport={width:l,height:c};const u=D.fromDimension(this.viewport.width,this.viewport.height,v.Zero);if(this.viewport.width>t){const _=(this.viewport.width-t)/this.viewport.width*this.resolution.width;u.top=0,u.left=_/2,u.right=this.resolution.width-_/2,u.bottom=this.resolution.height}if(this.viewport.height>e){const _=(this.viewport.height-e)/this.viewport.height*this.resolution.height;u.top=_/2,u.left=0,u.bottom=this.resolution.height-_/2,u.right=this.resolution.width}this._contentArea=u}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0,s="pixel",n="pixel";const o=this.canvas.parentElement;o.clientWidth/t<o.clientHeight?(this.canvas.style.width="100%",e=100,s="percent",i=this.canvas.offsetWidth/t):(this.canvas.style.height="100%",i=100,n="percent",e=this.canvas.offsetHeight*t),this.viewport={width:e,widthUnit:s,height:i,heightUnit:n},this._contentArea=D.fromDimension(this.resolution.width,this.resolution.height,v.Zero),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_applyDisplayMode(){this._setResolutionAndViewportByDisplayMode(this.parent),this.parent instanceof Window?this._browser.window.on("resize",this._resizeHandler):(this._resizeObserver=new ResizeObserver(()=>{this._resizeHandler()}),this._resizeObserver.observe(this.parent)),this.parent.addEventListener("resize",this._resizeHandler)}_setResolutionAndViewportByDisplayMode(t){this.displayMode==="FillContainer"&&(this.canvas.style.width="100%",this.canvas.style.height="100%",this.viewport={width:100,widthUnit:"percent",height:100,heightUnit:"percent"},this.resolution={width:this.canvas.offsetWidth,height:this.canvas.offsetHeight}),this.displayMode==="FillScreen"&&(document.body.style.margin="0px",document.body.style.overflow="hidden",this.resolution={width:t.innerWidth,height:t.innerHeight},this.viewport=this.resolution),this._contentArea=D.fromDimension(this.resolution.width,this.resolution.height,v.Zero),this.displayMode==="FitScreen"&&this._computeFit(),this.displayMode==="FitContainer"&&this._computeFitContainer(),this.displayMode==="FitScreenAndFill"&&this._computeFitScreenAndFill(),this.displayMode==="FitContainerAndFill"&&this._computeFitContainerAndFill(),this.displayMode==="FitScreenAndZoom"&&this._computeFitScreenAndZoom(),this.displayMode==="FitContainerAndZoom"&&this._computeFitContainerAndZoom()}}class gi{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}}function Tl(r){return!!r.playbackState}const Fo=class us{static unlock(){return new Promise((e,i)=>{if(us._UNLOCKED||!gi.create())return e(!0);const s=setTimeout(()=>{R.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),e(!1)},200),n=gi.create();n.resume().then(()=>{const o=n.createBuffer(1,1,22050),a=n.createBufferSource();let h=!1;a.buffer=o,a.connect(n.destination),a.onended=()=>h=!0,a.start(0),setTimeout(()=>{Tl(a)?(a.playbackState===a.PLAYING_STATE||a.playbackState===a.FINISHED_STATE)&&(us._UNLOCKED=!0):(n.currentTime>0||h)&&(us._UNLOCKED=!0)},0),clearTimeout(s),e(!0)},()=>{i()})})}static isUnlocked(){return this._UNLOCKED}};Fo._UNLOCKED=!1;let Bo=Fo;class kn{}kn.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class Qi{constructor(){this.states=new Map}get currentState(){return this._currentState}set currentState(t){this._currentState=t}static create(t,e){const i=new Qi;i.data=e;for(const s in t.states)i.states.set(s,{name:s,...t.states[s]});for(const s of i.states.values())for(const n of s.transitions)if(n!=="*"&&!i.states.has(n))throw Error(`Invalid state machine, state [${s.name}] has a transition to another state that doesn't exist [${n}]`);return i.currentState=i.startState=i.states.get(t.start),i}in(t){return this.currentState.name===t}go(t,e){var i,s;if(this.currentState.transitions.includes(t)||this.currentState.transitions.includes("*")){const n=this.states.get(t);return this.currentState.onExit&&((i=this.currentState)==null?void 0:i.onExit({to:n.name,data:this.data}))===!1||n!=null&&n.onEnter&&(n==null?void 0:n.onEnter({from:this.currentState.name,eventData:e,data:this.data}))===!1?!1:(this.currentState=n,(s=this.currentState)!=null&&s.onState&&this.currentState.onState(),!0)}return!1}update(t){this.currentState.onUpdate&&this.currentState.onUpdate(this.data,t)}save(t){localStorage.setItem(t,JSON.stringify({currentState:this.currentState.name,data:this.data}))}restore(t){const e=JSON.parse(localStorage.getItem(t));this.currentState=this.states.get(e.currentState),this.data=e.data}}class Lo{constructor(t){this._src=t,this._audioContext=gi.create(),this._volumeNode=this._audioContext.createGain(),this._playingFuture=new wt,this._stateMachine=Qi.create({start:"STOPPED",states:{PLAYING:{onEnter:({data:e})=>{this._createNewBufferSource(),this._handleEnd(),this.loop?this._instance.start(0,e.pausedAt*this._playbackRate):this._instance.start(0,e.pausedAt*this._playbackRate,this.duration),e.startedAt=this._audioContext.currentTime-e.pausedAt,e.pausedAt=0},onState:()=>this._playStarted(),onExit:({to:e})=>{e==="STOPPED"&&this._playingFuture.resolve(!0),this._instance.onended=null,this._instance.disconnect(),this._instance.stop(0),this._instance=null},transitions:["STOPPED","PAUSED","SEEK"]},SEEK:{onEnter:({eventData:e,data:i})=>{i.pausedAt=(e!=null?e:0)/this._playbackRate,i.startedAt=0},transitions:["*"]},STOPPED:{onEnter:({data:e})=>{e.pausedAt=0,e.startedAt=0,this._playingFuture.resolve(!0)},transitions:["PLAYING","PAUSED","SEEK"]},PAUSED:{onEnter:({data:e})=>{e.pausedAt=this._audioContext.currentTime-e.startedAt},transitions:["PLAYING","STOPPED","SEEK"]}}},{startedAt:0,pausedAt:0}),this._volume=1,this._loop=!1,this._playStarted=()=>{},this._playbackRate=1,this._createNewBufferSource()}_createNewBufferSource(){this._instance=this._audioContext.createBufferSource(),this._instance.buffer=this._src,this._instance.loop=this.loop,this._instance.playbackRate.value=this._playbackRate,this._instance.connect(this._volumeNode),this._volumeNode.connect(this._audioContext.destination)}_handleEnd(){this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)})}set loop(t){this._loop=t,this._instance&&(this._instance.loop=t,this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)}))}get loop(){return this._loop}set volume(t){t=F(t,0,1),this._volume=t,this._stateMachine.in("PLAYING")&&this._volumeNode.gain.setTargetAtTime?this._volumeNode.gain.setTargetAtTime(t,this._audioContext.currentTime,.1):this._volumeNode.gain.value=t}get volume(){return this._volume}get duration(){var t;return(t=this._duration)!=null?t:this.getTotalPlaybackDuration()}set duration(t){this._duration=t}isPlaying(){return this._stateMachine.in("PLAYING")}isPaused(){return this._stateMachine.in("PAUSED")||this._stateMachine.in("SEEK")}isStopped(){return this._stateMachine.in("STOPPED")}play(t=()=>{}){return this._playStarted=t,this._stateMachine.go("PLAYING"),this._playingFuture.promise}pause(){this._stateMachine.go("PAUSED")}stop(){this._stateMachine.go("STOPPED")}seek(t){this._stateMachine.go("PAUSED"),this._stateMachine.go("SEEK",t)}getTotalPlaybackDuration(){return this._src.duration}getPlaybackPosition(){const{pausedAt:t,startedAt:e}=this._stateMachine.data;return t?t*this._playbackRate:e?(this._audioContext.currentTime-e)*this._playbackRate:0}set playbackRate(t){this._instance.playbackRate.value=this._playbackRate=t}get playbackRate(){return this._instance.playbackRate.value}}class Un extends L{constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}stopPropagation(){}action(){}propagate(){}layPath(t){}}class Te extends Un{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class ko extends Un{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}function Pl(r){try{const t=new Audio,e=/.*\.([A-Za-z0-9]+)(?:(?:\?|\#).*)*$/,i=r.match(e)[1];return!!t.canPlayType("audio/"+i)}catch(t){return R.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}const Al={VolumeChange:"volumechange",Processed:"processed",Pause:"pause",Stop:"stop",PlaybackEnd:"playbackend",Resume:"resume",PlaybackStart:"playbackstart"};function El(r){var t;return!!((t=r[0])!=null&&t.paths)}class zn{constructor(...t){this.events=new X,this.logger=R.getInstance(),this._loop=!1,this._volume=1,this._isStopped=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._playbackRate=1,this._audioContext=gi.create();let e;El(t)?e=t[0]:e={paths:t},this._resource=new ai("",kn.type.arraybuffer);const{volume:i,position:s,playbackRate:n,loop:o,bustCache:a,duration:h}=e;this.volume=i!=null?i:this.volume,this.playbackRate=n!=null?n:this.playbackRate,this.loop=o!=null?o:this.loop,this.duration=h!=null?h:this.duration,this.bustCache=a!=null?a:this.bustCache,this.position=s!=null?s:this.position;for(const l of e.paths)if(Pl(l)){this.path=l;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",e.paths.join(", ")),this.logger.warn("Attempting to use",e.paths[0]),this.path=e.paths[0])}set loop(t){this._loop=t;for(const e of this._tracks)e.loop=this._loop;this.logger.debug("Set loop for all instances of sound",this.path,"to",this._loop)}get loop(){return this._loop}set volume(t){this._volume=t;for(const e of this._tracks)e.volume=this._volume;this.events.emit("volumechange",new Te(this)),this.logger.debug("Set loop for all instances of sound",this.path,"to",this._volume)}get volume(){return this._volume}get duration(){return this._duration}set duration(t){this._duration=t}get instances(){return this._tracks}get path(){return this._resource.path}set path(t){this._resource.path=t}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}isLoaded(){return!!this.data}async load(){var t,e;if(this.data)return this.data;const i=await this._resource.load(),s=await this.decodeAudio(i.slice(0));return this._duration=(e=(t=this._duration)!=null?t:s==null?void 0:s.duration)!=null?e:void 0,this.events.emit("processed",new ko(this,s)),this.data=s}async decodeAudio(t){try{return await this._audioContext.decodeAudioData(t.slice(0))}catch(e){return this.logger.error("Unable to decode this browser may not fully support this format, or the file may be corrupt, if this is an mp3 try removing id3 tags and album art from the file."),await Promise.reject()}}wireEngine(t){t&&(this._engine=t,this._engine.on("hidden",()=>{t.pauseAudioWhenHidden&&this.isPlaying()&&(this._wasPlayingOnHidden=!0,this.pause())}),this._engine.on("visible",()=>{t.pauseAudioWhenHidden&&this._wasPlayingOnHidden&&(this.play(),this._wasPlayingOnHidden=!1)}),this._engine.on("start",()=>{this._isStopped=!1}),this._engine.on("stop",()=>{this.stop(),this._isStopped=!0}))}instanceCount(){return this._tracks.length}isPlaying(){return this._tracks.some(t=>t.isPlaying())}isPaused(){return this._tracks.some(t=>t.isPaused())}isStopped(){return this._tracks.some(t=>t.isStopped())}play(t){return this.isLoaded()?this._isStopped?(this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1)):(this.volume=t!=null?t:this.volume,this.isPaused()?this._resumePlayback():(this.position&&this.seek(this.position),this._startPlayback())):(this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this.events.emit("pause",new Te(this)),this.logger.debug("Paused all instances of sound",this.path)}}stop(){for(const t of this._tracks)t.stop();this.events.emit("stop",new Te(this)),this._tracks.length=0,this.logger.debug("Stopped all instances of sound",this.path)}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._tracks.forEach(e=>{e.playbackRate=this._playbackRate})}seek(t,e=0){this._tracks.length===0&&this._getTrackInstance(this.data),this._tracks[e].seek(t)}getTotalPlaybackDuration(){return this.isLoaded()?this.data.duration:(this.logger.warnOnce(`Sound from ${this.path} is not loaded, cannot return total playback duration.Did you forget to add Sound to a loader? https://excaliburjs.com/docs/loaders/`),0)}getPlaybackPosition(t=0){return this._tracks.length?this._tracks[t].getPlaybackPosition():0}getTrackId(t){return this._tracks.indexOf(t)}async _resumePlayback(){if(this.isPaused()){const t=[];for(const e of this._tracks)t.push(e.play().then(()=>(this._tracks.splice(this.getTrackId(e),1),!0)));this.events.emit("resume",new Te(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),await Promise.all(t)}return!0}async _startPlayback(){const t=this._getTrackInstance(this.data),e=await t.play(()=>{this.events.emit("playbackstart",new Te(this,t)),this.logger.debug("Playing new instance for sound",this.path)});this.events.emit("playbackend",new Te(this,t));const i=this.getTrackId(t);return i!==-1&&this._tracks.splice(i,1),e}_getTrackInstance(t){var e;const i=new Lo(t);return i.loop=this.loop,i.volume=this.volume,i.duration=(e=this.duration)!=null?e:0,i.playbackRate=this._playbackRate,this._tracks.push(i),i}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Il={BeforeLoad:"beforeload",AfterLoad:"afterload",UserAction:"useraction",LoadResourceStart:"loadresourcestart",LoadResourceEnd:"loadresourceend"};function On(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class pi{constructor(t){this.events=new X,this.canvas=new qi({filtering:mt.Blended,smoothing:!0,cache:!1,draw:this.onDraw.bind(this)}),this._resources=[],this._numLoaded=0,this._loaded=!1,this._isLoading=!1,this._totalTimeMs=0,this._resourcesLoadedFuture=new wt,this._loaderCompleteFuture=new wt;var e;t&&((e=t.loadables)!=null&&e.length)&&this.addResources(t.loadables)}get resources(){return this._resources}onInitialize(t){this.engine=t,this.canvas.width=this.engine.screen.resolution.width,this.canvas.height=this.engine.screen.resolution.height}async onUserAction(){return await Promise.resolve()}async onBeforeLoad(){}async onAfterLoad(){await Di(500,this.engine.clock)}addResource(t){this._resources.push(t),this._loaded=!1}addResources(t){let e=0;const i=t.length;for(e;e<i;e++)this.addResource(t[e]);this._loaded=!1}markResourceComplete(){this._numLoaded++}get progress(){const t=this._resources.length;return t>0?F(this._numLoaded,0,t)/t:1}isLoaded(){return this._loaded||this._resources.length===0}onUpdate(t,e){this._totalTimeMs+=e}onDraw(t){const e=this._totalTimeMs/1e3;t.fillStyle=P.Black.toRGBA(),t.fillRect(0,0,this.engine.screen.resolution.width,this.engine.screen.resolution.height),t.save(),t.translate(this.engine.screen.resolution.width/2,this.engine.screen.resolution.height/2);const i=e*10;t.strokeStyle="white",t.lineWidth=10,t.lineCap="round",t.arc(0,0,40,i,i+Math.PI*3/2),t.stroke(),t.fillStyle="white",t.font="16px sans-serif";const s=(this.progress*100).toFixed(0)+"%",n=t.measureText(s),o=Math.abs(n.actualBoundingBoxLeft)+Math.abs(n.actualBoundingBoxRight),a=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);t.fillText(s,-o/2,a/2),t.restore()}areResourcesLoaded(){return this._resources.length===0?Promise.resolve():this._resourcesLoadedFuture.promise}async load(){if(this._isLoading)return this._loaderCompleteFuture.promise;if(this.isLoaded())return this.data=this._resources;this._isLoading=!0,this._loaderCompleteFuture=new wt,await this.onBeforeLoad(),this.events.emit("beforeload"),this.canvas.flagDirty(),await Promise.all(this._resources.filter(t=>!t.isLoaded()).map(async t=>{this.events.emit("loadresourcestart",t),await t.load().finally(()=>{this._numLoaded++,this.canvas.flagDirty(),this.events.emit("loadresourceend",t)})}));for(const t of this._resources)t instanceof zn&&t.wireEngine(this.engine);return this._resourcesLoadedFuture.resolve(),this.canvas.flagDirty(),await this.onUserAction(),this.events.emit("useraction"),await Bo.unlock(),await this.onAfterLoad(),this.events.emit("afterload"),this._isLoading=!1,this._loaded=!0,this._loaderCompleteFuture.resolve(this._resources),this.data=this._resources}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Rl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=",Ml='button#excalibur-play{display:inline-block;position:relative;z-index:999;border-radius:6px;border:none;padding:1rem 1.5rem 1rem 4rem;margin:0;text-decoration:none;background:#00b233;color:#fff;font-family:sans-serif;font-size:2rem;white-space:nowrap;line-height:1;cursor:pointer;text-align:center;transition:background .25s ease-in-out,transform .15s ease;-webkit-appearance:none;-moz-appearance:none;-webkit-animation:excalibur-button-fadein .2s;-moz-animation:excalibur-button-fadein .2s;-ms-animation:excalibur-button-fadein .2s;-o-animation:excalibur-button-fadein .2s;animation:excalibur-button-fadein .2s}button#excalibur-play:after{position:absolute;content:"";border:8px solid;border-color:transparent transparent transparent white;left:35px;top:24px;width:0;height:0}button#excalibur-play:before{position:absolute;content:"";border:3px solid;left:19px;top:14px;border-radius:20px;width:30px;height:30px}button#excalibur-play:hover,button#excalibur-play:focus{background:#00982c}button#excalibur-play:focus{outline:1px solid #fff;outline-offset:-4px}button#excalibur-play:active{transform:scale(.99)}@keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-moz-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-webkit-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-ms-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-o-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}',Uo=class Ua extends pi{constructor(t){const e=Array.isArray(t)?{loadables:t}:t;super(e),this._logger=R.getInstance(),this._originalOptions={loadables:[]},this.events=new X,this._playButtonShown=!1,this.logo=Rl,this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=P.White,this.backgroundColor="#176BAA",this._imageLoaded=new wt,this.suppressPlayButton=!1,this._playButtonStyles=Ml,this.playButtonText="Play game",this.startButtonFactory=()=>{let i=document.getElementById("excalibur-play");return i||(i=document.createElement("button")),i.id="excalibur-play",i.textContent=this.playButtonText,i.style.display="none",i},this._originalOptions={...Ua._DEFAULT_LOADER_OPTIONS,...e}}get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.onload=()=>this._imageLoaded.resolve(),this._imageElement.src=this.logo),this._imageElement}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");return t&&(this._playButtonRootElement=t),this._playButtonRootElement||(this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute",document.body.appendChild(this._playButtonRootElement)),this._styleBlock||(this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._playButtonStyles,document.head.appendChild(this._styleBlock)),this._playButtonElement||(this._playButtonElement=this.startButtonFactory(),this._playButtonRootElement.appendChild(this._playButtonElement)),this._playButtonElement}onInitialize(t){this.engine=t,this.screen=t.screen,this.canvas.width=this.engine.canvas.width,this.canvas.height=this.engine.canvas.height,this.screen.events.on("resize",()=>{this.canvas.width=this.engine.canvas.width,this.canvas.height=this.engine.canvas.height})}async showPlayButton(){var t,e;if(this.suppressPlayButton)this.hidePlayButton(),await Di(500,(t=this.engine)==null?void 0:t.clock);else{const i=()=>{try{this._positionPlayButton()}catch(n){}};return(e=this.engine)!=null&&e.browser&&this.engine.browser.window.on("resize",i),this._playButtonShown=!0,this._playButton.style.display="block",document.body.addEventListener("keyup",n=>{n.key==="Enter"&&this._playButton.click()}),this._positionPlayButton(),await new Promise(n=>{const o=a=>{var h;if(a.stopPropagation(),this.hidePlayButton(),(h=this.engine)!=null&&h.browser&&this.engine.browser.window.off("resize",i),this._originalOptions.fullscreenAfterLoad)try{this._logger.info("requesting fullscreen"),this._originalOptions.fullscreenContainer instanceof HTMLElement?this._originalOptions.fullscreenContainer.requestFullscreen():this.engine.screen.enterFullscreen(this._originalOptions.fullscreenContainer)}catch(l){this._logger.error("could not go fullscreen",l)}n()};this._playButton.addEventListener("click",o),this._playButton.addEventListener("touchend",o),this._playButton.addEventListener("pointerup",o),this.engine&&this.engine.input.gamepads.once("button",()=>o(new Event("button")))})}}hidePlayButton(){this._playButtonShown=!1,this._playButton.style.display="none"}dispose(){this._playButtonRootElement.parentElement&&(this._playButtonRootElement.removeChild(this._playButtonElement),document.body.removeChild(this._playButtonRootElement),document.head.removeChild(this._styleBlock),this._playButtonRootElement=null,this._playButtonElement=null,this._styleBlock=null)}async onUserAction(){var t;await Di(200,(t=this.engine)==null?void 0:t.clock),this.canvas.flagDirty(),await this.showPlayButton()}async onBeforeLoad(){this.screen.pushResolutionAndViewport(),this.screen.resolution={width:this.screen.resolution.width,height:this.screen.resolution.height},this.screen.applyResolutionAndViewport();const t=this._image;await this._imageLoaded.promise,await(t==null?void 0:t.decode())}async onAfterLoad(){this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport(),this.dispose()}_positionPlayButton(){if(this.engine){const{x:t,y:e,width:i,height:s}=this.engine.canvas.getBoundingClientRect();if(this._playButtonRootElement){const n=this._playButton.clientWidth,o=this._playButton.clientHeight;this.playButtonPosition?(this._playButtonRootElement.style.left=`${this.playButtonPosition.x}px`,this._playButtonRootElement.style.top=`${this.playButtonPosition.y}px`):(this._playButtonRootElement.style.left=`${t+i/2-n/2}px`,this._playButtonRootElement.style.top=`${e+s/2-o/2+100}px`)}}}onDraw(t){const e=this.engine.canvasHeight/this.engine.pixelRatio,i=this.engine.canvasWidth/this.engine.pixelRatio;this._positionPlayButton(),t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,i*.75);let o=i/2-n/2;this.logoPosition&&(o=this.logoPosition.x,s=this.logoPosition.y);const a=Math.floor(n*(this.logoHeight/this.logoWidth)),h=this.engine.screen.antialiasing;if(this.engine.screen.antialiasing=!0,this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,o,s,n,a):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,o,s-a-20,n,a),!this.suppressPlayButton&&this._playButtonShown){this.engine.screen.antialiasing=h;return}let l=o,c=s;this.loadingBarPosition&&(l=this.loadingBarPosition.x,c=this.loadingBarPosition.y),t.lineWidth=2,dn(t,l,c,n,20,10,this.loadingBarColor);const u=n*this.progress,_=5,f=u-_*2,p=20-_*2;dn(t,l+_,c+_,f>10?f:10,p,5,null,this.loadingBarColor),this.engine.screen.antialiasing=h}};Uo._DEFAULT_LOADER_OPTIONS={loadables:[],fullscreenAfterLoad:!1,fullscreenContainer:void 0};let Ji=Uo;const zo={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class Oo{constructor(){this._features=null,this.failedTests=[],this._criticalTests={canvasSupport:function(){const t=document.createElement("canvas");return!!(t.getContext&&t.getContext("2d"))},arrayBufferSupport:function(){const t=new XMLHttpRequest;t.open("GET","/");try{t.responseType="arraybuffer"}catch(e){return!1}return t.responseType==="arraybuffer"},dataUrlSupport:function(){return document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")===0},objectUrlSupport:function(){return"URL"in window&&"revokeObjectURL"in URL&&"createObjectURL"in URL},rgbaSupport:function(){const t=document.createElement("a").style;return t.cssText="background-color:rgba(150,255,150,.5)",(""+t.backgroundColor).indexOf("rgba")>-1}},this._warningTest={webAudioSupport:function(){return!!(window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext)},webglSupport:function(){const t=document.createElement("canvas");return!!(t.getContext&&t.getContext("webgl"))}},this._features=this._loadBrowserFeatures()}getBrowserFeatures(){return this._features===null&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t=`%cSUPPORTED BROWSER FEATURES
|
|
894
|
+
}`}),this._total=i}update(t){var e;this._started||(this._started=!0,this._total=this._duration,this._currentDuration=this._duration,this._entity.graphics.material=this._material),this._graphics&&(this._currentDuration-=t,this._graphics&&((e=this._material)==null||e.update(i=>{i.trySetUniformFloat("u_blend",this._currentDuration/this._total)})),this.isComplete()&&(this._entity.graphics.material=null))}isComplete(){return this._stopped||this._currentDuration<=0}stop(){this._graphics&&(this._graphics.isVisible=!0),this._stopped=!0}reset(){this._started=!1,this._stopped=!1}}class Po{constructor(t,e){this.id=H(),this._started=!1,this._stopped=!1,this._mode="dynamic";var i;if(this._entity=t,this._tx=this._entity.get(P),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only curveTo on Entities with TransformComponents.`);this._curve=new si({controlPoints:[b(0,0),...e.controlPoints],quality:e.quality}),this._durationMs=e.duration,this._mode=(i=e.mode)!=null?i:this._mode,this._currentMs=this._durationMs}update(t){this._started||(this._curve.setControlPoint(0,this._tx.globalPos.clone()),this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1);this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(e):this._tx.pos=this._curve.getUniformPoint(e),this.isComplete(this._entity)&&(this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(1):this._tx.pos=this._curve.getUniformPoint(1))}isComplete(t){return this._stopped||this._currentMs<0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}stop(){this._stopped=!0,this._currentMs=0}}class Eo{constructor(t,e){this.id=H(),this._started=!1,this._stopped=!1,this._mode="dynamic";var i;if(this._entity=t,this._tx=this._entity.get(P),!this._tx)throw new Error(`Entity ${t.name} has no TransformComponent, can only curveTo on Entities with TransformComponents.`);this._curve=this._curve=new si({controlPoints:[b(0,0),...e.controlPoints],quality:e.quality}),this._durationMs=e.duration,this._mode=(i=e.mode)!=null?i:this._mode,this._currentMs=this._durationMs}update(t){this._started||(this._curve.setControlPoint(0,this._tx.globalPos),this._curve.setControlPoint(1,this._curve.controlPoints[1].add(this._tx.globalPos)),this._curve.setControlPoint(2,this._curve.controlPoints[2].add(this._tx.globalPos)),this._curve.setControlPoint(3,this._curve.controlPoints[3].add(this._tx.globalPos)),this._started=!0),this._currentMs-=t;const e=B(Wt(0,this._durationMs,0,1,this._durationMs-this._currentMs),0,1);this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(e):this._tx.pos=this._curve.getUniformPoint(e),this.isComplete(this._entity)&&(this._mode==="dynamic"?this._tx.pos=this._curve.getPoint(1):this._tx.pos=this._curve.getUniformPoint(1))}isComplete(t){return this._stopped||this._currentMs<0}reset(){this._currentMs=this._durationMs,this._started=!1,this._stopped=!1}stop(){this._stopped=!0}}class fi{constructor(t){this._entity=t,this._queue=new eo(t)}getQueue(){return this._queue}update(t){this._queue.update(t)}clearActions(){this._queue.clearActions()}runAction(t){return t.reset(),this._queue.add(t),this}curveBy(t){return this._queue.add(new Eo(this._entity,t)),this}curveTo(t){return this._queue.add(new Po(this._entity,t)),this}easeTo(...t){var e,i;let s=0,n=0,o=0,a=Rt.Linear;return t[0]instanceof w?(s=t[0].x,n=t[0].y,o=t[1],a=(e=t[2])!=null?e:a):(s=t[0],n=t[1],o=t[2],a=(i=t[3])!=null?i:a),this._queue.add(new xo(this._entity,s,n,o,a)),this}easeBy(...t){var e,i;let s=0,n=0,o=0,a=Rt.Linear;return t[0]instanceof w?(s=t[0].x,n=t[0].y,o=t[1],a=(e=t[2])!=null?e:a):(s=t[0],n=t[1],o=t[2],a=(i=t[3])!=null?i:a),this._queue.add(new bo(this._entity,s,n,o,a)),this}moveTo(t,e,i){let s=0,n=0,o=0;return t instanceof w?(s=t.x,n=t.y,o=+(e!=null?e:0),this._queue.add(new An(this._entity,s,n,o))):typeof t=="number"&&typeof e=="number"&&typeof i=="number"?(s=t,n=e,o=i,this._queue.add(new An(this._entity,s,n,o))):oo(t)&&this._queue.add(new ao(this._entity,t)),this}moveBy(t,e,i){let s=0,n=0,o=0;return t instanceof w&&typeof e=="number"?(s=t.x,n=t.y,o=e,this._queue.add(new Tn(this._entity,s,n,o))):typeof t=="number"&&typeof e=="number"&&typeof i=="number"?(s=t,n=e,o=i,this._queue.add(new Tn(this._entity,s,n,o))):no(t)&&this._queue.add(new ro(this._entity,t)),this}rotateTo(t,e,i){return typeof t=="number"&&typeof e=="number"?this._queue.add(new lo(this._entity,t,e,i)):typeof t=="object"&&this._queue.add(new ho(this._entity,t)),this}rotateBy(t,e,i){return typeof t=="object"?this._queue.add(new co(this._entity,t)):this._queue.add(new uo(this._entity,t,e,i)),this}scaleTo(t,e,i,s){let n=1,o=1,a=0,h=0;return _o(t)?(this._queue.add(new fo(this._entity,t)),this):(t instanceof w&&e instanceof w&&(n=t.x,o=t.y,a=e.x,h=e.y),typeof t=="number"&&typeof e=="number"&&(n=t,o=e,a=i,h=s),this._queue.add(new go(this._entity,n,o,a,h)),this)}scaleBy(t,e,i){if(po(t))return this._queue.add(new mo(this._entity,t)),this;let s=1,n=1;return t instanceof w&&(s=t.x,n=t.y,i=e),typeof t=="number"&&typeof e=="number"&&(s=t,n=e),this._queue.add(new vo(this._entity,s,n,i)),this}blink(t,e,i=1){return this._queue.add(new yo(this._entity,t,e,i)),this}fade(t,e){return this._queue.add(new Co(this._entity,t,e)),this}flash(t,e=1e3){return this._queue.add(new Ao(this._entity,t,e)),this}delay(t){return this._queue.add(new So(t)),this}die(){return this._queue.add(new To(this._entity)),this}callMethod(t){return this._queue.add(new wo(t)),this}repeat(t,e){return e?(this._queue.add(new io(this._entity,t,e)),this):(this.repeatForever(t),this)}repeatForever(t){return this._queue.add(new so(this._entity,t)),this}follow(t,e){return e===void 0?this._queue.add(new Pn(this._entity,t)):this._queue.add(new Pn(this._entity,t,e)),this}meet(t,e,i){return e===void 0&&i===void 0?this._queue.add(new ji(this._entity,t)):i===void 0?this._queue.add(new ji(this._entity,t,e)):this._queue.add(new ji(this._entity,t,e,i)),this}toPromise(){return new Promise(e=>{this._queue.add(new wo(()=>{e()}))})}}class Qe extends Dt{constructor(){super(...arguments),this.dependencies=[P,O],this._ctx=null}onAdd(t){this._ctx=new fi(t)}onRemove(){this._ctx=null}_getCtx(){if(!this._ctx)throw new Error("Actions component not attached to an entity, no context available");return this._ctx}getQueue(){if(!this._ctx)throw new Error("Actions component not attached to an entity, no queue available");return this._ctx.getQueue()}runAction(t){if(!this._ctx)throw new Error("Actions component not attached to an entity, cannot run action");return this._ctx.runAction(t)}update(t){var e;return(e=this._ctx)==null?void 0:e.update(t)}clearActions(){var t;(t=this._ctx)==null||t.clearActions()}curveBy(t){return this._getCtx().curveBy.apply(this._ctx,[t])}curveTo(t){return this._getCtx().curveTo.apply(this._ctx,[t])}easeTo(...t){return this._getCtx().easeTo.apply(this._ctx,t)}easeBy(...t){return this._getCtx().easeBy.apply(this._ctx,t)}moveTo(t,e,i){return this._getCtx().moveTo.apply(this._ctx,[t,e,i])}moveBy(t,e,i){return this._getCtx().moveBy.apply(this._ctx,[t,e,i])}rotateTo(t,e,i){return this._getCtx().rotateTo.apply(this._ctx,[t,e,i])}rotateBy(t,e,i){return this._getCtx().rotateBy.apply(this._ctx,[t,e,i])}scaleTo(t,e,i,s){return this._getCtx().scaleTo.apply(this._ctx,[t,e,i,s])}scaleBy(t,e,i){return this._getCtx().scaleBy.apply(this._ctx,[t,e,i])}blink(t,e,i){return this._getCtx().blink(t,e,i)}fade(t,e){return this._getCtx().fade(t,e)}flash(t,e=1e3){return this._getCtx().flash(t,e)}delay(t){return this._getCtx().delay(t)}die(){return this._getCtx().die()}callMethod(t){return this._getCtx().callMethod(t)}repeat(t,e){return this._getCtx().repeat(t,e)}repeatForever(t){return this._getCtx().repeatForever(t)}follow(t,e){return this._getCtx().follow(t,e)}meet(t,e){return this._getCtx().meet(t,e)}toPromise(){return this._getCtx().toPromise()}}function Tl(r){return r instanceof kt}const Al={CollisionStart:"collisionstart",CollisionEnd:"collisionend",PreCollision:"precollision",PostCollision:"postcollision",Kill:"kill",PreKill:"prekill",PostKill:"postkill",PreDraw:"predraw",PostDraw:"postdraw",PreTransformDraw:"pretransformdraw",PostTransformDraw:"posttransformdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw",PointerUp:"pointerup",PointerDown:"pointerdown",PointerEnter:"pointerenter",PointerLeave:"pointerleave",PointerMove:"pointermove",PointerCancel:"pointercancel",Wheel:"pointerwheel",PointerDrag:"pointerdragstart",PointerDragEnd:"pointerdragend",PointerDragEnter:"pointerdragenter",PointerDragLeave:"pointerdragleave",PointerDragMove:"pointerdragmove",EnterViewPort:"enterviewport",ExitViewPort:"exitviewport",ActionStart:"actionstart",ActionComplete:"actioncomplete"},Io=class or extends At{constructor(t){super(),this.events=new X,this._anchor=It(w.Half,G=>this._handleAnchorChange(G)),this._offset=It(w.Zero,G=>this._handleOffsetChange(G)),this.logger=R.getInstance(),this._draggable=!1,this._dragging=!1,this._pointerDragStartHandler=()=>{this._dragging=!0},this._pointerDragEndHandler=()=>{this._dragging=!1},this._pointerDragMoveHandler=G=>{this._dragging&&(this.pos=G.worldPos)},this._pointerDragLeaveHandler=G=>{this._dragging&&(this.pos=G.worldPos)};const{name:e,x:i,y:s,pos:n,coordPlane:o,scale:a,width:h,height:l,radius:c,collider:u,vel:_,acc:f,rotation:m,angularVelocity:p,z:x,color:v,visible:g,opacity:y,anchor:S,offset:A,collisionType:I,collisionGroup:C,graphic:L,material:U}={...t};this.name=e!=null?e:this.name,this.anchor=S!=null?S:or.defaults.anchor.clone(),this.offset=A!=null?A:w.Zero,this.transform=new P,this.addComponent(this.transform),this.pos=n!=null?n:b(i!=null?i:0,s!=null?s:0),this.rotation=m!=null?m:0,this.scale=a!=null?a:b(1,1),this.z=x!=null?x:0,this.transform.coordPlane=o!=null?o:rt.World,this.pointer=new he,this.addComponent(this.pointer),this.graphics=new K({anchor:this.anchor,offset:this.offset,opacity:y}),this.addComponent(this.graphics),this.motion=new O,this.addComponent(this.motion),this.vel=_!=null?_:w.Zero,this.acc=f!=null?f:w.Zero,this.angularVelocity=p!=null?p:0,this.actions=new Qe,this.addComponent(this.actions),this.body=new N,this.addComponent(this.body),this.body.collisionType=I!=null?I:M.Passive,C&&(this.body.group=C),v&&(this.color=v),u?(this.collider=new tt(u),this.addComponent(this.collider)):c?(this.collider=new tt(ut.Circle(c)),this.addComponent(this.collider),v&&this.graphics.add(new Xi({color:v,radius:c}))):h>0&&l>0?(this.collider=new tt(ut.Box(h,l,this.anchor)),this.addComponent(this.collider),v&&h&&l&&this.graphics.add(new ui({color:v,width:h,height:l}))):(this.collider=new tt,this.addComponent(this.collider)),this.graphics.isVisible=g!=null?g:!0,L&&this.graphics.use(L),U&&(this.graphics.material=U)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t.clone()}get oldPos(){return this.body.oldPos}get oldGlobalPos(){return this.body.oldGlobalPos}set oldPos(t){this.body.oldPos.setTo(t.x,t.y)}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t.clone()}get oldVel(){return this.body.oldVel}set oldVel(t){this.body.oldVel.setTo(t.x,t.y)}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t.clone()}set oldAcc(t){this.body.oldAcc.setTo(t.x,t.y)}get oldAcc(){return this.body.oldAcc}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}get scale(){return this.get(P).scale}set scale(t){this.get(P).scale=t}get anchor(){return this._anchor}set anchor(t){this._anchor=It(t,e=>this._handleAnchorChange(e)),this._handleAnchorChange(t)}_handleAnchorChange(t){this.graphics&&(this.graphics.anchor=t)}get offset(){return this._offset}set offset(t){this._offset=It(t,e=>this._handleOffsetChange(e)),this._handleOffsetChange(t)}_handleOffsetChange(t){this.graphics&&(this.graphics.offset=t)}get isOffScreen(){return this.hasTag("ex.offscreen")}get draggable(){return this._draggable}set draggable(t){t&&(t&&!this._draggable?(this.events.on("pointerdragstart",this._pointerDragStartHandler),this.events.on("pointerdragend",this._pointerDragEndHandler),this.events.on("pointerdragmove",this._pointerDragMoveHandler),this.events.on("pointerdragleave",this._pointerDragLeaveHandler)):!t&&this._draggable&&(this.events.off("pointerdragstart",this._pointerDragStartHandler),this.events.off("pointerdragend",this._pointerDragEndHandler),this.events.off("pointerdragmove",this._pointerDragMoveHandler),this.events.off("pointerdragleave",this._pointerDragLeaveHandler)),this._draggable=t)}get color(){return this.graphics.color}set color(t){this.graphics.color=t}clone(){const t=new or({color:this.color.clone(),anchor:this.anchor.clone(),offset:this.offset.clone()});t.clearComponents(),t.processComponentRemoval(),t.addComponent(t.transform=this.transform.clone(),!0),t.addComponent(t.pointer=this.pointer.clone(),!0),t.addComponent(t.graphics=this.graphics.clone(),!0),t.addComponent(t.motion=this.motion.clone(),!0),t.addComponent(t.actions=this.actions.clone(),!0),t.addComponent(t.body=this.body.clone(),!0),this.collider.get()&&t.addComponent(t.collider=this.collider.clone(),!0);const e=[this.transform,this.pointer,this.graphics,this.motion,this.actions,this.body,this.collider],i=this.getComponents();for(const s of i)e.includes(s)||t.addComponent(s.clone(),!0);return t}onInitialize(t){}_initialize(t){super._initialize(t);for(const e of this.children)e._initialize(t)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_prekill(t){this.events.emit("prekill",new Ps(this)),this.onPreKill(t)}onPreKill(t){}_postkill(t){this.events.emit("postkill",new Es(this)),this.onPostKill(t)}onPostKill(t){}kill(){this.scene?(this._prekill(this.scene),this.events.emit("kill",new Ei(this)),super.kill(),this._postkill(this.scene)):this.logger.warn(`Cannot kill actor named "${this.name}", it was never added to the Scene`)}unkill(){this.isActive=!0}isKilled(){return!this.isActive}get z(){return this.get(P).z}set z(t){this.get(P).z=t}get center(){const t=this.getGlobalPos();return new w(t.x+this.width/2-this.anchor.x*this.width,t.y+this.height/2-this.anchor.y*this.height)}get localCenter(){return new w(this.pos.x+this.width/2-this.anchor.x*this.width,this.pos.y+this.height/2-this.anchor.y*this.height)}get width(){return this.collider.localBounds.width*this.getGlobalScale().x}get height(){return this.collider.localBounds.height*this.getGlobalScale().y}getGlobalRotation(){return this.get(P).globalRotation}get globalRotation(){return this.get(P).globalRotation}getGlobalPos(){return this.get(P).globalPos}get globalPos(){return this.get(P).globalPos}getGlobalScale(){return this.get(P).globalScale}get globalScale(){return this.get(P).globalScale}get globalZ(){return this.get(P).globalZ}contains(t,e,i=!1){const s=b(t,e),n=this.get(tt);n.update();const o=n.get();if(!o)return!1;const a=o.contains(s);return i?a||this.children.some(h=>h.contains(t,e,!0)):a}within(t,e){const i=this.get(tt),s=t.get(tt),n=i.get(),o=s.get();return n&&o?n.getClosestLineBetween(o).getLength()<=e:!1}update(t,e){this._initialize(t),this._add(t),this._preupdate(t,e),this._postupdate(t,e),this._remove(t)}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreCollisionResolve(t,e,i,s){}onPostCollisionResolve(t,e,i,s){}onCollisionStart(t,e,i,s){}onCollisionEnd(t,e,i,s){}_preupdate(t,e){this.events.emit("preupdate",new re(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.events.emit("postupdate",new oe(t,e,this)),this.onPostUpdate(t,e)}};Io.defaults={anchor:w.Half};let kt=Io;class tt extends Dt{constructor(t){super(),this.events=new X,this.$colliderAdded=new gt,this.$colliderRemoved=new gt,this._collidersToRemove=[],this.set(t)}get(){return this._collider}set(t){return this.clear(),t&&(this._collider=t,this._collider.owner=this.owner,t.events.pipe(this.events),this.$colliderAdded.notifyAll(t),this.update()),t}clear(){this._collider&&(this._collidersToRemove.push(this._collider),this._collider=null)}processColliderRemoval(){for(const t of this._collidersToRemove)t.events.unpipe(this.events),this.$colliderRemoved.notifyAll(t),t.owner=null}clone(){return new tt(this._collider.clone())}get bounds(){var t,e;return(e=(t=this._collider)==null?void 0:t.bounds)!=null?e:new F}get localBounds(){var t,e;return(e=(t=this._collider)==null?void 0:t.localBounds)!=null?e:new F}update(){var t;const e=(t=this.owner)==null?void 0:t.get(P);this._collider&&(this._collider.owner=this.owner,e&&this._collider.update(e.get()))}collide(t){let e=this._collider,i=t._collider;if(!e||!i)return[];let s=!1;if(i instanceof at&&(e=i,i=this._collider,s=!0),this._collider){const n=e.collide(i);return n?(s&&n.forEach(o=>{o.mtv=o.mtv.negate(),o.normal=o.normal.negate(),o.tangent=o.normal.perpendicular(),o.colliderA=this._collider,o.colliderB=t._collider}),n):[]}return[]}onAdd(t){this._collider&&this.update(),this.events.on("precollision",e=>{const i=e;t.events.emit("precollision",new ve(i.self,i.other,i.side,i.intersection,i.contact)),t instanceof kt&&t.onPreCollisionResolve(i.self,i.other,i.side,i.contact)}),this.events.on("postcollision",e=>{const i=e;t.events.emit("postcollision",new we(i.self,i.other,i.side,i.intersection,i.contact)),t instanceof kt&&t.onPostCollisionResolve(i.self,i.other,i.side,i.contact)}),this.events.on("collisionstart",e=>{const i=e;t.events.emit("collisionstart",new ni(i.self,i.other,i.side,i.contact)),t instanceof kt&&t.onCollisionStart(i.self,i.other,i.side,i.contact)}),this.events.on("collisionend",e=>{const i=e;t.events.emit("collisionend",new ri(i.self,i.other,i.side,i.lastContact)),t instanceof kt&&t.onCollisionEnd(i.self,i.other,i.side,i.lastContact)})}onRemove(){this.events.clear(),this.$colliderRemoved.notifyAll(this._collider)}useBoxCollider(t,e,i=w.Half,s=w.Zero){const n=ut.Box(t,e,i,s);return this.set(n)}usePolygonCollider(t,e=w.Zero){const i=ut.Polygon(t,e);return this.set(i)}useCircleCollider(t,e=w.Zero){const i=ut.Circle(t,e);return this.set(i)}useEdgeCollider(t,e){const i=ut.Edge(t,e);return this.set(i)}useCompositeCollider(t){return this.set(new at(t))}}var le=(r=>(r.Rotation="rotation",r.X="x",r.Y="y",r))(le||{});const En=class _s extends Dt{constructor(t){var e,i,s;super(),this.dependencies=[P,O],this.id=fe("body",_s._ID++),this.events=new X,this.oldTransform=new Kt,this.__oldTransformCaptured=!1,this.enableFixedUpdateInterpolate=!0,this.collisionType=M.PreventCollision,this.group=me.All,this._sleeping=!1,this.bounciness=.2,this.friction=.99,this.useGravity=!0,this.limitDegreeOfFreedom=[],this._oldGlobalPos=w.Zero,this.oldVel=new w(0,0),this.oldAcc=w.Zero,this._impulseScratch=b(0,0),this._distanceFromCenterScratch=b(0,0),t?(this.collisionType=(e=t.type)!=null?e:this.collisionType,this.group=(i=t.group)!=null?i:this.group,this.useGravity=(s=t.useGravity)!=null?s:this.useGravity,this._bodyConfig={...te().bodies,...t.config}):this._bodyConfig={...te().bodies},this.updatePhysicsConfig(this._bodyConfig),this._mass=_s._DEFAULT_CONFIG.defaultMass}get matrix(){return this.transform.get().matrix}updatePhysicsConfig(t){this._bodyConfig={...te().bodies,...t},this.canSleep=this._bodyConfig.canSleepByDefault,this.sleepMotion=this._bodyConfig.sleepEpsilon*5,this.wakeThreshold=this._bodyConfig.wakeThreshold}static updateDefaultPhysicsConfig(t){_s._DEFAULT_CONFIG=t}get mass(){return this._mass}set mass(t){this._mass=t,this._cachedInertia=void 0,this._cachedInverseInertia=void 0}get inverseMass(){return this.collisionType===M.Fixed?0:1/this.mass}get sleeping(){return this.isSleeping}get isSleeping(){return this._sleeping}setSleeping(t){this.isSleeping=t}set isSleeping(t){this._sleeping=t,t?(this.vel=w.Zero,this.acc=w.Zero,this.angularVelocity=0,this.sleepMotion=0):this.sleepMotion=this._bodyConfig.sleepEpsilon*5}updateMotion(){this._sleeping&&(this.isSleeping=!0);const t=this.vel.magnitude*this.vel.magnitude+Math.abs(this.angularVelocity*this.angularVelocity),e=this._bodyConfig.sleepBias;this.sleepMotion=e*this.sleepMotion+(1-e)*t,this.sleepMotion=B(this.sleepMotion,0,10*this._bodyConfig.sleepEpsilon),this.canSleep&&this.sleepMotion<this._bodyConfig.sleepEpsilon&&(this.isSleeping=!0)}get inertia(){if(this._cachedInertia)return this._cachedInertia;const t=this.owner.get(tt);if(t){t.$colliderAdded.subscribe(()=>{this._cachedInertia=null}),t.$colliderRemoved.subscribe(()=>{this._cachedInertia=null});const e=t.get();if(e)return this._cachedInertia=e.getInertia(this.mass)}return 0}get inverseInertia(){return this._cachedInverseInertia?this._cachedInverseInertia:this._cachedInverseInertia=this.collisionType===M.Fixed?0:1/this.inertia}get active(){var t;return!!((t=this.owner)!=null&&t.isActive)}get isActive(){var t;return!!((t=this.owner)!=null&&t.isActive)}get center(){return this.globalPos}onAdd(t){var e,i;this.transform=(e=this.owner)==null?void 0:e.get(P),this.motion=(i=this.owner)==null?void 0:i.get(O)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get globalPos(){return this.transform.globalPos}set globalPos(t){this.transform.globalPos=t}get oldPos(){return this.oldTransform.pos}get oldGlobalPos(){return this._oldGlobalPos}get vel(){return this.motion.vel}set vel(t){this.motion.vel=t}get acc(){return this.motion.acc}set acc(t){this.motion.acc=t}get torque(){return this.motion.torque}set torque(t){this.motion.torque=t}get oldRotation(){return this.oldTransform.rotation}get rotation(){return this.transform.globalRotation}set rotation(t){this.transform.globalRotation=t}get scale(){return this.transform.globalScale}set scale(t){this.transform.globalScale=t}get oldScale(){return this.oldTransform.scale}get scaleFactor(){return this.motion.scaleFactor}set scaleFactor(t){this.motion.scaleFactor=t}get angularVelocity(){return this.motion.angularVelocity}set angularVelocity(t){this.motion.angularVelocity=t}applyImpulse(t,e){if(this.collisionType!==M.Active)return;const i=e.scale(this.inverseMass,this._impulseScratch);if(this.limitDegreeOfFreedom.indexOf("x")>-1&&(i.x=0),this.limitDegreeOfFreedom.indexOf("y")>-1&&(i.y=0),this.vel.addEqual(i),!this.limitDegreeOfFreedom.includes("rotation")){const s=t.sub(this.globalPos,this._distanceFromCenterScratch);this.angularVelocity+=this.inverseInertia*s.cross(e)}}applyLinearImpulse(t){if(this.collisionType!==M.Active)return;const e=t.scale(this.inverseMass);this.limitDegreeOfFreedom.includes("x")&&(e.x=0),this.limitDegreeOfFreedom.includes("y")&&(e.y=0),this.vel=this.vel.add(e)}applyAngularImpulse(t,e){if(this.collisionType===M.Active&&!this.limitDegreeOfFreedom.includes("rotation")){const i=t.sub(this.globalPos);this.angularVelocity+=this.inverseInertia*i.cross(e)}}captureOldTransform(){this.__oldTransformCaptured=!0;const t=this.transform.get();t.clone(this.oldTransform),this.oldTransform.parent=t.parent,this.oldVel.setTo(this.vel.x,this.vel.y),this.oldAcc.setTo(this.acc.x,this.acc.y),this.oldGlobalPos.setTo(this.globalPos.x,this.globalPos.y)}clone(){return super.clone()}};En._ID=0,En._DEFAULT_CONFIG={...te().bodies};let N=En;class In{constructor(t,e){this.object=t,this.id=-1,this.cells=[],this.hasZeroBounds=!1,this.gridSize=e,this.bounds=t.bounds,this.hasZeroBounds=this.bounds.hasZeroDimensions(),this.leftX=Math.floor(this.bounds.left/this.gridSize),this.rightX=Math.floor(this.bounds.right/this.gridSize),this.bottomY=Math.floor(this.bounds.bottom/this.gridSize),this.topY=Math.floor(this.bounds.top/this.gridSize)}hasChanged(){const t=this.object.bounds,e=Math.floor(t.left/this.gridSize),i=Math.floor(t.right/this.gridSize),s=Math.floor(t.bottom/this.gridSize),n=Math.floor(t.top/this.gridSize);return this.leftX!==e||this.rightX!==i||this.bottomY!==s||this.topY!==n}clear(){for(const t of this.cells){const e=t.proxies.indexOf(this);e>-1&&t.proxies.splice(e,1)}}updateBounds(){this.bounds=this.object.bounds}update(){this.bounds=this.object.bounds,this.leftX=Math.floor(this.bounds.left/this.gridSize),this.rightX=Math.floor(this.bounds.right/this.gridSize),this.bottomY=Math.floor(this.bounds.bottom/this.gridSize),this.topY=Math.floor(this.bounds.top/this.gridSize),this.hasZeroBounds=this.object.bounds.hasZeroDimensions()}}class Zt{constructor(){this.proxies=[]}configure(t,e){this.x=t,this.y=e,this.key=Zt.calculateHashKey(t,e)}static calculateHashKey(t,e){return`${t}+${e}`}}class Rn{constructor(t){this.bounds=new F,this._hashGridCellPool=new qe(()=>new Zt,e=>(e.configure(0,0),e.proxies.length=0,e),1e3),this.gridSize=t.size,this.sparseHashGrid=new Map,this.objectToProxy=new Map,t.proxyFactory?this._buildProxy=e=>t.proxyFactory(e,this.gridSize):this._buildProxy=e=>new In(e,this.gridSize)}query(t){const e=new Set;if(t instanceof F){const i=t,s=Math.floor(i.left/this.gridSize),n=Math.floor(i.right/this.gridSize),o=Math.floor(i.bottom/this.gridSize),a=Math.floor(i.top/this.gridSize);for(let h=s;h<=n;h++)for(let l=a;l<=o;l++){const c=Zt.calculateHashKey(h,l),u=this.sparseHashGrid.get(c);if(u)for(let _=0;_<u.proxies.length;_++)u.proxies[_].updateBounds(),u.proxies[_].bounds.intersect(i)&&e.add(u.proxies[_].object)}}else{const i=t,s=Zt.calculateHashKey(Math.floor(i.x/this.gridSize),Math.floor(i.y/this.gridSize)),n=this.sparseHashGrid.get(s);if(n)for(let o=0;o<n.proxies.length;o++)n.proxies[o].updateBounds(),n.proxies[o].bounds.contains(i)&&e.add(n.proxies[o].object)}return Array.from(e)}get(t,e){const i=Zt.calculateHashKey(t,e);return this.sparseHashGrid.get(i)}_insert(t,e,i){const s=Zt.calculateHashKey(t,e);let n=this.sparseHashGrid.get(s);n||(n=this._hashGridCellPool.rent(),n.configure(t,e),this.sparseHashGrid.set(n.key,n)),n.proxies.push(i),i.cells.push(n),this.bounds.combine(i.bounds,this.bounds)}_remove(t,e,i){const s=Zt.calculateHashKey(t,e),n=this.sparseHashGrid.get(s);if(n){const o=n.proxies.indexOf(i);o>-1&&n.proxies.splice(o,1);const a=i.cells.indexOf(n);a>-1&&i.cells.splice(a,1),n.proxies.length===0&&(this._hashGridCellPool.return(n),this.sparseHashGrid.delete(s))}}track(t){const e=this._buildProxy(t);this.objectToProxy.set(t,e);for(let i=e.leftX;i<=e.rightX;i++)for(let s=e.topY;s<=e.bottomY;s++)this._insert(i,s,e)}untrack(t){const e=this.objectToProxy.get(t);e&&(e.clear(),this.objectToProxy.delete(t))}update(t){let e=0;for(const i of t){const s=this.objectToProxy.get(i);if(s&&s.hasChanged()){for(let n=s.leftX;n<=s.rightX;n++)for(let o=s.topY;o<=s.bottomY;o++)this._remove(n,o,s);s.update();for(let n=s.leftX;n<=s.rightX;n++)for(let o=s.topY;o<=s.bottomY;o++)this._insert(n,o,s);e++}}return e}debug(t,e){const i=T.Transparent,s=T.White;for(const n of this.sparseHashGrid.values())t.drawRectangle(b(n.x*this.gridSize,n.y*this.gridSize),this.gridSize,this.gridSize,i,s,2)}}class Ro extends In{constructor(t,e){var i,s,n;super(t,e),this.collider=t,this.id=-1,this.hasZeroBounds=!1,this.cells=[],this.gridSize=e;const o=t.bounds;this.hasZeroBounds=o.hasZeroDimensions(),this.leftX=Math.floor(o.left/this.gridSize),this.rightX=Math.floor(o.right/this.gridSize),this.bottomY=Math.floor(o.bottom/this.gridSize),this.topY=Math.floor(o.top/this.gridSize),this.owner=t.owner,this.body=(i=this.owner)==null?void 0:i.get(N),this.collisionType=(n=(s=this.body)==null?void 0:s.collisionType)!=null?n:M.PreventCollision}update(){var t,e,i;super.update(),this.body=(t=this.owner)==null?void 0:t.get(N),this.collisionType=(i=(e=this.body)==null?void 0:e.collisionType)!=null?i:M.PreventCollision,this.hasZeroBounds=this.collider.localBounds.hasZeroDimensions()}}class Mn{constructor(t){this._pairs=new Set,this._nonPairs=new Set,this._pairPool=new zi(()=>new pt({id:fe("collider",0)},{id:fe("collider",0)}),e=>(e.colliderA=null,e.colliderB=null,e),200),this.gridSize=t.size,this.hashGrid=new Rn({size:this.gridSize,proxyFactory:(e,i)=>new Ro(e,i)}),this._pairPool.disableWarnings=!0}getColliders(){return Array.from(this.hashGrid.objectToProxy.keys())}query(t){return this.hashGrid.query(t)}rayCast(t,e){var i,s,n;const o=[],a=(i=e==null?void 0:e.maxDistance)!=null?i:1/0,h=e==null?void 0:e.collisionGroup,l=h?h.category:(s=e==null?void 0:e.collisionMask)!=null?s:me.All.category,c=(n=e==null?void 0:e.searchAllColliders)!=null?n:!1,u=t.dir.normalize(),_=u.y/u.x,f=u.x/u.y,m=Math.sqrt(1+_*_)*this.gridSize,p=Math.sqrt(1+f*f)*this.gridSize,x=t.pos.x/this.gridSize,v=t.pos.y/this.gridSize,g=b(1,1);let y=~~x,S=~~v,A=0,I=0;u.x<0?(g.x=-1,A=(x-y)*m):(g.x=1,A=(y+1-x)*m),u.y<0?(g.y=-1,I=(v-S)*p):(g.y=1,I=(S+1-v)*p);const C=new Set;let L=!1,U=9999;for(;!L&&U>0&&(U--,!!this.hashGrid.bounds.contains(b(y*this.gridSize,S*this.gridSize)));){const G=Zt.calculateHashKey(y,S),et=this.hashGrid.sparseHashGrid.get(G);if(et){const ht=[];for(let $=0;$<et.proxies.length;$++){const W=et.proxies[$];if(!C.has(W.collider.id.value)){if(C.add(W.collider.id.value),W.body){if(e!=null&&e.ignoreCollisionGroupAll&&W.body.group===me.All)continue;const ft=(l&W.body.group.category)!==0;if(W.body.group&&!ft)continue}const ct=W.collider.rayCast(t,a);ct&&ht.push(ct)}}ht.sort(($,W)=>$.distance-W.distance);for(let $=0;$<ht.length;$++){const W=ht[$];if(e!=null&&e.filter){if(e.filter(W)&&(o.push(W),!c)){L=!0;break}}else if(o.push(W),!c){L=!0;break}}}A<I?(y+=g.x,A+=m):(S+=g.y,I+=p)}return o.sort((G,et)=>G.distance-et.distance),!c&&o.length?[o[0]]:o}track(t){let e=[t];if(t instanceof at){const i=t.getColliders();for(const s of i)s.owner=t.owner;e=i}for(const i of e)this.hashGrid.track(i)}untrack(t){let e=[t];t instanceof at&&(e=t.getColliders());for(const i of e)this.hashGrid.untrack(i)}_canCollide(t,e){return!(t.collider.id===e.collider.id||t.owner&&e.owner&&t.owner.id===e.owner.id||t.hasZeroBounds||e.hasZeroBounds||t.body&&e.body&&!t.body.group.canCollide(e.body.group)||t.collisionType===M.Fixed&&e.collisionType===M.Fixed||t.collisionType===M.PreventCollision||e.collisionType===M.PreventCollision||!t.owner.isActive||!e.owner.isActive)}broadphase(t,e){const i=[];this._pairs.clear(),this._nonPairs.clear();let s=0;for(const n of this.hashGrid.objectToProxy.values())if(n.id=s++,!(!n.owner.isActive||n.collisionType===M.PreventCollision))for(let o=0;o<n.cells.length;o++){const a=n.cells[o];for(let h=0;h<a.proxies.length;h++){const l=a.proxies[h];if(l.id===n.id)continue;const c=pt.calculatePairHash(n.collider.id,l.collider.id);if(!this._nonPairs.has(c))if(!this._pairs.has(c)&&this._canCollide(n,l)&&n.object.bounds.overlaps(l.object.bounds)){const u=this._pairPool.get();u.colliderA=n.collider,u.colliderB=l.collider,u.id=c,this._pairs.add(c),i.push(u)}else this._nonPairs.add(c)}}return i}narrowphase(t,e){const i=[];for(let s=0;s<t.length;s++){const n=t[s].collide();for(let o=0;o<n.length;o++){const a=n[o];i.push(a),e&&e.physics.contacts.set(a.id,a)}}return this._pairPool.done(),e&&(e.physics.collisions+=i.length),i}update(t,e){return this.hashGrid.update(t)}debug(t,e){this.hashGrid.debug(t,e)}}class Je{constructor(t,e){this.bounds=t,this.options=e,this._defaultOptions={maxDepth:10,capacity:10,level:0},this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null,this.options={...this._defaultOptions,...e},this.halfWidth=t.width/2,this.halfHeight=t.height/2}_split(){this._isDivided=!0;const t={maxDepth:this.options.maxDepth,capacity:this.options.capacity,level:this.options.level+1};this.topLeft=new Je(new F({left:this.bounds.left,top:this.bounds.top,right:this.bounds.left+this.halfWidth,bottom:this.bounds.top+this.halfHeight}),t),this.topRight=new Je(new F({left:this.bounds.left+this.halfWidth,top:this.bounds.top,right:this.bounds.right,bottom:this.bounds.top+this.halfHeight}),t),this.bottomLeft=new Je(new F({left:this.bounds.left,top:this.bounds.top+this.halfHeight,right:this.bounds.left+this.halfWidth,bottom:this.bounds.bottom}),t),this.bottomRight=new Je(new F({left:this.bounds.left+this.halfWidth,top:this.bounds.top+this.halfHeight,right:this.bounds.right,bottom:this.bounds.bottom}),t)}_insertIntoSubNodes(t){var e,i,s,n;(e=this.topLeft)!=null&&e.bounds.overlaps(t.bounds)&&this.topLeft.insert(t),(i=this.topRight)!=null&&i.bounds.overlaps(t.bounds)&&this.topRight.insert(t),(s=this.bottomLeft)!=null&&s.bounds.overlaps(t.bounds)&&this.bottomLeft.insert(t),(n=this.bottomRight)!=null&&n.bounds.overlaps(t.bounds)&&this.bottomRight.insert(t)}insert(t){if(this._isDivided){this._insertIntoSubNodes(t);return}if(this.items.push(t),this.items.length>this.options.capacity&&this.options.level<this.options.maxDepth){this._isDivided||this._split();for(const e of this.items)this._insertIntoSubNodes(e);this.items.length=0}}remove(t){var e,i,s,n;if(this.bounds.overlaps(t.bounds)){if(!this._isDivided){const o=this.items.indexOf(t);o>-1&&this.items.splice(o,1);return}(e=this.topLeft)!=null&&e.bounds.overlaps(t.bounds)&&this.topLeft.remove(t),(i=this.topRight)!=null&&i.bounds.overlaps(t.bounds)&&this.topRight.remove(t),(s=this.bottomLeft)!=null&&s.bounds.overlaps(t.bounds)&&this.bottomLeft.remove(t),(n=this.bottomRight)!=null&&n.bounds.overlaps(t.bounds)&&this.bottomRight.remove(t)}}query(t){let e=this.items;return this._isDivided&&(this.topLeft.bounds.overlaps(t)&&(e=e.concat(this.topLeft.query(t))),this.topRight.bounds.overlaps(t)&&(e=e.concat(this.topRight.query(t))),this.bottomLeft.bounds.overlaps(t)&&(e=e.concat(this.bottomLeft.query(t))),this.bottomRight.bounds.overlaps(t)&&(e=e.concat(this.bottomRight.query(t)))),e=e.filter((i,s)=>e.indexOf(i)>=s),e}clear(){this.items=[],this._isDivided=!1,this.topLeft=null,this.topRight=null,this.bottomLeft=null,this.bottomRight=null}getAllItems(){let t=this.items;return this._isDivided&&(t=t.concat(this.topLeft.getAllItems()),t=t.concat(this.topRight.getAllItems()),t=t.concat(this.bottomLeft.getAllItems()),t=t.concat(this.bottomRight.getAllItems())),t=t.filter((e,i)=>t.indexOf(e)>=i),t}getTreeDepth(){return this._isDivided?1+Math.max(this.topLeft.getTreeDepth(),this.topRight.getTreeDepth(),this.bottomLeft.getTreeDepth(),this.bottomRight.getTreeDepth()):0}debug(t){this.bounds.debug(t,{color:T.Yellow}),this._isDivided&&(this.topLeft.bounds.debug(t,{color:T.Yellow}),this.topRight.bounds.debug(t,{color:T.Yellow}),this.bottomLeft.bounds.debug(t,{color:T.Yellow}),this.bottomRight.bounds.debug(t,{color:T.Yellow}))}}class Fn{constructor(t){this.config=t,this.directionMap=new Map,this.distanceMap=new Map,this._compositeContactsIds=new Set}solve(t){this.preSolve(t),t=t.filter(i=>!i.isCanceled());let e;switch(this.config.contactSolveBias){case ae.HorizontalFirst:{e=nn;break}case ae.VerticalFirst:{e=sn;break}default:e=rn}t.sort((i,s)=>{const n=this.directionMap.get(i.id),o=this.directionMap.get(s.id),a=this.distanceMap.get(i.id),h=this.distanceMap.get(s.id);return e[n]-e[o]||a-h});for(const i of t)this.solvePosition(i),this.solveVelocity(i);return this.postSolve(t),t}preSolve(t){for(let i=0;i<t.length;i++){const s=t[i],n=s.id.indexOf("|");if(n>0){const l=s.id.substring(n+1);if(this._compositeContactsIds.has(l)){s.cancel();continue}this._compositeContactsIds.add(l)}if(Math.abs(s.mtv.x)<1e-4&&Math.abs(s.mtv.y)<1e-4){s.cancel();continue}const o=d.Side.fromDirection(s.mtv),a=s.mtv.negate(),h=Math.abs(s.info.separation);this.distanceMap.set(s.id,h),this.directionMap.set(s.id,o===d.Side.Left||o===d.Side.Right?"horizontal":"vertical"),s.colliderA.events.emit("precollision",new ve(s.colliderA,s.colliderB,o,a,s)),s.colliderB.events.emit("precollision",new ve(s.colliderB,s.colliderA,d.Side.getOpposite(o),a.negate(),s))}this._compositeContactsIds.clear()}postSolve(t){var e,i;for(let s=0;s<t.length;s++){const n=t[s];if(n.isCanceled())continue;const o=n.colliderA,a=n.colliderB,h=(e=o.owner)==null?void 0:e.get(N),l=(i=a.owner)==null?void 0:i.get(N);if(h&&l&&(h.collisionType===M.Passive||l.collisionType===M.Passive))continue;const c=d.Side.fromDirection(n.mtv),u=n.mtv.negate();n.colliderA.events.emit("postcollision",new we(n.colliderA,n.colliderB,c,u,n)),n.colliderB.events.emit("postcollision",new we(n.colliderB,n.colliderA,d.Side.getOpposite(c),u.negate(),n))}}solvePosition(t){var e,i;if(!t.colliderA.bounds.overlaps(t.colliderB.bounds,1e-4)){t.cancel();return}if(Math.abs(t.mtv.x)<1e-4&&Math.abs(t.mtv.y)<1e-4){t.cancel();return}let n=t.mtv;const o=t.colliderA,a=t.colliderB,h=(e=o.owner)==null?void 0:e.get(N),l=(i=a.owner)==null?void 0:i.get(N);if(h&&l){if(h.collisionType===M.Passive||l.collisionType===M.Passive)return;h.collisionType===M.Active&&l.collisionType===M.Active&&(n=n.scale(.5)),h.collisionType===M.Active&&(h.globalPos.x-=n.x,h.globalPos.y-=n.y,o.update(h.transform.get())),l.collisionType===M.Active&&(l.globalPos.x+=n.x,l.globalPos.y+=n.y,a.update(l.transform.get()))}}solveVelocity(t){var e,i;if(t.isCanceled())return;const s=t.colliderA,n=t.colliderB,o=(e=s.owner)==null?void 0:e.get(N),a=(i=n.owner)==null?void 0:i.get(N);if(o&&a){if(o.collisionType===M.Passive||a.collisionType===M.Passive)return;const h=t.normal,l=h.negate();if(o.collisionType===M.Active&&o.vel.normalize().dot(l)<0){const c=h.scale(h.dot(o.vel.negate()));o.vel=o.vel.add(c)}if(a.collisionType===M.Active&&a.vel.normalize().dot(h)<0){const c=l.scale(l.dot(a.vel.negate()));a.vel=a.vel.add(c)}}}}class Mo{constructor(t,e,i){this.point=t,this.local=e,this.contact=i,this.normalImpulse=0,this.tangentImpulse=0,this.normalMass=0,this.tangentMass=0,this.aToContact=new w(0,0),this.bToContact=new w(0,0),this.originalVelocityAndRestitution=0,this.update()}update(){const t=this.contact.bodyA,e=this.contact.colliderA,i=this.contact.bodyB,s=this.contact.colliderB;if(t&&i){const n=this.contact.normal,o=this.contact.tangent;this.aToContact=this.point.sub(e.center),this.bToContact=this.point.sub(s.center);const a=this.aToContact.cross(n),h=this.bToContact.cross(n);this.normalMass=t.inverseMass+i.inverseMass+t.inverseInertia*a*a+i.inverseInertia*h*h;const l=this.aToContact.cross(o),c=this.bToContact.cross(o);this.tangentMass=t.inverseMass+i.inverseMass+t.inverseInertia*l*l+i.inverseInertia*c*c}return this}getRelativeVelocity(){const t=this.contact.bodyA,e=this.contact.bodyB;if(t&&e){const i=t.vel.add(w.cross(t.angularVelocity,this.aToContact));return e.vel.add(w.cross(e.angularVelocity,this.bToContact)).sub(i)}return w.Zero}}class Dn{constructor(t){this.config=t,this.directionMap=new Map,this.distanceMap=new Map,this.lastFrameContacts=new Map,this.idToContactConstraint=new Map}getContactConstraints(t){var e;return(e=this.idToContactConstraint.get(t))!=null?e:[]}solve(t){this.preSolve(t),t=t.filter(i=>!i.isCanceled());let e;switch(this.config.contactSolveBias){case ae.HorizontalFirst:{e=nn;break}case ae.VerticalFirst:{e=sn;break}default:e=rn}return t.sort((i,s)=>{const n=this.directionMap.get(i.id),o=this.directionMap.get(s.id),a=this.distanceMap.get(i.id),h=this.distanceMap.get(s.id);return e[n]-e[o]||a-h}),this.solveVelocity(t),this.solvePosition(t),this.postSolve(t),t}preSolve(t){var e,i,s,n;for(let h=0;h<t.length;h++){const l=t[h];if(Math.abs(l.mtv.x)<1e-4&&Math.abs(l.mtv.y)<1e-4){l.cancel();continue}const c=d.Side.fromDirection(l.mtv),u=Math.abs(((e=l==null?void 0:l.info)==null?void 0:e.separation)||0);this.distanceMap.set(l.id,u),this.directionMap.set(l.id,c===d.Side.Left||c===d.Side.Right?"horizontal":"vertical"),l.colliderA.events.emit("precollision",new ve(l.colliderA,l.colliderB,c,l.mtv,l)),l.colliderA.events.emit("beforecollisionresolve",new Mi(l.colliderA,l.colliderB,c,l.mtv,l)),l.colliderB.events.emit("precollision",new ve(l.colliderB,l.colliderA,d.Side.getOpposite(c),l.mtv.negate(),l)),l.colliderB.events.emit("beforecollisionresolve",new Mi(l.colliderB,l.colliderA,d.Side.getOpposite(c),l.mtv.negate(),l)),l.matchAwake()}const a=Array.from(this.idToContactConstraint.keys());for(let h=0;h<t.length;h++){const l=t[h],c=a.indexOf(l.id);c>-1&&a.splice(c,1);const u=(i=this.idToContactConstraint.get(l.id))!=null?i:[];let _=0;const f=l.bodyA,m=l.colliderA,p=l.bodyB,x=l.colliderB;if(f&&p)for(let v=0;v<l.points.length;v++){const g=l.points[v],y=l.normal,S=l.tangent,A=g.sub(m.center),I=g.sub(x.center),C=A.cross(y),L=I.cross(y),U=f.inverseMass+p.inverseMass+f.inverseInertia*C*C+p.inverseInertia*L*L,G=A.cross(S),et=I.cross(S),ht=f.inverseMass+p.inverseMass+f.inverseInertia*G*G+p.inverseInertia*et*et;u[_]&&((n=(s=u[_])==null?void 0:s.point)==null?void 0:n.squareDistance(g))<4?(u[_].point=g,u[_].local=l.localPoints[_]):u[_]=new Mo(g,l.localPoints[_],l),u[_].aToContact=A,u[_].bToContact=I,u[_].normalMass=1/U,u[_].tangentMass=1/ht;const $=f.bounciness>p.bounciness?f.bounciness:p.bounciness,W=l.normal.dot(u[_].getRelativeVelocity());u[_].originalVelocityAndRestitution=0,W<-.1&&(u[_].originalVelocityAndRestitution=-$*W),_++}this.idToContactConstraint.set(l.id,u)}for(const h of a)this.idToContactConstraint.delete(h);if(this.config.warmStart)this.warmStart(t);else for(let h=0;h<t.length;h++){const l=t[h],c=this.getContactConstraints(l.id);for(const u of c)u.normalImpulse=0,u.tangentImpulse=0}}postSolve(t){for(let e=0;e<t.length;e++){const i=t[e],s=i.bodyA,n=i.bodyB;if(s&&n){if(s.collisionType===M.Passive||n.collisionType===M.Passive)continue;s.updateMotion(),n.updateMotion()}const o=d.Side.fromDirection(i.mtv);i.colliderA.events.emit("postcollision",new we(i.colliderA,i.colliderB,o,i.mtv,i)),i.colliderA.events.emit("aftercollisionresolve",new Fi(i.colliderA,i.colliderB,o,i.mtv,i)),i.colliderB.events.emit("postcollision",new we(i.colliderB,i.colliderA,d.Side.getOpposite(o),i.mtv.negate(),i)),i.colliderB.events.emit("aftercollisionresolve",new Fi(i.colliderB,i.colliderA,d.Side.getOpposite(o),i.mtv.negate(),i))}this.lastFrameContacts.clear();for(let e=0;e<t.length;e++){const i=t[e];this.lastFrameContacts.set(i.id,i)}}warmStart(t){var e;for(let i=0;i<t.length;i++){const s=t[i],n=s.bodyA,o=s.bodyB;if(n&&o){const a=(e=this.idToContactConstraint.get(s.id))!=null?e:[];for(const h of a)if(this.config.warmStart){const l=s.normal.scale(h.normalImpulse),c=s.tangent.scale(h.tangentImpulse),u=l.add(c);n.applyImpulse(h.point,u.negate()),o.applyImpulse(h.point,u)}else h.normalImpulse=0,h.tangentImpulse=0}}}solvePosition(t){var e;for(let i=0;i<this.config.positionIterations;i++)for(let s=0;s<t.length;s++){const n=t[s],o=n.bodyA,a=n.bodyB;if(o&&a){if(o.collisionType===M.Passive||a.collisionType===M.Passive)continue;const h=(e=this.idToContactConstraint.get(n.id))!=null?e:[];for(const l of h){const c=n.normal,u=Ut.FindContactSeparation(n,l.local),_=this.config.steeringFactor,f=-5,m=this.config.slop,p=B(_*(u+m),f,0),x=c.scale(-p*l.normalMass);if(o.collisionType===M.Active){const v=x.negate().scale(o.inverseMass);o.limitDegreeOfFreedom.includes(le.X)&&(v.x=0),o.limitDegreeOfFreedom.includes(le.Y)&&(v.y=0),o.globalPos=o.globalPos.add(v),o.limitDegreeOfFreedom.includes(le.Rotation)||(o.rotation-=l.aToContact.cross(x)*o.inverseInertia)}if(a.collisionType===M.Active){const v=x.scale(a.inverseMass);a.limitDegreeOfFreedom.includes(le.X)&&(v.x=0),a.limitDegreeOfFreedom.includes(le.Y)&&(v.y=0),a.globalPos=a.globalPos.add(v),a.limitDegreeOfFreedom.includes(le.Rotation)||(a.rotation+=l.bToContact.cross(x)*a.inverseInertia)}}}}}solveVelocity(t){var e;for(let i=0;i<this.config.velocityIterations;i++)for(let s=0;s<t.length;s++){const n=t[s],o=n.bodyA,a=n.bodyB;if(o&&a){if(o.collisionType===M.Passive||a.collisionType===M.Passive)continue;const h=Math.min(o.friction,a.friction),l=(e=this.idToContactConstraint.get(n.id))!=null?e:[];for(const c of l){let f=-c.getRelativeVelocity().dot(n.tangent)*c.tangentMass;const m=h*c.normalImpulse,p=B(c.tangentImpulse+f,-m,m);f=p-c.tangentImpulse,c.tangentImpulse=p;const x=n.tangent.scale(f);o.applyImpulse(c.point,x.negate()),a.applyImpulse(c.point,x)}for(const c of l){const _=c.getRelativeVelocity().dot(n.normal);let f=-c.normalMass*(_-c.originalVelocityAndRestitution);const m=Math.max(c.normalImpulse+f,0);f=m-c.normalImpulse,c.normalImpulse=m;const p=n.normal.scale(f);o.applyImpulse(c.point,p.negate()),a.applyImpulse(c.point,p)}}}}}class Qi extends Et{constructor(t,e){super(),this.world=t,this.physics=e,this.systemType=Pt.Update,this._physicsConfigDirty=!1,this.query=this.world.query({components:{all:[P,O]},tags:{not:this.physics.config.integration.onScreenOnly?["ex.offscreen"]:[]}}),e.$configUpdate.subscribe(()=>{this._physicsConfigDirty=!0})}update(t){let e,i;const s=this.query.entities,o=this.physics.config.substep;for(let a=0;a<s.length;a++){if(e=s[a].get(P),i=s[a].get(O),i.integration.onScreenOnly&&s[a].hasTag("ex.offscreen"))continue;const h=s[a].get(N);if(this._physicsConfigDirty&&h&&h.updatePhysicsConfig(this.physics.config.bodies),h!=null&&h.isSleeping)continue;const l=i.acc.clone();(h==null?void 0:h.collisionType)===M.Active&&(h!=null&&h.useGravity)&&l.addEqual(this.physics.config.gravity),s[a].parent||this.captureOldTransformWithChildren(s[a]),$r.integrate(e,i,l,t/o)}this._physicsConfigDirty&&(this._physicsConfigDirty=!1,this.query=this.world.query({components:{all:[P,O]},tags:{not:this.physics.config.integration.onScreenOnly?["ex.offscreen"]:[]}}))}captureOldTransformWithChildren(t){var e;(e=t.get(N))==null||e.captureOldTransform();for(let i=0;i<t.children.length;i++)this.captureOldTransformWithChildren(t.children[i])}}Qi.priority=Gt.Higher;class Ji extends Et{constructor(t,e){super(),this._physics=e,this.systemType=Pt.Update,this._configDirty=!1,this._lastFrameContacts=new Map,this._currentFrameContacts=new Map,this._arcadeSolver=new Fn(e.config.arcade),this._realisticSolver=new Dn(e.config.realistic),this._physics.$configUpdate.subscribe(()=>this._configDirty=!0),this._trackCollider=i=>this._processor.track(i),this._untrackCollider=i=>this._processor.untrack(i),this.query=t.query([P,tt]),this.query.entityAdded$.subscribe(i=>{const s=i.get(tt);s.$colliderAdded.subscribe(this._trackCollider),s.$colliderRemoved.subscribe(this._untrackCollider);const n=s.get();n&&this._processor.track(n)}),this.query.entityRemoved$.subscribe(i=>{const s=i.get(tt),n=s.get();s&&n&&this._processor.untrack(n)}),this._motionSystem=t.get(Qi)}get _processor(){return this._physics.collisionProcessor}initialize(t,e){this._engine=e.engine}update(t){var e,i,s,n;if(!this._physics.config.enabled)return;let o=[];for(let u=0;u<this.query.entities.length;u++){const f=this.query.entities[u].get(tt),m=f==null?void 0:f.get();if(f&&((e=f.owner)!=null&&e.isActive)&&m)if(f.update(),m instanceof at){const p=m.getColliders();m.compositeStrategy||(m.compositeStrategy=this._physics.config.colliders.compositeStrategy),o=o.concat(p)}else o.push(m)}this._processor.update(o,t);let a=this._processor.broadphase(o,t);this._currentFrameContacts.clear();let h=[];const l=this.getSolver(),c=this._physics.config.substep;for(let u=0;u<c;u++)if(u>0&&this._motionSystem.update(t),h.length&&(a=h.map(_=>new pt(_.colliderA,_.colliderB))),a.length){h=this._processor.narrowphase(a,(n=(s=(i=this._engine)==null?void 0:i.debug)==null?void 0:s.stats)==null?void 0:n.currFrame),h=l.solve(h);for(const _ of h){if(_.isCanceled())continue;const f=_.id.indexOf("|");if(f>0){const m=_.id.substring(f+1);this._currentFrameContacts.set(m,_)}else this._currentFrameContacts.set(_.id,_)}}this.runContactStartEnd(),this._lastFrameContacts.clear(),this._lastFrameContacts=new Map(this._currentFrameContacts);for(const u of this.query.entities){const _=u.get(tt);_&&_.processColliderRemoval()}}postupdate(){Ne.SeparationPool.done()}getSolver(){return this._configDirty&&(this._configDirty=!1,this._arcadeSolver=new Fn(this._physics.config.arcade),this._realisticSolver=new Dn(this._physics.config.realistic)),this._physics.config.solver===Ui.Realistic?this._realisticSolver:this._arcadeSolver}debug(t){this._processor.debug(t,0)}runContactStartEnd(){for(const[t,e]of this._currentFrameContacts)if(!this._lastFrameContacts.has(t)){const i=e.colliderA,s=e.colliderB,n=d.Side.fromDirection(e.mtv),o=d.Side.getOpposite(n);i.events.emit("collisionstart",new ni(i,s,n,e)),i.events.emit("contactstart",new Ii(i,s,n,e)),s.events.emit("collisionstart",new ni(s,i,o,e)),s.events.emit("contactstart",new Ii(s,i,o,e))}for(const[t,e]of this._lastFrameContacts)if(!this._currentFrameContacts.has(t)){const i=e.colliderA,s=e.colliderB,n=d.Side.fromDirection(e.mtv),o=d.Side.getOpposite(n);i.events.emit("collisionend",new ri(i,s,n,e)),i.events.emit("contactend",new Ri(i,s,n,e)),s.events.emit("collisionend",new ri(s,i,o,e)),s.events.emit("contactend",new Ri(s,i,o,e))}}}Ji.priority=Gt.Higher;class Fo{constructor(t){this.$configUpdate=new gt,this._configDirty=!1,this.config=t,this.$configUpdate.subscribe(e=>{this._configDirty=!0,N.updateDefaultPhysicsConfig(e.bodies)}),this._config.spatialPartition===hi.SparseHashGrid?this._collisionProcessor=new Mn(this._config.sparseHashGrid):this._collisionProcessor=new Li(this._config)}get config(){return Fh(this._config,t=>{this.$configUpdate.notifyAll(t)})}set config(t){this._config=t,this.$configUpdate.notifyAll(t)}get collisionProcessor(){if(this._configDirty){this._configDirty=!1;const t=this._collisionProcessor.getColliders();this._config.spatialPartition===hi.SparseHashGrid?this._collisionProcessor=new Mn(this._config.sparseHashGrid):this._collisionProcessor=new Li(this._config);for(const e of t)this._collisionProcessor.track(e)}return this._collisionProcessor}rayCast(t,e){return this.collisionProcessor.rayCast(t,e)}query(t){return this._collisionProcessor.query(t)}}var gi=(r=>(r.Fixed="Fixed",r.FitContainerAndFill="FitContainerAndFill",r.FitScreenAndFill="FitScreenAndFill",r.FitContainerAndZoom="FitContainerAndZoom",r.FitScreenAndZoom="FitScreenAndZoom",r.FitScreen="FitScreen",r.FillScreen="FillScreen",r.FitContainer="FitContainer",r.FillContainer="FillContainer",r))(gi||{});class Bn{static get SVGA(){return{width:800,height:600}}static get Standard(){return{width:1920,height:1080}}static get Atari2600(){return{width:160,height:192}}static get GameBoy(){return{width:160,height:144}}static get GameBoyAdvance(){return{width:240,height:160}}static get NintendoDS(){return{width:256,height:192}}static get NES(){return{width:256,height:224}}static get SNES(){return{width:256,height:244}}}const Pl={ScreenResize:"resize",PixelRatioChange:"pixelratio",FullScreenChange:"fullscreen"};class kn{constructor(t){this.events=new X,this._antialiasing=!0,this._canvasImageRendering="auto",this._resolutionStack=[],this._viewportStack=[],this._pixelRatioOverride=null,this._isFullscreen=!1,this._isDisposed=!1,this._logger=R.getInstance(),this._fullscreenChangeHandler=()=>{this._isDisposed||(this._isFullscreen=!this._isFullscreen,this._logger.debug("Fullscreen Change",this._isFullscreen),this.events.emit("fullscreen",{fullscreen:this.isFullscreen}))},this._pixelRatioChangeHandler=()=>{this._isDisposed||(this._logger.debug("Pixel Ratio Change",window.devicePixelRatio),this._listenForPixelRatio(),this._devicePixelRatio=this._calculateDevicePixelRatio(),this.applyResolutionAndViewport(),this.events.emit("pixelratio",{pixelRatio:this.pixelRatio}))},this._resizeHandler=()=>{if(this._isDisposed)return;const o=this.parent;this._logger.debug("View port resized"),this._setResolutionAndViewportByDisplayMode(o),this.applyResolutionAndViewport(),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})},this._devicePixelRatio=this._calculateDevicePixelRatio(),this._contentArea=new F,this._unsafeArea=new F;var e,i,s,n;this.viewport=t.viewport,this.resolution=(e=t.resolution)!=null?e:{...this.viewport},this._contentResolution=this.resolution,this._displayMode=(i=t.displayMode)!=null?i:"Fixed",this._canvas=t.canvas,this.graphicsContext=t.context,this._antialiasing=(s=t.antialiasing)!=null?s:this._antialiasing,this._canvasImageRendering=(n=t.canvasImageRendering)!=null?n:this._canvasImageRendering,this._browser=t.browser,this._pixelRatioOverride=t.pixelRatio,this._applyDisplayMode(),this._listenForPixelRatio(),this._canvas.addEventListener("fullscreenchange",this._fullscreenChangeHandler),this.applyResolutionAndViewport()}_listenForPixelRatio(){this._mediaQueryList&&!this._mediaQueryList.addEventListener&&this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._mediaQueryList=this._browser.window.nativeComponent.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this._mediaQueryList.addEventListener?this._mediaQueryList.addEventListener("change",this._pixelRatioChangeHandler,{once:!0}):this._mediaQueryList.addListener(this._pixelRatioChangeHandler)}dispose(){this._isDisposed||(this._isDisposed=!0,this.events.clear(),this._browser.window.off("resize",this._resizeHandler),this._browser.window.clear(),this._resizeObserver&&this._resizeObserver.disconnect(),this.parent.removeEventListener("resize",this._resizeHandler),this._mediaQueryList.removeEventListener?this._mediaQueryList.removeEventListener("change",this._pixelRatioChangeHandler):this._mediaQueryList.removeListener(this._pixelRatioChangeHandler),this._canvas.removeEventListener("fullscreenchange",this._fullscreenChangeHandler),this._canvas=null)}_calculateDevicePixelRatio(){return window.devicePixelRatio<1?1:window.devicePixelRatio||1}get pixelRatio(){return this._pixelRatioOverride?this._pixelRatioOverride:this._devicePixelRatio}get worldToPagePixelRatio(){if(this._canvas){const t=this.worldToPageCoordinates(w.Zero);return this.worldToPageCoordinates(b(1,0)).sub(t).x}else return 1}get pixelRatioOverride(){return this._pixelRatioOverride}set pixelRatioOverride(t){this._pixelRatioOverride=t}get isHiDpi(){return this.pixelRatio!==1}get displayMode(){return this._displayMode}get canvas(){return this._canvas}get parent(){switch(this.displayMode){case"FillContainer":case"FitContainer":case"FitContainerAndFill":case"FitContainerAndZoom":return this.canvas.parentElement||document.body;default:return window}}get resolution(){return this._resolution}set resolution(t){this._resolution=t}get viewport(){return this._viewport?this._viewport:this._resolution}set viewport(t){this._viewport=t}get aspectRatio(){return this._resolution.width/this._resolution.height}get scaledWidth(){return this._resolution.width*this.pixelRatio}get scaledHeight(){return this._resolution.height*this.pixelRatio}setCurrentCamera(t){this._camera=t}pushResolutionAndViewport(){this._resolutionStack.push(this.resolution),this._viewportStack.push(this.viewport),this.resolution={...this.resolution},this.viewport={...this.viewport}}peekViewport(){return this._viewportStack[this._viewportStack.length-1]}peekResolution(){return this._resolutionStack[this._resolutionStack.length-1]}popResolutionAndViewport(){this._resolutionStack.length&&this._viewportStack.length&&(this.resolution=this._resolutionStack.pop(),this.viewport=this._viewportStack.pop())}applyResolutionAndViewport(){if(this.graphicsContext instanceof $t&&!this.graphicsContext.checkIfResolutionSupported({width:this.scaledWidth,height:this.scaledHeight})&&(this._logger.warnOnce(`The currently configured resolution (${this.resolution.width}x${this.resolution.height}) and pixel ratio (${this.pixelRatio}) are too large for the platform WebGL implementation, this may work but cause WebGL rendering to behave oddly. Try reducing the resolution or disabling Hi DPI scaling to avoid this (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`),!this.pixelRatioOverride)){let s=Math.max(1,this.pixelRatio-.5),n=!1;for(;s>1&&!n;){s=Math.max(1,s-.5);const o=this._resolution.width*s,a=this._resolution.height*s;n=this.graphicsContext.checkIfResolutionSupported({width:o,height:a})}this.pixelRatioOverride=s,this._logger.warnOnce(`Scaled resolution too big attempted recovery! Pixel ratio was automatically reduced to (${this.pixelRatio}) to avoid 4k texture limit. Setting \`ex.Engine({pixelRatio: ...}) will override any automatic recalculation, do so at your own risk.\` (read more here https://excaliburjs.com/docs/screens#understanding-viewport--resolution).`)}this._canvas.width=this.scaledWidth,this._canvas.height=this.scaledHeight,this._canvasImageRendering==="auto"?this._canvas.style.imageRendering="auto":(this._canvas.style.imageRendering="pixelated",this._canvas.style.imageRendering===""&&(this._canvas.style.imageRendering="crisp-edges"));const t=this.viewport.widthUnit==="percent"?"%":"px",e=this.viewport.heightUnit==="percent"?"%":"px";this._canvas.style.width=this.viewport.width+t,this._canvas.style.height=this.viewport.height+e,this.graphicsContext.updateViewport(this.resolution),this.graphicsContext.resetTransform(),this.graphicsContext.smoothing=this._antialiasing,this.graphicsContext instanceof $i&&this.graphicsContext.scale(this.pixelRatio,this.pixelRatio),document.documentElement.style.setProperty("--ex-pixel-ratio",this.worldToPagePixelRatio.toString())}get antialiasing(){return this._antialiasing}set antialiasing(t){this._antialiasing=t,this.graphicsContext.smoothing=this._antialiasing}get isFullScreen(){return this._isFullscreen}get isFullscreen(){return this._isFullscreen}goFullScreen(t){return this.enterFullscreen(t)}enterFullscreen(t){var e,i,s,n,o,a;if(t){const h=document.getElementById(t);if(h!=null&&h.requestFullscreen||h!=null&&h.webkitRequestFullscreen){if(h.getAttribute("ex-fullscreen-listener")||(h.setAttribute("ex-fullscreen-listener","true"),h.addEventListener("fullscreenchange",this._fullscreenChangeHandler)),h.requestFullscreen)return(e=h.requestFullscreen())!=null?e:Promise.resolve();if(h.webkitRequestFullscreen)return(i=h.webkitRequestFullscreen())!=null?i:Promise.resolve()}}return(s=this._canvas)!=null&&s.requestFullscreen?(o=(n=this._canvas)==null?void 0:n.requestFullscreen())!=null?o:Promise.resolve():this._canvas.webkitRequestFullscreen?(a=this._canvas.webkitRequestFullscreen())!=null?a:Promise.resolve():(this._logger.warnOnce("Could not go fullscreen, is this an iPhone? Currently Apple does not support fullscreen on iPhones"),Promise.resolve())}exitFullScreen(){return this.exitFullscreen()}exitFullscreen(){return document.exitFullscreen()}_viewportToPixels(t){return{width:t.widthUnit==="percent"?this.canvas.offsetWidth:t.width,height:t.heightUnit==="percent"?this.canvas.offsetHeight:t.height}}pageToScreenCoordinates(t){let e=t.x,i=t.y;this._isFullscreen||(e-=oi(this._canvas).x,i-=oi(this._canvas).y);const s=this._viewportToPixels(this.viewport);if(this._isFullscreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const n=window.innerWidth/this.aspectRatio,o=(window.innerHeight-n)/2;i=(i-o)/n*s.height,e=e/window.innerWidth*s.width}else{const n=window.innerHeight*this.aspectRatio,o=(window.innerWidth-n)/2;e=(e-o)/n*s.width,i=i/window.innerHeight*s.height}return e=e/s.width*this.resolution.width,i=i/s.height*this.resolution.height,e=e-this.contentArea.left,i=i-this.contentArea.top,new w(e,i)}screenToPageCoordinates(t){let e=t.x,i=t.y;const s=this._viewportToPixels(this.viewport);if(e=e/this.resolution.width*s.width,i=i/this.resolution.height*s.height,this._isFullscreen)if(window.innerWidth/this.aspectRatio<window.innerHeight){const n=window.innerWidth/this.aspectRatio,o=(window.innerHeight-n)/2;i=i/s.height*n+o,e=e/s.width*window.innerWidth}else{const n=window.innerHeight*this.aspectRatio,o=(window.innerWidth-n)/2;e=e/s.width*n+o,i=i/s.height*window.innerHeight}return this._isFullscreen||(e+=oi(this._canvas).x,i+=oi(this._canvas).y),new w(e,i)}screenToWorldCoordinates(t){return t=t.add(b(this.contentArea.left,this.contentArea.top)),this._camera?this._camera.inverse.multiply(t):t.sub(b(this.resolution.width/2,this.resolution.height/2))}worldToScreenCoordinates(t){return this._camera?this._camera.transform.multiply(t):t.add(b(this.resolution.width/2,this.resolution.height/2))}pageToWorldCoordinates(t){const e=this.pageToScreenCoordinates(t);return this.screenToWorldCoordinates(e)}worldToPageCoordinates(t){const e=this.worldToScreenCoordinates(t);return this.screenToPageCoordinates(e)}getWorldBounds(){return F.fromDimension(this.resolution.width,this.resolution.height,w.Half).scale(b(1/this._camera.zoom,1/this._camera.zoom)).rotate(this._camera.rotation).translate(this._camera.drawPos)}getScreenBounds(){return F.fromDimension(this.resolution.width,this.resolution.height,w.Zero,w.Zero)}get canvasWidth(){return this.canvas.width}get halfCanvasWidth(){return this.canvas.width/2}get canvasHeight(){return this.canvas.height}get halfCanvasHeight(){return this.canvas.height/2}get drawWidth(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get width(){return this._camera?this.resolution.width/this._camera.zoom:this.resolution.width}get halfDrawWidth(){return this.drawWidth/2}get drawHeight(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get height(){return this._camera?this.resolution.height/this._camera.zoom:this.resolution.height}get halfDrawHeight(){return this.drawHeight/2}get center(){return b(this.halfDrawWidth,this.halfDrawHeight)}get contentArea(){return this._contentArea}get unsafeArea(){return this._unsafeArea}_computeFit(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=this.aspectRatio;let e=0,i=0;window.innerWidth/t<window.innerHeight?(e=window.innerWidth,i=window.innerWidth/t):(e=window.innerHeight*t,i=window.innerHeight),this.viewport={width:e,height:i},this._contentArea=F.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this._unsafeArea=F.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitScreenAndFill(){document.body.style.margin="0px",document.body.style.overflow="hidden";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndFill(t,e),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitContainerAndFill(){this.canvas.style.width="100%",this.canvas.style.height="100%",this._computeFitAndFill(this.canvas.offsetWidth,this.canvas.offsetHeight,{width:100,widthUnit:"percent",height:100,heightUnit:"percent"}),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitAndFill(t,e,i){if(this.viewport=i!=null?i:{width:t,height:e},t/e<=this._contentResolution.width/this._contentResolution.height){this.resolution={width:t*this._contentResolution.width/t,height:t*this._contentResolution.width/t*e/t};const s=(this.resolution.height-this._contentResolution.height)/2;this._contentArea=new F({top:s,left:0,right:this._contentResolution.width,bottom:this.resolution.height-s}),this._unsafeArea=new F({top:-s,left:0,right:this._contentResolution.width,bottom:this.resolution.height+s})}else{this.resolution={width:e*this._contentResolution.height/e*t/e,height:e*this._contentResolution.height/e};const s=(this.resolution.width-this._contentResolution.width)/2;this._contentArea=new F({top:0,left:s,right:this.resolution.width-s,bottom:this._contentResolution.height}),this._unsafeArea=new F({top:0,left:-s,right:this.resolution.width+s,bottom:this._contentResolution.height})}}_computeFitScreenAndZoom(){document.body.style.margin="0px",document.body.style.overflow="hidden",this.canvas.style.position="absolute";const t=window.innerWidth,e=window.innerHeight;this._computeFitAndZoom(t,e),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitContainerAndZoom(){this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.position="relative";const t=this.canvas.parentElement;t.style.overflow="hidden";const{offsetWidth:e,offsetHeight:i}=this.canvas;this._computeFitAndZoom(e,i),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_computeFitAndZoom(t,e){const i=this.aspectRatio;let s=0,n=0;t/i<e?(s=t,n=t/i):(s=e*i,n=e);const o=t/s,a=e/n,h=Math.max(o,a),l=s*h,c=n*h;l>t?this.canvas.style.left=-(l-t)/2+"px":this.canvas.style.left="",c>e?this.canvas.style.top=-(c-e)/2+"px":this.canvas.style.top="",this.viewport={width:l,height:c};const u=F.fromDimension(this.viewport.width,this.viewport.height,w.Zero);if(this.viewport.width>t){const _=(this.viewport.width-t)/this.viewport.width*this.resolution.width;u.top=0,u.left=_/2,u.right=this.resolution.width-_/2,u.bottom=this.resolution.height}if(this.viewport.height>e){const _=(this.viewport.height-e)/this.viewport.height*this.resolution.height;u.top=_/2,u.left=0,u.bottom=this.resolution.height-_/2,u.right=this.resolution.width}this._contentArea=u}_computeFitContainer(){const t=this.aspectRatio;let e=0,i=0,s="pixel",n="pixel";const o=this.canvas.parentElement;o.clientWidth/t<o.clientHeight?(this.canvas.style.width="100%",e=100,s="percent",i=this.canvas.offsetWidth/t):(this.canvas.style.height="100%",i=100,n="percent",e=this.canvas.offsetHeight*t),this.viewport={width:e,widthUnit:s,height:i,heightUnit:n},this._contentArea=F.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this.events.emit("resize",{resolution:this.resolution,viewport:this.viewport})}_applyDisplayMode(){this._setResolutionAndViewportByDisplayMode(this.parent),this.parent instanceof Window?this._browser.window.on("resize",this._resizeHandler):(this._resizeObserver=new ResizeObserver(()=>{this._resizeHandler()}),this._resizeObserver.observe(this.parent)),this.parent.addEventListener("resize",this._resizeHandler)}_setResolutionAndViewportByDisplayMode(t){this.displayMode==="FillContainer"&&(this.canvas.style.width="100%",this.canvas.style.height="100%",this.viewport={width:100,widthUnit:"percent",height:100,heightUnit:"percent"},this.resolution={width:this.canvas.offsetWidth,height:this.canvas.offsetHeight}),this.displayMode==="FillScreen"&&(document.body.style.margin="0px",document.body.style.overflow="hidden",this.resolution={width:t.innerWidth,height:t.innerHeight},this.viewport=this.resolution),this._contentArea=F.fromDimension(this.resolution.width,this.resolution.height,w.Zero),this.displayMode==="FitScreen"&&this._computeFit(),this.displayMode==="FitContainer"&&this._computeFitContainer(),this.displayMode==="FitScreenAndFill"&&this._computeFitScreenAndFill(),this.displayMode==="FitContainerAndFill"&&this._computeFitContainerAndFill(),this.displayMode==="FitScreenAndZoom"&&this._computeFitScreenAndZoom(),this.displayMode==="FitContainerAndZoom"&&this._computeFitContainerAndZoom()}}class pi{static create(){return this._INSTANCE||(window.AudioContext||window.webkitAudioContext)&&(this._INSTANCE=new AudioContext),this._INSTANCE}}function El(r){return!!r.playbackState}const Do=class fs{static unlock(){return new Promise((e,i)=>{if(fs._UNLOCKED||!pi.create())return e(!0);const s=setTimeout(()=>{R.getInstance().warn("Excalibur was unable to unlock the audio context, audio probably will not play in this browser."),e(!1)},200),n=pi.create();n.resume().then(()=>{const o=n.createBuffer(1,1,22050),a=n.createBufferSource();let h=!1;a.buffer=o,a.connect(n.destination),a.onended=()=>h=!0,a.start(0),setTimeout(()=>{El(a)?(a.playbackState===a.PLAYING_STATE||a.playbackState===a.FINISHED_STATE)&&(fs._UNLOCKED=!0):(n.currentTime>0||h)&&(fs._UNLOCKED=!0)},0),clearTimeout(s),e(!0)},()=>{i()})})}static isUnlocked(){return this._UNLOCKED}};Do._UNLOCKED=!1;let Bo=Do;class Ln{}Ln.type={any:"",blob:"blob",json:"json",text:"text",document:"document",arraybuffer:"arraybuffer"};class Ki{constructor(){this.states=new Map}get currentState(){return this._currentState}set currentState(t){this._currentState=t}static create(t,e){const i=new Ki;i.data=e;for(const s in t.states)i.states.set(s,{name:s,...t.states[s]});for(const s of i.states.values())for(const n of s.transitions)if(n!=="*"&&!i.states.has(n))throw Error(`Invalid state machine, state [${s.name}] has a transition to another state that doesn't exist [${n}]`);return i.currentState=i.startState=i.states.get(t.start),i}in(t){return this.currentState.name===t}go(t,e){var i,s;if(this.currentState.transitions.includes(t)||this.currentState.transitions.includes("*")){const n=this.states.get(t);return this.currentState.onExit&&((i=this.currentState)==null?void 0:i.onExit({to:n.name,data:this.data}))===!1||n!=null&&n.onEnter&&(n==null?void 0:n.onEnter({from:this.currentState.name,eventData:e,data:this.data}))===!1?!1:(this.currentState=n,(s=this.currentState)!=null&&s.onState&&this.currentState.onState(),!0)}return!1}update(t){this.currentState.onUpdate&&this.currentState.onUpdate(this.data,t)}save(t){localStorage.setItem(t,JSON.stringify({currentState:this.currentState.name,data:this.data}))}restore(t){const e=JSON.parse(localStorage.getItem(t));this.currentState=this.states.get(e.currentState),this.data=e.data}}class ko{constructor(t){this._src=t,this._audioContext=pi.create(),this._volumeNode=this._audioContext.createGain(),this._playingFuture=new wt,this._stateMachine=Ki.create({start:"STOPPED",states:{PLAYING:{onEnter:({data:e})=>{this._createNewBufferSource(),this._handleEnd(),this.loop?this._instance.start(0,e.pausedAt*this._playbackRate):this._instance.start(0,e.pausedAt*this._playbackRate,this.duration),e.startedAt=this._audioContext.currentTime-e.pausedAt,e.pausedAt=0},onState:()=>this._playStarted(),onExit:({to:e})=>{e==="STOPPED"&&this._playingFuture.resolve(!0),this._instance.onended=null,this._instance.disconnect(),this._instance.stop(0),this._instance=null},transitions:["STOPPED","PAUSED","SEEK"]},SEEK:{onEnter:({eventData:e,data:i})=>{i.pausedAt=(e!=null?e:0)/this._playbackRate,i.startedAt=0},transitions:["*"]},STOPPED:{onEnter:({data:e})=>{e.pausedAt=0,e.startedAt=0,this._playingFuture.resolve(!0)},transitions:["PLAYING","PAUSED","SEEK"]},PAUSED:{onEnter:({data:e})=>{e.pausedAt=this._audioContext.currentTime-e.startedAt},transitions:["PLAYING","STOPPED","SEEK"]}}},{startedAt:0,pausedAt:0}),this._volume=1,this._loop=!1,this._playStarted=()=>{},this._playbackRate=1,this._createNewBufferSource()}_createNewBufferSource(){this._instance=this._audioContext.createBufferSource(),this._instance.buffer=this._src,this._instance.loop=this.loop,this._instance.playbackRate.value=this._playbackRate,this._instance.connect(this._volumeNode),this._volumeNode.connect(this._audioContext.destination)}_handleEnd(){this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)})}set loop(t){this._loop=t,this._instance&&(this._instance.loop=t,this.loop||(this._instance.onended=()=>{this._playingFuture.resolve(!0)}))}get loop(){return this._loop}set volume(t){t=B(t,0,1),this._volume=t,this._stateMachine.in("PLAYING")&&this._volumeNode.gain.setTargetAtTime?this._volumeNode.gain.setTargetAtTime(t,this._audioContext.currentTime,.1):this._volumeNode.gain.value=t}get volume(){return this._volume}get duration(){var t;return(t=this._duration)!=null?t:this.getTotalPlaybackDuration()}set duration(t){this._duration=t}isPlaying(){return this._stateMachine.in("PLAYING")}isPaused(){return this._stateMachine.in("PAUSED")||this._stateMachine.in("SEEK")}isStopped(){return this._stateMachine.in("STOPPED")}play(t=()=>{}){return this._playStarted=t,this._stateMachine.go("PLAYING"),this._playingFuture.promise}pause(){this._stateMachine.go("PAUSED")}stop(){this._stateMachine.go("STOPPED")}seek(t){this._stateMachine.go("PAUSED"),this._stateMachine.go("SEEK",t)}getTotalPlaybackDuration(){return this._src.duration}getPlaybackPosition(){const{pausedAt:t,startedAt:e}=this._stateMachine.data;return t?t*this._playbackRate:e?(this._audioContext.currentTime-e)*this._playbackRate:0}set playbackRate(t){this._instance.playbackRate.value=this._playbackRate=t}get playbackRate(){return this._instance.playbackRate.value}}class Un extends k{constructor(t,e="MediaEvent"){super(),this.target=t,this._name=e}set bubbles(t){}get bubbles(){return!1}get _path(){return null}set _path(t){}stopPropagation(){}action(){}propagate(){}layPath(t){}}class Ae extends Un{constructor(t,e){super(t,"NativeSoundEvent"),this.track=e}}class Lo extends Un{constructor(t,e){super(t,"NativeSoundProcessedEvent"),this._processedData=e,this.data=this._processedData}}function Il(r){try{const t=new Audio,e=/.*\.([A-Za-z0-9]+)(?:(?:\?|\#).*)*$/,i=r.match(e)[1];return!!t.canPlayType("audio/"+i)}catch(t){return R.getInstance().warn("Cannot determine audio support, assuming no support for the Audio Tag",t),!1}}const Rl={VolumeChange:"volumechange",Processed:"processed",Pause:"pause",Stop:"stop",PlaybackEnd:"playbackend",Resume:"resume",PlaybackStart:"playbackstart"};function Ml(r){var t;return!!((t=r[0])!=null&&t.paths)}class zn{constructor(...t){this.events=new X,this.logger=R.getInstance(),this._loop=!1,this._volume=1,this._isStopped=!1,this._tracks=[],this._wasPlayingOnHidden=!1,this._playbackRate=1,this._audioContext=pi.create();let e;Ml(t)?e=t[0]:e={paths:t},this._resource=new li("",Ln.type.arraybuffer);const{volume:i,position:s,playbackRate:n,loop:o,bustCache:a,duration:h}=e;this.volume=i!=null?i:this.volume,this.playbackRate=n!=null?n:this.playbackRate,this.loop=o!=null?o:this.loop,this.duration=h!=null?h:this.duration,this.bustCache=a!=null?a:this.bustCache,this.position=s!=null?s:this.position;for(const l of e.paths)if(Il(l)){this.path=l;break}this.path||(this.logger.warn("This browser does not support any of the audio files specified:",e.paths.join(", ")),this.logger.warn("Attempting to use",e.paths[0]),this.path=e.paths[0])}set loop(t){this._loop=t;for(const e of this._tracks)e.loop=this._loop;this.logger.debug("Set loop for all instances of sound",this.path,"to",this._loop)}get loop(){return this._loop}set volume(t){this._volume=t;for(const e of this._tracks)e.volume=this._volume;this.events.emit("volumechange",new Ae(this)),this.logger.debug("Set loop for all instances of sound",this.path,"to",this._volume)}get volume(){return this._volume}get duration(){return this._duration}set duration(t){this._duration=t}get instances(){return this._tracks}get path(){return this._resource.path}set path(t){this._resource.path=t}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}isLoaded(){return!!this.data}async load(){var t,e;if(this.data)return this.data;const i=await this._resource.load(),s=await this.decodeAudio(i.slice(0));return this._duration=(e=(t=this._duration)!=null?t:s==null?void 0:s.duration)!=null?e:void 0,this.events.emit("processed",new Lo(this,s)),this.data=s}async decodeAudio(t){try{return await this._audioContext.decodeAudioData(t.slice(0))}catch(e){return this.logger.error("Unable to decode this browser may not fully support this format, or the file may be corrupt, if this is an mp3 try removing id3 tags and album art from the file."),await Promise.reject()}}wireEngine(t){t&&(this._engine=t,this._engine.on("hidden",()=>{t.pauseAudioWhenHidden&&this.isPlaying()&&(this._wasPlayingOnHidden=!0,this.pause())}),this._engine.on("visible",()=>{t.pauseAudioWhenHidden&&this._wasPlayingOnHidden&&(this.play(),this._wasPlayingOnHidden=!1)}),this._engine.on("start",()=>{this._isStopped=!1}),this._engine.on("stop",()=>{this.stop(),this._isStopped=!0}))}instanceCount(){return this._tracks.length}isPlaying(){return this._tracks.some(t=>t.isPlaying())}isPaused(){return this._tracks.some(t=>t.isPaused())}isStopped(){return this._tracks.some(t=>t.isStopped())}play(t){return this.isLoaded()?this._isStopped?(this.logger.warn("Cannot start playing. Engine is in a stopped state."),Promise.resolve(!1)):(this.volume=t!=null?t:this.volume,this.isPaused()?this._resumePlayback():(this.position&&this.seek(this.position),this._startPlayback())):(this.logger.warn("Cannot start playing. Resource",this.path,"is not loaded yet"),Promise.resolve(!0))}pause(){if(this.isPlaying()){for(const t of this._tracks)t.pause();this.events.emit("pause",new Ae(this)),this.logger.debug("Paused all instances of sound",this.path)}}stop(){for(const t of this._tracks)t.stop();this.events.emit("stop",new Ae(this)),this._tracks.length=0,this.logger.debug("Stopped all instances of sound",this.path)}get playbackRate(){return this._playbackRate}set playbackRate(t){this._playbackRate=t,this._tracks.forEach(e=>{e.playbackRate=this._playbackRate})}seek(t,e=0){this._tracks.length===0&&this._getTrackInstance(this.data),this._tracks[e].seek(t)}getTotalPlaybackDuration(){return this.isLoaded()?this.data.duration:(this.logger.warnOnce(`Sound from ${this.path} is not loaded, cannot return total playback duration.Did you forget to add Sound to a loader? https://excaliburjs.com/docs/loaders/`),0)}getPlaybackPosition(t=0){return this._tracks.length?this._tracks[t].getPlaybackPosition():0}getTrackId(t){return this._tracks.indexOf(t)}async _resumePlayback(){if(this.isPaused()){const t=[];for(const e of this._tracks)t.push(e.play().then(()=>(this._tracks.splice(this.getTrackId(e),1),!0)));this.events.emit("resume",new Ae(this)),this.logger.debug("Resuming paused instances for sound",this.path,this._tracks),await Promise.all(t)}return!0}async _startPlayback(){const t=this._getTrackInstance(this.data),e=await t.play(()=>{this.events.emit("playbackstart",new Ae(this,t)),this.logger.debug("Playing new instance for sound",this.path)});this.events.emit("playbackend",new Ae(this,t));const i=this.getTrackId(t);return i!==-1&&this._tracks.splice(i,1),e}_getTrackInstance(t){var e;const i=new ko(t);return i.loop=this.loop,i.volume=this.volume,i.duration=(e=this.duration)!=null?e:0,i.playbackRate=this._playbackRate,this._tracks.push(i),i}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Fl={BeforeLoad:"beforeload",AfterLoad:"afterload",UserAction:"useraction",LoadResourceStart:"loadresourcestart",LoadResourceEnd:"loadresourceend"};function On(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class mi{constructor(t){this.events=new X,this.canvas=new Yi({filtering:mt.Blended,smoothing:!0,cache:!1,draw:this.onDraw.bind(this)}),this._resources=[],this._numLoaded=0,this._loaded=!1,this._isLoading=!1,this._totalTimeMs=0,this._resourcesLoadedFuture=new wt,this._loaderCompleteFuture=new wt;var e;t&&((e=t.loadables)!=null&&e.length)&&this.addResources(t.loadables)}get resources(){return this._resources}onInitialize(t){this.engine=t,this.canvas.width=this.engine.screen.resolution.width,this.canvas.height=this.engine.screen.resolution.height}async onUserAction(){return await Promise.resolve()}async onBeforeLoad(){}async onAfterLoad(){await Di(500,this.engine.clock)}addResource(t){this._resources.push(t),this._loaded=!1}addResources(t){let e=0;const i=t.length;for(e;e<i;e++)this.addResource(t[e]);this._loaded=!1}markResourceComplete(){this._numLoaded++}get progress(){const t=this._resources.length;return t>0?B(this._numLoaded,0,t)/t:1}isLoaded(){return this._loaded||this._resources.length===0}onUpdate(t,e){this._totalTimeMs+=e}onDraw(t){const e=this._totalTimeMs/1e3;t.fillStyle=T.Black.toRGBA(),t.fillRect(0,0,this.engine.screen.resolution.width,this.engine.screen.resolution.height),t.save(),t.translate(this.engine.screen.resolution.width/2,this.engine.screen.resolution.height/2);const i=e*10;t.strokeStyle="white",t.lineWidth=10,t.lineCap="round",t.arc(0,0,40,i,i+Math.PI*3/2),t.stroke(),t.fillStyle="white",t.font="16px sans-serif";const s=(this.progress*100).toFixed(0)+"%",n=t.measureText(s),o=Math.abs(n.actualBoundingBoxLeft)+Math.abs(n.actualBoundingBoxRight),a=Math.abs(n.actualBoundingBoxAscent)+Math.abs(n.actualBoundingBoxDescent);t.fillText(s,-o/2,a/2),t.restore()}areResourcesLoaded(){return this._resources.length===0?Promise.resolve():this._resourcesLoadedFuture.promise}async load(){if(this._isLoading)return this._loaderCompleteFuture.promise;if(this.isLoaded())return this.data=this._resources;this._isLoading=!0,this._loaderCompleteFuture=new wt,await this.onBeforeLoad(),this.events.emit("beforeload"),this.canvas.flagDirty(),await Promise.all(this._resources.filter(t=>!t.isLoaded()).map(async t=>{this.events.emit("loadresourcestart",t),await t.load().finally(()=>{this._numLoaded++,this.canvas.flagDirty(),this.events.emit("loadresourceend",t)})}));for(const t of this._resources)t instanceof zn&&t.wireEngine(this.engine);return this._resourcesLoadedFuture.resolve(),this.canvas.flagDirty(),await this.onUserAction(),this.events.emit("useraction"),await Bo.unlock(),await this.onAfterLoad(),this.events.emit("afterload"),this._isLoading=!1,this._loaded=!0,this._loaderCompleteFuture.resolve(this._resources),this.data=this._resources}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}const Dl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdQAAAB2CAYAAABxhGI9AAAACXBIWXMAAAsSAAALEgHS3X78AAAKnUlEQVR42u3dP2wjSx0H8N8hJIonIRmJjsq0SBR+BQ1dcqKhe0lD77SvSwpKkJKGPulpktfRIMUdEqKIqV57rpAokM4dbSiyq7ONPTP7x39ifz7SFbnEnp3xer47O7uzH15fXwMA6OYHmgAABCoACFQAEKgAgEAFAIEKAAIVAAQqACBQAUCgAoBABQCBCgAIVAAQqAAgUAFAoAIAAhUABCoACFQAEKgAgECFLbmOiNeFf2PbAyz68Pr6qhUgbRwR92v+/zwiJrYHMEKFMmcN///UtgcQqFBk1PD/97U9Qx8VCFSgu4EmAIEKAAIVAAQqACBQ4Z25jojP8eX+0WtNAgIVaOY+Im5j+eKh24h41jQgUIEyZ7F5NaPU7wCBCiwYd/w9cOB+qAlgJ3KLLow0EV198803RWvJfvfddx+0lhEqHKu5JgAjVCBvlhmFzjQRXUekHz9+TP79y8uLRjNChXfvoePvAYEKxNtj1e42/O5JoIJABcrdRMRVLM+X3kTEpaaB988cKuzWg9EobTWdMx0Oly8uN4dqhAoARqgnaN3arHfqu7OyH8ItKLVB/P+CEfMTHyGPY3npx1m8zWGDEeoBfUk/xdti57dr/r1Wv2+6EPow3tZ5rRdS72s1neuF97xvWd+XTH0/V+UMttDWqbI/r2nrxfp+jv2uSjSO7S+OXy/A/3lN+9xX5T5HxEUPZZ0tfB71+w57eJ/HFu+z+jkv1u92YX9fbI/HhX3JA9rp5MPr66tWaG9UfUGbrHIzi7cLUyYFf/tpTady03EEeL8mUJ6i7MKYNvWNqr4Pe2jradXO60LrvPAz2PQ5RPX684ah8dxD+2zantnCgVipSVV+m/tgB9W2DDq2Sx/vM95wcHhZhWVJm8yrv58cSgfTdc70+++/X/r522+/tUKSEepBqo+om4ZLPerMjUwuNnQCtx1GWJtee1FwdD5uWd86xLs8UaVt2aNEO1/saZ/Z5rYMW4zq6v34rGV9Bg3q2eZ9SkeNm9qwyUh30OPIHYFKx5FG03C7znSOqYBq+qW/zpQ3anH037TNHluG6f0WPsPhHvab4QFty7ogOeuxDYcNy2/zu2214WNYWxmBurNO8bGn97pNBOO8xy/9uCorZZ4I2r4C7aJgO7ZV9iE49Dm6NvOWx+pWE9CUq3zbdTp9doz38TbXtzqH9RT5CyWe422OaZoZGeZCabrhPQY9HjwsjpTvCg4YtlE2+Ta/j2bzn8fqrDqgm+6yUHOmAvWUjAtGhbNYvsBknDnqH1Qhc7VmxHgeb/NbudA5j/UXlYwif2p6luhAc9teu1npiHKnDs8if6tCm7JLX3NKpgttXe9ruc9mHMd7a83iwdxF5vt8tutARaCeklRnNK9C8WnNF7geJQ4T4XG3JhSnVdilQrG+yOnrlVHfsEGYzhNBn7Lu6tS7+HJafJQ4EMiNlNqWXZ9WPvVgnVYHG5M1ByDXkT6leX2EgTqJtyt45yv7S2qO3sEZjZhDLXeR+YKdJ0Zdk8QocvH9N732KrNtq+FZ/zzIHABcJrYpd+Xv14lOd5ap76SgrduW/VTQ1qcQpqnbgu4ifZvUMNpd9XuoZmvCtPaQ2Y/BCHVLgbrJTeRPDdVf6pfMKDU2fOkHmVFFfXr3MsouLsnNvV5kRoe5+s431PeuoKPqWnaurY/ZPBEeqwceN4l96iwO6H7Mjq4y7VGPVNe10VaZMzVCPVWpI/Z6FZbcv5fMqGCU+dLfFGzj58jP8+bCdJCo7yzKTwdOF0bu9Ug7V4c+yz7FJfYeGoysUss0HssIdVZwYLDujMqlESoCdTtGsZtbHnJBeNdDSJSs0jTKdMJN1HNX54Wv7bvsU9NkVJVa13dX+/wuArV0X/l5RHyo/lnfF4G6p6DrS0kHdtXhy35TGErDPYZUn2WfWqDOo/lVqdMD2O/hKJhD7S/odukymq9s02QN4EEPR/zbaOumZc+r15zK1Zqznl9jsfiemTM1QmV3HUuTkedlg9HIQzRbUD93dfC+2tpj2fIHEH2+RqCCQH13gZq7hWXTNpVu19OB1fc9nQ0AKOKUb5lU0P1kDyOneoWk0lOZ9cIP0x7qu8+2BhCoR2wYu1+e7DmaXzBSsu5vaX1ne2zrpmUPTmxf7PM1Dm4y/vC7ny7Nif7+z/9ZmtM0Z3panPLtPmra9f16bcK0Dpbnwk43Vd/RHtu6zfNQTy1QBy3aqG2g9nVmxml+BOoJyT3NpWmn9xhfFnu4bvDa+44BXhqqfdf3uUF9+yz77AT31Yue2mjecYQ62NLfgkA9ghHqLNEhNem4H1c6vdyDxhf/bpz5m4coW/c39wi6VH2bPtHlcaV9cvXts+zxCe6rTeqc2ndL7uGd93QwM9bFcAzMoZZ7SgTBbWx+asui61h/iq1+RmjqdbnQXQ3T1DNQ63V/U9ucqm/pMzPb1rePsk/1iTOjgvatR4W3Lc8ULB78pELyrnAfeTcj1NU509/86mfJ33/8+Mf00a05UyPUEw7UVCeWG/WNEiExyHRMt5ltW30izUPk18ytt7lNfc8i//DvtvXto+ySA5BjljsLUF8lPkqMPEtW1JomDsiGBZ9Byb4NAvUITSN9GuwsIj6t6UTOqk7jJREkmzqli8xIs96udSO20sX0H1vW92IL9e1a9rgqVyf91gbPsTy9UD9n9lOkT8k+RfkFR5PMNqxOcdSf32PBvg3vilO+zdxE+okx9Wm0ph36XYsRZCpMF993GOk5qvqB3Dct6jvssb67KvuUNJ3frw92bhr8/STSF0JdRPMLpUCgnsgo9S76PZ246ZFk1wWvK5m3vVoYvW1Sz7nN91jfXbQ1ZQc7TW6HeaoOalypG/8/p/rP1aNAc6ZHzSnfdqPUPhdy2PQw6Nz9gSVhuhiqueUHR3uu7y7K3rdDX4u46ZrPbUa0IFBZ0seKQ3XQTRt2vm3W/a2DbNKys++rvm3ep6+y1x2UdP3bWU9lzra47U1GmlctX/sQ23t+aOlByLTh/4NAPaCRxtcdO5HLSJ/6vNtCwGx67VPmPbvWd1q9frKHtp4kAqRJ2HR9j762JfX3bZ//elPtj13PPDx1+D5tqk/Xi6NO8SHz7MmH19dXrdBNfVFP6T2PT1UHNit87/t4m5+aRH+nQBdvqyhZDKJLfZs8h7XPsqdV2ZOV+tanKB8aln0dyxdAXbV4j4gvt4oMOrbP6vbU73NW7TMlbdTnPrWpfqXfh9HKZ9vke7KuTeZRNtXRSe6+1FV//ce/ln5eXfsXgcqXzr6+9261M3moOoa7E6nvTZTfy7iNsmfb7kjfgXGsvxe0vihsEts9HTquPpt1q1vtahu2TqAiUAEEKj0zhwoARqgAu/OnX/442WH+9xc/Wvr58re/Tr7f41/+ZsRqhAoACFQAEKgAcHjMoQJskJsz/eqrr5Z+vvr7v5fmQFevAl5lztQIFQAQqAAgUAHgIJlDBdhgdQ41N2eKESoAIFABQKACwFEwhwoARqgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAEKgAgUAFAoAKAQAUAgQoACFQAEKgAIFABQKACAAIVAAQqAAhUABCoAIBABQCBCgACFQAQqAAgUAFAoAKAQAUAlvwPcFDns1DsH4sAAAAASUVORK5CYII=",Bl='button#excalibur-play{display:inline-block;position:relative;z-index:999;border-radius:6px;border:none;padding:1rem 1.5rem 1rem 4rem;margin:0;text-decoration:none;background:#00b233;color:#fff;font-family:sans-serif;font-size:2rem;white-space:nowrap;line-height:1;cursor:pointer;text-align:center;transition:background .25s ease-in-out,transform .15s ease;-webkit-appearance:none;-moz-appearance:none;-webkit-animation:excalibur-button-fadein .2s;-moz-animation:excalibur-button-fadein .2s;-ms-animation:excalibur-button-fadein .2s;-o-animation:excalibur-button-fadein .2s;animation:excalibur-button-fadein .2s}button#excalibur-play:after{position:absolute;content:"";border:8px solid;border-color:transparent transparent transparent white;left:35px;top:24px;width:0;height:0}button#excalibur-play:before{position:absolute;content:"";border:3px solid;left:19px;top:14px;border-radius:20px;width:30px;height:30px}button#excalibur-play:hover,button#excalibur-play:focus{background:#00982c}button#excalibur-play:focus{outline:1px solid #fff;outline-offset:-4px}button#excalibur-play:active{transform:scale(.99)}@keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-moz-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-webkit-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-ms-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}@-o-keyframes excalibur-button-fadein{0%{opacity:0}to{opacity:1}}',Uo=class Ua extends mi{constructor(t){const e=Array.isArray(t)?{loadables:t}:t;super(e),this._logger=R.getInstance(),this._originalOptions={loadables:[]},this.events=new X,this._playButtonShown=!1,this.logo=Dl,this.logoWidth=468,this.logoHeight=118,this.loadingBarColor=T.White,this.backgroundColor="#176BAA",this._imageLoaded=new wt,this.suppressPlayButton=!1,this._playButtonStyles=Bl,this.playButtonText="Play game",this.startButtonFactory=()=>{let i=document.getElementById("excalibur-play");return i||(i=document.createElement("button")),i.id="excalibur-play",i.textContent=this.playButtonText,i.style.display="none",i},this._originalOptions={...Ua._DEFAULT_LOADER_OPTIONS,...e}}get _image(){return this._imageElement||(this._imageElement=new Image,this._imageElement.onload=()=>this._imageLoaded.resolve(),this._imageElement.src=this.logo),this._imageElement}get playButtonRootElement(){return this._playButtonRootElement}get playButtonElement(){return this._playButtonElement}get _playButton(){const t=document.getElementById("excalibur-play-root");return t&&(this._playButtonRootElement=t),this._playButtonRootElement||(this._playButtonRootElement=document.createElement("div"),this._playButtonRootElement.id="excalibur-play-root",this._playButtonRootElement.style.position="absolute",document.body.appendChild(this._playButtonRootElement)),this._styleBlock||(this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._playButtonStyles,document.head.appendChild(this._styleBlock)),this._playButtonElement||(this._playButtonElement=this.startButtonFactory(),this._playButtonRootElement.appendChild(this._playButtonElement)),this._playButtonElement}onInitialize(t){this.engine=t,this.screen=t.screen,this.canvas.width=this.engine.canvas.width,this.canvas.height=this.engine.canvas.height,this.screen.events.on("resize",()=>{this.canvas.width=this.engine.canvas.width,this.canvas.height=this.engine.canvas.height})}async showPlayButton(){var t,e;if(this.suppressPlayButton)this.hidePlayButton(),await Di(500,(t=this.engine)==null?void 0:t.clock);else{const i=()=>{try{this._positionPlayButton()}catch(n){}};return(e=this.engine)!=null&&e.browser&&this.engine.browser.window.on("resize",i),this._playButtonShown=!0,this._playButton.style.display="block",document.body.addEventListener("keyup",n=>{n.key==="Enter"&&this._playButton.click()}),this._positionPlayButton(),await new Promise(n=>{const o=a=>{var h;if(a.stopPropagation(),this.hidePlayButton(),(h=this.engine)!=null&&h.browser&&this.engine.browser.window.off("resize",i),this._originalOptions.fullscreenAfterLoad)try{this._logger.info("requesting fullscreen"),this._originalOptions.fullscreenContainer instanceof HTMLElement?this._originalOptions.fullscreenContainer.requestFullscreen():this.engine.screen.enterFullscreen(this._originalOptions.fullscreenContainer)}catch(l){this._logger.error("could not go fullscreen",l)}n()};this._playButton.addEventListener("click",o),this._playButton.addEventListener("touchend",o),this._playButton.addEventListener("pointerup",o),this.engine&&this.engine.input.gamepads.once("button",()=>o(new Event("button")))})}}hidePlayButton(){this._playButtonShown=!1,this._playButton.style.display="none"}dispose(){this._playButtonRootElement.parentElement&&(this._playButtonRootElement.removeChild(this._playButtonElement),document.body.removeChild(this._playButtonRootElement),document.head.removeChild(this._styleBlock),this._playButtonRootElement=null,this._playButtonElement=null,this._styleBlock=null)}async onUserAction(){var t;await Di(200,(t=this.engine)==null?void 0:t.clock),this.canvas.flagDirty(),await this.showPlayButton()}async onBeforeLoad(){this.screen.pushResolutionAndViewport(),this.screen.resolution={width:this.screen.resolution.width,height:this.screen.resolution.height},this.screen.applyResolutionAndViewport();const t=this._image;await this._imageLoaded.promise,await(t==null?void 0:t.decode())}async onAfterLoad(){this.screen.popResolutionAndViewport(),this.screen.applyResolutionAndViewport(),this.dispose()}_positionPlayButton(){if(this.engine){const{x:t,y:e,width:i,height:s}=this.engine.canvas.getBoundingClientRect();if(this._playButtonRootElement){const n=this._playButton.clientWidth,o=this._playButton.clientHeight;this.playButtonPosition?(this._playButtonRootElement.style.left=`${this.playButtonPosition.x}px`,this._playButtonRootElement.style.top=`${this.playButtonPosition.y}px`):(this._playButtonRootElement.style.left=`${t+i/2-n/2}px`,this._playButtonRootElement.style.top=`${e+s/2-o/2+100}px`)}}}onDraw(t){const e=this.engine.canvasHeight/this.engine.pixelRatio,i=this.engine.canvasWidth/this.engine.pixelRatio;this._positionPlayButton(),t.fillStyle=this.backgroundColor,t.fillRect(0,0,i,e);let s=e/2;const n=Math.min(this.logoWidth,i*.75);let o=i/2-n/2;this.logoPosition&&(o=this.logoPosition.x,s=this.logoPosition.y);const a=Math.floor(n*(this.logoHeight/this.logoWidth)),h=this.engine.screen.antialiasing;if(this.engine.screen.antialiasing=!0,this.logoPosition?t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,o,s,n,a):t.drawImage(this._image,0,0,this.logoWidth,this.logoHeight,o,s-a-20,n,a),!this.suppressPlayButton&&this._playButtonShown){this.engine.screen.antialiasing=h;return}let l=o,c=s;this.loadingBarPosition&&(l=this.loadingBarPosition.x,c=this.loadingBarPosition.y),t.lineWidth=2,_n(t,l,c,n,20,10,this.loadingBarColor);const u=n*this.progress,_=5,f=u-_*2,m=20-_*2;_n(t,l+_,c+_,f>10?f:10,m,5,null,this.loadingBarColor),this.engine.screen.antialiasing=h}};Uo._DEFAULT_LOADER_OPTIONS={loadables:[],fullscreenAfterLoad:!1,fullscreenContainer:void 0};let ts=Uo;const zo={webgl:"WebGL",webaudio:"WebAudio",gamepadapi:"Gamepad API"};class Oo{constructor(){this._features=null,this.failedTests=[],this._criticalTests={canvasSupport:function(){const t=document.createElement("canvas");return!!(t.getContext&&t.getContext("2d"))},arrayBufferSupport:function(){const t=new XMLHttpRequest;t.open("GET","/");try{t.responseType="arraybuffer"}catch(e){return!1}return t.responseType==="arraybuffer"},dataUrlSupport:function(){return document.createElement("canvas").toDataURL("image/png").indexOf("data:image/png")===0},objectUrlSupport:function(){return"URL"in window&&"revokeObjectURL"in URL&&"createObjectURL"in URL},rgbaSupport:function(){const t=document.createElement("a").style;return t.cssText="background-color:rgba(150,255,150,.5)",(""+t.backgroundColor).indexOf("rgba")>-1}},this._warningTest={webAudioSupport:function(){return!!(window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext||window.oAudioContext)},webglSupport:function(){const t=document.createElement("canvas");return!!(t.getContext&&t.getContext("webgl"))}},this._features=this._loadBrowserFeatures()}getBrowserFeatures(){return this._features===null&&(this._features=this._loadBrowserFeatures()),this._features}logBrowserFeatures(){let t=`%cSUPPORTED BROWSER FEATURES
|
|
784
895
|
==========================%c
|
|
785
896
|
`;const e=["font-weight: bold; color: navy","font-weight: normal; color: inherit"],i=this.getBrowserFeatures();for(const s of Object.keys(zo))i[s]?(t+="(%c✓%c)",e.push("font-weight: bold; color: green"),e.push("font-weight: normal; color: inherit")):(t+="(%c✗%c)",e.push("font-weight: bold; color: red"),e.push("font-weight: normal; color: inherit")),t+=" "+zo[s]+`
|
|
786
|
-
`;e.unshift(t),console.log.apply(console,e)}_loadBrowserFeatures(){return{canvas:this._criticalTests.canvasSupport(),arraybuffer:this._criticalTests.arrayBufferSupport(),dataurl:this._criticalTests.dataUrlSupport(),objecturl:this._criticalTests.objectUrlSupport(),rgba:this._criticalTests.rgbaSupport(),webaudio:this._warningTest.webAudioSupport(),webgl:this._warningTest.webglSupport(),gamepadapi:!!navigator.getGamepads}}test(){let t=!1;for(const e in this._criticalTests)this._criticalTests[e].call(this)||(this.failedTests.push(e),R.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const e in this._warningTest)this._warningTest[e]()||R.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",e);return!0}}function Ho(r){return r instanceof Hn}class Hn extends Ft{constructor(t){var e,i;super({...t}),this.get(A).coordPlane=rt.Screen,this.anchor=(e=t==null?void 0:t.anchor)!=null?e:x(0,0),this.body.collisionType=(i=t==null?void 0:t.collisionType)!=null?i:M.PreventCollision,this.pointer.useGraphicsBounds=!0,this.pointer.useColliderShape=!1,!(t!=null&&t.collider)&&(t==null?void 0:t.width)>0&&(t==null?void 0:t.height)>0&&this.collider.useBoxCollider(this.width,this.height,this.anchor)}_initialize(t){this._engine=t,super._initialize(t)}contains(t,e,i=!0){if(i)return super.contains(t,e);const s=this._engine.worldToScreenCoordinates(new v(t,e));return super.contains(s.x,s.y)}}const No=class za{constructor(t){this._logger=R.getInstance(),this.id=0,this._elapsedTime=0,this._totalTimeAlive=0,this._running=!1,this._numberOfTicks=0,this.interval=10,this.repeats=!1,this.maxNumberOfRepeats=-1,this.randomRange=[0,0],this._baseInterval=10,this._generateRandomInterval=()=>this._baseInterval+this.random.integer(this.randomRange[0],this.randomRange[1]),this._complete=!1,this.scene=null;var e;const i=(e=t.action)!=null?e:t.fcn,s=t.interval,n=t.repeats,o=t.numberOfRepeats,a=t.randomRange,h=t.random;if(o&&o>=0&&(this.maxNumberOfRepeats=o,!n))throw new Error("repeats must be set to true if numberOfRepeats is set");if(this.id=za._MAX_ID++,this._callbacks=[],this._baseInterval=this.interval=s,a){if(a[0]>a[1])throw new Error("min value must be lower than max value for range");this.random=h!=null?h:new ie,this.randomRange=a,this.interval=this._generateRandomInterval(),this.on(()=>{this.interval=this._generateRandomInterval()})}this.repeats=n||this.repeats,i&&this.on(i)}get complete(){return this._complete}on(t){this._callbacks.push(t)}off(t){const e=this._callbacks.indexOf(t);this._callbacks.splice(e,1)}update(t){this._running&&(this._totalTimeAlive+=t,this._elapsedTime+=t,this.maxNumberOfRepeats>-1&&this._numberOfTicks>=this.maxNumberOfRepeats&&(this._complete=!0,this._running=!1,this._elapsedTime=0),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach(e=>{e.call(this)}),this._numberOfTicks++,this.repeats?this._elapsedTime=0:(this._complete=!0,this._running=!1,this._elapsedTime=0)))}reset(t,e){if(t&&t>=0&&(this._baseInterval=this.interval=t),this.maxNumberOfRepeats&&this.maxNumberOfRepeats>=0&&(this.maxNumberOfRepeats=e,!this.repeats))throw new Error("repeats must be set to true if numberOfRepeats is set");this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0}get timesRepeated(){return this._numberOfTicks}getTimeRunning(){return this._totalTimeAlive}get timeToNextAction(){return this.complete?0:this.interval-this._elapsedTime}get timeElapsedTowardNextAction(){return this._elapsedTime}get isRunning(){return this._running}pause(){return this._running=!1,this}resume(){return this._running=!0,this}start(){return this.scene||this._logger.warn("Cannot start a timer not part of a scene, timer wont start until added"),this._running=!0,this.complete&&(this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this}cancel(){this.pause(),this.scene&&this.scene.cancelTimer(this)}};No._MAX_ID=0;let Ki=No;function Wo(r){return r&&r._dispatchPointerEvents&&r._processPointerToObject}class Dl{get events(){return this.object.events}init(t,e,i){this.object=t,this.contains=e,this.active=i}}class Nn{constructor(){this._proxyPool=new Ve(()=>new Dl,t=>t,100),this._objectToProxy=new Map,this._proxies=[],this._lastFrameObjectToPointers=new Map,this._currentFrameObjectToPointers=new Map}addObject(t,e,i){const s=this._proxyPool.rent(!1);s.init(t,e,i),this._proxies.push(s),this._objectToProxy.set(t,s)}_getProxy(t){const e=this._objectToProxy.get(t);if(e)return e;throw new Error("No PointerTargetProxy for object")}removeObject(t){const e=this._objectToProxy.get(t);if(e){const i=this._proxies.indexOf(e);this._objectToProxy.delete(t),i>-1&&this._proxies.splice(i,1),this._proxyPool.return(e)}}_objectCurrentlyUnderPointer(t,e){return!!(this._currentFrameObjectToPointers.has(t)&&this._currentFrameObjectToPointers.get(t).includes(e))}_objectWasUnderPointer(t,e){return!!(this._lastFrameObjectToPointers.has(t)&&this._lastFrameObjectToPointers.get(t).includes(e))}_entered(t,e){return this._objectCurrentlyUnderPointer(t,e)&&!this._lastFrameObjectToPointers.has(t)}_left(t,e){return!this._currentFrameObjectToPointers.has(t)&&this._objectWasUnderPointer(t,e)}addPointerToObject(t,e){const i=this._objectToProxy.get(t);i&&this._addPointerToProxy(i,e)}_addPointerToProxy(t,e){if(!this._currentFrameObjectToPointers.has(t)){this._currentFrameObjectToPointers.set(t,[e]);return}const i=this._currentFrameObjectToPointers.get(t);this._currentFrameObjectToPointers.set(t,i.concat(e))}dispatchEvents(t,e){const i=new Set(this._lastFrameObjectToPointers.keys()),s=new Set(this._currentFrameObjectToPointers.keys());let n,o,a,h=[];if(e)for(let l=0;l<e.length;l++){const c=e[l],u=this._getProxy(c);h.push(u)}else{const l=new Set(i);for(const c of s)l.add(c);h=Array.from(l)}for(let l=0;l<h.length;l++){const c=h[l];if(Wo(c.object)&&c.object._dispatchPointerEvents(t),i.has(c)||s.has(c)){a=this._processDownAndEmit(t,c),o=this._processUpAndEmit(t,c),n=this._processMoveAndEmit(t,c);const u=[...n.values(),...a.values(),...o.values()];this._processEnterLeaveAndEmit(t,c,u),this._processCancelAndEmit(t,c),this._processWheelAndEmit(t,c)}}}processPointerToObject(t,e){for(let i=0;i<e.length;i++){const s=e[i],n=this._getProxy(s);Wo(s)&&s._processPointerToObject(t);for(const[o,a]of t.currentFramePointerCoords.entries())n.contains(a)&&this._addPointerToProxy(n,o)}}clear(){this._lastFrameObjectToPointers.clear(),this._lastFrameObjectToPointers=new Map(this._currentFrameObjectToPointers),this._currentFrameObjectToPointers.clear()}_processDownAndEmit(t,e){const i=new Map;for(const s of t.currentFrameDown)s.active&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointerdown",s),t.isDragStart(s.pointerId)&&e.events.emit("pointerdragstart",s)),i.set(s.pointerId,s);return i}_processUpAndEmit(t,e){const i=new Map;for(const s of t.currentFrameUp)s.active&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointerup",s),t.isDragEnd(s.pointerId)&&e.events.emit("pointerdragend",s)),i.set(s.pointerId,s);return i}_processMoveAndEmit(t,e){const i=new Map;for(const s of t.currentFrameMove)s.active&&e.active()&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointermove",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragmove",s)),i.set(s.pointerId,s);return i}_processEnterLeaveAndEmit(t,e,i){for(const s of i){if(s.active&&e.active()&&this._entered(e,s.pointerId)){e.events.emit("pointerenter",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragenter",s);break}if(s.active&&e.active()&&(this._left(e,s.pointerId)||this._objectCurrentlyUnderPointer(e,s.pointerId)&&s.type==="up")){e.events.emit("pointerleave",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragleave",s);break}}}_processCancelAndEmit(t,e){for(const i of t.currentFrameCancel)i.active&&e.active()&&this._objectCurrentlyUnderPointer(e,i.pointerId)&&e.events.emit("pointercancel",i)}_processWheelAndEmit(t,e){for(const i of t.currentFrameWheel)i.active&&e.active()&&this._objectCurrentlyUnderPointer(e,0)&&e.events.emit("pointerwheel",i)}}const Fl={PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PointerUp:"pointerup",PointerDown:"pointerdown",PointerMove:"pointermove",PointerCancel:"pointercancel"};class Go extends Tt{constructor(t){var e,i,s;super([],t.name),this.events=new X,this._token=0,this.logger=R.getInstance(),this.tiles=[],this._rows=[],this._cols=[],this.renderFromTopOfGraphic=!1,this.meshingLookBehind=10,this._collidersDirty=!0,this._oldRotation=0,this._originalOffsets=new WeakMap,this.meshingLookBehind=(e=t.meshingLookBehind)!=null?e:this.meshingLookBehind,this.addComponent(new A),this.addComponent(new H),this.addComponent(new W({type:M.Fixed})),this.addComponent(new j({onPostDraw:(o,a)=>this.draw(o,a)})),this.addComponent(new Ni((o,a)=>this.debug(o,a),!1)),this.addComponent(new tt),this.addComponent(new ae),this.pointer=this.get(ae),this._graphics=this.get(j),this.transform=this.get(A),this._motion=this.get(H),this.collider=this.get(tt),this._composite=this.collider.useCompositeCollider([]),this.transform.pos=(i=t.pos)!=null?i:v.Zero,this._oldPos=this.transform.pos.clone(),this._oldScale=this.transform.scale.clone(),this.renderFromTopOfGraphic=(s=t.renderFromTopOfGraphic)!=null?s:this.renderFromTopOfGraphic,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.rows=t.rows,this.columns=t.columns,this._pointerEventDispatcher=new Nn,this.tiles=new Array(this.rows*this.columns),this._rows=new Array(this.rows),this._cols=new Array(this.columns);let n=[];for(let o=0;o<this.columns;o++){for(let a=0;a<this.rows;a++){const h=new Vo({x:o,y:a,map:this});h.map=this,this.tiles[o+a*this.columns]=h,this._pointerEventDispatcher.addObject(h,l=>h.bounds.contains(l.worldPos),()=>!0),n.push(h),this._rows[a]||(this._rows[a]=[]),this._rows[a].push(h)}this._cols[o]=n,n=[]}this._graphics.localBounds=new D({left:0,top:0,right:this.columns*this.tileWidth*this.scale.x,bottom:this.rows*this.tileHeight*this.scale.y})}flagCollidersDirty(){this._collidersDirty=!0}flagTilesDirty(){for(let t=0;t<this.tiles.length;t++)this.tiles[t]&&this.tiles[t].flagDirty()}get x(){var t;return(t=this.transform.pos.x)!=null?t:0}set x(t){var e;(e=this.transform)!=null&&e.pos&&(this.get(A).pos=x(t,this.y))}get y(){var t,e;return(e=(t=this.transform)==null?void 0:t.pos.y)!=null?e:0}set y(t){var e;(e=this.transform)!=null&&e.pos&&(this.transform.pos=x(this.x,t))}get z(){var t;return(t=this.transform.z)!=null?t:0}set z(t){this.transform&&(this.transform.z=t)}get rotation(){var t,e;return(e=(t=this.transform)==null?void 0:t.rotation)!=null?e:0}set rotation(t){this.transform&&(t!==this.transform.rotation&&(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.rotation=t)}get scale(){var t,e;return(e=(t=this.transform)==null?void 0:t.scale)!=null?e:v.One}set scale(t){this.transform&&(t!=null&&t.equals(this.transform.scale)||(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.scale=t)}get pos(){return this.transform.pos}set pos(t){this.transform&&(t!=null&&t.equals(this.transform.pos)||(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.pos=t)}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}get width(){return this.tileWidth*this.columns*this.scale.x}get height(){return this.tileHeight*this.rows*this.scale.y}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_initialize(t){super._initialize(t),this._engine=t}_getOrSetColliderOriginalOffset(t){var e;if(this._originalOffsets.has(t))return(e=this._originalOffsets.get(t))!=null?e:v.Zero;{const i=t.offset;return this._originalOffsets.set(t,i),i}}_updateColliders(){this.collider.$colliderRemoved.notifyAll(this._composite),this._composite.clearColliders();const t=[];this._composite=this.collider.useCompositeCollider([]);let e=null;const i=(n,o)=>n&&o?n.top===o.top&&n.bottom===o.bottom&&n.right===o.left:!1,s=(n,o,a=this.meshingLookBehind)=>{if(!n)return!1;for(let h=o.length-1;h>=0;h--){if(a--<0)return!1;const l=o[h];if(i(l,n))return o[h]=l.combine(n),!0}return!1};for(let n=0;n<this.columns;n++){for(let o=0;o<this.rows;o++){const a=this.tiles[n+o*this.columns];if(a.solid)if(a.getColliders().length>0){for(const h of a.getColliders()){const l=this._getOrSetColliderOriginalOffset(h);h.offset=x(a.x*this.tileWidth*this.scale.x,a.y*this.tileHeight*this.scale.y).add(l),h.owner=this,this._composite.addCollider(h)}e&&!s(e,t)&&t.push(e),e=null}else e?e=e.combine(a.defaultGeometry):e=a.defaultGeometry;else e&&!s(e,t)&&t.push(e),e=null}e&&!s(e,t)&&t.push(e),e=null}for(const n of t){const o=ut.Box(n.width,n.height,v.Zero,x(n.left-this.pos.x,n.top-this.pos.y));o.owner=this,this._composite.addCollider(o)}this.collider.update(),this.collider.$colliderAdded.notifyAll(this._composite)}getTileByIndex(t){var e;return(e=this.tiles[t])!=null?e:null}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const{x:e,y:i}=this._getTileCoordinates(t),s=this.getTile(e,i);return e>=0&&i>=0&&e<this.columns&&i<this.rows&&s?s:null}_getTileCoordinates(t){t=this.transform.applyInverse(t);const e=Math.floor(t.x/this.tileWidth),i=Math.floor(t.y/this.tileHeight);return{x:e,y:i}}getRows(){return this._rows}getColumns(){return this._cols}getOnScreenTiles(){const t=this._engine.screen.getWorldBounds();let e=x(0,0),i=this.transform.coordPlane===rt.Screen?this._engine.screen.getScreenBounds():t;const s=this.get(Wi);if(s&&this.isInitialized){const p=v.One.sub(s.parallaxFactor);e=this._engine.currentScene.camera.pos.scale(p),i=i.translate(e.negate())}const n=this._getTileCoordinates(i.topLeft),o=this._getTileCoordinates(i.topRight),a=this._getTileCoordinates(i.bottomRight),h=this._getTileCoordinates(i.bottomLeft),l=Math.min(F(n.x,0,this.columns-1),F(o.x,0,this.columns-1)),c=Math.min(F(n.y,0,this.rows-1),F(o.y,0,this.rows-1)),u=Math.max(F(a.x,0,this.columns-1),F(h.x,0,this.columns-1)),_=Math.max(F(a.y,0,this.rows-1),F(h.y,0,this.rows-1)),f=[];for(let p=l;p<=u;p++)for(let g=c;g<=_;g++)f.push(this.getTile(p,g));return f}_processPointerToObject(t){const e=Array.from(t.currentFramePointerCoords.entries());for(const[i,s]of e){const n=this.getTileByPoint(this.transform.coordPlane===rt.World?s.worldPos:s.screenPos);n&&this._pointerEventDispatcher.addPointerToObject(n,i)}}_dispatchPointerEvents(t){this._pointerEventDispatcher.dispatchEvents(t)}update(t,e){this._initialize(t),this.onPreUpdate(t,e),this.emit("preupdate",new ne(t,e,this)),(!this._oldPos.equals(this.pos)||this._oldRotation!==this.rotation||!this._oldScale.equals(this.scale))&&(this.flagCollidersDirty(),this.flagTilesDirty()),this._collidersDirty&&(this._collidersDirty=!1,this._updateColliders()),this._pointerEventDispatcher.clear(),this._token++,this.pos.clone(this._oldPos),this._oldRotation=this.rotation,this.scale.clone(this._oldScale),this.transform.pos=this.pos,this.onPostUpdate(t,e),this.emit("postupdate",new re(t,e,this))}draw(t,e){if(!this.isInitialized)return;this.emit("predraw",new ke(t,e,this));let i,s,n;const o=this.getOnScreenTiles();for(let a=0;a<o.length;a++){const h=o[a],l=h.getGraphicsOffsets();for(i=h.getGraphics(),s=0,n=i.length;s<n;s++){const c=i[s],u=l[s];if(c){Sn(c)&&(c==null||c.tick(e,this._token));const _=this.renderFromTopOfGraphic?0:c.height-this.tileHeight;c.draw(t,h.x*this.tileWidth+u.x,h.y*this.tileHeight-_+u.y)}}}this.emit("postdraw",new Ue(t,e,this))}debug(t,e){const{showAll:i,showGrid:s,gridColor:n,gridWidth:o,showSolidBounds:a,solidBoundsColor:h,showColliderGeometry:l}=e.tilemap,{geometryColor:c,geometryLineWidth:u,geometryPointSize:_}=e.collider,f=this.tileWidth*this.columns*this.scale.x,p=this.tileHeight*this.rows*this.scale.y,g=this.pos;if(s||i){for(let w=0;w<this.rows+1;w++){const m=x(0,w*this.tileHeight*this.scale.y);t.drawLine(g.add(m),g.add(x(f,m.y)),n,o)}for(let w=0;w<this.columns+1;w++){const m=x(w*this.tileWidth*this.scale.x,0);t.drawLine(g.add(m),g.add(x(m.x,p)),n,o)}}if(i||a||l){const w=this._composite.getColliders();t.save(),t.translate(this.pos.x,this.pos.y),t.scale(this.scale.x,this.scale.y);for(const m of w){const b=m.localBounds,T=m.worldPos.sub(this.pos);a&&t.drawRectangle(T,b.width,b.height,h)}if(t.restore(),l)for(const m of w)m.debug(t,c,{lineWidth:u,pointSize:_})}if(i||a){if(t.save(),t.z=999,a)for(let w=0;w<this.tiles.length;w++)this.tiles[w].bounds.draw(t);t.restore()}}}class Vo{constructor(t){this._posDirty=!1,this.events=new X,this._solid=!1,this._graphics=[],this._offsets=[],this._colliders=[],this.data=new Map;var e,i;this.x=t.x,this.y=t.y,this.map=t.map,this._width=t.map.tileWidth*this.map.scale.x,this._height=t.map.tileHeight*this.map.scale.y,this.solid=(e=t.solid)!=null?e:this.solid,this._graphics=(i=t.graphics)!=null?i:[],this._recalculate()}get pos(){return this._posDirty&&(this._recalculate(),this._posDirty=!1),this._pos}get width(){return this._width}get height(){return this._height}get solid(){return this._solid}set solid(t){var e;(e=this.map)==null||e.flagCollidersDirty(),this._solid=t}getGraphics(){return this._graphics}getGraphicsOffsets(){return this._offsets}addGraphic(t,e){this._graphics.push(t),e!=null&&e.offset?this._offsets.push(e.offset):this._offsets.push(v.Zero)}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&(this._graphics.splice(e,1),this._offsets.splice(e,1))}clearGraphics(){this._graphics.length=0,this._offsets.length=0}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}flagDirty(){this._posDirty=!0}_recalculate(){const t=this.map.pos.add(x(this.x*this.map.tileWidth,this.y*this.map.tileHeight));this._geometry=new D(t.x,t.y,t.x+this.map.tileWidth,t.y+this.map.tileHeight),this._width=this.map.tileWidth*this.map.scale.x,this._height=this.map.tileHeight*this.map.scale.y,this._pos=this.map.pos.add(x(this.x*this._width,this.y*this._height)),this._bounds=new D(this._pos.x,this._pos.y,this._pos.x+this._width,this._pos.y+this._height),this.map.rotation&&(this._bounds=this._bounds.rotate(this.map.rotation,this.map.pos)),this._posDirty=!1}get bounds(){return this._posDirty&&this._recalculate(),this._bounds}get defaultGeometry(){return this._geometry}get center(){return this._posDirty&&this._recalculate(),new v(this._pos.x+this._width/2,this._pos.y+this._height/2)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){e?this.events.off(t,e):this.events.off(t)}}class mi extends Dt{constructor(t){super(),this.elevation=0,this.columns=t.columns,this.rows=t.rows,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight}}class qo extends Tt{constructor(t,e,i,s){super([new A,new j({offset:i!=null?i:v.Zero,onPostDraw:(_,f)=>this.draw(_,f)}),new mi(s)]),this.solid=!1,this.events=new X,this._tileBounds=new D,this._graphics=[],this._colliders=[],this.data=new Map,this.x=t,this.y=e,this.map=s,this._transform=this.get(A),this._isometricEntityComponent=this.get(mi);const n=this.map.tileWidth/2,o=this.map.tileHeight/2,a=(this.x-this.y)*n,h=(this.x+this.y)*o;this._transform.pos=x(a,h),this._isometricEntityComponent.elevation=s.elevation,this._gfx=this.get(j),this._gfx.isVisible=!1;const l=this.map.tileWidth,c=this.map.tileHeight,u=x(0,this.map.renderFromTopOfGraphic?c:0);this._gfx.localBounds=this._tileBounds=new D({left:-l/2,top:-c,right:l/2,bottom:c}).translate(u)}getGraphics(){return this._graphics}addGraphic(t,e){this._graphics.push(t),this._gfx.isVisible=this.map.isVisible,this._gfx.opacity=this.map.opacity,e!=null&&e.offset&&(this._gfx.offset=e.offset),this._gfx.localBounds=this._recalculateBounds()}_recalculateBounds(){let t=this._tileBounds.clone();for(const e of this._graphics){const i=x(this.map.graphicsOffset.x-this.map.tileWidth/2,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:e.height-this.map.tileHeight));t=t.combine(e.localBounds.translate(i))}return t}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&this._graphics.splice(e,1),this._gfx.localBounds=this._recalculateBounds()}clearGraphics(){this._graphics.length=0,this._gfx.isVisible=!1,this._gfx.localBounds=this._recalculateBounds()}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}get pos(){return this.map.tileToWorld(x(this.x,this.y))}get center(){return this.pos.add(x(0,this.map.tileHeight/2))}draw(t,e){const i=this.map.tileWidth/2;t.save(),t.translate(-i,0);for(const s of this._graphics)s.draw(t,this.map.graphicsOffset.x,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:s.height-this.map.tileHeight));t.restore()}}class Bl extends Tt{constructor(t){super([new A,new W({type:M.Fixed}),new tt,new ae,new Ni((c,u)=>this.debug(c,u),!1)],t.name),this.elevation=0,this.isVisible=!0,this.opacity=1,this.renderFromTopOfGraphic=!1,this.graphicsOffset=x(0,0),this._collidersDirty=!1,this._originalOffsets=new WeakMap;const{pos:e,tileWidth:i,tileHeight:s,columns:n,rows:o,renderFromTopOfGraphic:a,graphicsOffset:h,elevation:l}=t;this.transform=this.get(A),e&&(this.transform.pos=e),this.collider=this.get(tt),this.collider&&this.collider.set(this._composite=new at([])),this.pointer=this.get(ae),this.renderFromTopOfGraphic=a!=null?a:this.renderFromTopOfGraphic,this.graphicsOffset=h!=null?h:this.graphicsOffset,this.elevation=l!=null?l:this.elevation,this.tileWidth=i,this.tileHeight=s,this.columns=n,this.rows=o,this._pointerEventDispatcher=new Nn,this.tiles=new Array(n*o);for(let c=0;c<o;c++)for(let u=0;u<n;u++){const _=new qo(u,c,this.graphicsOffset,this);this.tiles[u+c*n]=_,this.addChild(_),this._pointerEventDispatcher.addObject(_,f=>this.getTileByPoint(f.worldPos)===_,()=>!0)}this.pointer.localBounds=D.fromDimension(i*n*this.transform.scale.x,s*o*this.transform.scale.y,x(.5,0))}get visible(){return this.isVisible}set visible(t){this.isVisible=t}_processPointerToObject(t){const e=Array.from(t.currentFramePointerCoords.entries());for(const[i,s]of e){const n=this.getTileByPoint(this.transform.coordPlane===rt.World?s.worldPos:s.screenPos);n&&this._pointerEventDispatcher.addPointerToObject(n,i)}}_dispatchPointerEvents(t){this._pointerEventDispatcher.dispatchEvents(t,this.tiles)}update(){this._collidersDirty&&(this.updateColliders(),this._collidersDirty=!1),this._pointerEventDispatcher.clear()}flagCollidersDirty(){this._collidersDirty=!0}_getOrSetColliderOriginalOffset(t){var e;if(this._originalOffsets.has(t))return(e=this._originalOffsets.get(t))!=null?e:v.Zero;{const i=t.offset;return this._originalOffsets.set(t,i),i}}updateColliders(){this._composite.clearColliders();const t=this.get(A).pos;for(const e of this.tiles)if(e.solid)for(const i of e.getColliders()){const s=this._getOrSetColliderOriginalOffset(i);i.offset=this.tileToWorld(x(e.x,e.y)).sub(t).add(s).sub(x(this.tileWidth/2,this.tileHeight)),i.owner=this,this._composite.addCollider(i)}this.collider.update()}worldToTile(t){t=t.sub(this.transform.globalPos);const e=this.tileWidth/2,i=this.tileHeight/2;return x(~~((t.x/e+t.y/i)/2),~~((t.y/i-t.x/e)/2))}tileToWorld(t){const e=this.tileWidth/2,i=this.tileHeight/2,s=(t.x-t.y)*e,n=(t.x+t.y)*i;return x(s,n).add(this.transform.pos)}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const e=this.worldToTile(t);return this.getTile(e.x,e.y)}_getMaxZIndex(){let t=Number.NEGATIVE_INFINITY;for(const e of this.tiles){const i=e.get(A).z;i>t&&(t=i)}return t}debug(t,e){const{showAll:i,showPosition:s,positionColor:n,positionSize:o,showGrid:a,gridColor:h,gridWidth:l,showColliderGeometry:c}=e.isometric,{geometryColor:u,geometryLineWidth:_,geometryPointSize:f}=e.collider;if(t.save(),t.z=this._getMaxZIndex()+.5,i||a){for(let p=0;p<this.rows+1;p++){const g=this.tileToWorld(x(0,p)),w=this.tileToWorld(x(this.columns,p));t.drawLine(g,w,h,l)}for(let p=0;p<this.columns+1;p++){const g=this.tileToWorld(x(p,0)),w=this.tileToWorld(x(p,this.rows));t.drawLine(g,w,h,l)}}if(i||s)for(const p of this.tiles)t.drawCircle(this.tileToWorld(x(p.x,p.y)),o,n);if(i||c){for(const p of this.tiles)if(p.solid)for(const g of p.getColliders())g.debug(t,u,{lineWidth:_,pointSize:f})}t.restore()}}class Wn extends At{constructor(t){super(),this.world=t,this.systemType=Pt.Update,this.query=this.world.query([A,mi])}update(){let t,e;for(let i=0;i<this.query.entities.length;i++){const s=this.query.entities[i];t=s.get(A),e=s.get(mi);const o=Math.max(e.columns*e.tileWidth,e.rows*e.tileHeight)*e.elevation+t.pos.y;t.z=o}}}Wn.priority=Nt.Lower;class Xo{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new $o(t))}lockToActorAxis(t,e){this.camera.addStrategy(new jo(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new Zo(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new Qo(t,e))}limitCameraBounds(t){this.camera.addStrategy(new Jo(t))}}var Yo=(r=>(r[r.X=0]="X",r[r.Y=1]="Y",r))(Yo||{});class $o{constructor(t){this.target=t,this.action=(e,i,s,n)=>e.center}}class jo{constructor(t,e){this.target=t,this.axis=e,this.action=(i,s,n,o)=>{const a=i.center,h=s.getFocus();return this.axis===0?new v(a.x,h.y):new v(h.x,a.y)}}}class Zo{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(s,n,o,a)=>{const h=s.center;let l=n.getFocus(),c=n.vel.clone();const u=h.sub(l).scale(this.cameraElasticity);c=c.add(u);const _=c.scale(-1).scale(this.cameraFriction);return c=c.add(_),l=l.add(c),l}}}class Qo{constructor(t,e){this.target=t,this.radius=e,this.action=(i,s,n,o)=>{const a=i.center,h=s.getFocus(),l=a.sub(h),c=l.magnitude;if(c>=this.radius){const u=c-this.radius;return h.add(l.normalize().scale(u))}return h}}}class Jo{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(e,i,s,n)=>{const o=i.getFocus();this.boundSizeChecked||((e.bottom-e.top<s.drawHeight||e.right-e.left<s.drawWidth)&&R.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let a=o.x,h=o.y;return o.x<e.left+s.halfDrawWidth?a=e.left+s.halfDrawWidth:o.x>e.right-s.halfDrawWidth&&(a=e.right-s.halfDrawWidth),o.y<e.top+s.halfDrawHeight?h=e.top+s.halfDrawHeight:o.y>e.bottom-s.halfDrawHeight&&(h=e.bottom-s.halfDrawHeight),x(a,h)}}}const Ll={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class Ko{constructor(){this.events=new X,this.transform=Q.identity(),this.inverse=Q.identity(),this._cameraStrategies=[],this.strategy=new Xo(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this._angularVelocity=0,this._posChanged=!1,this._pos=new se(v.Zero,()=>{this._posChanged=!0}),this.drawPos=this.pos.clone(),this._oldPos=this.pos.clone(),this.vel=v.Zero,this.acc=v.Zero,this._cameraMoving=!1,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=null,this._lerpEnd=null,this._isShaking=!1,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._elapsedShakeTime=0,this._xShake=0,this._yShake=0,this._isZooming=!1,this._zoomStart=1,this._zoomEnd=1,this._currentZoomTime=0,this._zoomDuration=0,this._legacyZoomEasing=It.EaseInOutCubic,this._useLegacyZoom=!1,this._zoomEasing=xs,this._legacyEasing=It.EaseInOutCubic,this._useLegacyEasing=!1,this._easing=xs,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1,this._snapPos=x(0,0)}get strategies(){return this._cameraStrategies}get zoom(){return this._z}set zoom(t){this._z=t,this._engine&&(this._halfWidth=this._engine.halfDrawWidth,this._halfHeight=this._engine.halfDrawHeight)}get angularVelocity(){return this._angularVelocity}set angularVelocity(t){this._angularVelocity=t}get pos(){return this._pos}set pos(t){this._posChanged=!0,this._pos=new se(t,()=>{this._posChanged=!0})}hasChanged(){return this._posChanged}get x(){return this.pos.x}set x(t){!this._follow&&!this._cameraMoving&&(this.pos=x(t,this.pos.y))}get y(){return this.pos.y}set y(t){!this._follow&&!this._cameraMoving&&(this.pos=x(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=x(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=x(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=x(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=x(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=It.EaseInOutCubic){if(typeof i!="function")throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise(s=>{this._lerpResolve=s}),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,Se(i)?this._legacyEasing=i:this._easing=i,this._lerpPromise)}shake(t,e,i){this._isShaking=!0,this._shakeMagnitudeX=t,this._shakeMagnitudeY=e,this._shakeDuration=i}zoomOverTime(t,e=0,i=It.EaseInOutCubic){if(this._zoomPromise=new Promise(s=>{this._zoomResolve=s}),e)this._isZooming=!0,Se(i)?this._legacyZoomEasing=i:this._easing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t;else return this._isZooming=!1,this.zoom=t,Promise.resolve(!0);return this._zoomPromise}get viewport(){return this._viewport?this._viewport:new D(0,0,0,0)}addStrategy(...t){this._cameraStrategies.push(...t)}setStrategies(t){this._cameraStrategies=[...t]}removeStrategy(t){Oe(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.events.emit("preupdate",new ne(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.events.emit("postupdate",new re(t,e,this)),this.onPostUpdate(t,e)}onPostUpdate(t,e){}get isInitialized(){return this._isInitialized}_initialize(t){if(!this.isInitialized){this._engine=t,this._screen=t.screen;const e=this._screen.contentArea;let i=x(e.width/2,e.height/2);if(!this._engine.loadingComplete){const s=this._screen.peekResolution();s&&(i=x(s.width/2,s.height/2))}this._halfWidth=i.x,this._halfHeight=i.y,this._posChanged||(this.pos=i),this.pos.clone(this.drawPos),this.updateTransform(this.pos),this.runStrategies(t,t.clock.elapsed()),this.updateViewport(),this.updateTransform(this.pos),this.pos.clone(this._oldPos),this.onInitialize(t),this.events.emit("initialize",new ze(t,this)),this._isInitialized=!0}}onInitialize(t){}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}runStrategies(t,e){for(const i of this._cameraStrategies)this.pos=i.action.call(i,i.target,this,t,e)}updateViewport(){this._viewport=new D(this.x-this._halfWidth,this.y-this._halfHeight,this.x+this._halfWidth,this.y+this._halfHeight)}update(t,e){if(this._initialize(t),this._preupdate(t,e),this.pos.clone(this._oldPos),this.pos=this.pos.add(this.vel.scale(e/1e3)),this.zoom+=this.dz*e/1e3,this.vel=this.vel.add(this.acc.scale(e/1e3)),this.dz+=this.az*e/1e3,this.rotation+=this.angularVelocity*e/1e3,this._isZooming)if(this._currentZoomTime<this._zoomDuration){let i=this.zoom;if(this._useLegacyZoom){const s=this._legacyZoomEasing;i=s(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration)}else i=ot(this._zoomStart,this._zoomEnd,this._zoomEasing(this._currentZoomTime/this._zoomDuration));this.zoom=i,this._currentZoomTime+=e}else this._isZooming=!1,this.zoom=this._zoomEnd,this._currentZoomTime=0,this._zoomResolve(!0);if(this._cameraMoving)if(this._currentLerpTime<this._lerpDuration){let i=this.pos;this._useLegacyEasing?i=It.CreateVectorEasingFunction(this._legacyEasing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration):(i.x=ot(this._lerpStart.x,this._lerpEnd.x,this._easing(this._currentLerpTime/this._lerpDuration)),i.y=ot(this._lerpStart.y,this._lerpEnd.y,this._easing(this._currentLerpTime/this._lerpDuration))),this.pos=i,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const i=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(i)}this._isDoneShaking()?(this._isShaking=!1,this._elapsedShakeTime=0,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._xShake=0,this._yShake=0):(this._elapsedShakeTime+=e,this._xShake=(Math.random()*this._shakeMagnitudeX|0)+1,this._yShake=(Math.random()*this._shakeMagnitudeY|0)+1),this.runStrategies(t,e),this.updateViewport(),this.updateTransform(this.pos),this._postupdate(t,e),this._posChanged=!1}draw(t){if(this.pos.clone(this.drawPos),this._engine.fixedUpdateTimestep){const e=this._engine.currentFrameLagMs/this._engine.fixedUpdateTimestep,i=this.pos.scale(e).add(this._oldPos.scale(1-e));i.clone(this.drawPos),this.updateTransform(i)}if(t.snapToPixel){const e=this.drawPos.clone(this._snapPos);e.x=~~(e.x+B*V(e.x)),e.y=~~(e.y+B*V(e.y)),e.clone(this.drawPos),this.updateTransform(e)}t.multiply(this.transform)}updateTransform(t){const e=this._screen.resolution.width/this.zoom,i=this._screen.resolution.height/this.zoom,s=x(-t.x+e/2+this._xShake,-t.y+i/2+this._yShake);this.transform.reset(),this.transform.scale(this.zoom,this.zoom),this.transform.translate(e/2,i/2),this.transform.rotate(this.rotation),this.transform.translate(-e/2,-i/2),this.transform.translate(s.x,s.y),this.transform.inverse(this.inverse)}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}const kl={ExitTrigger:"exit",EnterTrigger:"enter"};class ta extends Ft{constructor(t){var e,i,s,n;super({...t}),this.events=new X,this.filter=(e=t.filter)!=null?e:()=>!0,this.repeat=(i=t.repeat)!=null?i:-1,this.action=(s=t.action)!=null?s:()=>{},this.target=t.target,this.graphics.isVisible=(n=t.visible)!=null?n:!1,this.body.collisionType=M.Passive,this.events.on("collisionstart",({other:o})=>{this._matchesTarget(o.owner)&&(this.events.emit("enter",new qs(this,o.owner)),this._dispatchAction(o.owner),this.repeat===0&&this.kill())}),this.events.on("collisionend",({other:o})=>{this._matchesTarget(o.owner)&&this.events.emit("exit",new Xs(this,o.owner))})}_matchesTarget(t){return this.filter(t)&&(this.target===void 0||this.target===t)}_dispatchAction(t){this.repeat!==0&&(this.action.call(this,t),this.repeat--)}}class Gn extends At{constructor(t){super(),this.world=t,this.systemType=Pt.Draw,this.query=this.world.query([A])}initialize(t,e){this._graphicsContext=e.engine.graphicsContext,this._camera=e.camera,this._engine=e.engine,this._collisionSystem=t.systemManager.get(Zi)}update(){var t;if(!this._engine.isDebug)return;const e=this._engine.debug.filter;let i,s;const n=this._engine.debug.entity;let o;const a=this._engine.debug.transform;let h;const l=this._engine.debug.motion;let c;const u=this._engine.debug.collider,_=this._engine.debug.physics;let f;const p=this._engine.debug.graphics;let g,w;const m=this._engine.debug.body,b=this._engine.debug.camera;for(let T=0;T<this.query.entities.length;T++){const C=this.query.entities[T];if(C.hasTag("offscreen")||C instanceof Yi||e.useFilter&&(!(e.ids.length===0||e.ids.includes(C.id))||!(e.nameQuery===""||C.name.includes(e.nameQuery))))continue;let S=v.Zero;const I=x(0,16);if(i=C.id,s=C.name,o=C.get(A),this._pushCameraTransform(o),this._graphicsContext.save(),o.coordPlane===rt.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),this._graphicsContext.z=a.debugZIndex,this._applyTransform(C),o&&((a.showAll||a.showPosition)&&this._graphicsContext.debug.drawPoint(v.Zero,{size:4,color:a.positionColor}),(a.showAll||a.showPositionLabel)&&(this._graphicsContext.debug.drawText(`pos${o.pos.toString(2)}`,S),S=S.add(I)),(a.showAll||a.showZIndex)&&(this._graphicsContext.debug.drawText(`z(${o.z.toFixed(1)})`,S),S=S.add(I)),(n.showAll||n.showId)&&(this._graphicsContext.debug.drawText(`id(${i}) ${C.parent?"child of id("+((t=C.parent)==null?void 0:t.id)+")":""}`,S),S=S.add(I)),(n.showAll||n.showName)&&(this._graphicsContext.debug.drawText(`name(${s})`,S),S=S.add(I)),(a.showAll||a.showRotation)&&(this._graphicsContext.drawLine(v.Zero,v.fromAngle(o.rotation).scale(50).add(v.Zero),a.rotationColor,2),this._graphicsContext.debug.drawText(`rot deg(${hr(o.rotation).toFixed(2)})`,S),S=S.add(I)),(a.showAll||a.showScale)&&this._graphicsContext.drawLine(v.Zero,o.scale.add(v.Zero),a.scaleColor,2)),f=C.get(j),f&&(p.showAll||p.showBounds)&&f.localBounds.draw(this._graphicsContext,p.boundsColor),g=C.get(Ni),g&&(g.useTransform||this._graphicsContext.restore(),g.draw(this._graphicsContext,this._engine.debug),g.useTransform||(this._graphicsContext.save(),this._applyTransform(C))),w=C.get(W),w&&((m.showAll||m.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group(${w.group.name})`,S),S=S.add(I)),(m.showAll||m.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${w.collisionType})`,S),S=S.add(I)),(m.showAll||m.showMass)&&(this._graphicsContext.debug.drawText(`mass(${w.mass})`,S),S=S.add(I)),(m.showAll||m.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${w.sleepMotion})`,S),S=S.add(I)),(m.showAll||m.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${w.canSleep?w.isSleeping:"cant sleep"})`,S),S=S.add(I))),this._graphicsContext.restore(),this._graphicsContext.save(),o.coordPlane===rt.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),this._graphicsContext.z=a.debugZIndex,h=C.get(H),h&&((l.showAll||l.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${h.vel.toString(2)}`,S.add(o.globalPos)),this._graphicsContext.drawLine(o.globalPos,o.globalPos.add(h.vel),l.velocityColor,2),S=S.add(I)),(l.showAll||l.showAcceleration)&&this._graphicsContext.drawLine(o.globalPos,o.globalPos.add(h.acc),l.accelerationColor,2)),c=C.get(tt),c){const y=c.get();if((u.showAll||u.showGeometry)&&y&&y.debug(this._graphicsContext,u.geometryColor,{lineWidth:u.geometryLineWidth,pointSize:u.geometryPointSize}),u.showAll||u.showBounds){if(y instanceof at){const k=y.getColliders();for(const U of k){const z=U.bounds,Y=x(z.left,z.top);this._graphicsContext.debug.drawRect(Y.x,Y.y,z.width,z.height,{color:u.boundsColor}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${U.owner.id})`,Y)}c.bounds.draw(this._graphicsContext,u.boundsColor)}else if(y){const k=c.bounds,U=x(k.left,k.top);this._graphicsContext.debug.drawRect(U.x,U.y,k.width,k.height,{color:u.boundsColor}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${c.owner.id})`,U)}}}this._graphicsContext.restore(),this._popCameraTransform(o)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(_.showAll||_.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),_.showAll||_.showCollisionContacts||_.showCollisionNormals)for(const[T,C]of this._engine.debug.stats.currFrame.physics.contacts){if(_.showAll||_.showCollisionContacts)for(const S of C.points)this._graphicsContext.debug.drawPoint(S,{size:_.contactSize,color:_.collisionContactColor});if(_.showAll||_.showCollisionNormals)for(const S of C.points)this._graphicsContext.debug.drawLine(S,C.normal.scale(30).add(S),{color:_.collisionNormalColor})}this._graphicsContext.restore(),b&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(b.showAll||b.showFocus)&&this._graphicsContext.drawCircle(this._camera.pos,4,b.focusColor),(b.showAll||b.showZoom)&&this._graphicsContext.debug.drawText(`zoom(${this._camera.zoom})`,this._camera.pos),this._graphicsContext.restore()),this._graphicsContext.flush()}postupdate(t,e){this._engine.isDebug&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext),Cn.flush(this._graphicsContext),this._graphicsContext.restore())}_applyTransform(t){const e=t.getAncestors();for(const i of e){const s=i==null?void 0:i.get(A);s&&(this._graphicsContext.translate(s.pos.x,s.pos.y),this._graphicsContext.scale(s.scale.x,s.scale.y),this._graphicsContext.rotate(s.rotation))}}_pushCameraTransform(t){t.coordPlane===rt.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===rt.World&&this._graphicsContext.restore()}}Gn.priority=Nt.Lowest;class ts extends At{constructor(t){super(),this.world=t,this.systemType=Pt.Update,this._graphicsHashGrid=new Rn({size:100}),this._graphics=[],this._entityToPointer=new Map,this._pointerEventDispatcher=new Nn,this.overrideUseColliderShape=!1,this.overrideUseGraphicsBounds=!1,this._sortedTransforms=[],this._sortedEntities=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0},this.query=this.world.query([A,ae]),this.query.entityAdded$.subscribe(e=>{const i=e.get(A),s=e.get(ae);this._pointerEventDispatcher.addObject(e,o=>s&&s.localBounds?s.localBounds.transform(i.get().matrix).contains(i.coordPlane===rt.World?o.worldPos:o.screenPos):!1,()=>e.isActive),this._entityToPointer.set(e,s);const n=e.get(j);n&&(this._graphics.push(n),this._graphicsHashGrid.track(n)),this._sortedTransforms.push(i),this._sortedEntities.push(i.owner),i.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}),this.query.entityRemoved$.subscribe(e=>{this._pointerEventDispatcher.removeObject(e);const i=e.get(A);this._entityToPointer.delete(e);const s=e.get(j);if(s){const o=this._graphics.indexOf(s);o>-1&&this._graphics.splice(o,1),this._graphicsHashGrid.untrack(s)}i.zIndexChanged$.unsubscribe(this._zIndexUpdate);const n=this._sortedTransforms.indexOf(i);n>-1&&(this._sortedTransforms.splice(n,1),this._sortedEntities.splice(n,1))})}initialize(t,e){this._engine=e.engine,this._scene=e}preupdate(){this._scene.camera.hasChanged()&&this._scene.camera.updateTransform(this._scene.camera.pos),this._receivers=[this._engine.input.pointers,this._scene.input.pointers],this._engineReceiver=this._engine.input.pointers,this._zHasChanged&&(this._sortedTransforms.sort((t,e)=>e.z-t.z),this._sortedEntities=this._sortedTransforms.map(t=>t.owner),this._zHasChanged=!1)}update(){this._graphicsHashGrid.update(this._graphics);for(const[t,e]of this._engineReceiver.currentFramePointerCoords.entries()){const i=this._scene.physics.query(e.worldPos);for(let n=0;n<i.length;n++){const o=i[n],a=this._entityToPointer.get(o.owner);a&&(a.useColliderShape||this.overrideUseColliderShape)&&this._pointerEventDispatcher.addPointerToObject(o.owner,t)}const s=this._graphicsHashGrid.query(e.worldPos);for(let n=0;n<s.length;n++){const o=s[n],a=this._entityToPointer.get(o.owner);a&&(a.useGraphicsBounds||this.overrideUseGraphicsBounds)&&this._pointerEventDispatcher.addPointerToObject(o.owner,t)}}this._pointerEventDispatcher.processPointerToObject(this._engineReceiver,this._sortedEntities),this._pointerEventDispatcher.dispatchEvents(this._engineReceiver,this._sortedEntities),this._receivers.forEach(t=>t.update()),this._pointerEventDispatcher.clear(),this._receivers.forEach(t=>t.clear())}}ts.priority=Nt.Higher;class Vn extends At{constructor(t){super(),this.world=t,this.systemType=Pt.Update,this._actions=[],this.query=this.world.query([je]),this.query.entityAdded$.subscribe(e=>this._actions.push(e.get(je))),this.query.entityRemoved$.subscribe(e=>{const i=e.get(je),s=this._actions.indexOf(i);s>-1&&this._actions.splice(s,1)})}update(t){for(let e=0;e<this._actions.length;e++)this._actions[e].update(t)}}Vn.priority=Nt.Higher;class es{constructor(){this.events=new X,this.enabled=!1,this.supported=!!navigator.getGamepads,this._gamePadTimeStamps=[0,0,0,0],this._oldPads=[],this._pads=[],this._initSuccess=!1,this._navigator=navigator,this._minimumConfiguration=null,this._enabled=!0}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}toggleEnabled(t){this._enabled=t}setMinimumGamepadConfiguration(t){this._enableAndUpdate(),this._minimumConfiguration=t}_enableAndUpdate(){this.enabled||(this.enabled=!0,this.update())}_isGamepadValid(t){if(!this._minimumConfiguration)return!0;if(!t)return!1;const e=t.axes.filter(s=>typeof s!==void 0).length,i=t.buttons.filter(s=>typeof s!==void 0).length;return e>=this._minimumConfiguration.axis&&i>=this._minimumConfiguration.buttons&&t.connected}emit(t,e){this.events.emit(t,e)}on(t,e){return this._enableAndUpdate(),this.events.on(t,e)}once(t,e){return this._enableAndUpdate(),this.events.once(t,e)}off(t,e){this._enableAndUpdate(),this.events.off(t,e)}update(){var t,e;if(!this.enabled||!this.supported||!this._enabled)return;this.init();const i=this._navigator.getGamepads();for(let s=0;s<i.length;s++){if(i[s]){const o=this.at(s);!this.at(s).connected&&this._isGamepadValid(i[s])&&(o.events.pipe(this.events),this.events.emit("connect",new Ls(s,this.at(s)))),this.at(s).connected=!0}else{const o=this.at(s);o.connected&&(this.events.emit("disconnect",new ks(s,o)),o.events.unpipe(this.events)),o.connected=!1;continue}if(this.at(s).update(),i[s].timestamp&&i[s].timestamp===this._gamePadTimeStamps[s])continue;this._gamePadTimeStamps[s]=i[s].timestamp,this.at(s).navigatorGamepad=i[s];const n=i[s];if(n){for(let o=0;o<n.buttons.length;o++){const a=n.buttons[o],h=a==null?void 0:a.value;h!==((t=this._oldPads[s])==null?void 0:t.getButton(o))&&(a!=null&&a.pressed?(this.at(s).updateButton(o,h),this.at(s).events.emit("button",new Us(o in qn?o:-1,o,h,this.at(s)))):this.at(s).updateButton(o,0))}for(let o=0;o<n.axes.length;o++){const a=n.axes[o];a!==((e=this._oldPads[s])==null?void 0:e.getAxes(o))&&(this.at(s).updateAxes(o,a),this.at(s).events.emit("axis",new zs(o,a,this.at(s))))}}this._oldPads[s]=this._clonePad(i[s])}}at(t){if(this._enableAndUpdate(),t>=this._pads.length)for(let e=this._pads.length-1,i=t;e<i;e++)this._pads.push(new is),this._oldPads.push(new is);return this._pads[t]}getValidGamepads(){this._enableAndUpdate();const t=[];for(let e=0;e<this._pads.length;e++)this._isGamepadValid(this.at(e).navigatorGamepad)&&this.at(e).connected&&t.push(this.at(e));return t}count(){return this._pads.filter(t=>t.connected).length}_clonePads(t){const e=[];for(let i=0,s=t.length;i<s;i++)e.push(this._clonePad(t[i]));return e}_clonePad(t){let e,i;const s=new is;if(!t)return s;for(e=0,i=t.buttons.length;e<i;e++)t.buttons[e]&&s.updateButton(e,t.buttons[e].value);for(e=0,i=t.axes.length;e<i;e++)s.updateAxes(e,t.axes[e]);return s}}es.MinAxisMoveThreshold=.05;class is{constructor(){this.events=new X,this.connected=!1,this._axes=new Array(4),this._buttons=new Array(16),this._buttonsUp=new Array(16),this._buttonsDown=new Array(16);for(let t=0;t<this._buttons.length;t++)this._buttons[t]=0;for(let t=0;t<this._axes.length;t++)this._axes[t]=0}update(){this._buttonsDown=new Array(16),this._buttonsUp=new Array(16)}isButtonPressed(t,e=1){return this._buttons[t]>=e}isButtonHeld(t,e=1){return this._buttons[t]>=e}wasButtonPressed(t,e=1){return this._buttonsDown[t]>=e}wasButtonReleased(t){return!!this._buttonsUp[t]}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<es.MinAxisMoveThreshold?0:e}updateButton(t,e){e===0&&this._buttons[t]?this._buttonsUp[t]=1:this._buttonsDown[t]=e,this._buttons[t]=e}updateAxes(t,e){this._axes[t]=e}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}var qn=(r=>(r[r.Unknown=-1]="Unknown",r[r.Face1=0]="Face1",r[r.Face2=1]="Face2",r[r.Face3=2]="Face3",r[r.Face4=3]="Face4",r[r.LeftBumper=4]="LeftBumper",r[r.RightBumper=5]="RightBumper",r[r.LeftTrigger=6]="LeftTrigger",r[r.RightTrigger=7]="RightTrigger",r[r.Select=8]="Select",r[r.Start=9]="Start",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick",r[r.DpadUp=12]="DpadUp",r[r.DpadDown=13]="DpadDown",r[r.DpadLeft=14]="DpadLeft",r[r.DpadRight=15]="DpadRight",r[r.CenterButton=16]="CenterButton",r[r.MiscButton1=17]="MiscButton1",r))(qn||{}),ea=(r=>(r[r.LeftStickX=0]="LeftStickX",r[r.LeftStickY=1]="LeftStickY",r[r.RightStickX=2]="RightStickX",r[r.RightStickY=3]="RightStickY",r))(ea||{});class ia{constructor(t){this.inputs=t,this._handlers=new Map}execute(){for(const[t,e]of this._handlers.entries()){const i=t(this.inputs);i&&e(i)}}on(t,e){this._handlers.set(t,e)}}function sa(){try{const r=()=>{};window.top.addEventListener("blur",r),window.top.removeEventListener("blur",r)}catch(r){return!0}return!1}function na(){return window!==window.top}function ra(){let r;return sa()?(r=window,R.getInstance().warnOnce("Excalibur might be in a cross-origin iframe, in order to receive keyboard events it must be in focus")):na()?(r=window,R.getInstance().warnOnce("Excalibur might be in a iframe, in order to receive keyboard events it must be in focus")):r=window.top,r}var oa=(r=>(r.Backquote="Backquote",r.Backslash="Backslash",r.BracketLeft="BracketLeft",r.BracketRight="BracketRight",r.Comma="Comma",r.Key0="Digit0",r.Key1="Digit1",r.Key2="Digit2",r.Key3="Digit3",r.Key4="Digit4",r.Key5="Digit5",r.Key6="Digit6",r.Key7="Digit7",r.Key8="Digit8",r.Key9="Digit9",r.Digit0="Digit0",r.Digit1="Digit1",r.Digit2="Digit2",r.Digit3="Digit3",r.Digit4="Digit4",r.Digit5="Digit5",r.Digit6="Digit6",r.Digit7="Digit7",r.Digit8="Digit8",r.Digit9="Digit9",r.Equal="Equal",r.IntlBackslash="IntlBackslash",r.IntlRo="IntlRo",r.IntlYen="IntlYen",r.A="KeyA",r.B="KeyB",r.C="KeyC",r.D="KeyD",r.E="KeyE",r.F="KeyF",r.G="KeyG",r.H="KeyH",r.I="KeyI",r.J="KeyJ",r.K="KeyK",r.L="KeyL",r.M="KeyM",r.N="KeyN",r.O="KeyO",r.P="KeyP",r.Q="KeyQ",r.R="KeyR",r.S="KeyS",r.T="KeyT",r.U="KeyU",r.V="KeyV",r.W="KeyW",r.X="KeyX",r.Y="KeyY",r.Z="KeyZ",r.KeyA="KeyA",r.KeyB="KeyB",r.KeyC="KeyC",r.KeyD="KeyD",r.KeyE="KeyE",r.KeyF="KeyF",r.KeyG="KeyG",r.KeyH="KeyH",r.KeyI="KeyI",r.KeyJ="KeyJ",r.KeyK="KeyK",r.KeyL="KeyL",r.KeyM="KeyM",r.KeyN="KeyN",r.KeyO="KeyO",r.KeyP="KeyP",r.KeyQ="KeyQ",r.KeyR="KeyR",r.KeyS="KeyS",r.KeyT="KeyT",r.KeyU="KeyU",r.KeyV="KeyV",r.KeyW="KeyW",r.KeyX="KeyX",r.KeyY="KeyY",r.KeyZ="KeyZ",r.Minus="Minus",r.Period="Period",r.Quote="Quote",r.Semicolon="Semicolon",r.Slash="Slash",r.AltLeft="AltLeft",r.AltRight="AltRight",r.Alt="Alt",r.AltGraph="AltGraph",r.Backspace="Backspace",r.CapsLock="CapsLock",r.ContextMenu="ContextMenu",r.ControlLeft="ControlLeft",r.ControlRight="ControlRight",r.Enter="Enter",r.MetaLeft="MetaLeft",r.MetaRight="MetaRight",r.ShiftLeft="ShiftLeft",r.ShiftRight="ShiftRight",r.Space="Space",r.Tab="Tab",r.Convert="Convert",r.KanaMode="KanaMode",r.NonConvert="NonConvert",r.Delete="Delete",r.End="End",r.Help="Help",r.Home="Home",r.Insert="Insert",r.PageDown="PageDown",r.PageUp="PageUp",r.Up="ArrowUp",r.Down="ArrowDown",r.Left="ArrowLeft",r.Right="ArrowRight",r.ArrowUp="ArrowUp",r.ArrowDown="ArrowDown",r.ArrowLeft="ArrowLeft",r.ArrowRight="ArrowRight",r.NumLock="NumLock",r.Numpad0="Numpad0",r.Numpad1="Numpad1",r.Numpad2="Numpad2",r.Numpad3="Numpad3",r.Numpad4="Numpad4",r.Numpad5="Numpad5",r.Numpad6="Numpad6",r.Numpad7="Numpad7",r.Numpad8="Numpad8",r.Numpad9="Numpad9",r.Num0="Numpad0",r.Num1="Numpad1",r.Num2="Numpad2",r.Num3="Numpad3",r.Num4="Numpad4",r.Num5="Numpad5",r.Num6="Numpad6",r.Num7="Numpad7",r.Num8="Numpad8",r.Num9="Numpad9",r.NumAdd="NumpadAdd",r.NumpadAdd="NumpadAdd",r.NumDecimal="NumpadDecimal",r.NumpadDecimal="NumpadDecimal",r.NumDivide="NumpadDivide",r.NumpadDivide="NumpadDivide",r.NumEnter="NumpadEnter",r.NumpadEnter="NumpadEnter",r.NumMultiply="NumpadMultiply",r.NumpadMultiply="NumpadMultiply",r.NumSubtract="NumpadSubtract",r.NumpadSubtract="NumpadSubtract",r.Esc="Escape",r.Escape="Escape",r.F1="F1",r.F2="F2",r.F3="F3",r.F4="F4",r.F5="F5",r.F6="F6",r.F7="F7",r.F8="F8",r.F9="F9",r.F10="F10",r.F11="F11",r.F12="F12",r.F13="F13",r.F14="F14",r.F15="F15",r.F16="F16",r.F17="F17",r.F18="F18",r.F19="F19",r.F20="F20",r.PrintScreen="PrintScreen",r.ScrollLock="ScrollLock",r.Pause="Pause",r.Unidentified="Unidentified",r))(oa||{});class vi extends L{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class aa{constructor(){this.events=new X,this._enabled=!0,this._keys=[],this._keysUp=[],this._keysDown=[],this._releaseAllKeys=t=>{for(const e of this._keys){const i=new vi(e,t.key,t);this.events.emit("up",i),this.events.emit("release",i)}this._keysUp=Array.from(new Set(this._keys.concat(this._keysUp))),this._keys.length=0},this._handleKeyDown=t=>{if(!this._enabled)return;!t.metaKey&&(this._keys.includes("MetaLeft")||this._keys.includes("MetaRight"))&&this._releaseAllKeys(t);const e=t.code;if(this._keys.indexOf(e)===-1){this._keys.push(e),this._keysDown.push(e);const i=new vi(e,t.key,t);this.events.emit("down",i),this.events.emit("press",i)}},this._handleKeyUp=t=>{if(!this._enabled)return;const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new vi(e,t.key,t);this.events.emit("up",s),this.events.emit("release",s),t.key==="Meta"&&this._releaseAllKeys(t)}}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}init(t){let{global:e}=t;const{grabWindowFocus:i}=t;e?typeof e=="function"&&(e=e()):e=ra(),i&&e.focus(),e.addEventListener("blur",()=>{this._keys.length=0}),e.addEventListener("keyup",this._handleKeyUp),e.addEventListener("keydown",this._handleKeyDown)}toggleEnabled(t){this._enabled=t}clear(){this._keysDown.length=0,this._keysUp.length=0,this._keys.length=0}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.events.emit("hold",new vi(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._enabled?this._keysDown.indexOf(t)>-1:!1}isHeld(t){return this._enabled?this._keys.indexOf(t)>-1:!1}wasReleased(t){return this._enabled?this._keysUp.indexOf(t)>-1:!1}triggerEvent(t,e,i){t==="down"&&this._handleKeyDown(new KeyboardEvent("keydown",{code:e,key:i!=null?i:null})),t==="up"&&this._handleKeyUp(new KeyboardEvent("keyup",{code:e,key:i!=null?i:null}))}}class wi{constructor(t,e,i,s,n,o){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=o,this.active=!0}cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}}class ha{constructor(t,e,i,s,n,o,a,h,l,c,u,_){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=o,this.index=a,this.deltaX=h,this.deltaY=l,this.deltaZ=c,this.deltaMode=u,this.ev=_,this.active=!0}cancel(){this.active=!1}}class Xn{constructor(){this.events=new X,this.lastPagePos=v.Zero,this.lastScreenPos=v.Zero,this.lastWorldPos=v.Zero,this._onPointerMove=t=>{this.lastPagePos=new v(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new v(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new v(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new v(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new v(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new v(t.worldPos.x,t.worldPos.y)},this.on("move",this._onPointerMove),this.on("down",this._onPointerDown)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_updateWorldPosition(t){const e=Be.fromPagePosition(this.lastPagePos,t);this.lastScreenPos=e.screenPos,this.lastWorldPos=e.worldPos}}var xi=(r=>(r.Pixel="Pixel",r.Line="Line",r.Page="Page",r))(xi||{}),Pe=(r=>(r[r.NoButton=-1]="NoButton",r[r.Left=0]="Left",r[r.Middle=1]="Middle",r[r.Right=2]="Right",r[r.Unknown=3]="Unknown",r))(Pe||{}),le=(r=>(r.Left="Left",r.Middle="Middle",r.Right="Right",r.Unknown="Unknown",r.NoButton="NoButton",r))(le||{}),ce=(r=>(r.Touch="Touch",r.Mouse="Mouse",r.Pen="Pen",r.Unknown="Unknown",r))(ce||{});function Ul(r){return globalThis.TouchEvent&&r instanceof globalThis.TouchEvent}function zl(r){return globalThis.PointerEvent&&r instanceof globalThis.PointerEvent}class ss{constructor(t,e){this.target=t,this.engine=e,this.events=new X,this.primary=new Xn,this._activeNativePointerIdsToNormalized=new Map,this.lastFramePointerCoords=new Map,this.currentFramePointerCoords=new Map,this.currentFramePointerDown=new Map,this.lastFramePointerDown=new Map,this.currentFrameDown=[],this.currentFrameUp=[],this.currentFrameMove=[],this.currentFrameCancel=[],this.currentFrameWheel=[],this._enabled=!0,this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}toggleEnabled(t){this._enabled=t}recreate(t,e){const i=new ss(t,e);return i.primary=this.primary,i._pointers=this._pointers,i}at(t){if(t>=this._pointers.length)for(let e=this._pointers.length-1,i=t;e<i;e++)this._pointers.push(new Xn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return this._enabled&&(e=this.currentFramePointerDown.get(t))!=null?e:!1}wasDown(t){var e;return this._enabled&&(e=this.lastFramePointerDown.get(t))!=null?e:!1}isDragging(t){return this._enabled?this.isDown(t):!1}isDragStart(t){return this._enabled?this.isDown(t)&&!this.wasDown(t):!1}isDragEnd(t){return this._enabled?!this.isDown(t)&&this.wasDown(t):!1}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}update(){this.lastFramePointerDown=new Map(this.currentFramePointerDown),this.lastFramePointerCoords=new Map(this.currentFramePointerCoords);for(const t of this.currentFrameDown){if(!t.active)continue;this.emit("down",t),this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){if(!t.active)continue;this.emit("up",t),this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){if(!t.active)continue;this.emit("move",t),this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){if(!t.active)continue;this.emit("cancel",t),this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)t.active&&(this.emit("pointerwheel",t),this.emit("wheel",t),this.primary.emit("pointerwheel",t),this.primary.emit("wheel",t));if(this.engine.currentScene.camera.hasChanged())for(const t of this._pointers)t._updateWorldPosition(this.engine)}clear(){for(const t of this.currentFrameUp){this.currentFramePointerCoords.delete(t.pointerId);const e=this._activeNativePointerIdsToNormalized.entries();for(const[i,s]of e)s===t.pointerId&&this._activeNativePointerIdsToNormalized.delete(i)}this.currentFrameDown.length=0,this.currentFrameUp.length=0,this.currentFrameMove.length=0,this.currentFrameCancel.length=0,this.currentFrameWheel.length=0}init(t){var e;if(this.engine.isDisposed())return;this.target===this.engine.canvas?this.engine.canvas.style.touchAction="none":document.body.style.touchAction="none",window.PointerEvent?(this.target.addEventListener("pointerdown",this._boundHandle),this.target.addEventListener("pointerup",this._boundHandle),this.target.addEventListener("pointermove",this._boundHandle),this.target.addEventListener("pointercancel",this._boundHandle)):(this.target.addEventListener("touchstart",this._boundHandle),this.target.addEventListener("touchend",this._boundHandle),this.target.addEventListener("touchmove",this._boundHandle),this.target.addEventListener("touchcancel",this._boundHandle),this.target.addEventListener("mousedown",this._boundHandle),this.target.addEventListener("mouseup",this._boundHandle),this.target.addEventListener("mousemove",this._boundHandle));const i={passive:!(this.engine.pageScrollPreventionMode===Qe.All||this.engine.pageScrollPreventionMode===Qe.Canvas)};if("onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,i):document.onmousewheel!==void 0?this.target.addEventListener("mousewheel",this._boundWheel,i):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,i),((e=t==null?void 0:t.grabWindowFocus)!=null?e:!0)&&(sa()||na())){const n=()=>{window.focus()};window.PointerEvent?this.target.addEventListener("pointerdown",n):(this.target.addEventListener("touchstart",n),this.target.addEventListener("mousedown",n))}}detach(){window.PointerEvent?(this.target.removeEventListener("pointerdown",this._boundHandle),this.target.removeEventListener("pointerup",this._boundHandle),this.target.removeEventListener("pointermove",this._boundHandle),this.target.removeEventListener("pointercancel",this._boundHandle)):(this.target.removeEventListener("touchstart",this._boundHandle),this.target.removeEventListener("touchend",this._boundHandle),this.target.removeEventListener("touchmove",this._boundHandle),this.target.removeEventListener("touchcancel",this._boundHandle),this.target.removeEventListener("mousedown",this._boundHandle),this.target.removeEventListener("mouseup",this._boundHandle),this.target.removeEventListener("mousemove",this._boundHandle)),"onwheel"in document.createElement("div")?this.target.removeEventListener("wheel",this._boundWheel):document.onmousewheel!==void 0?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const i=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort((s,n)=>s-n).findIndex(s=>s===t);return this._activeNativePointerIdsToNormalized.set(t,i),i}_handle(t){if(!this._enabled)return;t.preventDefault();const e=new Map;let i,s;if(Ul(t)){i=le.Unknown,s=ce.Touch;for(let n=0;n<t.changedTouches.length;n++){const o=t.changedTouches[n],a=Be.fromPagePosition(o.pageX,o.pageY,this.engine),h=n+1,l=this._normalizePointerId(h);this.currentFramePointerCoords.set(l,a),e.set(l,a)}}else{i=this._nativeButtonToPointerButton(t.button),s=ce.Mouse;const n=Be.fromPagePosition(t.pageX,t.pageY,this.engine);let o=1;zl(t)&&(o=t.pointerId,s=this._stringToPointerType(t.pointerType));const a=this._normalizePointerId(o);this.currentFramePointerCoords.set(a,n),e.set(a,n)}for(const[n,o]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new wi("down",n,i,s,o,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new wi("up",n,i,s,o,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new wi("move",n,i,s,o,t));break;case"touchcancel":case"pointercancel":this.currentFrameCancel.push(new wi("cancel",n,i,s,o,t));break}}_handleWheel(t){if(!this._enabled)return;(this.engine.pageScrollPreventionMode===Qe.All||this.engine.pageScrollPreventionMode===Qe.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(x(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,o=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,a=t.deltaZ||0;let h=xi.Pixel;t.deltaMode&&(t.deltaMode===1?h=xi.Line:t.deltaMode===2&&(h=xi.Page));const l=new ha(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,o,a,h,t);this.currentFrameWheel.push(l)}triggerEvent(t,e){const i=this.engine.screen.worldToPageCoordinates(e);window.PointerEvent?this._handle(new window.PointerEvent("pointer"+t,{pointerId:0,clientX:i.x,clientY:i.y})):this._handle(new window.MouseEvent("mouse"+t,{clientX:i.x,clientY:i.y}));const s=this.engine.currentScene.world.get(ts);s.preupdate(this.engine.currentScene,1),s.update(1)}_nativeButtonToPointerButton(t){switch(t){case Pe.NoButton:return le.NoButton;case Pe.Left:return le.Left;case Pe.Middle:return le.Middle;case Pe.Right:return le.Right;case Pe.Unknown:return le.Unknown;default:return br(t)}}_stringToPointerType(t){switch(t){case"touch":return ce.Touch;case"mouse":return ce.Mouse;case"pen":return ce.Pen;default:return ce.Unknown}}}class Yn{constructor(t){this._enabled=!0;const{pointerTarget:e,grabWindowFocus:i,engine:s,global:n}=t;this.keyboard=new aa,this.pointers=new ss(e,s),this.gamepads=new es,this.keyboard.init({global:n,grabWindowFocus:i}),this.pointers.init({grabWindowFocus:i}),this.gamepads.init(),this.inputMapper=new ia({keyboard:this.keyboard,pointers:this.pointers,gamepads:this.gamepads})}get enabled(){return this._enabled}toggleEnabled(t){this._enabled=t,this.keyboard.toggleEnabled(this._enabled),this.pointers.toggleEnabled(this._enabled),this.gamepads.toggleEnabled(this._enabled)}update(){this._enabled&&(this.inputMapper.execute(),this.keyboard.update(),this.gamepads.update())}clear(){this.keyboard.clear(),this.pointers.clear()}}class Ol{}const Hl={Initialize:"initialize",Activate:"activate",Deactivate:"deactivate",PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw",PreLoad:"preload",TransitionStart:"transitionstart",TransitionEnd:"transitionend"};function $t(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Rt{constructor(){this._logger=R.getInstance(),this.events=new X,this.camera=new Ko,this.world=new Er(this),this.physics=new Do(Jt()),this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(Vn),this.world.add(new ji(this.world,this.physics)),this.world.add(new Zi(this.world,this.physics)),this.world.add(ts),this.world.add(Wn),this.world.add(gn),this.world.add(fn),this.world.add(Gn)}get actors(){return this.world.entityManager.entities.filter(t=>t instanceof Ft)}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter(t=>t instanceof ta)}get tileMaps(){return this.world.entityManager.entities.filter(t=>t instanceof Go)}get timers(){return this._timers}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}onPreLoad(t){}onTransition(t){}onInitialize(t){}onActivate(t){}onDeactivate(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreDraw(t,e){}onPostDraw(t,e){}_initializeChildren(){for(const t of this.entities)t._initialize(this.engine)}get isInitialized(){return this._isInitialized}async _initialize(t){var e;if(!this.isInitialized){try{this.engine=t,this.physics.config=this.engine.physics,this.input=new Yn({global:t.global,pointerTarget:t.pointerScope===Fe.Canvas?t.canvas:document,grabWindowFocus:t.grabWindowFocus,engine:t}),this.camera._initialize(t),this.world.systemManager.initialize(),await this.onInitialize(t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.events.emit("initialize",new ze(t,this))}catch(i){throw this._logger.error(`Error during scene initialization for scene ${(e=t.director)==null?void 0:e.getSceneName(this)}!`),i}this._isInitialized=!0}}async _activate(t){var e,i;try{this._logger.debug("Scene.onActivate",this),this.input.toggleEnabled(!0),await this.onActivate(t)}catch(s){throw this._logger.error(`Error during scene activation for scene ${(i=(e=this.engine)==null?void 0:e.director)==null?void 0:i.getSceneName(this)}!`),s}}async _deactivate(t){return this._logger.debug("Scene.onDeactivate",this),this.input.toggleEnabled(!1),await this.onDeactivate(t)}_preupdate(t,e){this.emit("preupdate",new ne(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new re(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new ke(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new Ue(t,e,this)),this.onPostDraw(t,e)}update(t,e){var i;if(!this.isInitialized){this._logger.warnOnce(`Scene update called before initialize for scene ${(i=t.director)==null?void 0:i.getSceneName(this)}!`);return}this._preupdate(t,e);let s,n;for(s=0,n=this._cancelQueue.length;s<n;s++)this.removeTimer(this._cancelQueue[s]);this._cancelQueue.length=0;for(const o of this._timers)o.update(e);this.world.update(Pt.Update,e),this.camera&&this.camera.update(t,e),this._collectActorStats(t),this._postupdate(t,e),this.input.update()}draw(t,e){var i;if(!this.isInitialized){this._logger.warnOnce("Scene draw called before initialize!");return}this._predraw(t,e),this.world.update(Pt.Draw,e),(i=this.engine)!=null&&i.isDebug&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new Ms(t,this)),this.emit("postdebugdraw",new Ds(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){if(this.emit("entityadded",{target:t}),t instanceof Ki){xr(this._timers,t)||this.addTimer(t);return}this.world.add(t),t.scene=this}transfer(t){let e;t instanceof Tt&&t.scene&&t.scene!==this&&(e=t.scene,t.scene.world.remove(t,!1)),t instanceof Ki&&t.scene&&(e=t.scene,t.scene.removeTimer(t)),e==null||e.emit("entityremoved",{target:t}),this.add(t)}remove(t){this.emit("entityremoved",{target:t}),t instanceof Tt&&(t.isActive&&t.kill(),this.world.remove(t)),t instanceof Ki&&this.removeTimer(t)}clear(t=!0){for(let e=this.entities.length-1;e>=0;e--)this.world.remove(this.entities[e],t);for(let e=this.timers.length-1;e>=0;e--)this.removeTimer(this.timers[e])}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return e!==-1&&this._timers.splice(e,1),t}cancelTimer(t){return this._cancelQueue.push(t),t}isTimerActive(t){return this._timers.indexOf(t)>-1&&!t.complete}isCurrentScene(){return this.engine?this.engine.currentScene===this:!1}_collectActorStats(t){const e=this.actors;for(let i=0;i<e.length;i++){const s=e[i];s instanceof Hn&&t.stats.currFrame.actors.ui++,t.stats.currFrame.actors.alive++;for(let n=0;n<s.children.length;n++){const o=s.children[n];Ho(o)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}}class la{constructor(t){this._engine=t,this._colorBlindPostProcessor=new Qr(Ye.Protanope)}correct(t){this._engine.graphicsContext instanceof Xt&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!1,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}simulate(t){this._engine.graphicsContext instanceof Xt&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!0,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}clear(){this._engine.graphicsContext.removePostProcessor(this._colorBlindPostProcessor)}}class ca{constructor(t){this.stats={currFrame:new bi,prevFrame:new bi},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!1,showName:!1},this.transform={showAll:!1,debugZIndex:1e7,showPosition:!1,showPositionLabel:!1,positionColor:P.Yellow,showZIndex:!1,showScale:!1,scaleColor:P.Green,showRotation:!1,rotationColor:P.Blue},this.graphics={showAll:!1,showBounds:!1,boundsColor:P.Yellow},this.collider={showAll:!1,showBounds:!1,boundsColor:P.Blue,showOwner:!1,showGeometry:!0,geometryColor:P.Green,geometryLineWidth:1,geometryPointSize:.5},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:P.Cyan,showCollisionContacts:!0,contactSize:2,collisionContactColor:P.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:P.Yellow,showAcceleration:!1,accelerationColor:P.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:P.Red,showZoom:!1},this.tilemap={showAll:!1,showGrid:!1,gridColor:P.Red,gridWidth:.5,showSolidBounds:!1,solidBoundsColor:P.fromHex("#8080807F"),showColliderGeometry:!0},this.isometric={showAll:!1,showPosition:!1,positionColor:P.Yellow,positionSize:1,showGrid:!1,gridColor:P.Red,gridWidth:1,showColliderGeometry:!0},this._engine=t,this.colorBlindMode=new la(this._engine)}useTestClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toTestClock();return e&&i.start(),this._engine.clock=i,i}useStandardClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toStandardClock();return e&&i.start(),this._engine.clock=i,i}}class bi{constructor(){this._id=0,this._elapsedMs=0,this._fps=0,this._actorStats={alive:0,killed:0,ui:0,get remaining(){return this.alive-this.killed},get total(){return this.remaining+this.ui}},this._durationStats={update:0,draw:0,get total(){return this.update+this.draw}},this._physicsStats=new ns,this._graphicsStats={drawCalls:0,drawnImages:0}}reset(t){t?(this.id=t.id,this.elapsedMs=t.elapsedMs,this.fps=t.fps,this.actors.alive=t.actors.alive,this.actors.killed=t.actors.killed,this.actors.ui=t.actors.ui,this.duration.update=t.duration.update,this.duration.draw=t.duration.draw,this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages):(this.id=this.elapsedMs=this.fps=0,this.actors.alive=this.actors.killed=this.actors.ui=0,this.duration.update=this.duration.draw=0,this._physicsStats.reset(),this.graphics.drawnImages=this.graphics.drawCalls=0)}clone(){const t=new bi;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get elapsedMs(){return this._elapsedMs}set elapsedMs(t){this._elapsedMs=t}get fps(){return this._fps}set fps(t){this._fps=t}get actors(){return this._actorStats}get duration(){return this._durationStats}get physics(){return this._physicsStats}get graphics(){return this._graphicsStats}}class ns{constructor(){this._pairs=0,this._collisions=0,this._contacts=new Map,this._fastBodies=0,this._fastBodyCollisions=0,this._broadphase=0,this._narrowphase=0}reset(t){t?(this.pairs=t.pairs,this.collisions=t.collisions,this.contacts=t.contacts,this.fastBodies=t.fastBodies,this.fastBodyCollisions=t.fastBodyCollisions,this.broadphase=t.broadphase,this.narrowphase=t.narrowphase):(this.pairs=this.collisions=this.fastBodies=0,this.fastBodyCollisions=this.broadphase=this.narrowphase=0,this.contacts.clear())}clone(){const t=new ns;return t.reset(this),t}get pairs(){return this._pairs}set pairs(t){this._pairs=t}get collisions(){return this._collisions}set collisions(t){this._collisions=t}get contacts(){return this._contacts}set contacts(t){this._contacts=t}get fastBodies(){return this._fastBodies}set fastBodies(t){this._fastBodies=t}get fastBodyCollisions(){return this._fastBodyCollisions}set fastBodyCollisions(t){this._fastBodyCollisions=t}get broadphase(){return this._broadphase}set broadphase(t){this._broadphase=t}get narrowphase(){return this._narrowphase}set narrowphase(t){this._narrowphase=t}}class $n{constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}on(t,e){this._nativeHandlers[t]&&this.off(t,this._nativeHandlers[t]),this._nativeHandlers[t]=this._decorate(e),this.nativeComponent.addEventListener(t,this._nativeHandlers[t])}off(t,e){e||(e=this._nativeHandlers[t]),this.nativeComponent.removeEventListener(t,e),this._nativeHandlers[t]=null}_decorate(t){return e=>{this._paused||t(e)}}pause(){this._paused=!0}resume(){this._paused=!1}clear(){for(const t in this._nativeHandlers)this.off(t)}}class da{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new $n(this._windowGlobal),this._documentComponent=new $n(this._documentGlobal)}get window(){return this._windowComponent}get document(){return this._documentComponent}pause(){this.window.pause(),this.document.pause()}resume(){this.window.resume(),this.document.resume()}clear(){this.window.clear(),this.document.clear()}}class ua{constructor(t){this._samplePeriod=100,this._currentFrameTime=0,this._frames=0,this._previousSampleTime=0,this._beginFrameTime=0;var e;this._fps=t.initialFps,this._samplePeriod=(e=t.samplePeriod)!=null?e:this._samplePeriod,this._currentFrameTime=1e3/t.initialFps,this._nowFn=t.nowFn,this._previousSampleTime=this._nowFn()}start(){this._beginFrameTime=this._nowFn()}end(){this._frames++;const t=this._nowFn();this._currentFrameTime=t-this._beginFrameTime,t>=this._previousSampleTime+this._samplePeriod&&(this._fps=this._frames*1e3/(t-this._previousSampleTime),this._previousSampleTime=t,this._frames=0)}get fps(){return this._fps}get instant(){return 1e3/this._currentFrameTime}}class jn{constructor(t){this._onFatalException=()=>{},this._maxFps=1/0,this._lastTime=0,this._elapsed=1,this._scheduledCbs=[],this._totalElapsed=0,this._nextScheduleId=0,this._idsToRemove=[];var e,i,s;this._options=t,this.tick=t.tick,this._lastTime=(e=this.now())!=null?e:0,this._maxFps=(i=t.maxFps)!=null?i:this._maxFps,this._onFatalException=(s=t.onFatalException)!=null?s:this._onFatalException,this.fpsSampler=new ua({initialFps:60,nowFn:()=>this.now()})}elapsed(){return this._elapsed}now(){return performance.now()}toTestClock(){return new _a({...this._options,defaultUpdateMs:16.6})}toStandardClock(){return new Zn({...this._options})}setFatalExceptionHandler(t){this._onFatalException=t}schedule(t,e=0,i="preframe"){const s=this._totalElapsed+e,n=this._nextScheduleId++;return this._scheduledCbs.push([n,t,s,i]),n}clearSchedule(t){this._idsToRemove.push(t)}__runScheduledCbs(t="preframe"){for(let e=this._scheduledCbs.length-1;e>-1;e--){const[i,s,n,o]=this._scheduledCbs[e];this._idsToRemove.includes(i)||t===o&&n<=this._totalElapsed&&(s(this._elapsed),this._scheduledCbs.splice(e,1))}for(const e of this._idsToRemove){const i=this._scheduledCbs.findIndex(([s])=>s===e);i!==-1&&this._scheduledCbs.splice(i,1)}}update(t){try{this.fpsSampler.start();const e=this.now();let i=e-this._lastTime||1;const s=1e3/this._maxFps;if(i>=s){let n=0;s!==0&&(n=i%s,i=i-n),i>200&&(i=1),this._elapsed=t||i,this._totalElapsed+=this._elapsed,this.__runScheduledCbs("preframe"),this.tick(t||i),this.__runScheduledCbs("postframe"),s!==0?this._lastTime=e-n:this._lastTime=e,this.fpsSampler.end()}}catch(e){this._onFatalException(e),this.stop()}}}class Zn extends jn{constructor(t){super(t),this._running=!1}isRunning(){return this._running}start(){if(this._running)return;this._running=!0;const t=()=>{if(this._running)try{this._requestId=window.requestAnimationFrame(t),this.update()}catch(e){throw window.cancelAnimationFrame(this._requestId),e}};t()}stop(){window.cancelAnimationFrame(this._requestId),this._running=!1}}class _a extends jn{constructor(t){super({...t}),this._logger=R.getInstance(),this._running=!1,this._currentTime=0,this._updateMs=t.defaultUpdateMs}now(){var t;return(t=this._currentTime)!=null?t:0}isRunning(){return this._running}start(){this._running=!0}stop(){this._running=!1}step(t){const e=t!=null?t:this._updateMs;this._running?(this.update(e),this._currentTime+=e):this._logger.warn("The clock is not running, no step will be performed")}run(t,e){for(let i=0;i<t;i++)this.step(e!=null?e:this._updateMs)}}const Nl="#ex-toast-container{position:absolute;height:0;min-width:50%;left:50%;top:0}.ex-toast-message{left:-50%;position:relative;display:flex;justify-content:space-between;padding:10px;margin-top:5px;font-size:18px;font-family:sans-serif;border-radius:6px;border:3px solid #b7b779;background-color:#fdfdc0}.ex-toast-message button{align-self:flex-start}";class fa{constructor(){this._toasterCss=Nl,this._isInitialized=!1}_initialize(){this._isInitialized||(this._container=document.createElement("div"),this._container.id="ex-toast-container",document.body.appendChild(this._container),this._isInitialized=!0,this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._toasterCss,document.head.appendChild(this._styleBlock))}dispose(){this._container.parentElement.removeChild(this._container),this._styleBlock.parentElement.removeChild(this._styleBlock),this._isInitialized=!1}_createFragment(t){const e=document.createElement("span");return e.innerText=t,e}toast(t,e,i){this._initialize();const s=document.createElement("div");s.className="ex-toast-message";const n=t.split("[LINK]").map(c=>this._createFragment(c));if(e){const c=document.createElement("a");c.href=e,i?c.innerText=i:c.innerText=e,n.splice(1,0,c)}const o=document.createElement("div");n.forEach(c=>{o.appendChild(c)}),s.appendChild(o);const a=document.createElement("button");a.innerText="x",a.addEventListener("click",()=>{this._container.removeChild(s)}),s.appendChild(a);const h=c=>{if(c.key==="Escape")try{this._container.removeChild(s)}catch(u){}document.removeEventListener("keydown",h)};document.addEventListener("keydown",h);const l=this._container.firstChild;this._container.insertBefore(s,l)}}const ga={NavigationStart:"navigationstart",Navigation:"navigation",NavigationEnd:"navigationend"};class pa{constructor(t,e){this._engine=t,this.events=new X,this._logger=R.getInstance(),this._initialized=!1,this.scenes={},this._sceneToInstance=new Map,this._sceneToLoader=new Map,this._sceneToTransition=new Map,this._loadedScenes=new Set,this._isTransitioning=!1,this.rootScene=this.currentScene=new Rt,this.add("root",this.rootScene),this.currentScene=this.rootScene,this.currentSceneName="root";for(const i in e){const s=e[i];this.add(i,s),i==="root"&&(this.rootScene=this.getSceneInstance("root"),this.currentScene=this.rootScene)}}get isTransitioning(){return this._isTransitioning}async onInitialize(){if(!this._initialized)if(this._initialized=!0,this._deferredGoto){const t=this._deferredGoto;this._deferredGoto=void 0;const e=this._deferredTransition;this._deferredTransition=void 0;const i=this.getSceneInstance(t);i&&e&&e._addToTargetScene(this._engine,i);const s=this._getInTransition(t),n=s==null?void 0:s.hideLoader;this.maybeLoadScene(t,n),await this.swapScene(t),i&&e&&await this.playTransition(e,i)}else await this.swapScene("root")}get isInitialized(){return this._initialized}configureStart(t,e){var i,s;const n=e==null?void 0:e.loader;n instanceof pi?this.mainLoader=n:On(n)?this.mainLoader=new n:this.mainLoader=new Ji;let o;if(e!=null&&e.inTransition){const{inTransition:h}=e;o=h}this.startScene=t;const a=(s=(i=e==null?void 0:e.inTransition)==null?void 0:i.hideLoader)!=null?s:!1;if(this.maybeLoadScene(t,a),o){const h=this.getSceneInstance(t);h&&(o._addToTargetScene(this._engine,h),this.swapScene(t).then(()=>(h.onTransition("in"),this.playTransition(o,h))))}else this.swapScene(t);this.currentSceneName=this.startScene}_getLoader(t){return this._sceneToLoader.get(t)}_getInTransition(t){var e;const i=this.scenes[t];if(!(i instanceof Rt||$t(i)))return(e=i==null?void 0:i.transitions)==null?void 0:e.in}_getOutTransition(t){var e;const i=this.scenes[t];if(!(i instanceof Rt||$t(i)))return(e=i==null?void 0:i.transitions)==null?void 0:e.out}getDeferredScene(){const t=this.getSceneDefinition(this._deferredGoto);return this._deferredGoto&&t?t:null}getSceneDefinition(t){const e=this.scenes[t];if(e instanceof Rt||$t(e))return e;if(e)return e.scene}getSceneName(t){for(const[e,i]of Object.entries(this.scenes))if(i instanceof Rt){if(t===i)return e}else if(!$t(i)&&t===i.scene)return e;for(const[e,i]of Object.entries(this.scenes))if($t(i)){if(t.constructor===i)return e}else if(!(i instanceof Rt)&&t.constructor===i.scene)return e;return null}assertAdded(t){return this}assertRemoved(t){return this}add(t,e){if(!(e instanceof Rt)&&!$t(e)){const{loader:i,transitions:s}=e,{in:n,out:o}=s!=null?s:{};this._sceneToTransition.set(t,{in:n,out:o}),On(i)?this._sceneToLoader.set(t,new i):i&&this._sceneToLoader.set(t,i)}return this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e,this.assertAdded(t)}remove(t){if(t instanceof Rt||$t(t)){const e=t;for(const i in this.scenes)if(this.scenes.hasOwnProperty(i)){const s=this.scenes[i];let n;if(s instanceof Rt||$t(s)?n=s:n=s.scene,n===e){if(i===this.currentSceneName)throw new Error(`Cannot remove a currently active scene: ${i}`);this._sceneToInstance.delete(i),this._sceneToTransition.delete(i),this._sceneToLoader.delete(i),delete this.scenes[i]}}}if(typeof t=="string"){if(t===this.currentSceneName)throw new Error(`Cannot remove a currently active scene: ${t}`);this._sceneToInstance.delete(t),this._sceneToTransition.delete(t),this._sceneToLoader.delete(t),delete this.scenes[t]}}async goToScene(t,e){var i,s,n,o,a,h;const l=this.getSceneInstance(t);if(!l){this._logger.warn(`Scene ${t} does not exist! Check the name, are you sure you added it?`);return}const c=this.currentScene,u=this.currentSceneName,_=(s=(i=this._engine.input)==null?void 0:i.enabled)!=null?s:!0;this._isTransitioning=!0;const f=(n=this.getSceneInstance(u))==null?void 0:n.onTransition("out"),p=l==null?void 0:l.onTransition("in");e={sourceOut:(o=this._getOutTransition(this.currentSceneName))!=null?o:f,destinationIn:(a=this._getInTransition(t))!=null?a:p,...e};const{sourceOut:g,destinationIn:w,sceneActivationData:m}=e,b=g!=null?g:this._getOutTransition(this.currentSceneName),T=w!=null?w:this._getInTransition(t),C=(b==null?void 0:b.hideLoader)||(T==null?void 0:T.hideLoader);C&&this.maybeLoadScene(t,C),this._emitEvent("navigationstart",u,t),b&&await this.playTransition(b,c),await this.maybeLoadScene(t,C),T&&await T.onPreviousSceneDeactivate(this.currentScene),T&&T._addToTargetScene(this._engine,l),await this.swapScene(t,m),this._emitEvent("navigation",u,t),T&&await this.playTransition(T,l),this._emitEvent("navigationend",u,t),(h=this._engine.input)==null||h.toggleEnabled(_),this._isTransitioning=!1}getSceneInstance(t){const e=this.getSceneDefinition(t);if(!e)return;if(this._sceneToInstance.has(t))return this._sceneToInstance.get(t);if(e instanceof Rt)return this._sceneToInstance.set(t,e),e;const i=new e;return this._sceneToInstance.set(t,i),i}async maybeLoadScene(t,e=!1){var i;const s=(i=this._getLoader(t))!=null?i:new pi,n=this.getSceneDefinition(t),o=this.getSceneInstance(t);n&&o&&!this._loadedScenes.has(o)&&(o.onPreLoad(s),o.events.emit("preload",{loader:s}),e?this._engine.load(s,e):await this._engine.load(s),this._loadedScenes.add(o))}async playTransition(t,e){var i,s,n,o,a,h,l;if(!this.isInitialized){this._deferredTransition=t;return}if(t){this.currentTransition=t;const c=(s=(i=e.input)==null?void 0:i.enabled)!=null?s:!0;(n=e.input)==null||n.toggleEnabled(!t.blockInput),(o=this._engine.input)==null||o.toggleEnabled(!t.blockInput),e.events.emit("transitionstart",t),this.currentTransition._addToTargetScene(this._engine,e),await this.currentTransition._play(),e.events.emit("transitionend",t),(a=e.input)==null||a.toggleEnabled(c)}(h=this.currentTransition)==null||h.kill(),(l=this.currentTransition)==null||l.reset(),this.currentTransition=void 0}async swapScene(t,e){const i=this._engine;if(!this.isInitialized){this._deferredGoto=t;return}const s=this.getSceneInstance(t);if(s){const n=this.currentScene,o=s;let a;if(this._logger.debug("Going to scene:",t),this.currentScene.isInitialized){const c={engine:i,previousScene:n,nextScene:o};a=await this.currentScene._deactivate(c),this.currentScene.events.emit("deactivate",new Ws(c,this.currentScene)),this.currentScene.input.clear()}const h=this._sceneToLoader.get(t);await(h==null?void 0:h.areResourcesLoaded()),this.currentScene=o,this.currentSceneName=t,i.screen.setCurrentCamera(o.camera),await this.currentScene._initialize(i);const l={engine:i,previousScene:n,previousSceneData:a,nextScene:o,data:e};await this.currentScene._activate(l),this.currentScene.events.emit("activate",new Ns(l,this.currentScene))}else this._logger.error("Scene",t,"does not exist!")}_emitEvent(t,e,i){const s=this.getSceneDefinition(e),n=this.getSceneDefinition(i);this.events.emit(t,{sourceScene:s,sourceName:e,destinationScene:n,destinationName:i})}}function ma(){const r={scope:(t,e)=>{const i=r.value;r.value=t;try{const s=e();return s&&typeof s.then=="function"?s.finally(()=>{r.value=i}):s}catch(s){throw s}finally{r.value=i}},value:void 0};return r}function va(r){return r.value}const Qn={textureCollectInterval:6e4};class wa{constructor(t){this.options=t,this._running=!1,this._collectionMap=new Map,this._collectors=new Map,this.collectStaleResources=e=>{if(this._running){for(const[i,[s,n]]of this._collectors.entries()){const o=this.options.getTimestamp();for(const[a,[h,l]]of this._collectionMap.entries()){if(i!==h||l+n>=o)continue;s(a)&&this._collectionMap.delete(a)}}this._collectHandle=requestIdleCallback(this.collectStaleResources)}}}registerCollector(t,e,i){this._collectors.set(t,[i,e])}addCollectableResource(t,e){this._collectionMap.set(e,[t,this.options.getTimestamp()])}touch(t){const e=this._collectionMap.get(t);e&&this._collectionMap.set(t,[e[0],this.options.getTimestamp()])}forceCollectAll(){for(const[t,[e]]of this._collectors.entries())for(const[i]of this._collectionMap.entries())e(i)&&this._collectionMap.delete(i)}running(){return this._running}start(){this._running=!0,this.collectStaleResources()}stop(){this._running=!1,cancelIdleCallback(this._collectHandle)}}Me();const Wl={FallbackGraphicsContext:"fallbackgraphicscontext",Initialize:"initialize",Visible:"visible",Hidden:"hidden",Start:"start",Stop:"stop",PreUpdate:"preupdate",PostUpdate:"postupdate",PreFrame:"preframe",PostFrame:"postframe",PreDraw:"predraw",PostDraw:"postdraw",...ga};var Qe=(r=>(r[r.None=0]="None",r[r.Canvas=1]="Canvas",r[r.All=2]="All",r))(Qe||{});const rs=class ue{constructor(t){this.scope=S=>ue.Context.scope(this,S),this.version=er,this.events=new X,this.maxFps=Number.POSITIVE_INFINITY,this._inputEnabled=!0,this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.enableCanvasTransparency=!0,this.onFatalException=S=>{R.getInstance().fatal(S,S.stack)},this._toaster=new fa,this._timescale=1,this._isInitialized=!1,this._hasCreatedCanvas=!1,this._originalOptions={},this._handleWebGLContextLost=S=>{var I;S.preventDefault(),this.clock.stop(),this._logger.fatalOnce("WebGL Graphics Lost",S);const y=document.createElement("div");y.id="ex-webgl-graphics-context-lost",y.style.position="absolute",y.style.zIndex="99",y.style.left="50%",y.style.top="50%",y.style.display="flex",y.style.flexDirection="column",y.style.transform="translate(-50%, -50%)",y.style.backgroundColor="white",y.style.padding="10px",y.style.borderStyle="solid 1px";const k=document.createElement("div");if(k.innerHTML=`
|
|
897
|
+
`;e.unshift(t),console.log.apply(console,e)}_loadBrowserFeatures(){return{canvas:this._criticalTests.canvasSupport(),arraybuffer:this._criticalTests.arrayBufferSupport(),dataurl:this._criticalTests.dataUrlSupport(),objecturl:this._criticalTests.objectUrlSupport(),rgba:this._criticalTests.rgbaSupport(),webaudio:this._warningTest.webAudioSupport(),webgl:this._warningTest.webglSupport(),gamepadapi:!!navigator.getGamepads}}test(){let t=!1;for(const e in this._criticalTests)this._criticalTests[e].call(this)||(this.failedTests.push(e),R.getInstance().error("Critical browser feature missing, Excalibur requires:",e),t=!0);if(t)return!1;for(const e in this._warningTest)this._warningTest[e]()||R.getInstance().warn("Warning browser feature missing, Excalibur will have reduced performance:",e);return!0}}function Ho(r){return r instanceof Hn}class Hn extends kt{constructor(t){var e,i;super({...t}),this.get(P).coordPlane=rt.Screen,this.anchor=(e=t==null?void 0:t.anchor)!=null?e:b(0,0),this.body.collisionType=(i=t==null?void 0:t.collisionType)!=null?i:M.PreventCollision,this.pointer.useGraphicsBounds=!0,this.pointer.useColliderShape=!1,!(t!=null&&t.collider)&&(t==null?void 0:t.width)>0&&(t==null?void 0:t.height)>0&&this.collider.useBoxCollider(this.width,this.height,this.anchor)}_initialize(t){this._engine=t,super._initialize(t)}contains(t,e,i=!0){if(i)return super.contains(t,e);const s=this._engine.worldToScreenCoordinates(new w(t,e));return super.contains(s.x,s.y)}}const No=class za{constructor(t){this._logger=R.getInstance(),this.id=0,this._elapsedTime=0,this._totalTimeAlive=0,this._running=!1,this._numberOfTicks=0,this.interval=10,this.repeats=!1,this.maxNumberOfRepeats=-1,this.randomRange=[0,0],this._baseInterval=10,this._generateRandomInterval=()=>this._baseInterval+this.random.integer(this.randomRange[0],this.randomRange[1]),this._complete=!1,this.scene=null;var e;const i=(e=t.action)!=null?e:t.fcn,s=t.interval,n=t.repeats,o=t.numberOfRepeats,a=t.randomRange,h=t.random;if(o&&o>=0&&(this.maxNumberOfRepeats=o,!n))throw new Error("repeats must be set to true if numberOfRepeats is set");if(this.id=za._MAX_ID++,this._callbacks=[],this._baseInterval=this.interval=s,a){if(a[0]>a[1])throw new Error("min value must be lower than max value for range");this.random=h!=null?h:new se,this.randomRange=a,this.interval=this._generateRandomInterval(),this.on(()=>{this.interval=this._generateRandomInterval()})}this.repeats=n||this.repeats,i&&this.on(i)}get complete(){return this._complete}on(t){this._callbacks.push(t)}off(t){const e=this._callbacks.indexOf(t);this._callbacks.splice(e,1)}update(t){this._running&&(this._totalTimeAlive+=t,this._elapsedTime+=t,this.maxNumberOfRepeats>-1&&this._numberOfTicks>=this.maxNumberOfRepeats&&(this._complete=!0,this._running=!1,this._elapsedTime=0),!this.complete&&this._elapsedTime>=this.interval&&(this._callbacks.forEach(e=>{e.call(this)}),this._numberOfTicks++,this.repeats?this._elapsedTime=0:(this._complete=!0,this._running=!1,this._elapsedTime=0)))}reset(t,e){if(t&&t>=0&&(this._baseInterval=this.interval=t),this.maxNumberOfRepeats&&this.maxNumberOfRepeats>=0&&(this.maxNumberOfRepeats=e,!this.repeats))throw new Error("repeats must be set to true if numberOfRepeats is set");this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0}get timesRepeated(){return this._numberOfTicks}getTimeRunning(){return this._totalTimeAlive}get timeToNextAction(){return this.complete?0:this.interval-this._elapsedTime}get timeElapsedTowardNextAction(){return this._elapsedTime}get isRunning(){return this._running}pause(){return this._running=!1,this}resume(){return this._running=!0,this}start(){return this.scene||this._logger.warn("Cannot start a timer not part of a scene, timer wont start until added"),this._running=!0,this.complete&&(this._complete=!1,this._elapsedTime=0,this._numberOfTicks=0),this}stop(){return this._running=!1,this._elapsedTime=0,this._numberOfTicks=0,this}cancel(){this.pause(),this.scene&&this.scene.cancelTimer(this)}};No._MAX_ID=0;let es=No;function Wo(r){return r&&r._dispatchPointerEvents&&r._processPointerToObject}class kl{get events(){return this.object.events}init(t,e,i){this.object=t,this.contains=e,this.active=i}}class Nn{constructor(){this._proxyPool=new qe(()=>new kl,t=>t,100),this._objectToProxy=new Map,this._proxies=[],this._lastFrameObjectToPointers=new Map,this._currentFrameObjectToPointers=new Map}addObject(t,e,i){const s=this._proxyPool.rent(!1);s.init(t,e,i),this._proxies.push(s),this._objectToProxy.set(t,s)}_getProxy(t){const e=this._objectToProxy.get(t);if(e)return e;throw new Error("No PointerTargetProxy for object")}removeObject(t){const e=this._objectToProxy.get(t);if(e){const i=this._proxies.indexOf(e);this._objectToProxy.delete(t),i>-1&&this._proxies.splice(i,1),this._proxyPool.return(e)}}_objectCurrentlyUnderPointer(t,e){return!!(this._currentFrameObjectToPointers.has(t)&&this._currentFrameObjectToPointers.get(t).includes(e))}_objectWasUnderPointer(t,e){return!!(this._lastFrameObjectToPointers.has(t)&&this._lastFrameObjectToPointers.get(t).includes(e))}_entered(t,e){return this._objectCurrentlyUnderPointer(t,e)&&!this._lastFrameObjectToPointers.has(t)}_left(t,e){return!this._currentFrameObjectToPointers.has(t)&&this._objectWasUnderPointer(t,e)}addPointerToObject(t,e){const i=this._objectToProxy.get(t);i&&this._addPointerToProxy(i,e)}_addPointerToProxy(t,e){if(!this._currentFrameObjectToPointers.has(t)){this._currentFrameObjectToPointers.set(t,[e]);return}const i=this._currentFrameObjectToPointers.get(t);this._currentFrameObjectToPointers.set(t,i.concat(e))}dispatchEvents(t,e){const i=new Set(this._lastFrameObjectToPointers.keys()),s=new Set(this._currentFrameObjectToPointers.keys());let n,o,a,h=[];if(e)for(let l=0;l<e.length;l++){const c=e[l],u=this._getProxy(c);h.push(u)}else{const l=new Set(i);for(const c of s)l.add(c);h=Array.from(l)}for(let l=0;l<h.length;l++){const c=h[l];if(Wo(c.object)&&c.object._dispatchPointerEvents(t),i.has(c)||s.has(c)){a=this._processDownAndEmit(t,c),o=this._processUpAndEmit(t,c),n=this._processMoveAndEmit(t,c);const u=[...n.values(),...a.values(),...o.values()];this._processEnterLeaveAndEmit(t,c,u),this._processCancelAndEmit(t,c),this._processWheelAndEmit(t,c)}}}processPointerToObject(t,e){for(let i=0;i<e.length;i++){const s=e[i],n=this._getProxy(s);Wo(s)&&s._processPointerToObject(t);for(const[o,a]of t.currentFramePointerCoords.entries())n.contains(a)&&this._addPointerToProxy(n,o)}}clear(){this._lastFrameObjectToPointers.clear(),this._lastFrameObjectToPointers=new Map(this._currentFrameObjectToPointers),this._currentFrameObjectToPointers.clear()}_processDownAndEmit(t,e){const i=new Map;for(const s of t.currentFrameDown)s.active&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointerdown",s),t.isDragStart(s.pointerId)&&e.events.emit("pointerdragstart",s)),i.set(s.pointerId,s);return i}_processUpAndEmit(t,e){const i=new Map;for(const s of t.currentFrameUp)s.active&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointerup",s),t.isDragEnd(s.pointerId)&&e.events.emit("pointerdragend",s)),i.set(s.pointerId,s);return i}_processMoveAndEmit(t,e){const i=new Map;for(const s of t.currentFrameMove)s.active&&e.active()&&this._objectCurrentlyUnderPointer(e,s.pointerId)&&(e.events.emit("pointermove",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragmove",s)),i.set(s.pointerId,s);return i}_processEnterLeaveAndEmit(t,e,i){for(const s of i){if(s.active&&e.active()&&this._entered(e,s.pointerId)){e.events.emit("pointerenter",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragenter",s);break}if(s.active&&e.active()&&(this._left(e,s.pointerId)||this._objectCurrentlyUnderPointer(e,s.pointerId)&&s.type==="up")){e.events.emit("pointerleave",s),t.isDragging(s.pointerId)&&e.events.emit("pointerdragleave",s);break}}}_processCancelAndEmit(t,e){for(const i of t.currentFrameCancel)i.active&&e.active()&&this._objectCurrentlyUnderPointer(e,i.pointerId)&&e.events.emit("pointercancel",i)}_processWheelAndEmit(t,e){for(const i of t.currentFrameWheel)i.active&&e.active()&&this._objectCurrentlyUnderPointer(e,0)&&e.events.emit("pointerwheel",i)}}const Ll={PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PointerUp:"pointerup",PointerDown:"pointerdown",PointerMove:"pointermove",PointerCancel:"pointercancel"};class Go extends At{constructor(t){var e,i,s;super([],t.name),this.events=new X,this._token=0,this.logger=R.getInstance(),this.tiles=[],this._rows=[],this._cols=[],this.renderFromTopOfGraphic=!1,this.meshingLookBehind=10,this._collidersDirty=!0,this._oldRotation=0,this._originalOffsets=new WeakMap,this.meshingLookBehind=(e=t.meshingLookBehind)!=null?e:this.meshingLookBehind,this.addComponent(new P),this.addComponent(new O),this.addComponent(new N({type:M.Fixed})),this.addComponent(new K({onPostDraw:(o,a)=>this.draw(o,a)})),this.addComponent(new Gi((o,a)=>this.debug(o,a),!1)),this.addComponent(new tt),this.addComponent(new he),this.pointer=this.get(he),this._graphics=this.get(K),this.transform=this.get(P),this._motion=this.get(O),this.collider=this.get(tt),this._composite=this.collider.useCompositeCollider([]),this.transform.pos=(i=t.pos)!=null?i:w.Zero,this._oldPos=this.transform.pos.clone(),this._oldScale=this.transform.scale.clone(),this.renderFromTopOfGraphic=(s=t.renderFromTopOfGraphic)!=null?s:this.renderFromTopOfGraphic,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight,this.rows=t.rows,this.columns=t.columns,this._pointerEventDispatcher=new Nn,this.tiles=new Array(this.rows*this.columns),this._rows=new Array(this.rows),this._cols=new Array(this.columns);let n=[];for(let o=0;o<this.columns;o++){for(let a=0;a<this.rows;a++){const h=new Vo({x:o,y:a,map:this});h.map=this,this.tiles[o+a*this.columns]=h,this._pointerEventDispatcher.addObject(h,l=>h.bounds.contains(l.worldPos),()=>!0),n.push(h),this._rows[a]||(this._rows[a]=[]),this._rows[a].push(h)}this._cols[o]=n,n=[]}this._graphics.localBounds=new F({left:0,top:0,right:this.columns*this.tileWidth*this.scale.x,bottom:this.rows*this.tileHeight*this.scale.y})}flagCollidersDirty(){this._collidersDirty=!0}flagTilesDirty(){for(let t=0;t<this.tiles.length;t++)this.tiles[t]&&this.tiles[t].flagDirty()}get x(){var t;return(t=this.transform.pos.x)!=null?t:0}set x(t){var e;(e=this.transform)!=null&&e.pos&&(this.get(P).pos=b(t,this.y))}get y(){var t,e;return(e=(t=this.transform)==null?void 0:t.pos.y)!=null?e:0}set y(t){var e;(e=this.transform)!=null&&e.pos&&(this.transform.pos=b(this.x,t))}get z(){var t;return(t=this.transform.z)!=null?t:0}set z(t){this.transform&&(this.transform.z=t)}get rotation(){var t,e;return(e=(t=this.transform)==null?void 0:t.rotation)!=null?e:0}set rotation(t){this.transform&&(t!==this.transform.rotation&&(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.rotation=t)}get scale(){var t,e;return(e=(t=this.transform)==null?void 0:t.scale)!=null?e:w.One}set scale(t){this.transform&&(t!=null&&t.equals(this.transform.scale)||(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.scale=t)}get pos(){return this.transform.pos}set pos(t){this.transform&&(t!=null&&t.equals(this.transform.pos)||(this.flagCollidersDirty(),this.flagTilesDirty()),this.transform.pos=t)}get vel(){return this._motion.vel}set vel(t){this._motion.vel=t}get width(){return this.tileWidth*this.columns*this.scale.x}get height(){return this.tileHeight*this.rows*this.scale.y}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_initialize(t){super._initialize(t),this._engine=t}_getOrSetColliderOriginalOffset(t){var e;if(this._originalOffsets.has(t))return(e=this._originalOffsets.get(t))!=null?e:w.Zero;{const i=t.offset;return this._originalOffsets.set(t,i),i}}_updateColliders(){this.collider.$colliderRemoved.notifyAll(this._composite),this._composite.clearColliders();const t=[];this._composite=this.collider.useCompositeCollider([]);let e=null;const i=(n,o)=>n&&o?n.top===o.top&&n.bottom===o.bottom&&n.right===o.left:!1,s=(n,o,a=this.meshingLookBehind)=>{if(!n)return!1;for(let h=o.length-1;h>=0;h--){if(a--<0)return!1;const l=o[h];if(i(l,n))return o[h]=l.combine(n),!0}return!1};for(let n=0;n<this.columns;n++){for(let o=0;o<this.rows;o++){const a=this.tiles[n+o*this.columns];if(a.solid)if(a.getColliders().length>0){for(const h of a.getColliders()){const l=this._getOrSetColliderOriginalOffset(h);h.offset=b(a.x*this.tileWidth*this.scale.x,a.y*this.tileHeight*this.scale.y).add(l),h.owner=this,this._composite.addCollider(h)}e&&!s(e,t)&&t.push(e),e=null}else e?e=e.combine(a.defaultGeometry):e=a.defaultGeometry;else e&&!s(e,t)&&t.push(e),e=null}e&&!s(e,t)&&t.push(e),e=null}for(const n of t){const o=ut.Box(n.width,n.height,w.Zero,b(n.left-this.pos.x,n.top-this.pos.y));o.owner=this,this._composite.addCollider(o)}this.collider.update(),this.collider.$colliderAdded.notifyAll(this._composite)}getTileByIndex(t){var e;return(e=this.tiles[t])!=null?e:null}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const{x:e,y:i}=this._getTileCoordinates(t),s=this.getTile(e,i);return e>=0&&i>=0&&e<this.columns&&i<this.rows&&s?s:null}_getTileCoordinates(t){t=this.transform.applyInverse(t);const e=Math.floor(t.x/this.tileWidth),i=Math.floor(t.y/this.tileHeight);return{x:e,y:i}}getRows(){return this._rows}getColumns(){return this._cols}getOnScreenTiles(){const t=this._engine.screen.getWorldBounds();let e=b(0,0),i=this.transform.coordPlane===rt.Screen?this._engine.screen.getScreenBounds():t;const s=this.get(Vi);if(s&&this.isInitialized){const m=w.One.sub(s.parallaxFactor);e=this._engine.currentScene.camera.pos.scale(m),i=i.translate(e.negate())}const n=this._getTileCoordinates(i.topLeft),o=this._getTileCoordinates(i.topRight),a=this._getTileCoordinates(i.bottomRight),h=this._getTileCoordinates(i.bottomLeft),l=Math.min(B(n.x,0,this.columns-1),B(o.x,0,this.columns-1)),c=Math.min(B(n.y,0,this.rows-1),B(o.y,0,this.rows-1)),u=Math.max(B(a.x,0,this.columns-1),B(h.x,0,this.columns-1)),_=Math.max(B(a.y,0,this.rows-1),B(h.y,0,this.rows-1)),f=[];for(let m=l;m<=u;m++)for(let p=c;p<=_;p++)f.push(this.getTile(m,p));return f}_processPointerToObject(t){const e=Array.from(t.currentFramePointerCoords.entries());for(const[i,s]of e){const n=this.getTileByPoint(this.transform.coordPlane===rt.World?s.worldPos:s.screenPos);n&&this._pointerEventDispatcher.addPointerToObject(n,i)}}_dispatchPointerEvents(t){this._pointerEventDispatcher.dispatchEvents(t)}update(t,e){this._initialize(t),this.onPreUpdate(t,e),this.emit("preupdate",new re(t,e,this)),(!this._oldPos.equals(this.pos)||this._oldRotation!==this.rotation||!this._oldScale.equals(this.scale))&&(this.flagCollidersDirty(),this.flagTilesDirty()),this._collidersDirty&&(this._collidersDirty=!1,this._updateColliders()),this._pointerEventDispatcher.clear(),this._token++,this.pos.clone(this._oldPos),this._oldRotation=this.rotation,this.scale.clone(this._oldScale),this.transform.pos=this.pos,this.onPostUpdate(t,e),this.emit("postupdate",new oe(t,e,this))}draw(t,e){if(!this.isInitialized)return;this.emit("predraw",new Ue(t,e,this));let i,s,n;const o=this.getOnScreenTiles();for(let a=0;a<o.length;a++){const h=o[a],l=h.getGraphicsOffsets();for(i=h.getGraphics(),s=0,n=i.length;s<n;s++){const c=i[s],u=l[s];if(c){Sn(c)&&(c==null||c.tick(e,this._token));const _=this.renderFromTopOfGraphic?0:c.height-this.tileHeight;c.draw(t,h.x*this.tileWidth+u.x,h.y*this.tileHeight-_+u.y)}}}this.emit("postdraw",new ze(t,e,this))}debug(t,e){const{showAll:i,showGrid:s,gridColor:n,gridWidth:o,showSolidBounds:a,solidBoundsColor:h,showColliderGeometry:l}=e.tilemap,{geometryColor:c,geometryLineWidth:u,geometryPointSize:_}=e.collider,f=this.tileWidth*this.columns*this.scale.x,m=this.tileHeight*this.rows*this.scale.y,p=this.pos;if(s||i){for(let x=0;x<this.rows+1;x++){const v=b(0,x*this.tileHeight*this.scale.y);t.drawLine(p.add(v),p.add(b(f,v.y)),n,o)}for(let x=0;x<this.columns+1;x++){const v=b(x*this.tileWidth*this.scale.x,0);t.drawLine(p.add(v),p.add(b(v.x,m)),n,o)}}if(i||a||l){const x=this._composite.getColliders();t.save(),t.translate(this.pos.x,this.pos.y),t.scale(this.scale.x,this.scale.y);for(const v of x){const g=v.localBounds,y=v.worldPos.sub(this.pos);a&&t.drawRectangle(y,g.width,g.height,h)}if(t.restore(),l)for(const v of x)v.debug(t,c,{lineWidth:u,pointSize:_})}if(i||a){if(t.save(),t.z=999,a)for(let x=0;x<this.tiles.length;x++)this.tiles[x].bounds.debug(t);t.restore()}}}class Vo{constructor(t){this._posDirty=!1,this.events=new X,this._solid=!1,this._graphics=[],this._offsets=[],this._colliders=[],this.data=new Map;var e,i;this.x=t.x,this.y=t.y,this.map=t.map,this._width=t.map.tileWidth*this.map.scale.x,this._height=t.map.tileHeight*this.map.scale.y,this.solid=(e=t.solid)!=null?e:this.solid,this._graphics=(i=t.graphics)!=null?i:[],this._recalculate()}get pos(){return this._posDirty&&(this._recalculate(),this._posDirty=!1),this._pos}get width(){return this._width}get height(){return this._height}get solid(){return this._solid}set solid(t){var e;(e=this.map)==null||e.flagCollidersDirty(),this._solid=t}getGraphics(){return this._graphics}getGraphicsOffsets(){return this._offsets}addGraphic(t,e){this._graphics.push(t),e!=null&&e.offset?this._offsets.push(e.offset):this._offsets.push(w.Zero)}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&(this._graphics.splice(e,1),this._offsets.splice(e,1))}clearGraphics(){this._graphics.length=0,this._offsets.length=0}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}flagDirty(){this._posDirty=!0}_recalculate(){const t=this.map.pos.add(b(this.x*this.map.tileWidth,this.y*this.map.tileHeight));this._geometry=new F(t.x,t.y,t.x+this.map.tileWidth,t.y+this.map.tileHeight),this._width=this.map.tileWidth*this.map.scale.x,this._height=this.map.tileHeight*this.map.scale.y,this._pos=this.map.pos.add(b(this.x*this._width,this.y*this._height)),this._bounds=new F(this._pos.x,this._pos.y,this._pos.x+this._width,this._pos.y+this._height),this.map.rotation&&(this._bounds=this._bounds.rotate(this.map.rotation,this.map.pos)),this._posDirty=!1}get bounds(){return this._posDirty&&this._recalculate(),this._bounds}get defaultGeometry(){return this._geometry}get center(){return this._posDirty&&this._recalculate(),new w(this._pos.x+this._width/2,this._pos.y+this._height/2)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){e?this.events.off(t,e):this.events.off(t)}}class vi extends Dt{constructor(t){super(),this.elevation=0,this.columns=t.columns,this.rows=t.rows,this.tileWidth=t.tileWidth,this.tileHeight=t.tileHeight}}class qo extends At{constructor(t,e,i,s){super([new P,new K({offset:i!=null?i:w.Zero,onPostDraw:(_,f)=>this.draw(_,f)}),new vi(s)]),this.solid=!1,this.events=new X,this._tileBounds=new F,this._graphics=[],this._colliders=[],this.data=new Map,this.x=t,this.y=e,this.map=s,this._transform=this.get(P),this._isometricEntityComponent=this.get(vi);const n=this.map.tileWidth/2,o=this.map.tileHeight/2,a=(this.x-this.y)*n,h=(this.x+this.y)*o;this._transform.pos=b(a,h),this._isometricEntityComponent.elevation=s.elevation,this._gfx=this.get(K),this._gfx.isVisible=!1;const l=this.map.tileWidth,c=this.map.tileHeight,u=b(0,this.map.renderFromTopOfGraphic?c:0);this._gfx.localBounds=this._tileBounds=new F({left:-l/2,top:-c,right:l/2,bottom:c}).translate(u)}getGraphics(){return this._graphics}addGraphic(t,e){this._graphics.push(t),this._gfx.isVisible=this.map.isVisible,this._gfx.opacity=this.map.opacity,e!=null&&e.offset&&(this._gfx.offset=e.offset),this._gfx.localBounds=this._recalculateBounds()}_recalculateBounds(){let t=this._tileBounds.clone();for(const e of this._graphics){const i=b(this.map.graphicsOffset.x-this.map.tileWidth/2,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:e.height-this.map.tileHeight));t=t.combine(e.localBounds.translate(i))}return t}removeGraphic(t){const e=this._graphics.indexOf(t);e>-1&&this._graphics.splice(e,1),this._gfx.localBounds=this._recalculateBounds()}clearGraphics(){this._graphics.length=0,this._gfx.isVisible=!1,this._gfx.localBounds=this._recalculateBounds()}getColliders(){return this._colliders}addCollider(t){this._colliders.push(t),this.map.flagCollidersDirty()}removeCollider(t){const e=this._colliders.indexOf(t);e>-1&&this._colliders.splice(e,1),this.map.flagCollidersDirty()}clearColliders(){this._colliders.length=0,this.map.flagCollidersDirty()}get pos(){return this.map.tileToWorld(b(this.x,this.y))}get center(){return this.pos.add(b(0,this.map.tileHeight/2))}draw(t,e){const i=this.map.tileWidth/2;t.save(),t.translate(-i,0);for(const s of this._graphics)s.draw(t,this.map.graphicsOffset.x,this.map.graphicsOffset.y-(this.map.renderFromTopOfGraphic?0:s.height-this.map.tileHeight));t.restore()}}class Ul extends At{constructor(t){super([new P,new N({type:M.Fixed}),new tt,new he,new Gi((c,u)=>this.debug(c,u),!1)],t.name),this.elevation=0,this.isVisible=!0,this.opacity=1,this.renderFromTopOfGraphic=!1,this.graphicsOffset=b(0,0),this._collidersDirty=!1,this._originalOffsets=new WeakMap;const{pos:e,tileWidth:i,tileHeight:s,columns:n,rows:o,renderFromTopOfGraphic:a,graphicsOffset:h,elevation:l}=t;this.transform=this.get(P),e&&(this.transform.pos=e),this.collider=this.get(tt),this.collider&&this.collider.set(this._composite=new at([])),this.pointer=this.get(he),this.renderFromTopOfGraphic=a!=null?a:this.renderFromTopOfGraphic,this.graphicsOffset=h!=null?h:this.graphicsOffset,this.elevation=l!=null?l:this.elevation,this.tileWidth=i,this.tileHeight=s,this.columns=n,this.rows=o,this._pointerEventDispatcher=new Nn,this.tiles=new Array(n*o);for(let c=0;c<o;c++)for(let u=0;u<n;u++){const _=new qo(u,c,this.graphicsOffset,this);this.tiles[u+c*n]=_,this.addChild(_),this._pointerEventDispatcher.addObject(_,f=>this.getTileByPoint(f.worldPos)===_,()=>!0)}this.pointer.localBounds=F.fromDimension(i*n*this.transform.scale.x,s*o*this.transform.scale.y,b(.5,0))}get visible(){return this.isVisible}set visible(t){this.isVisible=t}_processPointerToObject(t){const e=Array.from(t.currentFramePointerCoords.entries());for(const[i,s]of e){const n=this.getTileByPoint(this.transform.coordPlane===rt.World?s.worldPos:s.screenPos);n&&this._pointerEventDispatcher.addPointerToObject(n,i)}}_dispatchPointerEvents(t){this._pointerEventDispatcher.dispatchEvents(t,this.tiles)}update(){this._collidersDirty&&(this.updateColliders(),this._collidersDirty=!1),this._pointerEventDispatcher.clear()}flagCollidersDirty(){this._collidersDirty=!0}_getOrSetColliderOriginalOffset(t){var e;if(this._originalOffsets.has(t))return(e=this._originalOffsets.get(t))!=null?e:w.Zero;{const i=t.offset;return this._originalOffsets.set(t,i),i}}updateColliders(){this._composite.clearColliders();const t=this.get(P).pos;for(const e of this.tiles)if(e.solid)for(const i of e.getColliders()){const s=this._getOrSetColliderOriginalOffset(i);i.offset=this.tileToWorld(b(e.x,e.y)).sub(t).add(s).sub(b(this.tileWidth/2,this.tileHeight)),i.owner=this,this._composite.addCollider(i)}this.collider.update()}worldToTile(t){t=t.sub(this.transform.globalPos);const e=this.tileWidth/2,i=this.tileHeight/2;return b(~~((t.x/e+t.y/i)/2),~~((t.y/i-t.x/e)/2))}tileToWorld(t){const e=this.tileWidth/2,i=this.tileHeight/2,s=(t.x-t.y)*e,n=(t.x+t.y)*i;return b(s,n).add(this.transform.pos)}getTile(t,e){return t<0||e<0||t>=this.columns||e>=this.rows?null:this.tiles[t+e*this.columns]}getTileByPoint(t){const e=this.worldToTile(t);return this.getTile(e.x,e.y)}_getMaxZIndex(){let t=Number.NEGATIVE_INFINITY;for(const e of this.tiles){const i=e.get(P).z;i>t&&(t=i)}return t}debug(t,e){const{showAll:i,showPosition:s,positionColor:n,positionSize:o,showGrid:a,gridColor:h,gridWidth:l,showColliderGeometry:c}=e.isometric,{geometryColor:u,geometryLineWidth:_,geometryPointSize:f}=e.collider;if(t.save(),t.z=this._getMaxZIndex()+.5,i||a){for(let m=0;m<this.rows+1;m++){const p=this.tileToWorld(b(0,m)),x=this.tileToWorld(b(this.columns,m));t.debug.drawLine(p,x,{color:h,lineWidth:l})}for(let m=0;m<this.columns+1;m++){const p=this.tileToWorld(b(m,0)),x=this.tileToWorld(b(m,this.rows));t.debug.drawLine(p,x,{color:h,lineWidth:l})}}if(i||s)for(const m of this.tiles)t.debug.drawCircle(this.tileToWorld(b(m.x,m.y)),o,n);if(i||c){for(const m of this.tiles)if(m.solid)for(const p of m.getColliders())p.debug(t,u,{lineWidth:_,pointSize:f})}t.restore()}}class Wn extends Et{constructor(t){super(),this.world=t,this.systemType=Pt.Update,this.query=this.world.query([P,vi])}update(){let t,e;for(let i=0;i<this.query.entities.length;i++){const s=this.query.entities[i];t=s.get(P),e=s.get(vi);const o=Math.max(e.columns*e.tileWidth,e.rows*e.tileHeight)*e.elevation+t.pos.y;t.z=o}}}Wn.priority=Gt.Lower;class Xo{constructor(t){this.camera=t}lockToActor(t){this.camera.addStrategy(new $o(t))}lockToActorAxis(t,e){this.camera.addStrategy(new Zo(t,e))}elasticToActor(t,e,i){this.camera.addStrategy(new jo(t,e,i))}radiusAroundActor(t,e){this.camera.addStrategy(new Qo(t,e))}limitCameraBounds(t){this.camera.addStrategy(new Jo(t))}}var Yo=(r=>(r[r.X=0]="X",r[r.Y=1]="Y",r))(Yo||{});class $o{constructor(t){this.target=t,this.action=(e,i,s,n)=>e.center}}class Zo{constructor(t,e){this.target=t,this.axis=e,this.action=(i,s,n,o)=>{const a=i.center,h=s.getFocus();return this.axis===0?new w(a.x,h.y):new w(h.x,a.y)}}}class jo{constructor(t,e,i){this.target=t,this.cameraElasticity=e,this.cameraFriction=i,this.action=(s,n,o,a)=>{const h=s.center;let l=n.getFocus(),c=n.vel.clone();const u=h.sub(l).scale(this.cameraElasticity);c=c.add(u);const _=c.scale(-1).scale(this.cameraFriction);return c=c.add(_),l=l.add(c),l}}}class Qo{constructor(t,e){this.target=t,this.radius=e,this.action=(i,s,n,o)=>{const a=i.center,h=s.getFocus(),l=a.sub(h),c=l.magnitude;if(c>=this.radius){const u=c-this.radius;return h.add(l.normalize().scale(u))}return h}}}class Jo{constructor(t){this.target=t,this.boundSizeChecked=!1,this.action=(e,i,s,n)=>{const o=i.getFocus();this.boundSizeChecked||((e.bottom-e.top<s.drawHeight||e.right-e.left<s.drawWidth)&&R.getInstance().warn("Camera bounds should not be smaller than the engine viewport"),this.boundSizeChecked=!0);let a=o.x,h=o.y;return o.x<e.left+s.halfDrawWidth?a=e.left+s.halfDrawWidth:o.x>e.right-s.halfDrawWidth&&(a=e.right-s.halfDrawWidth),o.y<e.top+s.halfDrawHeight?h=e.top+s.halfDrawHeight:o.y>e.bottom-s.halfDrawHeight&&(h=e.bottom-s.halfDrawHeight),b(a,h)}}}const zl={Initialize:"initialize",PreUpdate:"preupdate",PostUpdate:"postupdate"};class Ko{constructor(){this.events=new X,this.transform=Z.identity(),this.inverse=Z.identity(),this._cameraStrategies=[],this.strategy=new Xo(this),this._z=1,this.dz=0,this.az=0,this.rotation=0,this._angularVelocity=0,this._posChanged=!1,this._pos=new ne(w.Zero,()=>{this._posChanged=!0}),this.drawPos=this.pos.clone(),this._oldPos=this.pos.clone(),this.vel=w.Zero,this.acc=w.Zero,this._cameraMoving=!1,this._currentLerpTime=0,this._lerpDuration=1e3,this._lerpStart=null,this._lerpEnd=null,this._isShaking=!1,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._elapsedShakeTime=0,this._xShake=0,this._yShake=0,this._isZooming=!1,this._zoomStart=1,this._zoomEnd=1,this._currentZoomTime=0,this._zoomDuration=0,this._legacyZoomEasing=Rt.EaseInOutCubic,this._useLegacyZoom=!1,this._zoomEasing=ys,this._legacyEasing=Rt.EaseInOutCubic,this._useLegacyEasing=!1,this._easing=ys,this._halfWidth=0,this._halfHeight=0,this._viewport=null,this._isInitialized=!1,this._snapPos=b(0,0)}get strategies(){return this._cameraStrategies}get zoom(){return this._z}set zoom(t){this._z=t,this._engine&&(this._halfWidth=this._engine.halfDrawWidth,this._halfHeight=this._engine.halfDrawHeight)}get angularVelocity(){return this._angularVelocity}set angularVelocity(t){this._angularVelocity=t}get pos(){return this._pos}set pos(t){this._posChanged=!0,this._pos=new ne(t,()=>{this._posChanged=!0})}hasChanged(){return this._posChanged}get x(){return this.pos.x}set x(t){!this._follow&&!this._cameraMoving&&(this.pos=b(t,this.pos.y))}get y(){return this.pos.y}set y(t){!this._follow&&!this._cameraMoving&&(this.pos=b(this.pos.x,t))}get dx(){return this.vel.x}set dx(t){this.vel=b(t,this.vel.y)}get dy(){return this.vel.y}set dy(t){this.vel=b(this.vel.x,t)}get ax(){return this.acc.x}set ax(t){this.acc=b(t,this.acc.y)}get ay(){return this.acc.y}set ay(t){this.acc=b(this.acc.x,t)}getFocus(){return this.pos}move(t,e,i=Rt.EaseInOutCubic){if(typeof i!="function")throw"Please specify an EasingFunction";return this._follow?Promise.reject(t):(this._lerpPromise&&this._lerpResolve&&this._lerpResolve(t),this._lerpPromise=new Promise(s=>{this._lerpResolve=s}),this._lerpStart=this.getFocus().clone(),this._lerpDuration=e,this._lerpEnd=t,this._currentLerpTime=0,this._cameraMoving=!0,Te(i)?this._legacyEasing=i:this._easing=i,this._lerpPromise)}shake(t,e,i){this._isShaking=!0,this._shakeMagnitudeX=t,this._shakeMagnitudeY=e,this._shakeDuration=i}zoomOverTime(t,e=0,i=Rt.EaseInOutCubic){if(this._zoomPromise=new Promise(s=>{this._zoomResolve=s}),e)this._isZooming=!0,Te(i)?this._legacyZoomEasing=i:this._easing=i,this._currentZoomTime=0,this._zoomDuration=e,this._zoomStart=this.zoom,this._zoomEnd=t;else return this._isZooming=!1,this.zoom=t,Promise.resolve(!0);return this._zoomPromise}get viewport(){return this._viewport?this._viewport:new F(0,0,0,0)}addStrategy(...t){this._cameraStrategies.push(...t)}setStrategies(t){this._cameraStrategies=[...t]}removeStrategy(t){He(t,this._cameraStrategies)}clearAllStrategies(){this._cameraStrategies.length=0}_preupdate(t,e){this.events.emit("preupdate",new re(t,e,this)),this.onPreUpdate(t,e)}onPreUpdate(t,e){}_postupdate(t,e){this.events.emit("postupdate",new oe(t,e,this)),this.onPostUpdate(t,e)}onPostUpdate(t,e){}get isInitialized(){return this._isInitialized}_initialize(t){if(!this.isInitialized){this._engine=t,this._screen=t.screen;const e=this._screen.contentArea;let i=b(e.width/2,e.height/2);if(!this._engine.loadingComplete){const s=this._screen.peekResolution();s&&(i=b(s.width/2,s.height/2))}this._halfWidth=i.x,this._halfHeight=i.y,this._posChanged||(this.pos=i),this.pos.clone(this.drawPos),this.updateTransform(this.pos),this.runStrategies(t,t.clock.elapsed()),this.updateViewport(),this.updateTransform(this.pos),this.pos.clone(this._oldPos),this.onInitialize(t),this.events.emit("initialize",new Oe(t,this)),this._isInitialized=!0}}onInitialize(t){}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}runStrategies(t,e){for(const i of this._cameraStrategies)this.pos=i.action.call(i,i.target,this,t,e)}updateViewport(){this._viewport=new F(this.x-this._halfWidth,this.y-this._halfHeight,this.x+this._halfWidth,this.y+this._halfHeight)}update(t,e){if(this._initialize(t),this._preupdate(t,e),this.pos.clone(this._oldPos),this.pos=this.pos.add(this.vel.scale(e/1e3)),this.zoom+=this.dz*e/1e3,this.vel=this.vel.add(this.acc.scale(e/1e3)),this.dz+=this.az*e/1e3,this.rotation+=this.angularVelocity*e/1e3,this._isZooming)if(this._currentZoomTime<this._zoomDuration){let i=this.zoom;if(this._useLegacyZoom){const s=this._legacyZoomEasing;i=s(this._currentZoomTime,this._zoomStart,this._zoomEnd,this._zoomDuration)}else i=ot(this._zoomStart,this._zoomEnd,this._zoomEasing(this._currentZoomTime/this._zoomDuration));this.zoom=i,this._currentZoomTime+=e}else this._isZooming=!1,this.zoom=this._zoomEnd,this._currentZoomTime=0,this._zoomResolve(!0);if(this._cameraMoving)if(this._currentLerpTime<this._lerpDuration){let i=this.pos;this._useLegacyEasing?i=Rt.CreateVectorEasingFunction(this._legacyEasing)(this._currentLerpTime,this._lerpStart,this._lerpEnd,this._lerpDuration):(i.x=ot(this._lerpStart.x,this._lerpEnd.x,this._easing(this._currentLerpTime/this._lerpDuration)),i.y=ot(this._lerpStart.y,this._lerpEnd.y,this._easing(this._currentLerpTime/this._lerpDuration))),this.pos=i,this._currentLerpTime+=e}else{this.pos=this._lerpEnd;const i=this._lerpEnd.clone();this._lerpStart=null,this._lerpEnd=null,this._currentLerpTime=0,this._cameraMoving=!1,this._lerpResolve(i)}this._isDoneShaking()?(this._isShaking=!1,this._elapsedShakeTime=0,this._shakeMagnitudeX=0,this._shakeMagnitudeY=0,this._shakeDuration=0,this._xShake=0,this._yShake=0):(this._elapsedShakeTime+=e,this._xShake=(Math.random()*this._shakeMagnitudeX|0)+1,this._yShake=(Math.random()*this._shakeMagnitudeY|0)+1),this.runStrategies(t,e),this.updateViewport(),this.updateTransform(this.pos),this._postupdate(t,e),this._posChanged=!1}draw(t){if(this.pos.clone(this.drawPos),this._engine.fixedUpdateTimestep){const e=this._engine.currentFrameLagMs/this._engine.fixedUpdateTimestep,i=this.pos.scale(e).add(this._oldPos.scale(1-e));i.clone(this.drawPos),this.updateTransform(i)}if(t.snapToPixel){const e=this.drawPos.clone(this._snapPos);e.x=~~(e.x+D*V(e.x)),e.y=~~(e.y+D*V(e.y)),e.clone(this.drawPos),this.updateTransform(e)}t.multiply(this.transform)}updateTransform(t){const e=this._screen.resolution.width/this.zoom,i=this._screen.resolution.height/this.zoom,s=b(-t.x+e/2+this._xShake,-t.y+i/2+this._yShake);this.transform.reset(),this.transform.scale(this.zoom,this.zoom),this.transform.translate(e/2,i/2),this.transform.rotate(this.rotation),this.transform.translate(-e/2,-i/2),this.transform.translate(s.x,s.y),this.transform.inverse(this.inverse)}_isDoneShaking(){return!this._isShaking||this._elapsedShakeTime>=this._shakeDuration}}const Ol={ExitTrigger:"exit",EnterTrigger:"enter"};class ta extends kt{constructor(t){var e,i,s,n;super({...t}),this.events=new X,this.filter=(e=t.filter)!=null?e:()=>!0,this.repeat=(i=t.repeat)!=null?i:-1,this.action=(s=t.action)!=null?s:()=>{},this.target=t.target,this.graphics.isVisible=(n=t.visible)!=null?n:!1,this.body.collisionType=M.Passive,this.events.on("collisionstart",({other:o})=>{this._matchesTarget(o.owner)&&(this.events.emit("enter",new Ys(this,o.owner)),this._dispatchAction(o.owner),this.repeat===0&&this.kill())}),this.events.on("collisionend",({other:o})=>{this._matchesTarget(o.owner)&&this.events.emit("exit",new $s(this,o.owner))})}_matchesTarget(t){return this.filter(t)&&(this.target===void 0||this.target===t)}_dispatchAction(t){this.repeat!==0&&(this.action.call(this,t),this.repeat--)}}class Gn extends Et{constructor(t){super(),this.world=t,this.systemType=Pt.Draw,this.query=this.world.query([P])}initialize(t,e){this._graphicsContext=e.engine.graphicsContext,this._camera=e.camera,this._engine=e.engine,this._collisionSystem=t.systemManager.get(Ji)}update(){var t;if(!this._engine.isDebug)return;const e=this._engine.debug.filter;let i,s;const n=this._engine.debug.entity;let o;const a=this._engine.debug.transform;let h;const l=this._engine.debug.motion;let c;const u=this._engine.debug.collider,_=this._engine.debug.physics;let f,m;const p=this._engine.debug.body,x=this._engine.debug.camera;for(let v=0;v<this.query.entities.length;v++){const g=this.query.entities[v];if(g.hasTag("offscreen")||g instanceof Zi||e.useFilter&&(!(e.ids.length===0||e.ids.includes(g.id))||!(e.nameQuery===""||g.name.includes(e.nameQuery))))continue;let y=w.Zero;const S=b(0,16);if(i=g.id,s=g.name,o=g.get(P),this._pushCameraTransform(o),this._graphicsContext.save(),o.coordPlane===rt.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),this._applyTransform(g),o&&((a.showAll||a.showPosition)&&this._graphicsContext.debug.drawPoint(w.Zero,{size:4,color:a.positionColor}),(a.showAll||a.showPositionLabel)&&(this._graphicsContext.debug.drawText(`pos${o.pos.toString(2)}`,y),y=y.add(S)),(a.showAll||a.showZIndex)&&(this._graphicsContext.debug.drawText(`z(${o.z.toFixed(1)})`,y),y=y.add(S)),(n.showAll||n.showId)&&(this._graphicsContext.debug.drawText(`id(${i}) ${g.parent?"child of id("+((t=g.parent)==null?void 0:t.id)+")":""}`,y),y=y.add(S)),(n.showAll||n.showName)&&(this._graphicsContext.debug.drawText(`name(${s})`,y),y=y.add(S)),(a.showAll||a.showRotation)&&(this._graphicsContext.drawLine(w.Zero,w.fromAngle(o.rotation).scale(50).add(w.Zero),a.rotationColor,2),this._graphicsContext.debug.drawText(`rot deg(${hr(o.rotation).toFixed(2)})`,y),y=y.add(S)),(a.showAll||a.showScale)&&this._graphicsContext.drawLine(w.Zero,o.scale.add(w.Zero),a.scaleColor,2)),f=g.get(Gi),f&&(f.useTransform||this._graphicsContext.restore(),f.draw(this._graphicsContext,this._engine.debug),f.useTransform||(this._graphicsContext.save(),this._applyTransform(g))),m=g.get(N),m&&((p.showAll||p.showCollisionGroup)&&(this._graphicsContext.debug.drawText(`collision group(${m.group.name})`,y),y=y.add(S)),(p.showAll||p.showCollisionType)&&(this._graphicsContext.debug.drawText(`collision type(${m.collisionType})`,y),y=y.add(S)),(p.showAll||p.showMass)&&(this._graphicsContext.debug.drawText(`mass(${m.mass})`,y),y=y.add(S)),(p.showAll||p.showMotion)&&(this._graphicsContext.debug.drawText(`motion(${m.sleepMotion})`,y),y=y.add(S)),(p.showAll||p.showSleeping)&&(this._graphicsContext.debug.drawText(`sleeping(${m.canSleep?m.isSleeping:"cant sleep"})`,y),y=y.add(S))),this._graphicsContext.restore(),this._graphicsContext.save(),o.coordPlane===rt.Screen&&this._graphicsContext.translate(this._engine.screen.contentArea.left,this._engine.screen.contentArea.top),h=g.get(O),h&&((l.showAll||l.showVelocity)&&(this._graphicsContext.debug.drawText(`vel${h.vel.toString(2)}`,y.add(o.globalPos)),this._graphicsContext.drawLine(o.globalPos,o.globalPos.add(h.vel),l.velocityColor,2),y=y.add(S)),(l.showAll||l.showAcceleration)&&this._graphicsContext.drawLine(o.globalPos,o.globalPos.add(h.acc),l.accelerationColor,2)),c=g.get(tt),c){const A=c.get();if((u.showAll||u.showGeometry)&&A&&A.debug(this._graphicsContext,u.geometryColor,{lineWidth:u.geometryLineWidth,pointSize:u.geometryPointSize}),u.showAll||u.showBounds){if(A instanceof at){const I=A.getColliders();for(const C of I){const L=C.bounds,U=b(L.left,L.top);this._graphicsContext.debug.drawRect(U.x,U.y,L.width,L.height,{color:u.boundsColor,dashed:!0}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${C.owner.id})`,U)}c.bounds.debug(this._graphicsContext,{color:u.boundsColor,dashed:!0})}else if(A){const I=c.bounds,C=b(I.left,I.top);this._graphicsContext.debug.drawRect(C.x,C.y,I.width,I.height,{color:u.boundsColor,dashed:!0}),(u.showAll||u.showOwner)&&this._graphicsContext.debug.drawText(`owner id(${c.owner.id})`,C)}}}this._graphicsContext.restore(),this._popCameraTransform(o)}if(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(_.showAll||_.showBroadphaseSpacePartitionDebug)&&this._collisionSystem.debug(this._graphicsContext),_.showAll||_.showCollisionContacts||_.showCollisionNormals)for(const[v,g]of this._engine.debug.stats.currFrame.physics.contacts){if(_.showAll||_.showCollisionContacts)for(const y of g.points)this._graphicsContext.debug.drawPoint(y,{size:_.contactSize,color:_.collisionContactColor});if(_.showAll||_.showCollisionNormals)for(const y of g.points)this._graphicsContext.debug.drawLine(y,g.normal.scale(30).add(y),{color:_.collisionNormalColor})}this._graphicsContext.restore(),x&&(this._graphicsContext.save(),this._camera.draw(this._graphicsContext),(x.showAll||x.showFocus)&&this._graphicsContext.debug.drawCircle(this._camera.pos,4,x.focusColor),(x.showAll||x.showZoom)&&this._graphicsContext.debug.drawText(`zoom(${this._camera.zoom})`,this._camera.pos),this._graphicsContext.restore())}postupdate(t,e){this._engine.isDebug&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext),Tt.flush(this._graphicsContext),this._graphicsContext.restore())}_applyTransform(t){const e=t.getAncestors();for(const i of e){const s=i==null?void 0:i.get(P);s&&(this._graphicsContext.translate(s.pos.x,s.pos.y),this._graphicsContext.scale(s.scale.x,s.scale.y),this._graphicsContext.rotate(s.rotation))}}_pushCameraTransform(t){t.coordPlane===rt.World&&(this._graphicsContext.save(),this._camera&&this._camera.draw(this._graphicsContext))}_popCameraTransform(t){t.coordPlane===rt.World&&this._graphicsContext.restore()}}Gn.priority=Gt.Lowest;class is extends Et{constructor(t){super(),this.world=t,this.systemType=Pt.Update,this._graphicsHashGrid=new Rn({size:100}),this._graphics=[],this._entityToPointer=new Map,this._pointerEventDispatcher=new Nn,this.overrideUseColliderShape=!1,this.overrideUseGraphicsBounds=!1,this._sortedTransforms=[],this._sortedEntities=[],this._zHasChanged=!1,this._zIndexUpdate=()=>{this._zHasChanged=!0},this.query=this.world.query([P,he]),this.query.entityAdded$.subscribe(e=>{const i=e.get(P),s=e.get(he);this._pointerEventDispatcher.addObject(e,o=>s&&s.localBounds?s.localBounds.transform(i.get().matrix).contains(i.coordPlane===rt.World?o.worldPos:o.screenPos):!1,()=>e.isActive),this._entityToPointer.set(e,s);const n=e.get(K);n&&(this._graphics.push(n),this._graphicsHashGrid.track(n)),this._sortedTransforms.push(i),this._sortedEntities.push(i.owner),i.zIndexChanged$.subscribe(this._zIndexUpdate),this._zHasChanged=!0}),this.query.entityRemoved$.subscribe(e=>{this._pointerEventDispatcher.removeObject(e);const i=e.get(P);this._entityToPointer.delete(e);const s=e.get(K);if(s){const o=this._graphics.indexOf(s);o>-1&&this._graphics.splice(o,1),this._graphicsHashGrid.untrack(s)}i.zIndexChanged$.unsubscribe(this._zIndexUpdate);const n=this._sortedTransforms.indexOf(i);n>-1&&(this._sortedTransforms.splice(n,1),this._sortedEntities.splice(n,1))})}initialize(t,e){this._engine=e.engine,this._scene=e}preupdate(){this._scene.camera.hasChanged()&&this._scene.camera.updateTransform(this._scene.camera.pos),this._receivers=[this._engine.input.pointers,this._scene.input.pointers],this._engineReceiver=this._engine.input.pointers,this._zHasChanged&&(this._sortedTransforms.sort((t,e)=>e.z-t.z),this._sortedEntities=this._sortedTransforms.map(t=>t.owner),this._zHasChanged=!1)}update(){this._graphicsHashGrid.update(this._graphics);for(const[t,e]of this._engineReceiver.currentFramePointerCoords.entries()){const i=this._scene.physics.query(e.worldPos);for(let n=0;n<i.length;n++){const o=i[n],a=this._entityToPointer.get(o.owner);a&&(a.useColliderShape||this.overrideUseColliderShape)&&o.contains(e.worldPos)&&this._pointerEventDispatcher.addPointerToObject(o.owner,t)}const s=this._graphicsHashGrid.query(e.worldPos);for(let n=0;n<s.length;n++){const o=s[n],a=this._entityToPointer.get(o.owner);a&&(a.useGraphicsBounds||this.overrideUseGraphicsBounds)&&this._pointerEventDispatcher.addPointerToObject(o.owner,t)}}this._pointerEventDispatcher.processPointerToObject(this._engineReceiver,this._sortedEntities),this._pointerEventDispatcher.dispatchEvents(this._engineReceiver,this._sortedEntities),this._receivers.forEach(t=>t.update()),this._pointerEventDispatcher.clear(),this._receivers.forEach(t=>t.clear())}}is.priority=Gt.Higher;class Vn extends Et{constructor(t){super(),this.world=t,this.systemType=Pt.Update,this._actions=[],this.query=this.world.query([Qe]),this.query.entityAdded$.subscribe(e=>this._actions.push(e.get(Qe))),this.query.entityRemoved$.subscribe(e=>{const i=e.get(Qe),s=this._actions.indexOf(i);s>-1&&this._actions.splice(s,1)})}update(t){for(let e=0;e<this._actions.length;e++)this._actions[e].update(t)}}Vn.priority=Gt.Higher;class ss{constructor(){this.events=new X,this.enabled=!1,this.supported=!!navigator.getGamepads,this._gamePadTimeStamps=[0,0,0,0],this._oldPads=[],this._pads=[],this._initSuccess=!1,this._navigator=navigator,this._minimumConfiguration=null,this._enabled=!0}init(){this.supported&&(this._initSuccess||(this._oldPads=this._clonePads(this._navigator.getGamepads()),this._oldPads.length&&this._oldPads[0]&&(this._initSuccess=!0)))}toggleEnabled(t){this._enabled=t}setMinimumGamepadConfiguration(t){this._enableAndUpdate(),this._minimumConfiguration=t}_enableAndUpdate(){this.enabled||(this.enabled=!0,this.update())}_isGamepadValid(t){if(!this._minimumConfiguration)return!0;if(!t)return!1;const e=t.axes.filter(s=>typeof s!==void 0).length,i=t.buttons.filter(s=>typeof s!==void 0).length;return e>=this._minimumConfiguration.axis&&i>=this._minimumConfiguration.buttons&&t.connected}emit(t,e){this.events.emit(t,e)}on(t,e){return this._enableAndUpdate(),this.events.on(t,e)}once(t,e){return this._enableAndUpdate(),this.events.once(t,e)}off(t,e){this._enableAndUpdate(),this.events.off(t,e)}update(){var t,e;if(!this.enabled||!this.supported||!this._enabled)return;this.init();const i=this._navigator.getGamepads();for(let s=0;s<i.length;s++){if(i[s]){const o=this.at(s);!this.at(s).connected&&this._isGamepadValid(i[s])&&(o.events.pipe(this.events),this.events.emit("connect",new Us(s,this.at(s)))),this.at(s).connected=!0}else{const o=this.at(s);o.connected&&(this.events.emit("disconnect",new zs(s,o)),o.events.unpipe(this.events)),o.connected=!1;continue}if(this.at(s).update(),i[s].timestamp&&i[s].timestamp===this._gamePadTimeStamps[s])continue;this._gamePadTimeStamps[s]=i[s].timestamp,this.at(s).navigatorGamepad=i[s];const n=i[s];if(n){for(let o=0;o<n.buttons.length;o++){const a=n.buttons[o],h=a==null?void 0:a.value;h!==((t=this._oldPads[s])==null?void 0:t.getButton(o))&&(a!=null&&a.pressed?(this.at(s).updateButton(o,h),this.at(s).events.emit("button",new Os(o in qn?o:-1,o,h,this.at(s)))):this.at(s).updateButton(o,0))}for(let o=0;o<n.axes.length;o++){const a=n.axes[o];a!==((e=this._oldPads[s])==null?void 0:e.getAxes(o))&&(this.at(s).updateAxes(o,a),this.at(s).events.emit("axis",new Hs(o,a,this.at(s))))}}this._oldPads[s]=this._clonePad(i[s])}}at(t){if(this._enableAndUpdate(),t>=this._pads.length)for(let e=this._pads.length-1,i=t;e<i;e++)this._pads.push(new ns),this._oldPads.push(new ns);return this._pads[t]}getValidGamepads(){this._enableAndUpdate();const t=[];for(let e=0;e<this._pads.length;e++)this._isGamepadValid(this.at(e).navigatorGamepad)&&this.at(e).connected&&t.push(this.at(e));return t}count(){return this._pads.filter(t=>t.connected).length}_clonePads(t){const e=[];for(let i=0,s=t.length;i<s;i++)e.push(this._clonePad(t[i]));return e}_clonePad(t){let e,i;const s=new ns;if(!t)return s;for(e=0,i=t.buttons.length;e<i;e++)t.buttons[e]&&s.updateButton(e,t.buttons[e].value);for(e=0,i=t.axes.length;e<i;e++)s.updateAxes(e,t.axes[e]);return s}}ss.MinAxisMoveThreshold=.05;class ns{constructor(){this.events=new X,this.connected=!1,this._axes=new Array(4),this._buttons=new Array(16),this._buttonsUp=new Array(16),this._buttonsDown=new Array(16);for(let t=0;t<this._buttons.length;t++)this._buttons[t]=0;for(let t=0;t<this._axes.length;t++)this._axes[t]=0}update(){this._buttonsDown=new Array(16),this._buttonsUp=new Array(16)}isButtonPressed(t,e=1){return this._buttons[t]>=e}isButtonHeld(t,e=1){return this._buttons[t]>=e}wasButtonPressed(t,e=1){return this._buttonsDown[t]>=e}wasButtonReleased(t){return!!this._buttonsUp[t]}getButton(t){return this._buttons[t]}getAxes(t){const e=this._axes[t];return Math.abs(e)<ss.MinAxisMoveThreshold?0:e}updateButton(t,e){e===0&&this._buttons[t]?this._buttonsUp[t]=1:this._buttonsDown[t]=e,this._buttons[t]=e}updateAxes(t,e){this._axes[t]=e}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}}var qn=(r=>(r[r.Unknown=-1]="Unknown",r[r.Face1=0]="Face1",r[r.Face2=1]="Face2",r[r.Face3=2]="Face3",r[r.Face4=3]="Face4",r[r.LeftBumper=4]="LeftBumper",r[r.RightBumper=5]="RightBumper",r[r.LeftTrigger=6]="LeftTrigger",r[r.RightTrigger=7]="RightTrigger",r[r.Select=8]="Select",r[r.Start=9]="Start",r[r.LeftStick=10]="LeftStick",r[r.RightStick=11]="RightStick",r[r.DpadUp=12]="DpadUp",r[r.DpadDown=13]="DpadDown",r[r.DpadLeft=14]="DpadLeft",r[r.DpadRight=15]="DpadRight",r[r.CenterButton=16]="CenterButton",r[r.MiscButton1=17]="MiscButton1",r))(qn||{}),ea=(r=>(r[r.LeftStickX=0]="LeftStickX",r[r.LeftStickY=1]="LeftStickY",r[r.RightStickX=2]="RightStickX",r[r.RightStickY=3]="RightStickY",r))(ea||{});class ia{constructor(t){this.inputs=t,this._handlers=new Map}execute(){for(const[t,e]of this._handlers.entries()){const i=t(this.inputs);i&&e(i)}}on(t,e){this._handlers.set(t,e)}}function sa(){try{const r=()=>{};window.top.addEventListener("blur",r),window.top.removeEventListener("blur",r)}catch(r){return!0}return!1}function na(){return window!==window.top}function ra(){let r;return sa()?(r=window,R.getInstance().warnOnce("Excalibur might be in a cross-origin iframe, in order to receive keyboard events it must be in focus")):na()?(r=window,R.getInstance().warnOnce("Excalibur might be in a iframe, in order to receive keyboard events it must be in focus")):r=window.top,r}var oa=(r=>(r.Backquote="Backquote",r.Backslash="Backslash",r.BracketLeft="BracketLeft",r.BracketRight="BracketRight",r.Comma="Comma",r.Key0="Digit0",r.Key1="Digit1",r.Key2="Digit2",r.Key3="Digit3",r.Key4="Digit4",r.Key5="Digit5",r.Key6="Digit6",r.Key7="Digit7",r.Key8="Digit8",r.Key9="Digit9",r.Digit0="Digit0",r.Digit1="Digit1",r.Digit2="Digit2",r.Digit3="Digit3",r.Digit4="Digit4",r.Digit5="Digit5",r.Digit6="Digit6",r.Digit7="Digit7",r.Digit8="Digit8",r.Digit9="Digit9",r.Equal="Equal",r.IntlBackslash="IntlBackslash",r.IntlRo="IntlRo",r.IntlYen="IntlYen",r.A="KeyA",r.B="KeyB",r.C="KeyC",r.D="KeyD",r.E="KeyE",r.F="KeyF",r.G="KeyG",r.H="KeyH",r.I="KeyI",r.J="KeyJ",r.K="KeyK",r.L="KeyL",r.M="KeyM",r.N="KeyN",r.O="KeyO",r.P="KeyP",r.Q="KeyQ",r.R="KeyR",r.S="KeyS",r.T="KeyT",r.U="KeyU",r.V="KeyV",r.W="KeyW",r.X="KeyX",r.Y="KeyY",r.Z="KeyZ",r.KeyA="KeyA",r.KeyB="KeyB",r.KeyC="KeyC",r.KeyD="KeyD",r.KeyE="KeyE",r.KeyF="KeyF",r.KeyG="KeyG",r.KeyH="KeyH",r.KeyI="KeyI",r.KeyJ="KeyJ",r.KeyK="KeyK",r.KeyL="KeyL",r.KeyM="KeyM",r.KeyN="KeyN",r.KeyO="KeyO",r.KeyP="KeyP",r.KeyQ="KeyQ",r.KeyR="KeyR",r.KeyS="KeyS",r.KeyT="KeyT",r.KeyU="KeyU",r.KeyV="KeyV",r.KeyW="KeyW",r.KeyX="KeyX",r.KeyY="KeyY",r.KeyZ="KeyZ",r.Minus="Minus",r.Period="Period",r.Quote="Quote",r.Semicolon="Semicolon",r.Slash="Slash",r.AltLeft="AltLeft",r.AltRight="AltRight",r.Alt="Alt",r.AltGraph="AltGraph",r.Backspace="Backspace",r.CapsLock="CapsLock",r.ContextMenu="ContextMenu",r.ControlLeft="ControlLeft",r.ControlRight="ControlRight",r.Enter="Enter",r.MetaLeft="MetaLeft",r.MetaRight="MetaRight",r.ShiftLeft="ShiftLeft",r.ShiftRight="ShiftRight",r.Space="Space",r.Tab="Tab",r.Convert="Convert",r.KanaMode="KanaMode",r.NonConvert="NonConvert",r.Delete="Delete",r.End="End",r.Help="Help",r.Home="Home",r.Insert="Insert",r.PageDown="PageDown",r.PageUp="PageUp",r.Up="ArrowUp",r.Down="ArrowDown",r.Left="ArrowLeft",r.Right="ArrowRight",r.ArrowUp="ArrowUp",r.ArrowDown="ArrowDown",r.ArrowLeft="ArrowLeft",r.ArrowRight="ArrowRight",r.NumLock="NumLock",r.Numpad0="Numpad0",r.Numpad1="Numpad1",r.Numpad2="Numpad2",r.Numpad3="Numpad3",r.Numpad4="Numpad4",r.Numpad5="Numpad5",r.Numpad6="Numpad6",r.Numpad7="Numpad7",r.Numpad8="Numpad8",r.Numpad9="Numpad9",r.Num0="Numpad0",r.Num1="Numpad1",r.Num2="Numpad2",r.Num3="Numpad3",r.Num4="Numpad4",r.Num5="Numpad5",r.Num6="Numpad6",r.Num7="Numpad7",r.Num8="Numpad8",r.Num9="Numpad9",r.NumAdd="NumpadAdd",r.NumpadAdd="NumpadAdd",r.NumDecimal="NumpadDecimal",r.NumpadDecimal="NumpadDecimal",r.NumDivide="NumpadDivide",r.NumpadDivide="NumpadDivide",r.NumEnter="NumpadEnter",r.NumpadEnter="NumpadEnter",r.NumMultiply="NumpadMultiply",r.NumpadMultiply="NumpadMultiply",r.NumSubtract="NumpadSubtract",r.NumpadSubtract="NumpadSubtract",r.Esc="Escape",r.Escape="Escape",r.F1="F1",r.F2="F2",r.F3="F3",r.F4="F4",r.F5="F5",r.F6="F6",r.F7="F7",r.F8="F8",r.F9="F9",r.F10="F10",r.F11="F11",r.F12="F12",r.F13="F13",r.F14="F14",r.F15="F15",r.F16="F16",r.F17="F17",r.F18="F18",r.F19="F19",r.F20="F20",r.PrintScreen="PrintScreen",r.ScrollLock="ScrollLock",r.Pause="Pause",r.Unidentified="Unidentified",r))(oa||{});class wi extends k{constructor(t,e,i){super(),this.key=t,this.value=e,this.originalEvent=i}}class aa{constructor(){this.events=new X,this._enabled=!0,this._keys=[],this._keysUp=[],this._keysDown=[],this._releaseAllKeys=t=>{for(const e of this._keys){const i=new wi(e,t.key,t);this.events.emit("up",i),this.events.emit("release",i)}this._keysUp=Array.from(new Set(this._keys.concat(this._keysUp))),this._keys.length=0},this._handleKeyDown=t=>{if(!this._enabled)return;!t.metaKey&&(this._keys.includes("MetaLeft")||this._keys.includes("MetaRight"))&&this._releaseAllKeys(t);const e=t.code;if(this._keys.indexOf(e)===-1){this._keys.push(e),this._keysDown.push(e);const i=new wi(e,t.key,t);this.events.emit("down",i),this.events.emit("press",i)}},this._handleKeyUp=t=>{if(!this._enabled)return;const e=t.code,i=this._keys.indexOf(e);this._keys.splice(i,1),this._keysUp.push(e);const s=new wi(e,t.key,t);this.events.emit("up",s),this.events.emit("release",s),t.key==="Meta"&&this._releaseAllKeys(t)}}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}init(t){let{global:e}=t;const{grabWindowFocus:i}=t;e?typeof e=="function"&&(e=e()):e=ra(),i&&e.focus(),e.addEventListener("blur",()=>{this._keys.length=0}),e.addEventListener("keyup",this._handleKeyUp),e.addEventListener("keydown",this._handleKeyDown)}toggleEnabled(t){this._enabled=t}clear(){this._keysDown.length=0,this._keysUp.length=0,this._keys.length=0}update(){this._keysDown.length=0,this._keysUp.length=0;for(let t=0;t<this._keys.length;t++)this.events.emit("hold",new wi(this._keys[t]))}getKeys(){return this._keys}wasPressed(t){return this._enabled?this._keysDown.indexOf(t)>-1:!1}isHeld(t){return this._enabled?this._keys.indexOf(t)>-1:!1}wasReleased(t){return this._enabled?this._keysUp.indexOf(t)>-1:!1}triggerEvent(t,e,i){t==="down"&&this._handleKeyDown(new KeyboardEvent("keydown",{code:e,key:i!=null?i:null})),t==="up"&&this._handleKeyUp(new KeyboardEvent("keyup",{code:e,key:i!=null?i:null}))}}class xi{constructor(t,e,i,s,n,o){this.type=t,this.pointerId=e,this.button=i,this.pointerType=s,this.coordinates=n,this.nativeEvent=o,this.active=!0}cancel(){this.active=!1}get pagePos(){return this.coordinates.pagePos}get screenPos(){return this.coordinates.screenPos}get worldPos(){return this.coordinates.worldPos}}class ha{constructor(t,e,i,s,n,o,a,h,l,c,u,_){this.x=t,this.y=e,this.pageX=i,this.pageY=s,this.screenX=n,this.screenY=o,this.index=a,this.deltaX=h,this.deltaY=l,this.deltaZ=c,this.deltaMode=u,this.ev=_,this.active=!0}cancel(){this.active=!1}}class Xn{constructor(){this.events=new X,this.lastPagePos=w.Zero,this.lastScreenPos=w.Zero,this.lastWorldPos=w.Zero,this._onPointerMove=t=>{this.lastPagePos=new w(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new w(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new w(t.worldPos.x,t.worldPos.y)},this._onPointerDown=t=>{this.lastPagePos=new w(t.pagePos.x,t.pagePos.y),this.lastScreenPos=new w(t.screenPos.x,t.screenPos.y),this.lastWorldPos=new w(t.worldPos.x,t.worldPos.y)},this.on("move",this._onPointerMove),this.on("down",this._onPointerDown)}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_updateWorldPosition(t){const e=ke.fromPagePosition(this.lastPagePos,t);this.lastScreenPos=e.screenPos,this.lastWorldPos=e.worldPos}}var bi=(r=>(r.Pixel="Pixel",r.Line="Line",r.Page="Page",r))(bi||{}),Pe=(r=>(r[r.NoButton=-1]="NoButton",r[r.Left=0]="Left",r[r.Middle=1]="Middle",r[r.Right=2]="Right",r[r.Unknown=3]="Unknown",r))(Pe||{}),ce=(r=>(r.Left="Left",r.Middle="Middle",r.Right="Right",r.Unknown="Unknown",r.NoButton="NoButton",r))(ce||{}),de=(r=>(r.Touch="Touch",r.Mouse="Mouse",r.Pen="Pen",r.Unknown="Unknown",r))(de||{});function Hl(r){return globalThis.TouchEvent&&r instanceof globalThis.TouchEvent}function Nl(r){return globalThis.PointerEvent&&r instanceof globalThis.PointerEvent}class rs{constructor(t,e){this.target=t,this.engine=e,this.events=new X,this.primary=new Xn,this._activeNativePointerIdsToNormalized=new Map,this.lastFramePointerCoords=new Map,this.currentFramePointerCoords=new Map,this.currentFramePointerDown=new Map,this.lastFramePointerDown=new Map,this.currentFrameDown=[],this.currentFrameUp=[],this.currentFrameMove=[],this.currentFrameCancel=[],this.currentFrameWheel=[],this._enabled=!0,this._pointers=[this.primary],this._boundHandle=this._handle.bind(this),this._boundWheel=this._handleWheel.bind(this)}toggleEnabled(t){this._enabled=t}recreate(t,e){const i=new rs(t,e);return i.primary=this.primary,i._pointers=this._pointers,i}at(t){if(t>=this._pointers.length)for(let e=this._pointers.length-1,i=t;e<i;e++)this._pointers.push(new Xn);return this._pointers[t]}count(){return this._pointers.length}isDown(t){var e;return this._enabled&&(e=this.currentFramePointerDown.get(t))!=null?e:!1}wasDown(t){var e;return this._enabled&&(e=this.lastFramePointerDown.get(t))!=null?e:!1}isDragging(t){return this._enabled?this.isDown(t):!1}isDragStart(t){return this._enabled?this.isDown(t)&&!this.wasDown(t):!1}isDragEnd(t){return this._enabled?!this.isDown(t)&&this.wasDown(t):!1}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}update(){this.lastFramePointerDown=new Map(this.currentFramePointerDown),this.lastFramePointerCoords=new Map(this.currentFramePointerCoords);for(const t of this.currentFrameDown){if(!t.active)continue;this.emit("down",t),this.at(t.pointerId).emit("down",t),this.primary.emit("pointerdown",t)}for(const t of this.currentFrameUp){if(!t.active)continue;this.emit("up",t),this.at(t.pointerId).emit("up",t)}for(const t of this.currentFrameMove){if(!t.active)continue;this.emit("move",t),this.at(t.pointerId).emit("move",t)}for(const t of this.currentFrameCancel){if(!t.active)continue;this.emit("cancel",t),this.at(t.pointerId).emit("cancel",t)}for(const t of this.currentFrameWheel)t.active&&(this.emit("pointerwheel",t),this.emit("wheel",t),this.primary.emit("pointerwheel",t),this.primary.emit("wheel",t));if(this.engine.currentScene.camera.hasChanged())for(const t of this._pointers)t._updateWorldPosition(this.engine)}clear(){for(const t of this.currentFrameUp){this.currentFramePointerCoords.delete(t.pointerId);const e=this._activeNativePointerIdsToNormalized.entries();for(const[i,s]of e)s===t.pointerId&&this._activeNativePointerIdsToNormalized.delete(i)}this.currentFrameDown.length=0,this.currentFrameUp.length=0,this.currentFrameMove.length=0,this.currentFrameCancel.length=0,this.currentFrameWheel.length=0}init(t){var e;if(this.engine.isDisposed())return;this.target===this.engine.canvas?this.engine.canvas.style.touchAction="none":document.body.style.touchAction="none",window.PointerEvent?(this.target.addEventListener("pointerdown",this._boundHandle),this.target.addEventListener("pointerup",this._boundHandle),this.target.addEventListener("pointermove",this._boundHandle),this.target.addEventListener("pointercancel",this._boundHandle)):(this.target.addEventListener("touchstart",this._boundHandle),this.target.addEventListener("touchend",this._boundHandle),this.target.addEventListener("touchmove",this._boundHandle),this.target.addEventListener("touchcancel",this._boundHandle),this.target.addEventListener("mousedown",this._boundHandle),this.target.addEventListener("mouseup",this._boundHandle),this.target.addEventListener("mousemove",this._boundHandle));const i={passive:!(this.engine.pageScrollPreventionMode===Ke.All||this.engine.pageScrollPreventionMode===Ke.Canvas)};if("onwheel"in document.createElement("div")?this.target.addEventListener("wheel",this._boundWheel,i):document.onmousewheel!==void 0?this.target.addEventListener("mousewheel",this._boundWheel,i):this.target.addEventListener("MozMousePixelScroll",this._boundWheel,i),((e=t==null?void 0:t.grabWindowFocus)!=null?e:!0)&&(sa()||na())){const n=()=>{window.focus()};window.PointerEvent?this.target.addEventListener("pointerdown",n):(this.target.addEventListener("touchstart",n),this.target.addEventListener("mousedown",n))}}detach(){window.PointerEvent?(this.target.removeEventListener("pointerdown",this._boundHandle),this.target.removeEventListener("pointerup",this._boundHandle),this.target.removeEventListener("pointermove",this._boundHandle),this.target.removeEventListener("pointercancel",this._boundHandle)):(this.target.removeEventListener("touchstart",this._boundHandle),this.target.removeEventListener("touchend",this._boundHandle),this.target.removeEventListener("touchmove",this._boundHandle),this.target.removeEventListener("touchcancel",this._boundHandle),this.target.removeEventListener("mousedown",this._boundHandle),this.target.removeEventListener("mouseup",this._boundHandle),this.target.removeEventListener("mousemove",this._boundHandle)),"onwheel"in document.createElement("div")?this.target.removeEventListener("wheel",this._boundWheel):document.onmousewheel!==void 0?this.target.addEventListener("mousewheel",this._boundWheel):this.target.addEventListener("MozMousePixelScroll",this._boundWheel)}_normalizePointerId(t){this._activeNativePointerIdsToNormalized.set(t,-1);const i=Array.from(this._activeNativePointerIdsToNormalized.keys()).sort((s,n)=>s-n).findIndex(s=>s===t);return this._activeNativePointerIdsToNormalized.set(t,i),i}_handle(t){if(!this._enabled)return;t.preventDefault();const e=new Map;let i,s;if(Hl(t)){i=ce.Unknown,s=de.Touch;for(let n=0;n<t.changedTouches.length;n++){const o=t.changedTouches[n],a=ke.fromPagePosition(o.pageX,o.pageY,this.engine),h=n+1,l=this._normalizePointerId(h);this.currentFramePointerCoords.set(l,a),e.set(l,a)}}else{i=this._nativeButtonToPointerButton(t.button),s=de.Mouse;const n=ke.fromPagePosition(t.pageX,t.pageY,this.engine);let o=1;Nl(t)&&(o=t.pointerId,s=this._stringToPointerType(t.pointerType));const a=this._normalizePointerId(o);this.currentFramePointerCoords.set(a,n),e.set(a,n)}for(const[n,o]of e.entries())switch(t.type){case"mousedown":case"pointerdown":case"touchstart":this.currentFrameDown.push(new xi("down",n,i,s,o,t)),this.currentFramePointerDown.set(n,!0);break;case"mouseup":case"pointerup":case"touchend":this.currentFrameUp.push(new xi("up",n,i,s,o,t)),this.currentFramePointerDown.set(n,!1);break;case"mousemove":case"pointermove":case"touchmove":this.currentFrameMove.push(new xi("move",n,i,s,o,t));break;case"touchcancel":case"pointercancel":this.currentFrameCancel.push(new xi("cancel",n,i,s,o,t));break}}_handleWheel(t){if(!this._enabled)return;(this.engine.pageScrollPreventionMode===Ke.All||this.engine.pageScrollPreventionMode===Ke.Canvas&&t.target===this.engine.canvas)&&t.preventDefault();const e=this.engine.screen.pageToScreenCoordinates(b(t.pageX,t.pageY)),i=this.engine.screen.screenToWorldCoordinates(e),s=-1/40,n=t.deltaX||t.wheelDeltaX*s||0,o=t.deltaY||t.wheelDeltaY*s||t.wheelDelta*s||t.detail||0,a=t.deltaZ||0;let h=bi.Pixel;t.deltaMode&&(t.deltaMode===1?h=bi.Line:t.deltaMode===2&&(h=bi.Page));const l=new ha(i.x,i.y,t.pageX,t.pageY,e.x,e.y,0,n,o,a,h,t);this.currentFrameWheel.push(l)}triggerEvent(t,e){const i=this.engine.screen.worldToPageCoordinates(e);window.PointerEvent?this._handle(new window.PointerEvent("pointer"+t,{pointerId:0,clientX:i.x,clientY:i.y})):this._handle(new window.MouseEvent("mouse"+t,{clientX:i.x,clientY:i.y}));const s=this.engine.currentScene.world.get(is);s.preupdate(this.engine.currentScene,1),s.update(1)}_nativeButtonToPointerButton(t){switch(t){case Pe.NoButton:return ce.NoButton;case Pe.Left:return ce.Left;case Pe.Middle:return ce.Middle;case Pe.Right:return ce.Right;case Pe.Unknown:return ce.Unknown;default:return br(t)}}_stringToPointerType(t){switch(t){case"touch":return de.Touch;case"mouse":return de.Mouse;case"pen":return de.Pen;default:return de.Unknown}}}class Yn{constructor(t){this._enabled=!0;const{pointerTarget:e,grabWindowFocus:i,engine:s,global:n}=t;this.keyboard=new aa,this.pointers=new rs(e,s),this.gamepads=new ss,this.keyboard.init({global:n,grabWindowFocus:i}),this.pointers.init({grabWindowFocus:i}),this.gamepads.init(),this.inputMapper=new ia({keyboard:this.keyboard,pointers:this.pointers,gamepads:this.gamepads})}get enabled(){return this._enabled}toggleEnabled(t){this._enabled=t,this.keyboard.toggleEnabled(this._enabled),this.pointers.toggleEnabled(this._enabled),this.gamepads.toggleEnabled(this._enabled)}update(){this._enabled&&(this.inputMapper.execute(),this.keyboard.update(),this.gamepads.update())}clear(){this.keyboard.clear(),this.pointers.clear()}}class Wl{}const Gl={Initialize:"initialize",Activate:"activate",Deactivate:"deactivate",PreUpdate:"preupdate",PostUpdate:"postupdate",PreDraw:"predraw",PostDraw:"postdraw",PreDebugDraw:"predebugdraw",PostDebugDraw:"postdebugdraw",PreLoad:"preload",TransitionStart:"transitionstart",TransitionEnd:"transitionend"};function jt(r){var t,e;return!!(r!=null&&r.prototype)&&!!((e=(t=r==null?void 0:r.prototype)==null?void 0:t.constructor)!=null&&e.name)}class Mt{constructor(){this._logger=R.getInstance(),this.events=new X,this.camera=new Ko,this.world=new Er(this),this.physics=new Fo(te()),this._isInitialized=!1,this._timers=[],this._cancelQueue=[],this.world.add(Vn),this.world.add(new Qi(this.world,this.physics)),this.world.add(new Ji(this.world,this.physics)),this.world.add(is),this.world.add(Wn),this.world.add(mn),this.world.add(pn),this.world.add(Gn)}get actors(){return this.world.entityManager.entities.filter(t=>t instanceof kt)}get entities(){return this.world.entityManager.entities}get triggers(){return this.world.entityManager.entities.filter(t=>t instanceof ta)}get tileMaps(){return this.world.entityManager.entities.filter(t=>t instanceof Go)}get timers(){return this._timers}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}onPreLoad(t){}onTransition(t){}onInitialize(t){}onActivate(t){}onDeactivate(t){}onPreUpdate(t,e){}onPostUpdate(t,e){}onPreDraw(t,e){}onPostDraw(t,e){}_initializeChildren(){for(const t of this.entities)t._initialize(this.engine)}get isInitialized(){return this._isInitialized}async _initialize(t){var e;if(!this.isInitialized){try{this.engine=t,this.physics.config=this.engine.physics,this.input=new Yn({global:t.global,pointerTarget:t.pointerScope===Be.Canvas?t.canvas:document,grabWindowFocus:t.grabWindowFocus,engine:t}),this.camera._initialize(t),this.world.systemManager.initialize(),await this.onInitialize(t),this._initializeChildren(),this._logger.debug("Scene.onInitialize",this,t),this.events.emit("initialize",new Oe(t,this))}catch(i){throw this._logger.error(`Error during scene initialization for scene ${(e=t.director)==null?void 0:e.getSceneName(this)}!`),i}this._isInitialized=!0}}async _activate(t){var e,i;try{this._logger.debug("Scene.onActivate",this),this.input.toggleEnabled(!0),await this.onActivate(t)}catch(s){throw this._logger.error(`Error during scene activation for scene ${(i=(e=this.engine)==null?void 0:e.director)==null?void 0:i.getSceneName(this)}!`),s}}async _deactivate(t){return this._logger.debug("Scene.onDeactivate",this),this.input.toggleEnabled(!1),await this.onDeactivate(t)}_preupdate(t,e){this.emit("preupdate",new re(t,e,this)),this.onPreUpdate(t,e)}_postupdate(t,e){this.emit("postupdate",new oe(t,e,this)),this.onPostUpdate(t,e)}_predraw(t,e){this.emit("predraw",new Ue(t,e,this)),this.onPreDraw(t,e)}_postdraw(t,e){this.emit("postdraw",new ze(t,e,this)),this.onPostDraw(t,e)}update(t,e){var i;if(!this.isInitialized){this._logger.warnOnce(`Scene update called before initialize for scene ${(i=t.director)==null?void 0:i.getSceneName(this)}!`);return}this._preupdate(t,e);let s,n;for(s=0,n=this._cancelQueue.length;s<n;s++)this.removeTimer(this._cancelQueue[s]);this._cancelQueue.length=0;for(const o of this._timers)o.update(e);this.world.update(Pt.Update,e),this.camera&&this.camera.update(t,e),this._collectActorStats(t),this._postupdate(t,e),this.input.update()}draw(t,e){var i;if(!this.isInitialized){this._logger.warnOnce("Scene draw called before initialize!");return}this._predraw(t,e),this.world.update(Pt.Draw,e),(i=this.engine)!=null&&i.isDebug&&this.debugDraw(t),this._postdraw(t,e)}debugDraw(t){this.emit("predebugdraw",new Ds(t,this)),this.emit("postdebugdraw",new Bs(t,this))}contains(t){return this.actors.indexOf(t)>-1}add(t){if(this.emit("entityadded",{target:t}),t instanceof es){xr(this._timers,t)||this.addTimer(t);return}this.world.add(t),t.scene=this}transfer(t){let e;t instanceof At&&t.scene&&t.scene!==this&&(e=t.scene,t.scene.world.remove(t,!1)),t instanceof es&&t.scene&&(e=t.scene,t.scene.removeTimer(t)),e==null||e.emit("entityremoved",{target:t}),this.add(t)}remove(t){this.emit("entityremoved",{target:t}),t instanceof At&&(t.isActive&&t.kill(),this.world.remove(t)),t instanceof es&&this.removeTimer(t)}clear(t=!0){for(let e=this.entities.length-1;e>=0;e--)this.world.remove(this.entities[e],t);for(let e=this.timers.length-1;e>=0;e--)this.removeTimer(this.timers[e])}addTimer(t){return this._timers.push(t),t.scene=this,t}removeTimer(t){const e=this._timers.indexOf(t);return e!==-1&&this._timers.splice(e,1),t}cancelTimer(t){return this._cancelQueue.push(t),t}isTimerActive(t){return this._timers.indexOf(t)>-1&&!t.complete}isCurrentScene(){return this.engine?this.engine.currentScene===this:!1}_collectActorStats(t){const e=this.actors;for(let i=0;i<e.length;i++){const s=e[i];s instanceof Hn&&t.stats.currFrame.actors.ui++,t.stats.currFrame.actors.alive++;for(let n=0;n<s.children.length;n++){const o=s.children[n];Ho(o)?t.stats.currFrame.actors.ui++:t.stats.currFrame.actors.alive++}}}}class la{constructor(t){this._engine=t,this._colorBlindPostProcessor=new Qr($e.Protanope)}correct(t){this._engine.graphicsContext instanceof $t&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!1,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}simulate(t){this._engine.graphicsContext instanceof $t&&(this.clear(),this._colorBlindPostProcessor.colorBlindnessMode=t,this._colorBlindPostProcessor.simulate=!0,this._engine.graphicsContext.addPostProcessor(this._colorBlindPostProcessor))}clear(){this._engine.graphicsContext.removePostProcessor(this._colorBlindPostProcessor)}}class ca{constructor(t){this.stats={currFrame:new yi,prevFrame:new yi},this.settings={text:{foreground:T.Black,background:T.Transparent,border:T.Transparent},z:{text:Number.POSITIVE_INFINITY,point:Number.MAX_SAFE_INTEGER-1,ray:Number.MAX_SAFE_INTEGER-1,dashed:Number.MAX_SAFE_INTEGER-2,solid:Number.MAX_SAFE_INTEGER-3}},this.filter={useFilter:!1,nameQuery:"",ids:[]},this.entity={showAll:!1,showId:!1,showName:!1},this.transform={showAll:!1,showPosition:!1,showPositionLabel:!1,positionColor:T.Yellow,showZIndex:!1,showScale:!1,scaleColor:T.Green,showRotation:!1,rotationColor:T.Blue},this.graphics={showAll:!1,showBounds:!1,boundsColor:T.Yellow},this.collider={showAll:!1,showBounds:!1,boundsColor:T.Blue,showOwner:!1,showGeometry:!0,geometryColor:T.Green,geometryLineWidth:2,geometryPointSize:2},this.physics={showAll:!1,showBroadphaseSpacePartitionDebug:!1,showCollisionNormals:!1,collisionNormalColor:T.Cyan,showCollisionContacts:!0,contactSize:10,collisionContactColor:T.Red},this.motion={showAll:!1,showVelocity:!1,velocityColor:T.Yellow,showAcceleration:!1,accelerationColor:T.Red},this.body={showAll:!1,showCollisionGroup:!1,showCollisionType:!1,showSleeping:!1,showMotion:!1,showMass:!1},this.camera={showAll:!1,showFocus:!1,focusColor:T.Red,showZoom:!1},this.tilemap={showAll:!1,showGrid:!1,gridColor:T.Red,gridWidth:.5,showSolidBounds:!1,solidBoundsColor:T.fromHex("#8080807F"),showColliderGeometry:!0},this.isometric={showAll:!1,showPosition:!1,positionColor:T.Yellow,positionSize:1,showGrid:!1,gridColor:T.Red,gridWidth:1,showColliderGeometry:!0},this._engine=t,this.colorBlindMode=new la(this._engine),Tt.registerDebugConfig(this)}useTestClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toTestClock();return e&&i.start(),this._engine.clock=i,i}useStandardClock(){const t=this._engine.clock,e=t.isRunning();t.stop();const i=t.toStandardClock();return e&&i.start(),this._engine.clock=i,i}}class yi{constructor(){this._id=0,this._elapsedMs=0,this._fps=0,this._actorStats={alive:0,killed:0,ui:0,get remaining(){return this.alive-this.killed},get total(){return this.remaining+this.ui}},this._durationStats={update:0,draw:0,get total(){return this.update+this.draw}},this._physicsStats=new os,this._graphicsStats={drawCalls:0,drawnImages:0}}reset(t){t?(this.id=t.id,this.elapsedMs=t.elapsedMs,this.fps=t.fps,this.actors.alive=t.actors.alive,this.actors.killed=t.actors.killed,this.actors.ui=t.actors.ui,this.duration.update=t.duration.update,this.duration.draw=t.duration.draw,this._physicsStats.reset(t.physics),this.graphics.drawCalls=t.graphics.drawCalls,this.graphics.drawnImages=t.graphics.drawnImages):(this.id=this.elapsedMs=this.fps=0,this.actors.alive=this.actors.killed=this.actors.ui=0,this.duration.update=this.duration.draw=0,this._physicsStats.reset(),this.graphics.drawnImages=this.graphics.drawCalls=0)}clone(){const t=new yi;return t.reset(this),t}get id(){return this._id}set id(t){this._id=t}get elapsedMs(){return this._elapsedMs}set elapsedMs(t){this._elapsedMs=t}get fps(){return this._fps}set fps(t){this._fps=t}get actors(){return this._actorStats}get duration(){return this._durationStats}get physics(){return this._physicsStats}get graphics(){return this._graphicsStats}}class os{constructor(){this._pairs=0,this._collisions=0,this._contacts=new Map,this._fastBodies=0,this._fastBodyCollisions=0,this._broadphase=0,this._narrowphase=0}reset(t){t?(this.pairs=t.pairs,this.collisions=t.collisions,this.contacts=t.contacts,this.fastBodies=t.fastBodies,this.fastBodyCollisions=t.fastBodyCollisions,this.broadphase=t.broadphase,this.narrowphase=t.narrowphase):(this.pairs=this.collisions=this.fastBodies=0,this.fastBodyCollisions=this.broadphase=this.narrowphase=0,this.contacts.clear())}clone(){const t=new os;return t.reset(this),t}get pairs(){return this._pairs}set pairs(t){this._pairs=t}get collisions(){return this._collisions}set collisions(t){this._collisions=t}get contacts(){return this._contacts}set contacts(t){this._contacts=t}get fastBodies(){return this._fastBodies}set fastBodies(t){this._fastBodies=t}get fastBodyCollisions(){return this._fastBodyCollisions}set fastBodyCollisions(t){this._fastBodyCollisions=t}get broadphase(){return this._broadphase}set broadphase(t){this._broadphase=t}get narrowphase(){return this._narrowphase}set narrowphase(t){this._narrowphase=t}}class $n{constructor(t){this.nativeComponent=t,this._paused=!1,this._nativeHandlers={}}on(t,e){this._nativeHandlers[t]&&this.off(t,this._nativeHandlers[t]),this._nativeHandlers[t]=this._decorate(e),this.nativeComponent.addEventListener(t,this._nativeHandlers[t])}off(t,e){e||(e=this._nativeHandlers[t]),this.nativeComponent.removeEventListener(t,e),this._nativeHandlers[t]=null}_decorate(t){return e=>{this._paused||t(e)}}pause(){this._paused=!0}resume(){this._paused=!1}clear(){for(const t in this._nativeHandlers)this.off(t)}}class da{constructor(t,e){this._windowGlobal=t,this._documentGlobal=e,this._windowComponent=new $n(this._windowGlobal),this._documentComponent=new $n(this._documentGlobal)}get window(){return this._windowComponent}get document(){return this._documentComponent}pause(){this.window.pause(),this.document.pause()}resume(){this.window.resume(),this.document.resume()}clear(){this.window.clear(),this.document.clear()}}class ua{constructor(t){this._samplePeriod=100,this._currentFrameTime=0,this._frames=0,this._previousSampleTime=0,this._beginFrameTime=0;var e;this._fps=t.initialFps,this._samplePeriod=(e=t.samplePeriod)!=null?e:this._samplePeriod,this._currentFrameTime=1e3/t.initialFps,this._nowFn=t.nowFn,this._previousSampleTime=this._nowFn()}start(){this._beginFrameTime=this._nowFn()}end(){this._frames++;const t=this._nowFn();this._currentFrameTime=t-this._beginFrameTime,t>=this._previousSampleTime+this._samplePeriod&&(this._fps=this._frames*1e3/(t-this._previousSampleTime),this._previousSampleTime=t,this._frames=0)}get fps(){return this._fps}get instant(){return 1e3/this._currentFrameTime}}class Zn{constructor(t){this._onFatalException=()=>{},this._maxFps=1/0,this._lastTime=0,this._elapsed=1,this._scheduledCbs=[],this._totalElapsed=0,this._nextScheduleId=0,this._idsToRemove=[];var e,i,s;this._options=t,this.tick=t.tick,this._lastTime=(e=this.now())!=null?e:0,this._maxFps=(i=t.maxFps)!=null?i:this._maxFps,this._onFatalException=(s=t.onFatalException)!=null?s:this._onFatalException,this.fpsSampler=new ua({initialFps:60,nowFn:()=>this.now()})}elapsed(){return this._elapsed}now(){return performance.now()}toTestClock(){return new _a({...this._options,defaultUpdateMs:16.6})}toStandardClock(){return new jn({...this._options})}setFatalExceptionHandler(t){this._onFatalException=t}schedule(t,e=0,i="preframe"){const s=this._totalElapsed+e,n=this._nextScheduleId++;return this._scheduledCbs.push([n,t,s,i]),n}clearSchedule(t){this._idsToRemove.push(t)}__runScheduledCbs(t="preframe"){for(let e=this._scheduledCbs.length-1;e>-1;e--){const[i,s,n,o]=this._scheduledCbs[e];this._idsToRemove.includes(i)||t===o&&n<=this._totalElapsed&&(s(this._elapsed),this._scheduledCbs.splice(e,1))}for(const e of this._idsToRemove){const i=this._scheduledCbs.findIndex(([s])=>s===e);i!==-1&&this._scheduledCbs.splice(i,1)}}update(t){try{this.fpsSampler.start();const e=this.now();let i=e-this._lastTime||1;const s=1e3/this._maxFps;if(i>=s){let n=0;s!==0&&(n=i%s,i=i-n),i>200&&(i=1),this._elapsed=t||i,this._totalElapsed+=this._elapsed,this.__runScheduledCbs("preframe"),this.tick(t||i),this.__runScheduledCbs("postframe"),s!==0?this._lastTime=e-n:this._lastTime=e,this.fpsSampler.end()}}catch(e){this._onFatalException(e),this.stop()}}}class jn extends Zn{constructor(t){super(t),this._running=!1}isRunning(){return this._running}start(){if(this._running)return;this._running=!0;const t=()=>{if(this._running)try{this._requestId=window.requestAnimationFrame(t),this.update()}catch(e){throw window.cancelAnimationFrame(this._requestId),e}};t()}stop(){window.cancelAnimationFrame(this._requestId),this._running=!1}}class _a extends Zn{constructor(t){super({...t}),this._logger=R.getInstance(),this._running=!1,this._currentTime=0,this._updateMs=t.defaultUpdateMs}now(){var t;return(t=this._currentTime)!=null?t:0}isRunning(){return this._running}start(){this._running=!0}stop(){this._running=!1}step(t){const e=t!=null?t:this._updateMs;this._running?(this.update(e),this._currentTime+=e):this._logger.warn("The clock is not running, no step will be performed")}run(t,e){for(let i=0;i<t;i++)this.step(e!=null?e:this._updateMs)}}const Vl="#ex-toast-container{position:absolute;height:0;min-width:50%;left:50%;top:0}.ex-toast-message{left:-50%;position:relative;display:flex;justify-content:space-between;padding:10px;margin-top:5px;font-size:18px;font-family:sans-serif;border-radius:6px;border:3px solid #b7b779;background-color:#fdfdc0}.ex-toast-message button{align-self:flex-start}";class fa{constructor(){this._toasterCss=Vl,this._isInitialized=!1}_initialize(){this._isInitialized||(this._container=document.createElement("div"),this._container.id="ex-toast-container",document.body.appendChild(this._container),this._isInitialized=!0,this._styleBlock=document.createElement("style"),this._styleBlock.textContent=this._toasterCss,document.head.appendChild(this._styleBlock))}dispose(){this._container.parentElement.removeChild(this._container),this._styleBlock.parentElement.removeChild(this._styleBlock),this._isInitialized=!1}_createFragment(t){const e=document.createElement("span");return e.innerText=t,e}toast(t,e,i){this._initialize();const s=document.createElement("div");s.className="ex-toast-message";const n=t.split("[LINK]").map(c=>this._createFragment(c));if(e){const c=document.createElement("a");c.href=e,i?c.innerText=i:c.innerText=e,n.splice(1,0,c)}const o=document.createElement("div");n.forEach(c=>{o.appendChild(c)}),s.appendChild(o);const a=document.createElement("button");a.innerText="x",a.addEventListener("click",()=>{this._container.removeChild(s)}),s.appendChild(a);const h=c=>{if(c.key==="Escape")try{this._container.removeChild(s)}catch(u){}document.removeEventListener("keydown",h)};document.addEventListener("keydown",h);const l=this._container.firstChild;this._container.insertBefore(s,l)}}const ga={NavigationStart:"navigationstart",Navigation:"navigation",NavigationEnd:"navigationend"};class pa{constructor(t,e){this._engine=t,this.events=new X,this._logger=R.getInstance(),this._initialized=!1,this.scenes={},this._sceneToInstance=new Map,this._sceneToLoader=new Map,this._sceneToTransition=new Map,this._loadedScenes=new Set,this._isTransitioning=!1,this.rootScene=this.currentScene=new Mt,this.add("root",this.rootScene),this.currentScene=this.rootScene,this.currentSceneName="root";for(const i in e){const s=e[i];this.add(i,s),i==="root"&&(this.rootScene=this.getSceneInstance("root"),this.currentScene=this.rootScene)}}get isTransitioning(){return this._isTransitioning}async onInitialize(){if(!this._initialized)if(this._initialized=!0,this._deferredGoto){const t=this._deferredGoto;this._deferredGoto=void 0;const e=this._deferredTransition;this._deferredTransition=void 0;const i=this.getSceneInstance(t);i&&e&&e._addToTargetScene(this._engine,i);const s=this._getInTransition(t),n=s==null?void 0:s.hideLoader;this.maybeLoadScene(t,n),await this.swapScene(t),i&&e&&await this.playTransition(e,i)}else await this.swapScene("root")}get isInitialized(){return this._initialized}configureStart(t,e){var i,s;const n=e==null?void 0:e.loader;n instanceof mi?this.mainLoader=n:On(n)?this.mainLoader=new n:this.mainLoader=new ts;let o;if(e!=null&&e.inTransition){const{inTransition:h}=e;o=h}this.startScene=t;const a=(s=(i=e==null?void 0:e.inTransition)==null?void 0:i.hideLoader)!=null?s:!1;if(this.maybeLoadScene(t,a),o){const h=this.getSceneInstance(t);h&&(o._addToTargetScene(this._engine,h),this.swapScene(t).then(()=>(h.onTransition("in"),this.playTransition(o,h))))}else this.swapScene(t);this.currentSceneName=this.startScene}_getLoader(t){return this._sceneToLoader.get(t)}_getInTransition(t){var e;const i=this.scenes[t];if(!(i instanceof Mt||jt(i)))return(e=i==null?void 0:i.transitions)==null?void 0:e.in}_getOutTransition(t){var e;const i=this.scenes[t];if(!(i instanceof Mt||jt(i)))return(e=i==null?void 0:i.transitions)==null?void 0:e.out}getDeferredScene(){const t=this.getSceneDefinition(this._deferredGoto);return this._deferredGoto&&t?t:null}getSceneDefinition(t){const e=this.scenes[t];if(e instanceof Mt||jt(e))return e;if(e)return e.scene}getSceneName(t){for(const[e,i]of Object.entries(this.scenes))if(i instanceof Mt){if(t===i)return e}else if(!jt(i)&&t===i.scene)return e;for(const[e,i]of Object.entries(this.scenes))if(jt(i)){if(t.constructor===i)return e}else if(!(i instanceof Mt)&&t.constructor===i.scene)return e;return null}assertAdded(t){return this}assertRemoved(t){return this}add(t,e){if(!(e instanceof Mt)&&!jt(e)){const{loader:i,transitions:s}=e,{in:n,out:o}=s!=null?s:{};this._sceneToTransition.set(t,{in:n,out:o}),On(i)?this._sceneToLoader.set(t,new i):i&&this._sceneToLoader.set(t,i)}return this.scenes[t]&&this._logger.warn("Scene",t,"already exists overwriting"),this.scenes[t]=e,this.assertAdded(t)}remove(t){if(t instanceof Mt||jt(t)){const e=t;for(const i in this.scenes)if(this.scenes.hasOwnProperty(i)){const s=this.scenes[i];let n;if(s instanceof Mt||jt(s)?n=s:n=s.scene,n===e){if(i===this.currentSceneName)throw new Error(`Cannot remove a currently active scene: ${i}`);this._sceneToInstance.delete(i),this._sceneToTransition.delete(i),this._sceneToLoader.delete(i),delete this.scenes[i]}}}if(typeof t=="string"){if(t===this.currentSceneName)throw new Error(`Cannot remove a currently active scene: ${t}`);this._sceneToInstance.delete(t),this._sceneToTransition.delete(t),this._sceneToLoader.delete(t),delete this.scenes[t]}}async goToScene(t,e){var i,s,n,o,a,h;const l=this.getSceneInstance(t);if(!l){this._logger.warn(`Scene ${t} does not exist! Check the name, are you sure you added it?`);return}const c=this.currentScene,u=this.currentSceneName,_=(s=(i=this._engine.input)==null?void 0:i.enabled)!=null?s:!0;this._isTransitioning=!0;const f=(n=this.getSceneInstance(u))==null?void 0:n.onTransition("out"),m=l==null?void 0:l.onTransition("in");e={sourceOut:(o=this._getOutTransition(this.currentSceneName))!=null?o:f,destinationIn:(a=this._getInTransition(t))!=null?a:m,...e};const{sourceOut:p,destinationIn:x,sceneActivationData:v}=e,g=p!=null?p:this._getOutTransition(this.currentSceneName),y=x!=null?x:this._getInTransition(t),S=(g==null?void 0:g.hideLoader)||(y==null?void 0:y.hideLoader);S&&this.maybeLoadScene(t,S),this._emitEvent("navigationstart",u,t),g&&await this.playTransition(g,c),await this.maybeLoadScene(t,S),y&&await y.onPreviousSceneDeactivate(this.currentScene),y&&y._addToTargetScene(this._engine,l),await this.swapScene(t,v),this._emitEvent("navigation",u,t),y&&await this.playTransition(y,l),this._emitEvent("navigationend",u,t),(h=this._engine.input)==null||h.toggleEnabled(_),this._isTransitioning=!1}getSceneInstance(t){const e=this.getSceneDefinition(t);if(!e)return;if(this._sceneToInstance.has(t))return this._sceneToInstance.get(t);if(e instanceof Mt)return this._sceneToInstance.set(t,e),e;const i=new e;return this._sceneToInstance.set(t,i),i}async maybeLoadScene(t,e=!1){var i;const s=(i=this._getLoader(t))!=null?i:new mi,n=this.getSceneDefinition(t),o=this.getSceneInstance(t);n&&o&&!this._loadedScenes.has(o)&&(o.onPreLoad(s),o.events.emit("preload",{loader:s}),e?this._engine.load(s,e):await this._engine.load(s),this._loadedScenes.add(o))}async playTransition(t,e){var i,s,n,o,a,h,l;if(!this.isInitialized){this._deferredTransition=t;return}if(t){this.currentTransition=t;const c=(s=(i=e.input)==null?void 0:i.enabled)!=null?s:!0;(n=e.input)==null||n.toggleEnabled(!t.blockInput),(o=this._engine.input)==null||o.toggleEnabled(!t.blockInput),e.events.emit("transitionstart",t),this.currentTransition._addToTargetScene(this._engine,e),await this.currentTransition._play(),e.events.emit("transitionend",t),(a=e.input)==null||a.toggleEnabled(c)}(h=this.currentTransition)==null||h.kill(),(l=this.currentTransition)==null||l.reset(),this.currentTransition=void 0}async swapScene(t,e){const i=this._engine;if(!this.isInitialized){this._deferredGoto=t;return}const s=this.getSceneInstance(t);if(s){const n=this.currentScene,o=s;let a;if(this._logger.debug("Going to scene:",t),this.currentScene.isInitialized){const c={engine:i,previousScene:n,nextScene:o};a=await this.currentScene._deactivate(c),this.currentScene.events.emit("deactivate",new Vs(c,this.currentScene)),this.currentScene.input.clear()}const h=this._sceneToLoader.get(t);await(h==null?void 0:h.areResourcesLoaded()),this.currentScene=o,this.currentSceneName=t,i.screen.setCurrentCamera(o.camera),await this.currentScene._initialize(i);const l={engine:i,previousScene:n,previousSceneData:a,nextScene:o,data:e};await this.currentScene._activate(l),this.currentScene.events.emit("activate",new Gs(l,this.currentScene))}else this._logger.error("Scene",t,"does not exist!")}_emitEvent(t,e,i){const s=this.getSceneDefinition(e),n=this.getSceneDefinition(i);this.events.emit(t,{sourceScene:s,sourceName:e,destinationScene:n,destinationName:i})}}function ma(){const r={scope:(t,e)=>{const i=r.value;r.value=t;try{const s=e();return s&&typeof s.then=="function"?s.finally(()=>{r.value=i}):s}catch(s){throw s}finally{r.value=i}},value:void 0};return r}function va(r){return r.value}const Qn={textureCollectInterval:6e4};class wa{constructor(t){this.options=t,this._running=!1,this._collectionMap=new Map,this._collectors=new Map,this.collectStaleResources=e=>{if(this._running){for(const[i,[s,n]]of this._collectors.entries()){const o=this.options.getTimestamp();for(const[a,[h,l]]of this._collectionMap.entries()){if(i!==h||l+n>=o)continue;s(a)&&this._collectionMap.delete(a)}}this._collectHandle=requestIdleCallback(this.collectStaleResources)}}}registerCollector(t,e,i){this._collectors.set(t,[i,e])}addCollectableResource(t,e){this._collectionMap.set(e,[t,this.options.getTimestamp()])}touch(t){const e=this._collectionMap.get(t);e&&this._collectionMap.set(t,[e[0],this.options.getTimestamp()])}forceCollectAll(){for(const[t,[e]]of this._collectors.entries())for(const[i]of this._collectionMap.entries())e(i)&&this._collectionMap.delete(i)}running(){return this._running}start(){this._running=!0,this.collectStaleResources()}stop(){this._running=!1,cancelIdleCallback(this._collectHandle)}}Fe();const ql={FallbackGraphicsContext:"fallbackgraphicscontext",Initialize:"initialize",Visible:"visible",Hidden:"hidden",Start:"start",Stop:"stop",PreUpdate:"preupdate",PostUpdate:"postupdate",PreFrame:"preframe",PostFrame:"postframe",PreDraw:"predraw",PostDraw:"postdraw",...ga};var Ke=(r=>(r[r.None=0]="None",r[r.Canvas=1]="Canvas",r[r.All=2]="All",r))(Ke||{});const as=class _e{constructor(t){this.scope=A=>_e.Context.scope(this,A),this.version=er,this.events=new X,this.maxFps=Number.POSITIVE_INFINITY,this._inputEnabled=!0,this._suppressPlayButton=!1,this.pauseAudioWhenHidden=!0,this._isDebug=!1,this.enableCanvasTransparency=!0,this.onFatalException=A=>{R.getInstance().fatal(A,A.stack)},this._toaster=new fa,this._timescale=1,this._isInitialized=!1,this._hasCreatedCanvas=!1,this._originalOptions={},this._handleWebGLContextLost=A=>{var I;A.preventDefault(),this.clock.stop(),this._logger.fatalOnce("WebGL Graphics Lost",A);const C=document.createElement("div");C.id="ex-webgl-graphics-context-lost",C.style.position="absolute",C.style.zIndex="99",C.style.left="50%",C.style.top="50%",C.style.display="flex",C.style.flexDirection="column",C.style.transform="translate(-50%, -50%)",C.style.backgroundColor="white",C.style.padding="10px",C.style.borderStyle="solid 1px";const L=document.createElement("div");if(L.innerHTML=`
|
|
787
898
|
<h1>There was an issue rendering, please refresh the page.</h1>
|
|
788
899
|
<div>
|
|
789
900
|
<p>WebGL Graphics Context Lost</p>
|
|
@@ -799,12 +910,12 @@ If you want to do custom drawing, use Actor.graphics, or any onPreDraw or onPost
|
|
|
799
910
|
<li>Graphics driver was updated</li>
|
|
800
911
|
</ul>
|
|
801
912
|
</div>
|
|
802
|
-
`,
|
|
913
|
+
`,C.appendChild(L),(I=this.canvas)!=null&&I.parentElement){this.canvas.parentElement.appendChild(C);const U=L.querySelector("#ex-webgl-graphics-reload");U==null||U.addEventListener("click",()=>location.reload())}},this._performanceThresholdTriggered=!1,this._fpsSamples=[],this._disposed=!1,this._isLoading=!1,this._hideLoader=!1,this._isReadyFuture=new wt,this.currentFrameElapsedMs=0,this.currentFrameLagMs=0,this._lagMs=0,this._screenShotRequests=[];var e,i,s,n,o,a,h,l,c;t={..._e._DEFAULT_ENGINE_OPTIONS,...t},this._originalOptions=t,De.freeze(),this.browser=new da(window,document);const u=new Oo;if(!t.suppressMinimumBrowserFeatureDetection&&!(this._compatible=u.test())){const A=document.createElement("div");if(A.innerText="Sorry, your browser does not support all the features needed for Excalibur",document.body.appendChild(A),u.failedTests.forEach(function(I){const C=document.createElement("div");C.innerText="Browser feature missing "+I,document.body.appendChild(C)}),t.canvasElementId){const I=document.getElementById(t.canvasElementId);I&&I.parentElement.removeChild(I)}return}else this._compatible=!0;if(console.log&&!t.suppressConsoleBootMessage&&(console.log(`%cPowered by Excalibur.js (v${er})`,"background: #176BAA; color: white; border-radius: 5px; padding: 15px; font-size: 1.5em; line-height: 80px;"),console.log(`
|
|
803
914
|
/| ________________
|
|
804
915
|
O|===|* >________________>
|
|
805
|
-
\\|`),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=R.getInstance(),this._logger.defaultLevel===Le.Debug&&u.logBrowserFeatures(),this._logger.debug("Building engine..."),t.garbageCollection===!0?this.garbageCollectorConfig={...Qn}:t.garbageCollection===!1?(this._logger.warn("WebGL Garbage Collection Disabled!!! If you leak any images over time your game will crash when GPU memory is exhausted"),this.garbageCollectorConfig=null):this.garbageCollectorConfig={...Qn,...t.garbageCollection},this._garbageCollector=new wa({getTimestamp:Date.now}),this.canvasElementId=t.canvasElementId,t.canvasElementId){if(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),document.getElementById(t.canvasElementId)===null)throw new Error("Cannot find existing element in the DOM, please ensure element is created prior to engine creation.");this.canvas=document.getElementById(t.canvasElementId),this._hasCreatedCanvas=!1}else t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement,this._hasCreatedCanvas=!1):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"),this._hasCreatedCanvas=!0);this.canvas&&!t.enableCanvasContextMenu&&this.canvas.addEventListener("contextmenu",
|
|
916
|
+
\\|`),console.log("Visit","http://excaliburjs.com","for more information")),t.suppressPlayButton&&(this._suppressPlayButton=!0),this._logger=R.getInstance(),this.debug=new ca(this),this._logger.defaultLevel===Le.Debug&&u.logBrowserFeatures(),this._logger.debug("Building engine..."),t.garbageCollection===!0?this.garbageCollectorConfig={...Qn}:t.garbageCollection===!1?(this._logger.warn("WebGL Garbage Collection Disabled!!! If you leak any images over time your game will crash when GPU memory is exhausted"),this.garbageCollectorConfig=null):this.garbageCollectorConfig={...Qn,...t.garbageCollection},this._garbageCollector=new wa({getTimestamp:Date.now}),this.canvasElementId=t.canvasElementId,t.canvasElementId){if(this._logger.debug("Using Canvas element specified: "+t.canvasElementId),document.getElementById(t.canvasElementId)===null)throw new Error("Cannot find existing element in the DOM, please ensure element is created prior to engine creation.");this.canvas=document.getElementById(t.canvasElementId),this._hasCreatedCanvas=!1}else t.canvasElement?(this._logger.debug("Using Canvas element specified:",t.canvasElement),this.canvas=t.canvasElement,this._hasCreatedCanvas=!1):(this._logger.debug("Using generated canvas element"),this.canvas=document.createElement("canvas"),this._hasCreatedCanvas=!0);this.canvas&&!t.enableCanvasContextMenu&&this.canvas.addEventListener("contextmenu",A=>{A.preventDefault()});let _=(e=t.displayMode)!=null?e:gi.Fixed;t.width&&t.height||t.viewport?(t.displayMode===void 0&&(_=gi.Fixed),this._logger.debug("Engine viewport is size "+t.width+" x "+t.height)):t.displayMode||(this._logger.debug("Engine viewport is fit"),_=gi.FitScreen);const f=t.global&&typeof t.global=="function"?t.global():t.global;this.global=f!=null?f:ra(),this.grabWindowFocus=t.grabWindowFocus,this.pointerScope=t.pointerScope,this._originalDisplayMode=_;let m,p,x,v,g,y;typeof t.antialiasing=="object"?{pixelArtSampler:m,nativeContextAntialiasing:x,multiSampleAntialiasing:y,filtering:g,canvasImageRendering:v}={...t.pixelArt?Hr:Or,...t.antialiasing}:(m=!!t.pixelArt,x=!1,y=t.antialiasing,v=t.antialiasing?"auto":"pixelated",g=t.antialiasing?mt.Blended:mt.Pixel),x&&y&&this._logger.warnOnce("Cannot use antialias setting nativeContextAntialiasing and multiSampleAntialiasing at the same time, they are incompatible settings. If you aren't sure use multiSampleAntialiasing"),t.pixelArt&&(p=.25),(!t.antialiasing||g===mt.Pixel)&&(p=0),p=(s=(i=t.uvPadding)!=null?i:p)!=null?s:.01;let S=De.isEnabled("use-canvas-context");if(!S)try{this.graphicsContext=new $t({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,pixelArtSampler:m,antialiasing:x,multiSampleAntialiasing:y,uvPadding:p,powerPreference:t.powerPreference,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting,garbageCollector:this.garbageCollectorConfig?{garbageCollector:this._garbageCollector,collectionInterval:this.garbageCollectorConfig.textureCollectInterval}:null,handleContextLost:(n=t.handleContextLost)!=null?n:this._handleWebGLContextLost,handleContextRestored:t.handleContextRestored})}catch(A){this._logger.warn(`Excalibur could not load webgl for some reason (${A.message}) and loaded a Canvas 2D fallback. Some features of Excalibur will not work in this mode.
|
|
806
917
|
|
|
807
|
-
Read more about this issue at https://excaliburjs.com/docs/performance`),
|
|
918
|
+
Read more about this issue at https://excaliburjs.com/docs/performance`),S=!0}S&&(this.graphicsContext=new $i({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,antialiasing:x,backgroundColor:t.backgroundColor,snapToPixel:t.snapToPixel,useDrawSorting:t.useDrawSorting})),this.screen=new kn({canvas:this.canvas,context:this.graphicsContext,antialiasing:x,canvasImageRendering:v,browser:this.browser,viewport:(o=t.viewport)!=null?o:t.width&&t.height?{width:t.width,height:t.height}:Bn.SVGA,resolution:t.resolution,displayMode:_,pixelRatio:t.suppressHiDPIScaling?1:(a=t.pixelRatio)!=null?a:null}),Xe.filtering=g,t.backgroundColor&&(this.backgroundColor=t.backgroundColor.clone()),this.maxFps=(h=t.maxFps)!=null?h:this.maxFps,this.fixedUpdateTimestep=(l=t.fixedUpdateTimestep)!=null?l:this.fixedUpdateTimestep,this.fixedUpdateFps=(c=t.fixedUpdateFps)!=null?c:this.fixedUpdateFps,this.fixedUpdateTimestep=this.fixedUpdateTimestep||1e3/this.fixedUpdateFps,this.clock=new jn({maxFps:this.maxFps,tick:this._mainloop.bind(this),onFatalException:A=>this.onFatalException(A)}),this.enableCanvasTransparency=t.enableCanvasTransparency,typeof t.physics=="boolean"?this.physics={...te(),enabled:t.physics}:(this.physics={...te()},ki(this.physics,t.physics)),this.director=new pa(this,t.scenes),this.director.events.pipe(this.events),this._initialize(t),window.___EXCALIBUR_DEVTOOL=this,_e.InstanceCount++}static useEngine(){const t=va(_e.Context);if(!t)throw new Error("Cannot inject engine with `useEngine()`, `useEngine()` was called outside of Engine lifecycle scope.");return t}get canvasWidth(){return this.screen.canvasWidth}get halfCanvasWidth(){return this.screen.halfCanvasWidth}get canvasHeight(){return this.screen.canvasHeight}get halfCanvasHeight(){return this.screen.halfCanvasHeight}get drawWidth(){return this.screen.drawWidth}get halfDrawWidth(){return this.screen.halfDrawWidth}get drawHeight(){return this.screen.drawHeight}get halfDrawHeight(){return this.screen.halfDrawHeight}get isHiDpi(){return this.screen.isHiDpi}get stats(){return this.debug.stats}get currentScene(){return this.director.currentScene}get currentSceneName(){return this.director.currentSceneName}get rootScene(){return this.director.rootScene}get scenes(){return this.director.scenes}get isFullscreen(){return this.screen.isFullScreen}get displayMode(){return this.screen.displayMode}get pixelRatio(){return this.screen.pixelRatio}get isDebug(){return this._isDebug}get snapToPixel(){return this.graphicsContext.snapToPixel}set snapToPixel(t){this.graphicsContext.snapToPixel=t}emit(t,e){this.events.emit(t,e)}on(t,e){return this.events.on(t,e)}once(t,e){return this.events.once(t,e)}off(t,e){this.events.off(t,e)}_monitorPerformanceThresholdAndTriggerFallback(){const{allow:t}=this._originalOptions.configurePerformanceCanvas2DFallback;let{threshold:e,showPlayerMessage:i}=this._originalOptions.configurePerformanceCanvas2DFallback;if(e===void 0&&(e=_e._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.threshold),i===void 0&&(i=_e._DEFAULT_ENGINE_OPTIONS.configurePerformanceCanvas2DFallback.showPlayerMessage),!De.isEnabled("use-canvas-context")&&t&&this.ready&&!this._performanceThresholdTriggered){this._fpsSamples.length===e.numberOfFrames&&this._fpsSamples.splice(0,1),this._fpsSamples.push(this.clock.fpsSampler.fps);let s=0;for(let o=0;o<this._fpsSamples.length;o++)s+=this._fpsSamples[o];const n=s/this._fpsSamples.length;this._fpsSamples.length===e.numberOfFrames&&n<=e.fps&&(this._performanceThresholdTriggered=!0,this._logger.warn(`Switching to browser 2D Canvas fallback due to performance. Some features of Excalibur will not work in this mode.
|
|
808
919
|
this might mean your browser doesn't have webgl enabled or hardware acceleration is unavailable.
|
|
809
920
|
|
|
810
921
|
If in Chrome:
|
|
@@ -815,6 +926,6 @@ If in Firefox, visit about:config
|
|
|
815
926
|
* Ensure webgl.force-enabled = true
|
|
816
927
|
* Ensure layers.acceleration.force-enabled = true
|
|
817
928
|
|
|
818
|
-
Read more about this issue at https://excaliburjs.com/docs/performance`),i&&this._toaster.toast("Excalibur is encountering performance issues. It's possible that your browser doesn't have hardware acceleration enabled. Visit [LINK] for more information and potential solutions.","https://excaliburjs.com/docs/performance"),this.useCanvas2DFallback(),this.emit("fallbackgraphicscontext",this.graphicsContext))}}useCanvas2DFallback(){var t,e,i;const s=this.canvas.cloneNode(!1);this.canvas.parentNode.replaceChild(s,this.canvas),this.canvas=s;const n={...this._originalOptions,antialiasing:this.screen.antialiasing},o=this._originalDisplayMode;this.graphicsContext=new Xi({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,antialiasing:n.antialiasing,backgroundColor:n.backgroundColor,snapToPixel:n.snapToPixel,useDrawSorting:n.useDrawSorting}),this.screen&&this.screen.dispose(),this.screen=new Ln({canvas:this.canvas,context:this.graphicsContext,antialiasing:(t=n.antialiasing)!=null?t:!0,browser:this.browser,viewport:(e=n.viewport)!=null?e:n.width&&n.height?{width:n.width,height:n.height}:Bn.SVGA,resolution:n.resolution,displayMode:o,pixelRatio:n.suppressHiDPIScaling?1:(i=n.pixelRatio)!=null?i:null}),this.screen.setCurrentCamera(this.currentScene.camera),this.input.pointers.detach();const a=n&&n.pointerScope===Fe.Document?document:this.canvas;this.input.pointers=this.input.pointers.recreate(a,this),this.input.pointers.init()}dispose(){this._disposed||(this._disposed=!0,this.stop(),this._garbageCollector.forceCollectAll(),this.input.toggleEnabled(!1),this._hasCreatedCanvas&&this.canvas.parentNode.removeChild(this.canvas),this.canvas=null,this.screen.dispose(),this.graphicsContext.dispose(),this.graphicsContext=null,ue.InstanceCount--)}isDisposed(){return this._disposed}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){if(t<0){R.getInstance().warnOnce("engine.timescale to a value less than 0 are ignored");return}this._timescale=t}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){return this.director.add(t,e),this}removeScene(t){this.director.remove(t)}add(t){if(arguments.length===2){this.director.add(arguments[0],arguments[1]);return}const e=this.director.getDeferredScene();e instanceof Rt?e.add(t):this.currentScene.add(t)}remove(t){t instanceof Tt&&this.currentScene.remove(t),(t instanceof Rt||$t(t))&&this.removeScene(t),typeof t=="string"&&this.removeScene(t)}async goToScene(t,e){await this.scope(async()=>{await this.director.goToScene(t,e)})}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){var e,i;this.pageScrollPreventionMode=t.scrollPreventionMode;const s=t&&t.pointerScope===Fe.Document?document:this.canvas,n=(i=(e=this._originalOptions)==null?void 0:e.grabWindowFocus)!=null?i:!0;this.input=new Yn({global:this.global,pointerTarget:s,grabWindowFocus:n,engine:this}),this.inputMapper=this.input.inputMapper,this.browser.document.on("visibilitychange",()=>{document.visibilityState==="hidden"?(this.events.emit("hidden",new Hs(this)),this._logger.debug("Window hidden")):document.visibilityState==="visible"&&(this.events.emit("visible",new Os(this)),this._logger.debug("Window visible"))}),!this.canvasElementId&&!t.canvasElement&&document.body.appendChild(this.canvas)}toggleInputEnabled(t){this._inputEnabled=t,this.input.toggleEnabled(this._inputEnabled)}onInitialize(t){}get isInitialized(){return this._isInitialized}async _overrideInitialize(t){this.isInitialized||(await this.director.onInitialize(),await this.onInitialize(t),this.events.emit("initialize",new ze(t,this)),this._isInitialized=!0)}_update(t){var e;if(this._isLoading){(e=this._loader)==null||e.onUpdate(this,t),this.input.update();return}this.clock.__runScheduledCbs("preupdate"),this._preupdate(t),this.currentScene.update(this,t),this.graphicsContext.updatePostProcessors(t),this.clock.__runScheduledCbs("postupdate"),this._postupdate(t),this.input.update()}_preupdate(t){this.emit("preupdate",new ne(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new re(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){var e,i;if(this.graphicsContext.backgroundColor=(e=this.currentScene.backgroundColor)!=null?e:this.backgroundColor,this.graphicsContext.beginDrawLifecycle(),this.graphicsContext.clear(),this.clock.__runScheduledCbs("predraw"),this._predraw(this.graphicsContext,t),this._isLoading){this._hideLoader||((i=this._loader)==null||i.canvas.draw(this.graphicsContext,0,0),this.clock.__runScheduledCbs("postdraw"),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle());return}this.currentScene.draw(this.graphicsContext,t),this.clock.__runScheduledCbs("postdraw"),this._postdraw(this.graphicsContext,t),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle(),this._checkForScreenShots()}_predraw(t,e){this.emit("predraw",new ke(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new Ue(t,e,this)),this.onPostDraw(t,e)}onPostDraw(t,e){}showDebug(t){this._isDebug=t}toggleDebug(){return this._isDebug=!this._isDebug,this._isDebug}get loadingComplete(){return!this._isLoading}get ready(){return this._isReadyFuture.isCompleted}isReady(){return this._isReadyFuture.promise}async start(t,e){await this.scope(async()=>{if(!this._compatible)throw new Error("Excalibur is incompatible with your browser");this._isLoading=!0;let i;return t instanceof pi?i=t:typeof t=="string"&&(this.director.configureStart(t,e),i=this.director.mainLoader),this._logger.debug("Starting game clock..."),this.browser.resume(),this.clock.start(),this.garbageCollectorConfig&&this._garbageCollector.start(),this._logger.debug("Game clock started"),await this.load(i!=null?i:new Ji),await this._overrideInitialize(this),this._isReadyFuture.resolve(),this.emit("start",new As(this)),this._isReadyFuture.promise})}_mainloop(t){this.scope(()=>{this.emit("preframe",new Fs(this,this.stats.prevFrame));const e=t*this.timescale;this.currentFrameElapsedMs=e;const i=this.stats.prevFrame.id+1;this.stats.currFrame.reset(),this.stats.currFrame.id=i,this.stats.currFrame.elapsedMs=e,this.stats.currFrame.fps=this.clock.fpsSampler.fps,st.clear();const s=this.clock.now(),n=this.fixedUpdateTimestep;if(this.fixedUpdateTimestep)for(this._lagMs+=e;this._lagMs>=n;)this._update(n),this._lagMs-=n;else this._update(e);const o=this.clock.now();this.currentFrameLagMs=this._lagMs,this._draw(e);const a=this.clock.now();this.stats.currFrame.duration.update=o-s,this.stats.currFrame.duration.draw=a-o,this.stats.currFrame.graphics.drawnImages=st.DrawnImagesCount,this.stats.currFrame.graphics.drawCalls=st.DrawCallCount,this.emit("postframe",new Bs(this,this.stats.currFrame)),this.stats.prevFrame.reset(this.stats.currFrame),this._monitorPerformanceThresholdAndTriggerFallback()})}stop(){this.clock.isRunning()&&(this.emit("stop",new Es(this)),this.browser.pause(),this.clock.stop(),this._garbageCollector.stop(),this._logger.debug("Game stopped"))}isRunning(){return this.clock.isRunning()}screenshot(t=!1){return new Promise(i=>{this._screenShotRequests.push({preserveHiDPIResolution:t,resolve:i})})}_checkForScreenShots(){for(const t of this._screenShotRequests){const e=t.preserveHiDPIResolution?this.canvas.width:this.screen.resolution.width,i=t.preserveHiDPIResolution?this.canvas.height:this.screen.resolution.height,s=document.createElement("canvas");s.width=e,s.height=i;const n=s.getContext("2d");n.imageSmoothingEnabled=this.screen.antialiasing,n.drawImage(this.canvas,0,0,e,i);const o=new Image,a=s.toDataURL("image/png");o.onload=()=>{t.resolve(o)},o.src=a}this._screenShotRequests.length=0}async load(t,e=!1){await this.scope(async()=>{try{if(t.isLoaded())return;this._loader=t,this._isLoading=!0,this._hideLoader=e,t instanceof Ji&&(t.suppressPlayButton=t.suppressPlayButton||this._suppressPlayButton),this._loader.onInitialize(this),await t.load()}catch(i){this._logger.error("Error loading resources, things may not behave properly",i),await Promise.resolve()}finally{this._isLoading=!1,this._hideLoader=!1,this._loader=null}})}};rs.Context=ma(),rs.InstanceCount=0,rs._DEFAULT_ENGINE_OPTIONS={width:0,height:0,enableCanvasTransparency:!0,useDrawSorting:!0,configurePerformanceCanvas2DFallback:{allow:!1,showPlayerMessage:!1,threshold:{fps:20,numberOfFrames:100}},canvasElementId:"",canvasElement:void 0,enableCanvasContextMenu:!1,snapToPixel:!1,antialiasing:!0,pixelArt:!1,garbageCollection:!0,powerPreference:"high-performance",pointerScope:Fe.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,grabWindowFocus:!0,scrollPreventionMode:1,backgroundColor:P.fromHex("#2185d0")};let os=rs;class Gl extends Ft{constructor(t){super(t),this._font=new Ce,this._text=new ui({text:"",font:this._font});const{text:e,pos:i,x:s,y:n,spriteFont:o,font:a,color:h,maxWidth:l}={text:"",...t};this.pos=i!=null?i:s&&n?x(s,n):this.pos,this.text=e!=null?e:this.text,this.font=a!=null?a:this.font,this.maxWidth=l!=null?l:this.maxWidth,this.spriteFont=o!=null?o:this.spriteFont,this._text.color=h!=null?h:this.color;const c=this.get(j);c.anchor=v.Zero,c.use(this._text)}set maxWidth(t){this._text.maxWidth=t}get maxWidth(){return this._text.maxWidth}get font(){return this._font}set font(t){this._font=t,this._text.font=t}get text(){return this._text.text}set text(t){this._text.text=t}get color(){return this._text.color}set color(t){this._text&&(this._text.color=t)}get opacity(){return this.graphics.opacity}set opacity(t){this.graphics.opacity=t}get spriteFont(){return this._spriteFont}set spriteFont(t){t&&(this._spriteFont=t,this._text.font=this._spriteFont)}_initialize(t){super._initialize(t)}getTextWidth(){return this._text.width}}var Ae=(r=>(r.Circle="circle",r.Rectangle="rectangle",r))(Ae||{});class Vl extends Ft{constructor(t){var e,i;super({width:(e=t.width)!=null?e:0,height:(i=t.height)!=null?i:0}),this._particlesToEmit=0,this._particlePool=new Ve(()=>new Yi({}),p=>p,500),this.numParticles=0,this.isEmitting=!0,this.deadParticles=[],this.emitRate=1,this.emitterType=Ae.Rectangle,this.radius=0,this.particle={life:2e3,transform:Vt.Global,graphic:void 0,opacity:1,angularVelocity:0,focus:void 0,focusAccel:void 0,randomRotation:!1},this._activeParticles=[];const{particle:s,x:n,y:o,z:a,pos:h,isEmitting:l,emitRate:c,emitterType:u,radius:_,random:f}={...t};this.particle={...this.particle,...s},this.pos=h!=null?h:x(n!=null?n:0,o!=null?o:0),this.z=a!=null?a:0,this.isEmitting=l!=null?l:this.isEmitting,this.emitRate=c!=null?c:this.emitRate,this.emitterType=u!=null?u:this.emitterType,this.radius=_!=null?_:this.radius,this.body.collisionType=M.PreventCollision,this.random=f!=null?f:new ie}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;if(!(t<=0)){t=t|0;for(let i=0;i<t;i++){const s=this._createParticle();(e=this==null?void 0:this.scene)!=null&&e.world&&(this.particle.transform===Vt.Global?this.scene.world.add(s):this.addChild(s)),this._activeParticles.push(s)}}}clearParticles(){for(let t=0;t<this._activeParticles.length;t++)this.removeParticle(this._activeParticles[t])}_createParticle(){let t=0,e=0;const i=Ot(this.particle.minAngle||0,this.particle.maxAngle||Math.PI*2,this.random),s=Ot(this.particle.minSpeed||0,this.particle.maxSpeed||0,this.random),n=this.particle.startSize||Ot(this.particle.minSize||5,this.particle.maxSize||5,this.random),o=s*Math.cos(i),a=s*Math.sin(i);if(this.emitterType===Ae.Rectangle)t=Ot(0,this.width,this.random),e=Ot(0,this.height,this.random);else if(this.emitterType===Ae.Circle){const l=Ot(0,this.radius,this.random);t=l*Math.cos(i),e=l*Math.sin(i)}const h=this._particlePool.rent();return h.unparent(),h.configure({transform:this.particle.transform,life:this.particle.life,opacity:this.particle.opacity,beginColor:this.particle.beginColor,endColor:this.particle.endColor,pos:x(t,e),z:this.particle.transform===Vt.Global?this.z:void 0,vel:x(o,a),acc:this.particle.acc,angularVelocity:this.particle.angularVelocity,startSize:this.particle.startSize,endSize:this.particle.endSize,size:n,graphic:this.particle.graphic,fade:this.particle.fade}),h.registerEmitter(this),this.particle.randomRotation&&(h.transform.rotation=Ot(0,Math.PI*2,this.random)),this.particle.focus&&(h.focus=this.particle.focus.add(x(this.pos.x,this.pos.y)),h.focusAccel=this.particle.focusAccel),h}update(t,e){var i;super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit)));for(let s=0;s<this.deadParticles.length;s++){(i=this==null?void 0:this.scene)!=null&&i.world&&(this.scene.world.remove(this.deadParticles[s],!1),this._particlePool.return(this.deadParticles[s]));const n=this._activeParticles.indexOf(this.deadParticles[s]);n>-1&&this._activeParticles.splice(n,1)}this.deadParticles.length=0}}function Jn(r,t){if(!t())throw new Error(r)}class as{constructor(t,e,i){this.emitRate=1,this._initialized=!1,this._vaos=[],this._buffers=[],this._drawIndex=0,this._numInputFloats=7,this._particleIndex=0,this._uploadIndex=0,this._wrappedLife=0,this._wrappedParticles=0,this._particleLife=0,this._clearRequested=!1,this._emitted=[];var s;this.emitter=t,this.particle=i,this._particleData=new Float32Array(this.emitter.maxParticles*this._numInputFloats),this._random=e,this._particleLife=(s=this.particle.life)!=null?s:2e3}get isInitialized(){return this._initialized}get maxParticles(){return this.emitter.maxParticles}initialize(t,e){if(this._initialized)return;const i=this.emitter.maxParticles,s=this._numInputFloats,n=this._particleData,o=4,a=t.createBuffer(),h=t.createVertexArray();t.bindVertexArray(h),t.bindBuffer(t.ARRAY_BUFFER,a),t.bufferData(t.ARRAY_BUFFER,i*s*o,t.DYNAMIC_DRAW),t.bufferSubData(t.ARRAY_BUFFER,0,n);let l=0;t.vertexAttribPointer(0,2,t.FLOAT,!1,s*o,0),l+=o*2,t.vertexAttribPointer(1,2,t.FLOAT,!1,s*o,l),l+=o*2,t.vertexAttribPointer(2,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(3,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(4,1,t.FLOAT,!1,s*o,l),l+=o*1,t.enableVertexAttribArray(0),t.enableVertexAttribArray(1),t.enableVertexAttribArray(2),t.enableVertexAttribArray(3),t.enableVertexAttribArray(4),this._vaos.push(h),this._buffers.push(a),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null);const c=t.createBuffer(),u=t.createVertexArray();t.bindVertexArray(u),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,i*s*o,t.DYNAMIC_DRAW),l=0,t.vertexAttribPointer(0,2,t.FLOAT,!1,s*o,0),l+=o*2,t.vertexAttribPointer(1,2,t.FLOAT,!1,s*o,l),l+=o*2,t.vertexAttribPointer(2,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(3,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(4,1,t.FLOAT,!1,s*o,l),l+=o*1,t.enableVertexAttribArray(0),t.enableVertexAttribArray(1),t.enableVertexAttribArray(2),t.enableVertexAttribArray(3),t.enableVertexAttribArray(4),this._vaos.push(u),this._buffers.push(c),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),this._currentVao=this._vaos[this._drawIndex%2],this._currentBuffer=this._buffers[(this._drawIndex+1)%2],this._initialized=!0}clearParticles(){this._particleData.fill(0),this._clearRequested=!0}emitParticles(t){const e=this._particleIndex,i=this.maxParticles*this._numInputFloats,s=t*this._numInputFloats+e;for(let n=e;n<s;n+=this._numInputFloats){let o=this._random.floating(this.particle.minAngle||0,this.particle.maxAngle||et);o+=this.particle.transform===Vt.Local?this.emitter.transform.rotation:this.emitter.transform.globalRotation;const a=this._random.floating(this.particle.minSpeed||0,this.particle.maxSpeed||0),h=this._random.floating(this.particle.minSpeed||0,this.particle.maxSpeed||0),l=a*Math.cos(o),c=h*Math.sin(o);let u=0,_=0;if(this.emitter.emitterType===Ae.Rectangle)u=this._random.floating(-.5,.5)*this.emitter.width,_=this._random.floating(-.5,.5)*this.emitter.height;else{const g=this._random.floating(0,this.emitter.radius);u=g*Math.cos(o),_=g*Math.sin(o)}const f=this.emitter.transform.apply(x(u,_)),p=[this.particle.transform===Vt.Local?u:f.x,this.particle.transform===Vt.Local?_:f.y,l,c,this.particle.randomRotation?Ot(0,et,this._random):this.particle.rotation||0,this.particle.angularVelocity||0,this._particleLife];this._particleData.set(p,n%this._particleData.length)}s>=i?(this._wrappedParticles+=(s-i)/this._numInputFloats,this._wrappedLife=this._particleLife):this._wrappedLife>0&&(this._wrappedParticles+=t),this._particleIndex=s%i,this._emitted.push([this._particleLife,e])}_uploadEmitted(t){this._particleIndex!==this._uploadIndex&&(t.bindBuffer(t.ARRAY_BUFFER,this._buffers[(this._drawIndex+1)%2]),this._particleIndex>=this._uploadIndex?t.bufferSubData(t.ARRAY_BUFFER,this._uploadIndex*4,this._particleData,this._uploadIndex,this._particleIndex-this._uploadIndex):(t.bufferSubData(t.ARRAY_BUFFER,this._uploadIndex*4,this._particleData,this._uploadIndex,this._particleData.length-this._uploadIndex),this._wrappedParticles&&t.bufferSubData(t.ARRAY_BUFFER,0,this._particleData,0,this._wrappedParticles*this._numInputFloats),this._wrappedLife=this._particleLife),t.bindBuffer(t.ARRAY_BUFFER,null)),this._uploadIndex=this._particleIndex%(this.maxParticles*this._numInputFloats)}update(t){var e;if(this._particleLife=(e=this.particle.life)!=null?e:this._particleLife,this._wrappedLife>0?this._wrappedLife-=t:(this._wrappedLife=0,this._wrappedParticles=0),!!this._emitted.length){for(let i=this._emitted.length-1;i>=0;i--){const s=this._emitted[i];s[0]-=t,s[0]<=0&&this._emitted.splice(i,1)}this._emitted.sort((i,s)=>i[0]-s[0])}}draw(t){if(this._initialized){if(this._clearRequested?(t.bindBuffer(t.ARRAY_BUFFER,this._buffers[(this._drawIndex+1)%2]),t.bufferSubData(t.ARRAY_BUFFER,0,this._particleData),t.bindBuffer(t.ARRAY_BUFFER,null),this._clearRequested=!1):this._uploadEmitted(t),t.bindVertexArray(this._currentVao),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer),this._wrappedLife&&this._emitted[0]&&this._emitted[0][1]>0){const e=this._emitted[0][1]/this._numInputFloats;Jn(`midpoint greater than 0, actual: ${e}`,()=>e>0),Jn(`midpoint is less than max, actual: ${e}`,()=>e<this.maxParticles),t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,this._emitted[0][1]*4,(this.maxParticles-e)*this._numInputFloats*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,e,this.maxParticles-e),t.endTransformFeedback(),t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,0,this._emitted[0][1]*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,e),t.endTransformFeedback()}else t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,0,this._particleData.length*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,this.maxParticles),t.endTransformFeedback();t.bindVertexArray(null),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,null),this._currentVao=this._vaos[this._drawIndex%2],this._currentBuffer=this._buffers[(this._drawIndex+1)%2],this._drawIndex=(this._drawIndex+1)%2}}}as.GPU_MAX_PARTICLES=1e5;class ql extends Ft{constructor(t){super({name:"GpuParticleEmitter",width:t.width,height:t.height}),this.particle={life:2e3,transform:Vt.Global,graphic:void 0,opacity:1,angularVelocity:0,focus:void 0,focusAccel:void 0,randomRotation:!1},this.graphics=new j,this.isEmitting=!1,this.emitRate=1,this.emitterType=Ae.Rectangle,this.radius=0,this.maxParticles=2e3,this._particlesToEmit=0,this.addComponent(this.graphics,!0),this.graphics.onPostDraw=this.draw.bind(this);const{particle:e,maxParticles:i,x:s,y:n,z:o,pos:a,isEmitting:h,emitRate:l,emitterType:c,radius:u,random:_}={...t};this.maxParticles=F(i!=null?i:this.maxParticles,0,as.GPU_MAX_PARTICLES),this.pos=a!=null?a:x(s!=null?s:0,n!=null?n:0),this.z=o!=null?o:0,this.isEmitting=h!=null?h:this.isEmitting,this.emitRate=l!=null?l:this.emitRate,this.emitterType=c!=null?c:this.emitterType,this.radius=u!=null?u:this.radius,this.particle={...this.particle,...e},this.random=_!=null?_:new ie,this.renderer=new as(this,this.random,this.particle)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get z(){return this.transform.z}set z(t){this.transform.z=t}_initialize(t){super._initialize(t);const e=t.graphicsContext;this.renderer.initialize(e.__gl,e)}update(t,e){super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit))),this.renderer.update(e)}emitParticles(t){t<=0||this.renderer.emitParticles(t|0)}clearParticles(){this.renderer.clearParticles()}draw(t,e){t.draw("ex.particle",this.renderer,e)}}class Kn{constructor(t,e){this.id=N(),this._stopped=!1,this._sequenceBuilder=e,this._sequenceContext=new _i(t),this._actionQueue=this._sequenceContext.getQueue(),this._sequenceBuilder(this._sequenceContext)}update(t){this._actionQueue.update(t)}isComplete(){return this._stopped||this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._stopped=!1,this._actionQueue.reset()}clone(t){return new Kn(t,this._sequenceBuilder)}}class Xl{constructor(t){this.id=N(),this._actions=t}update(t){for(let e=0;e<this._actions.length;e++)this._actions[e].update(t)}isComplete(t){return this._actions.every(e=>e.isComplete(t))}reset(){this._actions.forEach(t=>t.reset())}stop(){this._actions.forEach(t=>t.stop())}}function Yl(r){return!!r._initialize}function $l(r){return!!r.onAdd}function jl(r){return!!r.onRemove}function Zl(r){return!!r.onInitialize}function Ql(r){return!!r._preupdate}function Jl(r){return!!r.onPreUpdate}function Kl(r){return!!r.onPostUpdate}function tc(r){return!!r.onPostUpdate}function ec(r){return!!r.onAdd}function ic(r){return!!r.onRemove}function sc(r){return!!r.onPreDraw}function nc(r){return!!r.onPostDraw}class xa{constructor(t,e){this.soundManager=e}stop(t){if(!t)return;const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)e[i].stop()}setVolume(t,e){const i=this.soundManager.getSoundsForChannel(t);for(const s of i)this.soundManager._isMuted(s)||this.soundManager.setVolume(t,e)}play(t,e){e!=null||(e=this.soundManager.defaultVolume);const i=[],s=new Set,n=this.soundManager.getSoundsForChannel(t);for(const o of n){if(s.has(o)||this.soundManager._isMuted(o))continue;const a=this.soundManager._getEffectiveVolume(o);i.push(o.play(a*e)),s.add(o)}return Promise.all(i)}mute(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._muted.add(e[i]),e[i].pause()}unmute(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._muted.has(e[i])&&(e[i].play(),this.soundManager._muted.delete(e[i]))}toggle(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._isMuted(e[i])?(e[i].play(),this.soundManager._muted.delete(e[i])):(this.soundManager._muted.add(e[i]),e[i].pause())}}class rc{constructor(t){this._channelToConfig=new Map,this._nameToConfig=new Map,this._mix=new Map,this._muted=new Set,this._all=new Set,this._defaultVolume=1;var e;if(this._defaultVolume=(e=t.volume)!=null?e:1,this.channel=new xa(t,this),t.sounds)for(const[i,s]of Object.entries(t.sounds))this.track(i,s)}set defaultVolume(t){this._defaultVolume=F(t,0,1)}get defaultVolume(){return this._defaultVolume}getSounds(){return Array.from(this._all)}getSoundsForChannel(t){const e=this._channelToConfig.get(t);return e?e.sounds:[]}_isMuted(t){return this._muted.has(t)}_getEffectiveVolume(t){var e;if(this._isMuted(t))return 0;let i=this._defaultVolume;return this._mix.has(t)&&(i*=(e=this._mix.get(t))!=null?e:this._defaultVolume),i}play(t,e=this._defaultVolume){const i=this._nameToConfig.get(t);if(!i)return Promise.resolve();const{sound:s}=i;if(this._isMuted(s))return Promise.resolve();const n=e*this._getEffectiveVolume(s);return s.play(n)}getSound(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;return i}setVolume(t,e=this._defaultVolume){const i=this._nameToConfig.get(t);if(!i)return;const{sound:s}=i;this._setMix(s,e)}getVolume(t){var e;const i=this.getSound(t);return i&&(e=this._mix.get(i))!=null?e:0}_setMix(t,e){this._mix.set(t,e),t.volume=e}track(t,e){let i,s,n;e instanceof zn?(i=e,s=this._defaultVolume,n=[]):{sound:i,volume:s,channels:n}=e,this._nameToConfig.set(t,{sound:i,volume:s,channels:n}),this._mix.set(i,s!=null?s:this._defaultVolume),this._all.add(i),n&&this.addChannel(t,n)}untrack(t){this._nameToConfig.delete(t);const e=this.getSound(t);e&&(this._mix.delete(e),this._all.delete(e))}stop(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;i.stop();return}this._all.forEach(e=>e.stop())}mute(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;this._muted.add(i),i.pause();return}this._muted=new Set(this._all),this._muted.forEach(e=>e.pause())}unmute(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;i.play(),this._muted.delete(i);return}this._muted.forEach(e=>e.play()),this._muted.clear()}toggle(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;this._isMuted(i)?this.unmute(t):this.mute(t);return}this._muted.size>0?(this._muted.forEach(e=>e.play()),this._muted.clear()):(this._muted=new Set(this._all),this._muted.forEach(e=>e.pause()))}addChannel(t,e){const i=this.getSound(t);if(!i)return;const s=this._mix.get(i);this._mix.set(i,s!=null?s:this._defaultVolume),this._all.add(i);for(const n of e){let o=this._channelToConfig.get(n);o||(o={sounds:[i]}),o.sounds.indexOf(i)===-1&&o.sounds.push(i),this._channelToConfig.set(n,o)}}removeChannel(t,e){const i=this.getSound(t);if(i)for(const s of e){const n=this._channelToConfig.get(s);if(!n)return;const o=n.sounds.indexOf(i);o>=-1&&n.sounds.splice(o,1),this._channelToConfig.set(s,n)}}}class oc{constructor(t,e=!1){this.path=t,this.width=0,this.height=0,this._images=[],this.data=[],this._sprites=[],this._resource=new ai(t,"arraybuffer",e)}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){const t=await this._resource.load();this._stream=new ba(t),this._gif=new ya(this._stream);const e=this._gif.images.map(i=>new Gt(i.src,!1));return await Promise.all(e.map(i=>i.load())),this.data=this._images=e,this._sprites=this._images.map(i=>i.toSprite()),this.data}isLoaded(){return!!this.data}toSprite(t=0){var e;return(e=this._sprites[t])!=null?e:null}toSpriteSheet(){const t=this._sprites;return t.length?new be({sprites:t}):null}toAnimation(t){var e;const i=(e=this._gif)==null?void 0:e.images;if(i!=null&&i.length){const s=i.map((n,o)=>{var a;return{graphic:this._sprites[o],duration:((a=this._gif)==null?void 0:a.frames[o].delayMs)||void 0}});return this._animation=new zi({frames:s,frameDuration:t}),this._animation}return null}get readCheckBytes(){var t,e;return(e=(t=this._gif)==null?void 0:t.checkBytes)!=null?e:[]}}const hs=r=>r.reduce(function(t,e){return t*2+e},0),tr=r=>{const t=[];for(let e=7;e>=0;e--)t.push(!!(r&1<<e));return t};class ba{constructor(t){if(this.len=0,this.position=0,this.readByte=()=>{if(this.position>=this.data.byteLength)throw new Error("Attempted to read past end of stream.");return this.data[this.position++]},this.readBytes=e=>{const i=[];for(let s=0;s<e;s++)i.push(this.readByte());return i},this.read=e=>{let i="";for(let s=0;s<e;s++)i+=String.fromCharCode(this.readByte());return i},this.readUnsigned=()=>{const e=this.readBytes(2);return(e[1]<<8)+e[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,this.len===0)throw new Error("No data loaded from file")}}const ac=function(r,t){let e=0;const i=function(_){let f=0;for(let p=0;p<_;p++)t.charCodeAt(e>>3)&1<<(e&7)&&(f|=1<<p),e++;return f},s=[],n=1<<r,o=n+1;let a=r+1,h=[];const l=function(){h=[],a=r+1;for(let _=0;_<n;_++)h[_]=[_];h[n]=[],h[o]=null};let c=0,u=0;for(;;){if(u=c,c=i(a),c===n){l();continue}if(c===o)break;if(c<h.length)u!==n&&h.push(h[u].concat(h[c][0]));else{if(c!==h.length)throw new Error("Invalid LZW code.");h.push(h[u].concat(h[u][0]))}s.push.apply(s,h[c]),h.length===1<<a&&a<12&&a++}return s};class ya{constructor(t){this._handler={},this.frames=[],this.images=[],this.globalColorTableBytes=[],this.checkBytes=[],this.parseColorTableBytes=e=>{const i=[];for(let s=0;s<e;s++){const n=this._st.readBytes(3);i.push(n)}return i},this.readSubBlocks=()=>{let e,i;i="";do e=this._st.readByte(),i+=this._st.read(e);while(e!==0);return i},this.parseHeader=()=>{const e={sig:"",ver:"",width:0,height:0,colorResolution:0,globalColorTableSize:0,gctFlag:!1,sortedFlag:!1,globalColorTable:[],backgroundColorIndex:0,pixelAspectRatio:0};if(e.sig=this._st.read(3),e.ver=this._st.read(3),e.sig!=="GIF")throw new Error("Not a GIF file.");e.width=this._st.readUnsigned(),e.height=this._st.readUnsigned(),this._currentFrameCanvas.width=e.width,this._currentFrameCanvas.height=e.height;const i=tr(this._st.readByte());e.gctFlag=i.shift(),e.colorResolution=hs(i.splice(0,3)),e.sortedFlag=i.shift(),e.globalColorTableSize=hs(i.splice(0,3)),e.backgroundColorIndex=this._st.readByte(),e.pixelAspectRatio=this._st.readByte(),e.gctFlag&&(this.globalColorTableBytes=this.parseColorTableBytes(1<<e.globalColorTableSize+1)),this._handler.hdr&&this._handler.hdr(e)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=e=>{const i=h=>{this.checkBytes.push(this._st.readByte());const l=tr(this._st.readByte());return h.reserved=l.splice(0,3),h.disposalMethod=hs(l.splice(0,3)),h.userInputFlag=l.shift(),h.transparentColorFlag=l.shift(),h.delayTime=this._st.readUnsigned(),h.transparentColorIndex=this._st.readByte(),h.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(h)&&this.checkBytes.push(this._handler.gce),h},s=h=>{h.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(h)&&this.checkBytes.push(this._handler.com)},n=h=>{this.checkBytes.push(this._st.readByte()),h.ptHeader=this._st.readBytes(12),h.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(h)&&this.checkBytes.push(this._handler.pte)},o=h=>{const l=u=>{this.checkBytes.push(this._st.readByte()),u.unknown=this._st.readByte(),u.iterations=this._st.readUnsigned(),u.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(u)&&this.checkBytes.push(this._handler.app)},c=u=>{u.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[u.identifier]&&this._handler.app[u.identifier](u)&&this.checkBytes.push(this._handler.app[u.identifier])};switch(this.checkBytes.push(this._st.readByte()),h.identifier=this._st.read(8),h.authCode=this._st.read(3),h.identifier){case"NETSCAPE":l(h);break;default:c(h);break}},a=h=>{h.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(h)&&this.checkBytes.push(this._handler.unknown)};switch(e.label=this._st.readByte(),e.label){case 249:e.extType="gce",this._gce=i(e);break;case 254:e.extType="com",s(e);break;case 1:e.extType="pte",n(e);break;case 255:e.extType="app",o(e);break;default:e.extType="unknown",a(e);break}},this.parseImg=e=>{var i;const s=(a,h)=>{const l=new Array(a.length),c=a.length/h,u=(g,w)=>{const m=a.slice(w*h,(w+1)*h);l.splice.apply(l,[g*h,h].concat(m))},_=[0,4,2,1],f=[8,8,4,2];let p=0;for(let g=0;g<4;g++)for(let w=_[g];w<c;w+=f[g])u(w,p),p++;return l};e.leftPos=this._st.readUnsigned(),e.topPos=this._st.readUnsigned(),e.width=this._st.readUnsigned(),e.height=this._st.readUnsigned();const n=tr(this._st.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=hs(n.splice(0,3)),e.lctFlag&&(e.lctBytes=this.parseColorTableBytes(1<<e.lctSize+1)),e.lzwMinCodeSize=this._st.readByte();const o=this.readSubBlocks();e.pixels=ac(e.lzwMinCodeSize,o),e.interlaced&&(e.pixels=s(e.pixels,e.width)),(i=this._gce)!=null&&i.delayTime&&(e.delayMs=this._gce.delayTime*10),this.frames.push(e),this.arrayToImage(e,e.lctFlag?e.lctBytes:this.globalColorTableBytes),this._handler.img&&this._handler.img(e)&&this.checkBytes.push(this._handler)},this.parseBlocks=()=>{const e={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(e.sentinel)){case"!":e.type="ext",this.parseExt(e);break;case",":e.type="img",this.parseImg(e);break;case";":e.type="eof",this._handler.eof&&this._handler.eof(e)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+e.sentinel.toString(16))}e.type!=="eof"&&this.parseBlocks()},this.arrayToImage=(e,i)=>{var s,n,o,a;const h=document.createElement("canvas");h.width=e.width,h.height=e.height;const l=h.getContext("2d"),c=l.getImageData(0,0,h.width,h.height);let u=-1;(s=this._gce)!=null&&s.transparentColorFlag&&(u=this._gce.transparentColorIndex);for(let f=0;f<e.pixels.length;f++){const p=e.pixels[f],g=i[p];p===u?c.data.set([0,0,0,0],f*4):c.data.set([...g,255],f*4)}if(l.putImageData(c,0,0),((n=this._gce)==null?void 0:n.disposalMethod)===1&&this.images.length)this._currentFrameContext.drawImage(this.images[this.images.length-1],0,0);else if(((o=this._gce)==null?void 0:o.disposalMethod)===2&&((a=this._hdr)!=null&&a.gctFlag)){const f=i[this._hdr.backgroundColorIndex];this._currentFrameContext.fillStyle=`rgb(${f[0]}, ${f[1]}, ${f[2]})`,this._currentFrameContext.fillRect(0,0,this._hdr.width,this._hdr.height)}else this._currentFrameContext.clearRect(0,0,this._currentFrameCanvas.width,this._currentFrameCanvas.height);this._currentFrameContext.drawImage(h,e.leftPos,e.topPos,e.width,e.height);const _=new Image;_.src=this._currentFrameCanvas.toDataURL(),this.images.push(_)},this._st=t,this._handler={},this._currentFrameCanvas=document.createElement("canvas"),this._currentFrameContext=this._currentFrameCanvas.getContext("2d"),this.parseHeader(),this.parseBlocks()}}class hc{constructor(t,e,{bustCache:i,...s}={}){this.path=t,this.family=e,this._isLoaded=!1,this._resource=new ai(t,"blob",i),this._options=s}async load(){if(this.isLoaded())return this.data;try{const t=await this._resource.load(),e=URL.createObjectURL(t);this.data||(this.data=new FontFace(this.family,`url(${e})`),document.fonts.add(this.data)),await this.data.load(),this._isLoaded=!0}catch(t){throw`Error loading FontSource from path '${this.path}' with error [${t.message}]`}return this.data}isLoaded(){return this._isLoaded}toFont(t){return new Ce({family:this.family,...this._options,...t})}}const Ca=ma(),lc=/^\s*(?:function)?\*/;function Sa(r){return typeof r!="function"?!1:lc.test(Function.prototype.toString.call(r))?!0:Object.getPrototypeOf?Object.getPrototypeOf(r)===Object.getPrototypeOf(new Function("return function * () {}")()):!1}function Ta(...r){var t;const e=R.getInstance();let i,s,n,o;Sa(r[0])&&(s=globalThis,i=r[0],n=r[1]),Sa(r[1])&&(s=r[0],i=r[1],n=r[2]),r[1]instanceof os&&(s=r[0],o=r[1],i=r[2],n=r[3]),r[0]instanceof os&&(s=globalThis,o=r[0],i=r[1],n=r[2]);const a=va(Ca),h=n==null?void 0:n.timing,l=a?!1:(t=n==null?void 0:n.autostart)!=null?t:!0;let c;try{c=o!=null?o:os.useEngine()}catch(T){throw Error(`Cannot run coroutine without engine parameter outside of an excalibur lifecycle method.
|
|
819
|
-
Pass an engine parameter to ex.coroutine(engine, function * {...})`)}let u=!1,_=!1,f=!1;const
|
|
820
|
-
`,Function.prototype.toString.call(p)):(u=!0,w(c.clock.elapsed())),b),generator:g,done:m,then:m.then.bind(m),[Symbol.iterator]:()=>g};return b}class ls extends Tt{constructor(t){var e,i,s,n,o;super(),this._logger=R.getInstance(),this.transform=new A,this.graphics=new j,this._completeFuture=new wt,this.started=!1,this._currentDistance=0,this._currentProgress=0,this.done=this._completeFuture.promise,this._useLegacyEasing=!1,this.name=`Transition#${this.id}`,this.duration=t.duration,Se(t.easing)?(this.legacyEasing=(e=t.easing)!=null?e:It.Linear,this._useLegacyEasing=!0):this.easing=(i=t.easing)!=null?i:Ti,this.direction=(s=t.direction)!=null?s:"out",this.hideLoader=(n=t.hideLoader)!=null?n:!1,this.blockInput=(o=t.blockInput)!=null?o:!1,this.transform.coordPlane=rt.Screen,this.transform.pos=v.Zero,this.transform.z=1/0,this.graphics.anchor=v.Zero,this.addComponent(this.transform),this.addComponent(this.graphics),this.direction==="out"?this._currentProgress=0:this._currentProgress=1}get progress(){return this._currentProgress}get distance(){return this._currentDistance}get complete(){return this.direction==="out"?this.progress>=1:this.progress<=0}updateTransition(t,e){this.complete||(this._currentDistance+=F(e/this.duration,0,1),this._currentDistance>=1&&(this._currentDistance=1),this.direction==="out"?this._useLegacyEasing?this._currentProgress=F(this.legacyEasing(this._currentDistance,0,1,1),0,1):this._currentProgress=F(ot(0,1,this.easing(this._currentDistance)),0,1):this._useLegacyEasing?this._currentProgress=F(this.legacyEasing(this._currentDistance,1,0,1),0,1):this._currentProgress=F(ot(1,0,this.easing(this._currentDistance)),0,1))}async onPreviousSceneDeactivate(t){}onStart(t){}onUpdate(t){}onEnd(t){}onReset(){}reset(){this.started=!1,this._completeFuture=new wt,this.done=this._completeFuture.promise,this._currentDistance=0,this.direction==="out"?this._currentProgress=0:this._currentProgress=1,this.onReset()}_addToTargetScene(t,e){const i=e;if(this.started&&this._logger.warn(`Attempted to add a transition ${this.name} that is already playing.`),i.world.entityManager.getById(this.id))return this._co;this._engine=t,i.add(this);const s=this;return this._co=Ta(t,function*(){for(;!s.complete;){const n=yield;s.updateTransition(s._engine,n),s._execute()}},{autostart:!1}),this._co}async _play(){this.started&&(this.reset(),this._logger.warn(`Attempted to play a transition ${this.name} that is already playing, reset transition.`)),(!this._engine||!this._co)&&(this.reset(),this._logger.warn(`Attempted to play a transition ${this.name} that hasn't been added`)),this._co&&await this._co.start()}_execute(){this.isInitialized&&(this.started||(this.started=!0,this.onStart(this.progress)),this.onUpdate(this.progress),this.complete&&!this._completeFuture.isCompleted&&(this.onEnd(this.progress),this._completeFuture.resolve()))}}class cc extends ls{constructor(t){var e,i;super({...t,duration:(e=t.duration)!=null?e:2e3}),this.name=`FadeInOut#${this.id}`,this.color=(i=t.color)!=null?i:P.Black}onInitialize(t){this.transform.pos=t.screen.unsafeArea.topLeft,this.screenCover=new ci({width:t.screen.resolution.width,height:t.screen.resolution.height,color:this.color}),this.graphics.add(this.screenCover),this.graphics.opacity=this.progress}onReset(){this.graphics.opacity=this.progress}onStart(t){this.graphics.opacity=t}onEnd(t){this.graphics.opacity=t}onUpdate(t){this.graphics.opacity=t}}class dc extends ls{constructor(t){super({direction:"in",...t}),this.name=`CrossFade#${this.id}`}async onPreviousSceneDeactivate(t){this.image=await t.engine.screenshot(!0),await this.image.decode()}onInitialize(t){this.engine=t,this.transform.pos=t.screen.unsafeArea.topLeft,this.screenCover=Gt.fromHtmlImageElement(this.image).toSprite(),this.graphics.add(this.screenCover),this.transform.scale=x(1/t.screen.pixelRatio,1/t.screen.pixelRatio),this.graphics.opacity=this.progress}onStart(t){this.graphics.opacity=this.progress}onReset(){this.graphics.opacity=this.progress}onEnd(t){this.graphics.opacity=t}onUpdate(t){this.graphics.opacity=t}}class uc extends ls{constructor(t){var e;super({direction:"in",...t}),this._easing=It.Linear,this._start=v.Zero,this._end=v.Zero,this.name=`Slide#${this.id}`,this.slideDirection=t.slideDirection,this.transform.coordPlane=rt.Screen,this.graphics.forceOnScreen=!0,this._easing=(e=t.easingFunction)!=null?e:this._easing}async onPreviousSceneDeactivate(t){this._image=await t.engine.screenshot(!0),await this._image.decode(),this._screenCover=Gt.fromHtmlImageElement(this._image).toSprite()}onInitialize(t){this._engine=t;let e=t.screen.unsafeArea;switch(e.hasZeroDimensions()&&(e=t.screen.contentArea),this.slideDirection){case"up":{this._directionOffset=x(0,-e.height);break}case"down":{this._directionOffset=x(0,e.height);break}case"left":{this._directionOffset=x(-e.width,0);break}case"right":{this._directionOffset=x(e.width,0);break}}this._camera=this._engine.currentScene.camera,this._destinationCameraPosition=this._camera.pos.clone(),this._camera.pos=this._camera.pos.add(this._directionOffset),this.transform.pos=this.transform.pos.add(this._directionOffset),this._startCameraPosition=this._camera.pos.clone(),this._start=e.topLeft,this._end=this._start.add(this._directionOffset),this.transform.pos=this._start,this.graphics.use(this._screenCover),this.transform.scale=x(1/t.screen.pixelRatio,1/t.screen.pixelRatio)}onStart(t){const e=this._easing(this.distance,0,1,1);this.transform.pos.x=ot(this._start.x,this._end.x,e),this.transform.pos.y=ot(this._start.y,this._end.y,e),this._camera.pos.x=ot(this._startCameraPosition.x,this._destinationCameraPosition.x,e),this._camera.pos.y=ot(this._startCameraPosition.y,this._destinationCameraPosition.y,e)}onUpdate(t){const e=this._easing(this.distance,0,1,1);this.transform.pos.x=ot(this._start.x,this._end.x,e),this.transform.pos.y=ot(this._start.y,this._end.y,e),this._camera.pos.x=ot(this._startCameraPosition.x,this._destinationCameraPosition.x,e),this._camera.pos.y=ot(this._startCameraPosition.y,this._destinationCameraPosition.y,e)}}const _c=Object.freeze(Object.defineProperty({__proto__:null,ConsoleAppender:ys,DrawUtil:Uh,EasingFunctions:It,LogLevel:Le,Logger:R,Observable:gt,ScreenAppender:mr,addItemToArray:Ch,contains:xr,delay:Di,fail:br,getMinIndex:wr,getPosition:ni,isLegacyEasing:Se,isObject:Fi,mergeDeep:Bi,omit:yr,removeItemFromArray:Oe},Symbol.toStringTag,{value:"Module"})),Pa=5,Je={},fc=()=>{for(const r in Je)Je[r]=0},cs=(r,t)=>{const e=De.isEnabled("suppress-obsolete-message");Je[r]<Pa&&!e&&(R.getInstance().warn(r),console.trace&&t.showStackTrace&&console.trace()),Je[r]++};function gc(r){return r={message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1,...r},function(t,e,i){if(i&&!(typeof i.value=="function"||typeof i.get=="function"||typeof i.set=="function"))throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${t.name||""}${t.name&&e?".":""}${e||""}`} is marked obsolete: ${r.message}`+(r.alternateMethod?` Use ${r.alternateMethod} instead`:"");Je[n]||(Je[n]=0);const o=i?{...i}:t;if(!i){class a extends o{constructor(...l){cs(n,r),super(...l)}}return a}return i&&i.value?(o.value=function(){return cs(n,r),i.value.apply(this,arguments)},o):(i&&i.get&&(o.get=function(){return cs(n,r),i.get.apply(this,arguments)}),i&&i.set&&(o.set=function(){return cs(n,r),i.set.apply(this,arguments)}),o)}}class pc{constructor(){this._queue=[]}get length(){return this._queue.length}enqueue(){const t=new wt;return this._queue.push(t),t.promise}dequeue(t){this._queue.shift().resolve(t)}}class mc{constructor(t){this._count=t,this._waitQueue=new pc}get count(){return this._count}get waiting(){return this._waitQueue.length}async enter(){return this._count!==0?(this._count--,Promise.resolve()):this._waitQueue.enqueue()}exit(t=1){if(t!==0){for(;t!==0&&this._waitQueue.length!==0;)this._waitQueue.dequeue(null),t--;this._count+=t}}}const er="0.32.0-alpha.1570+3b683c5";Me(),d.ActionCompleteEvent=$s,d.ActionContext=_i,d.ActionQueue=eo,d.ActionSequence=Kn,d.ActionStartEvent=Ys,d.ActionsComponent=je,d.ActionsSystem=Vn,d.ActivateEvent=Ns,d.Actor=Ft,d.ActorEvents=Cl,d.AddEvent=js,d.AddedComponent=Sh,d.AffineMatrix=Q,d.Animation=zi,d.AnimationDirection=Br,d.AnimationEvents=Fh,d.AnimationStrategy=Lr,d.ArcadeSolver=Dn,d.AudioContextFactory=gi,d.Axes=ea,d.Axis=Yo,d.BaseAlign=an,d.BezierCurve=ei,d.Blink=yo,d.BodyComponent=W,d.BoundingBox=D,d.BrowserComponent=$n,d.BrowserEvents=da,d.Buttons=qn,d.Camera=Ko,d.CameraEvents=Ll,d.Canvas=qi,d.ChannelCollection=xa,d.Circle=Vi,d.CircleCollider=dt,d.Clock=jn,d.ClosestLineJumpTable=Wt,d.Collider=ri,d.ColliderComponent=tt,d.CollisionContact=we,d.CollisionEndEvent=si,d.CollisionGroup=pe,d.CollisionGroupManager=Pi,d.CollisionJumpTable=Lt,d.CollisionPostSolveEvent=Mi,d.CollisionPreSolveEvent=Ri,d.CollisionStartEvent=ii,d.CollisionSystem=Zi,d.CollisionType=M,d.Color=P,d.ColorBlindFlags=la,d.ColorBlindnessMode=Ye,d.ColorBlindnessPostProcessor=Qr,d.Component=Dt,d.CompositeCollider=at,d.ConsoleAppender=ys,d.ContactConstraintPoint=Mo,d.ContactEndEvent=Ii,d.ContactSolveBias=oe,d.ContactStartEvent=Ei,d.CoordPlane=rt,d.CrossFade=dc,d.CurveBy=Eo,d.CurveTo=Ao,d.DeactivateEvent=Ws,d.Debug=Cn,d.DebugConfig=ca,d.DebugGraphicsComponent=Ni,d.DebugSystem=Gn,d.DebugText=un,d.DefaultAntialiasOptions=Or,d.DefaultGarbageCollectionOptions=Qn,d.DefaultLoader=pi,d.DefaultPixelArtOptions=Hr,d.DegreeOfFreedom=he,d.Delay=So,d.Detector=Oo,d.Die=To,d.Direction=ln,d.Director=pa,d.DirectorEvents=ga,d.DisplayMode=fi,d.DynamicTree=Ks,d.DynamicTreeCollisionProcessor=Li,d.EX_VERSION=er,d.EaseBy=bo,d.EaseTo=xo,d.EasingFunctions=It,d.Edge=vs,d.EdgeCollider=Ct,d.ElasticToActorStrategy=Zo,d.EmitterType=Ae,d.Engine=os,d.EngineEvents=Wl,d.EnterTriggerEvent=qs,d.EnterViewPortEvent=Vs,d.Entity=Tt,d.EntityEvents=Eh,d.EntityManager=Sr,d.EventEmitter=X,d.EventTypes=Ss,d.Events=yh,d.ExResponse=kn,d.ExcaliburGraphicsContext2DCanvas=Xi,d.ExcaliburGraphicsContextWebGL=Xt,d.ExitTriggerEvent=Xs,d.ExitViewPortEvent=Gs,d.Fade=Co,d.FadeInOut=cc,d.Flags=De,d.Flash=Po,d.Follow=An,d.Font=Ce,d.FontCache=Gi,d.FontSource=hc,d.FontStyle=hn,d.FontUnit=rn,d.FpsSampler=ua,d.FrameStats=bi,d.Future=wt,d.GameEvent=L,d.GameStartEvent=As,d.GameStopEvent=Es,d.Gamepad=is,d.GamepadAxisEvent=zs,d.GamepadButtonEvent=Us,d.GamepadConnectEvent=Ls,d.GamepadDisconnectEvent=ks,d.Gamepads=es,d.GarbageCollector=wa,d.Gif=oc,d.GifParser=ya,d.GlobalCoordinates=Be,d.GpuParticleEmitter=ql,d.GpuParticleRenderer=as,d.Graph=ms,d.Graphic=it,d.GraphicsComponent=j,d.GraphicsGroup=Ne,d.GraphicsSystem=fn,d.HashColliderProxy=Ro,d.HashGridCell=Yt,d.HashGridProxy=In,d.HiddenEvent=Hs,d.HorizontalFirst=en,d.ImageFiltering=mt,d.ImageSource=Gt,d.ImageSourceAttributeConstants=O,d.ImageWrapping=_t,d.InitializeEvent=ze,d.InputHost=Yn,d.InputMapper=ia,d.IsometricEntityComponent=mi,d.IsometricEntitySystem=Wn,d.IsometricMap=Bl,d.IsometricTile=qo,d.KeyEvent=vi,d.Keyboard=aa,d.Keys=oa,d.KillEvent=Ai,d.Label=Gl,d.LimitCameraBoundsStrategy=Jo,d.Line=_n,d.LineSegment=J,d.Loader=Ji,d.LoaderEvents=Il,d.LockCameraToActorAxisStrategy=jo,d.LockCameraToActorStrategy=$o,d.LogLevel=Le,d.Logger=R,d.Material=Kr,d.Matrix=yt,d.MatrixLocations=cr,d.MediaEvent=Un,d.Meet=$i,d.MotionComponent=H,d.MotionSystem=ji,d.MoveBy=Tn,d.MoveByWithOptions=ro,d.MoveTo=Pn,d.MoveToWithOptions=ao,d.NativePointerButton=Pe,d.NativeSoundEvent=Te,d.NativeSoundProcessedEvent=ko,d.NineSlice=mn,d.NineSliceStretch=zr,d.Node=Si,d.None=sn,d.Observable=gt,d.OffscreenSystem=gn,d.Pair=pt,d.ParallaxComponent=Wi,d.ParallelActions=Xl,d.Particle=Yi,d.ParticleEmitter=Vl,d.ParticleRenderer=jr,d.ParticleTransform=Vt,d.PhysicsStats=ns,d.PhysicsWorld=Do,d.PointerAbstraction=Xn,d.PointerButton=le,d.PointerComponent=ae,d.PointerEvent=wi,d.PointerEventReceiver=ss,d.PointerScope=Fe,d.PointerSystem=ts,d.PointerType=ce,d.Polygon=pn,d.PolygonCollider=lt,d.Pool=Ui,d.PositionNode=_r,d.PostCollisionEvent=ve,d.PostDebugDrawEvent=Ds,d.PostDrawEvent=Ue,d.PostFrameEvent=Bs,d.PostKillEvent=Ps,d.PostTransformDrawEvent=Rs,d.PostUpdateEvent=re,d.PreCollisionEvent=me,d.PreDebugDrawEvent=Ms,d.PreDrawEvent=ke,d.PreFrameEvent=Fs,d.PreKillEvent=Ts,d.PreLoadEvent=Ol,d.PreTransformDrawEvent=Is,d.PreUpdateEvent=ne,d.Projection=Ke,d.QuadIndexBuffer=di,d.QuadTree=Ze,d.Query=Bt,d.QueryManager=Tr,d.RadiusAroundActorStrategy=Qo,d.Random=ie,d.Raster=We,d.Ray=fe,d.RealisticSolver=Fn,d.Rectangle=ci,d.RemoveEvent=Zs,d.RemovedComponent=Ph,d.RentalPool=Ve,d.Repeat=io,d.RepeatForever=so,d.Resolution=Bn,d.Resource=ai,d.ResourceEvents=Hh,d.RotateBy=uo,d.RotateByWithOptions=co,d.RotateTo=lo,d.RotateToWithOptions=ho,d.RotationType=Z,d.ScaleBy=vo,d.ScaleByWithOptions=mo,d.ScaleTo=go,d.ScaleToWithOptions=fo,d.Scene=Rt,d.SceneEvents=Hl,d.Screen=Ln,d.ScreenAppender=mr,d.ScreenElement=Hn,d.ScreenEvents=Sl,d.ScreenShader=Zr,d.ScrollPreventionMode=Qe,d.Semaphore=mc,d.SeparatingAxis=He,d.SeparationInfo=Mr,d.Shader=zt,d.Shape=ut,d.Slide=uc,d.SolverStrategy=ki,d.Sound=zn,d.SoundEvents=Al,d.SoundManager=rc,d.SparseHashGrid=Rn,d.SparseHashGridCollisionProcessor=Mn,d.SpatialPartitionStrategy=oi,d.Sprite=kt,d.SpriteFont=Oi,d.SpriteSheet=be,d.StandardClock=Zn,d.StateMachine=Qi,d.StrategyContainer=Xo,d.Stream=ba,d.System=At,d.SystemManager=Ar,d.SystemPriority=Nt,d.SystemType=Pt,d.TagQuery=Qs,d.TestClock=_a,d.Text=ui,d.TextAlign=on,d.TextureLoader=qe,d.Tile=Vo,d.TileMap=Go,d.TileMapEvents=Fl,d.TiledAnimation=vn,d.TiledSprite=li,d.Timer=Ki,d.Toaster=fa,d.Transform=Qt,d.TransformComponent=A,d.Transition=ls,d.TreeNode=Js,d.Trigger=ta,d.TriggerEvents=kl,d.TwoPI=et,d.UniformBuffer=Nr,d.Util=_c,d.Vector=v,d.VectorView=gs,d.VertexBuffer=qt,d.VertexLayout=Kt,d.VerticalFirst=tn,d.VisibleEvent=Os,d.WebAudio=Bo,d.WebAudioInstance=Lo,d.WheelDeltaMode=xi,d.WheelEvent=ha,d.World=Er,d.approximatelyEqual=ar,d.assert=Jn,d.canonicalizeAngle=Zt,d.clamp=F,d.coroutine=Ta,d.createId=_e,d.easeInBack=fh,d.easeInBounce=gr,d.easeInCirc=dh,d.easeInCubic=th,d.easeInElastic=mh,d.easeInExpo=hh,d.easeInOutBack=ph,d.easeInOutBounce=xh,d.easeInOutCirc=_h,d.easeInOutCubic=xs,d.easeInOutElastic=wh,d.easeInOutExpo=ch,d.easeInOutQuad=Ka,d.easeInOutQuart=nh,d.easeInOutQuint=ah,d.easeInOutSine=Za,d.easeInQuad=Qa,d.easeInQuart=ih,d.easeInQuint=rh,d.easeInSine=$a,d.easeOutBack=gh,d.easeOutBounce=bs,d.easeOutCirc=uh,d.easeOutCubic=eh,d.easeOutElastic=vh,d.easeOutExpo=lh,d.easeOutQuad=Ja,d.easeOutQuart=sh,d.easeOutQuint=oh,d.easeOutSine=ja,d.frac=Na,d.getDefaultPhysicsConfig=Jt,d.glTypeToUniformTypeName=Xr,d.hasGraphicsTick=Sn,d.hasOnAdd=ec,d.hasOnInitialize=Zl,d.hasOnPostUpdate=tc,d.hasOnPreUpdate=Jl,d.hasOnRemove=ic,d.hasPostDraw=nc,d.hasPreDraw=sc,d.has_add=$l,d.has_initialize=Yl,d.has_postupdate=Kl,d.has_preupdate=Ql,d.has_remove=jl,d.inverseLerp=dr,d.inverseLerpVector=ur,d.isActor=yl,d.isAddedComponent=Th,d.isComponentCtor=vr,d.isLegacyEasing=Se,d.isLoaderConstructor=On,d.isMoveByOptions=no,d.isMoveToOptions=oo,d.isRemovedComponent=Ah,d.isRotateByOptions=bl,d.isRotateToOptions=xl,d.isScaleByOptions=po,d.isScaleToOptions=_o,d.isSceneConstructor=$t,d.isScreenElement=Ho,d.isSystemConstructor=Pr,d.lerp=ot,d.lerpAngle=ps,d.lerpVector=ti,d.linear=Ti,d.maxMessages=Pa,d.nextActionId=N,d.obsolete=gc,d.parseImageFiltering=Ge,d.parseImageWrapping=Ut,d.pixelSnapEpsilon=B,d.randomInRange=Ot,d.randomIntInRange=Va,d.range=Ga,d.remap=Ht,d.remapVector=qa,d.resetObsoleteCounter=fc,d.sign=V,d.smootherstep=Ya,d.smoothstep=Xa,d.toDegrees=hr,d.toRadians=Wa,d.vec=x,d.webgl=Yh,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
|
|
929
|
+
Read more about this issue at https://excaliburjs.com/docs/performance`),i&&this._toaster.toast("Excalibur is encountering performance issues. It's possible that your browser doesn't have hardware acceleration enabled. Visit [LINK] for more information and potential solutions.","https://excaliburjs.com/docs/performance"),this.useCanvas2DFallback(),this.emit("fallbackgraphicscontext",this.graphicsContext))}}useCanvas2DFallback(){var t,e,i;const s=this.canvas.cloneNode(!1);this.canvas.parentNode.replaceChild(s,this.canvas),this.canvas=s;const n={...this._originalOptions,antialiasing:this.screen.antialiasing},o=this._originalDisplayMode;this.graphicsContext=new $i({canvasElement:this.canvas,enableTransparency:this.enableCanvasTransparency,antialiasing:n.antialiasing,backgroundColor:n.backgroundColor,snapToPixel:n.snapToPixel,useDrawSorting:n.useDrawSorting}),this.screen&&this.screen.dispose(),this.screen=new kn({canvas:this.canvas,context:this.graphicsContext,antialiasing:(t=n.antialiasing)!=null?t:!0,browser:this.browser,viewport:(e=n.viewport)!=null?e:n.width&&n.height?{width:n.width,height:n.height}:Bn.SVGA,resolution:n.resolution,displayMode:o,pixelRatio:n.suppressHiDPIScaling?1:(i=n.pixelRatio)!=null?i:null}),this.screen.setCurrentCamera(this.currentScene.camera),this.input.pointers.detach();const a=n&&n.pointerScope===Be.Document?document:this.canvas;this.input.pointers=this.input.pointers.recreate(a,this),this.input.pointers.init()}dispose(){this._disposed||(this._disposed=!0,this.stop(),this._garbageCollector.forceCollectAll(),this.input.toggleEnabled(!1),this._hasCreatedCanvas&&this.canvas.parentNode.removeChild(this.canvas),this.canvas=null,this.screen.dispose(),this.graphicsContext.dispose(),this.graphicsContext=null,_e.InstanceCount--)}isDisposed(){return this._disposed}getWorldBounds(){return this.screen.getWorldBounds()}get timescale(){return this._timescale}set timescale(t){if(t<0){R.getInstance().warnOnce("engine.timescale to a value less than 0 are ignored");return}this._timescale=t}addTimer(t){return this.currentScene.addTimer(t)}removeTimer(t){return this.currentScene.removeTimer(t)}addScene(t,e){return this.director.add(t,e),this}removeScene(t){this.director.remove(t)}add(t){if(arguments.length===2){this.director.add(arguments[0],arguments[1]);return}const e=this.director.getDeferredScene();e instanceof Mt?e.add(t):this.currentScene.add(t)}remove(t){t instanceof At&&this.currentScene.remove(t),(t instanceof Mt||jt(t))&&this.removeScene(t),typeof t=="string"&&this.removeScene(t)}async goToScene(t,e){await this.scope(async()=>{await this.director.goToScene(t,e)})}screenToWorldCoordinates(t){return this.screen.screenToWorldCoordinates(t)}worldToScreenCoordinates(t){return this.screen.worldToScreenCoordinates(t)}_initialize(t){var e,i;this.pageScrollPreventionMode=t.scrollPreventionMode;const s=t&&t.pointerScope===Be.Document?document:this.canvas,n=(i=(e=this._originalOptions)==null?void 0:e.grabWindowFocus)!=null?i:!0;this.input=new Yn({global:this.global,pointerTarget:s,grabWindowFocus:n,engine:this}),this.inputMapper=this.input.inputMapper,this.browser.document.on("visibilitychange",()=>{document.visibilityState==="hidden"?(this.events.emit("hidden",new Ws(this)),this._logger.debug("Window hidden")):document.visibilityState==="visible"&&(this.events.emit("visible",new Ns(this)),this._logger.debug("Window visible"))}),!this.canvasElementId&&!t.canvasElement&&document.body.appendChild(this.canvas)}toggleInputEnabled(t){this._inputEnabled=t,this.input.toggleEnabled(this._inputEnabled)}onInitialize(t){}get isInitialized(){return this._isInitialized}async _overrideInitialize(t){this.isInitialized||(await this.director.onInitialize(),await this.onInitialize(t),this.events.emit("initialize",new Oe(t,this)),this._isInitialized=!0)}_update(t){var e;if(this._isLoading){(e=this._loader)==null||e.onUpdate(this,t),this.input.update();return}this.clock.__runScheduledCbs("preupdate"),this._preupdate(t),this.currentScene.update(this,t),this.graphicsContext.updatePostProcessors(t),this.clock.__runScheduledCbs("postupdate"),this._postupdate(t),this.input.update()}_preupdate(t){this.emit("preupdate",new re(this,t,this)),this.onPreUpdate(this,t)}onPreUpdate(t,e){}_postupdate(t){this.emit("postupdate",new oe(this,t,this)),this.onPostUpdate(this,t)}onPostUpdate(t,e){}_draw(t){var e,i;if(this.graphicsContext.backgroundColor=(e=this.currentScene.backgroundColor)!=null?e:this.backgroundColor,this.graphicsContext.beginDrawLifecycle(),this.graphicsContext.clear(),this.clock.__runScheduledCbs("predraw"),this._predraw(this.graphicsContext,t),this._isLoading){this._hideLoader||((i=this._loader)==null||i.canvas.draw(this.graphicsContext,0,0),this.clock.__runScheduledCbs("postdraw"),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle());return}this.currentScene.draw(this.graphicsContext,t),this.clock.__runScheduledCbs("postdraw"),this._postdraw(this.graphicsContext,t),this.graphicsContext.flush(),this.graphicsContext.endDrawLifecycle(),this._checkForScreenShots()}_predraw(t,e){this.emit("predraw",new Ue(t,e,this)),this.onPreDraw(t,e)}onPreDraw(t,e){}_postdraw(t,e){this.emit("postdraw",new ze(t,e,this)),this.onPostDraw(t,e)}onPostDraw(t,e){}showDebug(t){this._isDebug=t}toggleDebug(){return this._isDebug=!this._isDebug,this._isDebug}get loadingComplete(){return!this._isLoading}get ready(){return this._isReadyFuture.isCompleted}isReady(){return this._isReadyFuture.promise}async start(t,e){await this.scope(async()=>{if(!this._compatible)throw new Error("Excalibur is incompatible with your browser");this._isLoading=!0;let i;return t instanceof mi?i=t:typeof t=="string"&&(this.director.configureStart(t,e),i=this.director.mainLoader),this._logger.debug("Starting game clock..."),this.browser.resume(),this.clock.start(),this.garbageCollectorConfig&&this._garbageCollector.start(),this._logger.debug("Game clock started"),await this.load(i!=null?i:new ts),await this._overrideInitialize(this),this._isReadyFuture.resolve(),this.emit("start",new Is(this)),this._isReadyFuture.promise})}_mainloop(t){this.scope(()=>{this.emit("preframe",new ks(this,this.stats.prevFrame));const e=t*this.timescale;this.currentFrameElapsedMs=e;const i=this.stats.prevFrame.id+1;this.stats.currFrame.reset(),this.stats.currFrame.id=i,this.stats.currFrame.elapsedMs=e,this.stats.currFrame.fps=this.clock.fpsSampler.fps,J.clear();const s=this.clock.now(),n=this.fixedUpdateTimestep;if(this.fixedUpdateTimestep)for(this._lagMs+=e;this._lagMs>=n;)this._update(n),this._lagMs-=n;else this._update(e);const o=this.clock.now();this.currentFrameLagMs=this._lagMs,this._draw(e);const a=this.clock.now();this.stats.currFrame.duration.update=o-s,this.stats.currFrame.duration.draw=a-o,this.stats.currFrame.graphics.drawnImages=J.DrawnImagesCount,this.stats.currFrame.graphics.drawCalls=J.DrawCallCount,this.emit("postframe",new Ls(this,this.stats.currFrame)),this.stats.prevFrame.reset(this.stats.currFrame),this._monitorPerformanceThresholdAndTriggerFallback()})}stop(){this.clock.isRunning()&&(this.emit("stop",new Rs(this)),this.browser.pause(),this.clock.stop(),this._garbageCollector.stop(),this._logger.debug("Game stopped"))}isRunning(){return this.clock.isRunning()}screenshot(t=!1){return new Promise(i=>{this._screenShotRequests.push({preserveHiDPIResolution:t,resolve:i})})}_checkForScreenShots(){for(const t of this._screenShotRequests){const e=t.preserveHiDPIResolution?this.canvas.width:this.screen.resolution.width,i=t.preserveHiDPIResolution?this.canvas.height:this.screen.resolution.height,s=document.createElement("canvas");s.width=e,s.height=i;const n=s.getContext("2d");n.imageSmoothingEnabled=this.screen.antialiasing,n.drawImage(this.canvas,0,0,e,i);const o=new Image,a=s.toDataURL("image/png");o.onload=()=>{t.resolve(o)},o.src=a}this._screenShotRequests.length=0}async load(t,e=!1){await this.scope(async()=>{try{if(t.isLoaded())return;this._loader=t,this._isLoading=!0,this._hideLoader=e,t instanceof ts&&(t.suppressPlayButton=t.suppressPlayButton||this._suppressPlayButton),this._loader.onInitialize(this),await t.load()}catch(i){this._logger.error("Error loading resources, things may not behave properly",i),await Promise.resolve()}finally{this._isLoading=!1,this._hideLoader=!1,this._loader=null}})}};as.Context=ma(),as.InstanceCount=0,as._DEFAULT_ENGINE_OPTIONS={width:0,height:0,enableCanvasTransparency:!0,useDrawSorting:!0,configurePerformanceCanvas2DFallback:{allow:!1,showPlayerMessage:!1,threshold:{fps:20,numberOfFrames:100}},canvasElementId:"",canvasElement:void 0,enableCanvasContextMenu:!1,snapToPixel:!1,antialiasing:!0,pixelArt:!1,garbageCollection:!0,powerPreference:"high-performance",pointerScope:Be.Canvas,suppressConsoleBootMessage:null,suppressMinimumBrowserFeatureDetection:null,suppressHiDPIScaling:null,suppressPlayButton:null,grabWindowFocus:!0,scrollPreventionMode:1,backgroundColor:T.fromHex("#2185d0")};let hs=as;class Xl extends kt{constructor(t){super(t),this._font=new Se,this._text=new _i({text:"",font:this._font});const{text:e,pos:i,x:s,y:n,spriteFont:o,font:a,color:h,maxWidth:l}={text:"",...t};this.pos=i!=null?i:s&&n?b(s,n):this.pos,this.text=e!=null?e:this.text,this.font=a!=null?a:this.font,this.maxWidth=l!=null?l:this.maxWidth,this.spriteFont=o!=null?o:this.spriteFont,this._text.color=h!=null?h:this.color;const c=this.get(K);c.anchor=w.Zero,c.use(this._text)}set maxWidth(t){this._text.maxWidth=t}get maxWidth(){return this._text.maxWidth}get font(){return this._font}set font(t){this._font=t,this._text.font=t}get text(){return this._text.text}set text(t){this._text.text=t}get color(){return this._text.color}set color(t){this._text&&(this._text.color=t)}get opacity(){return this.graphics.opacity}set opacity(t){this.graphics.opacity=t}get spriteFont(){return this._spriteFont}set spriteFont(t){t&&(this._spriteFont=t,this._text.font=this._spriteFont)}_initialize(t){super._initialize(t)}getTextWidth(){return this._text.width}}var Ee=(r=>(r.Circle="circle",r.Rectangle="rectangle",r))(Ee||{});class Yl extends kt{constructor(t){var e,i;super({width:(e=t.width)!=null?e:0,height:(i=t.height)!=null?i:0}),this._particlesToEmit=0,this._particlePool=new qe(()=>new Zi({}),m=>m,500),this.numParticles=0,this.isEmitting=!0,this.deadParticles=[],this.emitRate=1,this.emitterType=Ee.Rectangle,this.radius=0,this.particle={life:2e3,transform:Xt.Global,graphic:void 0,opacity:1,angularVelocity:0,focus:void 0,focusAccel:void 0,randomRotation:!1},this._activeParticles=[];const{particle:s,x:n,y:o,z:a,pos:h,isEmitting:l,emitRate:c,emitterType:u,radius:_,random:f}={...t};this.particle={...this.particle,...s},this.pos=h!=null?h:b(n!=null?n:0,o!=null?o:0),this.z=a!=null?a:0,this.isEmitting=l!=null?l:this.isEmitting,this.emitRate=c!=null?c:this.emitRate,this.emitterType=u!=null?u:this.emitterType,this.radius=_!=null?_:this.radius,this.body.collisionType=M.PreventCollision,this.random=f!=null?f:new se}removeParticle(t){this.deadParticles.push(t)}emitParticles(t){var e;if(!(t<=0)){t=t|0;for(let i=0;i<t;i++){const s=this._createParticle();(e=this==null?void 0:this.scene)!=null&&e.world&&(this.particle.transform===Xt.Global?this.scene.world.add(s):this.addChild(s)),this._activeParticles.push(s)}}}clearParticles(){for(let t=0;t<this._activeParticles.length;t++)this.removeParticle(this._activeParticles[t])}_createParticle(){let t=0,e=0;const i=Nt(this.particle.minAngle||0,this.particle.maxAngle||Math.PI*2,this.random),s=Nt(this.particle.minSpeed||0,this.particle.maxSpeed||0,this.random),n=this.particle.startSize||Nt(this.particle.minSize||5,this.particle.maxSize||5,this.random),o=s*Math.cos(i),a=s*Math.sin(i);if(this.emitterType===Ee.Rectangle)t=Nt(0,this.width,this.random),e=Nt(0,this.height,this.random);else if(this.emitterType===Ee.Circle){const l=Nt(0,this.radius,this.random);t=l*Math.cos(i),e=l*Math.sin(i)}const h=this._particlePool.rent();return h.unparent(),h.configure({transform:this.particle.transform,life:this.particle.life,opacity:this.particle.opacity,beginColor:this.particle.beginColor,endColor:this.particle.endColor,pos:b(t,e),z:this.particle.transform===Xt.Global?this.z:void 0,vel:b(o,a),acc:this.particle.acc,angularVelocity:this.particle.angularVelocity,startSize:this.particle.startSize,endSize:this.particle.endSize,size:n,graphic:this.particle.graphic,fade:this.particle.fade}),h.registerEmitter(this),this.particle.randomRotation&&(h.transform.rotation=Nt(0,Math.PI*2,this.random)),this.particle.focus&&(h.focus=this.particle.focus.add(b(this.pos.x,this.pos.y)),h.focusAccel=this.particle.focusAccel),h}update(t,e){var i;super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit)));for(let s=0;s<this.deadParticles.length;s++){(i=this==null?void 0:this.scene)!=null&&i.world&&(this.scene.world.remove(this.deadParticles[s],!1),this._particlePool.return(this.deadParticles[s]));const n=this._activeParticles.indexOf(this.deadParticles[s]);n>-1&&this._activeParticles.splice(n,1)}this.deadParticles.length=0}}function Jn(r,t){if(!t())throw new Error(r)}class ls{constructor(t,e,i){this.emitRate=1,this._initialized=!1,this._vaos=[],this._buffers=[],this._drawIndex=0,this._numInputFloats=7,this._particleIndex=0,this._uploadIndex=0,this._wrappedLife=0,this._wrappedParticles=0,this._particleLife=0,this._clearRequested=!1,this._emitted=[];var s;this.emitter=t,this.particle=i,this._particleData=new Float32Array(this.emitter.maxParticles*this._numInputFloats),this._random=e,this._particleLife=(s=this.particle.life)!=null?s:2e3}get isInitialized(){return this._initialized}get maxParticles(){return this.emitter.maxParticles}initialize(t,e){if(this._initialized)return;const i=this.emitter.maxParticles,s=this._numInputFloats,n=this._particleData,o=4,a=t.createBuffer(),h=t.createVertexArray();t.bindVertexArray(h),t.bindBuffer(t.ARRAY_BUFFER,a),t.bufferData(t.ARRAY_BUFFER,i*s*o,t.DYNAMIC_DRAW),t.bufferSubData(t.ARRAY_BUFFER,0,n);let l=0;t.vertexAttribPointer(0,2,t.FLOAT,!1,s*o,0),l+=o*2,t.vertexAttribPointer(1,2,t.FLOAT,!1,s*o,l),l+=o*2,t.vertexAttribPointer(2,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(3,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(4,1,t.FLOAT,!1,s*o,l),l+=o*1,t.enableVertexAttribArray(0),t.enableVertexAttribArray(1),t.enableVertexAttribArray(2),t.enableVertexAttribArray(3),t.enableVertexAttribArray(4),this._vaos.push(h),this._buffers.push(a),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null);const c=t.createBuffer(),u=t.createVertexArray();t.bindVertexArray(u),t.bindBuffer(t.ARRAY_BUFFER,c),t.bufferData(t.ARRAY_BUFFER,i*s*o,t.DYNAMIC_DRAW),l=0,t.vertexAttribPointer(0,2,t.FLOAT,!1,s*o,0),l+=o*2,t.vertexAttribPointer(1,2,t.FLOAT,!1,s*o,l),l+=o*2,t.vertexAttribPointer(2,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(3,1,t.FLOAT,!1,s*o,l),l+=o*1,t.vertexAttribPointer(4,1,t.FLOAT,!1,s*o,l),l+=o*1,t.enableVertexAttribArray(0),t.enableVertexAttribArray(1),t.enableVertexAttribArray(2),t.enableVertexAttribArray(3),t.enableVertexAttribArray(4),this._vaos.push(u),this._buffers.push(c),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),this._currentVao=this._vaos[this._drawIndex%2],this._currentBuffer=this._buffers[(this._drawIndex+1)%2],this._initialized=!0}clearParticles(){this._particleData.fill(0),this._clearRequested=!0}emitParticles(t){const e=this._particleIndex,i=this.maxParticles*this._numInputFloats,s=t*this._numInputFloats+e;for(let n=e;n<s;n+=this._numInputFloats){let o=this._random.floating(this.particle.minAngle||0,this.particle.maxAngle||it);o+=this.particle.transform===Xt.Local?this.emitter.transform.rotation:this.emitter.transform.globalRotation;const a=this._random.floating(this.particle.minSpeed||0,this.particle.maxSpeed||0),h=this._random.floating(this.particle.minSpeed||0,this.particle.maxSpeed||0),l=a*Math.cos(o),c=h*Math.sin(o);let u=0,_=0;if(this.emitter.emitterType===Ee.Rectangle)u=this._random.floating(-.5,.5)*this.emitter.width,_=this._random.floating(-.5,.5)*this.emitter.height;else{const p=this._random.floating(0,this.emitter.radius);u=p*Math.cos(o),_=p*Math.sin(o)}const f=this.emitter.transform.apply(b(u,_)),m=[this.particle.transform===Xt.Local?u:f.x,this.particle.transform===Xt.Local?_:f.y,l,c,this.particle.randomRotation?Nt(0,it,this._random):this.particle.rotation||0,this.particle.angularVelocity||0,this._particleLife];this._particleData.set(m,n%this._particleData.length)}s>=i?(this._wrappedParticles+=(s-i)/this._numInputFloats,this._wrappedLife=this._particleLife):this._wrappedLife>0&&(this._wrappedParticles+=t),this._particleIndex=s%i,this._emitted.push([this._particleLife,e])}_uploadEmitted(t){this._particleIndex!==this._uploadIndex&&(t.bindBuffer(t.ARRAY_BUFFER,this._buffers[(this._drawIndex+1)%2]),this._particleIndex>=this._uploadIndex?t.bufferSubData(t.ARRAY_BUFFER,this._uploadIndex*4,this._particleData,this._uploadIndex,this._particleIndex-this._uploadIndex):(t.bufferSubData(t.ARRAY_BUFFER,this._uploadIndex*4,this._particleData,this._uploadIndex,this._particleData.length-this._uploadIndex),this._wrappedParticles&&t.bufferSubData(t.ARRAY_BUFFER,0,this._particleData,0,this._wrappedParticles*this._numInputFloats),this._wrappedLife=this._particleLife),t.bindBuffer(t.ARRAY_BUFFER,null)),this._uploadIndex=this._particleIndex%(this.maxParticles*this._numInputFloats)}update(t){var e;if(this._particleLife=(e=this.particle.life)!=null?e:this._particleLife,this._wrappedLife>0?this._wrappedLife-=t:(this._wrappedLife=0,this._wrappedParticles=0),!!this._emitted.length){for(let i=this._emitted.length-1;i>=0;i--){const s=this._emitted[i];s[0]-=t,s[0]<=0&&this._emitted.splice(i,1)}this._emitted.sort((i,s)=>i[0]-s[0])}}draw(t){if(this._initialized){if(this._clearRequested?(t.bindBuffer(t.ARRAY_BUFFER,this._buffers[(this._drawIndex+1)%2]),t.bufferSubData(t.ARRAY_BUFFER,0,this._particleData),t.bindBuffer(t.ARRAY_BUFFER,null),this._clearRequested=!1):this._uploadEmitted(t),t.bindVertexArray(this._currentVao),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer),this._wrappedLife&&this._emitted[0]&&this._emitted[0][1]>0){const e=this._emitted[0][1]/this._numInputFloats;Jn(`midpoint greater than 0, actual: ${e}`,()=>e>0),Jn(`midpoint is less than max, actual: ${e}`,()=>e<this.maxParticles),t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,this._emitted[0][1]*4,(this.maxParticles-e)*this._numInputFloats*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,e,this.maxParticles-e),t.endTransformFeedback(),t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,0,this._emitted[0][1]*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,e),t.endTransformFeedback()}else t.bindBufferRange(t.TRANSFORM_FEEDBACK_BUFFER,0,this._currentBuffer,0,this._particleData.length*4),t.beginTransformFeedback(t.POINTS),t.drawArrays(t.POINTS,0,this.maxParticles),t.endTransformFeedback();t.bindVertexArray(null),t.bindBufferBase(t.TRANSFORM_FEEDBACK_BUFFER,0,null),this._currentVao=this._vaos[this._drawIndex%2],this._currentBuffer=this._buffers[(this._drawIndex+1)%2],this._drawIndex=(this._drawIndex+1)%2}}}ls.GPU_MAX_PARTICLES=1e5;class $l extends kt{constructor(t){super({name:"GpuParticleEmitter",width:t.width,height:t.height}),this.particle={life:2e3,transform:Xt.Global,graphic:void 0,opacity:1,angularVelocity:0,focus:void 0,focusAccel:void 0,randomRotation:!1},this.graphics=new K,this.isEmitting=!1,this.emitRate=1,this.emitterType=Ee.Rectangle,this.radius=0,this.maxParticles=2e3,this._particlesToEmit=0,this.addComponent(this.graphics,!0),this.graphics.onPostDraw=this.draw.bind(this);const{particle:e,maxParticles:i,x:s,y:n,z:o,pos:a,isEmitting:h,emitRate:l,emitterType:c,radius:u,random:_}={...t};this.maxParticles=B(i!=null?i:this.maxParticles,0,ls.GPU_MAX_PARTICLES),this.pos=a!=null?a:b(s!=null?s:0,n!=null?n:0),this.z=o!=null?o:0,this.isEmitting=h!=null?h:this.isEmitting,this.emitRate=l!=null?l:this.emitRate,this.emitterType=c!=null?c:this.emitterType,this.radius=u!=null?u:this.radius,this.particle={...this.particle,...e},this.random=_!=null?_:new se,this.renderer=new ls(this,this.random,this.particle)}get pos(){return this.transform.pos}set pos(t){this.transform.pos=t}get z(){return this.transform.z}set z(t){this.transform.z=t}_initialize(t){super._initialize(t);const e=t.graphicsContext;this.renderer.initialize(e.__gl,e)}update(t,e){super.update(t,e),this.isEmitting&&(this._particlesToEmit+=this.emitRate*(e/1e3),this._particlesToEmit>1&&(this.emitParticles(Math.floor(this._particlesToEmit)),this._particlesToEmit=this._particlesToEmit-Math.floor(this._particlesToEmit))),this.renderer.update(e)}emitParticles(t){t<=0||this.renderer.emitParticles(t|0)}clearParticles(){this.renderer.clearParticles()}draw(t,e){t.draw("ex.particle",this.renderer,e)}}class Kn{constructor(t,e){this.id=H(),this._stopped=!1,this._sequenceBuilder=e,this._sequenceContext=new fi(t),this._actionQueue=this._sequenceContext.getQueue(),this._sequenceBuilder(this._sequenceContext)}update(t){this._actionQueue.update(t)}isComplete(){return this._stopped||this._actionQueue.isComplete()}stop(){this._stopped=!0}reset(){this._stopped=!1,this._actionQueue.reset()}clone(t){return new Kn(t,this._sequenceBuilder)}}class Zl{constructor(t){this.id=H(),this._actions=t}update(t){for(let e=0;e<this._actions.length;e++)this._actions[e].update(t)}isComplete(t){return this._actions.every(e=>e.isComplete(t))}reset(){this._actions.forEach(t=>t.reset())}stop(){this._actions.forEach(t=>t.stop())}}function jl(r){return!!r._initialize}function Ql(r){return!!r.onAdd}function Jl(r){return!!r.onRemove}function Kl(r){return!!r.onInitialize}function tc(r){return!!r._preupdate}function ec(r){return!!r.onPreUpdate}function ic(r){return!!r.onPostUpdate}function sc(r){return!!r.onPostUpdate}function nc(r){return!!r.onAdd}function rc(r){return!!r.onRemove}function oc(r){return!!r.onPreDraw}function ac(r){return!!r.onPostDraw}class xa{constructor(t,e){this.soundManager=e}stop(t){if(!t)return;const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)e[i].stop()}setVolume(t,e){const i=this.soundManager.getSoundsForChannel(t);for(const s of i)this.soundManager._isMuted(s)||this.soundManager.setVolume(t,e)}play(t,e){e!=null||(e=this.soundManager.defaultVolume);const i=[],s=new Set,n=this.soundManager.getSoundsForChannel(t);for(const o of n){if(s.has(o)||this.soundManager._isMuted(o))continue;const a=this.soundManager._getEffectiveVolume(o);i.push(o.play(a*e)),s.add(o)}return Promise.all(i)}mute(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._muted.add(e[i]),e[i].pause()}unmute(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._muted.has(e[i])&&(e[i].play(),this.soundManager._muted.delete(e[i]))}toggle(t){const e=this.soundManager.getSoundsForChannel(t);for(let i=0;i<e.length;i++)this.soundManager._isMuted(e[i])?(e[i].play(),this.soundManager._muted.delete(e[i])):(this.soundManager._muted.add(e[i]),e[i].pause())}}class hc{constructor(t){this._channelToConfig=new Map,this._nameToConfig=new Map,this._mix=new Map,this._muted=new Set,this._all=new Set,this._defaultVolume=1;var e;if(this._defaultVolume=(e=t.volume)!=null?e:1,this.channel=new xa(t,this),t.sounds)for(const[i,s]of Object.entries(t.sounds))this.track(i,s)}set defaultVolume(t){this._defaultVolume=B(t,0,1)}get defaultVolume(){return this._defaultVolume}getSounds(){return Array.from(this._all)}getSoundsForChannel(t){const e=this._channelToConfig.get(t);return e?e.sounds:[]}_isMuted(t){return this._muted.has(t)}_getEffectiveVolume(t){var e;if(this._isMuted(t))return 0;let i=this._defaultVolume;return this._mix.has(t)&&(i*=(e=this._mix.get(t))!=null?e:this._defaultVolume),i}play(t,e=this._defaultVolume){const i=this._nameToConfig.get(t);if(!i)return Promise.resolve();const{sound:s}=i;if(this._isMuted(s))return Promise.resolve();const n=e*this._getEffectiveVolume(s);return s.play(n)}getSound(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;return i}setVolume(t,e=this._defaultVolume){const i=this._nameToConfig.get(t);if(!i)return;const{sound:s}=i;this._setMix(s,e)}getVolume(t){var e;const i=this.getSound(t);return i&&(e=this._mix.get(i))!=null?e:0}_setMix(t,e){this._mix.set(t,e),t.volume=e}track(t,e){let i,s,n;e instanceof zn?(i=e,s=this._defaultVolume,n=[]):{sound:i,volume:s,channels:n}=e,this._nameToConfig.set(t,{sound:i,volume:s,channels:n}),this._mix.set(i,s!=null?s:this._defaultVolume),this._all.add(i),n&&this.addChannel(t,n)}untrack(t){this._nameToConfig.delete(t);const e=this.getSound(t);e&&(this._mix.delete(e),this._all.delete(e))}stop(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;i.stop();return}this._all.forEach(e=>e.stop())}mute(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;this._muted.add(i),i.pause();return}this._muted=new Set(this._all),this._muted.forEach(e=>e.pause())}unmute(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;i.play(),this._muted.delete(i);return}this._muted.forEach(e=>e.play()),this._muted.clear()}toggle(t){if(t){const e=this._nameToConfig.get(t);if(!e)return;const{sound:i}=e;this._isMuted(i)?this.unmute(t):this.mute(t);return}this._muted.size>0?(this._muted.forEach(e=>e.play()),this._muted.clear()):(this._muted=new Set(this._all),this._muted.forEach(e=>e.pause()))}addChannel(t,e){const i=this.getSound(t);if(!i)return;const s=this._mix.get(i);this._mix.set(i,s!=null?s:this._defaultVolume),this._all.add(i);for(const n of e){let o=this._channelToConfig.get(n);o||(o={sounds:[i]}),o.sounds.indexOf(i)===-1&&o.sounds.push(i),this._channelToConfig.set(n,o)}}removeChannel(t,e){const i=this.getSound(t);if(i)for(const s of e){const n=this._channelToConfig.get(s);if(!n)return;const o=n.sounds.indexOf(i);o>=-1&&n.sounds.splice(o,1),this._channelToConfig.set(s,n)}}}class lc{constructor(t,e=!1){this.path=t,this.width=0,this.height=0,this._images=[],this.data=[],this._sprites=[],this._resource=new li(t,"arraybuffer",e)}get bustCache(){return this._resource.bustCache}set bustCache(t){this._resource.bustCache=t}async load(){const t=await this._resource.load();this._stream=new ba(t),this._gif=new ya(this._stream);const e=this._gif.images.map(i=>new qt(i.src,!1));return await Promise.all(e.map(i=>i.load())),this.data=this._images=e,this._sprites=this._images.map(i=>i.toSprite()),this.data}isLoaded(){return!!this.data}toSprite(t=0){var e;return(e=this._sprites[t])!=null?e:null}toSpriteSheet(){const t=this._sprites;return t.length?new ye({sprites:t}):null}toAnimation(t){var e;const i=(e=this._gif)==null?void 0:e.images;if(i!=null&&i.length){const s=i.map((n,o)=>{var a;return{graphic:this._sprites[o],duration:((a=this._gif)==null?void 0:a.frames[o].delayMs)||void 0}});return this._animation=new Oi({frames:s,frameDuration:t}),this._animation}return null}get readCheckBytes(){var t,e;return(e=(t=this._gif)==null?void 0:t.checkBytes)!=null?e:[]}}const cs=r=>r.reduce(function(t,e){return t*2+e},0),tr=r=>{const t=[];for(let e=7;e>=0;e--)t.push(!!(r&1<<e));return t};class ba{constructor(t){if(this.len=0,this.position=0,this.readByte=()=>{if(this.position>=this.data.byteLength)throw new Error("Attempted to read past end of stream.");return this.data[this.position++]},this.readBytes=e=>{const i=[];for(let s=0;s<e;s++)i.push(this.readByte());return i},this.read=e=>{let i="";for(let s=0;s<e;s++)i+=String.fromCharCode(this.readByte());return i},this.readUnsigned=()=>{const e=this.readBytes(2);return(e[1]<<8)+e[0]},this.data=new Uint8Array(t),this.len=this.data.byteLength,this.len===0)throw new Error("No data loaded from file")}}const cc=function(r,t){let e=0;const i=function(_){let f=0;for(let m=0;m<_;m++)t.charCodeAt(e>>3)&1<<(e&7)&&(f|=1<<m),e++;return f},s=[],n=1<<r,o=n+1;let a=r+1,h=[];const l=function(){h=[],a=r+1;for(let _=0;_<n;_++)h[_]=[_];h[n]=[],h[o]=null};let c=0,u=0;for(;;){if(u=c,c=i(a),c===n){l();continue}if(c===o)break;if(c<h.length)u!==n&&h.push(h[u].concat(h[c][0]));else{if(c!==h.length)throw new Error("Invalid LZW code.");h.push(h[u].concat(h[u][0]))}s.push.apply(s,h[c]),h.length===1<<a&&a<12&&a++}return s};class ya{constructor(t){this._handler={},this.frames=[],this.images=[],this.globalColorTableBytes=[],this.checkBytes=[],this.parseColorTableBytes=e=>{const i=[];for(let s=0;s<e;s++){const n=this._st.readBytes(3);i.push(n)}return i},this.readSubBlocks=()=>{let e,i;i="";do e=this._st.readByte(),i+=this._st.read(e);while(e!==0);return i},this.parseHeader=()=>{const e={sig:"",ver:"",width:0,height:0,colorResolution:0,globalColorTableSize:0,gctFlag:!1,sortedFlag:!1,globalColorTable:[],backgroundColorIndex:0,pixelAspectRatio:0};if(e.sig=this._st.read(3),e.ver=this._st.read(3),e.sig!=="GIF")throw new Error("Not a GIF file.");e.width=this._st.readUnsigned(),e.height=this._st.readUnsigned(),this._currentFrameCanvas.width=e.width,this._currentFrameCanvas.height=e.height;const i=tr(this._st.readByte());e.gctFlag=i.shift(),e.colorResolution=cs(i.splice(0,3)),e.sortedFlag=i.shift(),e.globalColorTableSize=cs(i.splice(0,3)),e.backgroundColorIndex=this._st.readByte(),e.pixelAspectRatio=this._st.readByte(),e.gctFlag&&(this.globalColorTableBytes=this.parseColorTableBytes(1<<e.globalColorTableSize+1)),this._handler.hdr&&this._handler.hdr(e)&&this.checkBytes.push(this._handler.hdr)},this.parseExt=e=>{const i=h=>{this.checkBytes.push(this._st.readByte());const l=tr(this._st.readByte());return h.reserved=l.splice(0,3),h.disposalMethod=cs(l.splice(0,3)),h.userInputFlag=l.shift(),h.transparentColorFlag=l.shift(),h.delayTime=this._st.readUnsigned(),h.transparentColorIndex=this._st.readByte(),h.terminator=this._st.readByte(),this._handler.gce&&this._handler.gce(h)&&this.checkBytes.push(this._handler.gce),h},s=h=>{h.comment=this.readSubBlocks(),this._handler.com&&this._handler.com(h)&&this.checkBytes.push(this._handler.com)},n=h=>{this.checkBytes.push(this._st.readByte()),h.ptHeader=this._st.readBytes(12),h.ptData=this.readSubBlocks(),this._handler.pte&&this._handler.pte(h)&&this.checkBytes.push(this._handler.pte)},o=h=>{const l=u=>{this.checkBytes.push(this._st.readByte()),u.unknown=this._st.readByte(),u.iterations=this._st.readUnsigned(),u.terminator=this._st.readByte(),this._handler.app&&this._handler.app.NETSCAPE&&this._handler.app.NETSCAPE(u)&&this.checkBytes.push(this._handler.app)},c=u=>{u.appData=this.readSubBlocks(),this._handler.app&&this._handler.app[u.identifier]&&this._handler.app[u.identifier](u)&&this.checkBytes.push(this._handler.app[u.identifier])};switch(this.checkBytes.push(this._st.readByte()),h.identifier=this._st.read(8),h.authCode=this._st.read(3),h.identifier){case"NETSCAPE":l(h);break;default:c(h);break}},a=h=>{h.data=this.readSubBlocks(),this._handler.unknown&&this._handler.unknown(h)&&this.checkBytes.push(this._handler.unknown)};switch(e.label=this._st.readByte(),e.label){case 249:e.extType="gce",this._gce=i(e);break;case 254:e.extType="com",s(e);break;case 1:e.extType="pte",n(e);break;case 255:e.extType="app",o(e);break;default:e.extType="unknown",a(e);break}},this.parseImg=e=>{var i;const s=(a,h)=>{const l=new Array(a.length),c=a.length/h,u=(p,x)=>{const v=a.slice(x*h,(x+1)*h);l.splice.apply(l,[p*h,h].concat(v))},_=[0,4,2,1],f=[8,8,4,2];let m=0;for(let p=0;p<4;p++)for(let x=_[p];x<c;x+=f[p])u(x,m),m++;return l};e.leftPos=this._st.readUnsigned(),e.topPos=this._st.readUnsigned(),e.width=this._st.readUnsigned(),e.height=this._st.readUnsigned();const n=tr(this._st.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=cs(n.splice(0,3)),e.lctFlag&&(e.lctBytes=this.parseColorTableBytes(1<<e.lctSize+1)),e.lzwMinCodeSize=this._st.readByte();const o=this.readSubBlocks();e.pixels=cc(e.lzwMinCodeSize,o),e.interlaced&&(e.pixels=s(e.pixels,e.width)),(i=this._gce)!=null&&i.delayTime&&(e.delayMs=this._gce.delayTime*10),this.frames.push(e),this.arrayToImage(e,e.lctFlag?e.lctBytes:this.globalColorTableBytes),this._handler.img&&this._handler.img(e)&&this.checkBytes.push(this._handler)},this.parseBlocks=()=>{const e={sentinel:this._st.readByte(),type:""};switch(String.fromCharCode(e.sentinel)){case"!":e.type="ext",this.parseExt(e);break;case",":e.type="img",this.parseImg(e);break;case";":e.type="eof",this._handler.eof&&this._handler.eof(e)&&this.checkBytes.push(this._handler.eof);break;default:throw new Error("Unknown block: 0x"+e.sentinel.toString(16))}e.type!=="eof"&&this.parseBlocks()},this.arrayToImage=(e,i)=>{var s,n,o,a;const h=document.createElement("canvas");h.width=e.width,h.height=e.height;const l=h.getContext("2d"),c=l.getImageData(0,0,h.width,h.height);let u=-1;(s=this._gce)!=null&&s.transparentColorFlag&&(u=this._gce.transparentColorIndex);for(let f=0;f<e.pixels.length;f++){const m=e.pixels[f],p=i[m];m===u?c.data.set([0,0,0,0],f*4):c.data.set([...p,255],f*4)}if(l.putImageData(c,0,0),((n=this._gce)==null?void 0:n.disposalMethod)===1&&this.images.length)this._currentFrameContext.drawImage(this.images[this.images.length-1],0,0);else if(((o=this._gce)==null?void 0:o.disposalMethod)===2&&((a=this._hdr)!=null&&a.gctFlag)){const f=i[this._hdr.backgroundColorIndex];this._currentFrameContext.fillStyle=`rgb(${f[0]}, ${f[1]}, ${f[2]})`,this._currentFrameContext.fillRect(0,0,this._hdr.width,this._hdr.height)}else this._currentFrameContext.clearRect(0,0,this._currentFrameCanvas.width,this._currentFrameCanvas.height);this._currentFrameContext.drawImage(h,e.leftPos,e.topPos,e.width,e.height);const _=new Image;_.src=this._currentFrameCanvas.toDataURL(),this.images.push(_)},this._st=t,this._handler={},this._currentFrameCanvas=document.createElement("canvas"),this._currentFrameContext=this._currentFrameCanvas.getContext("2d"),this.parseHeader(),this.parseBlocks()}}class dc{constructor(t,e,{bustCache:i,...s}={}){this.path=t,this.family=e,this._isLoaded=!1,this._resource=new li(t,"blob",i),this._options=s}async load(){if(this.isLoaded())return this.data;try{const t=await this._resource.load(),e=URL.createObjectURL(t);this.data||(this.data=new FontFace(this.family,`url(${e})`),document.fonts.add(this.data)),await this.data.load(),this._isLoaded=!0}catch(t){throw`Error loading FontSource from path '${this.path}' with error [${t.message}]`}return this.data}isLoaded(){return this._isLoaded}toFont(t){return new Se({family:this.family,...this._options,...t})}}const Ca=ma(),uc=/^\s*(?:function)?\*/;function Sa(r){return typeof r!="function"?!1:uc.test(Function.prototype.toString.call(r))?!0:Object.getPrototypeOf?Object.getPrototypeOf(r)===Object.getPrototypeOf(new Function("return function * () {}")()):!1}function Ta(...r){var t;const e=R.getInstance();let i,s,n,o;Sa(r[0])&&(s=globalThis,i=r[0],n=r[1]),Sa(r[1])&&(s=r[0],i=r[1],n=r[2]),r[1]instanceof hs&&(s=r[0],o=r[1],i=r[2],n=r[3]),r[0]instanceof hs&&(s=globalThis,o=r[0],i=r[1],n=r[2]);const a=va(Ca),h=n==null?void 0:n.timing,l=a?!1:(t=n==null?void 0:n.autostart)!=null?t:!0;let c;try{c=o!=null?o:hs.useEngine()}catch(y){throw Error(`Cannot run coroutine without engine parameter outside of an excalibur lifecycle method.
|
|
930
|
+
Pass an engine parameter to ex.coroutine(engine, function * {...})`)}let u=!1,_=!1,f=!1;const m=i.bind(s),p=m();let x;const v=new Promise((y,S)=>{x=A=>{try{if(f){_=!0,y();return}const{done:I,value:C}=Ca.scope(!0,()=>p.next(A));if(I||f){_=!0,y();return}C instanceof Promise?C.then(()=>{c.clock.schedule(x,0,h)}):C===void 0||C===void 0?c.clock.schedule(x,0,h):c.clock.schedule(x,C||0,h)}catch(I){S(I);return}},l&&(u=!0,x(c.clock.elapsed()))}),g={isRunning:()=>u&&!f&&!_,isComplete:()=>_,cancel:()=>{f=!0},start:()=>(u?e.warn(`.start() was called on a coroutine that was already started, this is probably a bug:
|
|
931
|
+
`,Function.prototype.toString.call(m)):(u=!0,x(c.clock.elapsed())),g),generator:p,done:v,then:v.then.bind(v),[Symbol.iterator]:()=>p};return g}class ds extends At{constructor(t){var e,i,s,n,o;super(),this._logger=R.getInstance(),this.transform=new P,this.graphics=new K,this._completeFuture=new wt,this.started=!1,this._currentDistance=0,this._currentProgress=0,this.done=this._completeFuture.promise,this._useLegacyEasing=!1,this.name=`Transition#${this.id}`,this.duration=t.duration,Te(t.easing)?(this.legacyEasing=(e=t.easing)!=null?e:Rt.Linear,this._useLegacyEasing=!0):this.easing=(i=t.easing)!=null?i:Ai,this.direction=(s=t.direction)!=null?s:"out",this.hideLoader=(n=t.hideLoader)!=null?n:!1,this.blockInput=(o=t.blockInput)!=null?o:!1,this.transform.coordPlane=rt.Screen,this.transform.pos=w.Zero,this.transform.z=1/0,this.graphics.anchor=w.Zero,this.addComponent(this.transform),this.addComponent(this.graphics),this.direction==="out"?this._currentProgress=0:this._currentProgress=1}get progress(){return this._currentProgress}get distance(){return this._currentDistance}get complete(){return this.direction==="out"?this.progress>=1:this.progress<=0}updateTransition(t,e){this.complete||(this._currentDistance+=B(e/this.duration,0,1),this._currentDistance>=1&&(this._currentDistance=1),this.direction==="out"?this._useLegacyEasing?this._currentProgress=B(this.legacyEasing(this._currentDistance,0,1,1),0,1):this._currentProgress=B(ot(0,1,this.easing(this._currentDistance)),0,1):this._useLegacyEasing?this._currentProgress=B(this.legacyEasing(this._currentDistance,1,0,1),0,1):this._currentProgress=B(ot(1,0,this.easing(this._currentDistance)),0,1))}async onPreviousSceneDeactivate(t){}onStart(t){}onUpdate(t){}onEnd(t){}onReset(){}reset(){this.started=!1,this._completeFuture=new wt,this.done=this._completeFuture.promise,this._currentDistance=0,this.direction==="out"?this._currentProgress=0:this._currentProgress=1,this.onReset()}_addToTargetScene(t,e){const i=e;if(this.started&&this._logger.warn(`Attempted to add a transition ${this.name} that is already playing.`),i.world.entityManager.getById(this.id))return this._co;this._engine=t,i.add(this);const s=this;return this._co=Ta(t,function*(){for(;!s.complete;){const n=yield;s.updateTransition(s._engine,n),s._execute()}},{autostart:!1}),this._co}async _play(){this.started&&(this.reset(),this._logger.warn(`Attempted to play a transition ${this.name} that is already playing, reset transition.`)),(!this._engine||!this._co)&&(this.reset(),this._logger.warn(`Attempted to play a transition ${this.name} that hasn't been added`)),this._co&&await this._co.start()}_execute(){this.isInitialized&&(this.started||(this.started=!0,this.onStart(this.progress)),this.onUpdate(this.progress),this.complete&&!this._completeFuture.isCompleted&&(this.onEnd(this.progress),this._completeFuture.resolve()))}}class _c extends ds{constructor(t){var e,i;super({...t,duration:(e=t.duration)!=null?e:2e3}),this.name=`FadeInOut#${this.id}`,this.color=(i=t.color)!=null?i:T.Black}onInitialize(t){this.transform.pos=t.screen.unsafeArea.topLeft,this.screenCover=new ui({width:t.screen.resolution.width,height:t.screen.resolution.height,color:this.color}),this.graphics.add(this.screenCover),this.graphics.opacity=this.progress}onReset(){this.graphics.opacity=this.progress}onStart(t){this.graphics.opacity=t}onEnd(t){this.graphics.opacity=t}onUpdate(t){this.graphics.opacity=t}}class fc extends ds{constructor(t){super({direction:"in",...t}),this.name=`CrossFade#${this.id}`}async onPreviousSceneDeactivate(t){this.image=await t.engine.screenshot(!0),await this.image.decode()}onInitialize(t){this.engine=t,this.transform.pos=t.screen.unsafeArea.topLeft,this.screenCover=qt.fromHtmlImageElement(this.image).toSprite(),this.graphics.add(this.screenCover),this.transform.scale=b(1/t.screen.pixelRatio,1/t.screen.pixelRatio),this.graphics.opacity=this.progress}onStart(t){this.graphics.opacity=this.progress}onReset(){this.graphics.opacity=this.progress}onEnd(t){this.graphics.opacity=t}onUpdate(t){this.graphics.opacity=t}}class gc extends ds{constructor(t){var e;super({direction:"in",...t}),this._easing=Rt.Linear,this._start=w.Zero,this._end=w.Zero,this.name=`Slide#${this.id}`,this.slideDirection=t.slideDirection,this.transform.coordPlane=rt.Screen,this.graphics.forceOnScreen=!0,this._easing=(e=t.easingFunction)!=null?e:this._easing}async onPreviousSceneDeactivate(t){this._image=await t.engine.screenshot(!0),await this._image.decode(),this._screenCover=qt.fromHtmlImageElement(this._image).toSprite()}onInitialize(t){this._engine=t;let e=t.screen.unsafeArea;switch(e.hasZeroDimensions()&&(e=t.screen.contentArea),this.slideDirection){case"up":{this._directionOffset=b(0,-e.height);break}case"down":{this._directionOffset=b(0,e.height);break}case"left":{this._directionOffset=b(-e.width,0);break}case"right":{this._directionOffset=b(e.width,0);break}}this._camera=this._engine.currentScene.camera,this._destinationCameraPosition=this._camera.pos.clone(),this._camera.pos=this._camera.pos.add(this._directionOffset),this.transform.pos=this.transform.pos.add(this._directionOffset),this._startCameraPosition=this._camera.pos.clone(),this._start=e.topLeft,this._end=this._start.add(this._directionOffset),this.transform.pos=this._start,this.graphics.use(this._screenCover),this.transform.scale=b(1/t.screen.pixelRatio,1/t.screen.pixelRatio)}onStart(t){const e=this._easing(this.distance,0,1,1);this.transform.pos.x=ot(this._start.x,this._end.x,e),this.transform.pos.y=ot(this._start.y,this._end.y,e),this._camera.pos.x=ot(this._startCameraPosition.x,this._destinationCameraPosition.x,e),this._camera.pos.y=ot(this._startCameraPosition.y,this._destinationCameraPosition.y,e)}onUpdate(t){const e=this._easing(this.distance,0,1,1);this.transform.pos.x=ot(this._start.x,this._end.x,e),this.transform.pos.y=ot(this._start.y,this._end.y,e),this._camera.pos.x=ot(this._startCameraPosition.x,this._destinationCameraPosition.x,e),this._camera.pos.y=ot(this._startCameraPosition.y,this._destinationCameraPosition.y,e)}}const pc=Object.freeze(Object.defineProperty({__proto__:null,ConsoleAppender:Ss,DrawUtil:Uh,EasingFunctions:Rt,LogLevel:Le,Logger:R,Observable:gt,ScreenAppender:mr,addItemToArray:Ch,contains:xr,delay:Di,fail:br,getMinIndex:wr,getPosition:oi,isLegacyEasing:Te,isObject:Bi,mergeDeep:ki,omit:yr,removeItemFromArray:He},Symbol.toStringTag,{value:"Module"})),Aa=5,ti={},mc=()=>{for(const r in ti)ti[r]=0},us=(r,t)=>{const e=De.isEnabled("suppress-obsolete-message");ti[r]<Aa&&!e&&(R.getInstance().warn(r),console.trace&&t.showStackTrace&&console.trace()),ti[r]++};function vc(r){return r={message:"This feature will be removed in future versions of Excalibur.",alternateMethod:null,showStackTrace:!1,...r},function(t,e,i){if(i&&!(typeof i.value=="function"||typeof i.get=="function"||typeof i.set=="function"))throw new SyntaxError("Only classes/functions/getters/setters can be marked as obsolete");const n=`${`${t.name||""}${t.name&&e?".":""}${e||""}`} is marked obsolete: ${r.message}`+(r.alternateMethod?` Use ${r.alternateMethod} instead`:"");ti[n]||(ti[n]=0);const o=i?{...i}:t;if(!i){class a extends o{constructor(...l){us(n,r),super(...l)}}return a}return i&&i.value?(o.value=function(){return us(n,r),i.value.apply(this,arguments)},o):(i&&i.get&&(o.get=function(){return us(n,r),i.get.apply(this,arguments)}),i&&i.set&&(o.set=function(){return us(n,r),i.set.apply(this,arguments)}),o)}}class wc{constructor(){this._queue=[]}get length(){return this._queue.length}enqueue(){const t=new wt;return this._queue.push(t),t.promise}dequeue(t){this._queue.shift().resolve(t)}}class xc{constructor(t){this._count=t,this._waitQueue=new wc}get count(){return this._count}get waiting(){return this._waitQueue.length}async enter(){return this._count!==0?(this._count--,Promise.resolve()):this._waitQueue.enqueue()}exit(t=1){if(t!==0){for(;t!==0&&this._waitQueue.length!==0;)this._waitQueue.dequeue(null),t--;this._count+=t}}}const er="0.32.0-alpha.1572+72a3430";Fe(),d.ActionCompleteEvent=js,d.ActionContext=fi,d.ActionQueue=eo,d.ActionSequence=Kn,d.ActionStartEvent=Zs,d.ActionsComponent=Qe,d.ActionsSystem=Vn,d.ActivateEvent=Gs,d.Actor=kt,d.ActorEvents=Al,d.AddEvent=Qs,d.AddedComponent=Sh,d.AffineMatrix=Z,d.Animation=Oi,d.AnimationDirection=Br,d.AnimationEvents=Dh,d.AnimationStrategy=kr,d.ArcadeSolver=Fn,d.AudioContextFactory=pi,d.Axes=ea,d.Axis=Yo,d.BaseAlign=ln,d.BezierCurve=si,d.Blink=yo,d.BodyComponent=N,d.BoundingBox=F,d.BrowserComponent=$n,d.BrowserEvents=da,d.Buttons=qn,d.Camera=Ko,d.CameraEvents=zl,d.Canvas=Yi,d.ChannelCollection=xa,d.Circle=Xi,d.CircleCollider=dt,d.Clock=Zn,d.ClosestLineJumpTable=Vt,d.Collider=ai,d.ColliderComponent=tt,d.CollisionContact=xe,d.CollisionEndEvent=ri,d.CollisionGroup=me,d.CollisionGroupManager=Pi,d.CollisionJumpTable=Ut,d.CollisionPostSolveEvent=Fi,d.CollisionPreSolveEvent=Mi,d.CollisionStartEvent=ni,d.CollisionSystem=Ji,d.CollisionType=M,d.Color=T,d.ColorBlindFlags=la,d.ColorBlindnessMode=$e,d.ColorBlindnessPostProcessor=Qr,d.Component=Dt,d.CompositeCollider=at,d.ConsoleAppender=Ss,d.ContactConstraintPoint=Mo,d.ContactEndEvent=Ri,d.ContactSolveBias=ae,d.ContactStartEvent=Ii,d.CoordPlane=rt,d.CrossFade=fc,d.CurveBy=Eo,d.CurveTo=Po,d.DeactivateEvent=Vs,d.Debug=Tt,d.DebugConfig=ca,d.DebugGraphicsComponent=Gi,d.DebugSystem=Gn,d.DebugText=fn,d.DefaultAntialiasOptions=Or,d.DefaultGarbageCollectionOptions=Qn,d.DefaultLoader=mi,d.DefaultPixelArtOptions=Hr,d.DegreeOfFreedom=le,d.Delay=So,d.Detector=Oo,d.Die=To,d.Direction=dn,d.Director=pa,d.DirectorEvents=ga,d.DisplayMode=gi,d.DynamicTree=en,d.DynamicTreeCollisionProcessor=Li,d.EX_VERSION=er,d.EaseBy=bo,d.EaseTo=xo,d.EasingFunctions=Rt,d.Edge=xs,d.EdgeCollider=St,d.ElasticToActorStrategy=jo,d.EmitterType=Ee,d.Engine=hs,d.EngineEvents=ql,d.EnterTriggerEvent=Ys,d.EnterViewPortEvent=Xs,d.Entity=At,d.EntityEvents=Eh,d.EntityManager=Sr,d.EventEmitter=X,d.EventTypes=As,d.Events=yh,d.ExResponse=Ln,d.ExcaliburGraphicsContext2DCanvas=$i,d.ExcaliburGraphicsContextWebGL=$t,d.ExitTriggerEvent=$s,d.ExitViewPortEvent=qs,d.Fade=Co,d.FadeInOut=_c,d.Flags=De,d.Flash=Ao,d.Follow=Pn,d.Font=Se,d.FontCache=qi,d.FontSource=dc,d.FontStyle=cn,d.FontUnit=an,d.FpsSampler=ua,d.FrameStats=yi,d.Future=wt,d.GameEvent=k,d.GameStartEvent=Is,d.GameStopEvent=Rs,d.Gamepad=ns,d.GamepadAxisEvent=Hs,d.GamepadButtonEvent=Os,d.GamepadConnectEvent=Us,d.GamepadDisconnectEvent=zs,d.Gamepads=ss,d.GarbageCollector=wa,d.Gif=lc,d.GifParser=ya,d.GlobalCoordinates=ke,d.GpuParticleEmitter=$l,d.GpuParticleRenderer=ls,d.Graph=ws,d.Graphic=st,d.GraphicsComponent=K,d.GraphicsGroup=We,d.GraphicsSystem=pn,d.HashColliderProxy=Ro,d.HashGridCell=Zt,d.HashGridProxy=In,d.HiddenEvent=Ws,d.HorizontalFirst=nn,d.ImageFiltering=mt,d.ImageSource=qt,d.ImageSourceAttributeConstants=z,d.ImageWrapping=_t,d.InitializeEvent=Oe,d.InputHost=Yn,d.InputMapper=ia,d.IsometricEntityComponent=vi,d.IsometricEntitySystem=Wn,d.IsometricMap=Ul,d.IsometricTile=qo,d.KeyEvent=wi,d.Keyboard=aa,d.Keys=oa,d.KillEvent=Ei,d.Label=Xl,d.LimitCameraBoundsStrategy=Jo,d.Line=gn,d.LineSegment=Q,d.Loader=ts,d.LoaderEvents=Fl,d.LockCameraToActorAxisStrategy=Zo,d.LockCameraToActorStrategy=$o,d.LogLevel=Le,d.Logger=R,d.Material=Kr,d.Matrix=Ct,d.MatrixLocations=cr,d.MediaEvent=Un,d.Meet=ji,d.MotionComponent=O,d.MotionSystem=Qi,d.MoveBy=Tn,d.MoveByWithOptions=ro,d.MoveTo=An,d.MoveToWithOptions=ao,d.NativePointerButton=Pe,d.NativeSoundEvent=Ae,d.NativeSoundProcessedEvent=Lo,d.NineSlice=wn,d.NineSliceStretch=zr,d.Node=Ti,d.None=rn,d.Observable=gt,d.OffscreenSystem=mn,d.Pair=pt,d.ParallaxComponent=Vi,d.ParallelActions=Zl,d.Particle=Zi,d.ParticleEmitter=Yl,d.ParticleRenderer=Zr,d.ParticleTransform=Xt,d.PhysicsStats=os,d.PhysicsWorld=Fo,d.PointerAbstraction=Xn,d.PointerButton=ce,d.PointerComponent=he,d.PointerEvent=xi,d.PointerEventReceiver=rs,d.PointerScope=Be,d.PointerSystem=is,d.PointerType=de,d.Polygon=vn,d.PolygonCollider=lt,d.Pool=zi,d.PositionNode=_r,d.PostCollisionEvent=we,d.PostDebugDrawEvent=Bs,d.PostDrawEvent=ze,d.PostFrameEvent=Ls,d.PostKillEvent=Es,d.PostTransformDrawEvent=Fs,d.PostUpdateEvent=oe,d.PreCollisionEvent=ve,d.PreDebugDrawEvent=Ds,d.PreDrawEvent=Ue,d.PreFrameEvent=ks,d.PreKillEvent=Ps,d.PreLoadEvent=Wl,d.PreTransformDrawEvent=Ms,d.PreUpdateEvent=re,d.Projection=ei,d.QuadIndexBuffer=Ze,d.QuadTree=Je,d.Query=Lt,d.QueryManager=Tr,d.RadiusAroundActorStrategy=Qo,d.Random=se,d.Raster=Ge,d.Ray=ge,d.RealisticSolver=Dn,d.Rectangle=ui,d.RemoveEvent=Js,d.RemovedComponent=Ah,d.RentalPool=qe,d.Repeat=io,d.RepeatForever=so,d.Resolution=Bn,d.Resource=li,d.ResourceEvents=Hh,d.RotateBy=uo,d.RotateByWithOptions=co,d.RotateTo=lo,d.RotateToWithOptions=ho,d.RotationType=j,d.ScaleBy=vo,d.ScaleByWithOptions=mo,d.ScaleTo=go,d.ScaleToWithOptions=fo,d.Scene=Mt,d.SceneEvents=Gl,d.Screen=kn,d.ScreenAppender=mr,d.ScreenElement=Hn,d.ScreenEvents=Pl,d.ScreenShader=jr,d.ScrollPreventionMode=Ke,d.Semaphore=xc,d.SeparatingAxis=Ne,d.SeparationInfo=Mr,d.Shader=Bt,d.Shape=ut,d.Slide=gc,d.SolverStrategy=Ui,d.Sound=zn,d.SoundEvents=Rl,d.SoundManager=hc,d.SparseHashGrid=Rn,d.SparseHashGridCollisionProcessor=Mn,d.SpatialPartitionStrategy=hi,d.Sprite=zt,d.SpriteFont=Hi,d.SpriteSheet=ye,d.StandardClock=jn,d.StateMachine=Ki,d.StrategyContainer=Xo,d.Stream=ba,d.System=Et,d.SystemManager=Pr,d.SystemPriority=Gt,d.SystemType=Pt,d.TagQuery=Ks,d.TestClock=_a,d.Text=_i,d.TextAlign=hn,d.TextureLoader=Xe,d.Tile=Vo,d.TileMap=Go,d.TileMapEvents=Ll,d.TiledAnimation=xn,d.TiledSprite=di,d.Timer=es,d.Toaster=fa,d.Transform=Kt,d.TransformComponent=P,d.Transition=ds,d.TreeNode=tn,d.Trigger=ta,d.TriggerEvents=Ol,d.TwoPI=it,d.UniformBuffer=Nr,d.Util=pc,d.Vector=w,d.VectorView=ms,d.VertexBuffer=Ht,d.VertexLayout=Yt,d.VerticalFirst=sn,d.VisibleEvent=Ns,d.WebAudio=Bo,d.WebAudioInstance=ko,d.WheelDeltaMode=bi,d.WheelEvent=ha,d.World=Er,d.approximatelyEqual=ar,d.assert=Jn,d.canonicalizeAngle=Jt,d.clamp=B,d.coroutine=Ta,d.createId=fe,d.easeInBack=fh,d.easeInBounce=gr,d.easeInCirc=dh,d.easeInCubic=th,d.easeInElastic=mh,d.easeInExpo=hh,d.easeInOutBack=ph,d.easeInOutBounce=xh,d.easeInOutCirc=_h,d.easeInOutCubic=ys,d.easeInOutElastic=wh,d.easeInOutExpo=ch,d.easeInOutQuad=Ka,d.easeInOutQuart=nh,d.easeInOutQuint=ah,d.easeInOutSine=ja,d.easeInQuad=Qa,d.easeInQuart=ih,d.easeInQuint=rh,d.easeInSine=$a,d.easeOutBack=gh,d.easeOutBounce=Cs,d.easeOutCirc=uh,d.easeOutCubic=eh,d.easeOutElastic=vh,d.easeOutExpo=lh,d.easeOutQuad=Ja,d.easeOutQuart=sh,d.easeOutQuint=oh,d.easeOutSine=Za,d.frac=Na,d.getDefaultPhysicsConfig=te,d.glTypeToUniformTypeName=Xr,d.hasGraphicsTick=Sn,d.hasOnAdd=nc,d.hasOnInitialize=Kl,d.hasOnPostUpdate=sc,d.hasOnPreUpdate=ec,d.hasOnRemove=rc,d.hasPostDraw=ac,d.hasPreDraw=oc,d.has_add=Ql,d.has_initialize=jl,d.has_postupdate=ic,d.has_preupdate=tc,d.has_remove=Jl,d.inverseLerp=dr,d.inverseLerpVector=ur,d.isActor=Tl,d.isAddedComponent=Th,d.isComponentCtor=vr,d.isLegacyEasing=Te,d.isLoaderConstructor=On,d.isMoveByOptions=no,d.isMoveToOptions=oo,d.isRemovedComponent=Ph,d.isRotateByOptions=Sl,d.isRotateToOptions=Cl,d.isScaleByOptions=po,d.isScaleToOptions=_o,d.isSceneConstructor=jt,d.isScreenElement=Ho,d.isSystemConstructor=Ar,d.lerp=ot,d.lerpAngle=vs,d.lerpVector=ii,d.linear=Ai,d.maxMessages=Aa,d.nextActionId=H,d.obsolete=vc,d.parseImageFiltering=Ve,d.parseImageWrapping=Ot,d.pixelSnapEpsilon=D,d.randomInRange=Nt,d.randomIntInRange=Va,d.range=Ga,d.remap=Wt,d.remapVector=qa,d.resetObsoleteCounter=mc,d.sign=V,d.smootherstep=Ya,d.smoothstep=Xa,d.toDegrees=hr,d.toRadians=Wa,d.vec=b,d.webgl=Yh,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
|