rapid-render 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,7 @@
1
1
 
2
- > [!WARNING]
3
- > This project is a work in progress! Expect bugs, report issues, and feel free to contribute.
4
-
5
2
  # Rapid.js
6
3
 
7
- A highly efficient ([stress-test](https://nightre.github.io/Rapid.js/docs/examples.htm)) and lightweight WebGL-based 2D rendering engine focused on rendering capabilities.
4
+ A highly efficient ([stress-test](https://nightre.github.io/Rapid.js/docs/examples.html)) and lightweight WebGL-based 2D rendering engine focused on rendering capabilities.
8
5
 
9
6
  ### [Website](https://nightre.github.io/Rapid.js/docs/index.html)
10
7
 
@@ -16,11 +13,14 @@ A highly efficient ([stress-test](https://nightre.github.io/Rapid.js/docs/exampl
16
13
  * **TileMap** - YSort, isometric
17
14
  * **Graphics Drawing**
18
15
  * **Text Rendering**
19
- * **Line Drawing**
16
+ * **Line Drawing** - line texture
20
17
  * **Custom Shaders**
21
18
  * **Mask**
22
19
  * **Frame Buffer Object**
23
20
 
21
+ > [!WARNING]
22
+ > This project is a work in progress! Expect bugs, report issues, and feel free to contribute.
23
+
24
24
  ## Install
25
25
 
26
26
  ```bash
@@ -59,10 +59,14 @@ For more examples and detailed documentation, visit our [website](https://nightr
59
59
 
60
60
  ## Roadmap
61
61
 
62
- * Light System
63
62
  * Line Texture
64
- * Particle System
63
+ * Light System
65
64
 
66
65
  ## Contributing
67
66
 
68
67
  Issues and PRs are welcome!
68
+
69
+ ## Screen shot
70
+
71
+ ![1](./screenshot/1.gif)
72
+ ![2](./screenshot/2.gif)
@@ -30,7 +30,7 @@ export interface IAttribute {
30
30
  stride: number;
31
31
  offset?: number;
32
32
  }
33
- export interface ITransform {
33
+ export interface ITransformOptions {
34
34
  position?: Vec2;
35
35
  scale?: Vec2 | number;
36
36
  rotation?: number;
@@ -45,14 +45,14 @@ export interface ITransform {
45
45
  afterSave?(): unknown;
46
46
  beforRestore?(): unknown;
47
47
  }
48
- export interface IRenderSpriteOptions extends ITransform, IShader {
48
+ export interface ISpriteRenderOptions extends ITransformOptions, IShaderRenderOptions {
49
49
  color?: Color;
50
50
  texture?: Texture;
51
51
  offset?: Vec2;
52
52
  flipX?: boolean;
53
53
  flipY?: boolean;
54
54
  }
55
- export interface ITextOptions {
55
+ export interface ITextTextureOptions {
56
56
  /**
57
57
  * The text string to be rendered.
58
58
  */
@@ -85,27 +85,35 @@ export interface ITextOptions {
85
85
  */
86
86
  textBaseline?: CanvasTextBaseline;
87
87
  }
88
- export interface ILineOptions {
88
+ export interface ILineRenderOptions extends IGraphicRenderOptions {
89
89
  width?: number;
90
90
  closed?: boolean;
91
- points: Vec2[];
92
91
  roundCap?: boolean;
93
- color?: Color;
92
+ textureMode?: LineTextureMode;
93
+ }
94
+ export declare enum LineTextureMode {
95
+ STRETCH = "stretch",
96
+ REPEAT = "repeat"
94
97
  }
95
- export interface IRenderLineOptions extends ILineOptions, ITransform {
98
+ export declare enum TextureWrapMode {
99
+ REPEAT = "repeat",
100
+ CLAMP = "clamp",
101
+ MIRROR = "mirror"
96
102
  }
97
- export interface IGraphicOptions extends ITransform, IShader {
103
+ export interface IRenderLineOptions extends ILineRenderOptions, ITransformOptions {
104
+ }
105
+ export interface IGraphicRenderOptions extends ITransformOptions, IShaderRenderOptions {
98
106
  points: Vec2[];
99
107
  color?: Color | Color[];
100
108
  drawType?: number;
101
109
  uv?: Vec2[];
102
110
  texture?: Texture;
103
111
  }
104
- export interface ICircleOptions extends IGraphicOptions {
112
+ export interface ICircleRenderOptions extends IGraphicRenderOptions {
105
113
  radius: number;
106
114
  segments?: number;
107
115
  }
108
- export interface IRectOptions extends IGraphicOptions {
116
+ export interface IRectRenderOptions extends IGraphicRenderOptions {
109
117
  width: number;
110
118
  height: number;
111
119
  }
@@ -115,7 +123,7 @@ export declare enum MaskType {
115
123
  }
116
124
  export type UniformType = Record<string, number | Array<any> | boolean | Texture>;
117
125
  export type Images = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | OffscreenCanvas;
118
- export interface IRegisterTileOptions extends IRenderSpriteOptions {
126
+ export interface IRegisterTileOptions extends ISpriteRenderOptions {
119
127
  texture: Texture;
120
128
  offsetX?: number;
121
129
  offsetY?: number;
@@ -124,18 +132,18 @@ export interface IRegisterTileOptions extends IRenderSpriteOptions {
124
132
  export interface YSortCallback {
125
133
  ySort: number;
126
134
  render?: () => void;
127
- renderSprite?: IRenderSpriteOptions;
135
+ renderSprite?: ISpriteRenderOptions;
128
136
  }
129
- export interface ILayerRender extends ITransform {
137
+ export interface ILayerRenderOptions extends ITransformOptions {
130
138
  error?: number | Vec2;
131
139
  errorX?: number;
132
140
  errorY?: number;
133
141
  ySortCallback?: Array<YSortCallback>;
134
142
  shape?: TilemapShape;
135
143
  tileSet: TileSet;
136
- eachTile?: (tileId: string | number, mapX: number, mapY: number) => IRenderSpriteOptions | undefined | void;
144
+ eachTile?: (tileId: string | number, mapX: number, mapY: number) => ISpriteRenderOptions | undefined | void;
137
145
  }
138
- export interface IShader {
146
+ export interface IShaderRenderOptions {
139
147
  shader?: GLShader;
140
148
  uniforms?: Uniform;
141
149
  }
@@ -147,3 +155,6 @@ export declare enum ShaderType {
147
155
  SPRITE = "sprite",
148
156
  GRAPHIC = "graphic"
149
157
  }
158
+ export interface IParticleEmitterOptions extends ITransformOptions, IShaderRenderOptions {
159
+ texture: Texture | Texture[] | [Texture, number][];
160
+ }
@@ -0,0 +1,5 @@
1
+ import Rapid from "./render";
2
+ export declare class LightManager {
3
+ render: Rapid;
4
+ constructor(render: Rapid);
5
+ }
package/dist/line.d.ts CHANGED
@@ -1,10 +1,16 @@
1
- import { ILineOptions } from "./interface";
1
+ import { ILineRenderOptions } from "./interface";
2
2
  import { Vec2 } from "./math";
3
3
  /**
4
4
  * @ignore
5
5
  */
6
6
  export declare const getLineNormal: (points: Vec2[], closed?: boolean) => {
7
- normal: Vec2;
8
- miters: number;
9
- }[];
10
- export declare const getLineGeometry: (options: ILineOptions) => Vec2[];
7
+ normals: {
8
+ normal: Vec2;
9
+ miters: number;
10
+ }[];
11
+ length: number;
12
+ };
13
+ export declare const getLineGeometry: (options: ILineRenderOptions) => {
14
+ vertices: Vec2[];
15
+ uv: Vec2[];
16
+ };
package/dist/math.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { IMathStruct as IMathObject, ITransform, WebGLContext } from "./interface";
1
+ import { IMathStruct as IMathObject, ITransformOptions, WebGLContext } from "./interface";
2
2
  /**
3
3
  * @ignore
4
4
  */
@@ -63,7 +63,8 @@ export declare class WebglBufferArray extends DynamicArrayBuffer {
63
63
  * webglbuffer 中的大小
64
64
  */
65
65
  private webglBufferSize;
66
- constructor(gl: WebGLContext, arrayType: ArrayType, type?: number);
66
+ readonly usage: number;
67
+ constructor(gl: WebGLContext, arrayType: ArrayType, type?: number, usage?: number);
67
68
  pushFloat32(value: number): void;
68
69
  pushUint32(value: number): void;
69
70
  pushUint16(value: number): void;
@@ -175,11 +176,11 @@ export declare class MatrixStack extends DynamicArrayBuffer {
175
176
  * @param transform - The transform to apply
176
177
  * @returns offset position
177
178
  */
178
- applyTransform(transform: ITransform, width?: number, height?: number): {
179
+ applyTransform(transform: ITransformOptions, width?: number, height?: number): {
179
180
  offsetX: number;
180
181
  offsetY: number;
181
182
  };
182
- applyTransformAfter(transform: ITransform): void;
183
+ applyTransformAfter(transform: ITransformOptions): void;
183
184
  }
184
185
  /**
185
186
  * @ignore
@@ -1,14 +1,14 @@
1
- import { EmitterOptions, ParticleOptions } from "./interface";
2
- export declare class Particle {
3
- options: Required<ParticleOptions>;
4
- constructor(options: ParticleOptions);
5
- update(deltaTime: number): void;
6
- isAlive(): boolean;
7
- }
8
- export declare class ParticleEmitter {
9
- particles: Particle[];
10
- options: EmitterOptions;
11
- emissionTimer: number;
12
- constructor(options: EmitterOptions);
13
- update(deltaTime: number): void;
14
- }
1
+ import { EmitterOptions, ParticleOptions } from "./interface";
2
+ export declare class Particle {
3
+ options: Required<ParticleOptions>;
4
+ constructor(options: ParticleOptions);
5
+ update(deltaTime: number): void;
6
+ isAlive(): boolean;
7
+ }
8
+ export declare class ParticleEmitter {
9
+ particles: Particle[];
10
+ options: EmitterOptions;
11
+ emissionTimer: number;
12
+ constructor(options: EmitterOptions);
13
+ update(deltaTime: number): void;
14
+ }
@@ -1 +1 @@
1
- var rapid=function(t){"use strict";var e,r,i;t.MaskType=void 0,(e=t.MaskType||(t.MaskType={})).Include="normal",e.Exclude="inverse",t.TilemapShape=void 0,(r=t.TilemapShape||(t.TilemapShape={})).SQUARE="square",r.ISOMETRIC="isometric",t.ShaderType=void 0,(i=t.ShaderType||(t.ShaderType={})).SPRITE="sprite",i.GRAPHIC="graphic";var s;t.ArrayType=void 0,(s=t.ArrayType||(t.ArrayType={}))[s.Float32=0]="Float32",s[s.Uint32=1]="Uint32",s[s.Uint16=2]="Uint16";class a{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(e){switch(e){case t.ArrayType.Float32:return Float32Array;case t.ArrayType.Uint32:return Uint32Array;case t.ArrayType.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case t.ArrayType.Float32:this.typedArray=this.float32;break;case t.ArrayType.Uint32:this.typedArray=this.uint32;break;case t.ArrayType.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class n extends a{constructor(t,e,r=t.ARRAY_BUFFER){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),t.STATIC_DRAW),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class h extends a{constructor(){super(t.ArrayType.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),a=r[e+0],n=r[e+1],h=r[e+2],o=r[e+3];r[e+0]=a*i-n*s,r[e+1]=a*s+n*i,r[e+2]=h*i-o*s,r[e+3]=h*s+o*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if("number"!=typeof t)return new l(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],a=e[t+3],n=e[t+4],h=e[t+5],o=r*a-i*s;return new Float32Array([a/o,-i/o,-s/o,r/o,(s*h-a*n)/o,(i*n-r*h)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new l(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=t,i[r+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,r=this.typedArray,i=this.getGlobalScale(),s=Math.cos(t),a=Math.sin(t);r[e+0]=s*i.x,r[e+1]=a*i.x,r[e+2]=-a*i.y,r[e+3]=s*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,r=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new l(r,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const r=this.getGlobalRotation(),i=Math.cos(r),s=Math.sin(r),a=this.usedElemNum-6,n=this.typedArray;n[a+0]=i*t,n[a+1]=s*t,n[a+2]=-s*e,n[a+3]=i*e}globalToLocal(t){const e=this.getInverse();return new l(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,r=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,s=t.y||0;(i||s)&&this.translate(i,s),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let a=t.offsetX||0,n=t.offsetY||0;t.offset&&(a+=t.offset.x,n+=t.offset.y);const h=t.origin;return h&&("number"==typeof h?(a-=h*e,n-=h*r):(a-=h.x*e,n-=h.y*r)),{offsetX:a,offsetY:n}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class o extends n{constructor(e,r,i,s){super(e,t.ArrayType.Uint16,e.ELEMENT_ARRAY_BUFFER),this.setMaxSize(r*s);for(let t=0;t<s;t++)this.addObject(t*i);this.bindBuffer(),this.bufferData()}addObject(t){}}class u{constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new u(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new u(e,r,i,s)}add(t){return new u(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new u(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}u.Red=new u(255,0,0,255),u.Green=new u(0,255,0,255),u.Blue=new u(0,0,255,255),u.Yellow=new u(255,255,0,255),u.Purple=new u(128,0,128,255),u.Orange=new u(255,165,0,255),u.Pink=new u(255,192,203,255),u.Gray=new u(128,128,128,255),u.Brown=new u(139,69,19,255),u.Cyan=new u(0,255,255,255),u.Magenta=new u(255,0,255,255),u.Lime=new u(192,255,0,255),u.White=new u(255,255,255,255),u.Black=new u(0,0,0,255),u.TRANSPARENT=new u(0,0,0,0);class l{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}add(t){return new l(this.x+t.x,this.y+t.y)}subtract(t){return new l(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof l?new l(this.x*t.x,this.y*t.y):new l(this.x*t,this.y*t)}divide(t){return t instanceof l?new l(this.x/t.x,this.y/t.y):new l(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)}clone(){return new l(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new l((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new l(Math.abs(this.x),Math.abs(this.y))}floor(){return new l(Math.floor(this.x),Math.floor(this.y))}ceil(){return new l(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new l(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new l(t[0],t[1])))}}l.ZERO=new l(0,0),l.ONE=new l(1,1),l.UP=new l(0,1),l.DOWN=new l(0,-1),l.LEFT=new l(-1,0),l.RIGHT=new l(1,0);const c=(t,e,r,i)=>{const s=[],a=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),n=Math.PI;for(let e=0;e<10;e++){const i=a+e/10*n,h=a+(e+1)/10*n,o=Math.cos(i)*r,u=Math.sin(i)*r,c=Math.cos(h)*r,d=Math.sin(h)*r;s.push(t),s.push(t.add(new l(o,u))),s.push(t.add(new l(c,d)))}return s},d=t=>{const e=t.points;if(e.length<2)return[];const r=((t,e=!1)=>{const r=[];if(t.length<2||e&&t.length<3)return r;const i=t.length,s=(t,e,r)=>{const i=e.subtract(t).normalize(),s=e.subtract(r).normalize(),a=s.dot(i);if(a<-.999)return{normal:i.perpendicular(),miters:1};{let t=s.add(i).normalize();i.cross(s)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-a)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const a=0===e?t[i-2]:t[e-1],n=t[e],h=t[e+1];r.push(s(a,n,h))}r.push(r[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();r.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();r.push({normal:i.perpendicular(),miters:1})}else r.push(s(t[e-1],t[e],t[e+1]));return r})(e,t.closed),i=(t.width||1)/2,s=[],a=t.roundCap||!1;for(let t=0;t<e.length-1;t++){const a=e[t],n=r[t].normal,h=r[t].miters,o=a.add(n.multiply(h*i)),u=a.subtract(n.multiply(h*i)),l=e[t+1],c=r[t+1].normal,d=r[t+1].miters,p=l.add(c.multiply(d*i)),f=l.subtract(c.multiply(d*i));s.push(o),s.push(u),s.push(p),s.push(p),s.push(f),s.push(u)}if(a&&!t.closed){const t=e[0],a=r[0].normal;s.push(...c(t,a,i,!0));const n=e[e.length-1],h=r[e.length-1].normal;s.push(...c(n,h,i,!1))}return s};var p="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n gl_FragColor = color;\r\n}\r\n",f="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n \r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const g=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};function m(t,e,r,i=!1,s=!1){const a=t.createTexture();if(!a)throw new Error("unable to create texture");return t.bindTexture(t.TEXTURE_2D,a),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,s),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),a}const y=5126;var x="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color * vColor;\r\n}",T="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}";const E=[{name:"aPosition",size:2,type:y,stride:24},{name:"aRegion",size:2,type:y,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:y,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],b=[{name:"aPosition",size:2,type:y,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:y,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class R{constructor(t,e,r,i,s=0){this.attributeLoc={},this.uniformLoc={},this.attributes=[];const a=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(r,t.maxTextureUnits-s);this.program=((t,e,r)=>{var i=t.createProgram(),s=g(t,e,35633),a=g(t,r,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,s),t.attachShader(i,a),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,a),this.gl=t.gl,this.usedTexture=s,this.parseShader(e),this.parseShader(a),i&&this.setAttributes(i)}setUniforms(t,e){const r=this.gl;for(const i of t.getUnifromNames()){const s=this.getUniform(i);e=t.bind(r,i,s,e)}return e}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(e,r,i,s,a=0){let n={[t.ShaderType.SPRITE]:x,[t.ShaderType.GRAPHIC]:p}[s],h={[t.ShaderType.SPRITE]:T,[t.ShaderType.GRAPHIC]:f}[s];const o={[t.ShaderType.SPRITE]:E,[t.ShaderType.GRAPHIC]:b}[s];return n=n.replace("void main(void) {",i+"\nvoid main(void) {"),h=h.replace("void main(void) {",r+"\nvoid main(void) {"),n=n.replace("gl_FragColor = ","fragment(color);\ngl_FragColor = "),h=h.replace("gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);","vec2 position = aPosition;\nvertex(position, vRegion);\ngl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new R(e,h,n,o,a)}}class w{constructor(e){this.usedTextures=[],this.needBind=new Set,this.shaders=new Map,this.isCostumShader=!1,this.rapid=e,this.gl=e.gl,this.webglArrayBuffer=new n(e.gl,t.ArrayType.Float32,e.gl.ARRAY_BUFFER),this.MAX_TEXTURE_UNIT_ARRAY=Array.from({length:e.maxTextureUnits},((t,e)=>e))}setTextureUnits(t){return this.MAX_TEXTURE_UNIT_ARRAY.slice(t,-1)}addVertex(t,e,...r){const[i,s]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}setCostumUnifrom(t){let e=!1;return this.costumUnifrom!=t?(e=!0,this.costumUnifrom=t):t?.isDirty&&(e=!0),t?.clearDirty(),e}exitRegion(){}initDefaultShader(t,e,r){this.setShader("default",t,e,r)}setShader(t,e,r,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new R(this.rapid,e,r,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e+this.currentShader.usedTexture),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[],this.isCostumShader=!1}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class S extends w{constructor(t){super(t),this.vertex=0,this.offset=l.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",f,p,b)}startRender(t,e,r,i){i&&this.currentShader?.setUniforms(i,1),this.offset=new l(t,e),this.vertex=0,this.webglArrayBuffer.clear(),r&&r.base&&(this.texture=this.useTexture(r.base.texture))}addVertex(t,e,r,i,s){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const A=Math.floor(16384);class v extends o{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class M extends w{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.setShader("default",T,x,E),this.indexBuffer=new v(e,A)}addVertex(t,e,r,i,s,a){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushUint32(a)}renderSprite(t,e,r,i,s,a,n,h,o,u,l,c,d){(this.batchSprite>=A||this.rapid.projectionDirty||l&&this.setCostumUnifrom(l))&&(this.render(),l&&this.currentShader.setUniforms(l,0),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const p=this.useTexture(t),f=c?a:i,g=c?i:a,m=d?n:s,y=d?s:n,x=h,T=h+e,E=o,b=o+r;this.addVertex(x,E,f,m,p,u),this.addVertex(T,E,g,m,p,u),this.addVertex(T,b,g,y,p,u),this.addVertex(x,b,f,y,p,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.setTextureUnits(this.currentShader.usedTexture))}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}hasPendingContent(){return this.batchSprite>0}}class U{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,e=this.antialias){let r=this.cache.get(t);if(!r){const i=await this.loadImage(t);r=F.fromImageSource(this.render,i,e),this.cache.set(t,r)}return new _(r)}textureFromFrameBufferObject(t){return new _(t)}async textureFromSource(t,e=this.antialias){let r=this.cache.get(t);return r||(r=F.fromImageSource(this.render,t,e),this.cache.set(t,r)),new _(r)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new N(this.render,t)}destroy(t){t instanceof _?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,r=this.antialias){return new B(this.render,t,e,r)}removeCache(t){const e=t instanceof _?t.base?.texture:t.texture;e&&this.cache.forEach(((t,r)=>{t===e&&this.cache.delete(r)}))}}class F{constructor(t,e,r){this.texture=t,this.width=e,this.height=r}static fromImageSource(t,e,r=!1){return new F(m(t.gl,e,r),e.width,e.height)}destroy(t){t.deleteTexture(this.texture)}}class _{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,r=!1){return new _(F.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}createSpritesHeet(t,e){if(!this.base)return[];const r=[],i=Math.floor(this.base.width/t),s=Math.floor(this.base.height/e);for(let a=0;a<s;a++)for(let s=0;s<i;s++){const i=this.clone();i.setClipRegion(s*t,a*e,t,e),r.push(i)}return r}clone(){return new _(this.base)}}class N extends _{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(F.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let a=0;for(const t of r)e.fillText(t,0,a),a+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class B extends F{constructor(t,e,r,i=!1){const s=t.gl,a=m(s,{width:e,height:r},i,!0,!1),n=s.createFramebuffer();if(!n)throw s.deleteTexture(a),new Error("Failed to create WebGL framebuffer");s.bindFramebuffer(s.FRAMEBUFFER,n),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a,0);const h=s.createRenderbuffer();if(!h)throw s.deleteFramebuffer(n),s.deleteTexture(a),new Error("Failed to create depth-stencil renderbuffer");s.bindRenderbuffer(s.RENDERBUFFER,h),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,e,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,h),super(a,e,r),this.gl=s,this.framebuffer=n,s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}const C=new Set;class I{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof _&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class P{constructor(t){this.rapid=t}getYSortRow(t,e,r){if(!t)return[];const i=[];for(const r of t){const t=Math.floor(r.ySort/e);i[t]||(i[t]=[]),i[t].push(r)}return i}getOffset(t){let e=(t.errorX??2)+1,r=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,r=i}else t.error&&(e=t.error.x+1,r=t.error.y+1);return{errorX:e,errorY:r}}getTileData(e,r){const i=r.shape??t.TilemapShape.SQUARE,s=e.width,a=i===t.TilemapShape.ISOMETRIC?e.height/2:e.height,n=this.rapid.matrixStack,h=n.globalToLocal(l.ZERO),o=n.getGlobalScale(),{errorX:u,errorY:c}=this.getOffset(r),d=Math.ceil(this.rapid.width/s/o.x)+2*u,p=Math.ceil(this.rapid.height/a/o.y)+2*c,f=new l(h.x<0?Math.ceil(h.x/s):Math.floor(h.x/s),h.y<0?Math.ceil(h.y/a):Math.floor(h.y/a));f.x-=u,f.y-=c;let g=new l(0-h.x%s-u*s,0-h.y%a-c*a);return g=g.add(h),{startTile:f,offset:g,viewportWidth:d,viewportHeight:p,height:a,width:s,shape:i}}renderYSortRow(t,e){for(const r of e)r.render?r.render():r.renderSprite&&t.renderSprite(r.renderSprite)}renderLayer(e,r){this.rapid.matrixStack.applyTransform(r);const i=r.tileSet,{startTile:s,offset:a,viewportWidth:n,viewportHeight:h,shape:o,width:u,height:l}=this.getTileData(i,r),c=this.getYSortRow(r.ySortCallback,l,h),d=r.ySortCallback&&r.ySortCallback.length>0;var p;0!==this.rapid.matrixStack.getGlobalRotation()&&(p="TileMapRender: tilemap is not supported rotation",C.has(p)||(C.add(p),console.warn(p)),this.rapid.matrixStack.setGlobalRotation(0));for(let p=0;p<h;p++){const h=p+s.y,f=c[h]??[];if(h<0||h>=e.length)this.renderYSortRow(this.rapid,f);else{for(let c=0;c<n;c++){const n=c+s.x;if(n<0||n>=e[h].length)continue;const d=e[h][n],g=i.getTile(d);if(!g)continue;let m=c*u+a.x,y=p*l+a.y,x=p*l+a.y+(g.ySortOffset??0);h%2!=0&&o===t.TilemapShape.ISOMETRIC&&(m+=u/2);const T=r.eachTile&&r.eachTile(d,n,h)||{};f.push({ySort:x,renderSprite:{...g,x:m+(g.x||0),y:y+(g.y||0),...T}})}d&&f.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,f)}}this.rapid.matrixStack.applyTransform(r)}localToMap(e,r){const i=r.tileSet;if(r.shape===t.TilemapShape.ISOMETRIC){let t=0,r=0;const s=i.height/2,a=i.width/2;let n=Math.floor(e.y/s);const h=n%2==0;let o=Math.floor(e.x/a);const u=o%2==0,c=e.x%a/a,d=e.y%s/s,p=d<c,f=d<1-c;return h||(n-=1),p&&!u&&h?n-=1:p||!u||h?f&&u&&h?(o-=2,n-=1):f||u||h||(n+=1):(n+=1,o-=2),t=o,r=n,t=Math.floor(o/2),new l(t,r)}return new l(Math.floor(e.x/i.width),Math.floor(e.y/i.height))}mapToLocal(e,r){const i=r.tileSet;if(r.shape===t.TilemapShape.ISOMETRIC){let t=new l(e.x*i.width,e.y*i.height/2);return e.y%2!=0&&(t.x+=i.width/2),t}return new l(e.x*i.width,e.y*i.height)}}return t.BaseTexture=F,t.Color=u,t.DynamicArrayBuffer=a,t.FrameBufferObject=B,t.GLShader=R,t.MathUtils=class{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}},t.MatrixStack=h,t.Rapid=class{constructor(t){this.projectionDirty=!0,this.matrixStack=new h,this.tileMap=new P(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new u(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[];const e=(t=>{const e={stencil:!0},r=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!r)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return r})(t.canvas);this.gl=e,this.canvas=t.canvas,this.textures=new U(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new u(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof I?{tileSet:e}:e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",M),this.registerRegion("graphic",S)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const r=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){this.startRender(),t(),this.endRender()}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:r,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,r,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,r=d({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:r})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,r)=>{const i=Array.isArray(t.color)?t.color[r]:t.color,s=t.uv?.[r];this.addGraphicVertex(e.x,e.y,s,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:r}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,r,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,r,i){this.currentRegion.addVertex(t,e,r?.x,r?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,r=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,r)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:r}=t,i=[new l(0,0),new l(e,0),new l(e,r),new l(0,r)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,r=t.radius,i=t.color||this.defaultColor,s=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,a=Math.cos(i)*r,n=Math.sin(i)*r;s.push(new l(a,n))}this.renderGraphic({...t,points:s,color:i,drawType:this.gl.TRIANGLE_FAN})}resize(t,e){const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.resizeWebglSize(t,e),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.width=t,this.height=e}resizeWebglSize(t,e,r){const i=t*(r||this.devicePixelRatio),s=e*(r||this.devicePixelRatio);this.gl.viewport(0,0,i,s),this.updateProjection(0,t,e,0),this.gl.scissor(0,0,i,s)}updateProjection(t,e,r,i){this.projection=this.createOrthMatrix(t,e,r,i),this.projectionDirty=!0}clear(t){const e=this.gl,r=t||this.backgroundColor;e.clearColor(r.r/255,r.g/255,r.b/255,r.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}drawMask(e=t.MaskType.Include,r){this.startDrawMask(e),r(),this.endDrawMask()}startDrawMask(e=t.MaskType.Include){const r=this.gl;this.currentMaskType.push(e),this.setMaskType(e,!0),r.stencilOp(r.KEEP,r.KEEP,r.REPLACE),r.colorMask(!1,!1,!1,!1)}endDrawMask(){const e=this.gl;this.quitCurrentRegion(),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??t.MaskType.Include,!1)}setMaskType(e,r=!1){const i=this.gl;if(this.quitCurrentRegion(),r)this.clearMask(),i.stencilFunc(i.ALWAYS,1,255);else switch(e){case t.MaskType.Include:i.stencilFunc(i.EQUAL,1,255);break;case t.MaskType.Exclude:i.stencilFunc(i.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,r,i=0){return R.createCostumShader(this,t,e,r,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeWebglSize(t.width,t.height,1),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeWebglSize(this.width,this.height),this.updateProjection(0,this.width,this.height,0),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}},t.SCALEFACTOR=2,t.Text=N,t.Texture=_,t.TextureCache=U,t.TileMapRender=P,t.TileSet=I,t.Uniform=class{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,r,i){const s=this.data[e];if("number"==typeof s)t.uniform1f(r,s);else if(Array.isArray(s))switch(s.length){case 1:Number.isInteger(s[0])?t.uniform1i(r,s[0]):t.uniform1f(r,s[0]);break;case 2:Number.isInteger(s[0])?t.uniform2iv(r,s):t.uniform2fv(r,s);break;case 3:Number.isInteger(s[0])?t.uniform3iv(r,s):t.uniform3fv(r,s);break;case 4:Number.isInteger(s[0])?t.uniform4iv(r,s):t.uniform4fv(r,s);break;case 9:t.uniformMatrix3fv(r,!1,s);break;case 16:t.uniformMatrix4fv(r,!1,s);break;default:console.error(`Unsupported uniform array length for ${e}:`,s.length)}else"boolean"==typeof s?t.uniform1i(r,s?1:0):s.base?.texture?(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,s.base.texture),t.uniform1i(r,i),i+=1):console.error(`Unsupported uniform type for ${e}:`,typeof s);return i}},t.Vec2=l,t.WebglBufferArray=n,t.WebglElementBufferArray=o,t.graphicAttributes=b,t.spriteAttributes=E,t}({});
1
+ var rapid=function(t){"use strict";var e,r,i,s,a;t.LineTextureMode=void 0,(e=t.LineTextureMode||(t.LineTextureMode={})).STRETCH="stretch",e.REPEAT="repeat",t.TextureWrapMode=void 0,(r=t.TextureWrapMode||(t.TextureWrapMode={})).REPEAT="repeat",r.CLAMP="clamp",r.MIRROR="mirror",t.MaskType=void 0,(i=t.MaskType||(t.MaskType={})).Include="normal",i.Exclude="inverse",t.TilemapShape=void 0,(s=t.TilemapShape||(t.TilemapShape={})).SQUARE="square",s.ISOMETRIC="isometric",t.ShaderType=void 0,(a=t.ShaderType||(t.ShaderType={})).SPRITE="sprite",a.GRAPHIC="graphic";class n{constructor(t){this.render=t}}var h;t.ArrayType=void 0,(h=t.ArrayType||(t.ArrayType={}))[h.Float32=0]="Float32",h[h.Uint32=1]="Uint32",h[h.Uint16=2]="Uint16";class o{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(e){switch(e){case t.ArrayType.Float32:return Float32Array;case t.ArrayType.Uint32:return Uint32Array;case t.ArrayType.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case t.ArrayType.Float32:this.typedArray=this.float32;break;case t.ArrayType.Uint32:this.typedArray=this.uint32;break;case t.ArrayType.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class u extends o{constructor(t,e,r=t.ARRAY_BUFFER,i=t.STATIC_DRAW){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r,this.usage=i}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),this.usage),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class l extends o{constructor(){super(t.ArrayType.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),a=r[e+0],n=r[e+1],h=r[e+2],o=r[e+3];r[e+0]=a*i-n*s,r[e+1]=a*s+n*i,r[e+2]=h*i-o*s,r[e+3]=h*s+o*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if("number"!=typeof t)return new p(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],a=e[t+3],n=e[t+4],h=e[t+5],o=r*a-i*s;return new Float32Array([a/o,-i/o,-s/o,r/o,(s*h-a*n)/o,(i*n-r*h)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new p(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=t,i[r+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,r=this.typedArray,i=this.getGlobalScale(),s=Math.cos(t),a=Math.sin(t);r[e+0]=s*i.x,r[e+1]=a*i.x,r[e+2]=-a*i.y,r[e+3]=s*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,r=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new p(r,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const r=this.getGlobalRotation(),i=Math.cos(r),s=Math.sin(r),a=this.usedElemNum-6,n=this.typedArray;n[a+0]=i*t,n[a+1]=s*t,n[a+2]=-s*e,n[a+3]=i*e}globalToLocal(t){const e=this.getInverse();return new p(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,r=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,s=t.y||0;(i||s)&&this.translate(i,s),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let a=t.offsetX||0,n=t.offsetY||0;t.offset&&(a+=t.offset.x,n+=t.offset.y);const h=t.origin;return h&&("number"==typeof h?(a-=h*e,n-=h*r):(a-=h.x*e,n-=h.y*r)),{offsetX:a,offsetY:n}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class c extends u{constructor(e,r,i,s){super(e,t.ArrayType.Uint16,e.ELEMENT_ARRAY_BUFFER,e.STATIC_DRAW),this.setMaxSize(r*s);for(let t=0;t<s;t++)this.addObject(t*i);this.bindBuffer(),this.bufferData()}addObject(t){}}class d{constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new d(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new d(e,r,i,s)}add(t){return new d(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new d(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}d.Red=new d(255,0,0,255),d.Green=new d(0,255,0,255),d.Blue=new d(0,0,255,255),d.Yellow=new d(255,255,0,255),d.Purple=new d(128,0,128,255),d.Orange=new d(255,165,0,255),d.Pink=new d(255,192,203,255),d.Gray=new d(128,128,128,255),d.Brown=new d(139,69,19,255),d.Cyan=new d(0,255,255,255),d.Magenta=new d(255,0,255,255),d.Lime=new d(192,255,0,255),d.White=new d(255,255,255,255),d.Black=new d(0,0,0,255),d.TRANSPARENT=new d(0,0,0,0);class p{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}add(t){return new p(this.x+t.x,this.y+t.y)}subtract(t){return new p(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof p?new p(this.x*t.x,this.y*t.y):new p(this.x*t,this.y*t)}divide(t){return t instanceof p?new p(this.x/t.x,this.y/t.y):new p(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)}clone(){return new p(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new p((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new p(Math.abs(this.x),Math.abs(this.y))}floor(){return new p(Math.floor(this.x),Math.floor(this.y))}ceil(){return new p(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new p(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new p(t[0],t[1])))}}p.ZERO=new p(0,0),p.ONE=new p(1,1),p.UP=new p(0,1),p.DOWN=new p(0,-1),p.LEFT=new p(-1,0),p.RIGHT=new p(1,0);const f=(t,e,r,i)=>{const s=[],a=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),n=Math.PI;for(let e=0;e<10;e++){const i=a+e/10*n,h=a+(e+1)/10*n,o=Math.cos(i)*r,u=Math.sin(i)*r,l=Math.cos(h)*r,c=Math.sin(h)*r;s.push(t),s.push(t.add(new p(o,u))),s.push(t.add(new p(l,c)))}return s},g=e=>{const r=e.points;if(r.length<2)return{vertices:[],uv:[]};const{normals:i,length:s}=((t,e=!1)=>{const r=[];if(t.length<2||e&&t.length<3)return{normals:r,length:0};const i=t.length;let s=0;if(e)for(let e=0;e<i;e++){const r=t[e],a=t[(e+1)%i];s+=r.distanceTo(a)}else for(let e=0;e<i-1;e++)s+=t[e].distanceTo(t[e+1]);const a=(t,e,r)=>{const i=e.subtract(t).normalize(),s=e.subtract(r).normalize(),a=s.dot(i);if(a<-.999)return{normal:i.perpendicular(),miters:1};{let t=s.add(i).normalize();i.cross(s)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-a)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const s=0===e?t[i-2]:t[e-1],n=t[e],h=t[e+1];r.push(a(s,n,h))}r.push(r[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();r.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();r.push({normal:i.perpendicular(),miters:1})}else r.push(a(t[e-1],t[e],t[e+1]));return{normals:r,length:s}})(r,e.closed),a=(e.width||1)/2,n=[],h=[],o=e.roundCap||!1,u=e.textureMode||t.LineTextureMode.STRETCH;let l=0;const c=e.texture?.width||1;for(let e=0;e<r.length-1;e++){const o=r[e],d=i[e].normal,f=i[e].miters,g=o.add(d.multiply(f*a)),m=o.subtract(d.multiply(f*a)),y=r[e+1],T=i[e+1].normal,x=i[e+1].miters,E=y.add(T.multiply(x*a)),R=y.subtract(T.multiply(x*a)),b=o.distanceTo(y);let w=0,S=0;u===t.LineTextureMode.STRETCH?(w=l/s,S=(l+b)/s):(w=l/c,S=w+b/c);const A=new p(w,0),M=new p(w,1),v=new p(S,0),U=new p(S,1);n.push(g),h.push(A),n.push(m),h.push(M),n.push(E),h.push(v),n.push(E),h.push(v),n.push(R),h.push(U),n.push(m),h.push(M),l+=b}if(o&&!e.closed){const t=r[0],e=i[0].normal,s=f(t,e,a,!0);n.push(...s);const h=r[r.length-1],o=i[r.length-1].normal,u=f(h,o,a,!1);n.push(...u)}return{vertices:n,uv:h}};var m="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n gl_FragColor = color;\r\n}\r\n",y="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n \r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const T=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};function x(t,e,r,i=!1,s=!1,a="clamp"){const n=t.createTexture();if(!n)throw new Error("unable to create texture");let h;switch(t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),a){case"repeat":h=t.REPEAT;break;case"mirror":h=t.MIRRORED_REPEAT;break;default:h=t.CLAMP_TO_EDGE}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,h),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,h),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,s),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),n}const E=5126;var R="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color * vColor;\r\n}",b="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}";const w=[{name:"aPosition",size:2,type:E,stride:24},{name:"aRegion",size:2,type:E,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:E,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],S=[{name:"aPosition",size:2,type:E,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:E,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class A{constructor(t,e,r,i,s=0){this.attributeLoc={},this.uniformLoc={},this.attributes=[];const a=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(r,t.maxTextureUnits-s);this.program=((t,e,r)=>{var i=t.createProgram(),s=T(t,e,35633),a=T(t,r,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,s),t.attachShader(i,a),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,a),this.gl=t.gl,this.usedTexture=s,this.parseShader(e),this.parseShader(a),i&&this.setAttributes(i)}setUniforms(t,e){const r=this.gl;for(const i of t.getUnifromNames()){const s=this.getUniform(i);e=t.bind(r,i,s,e)}return e}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(e,r,i,s,a=0){let n={[t.ShaderType.SPRITE]:R,[t.ShaderType.GRAPHIC]:m}[s],h={[t.ShaderType.SPRITE]:b,[t.ShaderType.GRAPHIC]:y}[s];const o={[t.ShaderType.SPRITE]:w,[t.ShaderType.GRAPHIC]:S}[s];return n=n.replace("void main(void) {",i+"\nvoid main(void) {"),h=h.replace("void main(void) {",r+"\nvoid main(void) {"),n=n.replace("gl_FragColor = ","fragment(color);\ngl_FragColor = "),h=h.replace("gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);","vec2 position = aPosition;\nvertex(position, vRegion);\ngl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new A(e,h,n,o,a)}}class M{constructor(e){this.usedTextures=[],this.needBind=new Set,this.shaders=new Map,this.isCostumShader=!1,this.rapid=e,this.gl=e.gl,this.webglArrayBuffer=new u(e.gl,t.ArrayType.Float32,e.gl.ARRAY_BUFFER,e.gl.STREAM_DRAW),this.MAX_TEXTURE_UNIT_ARRAY=Array.from({length:e.maxTextureUnits},((t,e)=>e))}setTextureUnits(t){return this.MAX_TEXTURE_UNIT_ARRAY.slice(t,-1)}addVertex(t,e,...r){const[i,s]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}setCostumUnifrom(t){let e=!1;return this.costumUnifrom!=t?(e=!0,this.costumUnifrom=t):t?.isDirty&&(e=!0),t?.clearDirty(),e}exitRegion(){}initDefaultShader(t,e,r){this.setShader("default",t,e,r)}setShader(t,e,r,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new A(this.rapid,e,r,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e+this.currentShader.usedTexture),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[],this.isCostumShader=!1}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class v extends M{constructor(t){super(t),this.vertex=0,this.offset=p.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",y,m,S)}startRender(t,e,r,i){i&&this.currentShader?.setUniforms(i,1),this.offset=new p(t,e),this.vertex=0,this.webglArrayBuffer.clear(),r&&r.base&&(this.texture=this.useTexture(r.base.texture))}addVertex(t,e,r,i,s){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const U=Math.floor(16384);class F extends c{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class _ extends M{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.setShader("default",b,R,w),this.indexBuffer=new F(e,U)}addVertex(t,e,r,i,s,a){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushUint32(a)}renderSprite(t,e,r,i,s,a,n,h,o,u,l,c,d){(this.batchSprite>=U||this.rapid.projectionDirty||l&&this.setCostumUnifrom(l))&&(this.render(),l&&this.currentShader.setUniforms(l,0),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const p=this.useTexture(t),f=c?a:i,g=c?i:a,m=d?n:s,y=d?s:n,T=h,x=h+e,E=o,R=o+r;this.addVertex(T,E,f,m,p,u),this.addVertex(x,E,g,m,p,u),this.addVertex(x,R,g,y,p,u),this.addVertex(T,R,f,y,p,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.setTextureUnits(this.currentShader.usedTexture))}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}hasPendingContent(){return this.batchSprite>0}}class C{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(e,r=this.antialias,i=t.TextureWrapMode.CLAMP){let s=this.cache.get(e);if(!s){const t=await this.loadImage(e);s=N.fromImageSource(this.render,t,r,i),this.cache.set(e,s)}return new I(s)}textureFromFrameBufferObject(t){return new I(t)}async textureFromSource(e,r=this.antialias,i=t.TextureWrapMode.CLAMP){let s=this.cache.get(e);return s||(s=N.fromImageSource(this.render,e,r,i),this.cache.set(e,s)),new I(s)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new B(this.render,t)}destroy(t){t instanceof I?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,r=this.antialias){return new P(this.render,t,e,r)}removeCache(t){const e=t instanceof I?t.base?.texture:t.texture;e&&this.cache.forEach(((t,r)=>{t===e&&this.cache.delete(r)}))}}class N{constructor(e,r,i,s=t.TextureWrapMode.CLAMP){this.texture=e,this.width=r,this.height=i,this.wrapMode=s}static fromImageSource(e,r,i=!1,s=t.TextureWrapMode.CLAMP){return new N(x(e.gl,r,i,!1,!1,s),r.width,r.height)}destroy(t){t.deleteTexture(this.texture)}}class I{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,r=!1){return new I(N.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}createSpritesHeet(t,e){if(!this.base)return[];const r=[],i=Math.floor(this.base.width/t),s=Math.floor(this.base.height/e);for(let a=0;a<s;a++)for(let s=0;s<i;s++){const i=this.clone();i.setClipRegion(s*t,a*e,t,e),r.push(i)}return r}clone(){return new I(this.base)}}class B extends I{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(N.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let a=0;for(const t of r)e.fillText(t,0,a),a+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class P extends N{constructor(t,e,r,i=!1){const s=t.gl,a=x(s,{width:e,height:r},i,!0,!1),n=s.createFramebuffer();if(!n)throw s.deleteTexture(a),new Error("Failed to create WebGL framebuffer");s.bindFramebuffer(s.FRAMEBUFFER,n),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a,0);const h=s.createRenderbuffer();if(!h)throw s.deleteFramebuffer(n),s.deleteTexture(a),new Error("Failed to create depth-stencil renderbuffer");s.bindRenderbuffer(s.RENDERBUFFER,h),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,e,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,h),super(a,e,r),this.gl=s,this.framebuffer=n,s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}const L=new Set;class D{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof I&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class k{constructor(t){this.rapid=t}getYSortRow(t,e,r){if(!t)return[];const i=[];for(const r of t){const t=Math.floor(r.ySort/e);i[t]||(i[t]=[]),i[t].push(r)}return i}getOffset(t){let e=(t.errorX??2)+1,r=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,r=i}else t.error&&(e=t.error.x+1,r=t.error.y+1);return{errorX:e,errorY:r}}getTileData(e,r){const i=r.shape??t.TilemapShape.SQUARE,s=e.width,a=i===t.TilemapShape.ISOMETRIC?e.height/2:e.height,n=this.rapid.matrixStack,h=n.globalToLocal(p.ZERO),o=n.getGlobalScale(),{errorX:u,errorY:l}=this.getOffset(r),c=Math.ceil(this.rapid.width/s/o.x)+2*u,d=Math.ceil(this.rapid.height/a/o.y)+2*l,f=new p(h.x<0?Math.ceil(h.x/s):Math.floor(h.x/s),h.y<0?Math.ceil(h.y/a):Math.floor(h.y/a));f.x-=u,f.y-=l;let g=new p(0-h.x%s-u*s,0-h.y%a-l*a);return g=g.add(h),{startTile:f,offset:g,viewportWidth:c,viewportHeight:d,height:a,width:s,shape:i}}renderYSortRow(t,e){for(const r of e)r.render?r.render():r.renderSprite&&t.renderSprite(r.renderSprite)}renderLayer(e,r){this.rapid.matrixStack.applyTransform(r);const i=r.tileSet,{startTile:s,offset:a,viewportWidth:n,viewportHeight:h,shape:o,width:u,height:l}=this.getTileData(i,r),c=this.getYSortRow(r.ySortCallback,l,h),d=r.ySortCallback&&r.ySortCallback.length>0;var p;0!==this.rapid.matrixStack.getGlobalRotation()&&(p="TileMapRender: tilemap is not supported rotation",L.has(p)||(L.add(p),console.warn(p)),this.rapid.matrixStack.setGlobalRotation(0));for(let p=0;p<h;p++){const h=p+s.y,f=c[h]??[];if(h<0||h>=e.length)this.renderYSortRow(this.rapid,f);else{for(let c=0;c<n;c++){const n=c+s.x;if(n<0||n>=e[h].length)continue;const d=e[h][n],g=i.getTile(d);if(!g)continue;let m=c*u+a.x,y=p*l+a.y,T=p*l+a.y+(g.ySortOffset??0);h%2!=0&&o===t.TilemapShape.ISOMETRIC&&(m+=u/2);const x=r.eachTile&&r.eachTile(d,n,h)||{};f.push({ySort:T,renderSprite:{...g,x:m+(g.x||0),y:y+(g.y||0),...x}})}d&&f.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,f)}}this.rapid.matrixStack.applyTransform(r)}localToMap(e,r){const i=r.tileSet;if(r.shape===t.TilemapShape.ISOMETRIC){let t=0,r=0;const s=i.height/2,a=i.width/2;let n=Math.floor(e.y/s);const h=n%2==0;let o=Math.floor(e.x/a);const u=o%2==0,l=e.x%a/a,c=e.y%s/s,d=c<l,f=c<1-l;return h||(n-=1),d&&!u&&h?n-=1:d||!u||h?f&&u&&h?(o-=2,n-=1):f||u||h||(n+=1):(n+=1,o-=2),t=o,r=n,t=Math.floor(o/2),new p(t,r)}return new p(Math.floor(e.x/i.width),Math.floor(e.y/i.height))}mapToLocal(e,r){const i=r.tileSet;if(r.shape===t.TilemapShape.ISOMETRIC){let t=new p(e.x*i.width,e.y*i.height/2);return e.y%2!=0&&(t.x+=i.width/2),t}return new p(e.x*i.width,e.y*i.height)}}return t.BaseTexture=N,t.Color=d,t.DynamicArrayBuffer=o,t.FrameBufferObject=P,t.GLShader=A,t.MathUtils=class{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}},t.MatrixStack=l,t.Rapid=class{constructor(t){this.projectionDirty=!0,this.matrixStack=new l,this.tileMap=new k(this),this.light=new n(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new d(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[];const e=(t=>{const e={stencil:!0},r=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!r)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return r})(t.canvas);this.gl=e,this.canvas=t.canvas,this.textures=new C(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new d(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof D?{tileSet:e}:e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",_),this.registerRegion("graphic",v)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const r=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){this.startRender(),t(),this.endRender()}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:r,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,r,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,{vertices:r,uv:i}=g({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:r,uv:i})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,r)=>{const i=Array.isArray(t.color)?t.color[r]:t.color,s=t.uv?.[r];this.addGraphicVertex(e.x,e.y,s,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:r}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,r,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,r,i){this.currentRegion.addVertex(t,e,r?.x,r?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,r=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,r)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:r}=t,i=[new p(0,0),new p(e,0),new p(e,r),new p(0,r)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,r=t.radius,i=t.color||this.defaultColor,s=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,a=Math.cos(i)*r,n=Math.sin(i)*r;s.push(new p(a,n))}this.renderGraphic({...t,points:s,color:i,drawType:this.gl.TRIANGLE_FAN})}resize(t,e){const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.resizeWebglSize(t,e),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.width=t,this.height=e}resizeWebglSize(t,e,r){const i=t*(r||this.devicePixelRatio),s=e*(r||this.devicePixelRatio);this.gl.viewport(0,0,i,s),this.updateProjection(0,t,e,0),this.gl.scissor(0,0,i,s)}updateProjection(t,e,r,i){this.projection=this.createOrthMatrix(t,e,r,i),this.projectionDirty=!0}clear(t){const e=this.gl,r=t||this.backgroundColor;e.clearColor(r.r/255,r.g/255,r.b/255,r.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}drawMask(e=t.MaskType.Include,r){this.startDrawMask(e),r(),this.endDrawMask()}startDrawMask(e=t.MaskType.Include){const r=this.gl;this.currentMaskType.push(e),this.setMaskType(e,!0),r.stencilOp(r.KEEP,r.KEEP,r.REPLACE),r.colorMask(!1,!1,!1,!1)}endDrawMask(){const e=this.gl;this.quitCurrentRegion(),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??t.MaskType.Include,!1)}setMaskType(e,r=!1){const i=this.gl;if(this.quitCurrentRegion(),r)this.clearMask(),i.stencilFunc(i.ALWAYS,1,255);else switch(e){case t.MaskType.Include:i.stencilFunc(i.EQUAL,1,255);break;case t.MaskType.Exclude:i.stencilFunc(i.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,r,i=0){return A.createCostumShader(this,t,e,r,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeWebglSize(t.width,t.height,1),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeWebglSize(this.width,this.height),this.updateProjection(0,this.width,this.height,0),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}},t.SCALEFACTOR=2,t.Text=B,t.Texture=I,t.TextureCache=C,t.TileMapRender=k,t.TileSet=D,t.Uniform=class{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,r,i){const s=this.data[e];if("number"==typeof s)t.uniform1f(r,s);else if(Array.isArray(s))switch(s.length){case 1:Number.isInteger(s[0])?t.uniform1i(r,s[0]):t.uniform1f(r,s[0]);break;case 2:Number.isInteger(s[0])?t.uniform2iv(r,s):t.uniform2fv(r,s);break;case 3:Number.isInteger(s[0])?t.uniform3iv(r,s):t.uniform3fv(r,s);break;case 4:Number.isInteger(s[0])?t.uniform4iv(r,s):t.uniform4fv(r,s);break;case 9:t.uniformMatrix3fv(r,!1,s);break;case 16:t.uniformMatrix4fv(r,!1,s);break;default:console.error(`Unsupported uniform array length for ${e}:`,s.length)}else"boolean"==typeof s?t.uniform1i(r,s?1:0):s.base?.texture?(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,s.base.texture),t.uniform1i(r,i),i+=1):console.error(`Unsupported uniform type for ${e}:`,typeof s);return i}},t.Vec2=p,t.WebglBufferArray=u,t.WebglElementBufferArray=c,t.graphicAttributes=S,t.spriteAttributes=w,t}({});
package/dist/rapid.js CHANGED
@@ -1 +1 @@
1
- var t,e,r;!function(t){t.Include="normal",t.Exclude="inverse"}(t||(t={})),function(t){t.SQUARE="square",t.ISOMETRIC="isometric"}(e||(e={})),function(t){t.SPRITE="sprite",t.GRAPHIC="graphic"}(r||(r={}));var i;!function(t){t[t.Float32=0]="Float32",t[t.Uint32=1]="Uint32",t[t.Uint16=2]="Uint16"}(i||(i={}));class s{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(t){switch(t){case i.Float32:return Float32Array;case i.Uint32:return Uint32Array;case i.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case i.Float32:this.typedArray=this.float32;break;case i.Uint32:this.typedArray=this.uint32;break;case i.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class n extends s{constructor(t,e,r=t.ARRAY_BUFFER){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),t.STATIC_DRAW),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class a extends s{constructor(){super(i.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),n=r[e+0],a=r[e+1],h=r[e+2],o=r[e+3];r[e+0]=n*i-a*s,r[e+1]=n*s+a*i,r[e+2]=h*i-o*s,r[e+3]=h*s+o*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if("number"!=typeof t)return new u(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],n=e[t+3],a=e[t+4],h=e[t+5],o=r*n-i*s;return new Float32Array([n/o,-i/o,-s/o,r/o,(s*h-n*a)/o,(i*a-r*h)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new u(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=t,i[r+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,r=this.typedArray,i=this.getGlobalScale(),s=Math.cos(t),n=Math.sin(t);r[e+0]=s*i.x,r[e+1]=n*i.x,r[e+2]=-n*i.y,r[e+3]=s*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,r=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new u(r,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const r=this.getGlobalRotation(),i=Math.cos(r),s=Math.sin(r),n=this.usedElemNum-6,a=this.typedArray;a[n+0]=i*t,a[n+1]=s*t,a[n+2]=-s*e,a[n+3]=i*e}globalToLocal(t){const e=this.getInverse();return new u(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,r=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,s=t.y||0;(i||s)&&this.translate(i,s),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let n=t.offsetX||0,a=t.offsetY||0;t.offset&&(n+=t.offset.x,a+=t.offset.y);const h=t.origin;return h&&("number"==typeof h?(n-=h*e,a-=h*r):(n-=h.x*e,a-=h.y*r)),{offsetX:n,offsetY:a}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class h extends n{constructor(t,e,r,s){super(t,i.Uint16,t.ELEMENT_ARRAY_BUFFER),this.setMaxSize(e*s);for(let t=0;t<s;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class o{constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new o(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new o(e,r,i,s)}add(t){return new o(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new o(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}o.Red=new o(255,0,0,255),o.Green=new o(0,255,0,255),o.Blue=new o(0,0,255,255),o.Yellow=new o(255,255,0,255),o.Purple=new o(128,0,128,255),o.Orange=new o(255,165,0,255),o.Pink=new o(255,192,203,255),o.Gray=new o(128,128,128,255),o.Brown=new o(139,69,19,255),o.Cyan=new o(0,255,255,255),o.Magenta=new o(255,0,255,255),o.Lime=new o(192,255,0,255),o.White=new o(255,255,255,255),o.Black=new o(0,0,0,255),o.TRANSPARENT=new o(0,0,0,0);class u{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}add(t){return new u(this.x+t.x,this.y+t.y)}subtract(t){return new u(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof u?new u(this.x*t.x,this.y*t.y):new u(this.x*t,this.y*t)}divide(t){return t instanceof u?new u(this.x/t.x,this.y/t.y):new u(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)}clone(){return new u(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new u((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new u(Math.abs(this.x),Math.abs(this.y))}floor(){return new u(Math.floor(this.x),Math.floor(this.y))}ceil(){return new u(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new u(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new u(t[0],t[1])))}}u.ZERO=new u(0,0),u.ONE=new u(1,1),u.UP=new u(0,1),u.DOWN=new u(0,-1),u.LEFT=new u(-1,0),u.RIGHT=new u(1,0);class l{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}}const c=(t,e,r,i)=>{const s=[],n=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),a=Math.PI;for(let e=0;e<10;e++){const i=n+e/10*a,h=n+(e+1)/10*a,o=Math.cos(i)*r,l=Math.sin(i)*r,c=Math.cos(h)*r,d=Math.sin(h)*r;s.push(t),s.push(t.add(new u(o,l))),s.push(t.add(new u(c,d)))}return s},d=t=>{const e=t.points;if(e.length<2)return[];const r=((t,e=!1)=>{const r=[];if(t.length<2||e&&t.length<3)return r;const i=t.length,s=(t,e,r)=>{const i=e.subtract(t).normalize(),s=e.subtract(r).normalize(),n=s.dot(i);if(n<-.999)return{normal:i.perpendicular(),miters:1};{let t=s.add(i).normalize();i.cross(s)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-n)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const n=0===e?t[i-2]:t[e-1],a=t[e],h=t[e+1];r.push(s(n,a,h))}r.push(r[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();r.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();r.push({normal:i.perpendicular(),miters:1})}else r.push(s(t[e-1],t[e],t[e+1]));return r})(e,t.closed),i=(t.width||1)/2,s=[],n=t.roundCap||!1;for(let t=0;t<e.length-1;t++){const n=e[t],a=r[t].normal,h=r[t].miters,o=n.add(a.multiply(h*i)),u=n.subtract(a.multiply(h*i)),l=e[t+1],c=r[t+1].normal,d=r[t+1].miters,f=l.add(c.multiply(d*i)),p=l.subtract(c.multiply(d*i));s.push(o),s.push(u),s.push(f),s.push(f),s.push(p),s.push(u)}if(n&&!t.closed){const t=e[0],n=r[0].normal;s.push(...c(t,n,i,!0));const a=e[e.length-1],h=r[e.length-1].normal;s.push(...c(a,h,i,!1))}return s};var f="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n gl_FragColor = color;\r\n}\r\n",p="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n \r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const g=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};function m(t,e,r,i=!1,s=!1){const n=t.createTexture();if(!n)throw new Error("unable to create texture");return t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,s),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),n}const y=5126;var x="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color * vColor;\r\n}",T="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}";const E=[{name:"aPosition",size:2,type:y,stride:24},{name:"aRegion",size:2,type:y,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:y,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],b=[{name:"aPosition",size:2,type:y,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:y,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class R{constructor(t,e,r,i,s=0){this.attributeLoc={},this.uniformLoc={},this.attributes=[];const n=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(r,t.maxTextureUnits-s);this.program=((t,e,r)=>{var i=t.createProgram(),s=g(t,e,35633),n=g(t,r,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,s),t.attachShader(i,n),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,n),this.gl=t.gl,this.usedTexture=s,this.parseShader(e),this.parseShader(n),i&&this.setAttributes(i)}setUniforms(t,e){const r=this.gl;for(const i of t.getUnifromNames()){const s=this.getUniform(i);e=t.bind(r,i,s,e)}return e}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(t,e,i,s,n=0){let a={[r.SPRITE]:x,[r.GRAPHIC]:f}[s],h={[r.SPRITE]:T,[r.GRAPHIC]:p}[s];const o={[r.SPRITE]:E,[r.GRAPHIC]:b}[s];return a=a.replace("void main(void) {",i+"\nvoid main(void) {"),h=h.replace("void main(void) {",e+"\nvoid main(void) {"),a=a.replace("gl_FragColor = ","fragment(color);\ngl_FragColor = "),h=h.replace("gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);","vec2 position = aPosition;\nvertex(position, vRegion);\ngl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new R(t,h,a,o,n)}}class w{constructor(t){this.usedTextures=[],this.needBind=new Set,this.shaders=new Map,this.isCostumShader=!1,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new n(t.gl,i.Float32,t.gl.ARRAY_BUFFER),this.MAX_TEXTURE_UNIT_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}setTextureUnits(t){return this.MAX_TEXTURE_UNIT_ARRAY.slice(t,-1)}addVertex(t,e,...r){const[i,s]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}setCostumUnifrom(t){let e=!1;return this.costumUnifrom!=t?(e=!0,this.costumUnifrom=t):t?.isDirty&&(e=!0),t?.clearDirty(),e}exitRegion(){}initDefaultShader(t,e,r){this.setShader("default",t,e,r)}setShader(t,e,r,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new R(this.rapid,e,r,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e+this.currentShader.usedTexture),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[],this.isCostumShader=!1}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class S extends w{constructor(t){super(t),this.vertex=0,this.offset=u.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",p,f,b)}startRender(t,e,r,i){i&&this.currentShader?.setUniforms(i,1),this.offset=new u(t,e),this.vertex=0,this.webglArrayBuffer.clear(),r&&r.base&&(this.texture=this.useTexture(r.base.texture))}addVertex(t,e,r,i,s){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const A=Math.floor(16384);class v extends h{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class M extends w{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.setShader("default",T,x,E),this.indexBuffer=new v(e,A)}addVertex(t,e,r,i,s,n){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushUint32(n)}renderSprite(t,e,r,i,s,n,a,h,o,u,l,c,d){(this.batchSprite>=A||this.rapid.projectionDirty||l&&this.setCostumUnifrom(l))&&(this.render(),l&&this.currentShader.setUniforms(l,0),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const f=this.useTexture(t),p=c?n:i,g=c?i:n,m=d?a:s,y=d?s:a,x=h,T=h+e,E=o,b=o+r;this.addVertex(x,E,p,m,f,u),this.addVertex(T,E,g,m,f,u),this.addVertex(T,b,g,y,f,u),this.addVertex(x,b,p,y,f,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.setTextureUnits(this.currentShader.usedTexture))}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}hasPendingContent(){return this.batchSprite>0}}class U{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,e=this.antialias){let r=this.cache.get(t);if(!r){const i=await this.loadImage(t);r=F.fromImageSource(this.render,i,e),this.cache.set(t,r)}return new _(r)}textureFromFrameBufferObject(t){return new _(t)}async textureFromSource(t,e=this.antialias){let r=this.cache.get(t);return r||(r=F.fromImageSource(this.render,t,e),this.cache.set(t,r)),new _(r)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new I(this.render,t)}destroy(t){t instanceof _?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,r=this.antialias){return new C(this.render,t,e,r)}removeCache(t){const e=t instanceof _?t.base?.texture:t.texture;e&&this.cache.forEach(((t,r)=>{t===e&&this.cache.delete(r)}))}}class F{constructor(t,e,r){this.texture=t,this.width=e,this.height=r}static fromImageSource(t,e,r=!1){return new F(m(t.gl,e,r),e.width,e.height)}destroy(t){t.deleteTexture(this.texture)}}class _{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,r=!1){return new _(F.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}createSpritesHeet(t,e){if(!this.base)return[];const r=[],i=Math.floor(this.base.width/t),s=Math.floor(this.base.height/e);for(let n=0;n<s;n++)for(let s=0;s<i;s++){const i=this.clone();i.setClipRegion(s*t,n*e,t,e),r.push(i)}return r}clone(){return new _(this.base)}}const N=2;class I extends _{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(F.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of r)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class C extends F{constructor(t,e,r,i=!1){const s=t.gl,n=m(s,{width:e,height:r},i,!0,!1),a=s.createFramebuffer();if(!a)throw s.deleteTexture(n),new Error("Failed to create WebGL framebuffer");s.bindFramebuffer(s.FRAMEBUFFER,a),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,n,0);const h=s.createRenderbuffer();if(!h)throw s.deleteFramebuffer(a),s.deleteTexture(n),new Error("Failed to create depth-stencil renderbuffer");s.bindRenderbuffer(s.RENDERBUFFER,h),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,e,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,h),super(n,e,r),this.gl=s,this.framebuffer=a,s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}const B=new Set;class P{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof _&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class D{constructor(t){this.rapid=t}getYSortRow(t,e,r){if(!t)return[];const i=[];for(const r of t){const t=Math.floor(r.ySort/e);i[t]||(i[t]=[]),i[t].push(r)}return i}getOffset(t){let e=(t.errorX??2)+1,r=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,r=i}else t.error&&(e=t.error.x+1,r=t.error.y+1);return{errorX:e,errorY:r}}getTileData(t,r){const i=r.shape??e.SQUARE,s=t.width,n=i===e.ISOMETRIC?t.height/2:t.height,a=this.rapid.matrixStack,h=a.globalToLocal(u.ZERO),o=a.getGlobalScale(),{errorX:l,errorY:c}=this.getOffset(r),d=Math.ceil(this.rapid.width/s/o.x)+2*l,f=Math.ceil(this.rapid.height/n/o.y)+2*c,p=new u(h.x<0?Math.ceil(h.x/s):Math.floor(h.x/s),h.y<0?Math.ceil(h.y/n):Math.floor(h.y/n));p.x-=l,p.y-=c;let g=new u(0-h.x%s-l*s,0-h.y%n-c*n);return g=g.add(h),{startTile:p,offset:g,viewportWidth:d,viewportHeight:f,height:n,width:s,shape:i}}renderYSortRow(t,e){for(const r of e)r.render?r.render():r.renderSprite&&t.renderSprite(r.renderSprite)}renderLayer(t,r){this.rapid.matrixStack.applyTransform(r);const i=r.tileSet,{startTile:s,offset:n,viewportWidth:a,viewportHeight:h,shape:o,width:u,height:l}=this.getTileData(i,r),c=this.getYSortRow(r.ySortCallback,l,h),d=r.ySortCallback&&r.ySortCallback.length>0;var f;0!==this.rapid.matrixStack.getGlobalRotation()&&(f="TileMapRender: tilemap is not supported rotation",B.has(f)||(B.add(f),console.warn(f)),this.rapid.matrixStack.setGlobalRotation(0));for(let f=0;f<h;f++){const h=f+s.y,p=c[h]??[];if(h<0||h>=t.length)this.renderYSortRow(this.rapid,p);else{for(let c=0;c<a;c++){const a=c+s.x;if(a<0||a>=t[h].length)continue;const d=t[h][a],g=i.getTile(d);if(!g)continue;let m=c*u+n.x,y=f*l+n.y,x=f*l+n.y+(g.ySortOffset??0);h%2!=0&&o===e.ISOMETRIC&&(m+=u/2);const T=r.eachTile&&r.eachTile(d,a,h)||{};p.push({ySort:x,renderSprite:{...g,x:m+(g.x||0),y:y+(g.y||0),...T}})}d&&p.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,p)}}this.rapid.matrixStack.applyTransform(r)}localToMap(t,r){const i=r.tileSet;if(r.shape===e.ISOMETRIC){let e=0,r=0;const s=i.height/2,n=i.width/2;let a=Math.floor(t.y/s);const h=a%2==0;let o=Math.floor(t.x/n);const l=o%2==0,c=t.x%n/n,d=t.y%s/s,f=d<c,p=d<1-c;return h||(a-=1),f&&!l&&h?a-=1:f||!l||h?p&&l&&h?(o-=2,a-=1):p||l||h||(a+=1):(a+=1,o-=2),e=o,r=a,e=Math.floor(o/2),new u(e,r)}return new u(Math.floor(t.x/i.width),Math.floor(t.y/i.height))}mapToLocal(t,r){const i=r.tileSet;if(r.shape===e.ISOMETRIC){let e=new u(t.x*i.width,t.y*i.height/2);return t.y%2!=0&&(e.x+=i.width/2),e}return new u(t.x*i.width,t.y*i.height)}}class L{constructor(t){this.projectionDirty=!0,this.matrixStack=new a,this.tileMap=new D(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new o(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[];const e=(t=>{const e={stencil:!0},r=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!r)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return r})(t.canvas);this.gl=e,this.canvas=t.canvas,this.textures=new U(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new o(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof P?{tileSet:e}:e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",M),this.registerRegion("graphic",S)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const r=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){this.startRender(),t(),this.endRender()}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:r,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,r,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,r=d({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:r})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,r)=>{const i=Array.isArray(t.color)?t.color[r]:t.color,s=t.uv?.[r];this.addGraphicVertex(e.x,e.y,s,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:r}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,r,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,r,i){this.currentRegion.addVertex(t,e,r?.x,r?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,r=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,r)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:r}=t,i=[new u(0,0),new u(e,0),new u(e,r),new u(0,r)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,r=t.radius,i=t.color||this.defaultColor,s=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,n=Math.cos(i)*r,a=Math.sin(i)*r;s.push(new u(n,a))}this.renderGraphic({...t,points:s,color:i,drawType:this.gl.TRIANGLE_FAN})}resize(t,e){const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.resizeWebglSize(t,e),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.width=t,this.height=e}resizeWebglSize(t,e,r){const i=t*(r||this.devicePixelRatio),s=e*(r||this.devicePixelRatio);this.gl.viewport(0,0,i,s),this.updateProjection(0,t,e,0),this.gl.scissor(0,0,i,s)}updateProjection(t,e,r,i){this.projection=this.createOrthMatrix(t,e,r,i),this.projectionDirty=!0}clear(t){const e=this.gl,r=t||this.backgroundColor;e.clearColor(r.r/255,r.g/255,r.b/255,r.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}drawMask(e=t.Include,r){this.startDrawMask(e),r(),this.endDrawMask()}startDrawMask(e=t.Include){const r=this.gl;this.currentMaskType.push(e),this.setMaskType(e,!0),r.stencilOp(r.KEEP,r.KEEP,r.REPLACE),r.colorMask(!1,!1,!1,!1)}endDrawMask(){const e=this.gl;this.quitCurrentRegion(),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??t.Include,!1)}setMaskType(e,r=!1){const i=this.gl;if(this.quitCurrentRegion(),r)this.clearMask(),i.stencilFunc(i.ALWAYS,1,255);else switch(e){case t.Include:i.stencilFunc(i.EQUAL,1,255);break;case t.Exclude:i.stencilFunc(i.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,r,i=0){return R.createCostumShader(this,t,e,r,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeWebglSize(t.width,t.height,1),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeWebglSize(this.width,this.height),this.updateProjection(0,this.width,this.height,0),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}}class G{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,r,i){const s=this.data[e];if("number"==typeof s)t.uniform1f(r,s);else if(Array.isArray(s))switch(s.length){case 1:Number.isInteger(s[0])?t.uniform1i(r,s[0]):t.uniform1f(r,s[0]);break;case 2:Number.isInteger(s[0])?t.uniform2iv(r,s):t.uniform2fv(r,s);break;case 3:Number.isInteger(s[0])?t.uniform3iv(r,s):t.uniform3fv(r,s);break;case 4:Number.isInteger(s[0])?t.uniform4iv(r,s):t.uniform4fv(r,s);break;case 9:t.uniformMatrix3fv(r,!1,s);break;case 16:t.uniformMatrix4fv(r,!1,s);break;default:console.error(`Unsupported uniform array length for ${e}:`,s.length)}else"boolean"==typeof s?t.uniform1i(r,s?1:0):s.base?.texture?(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,s.base.texture),t.uniform1i(r,i),i+=1):console.error(`Unsupported uniform type for ${e}:`,typeof s);return i}}export{i as ArrayType,F as BaseTexture,o as Color,s as DynamicArrayBuffer,C as FrameBufferObject,R as GLShader,t as MaskType,l as MathUtils,a as MatrixStack,L as Rapid,N as SCALEFACTOR,r as ShaderType,I as Text,_ as Texture,U as TextureCache,D as TileMapRender,P as TileSet,e as TilemapShape,G as Uniform,u as Vec2,n as WebglBufferArray,h as WebglElementBufferArray,b as graphicAttributes,E as spriteAttributes};
1
+ var t,e,r,i,s;!function(t){t.STRETCH="stretch",t.REPEAT="repeat"}(t||(t={})),function(t){t.REPEAT="repeat",t.CLAMP="clamp",t.MIRROR="mirror"}(e||(e={})),function(t){t.Include="normal",t.Exclude="inverse"}(r||(r={})),function(t){t.SQUARE="square",t.ISOMETRIC="isometric"}(i||(i={})),function(t){t.SPRITE="sprite",t.GRAPHIC="graphic"}(s||(s={}));class n{constructor(t){this.render=t}}var a;!function(t){t[t.Float32=0]="Float32",t[t.Uint32=1]="Uint32",t[t.Uint16=2]="Uint16"}(a||(a={}));class h{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(t){switch(t){case a.Float32:return Float32Array;case a.Uint32:return Uint32Array;case a.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case a.Float32:this.typedArray=this.float32;break;case a.Uint32:this.typedArray=this.uint32;break;case a.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class o extends h{constructor(t,e,r=t.ARRAY_BUFFER,i=t.STATIC_DRAW){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r,this.usage=i}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),this.usage),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class u extends h{constructor(){super(a.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),n=r[e+0],a=r[e+1],h=r[e+2],o=r[e+3];r[e+0]=n*i-a*s,r[e+1]=n*s+a*i,r[e+2]=h*i-o*s,r[e+3]=h*s+o*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if("number"!=typeof t)return new d(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],n=e[t+3],a=e[t+4],h=e[t+5],o=r*n-i*s;return new Float32Array([n/o,-i/o,-s/o,r/o,(s*h-n*a)/o,(i*a-r*h)/o])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new d(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=t,i[r+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,r=this.typedArray,i=this.getGlobalScale(),s=Math.cos(t),n=Math.sin(t);r[e+0]=s*i.x,r[e+1]=n*i.x,r[e+2]=-n*i.y,r[e+3]=s*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,r=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new d(r,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const r=this.getGlobalRotation(),i=Math.cos(r),s=Math.sin(r),n=this.usedElemNum-6,a=this.typedArray;a[n+0]=i*t,a[n+1]=s*t,a[n+2]=-s*e,a[n+3]=i*e}globalToLocal(t){const e=this.getInverse();return new d(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,r=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,s=t.y||0;(i||s)&&this.translate(i,s),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let n=t.offsetX||0,a=t.offsetY||0;t.offset&&(n+=t.offset.x,a+=t.offset.y);const h=t.origin;return h&&("number"==typeof h?(n-=h*e,a-=h*r):(n-=h.x*e,a-=h.y*r)),{offsetX:n,offsetY:a}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class l extends o{constructor(t,e,r,i){super(t,a.Uint16,t.ELEMENT_ARRAY_BUFFER,t.STATIC_DRAW),this.setMaxSize(e*i);for(let t=0;t<i;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class c{constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new c(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new c(e,r,i,s)}add(t){return new c(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new c(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}c.Red=new c(255,0,0,255),c.Green=new c(0,255,0,255),c.Blue=new c(0,0,255,255),c.Yellow=new c(255,255,0,255),c.Purple=new c(128,0,128,255),c.Orange=new c(255,165,0,255),c.Pink=new c(255,192,203,255),c.Gray=new c(128,128,128,255),c.Brown=new c(139,69,19,255),c.Cyan=new c(0,255,255,255),c.Magenta=new c(255,0,255,255),c.Lime=new c(192,255,0,255),c.White=new c(255,255,255,255),c.Black=new c(0,0,0,255),c.TRANSPARENT=new c(0,0,0,0);class d{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}add(t){return new d(this.x+t.x,this.y+t.y)}subtract(t){return new d(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof d?new d(this.x*t.x,this.y*t.y):new d(this.x*t,this.y*t)}divide(t){return t instanceof d?new d(this.x/t.x,this.y/t.y):new d(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)}clone(){return new d(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new d((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new d(Math.abs(this.x),Math.abs(this.y))}floor(){return new d(Math.floor(this.x),Math.floor(this.y))}ceil(){return new d(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new d(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new d(t[0],t[1])))}}d.ZERO=new d(0,0),d.ONE=new d(1,1),d.UP=new d(0,1),d.DOWN=new d(0,-1),d.LEFT=new d(-1,0),d.RIGHT=new d(1,0);class f{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}}const p=(t,e,r,i)=>{const s=[],n=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),a=Math.PI;for(let e=0;e<10;e++){const i=n+e/10*a,h=n+(e+1)/10*a,o=Math.cos(i)*r,u=Math.sin(i)*r,l=Math.cos(h)*r,c=Math.sin(h)*r;s.push(t),s.push(t.add(new d(o,u))),s.push(t.add(new d(l,c)))}return s},g=e=>{const r=e.points;if(r.length<2)return{vertices:[],uv:[]};const{normals:i,length:s}=((t,e=!1)=>{const r=[];if(t.length<2||e&&t.length<3)return{normals:r,length:0};const i=t.length;let s=0;if(e)for(let e=0;e<i;e++){const r=t[e],n=t[(e+1)%i];s+=r.distanceTo(n)}else for(let e=0;e<i-1;e++)s+=t[e].distanceTo(t[e+1]);const n=(t,e,r)=>{const i=e.subtract(t).normalize(),s=e.subtract(r).normalize(),n=s.dot(i);if(n<-.999)return{normal:i.perpendicular(),miters:1};{let t=s.add(i).normalize();i.cross(s)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-n)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const s=0===e?t[i-2]:t[e-1],a=t[e],h=t[e+1];r.push(n(s,a,h))}r.push(r[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();r.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();r.push({normal:i.perpendicular(),miters:1})}else r.push(n(t[e-1],t[e],t[e+1]));return{normals:r,length:s}})(r,e.closed),n=(e.width||1)/2,a=[],h=[],o=e.roundCap||!1,u=e.textureMode||t.STRETCH;let l=0;const c=e.texture?.width||1;for(let e=0;e<r.length-1;e++){const o=r[e],f=i[e].normal,p=i[e].miters,g=o.add(f.multiply(p*n)),m=o.subtract(f.multiply(p*n)),x=r[e+1],y=i[e+1].normal,T=i[e+1].miters,E=x.add(y.multiply(T*n)),R=x.subtract(y.multiply(T*n)),b=o.distanceTo(x);let w=0,S=0;u===t.STRETCH?(w=l/s,S=(l+b)/s):(w=l/c,S=w+b/c);const A=new d(w,0),v=new d(w,1),M=new d(S,0),U=new d(S,1);a.push(g),h.push(A),a.push(m),h.push(v),a.push(E),h.push(M),a.push(E),h.push(M),a.push(R),h.push(U),a.push(m),h.push(v),l+=b}if(o&&!e.closed){const t=r[0],e=i[0].normal,s=p(t,e,n,!0);a.push(...s);const h=r[r.length-1],o=i[r.length-1].normal,u=p(h,o,n,!1);a.push(...u)}return{vertices:a,uv:h}};var m="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n gl_FragColor = color;\r\n}\r\n",x="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n \r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const y=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};function T(t,e,r,i=!1,s=!1,n="clamp"){const a=t.createTexture();if(!a)throw new Error("unable to create texture");let h;switch(t.bindTexture(t.TEXTURE_2D,a),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),n){case"repeat":h=t.REPEAT;break;case"mirror":h=t.MIRRORED_REPEAT;break;default:h=t.CLAMP_TO_EDGE}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,h),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,h),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,s),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),a}const E=5126;var R="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color * vColor;\r\n}",b="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}";const w=[{name:"aPosition",size:2,type:E,stride:24},{name:"aRegion",size:2,type:E,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:E,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],S=[{name:"aPosition",size:2,type:E,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:E,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class A{constructor(t,e,r,i,s=0){this.attributeLoc={},this.uniformLoc={},this.attributes=[];const n=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(r,t.maxTextureUnits-s);this.program=((t,e,r)=>{var i=t.createProgram(),s=y(t,e,35633),n=y(t,r,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,s),t.attachShader(i,n),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,n),this.gl=t.gl,this.usedTexture=s,this.parseShader(e),this.parseShader(n),i&&this.setAttributes(i)}setUniforms(t,e){const r=this.gl;for(const i of t.getUnifromNames()){const s=this.getUniform(i);e=t.bind(r,i,s,e)}return e}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(t,e,r,i,n=0){let a={[s.SPRITE]:R,[s.GRAPHIC]:m}[i],h={[s.SPRITE]:b,[s.GRAPHIC]:x}[i];const o={[s.SPRITE]:w,[s.GRAPHIC]:S}[i];return a=a.replace("void main(void) {",r+"\nvoid main(void) {"),h=h.replace("void main(void) {",e+"\nvoid main(void) {"),a=a.replace("gl_FragColor = ","fragment(color);\ngl_FragColor = "),h=h.replace("gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);","vec2 position = aPosition;\nvertex(position, vRegion);\ngl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new A(t,h,a,o,n)}}class v{constructor(t){this.usedTextures=[],this.needBind=new Set,this.shaders=new Map,this.isCostumShader=!1,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new o(t.gl,a.Float32,t.gl.ARRAY_BUFFER,t.gl.STREAM_DRAW),this.MAX_TEXTURE_UNIT_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}setTextureUnits(t){return this.MAX_TEXTURE_UNIT_ARRAY.slice(t,-1)}addVertex(t,e,...r){const[i,s]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}setCostumUnifrom(t){let e=!1;return this.costumUnifrom!=t?(e=!0,this.costumUnifrom=t):t?.isDirty&&(e=!0),t?.clearDirty(),e}exitRegion(){}initDefaultShader(t,e,r){this.setShader("default",t,e,r)}setShader(t,e,r,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new A(this.rapid,e,r,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e+this.currentShader.usedTexture),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[],this.isCostumShader=!1}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class M extends v{constructor(t){super(t),this.vertex=0,this.offset=d.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",x,m,S)}startRender(t,e,r,i){i&&this.currentShader?.setUniforms(i,1),this.offset=new d(t,e),this.vertex=0,this.webglArrayBuffer.clear(),r&&r.base&&(this.texture=this.useTexture(r.base.texture))}addVertex(t,e,r,i,s){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const U=Math.floor(16384);class F extends l{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class _ extends v{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.setShader("default",b,R,w),this.indexBuffer=new F(e,U)}addVertex(t,e,r,i,s,n){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushUint32(n)}renderSprite(t,e,r,i,s,n,a,h,o,u,l,c,d){(this.batchSprite>=U||this.rapid.projectionDirty||l&&this.setCostumUnifrom(l))&&(this.render(),l&&this.currentShader.setUniforms(l,0),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const f=this.useTexture(t),p=c?n:i,g=c?i:n,m=d?a:s,x=d?s:a,y=h,T=h+e,E=o,R=o+r;this.addVertex(y,E,p,m,f,u),this.addVertex(T,E,g,m,f,u),this.addVertex(T,R,g,x,f,u),this.addVertex(y,R,p,x,f,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.setTextureUnits(this.currentShader.usedTexture))}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}hasPendingContent(){return this.batchSprite>0}}class C{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,r=this.antialias,i=e.CLAMP){let s=this.cache.get(t);if(!s){const e=await this.loadImage(t);s=N.fromImageSource(this.render,e,r,i),this.cache.set(t,s)}return new I(s)}textureFromFrameBufferObject(t){return new I(t)}async textureFromSource(t,r=this.antialias,i=e.CLAMP){let s=this.cache.get(t);return s||(s=N.fromImageSource(this.render,t,r,i),this.cache.set(t,s)),new I(s)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new B(this.render,t)}destroy(t){t instanceof I?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,r=this.antialias){return new D(this.render,t,e,r)}removeCache(t){const e=t instanceof I?t.base?.texture:t.texture;e&&this.cache.forEach(((t,r)=>{t===e&&this.cache.delete(r)}))}}class N{constructor(t,r,i,s=e.CLAMP){this.texture=t,this.width=r,this.height=i,this.wrapMode=s}static fromImageSource(t,r,i=!1,s=e.CLAMP){return new N(T(t.gl,r,i,!1,!1,s),r.width,r.height)}destroy(t){t.deleteTexture(this.texture)}}class I{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,r=!1){return new I(N.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}createSpritesHeet(t,e){if(!this.base)return[];const r=[],i=Math.floor(this.base.width/t),s=Math.floor(this.base.height/e);for(let n=0;n<s;n++)for(let s=0;s<i;s++){const i=this.clone();i.setClipRegion(s*t,n*e,t,e),r.push(i)}return r}clone(){return new I(this.base)}}const P=2;class B extends I{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(N.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let n=0;for(const t of r)e.fillText(t,0,n),n+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class D extends N{constructor(t,e,r,i=!1){const s=t.gl,n=T(s,{width:e,height:r},i,!0,!1),a=s.createFramebuffer();if(!a)throw s.deleteTexture(n),new Error("Failed to create WebGL framebuffer");s.bindFramebuffer(s.FRAMEBUFFER,a),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,n,0);const h=s.createRenderbuffer();if(!h)throw s.deleteFramebuffer(a),s.deleteTexture(n),new Error("Failed to create depth-stencil renderbuffer");s.bindRenderbuffer(s.RENDERBUFFER,h),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,e,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,h),super(n,e,r),this.gl=s,this.framebuffer=a,s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}const L=new Set;class G{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof I&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class O{constructor(t){this.rapid=t}getYSortRow(t,e,r){if(!t)return[];const i=[];for(const r of t){const t=Math.floor(r.ySort/e);i[t]||(i[t]=[]),i[t].push(r)}return i}getOffset(t){let e=(t.errorX??2)+1,r=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,r=i}else t.error&&(e=t.error.x+1,r=t.error.y+1);return{errorX:e,errorY:r}}getTileData(t,e){const r=e.shape??i.SQUARE,s=t.width,n=r===i.ISOMETRIC?t.height/2:t.height,a=this.rapid.matrixStack,h=a.globalToLocal(d.ZERO),o=a.getGlobalScale(),{errorX:u,errorY:l}=this.getOffset(e),c=Math.ceil(this.rapid.width/s/o.x)+2*u,f=Math.ceil(this.rapid.height/n/o.y)+2*l,p=new d(h.x<0?Math.ceil(h.x/s):Math.floor(h.x/s),h.y<0?Math.ceil(h.y/n):Math.floor(h.y/n));p.x-=u,p.y-=l;let g=new d(0-h.x%s-u*s,0-h.y%n-l*n);return g=g.add(h),{startTile:p,offset:g,viewportWidth:c,viewportHeight:f,height:n,width:s,shape:r}}renderYSortRow(t,e){for(const r of e)r.render?r.render():r.renderSprite&&t.renderSprite(r.renderSprite)}renderLayer(t,e){this.rapid.matrixStack.applyTransform(e);const r=e.tileSet,{startTile:s,offset:n,viewportWidth:a,viewportHeight:h,shape:o,width:u,height:l}=this.getTileData(r,e),c=this.getYSortRow(e.ySortCallback,l,h),d=e.ySortCallback&&e.ySortCallback.length>0;var f;0!==this.rapid.matrixStack.getGlobalRotation()&&(f="TileMapRender: tilemap is not supported rotation",L.has(f)||(L.add(f),console.warn(f)),this.rapid.matrixStack.setGlobalRotation(0));for(let f=0;f<h;f++){const h=f+s.y,p=c[h]??[];if(h<0||h>=t.length)this.renderYSortRow(this.rapid,p);else{for(let c=0;c<a;c++){const a=c+s.x;if(a<0||a>=t[h].length)continue;const d=t[h][a],g=r.getTile(d);if(!g)continue;let m=c*u+n.x,x=f*l+n.y,y=f*l+n.y+(g.ySortOffset??0);h%2!=0&&o===i.ISOMETRIC&&(m+=u/2);const T=e.eachTile&&e.eachTile(d,a,h)||{};p.push({ySort:y,renderSprite:{...g,x:m+(g.x||0),y:x+(g.y||0),...T}})}d&&p.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,p)}}this.rapid.matrixStack.applyTransform(e)}localToMap(t,e){const r=e.tileSet;if(e.shape===i.ISOMETRIC){let e=0,i=0;const s=r.height/2,n=r.width/2;let a=Math.floor(t.y/s);const h=a%2==0;let o=Math.floor(t.x/n);const u=o%2==0,l=t.x%n/n,c=t.y%s/s,f=c<l,p=c<1-l;return h||(a-=1),f&&!u&&h?a-=1:f||!u||h?p&&u&&h?(o-=2,a-=1):p||u||h||(a+=1):(a+=1,o-=2),e=o,i=a,e=Math.floor(o/2),new d(e,i)}return new d(Math.floor(t.x/r.width),Math.floor(t.y/r.height))}mapToLocal(t,e){const r=e.tileSet;if(e.shape===i.ISOMETRIC){let e=new d(t.x*r.width,t.y*r.height/2);return t.y%2!=0&&(e.x+=r.width/2),e}return new d(t.x*r.width,t.y*r.height)}}class k{constructor(t){this.projectionDirty=!0,this.matrixStack=new u,this.tileMap=new O(this),this.light=new n(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new c(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[];const e=(t=>{const e={stencil:!0},r=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!r)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return r})(t.canvas);this.gl=e,this.canvas=t.canvas,this.textures=new C(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new c(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof G?{tileSet:e}:e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",_),this.registerRegion("graphic",M)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const r=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){this.startRender(),t(),this.endRender()}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:r,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,r,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,{vertices:r,uv:i}=g({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:r,uv:i})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,r)=>{const i=Array.isArray(t.color)?t.color[r]:t.color,s=t.uv?.[r];this.addGraphicVertex(e.x,e.y,s,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:r}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,r,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,r,i){this.currentRegion.addVertex(t,e,r?.x,r?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,r=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,r)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:r}=t,i=[new d(0,0),new d(e,0),new d(e,r),new d(0,r)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,r=t.radius,i=t.color||this.defaultColor,s=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,n=Math.cos(i)*r,a=Math.sin(i)*r;s.push(new d(n,a))}this.renderGraphic({...t,points:s,color:i,drawType:this.gl.TRIANGLE_FAN})}resize(t,e){const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.resizeWebglSize(t,e),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.width=t,this.height=e}resizeWebglSize(t,e,r){const i=t*(r||this.devicePixelRatio),s=e*(r||this.devicePixelRatio);this.gl.viewport(0,0,i,s),this.updateProjection(0,t,e,0),this.gl.scissor(0,0,i,s)}updateProjection(t,e,r,i){this.projection=this.createOrthMatrix(t,e,r,i),this.projectionDirty=!0}clear(t){const e=this.gl,r=t||this.backgroundColor;e.clearColor(r.r/255,r.g/255,r.b/255,r.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}drawMask(t=r.Include,e){this.startDrawMask(t),e(),this.endDrawMask()}startDrawMask(t=r.Include){const e=this.gl;this.currentMaskType.push(t),this.setMaskType(t,!0),e.stencilOp(e.KEEP,e.KEEP,e.REPLACE),e.colorMask(!1,!1,!1,!1)}endDrawMask(){const t=this.gl;this.quitCurrentRegion(),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??r.Include,!1)}setMaskType(t,e=!1){const i=this.gl;if(this.quitCurrentRegion(),e)this.clearMask(),i.stencilFunc(i.ALWAYS,1,255);else switch(t){case r.Include:i.stencilFunc(i.EQUAL,1,255);break;case r.Exclude:i.stencilFunc(i.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,r,i=0){return A.createCostumShader(this,t,e,r,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeWebglSize(t.width,t.height,1),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeWebglSize(this.width,this.height),this.updateProjection(0,this.width,this.height,0),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}}class z{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,r,i){const s=this.data[e];if("number"==typeof s)t.uniform1f(r,s);else if(Array.isArray(s))switch(s.length){case 1:Number.isInteger(s[0])?t.uniform1i(r,s[0]):t.uniform1f(r,s[0]);break;case 2:Number.isInteger(s[0])?t.uniform2iv(r,s):t.uniform2fv(r,s);break;case 3:Number.isInteger(s[0])?t.uniform3iv(r,s):t.uniform3fv(r,s);break;case 4:Number.isInteger(s[0])?t.uniform4iv(r,s):t.uniform4fv(r,s);break;case 9:t.uniformMatrix3fv(r,!1,s);break;case 16:t.uniformMatrix4fv(r,!1,s);break;default:console.error(`Unsupported uniform array length for ${e}:`,s.length)}else"boolean"==typeof s?t.uniform1i(r,s?1:0):s.base?.texture?(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,s.base.texture),t.uniform1i(r,i),i+=1):console.error(`Unsupported uniform type for ${e}:`,typeof s);return i}}export{a as ArrayType,N as BaseTexture,c as Color,h as DynamicArrayBuffer,D as FrameBufferObject,A as GLShader,t as LineTextureMode,r as MaskType,f as MathUtils,u as MatrixStack,k as Rapid,P as SCALEFACTOR,s as ShaderType,B as Text,I as Texture,C as TextureCache,e as TextureWrapMode,O as TileMapRender,G as TileSet,i as TilemapShape,z as Uniform,d as Vec2,o as WebglBufferArray,l as WebglElementBufferArray,S as graphicAttributes,w as spriteAttributes};
@@ -1 +1 @@
1
- "use strict";var t,e,r;exports.MaskType=void 0,(t=exports.MaskType||(exports.MaskType={})).Include="normal",t.Exclude="inverse",exports.TilemapShape=void 0,(e=exports.TilemapShape||(exports.TilemapShape={})).SQUARE="square",e.ISOMETRIC="isometric",exports.ShaderType=void 0,(r=exports.ShaderType||(exports.ShaderType={})).SPRITE="sprite",r.GRAPHIC="graphic";var i;exports.ArrayType=void 0,(i=exports.ArrayType||(exports.ArrayType={}))[i.Float32=0]="Float32",i[i.Uint32=1]="Uint32",i[i.Uint16=2]="Uint16";class s{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(t){switch(t){case exports.ArrayType.Float32:return Float32Array;case exports.ArrayType.Uint32:return Uint32Array;case exports.ArrayType.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case exports.ArrayType.Float32:this.typedArray=this.float32;break;case exports.ArrayType.Uint32:this.typedArray=this.uint32;break;case exports.ArrayType.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class a extends s{constructor(t,e,r=t.ARRAY_BUFFER){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),t.STATIC_DRAW),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class n extends s{constructor(){super(exports.ArrayType.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),a=r[e+0],n=r[e+1],o=r[e+2],h=r[e+3];r[e+0]=a*i-n*s,r[e+1]=a*s+n*i,r[e+2]=o*i-h*s,r[e+3]=o*s+h*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if("number"!=typeof t)return new u(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],a=e[t+3],n=e[t+4],o=e[t+5],h=r*a-i*s;return new Float32Array([a/h,-i/h,-s/h,r/h,(s*o-a*n)/h,(i*n-r*o)/h])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new u(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=t,i[r+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,r=this.typedArray,i=this.getGlobalScale(),s=Math.cos(t),a=Math.sin(t);r[e+0]=s*i.x,r[e+1]=a*i.x,r[e+2]=-a*i.y,r[e+3]=s*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,r=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new u(r,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const r=this.getGlobalRotation(),i=Math.cos(r),s=Math.sin(r),a=this.usedElemNum-6,n=this.typedArray;n[a+0]=i*t,n[a+1]=s*t,n[a+2]=-s*e,n[a+3]=i*e}globalToLocal(t){const e=this.getInverse();return new u(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,r=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,s=t.y||0;(i||s)&&this.translate(i,s),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let a=t.offsetX||0,n=t.offsetY||0;t.offset&&(a+=t.offset.x,n+=t.offset.y);const o=t.origin;return o&&("number"==typeof o?(a-=o*e,n-=o*r):(a-=o.x*e,n-=o.y*r)),{offsetX:a,offsetY:n}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class o extends a{constructor(t,e,r,i){super(t,exports.ArrayType.Uint16,t.ELEMENT_ARRAY_BUFFER),this.setMaxSize(e*i);for(let t=0;t<i;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class h{constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new h(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new h(e,r,i,s)}add(t){return new h(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new h(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}h.Red=new h(255,0,0,255),h.Green=new h(0,255,0,255),h.Blue=new h(0,0,255,255),h.Yellow=new h(255,255,0,255),h.Purple=new h(128,0,128,255),h.Orange=new h(255,165,0,255),h.Pink=new h(255,192,203,255),h.Gray=new h(128,128,128,255),h.Brown=new h(139,69,19,255),h.Cyan=new h(0,255,255,255),h.Magenta=new h(255,0,255,255),h.Lime=new h(192,255,0,255),h.White=new h(255,255,255,255),h.Black=new h(0,0,0,255),h.TRANSPARENT=new h(0,0,0,0);class u{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}add(t){return new u(this.x+t.x,this.y+t.y)}subtract(t){return new u(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof u?new u(this.x*t.x,this.y*t.y):new u(this.x*t,this.y*t)}divide(t){return t instanceof u?new u(this.x/t.x,this.y/t.y):new u(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)}clone(){return new u(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new u((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new u(Math.abs(this.x),Math.abs(this.y))}floor(){return new u(Math.floor(this.x),Math.floor(this.y))}ceil(){return new u(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new u(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new u(t[0],t[1])))}}u.ZERO=new u(0,0),u.ONE=new u(1,1),u.UP=new u(0,1),u.DOWN=new u(0,-1),u.LEFT=new u(-1,0),u.RIGHT=new u(1,0);const l=(t,e,r,i)=>{const s=[],a=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),n=Math.PI;for(let e=0;e<10;e++){const i=a+e/10*n,o=a+(e+1)/10*n,h=Math.cos(i)*r,l=Math.sin(i)*r,c=Math.cos(o)*r,d=Math.sin(o)*r;s.push(t),s.push(t.add(new u(h,l))),s.push(t.add(new u(c,d)))}return s},c=t=>{const e=t.points;if(e.length<2)return[];const r=((t,e=!1)=>{const r=[];if(t.length<2||e&&t.length<3)return r;const i=t.length,s=(t,e,r)=>{const i=e.subtract(t).normalize(),s=e.subtract(r).normalize(),a=s.dot(i);if(a<-.999)return{normal:i.perpendicular(),miters:1};{let t=s.add(i).normalize();i.cross(s)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-a)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const a=0===e?t[i-2]:t[e-1],n=t[e],o=t[e+1];r.push(s(a,n,o))}r.push(r[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();r.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();r.push({normal:i.perpendicular(),miters:1})}else r.push(s(t[e-1],t[e],t[e+1]));return r})(e,t.closed),i=(t.width||1)/2,s=[],a=t.roundCap||!1;for(let t=0;t<e.length-1;t++){const a=e[t],n=r[t].normal,o=r[t].miters,h=a.add(n.multiply(o*i)),u=a.subtract(n.multiply(o*i)),l=e[t+1],c=r[t+1].normal,d=r[t+1].miters,p=l.add(c.multiply(d*i)),f=l.subtract(c.multiply(d*i));s.push(h),s.push(u),s.push(p),s.push(p),s.push(f),s.push(u)}if(a&&!t.closed){const t=e[0],a=r[0].normal;s.push(...l(t,a,i,!0));const n=e[e.length-1],o=r[e.length-1].normal;s.push(...l(n,o,i,!1))}return s};var d="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n gl_FragColor = color;\r\n}\r\n",p="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n \r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const f=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};function x(t,e,r,i=!1,s=!1){const a=t.createTexture();if(!a)throw new Error("unable to create texture");return t.bindTexture(t.TEXTURE_2D,a),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,s),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),a}const g=5126;var m="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color * vColor;\r\n}",y="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}";const T=[{name:"aPosition",size:2,type:g,stride:24},{name:"aRegion",size:2,type:g,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:g,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],E=[{name:"aPosition",size:2,type:g,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:g,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class b{constructor(t,e,r,i,s=0){this.attributeLoc={},this.uniformLoc={},this.attributes=[];const a=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(r,t.maxTextureUnits-s);this.program=((t,e,r)=>{var i=t.createProgram(),s=f(t,e,35633),a=f(t,r,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,s),t.attachShader(i,a),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,a),this.gl=t.gl,this.usedTexture=s,this.parseShader(e),this.parseShader(a),i&&this.setAttributes(i)}setUniforms(t,e){const r=this.gl;for(const i of t.getUnifromNames()){const s=this.getUniform(i);e=t.bind(r,i,s,e)}return e}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(t,e,r,i,s=0){let a={[exports.ShaderType.SPRITE]:m,[exports.ShaderType.GRAPHIC]:d}[i],n={[exports.ShaderType.SPRITE]:y,[exports.ShaderType.GRAPHIC]:p}[i];const o={[exports.ShaderType.SPRITE]:T,[exports.ShaderType.GRAPHIC]:E}[i];return a=a.replace("void main(void) {",r+"\nvoid main(void) {"),n=n.replace("void main(void) {",e+"\nvoid main(void) {"),a=a.replace("gl_FragColor = ","fragment(color);\ngl_FragColor = "),n=n.replace("gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);","vec2 position = aPosition;\nvertex(position, vRegion);\ngl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new b(t,n,a,o,s)}}class R{constructor(t){this.usedTextures=[],this.needBind=new Set,this.shaders=new Map,this.isCostumShader=!1,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new a(t.gl,exports.ArrayType.Float32,t.gl.ARRAY_BUFFER),this.MAX_TEXTURE_UNIT_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}setTextureUnits(t){return this.MAX_TEXTURE_UNIT_ARRAY.slice(t,-1)}addVertex(t,e,...r){const[i,s]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}setCostumUnifrom(t){let e=!1;return this.costumUnifrom!=t?(e=!0,this.costumUnifrom=t):t?.isDirty&&(e=!0),t?.clearDirty(),e}exitRegion(){}initDefaultShader(t,e,r){this.setShader("default",t,e,r)}setShader(t,e,r,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new b(this.rapid,e,r,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e+this.currentShader.usedTexture),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[],this.isCostumShader=!1}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class w extends R{constructor(t){super(t),this.vertex=0,this.offset=u.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",p,d,E)}startRender(t,e,r,i){i&&this.currentShader?.setUniforms(i,1),this.offset=new u(t,e),this.vertex=0,this.webglArrayBuffer.clear(),r&&r.base&&(this.texture=this.useTexture(r.base.texture))}addVertex(t,e,r,i,s){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const S=Math.floor(16384);class A extends o{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class v extends R{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.setShader("default",y,m,T),this.indexBuffer=new A(e,S)}addVertex(t,e,r,i,s,a){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushUint32(a)}renderSprite(t,e,r,i,s,a,n,o,h,u,l,c,d){(this.batchSprite>=S||this.rapid.projectionDirty||l&&this.setCostumUnifrom(l))&&(this.render(),l&&this.currentShader.setUniforms(l,0),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const p=this.useTexture(t),f=c?a:i,x=c?i:a,g=d?n:s,m=d?s:n,y=o,T=o+e,E=h,b=h+r;this.addVertex(y,E,f,g,p,u),this.addVertex(T,E,x,g,p,u),this.addVertex(T,b,x,m,p,u),this.addVertex(y,b,f,m,p,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.setTextureUnits(this.currentShader.usedTexture))}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}hasPendingContent(){return this.batchSprite>0}}class M{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,e=this.antialias){let r=this.cache.get(t);if(!r){const i=await this.loadImage(t);r=U.fromImageSource(this.render,i,e),this.cache.set(t,r)}return new F(r)}textureFromFrameBufferObject(t){return new F(t)}async textureFromSource(t,e=this.antialias){let r=this.cache.get(t);return r||(r=U.fromImageSource(this.render,t,e),this.cache.set(t,r)),new F(r)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new _(this.render,t)}destroy(t){t instanceof F?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,r=this.antialias){return new N(this.render,t,e,r)}removeCache(t){const e=t instanceof F?t.base?.texture:t.texture;e&&this.cache.forEach(((t,r)=>{t===e&&this.cache.delete(r)}))}}class U{constructor(t,e,r){this.texture=t,this.width=e,this.height=r}static fromImageSource(t,e,r=!1){return new U(x(t.gl,e,r),e.width,e.height)}destroy(t){t.deleteTexture(this.texture)}}class F{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,r=!1){return new F(U.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}createSpritesHeet(t,e){if(!this.base)return[];const r=[],i=Math.floor(this.base.width/t),s=Math.floor(this.base.height/e);for(let a=0;a<s;a++)for(let s=0;s<i;s++){const i=this.clone();i.setClipRegion(s*t,a*e,t,e),r.push(i)}return r}clone(){return new F(this.base)}}class _ extends F{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(U.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let a=0;for(const t of r)e.fillText(t,0,a),a+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class N extends U{constructor(t,e,r,i=!1){const s=t.gl,a=x(s,{width:e,height:r},i,!0,!1),n=s.createFramebuffer();if(!n)throw s.deleteTexture(a),new Error("Failed to create WebGL framebuffer");s.bindFramebuffer(s.FRAMEBUFFER,n),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a,0);const o=s.createRenderbuffer();if(!o)throw s.deleteFramebuffer(n),s.deleteTexture(a),new Error("Failed to create depth-stencil renderbuffer");s.bindRenderbuffer(s.RENDERBUFFER,o),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,e,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,o),super(a,e,r),this.gl=s,this.framebuffer=n,s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}const B=new Set;class C{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof F&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class I{constructor(t){this.rapid=t}getYSortRow(t,e,r){if(!t)return[];const i=[];for(const r of t){const t=Math.floor(r.ySort/e);i[t]||(i[t]=[]),i[t].push(r)}return i}getOffset(t){let e=(t.errorX??2)+1,r=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,r=i}else t.error&&(e=t.error.x+1,r=t.error.y+1);return{errorX:e,errorY:r}}getTileData(t,e){const r=e.shape??exports.TilemapShape.SQUARE,i=t.width,s=r===exports.TilemapShape.ISOMETRIC?t.height/2:t.height,a=this.rapid.matrixStack,n=a.globalToLocal(u.ZERO),o=a.getGlobalScale(),{errorX:h,errorY:l}=this.getOffset(e),c=Math.ceil(this.rapid.width/i/o.x)+2*h,d=Math.ceil(this.rapid.height/s/o.y)+2*l,p=new u(n.x<0?Math.ceil(n.x/i):Math.floor(n.x/i),n.y<0?Math.ceil(n.y/s):Math.floor(n.y/s));p.x-=h,p.y-=l;let f=new u(0-n.x%i-h*i,0-n.y%s-l*s);return f=f.add(n),{startTile:p,offset:f,viewportWidth:c,viewportHeight:d,height:s,width:i,shape:r}}renderYSortRow(t,e){for(const r of e)r.render?r.render():r.renderSprite&&t.renderSprite(r.renderSprite)}renderLayer(t,e){this.rapid.matrixStack.applyTransform(e);const r=e.tileSet,{startTile:i,offset:s,viewportWidth:a,viewportHeight:n,shape:o,width:h,height:u}=this.getTileData(r,e),l=this.getYSortRow(e.ySortCallback,u,n),c=e.ySortCallback&&e.ySortCallback.length>0;var d;0!==this.rapid.matrixStack.getGlobalRotation()&&(d="TileMapRender: tilemap is not supported rotation",B.has(d)||(B.add(d),console.warn(d)),this.rapid.matrixStack.setGlobalRotation(0));for(let d=0;d<n;d++){const n=d+i.y,p=l[n]??[];if(n<0||n>=t.length)this.renderYSortRow(this.rapid,p);else{for(let l=0;l<a;l++){const a=l+i.x;if(a<0||a>=t[n].length)continue;const c=t[n][a],f=r.getTile(c);if(!f)continue;let x=l*h+s.x,g=d*u+s.y,m=d*u+s.y+(f.ySortOffset??0);n%2!=0&&o===exports.TilemapShape.ISOMETRIC&&(x+=h/2);const y=e.eachTile&&e.eachTile(c,a,n)||{};p.push({ySort:m,renderSprite:{...f,x:x+(f.x||0),y:g+(f.y||0),...y}})}c&&p.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,p)}}this.rapid.matrixStack.applyTransform(e)}localToMap(t,e){const r=e.tileSet;if(e.shape===exports.TilemapShape.ISOMETRIC){let e=0,i=0;const s=r.height/2,a=r.width/2;let n=Math.floor(t.y/s);const o=n%2==0;let h=Math.floor(t.x/a);const l=h%2==0,c=t.x%a/a,d=t.y%s/s,p=d<c,f=d<1-c;return o||(n-=1),p&&!l&&o?n-=1:p||!l||o?f&&l&&o?(h-=2,n-=1):f||l||o||(n+=1):(n+=1,h-=2),e=h,i=n,e=Math.floor(h/2),new u(e,i)}return new u(Math.floor(t.x/r.width),Math.floor(t.y/r.height))}mapToLocal(t,e){const r=e.tileSet;if(e.shape===exports.TilemapShape.ISOMETRIC){let e=new u(t.x*r.width,t.y*r.height/2);return t.y%2!=0&&(e.x+=r.width/2),e}return new u(t.x*r.width,t.y*r.height)}}exports.BaseTexture=U,exports.Color=h,exports.DynamicArrayBuffer=s,exports.FrameBufferObject=N,exports.GLShader=b,exports.MathUtils=class{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}},exports.MatrixStack=n,exports.Rapid=class{constructor(t){this.projectionDirty=!0,this.matrixStack=new n,this.tileMap=new I(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new h(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[];const e=(t=>{const e={stencil:!0},r=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!r)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return r})(t.canvas);this.gl=e,this.canvas=t.canvas,this.textures=new M(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new h(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof C?{tileSet:e}:e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",v),this.registerRegion("graphic",w)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const r=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){this.startRender(),t(),this.endRender()}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:r,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,r,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,r=c({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:r})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,r)=>{const i=Array.isArray(t.color)?t.color[r]:t.color,s=t.uv?.[r];this.addGraphicVertex(e.x,e.y,s,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:r}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,r,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,r,i){this.currentRegion.addVertex(t,e,r?.x,r?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,r=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,r)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:r}=t,i=[new u(0,0),new u(e,0),new u(e,r),new u(0,r)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,r=t.radius,i=t.color||this.defaultColor,s=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,a=Math.cos(i)*r,n=Math.sin(i)*r;s.push(new u(a,n))}this.renderGraphic({...t,points:s,color:i,drawType:this.gl.TRIANGLE_FAN})}resize(t,e){const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.resizeWebglSize(t,e),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.width=t,this.height=e}resizeWebglSize(t,e,r){const i=t*(r||this.devicePixelRatio),s=e*(r||this.devicePixelRatio);this.gl.viewport(0,0,i,s),this.updateProjection(0,t,e,0),this.gl.scissor(0,0,i,s)}updateProjection(t,e,r,i){this.projection=this.createOrthMatrix(t,e,r,i),this.projectionDirty=!0}clear(t){const e=this.gl,r=t||this.backgroundColor;e.clearColor(r.r/255,r.g/255,r.b/255,r.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}drawMask(t=exports.MaskType.Include,e){this.startDrawMask(t),e(),this.endDrawMask()}startDrawMask(t=exports.MaskType.Include){const e=this.gl;this.currentMaskType.push(t),this.setMaskType(t,!0),e.stencilOp(e.KEEP,e.KEEP,e.REPLACE),e.colorMask(!1,!1,!1,!1)}endDrawMask(){const t=this.gl;this.quitCurrentRegion(),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??exports.MaskType.Include,!1)}setMaskType(t,e=!1){const r=this.gl;if(this.quitCurrentRegion(),e)this.clearMask(),r.stencilFunc(r.ALWAYS,1,255);else switch(t){case exports.MaskType.Include:r.stencilFunc(r.EQUAL,1,255);break;case exports.MaskType.Exclude:r.stencilFunc(r.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,r,i=0){return b.createCostumShader(this,t,e,r,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeWebglSize(t.width,t.height,1),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeWebglSize(this.width,this.height),this.updateProjection(0,this.width,this.height,0),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}},exports.SCALEFACTOR=2,exports.Text=_,exports.Texture=F,exports.TextureCache=M,exports.TileMapRender=I,exports.TileSet=C,exports.Uniform=class{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,r,i){const s=this.data[e];if("number"==typeof s)t.uniform1f(r,s);else if(Array.isArray(s))switch(s.length){case 1:Number.isInteger(s[0])?t.uniform1i(r,s[0]):t.uniform1f(r,s[0]);break;case 2:Number.isInteger(s[0])?t.uniform2iv(r,s):t.uniform2fv(r,s);break;case 3:Number.isInteger(s[0])?t.uniform3iv(r,s):t.uniform3fv(r,s);break;case 4:Number.isInteger(s[0])?t.uniform4iv(r,s):t.uniform4fv(r,s);break;case 9:t.uniformMatrix3fv(r,!1,s);break;case 16:t.uniformMatrix4fv(r,!1,s);break;default:console.error(`Unsupported uniform array length for ${e}:`,s.length)}else"boolean"==typeof s?t.uniform1i(r,s?1:0):s.base?.texture?(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,s.base.texture),t.uniform1i(r,i),i+=1):console.error(`Unsupported uniform type for ${e}:`,typeof s);return i}},exports.Vec2=u,exports.WebglBufferArray=a,exports.WebglElementBufferArray=o,exports.graphicAttributes=E,exports.spriteAttributes=T;
1
+ "use strict";var t,e,r,i,s;exports.LineTextureMode=void 0,(t=exports.LineTextureMode||(exports.LineTextureMode={})).STRETCH="stretch",t.REPEAT="repeat",exports.TextureWrapMode=void 0,(e=exports.TextureWrapMode||(exports.TextureWrapMode={})).REPEAT="repeat",e.CLAMP="clamp",e.MIRROR="mirror",exports.MaskType=void 0,(r=exports.MaskType||(exports.MaskType={})).Include="normal",r.Exclude="inverse",exports.TilemapShape=void 0,(i=exports.TilemapShape||(exports.TilemapShape={})).SQUARE="square",i.ISOMETRIC="isometric",exports.ShaderType=void 0,(s=exports.ShaderType||(exports.ShaderType={})).SPRITE="sprite",s.GRAPHIC="graphic";class a{constructor(t){this.render=t}}var n;exports.ArrayType=void 0,(n=exports.ArrayType||(exports.ArrayType={}))[n.Float32=0]="Float32",n[n.Uint32=1]="Uint32",n[n.Uint16=2]="Uint16";class o{constructor(t){this.usedElemNum=0,this.maxElemNum=512,this.bytePerElem=this.getArrayType(t).BYTES_PER_ELEMENT,this.arrayType=t,this.arraybuffer=new ArrayBuffer(this.maxElemNum*this.bytePerElem),this.updateTypedArray()}getArrayType(t){switch(t){case exports.ArrayType.Float32:return Float32Array;case exports.ArrayType.Uint32:return Uint32Array;case exports.ArrayType.Uint16:return Uint16Array}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case exports.ArrayType.Float32:this.typedArray=this.float32;break;case exports.ArrayType.Uint32:this.typedArray=this.uint32;break;case exports.ArrayType.Uint16:this.typedArray=this.uint16}}clear(){this.usedElemNum=0}resize(t=0){if((t+=this.usedElemNum)>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum<<=1;this.setMaxSize(this.maxElemNum)}}setMaxSize(t=this.maxElemNum){const e=this.typedArray;this.maxElemNum=t,this.arraybuffer=new ArrayBuffer(t*this.bytePerElem),this.updateTypedArray(),this.typedArray.set(e)}pushUint32(t){this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.float32[this.usedElemNum++]=t}pushUint16(t){this.uint16[this.usedElemNum++]=t}pop(t){this.usedElemNum-=t}getArray(t=0,e){return null==e?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.typedArray.length}}class h extends o{constructor(t,e,r=t.ARRAY_BUFFER,i=t.STATIC_DRAW){super(e),this.dirty=!0,this.webglBufferSize=0,this.gl=t,this.buffer=t.createBuffer(),this.type=r,this.usage=i}pushFloat32(t){super.pushFloat32(t),this.dirty=!0}pushUint32(t){super.pushUint32(t),this.dirty=!0}pushUint16(t){super.pushUint16(t),this.dirty=!0}bindBuffer(){this.gl.bindBuffer(this.type,this.buffer)}bufferData(){if(this.dirty){const t=this.gl;this.maxElemNum>this.webglBufferSize?(t.bufferData(this.type,this.getArray(),this.usage),this.webglBufferSize=this.maxElemNum):t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}class u extends o{constructor(){super(exports.ArrayType.Float32)}pushMat(){const t=this.usedElemNum-6,e=this.typedArray;this.resize(6),this.pushFloat32(e[t+0]),this.pushFloat32(e[t+1]),this.pushFloat32(e[t+2]),this.pushFloat32(e[t+3]),this.pushFloat32(e[t+4]),this.pushFloat32(e[t+5])}popMat(){this.pop(6)}pushIdentity(){this.resize(6),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0),this.pushFloat32(1),this.pushFloat32(0),this.pushFloat32(0)}translate(t,e){if("number"!=typeof t)return this.translate(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=i[r+0]*t+i[r+2]*e+i[r+4],i[r+5]=i[r+1]*t+i[r+3]*e+i[r+5]}rotate(t){const e=this.usedElemNum-6,r=this.typedArray,i=Math.cos(t),s=Math.sin(t),a=r[e+0],n=r[e+1],o=r[e+2],h=r[e+3];r[e+0]=a*i-n*s,r[e+1]=a*s+n*i,r[e+2]=o*i-h*s,r[e+3]=o*s+h*i}scale(t,e){if("number"!=typeof t)return this.scale(t.x,t.y);e||(e=t);const r=this.usedElemNum-6,i=this.typedArray;i[r+0]=i[r+0]*t,i[r+1]=i[r+1]*t,i[r+2]=i[r+2]*e,i[r+3]=i[r+3]*e}apply(t,e){if("number"!=typeof t)return new d(...this.apply(t.x,t.y));const r=this.usedElemNum-6,i=this.typedArray;return[i[r+0]*t+i[r+2]*e+i[r+4],i[r+1]*t+i[r+3]*e+i[r+5]]}getInverse(){const t=this.usedElemNum-6,e=this.typedArray,r=e[t+0],i=e[t+1],s=e[t+2],a=e[t+3],n=e[t+4],o=e[t+5],h=r*a-i*s;return new Float32Array([a/h,-i/h,-s/h,r/h,(s*o-a*n)/h,(i*n-r*o)/h])}getTransform(){const t=this.usedElemNum-6,e=this.typedArray;return new Float32Array([e[t+0],e[t+1],e[t+2],e[t+3],e[t+4],e[t+5]])}setTransform(t){const e=this.usedElemNum-6,r=this.typedArray;r[e+0]=t[0],r[e+1]=t[1],r[e+2]=t[2],r[e+3]=t[3],r[e+4]=t[4],r[e+5]=t[5]}getGlobalPosition(){const t=this.usedElemNum-6,e=this.typedArray;return new d(e[t+4],e[t+5])}setGlobalPosition(t,e){if("number"!=typeof t)return void this.setGlobalPosition(t.x,t.y);const r=this.usedElemNum-6,i=this.typedArray;i[r+4]=t,i[r+5]=e}getGlobalRotation(){const t=this.usedElemNum-6,e=this.typedArray;return Math.atan2(e[t+1],e[t+0])}setGlobalRotation(t){const e=this.usedElemNum-6,r=this.typedArray,i=this.getGlobalScale(),s=Math.cos(t),a=Math.sin(t);r[e+0]=s*i.x,r[e+1]=a*i.x,r[e+2]=-a*i.y,r[e+3]=s*i.y}getGlobalScale(){const t=this.usedElemNum-6,e=this.typedArray,r=Math.sqrt(e[t+0]*e[t+0]+e[t+1]*e[t+1]),i=Math.sqrt(e[t+2]*e[t+2]+e[t+3]*e[t+3]);return new d(r,i)}setGlobalScale(t,e){if("number"!=typeof t)return void this.setGlobalScale(t.x,t.y);const r=this.getGlobalRotation(),i=Math.cos(r),s=Math.sin(r),a=this.usedElemNum-6,n=this.typedArray;n[a+0]=i*t,n[a+1]=s*t,n[a+2]=-s*e,n[a+3]=i*e}globalToLocal(t){const e=this.getInverse();return new d(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])}localToGlobal(t){return this.apply(t)}toCSSTransform(){const t=this.usedElemNum-6,e=this.typedArray;return`matrix(${e[t+0]}, ${e[t+1]}, ${e[t+2]}, ${e[t+3]}, ${e[t+4]}, ${e[t+5]})`}identity(){const t=this.usedElemNum-6,e=this.typedArray;e[t+0]=1,e[t+1]=0,e[t+2]=0,e[t+3]=1,e[t+4]=0,e[t+5]=0}applyTransform(t,e=0,r=0){(t.saveTransform??1)&&this.pushMat(),t.afterSave&&t.afterSave();const i=t.x||0,s=t.y||0;(i||s)&&this.translate(i,s),t.position&&this.translate(t.position),t.rotation&&this.rotate(t.rotation),t.scale&&this.scale(t.scale);let a=t.offsetX||0,n=t.offsetY||0;t.offset&&(a+=t.offset.x,n+=t.offset.y);const o=t.origin;return o&&("number"==typeof o?(a-=o*e,n-=o*r):(a-=o.x*e,n-=o.y*r)),{offsetX:a,offsetY:n}}applyTransformAfter(t){t.beforRestore&&t.beforRestore(),(t.restoreTransform??1)&&this.popMat()}}class l extends h{constructor(t,e,r,i){super(t,exports.ArrayType.Uint16,t.ELEMENT_ARRAY_BUFFER,t.STATIC_DRAW),this.setMaxSize(e*i);for(let t=0;t<i;t++)this.addObject(t*r);this.bindBuffer(),this.bufferData()}addObject(t){}}class c{constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}get r(){return this._r}set r(t){this._r=t,this.updateUint()}get g(){return this._g}set g(t){this._g=t,this.updateUint()}get b(){return this._b}set b(t){this._b=t,this.updateUint()}get a(){return this._a}set a(t){this._a=t,this.updateUint()}updateUint(){this.uint32=(this._a<<24|this._b<<16|this._g<<8|this._r)>>>0}setRGBA(t,e,r,i){this.r=t,this.g=e,this.b=r,this.a=i,this.updateUint()}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new c(this._r,this._g,this._b,this._a)}equal(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static fromHex(t){t.startsWith("#")&&(t=t.slice(1));const e=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16);let s=255;return t.length>=8&&(s=parseInt(t.slice(6,8),16)),new c(e,r,i,s)}add(t){return new c(Math.min(this.r+t.r,255),Math.min(this.g+t.g,255),Math.min(this.b+t.b,255),Math.min(this.a+t.a,255))}subtract(t){return new c(Math.max(this.r-t.r,0),Math.max(this.g-t.g,0),Math.max(this.b-t.b,0),Math.max(this.a-t.a,0))}}c.Red=new c(255,0,0,255),c.Green=new c(0,255,0,255),c.Blue=new c(0,0,255,255),c.Yellow=new c(255,255,0,255),c.Purple=new c(128,0,128,255),c.Orange=new c(255,165,0,255),c.Pink=new c(255,192,203,255),c.Gray=new c(128,128,128,255),c.Brown=new c(139,69,19,255),c.Cyan=new c(0,255,255,255),c.Magenta=new c(255,0,255,255),c.Lime=new c(192,255,0,255),c.White=new c(255,255,255,255),c.Black=new c(0,0,0,255),c.TRANSPARENT=new c(0,0,0,0);class d{constructor(t,e){this.x=void 0!==t?t:0,this.y=void 0!==e?e:0}add(t){return new d(this.x+t.x,this.y+t.y)}subtract(t){return new d(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof d?new d(this.x*t.x,this.y*t.y):new d(this.x*t,this.y*t)}divide(t){return t instanceof d?new d(this.x/t.x,this.y/t.y):new d(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}distanceTo(t){const e=this.x-t.x,r=this.y-t.y;return Math.sqrt(e*e+r*r)}clone(){return new d(this.x,this.y)}copy(t){this.x=t.x,this.y=t.y}equal(t){return t.x==this.x&&t.y==this.y}perpendicular(){const t=this.x;return this.x=-this.y,this.y=t,this}invert(){return this.x=-this.x,this.y=-this.y,this}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}normalize(){const t=this.length();return this.x=this.x/t||0,this.y=this.y/t||0,this}angle(){return Math.atan2(this.y,this.x)}middle(t){return new d((this.x+t.x)/2,(this.y+t.y)/2)}abs(){return new d(Math.abs(this.x),Math.abs(this.y))}floor(){return new d(Math.floor(this.x),Math.floor(this.y))}ceil(){return new d(Math.ceil(this.x),Math.ceil(this.y))}snap(t){return new d(Math.round(this.x/t)*t,Math.round(this.y/t)*t)}stringify(){return`Vec2(${this.x}, ${this.y})`}static FromArray(t){return t.map((t=>new d(t[0],t[1])))}}d.ZERO=new d(0,0),d.ONE=new d(1,1),d.UP=new d(0,1),d.DOWN=new d(0,-1),d.LEFT=new d(-1,0),d.RIGHT=new d(1,0);const p=(t,e,r,i)=>{const s=[],a=i?Math.atan2(e.y,e.x):Math.atan2(-e.y,-e.x),n=Math.PI;for(let e=0;e<10;e++){const i=a+e/10*n,o=a+(e+1)/10*n,h=Math.cos(i)*r,u=Math.sin(i)*r,l=Math.cos(o)*r,c=Math.sin(o)*r;s.push(t),s.push(t.add(new d(h,u))),s.push(t.add(new d(l,c)))}return s},f=t=>{const e=t.points;if(e.length<2)return{vertices:[],uv:[]};const{normals:r,length:i}=((t,e=!1)=>{const r=[];if(t.length<2||e&&t.length<3)return{normals:r,length:0};const i=t.length;let s=0;if(e)for(let e=0;e<i;e++){const r=t[e],a=t[(e+1)%i];s+=r.distanceTo(a)}else for(let e=0;e<i-1;e++)s+=t[e].distanceTo(t[e+1]);const a=(t,e,r)=>{const i=e.subtract(t).normalize(),s=e.subtract(r).normalize(),a=s.dot(i);if(a<-.999)return{normal:i.perpendicular(),miters:1};{let t=s.add(i).normalize();i.cross(s)<0&&(t=t.multiply(-1));let e=1/Math.sqrt((1-a)/2);return{normal:t,miters:Math.min(e,4)}}};if(e){for(let e=0;e<i-1;e++){const s=0===e?t[i-2]:t[e-1],n=t[e],o=t[e+1];r.push(a(s,n,o))}r.push(r[0])}else for(let e=0;e<i;e++)if(0===e){const e=t[1].subtract(t[0]).normalize();r.push({normal:e.perpendicular(),miters:1})}else if(e===i-1){const i=t[e].subtract(t[e-1]).normalize();r.push({normal:i.perpendicular(),miters:1})}else r.push(a(t[e-1],t[e],t[e+1]));return{normals:r,length:s}})(e,t.closed),s=(t.width||1)/2,a=[],n=[],o=t.roundCap||!1,h=t.textureMode||exports.LineTextureMode.STRETCH;let u=0;const l=t.texture?.width||1;for(let t=0;t<e.length-1;t++){const o=e[t],c=r[t].normal,p=r[t].miters,f=o.add(c.multiply(p*s)),x=o.subtract(c.multiply(p*s)),g=e[t+1],m=r[t+1].normal,y=r[t+1].miters,T=g.add(m.multiply(y*s)),E=g.subtract(m.multiply(y*s)),R=o.distanceTo(g);let b=0,w=0;h===exports.LineTextureMode.STRETCH?(b=u/i,w=(u+R)/i):(b=u/l,w=b+R/l);const S=new d(b,0),A=new d(b,1),M=new d(w,0),v=new d(w,1);a.push(f),n.push(S),a.push(x),n.push(A),a.push(T),n.push(M),a.push(T),n.push(M),a.push(E),n.push(v),a.push(x),n.push(A),u+=R}if(o&&!t.closed){const t=e[0],i=r[0].normal,n=p(t,i,s,!0);a.push(...n);const o=e[e.length-1],h=r[e.length-1].normal,u=p(o,h,s,!1);a.push(...u)}return{vertices:a,uv:n}};var x="precision mediump float;\r\nvarying vec2 vRegion;\r\nvarying vec4 vColor;\r\n\r\nuniform sampler2D uTexture;\r\nuniform int uUseTexture;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n if(uUseTexture > 0){\r\n color = texture2D(uTexture, vRegion) * vColor;\r\n }else{\r\n color = vColor;\r\n }\r\n gl_FragColor = color;\r\n}\r\n",g="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec4 aColor;\r\nattribute vec2 aRegion;\r\n\r\nvarying vec4 vColor;\r\nuniform mat4 uProjectionMatrix;\r\nuniform vec4 uColor;\r\nvarying vec2 vRegion;\r\n\r\nvoid main(void) {\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n \r\n vColor = aColor;\r\n vRegion = aRegion;\r\n}\r\n";const m=(t,e,r)=>{const i=t.createShader(r);if(!i)throw new Error("Unable to create webgl shader");t.shaderSource(i,e),t.compileShader(i);if(!t.getShaderParameter(i,t.COMPILE_STATUS)){const r=t.getShaderInfoLog(i);throw console.error("Shader compilation failed:",r),new Error("Unable to compile shader: "+r+e)}return i};function y(t,e,r,i=!1,s=!1,a="clamp"){const n=t.createTexture();if(!n)throw new Error("unable to create texture");let o;switch(t.bindTexture(t.TEXTURE_2D,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,r?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,r?t.LINEAR:t.NEAREST),a){case"repeat":o=t.REPEAT;break;case"mirror":o=t.MIRRORED_REPEAT;break;default:o=t.CLAMP_TO_EDGE}return t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,o),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,s),i?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.width,e.height,0,t.RGBA,t.UNSIGNED_BYTE,null):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),n}const T=5126;var E="precision mediump float;\r\nuniform sampler2D uTextures[%TEXTURE_NUM%];\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vec4 color;\r\n %GET_COLOR%\r\n\r\n gl_FragColor = color * vColor;\r\n}",R="precision mediump float;\r\n\r\nattribute vec2 aPosition;\r\nattribute vec2 aRegion;\r\nattribute float aTextureId;\r\nattribute vec4 aColor;\r\n\r\nuniform mat4 uProjectionMatrix;\r\n\r\nvarying vec2 vRegion;\r\nvarying float vTextureId;\r\nvarying vec4 vColor;\r\n\r\nvoid main(void) {\r\n vRegion = aRegion;\r\n vTextureId = aTextureId;\r\n vColor = aColor;\r\n\r\n gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);\r\n}";const b=[{name:"aPosition",size:2,type:T,stride:24},{name:"aRegion",size:2,type:T,stride:24,offset:2*Float32Array.BYTES_PER_ELEMENT},{name:"aTextureId",size:1,type:T,stride:24,offset:4*Float32Array.BYTES_PER_ELEMENT},{name:"aColor",size:4,type:5121,stride:24,offset:5*Float32Array.BYTES_PER_ELEMENT,normalized:!0}],w=[{name:"aPosition",size:2,type:T,stride:20},{name:"aColor",size:4,type:5121,stride:20,offset:2*Float32Array.BYTES_PER_ELEMENT,normalized:!0},{name:"aRegion",size:2,type:T,stride:20,offset:3*Float32Array.BYTES_PER_ELEMENT}];class S{constructor(t,e,r,i,s=0){this.attributeLoc={},this.uniformLoc={},this.attributes=[];const a=function(t,e){if(t.includes("%TEXTURE_NUM%")&&(t=t.replace("%TEXTURE_NUM%",e.toString())),t.includes("%GET_COLOR%")){let r="";for(let t=0;t<e;t++)r+=0==t?`if(vTextureId == ${t}.0)`:t==e-1?"else":`else if(vTextureId == ${t}.0)`,r+=`{color = texture2D(uTextures[${t}], vRegion);}`;t=t.replace("%GET_COLOR%",r)}return t}(r,t.maxTextureUnits-s);this.program=((t,e,r)=>{var i=t.createProgram(),s=m(t,e,35633),a=m(t,r,35632);if(!i)throw new Error("Unable to create program shader");if(t.attachShader(i,s),t.attachShader(i,a),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=t.getProgramInfoLog(i);throw new Error("Unable to link shader program: "+e)}return i})(t.gl,e,a),this.gl=t.gl,this.usedTexture=s,this.parseShader(e),this.parseShader(a),i&&this.setAttributes(i)}setUniforms(t,e){const r=this.gl;for(const i of t.getUnifromNames()){const s=this.getUniform(i);e=t.bind(r,i,s,e)}return e}getUniform(t){return this.uniformLoc[t]}use(){this.gl.useProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/attribute\s+\w+\s+(\w+)/g);if(r)for(const t of r){const r=t.split(" ")[2],i=e.getAttribLocation(this.program,r);-1!=i&&(this.attributeLoc[r]=i)}const i=t.match(/uniform\s+\w+\s+(\w+)/g);if(i)for(const t of i){const r=t.split(" ")[2];this.uniformLoc[r]=e.getUniformLocation(this.program,r)}}setAttribute(t){const e=this.attributeLoc[t.name];if(void 0!==e){const r=this.gl;r.vertexAttribPointer(e,t.size,t.type,t.normalized||!1,t.stride,t.offset||0),r.enableVertexAttribArray(e)}}setAttributes(t){this.attributes=t;for(const e of t)this.setAttribute(e)}updateAttributes(){this.setAttributes(this.attributes)}static createCostumShader(t,e,r,i,s=0){let a={[exports.ShaderType.SPRITE]:E,[exports.ShaderType.GRAPHIC]:x}[i],n={[exports.ShaderType.SPRITE]:R,[exports.ShaderType.GRAPHIC]:g}[i];const o={[exports.ShaderType.SPRITE]:b,[exports.ShaderType.GRAPHIC]:w}[i];return a=a.replace("void main(void) {",r+"\nvoid main(void) {"),n=n.replace("void main(void) {",e+"\nvoid main(void) {"),a=a.replace("gl_FragColor = ","fragment(color);\ngl_FragColor = "),n=n.replace("gl_Position = uProjectionMatrix * vec4(aPosition, 0.0, 1.0);","vec2 position = aPosition;\nvertex(position, vRegion);\ngl_Position = uProjectionMatrix * vec4(position, 0.0, 1.0);"),new S(t,n,a,o,s)}}class A{constructor(t){this.usedTextures=[],this.needBind=new Set,this.shaders=new Map,this.isCostumShader=!1,this.rapid=t,this.gl=t.gl,this.webglArrayBuffer=new h(t.gl,exports.ArrayType.Float32,t.gl.ARRAY_BUFFER,t.gl.STREAM_DRAW),this.MAX_TEXTURE_UNIT_ARRAY=Array.from({length:t.maxTextureUnits},((t,e)=>e))}setTextureUnits(t){return this.MAX_TEXTURE_UNIT_ARRAY.slice(t,-1)}addVertex(t,e,...r){const[i,s]=this.rapid.matrixStack.apply(t,e);this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s)}useTexture(t){let e=this.usedTextures.indexOf(t);return-1===e&&(this.usedTextures.length>=this.rapid.maxTextureUnits&&this.render(),this.usedTextures.push(t),e=this.usedTextures.length-1,this.needBind.add(e)),e}enterRegion(t){this.currentShader=t??this.getShader("default"),this.currentShader.use(),this.initializeForNextRender(),this.webglArrayBuffer.bindBuffer(),this.currentShader.updateAttributes(),this.updateProjection(),this.isCostumShader=Boolean(t)}updateProjection(){this.gl.uniformMatrix4fv(this.currentShader.uniformLoc.uProjectionMatrix,!1,this.rapid.projection)}setCostumUnifrom(t){let e=!1;return this.costumUnifrom!=t?(e=!0,this.costumUnifrom=t):t?.isDirty&&(e=!0),t?.clearDirty(),e}exitRegion(){}initDefaultShader(t,e,r){this.setShader("default",t,e,r)}setShader(t,e,r,i){this.webglArrayBuffer.bindBuffer(),this.shaders.set(t,new S(this.rapid,e,r,i)),"default"===t&&(this.defaultShader=this.shaders.get(t))}getShader(t){return this.shaders.get(t)}render(){this.executeRender(),this.initializeForNextRender()}executeRender(){this.webglArrayBuffer.bufferData();const t=this.gl;for(const e of this.needBind)t.activeTexture(t.TEXTURE0+e+this.currentShader.usedTexture),t.bindTexture(t.TEXTURE_2D,this.usedTextures[e]);this.needBind.clear()}initializeForNextRender(){this.webglArrayBuffer.clear(),this.usedTextures=[],this.isCostumShader=!1}hasPendingContent(){return!1}isShaderChanged(t){return(t||this.defaultShader)!=this.currentShader}}class M extends A{constructor(t){super(t),this.vertex=0,this.offset=d.ZERO,this.drawType=t.gl.TRIANGLE_FAN,this.setShader("default",g,x,w)}startRender(t,e,r,i){i&&this.currentShader?.setUniforms(i,1),this.offset=new d(t,e),this.vertex=0,this.webglArrayBuffer.clear(),r&&r.base&&(this.texture=this.useTexture(r.base.texture))}addVertex(t,e,r,i,s){this.webglArrayBuffer.resize(3),super.addVertex(t+this.offset.x,e+this.offset.y),this.webglArrayBuffer.pushUint32(s),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.vertex+=1}executeRender(){super.executeRender();const t=this.gl;t.uniform1i(this.currentShader.uniformLoc.uUseTexture,void 0===this.texture?0:1),this.texture&&t.uniform1i(this.currentShader.uniformLoc.uTexture,this.texture),t.drawArrays(this.drawType,0,this.vertex),this.drawType=this.rapid.gl.TRIANGLE_FAN,this.vertex=0,this.texture=void 0}}const v=Math.floor(16384);class U extends l{constructor(t,e){super(t,6,4,e)}addObject(t){super.addObject(),this.pushUint16(t),this.pushUint16(t+1),this.pushUint16(t+2),this.pushUint16(t),this.pushUint16(t+3),this.pushUint16(t+2)}}class F extends A{constructor(t){const e=t.gl;super(t),this.batchSprite=0,this.setShader("default",R,E,b),this.indexBuffer=new U(e,v)}addVertex(t,e,r,i,s,a){super.addVertex(t,e),this.webglArrayBuffer.pushFloat32(r),this.webglArrayBuffer.pushFloat32(i),this.webglArrayBuffer.pushFloat32(s),this.webglArrayBuffer.pushUint32(a)}renderSprite(t,e,r,i,s,a,n,o,h,u,l,c,d){(this.batchSprite>=v||this.rapid.projectionDirty||l&&this.setCostumUnifrom(l))&&(this.render(),l&&this.currentShader.setUniforms(l,0),this.rapid.projectionDirty&&this.updateProjection()),this.batchSprite++,this.webglArrayBuffer.resize(20);const p=this.useTexture(t),f=c?a:i,x=c?i:a,g=d?n:s,m=d?s:n,y=o,T=o+e,E=h,R=h+r;this.addVertex(y,E,f,g,p,u),this.addVertex(T,E,x,g,p,u),this.addVertex(T,R,x,m,p,u),this.addVertex(y,R,f,m,p,u)}executeRender(){super.executeRender();const t=this.gl;t.drawElements(t.TRIANGLES,6*this.batchSprite,t.UNSIGNED_SHORT,0)}enterRegion(t){super.enterRegion(t),this.indexBuffer.bindBuffer(),this.gl.uniform1iv(this.currentShader.uniformLoc.uTextures,this.setTextureUnits(this.currentShader.usedTexture))}initializeForNextRender(){super.initializeForNextRender(),this.batchSprite=0}hasPendingContent(){return this.batchSprite>0}}class _{constructor(t,e){this.cache=new Map,this.render=t,this.antialias=e}async textureFromUrl(t,e=this.antialias,r=exports.TextureWrapMode.CLAMP){let i=this.cache.get(t);if(!i){const s=await this.loadImage(t);i=C.fromImageSource(this.render,s,e,r),this.cache.set(t,i)}return new N(i)}textureFromFrameBufferObject(t){return new N(t)}async textureFromSource(t,e=this.antialias,r=exports.TextureWrapMode.CLAMP){let i=this.cache.get(t);return i||(i=C.fromImageSource(this.render,t,e,r),this.cache.set(t,i)),new N(i)}async loadImage(t){return new Promise((e=>{const r=new Image;r.onload=()=>{e(r)},r.src=t}))}createText(t){return new I(this.render,t)}destroy(t){t instanceof N?(t.base?.destroy(this.render.gl),this.removeCache(t)):(t.destroy(this.render.gl),this.removeCache(t))}createFrameBufferObject(t,e,r=this.antialias){return new B(this.render,t,e,r)}removeCache(t){const e=t instanceof N?t.base?.texture:t.texture;e&&this.cache.forEach(((t,r)=>{t===e&&this.cache.delete(r)}))}}class C{constructor(t,e,r,i=exports.TextureWrapMode.CLAMP){this.texture=t,this.width=e,this.height=r,this.wrapMode=i}static fromImageSource(t,e,r=!1,i=exports.TextureWrapMode.CLAMP){return new C(y(t.gl,e,r,!1,!1,i),e.width,e.height)}destroy(t){t.deleteTexture(this.texture)}}class N{constructor(t){this.scale=1,this.setBaseTextur(t)}setBaseTextur(t){t&&(this.base=t,this.setClipRegion(0,0,t.width,t.height))}setClipRegion(t,e,r,i){if(this.base)return this.clipX=t/this.base.width,this.clipY=e/this.base.height,this.clipW=this.clipX+r/this.base.width,this.clipH=this.clipY+i/this.base.height,this.width=r*this.scale,this.height=i*this.scale,this}static fromImageSource(t,e,r=!1){return new N(C.fromImageSource(t,e,r))}static fromUrl(t,e){return t.textures.textureFromUrl(e)}createSpritesHeet(t,e){if(!this.base)return[];const r=[],i=Math.floor(this.base.width/t),s=Math.floor(this.base.height/e);for(let a=0;a<s;a++)for(let s=0;s<i;s++){const i=this.clone();i.setClipRegion(s*t,a*e,t,e),r.push(i)}return r}clone(){return new N(this.base)}}class I extends N{constructor(t,e){super(),this.scale=.5,this.rapid=t,this.options=e,this.text=e.text||" ",this.updateTextImage()}updateTextImage(){const t=this.createTextCanvas();this.setBaseTextur(C.fromImageSource(this.rapid,t,!0))}createTextCanvas(){const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";const r=this.text.split("\n");let i=0,s=0;for(const t of r){const r=e.measureText(t);i=Math.max(i,r.width),s+=this.options.fontSize||16}t.width=2*i,t.height=2*s,e.scale(2,2),e.font=`${this.options.fontSize||16}px ${this.options.fontFamily||"Arial"}`,e.fillStyle=this.options.color||"#000",e.textAlign=this.options.textAlign||"left",e.textBaseline=this.options.textBaseline||"top";let a=0;for(const t of r)e.fillText(t,0,a),a+=this.options.fontSize||16;return t}setText(t){this.text!=t&&(this.text=t,this.updateTextImage())}}class B extends C{constructor(t,e,r,i=!1){const s=t.gl,a=y(s,{width:e,height:r},i,!0,!1),n=s.createFramebuffer();if(!n)throw s.deleteTexture(a),new Error("Failed to create WebGL framebuffer");s.bindFramebuffer(s.FRAMEBUFFER,n),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,a,0);const o=s.createRenderbuffer();if(!o)throw s.deleteFramebuffer(n),s.deleteTexture(a),new Error("Failed to create depth-stencil renderbuffer");s.bindRenderbuffer(s.RENDERBUFFER,o),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,e,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,o),super(a,e,r),this.gl=s,this.framebuffer=n,s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null)}bind(){const t=this.gl;t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer),t.clearColor(.5,.2,.5,.5),t.clear(t.COLOR_BUFFER_BIT)}unbind(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}resize(t,e){this.width=t,this.height=e,this.gl.bindTexture(this.gl.TEXTURE_2D,this.texture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,e,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}destroy(t){t.deleteFramebuffer(this.framebuffer),super.destroy(t)}}const P=new Set;class L{constructor(t,e){this.textures=new Map,this.width=t,this.height=e}setTile(t,e){e instanceof N&&(e={texture:e}),this.textures.set(t,e)}getTile(t){return this.textures.get(t)}}class D{constructor(t){this.rapid=t}getYSortRow(t,e,r){if(!t)return[];const i=[];for(const r of t){const t=Math.floor(r.ySort/e);i[t]||(i[t]=[]),i[t].push(r)}return i}getOffset(t){let e=(t.errorX??2)+1,r=(t.errorY??2)+1;if("number"==typeof t.error){const i=(t.error??2)+1;e=i,r=i}else t.error&&(e=t.error.x+1,r=t.error.y+1);return{errorX:e,errorY:r}}getTileData(t,e){const r=e.shape??exports.TilemapShape.SQUARE,i=t.width,s=r===exports.TilemapShape.ISOMETRIC?t.height/2:t.height,a=this.rapid.matrixStack,n=a.globalToLocal(d.ZERO),o=a.getGlobalScale(),{errorX:h,errorY:u}=this.getOffset(e),l=Math.ceil(this.rapid.width/i/o.x)+2*h,c=Math.ceil(this.rapid.height/s/o.y)+2*u,p=new d(n.x<0?Math.ceil(n.x/i):Math.floor(n.x/i),n.y<0?Math.ceil(n.y/s):Math.floor(n.y/s));p.x-=h,p.y-=u;let f=new d(0-n.x%i-h*i,0-n.y%s-u*s);return f=f.add(n),{startTile:p,offset:f,viewportWidth:l,viewportHeight:c,height:s,width:i,shape:r}}renderYSortRow(t,e){for(const r of e)r.render?r.render():r.renderSprite&&t.renderSprite(r.renderSprite)}renderLayer(t,e){this.rapid.matrixStack.applyTransform(e);const r=e.tileSet,{startTile:i,offset:s,viewportWidth:a,viewportHeight:n,shape:o,width:h,height:u}=this.getTileData(r,e),l=this.getYSortRow(e.ySortCallback,u,n),c=e.ySortCallback&&e.ySortCallback.length>0;var d;0!==this.rapid.matrixStack.getGlobalRotation()&&(d="TileMapRender: tilemap is not supported rotation",P.has(d)||(P.add(d),console.warn(d)),this.rapid.matrixStack.setGlobalRotation(0));for(let d=0;d<n;d++){const n=d+i.y,p=l[n]??[];if(n<0||n>=t.length)this.renderYSortRow(this.rapid,p);else{for(let l=0;l<a;l++){const a=l+i.x;if(a<0||a>=t[n].length)continue;const c=t[n][a],f=r.getTile(c);if(!f)continue;let x=l*h+s.x,g=d*u+s.y,m=d*u+s.y+(f.ySortOffset??0);n%2!=0&&o===exports.TilemapShape.ISOMETRIC&&(x+=h/2);const y=e.eachTile&&e.eachTile(c,a,n)||{};p.push({ySort:m,renderSprite:{...f,x:x+(f.x||0),y:g+(f.y||0),...y}})}c&&p.sort(((t,e)=>t.ySort-e.ySort)),this.renderYSortRow(this.rapid,p)}}this.rapid.matrixStack.applyTransform(e)}localToMap(t,e){const r=e.tileSet;if(e.shape===exports.TilemapShape.ISOMETRIC){let e=0,i=0;const s=r.height/2,a=r.width/2;let n=Math.floor(t.y/s);const o=n%2==0;let h=Math.floor(t.x/a);const u=h%2==0,l=t.x%a/a,c=t.y%s/s,p=c<l,f=c<1-l;return o||(n-=1),p&&!u&&o?n-=1:p||!u||o?f&&u&&o?(h-=2,n-=1):f||u||o||(n+=1):(n+=1,h-=2),e=h,i=n,e=Math.floor(h/2),new d(e,i)}return new d(Math.floor(t.x/r.width),Math.floor(t.y/r.height))}mapToLocal(t,e){const r=e.tileSet;if(e.shape===exports.TilemapShape.ISOMETRIC){let e=new d(t.x*r.width,t.y*r.height/2);return t.y%2!=0&&(e.x+=r.width/2),e}return new d(t.x*r.width,t.y*r.height)}}exports.BaseTexture=C,exports.Color=c,exports.DynamicArrayBuffer=o,exports.FrameBufferObject=B,exports.GLShader=S,exports.MathUtils=class{static deg2rad(t){return t*(Math.PI/180)}static rad2deg(t){return t/(Math.PI/180)}static normalizeDegrees(t){return(t%360+360)%360}},exports.MatrixStack=u,exports.Rapid=class{constructor(t){this.projectionDirty=!0,this.matrixStack=new u,this.tileMap=new D(this),this.light=new a(this),this.devicePixelRatio=window.devicePixelRatio||1,this.defaultColor=new c(255,255,255,255),this.regions=new Map,this.currentMaskType=[],this.currentTransform=[],this.currentFBO=[];const e=(t=>{const e={stencil:!0},r=t.getContext("webgl2",e)||t.getContext("webgl",e);if(!r)throw new Error("Unable to initialize WebGL. Your browser may not support it.");return r})(t.canvas);this.gl=e,this.canvas=t.canvas,this.textures=new _(this,t.antialias??!1),this.maxTextureUnits=e.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.width=t.width||this.canvas.width,this.height=t.width||this.canvas.height,this.backgroundColor=t.backgroundColor||new c(255,255,255,255),this.registerBuildInRegion(),this.initWebgl(e)}renderTileMapLayer(t,e){this.tileMap.renderLayer(t,e instanceof L?{tileSet:e}:e)}initWebgl(t){this.resize(this.width,this.height),t.enable(t.BLEND),t.disable(t.DEPTH_TEST),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.enable(t.STENCIL_TEST),t.enable(t.SCISSOR_TEST)}clearTextureUnit(){for(let t=0;t<this.maxTextureUnits;t++)this.gl.activeTexture(this.gl.TEXTURE0+t),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}registerBuildInRegion(){this.registerRegion("sprite",F),this.registerRegion("graphic",M)}registerRegion(t,e){this.regions.set(t,new e(this))}quitCurrentRegion(){this.currentRegion&&this.currentRegion.hasPendingContent()&&(this.currentRegion.render(),this.currentRegion.exitRegion())}setRegion(t,e){if(t!=this.currentRegionName||this.currentRegion&&this.currentRegion.isShaderChanged(e)){const r=this.regions.get(t);this.quitCurrentRegion(),this.currentRegion=r,this.currentRegionName=t,r.enterRegion(e)}}save(){this.matrixStack.pushMat()}restore(){this.matrixStack.popMat()}withTransform(t){this.save(),t(),this.restore()}startRender(t=!0){this.clear(),t&&this.matrixStack.clear(),this.matrixStack.pushIdentity(),this.currentRegion=void 0,this.currentRegionName=void 0}endRender(){this.currentRegion?.render(),this.projectionDirty=!1}render(t){this.startRender(),t(),this.endRender()}renderSprite(t){const e=t.texture;if(!e||!e.base)return;const{offsetX:r,offsetY:i}=this.startDraw(t,e.width,e.height);this.setRegion("sprite",t.shader),this.currentRegion.renderSprite(e.base.texture,e.width,e.height,e.clipX,e.clipY,e.clipW,e.clipH,r,i,(t.color||this.defaultColor).uint32,t.uniforms,t.flipX,t.flipY),this.afterDraw()}renderTexture(t){t.base&&this.renderSprite({texture:t})}renderLine(t){const e=t.closed?[...t.points,t.points[0]]:t.points,{vertices:r,uv:i}=f({...t,points:e});this.renderGraphic({...t,drawType:this.gl.TRIANGLES,points:r,uv:i})}renderGraphic(t){this.startGraphicDraw(t),t.points.forEach(((e,r)=>{const i=Array.isArray(t.color)?t.color[r]:t.color,s=t.uv?.[r];this.addGraphicVertex(e.x,e.y,s,i)})),this.endGraphicDraw()}startGraphicDraw(t){const{offsetX:e,offsetY:r}=this.startDraw(t);this.setRegion("graphic",t.shader);const i=this.currentRegion;i.startRender(e,r,t.texture,t.uniforms),t.drawType&&(i.drawType=t.drawType)}addGraphicVertex(t,e,r,i){this.currentRegion.addVertex(t,e,r?.x,r?.y,(i||this.defaultColor).uint32)}endGraphicDraw(){this.currentRegion.render(),this.afterDraw()}startDraw(t,e=0,r=0){return this.currentTransform.push(t),this.matrixStack.applyTransform(t,e,r)}afterDraw(){this.currentTransform.length>0&&this.matrixStack.applyTransformAfter(this.currentTransform.pop())}renderRect(t){const{width:e,height:r}=t,i=[new d(0,0),new d(e,0),new d(e,r),new d(0,r)];this.renderGraphic({...t,points:i,drawType:this.gl.TRIANGLE_FAN})}renderCircle(t){const e=t.segments||32,r=t.radius,i=t.color||this.defaultColor,s=[];for(let t=0;t<=e;t++){const i=t/e*Math.PI*2,a=Math.cos(i)*r,n=Math.sin(i)*r;s.push(new d(a,n))}this.renderGraphic({...t,points:s,color:i,drawType:this.gl.TRIANGLE_FAN})}resize(t,e){const r=t*this.devicePixelRatio,i=e*this.devicePixelRatio;this.canvas.width=r,this.canvas.height=i,this.resizeWebglSize(t,e),this.canvas.style.width=t+"px",this.canvas.style.height=e+"px",this.width=t,this.height=e}resizeWebglSize(t,e,r){const i=t*(r||this.devicePixelRatio),s=e*(r||this.devicePixelRatio);this.gl.viewport(0,0,i,s),this.updateProjection(0,t,e,0),this.gl.scissor(0,0,i,s)}updateProjection(t,e,r,i){this.projection=this.createOrthMatrix(t,e,r,i),this.projectionDirty=!0}clear(t){const e=this.gl,r=t||this.backgroundColor;e.clearColor(r.r/255,r.g/255,r.b/255,r.a/255),e.clear(e.COLOR_BUFFER_BIT),this.clearMask()}createOrthMatrix(t,e,r,i){return new Float32Array([2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,-1,0,-(e+t)/(e-t),-(i+r)/(i-r),0,1])}drawMask(t=exports.MaskType.Include,e){this.startDrawMask(t),e(),this.endDrawMask()}startDrawMask(t=exports.MaskType.Include){const e=this.gl;this.currentMaskType.push(t),this.setMaskType(t,!0),e.stencilOp(e.KEEP,e.KEEP,e.REPLACE),e.colorMask(!1,!1,!1,!1)}endDrawMask(){const t=this.gl;this.quitCurrentRegion(),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),t.colorMask(!0,!0,!0,!0),this.setMaskType(this.currentMaskType.pop()??exports.MaskType.Include,!1)}setMaskType(t,e=!1){const r=this.gl;if(this.quitCurrentRegion(),e)this.clearMask(),r.stencilFunc(r.ALWAYS,1,255);else switch(t){case exports.MaskType.Include:r.stencilFunc(r.EQUAL,1,255);break;case exports.MaskType.Exclude:r.stencilFunc(r.NOTEQUAL,1,255)}}clearMask(){const t=this.gl;this.quitCurrentRegion(),t.clearStencil(0),t.clear(t.STENCIL_BUFFER_BIT),t.stencilFunc(t.ALWAYS,1,255)}createCostumShader(t,e,r,i=0){return S.createCostumShader(this,t,e,r,i)}startFBO(t){this.quitCurrentRegion(),t.bind(),this.clearTextureUnit(),this.resizeWebglSize(t.width,t.height,1),this.updateProjection(0,t.width,0,t.height),this.save(),this.matrixStack.identity(),this.currentFBO.push(t)}endFBO(){if(this.currentFBO.length>0){const t=this.currentFBO.pop();this.quitCurrentRegion(),t.unbind(),this.clearTextureUnit(),this.resizeWebglSize(this.width,this.height),this.updateProjection(0,this.width,this.height,0),this.restore()}}drawToFBO(t,e){this.startFBO(t),e(),this.endFBO()}},exports.SCALEFACTOR=2,exports.Text=I,exports.Texture=N,exports.TextureCache=_,exports.TileMapRender=D,exports.TileSet=L,exports.Uniform=class{constructor(t){this.isDirty=!1,this.data=t}setUniform(t,e){this.data[t]!=e&&(this.isDirty=!0),this.data[t]=e}clearDirty(){this.isDirty=!1}getUnifromNames(){return Object.keys(this.data)}bind(t,e,r,i){const s=this.data[e];if("number"==typeof s)t.uniform1f(r,s);else if(Array.isArray(s))switch(s.length){case 1:Number.isInteger(s[0])?t.uniform1i(r,s[0]):t.uniform1f(r,s[0]);break;case 2:Number.isInteger(s[0])?t.uniform2iv(r,s):t.uniform2fv(r,s);break;case 3:Number.isInteger(s[0])?t.uniform3iv(r,s):t.uniform3fv(r,s);break;case 4:Number.isInteger(s[0])?t.uniform4iv(r,s):t.uniform4fv(r,s);break;case 9:t.uniformMatrix3fv(r,!1,s);break;case 16:t.uniformMatrix4fv(r,!1,s);break;default:console.error(`Unsupported uniform array length for ${e}:`,s.length)}else"boolean"==typeof s?t.uniform1i(r,s?1:0):s.base?.texture?(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,s.base.texture),t.uniform1i(r,i),i+=1):console.error(`Unsupported uniform type for ${e}:`,typeof s);return i}},exports.Vec2=d,exports.WebglBufferArray=h,exports.WebglElementBufferArray=l,exports.graphicAttributes=w,exports.spriteAttributes=b;
@@ -5,7 +5,6 @@ import GLShader from "../webgl/glshader";
5
5
  import { Uniform } from "../webgl/uniform";
6
6
  declare class RenderRegion {
7
7
  currentShader?: GLShader;
8
- private currentShaderName;
9
8
  protected webglArrayBuffer: WebglBufferArray;
10
9
  protected rapid: Rapid;
11
10
  protected gl: WebGLContext;
package/dist/render.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { ICircleOptions, IGraphicOptions, ILayerRender, IRapidOptions, IRectOptions, IRenderLineOptions, IRenderSpriteOptions, ShaderType as ShaderType, MaskType, WebGLContext } from "./interface";
1
+ import { ICircleRenderOptions, IGraphicRenderOptions, ILayerRenderOptions, IRapidOptions, IRectRenderOptions, IRenderLineOptions, ISpriteRenderOptions, ShaderType as ShaderType, MaskType, WebGLContext } from "./interface";
2
+ import { LightManager } from "./light";
2
3
  import { Color, MatrixStack, Vec2 } from "./math";
3
4
  import RenderRegion from "./regions/region";
4
5
  import { FrameBufferObject, Texture, TextureCache } from "./texture";
@@ -14,9 +15,10 @@ declare class Rapid {
14
15
  projectionDirty: boolean;
15
16
  matrixStack: MatrixStack;
16
17
  textures: TextureCache;
18
+ tileMap: TileMapRender;
19
+ light: LightManager;
17
20
  width: number;
18
21
  height: number;
19
- tileMap: TileMapRender;
20
22
  backgroundColor: Color;
21
23
  readonly devicePixelRatio: number;
22
24
  readonly maxTextureUnits: number;
@@ -37,7 +39,7 @@ declare class Rapid {
37
39
  * @param data - The map data to render.
38
40
  * @param options - The options for rendering the tile map layer.
39
41
  */
40
- renderTileMapLayer(data: (number | string)[][], options: ILayerRender | TileSet): void;
42
+ renderTileMapLayer(data: (number | string)[][], options: ILayerRenderOptions | TileSet): void;
41
43
  /**
42
44
  * Initializes WebGL context settings.
43
45
  * @param gl - The WebGL context.
@@ -97,7 +99,7 @@ declare class Rapid {
97
99
  *
98
100
  * @param options - The rendering options for the sprite, including texture, position, color, and shader.
99
101
  */
100
- renderSprite(options: IRenderSpriteOptions): void;
102
+ renderSprite(options: ISpriteRenderOptions): void;
101
103
  /**
102
104
  * Renders a texture directly without additional options.
103
105
  * This is a convenience method that calls renderSprite with just the texture.
@@ -116,13 +118,13 @@ declare class Rapid {
116
118
  *
117
119
  * @param options - The options for rendering the graphic, including points, color, texture, and draw type.
118
120
  */
119
- renderGraphic(options: IGraphicOptions): void;
121
+ renderGraphic(options: IGraphicRenderOptions): void;
120
122
  /**
121
123
  * Starts the graphic drawing process.
122
124
  *
123
125
  * @param options - The options for the graphic drawing, including shader, texture, and draw type.
124
126
  */
125
- startGraphicDraw(options: IGraphicOptions): void;
127
+ startGraphicDraw(options: IGraphicRenderOptions): void;
126
128
  /**
127
129
  * Adds a vertex to the current graphic being drawn.
128
130
  *
@@ -143,13 +145,13 @@ declare class Rapid {
143
145
  *
144
146
  * @param options - The options for rendering the rectangle, including width, height, position, and color.
145
147
  */
146
- renderRect(options: IRectOptions): void;
148
+ renderRect(options: IRectRenderOptions): void;
147
149
  /**
148
150
  * Renders a circle with the specified options.
149
151
  *
150
152
  * @param options - The options for rendering the circle, including radius, position, color, and segment count.
151
153
  */
152
- renderCircle(options: ICircleOptions): void;
154
+ renderCircle(options: ICircleRenderOptions): void;
153
155
  /**
154
156
  * Resizes the canvas and updates the viewport and projection matrix.
155
157
  * @param width - The new width of the canvas.
package/dist/texture.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import Rapid from "./render";
2
- import { Images, ITextOptions, WebGLContext } from "./interface";
2
+ import { Images, ITextTextureOptions, TextureWrapMode, WebGLContext } from "./interface";
3
3
  /**
4
4
  * texture manager
5
5
  * @ignore
@@ -16,7 +16,7 @@ declare class TextureCache {
16
16
  * @param antialias
17
17
  * @returns
18
18
  */
19
- textureFromUrl(url: string, antialias?: boolean): Promise<Texture>;
19
+ textureFromUrl(url: string, antialias?: boolean, wrapMode?: TextureWrapMode): Promise<Texture>;
20
20
  /**
21
21
  * Create a new `Texture` instance from a FrameBufferObject.
22
22
  * @param fbo - The FrameBufferObject to create the texture from.
@@ -29,7 +29,7 @@ declare class TextureCache {
29
29
  * @param antialias - Whether to enable antialiasing.
30
30
  * @returns A new `Texture` instance created from the specified image source.
31
31
  */
32
- textureFromSource(source: Images, antialias?: boolean): Promise<Texture>;
32
+ textureFromSource(source: Images, antialias?: boolean, wrapMode?: TextureWrapMode): Promise<Texture>;
33
33
  /**
34
34
  * Load an image from the specified URL.
35
35
  * @param url - The URL of the image to load.
@@ -41,7 +41,7 @@ declare class TextureCache {
41
41
  * @param options - The options for rendering the text, such as font, size, color, etc.
42
42
  * @returns A new `Text` instance.
43
43
  */
44
- createText(options: ITextOptions): Text;
44
+ createText(options: ITextTextureOptions): Text;
45
45
  /**
46
46
  * Destroy the texture
47
47
  * @param texture
@@ -64,8 +64,9 @@ declare class BaseTexture {
64
64
  texture: WebGLTexture;
65
65
  width: number;
66
66
  height: number;
67
- constructor(texture: WebGLTexture, width: number, height: number);
68
- static fromImageSource(r: Rapid, image: Images, antialias?: boolean): BaseTexture;
67
+ wrapMode: TextureWrapMode;
68
+ constructor(texture: WebGLTexture, width: number, height: number, wrapMode?: TextureWrapMode);
69
+ static fromImageSource(r: Rapid, image: Images, antialias?: boolean, wrapMode?: TextureWrapMode): BaseTexture;
69
70
  /**
70
71
  * Destroy the texture
71
72
  * @param gl
@@ -167,7 +168,7 @@ declare class Text extends Texture {
167
168
  * Creates a new `Text` instance.
168
169
  * @param options - The options for rendering the text, such as font, size, color, etc.
169
170
  */
170
- constructor(rapid: Rapid, options: ITextOptions);
171
+ constructor(rapid: Rapid, options: ITextTextureOptions);
171
172
  private updateTextImage;
172
173
  /**
173
174
  * Creates a canvas element for rendering text.
package/dist/tilemap.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import Rapid from "./render";
2
- import { IRegisterTileOptions, ILayerRender } from "./interface";
2
+ import { IRegisterTileOptions, ILayerRenderOptions } from "./interface";
3
3
  import { Texture } from "./texture";
4
4
  import { Vec2 } from "./math";
5
5
  /**
@@ -79,19 +79,19 @@ export declare class TileMapRender {
79
79
  * @param options - The rendering options for the tilemap layer.
80
80
  * @returns
81
81
  */
82
- renderLayer(data: (number | string)[][], options: ILayerRender): void;
82
+ renderLayer(data: (number | string)[][], options: ILayerRenderOptions): void;
83
83
  /**
84
84
  * Converts local coordinates to map coordinates.
85
85
  * @param local - The local coordinates.
86
86
  * @param options - The rendering options.
87
87
  * @returns The map coordinates.
88
88
  */
89
- localToMap(local: Vec2, options: ILayerRender): Vec2;
89
+ localToMap(local: Vec2, options: ILayerRenderOptions): Vec2;
90
90
  /**
91
91
  * Converts map coordinates to local coordinates.
92
92
  * @param map - The map coordinates.
93
93
  * @param options - The rendering options.
94
94
  * @returns The local coordinates.
95
95
  */
96
- mapToLocal(map: Vec2, options: ILayerRender): Vec2;
96
+ mapToLocal(map: Vec2, options: ILayerRenderOptions): Vec2;
97
97
  }
@@ -31,7 +31,7 @@ export declare const createShaderProgram: (gl: WebGLContext, vsSource: string, f
31
31
  export declare function createTexture(gl: WebGLContext, source: TexImageSource | {
32
32
  width: number;
33
33
  height: number;
34
- }, antialias: boolean, withSize?: boolean, flipY?: boolean): WebGLTexture;
34
+ }, antialias: boolean, withSize?: boolean, flipY?: boolean, wrapMode?: 'repeat' | 'mirror' | 'clamp'): WebGLTexture;
35
35
  export declare function generateFragShader(fs: string, max: number): string;
36
36
  export declare const FLOAT = 5126;
37
37
  export declare const UNSIGNED_BYTE = 5121;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rapid-render",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "scripts": {
17
17
  "dev:build": "rollup -c rollup.config.dev.js -w",
18
- "dev:serve": "node dev-server.js",
18
+ "dev:serve": "node ./scripts/dev-server.js",
19
19
  "dev": "concurrently \"npm run dev:build\" \"npm run dev:serve\"",
20
20
  "build": "rollup -c rollup.config.prod.js && tsc",
21
21
  "docs": "typedoc"
@@ -28,11 +28,8 @@
28
28
  "rollup-plugin-typescript2": "^0.36.0",
29
29
  "tslib": "^2.6.2",
30
30
  "typedoc": "^0.26.6",
31
- "typescript": "^5.3.3"
32
- },
33
- "dependencies": {
31
+ "typescript": "^5.3.3",
34
32
  "express": "^4.18.2",
35
- "rollup-plugin-serve": "^3.0.0",
36
33
  "typedoc-theme-category-nav": "^0.0.3"
37
34
  }
38
- }
35
+ }