angry-pixel 2.2.0 → 2.2.2

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/lib/index.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["angry-pixel"]={})}(this,(function(t){"use strict";var e;t.BroadPhaseMethods=void 0,(e=t.BroadPhaseMethods||(t.BroadPhaseMethods={}))[e.QuadTree=0]="QuadTree",e[e.SpartialGrid=1]="SpartialGrid";class i{constructor(t=0,e=0){this._x=t,this._y=e}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}get magnitude(){return Math.sqrt(Math.pow(this._x,2)+Math.pow(this._y,2))}get direction(){return this._direction||(this._direction=new i),i.unit(this._direction,this)}set(t,e){this._x=t,this._y=e}copy(t){this.set(t.x,t.y)}equals(t){return this._x===t.x&&this._y===t.y}clone(){return new i(this._x,this._y)}distance(t){return Math.sqrt(Math.pow(this._x-t.x,2)+Math.pow(this._y-t.y,2))}static add(t,e,i){return t.set(e.x+i.x,e.y+i.y),t}static subtract(t,e,i){return t.set(e.x-i.x,e.y-i.y),t}static unit(t,e){const i=e.x*e.x+e.y*e.y;if(0===i)t.set(0,0);else{const s=1/Math.sqrt(i);t.set(e.x*s,e.y*s)}return t}static normal(t,e){return t.set(-e.y,e.x),this.unit(t,t)}static scale(t,e,i){return t.set(e.x*i,e.y*i),t}static dot(t,e){return t.x*e.x+t.y*e.y}static cross(t,e){return t.x*e.y-t.y*e.x}static round(t,e){return t.set(Math.round(e.x),Math.round(e.y)),t}static floor(t,e){return t.set(Math.floor(e.x),Math.floor(e.y)),t}static ceil(t,e){return t.set(Math.ceil(e.x),Math.ceil(e.y)),t}toString(){return`(${this._x}, ${this._y})`}}class s{constructor(t=0,e=0,s=0,r=0){this.width=0,this.height=0,this._position=new i,this._center=new i,this.set(t,e,s,r)}get x(){return this._position.x}set x(t){this._position.set(t,this._position.y)}get y(){return this._position.y}set y(t){this._position.set(this._position.x,t)}get x1(){return this._position.x+this.width}get y1(){return this._position.y+this.height}get position(){return this._position}set position(t){this._position.set(t.x,t.y)}get center(){return this._center.set(this.x+this.width/2,this.y+this.height/2),this._center}set(t,e,i,s){this._position.set(t,e),this.width=i,this.height=s}equals(t){return this.position.equals(t.position)&&this.width===t.width&&this.height===t.height}copy(t){this.set(t.x,t.y,t.width,t.height)}intersects(t){return!(this.x1<t.x||this.x>t.x1||this.y1<t.y||this.y>t.y1)}contains(t){return t instanceof s?t.x1<=this.x1&&t.x>=this.x&&t.y1<=this.y1&&t.y>=this.y:t instanceof i&&!(t.x<this.x||t.y<this.y||t.x>=this.x1||t.y>=this.y1)}toString(){return`(${this.position.x}, ${this.position.y}, ${this.width}, ${this.height})`}}const r=(t,e,i)=>Math.min(i,Math.max(e,t)),o=(t,e)=>Math.round(t*Math.pow(10,e))/Math.pow(10,e),n=(t,e,i=1)=>{const s=[];for(let r=t;r<=e;r+=i)s.push(r);return s},a=(t,e,i)=>t>=e&&t<=i;class h{constructor(){this.instances=new Map,this.types=new Map}add(t,e){if(!e&&!t.prototype.__ioc_injectable)throw new Error(`Type ${t.name} is not injectable`);return this.types.set(null!=e?e:t.prototype.__ioc_injectable,t),this}set(t,e){return this.instances.set(t,e),this}get(t){var e,i;if(!this.instances.has(t)){const s=this.types.get(t);if(!s)throw new Error(`${t.toString()} is not a valid type`);const r=new s(...(null!==(e=s.prototype.__ioc_inject_constructor)&&void 0!==e?e:[]).map((t=>this.get(t))));(null!==(i=s.prototype.__ioc_inject_prop)&&void 0!==i?i:[]).forEach((([t,e])=>r[t]=this.get(e))),this.instances.set(t,r)}return this.instances.get(t)}has(t){return this.types.has(t)||this.instances.has(t)}}function l(t){return function(e){e.prototype.__ioc_injectable&&e.prototype.__ioc_injectable===t||(e.prototype.__ioc_injectable=t)}}function c(t){return function(e,i,s){void 0!==s?(e.prototype.__ioc_inject_constructor||(e.prototype.__ioc_inject_constructor=[]),e.prototype.__ioc_inject_constructor[s]=t):void 0!==i&&(e.constructor.prototype.__ioc_inject_prop||(e.constructor.prototype.__ioc_inject_prop=[]),e.constructor.prototype.__ioc_inject_prop.push([i,t]))}}const d={CollisionRepository:Symbol.for("CollisionRepository"),CollisionBroadphaseResolver:Symbol.for("CollisionBroadphaseResolver"),CollisionResolutionMethod:Symbol.for("CollisionResolutionMethod"),CollisionAABBResolver:Symbol.for("CollisionAABBResolver"),CollisionCircumferenceAABBResolver:Symbol.for("CollisionCircumferenceAABBResolver"),CollisionCircumferenceResolver:Symbol.for("CollisionCircumferenceResolver"),CollisionSatResolver:Symbol.for("CollisionSatResolver"),CollisionMatrix:Symbol.for("CollisionMatrix")};var g,m=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let u=g=class{constructor(t=new s,e=0){this.rects=new Map,this.children=null,this.seenGen=[],this.retrieveSerial=0,this.minArea=new i,this.maxArea=new i,this.bounds=t,this.depth=e}update(t){this.clear(),0!==t.length&&(this.resize(t),this.ensureSeenCapacity(t.length),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e))))}ensureSeenCapacity(t){if(this.seenGen.length<t){const e=this.seenGen.length;this.seenGen.length=t,this.seenGen.fill(0,e,t)}}clear(){this.rects.clear(),this.children&&(this.children.forEach((t=>t.clear())),this.children=null)}resize(t){this.minArea.set(1/0,1/0),this.maxArea.set(-1/0,-1/0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))})),this.bounds.set(this.minArea.x,this.minArea.y,this.maxArea.x-this.minArea.x,this.maxArea.y-this.minArea.y)}insert(t,e){!this.children&&this.rects.size>=16&&this.depth<8&&(this.subdivide(),this.rects.forEach(((t,e)=>this.children.forEach((i=>{i.bounds.intersects(t)&&i.insert(e,t)})))),this.rects.clear()),this.children?this.children.forEach((i=>{i.bounds.intersects(e)&&i.insert(t,e)})):this.rects.set(t,e)}subdivide(){const t=this.bounds.x,e=this.bounds.y,i=this.bounds.width/2,r=this.bounds.height/2;this.children=[new g(new s(t,e,i,r),this.depth+1),new g(new s(t+i,e,i,r),this.depth+1),new g(new s(t,e+r,i,r),this.depth+1),new g(new s(t+i,e+r,i,r),this.depth+1)]}retrieve(t){2147483647==++this.retrieveSerial&&(this.retrieveSerial=1,this.seenGen.fill(0));const e=[];return this.retrieveFromNode(t,e,this.retrieveSerial,this.seenGen),e}retrieveFromNode(t,e,i,s){this.children?this.children.forEach((r=>{r.bounds.intersects(t)&&r.retrieveFromNode(t,e,i,s)})):this.rects.forEach(((r,o)=>{r.intersects(t)&&s[o]!==i&&(s[o]=i,e.push(o))}))}};u=g=m([l(d.CollisionBroadphaseResolver)],u);var p=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};const f=(t,e,i,s)=>Math.min((t-e)/i|0,s-1);let y=class{constructor(){this.area=new s,this.grid=[],this.rects=new Map,this.subdivisions=0,this.lastAreaX=NaN,this.lastAreaY=NaN,this.lastAreaW=NaN,this.lastAreaH=NaN,this.lastSubdivisions=-1,this.seenGen=[],this.retrieveSerial=0,this.retrieveResult=[],this.minArea=new i,this.maxArea=new i,this.coordinates={x0:0,x1:0,y0:0,y1:0}}update(t){if(0===t.length)return this.rects.clear(),void(this.grid.length>0&&this.clearGridCells());this.resize(t),this.ensureSeenCapacity(t.length),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e)))}ensureSeenCapacity(t){if(this.seenGen.length<t){const e=this.seenGen.length;this.seenGen.length=t,this.seenGen.fill(0,e,t)}}clearGridCells(){for(let t=0;t<this.subdivisions;t++)for(let e=0;e<this.subdivisions;e++)this.grid[t][e].length=0}resize(t){this.minArea.set(1/0,1/0),this.maxArea.set(-1/0,-1/0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))}));const e=this.minArea.x,i=this.minArea.y,s=this.maxArea.x-this.minArea.x,r=this.maxArea.y-this.minArea.y;this.area.set(e,i,s,r);const o=1+(t.length/16|0);this.cellWidth=Math.ceil(this.area.width/o),this.cellHeight=Math.ceil(this.area.height/o);this.grid.length>0&&o===this.lastSubdivisions&&e===this.lastAreaX&&i===this.lastAreaY&&s===this.lastAreaW&&r===this.lastAreaH?this.clearGridCells():(this.subdivisions=o,this.buildGrid(),this.lastSubdivisions=o,this.lastAreaX=e,this.lastAreaY=i,this.lastAreaW=s,this.lastAreaH=r),this.subdivisions=o,this.rects.clear()}buildGrid(){this.grid=[];for(let t=0;t<this.subdivisions;t++){this.grid[t]=[];for(let e=0;e<this.subdivisions;e++)this.grid[t][e]=[]}}insert(t,e){this.updateCoordinates(e);for(let e=this.coordinates.x0;e<=this.coordinates.x1;e++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++)this.grid[e][i].push(t);this.rects.set(t,e)}retrieve(t){this.retrieveResult.length=0,2147483647==++this.retrieveSerial&&(this.retrieveSerial=1,this.seenGen.fill(0)),this.updateCoordinates(t);for(let e=this.coordinates.x0;e<=this.coordinates.x1;e++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++){const s=this.grid[e][i];for(let e=0,i=s.length;e<i;e++){const i=s[e];this.rects.get(i).intersects(t)&&this.seenGen[i]!==this.retrieveSerial&&(this.seenGen[i]=this.retrieveSerial,this.retrieveResult.push(i))}}return this.retrieveResult}updateCoordinates(t){this.coordinates.x0=f(t.x,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.x1=f(t.x1,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.y0=f(t.y,this.area.y,this.cellHeight,this.subdivisions),this.coordinates.y1=f(t.y1,this.area.y,this.cellHeight,this.subdivisions)}};y=p([l(d.CollisionBroadphaseResolver)],y);class x{get vertexModel(){return this._vertexModel}set vertexModel(t){if(this._vertexModel=t,2===t.length)return this.vertices=[new i,new i],void(this.projectionAxes=[new i]);this.vertices=[],this.projectionAxes=[],this._vertexModel.forEach((()=>{this.vertices.push(new i),this.projectionAxes.push(new i)}))}constructor(t,e=0){this.rotation=e,this.boundingBox=new s,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new i,this.projectionAxes=[],this.radius=0,this.vertices=[],this.updateCollisions=!0,this._vertexModel=[],this.vertexModel=t}}class M{constructor(t){this.radius=t,this.boundingBox=new s,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new i,this.projectionAxes=[new i],this.rotation=0,this.vertexModel=[],this.vertices=[new i,new i],this.updateCollisions=!0}}var v=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n},b=function(t,e){return function(i,s){e(i,s,t)}};let S=class{constructor(t,e,i){this.AABBResolver=t,this.circumferenceAABBResolver=e,this.circumferenceResolver=i}findCollision(t,e){return t instanceof x&&e instanceof x?this.AABBResolver.resolve(t,e):t instanceof M&&e instanceof x?this.circumferenceAABBResolver.resolve(t,e):t instanceof x&&e instanceof M?this.circumferenceAABBResolver.resolve(e,t,!0):t instanceof M&&e instanceof M?this.circumferenceResolver.resolve(t,e):void 0}};var C;S=v([l(d.CollisionResolutionMethod),b(0,c(d.CollisionAABBResolver)),b(1,c(d.CollisionCircumferenceAABBResolver)),b(2,c(d.CollisionCircumferenceResolver))],S),t.CollisionMethods=void 0,(C=t.CollisionMethods||(t.CollisionMethods={}))[C.AABB=0]="AABB",C[C.SAT=1]="SAT";var A=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n},w=function(t,e){return function(i,s){e(i,s,t)}};let R=class{constructor(t,e){this.circumferenceResolver=t,this.satResolver=e}findCollision(t,e){return t instanceof M&&e instanceof M?this.circumferenceResolver.resolve(t,e):this.satResolver.resolve(t,e)}};R=A([l(d.CollisionResolutionMethod),w(0,c(d.CollisionCircumferenceResolver)),w(1,c(d.CollisionSatResolver))],R);var E=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let _=class{constructor(){this.direction=new i,this.resolutionDirection=new i,this.outDirection=new i}resolve({boundingBox:t},{boundingBox:e}){if(this.overlapX=Math.min(t.x1,e.x1)-Math.max(t.x,e.x),this.overlapY=Math.min(t.y1,e.y1)-Math.max(t.y,e.y),!(this.overlapX<0||this.overlapY<0))return this.checkOverlapForLines(t,e),this.direction.set(Math.sign(e.center.x-t.center.x),Math.sign(e.center.y-t.center.y)),this.preventContainment(t,e),this.overlapY<this.overlapX?(this.minOverlap=this.overlapY,this.resolutionDirection.set(0,this.direction.y)):(this.minOverlap=this.overlapX,this.resolutionDirection.set(this.direction.x,this.overlapY===this.overlapX?this.direction.y:0)),{direction:i.unit(this.outDirection,this.resolutionDirection),penetration:this.minOverlap}}checkOverlapForLines(t,e){0!==t.width&&0!==e.width||0!==this.overlapX||(this.overlapX=Math.min(Math.abs(t.x-e.x),Math.abs(t.x1-e.x1))),0!==t.height&&0!==e.height||0!==this.overlapY||(this.overlapY=Math.min(Math.abs(t.y-e.y),Math.abs(t.y1-e.y1)))}preventContainment(t,e){if(this.overlapY>0&&(t.y1>e.y1&&t.y<e.y||t.y1<e.y1&&t.y>e.y)){const i=Math.abs(t.y-e.y),s=Math.abs(t.y1-e.y1);this.overlapY+=i<s?i:s}if(this.overlapX>0&&(t.x1>e.x1&&t.x<e.x||t.x1<e.x1&&t.x>e.x)){const i=Math.abs(t.x-e.x),s=Math.abs(t.x1-e.x1);this.overlapX+=i<s?i:s}}};_=E([l(d.CollisionAABBResolver)],_);var T=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let P=class{constructor(){this.closestPoint=new i,this.distance=new i,this.direction=new i,this.outDirection=new i}resolve(t,e,s=!1){this.closestPoint.set(r(t.position.x,e.boundingBox.x,e.boundingBox.x1),r(t.position.y,e.boundingBox.y,e.boundingBox.y1)),i.subtract(this.distance,this.closestPoint,t.position);const o=this.distance.magnitude;if(!(o>t.radius))return i.unit(this.direction,this.distance),s?i.scale(this.outDirection,this.direction,-1):this.outDirection.copy(this.direction),{direction:this.outDirection,penetration:t.radius-o}}};P=T([l(d.CollisionCircumferenceAABBResolver)],P);var B=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let D=class{constructor(){this.distance=new i,this.outDirection=new i}resolve(t,e){i.subtract(this.distance,e.position,t.position);const s=this.distance.magnitude,r=t.radius+e.radius;if(!(s>r))return i.unit(this.outDirection,this.distance),{direction:this.outDirection,penetration:r-s}}};D=B([l(d.CollisionCircumferenceResolver)],D);var F=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let U=class{constructor(){this.mergedAxes=[],this.projA={min:0,max:0},this.projB={min:0,max:0},this.smallestAxis=new i,this.distance=new i(1/0,1/0),this.cache=new i,this.outDirection=new i}resolve(t,e){this.minOverlap=1/0,t instanceof M?this.setCircumferenceAxis(t,e):e instanceof M&&this.setCircumferenceAxis(e,t),this.mergeProjectionAxes(t,e);for(let s=0;s<this.mergedAxes.length;s++){const r=this.mergedAxes[s];if(t instanceof M?this.setCircumferenceVertices(t,r):e instanceof M&&this.setCircumferenceVertices(e,r),this.projectShapeOntoAxis(this.projA,t,r),this.projectShapeOntoAxis(this.projB,e,r),this.currentOverlap=Math.min(this.projA.max,this.projB.max)-Math.max(this.projA.min,this.projB.min),this.currentOverlap<0)return;if(this.invertAxis=!0,this.projA.max>this.projB.max&&this.projA.min<this.projB.min||this.projA.max<this.projB.max&&this.projA.min>this.projB.min){const t=Math.abs(this.projA.min-this.projB.min),e=Math.abs(this.projA.max-this.projB.max);t<e?this.currentOverlap+=t:(this.currentOverlap+=e,i.scale(r,r,-1),this.invertAxis=!1)}this.currentOverlap<this.minOverlap&&(this.minOverlap=this.currentOverlap,this.smallestAxis.copy(r),this.invertAxis&&this.projA.max<this.projB.max&&i.scale(this.smallestAxis,r,-1))}return i.scale(this.outDirection,this.smallestAxis,-1),{direction:this.outDirection,penetration:this.minOverlap}}mergeProjectionAxes(t,e){const i=t.projectionAxes,s=e.projectionAxes;this.mergedAxes.length=0;for(let t=0;t<i.length;t++)this.mergedAxes.push(i[t]);for(let t=0;t<s.length;t++){const e=s[t];let i=!1;for(let t=0;t<this.mergedAxes.length;t++)if(this.mergedAxes[t].equals(e)){i=!0;break}i||this.mergedAxes.push(e)}}projectShapeOntoAxis(t,e,s){t.min=1/0,t.max=-1/0;const r=e.vertices;for(let e=0;e<r.length;e++){const o=i.dot(s,r[e]);o<t.min&&(t.min=o),o>t.max&&(t.max=o)}return t}setCircumferenceAxis(t,e){this.distance.set(1/0,1/0);let s=1/0;const r=e.vertices;for(let e=0;e<r.length;e++){i.subtract(this.cache,r[e],t.position);const o=this.cache.x*this.cache.x+this.cache.y*this.cache.y;o<s&&(s=o,this.distance.copy(this.cache))}i.unit(t.projectionAxes[0],this.distance)}setCircumferenceVertices(t,e){i.add(t.vertices[0],t.position,i.scale(this.cache,i.unit(this.cache,e),-t.radius)),i.add(t.vertices[1],t.position,i.scale(this.cache,i.unit(this.cache,e),t.radius))}};U=F([l(d.CollisionSatResolver)],U);var I=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};t.CollisionRepository=class{constructor(){this.collisions=[]}findCollisionsForCollider(t){return this.collisions.filter((e=>e.localCollider===t))}findCollisionsForColliderAndLayer(t,e){return this.collisions.filter((i=>i.localCollider===t&&i.remoteCollider.layer===e))}findAll(){return this.collisions}persist(t){this.collisions.push(t)}removeAll(){this.collisions=[]}},t.CollisionRepository=I([l(d.CollisionRepository)],t.CollisionRepository);const L=t=>{if(null===t||"object"!=typeof t)return t;if("undefined"!=typeof Node&&t instanceof Node)return t;if("undefined"!=typeof FontFace&&t instanceof FontFace)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((t=>L(t)));if(t instanceof Map){const e=new Map;for(const[i,s]of t)e.set(L(i),L(s));return e}if(t instanceof Set){const e=new Set;for(const i of t)e.add(L(i));return e}const e=Object.getPrototypeOf(t),i=Object.create(e);for(const e of Object.keys(t))i[e]=L(t[e]);return i},j={EntityManager:Symbol.for("EntityManager"),SystemManager:Symbol.for("SystemManager")};var O=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};t.EntityManager=class{constructor(){this.lastEntityId=0,this.lastComponentTypeId=0,this.entities=new Set,this.components=new Map,this.disabledEntities=new Set,this.manuallyDisabledEntities=new Set,this.disabledComponents=new Map,this.parentEntities=new Map,this.childEntities=new Map}createEntity(t,e){const i=this.lastEntityId++;return t&&(this.entities.add(i),t.forEach((t=>this.addComponent(i,t))),e&&this.setParent(i,e)),i}createEntityFromArchetype({components:t,children:e,enabled:i},s){const r=this.lastEntityId++;return this.entities.add(r),this.createComponentsFromArchetype(t,r),s&&this.setParent(r,s),e&&e.forEach((t=>this.createEntityFromArchetype(t,r))),!1===i&&this.disableEntity(r),r}createComponentsFromArchetype(t,e){t.forEach((t=>{let i,s=!0;if("object"==typeof t&&"component"in t&&"enabled"in t&&!1===t.enabled&&(s=!1,t=t.component),"object"==typeof t)i=this.addComponent(e,L(t));else{if("function"!=typeof t)throw new Error("Invalid component type");i=this.addComponent(e,t)}s||this.disableComponent(i)}))}removeEntity(t){var e;this.getChildren(t).forEach((t=>this.removeEntity(t))),this.components.forEach((e=>{e.has(t)&&e.delete(t)})),this.disabledComponents.delete(t),this.disabledEntities.delete(t),this.manuallyDisabledEntities.delete(t);const i=this.getParent(t);i&&(null===(e=this.childEntities.get(i))||void 0===e||e.delete(t)),this.parentEntities.delete(t),this.childEntities.delete(t),this.entities.delete(t)}removeAllEntities(t){const e=t?this.search(t):[];if(e.length>0){const t=new Set(e.map((({entity:t})=>t)));for(const e of this.entities)t.has(e)||this.removeEntity(e)}else this.components.clear(),this.disabledComponents.clear(),this.disabledEntities.clear(),this.manuallyDisabledEntities.clear(),this.lastEntityId=0,this.entities.clear(),this.parentEntities.clear(),this.childEntities.clear()}isEntity(t){return this.entities.has(t)}isEntityEnabled(t){return this.isEntity(t)&&!this.disabledEntities.has(t)}enableEntity(t){this.disabledEntities.has(t)&&(this.disabledEntities.delete(t),this.getChildren(t).forEach((t=>{this.manuallyDisabledEntities.has(t)||this.enableEntity(t)})))}disableEntity(t){this.disabledEntities.has(t)||(this.disabledEntities.add(t),this.getChildren(t).forEach((t=>{this.disabledEntities.has(t)?this.manuallyDisabledEntities.add(t):this.disableEntity(t)})))}disableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.disableEntity(s)}enableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.enableEntity(s)}setParent(t,e){if(!this.isEntity(t)||!this.isEntity(e))throw new Error("Both entities must exist to set a parent-child relationship.");if(this.parentEntities.has(t)){const i=this.parentEntities.get(t);if(i===e)return;this.childEntities.get(i).delete(t)}this.parentEntities.set(t,e),this.childEntities.has(e)||this.childEntities.set(e,new Set),this.childEntities.get(e).add(t)}getParent(t){return this.parentEntities.get(t)}getChildren(t){return Array.from(this.childEntities.get(t)||[])}removeParent(t){const e=this.parentEntities.get(t);e&&(this.parentEntities.delete(t),this.childEntities.get(e).delete(t))}removeChild(t,e){this.parentEntities.get(e)===t&&(this.parentEntities.delete(e),this.childEntities.get(t).delete(e))}addComponent(t,e){var i;const s=this.getComponentTypeId(e),r="object"==typeof e?e:new e;if(this.components.has(s)||this.components.set(s,new Map),this.components.get(s).has(t)){const e=null!==(i=r.constructor.componentName)&&void 0!==i?i:r.constructor.name;throw new Error(`Entity ${t} already has a component of type ${e}`)}return this.components.get(s).set(t,r),r}hasComponent(t,e){return void 0!==this.getComponent(t,e)}getComponent(t,e){var i;return null===(i=this.components.get(this.getComponentTypeId(e)))||void 0===i?void 0:i.get(t)}getComponents(t){const e=[];return this.components.forEach((i=>i.forEach(((i,s)=>{t===s&&e.push(i)})))),e}updateComponentData(t,e,i){const s=this.getComponent(t,e);s&&i(s)}getEntityForComponent(t){const e=this.getComponentTypeId(t);if(this.components.has(e))for(const[i,s]of this.components.get(e))if(s===t)return i}removeComponent(t,e){var i;const s=this.getComponentTypeId("object"==typeof t?t:e),r="number"==typeof t?t:this.getEntityForComponent(t);void 0!==r&&(null===(i=this.components.get(s))||void 0===i?void 0:i.has(r))&&this.components.get(s).delete(r)}isComponentEnabled(t,e){var i,s;const r=this.getComponentTypeId("object"==typeof t?t:e);if("number"==typeof t&&!(null===(i=this.components.get(r))||void 0===i?void 0:i.has(t)))return!1;const o="number"==typeof t?t:this.getEntityForComponent(t);return!(null===(s=this.disabledComponents.get(o))||void 0===s?void 0:s.has(r))}disableComponent(t,e){const i="number"==typeof t?t:this.getEntityForComponent(t),s=this.getComponentTypeId("object"==typeof t?t:e);null!=i&&(this.disabledComponents.has(i)?this.disabledComponents.get(i).has(s)||this.disabledComponents.get(i).add(s):this.disabledComponents.set(i,new Set([s])))}enableComponent(t,e){var i;const s="number"==typeof t?t:this.getEntityForComponent(t),r=this.getComponentTypeId("object"==typeof t?t:e);void 0!==s&&(null===(i=this.disabledComponents.get(s))||void 0===i?void 0:i.has(r))&&this.disabledComponents.get(s).delete(r)}getComponentFromParent(t,e){let i=t;for(;i;){const t=this.getComponent(i,e);if(t)return t;i=this.getParent(i)}}search(t,e,i=!1){const s=[],r=this.getComponentTypeId(t),o="boolean"==typeof e?e:i,n="function"==typeof e?e:void 0;return this.components.has(r)&&this.components.get(r).forEach(((e,i)=>{n&&!n(e,i)||!(o||this.isEntityEnabled(i)&&this.isComponentEnabled(i,t))||s.push({entity:i,component:e})})),s}searchEntitiesByComponents(t){const e=[];let i=!0;for(const s of t){const t=this.getComponentTypeId(s);if(!t||!this.components.has(t))return[];if(i){e.push(...this.components.get(t).keys()),i=!1;continue}const r=new Set(this.components.get(t).keys());e.forEach(((t,i)=>{r.has(t)||e.splice(i,1)}))}return e}searchInChildren(t,e,i=!1){const s=this.getChildren(t);return this.search(e,i).filter((({entity:t})=>s.includes(t)))}getComponentTypeId(t){const e="object"==typeof t?t.constructor.prototype:t.prototype;return void 0===e.__ecs_type_id&&(e.__ecs_type_id=Number(`${++this.lastComponentTypeId}${(1e5*performance.now()).toFixed(0)}`)),e.__ecs_type_id}},t.EntityManager=O([l(j.EntityManager)],t.EntityManager);var k,G=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};t.SystemManager=class{constructor(){this.systems=[]}findSystemIndex(t){return this.systems.findIndex((e=>e[0]instanceof t))}addSystem(t,e){if(this.systems.some((t=>t[0]instanceof t.constructor)))throw new Error(`SystemManager already has an instance of ${t.constructor.name}.`);this.systems.push([t,e,!1,!1])}hasSystem(t){return this.systems.some((e=>e[0]instanceof t))}getSystem(t){const e=this.findSystemIndex(t);return-1!==e?this.systems[e][0]:void 0}groupHasSystems(t){return this.systems.filter((e=>e[1]===t)).length>0}enableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!0===this.systems[e][2])return;const i=this.systems[e];!1===i[3]&&(i[3]=!0,i[0].onCreate&&i[0].onCreate()),i[2]=!0,i[0].onEnabled&&i[0].onEnabled()}disableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!1===this.systems[e][2])return;const i=this.systems[e];i[2]=!1,i[0].onDisabled&&i[0].onDisabled()}setExecutionOrder(t,e){const i=this.findSystemIndex(t);if(-1===i)throw new Error(`Cannot set execution order because ${t.name} is not a system.`);this.systems.splice(e,0,this.systems.splice(i,1)[0])}removeSystem(t){const e=this.findSystemIndex(t);if(-1===e)return;const i=this.systems.splice(e,1)[0][0];i.onDestroy&&i.onDestroy()}disableAllSystems(){this.systems.forEach((t=>{t[2]&&this.disableSystem(t[0].constructor)}))}update(t){this.systems.filter((e=>e[1]===t&&!0===e[2])).forEach((t=>t[0].onUpdate()))}},t.SystemManager=G([l(j.SystemManager)],t.SystemManager),function(t){t.LegacyWebGL="webgl",t.WebGL2="webgl2"}(k||(k={}));class V{constructor(t){if(this.canvas=t,this.contextVersion=this.getContextVersion(),!this.contextVersion)throw new Error("Your browser does not support WebGL.");this.gl=this.canvas.getContext(this.contextVersion)}getContextVersion(){return null!==this.canvas.getContext(k.WebGL2)?k.WebGL2:null!==this.canvas.getContext(k.LegacyWebGL)?k.LegacyWebGL:void 0}}class N{constructor(){this.fontAtlas=new Map}hasFontAtlas(t){return this.fontAtlas.has(this.getId(t))}getFontAtlas(t){return this.fontAtlas.get(this.getId(t))}getOrCreate(t){var e;return null!==(e=this.getFontAtlas(t))&&void 0!==e?e:this.create(t)}create(t){const{font:e,charRanges:i,fontSize:s,spacing:r}=t;this.chars=[];for(let t=0;t<i.length;t+=2)for(let e=i[t];e<=i[t+1];e++)this.chars.push(String.fromCharCode(e));this.font=e instanceof FontFace?e.family:e,this.fontSize=s,this.spacing=r,this.id=this.getId(t);const o=this.renderAtlas();return this.fontAtlas.set(this.id,o),o}getId({font:t,charRanges:e,fontSize:i,spacing:s}){return JSON.stringify({font:t instanceof FontFace?t.family:t,charRanges:e,fontSize:i,spacing:s})}renderAtlas(){const t=new W(this.id,this.fontSize,Math.ceil(Math.sqrt(this.chars.length)),this.spacing),e=t.canvas.getContext("2d");e.clearRect(0,0,t.canvas.width,t.canvas.height),e.textBaseline="top",e.fillStyle="#FFFFFF",e.font=`${this.fontSize}px ${this.font}`;let i=0,s=0;for(let r=0;r<this.chars.length;r++)e.fillText(this.chars[r],i,s),t.glyphs.set(this.chars[r],{id:r,width:e.measureText(this.chars[r]).width}),(i+=this.fontSize+this.spacing)>t.canvas.width-this.fontSize&&(i=0,s+=this.fontSize+this.spacing);return t}}class W{constructor(t,e,i,s){this.id=t,this.fontSize=e,this.gridSize=i,this.spacing=s,this.canvas=document.createElement("canvas"),this.glyphs=new Map,this.canvas.width=this.gridSize*(this.fontSize+this.spacing),this.canvas.height=this.canvas.width}}class H{constructor(t,e){this.gl=t,this.shaderLoader=e}create(t,e){const i=this.gl.createProgram(),s=this.shaderLoader.load(this.gl.VERTEX_SHADER,t),r=this.shaderLoader.load(this.gl.FRAGMENT_SHADER,e);this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);const o=this.gl.LINK_STATUS;if(!this.gl.getProgramParameter(i,o)){const t=this.gl.getProgramInfoLog(i);throw this.gl.deleteProgram(i),new Error(`Unable to initialize the Program: ${t}`)}return i}}class z{constructor(t,e,i){this.gl=t,this.contextVersion=e,this.programFactory=i}loadProgram(){this.program=this.contextVersion===k.WebGL2?this.programFactory.create("#version 300 es\n\nin vec4 positionCoords;\nin vec2 textureCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nout vec2 texCoords;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * positionCoords;\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","#version 300 es\nprecision highp float;\n\nin vec2 texCoords;\n\n// texture, mask and darkness\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nout vec4 fragColor;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n fragColor = vec4(texColor.rgb, u_alpha * texColor.a); \n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < u_numLights; i++) {\n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n fragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n fragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"):this.programFactory.create("precision mediump float;\n\nattribute vec2 positionCoords;\nattribute vec2 textureCoords;\n\nvarying vec2 texCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * vec4(positionCoords, 0, 1);\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","precision mediump float;\n\nvarying vec2 texCoords;\n\n// texture, mask and darkness\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture2D(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n gl_FragColor = vec4(texColor.rgb, u_alpha * texColor.a);\n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < 64; i++) {\n if (u_lights[i].intensity == 0.0) continue; \n \n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n gl_FragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n gl_FragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"),this.positionCoordsAttr=this.gl.getAttribLocation(this.program,"positionCoords"),this.texCoordsAttr=this.gl.getAttribLocation(this.program,"textureCoords"),this.modelMatrixUniform=this.gl.getUniformLocation(this.program,"modelMatrix"),this.projectionMatrixUniform=this.gl.getUniformLocation(this.program,"projectionMatrix"),this.textureMatrixUniform=this.gl.getUniformLocation(this.program,"textureMatrix"),this.renderTextureUniform=this.gl.getUniformLocation(this.program,"u_renderTexture"),this.textureUniform=this.gl.getUniformLocation(this.program,"u_texImage"),this.solidColorUniform=this.gl.getUniformLocation(this.program,"u_solidColor"),this.useTintColorUniform=this.gl.getUniformLocation(this.program,"u_useTintColor"),this.tintColorUniform=this.gl.getUniformLocation(this.program,"u_tintColor"),this.useMaskColorUniform=this.gl.getUniformLocation(this.program,"u_useMaskColor"),this.maskColorUniform=this.gl.getUniformLocation(this.program,"u_maskColor"),this.maskColorMixUniform=this.gl.getUniformLocation(this.program,"u_maskColorMix"),this.alphaUniform=this.gl.getUniformLocation(this.program,"u_alpha"),this.renderLightUniform=this.gl.getUniformLocation(this.program,"u_renderLight"),this.numLightsUniform=this.gl.getUniformLocation(this.program,"u_numLights"),this.gl.useProgram(this.program),this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}class Y{constructor(t){this.gl=t}load(t,e){const i=this.gl.createShader(t);this.gl.shaderSource(i,e),this.gl.compileShader(i);const s=this.gl.COMPILE_STATUS;if(!this.gl.getShaderParameter(i,s)){const t=this.gl.getShaderInfoLog(i);throw this.gl.deleteShader(i),new Error(`Unable to initialize the shader program: ${t}`)}return i}}var X="undefined"!=typeof Float32Array?Float32Array:Array;function $(){var t=new X(16);return X!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function K(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function q(t,e,i){var s,r,o,n,a,h,l,c,d,g,m,u,p=i[0],f=i[1],y=i[2];return e===t?(t[12]=e[0]*p+e[4]*f+e[8]*y+e[12],t[13]=e[1]*p+e[5]*f+e[9]*y+e[13],t[14]=e[2]*p+e[6]*f+e[10]*y+e[14],t[15]=e[3]*p+e[7]*f+e[11]*y+e[15]):(s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],h=e[5],l=e[6],c=e[7],d=e[8],g=e[9],m=e[10],u=e[11],t[0]=s,t[1]=r,t[2]=o,t[3]=n,t[4]=a,t[5]=h,t[6]=l,t[7]=c,t[8]=d,t[9]=g,t[10]=m,t[11]=u,t[12]=s*p+a*f+d*y+e[12],t[13]=r*p+h*f+g*y+e[13],t[14]=o*p+l*f+m*y+e[14],t[15]=n*p+c*f+u*y+e[15]),t}function J(t,e,i){var s=i[0],r=i[1],o=i[2];return t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t[3]=e[3]*s,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function Q(t,e,i){var s=Math.sin(i),r=Math.cos(i),o=e[0],n=e[1],a=e[2],h=e[3],l=e[4],c=e[5],d=e[6],g=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*r+l*s,t[1]=n*r+c*s,t[2]=a*r+d*s,t[3]=h*r+g*s,t[4]=l*r-o*s,t[5]=c*r-n*s,t[6]=d*r-a*s,t[7]=g*r-h*s,t}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});var Z=function(t,e,i,s,r,o,n){var a=1/(e-i),h=1/(s-r),l=1/(o-n);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+i)*a,t[13]=(r+s)*h,t[14]=(n+o)*l,t[15]=1,t};const tt=(t,e,i,s)=>{t=K(t),Z(t,-e.canvas.width/2,e.canvas.width/2,-e.canvas.height/2,e.canvas.height/2,-1,1),J(t,t,[null!=i?i:1,null!=i?i:1,1]),q(t,t,[-s.x,-s.y,0])},et=t=>{const e=/^#?([a-f\d]{2})?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[2],16)/256,g:parseInt(e[3],16)/256,b:parseInt(e[4],16)/256,a:void 0!==e[1]?parseInt(e[1],16)/256:1}:null};class it{constructor(t){this.gl=t}render(t){const e=et(t);this.gl.clearColor(e.r,e.g,e.b,e.a),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}}var st;!function(t){t[t.Sprite=0]="Sprite",t[t.Text=1]="Text",t[t.Tilemap=2]="Tilemap",t[t.Mask=3]="Mask",t[t.Geometric=4]="Geometric",t[t.Video=5]="Video",t[t.Darkness=6]="Darkness"}(st||(st={}));var rt;t.GeometricShape=void 0,(rt=t.GeometricShape||(t.GeometricShape={}))[rt.Polygon=0]="Polygon",rt[rt.Circumference=1]="Circumference",rt[rt.Line=2]="Line";let ot=class{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.linesPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=new Float32Array(n(1,60,1).reduce(((t,e)=>[...t,Math.cos(e*i),Math.sin(e*i)]),[]));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,s,this.gl.STATIC_DRAW)}render(e,i,s){switch(this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),e.shape){case t.GeometricShape.Polygon:this.renderLines(e,i,this.gl.LINE_LOOP);break;case t.GeometricShape.Line:this.renderLines(e,i,this.gl.LINES);break;case t.GeometricShape.Circumference:this.renderCircumference(e,i,s);break;default:return!1}return!0}renderLines(t,e,i){var s;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.linesPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t.vertexModel.reduce(((t,e)=>[...t,e.x,e.y]),[])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:r,g:o,b:n,a:a}=et(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,r,o,n,a),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(i,0,t.vertexModel.length),this.lastShape="polygon"}renderCircumference(t,e,i){i===st.Geometric&&"circumference"===this.lastShape||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),J(this.modelMatrix,this.modelMatrix,[t.radius,t.radius,1]),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:s,g:r,b:o,a:n}=et(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,s,r,o,n),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(this.gl.LINE_LOOP,0,60),this.lastShape="circumference"}};var nt;t.MaskShape=void 0,(nt=t.MaskShape||(t.MaskShape={}))[nt.Rectangle=0]="Rectangle",nt[nt.Circumference=1]="Circumference",nt[nt.Polygon=2]="Polygon";let at=class{constructor(t,e){this.gl=t,this.programManager=e,this.type=st.Mask,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.rectanglePositionBuffer=this.gl.createBuffer(),this.polygonPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=[0,0];for(let t=0;t<=60;t++)s.push(Math.cos(t*i),Math.sin(t*i));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(s),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(e,i,s){return this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),e.shape===t.MaskShape.Rectangle?this.renderRectangle(e,i,s):e.shape===t.MaskShape.Circumference?this.renderCircumference(e,i,s):e.shape===t.MaskShape.Polygon&&this.renderPolygon(e,i,s),this.lastShape=e.shape,!0}renderRectangle(e,i,s){var r,o;s===st.Mask&&this.lastShape===t.MaskShape.Rectangle||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[e.position.x,e.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(r=e.rotation)&&void 0!==r?r:0),J(this.modelMatrix,this.modelMatrix,[e.width,e.height,1]),tt(this.projectionMatrix,this.gl,i.zoom,i.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),e.opacity>=0&&e.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:n,g:a,b:h,a:l}=et(e.color);this.gl.uniform4f(this.programManager.solidColorUniform,n,a,h,l),this.gl.uniform1f(this.programManager.alphaUniform,null!==(o=e.opacity)&&void 0!==o?o:1),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}renderCircumference(e,i,s){var r,o;s===st.Mask&&this.lastShape===t.MaskShape.Circumference||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[e.position.x,e.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(r=e.rotation)&&void 0!==r?r:0),J(this.modelMatrix,this.modelMatrix,[e.radius,e.radius,1]),tt(this.projectionMatrix,this.gl,i.zoom,i.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),e.opacity>=0&&e.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:n,g:a,b:h,a:l}=et(e.color);this.gl.uniform4f(this.programManager.solidColorUniform,n,a,h,l),this.gl.uniform1f(this.programManager.alphaUniform,null!==(o=e.opacity)&&void 0!==o?o:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,62)}renderPolygon(e,i,s){var r,o;s===st.Mask&&this.lastShape===t.MaskShape.Polygon||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.polygonPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(e.vertices.reduce(((t,e)=>[...t,e.x,e.y]),[0,0])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[e.position.x,e.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(r=e.rotation)&&void 0!==r?r:0),tt(this.projectionMatrix,this.gl,i.zoom,i.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),e.opacity>=0&&e.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:n,g:a,b:h,a:l}=et(e.color);this.gl.uniform4f(this.programManager.solidColorUniform,n,a,h,l),this.gl.uniform1f(this.programManager.alphaUniform,null!==(o=e.opacity)&&void 0!==o?o:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,e.vertices.length+1)}},ht=class{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r;i!==st.Darkness&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.width,t.height,1]),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0),this.gl.uniform1i(this.programManager.renderLightUniform,1);const{r:o,g:n,b:a,a:h}=et(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,n,a,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.numLightsUniform,t.lights.length);for(const[i,s]of t.lights.entries()){if(i>=64)break;this.gl.uniform2f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].position`),this.gl.canvas.width/2+(s.position.x-e.position.x)*e.zoom,this.gl.canvas.height/2+(s.position.y-e.position.y)*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].radius`),s.radius*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].smoothMode`),s.smooth?1:0),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].intensity`),Math.max(0,Math.min(1,s.intensity)))}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1i(this.programManager.renderLightUniform,0),!0}},lt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.tiledPosVertices=new Map,this.tiledTexVertices=new Map,this.lastTexture=null,this.isTiled=!1,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.tiledPositionBuffer=this.gl.createBuffer(),this.tiledTextureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW),this.lastDrawMode="sprite"}render(t,e,i){var s,r,o,n;this.isTiled=t.tiled&&(t.tiled.x>1||t.tiled.y>1),this.isTiled||i===st.Sprite&&"sprite"===this.lastDrawMode?this.isTiled&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledPositionVertices(t.tiled),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledTextureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledTextureVertices(t.tiled),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)):(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.lastDrawMode=this.isTiled?"tiled":"sprite",this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontally?-1:1),t.height*(t.flipVertically?-1:1),1]),this.textureMatrix=K(this.textureMatrix),t.slice&&(q(this.textureMatrix,this.textureMatrix,[t.slice.x/t.image.naturalWidth,t.slice.y/t.image.naturalHeight,0]),J(this.textureMatrix,this.textureMatrix,[t.slice.width/t.image.naturalWidth,t.slice.height/t.image.naturalHeight,1])),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromImage(t.image,t.smooth);if(this.lastTexture===a&&i===t.type||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=et(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=et(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(n=t.maskColorMix)&&void 0!==n?n:1)}return this.isTiled?this.gl.drawArrays(this.gl.TRIANGLES,0,t.tiled.x*t.tiled.y*6):this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}getTiledPositionVertices(t){const e=t.toString();if(!this.tiledPosVertices.has(e)){const i=[];for(let e=-t.x/2;e<t.x/2;e++)for(let s=-t.y/2;s<t.y/2;s++)i.push(e,s,e,s+1,e+1,s,e+1,s,e,s+1,e+1,s+1);this.tiledPosVertices.set(e,new Float32Array(i))}return this.tiledPosVertices.get(e)}getTiledTextureVertices(t){const e=t.toString();if(!this.tiledTexVertices.has(e)){const i=[];for(let e=0;e<t.x*t.y;e++)i.push(0,1,0,0,1,1,1,1,0,0,1,0);this.tiledTexVertices.set(e,new Float32Array(i))}return this.tiledTexVertices.get(e)}};var ct;t.TextAlignment=void 0,(ct=t.TextAlignment||(t.TextAlignment={}))[ct.Center=0]="Center",ct[ct.Right=1]="Right",ct[ct.Left=2]="Left";let dt=class{constructor(t,e,s,r){this.gl=t,this.programManager=e,this.textureManager=s,this.fontAtlasFactory=r,this.type=st.Text,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.shadowPosition=new i,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,s,r=!1){var o;if(!t.text)return!1;const n=this.fontAtlasFactory.getOrCreate(Object.assign({font:t.font},t.textureAtlas));if(r||(this.generateTextVertices(n,t),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),t.shadow){const{color:r,offset:o,opacity:n}=t.shadow,a=Object.assign(Object.assign({},t),{color:r,opacity:n,position:i.add(this.shadowPosition,t.position,o)});a.shadow=void 0,this.render(a,e,s,!0),s=st.Text}this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(o=t.rotation)&&void 0!==o?o:0),J(this.modelMatrix,this.modelMatrix,[t.fontSize*(t.flipHorizontally?-1:1),t.fontSize*(t.flipVertically?-1:1),1]),this.textureMatrix=K(this.textureMatrix),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromCanvas(n.id,n.canvas,t.smooth);this.lastTexture===a&&s===st.Text||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.useMaskColorUniform,0),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,t.opacity);const{r:h,g:l,b:c,a:d}=et(t.color);return this.gl.uniform1i(this.programManager.useTintColorUniform,1),this.gl.uniform4f(this.programManager.tintColorUniform,h,l,c,d),this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}generateTextVertices(e,i){this.posVertices=[],this.texVertices=[];const s=this.preProcessText(e,i),r=i.letterSpacing/i.fontSize,o=i.lineHeight/i.fontSize,n=i.boundingBox.height/i.fontSize,a=i.boundingBox.width/i.fontSize;let h=n/2;for(const n of s){const{text:s,width:l}=n;let c=i.alignment===t.TextAlignment.Center?-l/2:i.alignment===t.TextAlignment.Left?-a/2:a/2-l;for(const t of s){const i=e.glyphs.get(t);if(i){const t=i.width/e.fontSize;this.posVertices.push(c,h-1,c+t,h-1,c,h,c,h,c+t,h-1,c+t,h);const s=i.id%e.gridSize*(e.fontSize+e.spacing),o=(i.id/e.gridSize|0)*(e.fontSize+e.spacing),n=s/e.canvas.width,a=o/e.canvas.height,l=(s+i.width)/e.canvas.width,d=(o+e.fontSize)/e.canvas.height;this.texVertices.push(n,d,l,d,n,a,n,a,l,d,l,a),c+=t+r}}c=-a/2,h-=o}}preProcessText(t,{text:e,fontSize:i,letterSpacing:s,lineHeight:r,boundingBox:{width:o,height:n}}){const a=[];s/=i,r/=i,o/=i,n/=i;const h=t.glyphs.get(" ").width/t.fontSize+s;let l=0;const c=e.split("\n");for(const e of c){let i=[],c=0;l+=r;const d=e.split(" ");for(const e of d){if(l>n)return a;const d=0===i.length;let g=0;for(const i of e){const e=t.glyphs.get(i);e&&(g+=e.width/t.fontSize+s)}g-=s,d||(g+=h),d&&g>=o?(a.push({width:g,text:e}),l+=r):c+g===o?(i.push(e),a.push({width:c+g,text:i.join(" ")}),i=[],c=0,l+=r):c+g>o?(a.push({width:c,text:i.join(" ")}),i=[e],c=g-h,l+=r):(c+=g,i.push(e))}i.length>0&&a.push({width:c,text:i.join(" ")})}return a}};var gt;t.TilemapOrientation=void 0,(gt=t.TilemapOrientation||(t.TilemapOrientation={}))[gt.Center=0]="Center",gt[gt.RightUp=1]="RightUp",gt[gt.RightDown=2]="RightDown",gt[gt.RightCenter=3]="RightCenter";let mt=class{constructor(t,e,s){this.gl=t,this.programManager=e,this.textureManager=s,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.tileset={width:0,tileWidth:0,tileHeight:0,texMargin:new i,texSpacing:new i,texWidth:0,texHeight:0,texCorrection:new i},this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,i){var s,r,o,n;if(0===t.tiles.reduce(((t,e)=>t+e),0))return!1;if(this.processTileset(t),this.generateVertices(t),0===this.posVertices.length)return!1;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.tilemap.tileWidth*(t.flipHorizontal?-1:1),t.tilemap.tileHeight*(t.flipVertical?-1:1),1]),this.textureMatrix=K(this.textureMatrix),J(this.textureMatrix,this.textureMatrix,[this.tileset.tileWidth/t.tileset.image.naturalWidth,this.tileset.tileHeight/t.tileset.image.naturalHeight,1]),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromImage(t.tileset.image,t.smooth);if(this.lastTexture===a&&i===st.Tilemap||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=et(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=et(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(n=t.maskColorMix)&&void 0!==n?n:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}processTileset({tileset:t}){var e,s,r,o,n,a,h;t.margin=null!==(e=t.margin)&&void 0!==e?e:new i,t.spacing=null!==(s=t.spacing)&&void 0!==s?s:new i,t.correction=null!==(r=t.correction)&&void 0!==r?r:new i,this.tileset.width=t.width,this.tileset.tileWidth=t.tileWidth+(null!==(o=t.margin.x)&&void 0!==o?o:0)+(null!==(n=t.spacing.x)&&void 0!==n?n:0),this.tileset.tileHeight=t.tileHeight+(null!==(a=t.margin.y)&&void 0!==a?a:0)+(null!==(h=t.spacing.y)&&void 0!==h?h:0),this.tileset.texMargin.set(t.margin.x/this.tileset.tileWidth,t.margin.y/this.tileset.tileHeight),this.tileset.texSpacing.set(t.spacing.x/this.tileset.tileWidth,t.spacing.y/this.tileset.tileHeight),this.tileset.texCorrection.set(t.correction.x/this.tileset.tileWidth,t.correction.y/this.tileset.tileHeight),this.tileset.texWidth=1-this.tileset.texMargin.x-this.tileset.texSpacing.x-2*this.tileset.texCorrection.x,this.tileset.texHeight=1-this.tileset.texMargin.y-this.tileset.texSpacing.y-2*this.tileset.texCorrection.y}generateVertices({tiles:t,tilemap:e}){this.posVertices=[],this.texVertices=[];const i=Math.floor(t.length/e.width);t.forEach(((t,s)=>{if(0===t)return;const r=s%e.width-e.width/2,o=i/2-Math.floor(s/e.width);this.posVertices.push(r,o-1,r+1,o-1,r,o,r,o,r+1,o-1,r+1,o);const n=(t-1)%this.tileset.width+this.tileset.texMargin.x+this.tileset.texCorrection.x,a=Math.floor((t-1)/this.tileset.width)+this.tileset.texMargin.y+this.tileset.texCorrection.y;this.texVertices.push(n,a+this.tileset.texHeight,n+this.tileset.texWidth,a+this.tileset.texHeight,n,a,n,a,n+this.tileset.texWidth,a+this.tileset.texHeight,n+this.tileset.texWidth,a)}))}},ut=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.lastTexture=null,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r,o,n;i!==st.Video&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontal?-1:1),t.height*(t.flipVertical?-1:1),1]),this.textureMatrix=K(this.textureMatrix),t.slice&&(q(this.textureMatrix,this.textureMatrix,[t.slice.x/t.video.videoWidth,t.slice.y/t.video.videoHeight,0]),J(this.textureMatrix,this.textureMatrix,[t.slice.width/t.video.videoWidth,t.slice.height/t.video.videoHeight,1])),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromVideo(t.video);if(this.lastTexture===a&&i===st.Video||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),t.video.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t.video),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=et(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=et(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(n=t.maskColorMix)&&void 0!==n?n:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}};class pt{constructor(t){this.gl=t}createFromImage(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),t.naturalWidth?this.createFromSource(t,i,e):t.addEventListener("load",(()=>this.createFromSource(t,i,e))),i}createFromCanvas(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),this.createFromSource(t,i,e),i}createPixelTexture(){const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,1,1,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,new Uint8Array([0,0,0,255])),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),t}createFromSource(t,e,i=!1){this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),i?(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR)):(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST)),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}}const ft=(t,e)=>`${e?"_smooth_":""}${t}`;class yt{constructor(t){this.textureFactory=t,this.textures=new Map}getOrCreateTextureFromImage(t,e=!1){var i;return null!==(i=this.textures.get(ft(t.src,e)))&&void 0!==i?i:this.createTextureFromImage(t,e)}createTextureFromImage(t,e=!1){const i=this.textureFactory.createFromImage(t,e);return this.textures.set(ft(t.src,e),i),i}getOrCreateTextureFromCanvas(t,e,i=!1){var s;return null!==(s=this.textures.get(ft(t,i)))&&void 0!==s?s:this.createTextureFromCanvas(t,e,i)}createTextureFromCanvas(t,e,i=!1){const s=this.textureFactory.createFromCanvas(e,i);return this.textures.set(ft(t,i),s),s}getOrCreateTextureFromVideo(t){var e;return null!==(e=this.textures.get(t.src))&&void 0!==e?e:this.createTextureFromVideo(t)}createTextureFromVideo(t){const e=this.textureFactory.createPixelTexture();return this.textures.set(t.src,e),e}}const xt={CanvasElement:Symbol.for("CanvasElement"),WebGLManager:Symbol.for("WebGLManager")};var Mt=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n},vt=function(t,e){return function(i,s){e(i,s,t)}};let bt=class{constructor(t){this.renderers=new Map;const e=new V(t),i=e.gl,s=e.contextVersion,r=new z(i,s,new H(i,new Y(i))),o=new yt(new pt(i)),n=new N;this.renderers.set(st.Sprite,new lt(i,r,o)),this.renderers.set(st.Text,new dt(i,r,o,n)),this.renderers.set(st.Tilemap,new mt(i,r,o)),this.renderers.set(st.Geometric,new ot(i,r)),this.renderers.set(st.Mask,new at(i,r)),this.renderers.set(st.Video,new ut(i,r,o)),this.renderers.set(st.Darkness,new ht(i,r)),this.canvasColorRenderer=new it(i),r.loadProgram()}render(t,e){this.renderers.get(t.type).render(t,e,this.lastRender)&&(this.lastRender=t.type)}renderCanvasColor(t){this.canvasColorRenderer.render(t)}};bt=Mt([l(xt.WebGLManager),vt(0,c(xt.CanvasElement))],bt);const St=Object.assign(Object.assign(Object.assign({AssetManager:Symbol.for("AssetManager"),CreateSystemService:Symbol.for("CreateSystemService"),GameConfig:Symbol.for("GameConfig"),InputManager:Symbol.for("InputManager"),LoopManager:Symbol.for("LoopManager"),RenderManager:Symbol.for("RenderManager"),SceneManager:Symbol.for("SceneManager"),TimeManager:Symbol.for("TimeManager")},d),j),xt);function Ct(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n}function At(t,e){return function(i,s){e(i,s,t)}}function wt(t,e,i,s){return new(i||(i=Promise))((function(r,o){function n(t){try{h(s.next(t))}catch(t){o(t)}}function a(t){try{h(s.throw(t))}catch(t){o(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,a)}h((s=s.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class Rt{constructor(){this.buttons=new Map,this.axes=new Map,this._dpadAxes=new i,this._leftStickAxes=new i,this._rightStickAxes=new i}get dpadAxes(){return this._dpadAxes.set(this.dpadRight?1:this.dpadLeft?-1:0,this.dpadUp?1:this.dpadDown?-1:0),this._dpadAxes}get leftStickAxes(){return this._leftStickAxes.set(this.leftStickHorizontal,this.leftStickVertical),this._leftStickAxes}get rightStickAxes(){return this._rightStickAxes.set(this.rightStickHorizontal,this.rightStickVertical),this._rightStickAxes}get dpadUp(){var t;return null!==(t=this.buttons.get(12))&&void 0!==t&&t}get dpadDown(){var t;return null!==(t=this.buttons.get(13))&&void 0!==t&&t}get dpadLeft(){var t;return null!==(t=this.buttons.get(14))&&void 0!==t&&t}get dpadRight(){var t;return null!==(t=this.buttons.get(15))&&void 0!==t&&t}get bottomFace(){var t;return null!==(t=this.buttons.get(0))&&void 0!==t&&t}get rightFace(){var t;return null!==(t=this.buttons.get(1))&&void 0!==t&&t}get leftFace(){var t;return null!==(t=this.buttons.get(2))&&void 0!==t&&t}get topFace(){var t;return null!==(t=this.buttons.get(3))&&void 0!==t&&t}get leftShoulder(){var t;return null!==(t=this.buttons.get(4))&&void 0!==t&&t}get rightShoulder(){var t;return null!==(t=this.buttons.get(5))&&void 0!==t&&t}get leftTrigger(){var t;return null!==(t=this.buttons.get(6))&&void 0!==t&&t}get rightTrigger(){var t;return null!==(t=this.buttons.get(7))&&void 0!==t&&t}get back(){var t;return null!==(t=this.buttons.get(8))&&void 0!==t&&t}get start(){var t;return null!==(t=this.buttons.get(9))&&void 0!==t&&t}get leftStickButton(){var t;return null!==(t=this.buttons.get(10))&&void 0!==t&&t}get rightStickButton(){var t;return null!==(t=this.buttons.get(11))&&void 0!==t&&t}get leftStickHorizontal(){var t;return null!==(t=this.axes.get(0))&&void 0!==t?t:0}get leftStickVertical(){var t;return-(null!==(t=this.axes.get(1))&&void 0!==t?t:0)}get rightStickHorizontal(){var t;return null!==(t=this.axes.get(2))&&void 0!==t?t:0}get rightStickVertical(){var t;return-(null!==(t=this.axes.get(3))&&void 0!==t?t:0)}get anyButtonPressed(){var t;return null!==(t=Array.from(this.buttons.values()).find((t=>t)))&&void 0!==t&&t}vibrate(t=200,e=.2,i=.2,s=0){this.vibrationInput={duration:t,weakMagnitude:e,startDelay:s,strongMagnitude:i}}}class Et{constructor(){this.pressedKeys=[]}isPressed(t){return this.pressedKeys.includes(t)}orPressed(t){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)}andPressed(t){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)}isPressedReturn(t,e,i){return this.pressedKeys.includes(t)?e:i}orPressedReturn(t,e,i){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)?e:i}andPressedReturn(t,e,i){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)?e:i}}class _t{constructor(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new i,this.hasMoved=!1,this.wheelScroll=new i}}class Tt{constructor(){this.touching=!1,this.interactions=[]}}t.InputManager=class{constructor(){this.keyboard=new Et,this.mouse=new _t,this.touchScreen=new Tt,this.gamepads=[]}},t.InputManager=Ct([l(St.InputManager)],t.InputManager);const Pt=[60,120,180,240];var Bt;t.TimeManager=class{get deltaTime(){return this.unscaledDeltaTime*this.timeScale}get physicsDeltaTime(){return this.unscaledPhysicsDeltaTime*this.timeScale}get renderDeltaTime(){return this.browserDeltaTime*this.timeScale}get unscaledRenderDeltaTime(){return this.browserDeltaTime}constructor({physicsFramerate:t},e){if(this.entityManager=e,this.timeScale=1,this.browserDeltaTime=0,this.unscaledDeltaTime=0,this.unscaledPhysicsDeltaTime=0,this.maxDeltaTime=1/30,this.thenForGame=0,this.thenForPhysics=0,this.thenForRender=0,this.lastIntervalId=0,this.intervals=new Map,t&&!Pt.includes(t))throw new Error(`Invalid Physics frame rate. Allowed: [${Pt.join(", ")}]`);this.fixedGameFramerate=60,this.fixedGameDeltaTime=parseFloat((1/this.fixedGameFramerate).toFixed(6)),this.fixedPhysicsFramerate=null!=t?t:180,this.fixedPhysicsDeltaTime=parseFloat((1/this.fixedPhysicsFramerate).toFixed(6))}updateForRender(t){this.browserDeltaTime=Math.min(Math.max(0,t-this.thenForRender),this.maxDeltaTime),this.thenForRender=t}updateForGame(t){this.unscaledDeltaTime=Math.min(Math.max(this.fixedGameDeltaTime,t-this.thenForGame),this.maxDeltaTime),this.thenForGame=t}updateForPhysics(t){this.unscaledPhysicsDeltaTime=Math.min(Math.max(0,t-this.thenForPhysics),this.maxDeltaTime),this.thenForPhysics=t}updateIntervals(){if(0!==this.intervals.size)for(const[t,e]of this.intervals)this.intervalHealthCheck(e)?(e.executeImmediately?(e.timer=e.delay,e.executeImmediately=!1):e.timer+=1e3*(e.useTimeScale?this.deltaTime:this.unscaledDeltaTime),e.timer>=e.delay&&(e.callback(),e.times&&--e.times<=0?this.clearInterval(t):e.timer-=e.delay)):this.clearInterval(t)}intervalHealthCheck(t){return!(t.entityRef&&!this.entityManager.isEntityEnabled(t.entityRef))&&!(t.componentRef&&!this.entityManager.isComponentEnabled(t.componentRef))}setInterval({callback:t,delay:e,times:i,executeImmediately:s,entityRef:r,componentRef:o,useTimeScale:n=!0}){const a=++this.lastIntervalId;return this.intervals.set(a,{callback:t,delay:e,times:i,executeImmediately:s,entityRef:r,componentRef:o,timer:0,useTimeScale:n}),a}clearInterval(t){this.intervals.delete(t)}clearAllIntervals(){this.intervals.clear()}},t.TimeManager=Ct([l(St.TimeManager),At(0,c(St.GameConfig)),At(1,c(St.EntityManager))],t.TimeManager),function(t){t[t.Image=0]="Image",t[t.Audio=1]="Audio",t[t.Font=2]="Font",t[t.Video=3]="Video",t[t.Json=4]="Json"}(Bt||(Bt={})),t.AssetManager=class{constructor(){this.assets=[]}getAssetsLoaded(){return this.assets.reduce(((t,e)=>t&&e.loaded),!0)}loadImage(t,e){if(this.getImage(t))return this.getImage(t);const i=new Image;i.crossOrigin="",i.src=t;const s=this.createAsset(t,Bt.Image,i,e),r=()=>s.loaded=!0;return i.complete?r():i.addEventListener("load",r),i}loadAudio(t,e){if(this.getAudio(t))return this.getAudio(t);const i=new Audio;i.src=t;const s=this.createAsset(t,Bt.Audio,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}loadFont(t,e){if(this.getFont(t))return this.getFont(t);const i=new FontFace(t,`url(${e})`),s=this.createAsset(e,Bt.Font,i);return s.family=t,document.fonts.add(i),i.load().then((()=>s.loaded=!0)),i}loadVideo(t,e){if(this.getVideo(t))return this.getVideo(t);const i=document.createElement("video");i.playsInline=!0,i.src=t;const s=this.createAsset(t,Bt.Video,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}loadJson(t,e){return wt(this,void 0,void 0,(function*(){if(this.getJson(t))return this.getJson(t);const i=this.createAsset(t,Bt.Json,null,e),s=yield fetch(t),r=yield s.json();return i.loaded=!0,i.element=r,r}))}getImage(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Image&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getAudio(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Audio&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getFont(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Font&&e.family===t)))||void 0===e?void 0:e.element}getVideo(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Video&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getJson(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Json&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}createAsset(t,e,i,s){this.deleteAssetIfExists({url:t,name:s});const r={type:e,url:t,element:i,loaded:!1,name:s};return this.assets.push(r),r}deleteAssetIfExists({url:t,name:e}){const i=this.assets.findIndex((i=>i.url===t||void 0!==i.name&&i.name===e));-1!==i&&this.assets.splice(i,1)}},t.AssetManager=Ct([l(St.AssetManager)],t.AssetManager);class Dt{get playing(){return"playing"===this.state}get paused(){return"paused"===this.state}get stopped(){return"stopped"===this.state}constructor(t){this.action=void 0,this.stopOnSceneTransition=!0,this.fixedToTimeScale=!1,this.loop=!1,this.state="stopped",this.volume=1,this._currentAudioSource=void 0,this._playPromisePendind=!1,this._playAfterUserInput=!1,Object.assign(this,t)}play(t){t&&(this.audioSource=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}Dt.componentName="AudioPlayer";const Ft={AudioPlayerSystem:Symbol.for("AudioPlayerSystem"),ButtonSystem:Symbol.for("ButtonSystem"),TiledWrapperSystem:Symbol.for("TiledWrapperSystem"),TilemapPreProcessingSystem:Symbol.for("TilemapPreProcessingSystem"),TransformSystem:Symbol.for("TransformSystem"),GamepadSystem:Symbol.for("GamepadSystem"),KeyboardSystem:Symbol.for("KeyboardSystem"),MouseSystem:Symbol.for("MouseSystem"),TouchScreenSystem:Symbol.for("TouchScreenSystem"),UpdateBallColliderShapeSystem:Symbol.for("UpdateBallColliderShapeSystem"),UpdateBoxColliderShapeSystem:Symbol.for("UpdateBoxColliderShapeSystem"),UpdateEdgeColliderShapeSystem:Symbol.for("UpdateEdgeColliderShapeSystem"),UpdatePolygonColliderShapeSystem:Symbol.for("UpdatePolygonColliderShapeSystem"),UpdateTilemapColliderShapeSystem:Symbol.for("UpdateTilemapColliderShapeSystem"),UpdateCollidersAfterRepositionSystem:Symbol.for("UpdateCollidersAfterRepositionSystem"),ApplyRepositionSystem:Symbol.for("ApplyRepositionSystem"),ApplyVelocitySystem:Symbol.for("ApplyVelocitySystem"),ResolveCollisionSystem:Symbol.for("ResolveCollisionSystem"),AnimatorSystem:Symbol.for("AnimatorSystem"),CameraSystem:Symbol.for("CameraSystem"),ClearScreenSystem:Symbol.for("ClearScreenSystem"),CullingSystem:Symbol.for("CullingSystem"),MaskRendererSystem:Symbol.for("MaskRendererSystem"),RenderSystem:Symbol.for("RenderSystem"),DarknessLightRendererSystem:Symbol.for("DarknessLightRendererSystem"),SpriteRendererSystem:Symbol.for("SpriteRendererSystem"),GeometricRendererSystem:Symbol.for("GeometricRendererSystem"),TextRendererSystem:Symbol.for("TextRendererSystem"),TilemapRendererSystem:Symbol.for("TilemapRendererSystem"),VideoRendererSystem:Symbol.for("VideoRendererSystem"),DebugColliderRenderSystem:Symbol.for("DebugColliderRenderSystem"),DebugMousePositionSystem:Symbol.for("DebugMousePositionSystem"),DebugTextRendererSystem:Symbol.for("DebugTextRendererSystem")},Ut=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let It=class{constructor(t,e,i){this.entityManager=t,this.inputManager=e,this.timeManager=i,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{Ut.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(Dt).forEach((({component:{audioSource:t,playing:e}})=>{t&&"string"!=typeof t&&(document.hidden?t.pause():!document.hidden&&e&&t.play(),this.canPlay=!document.hidden)}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,Ut.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}checkGamepad(){return this.canPlay=this.inputManager.gamepads.some((t=>t.anyButtonPressed)),this.canPlay}onUpdate(){(this.canPlay||this.checkGamepad())&&this.entityManager.search(Dt).forEach((({component:t})=>{t.audioSource&&"string"!=typeof t.audioSource&&t.audioSource.duration&&(t._playAfterUserInput&&(t._playAfterUserInput=!1,t.action="play"),t.audioSource!==t._currentAudioSource&&(t._currentAudioSource&&(t._currentAudioSource.pause(),t._currentAudioSource.currentTime=0),t._currentAudioSource=t.audioSource,t.audioSource.currentTime=0,t.state="stopped"),t.audioSource.loop=t.loop,t.audioSource.volume=t.volume,"play"!==t.action||"playing"===t.state||t._playPromisePendind?"pause"===t.action&&"playing"===t.state?(t.audioSource.pause(),t.state="paused"):"stop"!==t.action||t.audioSource.paused&&0===t.audioSource.currentTime?"playing"===t.state&&t.audioSource.paused&&(t.state="stopped"):(t.audioSource.pause(),t.audioSource.currentTime=0,t.state="stopped"):(t._playPromisePendind=!0,t.audioSource.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,t.audioSource.play().then((()=>{t._playPromisePendind=!1,t.state="playing"})).catch((()=>{t._playAfterUserInput=!0,t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),t.action=void 0)}))}onDisabled(){this.entityManager.search(Dt).forEach((({component:{audioSource:t,stopOnSceneTransition:e}})=>{t&&"string"!=typeof t&&e&&(t.pause(),t.currentTime=0)}))}onDestroy(){this.onDisabled()}};var Lt;It=Ct([l(Ft.AudioPlayerSystem),At(0,c(St.EntityManager)),At(1,c(St.InputManager)),At(2,c(St.TimeManager))],It),function(t){t[t.GameLogic=0]="GameLogic",t[t.GamePhysics=1]="GamePhysics",t[t.GamePreRender=2]="GamePreRender",t[t.Physics=3]="Physics",t[t.PreGameLogic=4]="PreGameLogic",t[t.Render=5]="Render",t[t.Transform=6]="Transform"}(Lt||(Lt={}));const jt=(t,e)=>{t.prototype.__system_group||(t.prototype.__system_group=e)};class Ot{constructor(t){this.position=new i,this.scale=new i(1,1),this.rotation=0,this.ignoreParentPosition=!1,this.ignoreParentScale=!1,this.ignoreParentRotation=!1,this.localPosition=new i,this.localScale=new i(1,1),this.localRotation=0,this._awake=!1,this._parent=void 0,Object.assign(this,t)}}Ot.componentName="Transform";const kt="Default",Gt="Debug";class Vt{constructor(t){this.layers=[kt],this.zoom=1,this.depth=0,this.debug=!1,this._renderData={position:new i,depth:0,zoom:1,layers:[]},Object.assign(this,t)}}Vt.componentName="Camera";class Nt{constructor(t){this.fixedToTimeScale=!1,this.layer=kt,this.loop=!1,this.offset=new i,this.playing=!1,this.rotation=0,this.volume=1,this._currentVideoSrc=void 0,this._playPromisePendind=!1,this._renderData={type:st.Video,height:void 0,layer:void 0,position:new i,video:void 0,width:void 0,flipHorizontal:void 0,flipVertical:void 0,maskColor:void 0,maskColorMix:void 0,opacity:void 0,rotation:void 0,slice:void 0,tintColor:void 0},Object.assign(this,t)}play(t){t&&(this.video=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}Nt.componentName="VideoRenderer";const Wt=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let Ht=class{constructor(t,e,s,r,o){this.entityManager=t,this.renderManager=e,this.timeManager=s,this.assetManager=r,this.inputManager=o,this.scaledOffset=new i,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{Wt.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(Nt).forEach((({component:{video:t,playing:e}})=>{t&&"string"!=typeof t&&(document.hidden?t.pause():!document.hidden&&e&&t.play(),this.canPlay=!document.hidden)}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,Wt.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}checkGamepad(){return this.canPlay=this.inputManager.gamepads.some((t=>t.anyButtonPressed)),this.canPlay}onUpdate(){(this.canPlay||this.checkGamepad())&&this.entityManager.search(Nt).forEach((({entity:t,component:e})=>{var s,r;const o=this.entityManager.getComponent(t,Ot);if(!o)throw new Error("VideoRenderer component needs a Transform");if("string"==typeof e.video&&(e.video=this.assetManager.getVideo(e.video),!e.video))throw new Error(`Asset ${e.video} not found`);e.video&&e.video.duration&&(this.checkVideoState(e),this.scaledOffset.set(e.offset.x*o.localScale.x,e.offset.y*o.localScale.y),i.add(e._renderData.position,o.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.video=e.video,e._renderData.width=(null!==(s=e.width)&&void 0!==s?s:e.video.videoWidth)*Math.abs(o.localScale.x),e._renderData.height=(null!==(r=e.height)&&void 0!==r?r:e.video.videoHeight)*Math.abs(o.localScale.y),e._renderData.rotation=o.localRotation+e.rotation,e._renderData.slice=e.slice,e._renderData.flipHorizontal=e.flipHorizontally,e._renderData.flipVertical=e.flipVertically,e._renderData.opacity=e.opacity,e._renderData.maskColor=e.maskColor,e._renderData.maskColorMix=e.maskColorMix,e._renderData.tintColor=e.tintColor,0!==o.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,o),this.renderManager.addRenderData(e._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}checkVideoState(t){const{video:e,action:i,loop:s,volume:r}=t;"string"!=typeof e&&(e.src!==t._currentVideoSrc&&(t._currentVideoSrc=e.src,t.playing=!1,e.currentTime=0),e.loop=s,e.volume=r,e.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,"play"!==i||t.playing||t._playPromisePendind||!this.canPlay||(t._playPromisePendind=!0,e.play().then((()=>{t._playPromisePendind=!1,t.playing=!0})).catch((()=>{t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),"play"===i&&e.ended&&(t.action="stop",t.playing=!1),"stop"===i&&e.currentTime>0&&(e.pause(),e.currentTime=0,t.playing=!1),"pause"!==i||e.paused||e.pause())}onDisabled(){this.entityManager.search(Nt).forEach((({component:t})=>{t.video&&"string"!=typeof t.video&&(t.video.pause(),t.video.currentTime=0)}))}onDestroy(){this.onDisabled()}};Ht=Ct([l(Ft.VideoRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.TimeManager)),At(3,c(St.AssetManager)),At(4,c(St.InputManager))],Ht),t.SceneManager=class{constructor(t,e,i,s,r){this.systemManager=t,this.systemFactory=e,this.entityManager=i,this.assetManager=s,this.timeManager=r,this.scenes=new Map,this._loadingScene=!1,this._sceneLoadedThisFrame=!1,this.preserveEntitiesWithComponent=void 0}addScene(t,e,i=!1){const s=new t(this.entityManager,this.assetManager);this.scenes.set(e,s),i&&(this.openingSceneName=e)}loadScene(t,e){if(!this.scenes.has(t))throw new Error(`Invalid scene name: '${t}'`);this.sceneNameToBeLoaded=t,this.preserveEntitiesWithComponent=e}loadOpeningScene(){if(!this.openingSceneName)throw new Error("There is no opening scene");this.sceneNameToBeLoaded=this.openingSceneName}get loadingScene(){return this._loadingScene}get sceneLoadedThisFrame(){return this._sceneLoadedThisFrame}update(){this._sceneLoadedThisFrame=!1,this.sceneNameToBeLoaded&&(this.currentSceneName&&this.destroyCurrentScene(),this.currentSceneName=this.sceneNameToBeLoaded,this.sceneNameToBeLoaded=void 0,this.scenes.get(this.currentSceneName).loadAssets(),this.scenes.get(this.currentSceneName).registerSystems(),this._loadingScene=!0),this._loadingScene&&this.assetManager.getAssetsLoaded()&&(this._loadingScene=!1,this._sceneLoadedThisFrame=!0,this.scenes.get(this.currentSceneName).createEntities(),this.systemManager.update(Lt.Transform),this.systemManager.update(Lt.PreGameLogic),this.scenes.get(this.currentSceneName).systems.forEach(((t,e)=>{this.systemFactory.createSystemIfNotExists(t),this.systemManager.enableSystem(t),this.systemManager.setExecutionOrder(t,e)})))}destroyCurrentScene(){this.systemManager.disableSystem(It),this.systemManager.disableSystem(Ht),this.scenes.get(this.currentSceneName).systems.forEach((t=>this.systemManager.disableSystem(t))),this.entityManager.removeAllEntities(this.preserveEntitiesWithComponent),this.timeManager.clearAllIntervals(),this.systemManager.enableSystem(It),this.systemManager.enableSystem(Ht)}},t.SceneManager=Ct([l(St.SceneManager),At(0,c(St.SystemManager)),At(1,c(St.CreateSystemService)),At(2,c(St.EntityManager)),At(3,c(St.AssetManager)),At(4,c(St.TimeManager))],t.SceneManager);class zt{constructor(t){this.width=0,this.height=0,this.radius=0,this.touchEnabled=!0,this.offset=new i,this.pressed=!1,this.mouseOver=!1,Object.assign(this,t)}}var Yt;zt.componentName="Button",t.ButtonShape=void 0,(Yt=t.ButtonShape||(t.ButtonShape={}))[Yt.Rectangle=0]="Rectangle",Yt[Yt.Circumference=1]="Circumference";let Xt=class{constructor(t,e){this.entityManager=t,this.scaled={position:new i,width:0,height:0,radius:0},this.distance=new i,this.pressedLastFrame=!1,this.mouse=e.mouse,this.touchScreen=e.touchScreen}onUpdate(){this.entityManager.search(zt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("Button component needs a Transform");this.pressedLastFrame=e.pressed,e.pressed=!1,this.scale(e,i),e.mouseOver=this.isMouseOverButton(e),e.pressed=e.mouseOver&&this.mouse.leftButtonPressed,e.touchEnabled&&this.touchScreen.touching&&(this.resolveTouchAndRectangle(e),this.resolveTouchAndCircumference(e)),e.onClick&&!this.pressedLastFrame&&e.pressed&&e.onClick(),e.onPressed&&e.pressed&&e.onPressed()}))}scale(t,{localPosition:e,localScale:i}){this.scaled.width=t.width*i.x,this.scaled.height=t.height*i.y,this.scaled.position.x=e.x+t.offset.x*i.x,this.scaled.position.y=e.y+t.offset.y*i.y,this.scaled.radius=t.radius*Math.max(Math.abs(i.x),Math.abs(i.y))}isMouseOverButton(t){return this.isMouseOverRectangleButton(t)||this.isMouseOverCircumferenceButton(t)}isMouseOverRectangleButton(e){return e.shape===t.ButtonShape.Rectangle&&(a(this.mouse.positionInViewport.x,this.scaled.position.x-this.scaled.width/2,this.scaled.position.x+this.scaled.width/2)&&a(this.mouse.positionInViewport.y,this.scaled.position.y-this.scaled.height/2,this.scaled.position.y+this.scaled.height/2))}isMouseOverCircumferenceButton(e){return e.shape===t.ButtonShape.Circumference&&(i.subtract(this.distance,this.scaled.position,this.mouse.positionInViewport),this.distance.magnitude<=this.scaled.radius)}resolveTouchAndRectangle(e){if(e.shape===t.ButtonShape.Rectangle)for(const{positionInViewport:t,radius:i}of this.touchScreen.interactions){if(e.pressed)return;e.pressed=this.scaled.position.x+this.scaled.width/2>=t.x-i.x&&this.scaled.position.x-this.scaled.width/2<=t.x+i.x&&this.scaled.position.y+this.scaled.height/2>=t.y-i.y&&this.scaled.position.y-this.scaled.height/2<=t.y+i.y}}resolveTouchAndCircumference(e){if(e.shape===t.ButtonShape.Circumference)for(const{positionInViewport:t,radius:s}of this.touchScreen.interactions){if(e.pressed)return;i.subtract(this.distance,this.scaled.position,t),e.pressed=this.distance.magnitude<=this.scaled.radius+Math.max(s.x,s.y)}}};Xt=Ct([l(Ft.ButtonSystem),At(0,c(St.EntityManager)),At(1,c(St.InputManager))],Xt);class $t{constructor(t){Object.assign(this,t)}}$t.componentName="TiledWrapper";class Kt{constructor(t){this.layer=kt,this.tileset=void 0,this.data=[],this.chunks=[],this.width=0,this.height=0,this.tileWidth=void 0,this.tileHeight=void 0,this.tintColor=void 0,this.opacity=1,this.smooth=!1,this._processed=!1,this._renderData=[],Object.assign(this,t)}}Kt.componentName="TilemapRenderer";let qt=class{constructor(t,e){this.entityManager=t,this.assetManager=e}onUpdate(){this.entityManager.search($t).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Kt);if(!i)return;if("string"==typeof e.tilemap&&(e.tilemap=this.assetManager.getJson(e.tilemap),!e.tilemap))throw new Error(`Tilemap ${e.tilemap} not found`);const s=e.tilemap.layers.find((t=>t.name===e.layerToRender&&"tilelayer"===t.type));s&&(e.tilemap.infinite?i.chunks=s.chunks:i.data=s.data,i.width=e.tilemap.width)}))}};qt=Ct([l(Ft.TiledWrapperSystem),At(0,c(St.EntityManager)),At(1,c(St.AssetManager))],qt);const Jt=16;let Qt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Kt).forEach((({component:t})=>{var e,i;t._processed||(t.chunks&&t.chunks.length>0?this.chunksToData(t):t.data&&t.data.length>0&&this.dataToChunks(t),t.tileWidth=null!==(e=t.tileWidth)&&void 0!==e?e:t.tileset.tileWidth,t.tileHeight=null!==(i=t.tileHeight)&&void 0!==i?i:t.tileset.tileHeight,t._processed=!0)}))}dataToChunks(t){t.height=Math.ceil(t.data.length/t.width);const e=Math.ceil(t.width/Jt),i=Math.ceil(t.height/Jt);for(let s=0;s<i;s++)for(let i=0;i<e;i++){const e={x:i*Jt,y:s*Jt,width:Jt,height:Jt,data:[]};for(let i=0;i<e.width*e.height;i++){const s=e.x+i%e.width,r=t.width*(e.y+Math.floor(i/e.width));e.data[i]=s<t.width&&r<t.height*t.width?t.data[r+s]:0}t.chunks.push(e)}}chunksToData(t){t.data=[],t.chunks.forEach((e=>e.data.forEach(((i,s)=>{t.data[t.width*(e.y+Math.floor(s/e.width))+e.x+s%e.width]=i})))),t.height=Math.ceil(t.data.length/t.width)}};Qt=Ct([l(Ft.TilemapPreProcessingSystem),At(0,c(St.EntityManager))],Qt);let Zt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Ot).sort(((t,e)=>this.getBranchLength(t.entity)-this.getBranchLength(e.entity))).forEach((({component:t,entity:e})=>{const s=this.entityManager.getParent(e);s&&this.entityManager.isEntityEnabled(s)&&this.entityManager.isComponentEnabled(s,Ot)?(t._parent||(t._parent=this.entityManager.getComponent(s,Ot),t._awake&&!t.ignoreParentPosition&&i.subtract(t.position,t.localPosition,t._parent.position)),t._parent?this.translateChild(t):this.updateTransform(t)):(t._parent&&this.removeParent(t),this.updateTransform(t)),t._awake=!0}))}getBranchLength(t){const e=this.entityManager.getParent(t);return e?1+this.getBranchLength(e):0}removeParent(t){t._parent=void 0,t.position.copy(t.localPosition),t.rotation=t.localRotation}updateTransform(t){t.localPosition.copy(t.position),t.localScale.copy(t.scale),t.localRotation=t.rotation,t._parent=void 0}translateChild(t){t.localRotation=t.rotation+(t.ignoreParentRotation?0:t._parent.localRotation),t.localScale.x=t.scale.x*(t.ignoreParentScale?1:t._parent.scale.x),t.localScale.y=t.scale.y*(t.ignoreParentScale?1:t._parent.scale.y);const e=t.position.magnitude,i=Math.atan2(t.position.y,t.position.x)+(t.ignoreParentRotation?0:t._parent.localRotation);t.localPosition.set(e*Math.cos(i)+(t.ignoreParentPosition?0:t._parent.localPosition.x),e*Math.sin(i)+(t.ignoreParentPosition?0:t._parent.localPosition.y))}};Zt=Ct([l(Ft.TransformSystem),At(0,c(St.EntityManager))],Zt);let te=class{constructor(t){this.inputManager=t,this.gamepads=new Map,this.eventHandler=t=>{"gamepadconnected"===t.type?this.gamepadConnected(t.gamepad):"gamepaddisconnected"===t.type&&this.gamepadDisconected(t.gamepad)},window.addEventListener("gamepadconnected",this.eventHandler),window.addEventListener("gamepaddisconnected",this.eventHandler)}gamepadConnected(t){this.gamepads.set(t.index,t),this.inputManager.gamepads[t.index]||(this.inputManager.gamepads[t.index]=new Rt,this.inputManager.gamepads[t.index].index=t.index),this.inputManager.gamepads[t.index].id=t.id,this.inputManager.gamepads[t.index].connected=!0}gamepadDisconected(t){this.gamepads.delete(t.index),this.inputManager.gamepads[t.index].connected=!1}onUpdate(){for(const t of this.getGamepadsFromBrowser())t&&(!1===this.gamepads.has(t.index)?this.gamepadConnected(t):this.gamepads.set(t.index,t));this.gamepads.forEach((t=>{const e=this.inputManager.gamepads[t.index];t.buttons.forEach(((t,i)=>e.buttons.set(i,t.pressed))),t.axes.forEach(((t,i)=>e.axes.set(i,t))),e.vibrationInput&&(t.vibrationActuator.playEffect(t.vibrationActuator.type,{duration:e.vibrationInput.duration,weakMagnitude:e.vibrationInput.weakMagnitude,strongMagnitude:e.vibrationInput.strongMagnitude,startDelay:e.vibrationInput.startDelay}).catch((()=>e.vibrating=!1)).finally((()=>e.vibrating=!1)),e.vibrating=!0,e.vibrationInput=void 0)}))}getGamepadsFromBrowser(){return navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads:[]}};te=Ct([l(Ft.GamepadSystem),At(0,c(St.InputManager))],te);let ee=class{constructor(t,{keyboard:e}){this.pressedKeys=[],this.eventHandler=t=>{"keydown"!==t.type||this.pressedKeys.includes(t.code)||this.pressedKeys.push(t.code),"keyup"===t.type&&this.pressedKeys.includes(t.code)&&this.pressedKeys.splice(this.pressedKeys.indexOf(t.code),1)},this.keyboard=e,t.addEventListener("keydown",this.eventHandler),t.addEventListener("keyup",this.eventHandler),t.addEventListener("focusout",(()=>this.pressedKeys=[]))}onUpdate(){this.keyboard.pressedKeys=[...this.pressedKeys]}};ee=Ct([l(Ft.KeyboardSystem),At(0,c(St.CanvasElement)),At(1,c(St.InputManager))],ee);let ie=class{constructor(t,{mouse:e}){this.canvas=t,this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new i,this.lastPositionInViewport=new i,this.mouse=e,this.canvas.addEventListener("mousemove",(t=>this.updatePosition(t))),this.canvas.addEventListener("mousedown",(t=>this.updateButtonDown(t))),this.canvas.addEventListener("mouseup",(t=>this.updateButtonUp(t))),this.canvas.addEventListener("wheel",(t=>this.handleWheelEvent(t))),this.canvas.addEventListener("focusout",(()=>this.onFocusOut()))}updateButtonDown(t){this.canvas.focus(),t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0===t.button||this.leftButtonPressed,this.scrollButtonPressed=1===t.button||this.scrollButtonPressed,this.rightButtonPressed=2===t.button||this.rightButtonPressed}updateButtonUp(t){t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0!==t.button&&this.leftButtonPressed,this.scrollButtonPressed=1!==t.button&&this.scrollButtonPressed,this.rightButtonPressed=2!==t.button&&this.rightButtonPressed}updatePosition(t){t.preventDefault(),t.stopPropagation(),this.positionInViewport.set(t.offsetX/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-t.offsetY/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2)}handleWheelEvent(t){t.preventDefault(),t.stopPropagation(),this.wheelEvent=t}onFocusOut(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1}onUpdate(){this.mouse.leftButtonPressed=this.leftButtonPressed,this.mouse.rightButtonPressed=this.rightButtonPressed,this.mouse.scrollButtonPressed=this.scrollButtonPressed,this.mouse.positionInViewport.copy(this.positionInViewport),this.positionInViewport.equals(this.lastPositionInViewport)?this.mouse.hasMoved=!1:(this.mouse.hasMoved=!0,this.lastPositionInViewport.copy(this.positionInViewport)),this.wheelEvent?(this.mouse.wheelScroll.set(this.wheelEvent.deltaX,this.wheelEvent.deltaY),this.wheelEvent=void 0):this.mouse.wheelScroll.set(0,0)}};ie=Ct([l(Ft.MouseSystem),At(0,c(St.CanvasElement)),At(1,c(St.InputManager))],ie);let se=class{constructor(t,{touchScreen:e}){this.canvas=t,this.touching=!1,this.interactions=[],this.eventHandler=t=>{"touchstart"===t.type&&(this.touching=!0,this.updatePosition(t)),"touchmove"===t.type&&this.updatePosition(t),"touchend"!==t.type&&"touchcancel"!==t.type||(this.touching=!1)},this.touchScreen=e,this.canvas.addEventListener("touchstart",this.eventHandler),this.canvas.addEventListener("touchend",this.eventHandler),this.canvas.addEventListener("touchcancel",this.eventHandler),this.canvas.addEventListener("touchmove",this.eventHandler)}updatePosition(t){if(t.preventDefault(),t.stopPropagation(),this.interactions=[],0!==t.targetTouches.length)for(let e=0;e<t.targetTouches.length;e++)this.interactions[e]={positionInViewport:new i((t.targetTouches[e].clientX-this.canvas.offsetLeft)/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-(t.targetTouches[e].clientY-this.canvas.offsetTop)/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2),radius:new i(t.targetTouches[e].radiusX,t.targetTouches[e].radiusY)}}onUpdate(){this.touchScreen.touching=this.touching,this.touchScreen.interactions=[...this.touchScreen.interactions]}};se=Ct([l(Ft.TouchScreenSystem),At(0,c(St.CanvasElement)),At(1,c(St.InputManager))],se);class re{constructor(t){this.animations=new Map,this.speed=1,this.reset=!1,this.playing=!1,this.currentFrame=0,this.currentTime=0,this.ignoreTimeScale=!1,this._currentAnimation=void 0,this._assetsReady=!1,Object.assign(this,t)}}re.componentName="Animator";class oe{constructor(t){this.layer=kt,this.smooth=!1,this.offset=new i,this.flipHorizontally=!1,this.flipVertically=!1,this.rotation=0,this.opacity=1,this.scale=new i(1,1),this._renderData={type:st.Sprite,position:new i,layer:void 0,image:void 0,width:void 0,height:void 0},Object.assign(this,t)}}oe.componentName="SpriteRenderer";let ne=class{constructor(t,e,i){this.entityManager=t,this.timeManager=e,this.assetManager=i}onUpdate(){this.entityManager.search(re).forEach((({entity:t,component:e})=>{if(this.processAssets(e),this.reset(e),this.animation=e.animations.get(e.animation),!this.animation)return;this.play(e),e._currentAnimation=e.animation;const i=this.entityManager.getComponent(t,oe);i&&this.renderSprite(e,i)}))}processAssets(t){t._assetsReady||(t.animations.forEach((t=>{if("string"==typeof t.image){if(t.image=this.assetManager.getImage(t.image),!t.image)throw new Error(`Asset ${t.image} not found`)}else Array.isArray(t.image)&&(t.image=t.image.map((t=>{if("string"==typeof t){const e=this.assetManager.getImage(t);if(!e)throw new Error(`Asset ${t} not found`);return e}return t})))})),t._assetsReady=!0)}reset(t){t.reset&&(t.currentFrame=0,t.currentTime=0,t.playing=void 0!==t.animation,t.reset=!1)}play(t){t.animation!==t._currentAnimation&&(t._currentAnimation=t.animation,t.currentFrame=0,t.currentTime=0,t.playing=!0),t.playing&&(t.currentTime>=1/this.animation.fps*(t.currentFrame+1)&&(t.currentFrame===this.animation.frames.length-1?this.animation.loop?(t.currentFrame=0,t.currentTime=0):t.playing=!1:t.currentFrame++),t.currentTime+=(t.ignoreTimeScale?this.timeManager.unscaledRenderDeltaTime:this.timeManager.renderDeltaTime)*t.speed)}renderSprite(t,e){if(Array.isArray(this.animation.image))e.image=this.animation.image[t.currentFrame];else{if("string"==typeof this.animation.image)return;const i=this.animation.frames[t.currentFrame],s=Math.floor(this.animation.image.naturalWidth/this.animation.slice.size.x);e.image=this.animation.image,e.slice={x:i%s*this.animation.slice.size.x+this.animation.slice.offset.x,y:Math.floor(i/s)*this.animation.slice.size.y+this.animation.slice.offset.y,width:this.animation.slice.size.x-this.animation.slice.padding.y,height:this.animation.slice.size.y-this.animation.slice.padding.y}}}};ne=Ct([l(Ft.AnimatorSystem),At(0,c(St.EntityManager)),At(1,c(St.TimeManager)),At(2,c(St.AssetManager))],ne);let ae=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){this.entityManager.search(Vt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("Camera component needs a Transform");e._renderData.position.copy(i.localPosition),e._renderData.layers=[...e.layers],e._renderData.depth=e.depth,e._renderData.zoom=e.zoom,e.debug&&e._renderData.layers.push(Gt),this.renderManager.addCameraData(e._renderData)}))}};ae=Ct([l(Ft.CameraSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],ae);let he=class{constructor(t,e){this.webGLManager=t,this.gameConfig=e}onUpdate(){this.webGLManager.renderCanvasColor(this.gameConfig.canvasColor)}};he=Ct([l(Ft.ClearScreenSystem),At(0,c(St.WebGLManager)),At(1,c(St.GameConfig))],he);class le{constructor(t){this.radius=0,this.offset=new i,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}le.componentName="BallCollider";class ce{constructor(t){this.layer="",this.physics=!0,this.width=0,this.height=0,this.offset=new i,this.rotation=0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}ce.componentName="BoxCollider";class de{constructor(t){this.vertexModel=[],this.offset=new i,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}de.componentName="EdgeCollider";class ge{constructor(t){this.vertexModel=[],this.offset=new i,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}ge.componentName="PolygonCollider";class me{constructor(t){this.composite=!0,this.layer="",this.ignoreCollisionsWithLayers=[],this.offset=new i,this.physics=!0,this.shapes=[],Object.assign(this,t)}}me.componentName="TilemapCollider";let ue=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.gameConfig=i}onUpdate(){var e;(null===(e=this.gameConfig.debug)||void 0===e?void 0:e.colliders)&&[le,ce,ge,de,me].forEach((e=>this.entityManager.search(e).forEach((({component:e})=>e.shapes.forEach((e=>{const s={type:st.Geometric,position:new i,layer:Gt,color:this.gameConfig.debug.collidersColor,shape:void 0,radius:void 0,rotation:void 0,vertexModel:void 0};e instanceof x?this.gameConfig.collisions.collisionMethod===t.CollisionMethods.SAT?(s.shape=e.vertices.length>2?t.GeometricShape.Polygon:t.GeometricShape.Line,s.vertexModel=e.vertices):this.gameConfig.collisions.collisionMethod===t.CollisionMethods.AABB&&(s.shape=t.GeometricShape.Polygon,s.vertexModel=[new i(e.boundingBox.x,e.boundingBox.y),new i(e.boundingBox.x,e.boundingBox.y1),new i(e.boundingBox.x1,e.boundingBox.y1),new i(e.boundingBox.x1,e.boundingBox.y)]):e instanceof M&&(s.shape=t.GeometricShape.Circumference,s.position.copy(e.position),s.radius=e.radius),this.renderManager.addRenderData(s)}))))))}};ue=Ct([l(Ft.DebugColliderRenderSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.GameConfig))],ue);let pe=class{constructor(t,e){this.renderManager=t,this.canvas=e,this.viewport={x:0,x1:0,y:0,y1:0},this.object={x:0,x1:0,y:0,y1:0},this.culledRenderData=[]}onUpdate(){this.culledRenderData=[],this.renderManager.getCameraData().forEach((t=>{this.setViewport(t),this.renderManager.getRenderData().filter((e=>t.layers.includes(e.layer))).forEach((t=>{this.isInViewPort(t)&&(t.type===st.Tilemap&&this.applyCullingInTiles(t),this.culledRenderData.push(t))}))})),this.renderManager.setRenderData(this.culledRenderData)}isInViewPort(t){switch(t.type){case st.Video:case st.Darkness:case st.Sprite:this.setObjectForResizeable(t);break;case st.Mask:this.setObjectForMask(t);break;case st.Geometric:this.setObjectForGeometric(t);break;case st.Text:this.setObjectForText(t);break;case st.Tilemap:this.setObjectForTilemap(t)}return this.viewport.x1>=this.object.x&&this.viewport.x<=this.object.x1&&this.viewport.y1>=this.object.y&&this.viewport.y<=this.object.y1}setViewport({position:t,zoom:e}){this.viewport.x=t.x-this.canvas.width/e/2,this.viewport.x1=t.x+this.canvas.width/e/2,this.viewport.y=t.y-this.canvas.height/e/2,this.viewport.y1=t.y+this.canvas.height/e/2}setObjectForResizeable({position:t,width:e,height:i,rotation:s=0,tiled:r}){const o=Math.abs(Math.sin(s)),n=Math.abs(Math.cos(s));r&&(e*=r.x,i*=r.y);const a=o*i+n*e,h=o*e+n*i;this.object.x=t.x-a/2,this.object.x1=t.x+a/2,this.object.y=t.y-h/2,this.object.y1=t.y+h/2}setObjectForText({position:t,text:e,fontSize:i,lineHeight:s,letterSpacing:r,rotation:o}){const n=e.split("\n").reduce(((t,e)=>Math.max(t,e.length)),0)*(i+(null!=r?r:0))*2,a=e.split("\n").length*(null!=s?s:i);this.setObjectForResizeable({position:t,width:n,height:a,rotation:o})}setObjectForGeometric({position:e,vertexModel:i,shape:s,radius:r}){s===t.GeometricShape.Circumference?(this.object.x=e.x-r,this.object.y=e.y-r,this.object.x1=e.x+r,this.object.y1=e.y+r):(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,i.forEach((t=>{this.object.x=Math.min(t.x+e.x,this.object.x),this.object.y=Math.min(t.y+e.y,this.object.y),this.object.x1=Math.max(t.x+e.x,this.object.x1),this.object.y1=Math.max(t.y+e.y,this.object.y1)})))}setObjectForMask({position:e,vertices:i,shape:s,radius:r,rotation:o,width:n,height:a}){s===t.MaskShape.Circumference?(this.object.x=e.x-r,this.object.y=e.y-r,this.object.x1=e.x+r,this.object.y1=e.y+r):s===t.MaskShape.Polygon?(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,i.forEach((t=>{this.object.x=Math.min(t.x+e.x,this.object.x),this.object.y=Math.min(t.y+e.y,this.object.y),this.object.x1=Math.max(t.x+e.x,this.object.x1),this.object.y1=Math.max(t.y+e.y,this.object.y1)}))):this.setObjectForResizeable({position:e,width:n,height:a,rotation:o})}setObjectForTilemap(t){t.tilemap.height=Math.ceil(t.tiles.length/t.tilemap.width),this.setObjectForResizeable({position:t.position,width:t.tilemap.width*t.tilemap.tileWidth,height:t.tilemap.height*t.tilemap.tileHeight,rotation:t.rotation})}applyCullingInTiles(t){const{tiles:e,tilemap:{width:i,tileWidth:s,tileHeight:r}}=t;t.tiles=e.map(((t,e)=>this.viewport.x1>=this.object.x+e%i*s&&this.viewport.x<=this.object.x+e%i*s+s&&this.viewport.y1>=this.object.y1-((e/i|0)*r+r)&&this.viewport.y<=this.object.y1-(e/i|0)*r?t:0))}};pe=Ct([l(Ft.CullingSystem),At(0,c(St.RenderManager)),At(1,c(St.CanvasElement))],pe);class fe{constructor(t){this.width=0,this.height=0,this.radius=0,this.vertexModel=[],this.color="#000000",this.offset=new i,this.rotation=0,this.opacity=1,this.layer=kt,this._renderData={type:st.Mask,color:void 0,height:void 0,vertices:[],layer:void 0,opacity:void 0,position:new i,radius:void 0,rotation:void 0,shape:void 0,width:void 0},Object.assign(this,t)}}fe.componentName="MaskRenderer";let ye=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new i}onUpdate(){this.entityManager.search(fe).forEach((({entity:e,component:s})=>{const r=this.entityManager.getComponent(e,Ot);if(!r)throw new Error("MaskRenderer component needs a Transform");this.scaledOffset.set(s.offset.x*r.localScale.x,s.offset.y*r.localScale.y),i.add(s._renderData.position,r.localPosition,this.scaledOffset),s._renderData.width=s.width*Math.abs(r.localScale.x),s._renderData.height=s.height*Math.abs(r.localScale.y),s._renderData.rotation=r.localRotation+s.rotation,s._renderData.color=s.color,s._renderData.layer=s.layer,s._renderData.opacity=s.opacity,s._renderData.radius=s.radius*Math.max(Math.abs(r.localScale.x),Math.abs(r.localScale.y)),s._renderData.shape=s.shape,s.shape===t.MaskShape.Polygon&&(s._renderData.vertices.length!==s.vertexModel.length&&(s._renderData.vertices=s.vertexModel.map((()=>new i))),s.vertexModel.forEach(((t,e)=>s._renderData.vertices[e].set(t.x*r.localScale.x,t.y*r.localScale.y))),0!==r.localRotation&&s._renderData.vertices.forEach((t=>t.set(t.x*Math.cos(r.localRotation)-t.y*Math.sin(r.localRotation),t.x*Math.sin(r.localRotation)+t.y*Math.cos(r.localRotation))))),0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(s._renderData,r),this.renderManager.addRenderData(s._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};ye=Ct([l(Ft.MaskRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],ye);let xe=class{constructor(t){this.renderManager=t}onUpdate(){this.renderManager.render(),this.renderManager.removeCameraData(),this.renderManager.removeRenderData()}};xe=Ct([l(Ft.RenderSystem),At(0,c(St.RenderManager))],xe);class Me{constructor(t){this.radius=0,this.smooth=!1,this.layer=kt,this.intensity=1,this._boundingBox=new s,Object.assign(this,t)}}Me.componentName="LightRenderer";class ve{constructor(t){this.width=0,this.height=0,this.color="#000000",this.opacity=1,this.layer=kt,this._boundingBox=new s,this._renderData={type:st.Darkness,layer:void 0,color:void 0,opacity:void 0,width:void 0,height:void 0,position:void 0,rotation:void 0,lights:[]},Object.assign(this,t)}}ve.componentName="DarknessRenderer";let be=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){const t=this.entityManager.search(Me);t.forEach((({entity:t,component:e})=>this.updateLightRendererBoundingBox(t,e))),this.entityManager.search(ve).forEach((({entity:e,component:i})=>{this.updatDarknessRendererBoundingBox(e,i),i._renderData.layer=i.layer,i._renderData.color=i.color,i._renderData.opacity=i.opacity,i._renderData.width=i._boundingBox.width,i._renderData.height=i._boundingBox.height,i._renderData.position=i._boundingBox.center,i._renderData.rotation=0,i._renderData.lights=[],i._renderData.lights=t.filter((({component:t})=>t.layer===i.layer&&t._boundingBox.intersects(i._boundingBox))).map((({component:{_boundingBox:t,smooth:e,intensity:i}})=>({position:t.center,radius:t.width/2,smooth:e,intensity:i}))),this.renderManager.addRenderData(i._renderData)}))}updateLightRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("LightRenderer component needs a Transform");const s=e.radius*Math.abs(Math.max(i.localScale.x,i.localScale.y));e._boundingBox.set(i.localPosition.x-s,i.localPosition.y-s,2*s,2*s)}updatDarknessRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("DarknessRenderer component needs a Transform");const s=e.width*Math.abs(i.localScale.x),r=e.height*Math.abs(i.localScale.y);e._boundingBox.set(i.localPosition.x-s/2,i.localPosition.y-r/2,s,r)}};be=Ct([l(Ft.DarknessLightRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],be);class Se{constructor(e){this.shape=t.GeometricShape.Polygon,this.color="#FFFFFF",this.layer=kt,this.vertexModel=[],this.radius=0,this.offset=new i,this.rotation=0,this._renderData={type:st.Geometric,position:new i,layer:kt,color:"#FFFFFF",shape:t.GeometricShape.Polygon,vertexModel:[],rotation:0,radius:0},Object.assign(this,e)}}Se.componentName="GeometricRenderer";let Ce=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new i}onUpdate(){this.entityManager.search(Se).forEach((({entity:e,component:s})=>{const r=this.entityManager.getComponent(e,Ot);if(!r)throw new Error("GeometricRenderer component needs a Transform");if(!this.isValidGeometry(s))return;this.scaledOffset.set(s.offset.x*r.localScale.x,s.offset.y*r.localScale.y),i.add(s._renderData.position,r.localPosition,this.scaledOffset),s._renderData.layer=s.layer,s._renderData.color=s.color,s._renderData.shape=s.shape,s._renderData.rotation=r.localRotation+s.rotation,0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(s._renderData,r);const o=r.localScale.x,n=r.localScale.y;s.shape===t.GeometricShape.Circumference?(s._renderData.radius=s.radius*Math.max(Math.abs(o),Math.abs(n)),s._renderData.vertexModel.length=0):(this.ensureVertexModelLength(s,s.vertexModel.length),s.vertexModel.forEach(((t,e)=>s._renderData.vertexModel[e].set(t.x*o,t.y*n)))),this.renderManager.addRenderData(s._renderData)}))}isValidGeometry(e){switch(e.shape){case t.GeometricShape.Circumference:return e.radius>0;case t.GeometricShape.Polygon:return e.vertexModel.length>=3;case t.GeometricShape.Line:return e.vertexModel.length>=2&&e.vertexModel.length%2==0;default:return!1}}ensureVertexModelLength(t,e){const s=t._renderData.vertexModel;for(;s.length<e;)s.push(new i);s.length=e}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};Ce=Ct([l(Ft.GeometricRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],Ce);let Ae=class{constructor(t,e,s){this.entityManager=t,this.renderManager=e,this.assetManager=s,this.scaledOffset=new i}onUpdate(){this.entityManager.search(oe).forEach((({component:t,entity:e})=>{var s,r,o,n,a,h;const l=this.entityManager.getComponent(e,Ot);if(!l)throw new Error("SpriteRenderer component needs a Transform");if("string"==typeof t.image&&(t.image=this.assetManager.getImage(t.image),!t.image))throw new Error(`Asset ${t.image} not found`);t.image&&t.image.complete&&(this.scaledOffset.set(t.offset.x*l.localScale.x,t.offset.y*l.localScale.y),i.add(t._renderData.position,l.localPosition,this.scaledOffset),t._renderData.width=(null!==(o=null!==(s=t.width)&&void 0!==s?s:null===(r=t.slice)||void 0===r?void 0:r.width)&&void 0!==o?o:t.image.naturalWidth)*Math.abs(t.scale.x*l.localScale.x),t._renderData.height=(null!==(h=null!==(n=t.height)&&void 0!==n?n:null===(a=t.slice)||void 0===a?void 0:a.height)&&void 0!==h?h:t.image.naturalHeight)*Math.abs(t.scale.y*l.localScale.y),t._renderData.flipHorizontally=t.flipHorizontally!==l.scale.x<0,t._renderData.flipVertically=t.flipVertically!==l.scale.y<0,t._renderData.rotation=l.localRotation+t.rotation,0!==l.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(t._renderData,l),t._renderData.image=t.image,t._renderData.layer=t.layer,t._renderData.maskColor=t.maskColor,t._renderData.maskColorMix=t.maskColorMix,t._renderData.opacity=t.opacity,t._renderData.slice=t.slice,t._renderData.smooth=t.smooth,t._renderData.tintColor=t.tintColor,t._renderData.tiled=t.tiled,this.renderManager.addRenderData(t._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};Ae=Ct([l(Ft.SpriteRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.AssetManager))],Ae);const we={charRanges:[32,126,161,255],fontSize:64,spacing:8};class Re{constructor(e){this.color="#000000",this.flipHorizontally=!1,this.flipVertically=!1,this.font="Arial",this.fontSize=16,this.height=16,this.layer=kt,this.letterSpacing=0,this.lineHeight=void 0,this.offset=new i,this.opacity=1,this.alignment=t.TextAlignment.Center,this.rotation=0,this.shadow=void 0,this.smooth=!1,this.text="Hello World!",this.textureAtlas=Object.assign({},we),this.width=192,this._renderData={color:void 0,flipHorizontally:!1,flipVertically:!1,font:void 0,fontSize:void 0,layer:void 0,letterSpacing:void 0,lineHeight:void 0,opacity:void 0,position:new i,rotation:void 0,shadow:void 0,smooth:void 0,text:void 0,textureAtlas:Object.assign({},we),type:st.Text,boundingBox:{width:0,height:0},alignment:void 0},Object.assign(this,e)}}Re.componentName="TextRenderer";let Ee=class{constructor(t,e,s){this.entityManager=t,this.renderManager=e,this.assetManager=s,this.scaledOffset=new i}onUpdate(){this.entityManager.search(Re).forEach((({entity:t,component:e})=>{var s;const r=this.entityManager.getComponent(t,Ot);if(!r)throw new Error("TextRenderer component needs a Transform");if("string"==typeof e.font){const t=this.assetManager.getFont(e.font);t&&(e.font=t)}if(0===e.text.length||e.font instanceof FontFace&&"loaded"!==e.font.status)return;this.scaledOffset.set(e.offset.x*r.localScale.x,e.offset.y*r.localScale.y),i.add(e._renderData.position,r.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.font=e.font,e._renderData.fontSize=e.fontSize,e._renderData.text=e.text,e._renderData.color=e.color,e._renderData.lineHeight=null!==(s=e.lineHeight)&&void 0!==s?s:e.fontSize,e._renderData.letterSpacing=e.letterSpacing,e._renderData.smooth=e.smooth,e._renderData.rotation=r.localRotation+e.rotation,e._renderData.opacity=e.opacity,e._renderData.boundingBox={width:e.width,height:e.height},e._renderData.alignment=e.alignment;const{charRanges:o,fontSize:n,spacing:a}=e.textureAtlas;o&&(e._renderData.textureAtlas.charRanges=e.textureAtlas.charRanges),n&&(e._renderData.textureAtlas.fontSize=e.textureAtlas.fontSize),a&&(e._renderData.textureAtlas.spacing=e.textureAtlas.spacing),e._renderData.flipHorizontally=e.flipHorizontally,e._renderData.flipVertically=e.flipVertically,e._renderData.shadow=e.shadow,0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,r),this.renderManager.addRenderData(e._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};Ee=Ct([l(Ft.TextRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.AssetManager))],Ee);let _e=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.assetManager=i}onUpdate(){this.entityManager.search(Kt).forEach((({entity:e,component:s})=>{const r=this.entityManager.getComponent(e,Ot);if(!r)throw new Error("TilemapRenderer component needs a Transform");if("string"==typeof s.tileset.image&&(s.tileset.image=this.assetManager.getImage(s.tileset.image),!s.tileset.image))throw new Error(`Asset ${s.tileset.image} not found`);s._processed&&s.tileset.image&&s.tileset.image.complete&&s.chunks.forEach(((e,o)=>{s._renderData[o]||(s._renderData[o]=Te());const n=s._renderData[o];n.type=st.Tilemap,n.orientation=t.TilemapOrientation.Center,n.position=new i,n.layer=s.layer,n.tilemap.width=e.width,n.tilemap.height=Math.ceil(s.data.length/e.width),n.tilemap.tileWidth=s.tileWidth*Math.abs(r.localScale.x),n.tilemap.tileHeight=s.tileHeight*Math.abs(r.localScale.y),n.tilemap.realWidth=n.tilemap.width*n.tilemap.tileWidth,n.tilemap.realHeight=n.tilemap.height*n.tilemap.tileHeight,n.tiles=e.data,n.tileset=s.tileset,n.opacity=s.opacity,n.rotation=r.localRotation,n.tintColor=s.tintColor,n.smooth=s.smooth,n.maskColor=s.maskColor,n.maskColorMix=s.maskColorMix,n.position.x=r.localPosition.x+(e.x-s.width/2+e.width/2)*n.tilemap.tileWidth,n.position.y=r.localPosition.y+(s.height/2-e.y-e.height/2)*n.tilemap.tileHeight,this.renderManager.addRenderData(n)}))}))}};_e=Ct([l(Ft.TilemapRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.AssetManager))],_e);const Te=()=>({type:st.Tilemap,layer:void 0,position:new i,tilemap:{height:void 0,realHeight:void 0,realWidth:void 0,tileHeight:void 0,tileWidth:void 0,width:void 0},tiles:void 0,tileset:void 0});var Pe;t.RigidBodyType=void 0,(Pe=t.RigidBodyType||(t.RigidBodyType={}))[Pe.Dynamic=0]="Dynamic",Pe[Pe.Kinematic=1]="Kinematic",Pe[Pe.Static=2]="Static";class Be{constructor(e){this.type=t.RigidBodyType.Dynamic,this.velocity=new i,this.gravity=0,this.acceleration=new i,Object.assign(this,e)}}Be.componentName="RigidBody";let De=class{constructor(e,s,r){this.entityManager=e,this.timeManager=s,this.transformSystem=r,this.types=new Set([t.RigidBodyType.Dynamic,t.RigidBodyType.Kinematic]),this.displacement=new i,this.totalAcceleration=new i,this.scaledAcceleration=new i,this.scaledVelocity=new i}onUpdate(){this.entityManager.search(Be).filter((({component:{type:t}})=>this.types.has(t))).forEach((({component:{velocity:e,acceleration:s,gravity:r,type:o},entity:n})=>{const{position:a}=this.entityManager.getComponent(n,Ot);o===t.RigidBodyType.Dynamic?(this.totalAcceleration.y=s.y-r,this.totalAcceleration.x=s.x):this.totalAcceleration.copy(s),i.add(e,e,i.scale(this.scaledAcceleration,this.totalAcceleration,this.timeManager.physicsDeltaTime)),i.add(a,a,i.add(this.displacement,i.scale(this.scaledVelocity,e,this.timeManager.physicsDeltaTime),i.scale(this.scaledAcceleration,this.totalAcceleration,.5*Math.pow(this.timeManager.physicsDeltaTime,2))))})),this.transformSystem.onUpdate()}};De=Ct([l(Ft.ApplyVelocitySystem),At(0,c(St.EntityManager)),At(1,c(St.TimeManager)),At(2,c(Ft.TransformSystem))],De);class Fe{constructor(){this.auxMin=new i,this.auxMax=new i,this.auxScaledOffset=new i}updatePositionAndVertices(t,e,i){this.translatePosition(t,e,i),t instanceof x?(this.auxAngle=t.rotation+i.localRotation,t.vertexModel.forEach(((e,s)=>t.vertices[s].set(e.x*i.localScale.x,e.y*i.localScale.y))),t.vertices.forEach((e=>e.set(e.x*Math.cos(this.auxAngle)-e.y*Math.sin(this.auxAngle)+t.position.x,e.x*Math.sin(this.auxAngle)+e.y*Math.cos(this.auxAngle)+t.position.y)))):t instanceof M&&(t.radius*=Math.max(Math.abs(i.localScale.x),Math.abs(i.localScale.y)))}translatePosition(t,e,{localPosition:s,localScale:r,localRotation:o}){if(this.auxScaledOffset.set(e.x*r.x,e.y*r.y),0!==o){const e=Math.atan2(this.auxScaledOffset.y,this.auxScaledOffset.x)+o,i=this.auxScaledOffset.magnitude;t.position.set(s.x+i*Math.cos(e),s.y+i*Math.sin(e))}else i.add(t.position,s,this.auxScaledOffset)}updateBoundingBox(t){t instanceof M?this.updateCircumferenceBoundingBox(t):t instanceof x&&this.updatePolygonBoundingBox(t)}updateCircumferenceBoundingBox(t){t.boundingBox.set(t.position.x-t.radius,t.position.y-t.radius,2*t.radius,2*t.radius)}updatePolygonBoundingBox(t){this.auxMin.x=t.vertices[0].x,this.auxMin.y=t.vertices[0].y,this.auxMax.x=t.vertices[0].x,this.auxMax.y=t.vertices[0].y,t.vertices.forEach((t=>{this.auxMin.x=Math.min(t.x,this.auxMin.x),this.auxMin.y=Math.min(t.y,this.auxMin.y),this.auxMax.x=Math.max(t.x,this.auxMax.x),this.auxMax.y=Math.max(t.y,this.auxMax.y)})),t.boundingBox.set(this.auxMin.x,this.auxMin.y,this.auxMax.x-this.auxMin.x,this.auxMax.y-this.auxMin.y)}updateProjectionAxes(t){var e;if(t.vertices.length>2)for(let s=0;s<t.vertices.length;s++)i.normal(t.projectionAxes[s],i.subtract(t.projectionAxes[s],null!==(e=t.vertices[s+1])&&void 0!==e?e:t.vertices[0],t.vertices[s]));else i.normal(t.projectionAxes[0],i.subtract(t.projectionAxes[0],t.vertices[1],t.vertices[0]))}}let Ue=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(le).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new M(t.radius)),t.shapes[0].radius=t.radius,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Ue=Ct([l(Ft.UpdateBallColliderShapeSystem),At(0,c(St.EntityManager))],Ue);let Ie=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ce).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new x([new i,new i,new i,new i])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel[0].set(-t.width/2,-t.height/2),t.shapes[0].vertexModel[1].set(-t.width/2,t.height/2),t.shapes[0].vertexModel[2].set(t.width/2,t.height/2),t.shapes[0].vertexModel[3].set(t.width/2,-t.height/2),this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Ie=Ct([l(Ft.UpdateBoxColliderShapeSystem),At(0,c(St.EntityManager))],Ie);let Le=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(de).forEach((({component:t,entity:e})=>{for(let s=0;s<t.vertexModel.length-1;s++)t.shapes[s]||(t.shapes[s]=new x([new i,new i])),t.shapes[s].rotation=t.rotation,t.shapes[s].vertexModel=[t.vertexModel[s],t.vertexModel[s+1]],this.updatePositionAndVertices(t.shapes[s],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[s]),this.updateProjectionAxes(t.shapes[s])}))}};Le=Ct([l(Ft.UpdateEdgeColliderShapeSystem),At(0,c(St.EntityManager))],Le);let je=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ge).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new x([])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel=t.vertexModel,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};je=Ct([l(Ft.UpdatePolygonColliderShapeSystem),At(0,c(St.EntityManager))],je);let Oe=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(me).forEach((({component:t,entity:e})=>{const i=this.entityManager.getComponent(e,Kt);if(i&&0!==i.data.length){0===t.shapes.length&&(t.composite?this.useEdges(t,i):this.useBoxes(t,i));for(const i of t.shapes)this.updatePositionAndVertices(i,t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(i),this.updateProjectionAxes(i)}}))}useBoxes(t,e){t.shapes=[],e.data.forEach(((i,s)=>{if(!this.needsCollider(i,s,e))return;const r=new x(this.generateRectangleVertices(s,e));r.updateCollisions=!1,t.shapes.push(r)}))}generateRectangleVertices(t,{width:e,height:s,tileWidth:r,tileHeight:o}){const n=-e*r/2+t%e*r,a=s*o/2-Math.floor(t/e)*o;return[new i(n,a-o),new i(n,a),new i(n+r,a),new i(n+r,a-o)]}needsCollider(t,e,{data:i,width:s,height:r}){return 0!==t&&this.getNeighbors(e,s,r).some((t=>!t||!i[t]||0===i[t]))}useEdges(t,e){t.shapes=[];const s=[],r=[];let o,n;e.data.forEach(((t,i)=>{if(0===t)return;const o=i%e.width,n=Math.floor(i/e.width);s[n]||(s[n]=[]),s[n+1]||(s[n+1]=[]),r[n]||(r[n]=[]),r[n+1]||(r[n+1]=[]);const a=this.getNeighbors(i,e.width,e.height);this.hasTile(a[0],e)||(s[n][o]=!0),this.hasTile(a[2],e)||(s[n+1][o]=!0),this.hasTile(a[1],e)||(r[n][o]=!0),this.hasTile(a[3],e)||(r[n][o+1]=!0)}));for(let r=0;r<s.length;r++)if(s[r])for(let a=0;a<s[r].length;a++)!o||!n||r===n.y&&s[r][a]||(t.shapes.push(this.createEdge(o,n,e)),o=void 0,n=void 0),s[r][a]&&(o||(o=new i(a,r)),n=new i(a+1,r));o&&n&&t.shapes.push(this.createEdge(o,n,e)),o=void 0,n=void 0;for(let s=0;s<=e.width;s++)for(let a=0;a<r.length;a++)r[a]&&(!o||!n||s===n.x&&r[a][s]||(t.shapes.push(this.createEdge(o,n,e)),o=void 0,n=void 0),r[a][s]&&(o||(o=new i(s,a)),n=new i(s,a+1)));o&&n&&t.shapes.push(this.createEdge(o,n,e))}hasTile(t,{data:e}){return void 0!==t&&e[t]&&e[t]>0}createEdge(t,e,{width:s,height:r,tileWidth:o,tileHeight:n}){t.x=-s*o/2+t.x*o,t.y=r*n/2-t.y*n,e.x=-s*o/2+e.x*o,e.y=r*n/2-e.y*n;const a=new x([new i(t.x,t.y),new i(e.x,e.y)]);return a.updateCollisions=!1,a}getNeighbors(t,e,i){return[t-e>=0?t-e:void 0,t%e>0?t-1:void 0,t+e<=e*i?t+e:void 0,t%e<e-1?t+1:void 0]}};Oe=Ct([l(Ft.UpdateTilemapColliderShapeSystem),At(0,c(St.EntityManager))],Oe);let ke=class{constructor(t,e,i,s,r){if(this.entityManager=t,this.broadPhaseResolver=e,this.collisionResolutionMethod=s,this.collisionRepository=r,this.colliderTypes=[le,ce,ge,de,me],this.colliders=[],this.collisions=new Set,this.shapes=[],null!=i){const t=new Map;for(let e=0;e<i.length;e++){const[s,r]=i[e];t.has(s)||t.set(s,new Set),t.has(r)||t.set(r,new Set),t.get(s).add(r),t.get(r).add(s)}this.layerNeighbors=t}else this.layerNeighbors=null}onUpdate(){this.collisionRepository.removeAll(),this.colliders=[],this.collisions.clear(),this.shapes=[],this.colliderTypes.forEach((t=>this.entityManager.search(t).forEach((({component:t,entity:e})=>{this.colliders.push(t),t.shapes.forEach((i=>{var s;i.entity=e,i.collider=this.colliders.length-1,i.id=this.shapes.length,i.ignoreCollisionsWithLayers=null!==(s=t.ignoreCollisionsWithLayers)&&void 0!==s?s:[],i.layer=t.layer,this.shapes.push(i)}))})))),this.broadPhaseResolver.update(this.shapes),this.shapes.filter((t=>t.updateCollisions)).forEach((t=>this.narrowPhase(t,this.broadPhase(t))))}broadPhase({boundingBox:t,layer:e}){const i=this.broadPhaseResolver.retrieve(t),s=i.length,r=[];if(this.layerNeighbors){const t=this.layerNeighbors.get(e);if(!t)return r;for(let e=0;e<s;e++){const s=this.shapes[i[e]];t.has(s.layer)&&r.push(s)}return r}for(let t=0;t<s;t++)r.push(this.shapes[i[t]]);return r}narrowPhase(t,e){e.filter((e=>t.entity!==e.entity&&t.id!==e.id&&!t.ignoreCollisionsWithLayers.includes(e.layer)&&!e.ignoreCollisionsWithLayers.includes(t.layer)&&!this.isResolved(t,e))).forEach((e=>{const s=this.collisionResolutionMethod.findCollision(t,e);if(s){const r=s.penetration,o=s.direction.clone();this.collisionRepository.persist({localCollider:this.colliders[t.collider],localEntity:t.entity,remoteCollider:this.colliders[e.collider],remoteEntity:e.entity,resolution:{direction:o,penetration:r}});const n=s.direction.clone();i.scale(n,n,-1),this.collisionRepository.persist({localCollider:this.colliders[e.collider],localEntity:e.entity,remoteCollider:this.colliders[t.collider],remoteEntity:t.entity,resolution:{direction:n,penetration:r}}),this.collisions.add(`${t.id}-${e.id}`),this.collisions.add(`${e.id}-${t.id}`)}}))}isResolved(t,e){return this.collisions.has(`${t.id}-${e.id}`)}};ke=Ct([l(Ft.ResolveCollisionSystem),At(0,c(St.EntityManager)),At(1,c(St.CollisionBroadphaseResolver)),At(2,c(St.CollisionMatrix)),At(3,c(St.CollisionResolutionMethod)),At(4,c(St.CollisionRepository))],ke);let Ge=class{constructor(t,e,s){this.entityManager=t,this.collisionRepository=e,this.transformSystem=s,this.correction=new i,this.maxCorrection=new i}onUpdate(){const e=this.collisionRepository.findAll().filter((({localCollider:t,remoteCollider:e,remoteEntity:i,localEntity:s})=>t.physics&&e.physics&&this.entityManager.hasComponent(s,Be)&&this.entityManager.hasComponent(i,Be)));0!==e.length&&(this.entityManager.search(Be,(e=>e.type===t.RigidBodyType.Dynamic)).forEach((({component:s,entity:r})=>{if(this.maxCorrection.set(0,0),e.filter((({localEntity:t})=>r===t)).forEach((({remoteEntity:e,resolution:{direction:s,penetration:r}})=>{this.entityManager.getComponent(e,Be).type===t.RigidBodyType.Dynamic&&(r/=2),i.scale(this.correction,s,-r),this.correction.magnitude>this.maxCorrection.magnitude&&this.maxCorrection.copy(this.correction)})),0===this.maxCorrection.x&&0===this.maxCorrection.y)return;const{position:o}=this.entityManager.getComponent(r,Ot);i.add(o,o,this.maxCorrection),s.gravity>0&&this.maxCorrection.y*s.velocity.y<0&&(s.velocity.y=0)})),this.transformSystem.onUpdate())}};Ge=Ct([l(Ft.ApplyRepositionSystem),At(0,c(St.EntityManager)),At(1,c(St.CollisionRepository)),At(2,c(Ft.TransformSystem))],Ge);const Ve=new Set([ce,le,ge,de,me]);let Ne=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(Be,(e=>e.type===t.RigidBodyType.Dynamic)).forEach((({entity:t})=>{const e=this.entityManager.getComponent(t,Ot);for(const i of Ve)if(this.entityManager.hasComponent(t,i)){const s=this.entityManager.getComponent(t,i);s.shapes.forEach((t=>{this.updatePositionAndVertices(t,s.offset,e),this.updateBoundingBox(t)}))}}))}};Ne=Ct([l(Ft.UpdateCollidersAfterRepositionSystem),At(0,c(St.EntityManager))],Ne);const We=24;let He=class{constructor(t,e,s,r,o){this.entityManager=t,this.renderManager=e,this.inputManager=s,this.canvas=r,this.gameConfig=o,this.positionInViewport=new i,this.positionInCameraViewport=new i,this.positionInWorldspace=new i,this.renderDataPerCamera=new Map}onUpdate(){var t;if(!(null===(t=this.gameConfig.debug)||void 0===t?void 0:t.mousePosition)||!this.inputManager.mouse)return;const{positionInViewport:e}=this.inputManager.mouse;this.entityManager.search(Vt,(t=>t.debug)).forEach((({entity:t,component:s})=>{const{zoom:r}=s,o=this.entityManager.getComponent(t,Ot).position;this.renderDataPerCamera.has(t)||this.renderDataPerCamera.set(t,ze());const n=this.renderDataPerCamera.get(t);i.floor(this.positionInWorldspace,i.add(this.positionInWorldspace,o,i.scale(this.positionInWorldspace,e,1/r))),i.floor(this.positionInCameraViewport,i.scale(this.positionInCameraViewport,e,1/r)),i.round(this.positionInViewport,e),n.color=this.gameConfig.debug.textColor,n.text=`mouse_position: canvas_viewport=${this.positionInViewport}, camera_viewport=${this.positionInCameraViewport}, world_space=${this.positionInWorldspace}`,n.fontSize=We/r,n.lineHeight=n.fontSize,n.shadow.offset.x=2/r,n.shadow.offset.y=-2/r,n.boundingBox={width:this.canvas.width/r,height:n.fontSize},this.updateRenderDataPosition(n,o,r),this.renderManager.addRenderData(n)}))}updateRenderDataPosition(e,i,s){switch(e.position.x=i.x,this.gameConfig.debug.textPosition){case"top-right":e.alignment=t.TextAlignment.Right,e.position.y=i.y+(this.canvas.height/2-We)/s;break;case"top-left":e.alignment=t.TextAlignment.Left,e.position.y=i.y+(this.canvas.height/2-We)/s;break;case"bottom-left":e.alignment=t.TextAlignment.Left,e.position.y=i.y-(this.canvas.height/2-We)/s;break;default:e.alignment=t.TextAlignment.Right,e.position.y=i.y-(this.canvas.height/2-We)/s}}};He=Ct([l(Ft.DebugMousePositionSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.InputManager)),At(3,c(St.CanvasElement)),At(4,c(St.GameConfig))],He);const ze=(e=24)=>({type:st.Text,text:"",position:new i,layer:Gt,color:"#00FF00",fontSize:e,font:"Arial",shadow:{color:"#000000",opacity:1,offset:new i(1,-1)},flipHorizontally:!1,flipVertically:!1,letterSpacing:0,lineHeight:e,opacity:1,rotation:0,smooth:!1,textureAtlas:Object.assign({},we),boundingBox:{width:0,height:0},alignment:t.TextAlignment.Left});let Ye=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.gameConfig=i}onUpdate(){var e;(null===(e=this.gameConfig.debug)||void 0===e?void 0:e.textRendererBoundingBoxes)&&this.entityManager.search(Re).forEach((({entity:e,component:{width:s,height:r,rotation:o,layer:n,offset:a}})=>{const h=this.entityManager.getComponent(e,Ot);if(!h)return;const l={type:st.Geometric,shape:t.GeometricShape.Polygon,position:i.add(new i,h.localPosition,a),layer:n,color:this.gameConfig.debug.textBoxColor,radius:void 0,rotation:o+h.localRotation,vertexModel:[new i(-s/2,-r/2),new i(-s/2,r/2),new i(s/2,r/2),new i(s/2,-r/2)]};this.renderManager.addRenderData(l)}))}};Ye=Ct([l(Ft.DebugTextRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.GameConfig))],Ye);const Xe=new Map([[Lt.PreGameLogic,[{name:Ft.KeyboardSystem,type:ee},{name:Ft.MouseSystem,type:ie},{name:Ft.TouchScreenSystem,type:se},{name:Ft.GamepadSystem,type:te},{name:Ft.ButtonSystem,type:Xt},{name:Ft.AudioPlayerSystem,type:It},{name:Ft.TiledWrapperSystem,type:qt},{name:Ft.TilemapPreProcessingSystem,type:Qt}]],[Lt.Transform,[{name:Ft.TransformSystem,type:Zt}]],[Lt.Physics,[{name:Ft.ApplyVelocitySystem,type:De},{name:Ft.UpdateBallColliderShapeSystem,type:Ue},{name:Ft.UpdateBoxColliderShapeSystem,type:Ie},{name:Ft.UpdateEdgeColliderShapeSystem,type:Le},{name:Ft.UpdatePolygonColliderShapeSystem,type:je},{name:Ft.UpdateTilemapColliderShapeSystem,type:Oe},{name:Ft.ResolveCollisionSystem,type:ke},{name:Ft.ApplyRepositionSystem,type:Ge},{name:Ft.UpdateCollidersAfterRepositionSystem,type:Ne}]],[Lt.Render,[{name:Ft.AnimatorSystem,type:ne},{name:Ft.CameraSystem,type:ae},{name:Ft.TilemapRendererSystem,type:_e},{name:Ft.SpriteRendererSystem,type:Ae},{name:Ft.GeometricRendererSystem,type:Ce},{name:Ft.MaskRendererSystem,type:ye},{name:Ft.DarknessLightRendererSystem,type:be},{name:Ft.TextRendererSystem,type:Ee},{name:Ft.VideoRendererSystem,type:Ht},{name:Ft.DebugColliderRenderSystem,type:ue},{name:Ft.DebugMousePositionSystem,type:He},{name:Ft.DebugTextRendererSystem,type:Ye},{name:Ft.CullingSystem,type:pe},{name:Ft.ClearScreenSystem,type:he},{name:Ft.RenderSystem,type:xe}]]]);let $e=class{constructor(t,e,i){this.timeManager=t,this.systemManager=e,this.sceneManager=i,this.running=!1,this.gameLoopAccumulator=0}start(){this.running||(this.running=!0,this.gameLoopAccumulator=0,this.enableSystems(),this.sceneManager.loadOpeningScene(),this.requestAnimationLoop(window.performance.now()),this.asyncPhysicsLoop())}enableSystems(){Xe.forEach((t=>{t.forEach((({type:t})=>this.systemManager.enableSystem(t)))}))}stop(){this.running&&(this.systemManager.disableAllSystems(),this.running=!1)}requestAnimationLoop(t){this.running&&(this.timeManager.updateForRender(.001*t),this.sceneManager.update(),this.sceneManager.loadingScene||(this.gameLoopAccumulator+=this.timeManager.browserDeltaTime,this.sceneManager.sceneLoadedThisFrame&&(this.gameLoopAccumulator=this.timeManager.fixedGameDeltaTime),this.gameLoopAccumulator>=this.timeManager.fixedGameDeltaTime&&(this.gameLogicIteration(.001*t),this.gameLoopAccumulator-=this.timeManager.fixedGameDeltaTime),this.renderIteration()),window.requestAnimationFrame((t=>this.requestAnimationLoop(t))))}gameLogicIteration(t){this.timeManager.updateForGame(t),this.systemManager.update(Lt.PreGameLogic),this.systemManager.update(Lt.GameLogic),this.timeManager.updateIntervals(),this.systemManager.update(Lt.Transform)}renderIteration(){this.systemManager.groupHasSystems(Lt.GamePreRender)&&(this.systemManager.update(Lt.GamePreRender),this.systemManager.update(Lt.Transform)),this.systemManager.update(Lt.Render)}asyncPhysicsLoop(){this.physicsIntervalId=window.setInterval((()=>{if(!this.running)return window.clearInterval(this.physicsIntervalId);this.timeManager.updateForPhysics(.001*window.performance.now()),document.hidden||this.physicsIteration()}),1e3/this.timeManager.fixedPhysicsFramerate)}physicsIteration(){this.timeManager.timeScale<=0||(this.systemManager.groupHasSystems(Lt.GamePhysics)&&(this.systemManager.update(Lt.GamePhysics),this.systemManager.update(Lt.Transform)),this.systemManager.update(Lt.Physics))}};$e=Ct([l(St.LoopManager),At(0,c(St.TimeManager)),At(1,c(St.SystemManager)),At(2,c(St.SceneManager))],$e);class Ke{constructor(t,e){this.container=t,this.systemManager=e,this.lastSystemTypeId=0}createSystemIfNotExists(t){if(this.systemManager.hasSystem(t))return;const e="__system_"+this.lastSystemTypeId++;var i;this.container.add(t,e),this.systemManager.addSystem(this.container.get(e),null!==(i=t.prototype.__system_group)&&void 0!==i?i:Lt.GameLogic)}}let qe=class{constructor(t){this.webGLManager=t,this.renderData=[],this.cameraData=[]}addCameraData(t){this.cameraData.push(t)}addRenderData(t){this.renderData.push(t)}setRenderData(t){this.renderData=t}getCameraData(){return this.cameraData}getRenderData(){return this.renderData}removeCameraData(){this.cameraData=[]}removeRenderData(){this.renderData=[]}render(){this.cameraData.sort(((t,e)=>t.depth-e.depth)).forEach((t=>this.renderData.filter((e=>t.layers.includes(e.layer))).sort(((e,i)=>t.layers.indexOf(e.layer)-t.layers.indexOf(i.layer))).forEach((e=>this.webGLManager.render(e,t)))))}};qe=Ct([l(St.RenderManager),At(0,c(St.WebGLManager))],qe);const Je=e=>{var i,s,r,o,n,a,h,l,c,d,g,m;if(!(e.containerNode instanceof HTMLElement))throw new Error("GameConfig Error: Invalid containerNode");if("number"!=typeof e.width)throw new Error("GameConfig Error: Invalid width");if("number"!=typeof e.height)throw new Error("GameConfig Error: Invalid height");e.canvasColor=null!==(i=e.canvasColor)&&void 0!==i?i:"#000000",e.physicsFramerate=null!==(s=e.physicsFramerate)&&void 0!==s?s:180,e.headless=null!==(r=e.headless)&&void 0!==r&&r,e.debug=null!==(o=e.debug)&&void 0!==o?o:{colliders:!1,mousePosition:!1,textRendererBoundingBoxes:!1},e.debug.collidersColor=null!==(n=e.debug.collidersColor)&&void 0!==n?n:"#00FF00",e.debug.textColor=null!==(a=e.debug.textColor)&&void 0!==a?a:"#00FF00",e.debug.textBoxColor=null!==(h=e.debug.textBoxColor)&&void 0!==h?h:"#0000FF",e.debug.textPosition=null!==(l=e.debug.textPosition)&&void 0!==l?l:"bottom-left",e.collisions=null!==(c=e.collisions)&&void 0!==c?c:{},e.collisions.collisionBroadPhaseMethod=null!==(d=e.collisions.collisionBroadPhaseMethod)&&void 0!==d?d:t.BroadPhaseMethods.SpartialGrid,e.collisions.collisionMatrix=null!==(g=e.collisions.collisionMatrix)&&void 0!==g?g:void 0,e.collisions.collisionMethod=null!==(m=e.collisions.collisionMethod)&&void 0!==m?m:t.CollisionMethods.SAT},Qe=({containerNode:t,width:e,height:i})=>{const s=document.createElement("canvas");return s.id="angryPixelGameCanvas",s.width=Math.floor(e),s.height=Math.floor(i),s.tabIndex=0,s.addEventListener("contextmenu",(t=>t.preventDefault())),t.appendChild(s),s.focus(),s},Ze=e=>{e.add(t.EntityManager),e.add(t.SystemManager),e.set(St.CreateSystemService,new Ke(e,e.get(St.SystemManager))),e.add(t.TimeManager),e.add(t.AssetManager),e.add(t.InputManager),e.add(t.SceneManager),e.add(t.InputManager),e.add($e),e.add(bt),e.add(qe)},ti=t=>{t.get(St.GameConfig).headless&&ei(Xe),Xe.forEach(((e,i)=>e.forEach((({type:e,name:s})=>{t.add(e),t.get(St.SystemManager).addSystem(t.get(s),i)}))))},ei=t=>{t.delete(Lt.Render),t.set(Lt.PreGameLogic,t.get(Lt.PreGameLogic).filter((({name:t})=>![Ft.AudioPlayerSystem,Ft.ButtonSystem,Ft.GamepadSystem,Ft.KeyboardSystem,Ft.MouseSystem,Ft.TouchScreenSystem].includes(t))))},ii=e=>{const{collisions:{collisionBroadPhaseMethod:i,collisionMatrix:s,collisionMethod:r}}=e.get(St.GameConfig);e.add(t.CollisionRepository),e.add(D),r===t.CollisionMethods.AABB?(e.add(_),e.add(P)):e.add(U),e.add(i===t.BroadPhaseMethods.QuadTree?u:y),e.add(r===t.CollisionMethods.AABB?S:R),e.set(St.CollisionMatrix,s)},si=t=>{const e=t.get(St.GameConfig);e.dependencies&&e.dependencies.forEach((([e,i])=>{t.set(e,i)}))};class ri{onUpdate(){}onCreate(){}onEnabled(){}onDisabled(){}onDestroy(){}}Ct([c(St.EntityManager)],ri.prototype,"entityManager",void 0),Ct([c(St.AssetManager)],ri.prototype,"assetManager",void 0),Ct([c(St.SceneManager)],ri.prototype,"sceneManager",void 0),Ct([c(St.TimeManager)],ri.prototype,"timeManager",void 0),Ct([c(St.InputManager)],ri.prototype,"inputManager",void 0),Ct([c(St.CollisionRepository)],ri.prototype,"collisionRepository",void 0),Ct([c(St.GameConfig)],ri.prototype,"gameConfig",void 0);const oi={AssetManager:St.AssetManager,CanvasElement:xt.CanvasElement,CollisionRepository:d.CollisionRepository,EntityManager:j.EntityManager,GameConfig:St.GameConfig,InputManager:St.InputManager,SceneManager:St.SceneManager,SystemManager:j.SystemManager,TimeManager:St.TimeManager};t.Animation=class{constructor(t){var e,s,r;this.slice={size:new i,offset:new i,padding:new i},this.frames=[],this.fps=12,this.loop=!1,t&&(this.image=t.image,this.frames=null!==(e=t.frames)&&void 0!==e?e:this.frames,this.fps=null!==(s=t.fps)&&void 0!==s?s:this.fps,this.loop=null!==(r=t.loop)&&void 0!==r?r:this.loop,t.slice&&(this.slice.size.copy(t.slice.size),t.slice.offset&&this.slice.offset.copy(t.slice.offset),t.slice.padding&&this.slice.padding.copy(t.slice.padding)))}},t.Animator=re,t.AudioPlayer=Dt,t.BallCollider=le,t.BoxCollider=ce,t.Button=zt,t.Camera=Vt,t.Circumference=M,t.DarknessRenderer=ve,t.EdgeCollider=de,t.Game=class{constructor(t){this.container=(t=>{Je(t);const e=new h;return e.set(St.GameConfig,t),e.set(St.CanvasElement,Qe(t)),ii(e),Ze(e),ti(e),si(e),e})(t)}get running(){return this.container.get(St.LoopManager).running}addScene(t,e,i=!1){this.container.get(St.SceneManager).addScene(t,e,i)}addDependencyType(t,e){this.container.add(t,e)}addDependencyInstance(t,e){this.container.set(e,t)}start(){this.container.get(St.LoopManager).start()}stop(){this.container.get(St.LoopManager).stop()}},t.GameSystem=ri,t.GamepadController=Rt,t.GeometricRenderer=Se,t.Keyboard=Et,t.LightRenderer=Me,t.MaskRenderer=fe,t.Mouse=_t,t.Polygon=x,t.PolygonCollider=ge,t.Rectangle=s,t.RigidBody=Be,t.SYMBOLS=oi,t.Scene=class{constructor(t,e){this.entityManager=t,this.assetManager=e,this.systems=[]}registerSystems(){}loadAssets(){}createEntities(){}addSystem(t){this.systems.push(t)}addSystems(t){this.systems.push(...t)}},t.SpriteRenderer=oe,t.TextRenderer=Re,t.TiledWrapper=$t,t.TilemapCollider=me,t.TilemapRenderer=Kt,t.TouchScreen=Tt,t.Transform=Ot,t.Vector2=i,t.VideoRenderer=Nt,t.between=a,t.clamp=r,t.debugRenderLayer=Gt,t.decorate=function(t,e,i){"number"==typeof i?t(e.prototype,void 0,i):void 0!==i?t(e.prototype,i):t(e)},t.defaultRenderLayer=kt,t.defaultTextureAtlasOptions=we,t.degreesToRadians=t=>t*(Math.PI/180),t.disableComponent=t=>({enabled:!1,component:t}),t.fixedRound=o,t.gameLogicSystem=function(){return function(t){jt(t,Lt.GameLogic)}},t.gamePhysicsSystem=function(){return function(t){jt(t,Lt.GamePhysics)}},t.gamePreRenderSystem=function(){return function(t){jt(t,Lt.GamePreRender)}},t.inject=c,t.injectable=l,t.playSfx=({audioSource:t,volume:e=1,loop:i=!1})=>{t.volume=e,t.loop=i,t.currentTime=0,t.play().catch((t=>console.warn("playSfx error:",t)))},t.radiansToDegrees=t=>t*(180/Math.PI),t.randomFloat=(t,e,i=2)=>o(Math.random()*(e-t)+t,i),t.randomInt=(t,e)=>Math.round(Math.random()*(e-t))+t,t.range=n,t.rgbToHex=({r:t,g:e,b:i},s="#")=>{const r=t=>t.toString(16).padStart(2,"0");return`${s}${r(t)}${r(e)}${r(i)}`},t.stopSfx=t=>{t.pause(),t.currentTime=0}}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["angry-pixel"]={})}(this,(function(t){"use strict";var e;t.BroadPhaseMethods=void 0,(e=t.BroadPhaseMethods||(t.BroadPhaseMethods={}))[e.QuadTree=0]="QuadTree",e[e.SpartialGrid=1]="SpartialGrid";class i{constructor(t=0,e=0){this._x=t,this._y=e}get x(){return this._x}set x(t){this._x=t}get y(){return this._y}set y(t){this._y=t}get magnitude(){return Math.sqrt(Math.pow(this._x,2)+Math.pow(this._y,2))}get direction(){return this._direction||(this._direction=new i),i.unit(this._direction,this)}set(t,e){this._x=t,this._y=e}copy(t){this.set(t.x,t.y)}equals(t){return this._x===t.x&&this._y===t.y}clone(){return new i(this._x,this._y)}distance(t){return Math.sqrt(Math.pow(this._x-t.x,2)+Math.pow(this._y-t.y,2))}static add(t,e,i){return t.set(e.x+i.x,e.y+i.y),t}static subtract(t,e,i){return t.set(e.x-i.x,e.y-i.y),t}static unit(t,e){const i=e.x*e.x+e.y*e.y;if(0===i)t.set(0,0);else{const s=1/Math.sqrt(i);t.set(e.x*s,e.y*s)}return t}static normal(t,e){return t.set(-e.y,e.x),this.unit(t,t)}static scale(t,e,i){return t.set(e.x*i,e.y*i),t}static dot(t,e){return t.x*e.x+t.y*e.y}static cross(t,e){return t.x*e.y-t.y*e.x}static round(t,e){return t.set(Math.round(e.x),Math.round(e.y)),t}static floor(t,e){return t.set(Math.floor(e.x),Math.floor(e.y)),t}static ceil(t,e){return t.set(Math.ceil(e.x),Math.ceil(e.y)),t}toString(){return`(${this._x}, ${this._y})`}}class s{constructor(t=0,e=0,s=0,r=0){this.width=0,this.height=0,this._position=new i,this._center=new i,this.set(t,e,s,r)}get x(){return this._position.x}set x(t){this._position.set(t,this._position.y)}get y(){return this._position.y}set y(t){this._position.set(this._position.x,t)}get x1(){return this._position.x+this.width}get y1(){return this._position.y+this.height}get position(){return this._position}set position(t){this._position.set(t.x,t.y)}get center(){return this._center.set(this.x+this.width/2,this.y+this.height/2),this._center}set(t,e,i,s){this._position.set(t,e),this.width=i,this.height=s}equals(t){return this.position.equals(t.position)&&this.width===t.width&&this.height===t.height}copy(t){this.set(t.x,t.y,t.width,t.height)}intersects(t){return!(this.x1<t.x||this.x>t.x1||this.y1<t.y||this.y>t.y1)}contains(t){return t instanceof s?t.x1<=this.x1&&t.x>=this.x&&t.y1<=this.y1&&t.y>=this.y:t instanceof i&&!(t.x<this.x||t.y<this.y||t.x>=this.x1||t.y>=this.y1)}toString(){return`(${this.position.x}, ${this.position.y}, ${this.width}, ${this.height})`}}const r=(t,e,i)=>Math.min(i,Math.max(e,t)),o=(t,e)=>Math.round(t*Math.pow(10,e))/Math.pow(10,e),n=(t,e,i=1)=>{const s=[];for(let r=t;r<=e;r+=i)s.push(r);return s},a=(t,e,i)=>t>=e&&t<=i;class h{constructor(){this.instances=new Map,this.types=new Map}add(t,e){if(!e&&!t.prototype.__ioc_injectable)throw new Error(`Type ${t.name} is not injectable`);return this.types.set(null!=e?e:t.prototype.__ioc_injectable,t),this}set(t,e){return this.instances.set(t,e),this}get(t){var e,i;if(!this.instances.has(t)){const s=this.types.get(t);if(!s)throw new Error(`${t.toString()} is not a valid type`);const r=new s(...(null!==(e=s.prototype.__ioc_inject_constructor)&&void 0!==e?e:[]).map((t=>this.get(t))));(null!==(i=s.prototype.__ioc_inject_prop)&&void 0!==i?i:[]).forEach((([t,e])=>r[t]=this.get(e))),this.instances.set(t,r)}return this.instances.get(t)}has(t){return this.types.has(t)||this.instances.has(t)}}function l(t){return function(e){e.prototype.__ioc_injectable&&e.prototype.__ioc_injectable===t||(e.prototype.__ioc_injectable=t)}}function c(t){return function(e,i,s){void 0!==s?(e.prototype.__ioc_inject_constructor||(e.prototype.__ioc_inject_constructor=[]),e.prototype.__ioc_inject_constructor[s]=t):void 0!==i&&(e.constructor.prototype.__ioc_inject_prop||(e.constructor.prototype.__ioc_inject_prop=[]),e.constructor.prototype.__ioc_inject_prop.push([i,t]))}}const d={CollisionRepository:Symbol.for("CollisionRepository"),CollisionBroadphaseResolver:Symbol.for("CollisionBroadphaseResolver"),CollisionResolutionMethod:Symbol.for("CollisionResolutionMethod"),CollisionAABBResolver:Symbol.for("CollisionAABBResolver"),CollisionCircumferenceAABBResolver:Symbol.for("CollisionCircumferenceAABBResolver"),CollisionCircumferenceResolver:Symbol.for("CollisionCircumferenceResolver"),CollisionSatResolver:Symbol.for("CollisionSatResolver"),CollisionMatrix:Symbol.for("CollisionMatrix")};var g,m=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let u=g=class{constructor(t=new s,e=0){this.rects=new Map,this.children=null,this.seenGen=[],this.retrieveSerial=0,this.minArea=new i,this.maxArea=new i,this.bounds=t,this.depth=e}update(t){this.clear(),0!==t.length&&(this.resize(t),this.ensureSeenCapacity(t.length),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e))))}ensureSeenCapacity(t){if(this.seenGen.length<t){const e=this.seenGen.length;this.seenGen.length=t,this.seenGen.fill(0,e,t)}}clear(){this.rects.clear(),this.children&&(this.children.forEach((t=>t.clear())),this.children=null)}resize(t){this.minArea.set(1/0,1/0),this.maxArea.set(-1/0,-1/0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))})),this.bounds.set(this.minArea.x,this.minArea.y,this.maxArea.x-this.minArea.x,this.maxArea.y-this.minArea.y)}insert(t,e){!this.children&&this.rects.size>=16&&this.depth<8&&(this.subdivide(),this.rects.forEach(((t,e)=>this.children.forEach((i=>{i.bounds.intersects(t)&&i.insert(e,t)})))),this.rects.clear()),this.children?this.children.forEach((i=>{i.bounds.intersects(e)&&i.insert(t,e)})):this.rects.set(t,e)}subdivide(){const t=this.bounds.x,e=this.bounds.y,i=this.bounds.width/2,r=this.bounds.height/2;this.children=[new g(new s(t,e,i,r),this.depth+1),new g(new s(t+i,e,i,r),this.depth+1),new g(new s(t,e+r,i,r),this.depth+1),new g(new s(t+i,e+r,i,r),this.depth+1)]}retrieve(t){2147483647==++this.retrieveSerial&&(this.retrieveSerial=1,this.seenGen.fill(0));const e=[];return this.retrieveFromNode(t,e,this.retrieveSerial,this.seenGen),e}retrieveFromNode(t,e,i,s){this.children?this.children.forEach((r=>{r.bounds.intersects(t)&&r.retrieveFromNode(t,e,i,s)})):this.rects.forEach(((r,o)=>{r.intersects(t)&&s[o]!==i&&(s[o]=i,e.push(o))}))}};u=g=m([l(d.CollisionBroadphaseResolver)],u);var p=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};const f=(t,e,i,s)=>Math.min((t-e)/i|0,s-1);let y=class{constructor(){this.area=new s,this.grid=[],this.rects=new Map,this.subdivisions=0,this.lastAreaX=NaN,this.lastAreaY=NaN,this.lastAreaW=NaN,this.lastAreaH=NaN,this.lastSubdivisions=-1,this.seenGen=[],this.retrieveSerial=0,this.retrieveResult=[],this.minArea=new i,this.maxArea=new i,this.coordinates={x0:0,x1:0,y0:0,y1:0}}update(t){if(0===t.length)return this.rects.clear(),void(this.grid.length>0&&this.clearGridCells());this.resize(t),this.ensureSeenCapacity(t.length),t.forEach((({id:t,boundingBox:e})=>this.insert(t,e)))}ensureSeenCapacity(t){if(this.seenGen.length<t){const e=this.seenGen.length;this.seenGen.length=t,this.seenGen.fill(0,e,t)}}clearGridCells(){for(let t=0;t<this.subdivisions;t++)for(let e=0;e<this.subdivisions;e++)this.grid[t][e].length=0}resize(t){this.minArea.set(1/0,1/0),this.maxArea.set(-1/0,-1/0),t.forEach((({boundingBox:t})=>{this.minArea.set(Math.min(t.x,this.minArea.x),Math.min(t.y,this.minArea.y)),this.maxArea.set(Math.max(t.x1,this.maxArea.x),Math.max(t.y1,this.maxArea.y))}));const e=this.minArea.x,i=this.minArea.y,s=this.maxArea.x-this.minArea.x,r=this.maxArea.y-this.minArea.y;this.area.set(e,i,s,r);const o=1+(t.length/16|0);this.cellWidth=Math.ceil(this.area.width/o),this.cellHeight=Math.ceil(this.area.height/o);this.grid.length>0&&o===this.lastSubdivisions&&e===this.lastAreaX&&i===this.lastAreaY&&s===this.lastAreaW&&r===this.lastAreaH?this.clearGridCells():(this.subdivisions=o,this.buildGrid(),this.lastSubdivisions=o,this.lastAreaX=e,this.lastAreaY=i,this.lastAreaW=s,this.lastAreaH=r),this.subdivisions=o,this.rects.clear()}buildGrid(){this.grid=[];for(let t=0;t<this.subdivisions;t++){this.grid[t]=[];for(let e=0;e<this.subdivisions;e++)this.grid[t][e]=[]}}insert(t,e){this.updateCoordinates(e);for(let e=this.coordinates.x0;e<=this.coordinates.x1;e++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++)this.grid[e][i].push(t);this.rects.set(t,e)}retrieve(t){this.retrieveResult.length=0,2147483647==++this.retrieveSerial&&(this.retrieveSerial=1,this.seenGen.fill(0)),this.updateCoordinates(t);for(let e=this.coordinates.x0;e<=this.coordinates.x1;e++)for(let i=this.coordinates.y0;i<=this.coordinates.y1;i++){const s=this.grid[e][i];for(let e=0,i=s.length;e<i;e++){const i=s[e];this.rects.get(i).intersects(t)&&this.seenGen[i]!==this.retrieveSerial&&(this.seenGen[i]=this.retrieveSerial,this.retrieveResult.push(i))}}return this.retrieveResult}updateCoordinates(t){this.coordinates.x0=f(t.x,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.x1=f(t.x1,this.area.x,this.cellWidth,this.subdivisions),this.coordinates.y0=f(t.y,this.area.y,this.cellHeight,this.subdivisions),this.coordinates.y1=f(t.y1,this.area.y,this.cellHeight,this.subdivisions)}};y=p([l(d.CollisionBroadphaseResolver)],y);class x{get vertexModel(){return this._vertexModel}set vertexModel(t){if(this._vertexModel=t,2===t.length)return this.vertices=[new i,new i],void(this.projectionAxes=[new i]);this.vertices=[],this.projectionAxes=[],this._vertexModel.forEach((()=>{this.vertices.push(new i),this.projectionAxes.push(new i)}))}constructor(t,e=0){this.rotation=e,this.boundingBox=new s,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new i,this.projectionAxes=[],this.radius=0,this.vertices=[],this.updateCollisions=!0,this._vertexModel=[],this.vertexModel=t}}class M{constructor(t){this.radius=t,this.boundingBox=new s,this.collider=void 0,this.entity=void 0,this.id=void 0,this.ignoreCollisionsWithLayers=void 0,this.layer=void 0,this.position=new i,this.projectionAxes=[new i],this.rotation=0,this.vertexModel=[],this.vertices=[new i,new i],this.updateCollisions=!0}}var v=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n},b=function(t,e){return function(i,s){e(i,s,t)}};let S=class{constructor(t,e,i){this.AABBResolver=t,this.circumferenceAABBResolver=e,this.circumferenceResolver=i}findCollision(t,e){return t instanceof x&&e instanceof x?this.AABBResolver.resolve(t,e):t instanceof M&&e instanceof x?this.circumferenceAABBResolver.resolve(t,e):t instanceof x&&e instanceof M?this.circumferenceAABBResolver.resolve(e,t,!0):t instanceof M&&e instanceof M?this.circumferenceResolver.resolve(t,e):void 0}};var C;S=v([l(d.CollisionResolutionMethod),b(0,c(d.CollisionAABBResolver)),b(1,c(d.CollisionCircumferenceAABBResolver)),b(2,c(d.CollisionCircumferenceResolver))],S),t.CollisionMethods=void 0,(C=t.CollisionMethods||(t.CollisionMethods={}))[C.AABB=0]="AABB",C[C.SAT=1]="SAT";var A=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n},w=function(t,e){return function(i,s){e(i,s,t)}};let R=class{constructor(t,e){this.circumferenceResolver=t,this.satResolver=e}findCollision(t,e){return t instanceof M&&e instanceof M?this.circumferenceResolver.resolve(t,e):this.satResolver.resolve(t,e)}};R=A([l(d.CollisionResolutionMethod),w(0,c(d.CollisionCircumferenceResolver)),w(1,c(d.CollisionSatResolver))],R);var E=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let _=class{constructor(){this.direction=new i,this.resolutionDirection=new i,this.outDirection=new i}resolve({boundingBox:t},{boundingBox:e}){if(this.overlapX=Math.min(t.x1,e.x1)-Math.max(t.x,e.x),this.overlapY=Math.min(t.y1,e.y1)-Math.max(t.y,e.y),!(this.overlapX<0||this.overlapY<0))return this.checkOverlapForLines(t,e),this.direction.set(Math.sign(e.center.x-t.center.x),Math.sign(e.center.y-t.center.y)),this.preventContainment(t,e),this.overlapY<this.overlapX?(this.minOverlap=this.overlapY,this.resolutionDirection.set(0,this.direction.y)):(this.minOverlap=this.overlapX,this.resolutionDirection.set(this.direction.x,this.overlapY===this.overlapX?this.direction.y:0)),{direction:i.unit(this.outDirection,this.resolutionDirection),penetration:this.minOverlap}}checkOverlapForLines(t,e){0!==t.width&&0!==e.width||0!==this.overlapX||(this.overlapX=Math.min(Math.abs(t.x-e.x),Math.abs(t.x1-e.x1))),0!==t.height&&0!==e.height||0!==this.overlapY||(this.overlapY=Math.min(Math.abs(t.y-e.y),Math.abs(t.y1-e.y1)))}preventContainment(t,e){if(this.overlapY>0&&(t.y1>e.y1&&t.y<e.y||t.y1<e.y1&&t.y>e.y)){const i=Math.abs(t.y-e.y),s=Math.abs(t.y1-e.y1);this.overlapY+=i<s?i:s}if(this.overlapX>0&&(t.x1>e.x1&&t.x<e.x||t.x1<e.x1&&t.x>e.x)){const i=Math.abs(t.x-e.x),s=Math.abs(t.x1-e.x1);this.overlapX+=i<s?i:s}}};_=E([l(d.CollisionAABBResolver)],_);var T=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let P=class{constructor(){this.closestPoint=new i,this.distance=new i,this.direction=new i,this.outDirection=new i}resolve(t,e,s=!1){this.closestPoint.set(r(t.position.x,e.boundingBox.x,e.boundingBox.x1),r(t.position.y,e.boundingBox.y,e.boundingBox.y1)),i.subtract(this.distance,this.closestPoint,t.position);const o=this.distance.magnitude;if(!(o>t.radius))return i.unit(this.direction,this.distance),s?i.scale(this.outDirection,this.direction,-1):this.outDirection.copy(this.direction),{direction:this.outDirection,penetration:t.radius-o}}};P=T([l(d.CollisionCircumferenceAABBResolver)],P);var B=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let D=class{constructor(){this.distance=new i,this.outDirection=new i}resolve(t,e){i.subtract(this.distance,e.position,t.position);const s=this.distance.magnitude,r=t.radius+e.radius;if(!(s>r))return i.unit(this.outDirection,this.distance),{direction:this.outDirection,penetration:r-s}}};D=B([l(d.CollisionCircumferenceResolver)],D);var F=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};let U=class{constructor(){this.mergedAxes=[],this.projA={min:0,max:0},this.projB={min:0,max:0},this.smallestAxis=new i,this.distance=new i(1/0,1/0),this.cache=new i,this.outDirection=new i}resolve(t,e){this.minOverlap=1/0,t instanceof M?this.setCircumferenceAxis(t,e):e instanceof M&&this.setCircumferenceAxis(e,t),this.mergeProjectionAxes(t,e);for(let s=0;s<this.mergedAxes.length;s++){const r=this.mergedAxes[s];if(t instanceof M?this.setCircumferenceVertices(t,r):e instanceof M&&this.setCircumferenceVertices(e,r),this.projectShapeOntoAxis(this.projA,t,r),this.projectShapeOntoAxis(this.projB,e,r),this.currentOverlap=Math.min(this.projA.max,this.projB.max)-Math.max(this.projA.min,this.projB.min),this.currentOverlap<0)return;if(this.invertAxis=!0,this.projA.max>this.projB.max&&this.projA.min<this.projB.min||this.projA.max<this.projB.max&&this.projA.min>this.projB.min){const t=Math.abs(this.projA.min-this.projB.min),e=Math.abs(this.projA.max-this.projB.max);t<e?this.currentOverlap+=t:(this.currentOverlap+=e,i.scale(r,r,-1),this.invertAxis=!1)}this.currentOverlap<this.minOverlap&&(this.minOverlap=this.currentOverlap,this.smallestAxis.copy(r),this.invertAxis&&this.projA.max<this.projB.max&&i.scale(this.smallestAxis,r,-1))}return i.scale(this.outDirection,this.smallestAxis,-1),{direction:this.outDirection,penetration:this.minOverlap}}mergeProjectionAxes(t,e){const i=t.projectionAxes,s=e.projectionAxes;this.mergedAxes.length=0;for(let t=0;t<i.length;t++)this.mergedAxes.push(i[t]);for(let t=0;t<s.length;t++){const e=s[t];let i=!1;for(let t=0;t<this.mergedAxes.length;t++)if(this.mergedAxes[t].equals(e)){i=!0;break}i||this.mergedAxes.push(e)}}projectShapeOntoAxis(t,e,s){t.min=1/0,t.max=-1/0;const r=e.vertices;for(let e=0;e<r.length;e++){const o=i.dot(s,r[e]);o<t.min&&(t.min=o),o>t.max&&(t.max=o)}return t}setCircumferenceAxis(t,e){this.distance.set(1/0,1/0);let s=1/0;const r=e.vertices;for(let e=0;e<r.length;e++){i.subtract(this.cache,r[e],t.position);const o=this.cache.x*this.cache.x+this.cache.y*this.cache.y;o<s&&(s=o,this.distance.copy(this.cache))}i.unit(t.projectionAxes[0],this.distance)}setCircumferenceVertices(t,e){i.add(t.vertices[0],t.position,i.scale(this.cache,i.unit(this.cache,e),-t.radius)),i.add(t.vertices[1],t.position,i.scale(this.cache,i.unit(this.cache,e),t.radius))}};U=F([l(d.CollisionSatResolver)],U);var I=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};t.CollisionRepository=class{constructor(){this.collisions=[]}findCollisionsForCollider(t){return this.collisions.filter((e=>e.localCollider===t))}findCollisionsForColliderAndLayer(t,e){return this.collisions.filter((i=>i.localCollider===t&&i.remoteCollider.layer===e))}findAll(){return this.collisions}persist(t){this.collisions.push(t)}removeAll(){this.collisions=[]}},t.CollisionRepository=I([l(d.CollisionRepository)],t.CollisionRepository);const L=t=>{if(null===t||"object"!=typeof t)return t;if("undefined"!=typeof Node&&t instanceof Node)return t;if("undefined"!=typeof FontFace&&t instanceof FontFace)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map((t=>L(t)));if(t instanceof Map){const e=new Map;for(const[i,s]of t)e.set(L(i),L(s));return e}if(t instanceof Set){const e=new Set;for(const i of t)e.add(L(i));return e}const e=Object.getPrototypeOf(t),i=Object.create(e);for(const e of Object.keys(t))i[e]=L(t[e]);return i},j={EntityManager:Symbol.for("EntityManager"),SystemManager:Symbol.for("SystemManager")};var O=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};t.EntityManager=class{constructor(){this.lastEntityId=0,this.lastComponentTypeId=0,this.entities=new Set,this.components=new Map,this.disabledEntities=new Set,this.manuallyDisabledEntities=new Set,this.disabledComponents=new Map,this.parentEntities=new Map,this.childEntities=new Map}createEntity(t,e){const i=this.lastEntityId++;return t&&(this.entities.add(i),t.forEach((t=>this.addComponent(i,t))),e&&this.setParent(i,e)),i}createEntityFromArchetype({components:t,children:e,enabled:i},s){const r=this.lastEntityId++;return this.entities.add(r),this.createComponentsFromArchetype(t,r),s&&this.setParent(r,s),e&&e.forEach((t=>this.createEntityFromArchetype(t,r))),!1===i&&this.disableEntity(r),r}createComponentsFromArchetype(t,e){t.forEach((t=>{let i,s=!0;if("object"==typeof t&&"component"in t&&"enabled"in t&&!1===t.enabled&&(s=!1,t=t.component),"object"==typeof t)i=this.addComponent(e,L(t));else{if("function"!=typeof t)throw new Error("Invalid component type");i=this.addComponent(e,t)}s||this.disableComponent(i)}))}removeEntity(t){var e;this.getChildren(t).forEach((t=>this.removeEntity(t))),this.components.forEach((e=>{e.has(t)&&e.delete(t)})),this.disabledComponents.delete(t),this.disabledEntities.delete(t),this.manuallyDisabledEntities.delete(t);const i=this.getParent(t);i&&(null===(e=this.childEntities.get(i))||void 0===e||e.delete(t)),this.parentEntities.delete(t),this.childEntities.delete(t),this.entities.delete(t)}removeAllEntities(t){const e=t?this.search(t):[];if(e.length>0){const t=new Set(e.map((({entity:t})=>t)));for(const e of this.entities)t.has(e)||this.removeEntity(e)}else this.components.clear(),this.disabledComponents.clear(),this.disabledEntities.clear(),this.manuallyDisabledEntities.clear(),this.lastEntityId=0,this.entities.clear(),this.parentEntities.clear(),this.childEntities.clear()}isEntity(t){return this.entities.has(t)}isEntityEnabled(t){return this.isEntity(t)&&!this.disabledEntities.has(t)}enableEntity(t){this.disabledEntities.has(t)&&(this.disabledEntities.delete(t),this.getChildren(t).forEach((t=>{this.manuallyDisabledEntities.has(t)||this.enableEntity(t)})))}disableEntity(t){this.disabledEntities.has(t)||(this.disabledEntities.add(t),this.getChildren(t).forEach((t=>{this.disabledEntities.has(t)?this.manuallyDisabledEntities.add(t):this.disableEntity(t)})))}disableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.disableEntity(s)}enableEntitiesByComponent(t){var e,i;for(const s of null!==(i=null===(e=this.components.get(this.getComponentTypeId(t)))||void 0===e?void 0:e.keys())&&void 0!==i?i:[])this.enableEntity(s)}setParent(t,e){if(!this.isEntity(t)||!this.isEntity(e))throw new Error("Both entities must exist to set a parent-child relationship.");if(this.parentEntities.has(t)){const i=this.parentEntities.get(t);if(i===e)return;this.childEntities.get(i).delete(t)}this.parentEntities.set(t,e),this.childEntities.has(e)||this.childEntities.set(e,new Set),this.childEntities.get(e).add(t)}getParent(t){return this.parentEntities.get(t)}getChildren(t){return Array.from(this.childEntities.get(t)||[])}removeParent(t){const e=this.parentEntities.get(t);e&&(this.parentEntities.delete(t),this.childEntities.get(e).delete(t))}removeChild(t,e){this.parentEntities.get(e)===t&&(this.parentEntities.delete(e),this.childEntities.get(t).delete(e))}addComponent(t,e){var i;const s=this.getComponentTypeId(e),r="object"==typeof e?e:new e;if(this.components.has(s)||this.components.set(s,new Map),this.components.get(s).has(t)){const e=null!==(i=r.constructor.componentName)&&void 0!==i?i:r.constructor.name;throw new Error(`Entity ${t} already has a component of type ${e}`)}return this.components.get(s).set(t,r),r}hasComponent(t,e){return void 0!==this.getComponent(t,e)}getComponent(t,e){var i;return null===(i=this.components.get(this.getComponentTypeId(e)))||void 0===i?void 0:i.get(t)}getComponents(t){const e=[];return this.components.forEach((i=>i.forEach(((i,s)=>{t===s&&e.push(i)})))),e}updateComponentData(t,e,i){const s=this.getComponent(t,e);s&&i(s)}getEntityForComponent(t){const e=this.getComponentTypeId(t);if(this.components.has(e))for(const[i,s]of this.components.get(e))if(s===t)return i}removeComponent(t,e){var i;const s=this.getComponentTypeId("object"==typeof t?t:e),r="number"==typeof t?t:this.getEntityForComponent(t);void 0!==r&&(null===(i=this.components.get(s))||void 0===i?void 0:i.has(r))&&this.components.get(s).delete(r)}isComponentEnabled(t,e){var i,s;const r=this.getComponentTypeId("object"==typeof t?t:e);if("number"==typeof t&&!(null===(i=this.components.get(r))||void 0===i?void 0:i.has(t)))return!1;const o="number"==typeof t?t:this.getEntityForComponent(t);return!(null===(s=this.disabledComponents.get(o))||void 0===s?void 0:s.has(r))}disableComponent(t,e){const i="number"==typeof t?t:this.getEntityForComponent(t),s=this.getComponentTypeId("object"==typeof t?t:e);null!=i&&(this.disabledComponents.has(i)?this.disabledComponents.get(i).has(s)||this.disabledComponents.get(i).add(s):this.disabledComponents.set(i,new Set([s])))}enableComponent(t,e){var i;const s="number"==typeof t?t:this.getEntityForComponent(t),r=this.getComponentTypeId("object"==typeof t?t:e);void 0!==s&&(null===(i=this.disabledComponents.get(s))||void 0===i?void 0:i.has(r))&&this.disabledComponents.get(s).delete(r)}getComponentFromParent(t,e){let i=t;for(;i;){const t=this.getComponent(i,e);if(t)return t;i=this.getParent(i)}}search(t,e,i=!1){const s=[],r=this.getComponentTypeId(t),o="boolean"==typeof e?e:i,n="function"==typeof e?e:void 0;return this.components.has(r)&&this.components.get(r).forEach(((e,i)=>{n&&!n(e,i)||!(o||this.isEntityEnabled(i)&&this.isComponentEnabled(i,t))||s.push({entity:i,component:e})})),s}searchEntitiesByComponents(t){const e=[];let i=!0;for(const s of t){const t=this.getComponentTypeId(s);if(!t||!this.components.has(t))return[];if(i){e.push(...this.components.get(t).keys()),i=!1;continue}const r=new Set(this.components.get(t).keys());e.forEach(((t,i)=>{r.has(t)||e.splice(i,1)}))}return e}searchInChildren(t,e,i=!1){const s=this.getChildren(t);return this.search(e,i).filter((({entity:t})=>s.includes(t)))}getComponentTypeId(t){const e="object"==typeof t?t.constructor.prototype:t.prototype;return void 0===e.__ecs_type_id&&(e.__ecs_type_id=Number(`${++this.lastComponentTypeId}${(1e5*performance.now()).toFixed(0)}`)),e.__ecs_type_id}},t.EntityManager=O([l(j.EntityManager)],t.EntityManager);var k,G=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n};t.SystemManager=class{constructor(){this.systems=[]}findSystemIndex(t){return this.systems.findIndex((e=>e[0]instanceof t))}addSystem(t,e){if(this.systems.some((t=>t[0]instanceof t.constructor)))throw new Error(`SystemManager already has an instance of ${t.constructor.name}.`);this.systems.push([t,e,!1,!1])}hasSystem(t){return this.systems.some((e=>e[0]instanceof t))}getSystem(t){const e=this.findSystemIndex(t);return-1!==e?this.systems[e][0]:void 0}groupHasSystems(t){return this.systems.filter((e=>e[1]===t)).length>0}enableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!0===this.systems[e][2])return;const i=this.systems[e];!1===i[3]&&(i[3]=!0,i[0].onCreate&&i[0].onCreate()),i[2]=!0,i[0].onEnabled&&i[0].onEnabled()}disableSystem(t){const e=this.findSystemIndex(t);if(-1===e||!1===this.systems[e][2])return;const i=this.systems[e];i[2]=!1,i[0].onDisabled&&i[0].onDisabled()}setExecutionOrder(t,e){const i=this.findSystemIndex(t);if(-1===i)throw new Error(`Cannot set execution order because ${t.name} is not a system.`);this.systems.splice(e,0,this.systems.splice(i,1)[0])}removeSystem(t){const e=this.findSystemIndex(t);if(-1===e)return;const i=this.systems.splice(e,1)[0][0];i.onDestroy&&i.onDestroy()}disableAllSystems(){this.systems.forEach((t=>{t[2]&&this.disableSystem(t[0].constructor)}))}update(t){this.systems.filter((e=>e[1]===t&&!0===e[2])).forEach((t=>t[0].onUpdate()))}},t.SystemManager=G([l(j.SystemManager)],t.SystemManager),function(t){t.LegacyWebGL="webgl",t.WebGL2="webgl2"}(k||(k={}));class V{constructor(t){if(this.canvas=t,this.contextVersion=this.getContextVersion(),!this.contextVersion)throw new Error("Your browser does not support WebGL.");this.gl=this.canvas.getContext(this.contextVersion)}getContextVersion(){return null!==this.canvas.getContext(k.WebGL2)?k.WebGL2:null!==this.canvas.getContext(k.LegacyWebGL)?k.LegacyWebGL:void 0}}class N{constructor(){this.fontAtlas=new Map}hasFontAtlas(t){return this.fontAtlas.has(this.getId(t))}getFontAtlas(t){return this.fontAtlas.get(this.getId(t))}getOrCreate(t){var e;return null!==(e=this.getFontAtlas(t))&&void 0!==e?e:this.create(t)}create(t){const{font:e,charRanges:i,fontSize:s,spacing:r}=t;this.chars=[];for(let t=0;t<i.length;t+=2)for(let e=i[t];e<=i[t+1];e++)this.chars.push(String.fromCharCode(e));this.font=e instanceof FontFace?e.family:e,this.fontSize=s,this.spacing=r,this.id=this.getId(t);const o=this.renderAtlas();return this.fontAtlas.set(this.id,o),o}getId({font:t,charRanges:e,fontSize:i,spacing:s}){return JSON.stringify({font:t instanceof FontFace?t.family:t,charRanges:e,fontSize:i,spacing:s})}renderAtlas(){const t=new W(this.id,this.fontSize,Math.ceil(Math.sqrt(this.chars.length)),this.spacing),e=t.canvas.getContext("2d");e.clearRect(0,0,t.canvas.width,t.canvas.height),e.textBaseline="top",e.fillStyle="#FFFFFF",e.font=`${this.fontSize}px ${this.font}`;let i=0,s=0;for(let r=0;r<this.chars.length;r++)e.fillText(this.chars[r],i,s),t.glyphs.set(this.chars[r],{id:r,width:e.measureText(this.chars[r]).width}),(i+=this.fontSize+this.spacing)>t.canvas.width-this.fontSize&&(i=0,s+=this.fontSize+this.spacing);return t}}class W{constructor(t,e,i,s){this.id=t,this.fontSize=e,this.gridSize=i,this.spacing=s,this.canvas=document.createElement("canvas"),this.glyphs=new Map,this.canvas.width=this.gridSize*(this.fontSize+this.spacing),this.canvas.height=this.canvas.width}}class H{constructor(t,e){this.gl=t,this.shaderLoader=e}create(t,e){const i=this.gl.createProgram(),s=this.shaderLoader.load(this.gl.VERTEX_SHADER,t),r=this.shaderLoader.load(this.gl.FRAGMENT_SHADER,e);this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);const o=this.gl.LINK_STATUS;if(!this.gl.getProgramParameter(i,o)){const t=this.gl.getProgramInfoLog(i);throw this.gl.deleteProgram(i),new Error(`Unable to initialize the Program: ${t}`)}return i}}class z{constructor(t,e,i){this.gl=t,this.contextVersion=e,this.programFactory=i}loadProgram(){this.program=this.contextVersion===k.WebGL2?this.programFactory.create("#version 300 es\n\nin vec4 positionCoords;\nin vec2 textureCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nout vec2 texCoords;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * positionCoords;\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","#version 300 es\nprecision highp float;\n\nin vec2 texCoords;\n\n// texture, mask and darkness\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nout vec4 fragColor;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n fragColor = vec4(texColor.rgb, u_alpha * texColor.a); \n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < u_numLights; i++) {\n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n fragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n fragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"):this.programFactory.create("precision mediump float;\n\nattribute vec2 positionCoords;\nattribute vec2 textureCoords;\n\nvarying vec2 texCoords;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelMatrix;\nuniform mat4 textureMatrix;\n\nvoid main()\n{\n gl_Position = projectionMatrix * modelMatrix * vec4(positionCoords, 0, 1);\n texCoords = (textureMatrix * vec4(textureCoords, 0, 1)).xy;\n}","precision mediump float;\n\nvarying vec2 texCoords;\n\n// texture, mask and darkness\nuniform int u_renderTexture;\nuniform sampler2D u_texImage;\nuniform vec4 u_solidColor;\nuniform int u_useTintColor;\nuniform vec4 u_tintColor;\nuniform int u_useMaskColor;\nuniform vec4 u_maskColor;\nuniform float u_maskColorMix;\nuniform float u_alpha;\n\n// light\nstruct Light {\n vec2 position;\n float radius;\n float smoothMode;\n float intensity;\n};\n\nuniform int u_renderLight;\nuniform Light u_lights[64];\nuniform int u_numLights;\n\nvoid main()\n{\n if (u_renderTexture == 1) {\n vec4 texColor = texture2D(u_texImage, texCoords);\n\n if (texColor.a < 0.0001) {\n discard;\n }\n\n if (u_useTintColor == 1) {\n texColor = u_tintColor * texColor;\n }\n\n if (u_useMaskColor == 1) {\n texColor = mix(texColor, u_maskColor, clamp(u_maskColorMix, 0.0, 1.0));\n }\n\n gl_FragColor = vec4(texColor.rgb, u_alpha * texColor.a);\n } else if (u_renderLight == 1) {\n vec2 fragCoord = gl_FragCoord.xy;\n float alpha = u_alpha;\n\n for (int i = 0; i < 64; i++) {\n if (u_lights[i].intensity == 0.0) continue; \n \n Light light = u_lights[i];\n float dist = distance(fragCoord, light.position);\n \n if (dist < light.radius) {\n alpha -= (light.smoothMode > 0.0 ? smoothstep(light.radius, 0.0, dist) : 1.0) * light.intensity;\n }\n }\n\n alpha = clamp(alpha, 0.0, u_alpha);\n\n gl_FragColor = vec4(u_solidColor.rgb, alpha);\n } else {\n gl_FragColor = vec4(u_solidColor.rgb, u_alpha);\n }\n}"),this.positionCoordsAttr=this.gl.getAttribLocation(this.program,"positionCoords"),this.texCoordsAttr=this.gl.getAttribLocation(this.program,"textureCoords"),this.modelMatrixUniform=this.gl.getUniformLocation(this.program,"modelMatrix"),this.projectionMatrixUniform=this.gl.getUniformLocation(this.program,"projectionMatrix"),this.textureMatrixUniform=this.gl.getUniformLocation(this.program,"textureMatrix"),this.renderTextureUniform=this.gl.getUniformLocation(this.program,"u_renderTexture"),this.textureUniform=this.gl.getUniformLocation(this.program,"u_texImage"),this.solidColorUniform=this.gl.getUniformLocation(this.program,"u_solidColor"),this.useTintColorUniform=this.gl.getUniformLocation(this.program,"u_useTintColor"),this.tintColorUniform=this.gl.getUniformLocation(this.program,"u_tintColor"),this.useMaskColorUniform=this.gl.getUniformLocation(this.program,"u_useMaskColor"),this.maskColorUniform=this.gl.getUniformLocation(this.program,"u_maskColor"),this.maskColorMixUniform=this.gl.getUniformLocation(this.program,"u_maskColorMix"),this.alphaUniform=this.gl.getUniformLocation(this.program,"u_alpha"),this.renderLightUniform=this.gl.getUniformLocation(this.program,"u_renderLight"),this.numLightsUniform=this.gl.getUniformLocation(this.program,"u_numLights"),this.gl.useProgram(this.program),this.gl.blendFunc(this.gl.SRC_ALPHA,this.gl.ONE_MINUS_SRC_ALPHA)}}class Y{constructor(t){this.gl=t}load(t,e){const i=this.gl.createShader(t);this.gl.shaderSource(i,e),this.gl.compileShader(i);const s=this.gl.COMPILE_STATUS;if(!this.gl.getShaderParameter(i,s)){const t=this.gl.getShaderInfoLog(i);throw this.gl.deleteShader(i),new Error(`Unable to initialize the shader program: ${t}`)}return i}}var X="undefined"!=typeof Float32Array?Float32Array:Array;function $(){var t=new X(16);return X!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function K(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function q(t,e,i){var s,r,o,n,a,h,l,c,d,g,m,u,p=i[0],f=i[1],y=i[2];return e===t?(t[12]=e[0]*p+e[4]*f+e[8]*y+e[12],t[13]=e[1]*p+e[5]*f+e[9]*y+e[13],t[14]=e[2]*p+e[6]*f+e[10]*y+e[14],t[15]=e[3]*p+e[7]*f+e[11]*y+e[15]):(s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],h=e[5],l=e[6],c=e[7],d=e[8],g=e[9],m=e[10],u=e[11],t[0]=s,t[1]=r,t[2]=o,t[3]=n,t[4]=a,t[5]=h,t[6]=l,t[7]=c,t[8]=d,t[9]=g,t[10]=m,t[11]=u,t[12]=s*p+a*f+d*y+e[12],t[13]=r*p+h*f+g*y+e[13],t[14]=o*p+l*f+m*y+e[14],t[15]=n*p+c*f+u*y+e[15]),t}function J(t,e,i){var s=i[0],r=i[1],o=i[2];return t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t[3]=e[3]*s,t[4]=e[4]*r,t[5]=e[5]*r,t[6]=e[6]*r,t[7]=e[7]*r,t[8]=e[8]*o,t[9]=e[9]*o,t[10]=e[10]*o,t[11]=e[11]*o,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function Q(t,e,i){var s=Math.sin(i),r=Math.cos(i),o=e[0],n=e[1],a=e[2],h=e[3],l=e[4],c=e[5],d=e[6],g=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=o*r+l*s,t[1]=n*r+c*s,t[2]=a*r+d*s,t[3]=h*r+g*s,t[4]=l*r-o*s,t[5]=c*r-n*s,t[6]=d*r-a*s,t[7]=g*r-h*s,t}Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});var Z=function(t,e,i,s,r,o,n){var a=1/(e-i),h=1/(s-r),l=1/(o-n);return t[0]=-2*a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+i)*a,t[13]=(r+s)*h,t[14]=(n+o)*l,t[15]=1,t};const tt=(t,e,i,s)=>{t=K(t),Z(t,-e.canvas.width/2,e.canvas.width/2,-e.canvas.height/2,e.canvas.height/2,-1,1),J(t,t,[null!=i?i:1,null!=i?i:1,1]),q(t,t,[-s.x,-s.y,0])},et=t=>{const e=/^#?([a-f\d]{2})?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[2],16)/256,g:parseInt(e[3],16)/256,b:parseInt(e[4],16)/256,a:void 0!==e[1]?parseInt(e[1],16)/256:1}:null};class it{constructor(t){this.gl=t}render(t){const e=et(t);this.gl.clearColor(e.r,e.g,e.b,e.a),this.gl.clear(this.gl.COLOR_BUFFER_BIT)}}var st;!function(t){t[t.Sprite=0]="Sprite",t[t.Text=1]="Text",t[t.Tilemap=2]="Tilemap",t[t.Mask=3]="Mask",t[t.Geometric=4]="Geometric",t[t.Video=5]="Video",t[t.Darkness=6]="Darkness"}(st||(st={}));var rt;t.GeometricShape=void 0,(rt=t.GeometricShape||(t.GeometricShape={}))[rt.Polygon=0]="Polygon",rt[rt.Circumference=1]="Circumference",rt[rt.Line=2]="Line";let ot=class{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.linesPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=new Float32Array(n(1,60,1).reduce(((t,e)=>[...t,Math.cos(e*i),Math.sin(e*i)]),[]));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,s,this.gl.STATIC_DRAW)}render(e,i,s){switch(this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),e.shape){case t.GeometricShape.Polygon:this.renderLines(e,i,this.gl.LINE_LOOP);break;case t.GeometricShape.Line:this.renderLines(e,i,this.gl.LINES);break;case t.GeometricShape.Circumference:this.renderCircumference(e,i,s);break;default:return!1}return!0}renderLines(t,e,i){var s;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.linesPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(t.vertexModel.reduce(((t,e)=>[...t,e.x,e.y]),[])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:r,g:o,b:n,a:a}=et(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,r,o,n,a),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(i,0,t.vertexModel.length),this.lastShape="polygon"}renderCircumference(t,e,i){i===st.Geometric&&"circumference"===this.lastShape||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),J(this.modelMatrix,this.modelMatrix,[t.radius,t.radius,1]),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:s,g:r,b:o,a:n}=et(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,s,r,o,n),this.gl.uniform1f(this.programManager.alphaUniform,1),this.gl.drawArrays(this.gl.LINE_LOOP,0,60),this.lastShape="circumference"}};var nt;t.MaskShape=void 0,(nt=t.MaskShape||(t.MaskShape={}))[nt.Rectangle=0]="Rectangle",nt[nt.Circumference=1]="Circumference",nt[nt.Polygon=2]="Polygon";let at=class{constructor(t,e){this.gl=t,this.programManager=e,this.type=st.Mask,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.circumferencePositionBuffer=this.gl.createBuffer(),this.rectanglePositionBuffer=this.gl.createBuffer(),this.polygonPositionBuffer=this.gl.createBuffer();const i=2*Math.PI/60,s=[0,0];for(let t=0;t<=60;t++)s.push(Math.cos(t*i),Math.sin(t*i));this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(s),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(e,i,s){return this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr),e.shape===t.MaskShape.Rectangle?this.renderRectangle(e,i,s):e.shape===t.MaskShape.Circumference?this.renderCircumference(e,i,s):e.shape===t.MaskShape.Polygon&&this.renderPolygon(e,i,s),this.lastShape=e.shape,!0}renderRectangle(e,i,s){var r,o;s===st.Mask&&this.lastShape===t.MaskShape.Rectangle||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.rectanglePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[e.position.x,e.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(r=e.rotation)&&void 0!==r?r:0),J(this.modelMatrix,this.modelMatrix,[e.width,e.height,1]),tt(this.projectionMatrix,this.gl,i.zoom,i.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),e.opacity>=0&&e.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:n,g:a,b:h,a:l}=et(e.color);this.gl.uniform4f(this.programManager.solidColorUniform,n,a,h,l),this.gl.uniform1f(this.programManager.alphaUniform,null!==(o=e.opacity)&&void 0!==o?o:1),this.gl.drawArrays(this.gl.TRIANGLES,0,6)}renderCircumference(e,i,s){var r,o;s===st.Mask&&this.lastShape===t.MaskShape.Circumference||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.circumferencePositionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[e.position.x,e.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(r=e.rotation)&&void 0!==r?r:0),J(this.modelMatrix,this.modelMatrix,[e.radius,e.radius,1]),tt(this.projectionMatrix,this.gl,i.zoom,i.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),e.opacity>=0&&e.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:n,g:a,b:h,a:l}=et(e.color);this.gl.uniform4f(this.programManager.solidColorUniform,n,a,h,l),this.gl.uniform1f(this.programManager.alphaUniform,null!==(o=e.opacity)&&void 0!==o?o:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,62)}renderPolygon(e,i,s){var r,o;s===st.Mask&&this.lastShape===t.MaskShape.Polygon||(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.polygonPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(e.vertices.reduce(((t,e)=>[...t,e.x,e.y]),[0,0])),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[e.position.x,e.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(r=e.rotation)&&void 0!==r?r:0),tt(this.projectionMatrix,this.gl,i.zoom,i.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),e.opacity>=0&&e.opacity<1?this.gl.enable(this.gl.BLEND):this.gl.disable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0);const{r:n,g:a,b:h,a:l}=et(e.color);this.gl.uniform4f(this.programManager.solidColorUniform,n,a,h,l),this.gl.uniform1f(this.programManager.alphaUniform,null!==(o=e.opacity)&&void 0!==o?o:1),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,e.vertices.length+1)}},ht=class{constructor(t,e){this.gl=t,this.programManager=e,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r;i!==st.Darkness&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.disableVertexAttribArray(this.programManager.texCoordsAttr)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.width,t.height,1]),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND),this.gl.uniform1i(this.programManager.renderTextureUniform,0),this.gl.uniform1i(this.programManager.renderLightUniform,1);const{r:o,g:n,b:a,a:h}=et(t.color);this.gl.uniform4f(this.programManager.solidColorUniform,o,n,a,h),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.numLightsUniform,t.lights.length);for(const[i,s]of t.lights.entries()){if(i>=64)break;this.gl.uniform2f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].position`),this.gl.canvas.width/2+(s.position.x-e.position.x)*e.zoom,this.gl.canvas.height/2+(s.position.y-e.position.y)*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].radius`),s.radius*e.zoom),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].smoothMode`),s.smooth?1:0),this.gl.uniform1f(this.gl.getUniformLocation(this.programManager.program,`u_lights[${i}].intensity`),Math.max(0,Math.min(1,s.intensity)))}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.uniform1i(this.programManager.renderLightUniform,0),!0}},lt=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.tiledPosVertices=new Map,this.tiledTexVertices=new Map,this.lastTexture=null,this.isTiled=!1,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.tiledPositionBuffer=this.gl.createBuffer(),this.tiledTextureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW),this.lastDrawMode="sprite"}render(t,e,i){var s,r,o,n;this.isTiled=t.tiled&&(t.tiled.x>1||t.tiled.y>1),this.isTiled||i===st.Sprite&&"sprite"===this.lastDrawMode?this.isTiled&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledPositionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledPositionVertices(t.tiled),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.tiledTextureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,this.getTiledTextureVertices(t.tiled),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)):(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.lastDrawMode=this.isTiled?"tiled":"sprite",this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontally?-1:1),t.height*(t.flipVertically?-1:1),1]),this.textureMatrix=K(this.textureMatrix),t.slice&&(q(this.textureMatrix,this.textureMatrix,[t.slice.x/t.image.naturalWidth,t.slice.y/t.image.naturalHeight,0]),J(this.textureMatrix,this.textureMatrix,[t.slice.width/t.image.naturalWidth,t.slice.height/t.image.naturalHeight,1])),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromImage(t.image,t.smooth);if(this.lastTexture===a&&i===t.type||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=et(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=et(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(n=t.maskColorMix)&&void 0!==n?n:1)}return this.isTiled?this.gl.drawArrays(this.gl.TRIANGLES,0,t.tiled.x*t.tiled.y*6):this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}getTiledPositionVertices(t){const e=t.toString();if(!this.tiledPosVertices.has(e)){const i=[];for(let e=-t.x/2;e<t.x/2;e++)for(let s=-t.y/2;s<t.y/2;s++)i.push(e,s,e,s+1,e+1,s,e+1,s,e,s+1,e+1,s+1);this.tiledPosVertices.set(e,new Float32Array(i))}return this.tiledPosVertices.get(e)}getTiledTextureVertices(t){const e=t.toString();if(!this.tiledTexVertices.has(e)){const i=[];for(let e=0;e<t.x*t.y;e++)i.push(0,1,0,0,1,1,1,1,0,0,1,0);this.tiledTexVertices.set(e,new Float32Array(i))}return this.tiledTexVertices.get(e)}};var ct;t.TextAlignment=void 0,(ct=t.TextAlignment||(t.TextAlignment={}))[ct.Center=0]="Center",ct[ct.Right=1]="Right",ct[ct.Left=2]="Left";let dt=class{constructor(t,e,s,r){this.gl=t,this.programManager=e,this.textureManager=s,this.fontAtlasFactory=r,this.type=st.Text,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.shadowPosition=new i,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,s,r=!1){var o;if(!t.text)return!1;const n=this.fontAtlasFactory.getOrCreate(Object.assign({font:t.font},t.textureAtlas));if(r||(this.generateTextVertices(n,t),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),t.shadow){const{color:r,offset:o,opacity:n}=t.shadow,a=Object.assign(Object.assign({},t),{color:r,opacity:n,position:i.add(this.shadowPosition,t.position,o)});a.shadow=void 0,this.render(a,e,s,!0),s=st.Text}this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(o=t.rotation)&&void 0!==o?o:0),J(this.modelMatrix,this.modelMatrix,[t.fontSize*(t.flipHorizontally?-1:1),t.fontSize*(t.flipVertically?-1:1),1]),this.textureMatrix=K(this.textureMatrix),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromCanvas(n.id,n.canvas,t.smooth);this.lastTexture===a&&s===st.Text||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.useMaskColorUniform,0),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,t.opacity);const{r:h,g:l,b:c,a:d}=et(t.color);return this.gl.uniform1i(this.programManager.useTintColorUniform,1),this.gl.uniform4f(this.programManager.tintColorUniform,h,l,c,d),this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}generateTextVertices(e,i){this.posVertices=[],this.texVertices=[];const s=this.preProcessText(e,i),r=i.letterSpacing/i.fontSize,o=i.lineHeight/i.fontSize,n=i.boundingBox.height/i.fontSize,a=i.boundingBox.width/i.fontSize;let h=n/2;for(const n of s){const{text:s,width:l}=n;let c=i.alignment===t.TextAlignment.Center?-l/2:i.alignment===t.TextAlignment.Left?-a/2:a/2-l;for(const t of s){const i=e.glyphs.get(t);if(i){const t=i.width/e.fontSize;this.posVertices.push(c,h-1,c+t,h-1,c,h,c,h,c+t,h-1,c+t,h);const s=i.id%e.gridSize*(e.fontSize+e.spacing),o=(i.id/e.gridSize|0)*(e.fontSize+e.spacing),n=s/e.canvas.width,a=o/e.canvas.height,l=(s+i.width)/e.canvas.width,d=(o+e.fontSize)/e.canvas.height;this.texVertices.push(n,d,l,d,n,a,n,a,l,d,l,a),c+=t+r}}c=-a/2,h-=o}}preProcessText(t,{text:e,fontSize:i,letterSpacing:s,lineHeight:r,boundingBox:{width:o,height:n}}){const a=[];s/=i,r/=i,o/=i,n/=i;const h=t.glyphs.get(" ").width/t.fontSize+s;let l=0;const c=e.split("\n");for(const e of c){let i=[],c=0;l+=r;const d=e.split(" ");for(const e of d){if(l>n)return a;const d=0===i.length;let g=0;for(const i of e){const e=t.glyphs.get(i);e&&(g+=e.width/t.fontSize+s)}g-=s,d||(g+=h),d&&g>=o?(a.push({width:g,text:e}),l+=r):c+g===o?(i.push(e),a.push({width:c+g,text:i.join(" ")}),i=[],c=0,l+=r):c+g>o?(a.push({width:c,text:i.join(" ")}),i=[e],c=g-h,l+=r):(c+=g,i.push(e))}i.length>0&&a.push({width:c,text:i.join(" ")})}return a}};var gt;t.TilemapOrientation=void 0,(gt=t.TilemapOrientation||(t.TilemapOrientation={}))[gt.Center=0]="Center",gt[gt.RightUp=1]="RightUp",gt[gt.RightDown=2]="RightDown",gt[gt.RightCenter=3]="RightCenter";let mt=class{constructor(t,e,s){this.gl=t,this.programManager=e,this.textureManager=s,this.posVertices=[],this.texVertices=[],this.lastTexture=null,this.tileset={width:0,tileWidth:0,tileHeight:0,texMargin:new i,texSpacing:new i,texWidth:0,texHeight:0,texCorrection:new i},this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer()}render(t,e,i){var s,r,o,n;if(0===t.tiles.reduce(((t,e)=>t+e),0))return!1;if(this.processTileset(t),this.generateVertices(t),0===this.posVertices.length)return!1;this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.posVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array(this.texVertices),this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.tilemap.tileWidth*(t.flipHorizontal?-1:1),t.tilemap.tileHeight*(t.flipVertical?-1:1),1]),this.textureMatrix=K(this.textureMatrix),J(this.textureMatrix,this.textureMatrix,[this.tileset.tileWidth/t.tileset.image.naturalWidth,this.tileset.tileHeight/t.tileset.image.naturalHeight,1]),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromImage(t.tileset.image,t.smooth);if(this.lastTexture===a&&i===st.Tilemap||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=et(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=et(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(n=t.maskColorMix)&&void 0!==n?n:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,this.posVertices.length/2),!0}processTileset({tileset:t}){var e,s,r,o,n,a,h;t.margin=null!==(e=t.margin)&&void 0!==e?e:new i,t.spacing=null!==(s=t.spacing)&&void 0!==s?s:new i,t.correction=null!==(r=t.correction)&&void 0!==r?r:new i,this.tileset.width=t.width,this.tileset.tileWidth=t.tileWidth+(null!==(o=t.margin.x)&&void 0!==o?o:0)+(null!==(n=t.spacing.x)&&void 0!==n?n:0),this.tileset.tileHeight=t.tileHeight+(null!==(a=t.margin.y)&&void 0!==a?a:0)+(null!==(h=t.spacing.y)&&void 0!==h?h:0),this.tileset.texMargin.set(t.margin.x/this.tileset.tileWidth,t.margin.y/this.tileset.tileHeight),this.tileset.texSpacing.set(t.spacing.x/this.tileset.tileWidth,t.spacing.y/this.tileset.tileHeight),this.tileset.texCorrection.set(t.correction.x/this.tileset.tileWidth,t.correction.y/this.tileset.tileHeight),this.tileset.texWidth=1-this.tileset.texMargin.x-this.tileset.texSpacing.x-2*this.tileset.texCorrection.x,this.tileset.texHeight=1-this.tileset.texMargin.y-this.tileset.texSpacing.y-2*this.tileset.texCorrection.y}generateVertices({tiles:t,tilemap:e}){this.posVertices=[],this.texVertices=[];const i=Math.floor(t.length/e.width);t.forEach(((t,s)=>{if(0===t)return;const r=s%e.width-e.width/2,o=i/2-Math.floor(s/e.width);this.posVertices.push(r,o-1,r+1,o-1,r,o,r,o,r+1,o-1,r+1,o);const n=(t-1)%this.tileset.width+this.tileset.texMargin.x+this.tileset.texCorrection.x,a=Math.floor((t-1)/this.tileset.width)+this.tileset.texMargin.y+this.tileset.texCorrection.y;this.texVertices.push(n,a+this.tileset.texHeight,n+this.tileset.texWidth,a+this.tileset.texHeight,n,a,n,a,n+this.tileset.texWidth,a+this.tileset.texHeight,n+this.tileset.texWidth,a)}))}},ut=class{constructor(t,e,i){this.gl=t,this.programManager=e,this.textureManager=i,this.lastTexture=null,this.projectionMatrix=$(),this.modelMatrix=$(),this.textureMatrix=$(),this.positionBuffer=this.gl.createBuffer(),this.textureBuffer=this.gl.createBuffer(),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-.5,-.5,-.5,.5,.5,-.5,.5,-.5,-.5,.5,.5,.5]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([0,1,0,0,1,1,1,1,0,0,1,0]),this.gl.STATIC_DRAW)}render(t,e,i){var s,r,o,n;i!==st.Video&&(this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.positionBuffer),this.gl.enableVertexAttribArray(this.programManager.positionCoordsAttr),this.gl.vertexAttribPointer(this.programManager.positionCoordsAttr,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureBuffer),this.gl.enableVertexAttribArray(this.programManager.texCoordsAttr),this.gl.vertexAttribPointer(this.programManager.texCoordsAttr,2,this.gl.FLOAT,!1,0,0)),this.modelMatrix=K(this.modelMatrix),q(this.modelMatrix,this.modelMatrix,[t.position.x,t.position.y,0]),Q(this.modelMatrix,this.modelMatrix,null!==(s=t.rotation)&&void 0!==s?s:0),J(this.modelMatrix,this.modelMatrix,[t.width*(t.flipHorizontal?-1:1),t.height*(t.flipVertical?-1:1),1]),this.textureMatrix=K(this.textureMatrix),t.slice&&(q(this.textureMatrix,this.textureMatrix,[t.slice.x/t.video.videoWidth,t.slice.y/t.video.videoHeight,0]),J(this.textureMatrix,this.textureMatrix,[t.slice.width/t.video.videoWidth,t.slice.height/t.video.videoHeight,1])),tt(this.projectionMatrix,this.gl,e.zoom,e.position),this.gl.uniformMatrix4fv(this.programManager.projectionMatrixUniform,!1,this.projectionMatrix),this.gl.uniformMatrix4fv(this.programManager.modelMatrixUniform,!1,this.modelMatrix),this.gl.uniformMatrix4fv(this.programManager.textureMatrixUniform,!1,this.textureMatrix),this.gl.enable(this.gl.BLEND);const a=this.textureManager.getOrCreateTextureFromVideo(t.video);if(this.lastTexture===a&&i===st.Video||(this.gl.bindTexture(this.gl.TEXTURE_2D,a),this.gl.uniform1i(this.programManager.textureUniform,0),this.lastTexture=a),t.video.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA&&this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t.video),this.gl.uniform1i(this.programManager.renderTextureUniform,1),this.gl.uniform1f(this.programManager.alphaUniform,null!==(r=t.opacity)&&void 0!==r?r:1),this.gl.uniform1i(this.programManager.useTintColorUniform,t.tintColor?1:0),t.tintColor){const{r:e,g:i,b:s,a:r}=et(t.tintColor);this.gl.uniform4f(this.programManager.tintColorUniform,e,i,s,r)}if(this.gl.uniform1i(this.programManager.useMaskColorUniform,t.maskColor?1:0),t.maskColor){const{r:e,g:i,b:s}=et(t.maskColor);this.gl.uniform4f(this.programManager.maskColorUniform,e,i,s,null!==(o=t.opacity)&&void 0!==o?o:1),this.gl.uniform1f(this.programManager.maskColorMixUniform,null!==(n=t.maskColorMix)&&void 0!==n?n:1)}return this.gl.drawArrays(this.gl.TRIANGLES,0,6),!0}};class pt{constructor(t){this.gl=t}createFromImage(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),t.naturalWidth?this.createFromSource(t,i,e):t.addEventListener("load",(()=>this.createFromSource(t,i,e))),i}createFromCanvas(t,e=!1,i=null){return i=null!=i?i:this.gl.createTexture(),this.createFromSource(t,i,e),i}createPixelTexture(){const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,1,1,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,new Uint8Array([0,0,0,255])),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),t}createFromSource(t,e,i=!1){this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),i?(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR)):(this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.NEAREST),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.NEAREST)),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}}const ft=(t,e)=>`${e?"_smooth_":""}${t}`;class yt{constructor(t){this.textureFactory=t,this.textures=new Map}getOrCreateTextureFromImage(t,e=!1){var i;return null!==(i=this.textures.get(ft(t.src,e)))&&void 0!==i?i:this.createTextureFromImage(t,e)}createTextureFromImage(t,e=!1){const i=this.textureFactory.createFromImage(t,e);return this.textures.set(ft(t.src,e),i),i}getOrCreateTextureFromCanvas(t,e,i=!1){var s;return null!==(s=this.textures.get(ft(t,i)))&&void 0!==s?s:this.createTextureFromCanvas(t,e,i)}createTextureFromCanvas(t,e,i=!1){const s=this.textureFactory.createFromCanvas(e,i);return this.textures.set(ft(t,i),s),s}getOrCreateTextureFromVideo(t){var e;return null!==(e=this.textures.get(t.src))&&void 0!==e?e:this.createTextureFromVideo(t)}createTextureFromVideo(t){const e=this.textureFactory.createPixelTexture();return this.textures.set(t.src,e),e}}const xt={CanvasElement:Symbol.for("CanvasElement"),WebGLManager:Symbol.for("WebGLManager")};var Mt=function(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n},vt=function(t,e){return function(i,s){e(i,s,t)}};let bt=class{constructor(t){this.renderers=new Map;const e=new V(t),i=e.gl,s=e.contextVersion,r=new z(i,s,new H(i,new Y(i))),o=new yt(new pt(i)),n=new N;this.renderers.set(st.Sprite,new lt(i,r,o)),this.renderers.set(st.Text,new dt(i,r,o,n)),this.renderers.set(st.Tilemap,new mt(i,r,o)),this.renderers.set(st.Geometric,new ot(i,r)),this.renderers.set(st.Mask,new at(i,r)),this.renderers.set(st.Video,new ut(i,r,o)),this.renderers.set(st.Darkness,new ht(i,r)),this.canvasColorRenderer=new it(i),r.loadProgram()}render(t,e){this.renderers.get(t.type).render(t,e,this.lastRender)&&(this.lastRender=t.type)}renderCanvasColor(t){this.canvasColorRenderer.render(t)}};bt=Mt([l(xt.WebGLManager),vt(0,c(xt.CanvasElement))],bt);const St=Object.assign(Object.assign(Object.assign({AssetManager:Symbol.for("AssetManager"),CreateSystemService:Symbol.for("CreateSystemService"),GameConfig:Symbol.for("GameConfig"),InputManager:Symbol.for("InputManager"),LoopManager:Symbol.for("LoopManager"),RenderManager:Symbol.for("RenderManager"),SceneManager:Symbol.for("SceneManager"),TimeManager:Symbol.for("TimeManager")},d),j),xt);function Ct(t,e,i,s){var r,o=arguments.length,n=o<3?e:null===s?s=Object.getOwnPropertyDescriptor(e,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(t,e,i,s);else for(var a=t.length-1;a>=0;a--)(r=t[a])&&(n=(o<3?r(n):o>3?r(e,i,n):r(e,i))||n);return o>3&&n&&Object.defineProperty(e,i,n),n}function At(t,e){return function(i,s){e(i,s,t)}}function wt(t,e,i,s){return new(i||(i=Promise))((function(r,o){function n(t){try{h(s.next(t))}catch(t){o(t)}}function a(t){try{h(s.throw(t))}catch(t){o(t)}}function h(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,a)}h((s=s.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class Rt{constructor(){this.buttons=new Map,this.axes=new Map,this._dpadAxes=new i,this._leftStickAxes=new i,this._rightStickAxes=new i}get dpadAxes(){return this._dpadAxes.set(this.dpadRight?1:this.dpadLeft?-1:0,this.dpadUp?1:this.dpadDown?-1:0),this._dpadAxes}get leftStickAxes(){return this._leftStickAxes.set(this.leftStickHorizontal,this.leftStickVertical),this._leftStickAxes}get rightStickAxes(){return this._rightStickAxes.set(this.rightStickHorizontal,this.rightStickVertical),this._rightStickAxes}get dpadUp(){var t;return null!==(t=this.buttons.get(12))&&void 0!==t&&t}get dpadDown(){var t;return null!==(t=this.buttons.get(13))&&void 0!==t&&t}get dpadLeft(){var t;return null!==(t=this.buttons.get(14))&&void 0!==t&&t}get dpadRight(){var t;return null!==(t=this.buttons.get(15))&&void 0!==t&&t}get bottomFace(){var t;return null!==(t=this.buttons.get(0))&&void 0!==t&&t}get rightFace(){var t;return null!==(t=this.buttons.get(1))&&void 0!==t&&t}get leftFace(){var t;return null!==(t=this.buttons.get(2))&&void 0!==t&&t}get topFace(){var t;return null!==(t=this.buttons.get(3))&&void 0!==t&&t}get leftShoulder(){var t;return null!==(t=this.buttons.get(4))&&void 0!==t&&t}get rightShoulder(){var t;return null!==(t=this.buttons.get(5))&&void 0!==t&&t}get leftTrigger(){var t;return null!==(t=this.buttons.get(6))&&void 0!==t&&t}get rightTrigger(){var t;return null!==(t=this.buttons.get(7))&&void 0!==t&&t}get back(){var t;return null!==(t=this.buttons.get(8))&&void 0!==t&&t}get start(){var t;return null!==(t=this.buttons.get(9))&&void 0!==t&&t}get leftStickButton(){var t;return null!==(t=this.buttons.get(10))&&void 0!==t&&t}get rightStickButton(){var t;return null!==(t=this.buttons.get(11))&&void 0!==t&&t}get leftStickHorizontal(){var t;return null!==(t=this.axes.get(0))&&void 0!==t?t:0}get leftStickVertical(){var t;return-(null!==(t=this.axes.get(1))&&void 0!==t?t:0)}get rightStickHorizontal(){var t;return null!==(t=this.axes.get(2))&&void 0!==t?t:0}get rightStickVertical(){var t;return-(null!==(t=this.axes.get(3))&&void 0!==t?t:0)}get anyButtonPressed(){var t;return null!==(t=Array.from(this.buttons.values()).find((t=>t)))&&void 0!==t&&t}vibrate(t=200,e=.2,i=.2,s=0){this.vibrationInput={duration:t,weakMagnitude:e,startDelay:s,strongMagnitude:i}}}class Et{constructor(){this.pressedKeys=[]}isPressed(t){return this.pressedKeys.includes(t)}orPressed(t){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)}andPressed(t){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)}isPressedReturn(t,e,i){return this.pressedKeys.includes(t)?e:i}orPressedReturn(t,e,i){return t.reduce(((t,e)=>t||this.pressedKeys.includes(e)),!1)?e:i}andPressedReturn(t,e,i){return t.reduce(((t,e)=>t&&this.pressedKeys.includes(e)),!0)?e:i}}class _t{constructor(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new i,this.hasMoved=!1,this.wheelScroll=new i}}class Tt{constructor(){this.touching=!1,this.interactions=[]}}t.InputManager=class{constructor(){this.keyboard=new Et,this.mouse=new _t,this.touchScreen=new Tt,this.gamepads=[]}},t.InputManager=Ct([l(St.InputManager)],t.InputManager);const Pt=[60,120,180,240];var Bt;t.TimeManager=class{get deltaTime(){return this.unscaledDeltaTime*this.timeScale}get physicsDeltaTime(){return this.unscaledPhysicsDeltaTime*this.timeScale}get renderDeltaTime(){return this.browserDeltaTime*this.timeScale}get unscaledRenderDeltaTime(){return this.browserDeltaTime}constructor({physicsFramerate:t},e){if(this.entityManager=e,this.timeScale=1,this.browserDeltaTime=0,this.unscaledDeltaTime=0,this.unscaledPhysicsDeltaTime=0,this.maxDeltaTime=1/30,this.thenForGame=0,this.thenForPhysics=0,this.thenForRender=0,this.lastIntervalId=0,this.intervals=new Map,t&&!Pt.includes(t))throw new Error(`Invalid Physics frame rate. Allowed: [${Pt.join(", ")}]`);this.fixedGameFramerate=60,this.fixedGameDeltaTime=parseFloat((1/this.fixedGameFramerate).toFixed(6)),this.fixedPhysicsFramerate=null!=t?t:180,this.fixedPhysicsDeltaTime=parseFloat((1/this.fixedPhysicsFramerate).toFixed(6))}updateForRender(t){this.browserDeltaTime=Math.min(Math.max(0,t-this.thenForRender),this.maxDeltaTime),this.thenForRender=t}updateForGame(t){this.unscaledDeltaTime=Math.min(Math.max(this.fixedGameDeltaTime,t-this.thenForGame),this.maxDeltaTime),this.thenForGame=t}updateForPhysics(t){this.unscaledPhysicsDeltaTime=Math.min(Math.max(0,t-this.thenForPhysics),this.maxDeltaTime),this.thenForPhysics=t}updateIntervals(){if(0!==this.intervals.size)for(const[t,e]of this.intervals)this.intervalHealthCheck(e)?(e.executeImmediately?(e.timer=e.delay,e.executeImmediately=!1):e.timer+=1e3*(e.useTimeScale?this.deltaTime:this.unscaledDeltaTime),e.timer>=e.delay&&(e.callback(),e.times&&--e.times<=0?this.clearInterval(t):e.timer-=e.delay)):this.clearInterval(t)}intervalHealthCheck(t){return!(t.entityRef&&!this.entityManager.isEntityEnabled(t.entityRef))&&!(t.componentRef&&!this.entityManager.isComponentEnabled(t.componentRef))}setInterval({callback:t,delay:e,times:i,executeImmediately:s,entityRef:r,componentRef:o,useTimeScale:n=!0}){const a=++this.lastIntervalId;return this.intervals.set(a,{callback:t,delay:e,times:i,executeImmediately:s,entityRef:r,componentRef:o,timer:0,useTimeScale:n}),a}clearInterval(t){this.intervals.delete(t)}clearAllIntervals(){this.intervals.clear()}},t.TimeManager=Ct([l(St.TimeManager),At(0,c(St.GameConfig)),At(1,c(St.EntityManager))],t.TimeManager),function(t){t[t.Image=0]="Image",t[t.Audio=1]="Audio",t[t.Font=2]="Font",t[t.Video=3]="Video",t[t.Json=4]="Json"}(Bt||(Bt={})),t.AssetManager=class{constructor(){this.assets=[]}getAssetsLoaded(){return this.assets.reduce(((t,e)=>t&&e.loaded),!0)}loadImage(t,e){if(this.getImage(t))return this.getImage(t);const i=new Image;i.crossOrigin="",i.src=t;const s=this.createAsset(t,Bt.Image,i,e),r=()=>s.loaded=!0;return i.complete?r():i.addEventListener("load",r),i}loadAudio(t,e){if(this.getAudio(t))return this.getAudio(t);const i=new Audio;i.src=t;const s=this.createAsset(t,Bt.Audio,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}loadFont(t,e){if(this.getFont(t))return this.getFont(t);const i=new FontFace(t,`url(${e})`),s=this.createAsset(e,Bt.Font,i);return s.family=t,document.fonts.add(i),i.load().then((()=>s.loaded=!0)),i}loadVideo(t,e){if(this.getVideo(t))return this.getVideo(t);const i=document.createElement("video");i.playsInline=!0,i.src=t;const s=this.createAsset(t,Bt.Video,i,e);return i.duration?s.loaded=!0:i.addEventListener("canplaythrough",(()=>s.loaded=!0)),i}loadJson(t,e){return wt(this,void 0,void 0,(function*(){if(this.getJson(t))return this.getJson(t);const i=this.createAsset(t,Bt.Json,null,e),s=yield fetch(t),r=yield s.json();return i.loaded=!0,i.element=r,r}))}getImage(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Image&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getAudio(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Audio&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getFont(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Font&&e.family===t)))||void 0===e?void 0:e.element}getVideo(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Video&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}getJson(t){var e;return null===(e=this.assets.find((e=>e.type===Bt.Json&&(e.url===t||e.name===t))))||void 0===e?void 0:e.element}createAsset(t,e,i,s){this.deleteAssetIfExists({url:t,name:s});const r={type:e,url:t,element:i,loaded:!1,name:s};return this.assets.push(r),r}deleteAssetIfExists({url:t,name:e}){const i=this.assets.findIndex((i=>i.url===t||void 0!==i.name&&i.name===e));-1!==i&&this.assets.splice(i,1)}},t.AssetManager=Ct([l(St.AssetManager)],t.AssetManager);class Dt{get playing(){return"playing"===this.state}get paused(){return"paused"===this.state}get stopped(){return"stopped"===this.state}constructor(t){this.action=void 0,this.stopOnSceneTransition=!0,this.fixedToTimeScale=!1,this.loop=!1,this.state="stopped",this.volume=1,this._currentAudioSource=void 0,this._playPromisePendind=!1,this._playAfterUserInput=!1,Object.assign(this,t)}play(t){t&&(this.audioSource=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}Dt.componentName="AudioPlayer";const Ft={AudioPlayerSystem:Symbol.for("AudioPlayerSystem"),ButtonSystem:Symbol.for("ButtonSystem"),TiledWrapperSystem:Symbol.for("TiledWrapperSystem"),TilemapPreProcessingSystem:Symbol.for("TilemapPreProcessingSystem"),TransformSystem:Symbol.for("TransformSystem"),GamepadSystem:Symbol.for("GamepadSystem"),KeyboardSystem:Symbol.for("KeyboardSystem"),MouseSystem:Symbol.for("MouseSystem"),TouchScreenSystem:Symbol.for("TouchScreenSystem"),UpdateBallColliderShapeSystem:Symbol.for("UpdateBallColliderShapeSystem"),UpdateBoxColliderShapeSystem:Symbol.for("UpdateBoxColliderShapeSystem"),UpdateEdgeColliderShapeSystem:Symbol.for("UpdateEdgeColliderShapeSystem"),UpdatePolygonColliderShapeSystem:Symbol.for("UpdatePolygonColliderShapeSystem"),UpdateTilemapColliderShapeSystem:Symbol.for("UpdateTilemapColliderShapeSystem"),UpdateCollidersAfterRepositionSystem:Symbol.for("UpdateCollidersAfterRepositionSystem"),ApplyRepositionSystem:Symbol.for("ApplyRepositionSystem"),ApplyVelocitySystem:Symbol.for("ApplyVelocitySystem"),ResolveCollisionSystem:Symbol.for("ResolveCollisionSystem"),AnimatorSystem:Symbol.for("AnimatorSystem"),CameraSystem:Symbol.for("CameraSystem"),ClearScreenSystem:Symbol.for("ClearScreenSystem"),CullingSystem:Symbol.for("CullingSystem"),MaskRendererSystem:Symbol.for("MaskRendererSystem"),RenderSystem:Symbol.for("RenderSystem"),DarknessLightRendererSystem:Symbol.for("DarknessLightRendererSystem"),SpriteRendererSystem:Symbol.for("SpriteRendererSystem"),GeometricRendererSystem:Symbol.for("GeometricRendererSystem"),TextRendererSystem:Symbol.for("TextRendererSystem"),TilemapRendererSystem:Symbol.for("TilemapRendererSystem"),VideoRendererSystem:Symbol.for("VideoRendererSystem"),DebugColliderRenderSystem:Symbol.for("DebugColliderRenderSystem"),DebugMousePositionSystem:Symbol.for("DebugMousePositionSystem"),DebugTextRendererSystem:Symbol.for("DebugTextRendererSystem")},Ut=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let It=class{constructor(t,e,i){this.entityManager=t,this.inputManager=e,this.timeManager=i,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{Ut.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(Dt).forEach((({component:{audioSource:t,playing:e}})=>{t&&"string"!=typeof t&&(document.hidden?t.pause():!document.hidden&&e&&t.play(),this.canPlay=!document.hidden)}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,Ut.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}checkGamepad(){return this.canPlay=this.inputManager.gamepads.some((t=>t.anyButtonPressed)),this.canPlay}onUpdate(){(this.canPlay||this.checkGamepad())&&this.entityManager.search(Dt).forEach((({component:t})=>{t.audioSource&&"string"!=typeof t.audioSource&&t.audioSource.duration&&(t._playAfterUserInput&&(t._playAfterUserInput=!1,t.action="play"),t.audioSource!==t._currentAudioSource&&(t._currentAudioSource&&(t._currentAudioSource.pause(),t._currentAudioSource.currentTime=0),t._currentAudioSource=t.audioSource,t.audioSource.currentTime=0,t.state="stopped"),t.audioSource.loop=t.loop,t.audioSource.volume=t.volume,"play"!==t.action||"playing"===t.state||t._playPromisePendind?"pause"===t.action&&"playing"===t.state?(t.audioSource.pause(),t.state="paused"):"stop"!==t.action||t.audioSource.paused&&0===t.audioSource.currentTime?"playing"===t.state&&t.audioSource.paused&&(t.state="stopped"):(t.audioSource.pause(),t.audioSource.currentTime=0,t.state="stopped"):(t._playPromisePendind=!0,t.audioSource.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,t.audioSource.play().then((()=>{t._playPromisePendind=!1,t.state="playing"})).catch((()=>{t._playAfterUserInput=!0,t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),t.action=void 0)}))}onDisabled(){this.entityManager.search(Dt).forEach((({component:{audioSource:t,stopOnSceneTransition:e}})=>{t&&"string"!=typeof t&&e&&(t.pause(),t.currentTime=0)}))}onDestroy(){this.onDisabled()}};var Lt;It=Ct([l(Ft.AudioPlayerSystem),At(0,c(St.EntityManager)),At(1,c(St.InputManager)),At(2,c(St.TimeManager))],It),function(t){t[t.GameLogic=0]="GameLogic",t[t.GamePhysics=1]="GamePhysics",t[t.GamePreRender=2]="GamePreRender",t[t.Physics=3]="Physics",t[t.PreGameLogic=4]="PreGameLogic",t[t.Render=5]="Render",t[t.Transform=6]="Transform"}(Lt||(Lt={}));const jt=(t,e)=>{t.prototype.__system_group||(t.prototype.__system_group=e)};class Ot{constructor(t){this.position=new i,this.scale=new i(1,1),this.rotation=0,this.ignoreParentPosition=!1,this.ignoreParentScale=!1,this.ignoreParentRotation=!1,this.localPosition=new i,this.localScale=new i(1,1),this.localRotation=0,this._awake=!1,this._parent=void 0,Object.assign(this,t)}}Ot.componentName="Transform";const kt="Default",Gt="Debug";class Vt{constructor(t){this.layers=[kt],this.zoom=1,this.depth=0,this.debug=!1,this._renderData={position:new i,depth:0,zoom:1,layers:[]},Object.assign(this,t)}}Vt.componentName="Camera";class Nt{constructor(t){this.fixedToTimeScale=!1,this.layer=kt,this.loop=!1,this.offset=new i,this.playing=!1,this.rotation=0,this.volume=1,this._currentVideoSrc=void 0,this._playPromisePendind=!1,this._renderData={type:st.Video,height:void 0,layer:void 0,position:new i,video:void 0,width:void 0,flipHorizontal:void 0,flipVertical:void 0,maskColor:void 0,maskColorMix:void 0,opacity:void 0,rotation:void 0,slice:void 0,tintColor:void 0},Object.assign(this,t)}play(t){t&&(this.video=t),this.action="play"}pause(){this.action="pause"}stop(){this.action="stop"}}Nt.componentName="VideoRenderer";const Wt=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","pointerup","touchend","keydown","keyup"];let Ht=class{constructor(t,e,s,r,o){this.entityManager=t,this.renderManager=e,this.timeManager=s,this.assetManager=r,this.inputManager=o,this.scaledOffset=new i,this.canPlay=!0,this.userInputErrorCatched=!1,this.userInputEventHandler=()=>{Wt.forEach((t=>{window.removeEventListener(t,this.userInputEventHandler)})),this.canPlay=!0}}onCreate(){document.addEventListener("visibilitychange",(()=>{this.entityManager.search(Nt).forEach((({component:{video:t,playing:e}})=>{t&&"string"!=typeof t&&(document.hidden?t.pause():!document.hidden&&e&&t.play(),this.canPlay=!document.hidden)}))}))}catchUserInput(){this.canPlay=!1,this.userInputErrorCatched=!0,Wt.forEach((t=>window.addEventListener(t,this.userInputEventHandler)))}checkGamepad(){return this.canPlay=this.inputManager.gamepads.some((t=>t.anyButtonPressed)),this.canPlay}onUpdate(){(this.canPlay||this.checkGamepad())&&this.entityManager.search(Nt).forEach((({entity:t,component:e})=>{var s,r;const o=this.entityManager.getComponent(t,Ot);if(!o)throw new Error("VideoRenderer component needs a Transform");if("string"==typeof e.video&&(e.video=this.assetManager.getVideo(e.video),!e.video))throw new Error(`Asset ${e.video} not found`);e.video&&e.video.duration&&(this.checkVideoState(e),this.scaledOffset.set(e.offset.x*o.localScale.x,e.offset.y*o.localScale.y),i.add(e._renderData.position,o.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.video=e.video,e._renderData.width=(null!==(s=e.width)&&void 0!==s?s:e.video.videoWidth)*Math.abs(o.localScale.x),e._renderData.height=(null!==(r=e.height)&&void 0!==r?r:e.video.videoHeight)*Math.abs(o.localScale.y),e._renderData.rotation=o.localRotation+e.rotation,e._renderData.slice=e.slice,e._renderData.flipHorizontal=e.flipHorizontally,e._renderData.flipVertical=e.flipVertically,e._renderData.opacity=e.opacity,e._renderData.maskColor=e.maskColor,e._renderData.maskColorMix=e.maskColorMix,e._renderData.tintColor=e.tintColor,0!==o.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,o),this.renderManager.addRenderData(e._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}checkVideoState(t){const{video:e,action:i,loop:s,volume:r}=t;"string"!=typeof e&&(e.src!==t._currentVideoSrc&&(t._currentVideoSrc=e.src,t.playing=!1,e.currentTime=0),e.loop=s,e.volume=r,e.playbackRate=t.fixedToTimeScale?this.timeManager.timeScale<.0625?0:Math.min(this.timeManager.timeScale,16):1,"play"!==i||t.playing||t._playPromisePendind||!this.canPlay||(t._playPromisePendind=!0,e.play().then((()=>{t._playPromisePendind=!1,t.playing=!0})).catch((()=>{t._playPromisePendind=!1,this.userInputErrorCatched||this.catchUserInput()}))),"play"===i&&e.ended&&(t.action="stop",t.playing=!1),"stop"===i&&e.currentTime>0&&(e.pause(),e.currentTime=0,t.playing=!1),"pause"!==i||e.paused||e.pause())}onDisabled(){this.entityManager.search(Nt).forEach((({component:t})=>{t.video&&"string"!=typeof t.video&&(t.video.pause(),t.video.currentTime=0)}))}onDestroy(){this.onDisabled()}};Ht=Ct([l(Ft.VideoRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.TimeManager)),At(3,c(St.AssetManager)),At(4,c(St.InputManager))],Ht),t.SceneManager=class{constructor(t,e,i,s,r){this.systemManager=t,this.systemFactory=e,this.entityManager=i,this.assetManager=s,this.timeManager=r,this.scenes=new Map,this._loadingScene=!1,this._sceneLoadedThisFrame=!1,this.preserveEntitiesWithComponent=void 0}addScene(t,e,i=!1){const s=new t(this.entityManager,this.assetManager);this.scenes.set(e,s),i&&(this.openingSceneName=e)}loadScene(t,e){if(!this.scenes.has(t))throw new Error(`Invalid scene name: '${t}'`);this.sceneNameToBeLoaded=t,this.preserveEntitiesWithComponent=e}loadOpeningScene(){if(!this.openingSceneName)throw new Error("There is no opening scene");this.sceneNameToBeLoaded=this.openingSceneName}get loadingScene(){return this._loadingScene}get sceneLoadedThisFrame(){return this._sceneLoadedThisFrame}update(){this._sceneLoadedThisFrame=!1,this.sceneNameToBeLoaded&&(this.currentSceneName&&this.destroyCurrentScene(),this.currentSceneName=this.sceneNameToBeLoaded,this.sceneNameToBeLoaded=void 0,this.scenes.get(this.currentSceneName).loadAssets(),this.scenes.get(this.currentSceneName).registerSystems(),this._loadingScene=!0),this._loadingScene&&this.assetManager.getAssetsLoaded()&&(this._loadingScene=!1,this._sceneLoadedThisFrame=!0,this.scenes.get(this.currentSceneName).createEntities(),this.systemManager.update(Lt.Transform),this.systemManager.update(Lt.PreGameLogic),this.scenes.get(this.currentSceneName).systems.forEach(((t,e)=>{this.systemFactory.createSystemIfNotExists(t),this.systemManager.enableSystem(t),this.systemManager.setExecutionOrder(t,e)})))}destroyCurrentScene(){this.systemManager.disableSystem(It),this.systemManager.disableSystem(Ht),this.scenes.get(this.currentSceneName).systems.forEach((t=>this.systemManager.disableSystem(t))),this.entityManager.removeAllEntities(this.preserveEntitiesWithComponent),this.timeManager.clearAllIntervals(),this.systemManager.enableSystem(It),this.systemManager.enableSystem(Ht)}},t.SceneManager=Ct([l(St.SceneManager),At(0,c(St.SystemManager)),At(1,c(St.CreateSystemService)),At(2,c(St.EntityManager)),At(3,c(St.AssetManager)),At(4,c(St.TimeManager))],t.SceneManager);class zt{constructor(t){this.width=0,this.height=0,this.radius=0,this.touchEnabled=!0,this.offset=new i,this.pressed=!1,this.mouseOver=!1,Object.assign(this,t)}}var Yt;zt.componentName="Button",t.ButtonShape=void 0,(Yt=t.ButtonShape||(t.ButtonShape={}))[Yt.Rectangle=0]="Rectangle",Yt[Yt.Circumference=1]="Circumference";let Xt=class{constructor(t,e){this.entityManager=t,this.scaled={position:new i,width:0,height:0,radius:0},this.distance=new i,this.pressedLastFrame=!1,this.mouse=e.mouse,this.touchScreen=e.touchScreen}onUpdate(){this.entityManager.search(zt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("Button component needs a Transform");this.pressedLastFrame=e.pressed,e.pressed=!1,this.scale(e,i),e.mouseOver=this.isMouseOverButton(e),e.pressed=e.mouseOver&&this.mouse.leftButtonPressed,e.touchEnabled&&this.touchScreen.touching&&(this.resolveTouchAndRectangle(e),this.resolveTouchAndCircumference(e)),e.onClick&&!this.pressedLastFrame&&e.pressed&&e.onClick(),e.onPressed&&e.pressed&&e.onPressed()}))}scale(t,{localPosition:e,localScale:i}){this.scaled.width=t.width*i.x,this.scaled.height=t.height*i.y,this.scaled.position.x=e.x+t.offset.x*i.x,this.scaled.position.y=e.y+t.offset.y*i.y,this.scaled.radius=t.radius*Math.max(Math.abs(i.x),Math.abs(i.y))}isMouseOverButton(t){return this.isMouseOverRectangleButton(t)||this.isMouseOverCircumferenceButton(t)}isMouseOverRectangleButton(e){return e.shape===t.ButtonShape.Rectangle&&(a(this.mouse.positionInViewport.x,this.scaled.position.x-this.scaled.width/2,this.scaled.position.x+this.scaled.width/2)&&a(this.mouse.positionInViewport.y,this.scaled.position.y-this.scaled.height/2,this.scaled.position.y+this.scaled.height/2))}isMouseOverCircumferenceButton(e){return e.shape===t.ButtonShape.Circumference&&(i.subtract(this.distance,this.scaled.position,this.mouse.positionInViewport),this.distance.magnitude<=this.scaled.radius)}resolveTouchAndRectangle(e){if(e.shape===t.ButtonShape.Rectangle)for(const{positionInViewport:t,radius:i}of this.touchScreen.interactions){if(e.pressed)return;e.pressed=this.scaled.position.x+this.scaled.width/2>=t.x-i.x&&this.scaled.position.x-this.scaled.width/2<=t.x+i.x&&this.scaled.position.y+this.scaled.height/2>=t.y-i.y&&this.scaled.position.y-this.scaled.height/2<=t.y+i.y}}resolveTouchAndCircumference(e){if(e.shape===t.ButtonShape.Circumference)for(const{positionInViewport:t,radius:s}of this.touchScreen.interactions){if(e.pressed)return;i.subtract(this.distance,this.scaled.position,t),e.pressed=this.distance.magnitude<=this.scaled.radius+Math.max(s.x,s.y)}}};Xt=Ct([l(Ft.ButtonSystem),At(0,c(St.EntityManager)),At(1,c(St.InputManager))],Xt);class $t{constructor(t){Object.assign(this,t)}}$t.componentName="TiledWrapper";class Kt{constructor(t){this.layer=kt,this.tileset=void 0,this.data=[],this.chunks=[],this.width=0,this.height=0,this.tileWidth=void 0,this.tileHeight=void 0,this.tintColor=void 0,this.opacity=1,this.smooth=!1,this._processed=!1,this._renderData=[],Object.assign(this,t)}}Kt.componentName="TilemapRenderer";let qt=class{constructor(t,e){this.entityManager=t,this.assetManager=e}onUpdate(){this.entityManager.search($t).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Kt);if(!i)return;if("string"==typeof e.tilemap&&(e.tilemap=this.assetManager.getJson(e.tilemap),!e.tilemap))throw new Error(`Tilemap ${e.tilemap} not found`);const s=e.tilemap.layers.find((t=>t.name===e.layerToRender&&"tilelayer"===t.type));s&&(e.tilemap.infinite?i.chunks=s.chunks:i.data=s.data,i.width=e.tilemap.width)}))}};qt=Ct([l(Ft.TiledWrapperSystem),At(0,c(St.EntityManager)),At(1,c(St.AssetManager))],qt);const Jt=16;let Qt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Kt).forEach((({component:t})=>{var e,i;t._processed||(t.chunks&&t.chunks.length>0?this.chunksToData(t):t.data&&t.data.length>0&&this.dataToChunks(t),t.tileWidth=null!==(e=t.tileWidth)&&void 0!==e?e:t.tileset.tileWidth,t.tileHeight=null!==(i=t.tileHeight)&&void 0!==i?i:t.tileset.tileHeight,t._processed=!0)}))}dataToChunks(t){t.height=Math.ceil(t.data.length/t.width);const e=Math.ceil(t.width/Jt),i=Math.ceil(t.height/Jt);for(let s=0;s<i;s++)for(let i=0;i<e;i++){const e={x:i*Jt,y:s*Jt,width:Jt,height:Jt,data:[]};for(let i=0;i<e.width*e.height;i++){const s=e.x+i%e.width,r=t.width*(e.y+Math.floor(i/e.width));e.data[i]=s<t.width&&r<t.height*t.width?t.data[r+s]:0}t.chunks.push(e)}}chunksToData(t){t.data=[],t.chunks.forEach((e=>e.data.forEach(((i,s)=>{t.data[t.width*(e.y+Math.floor(s/e.width))+e.x+s%e.width]=i})))),t.height=Math.ceil(t.data.length/t.width)}};Qt=Ct([l(Ft.TilemapPreProcessingSystem),At(0,c(St.EntityManager))],Qt);let Zt=class{constructor(t){this.entityManager=t}onUpdate(){this.entityManager.search(Ot).sort(((t,e)=>this.getBranchLength(t.entity)-this.getBranchLength(e.entity))).forEach((({component:t,entity:e})=>{const s=this.entityManager.getParent(e);s&&this.entityManager.isEntityEnabled(s)&&this.entityManager.isComponentEnabled(s,Ot)?(t._parent||(t._parent=this.entityManager.getComponent(s,Ot),t._awake&&!t.ignoreParentPosition&&i.subtract(t.position,t.localPosition,t._parent.position)),t._parent?this.translateChild(t):this.updateTransform(t)):(t._parent&&this.removeParent(t),this.updateTransform(t)),t._awake=!0}))}getBranchLength(t){const e=this.entityManager.getParent(t);return e?1+this.getBranchLength(e):0}removeParent(t){t._parent=void 0,t.position.copy(t.localPosition),t.rotation=t.localRotation}updateTransform(t){t.localPosition.copy(t.position),t.localScale.copy(t.scale),t.localRotation=t.rotation,t._parent=void 0}translateChild(t){t.localRotation=t.rotation+(t.ignoreParentRotation?0:t._parent.localRotation),t.localScale.x=t.scale.x*(t.ignoreParentScale?1:t._parent.scale.x),t.localScale.y=t.scale.y*(t.ignoreParentScale?1:t._parent.scale.y);const e=t.position.magnitude,i=Math.atan2(t.position.y,t.position.x)+(t.ignoreParentRotation?0:t._parent.localRotation);t.localPosition.set(e*Math.cos(i)+(t.ignoreParentPosition?0:t._parent.localPosition.x),e*Math.sin(i)+(t.ignoreParentPosition?0:t._parent.localPosition.y))}};Zt=Ct([l(Ft.TransformSystem),At(0,c(St.EntityManager))],Zt);let te=class{constructor(t){this.inputManager=t,this.gamepads=new Map,this.eventHandler=t=>{"gamepadconnected"===t.type?this.gamepadConnected(t.gamepad):"gamepaddisconnected"===t.type&&this.gamepadDisconected(t.gamepad)},window.addEventListener("gamepadconnected",this.eventHandler),window.addEventListener("gamepaddisconnected",this.eventHandler)}gamepadConnected(t){this.gamepads.set(t.index,t),this.inputManager.gamepads[t.index]||(this.inputManager.gamepads[t.index]=new Rt,this.inputManager.gamepads[t.index].index=t.index),this.inputManager.gamepads[t.index].id=t.id,this.inputManager.gamepads[t.index].connected=!0}gamepadDisconected(t){this.gamepads.delete(t.index),this.inputManager.gamepads[t.index].connected=!1}onUpdate(){for(const t of this.getGamepadsFromBrowser())t&&(!1===this.gamepads.has(t.index)?this.gamepadConnected(t):this.gamepads.set(t.index,t));this.gamepads.forEach((t=>{const e=this.inputManager.gamepads[t.index];t.buttons.forEach(((t,i)=>e.buttons.set(i,t.pressed))),t.axes.forEach(((t,i)=>e.axes.set(i,t))),e.vibrationInput&&(t.vibrationActuator.playEffect(t.vibrationActuator.type,{duration:e.vibrationInput.duration,weakMagnitude:e.vibrationInput.weakMagnitude,strongMagnitude:e.vibrationInput.strongMagnitude,startDelay:e.vibrationInput.startDelay}).catch((()=>e.vibrating=!1)).finally((()=>e.vibrating=!1)),e.vibrating=!0,e.vibrationInput=void 0)}))}getGamepadsFromBrowser(){return navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads:[]}};te=Ct([l(Ft.GamepadSystem),At(0,c(St.InputManager))],te);let ee=class{constructor(t,{keyboard:e}){this.pressedKeys=[],this.eventHandler=t=>{"keydown"!==t.type||this.pressedKeys.includes(t.code)||this.pressedKeys.push(t.code),"keyup"===t.type&&this.pressedKeys.includes(t.code)&&this.pressedKeys.splice(this.pressedKeys.indexOf(t.code),1)},this.keyboard=e,t.addEventListener("keydown",this.eventHandler),t.addEventListener("keyup",this.eventHandler),t.addEventListener("focusout",(()=>this.pressedKeys=[]))}onUpdate(){this.keyboard.pressedKeys=[...this.pressedKeys]}};ee=Ct([l(Ft.KeyboardSystem),At(0,c(St.CanvasElement)),At(1,c(St.InputManager))],ee);let ie=class{constructor(t,{mouse:e}){this.canvas=t,this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1,this.positionInViewport=new i,this.lastPositionInViewport=new i,this.mouse=e,this.canvas.addEventListener("mousemove",(t=>this.updatePosition(t))),this.canvas.addEventListener("mousedown",(t=>this.updateButtonDown(t))),this.canvas.addEventListener("mouseup",(t=>this.updateButtonUp(t))),this.canvas.addEventListener("wheel",(t=>this.handleWheelEvent(t))),this.canvas.addEventListener("focusout",(()=>this.onFocusOut()))}updateButtonDown(t){this.canvas.focus(),t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0===t.button||this.leftButtonPressed,this.scrollButtonPressed=1===t.button||this.scrollButtonPressed,this.rightButtonPressed=2===t.button||this.rightButtonPressed}updateButtonUp(t){t.preventDefault(),t.stopPropagation(),this.leftButtonPressed=0!==t.button&&this.leftButtonPressed,this.scrollButtonPressed=1!==t.button&&this.scrollButtonPressed,this.rightButtonPressed=2!==t.button&&this.rightButtonPressed}updatePosition(t){t.preventDefault(),t.stopPropagation(),this.positionInViewport.set(t.offsetX/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-t.offsetY/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2)}handleWheelEvent(t){t.preventDefault(),t.stopPropagation(),this.wheelEvent=t}onFocusOut(){this.leftButtonPressed=!1,this.scrollButtonPressed=!1,this.rightButtonPressed=!1}onUpdate(){this.mouse.leftButtonPressed=this.leftButtonPressed,this.mouse.rightButtonPressed=this.rightButtonPressed,this.mouse.scrollButtonPressed=this.scrollButtonPressed,this.mouse.positionInViewport.copy(this.positionInViewport),this.positionInViewport.equals(this.lastPositionInViewport)?this.mouse.hasMoved=!1:(this.mouse.hasMoved=!0,this.lastPositionInViewport.copy(this.positionInViewport)),this.wheelEvent?(this.mouse.wheelScroll.set(this.wheelEvent.deltaX,this.wheelEvent.deltaY),this.wheelEvent=void 0):this.mouse.wheelScroll.set(0,0)}};ie=Ct([l(Ft.MouseSystem),At(0,c(St.CanvasElement)),At(1,c(St.InputManager))],ie);let se=class{constructor(t,{touchScreen:e}){this.canvas=t,this.touching=!1,this.interactions=[],this.eventHandler=t=>{"touchstart"===t.type&&(this.touching=!0,this.updatePosition(t)),"touchmove"===t.type&&this.updatePosition(t),"touchend"!==t.type&&"touchcancel"!==t.type||(this.touching=!1)},this.touchScreen=e,this.canvas.addEventListener("touchstart",this.eventHandler),this.canvas.addEventListener("touchend",this.eventHandler),this.canvas.addEventListener("touchcancel",this.eventHandler),this.canvas.addEventListener("touchmove",this.eventHandler)}updatePosition(t){if(t.preventDefault(),t.stopPropagation(),this.interactions=[],0!==t.targetTouches.length)for(let e=0;e<t.targetTouches.length;e++)this.interactions[e]={positionInViewport:new i((t.targetTouches[e].clientX-this.canvas.offsetLeft)/(this.canvas.clientWidth/this.canvas.width)-this.canvas.width/2,-(t.targetTouches[e].clientY-this.canvas.offsetTop)/(this.canvas.clientHeight/this.canvas.height)+this.canvas.height/2),radius:new i(t.targetTouches[e].radiusX,t.targetTouches[e].radiusY)}}onUpdate(){this.touchScreen.touching=this.touching,this.touchScreen.interactions=this.touching?[...this.interactions]:[]}};se=Ct([l(Ft.TouchScreenSystem),At(0,c(St.CanvasElement)),At(1,c(St.InputManager))],se);class re{constructor(t){this.animations=new Map,this.speed=1,this.reset=!1,this.playing=!1,this.currentFrame=0,this.currentTime=0,this.ignoreTimeScale=!1,this._currentAnimation=void 0,this._assetsReady=!1,Object.assign(this,t)}}re.componentName="Animator";class oe{constructor(t){this.layer=kt,this.smooth=!1,this.offset=new i,this.flipHorizontally=!1,this.flipVertically=!1,this.rotation=0,this.opacity=1,this.scale=new i(1,1),this._renderData={type:st.Sprite,position:new i,layer:void 0,image:void 0,width:void 0,height:void 0},Object.assign(this,t)}}oe.componentName="SpriteRenderer";let ne=class{constructor(t,e,i){this.entityManager=t,this.timeManager=e,this.assetManager=i}onUpdate(){this.entityManager.search(re).forEach((({entity:t,component:e})=>{if(this.processAssets(e),this.reset(e),this.animation=e.animations.get(e.animation),!this.animation)return;this.play(e),e._currentAnimation=e.animation;const i=this.entityManager.getComponent(t,oe);i&&this.renderSprite(e,i)}))}processAssets(t){t._assetsReady||(t.animations.forEach((t=>{if("string"==typeof t.image){if(t.image=this.assetManager.getImage(t.image),!t.image)throw new Error(`Asset ${t.image} not found`)}else Array.isArray(t.image)&&(t.image=t.image.map((t=>{if("string"==typeof t){const e=this.assetManager.getImage(t);if(!e)throw new Error(`Asset ${t} not found`);return e}return t})))})),t._assetsReady=!0)}reset(t){t.reset&&(t.currentFrame=0,t.currentTime=0,t.playing=void 0!==t.animation,t.reset=!1)}play(t){t.animation!==t._currentAnimation&&(t._currentAnimation=t.animation,t.currentFrame=0,t.currentTime=0,t.playing=!0),t.playing&&(t.currentTime>=1/this.animation.fps*(t.currentFrame+1)&&(t.currentFrame===this.animation.frames.length-1?this.animation.loop?(t.currentFrame=0,t.currentTime=0):t.playing=!1:t.currentFrame++),t.currentTime+=(t.ignoreTimeScale?this.timeManager.unscaledRenderDeltaTime:this.timeManager.renderDeltaTime)*t.speed)}renderSprite(t,e){if(Array.isArray(this.animation.image))e.image=this.animation.image[t.currentFrame];else{if("string"==typeof this.animation.image)return;const i=this.animation.frames[t.currentFrame],s=Math.floor(this.animation.image.naturalWidth/this.animation.slice.size.x);e.image=this.animation.image,e.slice={x:i%s*this.animation.slice.size.x+this.animation.slice.offset.x,y:Math.floor(i/s)*this.animation.slice.size.y+this.animation.slice.offset.y,width:this.animation.slice.size.x-this.animation.slice.padding.y,height:this.animation.slice.size.y-this.animation.slice.padding.y}}}};ne=Ct([l(Ft.AnimatorSystem),At(0,c(St.EntityManager)),At(1,c(St.TimeManager)),At(2,c(St.AssetManager))],ne);let ae=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){this.entityManager.search(Vt).forEach((({entity:t,component:e})=>{const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("Camera component needs a Transform");e._renderData.position.copy(i.localPosition),e._renderData.layers=[...e.layers],e._renderData.depth=e.depth,e._renderData.zoom=e.zoom,e.debug&&e._renderData.layers.push(Gt),this.renderManager.addCameraData(e._renderData)}))}};ae=Ct([l(Ft.CameraSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],ae);let he=class{constructor(t,e){this.webGLManager=t,this.gameConfig=e}onUpdate(){this.webGLManager.renderCanvasColor(this.gameConfig.canvasColor)}};he=Ct([l(Ft.ClearScreenSystem),At(0,c(St.WebGLManager)),At(1,c(St.GameConfig))],he);class le{constructor(t){this.radius=0,this.offset=new i,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}le.componentName="BallCollider";class ce{constructor(t){this.layer="",this.physics=!0,this.width=0,this.height=0,this.offset=new i,this.rotation=0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}ce.componentName="BoxCollider";class de{constructor(t){this.vertexModel=[],this.offset=new i,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}de.componentName="EdgeCollider";class ge{constructor(t){this.vertexModel=[],this.offset=new i,this.rotation=0,this.layer="",this.physics=!0,this.ignoreCollisionsWithLayers=[],this.shapes=[],Object.assign(this,t)}}ge.componentName="PolygonCollider";class me{constructor(t){this.composite=!0,this.layer="",this.ignoreCollisionsWithLayers=[],this.offset=new i,this.physics=!0,this.shapes=[],Object.assign(this,t)}}me.componentName="TilemapCollider";let ue=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.gameConfig=i}onUpdate(){var e;(null===(e=this.gameConfig.debug)||void 0===e?void 0:e.colliders)&&[le,ce,ge,de,me].forEach((e=>this.entityManager.search(e).forEach((({component:e})=>e.shapes.forEach((e=>{const s={type:st.Geometric,position:new i,layer:Gt,color:this.gameConfig.debug.collidersColor,shape:void 0,radius:void 0,rotation:void 0,vertexModel:void 0};e instanceof x?this.gameConfig.collisions.collisionMethod===t.CollisionMethods.SAT?(s.shape=e.vertices.length>2?t.GeometricShape.Polygon:t.GeometricShape.Line,s.vertexModel=e.vertices):this.gameConfig.collisions.collisionMethod===t.CollisionMethods.AABB&&(s.shape=t.GeometricShape.Polygon,s.vertexModel=[new i(e.boundingBox.x,e.boundingBox.y),new i(e.boundingBox.x,e.boundingBox.y1),new i(e.boundingBox.x1,e.boundingBox.y1),new i(e.boundingBox.x1,e.boundingBox.y)]):e instanceof M&&(s.shape=t.GeometricShape.Circumference,s.position.copy(e.position),s.radius=e.radius),this.renderManager.addRenderData(s)}))))))}};ue=Ct([l(Ft.DebugColliderRenderSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.GameConfig))],ue);let pe=class{constructor(t,e){this.renderManager=t,this.canvas=e,this.viewport={x:0,x1:0,y:0,y1:0},this.object={x:0,x1:0,y:0,y1:0},this.culledRenderData=[]}onUpdate(){this.culledRenderData=[],this.renderManager.getCameraData().forEach((t=>{this.setViewport(t),this.renderManager.getRenderData().filter((e=>t.layers.includes(e.layer))).forEach((t=>{this.isInViewPort(t)&&(t.type===st.Tilemap&&this.applyCullingInTiles(t),this.culledRenderData.push(t))}))})),this.renderManager.setRenderData(this.culledRenderData)}isInViewPort(t){switch(t.type){case st.Video:case st.Darkness:case st.Sprite:this.setObjectForResizeable(t);break;case st.Mask:this.setObjectForMask(t);break;case st.Geometric:this.setObjectForGeometric(t);break;case st.Text:this.setObjectForText(t);break;case st.Tilemap:this.setObjectForTilemap(t)}return this.viewport.x1>=this.object.x&&this.viewport.x<=this.object.x1&&this.viewport.y1>=this.object.y&&this.viewport.y<=this.object.y1}setViewport({position:t,zoom:e}){this.viewport.x=t.x-this.canvas.width/e/2,this.viewport.x1=t.x+this.canvas.width/e/2,this.viewport.y=t.y-this.canvas.height/e/2,this.viewport.y1=t.y+this.canvas.height/e/2}setObjectForResizeable({position:t,width:e,height:i,rotation:s=0,tiled:r}){const o=Math.abs(Math.sin(s)),n=Math.abs(Math.cos(s));r&&(e*=r.x,i*=r.y);const a=o*i+n*e,h=o*e+n*i;this.object.x=t.x-a/2,this.object.x1=t.x+a/2,this.object.y=t.y-h/2,this.object.y1=t.y+h/2}setObjectForText({position:t,text:e,fontSize:i,lineHeight:s,letterSpacing:r,rotation:o}){const n=e.split("\n").reduce(((t,e)=>Math.max(t,e.length)),0)*(i+(null!=r?r:0))*2,a=e.split("\n").length*(null!=s?s:i);this.setObjectForResizeable({position:t,width:n,height:a,rotation:o})}setObjectForGeometric({position:e,vertexModel:i,shape:s,radius:r}){s===t.GeometricShape.Circumference?(this.object.x=e.x-r,this.object.y=e.y-r,this.object.x1=e.x+r,this.object.y1=e.y+r):(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,i.forEach((t=>{this.object.x=Math.min(t.x+e.x,this.object.x),this.object.y=Math.min(t.y+e.y,this.object.y),this.object.x1=Math.max(t.x+e.x,this.object.x1),this.object.y1=Math.max(t.y+e.y,this.object.y1)})))}setObjectForMask({position:e,vertices:i,shape:s,radius:r,rotation:o,width:n,height:a}){s===t.MaskShape.Circumference?(this.object.x=e.x-r,this.object.y=e.y-r,this.object.x1=e.x+r,this.object.y1=e.y+r):s===t.MaskShape.Polygon?(this.object.x=Number.MAX_SAFE_INTEGER,this.object.y=Number.MAX_SAFE_INTEGER,this.object.x1=Number.MIN_SAFE_INTEGER,this.object.y1=Number.MIN_SAFE_INTEGER,i.forEach((t=>{this.object.x=Math.min(t.x+e.x,this.object.x),this.object.y=Math.min(t.y+e.y,this.object.y),this.object.x1=Math.max(t.x+e.x,this.object.x1),this.object.y1=Math.max(t.y+e.y,this.object.y1)}))):this.setObjectForResizeable({position:e,width:n,height:a,rotation:o})}setObjectForTilemap(t){t.tilemap.height=Math.ceil(t.tiles.length/t.tilemap.width),this.setObjectForResizeable({position:t.position,width:t.tilemap.width*t.tilemap.tileWidth,height:t.tilemap.height*t.tilemap.tileHeight,rotation:t.rotation})}applyCullingInTiles(t){const{tiles:e,tilemap:{width:i,tileWidth:s,tileHeight:r}}=t;t.tiles=e.map(((t,e)=>this.viewport.x1>=this.object.x+e%i*s&&this.viewport.x<=this.object.x+e%i*s+s&&this.viewport.y1>=this.object.y1-((e/i|0)*r+r)&&this.viewport.y<=this.object.y1-(e/i|0)*r?t:0))}};pe=Ct([l(Ft.CullingSystem),At(0,c(St.RenderManager)),At(1,c(St.CanvasElement))],pe);class fe{constructor(t){this.width=0,this.height=0,this.radius=0,this.vertexModel=[],this.color="#000000",this.offset=new i,this.rotation=0,this.opacity=1,this.layer=kt,this._renderData={type:st.Mask,color:void 0,height:void 0,vertices:[],layer:void 0,opacity:void 0,position:new i,radius:void 0,rotation:void 0,shape:void 0,width:void 0},Object.assign(this,t)}}fe.componentName="MaskRenderer";let ye=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new i}onUpdate(){this.entityManager.search(fe).forEach((({entity:e,component:s})=>{const r=this.entityManager.getComponent(e,Ot);if(!r)throw new Error("MaskRenderer component needs a Transform");this.scaledOffset.set(s.offset.x*r.localScale.x,s.offset.y*r.localScale.y),i.add(s._renderData.position,r.localPosition,this.scaledOffset),s._renderData.width=s.width*Math.abs(r.localScale.x),s._renderData.height=s.height*Math.abs(r.localScale.y),s._renderData.rotation=r.localRotation+s.rotation,s._renderData.color=s.color,s._renderData.layer=s.layer,s._renderData.opacity=s.opacity,s._renderData.radius=s.radius*Math.max(Math.abs(r.localScale.x),Math.abs(r.localScale.y)),s._renderData.shape=s.shape,s.shape===t.MaskShape.Polygon&&(s._renderData.vertices.length!==s.vertexModel.length&&(s._renderData.vertices=s.vertexModel.map((()=>new i))),s.vertexModel.forEach(((t,e)=>s._renderData.vertices[e].set(t.x*r.localScale.x,t.y*r.localScale.y))),0!==r.localRotation&&s._renderData.vertices.forEach((t=>t.set(t.x*Math.cos(r.localRotation)-t.y*Math.sin(r.localRotation),t.x*Math.sin(r.localRotation)+t.y*Math.cos(r.localRotation))))),0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(s._renderData,r),this.renderManager.addRenderData(s._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};ye=Ct([l(Ft.MaskRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],ye);let xe=class{constructor(t){this.renderManager=t}onUpdate(){this.renderManager.render(),this.renderManager.removeCameraData(),this.renderManager.removeRenderData()}};xe=Ct([l(Ft.RenderSystem),At(0,c(St.RenderManager))],xe);class Me{constructor(t){this.radius=0,this.smooth=!1,this.layer=kt,this.intensity=1,this._boundingBox=new s,Object.assign(this,t)}}Me.componentName="LightRenderer";class ve{constructor(t){this.width=0,this.height=0,this.color="#000000",this.opacity=1,this.layer=kt,this._boundingBox=new s,this._renderData={type:st.Darkness,layer:void 0,color:void 0,opacity:void 0,width:void 0,height:void 0,position:void 0,rotation:void 0,lights:[]},Object.assign(this,t)}}ve.componentName="DarknessRenderer";let be=class{constructor(t,e){this.entityManager=t,this.renderManager=e}onUpdate(){const t=this.entityManager.search(Me);t.forEach((({entity:t,component:e})=>this.updateLightRendererBoundingBox(t,e))),this.entityManager.search(ve).forEach((({entity:e,component:i})=>{this.updatDarknessRendererBoundingBox(e,i),i._renderData.layer=i.layer,i._renderData.color=i.color,i._renderData.opacity=i.opacity,i._renderData.width=i._boundingBox.width,i._renderData.height=i._boundingBox.height,i._renderData.position=i._boundingBox.center,i._renderData.rotation=0,i._renderData.lights=[],i._renderData.lights=t.filter((({component:t})=>t.layer===i.layer&&t._boundingBox.intersects(i._boundingBox))).map((({component:{_boundingBox:t,smooth:e,intensity:i}})=>({position:t.center,radius:t.width/2,smooth:e,intensity:i}))),this.renderManager.addRenderData(i._renderData)}))}updateLightRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("LightRenderer component needs a Transform");const s=e.radius*Math.abs(Math.max(i.localScale.x,i.localScale.y));e._boundingBox.set(i.localPosition.x-s,i.localPosition.y-s,2*s,2*s)}updatDarknessRendererBoundingBox(t,e){const i=this.entityManager.getComponent(t,Ot);if(!i)throw new Error("DarknessRenderer component needs a Transform");const s=e.width*Math.abs(i.localScale.x),r=e.height*Math.abs(i.localScale.y);e._boundingBox.set(i.localPosition.x-s/2,i.localPosition.y-r/2,s,r)}};be=Ct([l(Ft.DarknessLightRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],be);class Se{constructor(e){this.shape=t.GeometricShape.Polygon,this.color="#FFFFFF",this.layer=kt,this.vertexModel=[],this.radius=0,this.offset=new i,this.rotation=0,this._renderData={type:st.Geometric,position:new i,layer:kt,color:"#FFFFFF",shape:t.GeometricShape.Polygon,vertexModel:[],rotation:0,radius:0},Object.assign(this,e)}}Se.componentName="GeometricRenderer";let Ce=class{constructor(t,e){this.entityManager=t,this.renderManager=e,this.scaledOffset=new i}onUpdate(){this.entityManager.search(Se).forEach((({entity:e,component:s})=>{const r=this.entityManager.getComponent(e,Ot);if(!r)throw new Error("GeometricRenderer component needs a Transform");if(!this.isValidGeometry(s))return;this.scaledOffset.set(s.offset.x*r.localScale.x,s.offset.y*r.localScale.y),i.add(s._renderData.position,r.localPosition,this.scaledOffset),s._renderData.layer=s.layer,s._renderData.color=s.color,s._renderData.shape=s.shape,s._renderData.rotation=r.localRotation+s.rotation,0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(s._renderData,r);const o=r.localScale.x,n=r.localScale.y;s.shape===t.GeometricShape.Circumference?(s._renderData.radius=s.radius*Math.max(Math.abs(o),Math.abs(n)),s._renderData.vertexModel.length=0):(this.ensureVertexModelLength(s,s.vertexModel.length),s.vertexModel.forEach(((t,e)=>s._renderData.vertexModel[e].set(t.x*o,t.y*n)))),this.renderManager.addRenderData(s._renderData)}))}isValidGeometry(e){switch(e.shape){case t.GeometricShape.Circumference:return e.radius>0;case t.GeometricShape.Polygon:return e.vertexModel.length>=3;case t.GeometricShape.Line:return e.vertexModel.length>=2&&e.vertexModel.length%2==0;default:return!1}}ensureVertexModelLength(t,e){const s=t._renderData.vertexModel;for(;s.length<e;)s.push(new i);s.length=e}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};Ce=Ct([l(Ft.GeometricRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager))],Ce);let Ae=class{constructor(t,e,s){this.entityManager=t,this.renderManager=e,this.assetManager=s,this.scaledOffset=new i}onUpdate(){this.entityManager.search(oe).forEach((({component:t,entity:e})=>{var s,r,o,n,a,h;const l=this.entityManager.getComponent(e,Ot);if(!l)throw new Error("SpriteRenderer component needs a Transform");if("string"==typeof t.image&&(t.image=this.assetManager.getImage(t.image),!t.image))throw new Error(`Asset ${t.image} not found`);t.image&&t.image.complete&&(this.scaledOffset.set(t.offset.x*l.localScale.x,t.offset.y*l.localScale.y),i.add(t._renderData.position,l.localPosition,this.scaledOffset),t._renderData.width=(null!==(o=null!==(s=t.width)&&void 0!==s?s:null===(r=t.slice)||void 0===r?void 0:r.width)&&void 0!==o?o:t.image.naturalWidth)*Math.abs(t.scale.x*l.localScale.x),t._renderData.height=(null!==(h=null!==(n=t.height)&&void 0!==n?n:null===(a=t.slice)||void 0===a?void 0:a.height)&&void 0!==h?h:t.image.naturalHeight)*Math.abs(t.scale.y*l.localScale.y),t._renderData.flipHorizontally=t.flipHorizontally!==l.scale.x<0,t._renderData.flipVertically=t.flipVertically!==l.scale.y<0,t._renderData.rotation=l.localRotation+t.rotation,0!==l.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(t._renderData,l),t._renderData.image=t.image,t._renderData.layer=t.layer,t._renderData.maskColor=t.maskColor,t._renderData.maskColorMix=t.maskColorMix,t._renderData.opacity=t.opacity,t._renderData.slice=t.slice,t._renderData.smooth=t.smooth,t._renderData.tintColor=t.tintColor,t._renderData.tiled=t.tiled,this.renderManager.addRenderData(t._renderData))}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};Ae=Ct([l(Ft.SpriteRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.AssetManager))],Ae);const we={charRanges:[32,126,161,255],fontSize:64,spacing:8};class Re{constructor(e){this.color="#000000",this.flipHorizontally=!1,this.flipVertically=!1,this.font="Arial",this.fontSize=16,this.height=16,this.layer=kt,this.letterSpacing=0,this.lineHeight=void 0,this.offset=new i,this.opacity=1,this.alignment=t.TextAlignment.Center,this.rotation=0,this.shadow=void 0,this.smooth=!1,this.text="Hello World!",this.textureAtlas=Object.assign({},we),this.width=192,this._renderData={color:void 0,flipHorizontally:!1,flipVertically:!1,font:void 0,fontSize:void 0,layer:void 0,letterSpacing:void 0,lineHeight:void 0,opacity:void 0,position:new i,rotation:void 0,shadow:void 0,smooth:void 0,text:void 0,textureAtlas:Object.assign({},we),type:st.Text,boundingBox:{width:0,height:0},alignment:void 0},Object.assign(this,e)}}Re.componentName="TextRenderer";let Ee=class{constructor(t,e,s){this.entityManager=t,this.renderManager=e,this.assetManager=s,this.scaledOffset=new i}onUpdate(){this.entityManager.search(Re).forEach((({entity:t,component:e})=>{var s;const r=this.entityManager.getComponent(t,Ot);if(!r)throw new Error("TextRenderer component needs a Transform");if("string"==typeof e.font){const t=this.assetManager.getFont(e.font);t&&(e.font=t)}if(0===e.text.length||e.font instanceof FontFace&&"loaded"!==e.font.status)return;this.scaledOffset.set(e.offset.x*r.localScale.x,e.offset.y*r.localScale.y),i.add(e._renderData.position,r.localPosition,this.scaledOffset),e._renderData.layer=e.layer,e._renderData.font=e.font,e._renderData.fontSize=e.fontSize,e._renderData.text=e.text,e._renderData.color=e.color,e._renderData.lineHeight=null!==(s=e.lineHeight)&&void 0!==s?s:e.fontSize,e._renderData.letterSpacing=e.letterSpacing,e._renderData.smooth=e.smooth,e._renderData.rotation=r.localRotation+e.rotation,e._renderData.opacity=e.opacity,e._renderData.boundingBox={width:e.width,height:e.height},e._renderData.alignment=e.alignment;const{charRanges:o,fontSize:n,spacing:a}=e.textureAtlas;o&&(e._renderData.textureAtlas.charRanges=e.textureAtlas.charRanges),n&&(e._renderData.textureAtlas.fontSize=e.textureAtlas.fontSize),a&&(e._renderData.textureAtlas.spacing=e.textureAtlas.spacing),e._renderData.flipHorizontally=e.flipHorizontally,e._renderData.flipVertically=e.flipVertically,e._renderData.shadow=e.shadow,0!==r.localRotation&&this.scaledOffset.magnitude>0&&this.translateRenderPosition(e._renderData,r),this.renderManager.addRenderData(e._renderData)}))}translateRenderPosition(t,e){const i=Math.atan2(this.scaledOffset.y,this.scaledOffset.x)+e.localRotation;t.position.set(e.localPosition.x+this.scaledOffset.magnitude*Math.cos(i),e.localPosition.y+this.scaledOffset.magnitude*Math.sin(i))}};Ee=Ct([l(Ft.TextRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.AssetManager))],Ee);let _e=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.assetManager=i}onUpdate(){this.entityManager.search(Kt).forEach((({entity:e,component:s})=>{const r=this.entityManager.getComponent(e,Ot);if(!r)throw new Error("TilemapRenderer component needs a Transform");if("string"==typeof s.tileset.image&&(s.tileset.image=this.assetManager.getImage(s.tileset.image),!s.tileset.image))throw new Error(`Asset ${s.tileset.image} not found`);s._processed&&s.tileset.image&&s.tileset.image.complete&&s.chunks.forEach(((e,o)=>{s._renderData[o]||(s._renderData[o]=Te());const n=s._renderData[o];n.type=st.Tilemap,n.orientation=t.TilemapOrientation.Center,n.position=new i,n.layer=s.layer,n.tilemap.width=e.width,n.tilemap.height=Math.ceil(s.data.length/e.width),n.tilemap.tileWidth=s.tileWidth*Math.abs(r.localScale.x),n.tilemap.tileHeight=s.tileHeight*Math.abs(r.localScale.y),n.tilemap.realWidth=n.tilemap.width*n.tilemap.tileWidth,n.tilemap.realHeight=n.tilemap.height*n.tilemap.tileHeight,n.tiles=e.data,n.tileset=s.tileset,n.opacity=s.opacity,n.rotation=r.localRotation,n.tintColor=s.tintColor,n.smooth=s.smooth,n.maskColor=s.maskColor,n.maskColorMix=s.maskColorMix,n.position.x=r.localPosition.x+(e.x-s.width/2+e.width/2)*n.tilemap.tileWidth,n.position.y=r.localPosition.y+(s.height/2-e.y-e.height/2)*n.tilemap.tileHeight,this.renderManager.addRenderData(n)}))}))}};_e=Ct([l(Ft.TilemapRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.AssetManager))],_e);const Te=()=>({type:st.Tilemap,layer:void 0,position:new i,tilemap:{height:void 0,realHeight:void 0,realWidth:void 0,tileHeight:void 0,tileWidth:void 0,width:void 0},tiles:void 0,tileset:void 0});var Pe;t.RigidBodyType=void 0,(Pe=t.RigidBodyType||(t.RigidBodyType={}))[Pe.Dynamic=0]="Dynamic",Pe[Pe.Kinematic=1]="Kinematic",Pe[Pe.Static=2]="Static";class Be{constructor(e){this.type=t.RigidBodyType.Dynamic,this.velocity=new i,this.gravity=0,this.acceleration=new i,Object.assign(this,e)}}Be.componentName="RigidBody";let De=class{constructor(e,s,r){this.entityManager=e,this.timeManager=s,this.transformSystem=r,this.types=new Set([t.RigidBodyType.Dynamic,t.RigidBodyType.Kinematic]),this.displacement=new i,this.totalAcceleration=new i,this.scaledAcceleration=new i,this.scaledVelocity=new i}onUpdate(){this.entityManager.search(Be).filter((({component:{type:t}})=>this.types.has(t))).forEach((({component:{velocity:e,acceleration:s,gravity:r,type:o},entity:n})=>{const{position:a}=this.entityManager.getComponent(n,Ot);o===t.RigidBodyType.Dynamic?(this.totalAcceleration.y=s.y-r,this.totalAcceleration.x=s.x):this.totalAcceleration.copy(s),i.add(e,e,i.scale(this.scaledAcceleration,this.totalAcceleration,this.timeManager.physicsDeltaTime)),i.add(a,a,i.add(this.displacement,i.scale(this.scaledVelocity,e,this.timeManager.physicsDeltaTime),i.scale(this.scaledAcceleration,this.totalAcceleration,.5*Math.pow(this.timeManager.physicsDeltaTime,2))))})),this.transformSystem.onUpdate()}};De=Ct([l(Ft.ApplyVelocitySystem),At(0,c(St.EntityManager)),At(1,c(St.TimeManager)),At(2,c(Ft.TransformSystem))],De);class Fe{constructor(){this.auxMin=new i,this.auxMax=new i,this.auxScaledOffset=new i}updatePositionAndVertices(t,e,i){this.translatePosition(t,e,i),t instanceof x?(this.auxAngle=t.rotation+i.localRotation,t.vertexModel.forEach(((e,s)=>t.vertices[s].set(e.x*i.localScale.x,e.y*i.localScale.y))),t.vertices.forEach((e=>e.set(e.x*Math.cos(this.auxAngle)-e.y*Math.sin(this.auxAngle)+t.position.x,e.x*Math.sin(this.auxAngle)+e.y*Math.cos(this.auxAngle)+t.position.y)))):t instanceof M&&(t.radius*=Math.max(Math.abs(i.localScale.x),Math.abs(i.localScale.y)))}translatePosition(t,e,{localPosition:s,localScale:r,localRotation:o}){if(this.auxScaledOffset.set(e.x*r.x,e.y*r.y),0!==o){const e=Math.atan2(this.auxScaledOffset.y,this.auxScaledOffset.x)+o,i=this.auxScaledOffset.magnitude;t.position.set(s.x+i*Math.cos(e),s.y+i*Math.sin(e))}else i.add(t.position,s,this.auxScaledOffset)}updateBoundingBox(t){t instanceof M?this.updateCircumferenceBoundingBox(t):t instanceof x&&this.updatePolygonBoundingBox(t)}updateCircumferenceBoundingBox(t){t.boundingBox.set(t.position.x-t.radius,t.position.y-t.radius,2*t.radius,2*t.radius)}updatePolygonBoundingBox(t){this.auxMin.x=t.vertices[0].x,this.auxMin.y=t.vertices[0].y,this.auxMax.x=t.vertices[0].x,this.auxMax.y=t.vertices[0].y,t.vertices.forEach((t=>{this.auxMin.x=Math.min(t.x,this.auxMin.x),this.auxMin.y=Math.min(t.y,this.auxMin.y),this.auxMax.x=Math.max(t.x,this.auxMax.x),this.auxMax.y=Math.max(t.y,this.auxMax.y)})),t.boundingBox.set(this.auxMin.x,this.auxMin.y,this.auxMax.x-this.auxMin.x,this.auxMax.y-this.auxMin.y)}updateProjectionAxes(t){var e;if(t.vertices.length>2)for(let s=0;s<t.vertices.length;s++)i.normal(t.projectionAxes[s],i.subtract(t.projectionAxes[s],null!==(e=t.vertices[s+1])&&void 0!==e?e:t.vertices[0],t.vertices[s]));else i.normal(t.projectionAxes[0],i.subtract(t.projectionAxes[0],t.vertices[1],t.vertices[0]))}}let Ue=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(le).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new M(t.radius)),t.shapes[0].radius=t.radius,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Ue=Ct([l(Ft.UpdateBallColliderShapeSystem),At(0,c(St.EntityManager))],Ue);let Ie=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ce).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new x([new i,new i,new i,new i])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel[0].set(-t.width/2,-t.height/2),t.shapes[0].vertexModel[1].set(-t.width/2,t.height/2),t.shapes[0].vertexModel[2].set(t.width/2,t.height/2),t.shapes[0].vertexModel[3].set(t.width/2,-t.height/2),this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};Ie=Ct([l(Ft.UpdateBoxColliderShapeSystem),At(0,c(St.EntityManager))],Ie);let Le=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(de).forEach((({component:t,entity:e})=>{for(let s=0;s<t.vertexModel.length-1;s++)t.shapes[s]||(t.shapes[s]=new x([new i,new i])),t.shapes[s].rotation=t.rotation,t.shapes[s].vertexModel=[t.vertexModel[s],t.vertexModel[s+1]],this.updatePositionAndVertices(t.shapes[s],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[s]),this.updateProjectionAxes(t.shapes[s])}))}};Le=Ct([l(Ft.UpdateEdgeColliderShapeSystem),At(0,c(St.EntityManager))],Le);let je=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(ge).forEach((({component:t,entity:e})=>{0===t.shapes.length&&(t.shapes[0]=new x([])),t.shapes[0].rotation=t.rotation,t.shapes[0].vertexModel=t.vertexModel,this.updatePositionAndVertices(t.shapes[0],t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(t.shapes[0]),this.updateProjectionAxes(t.shapes[0])}))}};je=Ct([l(Ft.UpdatePolygonColliderShapeSystem),At(0,c(St.EntityManager))],je);let Oe=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(me).forEach((({component:t,entity:e})=>{const i=this.entityManager.getComponent(e,Kt);if(i&&0!==i.data.length){0===t.shapes.length&&(t.composite?this.useEdges(t,i):this.useBoxes(t,i));for(const i of t.shapes)this.updatePositionAndVertices(i,t.offset,this.entityManager.getComponent(e,Ot)),this.updateBoundingBox(i),this.updateProjectionAxes(i)}}))}useBoxes(t,e){t.shapes=[],e.data.forEach(((i,s)=>{if(!this.needsCollider(i,s,e))return;const r=new x(this.generateRectangleVertices(s,e));r.updateCollisions=!1,t.shapes.push(r)}))}generateRectangleVertices(t,{width:e,height:s,tileWidth:r,tileHeight:o}){const n=-e*r/2+t%e*r,a=s*o/2-Math.floor(t/e)*o;return[new i(n,a-o),new i(n,a),new i(n+r,a),new i(n+r,a-o)]}needsCollider(t,e,{data:i,width:s,height:r}){return 0!==t&&this.getNeighbors(e,s,r).some((t=>!t||!i[t]||0===i[t]))}useEdges(t,e){t.shapes=[];const s=[],r=[];let o,n;e.data.forEach(((t,i)=>{if(0===t)return;const o=i%e.width,n=Math.floor(i/e.width);s[n]||(s[n]=[]),s[n+1]||(s[n+1]=[]),r[n]||(r[n]=[]),r[n+1]||(r[n+1]=[]);const a=this.getNeighbors(i,e.width,e.height);this.hasTile(a[0],e)||(s[n][o]=!0),this.hasTile(a[2],e)||(s[n+1][o]=!0),this.hasTile(a[1],e)||(r[n][o]=!0),this.hasTile(a[3],e)||(r[n][o+1]=!0)}));for(let r=0;r<s.length;r++)if(s[r])for(let a=0;a<s[r].length;a++)!o||!n||r===n.y&&s[r][a]||(t.shapes.push(this.createEdge(o,n,e)),o=void 0,n=void 0),s[r][a]&&(o||(o=new i(a,r)),n=new i(a+1,r));o&&n&&t.shapes.push(this.createEdge(o,n,e)),o=void 0,n=void 0;for(let s=0;s<=e.width;s++)for(let a=0;a<r.length;a++)r[a]&&(!o||!n||s===n.x&&r[a][s]||(t.shapes.push(this.createEdge(o,n,e)),o=void 0,n=void 0),r[a][s]&&(o||(o=new i(s,a)),n=new i(s,a+1)));o&&n&&t.shapes.push(this.createEdge(o,n,e))}hasTile(t,{data:e}){return void 0!==t&&e[t]&&e[t]>0}createEdge(t,e,{width:s,height:r,tileWidth:o,tileHeight:n}){t.x=-s*o/2+t.x*o,t.y=r*n/2-t.y*n,e.x=-s*o/2+e.x*o,e.y=r*n/2-e.y*n;const a=new x([new i(t.x,t.y),new i(e.x,e.y)]);return a.updateCollisions=!1,a}getNeighbors(t,e,i){return[t-e>=0?t-e:void 0,t%e>0?t-1:void 0,t+e<=e*i?t+e:void 0,t%e<e-1?t+1:void 0]}};Oe=Ct([l(Ft.UpdateTilemapColliderShapeSystem),At(0,c(St.EntityManager))],Oe);let ke=class{constructor(t,e,i,s,r){if(this.entityManager=t,this.broadPhaseResolver=e,this.collisionResolutionMethod=s,this.collisionRepository=r,this.colliderTypes=[le,ce,ge,de,me],this.colliders=[],this.collisions=new Set,this.shapes=[],null!=i){const t=new Map;for(let e=0;e<i.length;e++){const[s,r]=i[e];t.has(s)||t.set(s,new Set),t.has(r)||t.set(r,new Set),t.get(s).add(r),t.get(r).add(s)}this.layerNeighbors=t}else this.layerNeighbors=null}onUpdate(){this.collisionRepository.removeAll(),this.colliders=[],this.collisions.clear(),this.shapes=[],this.colliderTypes.forEach((t=>this.entityManager.search(t).forEach((({component:t,entity:e})=>{this.colliders.push(t),t.shapes.forEach((i=>{var s;i.entity=e,i.collider=this.colliders.length-1,i.id=this.shapes.length,i.ignoreCollisionsWithLayers=null!==(s=t.ignoreCollisionsWithLayers)&&void 0!==s?s:[],i.layer=t.layer,this.shapes.push(i)}))})))),this.broadPhaseResolver.update(this.shapes),this.shapes.filter((t=>t.updateCollisions)).forEach((t=>this.narrowPhase(t,this.broadPhase(t))))}broadPhase({boundingBox:t,layer:e}){const i=this.broadPhaseResolver.retrieve(t),s=i.length,r=[];if(this.layerNeighbors){const t=this.layerNeighbors.get(e);if(!t)return r;for(let e=0;e<s;e++){const s=this.shapes[i[e]];t.has(s.layer)&&r.push(s)}return r}for(let t=0;t<s;t++)r.push(this.shapes[i[t]]);return r}narrowPhase(t,e){e.filter((e=>t.entity!==e.entity&&t.id!==e.id&&!t.ignoreCollisionsWithLayers.includes(e.layer)&&!e.ignoreCollisionsWithLayers.includes(t.layer)&&!this.isResolved(t,e))).forEach((e=>{const s=this.collisionResolutionMethod.findCollision(t,e);if(s){const r=s.penetration,o=s.direction.clone();this.collisionRepository.persist({localCollider:this.colliders[t.collider],localEntity:t.entity,remoteCollider:this.colliders[e.collider],remoteEntity:e.entity,resolution:{direction:o,penetration:r}});const n=s.direction.clone();i.scale(n,n,-1),this.collisionRepository.persist({localCollider:this.colliders[e.collider],localEntity:e.entity,remoteCollider:this.colliders[t.collider],remoteEntity:t.entity,resolution:{direction:n,penetration:r}}),this.collisions.add(`${t.id}-${e.id}`),this.collisions.add(`${e.id}-${t.id}`)}}))}isResolved(t,e){return this.collisions.has(`${t.id}-${e.id}`)}};ke=Ct([l(Ft.ResolveCollisionSystem),At(0,c(St.EntityManager)),At(1,c(St.CollisionBroadphaseResolver)),At(2,c(St.CollisionMatrix)),At(3,c(St.CollisionResolutionMethod)),At(4,c(St.CollisionRepository))],ke);let Ge=class{constructor(t,e,s){this.entityManager=t,this.collisionRepository=e,this.transformSystem=s,this.correction=new i,this.maxCorrection=new i}onUpdate(){const e=this.collisionRepository.findAll().filter((({localCollider:t,remoteCollider:e,remoteEntity:i,localEntity:s})=>t.physics&&e.physics&&this.entityManager.hasComponent(s,Be)&&this.entityManager.hasComponent(i,Be)));0!==e.length&&(this.entityManager.search(Be,(e=>e.type===t.RigidBodyType.Dynamic)).forEach((({component:s,entity:r})=>{if(this.maxCorrection.set(0,0),e.filter((({localEntity:t})=>r===t)).forEach((({remoteEntity:e,resolution:{direction:s,penetration:r}})=>{this.entityManager.getComponent(e,Be).type===t.RigidBodyType.Dynamic&&(r/=2),i.scale(this.correction,s,-r),this.correction.magnitude>this.maxCorrection.magnitude&&this.maxCorrection.copy(this.correction)})),0===this.maxCorrection.x&&0===this.maxCorrection.y)return;const{position:o}=this.entityManager.getComponent(r,Ot);i.add(o,o,this.maxCorrection),s.gravity>0&&this.maxCorrection.y*s.velocity.y<0&&(s.velocity.y=0)})),this.transformSystem.onUpdate())}};Ge=Ct([l(Ft.ApplyRepositionSystem),At(0,c(St.EntityManager)),At(1,c(St.CollisionRepository)),At(2,c(Ft.TransformSystem))],Ge);const Ve=new Set([ce,le,ge,de,me]);let Ne=class extends Fe{constructor(t){super(),this.entityManager=t}onUpdate(){this.entityManager.search(Be,(e=>e.type===t.RigidBodyType.Dynamic)).forEach((({entity:t})=>{const e=this.entityManager.getComponent(t,Ot);for(const i of Ve)if(this.entityManager.hasComponent(t,i)){const s=this.entityManager.getComponent(t,i);s.shapes.forEach((t=>{this.updatePositionAndVertices(t,s.offset,e),this.updateBoundingBox(t)}))}}))}};Ne=Ct([l(Ft.UpdateCollidersAfterRepositionSystem),At(0,c(St.EntityManager))],Ne);const We=24;let He=class{constructor(t,e,s,r,o){this.entityManager=t,this.renderManager=e,this.inputManager=s,this.canvas=r,this.gameConfig=o,this.positionInViewport=new i,this.positionInCameraViewport=new i,this.positionInWorldspace=new i,this.renderDataPerCamera=new Map}onUpdate(){var t;if(!(null===(t=this.gameConfig.debug)||void 0===t?void 0:t.mousePosition)||!this.inputManager.mouse)return;const{positionInViewport:e}=this.inputManager.mouse;this.entityManager.search(Vt,(t=>t.debug)).forEach((({entity:t,component:s})=>{const{zoom:r}=s,o=this.entityManager.getComponent(t,Ot).position;this.renderDataPerCamera.has(t)||this.renderDataPerCamera.set(t,ze());const n=this.renderDataPerCamera.get(t);i.floor(this.positionInWorldspace,i.add(this.positionInWorldspace,o,i.scale(this.positionInWorldspace,e,1/r))),i.floor(this.positionInCameraViewport,i.scale(this.positionInCameraViewport,e,1/r)),i.round(this.positionInViewport,e),n.color=this.gameConfig.debug.textColor,n.text=`mouse_position: canvas_viewport=${this.positionInViewport}, camera_viewport=${this.positionInCameraViewport}, world_space=${this.positionInWorldspace}`,n.fontSize=We/r,n.lineHeight=n.fontSize,n.shadow.offset.x=2/r,n.shadow.offset.y=-2/r,n.boundingBox={width:this.canvas.width/r,height:n.fontSize},this.updateRenderDataPosition(n,o,r),this.renderManager.addRenderData(n)}))}updateRenderDataPosition(e,i,s){switch(e.position.x=i.x,this.gameConfig.debug.textPosition){case"top-right":e.alignment=t.TextAlignment.Right,e.position.y=i.y+(this.canvas.height/2-We)/s;break;case"top-left":e.alignment=t.TextAlignment.Left,e.position.y=i.y+(this.canvas.height/2-We)/s;break;case"bottom-left":e.alignment=t.TextAlignment.Left,e.position.y=i.y-(this.canvas.height/2-We)/s;break;default:e.alignment=t.TextAlignment.Right,e.position.y=i.y-(this.canvas.height/2-We)/s}}};He=Ct([l(Ft.DebugMousePositionSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.InputManager)),At(3,c(St.CanvasElement)),At(4,c(St.GameConfig))],He);const ze=(e=24)=>({type:st.Text,text:"",position:new i,layer:Gt,color:"#00FF00",fontSize:e,font:"Arial",shadow:{color:"#000000",opacity:1,offset:new i(1,-1)},flipHorizontally:!1,flipVertically:!1,letterSpacing:0,lineHeight:e,opacity:1,rotation:0,smooth:!1,textureAtlas:Object.assign({},we),boundingBox:{width:0,height:0},alignment:t.TextAlignment.Left});let Ye=class{constructor(t,e,i){this.entityManager=t,this.renderManager=e,this.gameConfig=i}onUpdate(){var e;(null===(e=this.gameConfig.debug)||void 0===e?void 0:e.textRendererBoundingBoxes)&&this.entityManager.search(Re).forEach((({entity:e,component:{width:s,height:r,rotation:o,layer:n,offset:a}})=>{const h=this.entityManager.getComponent(e,Ot);if(!h)return;const l={type:st.Geometric,shape:t.GeometricShape.Polygon,position:i.add(new i,h.localPosition,a),layer:n,color:this.gameConfig.debug.textBoxColor,radius:void 0,rotation:o+h.localRotation,vertexModel:[new i(-s/2,-r/2),new i(-s/2,r/2),new i(s/2,r/2),new i(s/2,-r/2)]};this.renderManager.addRenderData(l)}))}};Ye=Ct([l(Ft.DebugTextRendererSystem),At(0,c(St.EntityManager)),At(1,c(St.RenderManager)),At(2,c(St.GameConfig))],Ye);const Xe=new Map([[Lt.PreGameLogic,[{name:Ft.KeyboardSystem,type:ee},{name:Ft.MouseSystem,type:ie},{name:Ft.TouchScreenSystem,type:se},{name:Ft.GamepadSystem,type:te},{name:Ft.ButtonSystem,type:Xt},{name:Ft.AudioPlayerSystem,type:It},{name:Ft.TiledWrapperSystem,type:qt},{name:Ft.TilemapPreProcessingSystem,type:Qt}]],[Lt.Transform,[{name:Ft.TransformSystem,type:Zt}]],[Lt.Physics,[{name:Ft.ApplyVelocitySystem,type:De},{name:Ft.UpdateBallColliderShapeSystem,type:Ue},{name:Ft.UpdateBoxColliderShapeSystem,type:Ie},{name:Ft.UpdateEdgeColliderShapeSystem,type:Le},{name:Ft.UpdatePolygonColliderShapeSystem,type:je},{name:Ft.UpdateTilemapColliderShapeSystem,type:Oe},{name:Ft.ResolveCollisionSystem,type:ke},{name:Ft.ApplyRepositionSystem,type:Ge},{name:Ft.UpdateCollidersAfterRepositionSystem,type:Ne}]],[Lt.Render,[{name:Ft.AnimatorSystem,type:ne},{name:Ft.CameraSystem,type:ae},{name:Ft.TilemapRendererSystem,type:_e},{name:Ft.SpriteRendererSystem,type:Ae},{name:Ft.GeometricRendererSystem,type:Ce},{name:Ft.MaskRendererSystem,type:ye},{name:Ft.DarknessLightRendererSystem,type:be},{name:Ft.TextRendererSystem,type:Ee},{name:Ft.VideoRendererSystem,type:Ht},{name:Ft.DebugColliderRenderSystem,type:ue},{name:Ft.DebugMousePositionSystem,type:He},{name:Ft.DebugTextRendererSystem,type:Ye},{name:Ft.CullingSystem,type:pe},{name:Ft.ClearScreenSystem,type:he},{name:Ft.RenderSystem,type:xe}]]]);let $e=class{constructor(t,e,i){this.timeManager=t,this.systemManager=e,this.sceneManager=i,this.running=!1,this.gameLoopAccumulator=0}start(){this.running||(this.running=!0,this.gameLoopAccumulator=0,this.enableSystems(),this.sceneManager.loadOpeningScene(),this.requestAnimationLoop(window.performance.now()),this.asyncPhysicsLoop())}enableSystems(){Xe.forEach((t=>{t.forEach((({type:t})=>this.systemManager.enableSystem(t)))}))}stop(){this.running&&(this.systemManager.disableAllSystems(),this.running=!1)}requestAnimationLoop(t){this.running&&(this.timeManager.updateForRender(.001*t),this.sceneManager.update(),this.sceneManager.loadingScene||(this.gameLoopAccumulator+=this.timeManager.browserDeltaTime,this.sceneManager.sceneLoadedThisFrame&&(this.gameLoopAccumulator=this.timeManager.fixedGameDeltaTime),this.gameLoopAccumulator>=this.timeManager.fixedGameDeltaTime&&(this.gameLogicIteration(.001*t),this.gameLoopAccumulator-=this.timeManager.fixedGameDeltaTime),this.renderIteration()),window.requestAnimationFrame((t=>this.requestAnimationLoop(t))))}gameLogicIteration(t){this.timeManager.updateForGame(t),this.systemManager.update(Lt.PreGameLogic),this.systemManager.update(Lt.GameLogic),this.timeManager.updateIntervals(),this.systemManager.update(Lt.Transform)}renderIteration(){this.systemManager.groupHasSystems(Lt.GamePreRender)&&(this.systemManager.update(Lt.GamePreRender),this.systemManager.update(Lt.Transform)),this.systemManager.update(Lt.Render)}asyncPhysicsLoop(){this.physicsIntervalId=window.setInterval((()=>{if(!this.running)return window.clearInterval(this.physicsIntervalId);this.timeManager.updateForPhysics(.001*window.performance.now()),document.hidden||this.physicsIteration()}),1e3/this.timeManager.fixedPhysicsFramerate)}physicsIteration(){this.timeManager.timeScale<=0||(this.systemManager.groupHasSystems(Lt.GamePhysics)&&(this.systemManager.update(Lt.GamePhysics),this.systemManager.update(Lt.Transform)),this.systemManager.update(Lt.Physics))}};$e=Ct([l(St.LoopManager),At(0,c(St.TimeManager)),At(1,c(St.SystemManager)),At(2,c(St.SceneManager))],$e);class Ke{constructor(t,e){this.container=t,this.systemManager=e,this.lastSystemTypeId=0}createSystemIfNotExists(t){if(this.systemManager.hasSystem(t))return;const e="__system_"+this.lastSystemTypeId++;var i;this.container.add(t,e),this.systemManager.addSystem(this.container.get(e),null!==(i=t.prototype.__system_group)&&void 0!==i?i:Lt.GameLogic)}}let qe=class{constructor(t){this.webGLManager=t,this.renderData=[],this.cameraData=[]}addCameraData(t){this.cameraData.push(t)}addRenderData(t){this.renderData.push(t)}setRenderData(t){this.renderData=t}getCameraData(){return this.cameraData}getRenderData(){return this.renderData}removeCameraData(){this.cameraData=[]}removeRenderData(){this.renderData=[]}render(){this.cameraData.sort(((t,e)=>t.depth-e.depth)).forEach((t=>this.renderData.filter((e=>t.layers.includes(e.layer))).sort(((e,i)=>t.layers.indexOf(e.layer)-t.layers.indexOf(i.layer))).forEach((e=>this.webGLManager.render(e,t)))))}};qe=Ct([l(St.RenderManager),At(0,c(St.WebGLManager))],qe);const Je=e=>{var i,s,r,o,n,a,h,l,c,d,g,m;if(!(e.containerNode instanceof HTMLElement))throw new Error("GameConfig Error: Invalid containerNode");if("number"!=typeof e.width)throw new Error("GameConfig Error: Invalid width");if("number"!=typeof e.height)throw new Error("GameConfig Error: Invalid height");e.canvasColor=null!==(i=e.canvasColor)&&void 0!==i?i:"#000000",e.physicsFramerate=null!==(s=e.physicsFramerate)&&void 0!==s?s:180,e.headless=null!==(r=e.headless)&&void 0!==r&&r,e.debug=null!==(o=e.debug)&&void 0!==o?o:{colliders:!1,mousePosition:!1,textRendererBoundingBoxes:!1},e.debug.collidersColor=null!==(n=e.debug.collidersColor)&&void 0!==n?n:"#00FF00",e.debug.textColor=null!==(a=e.debug.textColor)&&void 0!==a?a:"#00FF00",e.debug.textBoxColor=null!==(h=e.debug.textBoxColor)&&void 0!==h?h:"#0000FF",e.debug.textPosition=null!==(l=e.debug.textPosition)&&void 0!==l?l:"bottom-left",e.collisions=null!==(c=e.collisions)&&void 0!==c?c:{},e.collisions.collisionBroadPhaseMethod=null!==(d=e.collisions.collisionBroadPhaseMethod)&&void 0!==d?d:t.BroadPhaseMethods.SpartialGrid,e.collisions.collisionMatrix=null!==(g=e.collisions.collisionMatrix)&&void 0!==g?g:void 0,e.collisions.collisionMethod=null!==(m=e.collisions.collisionMethod)&&void 0!==m?m:t.CollisionMethods.SAT},Qe=({containerNode:t,width:e,height:i})=>{const s=document.createElement("canvas");return s.id="angryPixelGameCanvas",s.width=Math.floor(e),s.height=Math.floor(i),s.tabIndex=0,s.addEventListener("contextmenu",(t=>t.preventDefault())),t.appendChild(s),s.focus(),s},Ze=e=>{e.add(t.EntityManager),e.add(t.SystemManager),e.set(St.CreateSystemService,new Ke(e,e.get(St.SystemManager))),e.add(t.TimeManager),e.add(t.AssetManager),e.add(t.InputManager),e.add(t.SceneManager),e.add(t.InputManager),e.add($e),e.add(bt),e.add(qe)},ti=t=>{t.get(St.GameConfig).headless&&ei(Xe),Xe.forEach(((e,i)=>e.forEach((({type:e,name:s})=>{t.add(e),t.get(St.SystemManager).addSystem(t.get(s),i)}))))},ei=t=>{t.delete(Lt.Render),t.set(Lt.PreGameLogic,t.get(Lt.PreGameLogic).filter((({name:t})=>![Ft.AudioPlayerSystem,Ft.ButtonSystem,Ft.GamepadSystem,Ft.KeyboardSystem,Ft.MouseSystem,Ft.TouchScreenSystem].includes(t))))},ii=e=>{const{collisions:{collisionBroadPhaseMethod:i,collisionMatrix:s,collisionMethod:r}}=e.get(St.GameConfig);e.add(t.CollisionRepository),e.add(D),r===t.CollisionMethods.AABB?(e.add(_),e.add(P)):e.add(U),e.add(i===t.BroadPhaseMethods.QuadTree?u:y),e.add(r===t.CollisionMethods.AABB?S:R),e.set(St.CollisionMatrix,s)},si=t=>{const e=t.get(St.GameConfig);e.dependencies&&e.dependencies.forEach((([e,i])=>{t.set(e,i)}))};class ri{onUpdate(){}onCreate(){}onEnabled(){}onDisabled(){}onDestroy(){}}Ct([c(St.EntityManager)],ri.prototype,"entityManager",void 0),Ct([c(St.AssetManager)],ri.prototype,"assetManager",void 0),Ct([c(St.SceneManager)],ri.prototype,"sceneManager",void 0),Ct([c(St.TimeManager)],ri.prototype,"timeManager",void 0),Ct([c(St.InputManager)],ri.prototype,"inputManager",void 0),Ct([c(St.CollisionRepository)],ri.prototype,"collisionRepository",void 0),Ct([c(St.GameConfig)],ri.prototype,"gameConfig",void 0);const oi={AssetManager:St.AssetManager,CanvasElement:xt.CanvasElement,CollisionRepository:d.CollisionRepository,EntityManager:j.EntityManager,GameConfig:St.GameConfig,InputManager:St.InputManager,SceneManager:St.SceneManager,SystemManager:j.SystemManager,TimeManager:St.TimeManager};t.Animation=class{constructor(t){var e,s,r;this.slice={size:new i,offset:new i,padding:new i},this.frames=[],this.fps=12,this.loop=!1,t&&(this.image=t.image,this.frames=null!==(e=t.frames)&&void 0!==e?e:this.frames,this.fps=null!==(s=t.fps)&&void 0!==s?s:this.fps,this.loop=null!==(r=t.loop)&&void 0!==r?r:this.loop,t.slice&&(this.slice.size.copy(t.slice.size),t.slice.offset&&this.slice.offset.copy(t.slice.offset),t.slice.padding&&this.slice.padding.copy(t.slice.padding)))}},t.Animator=re,t.AudioPlayer=Dt,t.BallCollider=le,t.BoxCollider=ce,t.Button=zt,t.Camera=Vt,t.Circumference=M,t.DarknessRenderer=ve,t.EdgeCollider=de,t.Game=class{constructor(t){this.container=(t=>{Je(t);const e=new h;return e.set(St.GameConfig,t),e.set(St.CanvasElement,Qe(t)),ii(e),Ze(e),ti(e),si(e),e})(t)}get running(){return this.container.get(St.LoopManager).running}addScene(t,e,i=!1){this.container.get(St.SceneManager).addScene(t,e,i)}addDependencyType(t,e){this.container.add(t,e)}addDependencyInstance(t,e){this.container.set(e,t)}start(){this.container.get(St.LoopManager).start()}stop(){this.container.get(St.LoopManager).stop()}},t.GameSystem=ri,t.GamepadController=Rt,t.GeometricRenderer=Se,t.Keyboard=Et,t.LightRenderer=Me,t.MaskRenderer=fe,t.Mouse=_t,t.Polygon=x,t.PolygonCollider=ge,t.Rectangle=s,t.RigidBody=Be,t.SYMBOLS=oi,t.Scene=class{constructor(t,e){this.entityManager=t,this.assetManager=e,this.systems=[]}registerSystems(){}loadAssets(){}createEntities(){}addSystem(t){this.systems.push(t)}addSystems(t){this.systems.push(...t)}},t.SpriteRenderer=oe,t.TextRenderer=Re,t.TiledWrapper=$t,t.TilemapCollider=me,t.TilemapRenderer=Kt,t.TouchScreen=Tt,t.Transform=Ot,t.Vector2=i,t.VideoRenderer=Nt,t.between=a,t.clamp=r,t.debugRenderLayer=Gt,t.decorate=function(t,e,i){"number"==typeof i?t(e.prototype,void 0,i):void 0!==i?t(e.prototype,i):t(e)},t.defaultRenderLayer=kt,t.defaultTextureAtlasOptions=we,t.degreesToRadians=t=>t*(Math.PI/180),t.disableComponent=t=>({enabled:!1,component:t}),t.fixedRound=o,t.gameLogicSystem=function(){return function(t){jt(t,Lt.GameLogic)}},t.gamePhysicsSystem=function(){return function(t){jt(t,Lt.GamePhysics)}},t.gamePreRenderSystem=function(){return function(t){jt(t,Lt.GamePreRender)}},t.inject=c,t.injectable=l,t.playSfx=({audioSource:t,volume:e=1,loop:i=!1})=>{t.volume=e,t.loop=i,t.currentTime=0,t.play().catch((t=>console.warn("playSfx error:",t)))},t.radiansToDegrees=t=>t*(180/Math.PI),t.randomFloat=(t,e,i=2)=>o(Math.random()*(e-t)+t,i),t.randomInt=(t,e)=>Math.round(Math.random()*(e-t))+t,t.range=n,t.rgbToHex=({r:t,g:e,b:i},s="#")=>{const r=t=>t.toString(16).padStart(2,"0");return`${s}${r(t)}${r(e)}${r(i)}`},t.stopSfx=t=>{t.pause(),t.currentTime=0}}));
2
2
  //# sourceMappingURL=index.js.map