rapid-render 1.0.17 → 1.0.18
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/dist/extensions/light.d.ts +5 -0
- package/dist/index.d.ts +1 -0
- package/dist/rapid-render.js +210 -201
- package/dist/rapid-render.umd.cjs +23 -26
- package/dist/region/atlasSpriteRegion.d.ts +0 -2
- package/dist/region/graphicRegion.d.ts +1 -0
- package/dist/region/particleRegion.d.ts +1 -1
- package/dist/region/region.d.ts +2 -0
- package/dist/region/spriteRegion.d.ts +0 -2
- package/dist/webgl/glshader.d.ts +1 -0
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(T,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(T=typeof globalThis<"u"?globalThis:T||self,f(T.RapidRender={}))})(this,(function(T){"use strict";class f{_r;_g;_b;_a;uint32;premultipliedUint32;static clampByte(t){return t<=0?0:t>=255?255:Math.round(t)}constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}setClearColor(t){t.clearColor(this.r/255,this.g/255,this.b/255,this.a/255)}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;const t=f.clampByte(this._a),e=f.clampByte(this._r*t/255),r=f.clampByte(this._g*t/255),i=f.clampByte(this._b*t/255);this.premultipliedUint32=(t<<24|i<<16|r<<8|e)>>>0}reset(){this._r=0,this._g=0,this._b=0,this._a=255,this.updateUint()}setRGBA(t,e,r,i){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}setHSL(t,e,r){t=(t%360+360)%360,e=Math.max(0,Math.min(100,e))/100,r=Math.max(0,Math.min(100,r))/100;const i=(1-Math.abs(2*r-1))*e,s=i*(1-Math.abs(t/60%2-1)),a=r-i/2;let h=0,o=0,c=0;return t<60?[h,o,c]=[i,s,0]:t<120?[h,o,c]=[s,i,0]:t<180?[h,o,c]=[0,i,s]:t<240?[h,o,c]=[0,s,i]:t<300?[h,o,c]=[s,0,i]:[h,o,c]=[i,0,s],this.setRGBA((h+a)*255,(o+a)*255,(c+a)*255,255),this}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new f(this._r,this._g,this._b,this._a)}toHexString(t=!0){const e=this.r.toString(16).padStart(2,"0"),r=this.g.toString(16).padStart(2,"0"),i=this.b.toString(16).padStart(2,"0"),s=this.a.toString(16).padStart(2,"0");return`#${e}${r}${i}${t?s:""}`}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static FromHSL(t,e,r){return new f(0,0,0).setHSL(t,e,r)}static FromRGB(t,e,r){return new f(t,e,r)}static fromNorm(t,e,r,i=1){return new f(Math.round(t*255),Math.round(e*255),Math.round(r*255),Math.round(i*255))}static packColor(t,e,r,i,s){const a=f.clampByte(i),h=s?a/255:1,o=f.clampByte(t*h),c=f.clampByte(e*h),u=f.clampByte(r*h);return(a<<24|u<<16|c<<8|o)>>>0}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 f(e,r,i,s)}add(t){return new f(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 f(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)}divide(t){return t instanceof f?new f(this.r/t.r,this.g/t.g,this.b/t.b,this.a/t.a):new f(this.r/t,this.g/t,this.b/t,this.a/t)}multiply(t){return t instanceof f?new f(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a):new f(this.r*t,this.g*t,this.b*t,this.a*t)}clamp(){this._r=Math.max(0,Math.min(255,this._r)),this._g=Math.max(0,Math.min(255,this._g)),this._b=Math.max(0,Math.min(255,this._b)),this._a=Math.max(0,Math.min(255,this._a)),this.updateUint()}static Red=new f(255,0,0,255);static Green=new f(0,255,0,255);static Blue=new f(0,0,255,255);static Yellow=new f(255,255,0,255);static Purple=new f(128,0,128,255);static Orange=new f(255,165,0,255);static Pink=new f(255,192,203,255);static Gray=new f(128,128,128,255);static Brown=new f(139,69,19,255);static Cyan=new f(0,255,255,255);static Magenta=new f(255,0,255,255);static Lime=new f(192,255,0,255);static White=new f(255,255,255,255);static Black=new f(0,0,0,255);static Transparent=new f(0,0,0,0)}var j=(n=>(n[n.LINEAR=0]="LINEAR",n[n.NEAREST=1]="NEAREST",n))(j||{}),Y=(n=>(n[n.REPEAT=0]="REPEAT",n[n.CLAMP=1]="CLAMP",n[n.MIRRORED_REPEAT=2]="MIRRORED_REPEAT",n))(Y||{});class gt{render;cache=new Map;constructor(t){this.render=t}async load(t,e){let r=this.cache.get(t);if(r)return new N(r);try{const i=await this._fetchImage(t);return r=k.fromSource(this.render,i,e),r.uid=t,this.cache.set(t,r),new N(r)}catch(i){throw console.error(`[TextureManager] Failed to load: ${t}`,i),i}}create(t,e){if(e?.key&&this.cache.has(e.key))return new N(this.cache.get(e.key));const r=k.fromSource(this.render,t,e);return e?.key&&(r.uid=e.key,this.cache.set(e.key,r)),new N(r)}createRenderTexture(t){return new pt(this.render,t)}createTextTexture(t){return new vt(this.render,t)}destroy(t,e=!1){let r,i;typeof t=="string"?(i=t,r=this.cache.get(i)):t instanceof N?(r=t.base,i=r?.uid,t.destroy()):(r=t,i=r.uid),r&&(r.refCount<=0||e)&&(r.destroy(this.render.gl),i&&this.cache.delete(i))}destroyAll(){for(const t of this.cache.values())t.destroy(this.render.gl);this.cache.clear()}_fetchImage(t){return new Promise((e,r)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>e(i),i.onerror=()=>r(new Error(`Failed to load image resource: ${t}`)),i.src=t})}}class k{glTexture=null;width;height;uid;refCount=0;constructor(t,e,r){this.glTexture=t,this.width=e,this.height=r}static fromSource(t,e,r={}){const i=et(t,e,r);return new k(i,e.width,e.height)}updateSource(t,e,r={}){this.glTexture&&(t.bindTexture(t.TEXTURE_2D,this.glTexture),r.textureFilter!==void 0&&at(t,r.textureFilter),r.wrap!==void 0&&nt(t,r.wrap),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),r.premultipliedAlpha!==void 0&&t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r.premultipliedAlpha),this.width===e.width&&this.height===e.height?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,e):(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),this.width=e.width,this.height=e.height),r.premultipliedAlpha!==void 0&&t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1))}setFilterMode(t,e){this.glTexture&&(t.bindTexture(t.TEXTURE_2D,this.glTexture),at(t,e),t.bindTexture(t.TEXTURE_2D,null))}setWrapMode(t,e){this.glTexture&&(t.bindTexture(t.TEXTURE_2D,this.glTexture),nt(t,e),t.bindTexture(t.TEXTURE_2D,null))}destroy(t){this.glTexture&&(t.deleteTexture(this.glTexture),this.glTexture=null)}}class N{base;uvX=0;uvY=0;uvW=1;uvH=1;rawWidth=0;rawHeight=0;offsetX=0;offsetY=0;scale=1;isAtlas=!1;flipY=!1;isRotated=!1;glTexture=null;get width(){return this.isRotated?this.rawHeight:this.rawWidth}get height(){return this.isRotated?this.rawWidth:this.rawHeight}_px=0;_py=0;constructor(t){t&&this.setBase(t)}setBase(t){return this.base===t?this:(this.base&&this.base.refCount--,this.base=t,this.base.refCount++,this.setRegion(0,0,t.width,t.height),this.glTexture=t.glTexture,this)}setRegion(t,e,r,i){return this.base?(this._px=t,this._py=e,this.isAtlas=t!==0||e!==0||r!==this.base.width||i!==this.base.height,this.uvX=t/this.base.width,this.uvY=e/this.base.height,this.uvW=this.uvX+r/this.base.width,this.uvH=this.uvY+i/this.base.height,this.rawWidth=r*this.scale,this.rawHeight=i*this.scale,this):this}getSubTexture(t,e,r,i){if(!this.base)return new N;const s=this.clone(),a=this._px,h=this._py;return s.setRegion(a+t,h+e,r,i),s}clone(t){const e=t??new N(this.base);return t&&this.base&&t.setBase(this.base),e.scale=this.scale,e.uvX=this.uvX,e.uvY=this.uvY,e.uvW=this.uvW,e.uvH=this.uvH,e.rawWidth=this.rawWidth,e.rawHeight=this.rawHeight,e.offsetX=this.offsetX,e.offsetY=this.offsetY,e.flipY=this.flipY,e.isRotated=this.isRotated,e.isAtlas=this.isAtlas,e._px=this._px,e._py=this._py,e}splitGrid(t,e,r,i,s=0){if(!this.base)return[];const a=[],h=this.rawWidth,o=this.rawHeight,c=Math.max(0,s),u=t+c,l=e+c,m=r??Math.floor((h+c)/u),d=i??Math.floor((o+c)/l);for(let x=0;x<d;x++)for(let p=0;p<m;p++)a.push(this.getSubTexture(p*u,x*l,t,e));return a}static fromImageSource(t,e,r={}){const i=et(t,e,r);return new N(new k(i,e.width,e.height))}destroy(){this.base&&(this.base.refCount--,this.base=void 0),this.glTexture=null}}class pt extends N{framebuffer;renderbuffer;gl;clearColor;_allocW=0;_allocH=0;constructor(t,e){super(),this.gl=t.gl,this.clearColor=e.clearColor??f.Black;const r=Math.max(Math.round(e.width),1),i=Math.max(Math.round(e.height),1),a=et(t,{width:r,height:i},{...e,onlySize:!0});if(this.setBase(new k(a,r,i)),this.framebuffer=this.gl.createFramebuffer(),this.renderbuffer=this.gl.createRenderbuffer(),!this.framebuffer||!this.renderbuffer)throw new Error("Failed to create Framebuffer or Renderbuffer");this.resize(r,i,!0)}resize(t,e,r=!1){t=Math.max(Math.round(t),1),e=Math.max(Math.round(e),1);const i=this.rawWidth===t&&this.rawHeight===e;if(!r&&i)return;const s=this.gl;(r||t>this._allocW||e>this._allocH)&&this.base&&(this._allocW=Math.max(this._allocW,t),this._allocH=Math.max(this._allocH,e),this.base.width=this._allocW,this.base.height=this._allocH,s.bindTexture(s.TEXTURE_2D,this.base.glTexture),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this._allocW,this._allocH,0,s.RGBA,s.UNSIGNED_BYTE,null),s.bindRenderbuffer(s.RENDERBUFFER,this.renderbuffer),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,this._allocW,this._allocH),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.base.glTexture,0),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,this.renderbuffer),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindTexture(s.TEXTURE_2D,null)),this.rawWidth=t,this.rawHeight=e,this.uvX=0,this.uvW=t/this._allocW,this.uvY=0,this.uvH=e/this._allocH}activate(t=!1){if(!this.framebuffer)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer),e.viewport(0,0,this.rawWidth,this.rawHeight),t&&this.clear()}clear(t){if(!this.framebuffer)return;const e=this.gl,r=t??this.clearColor;r&&(r.setClearColor(e),e.clear(e.COLOR_BUFFER_BIT|e.STENCIL_BUFFER_BIT))}deactivate(){const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)}GetPixels(t=0,e=0,r=this.rawWidth,i=this.rawHeight){if(!this.framebuffer)return new Uint8Array(0);const s=Math.floor(t),a=Math.floor(e),h=Math.floor(r),o=Math.floor(i);if(h<=0||o<=0)return new Uint8Array(0);if(s<0||a<0||s>=this.rawWidth||a>=this.rawHeight)return new Uint8Array(0);const c=Math.min(h,this.rawWidth-s),u=Math.min(o,this.rawHeight-a),l=this.gl,m=l.getParameter(l.FRAMEBUFFER_BINDING);l.bindFramebuffer(l.FRAMEBUFFER,this.framebuffer);const d=new Uint8Array(c*u*4);return l.readPixels(s,a,c,u,l.RGBA,l.UNSIGNED_BYTE,d),l.bindFramebuffer(l.FRAMEBUFFER,m),d}GetColorAt(t,e){const r=this.GetPixels(t,e,1,1);return r.length<4?new f(0,0,0,0):new f(r[0],r[1],r[2],r[3])}destroy(){super.destroy(),this.framebuffer&&this.gl.deleteFramebuffer(this.framebuffer),this.renderbuffer&&this.gl.deleteRenderbuffer(this.renderbuffer),this.base?.destroy(this.gl)}}const kt={fontFamily:"Arial",fontSize:24,fontWeight:"normal",fill:"#000000",strokeThickness:0,align:"left",lineHeight:1};class vt extends N{canvas;ctx;render;_text;_style;options;flipY=!0;constructor(t,e){super(),this.render=t,this._style={...kt,...e},this._text=e?.text??"",this.options={premultipliedAlpha:t.premultipliedAlpha,...e},this.scale=1/t.dpr,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("Failed to get 2d context for TextTexture");this.ctx=r,this.canvas.width=1,this.canvas.height=1;const i=et(t,this.canvas,this.options);this.setBase(new k(i,1,1)),this.update()}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this.update())}get style(){return this._style}set style(t){this._style={...this._style,...t},this.update()}updateOffset(t,e){switch(this._style.align){case"center":return t/2;case"right":return t;default:return e}}update(){const t=this.ctx,e=this.style,r=e.fontSize,i=e.fontWeight,s=e.fontFamily,a=e.lineHeight,h=`${i} ${r}px ${s}`,o=this.render.dpr;t.font=h,t.textBaseline="top";const c=this._text.split(`
|
|
2
|
-
`);let u=0,l=0;const x=t.measureText(c[0]||"M").fontBoundingBoxDescent;for(const U of c){const w=t.measureText(U);w.width>u&&(u=w.width),l+=x*a}l-=x*(a-1);const p=this._style.strokeThickness||0,v=Math.ceil(u+p*2)||1,y=Math.ceil(l+p*2)||1,M=Math.ceil(v*o),A=Math.ceil(y*o);(this.canvas.width!==M||this.canvas.height!==A)&&(this.canvas.width=M,this.canvas.height=A),t.setTransform(o,0,0,o,0,0),t.clearRect(0,0,v,y),t.font=h,t.textBaseline="top",t.textAlign=this._style.align;const L=this.updateOffset(v,p),P=e.strokeThickness,O=P>0;O&&(t.lineWidth=P,t.strokeStyle=e.stroke,t.lineJoin="round"),e.fill&&(t.fillStyle=e.fill);let F=p;for(const U of c)O&&t.strokeText(U,L,F),e.fill&&t.fillText(U,L,F),F+=x*a;this.base?.updateSource(this.render.gl,this.canvas,this.options),this.setRegion(0,0,M,A)}}const Ht=(n,t=!1,e=!0)=>{const r=n.getContext("webgl2",{stencil:!0,antialias:t,premultipliedAlpha:e});if(!r)throw new Error("WebGL2 is not supported in this browser.");return r},yt=(n,t,e)=>{const r=n.createShader(e);if(!r)throw new Error("Unable to create webgl shader");if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS)){const s=n.getShaderInfoLog(r);throw console.error("Shader compilation failed:",s),new Error("Unable to compile shader: "+s+t)}return r},Gt=(n,t,e)=>{var r=n.createProgram(),i=yt(n,t,35633),s=yt(n,e,35632);if(!r)throw new Error("Unable to create program shader");if(n.attachShader(r,i),n.attachShader(r,s),n.linkProgram(r),!n.getProgramParameter(r,n.LINK_STATUS)){const h=n.getProgramInfoLog(r);throw new Error("Unable to link shader program: "+h)}return r};function nt(n,t){const e={[Y.CLAMP]:n.CLAMP_TO_EDGE,[Y.REPEAT]:n.REPEAT,[Y.MIRRORED_REPEAT]:n.MIRRORED_REPEAT}[t]||n.CLAMP_TO_EDGE;n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e)}function at(n,t){const e={[j.LINEAR]:n.LINEAR,[j.NEAREST]:n.NEAREST}[t]??n.NEAREST;n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,e)}function et(n,t,e){const r=n.gl,i=r.createTexture();if(!i)throw new Error("Unable to create WebGL texture");if(r.bindTexture(r.TEXTURE_2D,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,0),r.pixelStorei(r.UNPACK_ALIGNMENT,1),nt(r,e.wrap??Y.CLAMP),at(r,e.textureFilter??n.textureFilter),e.onlySize){const s=t;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,s.width,s.height,0,r.RGBA,r.UNSIGNED_BYTE,null)}else{const s=e.premultipliedAlpha??n.premultipliedAlpha;s&&r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),s&&r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1)}return r.bindTexture(r.TEXTURE_2D,null),i}function B(n,t,e="vTextureId",r="uv",i="return"){if(n.includes("%TEXTURE_NUM%")&&(n=n.replaceAll("%TEXTURE_NUM%",t.toString())),n.includes("%GET_COLOR%")){let s="";for(let a=0;a<t;a++)a==0?s+=`if(${e} == ${a})`:a==t-1?s+="else":s+=`else if(${e} == ${a})`,s+=`{${i} texture(uTextures[${a}], ${r});}`;n=n.replaceAll("%GET_COLOR%",s)}return n}const Vt=5126,ht=5121;function Xt(n,t,e){n.vertexAttribDivisor(t,e)}function Tt(n,t,e,r,i){n.drawArraysInstanced(t,e,r,i)}let Yt=0;class ot{program;attributeLoc={};uniformLoc={};isCustom=!1;padding=0;uniformType={};uniformIsArray={};gl;shaderId=Yt++;vao;constructor(t,e,r,i){this.gl=t,this.program=Gt(t,e,r),this.parseShader(e),this.parseShader(r),this.vao=t.createVertexArray(),i&&this.setAttributes(i)}use(){this.gl.useProgram(this.program)}bindVAO(){this.gl.bindVertexArray(this.vao)}unbindVAO(){this.gl.bindVertexArray(null)}setUniform(t,e){const r=this.uniformLoc[t];if(r===void 0)return;const i=this.uniformType[t],s=this.uniformIsArray[t];zt(this.gl,r,i,e,s)}setUniforms(t){for(const e in t)this.setUniform(e,t[e])}setAttribute(t){const e=this.attributeLoc[t.name];if(e===void 0)return;const r=this.gl;r.vertexAttribPointer(e,t.size,t.type??Vt,t.normalized??!1,t.stride,t.offset??0),r.enableVertexAttribArray(e),Xt(r,e,t.divisor??0)}setAttributes(t){for(const e of t)this.setAttribute(e)}destroy(){this.gl.deleteProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/(?:in|attribute)\s+\w+\s+\w+/g);if(r)for(const s of r){const h=s.split(/\s+/)[2],o=e.getAttribLocation(this.program,h);o!==-1&&(this.attributeLoc[h]=o)}const i=t.matchAll(/uniform\s+(?:(?:lowp|mediump|highp)\s+)?(\w+)\s+(\w+)(\s*\[\s*\d+\s*\])?/g);for(const s of i){const a=s[1],h=s[2],o=e.getUniformLocation(this.program,h);o!==null&&(this.uniformLoc[h]=o,this.uniformType[h]=a,this.uniformIsArray[h]=s[3]!==void 0)}}}function zt(n,t,e,r,i=!1){switch(e){case"float":return i?n.uniform1fv(t,r):n.uniform1f(t,r);case"int":case"bool":case"sampler2D":case"samplerCube":return i?n.uniform1iv(t,r):n.uniform1i(t,r);case"vec2":return n.uniform2fv(t,r);case"vec3":return n.uniform3fv(t,r);case"vec4":return n.uniform4fv(t,r);case"ivec2":case"bvec2":return n.uniform2iv(t,r);case"ivec3":case"bvec3":return n.uniform3iv(t,r);case"ivec4":case"bvec4":return n.uniform4iv(t,r);case"mat2":return n.uniformMatrix2fv(t,!1,r);case"mat3":return n.uniformMatrix3fv(t,!1,r);case"mat4":return n.uniformMatrix4fv(t,!1,r);case"mat3x2":return n.uniformMatrix3x2fv(t,!1,r);default:return $t(n,t,r)}}function $t(n,t,e){if(typeof e=="number")return n.uniform1f(t,e);const r=e;switch(r.length){case 2:return n.uniform2fv(t,r);case 3:return n.uniform3fv(t,r);case 4:return n.uniform4fv(t,r);case 9:return n.uniformMatrix3fv(t,!1,r);case 16:return n.uniformMatrix4fv(t,!1,r);default:return n.uniform1fv(t,r)}}class rt{vs;fs;glshader=new Map;uniforms={};uniformDirty=new Set;uniformTextures={};uniformArrayTexture={};usedTextureUnitNum=0;padding=0;rapid;prefix=[];constructor(t,e="",r="",i=0,s){this.vs=e,this.fs=r,this.rapid=t,this.uniforms=s??{},this.usedTextureUnitNum=i}setUniforms(t){this.rapid.flush();const e={},r={},i={};for(const[s,a]of Object.entries(t))a instanceof WebGLTexture?r[s]=a:Array.isArray(a)&&a[0]instanceof WebGLTexture?i[s]=a:e[s]=a;Object.assign(this.uniforms,e),Object.assign(this.uniformTextures,r),Object.assign(this.uniformArrayTexture,i);for(const s of this.glshader.keys())this.uniformDirty.add(s)}setPadding(t){this.padding=t;for(const e of this.glshader.values())e.padding=t;return this}applyUniform(t,e){const r=this.glshader.get(t);r&&(Object.keys(e).length>0&&r.setUniforms(e),this.uniformDirty.has(t)&&(r.setUniforms(this.uniforms),this.uniformDirty.delete(t)))}getGLShader(t,e,r,i){if(this.glshader.has(e))return this.glshader.get(e);if(i==null||r==null)return console.warn("CustomGlShader: missing base shader for "+e),null;const s=this.prefix.length==0?[""]:this.prefix;r=r.replace("// CUSTOM_CODE_CALL",s.map(h=>h+"vertex(position, vRegion);").join("")),r=r.replace("// CUSTOM_CODE",this.vs),i=i.replace("// CUSTOM_CODE_CALL",s.map(h=>h+"fragment(fragColor, vRegion);").join("")),i=i.replace("// CUSTOM_CODE",this.fs);const a=t.createShader(r,i);return a.isCustom=!0,a.padding=this.padding,this.glshader.set(e,a),this.uniformDirty.add(e),a}destroy(){this.glshader.forEach(t=>t.destroy())}}class Et{constructor(t){this.rapid=t,this.gl=t.gl,this.maxTextureUnits=t.maxTextureUnits,this.matrixStore=t.matrix}defaultShader;currentShader;customShader=null;customShaderUsedTextureNum=0;gl;maxTextureUnits;matrixStore;isDefaultShader=!0;KEY="default";vs="";fs="";usedTextures=[];usedTexturePadding=[];createBuffer(){}createDefaultShader(){}get freeTextureUnitNum(){return this.maxTextureUnits-this.usedTextures.length-this.customShaderUsedTextureNum}getTextureUnitList(){return Array.from({length:this.maxTextureUnits},(t,e)=>e)}findTextureUnit(t,e=0,r=0){for(let i=0;i<this.usedTextures.length;i++){const s=i*2;if(this.usedTextures[i]===t&&this.usedTexturePadding[s]===e&&this.usedTexturePadding[s+1]===r)return i}return-1}useTexture(t,e=0,r=0){const i=this.findTextureUnit(t,e,r);return i==-1?(this.freeTextureUnitNum===0&&this.flush(),this.usedTextures.push(t),this.usedTexturePadding.push(e),this.usedTexturePadding.push(r),this.usedTextures.length-1):i}createShader(t,e){return new ot(this.gl,t,e)}createCustomShader(t){return t.getGLShader(this,this.KEY,this.vs,this.fs)}getCustomShader(t){if(!t)return this.defaultShader;if(t instanceof rt){const e=this.createCustomShader(t);return e??this.defaultShader}return t}isSameShader(t){return this.isDefaultShader&&!t?!0:this.getCustomShader(t)==this.currentShader}enter(t){this.resetRender(),this.currentShader=this.getCustomShader(t),t instanceof rt?(this.customShader=t,this.customShaderUsedTextureNum=t.usedTextureUnitNum):(this.customShader=null,this.customShaderUsedTextureNum=0),this.isDefaultShader=this.currentShader==this.defaultShader,this.currentShader.use(),this.currentShader.setUniform("u_projection",this.rapid.projection)}exit(){this.hasPendingContent()&&this.flush(),this.gl.bindVertexArray(null)}flush(){this.render(),this.resetRender()}render(){this.prepareRender()}prepareRender(){const t=this.currentShader;if(t.use(),this.customShader){const r=this.customShader,i={};for(const[s,a]of Object.entries(r.uniformTextures))i[s]=this.useTexture(a);for(const[s,a]of Object.entries(r.uniformArrayTexture))i[s]=a.map(h=>this.useTexture(h));this.customShader.applyUniform(this.KEY,i)}const e=this.gl;for(let r=0;r<this.usedTextures.length;r++)e.activeTexture(e.TEXTURE0+r),e.bindTexture(e.TEXTURE_2D,this.usedTextures[r]);t.setUniform("uTextures",Int32Array.from({length:this.usedTextures.length},(r,i)=>i)),t.setUniform("uPadding",Float32Array.from({length:this.usedTexturePadding.length},(r,i)=>this.usedTexturePadding[i]))}resetRender(){const t=this.gl;for(let e=0;e<this.usedTextures.length;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,null);this.usedTextures.length=0,this.usedTexturePadding.length=0}hasPendingContent(){return!1}}var S=(n=>(n[n.Float32=0]="Float32",n[n.Uint32=1]="Uint32",n[n.Uint16=2]="Uint16",n))(S||{});class b{usedElemNum;typedArray;arrayType;maxElemNum;bytePerElem;arraybuffer;uint32;float32;uint16;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 0:return Float32Array;case 1:return Uint32Array;case 2:return Uint16Array;default:throw new Error("Unsupported ArrayType")}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case 0:this.typedArray=this.float32;break;case 1:this.typedArray=this.uint32;break;case 2:this.typedArray=this.uint16;break}}clear(){this.usedElemNum=0}static removeAtIndices(t,e){const r=Math.max(...e.map(h=>h.usedElemNum)),i=[...new Set(t)].filter(h=>h>=0&&h<r).sort((h,o)=>h-o);if(i.length===0)return 0;let s=0,a=0;for(let h=0;h<r;h++){if(a<i.length&&h===i[a]){a++;continue}if(s!==h)for(const o of e)o.typedArray[s]=o.typedArray[h];s++}for(const h of e)h.usedElemNum=s;return r-s}resize(t=0){if(t+=this.usedElemNum,t>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum*=2;return this.setMaxSize(this.maxElemNum),!0}return!1}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.resize(1),this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.resize(1),this.float32[this.usedElemNum++]=t}push(t){this.resize(1),this.typedArray[this.usedElemNum++]=t}pop(){return this.typedArray[--this.usedElemNum]}top(){return this.typedArray[this.usedElemNum-1]}get(t){return this.typedArray[t]}getArray(t=0,e){return e===void 0?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.usedElemNum}}class ct extends b{buffer;gl;dirty=!0;type;webglBufferSize=0;usage;constructor(t,e,r=t.ARRAY_BUFFER,i=t.DYNAMIC_DRAW){super(e),this.gl=t,this.buffer=t.createBuffer(),this.type=r,this.usage=i}makeDirty(){this.dirty=!0}clear(){super.clear(),this.dirty=!1}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.maxElemNum*this.bytePerElem,this.usage),this.webglBufferSize=this.maxElemNum),t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}const it=`#version 300 es\r
|
|
1
|
+
(function(v,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(v=typeof globalThis<"u"?globalThis:v||self,f(v.RapidRender={}))})(this,(function(v){"use strict";class f{_r;_g;_b;_a;uint32;premultipliedUint32;static clampByte(t){return t<=0?0:t>=255?255:Math.round(t)}constructor(t,e,r,i=255){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}setClearColor(t){t.clearColor(this.r/255,this.g/255,this.b/255,this.a/255)}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;const t=f.clampByte(this._a),e=f.clampByte(this._r*t/255),r=f.clampByte(this._g*t/255),i=f.clampByte(this._b*t/255);this.premultipliedUint32=(t<<24|i<<16|r<<8|e)>>>0}reset(){this._r=0,this._g=0,this._b=0,this._a=255,this.updateUint()}setRGBA(t,e,r,i){this._r=t,this._g=e,this._b=r,this._a=i,this.updateUint()}setHSL(t,e,r){t=(t%360+360)%360,e=Math.max(0,Math.min(100,e))/100,r=Math.max(0,Math.min(100,r))/100;const i=(1-Math.abs(2*r-1))*e,s=i*(1-Math.abs(t/60%2-1)),a=r-i/2;let h=0,o=0,c=0;return t<60?[h,o,c]=[i,s,0]:t<120?[h,o,c]=[s,i,0]:t<180?[h,o,c]=[0,i,s]:t<240?[h,o,c]=[0,s,i]:t<300?[h,o,c]=[s,0,i]:[h,o,c]=[i,0,s],this.setRGBA((h+a)*255,(o+a)*255,(c+a)*255,255),this}copy(t){this.setRGBA(t.r,t.g,t.b,t.a)}clone(){return new f(this._r,this._g,this._b,this._a)}toHexString(t=!0){const e=this.r.toString(16).padStart(2,"0"),r=this.g.toString(16).padStart(2,"0"),i=this.b.toString(16).padStart(2,"0"),s=this.a.toString(16).padStart(2,"0");return`#${e}${r}${i}${t?s:""}`}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b&&t.a===this.a}static FromHSL(t,e,r){return new f(0,0,0).setHSL(t,e,r)}static FromRGB(t,e,r){return new f(t,e,r)}static fromNorm(t,e,r,i=1){return new f(Math.round(t*255),Math.round(e*255),Math.round(r*255),Math.round(i*255))}static packColor(t,e,r,i,s){const a=f.clampByte(i),h=s?a/255:1,o=f.clampByte(t*h),c=f.clampByte(e*h),u=f.clampByte(r*h);return(a<<24|u<<16|c<<8|o)>>>0}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 f(e,r,i,s)}add(t){return new f(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 f(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)}divide(t){return t instanceof f?new f(this.r/t.r,this.g/t.g,this.b/t.b,this.a/t.a):new f(this.r/t,this.g/t,this.b/t,this.a/t)}multiply(t){return t instanceof f?new f(this.r*t.r,this.g*t.g,this.b*t.b,this.a*t.a):new f(this.r*t,this.g*t,this.b*t,this.a*t)}clamp(){this._r=Math.max(0,Math.min(255,this._r)),this._g=Math.max(0,Math.min(255,this._g)),this._b=Math.max(0,Math.min(255,this._b)),this._a=Math.max(0,Math.min(255,this._a)),this.updateUint()}static Red=new f(255,0,0,255);static Green=new f(0,255,0,255);static Blue=new f(0,0,255,255);static Yellow=new f(255,255,0,255);static Purple=new f(128,0,128,255);static Orange=new f(255,165,0,255);static Pink=new f(255,192,203,255);static Gray=new f(128,128,128,255);static Brown=new f(139,69,19,255);static Cyan=new f(0,255,255,255);static Magenta=new f(255,0,255,255);static Lime=new f(192,255,0,255);static White=new f(255,255,255,255);static Black=new f(0,0,0,255);static Transparent=new f(0,0,0,0)}var $=(n=>(n[n.LINEAR=0]="LINEAR",n[n.NEAREST=1]="NEAREST",n))($||{}),X=(n=>(n[n.REPEAT=0]="REPEAT",n[n.CLAMP=1]="CLAMP",n[n.MIRRORED_REPEAT=2]="MIRRORED_REPEAT",n))(X||{});class pt{render;cache=new Map;constructor(t){this.render=t}async load(t,e){let r=this.cache.get(t);if(r)return new N(r);try{const i=await this._fetchImage(t);return r=B.fromSource(this.render,i,e),r.uid=t,this.cache.set(t,r),new N(r)}catch(i){throw console.error(`[TextureManager] Failed to load: ${t}`,i),i}}create(t,e){if(e?.key&&this.cache.has(e.key))return new N(this.cache.get(e.key));const r=B.fromSource(this.render,t,e);return e?.key&&(r.uid=e.key,this.cache.set(e.key,r)),new N(r)}createRenderTexture(t){return new vt(this.render,t)}createTextTexture(t){return new yt(this.render,t)}destroy(t,e=!1){let r,i;typeof t=="string"?(i=t,r=this.cache.get(i)):t instanceof N?(r=t.base,i=r?.uid,t.destroy()):(r=t,i=r.uid),r&&(r.refCount<=0||e)&&(r.destroy(this.render.gl),i&&this.cache.delete(i))}destroyAll(){for(const t of this.cache.values())t.destroy(this.render.gl);this.cache.clear()}_fetchImage(t){return new Promise((e,r)=>{const i=new Image;i.crossOrigin="anonymous",i.onload=()=>e(i),i.onerror=()=>r(new Error(`Failed to load image resource: ${t}`)),i.src=t})}}class B{glTexture=null;width;height;uid;refCount=0;constructor(t,e,r){this.glTexture=t,this.width=e,this.height=r}static fromSource(t,e,r={}){const i=et(t,e,r);return new B(i,e.width,e.height)}updateSource(t,e,r={}){this.glTexture&&(t.bindTexture(t.TEXTURE_2D,this.glTexture),r.textureFilter!==void 0&&at(t,r.textureFilter),r.wrap!==void 0&&nt(t,r.wrap),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),r.premultipliedAlpha!==void 0&&t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r.premultipliedAlpha),this.width===e.width&&this.height===e.height?t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,e):(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),this.width=e.width,this.height=e.height),r.premultipliedAlpha!==void 0&&t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1))}setFilterMode(t,e){this.glTexture&&(t.bindTexture(t.TEXTURE_2D,this.glTexture),at(t,e),t.bindTexture(t.TEXTURE_2D,null))}setWrapMode(t,e){this.glTexture&&(t.bindTexture(t.TEXTURE_2D,this.glTexture),nt(t,e),t.bindTexture(t.TEXTURE_2D,null))}destroy(t){this.glTexture&&(t.deleteTexture(this.glTexture),this.glTexture=null)}}class N{base;uvX=0;uvY=0;uvW=1;uvH=1;rawWidth=0;rawHeight=0;offsetX=0;offsetY=0;scale=1;isAtlas=!1;flipY=!1;isRotated=!1;glTexture=null;get width(){return this.isRotated?this.rawHeight:this.rawWidth}get height(){return this.isRotated?this.rawWidth:this.rawHeight}_px=0;_py=0;constructor(t){t&&this.setBase(t)}setBase(t){return this.base===t?this:(this.base&&this.base.refCount--,this.base=t,this.base.refCount++,this.setRegion(0,0,t.width,t.height),this.glTexture=t.glTexture,this)}setRegion(t,e,r,i){return this.base?(this._px=t,this._py=e,this.isAtlas=t!==0||e!==0||r!==this.base.width||i!==this.base.height,this.uvX=t/this.base.width,this.uvY=e/this.base.height,this.uvW=this.uvX+r/this.base.width,this.uvH=this.uvY+i/this.base.height,this.rawWidth=r*this.scale,this.rawHeight=i*this.scale,this):this}getSubTexture(t,e,r,i){if(!this.base)return new N;const s=this.clone(),a=this._px,h=this._py;return s.setRegion(a+t,h+e,r,i),s}clone(t){const e=t??new N(this.base);return t&&this.base&&t.setBase(this.base),e.scale=this.scale,e.uvX=this.uvX,e.uvY=this.uvY,e.uvW=this.uvW,e.uvH=this.uvH,e.rawWidth=this.rawWidth,e.rawHeight=this.rawHeight,e.offsetX=this.offsetX,e.offsetY=this.offsetY,e.flipY=this.flipY,e.isRotated=this.isRotated,e.isAtlas=this.isAtlas,e._px=this._px,e._py=this._py,e}splitGrid(t,e,r,i,s=0){if(!this.base)return[];const a=[],h=this.rawWidth,o=this.rawHeight,c=Math.max(0,s),u=t+c,l=e+c,m=r??Math.floor((h+c)/u),d=i??Math.floor((o+c)/l);for(let x=0;x<d;x++)for(let p=0;p<m;p++)a.push(this.getSubTexture(p*u,x*l,t,e));return a}static fromImageSource(t,e,r={}){const i=et(t,e,r);return new N(new B(i,e.width,e.height))}destroy(){this.base&&(this.base.refCount--,this.base=void 0),this.glTexture=null}}class vt extends N{framebuffer;renderbuffer;gl;clearColor;_allocW=0;_allocH=0;constructor(t,e){super(),this.gl=t.gl,this.clearColor=e.clearColor??f.Black;const r=Math.max(Math.round(e.width),1),i=Math.max(Math.round(e.height),1),a=et(t,{width:r,height:i},{...e,onlySize:!0});if(this.setBase(new B(a,r,i)),this.framebuffer=this.gl.createFramebuffer(),this.renderbuffer=this.gl.createRenderbuffer(),!this.framebuffer||!this.renderbuffer)throw new Error("Failed to create Framebuffer or Renderbuffer");this.resize(r,i,!0)}resize(t,e,r=!1){t=Math.max(Math.round(t),1),e=Math.max(Math.round(e),1);const i=this.rawWidth===t&&this.rawHeight===e;if(!r&&i)return;const s=this.gl;(r||t>this._allocW||e>this._allocH)&&this.base&&(this._allocW=Math.max(this._allocW,t),this._allocH=Math.max(this._allocH,e),this.base.width=this._allocW,this.base.height=this._allocH,s.bindTexture(s.TEXTURE_2D,this.base.glTexture),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this._allocW,this._allocH,0,s.RGBA,s.UNSIGNED_BYTE,null),s.bindRenderbuffer(s.RENDERBUFFER,this.renderbuffer),s.renderbufferStorage(s.RENDERBUFFER,s.STENCIL_INDEX8,this._allocW,this._allocH),s.bindFramebuffer(s.FRAMEBUFFER,this.framebuffer),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.base.glTexture,0),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,this.renderbuffer),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindTexture(s.TEXTURE_2D,null)),this.rawWidth=t,this.rawHeight=e,this.uvX=0,this.uvW=t/this._allocW,this.uvY=0,this.uvH=e/this._allocH}activate(t=!1){if(!this.framebuffer)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer),e.viewport(0,0,this.rawWidth,this.rawHeight),t&&this.clear()}clear(t){if(!this.framebuffer)return;const e=this.gl,r=t??this.clearColor;r&&(r.setClearColor(e),e.clear(e.COLOR_BUFFER_BIT|e.STENCIL_BUFFER_BIT))}deactivate(){const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)}GetPixels(t=0,e=0,r=this.rawWidth,i=this.rawHeight){if(!this.framebuffer)return new Uint8Array(0);const s=Math.floor(t),a=Math.floor(e),h=Math.floor(r),o=Math.floor(i);if(h<=0||o<=0)return new Uint8Array(0);if(s<0||a<0||s>=this.rawWidth||a>=this.rawHeight)return new Uint8Array(0);const c=Math.min(h,this.rawWidth-s),u=Math.min(o,this.rawHeight-a),l=this.gl,m=l.getParameter(l.FRAMEBUFFER_BINDING);l.bindFramebuffer(l.FRAMEBUFFER,this.framebuffer);const d=new Uint8Array(c*u*4);return l.readPixels(s,a,c,u,l.RGBA,l.UNSIGNED_BYTE,d),l.bindFramebuffer(l.FRAMEBUFFER,m),d}GetColorAt(t,e){const r=this.GetPixels(t,e,1,1);return r.length<4?new f(0,0,0,0):new f(r[0],r[1],r[2],r[3])}destroy(){super.destroy(),this.framebuffer&&this.gl.deleteFramebuffer(this.framebuffer),this.renderbuffer&&this.gl.deleteRenderbuffer(this.renderbuffer),this.base?.destroy(this.gl)}}const zt={fontFamily:"Arial",fontSize:24,fontWeight:"normal",fill:"#000000",strokeThickness:0,align:"left",lineHeight:1};class yt extends N{canvas;ctx;render;_text;_style;options;flipY=!0;constructor(t,e){super(),this.render=t,this._style={...zt,...e},this._text=e?.text??"",this.options={premultipliedAlpha:t.premultipliedAlpha,...e},this.scale=1/t.dpr,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("2d",{willReadFrequently:!0});if(!r)throw new Error("Failed to get 2d context for TextTexture");this.ctx=r,this.canvas.width=1,this.canvas.height=1;const i=et(t,this.canvas,this.options);this.setBase(new B(i,1,1)),this.update()}get text(){return this._text}set text(t){this._text!==t&&(this._text=t,this.update())}get style(){return this._style}set style(t){this._style={...this._style,...t},this.update()}updateOffset(t,e){switch(this._style.align){case"center":return t/2;case"right":return t;default:return e}}update(){const t=this.ctx,e=this.style,r=e.fontSize,i=e.fontWeight,s=e.fontFamily,a=e.lineHeight,h=`${i} ${r}px ${s}`,o=this.render.dpr;t.font=h,t.textBaseline="top";const c=this._text.split(`
|
|
2
|
+
`);let u=0,l=0;const x=t.measureText(c[0]||"M").fontBoundingBoxDescent;for(const U of c){const w=t.measureText(U);w.width>u&&(u=w.width),l+=x*a}l-=x*(a-1);const p=this._style.strokeThickness||0,y=Math.ceil(u+p*2)||1,T=Math.ceil(l+p*2)||1,R=Math.ceil(y*o),A=Math.ceil(T*o);(this.canvas.width!==R||this.canvas.height!==A)&&(this.canvas.width=R,this.canvas.height=A),t.setTransform(o,0,0,o,0,0),t.clearRect(0,0,y,T),t.font=h,t.textBaseline="top",t.textAlign=this._style.align;const L=this.updateOffset(y,p),P=e.strokeThickness,O=P>0;O&&(t.lineWidth=P,t.strokeStyle=e.stroke,t.lineJoin="round"),e.fill&&(t.fillStyle=e.fill);let F=p;for(const U of c)O&&t.strokeText(U,L,F),e.fill&&t.fillText(U,L,F),F+=x*a;this.base?.updateSource(this.render.gl,this.canvas,this.options),this.setRegion(0,0,R,A)}}const Yt=(n,t=!1,e=!0)=>{const r=n.getContext("webgl2",{stencil:!0,antialias:t,premultipliedAlpha:e});if(!r)throw new Error("WebGL2 is not supported in this browser.");return r},Tt=(n,t,e)=>{const r=n.createShader(e);if(!r)throw new Error("Unable to create webgl shader");if(n.shaderSource(r,t),n.compileShader(r),!n.getShaderParameter(r,n.COMPILE_STATUS)){const s=n.getShaderInfoLog(r);throw console.error("Shader compilation failed:",s),new Error("Unable to compile shader: "+s+t)}return r},$t=(n,t,e)=>{var r=n.createProgram(),i=Tt(n,t,35633),s=Tt(n,e,35632);if(!r)throw new Error("Unable to create program shader");if(n.attachShader(r,i),n.attachShader(r,s),n.linkProgram(r),!n.getProgramParameter(r,n.LINK_STATUS)){const h=n.getProgramInfoLog(r);throw new Error("Unable to link shader program: "+h)}return r};function nt(n,t){const e={[X.CLAMP]:n.CLAMP_TO_EDGE,[X.REPEAT]:n.REPEAT,[X.MIRRORED_REPEAT]:n.MIRRORED_REPEAT}[t]||n.CLAMP_TO_EDGE;n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,e)}function at(n,t){const e={[$.LINEAR]:n.LINEAR,[$.NEAREST]:n.NEAREST}[t]??n.NEAREST;n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,e),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,e)}function et(n,t,e){const r=n.gl,i=r.createTexture();if(!i)throw new Error("Unable to create WebGL texture");if(r.bindTexture(r.TEXTURE_2D,i),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,0),r.pixelStorei(r.UNPACK_ALIGNMENT,1),nt(r,e.wrap??X.CLAMP),at(r,e.textureFilter??n.textureFilter),e.onlySize){const s=t;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,s.width,s.height,0,r.RGBA,r.UNSIGNED_BYTE,null)}else{const s=e.premultipliedAlpha??n.premultipliedAlpha;s&&r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t),s&&r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1)}return r.bindTexture(r.TEXTURE_2D,null),i}function j(n,t,e="vTextureId",r="uv",i="return"){if(n.includes("%TEXTURE_NUM%")&&(n=n.replaceAll("%TEXTURE_NUM%",t.toString())),n.includes("%GET_COLOR%")){let s="";for(let a=0;a<t;a++)a==0?s+=`if(${e} == ${a})`:a==t-1?s+="else":s+=`else if(${e} == ${a})`,s+=`{${i} texture(uTextures[${a}], ${r});}`;n=n.replaceAll("%GET_COLOR%",s)}return n}const jt=5126,ht=5121;function Kt(n,t,e){n.vertexAttribDivisor(t,e)}function Mt(n,t,e,r,i){n.drawArraysInstanced(t,e,r,i)}let qt=0;class ot{program;attributeLoc={};uniformLoc={};isCustom=!1;padding=0;uniformType={};uniformIsArray={};gl;shaderId=qt++;vao;constructor(t,e,r,i){this.gl=t,this.program=$t(t,e,r),this.parseShader(e),this.parseShader(r),this.vao=t.createVertexArray(),i&&this.setAttributes(i)}use(){this.gl.useProgram(this.program)}bindVAO(){this.gl.bindVertexArray(this.vao)}unbindVAO(){this.gl.bindVertexArray(null)}setUniform(t,e){const r=this.uniformLoc[t];if(r===void 0)return;const i=this.uniformType[t],s=this.uniformIsArray[t];Qt(this.gl,r,i,e,s)}setUniforms(t){for(const e in t)this.setUniform(e,t[e])}setAttribute(t){const e=this.attributeLoc[t.name];if(e===void 0)return;const r=this.gl;r.vertexAttribPointer(e,t.size,t.type??jt,t.normalized??!1,t.stride,t.offset??0),r.enableVertexAttribArray(e),Kt(r,e,t.divisor??0)}setAttributes(t){for(const e of t)this.setAttribute(e)}destroy(){this.gl.deleteProgram(this.program)}parseShader(t){const e=this.gl,r=t.match(/(?:in|attribute)\s+\w+\s+\w+/g);if(r)for(const s of r){const h=s.split(/\s+/)[2],o=e.getAttribLocation(this.program,h);o!==-1&&(this.attributeLoc[h]=o)}const i=t.matchAll(/uniform\s+(?:(?:lowp|mediump|highp)\s+)?(\w+)\s+(\w+)(\s*\[\s*\d+\s*\])?/g);for(const s of i){const a=s[1],h=s[2],o=e.getUniformLocation(this.program,h);o!==null&&(this.uniformLoc[h]=o,this.uniformType[h]=a,this.uniformIsArray[h]=s[3]!==void 0)}}}function Qt(n,t,e,r,i=!1){switch(e){case"float":return i?n.uniform1fv(t,r):n.uniform1f(t,r);case"int":case"bool":case"sampler2D":case"samplerCube":return i?n.uniform1iv(t,r):n.uniform1i(t,r);case"vec2":return n.uniform2fv(t,r);case"vec3":return n.uniform3fv(t,r);case"vec4":return n.uniform4fv(t,r);case"ivec2":case"bvec2":return n.uniform2iv(t,r);case"ivec3":case"bvec3":return n.uniform3iv(t,r);case"ivec4":case"bvec4":return n.uniform4iv(t,r);case"mat2":return n.uniformMatrix2fv(t,!1,r);case"mat3":return n.uniformMatrix3fv(t,!1,r);case"mat4":return n.uniformMatrix4fv(t,!1,r);case"mat3x2":return n.uniformMatrix3x2fv(t,!1,r);default:return Zt(n,t,r)}}function Zt(n,t,e){if(typeof e=="number")return n.uniform1f(t,e);const r=e;switch(r.length){case 2:return n.uniform2fv(t,r);case 3:return n.uniform3fv(t,r);case 4:return n.uniform4fv(t,r);case 9:return n.uniformMatrix3fv(t,!1,r);case 16:return n.uniformMatrix4fv(t,!1,r);default:return n.uniform1fv(t,r)}}class rt{vs;fs;glshader=new Map;uniforms={};uniformDirty=new Set;uniformTextures={};uniformArrayTexture={};usedTextureUnitNum=0;padding=0;rapid;prefix=[];constructor(t,e="",r="",i=0,s){this.vs=e,this.fs=r,this.rapid=t,this.uniforms=s??{},this.usedTextureUnitNum=i}setUniforms(t){this.rapid.flush();const e={},r={},i={};for(const[s,a]of Object.entries(t))a instanceof WebGLTexture?r[s]=a:Array.isArray(a)&&a[0]instanceof WebGLTexture?i[s]=a:e[s]=a;Object.assign(this.uniforms,e),Object.assign(this.uniformTextures,r),Object.assign(this.uniformArrayTexture,i);for(const s of this.glshader.keys())this.uniformDirty.add(s)}setPadding(t){this.padding=t;for(const e of this.glshader.values())e.padding=t;return this}applyUniform(t,e){const r=this.glshader.get(t);r&&(Object.keys(e).length>0&&r.setUniforms(e),this.uniformDirty.has(t)&&(r.setUniforms(this.uniforms),this.uniformDirty.delete(t)))}replaceCustomCode(t,e){return t=t.replace("// CUSTOM_CODE",e+"// CUSTOM_CODE"),t}getGLShader(t,e,r,i){if(this.glshader.has(e))return this.glshader.get(e);if(i==null||r==null)return console.warn("CustomGlShader: missing base shader for "+e),null;const s=this.prefix.length==0?[""]:this.prefix;r=r.replace("// CUSTOM_CODE_CALL",s.map(h=>h+"vertex(position, vRegion);").join("")),r=this.replaceCustomCode(r,this.vs),i=i.replace("// CUSTOM_CODE_CALL",s.map(h=>h+"fragment(fragColor, vRegion);").join("")),i=this.replaceCustomCode(i,this.fs);const a=t.createShader(r,i);return a.isCustom=!0,a.padding=this.padding,this.glshader.set(e,a),this.uniformDirty.add(e),a}destroy(){this.glshader.forEach(t=>t.destroy())}}class Rt{constructor(t){this.rapid=t,this.gl=t.gl,this.maxTextureUnits=t.maxTextureUnits,this.matrixStore=t.matrix}defaultShader;currentShader;customShader=null;customShaderUsedTextureNum=0;gl;maxTextureUnits;matrixStore;isDefaultShader=!0;KEY="default";vs="";fs="";usedTextures=[];usedTexturePadding=[];extraTextureUnit=0;createBuffer(){}createDefaultShader(){}get freeTextureUnitNum(){return this.maxTextureUnits-this.usedTextures.length-this.customShaderUsedTextureNum}getTextureUnitList(){return Array.from({length:this.maxTextureUnits},(t,e)=>e)}findTextureUnit(t,e=0,r=0){for(let i=0;i<this.usedTextures.length;i++){const s=i*2;if(this.usedTextures[i]===t&&this.usedTexturePadding[s]===e&&this.usedTexturePadding[s+1]===r)return i}return-1}useTexture(t,e=0,r=0){const i=this.findTextureUnit(t,e,r);return i==-1?(this.freeTextureUnitNum===0&&this.flush(),this.usedTextures.push(t),this.usedTexturePadding.push(e),this.usedTexturePadding.push(r),this.usedTextures.length-1):i}getMaxTexutreUnit(t){return this.rapid.maxTextureUnits-this.extraTextureUnit-(t?.usedTextureUnitNum??0)}createShader(t,e){const r=this.getMaxTexutreUnit();return e=j(e,r),t=j(t,r),new ot(this.gl,t,e)}createCustomShader(t){const e=this.getMaxTexutreUnit(t),r=j(this.fs,e),i=j(this.vs,e);return t.getGLShader(this,this.KEY,i,r)}getCustomShader(t){if(!t)return this.defaultShader;if(t instanceof rt){const e=this.createCustomShader(t);return e??this.defaultShader}return t}isSameShader(t){return this.isDefaultShader&&!t?!0:this.getCustomShader(t)==this.currentShader}enter(t){this.resetRender(),this.currentShader=this.getCustomShader(t),t instanceof rt?(this.customShader=t,this.customShaderUsedTextureNum=t.usedTextureUnitNum):(this.customShader=null,this.customShaderUsedTextureNum=0),this.isDefaultShader=this.currentShader==this.defaultShader,this.currentShader.use(),this.currentShader.setUniform("u_projection",this.rapid.projection)}exit(){this.hasPendingContent()&&this.flush(),this.gl.bindVertexArray(null)}flush(){this.render(),this.resetRender()}render(){this.prepareRender()}prepareRender(){const t=this.currentShader;if(t.use(),this.customShader){const r=this.customShader,i={};for(const[s,a]of Object.entries(r.uniformTextures))i[s]=this.useTexture(a);for(const[s,a]of Object.entries(r.uniformArrayTexture))i[s]=a.map(h=>this.useTexture(h));this.customShader.applyUniform(this.KEY,i)}const e=this.gl;for(let r=0;r<this.usedTextures.length;r++)e.activeTexture(e.TEXTURE0+r),e.bindTexture(e.TEXTURE_2D,this.usedTextures[r]);t.setUniform("uTextures",Int32Array.from({length:this.usedTextures.length},(r,i)=>i)),t.setUniform("uPadding",Float32Array.from({length:this.usedTexturePadding.length},(r,i)=>this.usedTexturePadding[i]))}resetRender(){const t=this.gl;for(let e=0;e<this.usedTextures.length;e++)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,null);this.usedTextures.length=0,this.usedTexturePadding.length=0}hasPendingContent(){return!1}}var S=(n=>(n[n.Float32=0]="Float32",n[n.Uint32=1]="Uint32",n[n.Uint16=2]="Uint16",n))(S||{});class b{usedElemNum;typedArray;arrayType;maxElemNum;bytePerElem;arraybuffer;uint32;float32;uint16;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 0:return Float32Array;case 1:return Uint32Array;case 2:return Uint16Array;default:throw new Error("Unsupported ArrayType")}}updateTypedArray(){switch(this.uint32=new Uint32Array(this.arraybuffer),this.float32=new Float32Array(this.arraybuffer),this.uint16=new Uint16Array(this.arraybuffer),this.arrayType){case 0:this.typedArray=this.float32;break;case 1:this.typedArray=this.uint32;break;case 2:this.typedArray=this.uint16;break}}clear(){this.usedElemNum=0}static removeAtIndices(t,e){const r=Math.max(...e.map(h=>h.usedElemNum)),i=[...new Set(t)].filter(h=>h>=0&&h<r).sort((h,o)=>h-o);if(i.length===0)return 0;let s=0,a=0;for(let h=0;h<r;h++){if(a<i.length&&h===i[a]){a++;continue}if(s!==h)for(const o of e)o.typedArray[s]=o.typedArray[h];s++}for(const h of e)h.usedElemNum=s;return r-s}resize(t=0){if(t+=this.usedElemNum,t>this.maxElemNum){for(;t>this.maxElemNum;)this.maxElemNum*=2;return this.setMaxSize(this.maxElemNum),!0}return!1}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.resize(1),this.uint32[this.usedElemNum++]=t}pushFloat32(t){this.resize(1),this.float32[this.usedElemNum++]=t}push(t){this.resize(1),this.typedArray[this.usedElemNum++]=t}pop(){return this.typedArray[--this.usedElemNum]}top(){return this.typedArray[this.usedElemNum-1]}get(t){return this.typedArray[t]}getArray(t=0,e){return e===void 0?this.typedArray:this.typedArray.subarray(t,e)}get length(){return this.usedElemNum}}class ct extends b{buffer;gl;dirty=!0;type;webglBufferSize=0;usage;constructor(t,e,r=t.ARRAY_BUFFER,i=t.DYNAMIC_DRAW){super(e),this.gl=t,this.buffer=t.createBuffer(),this.type=r,this.usage=i}makeDirty(){this.dirty=!0}clear(){super.clear(),this.dirty=!1}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.maxElemNum*this.bytePerElem,this.usage),this.webglBufferSize=this.maxElemNum),t.bufferSubData(this.type,0,this.getArray(0,this.usedElemNum)),this.dirty=!1}}}const it=`#version 300 es\r
|
|
3
3
|
precision highp float;\r
|
|
4
4
|
\r
|
|
5
5
|
// per-vertex\r
|
|
@@ -47,7 +47,7 @@ void main(void) {\r
|
|
|
47
47
|
\r
|
|
48
48
|
gl_Position = u_projection * position;\r
|
|
49
49
|
}\r
|
|
50
|
-
`,
|
|
50
|
+
`,Et=`#version 300 es\r
|
|
51
51
|
precision mediump float;\r
|
|
52
52
|
\r
|
|
53
53
|
uniform sampler2D uTextures[%TEXTURE_NUM%];\r
|
|
@@ -84,7 +84,7 @@ void main(void) {\r
|
|
|
84
84
|
\r
|
|
85
85
|
// CUSTOM_CODE_CALL\r
|
|
86
86
|
}\r
|
|
87
|
-
`,K=48,
|
|
87
|
+
`,K=48,Jt=new Float32Array([0,0,1,0,0,1,1,1]);class ut extends Rt{instanceBuffer;quadBuffer;instanceCount=0;localSpriteMatrix=new Float32Array(6);worldSpriteMatrix=new Float32Array(6);KEY="Sprite";constructor(t){super(t),this.createBuffer(),this.createDefaultShader()}createBuffer(){const t=this.gl;this.quadBuffer=new ct(t,S.Float32,t.ARRAY_BUFFER,t.STATIC_DRAW),this.quadBuffer.bindBuffer();for(const e of Jt)this.quadBuffer.pushFloat32(e);this.quadBuffer.makeDirty(),this.quadBuffer.bufferData(),this.instanceBuffer=new ct(t,S.Uint32,t.ARRAY_BUFFER,t.DYNAMIC_DRAW)}createDefaultShader(){return this.vs=it,this.fs=Et,this.defaultShader=this.createShader(it,Et),this.defaultShader}createShader(t,e){const r=super.createShader(t,e);return r.use(),r.bindVAO(),this.instanceBuffer.bindBuffer(),r.setAttributes([{name:"aMatrixRow0",size:3,stride:K,offset:0,divisor:1},{name:"aMatrixRow1",size:3,stride:K,offset:12,divisor:1},{name:"aUVRect",size:4,stride:K,offset:24,divisor:1},{name:"aColor",size:4,type:ht,normalized:!0,stride:K,offset:40,divisor:1},{name:"aTextureId",size:1,type:ht,stride:K,offset:44,divisor:1}]),this.quadBuffer.bindBuffer(),r.setAttributes([{name:"aVertex",size:2,stride:8,offset:0,divisor:0}]),r.unbindVAO(),this.currentShader&&this.currentShader.use(),r}drawSprite(t,e,r=0,i=0,s=1,a=1,h=4294967295,o=0,c=0,u=!1,l=!1,m=!1){const d=e*6,x=this.matrixStore.data;this.drawSpriteAffine(t,x[d],x[d+1],x[d+2],x[d+3],x[d+4],x[d+5],r,i,s,a,h,o,c,u,l,m)}drawSpriteAffine(t,e,r,i,s,a,h,o=0,c=0,u=1,l=1,m=4294967295,d=0,x=0,p=!1,y=!1,T=!1){const R=t.base,A=t.rawWidth,L=t.rawHeight,P=t.offsetX,O=t.offsetY,F=this.useTexture(t.glTexture,d/R.width,x/R.height),U=this.instanceBuffer,w=U.usedElemNum;U.resize(12);const _=U.float32,H=U.uint32,G=T?L:A,V=T?A:L,W=G+2*d,D=V+2*x,z=P-d,tt=O-x,E=this.localSpriteMatrix;T?(E[0]=0,E[1]=y?D:-D,E[2]=p?-W:W,E[3]=0,E[4]=z+(p?W:0),E[5]=tt+(y?0:D)):(E[0]=p?-W:W,E[1]=0,E[2]=0,E[3]=y?-D:D,E[4]=z+(p?W:0),E[5]=tt+(y?D:0));const C=this.worldSpriteMatrix;C[0]=e*E[0]+i*E[1],C[1]=r*E[0]+s*E[1],C[2]=e*E[2]+i*E[3],C[3]=r*E[2]+s*E[3],C[4]=a+e*E[4]+i*E[5],C[5]=h+r*E[4]+s*E[5],_[w+6]=o,_[w+7]=c,_[w+8]=u,_[w+9]=l,H[w+10]=m,H[w+11]=F,this.rapid.roundPixels&&(C[4]=Math.round(C[4]),C[5]=Math.round(C[5])),_[w]=C[0],_[w+1]=C[2],_[w+2]=C[4],_[w+3]=C[1],_[w+4]=C[3],_[w+5]=C[5],U.usedElemNum+=12,U.makeDirty(),this.instanceCount++}render(){if(this.instanceCount===0)return;this.prepareRender();const t=this.gl,e=this.currentShader;this.instanceBuffer.bindBuffer(),this.instanceBuffer.bufferData(),e.bindVAO(),Mt(t,t.TRIANGLE_STRIP,0,4,this.instanceCount),this.rapid.drawcallCount++}resetRender(){super.resetRender(),this.instanceBuffer.clear(),this.instanceCount=0}hasPendingContent(){return this.instanceCount>0}}const M=6;class te{matrixCount=0;buffer;data;temporary=-1;constructor(t=10){this.buffer=new b(S.Float32),this.buffer.resize(t*M),this.data=this.buffer.getArray(),this.reset()}alloc(){const t=this.allocDirty();return this.identity(t),t}allocDirty(){return this.buffer.resize(M)&&(this.data=this.buffer.getArray()),this.buffer.usedElemNum+=M,this.matrixCount++}reset(){this.matrixCount=0,this.buffer.usedElemNum=0,this.temporary=this.alloc()}identity(t){const e=t*M,r=this.data;r[e]=1,r[e+1]=0,r[e+2]=0,r[e+3]=1,r[e+4]=0,r[e+5]=0}translate(t,e,r){const i=t*M,s=this.data;s[i+4]=s[i]*e+s[i+2]*r+s[i+4],s[i+5]=s[i+1]*e+s[i+3]*r+s[i+5]}scale(t,e,r){const i=t*M,s=this.data;s[i]*=e,s[i+1]*=e,s[i+2]*=r,s[i+3]*=r}rotate(t,e){const r=t*M,i=this.data,s=Math.cos(e),a=Math.sin(e),h=i[r],o=i[r+1],c=i[r+2],u=i[r+3];i[r]=h*s+c*a,i[r+1]=o*s+u*a,i[r+2]=h*-a+c*s,i[r+3]=o*-a+u*s}rotateWithOffset(t,e,r,i){this.translate(t,r,i),this.rotate(t,e),this.translate(t,-r,-i)}copy(t,e){const r=t*M,i=e*M,s=this.data;s[r]=s[i],s[r+1]=s[i+1],s[r+2]=s[i+2],s[r+3]=s[i+3],s[r+4]=s[i+4],s[r+5]=s[i+5]}multiply(t,e){this.multiplyOut(t,t,e)}multiplyOut(t,e,r){const i=t*M,s=e*M,a=r*M,h=this.data,o=h[s],c=h[s+1],u=h[s+2],l=h[s+3],m=h[s+4],d=h[s+5],x=h[a],p=h[a+1],y=h[a+2],T=h[a+3],R=h[a+4],A=h[a+5];h[i]=o*x+u*p,h[i+1]=c*x+l*p,h[i+2]=o*y+u*T,h[i+3]=c*y+l*T,h[i+4]=o*R+u*A+m,h[i+5]=c*R+l*A+d}invert(t){const e=t*M,r=this.data,i=r[e],s=r[e+1],a=r[e+2],h=r[e+3],o=r[e+4],c=r[e+5];let u=i*h-s*a;if(!u){this.identity(t);return}u=1/u,r[e]=h*u,r[e+1]=-s*u,r[e+2]=-a*u,r[e+3]=i*u,r[e+4]=(a*c-h*o)*u,r[e+5]=(s*o-i*c)*u}transformPoint(t,e,r){const i=t*M,s=this.data;return{x:e*s[i]+r*s[i+2]+s[i+4],y:e*s[i+1]+r*s[i+3]+s[i+5]}}worldToLocal(t,e,r){const i=this.allocDirty();this.copy(i,t),this.invert(i);const s=this.transformPoint(i,e,r);return this.matrixCount--,this.buffer.usedElemNum-=M,s}localToWorld(t,e,r){return this.transformPoint(t,e,r)}getPosition(t){const e=t*M,r=this.data;return{x:r[e+4],y:r[e+5]}}getScale(t){const e=t*M,r=this.data,i=Math.sqrt(r[e]*r[e]+r[e+1]*r[e+1]),s=Math.sqrt(r[e+2]*r[e+2]+r[e+3]*r[e+3]);return{x:i,y:s}}getRotation(t){const e=t*M,r=this.data;return Math.atan2(r[e+1],r[e])}toCSSMatrix(t,e=1,r=1){const i=t*M,s=this.data;return`matrix(${s[i]*e}, ${s[i+1]*r}, ${s[i+2]*e}, ${s[i+3]*r}, ${s[i+4]*e}, ${s[i+5]*r})`}getMatrix(t){const e=t*M;return this.data.slice(e,e+M)}getMatrixRef(t){const e=t*M;return this.data.subarray(e,e+M)}setMatrix(t,e){const r=t*M,i=this.data;i[r]=e[0],i[r+1]=e[1],i[r+2]=e[2],i[r+3]=e[3],i[r+4]=e[4],i[r+5]=e[5]}multiplyAffineInPlace(t,e,r,i,s,a,h){const o=t*6,c=this.data,u=c[o],l=c[o+1],m=c[o+2],d=c[o+3],x=c[o+4],p=c[o+5];c[o]=u*e+m*r,c[o+1]=l*e+d*r,c[o+2]=u*i+m*s,c[o+3]=l*i+d*s,c[o+4]=u*a+m*h+x,c[o+5]=l*a+d*h+p}multiplyAffine(t,e,r,i,s,a,h,o){const c=t*6,u=e*6,l=this.data,m=l[c],d=l[c+1],x=l[c+2],p=l[c+3],y=l[c+4],T=l[c+5];l[u]=m*r+x*i,l[u+1]=d*r+p*i,l[u+2]=m*s+x*a,l[u+3]=d*s+p*a,l[u+4]=m*h+x*o+y,l[u+5]=d*h+p*o+T}}class ee{matrix=new te;step=0;stack=new b(S.Uint32);stepWorldM=new b(S.Uint32);stepAction=new b(S.Uint32);stepParentM=new b(S.Uint32);stepClose=new b(S.Uint32);stepStack=new b(S.Uint32);curLocalM=-1;curWorldM=-1;rapid;constructor(t){this.reset(),this.rapid=t}save(){this.stack.push(this.curWorldM);const t=this.curWorldM;return this.curLocalM=this.matrix.alloc(),this.curWorldM=this.matrix.allocDirty(),this.stepWorldM.push(this.curWorldM),this.stepParentM.push(t),this.stepAction.push(1),this.stepClose.push(0),this.stepStack.push(this.step),this.matrix.copy(this.curWorldM,t),{world:this.curWorldM,local:this.curLocalM,step:this.step++}}restore(){this.stack.length==0||this.stepStack.length==0||(this.curWorldM=this.stack.pop(),this.curLocalM=this.curWorldM-1,this.stepParentM.push(this.stack.get(this.stack.length-1)),this.stepWorldM.push(this.curWorldM),this.stepAction.push(0),this.stepClose.push(0),this.stepClose.typedArray[this.stepStack.pop()]=this.step,this.step++)}restoreAll(){for(;this.stack.length>0&&this.stepStack.length>0;)this.restore()}getStep(t){return typeof t=="number"?t:t.step}walkSubtree(t,e,r=1/0){let i=0,s=t;for(;s<this.step;){const a=this.stepAction.get(s);if(a===1){if(i++,i>r){const h=this.stepClose.get(s);if(h>s){s=h+1,i--;continue}}}else i--;if(e(s,a,i)===!1||a===0&&i===0)return;s++}}getParent(t){const e=this.getStep(t);return this.stepParentM.get(e)}getChildren(t){const e=this.getStep(t),r=this.stepClose.get(e),i=[];let s=e+1;for(;s<r;)this.stepAction.get(s)===1?(i.push(s),s=this.stepClose.get(s)+1):s++;return i}updateMatrixSubtree(t){const e=this.getStep(t);this.walkSubtree(e,(r,i)=>{if(i===1){const s=this.stepWorldM.get(r),a=s-1,h=this.stepParentM.get(r);this.matrix.multiplyOut(s,h,a)}})}translate(t,e){this.matrix.translate(this.curLocalM,t,e),this.matrix.translate(this.curWorldM,t,e)}scale(t,e=t){this.matrix.scale(this.curLocalM,t,e),this.matrix.scale(this.curWorldM,t,e)}rotate(t){this.matrix.rotate(this.curLocalM,t),this.matrix.rotate(this.curWorldM,t)}rotateWithOffset(t,e,r){this.matrix.rotateWithOffset(this.curLocalM,t,e,r),this.matrix.rotateWithOffset(this.curWorldM,t,e,r)}identity(){this.matrix.identity(this.curLocalM),this.matrix.identity(this.curWorldM)}reset(){this.matrix.reset(),this.stack.clear(),this.stepAction.clear(),this.stepWorldM.clear(),this.stepParentM.clear(),this.stepClose.clear(),this.stepStack.clear(),this.step=0,this.curLocalM=this.matrix.alloc(),this.curWorldM=this.matrix.alloc()}localToWorld(t,e){return this.matrix.localToWorld(this.curWorldM,t,e)}worldToLocal(t,e){return this.matrix.worldToLocal(this.curWorldM,t,e)}getGlobalPosition(){return this.matrix.getPosition(this.curWorldM)}getGlobalScale(){return this.matrix.getScale(this.curWorldM)}getGlobalRotation(){return this.matrix.getRotation(this.curWorldM)}toCSSMatrix(){return this.matrix.toCSSMatrix(this.curWorldM)}getTransform(){const t=this.curWorldM*M;return this.matrix.data.slice(t,t+M)}setTransform(t){const e=this.curWorldM*M,r=this.matrix.data;r[e]=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]}transformPoint(t,e){return this.matrix.transformPoint(this.curLocalM,t,e)}applyTransform(t,e=0,r=0,i=-1){let s=t.x??0,a=t.y??0;t.position&&(s+=t.position.x,a+=t.position.y);let h=1,o=1;const c=t.scale;c&&(typeof c=="number"?(h=c,o=c):(h=c.x,o=c.y));const u=t.rotation??0;let l=t.offsetX??0,m=t.offsetY??0;t.offset&&(l+=t.offset.x,m+=t.offset.y);const d=t.origin;d!==void 0&&(typeof d=="number"?(l-=d*e,m-=d*r):(l-=d.x*e,m-=d.y*r));const x=u?Math.cos(u):1,p=u?Math.sin(u):0,y=x*h,T=p*h,R=-p*o,A=x*o,L=s+y*l+R*m,P=a+T*l+A*m;if(i!==-1){this.matrix.multiplyAffine(this.curWorldM,i,y,T,R,A,L,P);return}this.matrix.multiplyAffineInPlace(this.curLocalM,y,T,R,A,L,P),this.matrix.multiplyAffineInPlace(this.curWorldM,y,T,R,A,L,P)}}const re=`#version 300 es\r
|
|
88
88
|
precision highp float;\r
|
|
89
89
|
\r
|
|
90
90
|
in vec2 aPosition;\r
|
|
@@ -115,7 +115,7 @@ void main(void) {\r
|
|
|
115
115
|
// CUSTOM_CODE_CALL\r
|
|
116
116
|
gl_Position = u_projection * position;\r
|
|
117
117
|
}\r
|
|
118
|
-
`,
|
|
118
|
+
`,ie=`#version 300 es\r
|
|
119
119
|
precision mediump float;\r
|
|
120
120
|
\r
|
|
121
121
|
in vec4 vColor;\r
|
|
@@ -123,6 +123,7 @@ in vec2 vRegion;\r
|
|
|
123
123
|
in vec4 vUVRect;\r
|
|
124
124
|
\r
|
|
125
125
|
uniform sampler2D uTexture;\r
|
|
126
|
+
uniform sampler2D uTextures[%TEXTURE_NUM%];\r
|
|
126
127
|
uniform int uUseTexture;\r
|
|
127
128
|
\r
|
|
128
129
|
out vec4 fragColor;\r
|
|
@@ -161,7 +162,7 @@ void main(void) {\r
|
|
|
161
162
|
fragColor = sampleTexture(vRegion) * vColor;\r
|
|
162
163
|
// CUSTOM_CODE_CALL\r
|
|
163
164
|
}\r
|
|
164
|
-
`,
|
|
165
|
+
`,se=`#version 300 es\r
|
|
165
166
|
precision highp float;\r
|
|
166
167
|
\r
|
|
167
168
|
in vec2 aPosition;\r
|
|
@@ -184,7 +185,7 @@ void main(void) {\r
|
|
|
184
185
|
);\r
|
|
185
186
|
gl_Position = u_projection * position;\r
|
|
186
187
|
}\r
|
|
187
|
-
`,
|
|
188
|
+
`,ne=`#version 300 es\r
|
|
188
189
|
precision mediump float;\r
|
|
189
190
|
\r
|
|
190
191
|
in vec2 vRegion;\r
|
|
@@ -204,7 +205,7 @@ void main(void) {\r
|
|
|
204
205
|
discard;\r
|
|
205
206
|
}\r
|
|
206
207
|
}\r
|
|
207
|
-
`,q=20;class
|
|
208
|
+
`,q=20;class ae extends Rt{vertexBuffer;vertexCount=0;extraTextureUnit=1;matrixIndex=-1;drawMode=this.gl.TRIANGLES;texture;maskShader;KEY="Graphic";constructor(t){super(t),this.createBuffer(),this.createDefaultShader()}createBuffer(){const t=this.gl;this.vertexBuffer=new ct(t,S.Float32,t.ARRAY_BUFFER,t.DYNAMIC_DRAW),this.maskShader=this.createMaskShader(se,ne)}createDefaultShader(){return this.vs=re,this.fs=ie,this.defaultShader=this.createShader(this.vs,this.fs),this.defaultShader}createMaskShader(t,e){const r=this.gl,i=new ot(r,t,e);return i.use(),i.bindVAO(),this.vertexBuffer.bindBuffer(),i.setAttributes([{name:"aPosition",size:2,type:r.FLOAT,stride:q-4,offset:0,divisor:0},{name:"aUV",size:2,type:r.FLOAT,stride:q-4,offset:8,divisor:0}]),i.unbindVAO(),this.currentShader&&this.currentShader.use(),i}createShader(t,e){const r=this.gl,i=super.createShader(t,e);return i.use(),i.bindVAO(),this.vertexBuffer.bindBuffer(),i.setAttributes([{name:"aPosition",size:2,type:r.FLOAT,stride:q,offset:0,divisor:0},{name:"aColor",size:4,type:r.UNSIGNED_BYTE,normalized:!0,stride:q,offset:8,divisor:0},{name:"aUV",size:2,type:r.FLOAT,stride:q,offset:12,divisor:0}]),i.unbindVAO(),this.currentShader&&this.currentShader.use(),i}startGraphic(t,e=this.gl.TRIANGLES,r){this.vertexBuffer.clear(),this.vertexCount=0,this.matrixIndex=t,this.drawMode=e,this.texture=r,this.texture?.glTexture&&this.useTexture(this.texture.glTexture,0,0)}addVertex(t,e,r=0,i=0,s=4294967295){const a=this.vertexBuffer;a.pushFloat32(t),a.pushFloat32(e),this.currentShader!=this.maskShader&&a.pushUint32(s),a.pushFloat32(r),a.pushFloat32(i),this.vertexCount++,this.vertexBuffer.makeDirty()}endGraphic(){this.flush()}render(){if(this.vertexCount===0)return;this.prepareRender();const t=this.gl,e=this.currentShader,r=this.matrixIndex*6,i=this.matrixStore.data;let s=i[r+4],a=i[r+5];this.rapid.roundPixels&&(s=Math.round(s),a=Math.round(a)),e.setUniform("uMatrixRow0",[i[r],i[r+2],s]),e.setUniform("uMatrixRow1",[i[r+1],i[r+3],a]),e.setUniform("uUVRect",this.texture?[this.texture.uvX,this.texture.uvY,this.texture.uvW,this.texture.uvH]:[0,0,1,1]),this.texture?.glTexture?(t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.texture.glTexture),e.setUniform("uTexture",0),e.setUniform("uUseTexture",1)):e.setUniform("uUseTexture",0),this.vertexBuffer.bindBuffer(),this.vertexBuffer.bufferData(),e.bindVAO(),t.drawArrays(this.drawMode,0,this.vertexCount),this.rapid.drawcallCount++,this.texture=void 0}hasPendingContent(){return!1}}class g{x;y;static ZERO=new g(0,0);static ONE=new g(1,1);static UP=new g(0,1);static DOWN=new g(0,-1);static LEFT=new g(-1,0);static RIGHT=new g(1,0);constructor(t,e){this.x=t!==void 0?t:0,this.y=e!==void 0?e:0}set(t,e){return e===void 0?(this.x=t,this.y=t):(this.x=t,this.y=e),this}add(t){return new g(this.x+t.x,this.y+t.y)}subtract(t){return new g(this.x-t.x,this.y-t.y)}multiply(t){return t instanceof g?new g(this.x*t.x,this.y*t.y):new g(this.x*t,this.y*t)}divide(t){return t instanceof g?new g(this.x/t.x,this.y/t.y):new g(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 g(this.x,this.y)}to(t){this.x=t.x,this.y=t.y}equals(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}inverted(){return new g(this.x*-1,this.y*-1)}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}squaredLength(){return 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}normalized(){const t=this.length();return new g(this.x/t||0,this.y/t||0)}fix(t=1e-13){this.x=Math.abs(this.x)<t?0:this.x,this.y=Math.abs(this.y)<t?0:this.y}fixed(t=1e-13){return new g(Math.abs(this.x)<t?0:this.x,Math.abs(this.y)<t?0:this.y)}angle(){return Math.atan2(this.y,this.x)}abs(){return new g(Math.abs(this.x),Math.abs(this.y))}floor(){return new g(Math.floor(this.x),Math.floor(this.y))}ceil(){return new g(Math.ceil(this.x),Math.ceil(this.y))}stringify(){return`Vec2(${this.x}, ${this.y})`}clear(){this.x=0,this.y=0}isPrettyMuchZero(){return Math.abs(this.x)<1e-4&&Math.abs(this.y)<1e-4}isZero(){return this.x==0&&this.y==0}isNotZero(){return this.x!==0||this.y!==0}setToPolar(t,e=1){return this.x=Math.cos(t)*e,this.y=Math.sin(t)*e,this}static FromArray(t){return t.map(e=>new g(e[0],e[1]))}static fromAngle(t){return new g(Math.cos(t),Math.sin(t))}}const wt=(n,t)=>{const[e,r,i,s,a,h]=t,o=new Float32Array([e,i,0,0,r,s,0,0,0,0,1,0,a,h,0,1]);return St(o,n)},St=(n,t)=>{const e=new Float32Array(16);for(let r=0;r<4;r++)for(let i=0;i<4;i++){let s=0;for(let a=0;a<4;a++)s+=n[i*4+a]*t[a*4+r];e[i*4+r]=s}return e};var At=(n=>(n[n.STRETCH=0]="STRETCH",n[n.REPEAT=1]="REPEAT",n))(At||{});const lt=10,bt=(n,t,e,r,i,s)=>{const a=[],h=[],o=r?Math.atan2(t.y,t.x):Math.atan2(-t.y,-t.x),c=Math.PI,u=new g(t.y,-t.x);for(let l=0;l<lt;l++){const m=l/lt,d=(l+1)/lt,x=o+m*c,p=o+d*c,y=new g(Math.cos(x)*e,Math.sin(x)*e),T=new g(Math.cos(p)*e,Math.sin(p)*e);a.push(n),h.push(new g(i,.5)),a.push(n.add(y)),h.push(new g(i+y.dot(u)*s,.5-.5*y.dot(t)/e)),a.push(n.add(T)),h.push(new g(i+T.dot(u)*s,.5-.5*T.dot(t)/e))}return{vertices:a,uv:h}},Ut=(n,t=!1)=>{const e=[];if(n.length<2||t&&n.length<3)return{normals:e,length:0};const r=4,i=.001,s=n.length;let a=0;if(t)for(let o=0;o<s;o++){const c=n[o],u=n[(o+1)%s];a+=c.distanceTo(u)}else for(let o=0;o<s-1;o++)a+=n[o].distanceTo(n[o+1]);const h=(o,c,u)=>{const l=c.subtract(o).normalize(),m=c.subtract(u).normalize(),d=m.dot(l);if(d<-1+i)return{normal:l.perpendicular(),miters:1};{let x=m.add(l).normalize();l.cross(m)<0&&(x=x.multiply(-1));let p=1/Math.sqrt((1-d)/2);return{normal:x,miters:Math.min(p,r)}}};if(t)for(let o=0;o<s;o++){const c=o===0?n[s-1]:n[o-1],u=n[o],l=o===s-1?n[0]:n[o+1];e.push(h(c,u,l))}else for(let o=0;o<s;o++)if(o===0){const c=n[1].subtract(n[0]).normalize();e.push({normal:c.perpendicular(),miters:1})}else if(o===s-1){const c=n[o].subtract(n[o-1]).normalize();e.push({normal:c.perpendicular(),miters:1})}else e.push(h(n[o-1],n[o],n[o+1]));return{normals:e,length:a}},Ct=n=>{const t=n.points;if(t.length<2)return{vertices:[],uv:[]};const{normals:e,length:r}=Ut(t,n.closed),i=(n.width||1)/2,s=[],a=[],h=n.roundCap||!1,o=n.textureMode||0;let c=0;const u=n.texture?.rawWidth||1,l=n.closed?t.length:t.length-1;for(let m=0;m<l;m++){const d=t[m],x=e[m].normal,p=e[m].miters,y=(m+1)%t.length,T=t[y],R=e[y].normal,A=e[y].miters,L=d.add(x.multiply(p*i)),P=d.subtract(x.multiply(p*i)),O=T.add(R.multiply(A*i)),F=T.subtract(R.multiply(A*i)),U=d.distanceTo(T);let w=0,_=0;o===0?(w=c/r,_=(c+U)/r):(w=c/u,_=w+U/u);const H=new g(w,0),G=new g(w,1),V=new g(_,0),W=new g(_,1);s.push(L),a.push(H),s.push(P),a.push(G),s.push(O),a.push(V),s.push(O),a.push(V),s.push(F),a.push(W),s.push(P),a.push(G),c+=U}if(h&&!n.closed){const m=t[0],d=e[0].normal,x=o===0?r>0?1/r:0:1/u,p=bt(m,d,i,!0,0,x);s.push(...p.vertices),a.push(...p.uv);const y=t[t.length-1],T=e[t.length-1].normal,R=o===0?1:c/u,A=o===0?r>0?1/r:0:1/u,L=bt(y,T,i,!1,R,A);s.push(...L.vertices),a.push(...L.uv)}return{vertices:s,uv:a}},Q=(n,t,e,r)=>{if(t.customMatrix!==void 0)return t.customMatrix;if(t.modifyStack){n.matrixStack.applyTransform(t,e,r);return}else{const i=n.matrix.temporary;return n.matrixStack.applyTransform(t,e,r,i),i}},_t=(n,t)=>t?n?t.premultipliedUint32:t.uint32:4294967295,he=2,Lt=(n,t)=>{const e=Q(n,t,t.texture.rawWidth,t.texture.rawHeight),r=t.texture;if(!r?.base||n.inCreateMask)return;const i=r.isAtlas?n.atlasSpriteRegion:n.spriteRegion;n.enterRegion(i,t.shader);let s=r.uvX,a=r.uvY,h=r.uvW,o=r.uvH;const c=!!t.flipX,u=!!t.flipY!=!!r.flipY;let l=t.padding??i.currentShader.padding;r.isAtlas&&(l+=he);const m=s<=h?l:-l,d=a<=o?l:-l;i.drawSprite(r,e??t.customMatrix??n.matrixStack.curWorldM,s,a,h,o,n.getColorUint32(t.color),m,d,c,u,r.isRotated)},Pt=(n,t)=>{const e=n.particleRegion;n.enterRegion(e,t.shader);const r=t.texture,i=t.count??t.x.length,s=t.color;e.drawParticles(r,t.x,t.y,t.rotation,s,i,t.scaleX,t.scaleY,t.u0??r.uvX,t.v0??r.uvY,t.u1??r.uvW,t.v1??r.uvH,t.flipX,t.flipY,r.isRotated,t.originX,t.originY,n.premultipliedAlpha,t.reverseOrder,t.customMatrix)},dt=(n,t)=>{if(t.points.length===0)return;const e=Q(n,t,0,0);n.startGraphic(t.drawMode??n.gl.TRIANGLES,t.texture,t.shader,e??t.customMatrix);for(let r=0;r<t.points.length;r++){const i=t.points[r],s=t.uv?.[r],a=Array.isArray(t.color)?t.color[r]:t.color;n.addGraphicVertex(i.x,i.y,s?.x??0,s?.y??0,n.getColorUint32(a))}n.endGraphic()},Nt=(n,t)=>{if(n.inCreateMask)return;const{vertices:e,uv:r}=Ct(t);dt(n,{...t,points:e,uv:r,drawMode:n.gl.TRIANGLES})},It=(n,t)=>{const e=Q(n,t,t.texture.rawWidth,t.texture.rawHeight);n.startMaskGraphic(n.gl.TRIANGLE_FAN,t.texture,e??t.customMatrix),n.addRectVertex(t.texture.rawWidth,t.texture.rawHeight),n.endGraphic()},Wt=(n,t)=>{const e=Q(n,t,t.width,t.height);n.startGraphic(n.gl.TRIANGLE_FAN,t.texture,t.shader,e??t.customMatrix),n.addRectVertex(t.width,t.height,t.color),n.endGraphic()},Ot=(n,t)=>{const e=t.segments??32,r=Q(n,t,0,0);n.startGraphic(n.gl.TRIANGLE_FAN,void 0,t.shader,r??t.customMatrix);const i=n.getColorUint32(t.color);n.addGraphicVertex(0,0,.5,.5,i),n.addCircleVertex(t.radius,t.color,e),n.addGraphicVertex(t.radius,0,1,.5,i),n.endGraphic()},Ft=`#version 300 es\r
|
|
208
209
|
precision mediump float;\r
|
|
209
210
|
\r
|
|
210
211
|
uniform sampler2D uTextures[%TEXTURE_NUM%];\r
|
|
@@ -247,7 +248,7 @@ void main(void) {\r
|
|
|
247
248
|
\r
|
|
248
249
|
// CUSTOM_CODE_CALL\r
|
|
249
250
|
}\r
|
|
250
|
-
`;class
|
|
251
|
+
`;class oe extends ut{KEY="AtlasSprite";constructor(t){super(t)}createDefaultShader(){return this.vs=it,this.fs=Ft,this.defaultShader=this.createShader(it,Ft),this.defaultShader}}const ce=`#version 300 es\r
|
|
251
252
|
precision highp float;\r
|
|
252
253
|
\r
|
|
253
254
|
// per-vertex\r
|
|
@@ -274,23 +275,21 @@ void main(void) {\r
|
|
|
274
275
|
vColor = aColor;\r
|
|
275
276
|
\r
|
|
276
277
|
vRegion = aUVRect.xy + aVertex * (aUVRect.zw - aUVRect.xy);\r
|
|
277
|
-
// CUSTOM_CODE_CALL\r
|
|
278
278
|
\r
|
|
279
279
|
vec2 scaled = (aVertex - aOrigin) * aScale;\r
|
|
280
280
|
float c = cos(aRotation);\r
|
|
281
281
|
float s = sin(aRotation);\r
|
|
282
282
|
\r
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
scaled.x * s + scaled.y * c\r
|
|
286
|
-
) + aPosition;\r
|
|
283
|
+
vec4 position = vec4(mat2(c, s, -s, c) * scaled + aPosition, 0.0, 1.0);\r
|
|
284
|
+
// CUSTOM_CODE_CALL\r
|
|
287
285
|
\r
|
|
288
|
-
gl_Position = u_projection *
|
|
286
|
+
gl_Position = u_projection * position;\r
|
|
289
287
|
}\r
|
|
290
|
-
`,
|
|
288
|
+
`,ue=`#version 300 es\r
|
|
291
289
|
precision mediump float;\r
|
|
292
290
|
\r
|
|
293
291
|
uniform sampler2D uTexture;\r
|
|
292
|
+
uniform sampler2D uTextures[%TEXTURE_NUM%];\r
|
|
294
293
|
\r
|
|
295
294
|
in vec2 vRegion;\r
|
|
296
295
|
in vec4 vColor;\r
|
|
@@ -303,7 +302,7 @@ void main(void) {\r
|
|
|
303
302
|
\r
|
|
304
303
|
// CUSTOM_CODE_CALL\r
|
|
305
304
|
}\r
|
|
306
|
-
`,
|
|
305
|
+
`,k=48,le=k/4;class de extends ut{KEY="ParticleSprite";texture;customMatrix;particleLoopCache=new Map;extraTextureUnit=1;constructor(t){super(t)}createDefaultShader(){const t=ue,e=ce;return this.vs=e,this.fs=t,this.defaultShader=this.createShader(e,t),this.defaultShader}enter(t){super.enter(t),this.currentShader.setUniform("u_projection",this.rapid.projection)}createShader(t,e){const r=super.createShader(t,e);return r.use(),r.bindVAO(),this.instanceBuffer.bindBuffer(),r.setAttributes([{name:"aPosition",size:2,stride:k,offset:0,divisor:1},{name:"aScale",size:2,stride:k,offset:8,divisor:1},{name:"aRotation",size:1,stride:k,offset:16,divisor:1},{name:"aUVRect",size:4,stride:k,offset:20,divisor:1},{name:"aColor",size:4,type:ht,normalized:!0,stride:k,offset:36,divisor:1},{name:"aOrigin",size:2,stride:k,offset:40,divisor:1}]),this.quadBuffer.bindBuffer(),r.setAttributes([{name:"aVertex",size:2,stride:8,offset:0,divisor:0}]),r.unbindVAO(),this.currentShader&&this.currentShader.use(),r}drawParticles(t,e,r,i=0,s=4294967295,a,h=1,o=1,c=0,u=0,l=1,m=1,d=!1,x=!1,p=!1,y=.5,T=.5,R,A=!1,L){if(!t.glTexture||a<=0)return;this.texture&&t!==this.texture&&this.flush();const P=typeof h=="number",O=typeof o=="number",F=typeof i=="number",U=typeof s=="number",w=typeof c=="number",_=!U&&typeof s[0]=="number",H=t.uvW-t.uvX,G=t.uvH-t.uvY,V=H===0?0:1/H,W=G===0?0:1/G;let D=t.rawWidth*(d?-1:1);P&&(D*=h);let z=t.rawHeight*(x?-1:1);O&&(z*=o),w&&(D*=(l-c)*V,z*=(m-u)*W);let tt=p?Math.PI/2:0;F&&(tt+=i);const E=s??4294967295,C=this.getParticleLoop(P,O,F,w,U,_,A,R);this.texture||(this.texture=t,this.useTexture(t.glTexture,0,0));const xt=a,Y=this.instanceBuffer;let gt=Y.usedElemNum;Y.resize(xt*le);const ve=Y.float32,ye=Y.uint32;gt=C(e,r,h,o,i,c,u,l,m,s,ve,ye,D,z,V,W,tt,E,y,T,a,xt,gt),Y.usedElemNum=gt,Y.makeDirty(),this.instanceCount+=xt,this.customMatrix=L,this.flush()}getParticleLoop(t,e,r,i,s,a,h,o){const c=[...arguments].join("_");if(this.particleLoopCache.has(c))return this.particleLoopCache.get(c);let u=`
|
|
307
306
|
return function( x, y, scaleX, scaleY, rotation, u0, v0, u1, v1, color, f32, u32, rawWidth, rawHeight, uv2texW, uv2texH, rotationOffset, staticColor, originX, originY, count, batchCount, index ) {
|
|
308
307
|
${t&&i?"const baseSx = rawWidth;":""}
|
|
309
308
|
${e&&i?"const baseSy = rawHeight;":""}
|
|
@@ -342,7 +341,7 @@ f32[idx + 11] = originY;
|
|
|
342
341
|
}
|
|
343
342
|
return idx;
|
|
344
343
|
}
|
|
345
|
-
`;const l=new Function(u)();return this.particleLoopCache.set(c,l),l}render(){if(this.instanceCount===0)return;this.prepareRender();const t=this.gl;this.texture&&(t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.texture.glTexture));const e=this.currentShader;this.instanceBuffer.bindBuffer(),this.instanceBuffer.bufferData(),e.bindVAO();const r=this.rapid.matrixStack,s=this.rapid.matrix.getMatrix(this.customMatrix??r.curWorldM),a=Rt(this.rapid.projection,s);this.currentShader.setUniform("u_projection",a),Tt(t,t.TRIANGLE_STRIP,0,4,this.instanceCount),this.rapid.drawcallCount++,this.texture=void 0,this.customMatrix=void 0}}var dt=(n=>(n[n.EQUAL=0]="EQUAL",n[n.NOT_EQUAL=1]="NOT_EQUAL",n))(dt||{}),Nt=(n=>(n[n.NORMAL=0]="NORMAL",n[n.ADD=1]="ADD",n[n.MULTIPLY=2]="MULTIPLY",n[n.SCREEN=3]="SCREEN",n[n.ERASE=4]="ERASE",n))(Nt||{}),It=(n=>(n[n.CanvasItem=0]="CanvasItem",n[n.Viewport=1]="Viewport",n))(It||{});class fe{gl;canvas;projection=new Float32Array(16);projectionDirty=!0;dpr;backgroundColor=f.Black;logicWidth=0;logicHeight=0;physicsWidth=0;physicsHeight=0;currentRegion=null;maxTextureUnits=0;matrixStack=new qt(this);matrix;spriteRegion;graphicRegion;atlasSpriteRegion;particleRegion;drawcallCount=0;inCreateMask=!1;texture;premultipliedAlpha;antialias;roundPixels;textureFilter;scaleMode;_filterRT=[null,null];_filterInput=new N;get height(){return this.logicHeight}get width(){return this.logicWidth}constructor(t){this.canvas=t.canvas,this.dpr=window.devicePixelRatio||1,this.antialias=t.antialias??!1,this.textureFilter=t.textureFilter??j.NEAREST,this.premultipliedAlpha=t.premultipliedAlpha??!0,this.roundPixels=t.roundPixels??!1,this.scaleMode=t.scaleMode??0;const e=Ht(this.canvas,this.antialias,this.premultipliedAlpha);this.gl=e,this.maxTextureUnits=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.matrix=this.matrixStack.matrix,this.spriteRegion=new ut(this),this.graphicRegion=new ee(this),this.atlasSpriteRegion=new ue(this),this.particleRegion=new de(this);const r=this.canvas.clientWidth||this.canvas.width,i=this.canvas.clientHeight||this.canvas.height;this.physicsWidth=t.physicsWidth||Math.round(r*this.dpr),this.physicsHeight=t.physicsHeight||Math.round(i*this.dpr),this.logicWidth=t.logicWidth||t.width||this.physicsWidth/this.dpr,this.logicHeight=t.logicHeight||t.height||this.physicsHeight/this.dpr,this.resize(this.logicWidth,this.logicHeight,this.physicsWidth,this.physicsHeight),this.texture=new gt(this),t.backgroundColor&&(this.backgroundColor=t.backgroundColor),e.enable(e.BLEND),this.premultipliedAlpha?e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA):e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.enable(e.STENCIL_TEST),e.stencilFunc(e.ALWAYS,1,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP)}setTextureFilter(t){this.textureFilter=t}getColorUint32(t){return re(this.premultipliedAlpha,t)}enterRegion(t,e){this.currentRegion===t&&this.currentRegion.isSameShader(e)||(this.flush(),this.currentRegion=t,t.enter(e))}drawParticles(t){ne(this,t)}drawSprite(t){se(this,t)}drawLine(t){ae(this,t)}drawGraphic(t){Ct(this,t)}drawRect(t){oe(this,t)}drawCircle(t){ce(this,t)}startGraphic(t=this.gl.TRIANGLES,e,r,i){this.enterRegion(this.graphicRegion,r),this.graphicRegion.startGraphic(i??this.matrixStack.curWorldM,t,e)}startMaskGraphic(t=this.gl.TRIANGLES,e,r){this.startGraphic(t,e,this.graphicRegion.maskShader,r)}drawMaskImage(t){he(this,t)}addRectVertex(t,e,r){const i=this.getColorUint32(r);this.addGraphicVertex(0,0,0,0,i),this.addGraphicVertex(t,0,1,0,i),this.addGraphicVertex(t,e,1,1,i),this.addGraphicVertex(0,e,0,1,i)}addCircleVertex(t,e,r=32){const i=Math.PI*2/r,s=this.getColorUint32(e);for(let a=0;a<r;a++){const h=i*a,o=Math.cos(h)*t,c=Math.sin(h)*t,u=.5+Math.cos(h)*.5,l=.5+Math.sin(h)*.5;this.addGraphicVertex(o,c,u,l,s)}}addGraphicVertex(t,e,r=0,i=0,s=4294967295){this.graphicRegion.addVertex(t,e,r,i,typeof s=="number"?s:this.getColorUint32(s))}endGraphic(){this.graphicRegion.endGraphic()}resize(t,e,r,i){this.flush();const s=r??this.canvas.clientWidth??this.canvas.width,a=i??this.canvas.clientHeight??this.canvas.height;switch(r!==void 0&&(this.canvas.style.width=s+"px"),i!==void 0&&(this.canvas.style.height=a+"px"),this.physicsWidth=s*this.dpr,this.physicsHeight=a*this.dpr,this.logicWidth=t,this.logicHeight=e,this.scaleMode){case 1:this.canvas.width=t,this.canvas.height=e,this.canvas.style.imageRendering="pixelated",this.gl.viewport(0,0,t,e);break;case 0:this.canvas.width=this.physicsWidth,this.canvas.height=this.physicsHeight,this.canvas.style.imageRendering="auto",this.gl.viewport(0,0,this.physicsWidth,this.physicsHeight);break;default:throw new Error("scaleMode can only be CanvasScaleMode.Viewport or CanvasScaleMode.CanvasItem")}this.updateProjection(0,this.logicWidth,this.logicHeight,0)}updateProjection(t,e,r,i){this.updateOrthMatrix(this.projection,t,e,r,i),this.projectionDirty=!0}clear(){const t=this.gl;this.backgroundColor.setClearColor(t),t.clear(t.COLOR_BUFFER_BIT|t.STENCIL_BUFFER_BIT),this.drawcallCount=0,this.matrixStack.reset()}updateOrthMatrix(t,e,r,i,s){t[0]=2/(r-e),t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2/(s-i),t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=-1,t[11]=0,t[12]=-(r+e)/(r-e),t[13]=-(s+i)/(s-i),t[14]=0,t[15]=1}flush(){this.currentRegion&&(this.currentRegion.exit(),this.currentRegion=null)}applyFilters(t,e){if(e.length===0)throw new Error("applyFilters: shaders array must not be empty.");const r=Math.max(...e.map(c=>c.padding)),i=r,s=t.rawWidth+r*2,a=t.rawHeight+r*2;for(let c=0;c<2;c++)this._filterRT[c]?this._filterRT[c].resize(s,a):this._filterRT[c]=this.texture.createRenderTexture({width:s,height:a});let h=t.clone(this._filterInput),o=0;this.matrixStack.save(),this.matrixStack.identity();for(let c=0;c<e.length;c++){const u=this._filterRT[o%2];u.offsetX=0,u.offsetY=0,this.enterRenderTexture(u),this.clearRenderTexture(),this.drawSprite({texture:h,shader:e[c],offsetX:c==0?i:0,offsetY:c==0?i:0,padding:r}),this.leaveRenderTexture(),h=u,o++}return this.matrixStack.restore(),h.offsetX=-i,h.offsetY=-i,h}enterRenderTexture(t){this.flush(),t.activate(),this.gl.viewport(0,0,t.rawWidth,t.rawHeight),this.updateProjection(0,t.rawWidth,0,t.rawHeight)}clearRenderTexture(t=new f(0,0,0,0)){this.flush();const e=this.gl;t.setClearColor(e),e.clear(e.COLOR_BUFFER_BIT)}leaveRenderTexture(){this.flush(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.viewport(0,0,this.physicsWidth,this.physicsHeight),this.updateProjection(0,this.logicWidth,this.logicHeight,0)}drawToRenderTexture(t,e,r=new f(0,0,0,0)){this.enterRenderTexture(t);try{r!==null&&this.clearRenderTexture(r),e()}finally{this.leaveRenderTexture()}}withMask(t,e,r=0,i=1){this.clearMask(),this.startDrawMask(i);try{t()}finally{this.endDrawMask()}this.enterMask(r,i);try{e()}finally{this.exitMask()}}withTransform(t,e,r=0,i=0){this.matrixStack.save();try{e&&this.matrixStack.applyTransform(e,r,i),t()}finally{this.matrixStack.restore()}}withScissor(t,e,r,i,s){this.startScissor(t,e,r,i);try{s()}finally{this.endScissor()}}withBlendMode(t,e){this.setBlendMode(t);try{e()}finally{this.setBlendMode(0)}}startDrawMask(t=1,e=255){this.flush();const r=this.gl;r.stencilMask(e),r.colorMask(!1,!1,!1,!1),r.stencilFunc(r.ALWAYS,t,e),r.stencilOp(r.KEEP,r.KEEP,r.REPLACE),this.enterRegion(this.graphicRegion,this.graphicRegion.maskShader),this.inCreateMask=!0}endDrawMask(){this.flush();const t=this.gl;t.colorMask(!0,!0,!0,!0),t.stencilMask(0),this.inCreateMask=!1}clearMask(t=255){this.flush();const e=this.gl;e.stencilMask(t),e.clear(e.STENCIL_BUFFER_BIT),this.inCreateMask=!1}enterMask(t,e=1,r=255){this.flush();const i=this.gl;i.colorMask(!0,!0,!0,!0),i.stencilMask(0),i.stencilFunc(t===0?i.EQUAL:i.NOTEQUAL,e,r),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),this.inCreateMask=!1}exitMask(){this.flush();const t=this.gl;t.colorMask(!0,!0,!0,!0),t.stencilMask(255),t.stencilFunc(t.ALWAYS,1,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),this.inCreateMask=!1}setBlendMode(t){this.flush();const e=this.gl;switch(t){case 0:this.premultipliedAlpha?e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA):e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 1:e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,e.ONE);break;case 2:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 3:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 4:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE_MINUS_SRC_ALPHA);break}}startScissor(t,e,r,i){this.flush();const s=this.gl,a=this.physicsWidth/this.logicWidth,h=this.physicsHeight/this.logicHeight,o=Math.round(t*a),c=Math.round(this.physicsHeight-(e+i)*h),u=Math.round(r*a),l=Math.round(i*h);s.enable(s.SCISSOR_TEST),s.scissor(o,c,u,l)}endScissor(){this.flush(),this.gl.disable(this.gl.SCISSOR_TEST)}applyCamera(t){this.matrixStack.applyTransform(t);const e=this.matrixStack.curWorldM;this.matrix.invert(e)}logicToPhysics(t){return t.multiply(new g(this.physicsWidth/this.logicWidth,this.physicsHeight/this.logicHeight))}physicsToLogic(t){return t.multiply(new g(this.logicWidth/this.physicsWidth,this.logicHeight/this.physicsHeight))}cssToDevicePixel(t){return t.multiply(this.dpr)}cssToLogic(t){const e=this.cssToDevicePixel(t);return this.physicsToLogic(e)}devicePixelToCss(t){return t.divide(this.dpr)}toCSSMatrix(t){const e=this.physicsWidth/this.dpr/this.logicWidth,r=this.physicsHeight/this.dpr/this.logicHeight;return this.matrix.toCSSMatrix(t??this.matrixStack.curWorldM,e,r)}}function me(n){return!(n===null||typeof n!="object"||Array.isArray(n)||n instanceof g||n instanceof f)}class I{static float(t,e){return Math.random()*(e-t)+t}static int(t,e){return Math.floor(Math.random()*(e-t+1))+t}static angle(){return Math.random()*Math.PI*2}static vector(t,e,r,i){return new g(I.float(t,e),I.float(r,i))}static randomColor(t,e){return new f(I.float(t.r,e.r),I.float(t.g,e.g),I.float(t.b,e.b),I.float(t.a,e.a))}static pick(t){return t[I.int(0,t.length-1)]}static pickWeight(t){if(!t||t.length===0)return null;let e=0;for(const[,i]of t)e+=i;let r=Math.random()*e;for(const[i,s]of t)if(r-=s,r<=0)return i;return t[t.length-1][0]}static scalarOrRange(t,e){if(t==null)return e;if(Array.isArray(t)){const[r,i]=t;if(typeof r=="number")return I.float(r,i);if(r instanceof g)return I.vector(r.x,i.x,r.y,i.y);if(r instanceof f)return I.randomColor(r,i)}return typeof t=="number"?t:t.clone()}}const st=(n,t)=>(Array.isArray(n)?n:[n]).slice(0,t);var Wt=(n=>(n.POINT="point",n.CIRCLE="circle",n.RECT="rect",n))(Wt||{});const Ot=10,Ft=0,Dt=!0;class Z{components;constructor(t=1){if(!Number.isInteger(t)||t<=0)throw new RangeError("ParticleAttributeStore size must be a positive integer");this.components=Array.from({length:t},()=>({value:new b(S.Float32),delta:new b(S.Float32),damping:new b(S.Float32)}))}getArrayBuffer(){return this.components.flatMap(({value:t,delta:e,damping:r})=>[t,e,r])}update(t){for(const{value:e,delta:r,damping:i}of this.components)for(let s=0;s<e.usedElemNum;s++)e.typedArray[s]*=Math.pow(i.get(s),t),e.typedArray[s]+=r.get(s)*t}get(t,e=0){return this.components[e].value.get(t)}getComponent(t,e){if(typeof t=="number")return t;if(t instanceof g)return e===0?t.x:t.y;switch(e){case 0:return t.r;case 1:return t.g;case 2:return t.b;case 3:return t.a;default:return 0}}resolveComponent(t,e,r){return t===void 0?r:Array.isArray(t)?I.float(this.getComponent(t[0],e),this.getComponent(t[1],e)):this.getComponent(t,e)}create(t,e,r=1){const i=me(t)?t:void 0,s=i===void 0?t:void 0,a=r>0?r:1;let h=0;for(let o=0;o<this.components.length;o++){const{value:c,delta:u,damping:l}=this.components[o],m=this.getComponent(e,o),d=s===void 0?this.resolveComponent(i?.start,o,m):this.getComponent(s,o),x=i?.end===void 0?d:this.resolveComponent(i.end,o,m);c.push(d),u.push(i?.delta===void 0?(x-d)/a:this.getComponent(i.delta,o)),l.push(i?.damping??1),o===0&&(h=d)}return h}}class ft{options;emitting=!1;emitTimer=0;emitRate=Ot;emitTime=Ft;emitTimeCounter=0;localSpace=Dt;rapid;x=new b(S.Float32);y=new b(S.Float32);scaleX=new b(S.Float32);scaleY=new b(S.Float32);rotation=new b(S.Float32);color=new b(S.Uint32);remainingLife=new b(S.Float32);animations={speed:new Z,rotation:new Z,scale:new Z,color:new Z(4),velocity:new Z(2)};count=0;constructor(t,e){this.rapid=t,this.options=e,this.emitRate=e.emitRate??Ot,this.emitTime=e.emitTime??Ft,this.localSpace=e.localSpace??Dt}getAllArrayBuffer(){return[this.x,this.y,this.scaleX,this.scaleY,this.rotation,this.color,this.remainingLife,...Object.values(this.animations).flatMap(t=>t.getArrayBuffer())]}setTexture(t){this.options.texture=t}clone(){return new ft(this.rapid,{...this.options})}setEmitRate(t){this.emitRate=t}setEmitTime(t){this.emitTime=t}start(){this.emitting=!0,this.emitTimeCounter=0}stop(){this.emitting=!1}clear(){for(const t of this.getAllArrayBuffer())t.clear();this.count=0,this.emitTimeCounter=0}emit(t){const e=this.options.maxParticles??1/0,r=Math.min(t,e-this.count);for(let i=0;i<r;i++)this.createParticle()}createParticle(){const t=I.scalarOrRange(this.options.life,1);this.remainingLife.push(t);let e=0,r=0;switch(this.options.emitShape){case"circle":{const c=Math.random()*Math.PI*2,u=(this.options.emitRadius??0)*Math.sqrt(Math.random());e=Math.cos(c)*u,r=Math.sin(c)*u;break}case"rect":{e=(Math.random()-.5)*(this.options.emitRect?.width??0),r=(Math.random()-.5)*(this.options.emitRect?.height??0);break}}const i=this.rapid.matrixStack;if(this.localSpace)this.x.push(e),this.y.push(r);else{const{x:c,y:u}=i.localToWorld(e,r);this.x.push(c),this.y.push(u)}const s=this.options.animation,a=this.animations,h=a.scale.create(s.scale,1,t),o=a.rotation.create(s.rotation,0,t);a.speed.create(s.speed,0,t),a.velocity.create(s.velocity,g.ZERO,t),a.color.create(s.color,f.White,t),this.rotation.push(o),this.scaleX.push(h),this.scaleY.push(h),this.color.pushUint32(f.packColor(a.color.get(this.count,0),a.color.get(this.count,1),a.color.get(this.count,2),a.color.get(this.count,3),this.rapid.premultipliedAlpha)),this.count+=1}update(t){if(this.emitting&&this.emitRate>0)if(this.emitTime>0){if(this.emitTimeCounter+=t,this.emitTimeCounter>=this.emitTime){const r=Math.floor(this.emitTimeCounter/this.emitTime);this.emit(this.emitRate*r),this.emitTimeCounter-=r*this.emitTime}}else{this.emitTimer+=t;const r=Math.floor(this.emitTimer*this.emitRate);r>0&&(this.emit(r),this.emitTimer-=r/this.emitRate)}const e=this.updateParticle(t);this.count-=e.length,b.removeAtIndices(e,this.getAllArrayBuffer())}updateParticle(t){const e=[],r=this.animations;Object.values(r).forEach(i=>i.update(t));for(let i=0;i<this.count;i++){if(this.remainingLife.typedArray[i]-=t,this.remainingLife.typedArray[i]<=0){e.push(i);continue}const s=r.rotation.get(i),a=r.scale.get(i),h=r.speed.get(i);this.rotation.typedArray[i]=s,this.scaleX.typedArray[i]=a,this.scaleY.typedArray[i]=a,this.color.uint32[i]=f.packColor(r.color.get(i,0),r.color.get(i,1),r.color.get(i,2),r.color.get(i,3),this.rapid.premultipliedAlpha),this.x.typedArray[i]+=(h*Math.cos(s)+r.velocity.get(i,0))*t,this.y.typedArray[i]+=(h*Math.sin(s)+r.velocity.get(i,1))*t}return e}render(){const t=this.options,e=this.localSpace?void 0:this.rapid.matrix.alloc();this.rapid.drawParticles({texture:t.texture,shader:t.shader,x:this.x.typedArray,y:this.y.typedArray,scaleX:this.scaleX.typedArray,scaleY:this.scaleY.typedArray,rotation:this.rotation.typedArray,color:this.color.typedArray,count:this.count,reverseOrder:!0,originX:t.origin?.x??.5,originY:t.origin?.y??.5,customMatrix:e})}isActive(){return this.emitting||this.count>0}oneShot(){this.emit(this.emitRate)}}const xe=`
|
|
344
|
+
`;const l=new Function(u)();return this.particleLoopCache.set(c,l),l}render(){if(this.instanceCount===0)return;this.prepareRender();const t=this.gl;this.texture&&(t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.texture.glTexture));const e=this.currentShader;this.instanceBuffer.bindBuffer(),this.instanceBuffer.bufferData(),e.bindVAO();const r=this.rapid.matrixStack,s=this.rapid.matrix.getMatrix(this.customMatrix??r.curWorldM),a=wt(this.rapid.projection,s);this.currentShader.setUniform("u_projection",a),Mt(t,t.TRIANGLE_STRIP,0,4,this.instanceCount),this.rapid.drawcallCount++,this.texture=void 0,this.customMatrix=void 0}}var ft=(n=>(n[n.EQUAL=0]="EQUAL",n[n.NOT_EQUAL=1]="NOT_EQUAL",n))(ft||{}),Dt=(n=>(n[n.NORMAL=0]="NORMAL",n[n.ADD=1]="ADD",n[n.MULTIPLY=2]="MULTIPLY",n[n.SCREEN=3]="SCREEN",n[n.ERASE=4]="ERASE",n))(Dt||{}),Bt=(n=>(n[n.CanvasItem=0]="CanvasItem",n[n.Viewport=1]="Viewport",n))(Bt||{});class fe{gl;canvas;projection=new Float32Array(16);projectionDirty=!0;dpr;backgroundColor=f.Black;logicWidth=0;logicHeight=0;physicsWidth=0;physicsHeight=0;currentRegion=null;maxTextureUnits=0;matrixStack=new ee(this);matrix;spriteRegion;graphicRegion;atlasSpriteRegion;particleRegion;drawcallCount=0;inCreateMask=!1;texture;premultipliedAlpha;antialias;roundPixels;textureFilter;scaleMode;_filterRT=[null,null];_filterInput=new N;get height(){return this.logicHeight}get width(){return this.logicWidth}constructor(t){this.canvas=t.canvas,this.dpr=window.devicePixelRatio||1,this.antialias=t.antialias??!1,this.textureFilter=t.textureFilter??$.NEAREST,this.premultipliedAlpha=t.premultipliedAlpha??!0,this.roundPixels=t.roundPixels??!1,this.scaleMode=t.scaleMode??0;const e=Yt(this.canvas,this.antialias,this.premultipliedAlpha);this.gl=e,this.maxTextureUnits=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.matrix=this.matrixStack.matrix,this.spriteRegion=new ut(this),this.graphicRegion=new ae(this),this.atlasSpriteRegion=new oe(this),this.particleRegion=new de(this);const r=this.canvas.clientWidth||this.canvas.width,i=this.canvas.clientHeight||this.canvas.height;this.physicsWidth=t.physicsWidth||Math.round(r*this.dpr),this.physicsHeight=t.physicsHeight||Math.round(i*this.dpr),this.logicWidth=t.logicWidth||t.width||this.physicsWidth/this.dpr,this.logicHeight=t.logicHeight||t.height||this.physicsHeight/this.dpr,this.resize(this.logicWidth,this.logicHeight,this.physicsWidth,this.physicsHeight),this.texture=new pt(this),t.backgroundColor&&(this.backgroundColor=t.backgroundColor),e.enable(e.BLEND),this.premultipliedAlpha?e.blendFunc(e.ONE,e.ONE_MINUS_SRC_ALPHA):e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.enable(e.STENCIL_TEST),e.stencilFunc(e.ALWAYS,1,255),e.stencilOp(e.KEEP,e.KEEP,e.KEEP)}setTextureFilter(t){this.textureFilter=t}getColorUint32(t){return _t(this.premultipliedAlpha,t)}enterRegion(t,e){this.currentRegion===t&&this.currentRegion.isSameShader(e)||(this.flush(),this.currentRegion=t,t.enter(e))}drawParticles(t){Pt(this,t)}drawSprite(t){Lt(this,t)}drawLine(t){Nt(this,t)}drawGraphic(t){dt(this,t)}drawRect(t){Wt(this,t)}drawCircle(t){Ot(this,t)}startGraphic(t=this.gl.TRIANGLES,e,r,i){this.enterRegion(this.graphicRegion,r),this.graphicRegion.startGraphic(i??this.matrixStack.curWorldM,t,e)}startMaskGraphic(t=this.gl.TRIANGLES,e,r){this.startGraphic(t,e,this.graphicRegion.maskShader,r)}drawMaskImage(t){It(this,t)}addRectVertex(t,e,r){const i=this.getColorUint32(r);this.addGraphicVertex(0,0,0,0,i),this.addGraphicVertex(t,0,1,0,i),this.addGraphicVertex(t,e,1,1,i),this.addGraphicVertex(0,e,0,1,i)}addCircleVertex(t,e,r=32){const i=Math.PI*2/r,s=this.getColorUint32(e);for(let a=0;a<r;a++){const h=i*a,o=Math.cos(h)*t,c=Math.sin(h)*t,u=.5+Math.cos(h)*.5,l=.5+Math.sin(h)*.5;this.addGraphicVertex(o,c,u,l,s)}}addGraphicVertex(t,e,r=0,i=0,s=4294967295){this.graphicRegion.addVertex(t,e,r,i,typeof s=="number"?s:this.getColorUint32(s))}endGraphic(){this.graphicRegion.endGraphic()}resize(t,e,r,i){this.flush();const s=r??this.canvas.clientWidth??this.canvas.width,a=i??this.canvas.clientHeight??this.canvas.height;switch(r!==void 0&&(this.canvas.style.width=s+"px"),i!==void 0&&(this.canvas.style.height=a+"px"),this.physicsWidth=s*this.dpr,this.physicsHeight=a*this.dpr,this.logicWidth=t,this.logicHeight=e,this.scaleMode){case 1:this.canvas.width=t,this.canvas.height=e,this.canvas.style.imageRendering="pixelated",this.gl.viewport(0,0,t,e);break;case 0:this.canvas.width=this.physicsWidth,this.canvas.height=this.physicsHeight,this.canvas.style.imageRendering="auto",this.gl.viewport(0,0,this.physicsWidth,this.physicsHeight);break;default:throw new Error("scaleMode can only be CanvasScaleMode.Viewport or CanvasScaleMode.CanvasItem")}this.updateProjection(0,this.logicWidth,this.logicHeight,0)}updateProjection(t,e,r,i){this.updateOrthMatrix(this.projection,t,e,r,i),this.projectionDirty=!0}clear(){const t=this.gl;this.backgroundColor.setClearColor(t),t.clear(t.COLOR_BUFFER_BIT|t.STENCIL_BUFFER_BIT),this.drawcallCount=0,this.matrixStack.reset()}updateOrthMatrix(t,e,r,i,s){t[0]=2/(r-e),t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2/(s-i),t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=-1,t[11]=0,t[12]=-(r+e)/(r-e),t[13]=-(s+i)/(s-i),t[14]=0,t[15]=1}flush(){this.currentRegion&&(this.currentRegion.exit(),this.currentRegion=null)}applyFilters(t,e){if(e.length===0)throw new Error("applyFilters: shaders array must not be empty.");const r=Math.max(...e.map(c=>c.padding)),i=r,s=t.rawWidth+r*2,a=t.rawHeight+r*2;for(let c=0;c<2;c++)this._filterRT[c]?this._filterRT[c].resize(s,a):this._filterRT[c]=this.texture.createRenderTexture({width:s,height:a});let h=t.clone(this._filterInput),o=0;this.matrixStack.save(),this.matrixStack.identity();for(let c=0;c<e.length;c++){const u=this._filterRT[o%2];u.offsetX=0,u.offsetY=0,this.enterRenderTexture(u),this.clearRenderTexture(),this.drawSprite({texture:h,shader:e[c],offsetX:c==0?i:0,offsetY:c==0?i:0,padding:r}),this.leaveRenderTexture(),h=u,o++}return this.matrixStack.restore(),h.offsetX=-i,h.offsetY=-i,h}enterRenderTexture(t){this.flush(),t.activate(),this.gl.viewport(0,0,t.rawWidth,t.rawHeight),this.updateProjection(0,t.rawWidth,0,t.rawHeight)}clearRenderTexture(t=new f(0,0,0,0)){this.flush();const e=this.gl;t.setClearColor(e),e.clear(e.COLOR_BUFFER_BIT)}leaveRenderTexture(){this.flush(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.viewport(0,0,this.physicsWidth,this.physicsHeight),this.updateProjection(0,this.logicWidth,this.logicHeight,0)}drawToRenderTexture(t,e,r=new f(0,0,0,0)){this.enterRenderTexture(t);try{r!==null&&this.clearRenderTexture(r),e()}finally{this.leaveRenderTexture()}}withMask(t,e,r=0,i=1){this.clearMask(),this.startDrawMask(i);try{t()}finally{this.endDrawMask()}this.enterMask(r,i);try{e()}finally{this.exitMask()}}withTransform(t,e,r=0,i=0){this.matrixStack.save();try{e&&this.matrixStack.applyTransform(e,r,i),t()}finally{this.matrixStack.restore()}}withScissor(t,e,r,i,s){this.startScissor(t,e,r,i);try{s()}finally{this.endScissor()}}withBlendMode(t,e){this.setBlendMode(t);try{e()}finally{this.setBlendMode(0)}}startDrawMask(t=1,e=255){this.flush();const r=this.gl;r.stencilMask(e),r.colorMask(!1,!1,!1,!1),r.stencilFunc(r.ALWAYS,t,e),r.stencilOp(r.KEEP,r.KEEP,r.REPLACE),this.enterRegion(this.graphicRegion,this.graphicRegion.maskShader),this.inCreateMask=!0}endDrawMask(){this.flush();const t=this.gl;t.colorMask(!0,!0,!0,!0),t.stencilMask(0),this.inCreateMask=!1}clearMask(t=255){this.flush();const e=this.gl;e.stencilMask(t),e.clear(e.STENCIL_BUFFER_BIT),this.inCreateMask=!1}enterMask(t,e=1,r=255){this.flush();const i=this.gl;i.colorMask(!0,!0,!0,!0),i.stencilMask(0),i.stencilFunc(t===0?i.EQUAL:i.NOTEQUAL,e,r),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),this.inCreateMask=!1}exitMask(){this.flush();const t=this.gl;t.colorMask(!0,!0,!0,!0),t.stencilMask(255),t.stencilFunc(t.ALWAYS,1,255),t.stencilOp(t.KEEP,t.KEEP,t.KEEP),this.inCreateMask=!1}setBlendMode(t){this.flush();const e=this.gl;switch(t){case 0:this.premultipliedAlpha?e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA):e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 1:e.blendFuncSeparate(e.ONE,e.ONE,e.ONE,e.ONE);break;case 2:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 3:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_COLOR,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 4:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE_MINUS_SRC_ALPHA);break}}startScissor(t,e,r,i){this.flush();const s=this.gl,a=this.physicsWidth/this.logicWidth,h=this.physicsHeight/this.logicHeight,o=Math.round(t*a),c=Math.round(this.physicsHeight-(e+i)*h),u=Math.round(r*a),l=Math.round(i*h);s.enable(s.SCISSOR_TEST),s.scissor(o,c,u,l)}endScissor(){this.flush(),this.gl.disable(this.gl.SCISSOR_TEST)}applyCamera(t){this.matrixStack.applyTransform(t);const e=this.matrixStack.curWorldM;this.matrix.invert(e)}logicToPhysics(t){return t.multiply(new g(this.physicsWidth/this.logicWidth,this.physicsHeight/this.logicHeight))}physicsToLogic(t){return t.multiply(new g(this.logicWidth/this.physicsWidth,this.logicHeight/this.physicsHeight))}cssToDevicePixel(t){return t.multiply(this.dpr)}cssToLogic(t){const e=this.cssToDevicePixel(t);return this.physicsToLogic(e)}devicePixelToCss(t){return t.divide(this.dpr)}toCSSMatrix(t){const e=this.physicsWidth/this.dpr/this.logicWidth,r=this.physicsHeight/this.dpr/this.logicHeight;return this.matrix.toCSSMatrix(t??this.matrixStack.curWorldM,e,r)}}function me(n){return!(n===null||typeof n!="object"||Array.isArray(n)||n instanceof g||n instanceof f)}class I{static float(t,e){return Math.random()*(e-t)+t}static int(t,e){return Math.floor(Math.random()*(e-t+1))+t}static angle(){return Math.random()*Math.PI*2}static vector(t,e,r,i){return new g(I.float(t,e),I.float(r,i))}static randomColor(t,e){return new f(I.float(t.r,e.r),I.float(t.g,e.g),I.float(t.b,e.b),I.float(t.a,e.a))}static pick(t){return t[I.int(0,t.length-1)]}static pickWeight(t){if(!t||t.length===0)return null;let e=0;for(const[,i]of t)e+=i;let r=Math.random()*e;for(const[i,s]of t)if(r-=s,r<=0)return i;return t[t.length-1][0]}static scalarOrRange(t,e){if(t==null)return e;if(Array.isArray(t)){const[r,i]=t;if(typeof r=="number")return I.float(r,i);if(r instanceof g)return I.vector(r.x,i.x,r.y,i.y);if(r instanceof f)return I.randomColor(r,i)}return typeof t=="number"?t:t.clone()}}const st=(n,t)=>(Array.isArray(n)?n:[n]).slice(0,t);var kt=(n=>(n.POINT="point",n.CIRCLE="circle",n.RECT="rect",n))(kt||{});const Ht=10,Gt=0,Vt=!0;class Z{components;constructor(t=1){if(!Number.isInteger(t)||t<=0)throw new RangeError("ParticleAttributeStore size must be a positive integer");this.components=Array.from({length:t},()=>({value:new b(S.Float32),delta:new b(S.Float32),damping:new b(S.Float32)}))}getArrayBuffer(){return this.components.flatMap(({value:t,delta:e,damping:r})=>[t,e,r])}update(t){for(const{value:e,delta:r,damping:i}of this.components)for(let s=0;s<e.usedElemNum;s++)e.typedArray[s]*=Math.pow(i.get(s),t),e.typedArray[s]+=r.get(s)*t}get(t,e=0){return this.components[e].value.get(t)}getComponent(t,e){if(typeof t=="number")return t;if(t instanceof g)return e===0?t.x:t.y;switch(e){case 0:return t.r;case 1:return t.g;case 2:return t.b;case 3:return t.a;default:return 0}}resolveComponent(t,e,r){return t===void 0?r:Array.isArray(t)?I.float(this.getComponent(t[0],e),this.getComponent(t[1],e)):this.getComponent(t,e)}create(t,e,r=1){const i=me(t)?t:void 0,s=i===void 0?t:void 0,a=r>0?r:1;let h=0;for(let o=0;o<this.components.length;o++){const{value:c,delta:u,damping:l}=this.components[o],m=this.getComponent(e,o),d=s===void 0?this.resolveComponent(i?.start,o,m):this.getComponent(s,o),x=i?.end===void 0?d:this.resolveComponent(i.end,o,m);c.push(d),u.push(i?.delta===void 0?(x-d)/a:this.getComponent(i.delta,o)),l.push(i?.damping??1),o===0&&(h=d)}return h}}class mt{options;emitting=!1;emitTimer=0;emitRate=Ht;emitTime=Gt;emitTimeCounter=0;localSpace=Vt;rapid;x=new b(S.Float32);y=new b(S.Float32);scaleX=new b(S.Float32);scaleY=new b(S.Float32);rotation=new b(S.Float32);color=new b(S.Uint32);remainingLife=new b(S.Float32);animations={speed:new Z,rotation:new Z,scale:new Z,color:new Z(4),velocity:new Z(2)};count=0;constructor(t,e){this.rapid=t,this.options=e,this.emitRate=e.emitRate??Ht,this.emitTime=e.emitTime??Gt,this.localSpace=e.localSpace??Vt}getAllArrayBuffer(){return[this.x,this.y,this.scaleX,this.scaleY,this.rotation,this.color,this.remainingLife,...Object.values(this.animations).flatMap(t=>t.getArrayBuffer())]}setTexture(t){this.options.texture=t}clone(){return new mt(this.rapid,{...this.options})}setEmitRate(t){this.emitRate=t}setEmitTime(t){this.emitTime=t}start(){this.emitting=!0,this.emitTimeCounter=0}stop(){this.emitting=!1}clear(){for(const t of this.getAllArrayBuffer())t.clear();this.count=0,this.emitTimeCounter=0}emit(t){const e=this.options.maxParticles??1/0,r=Math.min(t,e-this.count);for(let i=0;i<r;i++)this.createParticle()}createParticle(){const t=I.scalarOrRange(this.options.life,1);this.remainingLife.push(t);let e=0,r=0;switch(this.options.emitShape){case"circle":{const c=Math.random()*Math.PI*2,u=(this.options.emitRadius??0)*Math.sqrt(Math.random());e=Math.cos(c)*u,r=Math.sin(c)*u;break}case"rect":{e=(Math.random()-.5)*(this.options.emitRect?.width??0),r=(Math.random()-.5)*(this.options.emitRect?.height??0);break}}const i=this.rapid.matrixStack;if(this.localSpace)this.x.push(e),this.y.push(r);else{const{x:c,y:u}=i.localToWorld(e,r);this.x.push(c),this.y.push(u)}const s=this.options.animation,a=this.animations,h=a.scale.create(s.scale,1,t),o=a.rotation.create(s.rotation,0,t);a.speed.create(s.speed,0,t),a.velocity.create(s.velocity,g.ZERO,t),a.color.create(s.color,f.White,t),this.rotation.push(o),this.scaleX.push(h),this.scaleY.push(h),this.color.pushUint32(f.packColor(a.color.get(this.count,0),a.color.get(this.count,1),a.color.get(this.count,2),a.color.get(this.count,3),this.rapid.premultipliedAlpha)),this.count+=1}update(t){if(this.emitting&&this.emitRate>0)if(this.emitTime>0){if(this.emitTimeCounter+=t,this.emitTimeCounter>=this.emitTime){const r=Math.floor(this.emitTimeCounter/this.emitTime);this.emit(this.emitRate*r),this.emitTimeCounter-=r*this.emitTime}}else{this.emitTimer+=t;const r=Math.floor(this.emitTimer*this.emitRate);r>0&&(this.emit(r),this.emitTimer-=r/this.emitRate)}const e=this.updateParticle(t);this.count-=e.length,b.removeAtIndices(e,this.getAllArrayBuffer())}updateParticle(t){const e=[],r=this.animations;Object.values(r).forEach(i=>i.update(t));for(let i=0;i<this.count;i++){if(this.remainingLife.typedArray[i]-=t,this.remainingLife.typedArray[i]<=0){e.push(i);continue}const s=r.rotation.get(i),a=r.scale.get(i),h=r.speed.get(i);this.rotation.typedArray[i]=s,this.scaleX.typedArray[i]=a,this.scaleY.typedArray[i]=a,this.color.uint32[i]=f.packColor(r.color.get(i,0),r.color.get(i,1),r.color.get(i,2),r.color.get(i,3),this.rapid.premultipliedAlpha),this.x.typedArray[i]+=(h*Math.cos(s)+r.velocity.get(i,0))*t,this.y.typedArray[i]+=(h*Math.sin(s)+r.velocity.get(i,1))*t}return e}render(){const t=this.options,e=this.localSpace?void 0:this.rapid.matrix.alloc();this.rapid.drawParticles({texture:t.texture,shader:t.shader,x:this.x.typedArray,y:this.y.typedArray,scaleX:this.scaleX.typedArray,scaleY:this.scaleY.typedArray,rotation:this.rotation.typedArray,color:this.color.typedArray,count:this.count,reverseOrder:!0,originX:t.origin?.x??.5,originY:t.origin?.y??.5,customMatrix:e})}isActive(){return this.emitting||this.count>0}oneShot(){this.emit(this.emitRate)}}const xe=`
|
|
346
345
|
uniform mediump int uLightTextureId[%TEXTURE_NUM%];
|
|
347
346
|
|
|
348
347
|
uniform sampler2D uNormalMap;
|
|
@@ -354,13 +353,15 @@ uniform mat3x2 uLightMatrix[%TEXTURE_NUM%];
|
|
|
354
353
|
uniform float uLightHeight[%TEXTURE_NUM%];
|
|
355
354
|
uniform float uMetallic;
|
|
356
355
|
uniform float uRoughness;
|
|
356
|
+
uniform vec3 uAmbientColor;
|
|
357
|
+
uniform vec2 uNormalScale;
|
|
357
358
|
|
|
358
359
|
void light_fragment(inout vec4 color, in vec2 vRegion) {
|
|
359
360
|
if (color.a < 0.005) return;
|
|
360
361
|
|
|
361
|
-
// 屏幕坐标映射到世界坐标
|
|
362
362
|
vec2 worldPos = vec2(gl_FragCoord.x, uResolution.y - gl_FragCoord.y) * (uLogicalResolution / uResolution);
|
|
363
|
-
vec3 normal = normalize(texture(uNormalMap, vRegion).rgb * 2.0 - 1.0)
|
|
363
|
+
vec3 normal = normalize(texture(uNormalMap, vRegion).rgb * 2.0 - 1.0);
|
|
364
|
+
normal = normalize(normal * vec3(uNormalScale, 1.0));
|
|
364
365
|
|
|
365
366
|
vec3 totalDiffuse = vec3(0.0);
|
|
366
367
|
vec3 totalSpecular = vec3(0.0);
|
|
@@ -375,11 +376,8 @@ void light_fragment(inout vec4 color, in vec2 vRegion) {
|
|
|
375
376
|
mat2 lightBasis = mat2(uLightMatrix[i][0], uLightMatrix[i][1]);
|
|
376
377
|
vec2 lightUV = inverse(lightBasis) * (worldPos - lightPos) + 0.5;
|
|
377
378
|
|
|
378
|
-
// 判断当前像素是否在该光源范围内
|
|
379
379
|
if (lightUV.x >= 0.0 && lightUV.x <= 1.0 && lightUV.y >= 0.0 && lightUV.y <= 1.0) {
|
|
380
380
|
|
|
381
|
-
// ⭐️ 核心修复:sampler2DArray 采样必须传 vec3
|
|
382
|
-
// 第三个分量是该光源对应的图层 ID (转为 float)
|
|
383
381
|
int layer = uLightTextureId[i];
|
|
384
382
|
vec4 lightTex;
|
|
385
383
|
%GET_COLOR%
|
|
@@ -394,7 +392,6 @@ void light_fragment(inout vec4 color, in vec2 vRegion) {
|
|
|
394
392
|
}
|
|
395
393
|
}
|
|
396
394
|
|
|
397
|
-
|
|
398
|
-
color.rgb = color.rgb * (vec3(0.1, 0.1, 0.15) + totalDiffuse) + totalSpecular;
|
|
395
|
+
color.rgb = color.rgb * (uAmbientColor + totalDiffuse) + totalSpecular;
|
|
399
396
|
}
|
|
400
|
-
`,ge="void light_vertex(inout vec4 p, vec2 u) {}",J=8;class
|
|
397
|
+
`,ge="void light_vertex(inout vec4 p, vec2 u) {}",J=8;class Xt extends rt{constructor(t,e="",r="",i=0,s){super(t,e,r,i+2,s),this.prefix.push("light_")}getGLShader(t,e,r,i){const s=j(xe,t.getMaxTexutreUnit(this),"layer","lightUV","lightTex = ");return i=this.replaceCustomCode(i,s),r=this.replaceCustomCode(r,ge),super.getGLShader(t,e,r,i)}}class pe{shader;rapid;rt;constructor(t){this.rapid=t,this.shader=new Xt(t),this.rt=t.texture.createRenderTexture({width:0,height:0})}lightShadow(t,e,r){if(r.length===0)return;const i=this.rapid,s=typeof e=="number"?e:e.world,a=new g(t.rawWidth*.5,t.rawHeight*.5),h=r.map(c=>{const u=i.matrixStack.localToWorld(c.x,c.y),l=i.matrix.worldToLocal(s,u.x,u.y);return new g((l.x+.5)*t.rawWidth,(l.y+.5)*t.rawHeight)});this.rt.resize(t.rawWidth,t.rawHeight);const o=Math.hypot(t.rawWidth,t.rawHeight)*.5*1.05;return i.drawToRenderTexture(this.rt,()=>{i.withMask(()=>{i.startMaskGraphic(i.gl.TRIANGLES);for(let c=0;c<h.length;c++){const u=h[c],l=h[(c+1)%h.length],m=u.subtract(a).normalized(),d=l.subtract(a).normalized(),x=Math.max(-.999,Math.min(1,m.dot(d))),p=Math.sqrt((1+x)*.5),y=o/p,T=a.add(m.multiply(y)),R=a.add(d.multiply(y));i.addGraphicVertex(u.x,u.y),i.addGraphicVertex(l.x,l.y),i.addGraphicVertex(R.x,R.y),i.addGraphicVertex(u.x,u.y),i.addGraphicVertex(R.x,R.y),i.addGraphicVertex(T.x,T.y)}i.endGraphic()},()=>{i.drawSprite({texture:t})},ft.NOT_EQUAL)}),this.rt}setupLight(t){const e=t.customShader??this.shader,r=st(t.lightMatrix,J),i=st(t.color,J),s=st(t.lightHeight,J),a=st(t.lightTexture,J);return e.setUniforms({uResolution:[this.rapid.physicsWidth,this.rapid.physicsHeight],uLogicalResolution:[this.rapid.logicWidth,this.rapid.logicHeight],uNormalMap:t.normalMap.glTexture,uLightTextureId:a.map(h=>h.glTexture),uLightCount:r.length,uLightMatrix:Float32Array.from(r.flatMap(h=>Array.from(this.rapid.matrix.getMatrix(typeof h=="number"?h:h.world)))),uLightColor:Float32Array.from(r.flatMap((h,o)=>{const c=i[o]??i[0];return c?[c.r/255,c.g/255,c.b/255,c.a/255]:[1,1,1,1]})),uLightHeight:Float32Array.from(r.map((h,o)=>s[o]??s[0]??80)),uMetallic:t.metallic??.8,uRoughness:t.roughness??.15,uAmbientColor:t.ambientColor?[t.ambientColor.r/255,t.ambientColor.g/255,t.ambientColor.b/255]:[.1,.1,.15],uNormalScale:[t.normalScaleX??1,t.normalScaleY??1]}),e}}v.BaseTexture=B,v.BlendMode=Dt,v.CanvasScaleMode=Bt,v.Color=f,v.CustomGlShader=rt,v.GLShader=ot,v.Light=pe,v.LightShader=Xt,v.LineTextureMode=At,v.MAX_LIGHTS=J,v.MaskType=ft,v.ParticleEmitter=mt,v.ParticleShape=kt,v.Rapid=fe,v.RenderTexture=vt,v.TextTexture=yt,v.Texture=N,v.TextureFilterMode=$,v.TextureManager=pt,v.TextureWrapMode=X,v.Vec2=g,v.composeProjectionWithAffine=wt,v.drawCircle=Ot,v.drawGraphic=dt,v.drawLine=Nt,v.drawMaskImage=It,v.drawParticles=Pt,v.drawRect=Wt,v.drawSprite=Lt,v.getColorUint32=_t,v.getLineGeometry=Ct,v.getLineNormal=Ut,v.multiplyMat4=St,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})}));
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { SpriteRegion } from './spriteRegion';
|
|
2
2
|
import { Rapid } from '../render';
|
|
3
|
-
import { CustomGlShader } from '../webgl/glshader';
|
|
4
3
|
export declare class AtlasSpriteRegion extends SpriteRegion {
|
|
5
4
|
KEY: string;
|
|
6
5
|
constructor(rapid: Rapid);
|
|
7
|
-
createCustomShader(customShader: CustomGlShader): import('..').GLShader | null;
|
|
8
6
|
createDefaultShader(): import('..').GLShader;
|
|
9
7
|
}
|
|
@@ -8,8 +8,8 @@ export declare class ParticleRegion extends SpriteRegion {
|
|
|
8
8
|
texture?: Texture;
|
|
9
9
|
customMatrix?: number;
|
|
10
10
|
particleLoopCache: Map<string, Function>;
|
|
11
|
+
protected extraTextureUnit: number;
|
|
11
12
|
constructor(rapid: Rapid);
|
|
12
|
-
createCustomShader(customShader: CustomGlShader): GLShader | null;
|
|
13
13
|
createDefaultShader(): GLShader;
|
|
14
14
|
enter(customShader?: GLShader | CustomGlShader): void;
|
|
15
15
|
createShader(vs: string, fs: string): GLShader;
|
package/dist/region/region.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export declare class Region {
|
|
|
17
17
|
fs: string;
|
|
18
18
|
protected usedTextures: WebGLTexture[];
|
|
19
19
|
protected usedTexturePadding: number[];
|
|
20
|
+
protected extraTextureUnit: number;
|
|
20
21
|
constructor(rapid: Rapid);
|
|
21
22
|
protected createBuffer(): void;
|
|
22
23
|
protected createDefaultShader(): void;
|
|
@@ -24,6 +25,7 @@ export declare class Region {
|
|
|
24
25
|
getTextureUnitList(): number[];
|
|
25
26
|
protected findTextureUnit(texture: WebGLTexture, paddingX?: number, paddingY?: number): number;
|
|
26
27
|
useTexture(texture: WebGLTexture, paddingX?: number, paddingY?: number): number;
|
|
28
|
+
getMaxTexutreUnit(customShader?: CustomGlShader): number;
|
|
27
29
|
createShader(vs: string, fs: string): GLShader;
|
|
28
30
|
createCustomShader(customShader: CustomGlShader): GLShader | null;
|
|
29
31
|
getCustomShader(customShader?: GLShader | CustomGlShader): GLShader;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Rapid } from '../render';
|
|
2
2
|
import { Region } from './region';
|
|
3
|
-
import { CustomGlShader } from '../webgl/glshader';
|
|
4
3
|
import { WebglBufferArray } from '../buffer';
|
|
5
4
|
import { Texture } from '../texture';
|
|
6
5
|
export declare const QUAD_VERTICES: Float32Array<ArrayBuffer>;
|
|
@@ -15,7 +14,6 @@ export declare class SpriteRegion extends Region {
|
|
|
15
14
|
createBuffer(): void;
|
|
16
15
|
createDefaultShader(): import('..').GLShader;
|
|
17
16
|
createShader(vs: string, fs: string): import('..').GLShader;
|
|
18
|
-
createCustomShader(customShader: CustomGlShader): import('..').GLShader | null;
|
|
19
17
|
/**
|
|
20
18
|
* Draws a textured sprite via instanced rendering to significantly improve performance.
|
|
21
19
|
* @param texture The WebGLTexture to map.
|
package/dist/webgl/glshader.d.ts
CHANGED
|
@@ -110,6 +110,7 @@ export declare class CustomGlShader {
|
|
|
110
110
|
* @param textureUniforms Map of texture uniform names to assigned texture unit indices.
|
|
111
111
|
*/
|
|
112
112
|
applyUniform(key: string, textureUniforms: Record<string, number | number[]>): void;
|
|
113
|
+
replaceCustomCode(shader: string, code: string): string;
|
|
113
114
|
/**
|
|
114
115
|
* Retrieves or compiles a customized GLShader for a specific region.
|
|
115
116
|
* @param region The Region requesting the shader.
|
package/package.json
CHANGED