@idetik/core 0.22.1 → 0.22.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.cjs
CHANGED
|
@@ -415,7 +415,7 @@ void main() {
|
|
|
415
415
|
fragColor = vec4(color.rgb, alpha);
|
|
416
416
|
}`;const Fo={projectedLine:{vertex:Do,fragment:so},points:{vertex:ho,fragment:yo},wireframe:{vertex:to,fragment:Go},floatScalarImage:{vertex:KB,fragment:DQ},intScalarImage:{vertex:KB,fragment:DQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:KB,fragment:DQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:KB,fragment:wo},floatVolume:{vertex:sQ,fragment:hQ},intVolume:{vertex:sQ,fragment:hQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:sQ,fragment:hQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},XC={debug:10,info:20,warn:30,error:40},eo={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function ro(){const Q=typeof process<"u"&&typeof process.env?.NODE_ENV=="string"?process.env.NODE_ENV:void 0;if(Q==="production"||Q==="development"||Q==="test")return Q;if(typeof window<"u"){const{NODE_ENV:A}=window;if(A==="production"||A==="development"||A==="test")return A}return"development"}class AA{static logLevel_=ro()==="production"?"warn":"debug";static setLogLevel(A){AA.logLevel_=A}static debug(A,I,...g){AA.log("debug",A,I,...g)}static info(A,I,...g){AA.log("info",A,I,...g)}static warn(A,I,...g){AA.log("warn",A,I,...g)}static error(A,I,...g){AA.log("error",A,I,...g)}static log(A,I,g,...B){if(XC[A]<XC[AA.logLevel_])return;const C=new Date().toISOString(),E=eo[A],i=`[${C}][${A.toUpperCase()}][${I}]`,o=[`${E}${i}`,g,...B];switch(A){case"debug":console.debug(...o);break;case"info":console.info(...o);break;case"warn":console.warn(...o);break;case"error":console.error(...o);break}}}class no{gl_;program_;uniformInfo_=new Map;constructor(A,I,g){this.gl_=A;const B=A.createProgram();if(!B)throw new Error("Failed to create WebGL shader program");this.program_=B;const C=[];try{C.push(this.addShader(I,A.VERTEX_SHADER)),C.push(this.addShader(g,A.FRAGMENT_SHADER)),this.link(),this.preprocessUniformLocations()}catch(E){throw A.deleteProgram(B),E}finally{C.forEach(E=>this.gl_.deleteShader(E))}}setUniform(A,I){const[g,B]=this.uniformInfo_.get(A)??[];if(!g||!B)throw new Error(`Uniform "${A}" not found in shader program`);const C=B.type;switch(C){case this.gl_.BOOL:case this.gl_.FLOAT:typeof I=="number"?this.gl_.uniform1f(g,I):this.gl_.uniform1fv(g,I);break;case this.gl_.INT:typeof I=="number"?this.gl_.uniform1i(g,I):this.gl_.uniform1iv(g,I);break;case this.gl_.FLOAT_VEC2:this.gl_.uniform2fv(g,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(g,I);break;case this.gl_.FLOAT_VEC4:this.gl_.uniform4fv(g,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(g,!1,I);break;case this.gl_.UNSIGNED_INT:this.gl_.uniform1ui(g,I);break;case this.gl_.SAMPLER_2D:case this.gl_.SAMPLER_CUBE:case this.gl_.SAMPLER_3D:case this.gl_.SAMPLER_2D_ARRAY:case this.gl_.SAMPLER_2D_SHADOW:case this.gl_.SAMPLER_CUBE_SHADOW:case this.gl_.SAMPLER_2D_ARRAY_SHADOW:case this.gl_.INT_SAMPLER_2D:case this.gl_.INT_SAMPLER_3D:case this.gl_.INT_SAMPLER_CUBE:case this.gl_.INT_SAMPLER_2D_ARRAY:case this.gl_.UNSIGNED_INT_SAMPLER_2D:case this.gl_.UNSIGNED_INT_SAMPLER_3D:case this.gl_.UNSIGNED_INT_SAMPLER_CUBE:case this.gl_.UNSIGNED_INT_SAMPLER_2D_ARRAY:this.gl_.uniform1i(g,I);break;default:{const E=C;throw new Error(`Unhandled uniform type: ${E}`)}}}preprocessUniformLocations(){const A=this.gl_.getProgramParameter(this.program_,this.gl_.ACTIVE_UNIFORMS);for(let I=0;I<A;I++){const g=this.gl_.getActiveUniform(this.program_,I);if(g){if(!No.has(g.type))throw new Error(`Unsupported uniform type "${g.type}" (GLenum) found in shader program for uniform "${g.name}"`);const B=this.gl_.getUniformLocation(this.program_,g.name);B&&(this.uniformInfo_.set(g.name,[B,g]),AA.debug("WebGLShaderProgram","Uniform found:",g.name,g.type,g.size))}}}addShader(A,I){const g=this.gl_.createShader(I);if(!g)throw new Error(`Failed to create a new shader of type ${I}`);if(this.gl_.shaderSource(g,A),this.gl_.compileShader(g),!this.gl_.getShaderParameter(g,this.gl_.COMPILE_STATUS)){const B=this.gl_.getShaderInfoLog(g);throw this.gl_.deleteShader(g),new Error(`Error compiling shader: ${B}`)}return this.gl_.attachShader(this.program_,g),g}link(){if(this.gl_.linkProgram(this.program_),!this.getParameter(this.gl_.LINK_STATUS)){const A=this.gl_.getProgramInfoLog(this.program_);throw new Error(`Error linking program: ${A}`)}}use(){this.gl_.useProgram(this.program_)}getParameter(A){return this.gl_.getProgramParameter(this.program_,A)}get uniformNames(){return Array.from(this.uniformInfo_.keys())}}const So=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,WebGL2RenderingContext.INT,WebGL2RenderingContext.FLOAT_VEC2,WebGL2RenderingContext.FLOAT_VEC3,WebGL2RenderingContext.FLOAT_VEC4,WebGL2RenderingContext.FLOAT_MAT4,WebGL2RenderingContext.SAMPLER_2D,WebGL2RenderingContext.SAMPLER_CUBE,WebGL2RenderingContext.SAMPLER_3D,WebGL2RenderingContext.SAMPLER_2D_ARRAY,WebGL2RenderingContext.SAMPLER_2D_SHADOW,WebGL2RenderingContext.SAMPLER_CUBE_SHADOW,WebGL2RenderingContext.SAMPLER_2D_ARRAY_SHADOW,WebGL2RenderingContext.INT,WebGL2RenderingContext.INT_SAMPLER_2D,WebGL2RenderingContext.INT_SAMPLER_3D,WebGL2RenderingContext.INT_SAMPLER_CUBE,WebGL2RenderingContext.INT_SAMPLER_2D_ARRAY,WebGL2RenderingContext.UNSIGNED_INT,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_3D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_CUBE,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D_ARRAY]:[],No=new Set(So),yQ="#pragma inject_defines";class Ro{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const g=Fo[A],B=jC(g.vertex,g.vertexDefines),C=jC(g.fragment,g.fragmentDefines);I=new no(this.gl_,B,C),I.use();const E=this.gl_.getError();if(E!==this.gl_.NO_ERROR)throw new Error(`Error using WebGL program: ${E}`);this.programs_.set(A,I)}else I.use();return I}}function jC(Q,A){if(A===void 0||A.size==0)return Q;if(!Q.includes(yQ))throw new Error(`Shader source does not contain "${yQ}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
417
417
|
`),B=`#line __LINE__ + ${1-A.size}`,C=`${I}
|
|
418
|
-
${B}`;return Q.replace(yQ,C)}const MB={};function zC(Q){const A=Q??"";return MB[A]=(MB[A]??0)+1,Q?`${Q}-${MB[A]}`:String(MB[A])}class tQ{id=zC()}var JA=1e-6,OA=typeof Float32Array<"u"?Float32Array:Array,co=Math.PI/180;function Uo(Q){return Q*co}function _C(){var Q=new OA(9);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[5]=0,Q[6]=0,Q[7]=0),Q[0]=1,Q[4]=1,Q[8]=1,Q}function ko(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[4],Q[4]=A[5],Q[5]=A[6],Q[6]=A[8],Q[7]=A[9],Q[8]=A[10],Q}function CI(){var Q=new OA(16);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0),Q[0]=1,Q[5]=1,Q[10]=1,Q[15]=1,Q}function Lo(Q,A,I,g,B,C,E,i,o,a,D,s,G,F,J,m){var d=new OA(16);return d[0]=Q,d[1]=A,d[2]=I,d[3]=g,d[4]=B,d[5]=C,d[6]=E,d[7]=i,d[8]=o,d[9]=a,d[10]=D,d[11]=s,d[12]=G,d[13]=F,d[14]=J,d[15]=m,d}function HB(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=A[4],i=A[5],o=A[6],a=A[7],D=A[8],s=A[9],G=A[10],F=A[11],J=A[12],m=A[13],d=A[14],T=A[15],z=I*i-g*E,u=I*o-B*E,f=I*a-C*E,Z=g*o-B*i,V=g*a-C*i,CA=B*a-C*o,sA=D*m-s*J,DA=D*d-G*J,hA=D*T-F*J,yA=s*d-G*m,uA=s*T-F*m,fA=G*T-F*d,RA=z*fA-u*uA+f*yA+Z*hA-V*DA+CA*sA;return RA?(RA=1/RA,Q[0]=(i*fA-o*uA+a*yA)*RA,Q[1]=(B*uA-g*fA-C*yA)*RA,Q[2]=(m*CA-d*V+T*Z)*RA,Q[3]=(G*V-s*CA-F*Z)*RA,Q[4]=(o*hA-E*fA-a*DA)*RA,Q[5]=(I*fA-B*hA+C*DA)*RA,Q[6]=(d*f-J*CA-T*u)*RA,Q[7]=(D*CA-G*f+F*u)*RA,Q[8]=(E*uA-i*hA+a*sA)*RA,Q[9]=(g*hA-I*uA-C*sA)*RA,Q[10]=(J*V-m*f+T*z)*RA,Q[11]=(s*f-D*V-F*z)*RA,Q[12]=(i*DA-E*yA-o*sA)*RA,Q[13]=(I*yA-g*DA+B*sA)*RA,Q[14]=(m*u-J*Z-d*z)*RA,Q[15]=(D*Z-s*u+G*z)*RA,Q):null}function xI(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=A[4],o=A[5],a=A[6],D=A[7],s=A[8],G=A[9],F=A[10],J=A[11],m=A[12],d=A[13],T=A[14],z=A[15],u=I[0],f=I[1],Z=I[2],V=I[3];return Q[0]=u*g+f*i+Z*s+V*m,Q[1]=u*B+f*o+Z*G+V*d,Q[2]=u*C+f*a+Z*F+V*T,Q[3]=u*E+f*D+Z*J+V*z,u=I[4],f=I[5],Z=I[6],V=I[7],Q[4]=u*g+f*i+Z*s+V*m,Q[5]=u*B+f*o+Z*G+V*d,Q[6]=u*C+f*a+Z*F+V*T,Q[7]=u*E+f*D+Z*J+V*z,u=I[8],f=I[9],Z=I[10],V=I[11],Q[8]=u*g+f*i+Z*s+V*m,Q[9]=u*B+f*o+Z*G+V*d,Q[10]=u*C+f*a+Z*F+V*T,Q[11]=u*E+f*D+Z*J+V*z,u=I[12],f=I[13],Z=I[14],V=I[15],Q[12]=u*g+f*i+Z*s+V*m,Q[13]=u*B+f*o+Z*G+V*d,Q[14]=u*C+f*a+Z*F+V*T,Q[15]=u*E+f*D+Z*J+V*z,Q}function Jo(Q,A){return Q[0]=A[0],Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=A[1],Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=A[2],Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,Q}function Yo(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=B+B,a=C+C,D=E+E,s=B*o,G=B*a,F=B*D,J=C*a,m=C*D,d=E*D,T=i*o,z=i*a,u=i*D,f=g[0],Z=g[1],V=g[2];return Q[0]=(1-(J+d))*f,Q[1]=(G+u)*f,Q[2]=(F-z)*f,Q[3]=0,Q[4]=(G-u)*Z,Q[5]=(1-(s+d))*Z,Q[6]=(m+T)*Z,Q[7]=0,Q[8]=(F+z)*V,Q[9]=(m-T)*V,Q[10]=(1-(s+J))*V,Q[11]=0,Q[12]=I[0],Q[13]=I[1],Q[14]=I[2],Q[15]=1,Q}function Ko(Q,A,I,g,B){var C=1/Math.tan(A/2);if(Q[0]=C/I,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=C,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=-1,Q[12]=0,Q[13]=0,Q[15]=0,B!=null&&B!==1/0){var E=1/(g-B);Q[10]=(B+g)*E,Q[14]=2*B*g*E}else Q[10]=-1,Q[14]=-2*g;return Q}var Mo=Ko;function Ho(Q,A,I,g,B,C,E){var i=1/(A-I),o=1/(g-B),a=1/(C-E);return Q[0]=-2*i,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=-2*o,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=2*a,Q[11]=0,Q[12]=(A+I)*i,Q[13]=(B+g)*o,Q[14]=(E+C)*a,Q[15]=1,Q}var qo=Ho;function lo(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=g[0],o=g[1],a=g[2],D=B-I[0],s=C-I[1],G=E-I[2],F=D*D+s*s+G*G;F>0&&(F=1/Math.sqrt(F),D*=F,s*=F,G*=F);var J=o*G-a*s,m=a*D-i*G,d=i*s-o*D;return F=J*J+m*m+d*d,F>0&&(F=1/Math.sqrt(F),J*=F,m*=F,d*=F),Q[0]=J,Q[1]=m,Q[2]=d,Q[3]=0,Q[4]=s*d-G*m,Q[5]=G*J-D*d,Q[6]=D*m-s*J,Q[7]=0,Q[8]=D,Q[9]=s,Q[10]=G,Q[11]=0,Q[12]=B,Q[13]=C,Q[14]=E,Q[15]=1,Q}function fo(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=Q[3],E=Q[4],i=Q[5],o=Q[6],a=Q[7],D=Q[8],s=Q[9],G=Q[10],F=Q[11],J=Q[12],m=Q[13],d=Q[14],T=Q[15],z=A[0],u=A[1],f=A[2],Z=A[3],V=A[4],CA=A[5],sA=A[6],DA=A[7],hA=A[8],yA=A[9],uA=A[10],fA=A[11],RA=A[12],pI=A[13],kI=A[14],mI=A[15];return Math.abs(I-z)<=JA*Math.max(1,Math.abs(I),Math.abs(z))&&Math.abs(g-u)<=JA*Math.max(1,Math.abs(g),Math.abs(u))&&Math.abs(B-f)<=JA*Math.max(1,Math.abs(B),Math.abs(f))&&Math.abs(C-Z)<=JA*Math.max(1,Math.abs(C),Math.abs(Z))&&Math.abs(E-V)<=JA*Math.max(1,Math.abs(E),Math.abs(V))&&Math.abs(i-CA)<=JA*Math.max(1,Math.abs(i),Math.abs(CA))&&Math.abs(o-sA)<=JA*Math.max(1,Math.abs(o),Math.abs(sA))&&Math.abs(a-DA)<=JA*Math.max(1,Math.abs(a),Math.abs(DA))&&Math.abs(D-hA)<=JA*Math.max(1,Math.abs(D),Math.abs(hA))&&Math.abs(s-yA)<=JA*Math.max(1,Math.abs(s),Math.abs(yA))&&Math.abs(G-uA)<=JA*Math.max(1,Math.abs(G),Math.abs(uA))&&Math.abs(F-fA)<=JA*Math.max(1,Math.abs(F),Math.abs(fA))&&Math.abs(J-RA)<=JA*Math.max(1,Math.abs(J),Math.abs(RA))&&Math.abs(m-pI)<=JA*Math.max(1,Math.abs(m),Math.abs(pI))&&Math.abs(d-kI)<=JA*Math.max(1,Math.abs(d),Math.abs(kI))&&Math.abs(T-mI)<=JA*Math.max(1,Math.abs(T),Math.abs(mI))}function dA(){var Q=new OA(3);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q}function dI(Q){var A=new OA(3);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A}function GQ(Q){var A=Q[0],I=Q[1],g=Q[2];return Math.sqrt(A*A+I*I+g*g)}function SA(Q,A,I){var g=new OA(3);return g[0]=Q,g[1]=A,g[2]=I,g}function wQ(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q}function Qg(Q,A,I,g){return Q[0]=A,Q[1]=I,Q[2]=g,Q}function gB(Q,A,I){return Q[0]=A[0]+I[0],Q[1]=A[1]+I[1],Q[2]=A[2]+I[2],Q}function po(Q,A,I){return Q[0]=A[0]-I[0],Q[1]=A[1]-I[1],Q[2]=A[2]-I[2],Q}function mo(Q,A,I){return Q[0]=A[0]*I[0],Q[1]=A[1]*I[1],Q[2]=A[2]*I[2],Q}function BB(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q}function $C(Q,A,I,g){return Q[0]=A[0]+I[0]*g,Q[1]=A[1]+I[1]*g,Q[2]=A[2]+I[2]*g,Q}function AE(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1],B=A[2]-Q[2];return I*I+g*g+B*B}function uo(Q,A){var I=A[0],g=A[1],B=A[2],C=I*I+g*g+B*B;return C>0&&(C=1/Math.sqrt(C)),Q[0]=A[0]*C,Q[1]=A[1]*C,Q[2]=A[2]*C,Q}function IE(Q,A){return Q[0]*A[0]+Q[1]*A[1]+Q[2]*A[2]}function FQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return Q[0]=B*o-C*i,Q[1]=C*E-g*o,Q[2]=g*i-B*E,Q}function eQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[3]*g+I[7]*B+I[11]*C+I[15];return E=E||1,Q[0]=(I[0]*g+I[4]*B+I[8]*C+I[12])/E,Q[1]=(I[1]*g+I[5]*B+I[9]*C+I[13])/E,Q[2]=(I[2]*g+I[6]*B+I[10]*C+I[14])/E,Q}function xo(Q){return Q[0]=0,Q[1]=0,Q[2]=0,Q}function rQ(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=JA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(g-E)<=JA*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(B-i)<=JA*Math.max(1,Math.abs(B),Math.abs(i))}var nQ=po,Wo=GQ;(function(){var Q=dA();return function(A,I,g,B,C,E){var i,o;for(I||(I=3),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2];return A}})();function cg(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0,Q[3]=0),Q}function To(Q){var A=new OA(4);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A[3]=Q[3],A}function dB(Q,A,I,g){var B=new OA(4);return B[0]=Q,B[1]=A,B[2]=I,B[3]=g,B}function bo(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[3],Q}function Zo(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q[3]=A[3]*I,Q}function Po(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=I*I+g*g+B*B+C*C;return E>0&&(E=1/Math.sqrt(E)),Q[0]=I*E,Q[1]=g*E,Q[2]=B*E,Q[3]=C*E,Q}function QB(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3];return Q[0]=I[0]*g+I[4]*B+I[8]*C+I[12]*E,Q[1]=I[1]*g+I[5]*B+I[9]*C+I[13]*E,Q[2]=I[2]*g+I[6]*B+I[10]*C+I[14]*E,Q[3]=I[3]*g+I[7]*B+I[11]*C+I[15]*E,Q}(function(){var Q=cg();return function(A,I,g,B,C,E){var i,o;for(I||(I=4),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],Q[3]=A[i+3],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2],A[i+3]=Q[3];return A}})();function SQ(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q[3]=1,Q}function Vo(Q,A,I){I=I*.5;var g=Math.sin(I);return Q[0]=g*A[0],Q[1]=g*A[1],Q[2]=g*A[2],Q[3]=Math.cos(I),Q}function Oo(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=I[0],o=I[1],a=I[2],D=I[3];return Q[0]=g*D+E*i+B*a-C*o,Q[1]=B*D+E*o+C*i-g*a,Q[2]=C*D+E*a+g*o-B*i,Q[3]=E*D-g*i-B*o-C*a,Q}function NQ(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=I[0],a=I[1],D=I[2],s=I[3],G,F,J,m,d;return F=B*o+C*a+E*D+i*s,F<0&&(F=-F,o=-o,a=-a,D=-D,s=-s),1-F>JA?(G=Math.acos(F),J=Math.sin(G),m=Math.sin((1-g)*G)/J,d=Math.sin(g*G)/J):(m=1-g,d=g),Q[0]=m*B+d*o,Q[1]=m*C+d*a,Q[2]=m*E+d*D,Q[3]=m*i+d*s,Q}function gE(Q,A){var I=A[0]+A[4]+A[8],g;if(I>0)g=Math.sqrt(I+1),Q[3]=.5*g,g=.5/g,Q[0]=(A[5]-A[7])*g,Q[1]=(A[6]-A[2])*g,Q[2]=(A[1]-A[3])*g;else{var B=0;A[4]>A[0]&&(B=1),A[8]>A[B*3+B]&&(B=2);var C=(B+1)%3,E=(B+2)%3;g=Math.sqrt(A[B*3+B]-A[C*3+C]-A[E*3+E]+1),Q[B]=.5*g,g=.5/g,Q[3]=(A[C*3+E]-A[E*3+C])*g,Q[C]=(A[C*3+B]+A[B*3+C])*g,Q[E]=(A[E*3+B]+A[B*3+E])*g}return Q}var vo=To,Xo=bo,RQ=Po;(function(){var Q=dA(),A=SA(1,0,0),I=SA(0,1,0);return function(g,B,C){var E=IE(B,C);return E<-.999999?(FQ(Q,A,B),Wo(Q)<1e-6&&FQ(Q,I,B),uo(Q,Q),Vo(g,Q,Math.PI),g):E>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(FQ(Q,B,C),g[0]=Q[0],g[1]=Q[1],g[2]=Q[2],g[3]=1+E,RQ(g,g))}})(),(function(){var Q=SQ(),A=SQ();return function(I,g,B,C,E,i){return NQ(Q,g,E,i),NQ(A,B,C,i),NQ(I,Q,A,2*i*(1-i)),I}})(),(function(){var Q=_C();return function(A,I,g,B){return Q[0]=g[0],Q[3]=g[1],Q[6]=g[2],Q[1]=B[0],Q[4]=B[1],Q[7]=B[2],Q[2]=-I[0],Q[5]=-I[1],Q[8]=-I[2],RQ(A,gE(A,Q))}})();function BE(){var Q=new OA(2);return OA!=Float32Array&&(Q[0]=0,Q[1]=0),Q}function QE(Q){var A=new OA(2);return A[0]=Q[0],A[1]=Q[1],A}function WA(Q,A){var I=new OA(2);return I[0]=Q,I[1]=A,I}function jo(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1];return Math.sqrt(I*I+g*g)}function zo(Q){var A=Q[0],I=Q[1];return A*A+I*I}function _o(Q,A,I,g){var B=A[0],C=A[1];return Q[0]=B+g*(I[0]-B),Q[1]=C+g*(I[1]-C),Q}function CE(Q,A){return Q[0]===A[0]&&Q[1]===A[1]}function cQ(Q,A){var I=Q[0],g=Q[1],B=A[0],C=A[1];return Math.abs(I-B)<=JA*Math.max(1,Math.abs(I),Math.abs(B))&&Math.abs(g-C)<=JA*Math.max(1,Math.abs(g),Math.abs(C))}(function(){var Q=BE();return function(A,I,g,B,C,E){var i,o;for(I||(I=2),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1];return A}})();class WI{min;max;constructor(A,I){this.min=A?dI(A):SA(1/0,1/0,1/0),this.max=I?dI(I):SA(-1/0,-1/0,-1/0)}clone(){return new WI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:g}=this,B=[SA(I[0],I[1],I[2]),SA(I[0],I[1],g[2]),SA(I[0],g[1],I[2]),SA(I[0],g[1],g[2]),SA(g[0],I[1],I[2]),SA(g[0],I[1],g[2]),SA(g[0],g[1],I[2]),SA(g[0],g[1],g[2])];this.min=SA(1/0,1/0,1/0),this.max=SA(-1/0,-1/0,-1/0);const C=dA();for(const E of B)eQ(C,E,A),this.expandWithPoint(C)}}const EE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class Ug extends tQ{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],g="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=g,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,g=new WI,B=dA();for(let C=0;C<this.vertexData_.length;C+=this.stride)B[0]=this.vertexData_[C+I+0],B[1]=this.vertexData_[C+I+1],B[2]=this.vertexData_[C+I+2],g.expandWithPoint(B);this.boundingBox_=g}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class $o{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:g}=A,B=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(B,C),this.gl_.bufferData(B,g,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(D=>{const s=EE[D.type];this.gl_.vertexAttribPointer(s,D.itemSize,this.gl_.FLOAT,!1,i,D.offset),this.gl_.enableVertexAttribArray(s)});const o={vao:I,vbo:C},{indexData:a}=A;if(a.length){const D=this.gl_.ELEMENT_ARRAY_BUFFER,s=this.gl_.createBuffer();if(!s)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(D,s),this.gl_.bufferData(D,a,this.gl_.STATIC_DRAW),o.ebo=s}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class Aa{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>=this.maxTextureUnits_)throw new Error(`Texture index ${I} must be in [0, ${this.maxTextureUnits_-1}]`);this.gl_.activeTexture(this.gl_.TEXTURE0+I);const g=this.getTextureType(A),B=this.getDataFormatInfo(A.dataFormat,A.dataType);this.textures_.has(A)||this.generateTexture(A,B,g);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(g,C),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,g),this.uploadTextureData(A,B,g),A.needsUpdate=!1),this.currentTexture_=A}disposeTexture(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),this.currentTexture_===A&&(this.currentTexture_=null);const g=this.getDataFormatInfo(A.dataFormat,A.dataType),B=this.computeStorageBytes(A,g);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-B),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.disposeTexture(A);this.gpuTextureBytes_=0,this.textureCount_=0}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,g){const B=this.gl_.createTexture();if(!B)throw new Error("Failed to create texture");if(this.gl_.bindTexture(g,B),this.isTexture2D(A))this.gl_.texStorage2D(g,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(g,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,B),this.gl_.bindTexture(g,null)}configureTextureParameters(A,I){const g=this.gl_,B=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);g.pixelStorei(g.UNPACK_ALIGNMENT,A.unpackAlignment),g.texParameteri(I,g.TEXTURE_MIN_FILTER,B),g.texParameteri(I,g.TEXTURE_MAG_FILTER,C),g.texParameteri(I,g.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),g.texParameteri(I,g.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),g.texParameteri(I,g.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,g){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(g,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(g,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:g,dataType:B}=I;if(g==="scalar"&&B!=="float"&&A!=="nearest")return AA.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}computeStorageBytes(A,I){const g=this.bytesPerTexel(I),B=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),o=0;for(let a=0;a<B;a++)o+=E*i*C*g,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class gI{min;max;constructor(A,I){this.min=A?QE(A):WA(1/0,1/0),this.max=I?QE(I):WA(-1/0,-1/0)}clone(){return new gI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1])}static equals(A,I){return CE(A.min,I.min)&&CE(A.max,I.max)}floor(){return new gI(WA(Math.floor(this.min[0]),Math.floor(this.min[1])),WA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],g=this.max[0]-this.min[0],B=this.max[1]-this.min[1];return{x:A,y:I,width:g,height:B}}}class Ia{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW)}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"premultiplied":this.setBlendFunc(this.gl_.ONE_MINUS_DST_ALPHA,this.gl_.ONE);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&gI.equals(I,this.currentViewport_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.viewport(g,B,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&gI.equals(I,this.currentScissor_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.scissor(g,B,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}setStencilTest(A){A?this.enable(this.gl_.STENCIL_TEST):this.disable(this.gl_.STENCIL_TEST)}}const ga=Jo(CI(),[1,-1,1]);class UQ extends vC{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;currentViewportSize_=[0,0];constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0,stencil:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,AA.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new Ro(I),this.bindings_=new $o(I),this.textures_=new Aa(I),this.state_=new Ia(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0;const{opaque:I,transparent:g}=A.layerManager.partitionLayers();for(const D of[...I,...g])D.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new gI(WA(0,0),WA(this.width,this.height)),E=gI.equals(B.floor(),C.floor()),i=gI.intersects(B,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(B);else{AA.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(B),this.clear();const o=B.toRect();this.currentViewportSize_=[o.width,o.height];const a=A.camera.frustum;this.state_.setDepthMask(!0);for(const D of I)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.state_.setDepthMask(!1);for(const D of g)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.renderedObjects_=this.renderedObjectsPerFrame_}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilFunc(this.gl_.EQUAL,0,255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.INCR)}renderLayer(A,I,g){if(A.objects.length===0)return;this.state_.setBlendingMode(A.transparent?A.blendMode:"none");const B=A.hasMultipleLODs();this.state_.setStencilTest(B),B&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{g.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,g){const B=A.objects[I];if(B.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),!B.programName)return;this.state_.setCullFaceMode(B.cullFaceMode),this.state_.setDepthTesting(B.depthTest),this.state_.setDepthMask(B.depthTest),this.bindings_.bindGeometry(B.geometry),B.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(B.programName);if(this.drawGeometry(B.geometry,B,A,C,g),B.wireframeEnabled){this.bindings_.bindGeometry(B.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",B.wireframeColor.rgb),this.drawGeometry(B.wireframeGeometry,B,A,E,g)}}drawGeometry(A,I,g,B,C){const E=xI(CI(),C.viewMatrix,I.transform.matrix),i=xI(CI(),ga,C.projectionMatrix),o=this.currentViewportSize_,a=I.getUniforms(),s={...g.getUniforms(),...a};for(const J of B.uniformNames)switch(J){case"ModelView":B.setUniform(J,E);break;case"Projection":B.setUniform(J,i);break;case"Resolution":B.setUniform(J,o);break;case"u_opacity":B.setUniform(J,g.opacity);break;case"CameraPositionModel":{const m=HB(CI(),E),d=dB(0,0,0,1),T=QB(cg(),d,m);B.setUniform(J,SA(T[0],T[1],T[2]));break}default:J in s&&B.setUniform(J,s[J])}const G=this.glGetPrimitive(A.primitive),F=A.indexData;F.length?this.gl_.drawElements(G,F.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(G,0,A.vertexCount)}glGetPrimitive(A){switch(A){case"points":return this.gl_.POINTS;case"triangles":return this.gl_.TRIANGLES;case"lines":return this.gl_.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const g=new gI(WA(0,0),WA(A,I));this.state_.setViewport(g)}clear(){this.gl_.clearColor(...this.backgroundColor.rgba),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}const Ba=16;class Qa{device_;slotSize_;buffer_;capacity_=Ba;cursor_=0;version_=0;clear_=[];constructor(A,I){const g=A.limits.minUniformBufferOffsetAlignment;this.device_=A,this.slotSize_=Math.ceil(I/g)*g,this.buffer_=this.createBuffer()}clear(){for(const A of this.clear_)A.destroy();this.clear_.length=0,this.cursor_=0}write(A){return this.cursor_>=this.capacity_&&this.resize(),this.device_.queue.writeBuffer(this.buffer_,this.cursor_*this.slotSize_,A),this.cursor_++,(this.cursor_-1)*this.slotSize_}get buffer(){return this.buffer_}get version(){return this.version_}resize(){const A=this.buffer_;this.capacity_*=2,this.buffer_=this.createBuffer();const I=this.device_.createCommandEncoder();I.copyBufferToBuffer(A,0,this.buffer_,0,A.size),this.device_.queue.submit([I.finish()]),this.clear_.push(A),this.version_++}createBuffer(){return this.device_.createBuffer({size:this.capacity_*this.slotSize_,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC})}}const Ca=0,Ea=1;class ia{device_;uniformBindings_=[];textureBindings_=[];constructor(A){this.device_=A}clearUniformBindings(){for(const A of this.uniformBindings_)A.buffer.clear()}setUniforms(A,I){const g=I.shaderModule.layouts.uniforms,B=I.uniformsData;let C=this.uniformBindings_.find(o=>o.layout===g);if(!C){const o=new Qa(this.device_,B.byteLength),a=this.createUniformsBindGroup(g,o,B.byteLength);C={layout:g,buffer:o,group:a,version:o.version},this.uniformBindings_.push(C)}const E=C.buffer.write(B);C.version!==C.buffer.version&&(C.group=this.createUniformsBindGroup(g,C.buffer,B.byteLength),C.version=C.buffer.version),A.setBindGroup(Ca,C.group,[E])}setTexture(A,I,g){const B=I.shaderModule.layouts.textures;if(!B)throw new Error("setTexture called on pipeline without a texture layout");let C=this.textureBindings_.find(E=>E.layout===B&&E.texture===g);if(!C){const E=this.createTexturesBindGroup(B,g);C={layout:B,texture:g,group:E},this.textureBindings_.push(C)}A.setBindGroup(Ea,C.group)}createUniformsBindGroup(A,I,g){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:{buffer:I.buffer,size:g}}]})}createTexturesBindGroup(A,I){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:I.createView()}]})}}class oa{device_;buffers_;constructor(A){this.device_=A,this.buffers_=[]}get(A){const I=this.buffers_.find(o=>o.geometry===A);if(I)return I;const g=this.device_.createBuffer({size:A.vertexData.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(g.getMappedRange()).set(A.vertexData),g.unmap();let B=null;A.indexData.byteLength>0&&(B=this.device_.createBuffer({size:A.indexData.byteLength,usage:GPUBufferUsage.INDEX,mappedAtCreation:!0}),new Uint32Array(B.getMappedRange()).set(A.indexData),B.unmap());const{attributes:C,attributesKey:E}=Da(A),i={geometry:A,vertexBuffer:g,indexBuffer:B,attributes:C,attributesKey:E};return this.buffers_.push(i),i}dispose(A){const I=this.buffers_.findIndex(B=>B.geometry===A);if(I===-1)return;const g=this.buffers_[I];g.vertexBuffer.destroy(),g.indexBuffer?.destroy(),this.buffers_.splice(I,1)}disposeAll(){for(const A of this.buffers_)A.vertexBuffer.destroy(),A.indexBuffer?.destroy();this.buffers_.length=0}}function aa(Q){switch(Q){case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("Unsupported vertex format size")}}function Da(Q){const A=[];let I="";for(const g of Q.attributes)A.push({shaderLocation:EE[g.type],offset:g.offset,format:aa(g.itemSize)}),I+=`${g.type},${g.offset},${g.itemSize}|`;return{attributes:A,attributesKey:I}}function sa(Q){return Q===1||Q===2||Q===4||Q===8}function kg(Q){if(Q instanceof Int8Array)return"byte";if(Q instanceof Int16Array)return"short";if(Q instanceof Int32Array)return"int";if(Q instanceof Uint8Array)return"unsigned_byte";if(Q instanceof Uint16Array)return"unsigned_short";if(Q instanceof Uint32Array)return"unsigned_int";if(Q instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function ha(Q){switch(Q.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function ya(Q){switch(Q.dataType){case"byte":case"unsigned_byte":return 1;case"short":case"unsigned_short":return 2;case"int":case"unsigned_int":case"float":return 4}}function ta(Q){if(Q.dataFormat==="rgb"||Q.dataFormat==="rgba")return[0,1];switch(Q.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class kQ extends tQ{dataFormat="rgba";dataType="unsigned_byte";maxFilter="nearest";minFilter="nearest";mipmapLevels=1;unpackAlignment=4;wrapR="clamp_to_edge";wrapS="clamp_to_edge";wrapT="clamp_to_edge";needsUpdate=!0;get type(){return"Texture"}}class Ga{device_;textures_;constructor(A){this.device_=A,this.textures_=[]}get(A){const I=this.textures_.find(C=>C.entry===A);if(I)return A.needsUpdate&&this.upload(A,I.texture),I.texture;const g={width:A.width,height:A.height},B=this.device_.createTexture({size:g,format:wa(A),usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});return this.upload(A,B),this.textures_.push({entry:A,texture:B}),B}upload(A,I){const g={width:A.width,height:A.height},B=ha(A),C=ya(A),E=A.width*B*C;this.device_.queue.writeTexture({texture:I},A.data,{bytesPerRow:E},g),A.needsUpdate=!1}dispose(A){const I=this.textures_.findIndex(g=>g.entry===A);I!==-1&&(this.textures_[I].texture.destroy(),this.textures_.splice(I,1))}disposeAll(){for(const A of this.textures_)A.texture.destroy();this.textures_.length=0}}function wa(Q){if(Q.dataFormat==="rgb")throw new Error("RGB texture format is not supported in WebGPU");if(Q.dataFormat==="scalar")switch(Q.dataType){case"byte":return"r8snorm";case"unsigned_byte":return"r8unorm";case"short":return"r16sint";case"unsigned_short":return"r16uint";case"int":return"r32sint";case"unsigned_int":return"r32uint";case"float":return"r32float"}switch(Q.dataType){case"byte":return"rgba8snorm";case"unsigned_byte":return"rgba8unorm";case"short":return"rgba16sint";case"unsigned_short":return"rgba16uint";case"int":return"rgba32sint";case"unsigned_int":return"rgba32uint";case"float":return"rgba32float"}}const LQ=(Q,A)=>((Q+A-1)/A|0)*A;function Fa(Q){return Object.keys(Q)}function ea(Q,A){return new Array(Q).fill(0).map((I,g)=>A(g))}const iE=Q=>ArrayBuffer.isView(Q)&&!(Q instanceof DataView),oE=Q=>Q,rA=oE({i32:{numElements:1,align:4,size:4,type:"i32",View:Int32Array},u32:{numElements:1,align:4,size:4,type:"u32",View:Uint32Array},f32:{numElements:1,align:4,size:4,type:"f32",View:Float32Array},f16:{numElements:1,align:2,size:2,type:"u16",View:Uint16Array},vec2f:{numElements:2,align:8,size:8,type:"f32",View:Float32Array},vec2i:{numElements:2,align:8,size:8,type:"i32",View:Int32Array},vec2u:{numElements:2,align:8,size:8,type:"u32",View:Uint32Array},vec2h:{numElements:2,align:4,size:4,type:"u16",View:Uint16Array},vec3i:{numElements:3,align:16,size:12,type:"i32",View:Int32Array},vec3u:{numElements:3,align:16,size:12,type:"u32",View:Uint32Array},vec3f:{numElements:3,align:16,size:12,type:"f32",View:Float32Array},vec3h:{numElements:3,align:8,size:6,type:"u16",View:Uint16Array},vec4i:{numElements:4,align:16,size:16,type:"i32",View:Int32Array},vec4u:{numElements:4,align:16,size:16,type:"u32",View:Uint32Array},vec4f:{numElements:4,align:16,size:16,type:"f32",View:Float32Array},vec4h:{numElements:4,align:8,size:8,type:"u16",View:Uint16Array},mat2x2f:{numElements:4,align:8,size:16,type:"f32",View:Float32Array},mat2x2h:{numElements:4,align:4,size:8,type:"u16",View:Uint16Array},mat3x2f:{numElements:6,align:8,size:24,type:"f32",View:Float32Array},mat3x2h:{numElements:6,align:4,size:12,type:"u16",View:Uint16Array},mat4x2f:{numElements:8,align:8,size:32,type:"f32",View:Float32Array},mat4x2h:{numElements:8,align:4,size:16,type:"u16",View:Uint16Array},mat2x3f:{numElements:8,align:16,size:32,pad:[3,1],type:"f32",View:Float32Array},mat2x3h:{numElements:8,align:8,size:16,pad:[3,1],type:"u16",View:Uint16Array},mat3x3f:{numElements:12,align:16,size:48,pad:[3,1],type:"f32",View:Float32Array},mat3x3h:{numElements:12,align:8,size:24,pad:[3,1],type:"u16",View:Uint16Array},mat4x3f:{numElements:16,align:16,size:64,pad:[3,1],type:"f32",View:Float32Array},mat4x3h:{numElements:16,align:8,size:32,pad:[3,1],type:"u16",View:Uint16Array},mat2x4f:{numElements:8,align:16,size:32,type:"f32",View:Float32Array},mat2x4h:{numElements:8,align:8,size:16,type:"u16",View:Uint16Array},mat3x4f:{numElements:12,align:16,size:48,pad:[3,1],type:"f32",View:Float32Array},mat3x4h:{numElements:12,align:8,size:24,pad:[3,1],type:"u16",View:Uint16Array},mat4x4f:{numElements:16,align:16,size:64,type:"f32",View:Float32Array},mat4x4h:{numElements:16,align:8,size:32,type:"u16",View:Uint16Array},bool:{numElements:0,align:1,size:0,type:"bool",View:Uint32Array}}),Lg=oE({...rA,"atomic<i32>":rA.i32,"atomic<u32>":rA.u32,"vec2<i32>":rA.vec2i,"vec2<u32>":rA.vec2u,"vec2<f32>":rA.vec2f,"vec2<f16>":rA.vec2h,"vec3<i32>":rA.vec3i,"vec3<u32>":rA.vec3u,"vec3<f32>":rA.vec3f,"vec3<f16>":rA.vec3h,"vec4<i32>":rA.vec4i,"vec4<u32>":rA.vec4u,"vec4<f32>":rA.vec4f,"vec4<f16>":rA.vec4h,"mat2x2<f32>":rA.mat2x2f,"mat2x2<f16>":rA.mat2x2h,"mat3x2<f32>":rA.mat3x2f,"mat3x2<f16>":rA.mat3x2h,"mat4x2<f32>":rA.mat4x2f,"mat4x2<f16>":rA.mat4x2h,"mat2x3<f32>":rA.mat2x3f,"mat2x3<f16>":rA.mat2x3h,"mat3x3<f32>":rA.mat3x3f,"mat3x3<f16>":rA.mat3x3h,"mat4x3<f32>":rA.mat4x3f,"mat4x3<f16>":rA.mat4x3h,"mat2x4<f32>":rA.mat2x4f,"mat2x4<f16>":rA.mat2x4h,"mat3x4<f32>":rA.mat3x4f,"mat3x4<f16>":rA.mat3x4h,"mat4x4<f32>":rA.mat4x4f,"mat4x4<f16>":rA.mat4x4h}),ra=Fa(Lg);function na(Q=[],A){const I=new Set;for(const g of ra){const B=Lg[g];I.has(B)||(I.add(B),B.flatten=Q.includes(g)?A:!A)}}na();function Sa(Q){const A=Q;if(A.elementType)return A.size;{const g=Q,B=A.numElements||1;if(g.fields)return Q.size*B;{const C=Q,{align:E}=Lg[C.type];return B>1?LQ(Q.size,E)*B:Q.size}}}function aE(Q,A,I,g){const{size:B,type:C}=Q;try{const{View:E,align:i,size:o}=Lg[C],a=g!==void 0,D=a?LQ(B,i):o,s=D/E.BYTES_PER_ELEMENT,G=a?g===0?(A.byteLength-I)/D:g:1;return new E(A,I,s*G)}catch{throw new Error(`unknown type: ${C}`)}}function Na(Q){return!Q.fields&&!Q.elementType}function Ra(Q,A,I){const g=I||0,B=new ArrayBuffer(Sa(Q)),C=(E,i)=>{const o=E,a=o.elementType;if(a){if(Na(a)&&Lg[a.type].flatten)return aE(a,B,i,o.numElements);{const{size:D}=DE(E),s=o.numElements===0?(B.byteLength-i)/D:o.numElements;return ea(s,G=>C(a,i+D*G))}}else{if(typeof E=="string")throw Error("unreachable");{const D=E.fields;if(D){const s={};for(const[G,{type:F,offset:J}]of Object.entries(D))s[G]=C(F,i+J);return s}else return aE(E,B,i)}}};return{views:C(Q,g),arrayBuffer:B}}function JQ(Q,A){if(Q!==void 0)if(iE(A)){const I=A;if(I.length===1&&typeof Q=="number")I[0]=Q;else if(Array.isArray(Q[0])||iE(Q[0])){const g=Q[0].length,B=g===3?4:g;for(let C=0;C<Q.length;++C){const E=C*B;I.set(Q[C],E)}}else I.set(Q)}else if(Array.isArray(A)){const I=A;Q.forEach((g,B)=>{JQ(g,I[B])})}else{const I=A;for(const[g,B]of Object.entries(Q)){const C=I[g];C&&JQ(B,C)}}}function ca(Q,A,I=0){const g=Q,B=g.group===void 0?Q:g.typeDefinition,C=Ra(B,A,I);return{...C,set(E){JQ(E,C.views)}}}function YQ(Q){const I=Q.elementType;if(I)return YQ(I);const B=Q.fields;if(B)return Object.values(B).reduce((i,{type:o})=>Math.max(i,YQ(o)),0);const{type:C}=Q,{align:E}=Lg[C];return E}function DE(Q){const I=Q.elementType;if(I){const C=I.size,E=YQ(I);return{unalignedSize:C,align:E,size:LQ(C,E)}}const B=Q.fields;if(B){const C=Object.values(B).pop();if(C.type.size===0)return DE(C.type)}return{size:0,unalignedSize:0,align:1}}class wI{constructor(A,I){this.name=A,this.attributes=I,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class sE{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class TI extends wI{constructor(A,I){super(A,I),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class bI extends wI{constructor(A,I){super(A,I),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class KQ extends wI{constructor(A,I,g){super(A,g),this.format=I}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class Cg extends wI{constructor(A,I,g,B){super(A,g),this.format=I,this.access=B}get isTemplate(){return!0}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}var pA;(Q=>{Q[Q.Uniform=0]="Uniform",Q[Q.Storage=1]="Storage",Q[Q.Immediate=2]="Immediate",Q[Q.Texture=3]="Texture",Q[Q.Sampler=4]="Sampler",Q[Q.StorageTexture=5]="StorageTexture"})(pA||(pA={}));class CB{constructor(A,I,g,B,C,E,i){this.relations=null,this.name=A,this.type=I,this.group=g,this.binding=B,this.attributes=C,this.resourceType=E,this.access=i}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class Ua{constructor(A,I){this.name=A,this.type=I}}class ka{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B,this.interpolation=null}}class hE{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B}}class La{constructor(A,I,g,B){this.name=A,this.type=I,this.attributes=g,this.id=B}}class Ja{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g}}class Ya{constructor(A,I=null,g){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=A,this.stage=I,this.attributes=g}}class Ka{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function Ma(Q){var A=(32768&Q)>>15,I=(31744&Q)>>10,g=1023&Q;return I==0?(A?-1:1)*Math.pow(2,-14)*(g/Math.pow(2,10)):I==31?g?NaN:1/0*(A?-1:1):(A?-1:1)*Math.pow(2,I-15)*(1+g/Math.pow(2,10))}const yE=new Float32Array(1),Ha=new Int32Array(yE.buffer),BI=new Uint16Array(1);function da(Q){yE[0]=Q;const A=Ha[0],I=A>>31&1;let g=A>>23&255,B=8388607&A;if(g===255)return BI[0]=I<<15|31744|(B!==0?512:0),BI[0];if(g===0){if(B===0)return BI[0]=I<<15,BI[0];B|=8388608;let C=113;for(;!(8388608&B);)B<<=1,C--;return g=127-C,B&=8388607,g>0?(B=(B>>126-g)+(B>>127-g&1),BI[0]=I<<15|g<<10|B>>13,BI[0]):(BI[0]=I<<15,BI[0])}return g=g-127+15,g>=31?(BI[0]=I<<15|31744,BI[0]):g<=0?g<-10?(BI[0]=I<<15,BI[0]):(B=(8388608|B)>>1-g,BI[0]=I<<15|B>>13,BI[0]):(B>>=13,BI[0]=I<<15|g<<10|B,BI[0])}const MQ=new Uint32Array(1),tE=new Float32Array(MQ.buffer,0,1);function GE(Q){const A=112+(Q>>6&31)<<23|(63&Q)<<17;return MQ[0]=A,tE[0]}function qa(Q,A,I,g,B,C,E,i,o){const a=g*(E>>=B)*(C>>=B)+I*E+A*i;switch(o){case"r8unorm":return[cA(Q,a,"8unorm",1)[0]];case"r8snorm":return[cA(Q,a,"8snorm",1)[0]];case"r8uint":return[cA(Q,a,"8uint",1)[0]];case"r8sint":return[cA(Q,a,"8sint",1)[0]];case"rg8unorm":{const D=cA(Q,a,"8unorm",2);return[D[0],D[1]]}case"rg8snorm":{const D=cA(Q,a,"8snorm",2);return[D[0],D[1]]}case"rg8uint":{const D=cA(Q,a,"8uint",2);return[D[0],D[1]]}case"rg8sint":{const D=cA(Q,a,"8sint",2);return[D[0],D[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const D=cA(Q,a,"8unorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8snorm":{const D=cA(Q,a,"8snorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8uint":{const D=cA(Q,a,"8uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba8sint":{const D=cA(Q,a,"8sint",4);return[D[0],D[1],D[2],D[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const D=cA(Q,a,"8unorm",4);return[D[2],D[1],D[0],D[3]]}case"r16uint":return[cA(Q,a,"16uint",1)[0]];case"r16sint":return[cA(Q,a,"16sint",1)[0]];case"r16float":return[cA(Q,a,"16float",1)[0]];case"rg16uint":{const D=cA(Q,a,"16uint",2);return[D[0],D[1]]}case"rg16sint":{const D=cA(Q,a,"16sint",2);return[D[0],D[1]]}case"rg16float":{const D=cA(Q,a,"16float",2);return[D[0],D[1]]}case"rgba16uint":{const D=cA(Q,a,"16uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16sint":{const D=cA(Q,a,"16sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16float":{const D=cA(Q,a,"16float",4);return[D[0],D[1],D[2],D[3]]}case"r32uint":return[cA(Q,a,"32uint",1)[0]];case"r32sint":return[cA(Q,a,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[cA(Q,a,"32float",1)[0]];case"rg32uint":{const D=cA(Q,a,"32uint",2);return[D[0],D[1]]}case"rg32sint":{const D=cA(Q,a,"32sint",2);return[D[0],D[1]]}case"rg32float":{const D=cA(Q,a,"32float",2);return[D[0],D[1]]}case"rgba32uint":{const D=cA(Q,a,"32uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32sint":{const D=cA(Q,a,"32sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32float":{const D=cA(Q,a,"32float",4);return[D[0],D[1],D[2],D[3]]}case"rg11b10ufloat":{const D=new Uint32Array(Q.buffer,a,1)[0],s=(4192256&D)>>11,G=(4290772992&D)>>22;return[GE(2047&D),GE(s),(function(F){const J=112+(F>>5&31)<<23|(31&F)<<18;return MQ[0]=J,tE[0]})(G),1]}}return null}function cA(Q,A,I,g){const B=[0,0,0,0];for(let C=0;C<g;++C)switch(I){case"8unorm":B[C]=Q[A]/255,A++;break;case"8snorm":B[C]=Q[A]/255*2-1,A++;break;case"8uint":B[C]=Q[A],A++;break;case"8sint":B[C]=Q[A]-127,A++;break;case"16uint":B[C]=Q[A]|Q[A+1]<<8,A+=2;break;case"16sint":B[C]=(Q[A]|Q[A+1]<<8)-32768,A+=2;break;case"16float":B[C]=Ma(Q[A]|Q[A+1]<<8),A+=2;break;case"32uint":case"32sint":B[C]=Q[A]|Q[A+1]<<8|Q[A+2]<<16|Q[A+3]<<24,A+=4;break;case"32float":B[C]=new Float32Array(Q.buffer,A,1)[0],A+=4}return B}function UA(Q,A,I,g,B){for(let C=0;C<g;++C)switch(I){case"8unorm":Q[A]=255*B[C],A++;break;case"8snorm":Q[A]=.5*(B[C]+1)*255,A++;break;case"8uint":Q[A]=B[C],A++;break;case"8sint":Q[A]=B[C]+127,A++;break;case"16uint":new Uint16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16sint":new Int16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16float":{const E=da(B[C]);new Uint16Array(Q.buffer,A,1)[0]=E,A+=2;break}case"32uint":new Uint32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32sint":new Int32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32float":new Float32Array(Q.buffer,A,1)[0]=B[C],A+=4}return B}const HQ={r8unorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8snorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8uint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8sint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg8unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8snorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"rgba8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8snorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},bgra8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bgra8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r16uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16float:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg16uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba16uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r32uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg32uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba32uint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32sint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32float:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rg11b10ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},stencil8:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!1,hasStencil:!0,channels:1},depth16unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},depth24plus:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,depthOnlyFormat:"depth32float",channels:1},"depth24plus-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,depthOnlyFormat:"depth32float",channels:1},depth32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},"depth32float-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,stencilOnlyFormat:"depth32float",channels:1},rgb9e5ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bc1-rgba-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc1-rgba-unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc4-r-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc4-r-snorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc5-rg-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc5-rg-snorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc6h-rgb-ufloat":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc6h-rgb-float":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"eac-r11unorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-r11snorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-rg11unorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"eac-rg11snorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"astc-4x4-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-4x4-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x5-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-5x5-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x6-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-6x6-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-8x5-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x5-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x6-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x6-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x8-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-8x8-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-10x5-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x5-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x6-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x6-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x8-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x8-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x10-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-10x10-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x12-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4},"astc-12x12-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4}};class FI{constructor(){this.id=FI._id++,this.line=0}get isAstNode(){return!0}get astNodeType(){return""}search(A){A(this)}searchBlock(A,I){if(A){I(qB.instance);for(const g of A)g instanceof Array?this.searchBlock(g,I):g.search(I);I(lB.instance)}}constEvaluate(A,I){throw new Error("Cannot evaluate node")}constEvaluateString(A){var I,g;return(g=(I=this.constEvaluate(A))===null||I===void 0?void 0:I.toString())!==null&&g!==void 0?g:""}}FI._id=0;class qB extends FI{}qB.instance=new qB;class lB extends FI{}lB.instance=new lB;const wE=new Set(["all","any","select","arrayLength","abs","acos","acosh","asin","asinh","atan","atanh","atan2","ceil","clamp","cos","cosh","countLeadingZeros","countOneBits","countTrailingZeros","cross","degrees","determinant","distance","dot","dot4U8Packed","dot4I8Packed","exp","exp2","extractBits","faceForward","firstLeadingBit","firstTrailingBit","floor","fma","fract","frexp","insertBits","inverseSqrt","ldexp","length","log","log2","max","min","mix","modf","normalize","pow","quantizeToF16","radians","reflect","refract","reverseBits","round","saturate","sign","sin","sinh","smoothstep","sqrt","step","tan","tanh","transpose","trunc","dpdx","dpdxCoarse","dpdxFine","dpdy","dpdyCoarse","dpdyFine","fwidth","fwidthCoarse","fwidthFine","textureDimensions","textureGather","textureGatherCompare","textureLoad","textureNumLayers","textureNumLevels","textureNumSamples","textureSample","textureSampleBias","textureSampleCompare","textureSampleCompareLevel","textureSampleGrad","textureSampleLevel","textureSampleBaseClampToEdge","textureStore","atomicLoad","atomicStore","atomicAdd","atomicSub","atomicMax","atomicMin","atomicAnd","atomicOr","atomicXor","atomicExchange","atomicCompareExchangeWeak","pack4x8snorm","pack4x8unorm","pack4xI8","pack4xU8","pack4x8Clamp","pack4xU8Clamp","pack2x16snorm","pack2x16unorm","pack2x16float","unpack4x8snorm","unpack4x8unorm","unpack4xI8","unpack4xU8","unpack2x16snorm","unpack2x16unorm","unpack2x16float","storageBarrier","textureBarrier","workgroupBarrier","workgroupUniformLoad","subgroupAdd","subgroupExclusiveAdd","subgroupInclusiveAdd","subgroupAll","subgroupAnd","subgroupAny","subgroupBallot","subgroupBroadcast","subgroupBroadcastFirst","subgroupElect","subgroupMax","subgroupMin","subgroupMul","subgroupExclusiveMul","subgroupInclusiveMul","subgroupOr","subgroupShuffle","subgroupShuffleDown","subgroupShuffleUp","subgroupShuffleXor","subgroupXor","quadBroadcast","quadSwapDiagonal","quadSwapX","quadSwapY"]);class qA extends FI{}class EB extends qA{constructor(A,I,g,B,C,E){super(),this.calls=new Set,this.name=A,this.args=I,this.returnType=g,this.body=B,this.startLine=C,this.endLine=E}get astNodeType(){return"function"}search(A){if(this.attributes)for(const I of this.attributes)A(I);A(this);for(const I of this.args)A(I);this.searchBlock(this.body,A)}}class FE extends qA{constructor(A){super(),this.expression=A}get astNodeType(){return"staticAssert"}search(A){this.expression.search(A)}}class eE extends qA{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"while"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class dQ extends qA{constructor(A,I){super(),this.body=A,this.loopId=I}get astNodeType(){return"continuing"}search(A){this.searchBlock(this.body,A)}}class rE extends qA{constructor(A,I,g,B){super(),this.init=A,this.condition=I,this.increment=g,this.body=B}get astNodeType(){return"for"}search(A){var I,g,B;(I=this.init)===null||I===void 0||I.search(A),(g=this.condition)===null||g===void 0||g.search(A),(B=this.increment)===null||B===void 0||B.search(A),this.searchBlock(this.body,A)}}class YI extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"var"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class qQ extends qA{constructor(A,I,g){super(),this.attributes=null,this.name=A,this.type=I,this.value=g}get astNodeType(){return"override"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class iB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"let"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class fB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"const"}constEvaluate(A,I){return this.value.constEvaluate(A,I)}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}var Jg,oB,M,R;(Q=>{Q.increment="++",Q.decrement="--"})(Jg||(Jg={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for IncrementOperator");return Q[I]}})(Jg||(Jg={}));class nE extends qA{constructor(A,I){super(),this.operator=A,this.variable=I}get astNodeType(){return"increment"}search(A){this.variable.search(A)}}(Q=>{Q.assign="=",Q.addAssign="+=",Q.subtractAssign="-=",Q.multiplyAssign="*=",Q.divideAssign="/=",Q.moduloAssign="%=",Q.andAssign="&=",Q.orAssign="|=",Q.xorAssign="^=",Q.shiftLeftAssign="<<=",Q.shiftRightAssign=">>="})(oB||(oB={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for AssignOperator");return I}})(oB||(oB={}));class SE extends qA{constructor(A,I,g){super(),this.operator=A,this.variable=I,this.value=g}get astNodeType(){return"assign"}search(A){this.variable.search(A),this.value.search(A)}}class lQ extends qA{constructor(A,I){super(),this.name=A,this.args=I}get astNodeType(){return"call"}isBuiltin(){return wE.has(this.name)}search(A){for(const I of this.args)I.search(A);A(this)}}class NE extends qA{constructor(A,I){super(),this.body=A,this.continuing=I}get astNodeType(){return"loop"}search(A){var I;this.searchBlock(this.body,A),(I=this.continuing)===null||I===void 0||I.search(A)}}class RE extends qA{constructor(A,I){super(),this.condition=A,this.cases=I}get astNodeType(){return"switch"}search(A){A(this);for(const I of this.cases)I.search(A)}}class cE extends qA{constructor(A,I,g,B){super(),this.condition=A,this.body=I,this.elseif=g,this.else=B}get astNodeType(){return"if"}search(A){this.condition.search(A),this.searchBlock(this.body,A),this.searchBlock(this.elseif,A),this.searchBlock(this.else,A)}}class UE extends qA{constructor(A){super(),this.value=A}get astNodeType(){return"return"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class la extends qA{constructor(A){super(),this.name=A}get astNodeType(){return"enable"}}class fa extends qA{constructor(A){super(),this.extensions=A}get astNodeType(){return"requires"}}class kE extends qA{constructor(A,I){super(),this.severity=A,this.rule=I}get astNodeType(){return"diagnostic"}}class fQ extends qA{constructor(A,I){super(),this.name=A,this.type=I}get astNodeType(){return"alias"}}class pa extends qA{get astNodeType(){return"discard"}}class LE extends qA{constructor(){super(...arguments),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class JE extends qA{constructor(){super(...arguments),this.loopId=-1}get astNodeType(){return"continue"}}class l extends qA{constructor(A){super(),this.attributes=null,this.name=A}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(A){let I=A[0];if(I.name==="f32")return I;for(let g=1;g<A.length;++g){const B=l._priority.get(I.name);l._priority.get(A[g].name)<B&&(I=A[g])}return I.name==="x32"?l.i32:I}getTypeName(){return this.name}}l.x32=new l("x32"),l.f32=new l("f32"),l.i32=new l("i32"),l.u32=new l("u32"),l.f16=new l("f16"),l.bool=new l("bool"),l.void=new l("void"),l._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class YE extends l{constructor(A){super(A)}}class qI extends l{constructor(A,I,g,B){super(A),this.members=I,this.startLine=g,this.endLine=B}get astNodeType(){return"struct"}get isStruct(){return!0}getMemberIndex(A){for(let I=0;I<this.members.length;I++)if(this.members[I].name===A)return I;return-1}search(A){for(const I of this.members)A(I)}}class L extends l{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"template"}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}L.vec2f=new L("vec2",l.f32,null),L.vec3f=new L("vec3",l.f32,null),L.vec4f=new L("vec4",l.f32,null),L.vec2i=new L("vec2",l.i32,null),L.vec3i=new L("vec3",l.i32,null),L.vec4i=new L("vec4",l.i32,null),L.vec2u=new L("vec2",l.u32,null),L.vec3u=new L("vec3",l.u32,null),L.vec4u=new L("vec4",l.u32,null),L.vec2h=new L("vec2",l.f16,null),L.vec3h=new L("vec3",l.f16,null),L.vec4h=new L("vec4",l.f16,null),L.vec2b=new L("vec2",l.bool,null),L.vec3b=new L("vec3",l.bool,null),L.vec4b=new L("vec4",l.bool,null),L.mat2x2f=new L("mat2x2",l.f32,null),L.mat2x3f=new L("mat2x3",l.f32,null),L.mat2x4f=new L("mat2x4",l.f32,null),L.mat3x2f=new L("mat3x2",l.f32,null),L.mat3x3f=new L("mat3x3",l.f32,null),L.mat3x4f=new L("mat3x4",l.f32,null),L.mat4x2f=new L("mat4x2",l.f32,null),L.mat4x3f=new L("mat4x3",l.f32,null),L.mat4x4f=new L("mat4x4",l.f32,null),L.mat2x2h=new L("mat2x2",l.f16,null),L.mat2x3h=new L("mat2x3",l.f16,null),L.mat2x4h=new L("mat2x4",l.f16,null),L.mat3x2h=new L("mat3x2",l.f16,null),L.mat3x3h=new L("mat3x3",l.f16,null),L.mat3x4h=new L("mat3x4",l.f16,null),L.mat4x2h=new L("mat4x2",l.f16,null),L.mat4x3h=new L("mat4x3",l.f16,null),L.mat4x4h=new L("mat4x4",l.f16,null),L.mat2x2i=new L("mat2x2",l.i32,null),L.mat2x3i=new L("mat2x3",l.i32,null),L.mat2x4i=new L("mat2x4",l.i32,null),L.mat3x2i=new L("mat3x2",l.i32,null),L.mat3x3i=new L("mat3x3",l.i32,null),L.mat3x4i=new L("mat3x4",l.i32,null),L.mat4x2i=new L("mat4x2",l.i32,null),L.mat4x3i=new L("mat4x3",l.i32,null),L.mat4x4i=new L("mat4x4",l.i32,null),L.mat2x2u=new L("mat2x2",l.u32,null),L.mat2x3u=new L("mat2x3",l.u32,null),L.mat2x4u=new L("mat2x4",l.u32,null),L.mat3x2u=new L("mat3x2",l.u32,null),L.mat3x3u=new L("mat3x3",l.u32,null),L.mat3x4u=new L("mat3x4",l.u32,null),L.mat4x2u=new L("mat4x2",l.u32,null),L.mat4x3u=new L("mat4x3",l.u32,null),L.mat4x4u=new L("mat4x4",l.u32,null);class pB extends l{constructor(A,I,g,B){super(A),this.storage=I,this.type=g,this.access=B}get astNodeType(){return"pointer"}}class aB extends l{constructor(A,I,g,B){super(A),this.attributes=I,this.format=g,this.count=B}get astNodeType(){return"array"}get isArray(){return!0}}class DB extends l{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"sampler"}}class NI extends FI{constructor(){super(),this.postfix=null,this.hasParen=!1}}class Eg extends NI{constructor(A){super(),this.value=A}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class KI extends NI{constructor(A,I){super(),this.type=A,this.args=I}get astNodeType(){return"createExpr"}search(A){if(A(this),this.args)for(const I of this.args)I.search(A)}constEvaluate(A,I){return I&&(I[0]=this.type),A.evalExpression(this,A.context)}}class pQ extends NI{constructor(A,I){super(),this.cachedReturnValue=null,this.name=A,this.args=I}get astNodeType(){return"callExpr"}setCachedReturnValue(A){this.cachedReturnValue=A}get isBuiltin(){return wE.has(this.name)}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){for(const I of this.args)I.search(A);A(this)}}class EI extends NI{constructor(A){super(),this.name=A}get astNodeType(){return"varExpr"}search(A){A(this),this.postfix&&this.postfix.search(A)}constEvaluate(A,I){return A.evalExpression(this,A.context)}}class KE extends NI{constructor(A,I){super(),this.name=A,this.initializer=I}get astNodeType(){return"constExpr"}constEvaluate(A,I){const g=A.evalExpression(this.initializer,A.context);return g!==null&&this.postfix?g.getSubData(A,this.postfix,A.context):g}search(A){this.initializer.search(A)}}class vA extends NI{constructor(A,I){super(),this.value=A,this.type=I}get astNodeType(){return"literalExpr"}constEvaluate(A,I){return I!==void 0&&(I[0]=this.type),this.value}get isScalar(){return this.value instanceof U}get isVector(){return this.value instanceof e||this.value instanceof EA}get scalarValue(){return this.value instanceof U?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof e||this.value instanceof EA?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class ME extends NI{constructor(A,I){super(),this.type=A,this.value=I}get astNodeType(){return"bitcastExpr"}search(A){this.value.search(A)}}class Yg extends NI{constructor(A){super(),this.index=A}search(A){this.index.search(A)}}class HE extends NI{constructor(){super()}}class TA extends HE{constructor(A,I){super(),this.operator=A,this.right=I}get astNodeType(){return"unaryOp"}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.right.search(A)}}class RI extends HE{constructor(A,I,g){super(),this.operator=A,this.left=I,this.right=g}get astNodeType(){return"binaryOp"}_getPromotedType(A,I){return A.name===I.name?A:A.name==="f32"||I.name==="f32"?l.f32:A.name==="u32"||I.name==="u32"?l.u32:l.i32}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.left.search(A),this.right.search(A)}}class dE extends FI{constructor(A){super(),this.body=A}search(A){A(this),this.searchBlock(this.body,A)}}class mB extends NI{get astNodeType(){return"default"}}class qE extends dE{constructor(A,I){super(I),this.selectors=A}get astNodeType(){return"case"}search(A){this.searchBlock(this.body,A)}}class lE extends dE{constructor(A){super(A)}get astNodeType(){return"default"}search(A){this.searchBlock(this.body,A)}}class fE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"argument"}}class ma extends FI{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"elseif"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class pE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"member"}}class mE extends FI{constructor(A,I){super(),this.name=A,this.value=I}get astNodeType(){return"attribute"}}class cI{constructor(A,I){this.parent=null,this.typeInfo=A,this.parent=I,this.id=cI._id++}setDataValue(A,I,g,B){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(A,I,g){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}cI._id=0;class uE extends cI{constructor(A,I){super(A,I)}clone(){return this}toString(){return this.typeInfo.name}}class mQ extends cI{constructor(){super(new wI("void",null),null)}clone(){return this}toString(){return"void"}}mQ.void=new mQ;class Kg extends cI{constructor(A){super(new KQ("pointer",A.typeInfo,null),null),this.reference=A}clone(){return this}setDataValue(A,I,g,B){this.reference.setDataValue(A,I,g,B)}getSubData(A,I,g){return I?this.reference.getSubData(A,I,g):this}toString(){return`&${this.reference.toString()}`}}class U extends cI{constructor(A,I,g=null){super(I,g),A instanceof Int32Array||A instanceof Uint32Array||A instanceof Float32Array?this.data=A:this.typeInfo.name==="x32"?A-Math.floor(A)!==0?this.data=new Float32Array([A]):this.data=A>=0?new Uint32Array([A]):new Int32Array([A]):this.typeInfo.name==="i32"||this.typeInfo.name==="bool"?this.data=new Int32Array([A]):this.typeInfo.name==="u32"?this.data=new Uint32Array([A]):this.typeInfo.name==="f32"||this.typeInfo.name==="f16"?this.data=new Float32Array([A]):console.error("ScalarData2: Invalid type",I)}clone(){if(this.data instanceof Float32Array)return new U(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new U(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new U(new Uint32Array(this.data),this.typeInfo,null);throw new Error("ScalarData: Invalid data type")}get value(){return this.data[0]}set value(A){this.data[0]=A}setDataValue(A,I,g,B){if(g)return void console.error("SetDataValue: Scalar data does not support postfix",g);if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);let C=I.data[0];this.typeInfo.name==="i32"||this.typeInfo.name==="u32"?C=Math.floor(C):this.typeInfo.name==="bool"&&(C=C?1:0),this.data[0]=C}getSubData(A,I,g){return I?(console.error("getSubData: Scalar data does not support postfix",I),null):this}toString(){return`${this.value}`}}function ua(Q,A,I){const g=A.length;return g===2?I==="f32"?new e(new Float32Array(A),Q.getTypeInfo("vec2f")):I==="i32"||I==="bool"?new e(new Int32Array(A),Q.getTypeInfo("vec2i")):I==="u32"?new e(new Uint32Array(A),Q.getTypeInfo("vec2u")):I==="f16"?new e(new Float32Array(A),Q.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${I}`),null):g===3?I==="f32"?new e(new Float32Array(A),Q.getTypeInfo("vec3f")):I==="i32"||I==="bool"?new e(new Int32Array(A),Q.getTypeInfo("vec3i")):I==="u32"?new e(new Uint32Array(A),Q.getTypeInfo("vec3u")):I==="f16"?new e(new Float32Array(A),Q.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${I}`),null):g===4?I==="f32"?new e(new Float32Array(A),Q.getTypeInfo("vec4f")):I==="i32"||I==="bool"?new e(new Int32Array(A),Q.getTypeInfo("vec4i")):I==="u32"?new e(new Uint32Array(A),Q.getTypeInfo("vec4u")):I==="f16"?new e(new Float32Array(A),Q.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${I}`),null):(console.error(`getSubData: Invalid vector size ${A.length}`),null)}class e extends cI{constructor(A,I,g=null){if(super(I,g),A instanceof Float32Array||A instanceof Uint32Array||A instanceof Int32Array)this.data=A;else{const B=this.typeInfo.name;B==="vec2f"||B==="vec3f"||B==="vec4f"?this.data=new Float32Array(A):B==="vec2i"||B==="vec3i"||B==="vec4i"?this.data=new Int32Array(A):B==="vec2u"||B==="vec3u"||B==="vec4u"?this.data=new Uint32Array(A):B==="vec2h"||B==="vec3h"||B==="vec4h"?this.data=new Float32Array(A):B==="vec2b"||B==="vec3b"||B==="vec4b"?this.data=new Int32Array(A):B==="vec2"||B==="vec3"||B==="vec4"?this.data=new Float32Array(A):console.error(`VectorData: Invalid type ${B}`)}}clone(){if(this.data instanceof Float32Array)return new e(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new e(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new e(new Uint32Array(this.data),this.typeInfo,null);throw new Error("VectorData: Invalid data type")}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set vector postfix"):I instanceof e?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;let B=A.getTypeInfo("f32");if(this.typeInfo instanceof Cg)B=this.typeInfo.format||B;else{const E=this.typeInfo.name;E==="vec2f"||E==="vec3f"||E==="vec4f"?B=A.getTypeInfo("f32"):E==="vec2i"||E==="vec3i"||E==="vec4i"?B=A.getTypeInfo("i32"):E==="vec2b"||E==="vec3b"||E==="vec4b"?B=A.getTypeInfo("bool"):E==="vec2u"||E==="vec3u"||E==="vec4u"?B=A.getTypeInfo("u32"):E==="vec2h"||E==="vec3h"||E==="vec4h"?B=A.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${E}`)}let C=this;for(;I!==null&&C!==null;){if(I instanceof Yg){const E=I.index;let i=-1;if(E instanceof vA){if(!(E.value instanceof U))return console.error(`GetSubData: Invalid array index ${E.value}`),null;i=E.value.value}else{const o=A.evalExpression(E,g);if(!(o instanceof U))return console.error("GetSubData: Unknown index type",E),null;i=o.value}if(i<0||i>=C.data.length)return console.error("GetSubData: Index out of range",i),null;if(C.data instanceof Float32Array){const o=new Float32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Int32Array){const o=new Int32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Uint32Array){const o=new Uint32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}throw new Error("GetSubData: Invalid data type")}if(!(I instanceof Eg))return console.error("GetSubData: Unknown postfix",I),null;{const E=I.value.toLowerCase();if(E.length===1){let o=0;if(E==="x"||E==="r")o=0;else if(E==="y"||E==="g")o=1;else if(E==="z"||E==="b")o=2;else{if(E!=="w"&&E!=="a")return console.error(`GetSubData: Unknown member ${E}`),null;o=3}if(this.data instanceof Float32Array){let a=new Float32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Int32Array){let a=new Int32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Uint32Array){let a=new Uint32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}}const i=[];for(const o of E)o==="x"||o==="r"?i.push(this.data[0]):o==="y"||o==="g"?i.push(this.data[1]):o==="z"||o==="b"?i.push(this.data[2]):o==="w"||o==="a"?i.push(this.data[3]):console.error(`GetDataValue: Unknown member ${o}`);C=ua(A,i,B.name)}I=I.postfix}return C}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class EA extends cI{constructor(A,I,g=null){super(I,g),A instanceof Float32Array?this.data=A:this.data=new Float32Array(A)}clone(){return new EA(new Float32Array(this.data),this.typeInfo,null)}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set matrix postfix"):I instanceof EA?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;const B=this.typeInfo.name;if(A.getTypeInfo("f32"),this.typeInfo instanceof Cg)this.typeInfo.format;else if(B.endsWith("f"))A.getTypeInfo("f32");else if(B.endsWith("i"))A.getTypeInfo("i32");else if(B.endsWith("u"))A.getTypeInfo("u32");else{if(!B.endsWith("h"))return console.error(`GetDataValue: Unknown type ${B}`),null;A.getTypeInfo("f16")}if(I instanceof Yg){const C=I.index;let E=-1;if(C instanceof vA){if(!(C.value instanceof U))return console.error(`GetDataValue: Invalid array index ${C.value}`),null;E=C.value.value}else{const a=A.evalExpression(C,g);if(!(a instanceof U))return console.error("GetDataValue: Unknown index type",C),null;E=a.value}if(E<0||E>=this.data.length)return console.error("GetDataValue: Index out of range",E),null;const i=B.endsWith("h")?"h":"f";let o;if(B==="mat2x2"||B==="mat2x2f"||B==="mat2x2h"||B==="mat3x2"||B==="mat3x2f"||B==="mat3x2h"||B==="mat4x2"||B==="mat4x2f"||B==="mat4x2h")o=new e(new Float32Array(this.data.buffer,this.data.byteOffset+2*E*4,2),A.getTypeInfo(`vec2${i}`));else if(B==="mat2x3"||B==="mat2x3f"||B==="mat2x3h"||B==="mat3x3"||B==="mat3x3f"||B==="mat3x3h"||B==="mat4x3"||B==="mat4x3f"||B==="mat4x3h")o=new e(new Float32Array(this.data.buffer,this.data.byteOffset+3*E*4,3),A.getTypeInfo(`vec3${i}`));else{if(B!=="mat2x4"&&B!=="mat2x4f"&&B!=="mat2x4h"&&B!=="mat3x4"&&B!=="mat3x4f"&&B!=="mat3x4h"&&B!=="mat4x4"&&B!=="mat4x4f"&&B!=="mat4x4h")return console.error(`GetDataValue: Unknown type ${B}`),null;o=new e(new Float32Array(this.data.buffer,this.data.byteOffset+4*E*4,4),A.getTypeInfo(`vec4${i}`))}return I.postfix?o.getSubData(A,I.postfix,g):o}return console.error("GetDataValue: Invalid postfix",I),null}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class lA extends cI{constructor(A,I,g=0,B=null){super(I,B),this.buffer=A instanceof ArrayBuffer?A:A.buffer,this.offset=g}clone(){const A=new Uint8Array(new Uint8Array(this.buffer,this.offset,this.typeInfo.size));return new lA(A.buffer,this.typeInfo,0,null)}setDataValue(A,I,g,B){if(I===null)return void console.log("setDataValue: NULL data.");let C=this.offset,E=this.typeInfo;for(;g;){if(g instanceof Yg)if(E instanceof bI){const i=g.index;if(i instanceof vA){if(!(i.value instanceof U))return void console.error(`SetDataValue: Invalid index type ${i.value}`);C+=i.value.value*E.stride}else{const o=A.evalExpression(i,B);if(!(o instanceof U))return void console.error("SetDataValue: Unknown index type",i);C+=o.value*E.stride}E=E.format}else console.error(`SetDataValue: Type ${E.getTypeName()} is not an array`);else{if(!(g instanceof Eg))return void console.error("SetDataValue: Unknown postfix type",g);{const i=g.value;if(E instanceof TI){let o=!1;for(const a of E.members)if(a.name===i){C+=a.offset,E=a.type,o=!0;break}if(!o)return void console.error(`SetDataValue: Member ${i} not found`)}else if(E instanceof wI){const o=E.getTypeName();let a=0;if(i==="x"||i==="r")a=0;else if(i==="y"||i==="g")a=1;else if(i==="z"||i==="b")a=2;else{if(i!=="w"&&i!=="a")return void console.error(`SetDataValue: Unknown member ${i}`);a=3}if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);const D=I.value;return o==="vec2f"?void(new Float32Array(this.buffer,C,2)[a]=D):o==="vec3f"?void(new Float32Array(this.buffer,C,3)[a]=D):o==="vec4f"?void(new Float32Array(this.buffer,C,4)[a]=D):o==="vec2i"?void(new Int32Array(this.buffer,C,2)[a]=D):o==="vec3i"?void(new Int32Array(this.buffer,C,3)[a]=D):o==="vec4i"?void(new Int32Array(this.buffer,C,4)[a]=D):o==="vec2u"?void(new Uint32Array(this.buffer,C,2)[a]=D):o==="vec3u"?void(new Uint32Array(this.buffer,C,3)[a]=D):o==="vec4u"?void(new Uint32Array(this.buffer,C,4)[a]=D):void console.error(`SetDataValue: Type ${o} is not a struct`)}}}g=g.postfix}this.setData(A,I,E,C,B)}setData(A,I,g,B,C){const E=g.getTypeName();if(E!=="f32"&&E!=="f16")if(E!=="i32"&&E!=="atomic<i32>"&&E!=="x32")if(E!=="u32"&&E!=="atomic<u32>")if(E!=="bool"){if(E==="vec2f"||E==="vec2h"){const i=new Float32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3f"||E==="vec3h"){const i=new Float32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4f"||E==="vec4h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2i"){const i=new Int32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3i"){const i=new Int32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4i"){const i=new Int32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2u"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3u"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4u"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2b"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3b"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4b"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x2f"||E==="mat2x2h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x3f"||E==="mat2x3h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat2x4f"||E==="mat2x4h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat3x2f"||E==="mat3x2h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat3x3f"||E==="mat3x3h"){const i=new Float32Array(this.buffer,B,9);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8]))}if(E==="mat3x4f"||E==="mat3x4h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x2f"||E==="mat4x2h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat4x3f"||E==="mat4x3h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x4f"||E==="mat4x4h"){const i=new Float32Array(this.buffer,B,16);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11],i[12]=I.data[12],i[13]=I.data[13],i[14]=I.data[14],i[15]=I.data[15]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11],i[12]=I[12],i[13]=I[13],i[14]=I[14],i[15]=I[15]))}if(I instanceof lA){if(g===I.typeInfo)return void new Uint8Array(this.buffer,B,I.buffer.byteLength).set(new Uint8Array(I.buffer));console.error("SetDataValue: Type mismatch",E,I.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${E}`)}else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Uint32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Float32Array(this.buffer,B,1)[0]=I.value)}getSubData(A,I,g){var B,C,E;if(I===null)return this;let i=this.offset,o=this.typeInfo;for(;I;){if(I instanceof Yg){const D=I.index,s=D instanceof NI?A.evalExpression(D,g):D;let G=0;if(s instanceof U?G=s.value:typeof s=="number"?G=s:console.error("GetDataValue: Invalid index type",D),o instanceof bI)i+=G*o.stride,o=o.format;else{const F=o.getTypeName();F==="mat4x4"||F==="mat4x4f"||F==="mat4x4h"?(i+=16*G,o=A.getTypeInfo("vec4f")):F==="mat4x3"||F==="mat4x3f"||F==="mat4x3h"?(i+=12*G,o=A.getTypeInfo("vec3f")):F==="mat4x2"||F==="mat4x2f"||F==="mat4x2h"?(i+=8*G,o=A.getTypeInfo("vec2f")):F==="mat3x4"||F==="mat3x4f"||F==="mat3x4h"?(i+=12*G,o=A.getTypeInfo("vec4f")):F==="mat3x3"||F==="mat3x3f"||F==="mat3x3h"?(i+=9*G,o=A.getTypeInfo("vec3f")):F==="mat3x2"||F==="mat3x2f"||F==="mat3x2h"?(i+=6*G,o=A.getTypeInfo("vec2f")):F==="mat2x4"||F==="mat2x4f"||F==="mat2x4h"?(i+=8*G,o=A.getTypeInfo("vec4f")):F==="mat2x3"||F==="mat2x3f"||F==="mat2x3h"?(i+=6*G,o=A.getTypeInfo("vec3f")):F==="mat2x2"||F==="mat2x2f"||F==="mat2x2h"?(i+=4*G,o=A.getTypeInfo("vec2f")):F==="vec2f"||F==="vec3f"||F==="vec4f"?(i+=4*G,o=A.getTypeInfo("f32")):F==="vec2h"||F==="vec3h"||F==="vec4h"?(i+=2*G,o=A.getTypeInfo("f16")):F==="vec2b"||F==="vec3b"||F==="vec4b"?(i+=1*G,o=A.getTypeInfo("bool")):F==="vec2i"||F==="vec3i"||F==="vec4i"?(i+=4*G,o=A.getTypeInfo("i32")):F==="vec2u"||F==="vec3u"||F==="vec4u"?(i+=4*G,o=A.getTypeInfo("u32")):console.error(`getDataValue: Type ${o.getTypeName()} is not an array`)}}else{if(!(I instanceof Eg))return console.error("GetDataValue: Unknown postfix type",I),null;{const D=I.value;if(o instanceof TI){let s=!1;for(const G of o.members)if(G.name===D){i+=G.offset,o=G.type,s=!0;break}if(!s)return console.error(`GetDataValue: Member ${D} not found`),null}else if(o instanceof wI){const s=o.getTypeName();if(s==="vec2f"||s==="vec3f"||s==="vec4f"||s==="vec2i"||s==="vec3i"||s==="vec4i"||s==="vec2u"||s==="vec3u"||s==="vec4u"||s==="vec2b"||s==="vec3b"||s==="vec4b"||s==="vec2h"||s==="vec3h"||s==="vec4h"||s==="vec2"||s==="vec3"||s==="vec4"){if(D.length>0&&D.length<5){let G="f";const F=[];for(let J=0;J<D.length;++J){const m=D[J].toLowerCase();let d=0;if(m==="x"||m==="r")d=0;else if(m==="y"||m==="g")d=1;else if(m==="z"||m==="b")d=2;else{if(m!=="w"&&m!=="a")return console.error(`Unknown member ${D}`),null;d=3}if(D.length===1){if(s.endsWith("f"))return this.buffer.byteLength<i+4*d+4?(console.log("Insufficient buffer data"),null):new U(new Float32Array(this.buffer,i+4*d,1),A.getTypeInfo("f32"),this);if(s.endsWith("h"))return new U(new Float32Array(this.buffer,i+4*d,1),A.getTypeInfo("f16"),this);if(s.endsWith("i"))return new U(new Int32Array(this.buffer,i+4*d,1),A.getTypeInfo("i32"),this);if(s.endsWith("b"))return new U(new Int32Array(this.buffer,i+4*d,1),A.getTypeInfo("bool"),this);if(s.endsWith("u"))return new U(new Uint32Array(this.buffer,i+4*d,1),A.getTypeInfo("i32"),this)}if(s==="vec2f")F.push(new Float32Array(this.buffer,i,2)[d]);else if(s==="vec3f"){if(i+12>=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const T=new Float32Array(this.buffer,i,3);F.push(T[d])}else if(s==="vec4f")F.push(new Float32Array(this.buffer,i,4)[d]);else if(s==="vec2i")G="i",F.push(new Int32Array(this.buffer,i,2)[d]);else if(s==="vec3i")G="i",F.push(new Int32Array(this.buffer,i,3)[d]);else if(s==="vec4i")G="i",F.push(new Int32Array(this.buffer,i,4)[d]);else if(s==="vec2u"){G="u";const T=new Uint32Array(this.buffer,i,2);F.push(T[d])}else s==="vec3u"?(G="u",F.push(new Uint32Array(this.buffer,i,3)[d])):s==="vec4u"&&(G="u",F.push(new Uint32Array(this.buffer,i,4)[d]))}return F.length===2?o=A.getTypeInfo(`vec2${G}`):F.length===3?o=A.getTypeInfo(`vec3${G}`):F.length===4?o=A.getTypeInfo(`vec4${G}`):console.error(`GetDataValue: Invalid vector length ${F.length}`),new e(F,o,null)}return console.error(`GetDataValue: Unknown member ${D}`),null}return console.error(`GetDataValue: Type ${s} is not a struct`),null}}}I=I.postfix}const a=o.getTypeName();return a==="f32"?new U(new Float32Array(this.buffer,i,1),o,this):a==="i32"?new U(new Int32Array(this.buffer,i,1),o,this):a==="u32"?new U(new Uint32Array(this.buffer,i,1),o,this):a==="vec2f"?new e(new Float32Array(this.buffer,i,2),o,this):a==="vec3f"?new e(new Float32Array(this.buffer,i,3),o,this):a==="vec4f"?new e(new Float32Array(this.buffer,i,4),o,this):a==="vec2i"?new e(new Int32Array(this.buffer,i,2),o,this):a==="vec3i"?new e(new Int32Array(this.buffer,i,3),o,this):a==="vec4i"?new e(new Int32Array(this.buffer,i,4),o,this):a==="vec2u"?new e(new Uint32Array(this.buffer,i,2),o,this):a==="vec3u"?new e(new Uint32Array(this.buffer,i,3),o,this):a==="vec4u"?new e(new Uint32Array(this.buffer,i,4),o,this):o instanceof Cg&&o.name==="atomic"?((B=o.format)===null||B===void 0?void 0:B.name)==="u32"?new U(new Uint32Array(this.buffer,i,1)[0],o.format,this):((C=o.format)===null||C===void 0?void 0:C.name)==="i32"?new U(new Int32Array(this.buffer,i,1)[0],o.format,this):(console.error(`GetDataValue: Invalid atomic format ${(E=o.format)===null||E===void 0?void 0:E.name}`),null):new lA(this.buffer,o,i,this)}toArray(){const A=this.typeInfo.getTypeName();return A==="f32"||A==="f16"?new Float32Array(this.buffer,this.offset,1):A==="i32"||A==="atomic<i32>"||A==="x32"?new Int32Array(this.buffer,this.offset,1):A==="u32"||A==="atomic<u32>"?new Uint32Array(this.buffer,this.offset,1):A==="bool"?new Int32Array(this.buffer,this.offset,1):A==="vec2f"||A==="vec2h"?new Float32Array(this.buffer,this.offset,2):A==="vec3f"||A==="vec3h"?new Float32Array(this.buffer,this.offset,3):A==="vec4f"||A==="vec4h"?new Float32Array(this.buffer,this.offset,4):A==="vec2i"?new Int32Array(this.buffer,this.offset,2):A==="vec3i"?new Int32Array(this.buffer,this.offset,3):A==="vec4i"?new Int32Array(this.buffer,this.offset,4):A==="vec2u"?new Uint32Array(this.buffer,this.offset,2):A==="vec3u"?new Uint32Array(this.buffer,this.offset,3):A==="vec4u"?new Uint32Array(this.buffer,this.offset,4):A==="vec2b"?new Uint32Array(this.buffer,this.offset,2):A==="vec3b"?new Uint32Array(this.buffer,this.offset,3):A==="vec4b"?new Uint32Array(this.buffer,this.offset,4):A==="mat2x2f"||A==="mat2x2h"?new Float32Array(this.buffer,this.offset,4):A==="mat2x3f"||A==="mat2x3h"?new Float32Array(this.buffer,this.offset,6):A==="mat2x4f"||A==="mat2x4h"?new Float32Array(this.buffer,this.offset,8):A==="mat3x2f"||A==="mat3x2h"?new Float32Array(this.buffer,this.offset,6):A==="mat3x3f"||A==="mat3x3h"?new Float32Array(this.buffer,this.offset,9):A==="mat3x4f"||A==="mat3x4h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x2f"||A==="mat4x2h"?new Float32Array(this.buffer,this.offset,8):A==="mat4x3f"||A==="mat4x3h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x4f"||A==="mat4x4h"?new Float32Array(this.buffer,this.offset,16):null}toString(){let A="";if(this.typeInfo instanceof bI)if(this.typeInfo.format.name==="f32"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="i32"){const I=new Int32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="u32"){const I=new Uint32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="vec2f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}]`;for(let g=1;g<I.length/2;++g)A+=`, [${I[2*g]}, ${I[2*g+1]}]`}else if(this.typeInfo.format.name==="vec3f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}]`}else if(this.typeInfo.format.name==="vec4f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}, ${I[3]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}, ${I[g+3]}]`}else A="[...]";else this.typeInfo instanceof TI?A+="{...}":A="[...]";return A}}class lI extends cI{constructor(A,I,g,B){super(I,null),this.data=A,this.descriptor=g,this.view=B}clone(){return new lI(this.data,this.typeInfo,this.descriptor,this.view)}get width(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>0?(A=g[0])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.width)!==null&&I!==void 0?I:0}get height(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>1?(A=g[1])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.height)!==null&&I!==void 0?I:0}get depthOrArrayLayers(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>2?(A=g[2])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.depthOrArrayLayers)!==null&&I!==void 0?I:0}get format(){var A;return this.descriptor&&(A=this.descriptor.format)!==null&&A!==void 0?A:"rgba8unorm"}get sampleCount(){var A;return this.descriptor&&(A=this.descriptor.sampleCount)!==null&&A!==void 0?A:1}get mipLevelCount(){var A;return this.descriptor&&(A=this.descriptor.mipLevelCount)!==null&&A!==void 0?A:1}get dimension(){var A;return this.descriptor&&(A=this.descriptor.dimension)!==null&&A!==void 0?A:"2d"}getMipLevelSize(A){if(A>=this.mipLevelCount)return[0,0,0];const I=[this.width,this.height,this.depthOrArrayLayers];for(let g=0;g<I.length;++g)I[g]=Math.max(1,I[g]>>A);return I}get texelByteSize(){const A=this.format,I=HQ[A];return I?I.isDepthStencil?4:I.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const A=this.format,I=HQ[A];return!!I&&I.isDepthStencil}getGpuSize(){const A=this.format,I=HQ[A],g=this.width;if(!A||g<=0||!I)return-1;const B=this.height,C=this.depthOrArrayLayers,E=this.dimension;return g/I.blockWidth*(E==="1d"?1:B/I.blockHeight)*I.bytesPerBlock*C}getPixel(A,I,g=0,B=0){const C=this.texelByteSize,E=this.bytesPerRow,i=this.height,o=this.data[B];return qa(new Uint8Array(o),A,I,g,B,i,E,C,this.format)}setPixel(A,I,g,B,C){const E=this.texelByteSize,i=this.bytesPerRow,o=this.height,a=this.data[B];(function(D,s,G,F,J,m,d,T,z,u){const f=F*(d>>=J)*(m>>=J)+G*d+s*T;switch(z){case"r8unorm":return void UA(D,f,"8unorm",1,u);case"r8snorm":return void UA(D,f,"8snorm",1,u);case"r8uint":return void UA(D,f,"8uint",1,u);case"r8sint":return void UA(D,f,"8sint",1,u);case"rg8unorm":return void UA(D,f,"8unorm",2,u);case"rg8snorm":return void UA(D,f,"8snorm",2,u);case"rg8uint":return void UA(D,f,"8uint",2,u);case"rg8sint":return void UA(D,f,"8sint",2,u);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void UA(D,f,"8unorm",4,u);case"rgba8snorm":return void UA(D,f,"8snorm",4,u);case"rgba8uint":return void UA(D,f,"8uint",4,u);case"rgba8sint":return void UA(D,f,"8sint",4,u);case"r16uint":return void UA(D,f,"16uint",1,u);case"r16sint":return void UA(D,f,"16sint",1,u);case"r16float":return void UA(D,f,"16float",1,u);case"rg16uint":return void UA(D,f,"16uint",2,u);case"rg16sint":return void UA(D,f,"16sint",2,u);case"rg16float":return void UA(D,f,"16float",2,u);case"rgba16uint":return void UA(D,f,"16uint",4,u);case"rgba16sint":return void UA(D,f,"16sint",4,u);case"rgba16float":return void UA(D,f,"16float",4,u);case"r32uint":return void UA(D,f,"32uint",1,u);case"r32sint":return void UA(D,f,"32sint",1,u);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void UA(D,f,"32float",1,u);case"rg32uint":return void UA(D,f,"32uint",2,u);case"rg32sint":return void UA(D,f,"32sint",2,u);case"rg32float":return void UA(D,f,"32float",2,u);case"rgba32uint":return void UA(D,f,"32uint",4,u);case"rgba32sint":return void UA(D,f,"32sint",4,u);case"rgba32float":return void UA(D,f,"32float",4,u);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}})(new Uint8Array(a),A,I,g,B,o,i,E,this.format,C)}}(Q=>{Q[Q.token=0]="token",Q[Q.keyword=1]="keyword",Q[Q.reserved=2]="reserved"})(R||(R={}));class c{constructor(A,I,g){this.name=A,this.type=I,this.rule=g}toString(){return this.name}}class y{}M=y,y.none=new c("",R.reserved,""),y.eof=new c("EOF",R.token,""),y.reserved={asm:new c("asm",R.reserved,"asm"),bf16:new c("bf16",R.reserved,"bf16"),do:new c("do",R.reserved,"do"),enum:new c("enum",R.reserved,"enum"),f16:new c("f16",R.reserved,"f16"),f64:new c("f64",R.reserved,"f64"),handle:new c("handle",R.reserved,"handle"),i8:new c("i8",R.reserved,"i8"),i16:new c("i16",R.reserved,"i16"),i64:new c("i64",R.reserved,"i64"),mat:new c("mat",R.reserved,"mat"),premerge:new c("premerge",R.reserved,"premerge"),regardless:new c("regardless",R.reserved,"regardless"),typedef:new c("typedef",R.reserved,"typedef"),u8:new c("u8",R.reserved,"u8"),u16:new c("u16",R.reserved,"u16"),u64:new c("u64",R.reserved,"u64"),unless:new c("unless",R.reserved,"unless"),using:new c("using",R.reserved,"using"),vec:new c("vec",R.reserved,"vec"),void:new c("void",R.reserved,"void")},y.keywords={array:new c("array",R.keyword,"array"),atomic:new c("atomic",R.keyword,"atomic"),bool:new c("bool",R.keyword,"bool"),f32:new c("f32",R.keyword,"f32"),i32:new c("i32",R.keyword,"i32"),mat2x2:new c("mat2x2",R.keyword,"mat2x2"),mat2x3:new c("mat2x3",R.keyword,"mat2x3"),mat2x4:new c("mat2x4",R.keyword,"mat2x4"),mat3x2:new c("mat3x2",R.keyword,"mat3x2"),mat3x3:new c("mat3x3",R.keyword,"mat3x3"),mat3x4:new c("mat3x4",R.keyword,"mat3x4"),mat4x2:new c("mat4x2",R.keyword,"mat4x2"),mat4x3:new c("mat4x3",R.keyword,"mat4x3"),mat4x4:new c("mat4x4",R.keyword,"mat4x4"),ptr:new c("ptr",R.keyword,"ptr"),sampler:new c("sampler",R.keyword,"sampler"),sampler_comparison:new c("sampler_comparison",R.keyword,"sampler_comparison"),struct:new c("struct",R.keyword,"struct"),texture_1d:new c("texture_1d",R.keyword,"texture_1d"),texture_2d:new c("texture_2d",R.keyword,"texture_2d"),texture_2d_array:new c("texture_2d_array",R.keyword,"texture_2d_array"),texture_3d:new c("texture_3d",R.keyword,"texture_3d"),texture_cube:new c("texture_cube",R.keyword,"texture_cube"),texture_cube_array:new c("texture_cube_array",R.keyword,"texture_cube_array"),texture_multisampled_2d:new c("texture_multisampled_2d",R.keyword,"texture_multisampled_2d"),texture_storage_1d:new c("texture_storage_1d",R.keyword,"texture_storage_1d"),texture_storage_2d:new c("texture_storage_2d",R.keyword,"texture_storage_2d"),texture_storage_2d_array:new c("texture_storage_2d_array",R.keyword,"texture_storage_2d_array"),texture_storage_3d:new c("texture_storage_3d",R.keyword,"texture_storage_3d"),texture_depth_2d:new c("texture_depth_2d",R.keyword,"texture_depth_2d"),texture_depth_2d_array:new c("texture_depth_2d_array",R.keyword,"texture_depth_2d_array"),texture_depth_cube:new c("texture_depth_cube",R.keyword,"texture_depth_cube"),texture_depth_cube_array:new c("texture_depth_cube_array",R.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new c("texture_depth_multisampled_2d",R.keyword,"texture_depth_multisampled_2d"),texture_external:new c("texture_external",R.keyword,"texture_external"),u32:new c("u32",R.keyword,"u32"),vec2:new c("vec2",R.keyword,"vec2"),vec3:new c("vec3",R.keyword,"vec3"),vec4:new c("vec4",R.keyword,"vec4"),bitcast:new c("bitcast",R.keyword,"bitcast"),block:new c("block",R.keyword,"block"),break:new c("break",R.keyword,"break"),case:new c("case",R.keyword,"case"),continue:new c("continue",R.keyword,"continue"),continuing:new c("continuing",R.keyword,"continuing"),default:new c("default",R.keyword,"default"),diagnostic:new c("diagnostic",R.keyword,"diagnostic"),discard:new c("discard",R.keyword,"discard"),else:new c("else",R.keyword,"else"),enable:new c("enable",R.keyword,"enable"),fallthrough:new c("fallthrough",R.keyword,"fallthrough"),false:new c("false",R.keyword,"false"),fn:new c("fn",R.keyword,"fn"),for:new c("for",R.keyword,"for"),function:new c("function",R.keyword,"function"),if:new c("if",R.keyword,"if"),let:new c("let",R.keyword,"let"),const:new c("const",R.keyword,"const"),loop:new c("loop",R.keyword,"loop"),while:new c("while",R.keyword,"while"),private:new c("private",R.keyword,"private"),read:new c("read",R.keyword,"read"),read_write:new c("read_write",R.keyword,"read_write"),return:new c("return",R.keyword,"return"),requires:new c("requires",R.keyword,"requires"),storage:new c("storage",R.keyword,"storage"),immediate:new c("immediate",R.keyword,"immediate"),switch:new c("switch",R.keyword,"switch"),true:new c("true",R.keyword,"true"),alias:new c("alias",R.keyword,"alias"),type:new c("type",R.keyword,"type"),uniform:new c("uniform",R.keyword,"uniform"),var:new c("var",R.keyword,"var"),override:new c("override",R.keyword,"override"),workgroup:new c("workgroup",R.keyword,"workgroup"),write:new c("write",R.keyword,"write"),r8unorm:new c("r8unorm",R.keyword,"r8unorm"),r8snorm:new c("r8snorm",R.keyword,"r8snorm"),r8uint:new c("r8uint",R.keyword,"r8uint"),r8sint:new c("r8sint",R.keyword,"r8sint"),r16uint:new c("r16uint",R.keyword,"r16uint"),r16sint:new c("r16sint",R.keyword,"r16sint"),r16float:new c("r16float",R.keyword,"r16float"),rg8unorm:new c("rg8unorm",R.keyword,"rg8unorm"),rg8snorm:new c("rg8snorm",R.keyword,"rg8snorm"),rg8uint:new c("rg8uint",R.keyword,"rg8uint"),rg8sint:new c("rg8sint",R.keyword,"rg8sint"),r32uint:new c("r32uint",R.keyword,"r32uint"),r32sint:new c("r32sint",R.keyword,"r32sint"),r32float:new c("r32float",R.keyword,"r32float"),rg16uint:new c("rg16uint",R.keyword,"rg16uint"),rg16sint:new c("rg16sint",R.keyword,"rg16sint"),rg16float:new c("rg16float",R.keyword,"rg16float"),rgba8unorm:new c("rgba8unorm",R.keyword,"rgba8unorm"),rgba8unorm_srgb:new c("rgba8unorm_srgb",R.keyword,"rgba8unorm_srgb"),rgba8snorm:new c("rgba8snorm",R.keyword,"rgba8snorm"),rgba8uint:new c("rgba8uint",R.keyword,"rgba8uint"),rgba8sint:new c("rgba8sint",R.keyword,"rgba8sint"),bgra8unorm:new c("bgra8unorm",R.keyword,"bgra8unorm"),bgra8unorm_srgb:new c("bgra8unorm_srgb",R.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new c("rgb10a2unorm",R.keyword,"rgb10a2unorm"),rg11b10float:new c("rg11b10float",R.keyword,"rg11b10float"),rg32uint:new c("rg32uint",R.keyword,"rg32uint"),rg32sint:new c("rg32sint",R.keyword,"rg32sint"),rg32float:new c("rg32float",R.keyword,"rg32float"),rgba16uint:new c("rgba16uint",R.keyword,"rgba16uint"),rgba16sint:new c("rgba16sint",R.keyword,"rgba16sint"),rgba16float:new c("rgba16float",R.keyword,"rgba16float"),rgba32uint:new c("rgba32uint",R.keyword,"rgba32uint"),rgba32sint:new c("rgba32sint",R.keyword,"rgba32sint"),rgba32float:new c("rgba32float",R.keyword,"rgba32float"),static_assert:new c("static_assert",R.keyword,"static_assert"),const_assert:new c("const_assert",R.keyword,"const_assert")},y.tokens={decimal_float_literal:new c("decimal_float_literal",R.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new c("hex_float_literal",R.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new c("int_literal",R.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new c("uint_literal",R.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new c("name",R.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new c("ident",R.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new c("and",R.token,"&"),and_and:new c("and_and",R.token,"&&"),arrow:new c("arrow ",R.token,"->"),attr:new c("attr",R.token,"@"),forward_slash:new c("forward_slash",R.token,"/"),bang:new c("bang",R.token,"!"),bracket_left:new c("bracket_left",R.token,"["),bracket_right:new c("bracket_right",R.token,"]"),brace_left:new c("brace_left",R.token,"{"),brace_right:new c("brace_right",R.token,"}"),colon:new c("colon",R.token,":"),comma:new c("comma",R.token,","),equal:new c("equal",R.token,"="),equal_equal:new c("equal_equal",R.token,"=="),not_equal:new c("not_equal",R.token,"!="),greater_than:new c("greater_than",R.token,">"),greater_than_equal:new c("greater_than_equal",R.token,">="),shift_right:new c("shift_right",R.token,">>"),less_than:new c("less_than",R.token,"<"),less_than_equal:new c("less_than_equal",R.token,"<="),shift_left:new c("shift_left",R.token,"<<"),modulo:new c("modulo",R.token,"%"),minus:new c("minus",R.token,"-"),minus_minus:new c("minus_minus",R.token,"--"),period:new c("period",R.token,"."),plus:new c("plus",R.token,"+"),plus_plus:new c("plus_plus",R.token,"++"),or:new c("or",R.token,"|"),or_or:new c("or_or",R.token,"||"),paren_left:new c("paren_left",R.token,"("),paren_right:new c("paren_right",R.token,")"),semicolon:new c("semicolon",R.token,";"),star:new c("star",R.token,"*"),tilde:new c("tilde",R.token,"~"),underscore:new c("underscore",R.token,"_"),xor:new c("xor",R.token,"^"),plus_equal:new c("plus_equal",R.token,"+="),minus_equal:new c("minus_equal",R.token,"-="),times_equal:new c("times_equal",R.token,"*="),division_equal:new c("division_equal",R.token,"/="),modulo_equal:new c("modulo_equal",R.token,"%="),and_equal:new c("and_equal",R.token,"&="),or_equal:new c("or_equal",R.token,"|="),xor_equal:new c("xor_equal",R.token,"^="),shift_right_equal:new c("shift_right_equal",R.token,">>="),shift_left_equal:new c("shift_left_equal",R.token,"<<=")},y.simpleTokens={"@":M.tokens.attr,"{":M.tokens.brace_left,"}":M.tokens.brace_right,":":M.tokens.colon,",":M.tokens.comma,"(":M.tokens.paren_left,")":M.tokens.paren_right,";":M.tokens.semicolon},y.literalTokens={"&":M.tokens.and,"&&":M.tokens.and_and,"->":M.tokens.arrow,"/":M.tokens.forward_slash,"!":M.tokens.bang,"[":M.tokens.bracket_left,"]":M.tokens.bracket_right,"=":M.tokens.equal,"==":M.tokens.equal_equal,"!=":M.tokens.not_equal,">":M.tokens.greater_than,">=":M.tokens.greater_than_equal,">>":M.tokens.shift_right,"<":M.tokens.less_than,"<=":M.tokens.less_than_equal,"<<":M.tokens.shift_left,"%":M.tokens.modulo,"-":M.tokens.minus,"--":M.tokens.minus_minus,".":M.tokens.period,"+":M.tokens.plus,"++":M.tokens.plus_plus,"|":M.tokens.or,"||":M.tokens.or_or,"*":M.tokens.star,"~":M.tokens.tilde,_:M.tokens.underscore,"^":M.tokens.xor,"+=":M.tokens.plus_equal,"-=":M.tokens.minus_equal,"*=":M.tokens.times_equal,"/=":M.tokens.division_equal,"%=":M.tokens.modulo_equal,"&=":M.tokens.and_equal,"|=":M.tokens.or_equal,"^=":M.tokens.xor_equal,">>=":M.tokens.shift_right_equal,"<<=":M.tokens.shift_left_equal},y.regexTokens={decimal_float_literal:M.tokens.decimal_float_literal,hex_float_literal:M.tokens.hex_float_literal,int_literal:M.tokens.int_literal,uint_literal:M.tokens.uint_literal,ident:M.tokens.ident},y.storage_class=[M.keywords.function,M.keywords.private,M.keywords.workgroup,M.keywords.uniform,M.keywords.storage,M.keywords.immediate],y.access_mode=[M.keywords.read,M.keywords.write,M.keywords.read_write],y.sampler_type=[M.keywords.sampler,M.keywords.sampler_comparison],y.sampled_texture_type=[M.keywords.texture_1d,M.keywords.texture_2d,M.keywords.texture_2d_array,M.keywords.texture_3d,M.keywords.texture_cube,M.keywords.texture_cube_array],y.multisampled_texture_type=[M.keywords.texture_multisampled_2d],y.storage_texture_type=[M.keywords.texture_storage_1d,M.keywords.texture_storage_2d,M.keywords.texture_storage_2d_array,M.keywords.texture_storage_3d],y.depth_texture_type=[M.keywords.texture_depth_2d,M.keywords.texture_depth_2d_array,M.keywords.texture_depth_cube,M.keywords.texture_depth_cube_array,M.keywords.texture_depth_multisampled_2d],y.texture_external_type=[M.keywords.texture_external],y.any_texture_type=[...M.sampled_texture_type,...M.multisampled_texture_type,...M.storage_texture_type,...M.depth_texture_type,...M.texture_external_type],y.texel_format=[M.keywords.r8unorm,M.keywords.r8snorm,M.keywords.r8uint,M.keywords.r8sint,M.keywords.r16uint,M.keywords.r16sint,M.keywords.r16float,M.keywords.rg8unorm,M.keywords.rg8snorm,M.keywords.rg8uint,M.keywords.rg8sint,M.keywords.r32uint,M.keywords.r32sint,M.keywords.r32float,M.keywords.rg16uint,M.keywords.rg16sint,M.keywords.rg16float,M.keywords.rgba8unorm,M.keywords.rgba8unorm_srgb,M.keywords.rgba8snorm,M.keywords.rgba8uint,M.keywords.rgba8sint,M.keywords.bgra8unorm,M.keywords.bgra8unorm_srgb,M.keywords.rgb10a2unorm,M.keywords.rg11b10float,M.keywords.rg32uint,M.keywords.rg32sint,M.keywords.rg32float,M.keywords.rgba16uint,M.keywords.rgba16sint,M.keywords.rgba16float,M.keywords.rgba32uint,M.keywords.rgba32sint,M.keywords.rgba32float],y.const_literal=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.keywords.true,M.keywords.false],y.literal_or_ident=[M.tokens.ident,M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.tokens.name],y.element_count_expression=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.ident],y.template_types=[M.keywords.vec2,M.keywords.vec3,M.keywords.vec4,M.keywords.mat2x2,M.keywords.mat2x3,M.keywords.mat2x4,M.keywords.mat3x2,M.keywords.mat3x3,M.keywords.mat3x4,M.keywords.mat4x2,M.keywords.mat4x3,M.keywords.mat4x4,M.keywords.atomic,M.keywords.bitcast,...M.any_texture_type],y.attribute_name=[M.tokens.ident,M.keywords.block,M.keywords.diagnostic],y.assignment_operators=[M.tokens.equal,M.tokens.plus_equal,M.tokens.minus_equal,M.tokens.times_equal,M.tokens.division_equal,M.tokens.modulo_equal,M.tokens.and_equal,M.tokens.or_equal,M.tokens.xor_equal,M.tokens.shift_right_equal,M.tokens.shift_left_equal],y.increment_operators=[M.tokens.plus_plus,M.tokens.minus_minus];class xE{constructor(A,I,g,B,C){this.type=A,this.lexeme=I,this.line=g,this.start=B,this.end=C}toString(){return this.lexeme}isTemplateType(){return y.template_types.includes(this.type)}isArrayType(){return this.type===y.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class uB{constructor(A){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=A??""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new xE(y.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let A=this._advance();if(A==`
|
|
418
|
+
${B}`;return Q.replace(yQ,C)}const MB={};function zC(Q){const A=Q??"";return MB[A]=(MB[A]??0)+1,Q?`${Q}-${MB[A]}`:String(MB[A])}class tQ{id=zC()}var JA=1e-6,OA=typeof Float32Array<"u"?Float32Array:Array,co=Math.PI/180;function Uo(Q){return Q*co}function _C(){var Q=new OA(9);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[5]=0,Q[6]=0,Q[7]=0),Q[0]=1,Q[4]=1,Q[8]=1,Q}function ko(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[4],Q[4]=A[5],Q[5]=A[6],Q[6]=A[8],Q[7]=A[9],Q[8]=A[10],Q}function CI(){var Q=new OA(16);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0),Q[0]=1,Q[5]=1,Q[10]=1,Q[15]=1,Q}function Lo(Q,A,I,g,B,C,E,i,o,a,D,s,G,F,J,m){var d=new OA(16);return d[0]=Q,d[1]=A,d[2]=I,d[3]=g,d[4]=B,d[5]=C,d[6]=E,d[7]=i,d[8]=o,d[9]=a,d[10]=D,d[11]=s,d[12]=G,d[13]=F,d[14]=J,d[15]=m,d}function HB(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=A[4],i=A[5],o=A[6],a=A[7],D=A[8],s=A[9],G=A[10],F=A[11],J=A[12],m=A[13],d=A[14],T=A[15],z=I*i-g*E,u=I*o-B*E,f=I*a-C*E,Z=g*o-B*i,V=g*a-C*i,CA=B*a-C*o,sA=D*m-s*J,DA=D*d-G*J,hA=D*T-F*J,yA=s*d-G*m,uA=s*T-F*m,fA=G*T-F*d,RA=z*fA-u*uA+f*yA+Z*hA-V*DA+CA*sA;return RA?(RA=1/RA,Q[0]=(i*fA-o*uA+a*yA)*RA,Q[1]=(B*uA-g*fA-C*yA)*RA,Q[2]=(m*CA-d*V+T*Z)*RA,Q[3]=(G*V-s*CA-F*Z)*RA,Q[4]=(o*hA-E*fA-a*DA)*RA,Q[5]=(I*fA-B*hA+C*DA)*RA,Q[6]=(d*f-J*CA-T*u)*RA,Q[7]=(D*CA-G*f+F*u)*RA,Q[8]=(E*uA-i*hA+a*sA)*RA,Q[9]=(g*hA-I*uA-C*sA)*RA,Q[10]=(J*V-m*f+T*z)*RA,Q[11]=(s*f-D*V-F*z)*RA,Q[12]=(i*DA-E*yA-o*sA)*RA,Q[13]=(I*yA-g*DA+B*sA)*RA,Q[14]=(m*u-J*Z-d*z)*RA,Q[15]=(D*Z-s*u+G*z)*RA,Q):null}function xI(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=A[4],o=A[5],a=A[6],D=A[7],s=A[8],G=A[9],F=A[10],J=A[11],m=A[12],d=A[13],T=A[14],z=A[15],u=I[0],f=I[1],Z=I[2],V=I[3];return Q[0]=u*g+f*i+Z*s+V*m,Q[1]=u*B+f*o+Z*G+V*d,Q[2]=u*C+f*a+Z*F+V*T,Q[3]=u*E+f*D+Z*J+V*z,u=I[4],f=I[5],Z=I[6],V=I[7],Q[4]=u*g+f*i+Z*s+V*m,Q[5]=u*B+f*o+Z*G+V*d,Q[6]=u*C+f*a+Z*F+V*T,Q[7]=u*E+f*D+Z*J+V*z,u=I[8],f=I[9],Z=I[10],V=I[11],Q[8]=u*g+f*i+Z*s+V*m,Q[9]=u*B+f*o+Z*G+V*d,Q[10]=u*C+f*a+Z*F+V*T,Q[11]=u*E+f*D+Z*J+V*z,u=I[12],f=I[13],Z=I[14],V=I[15],Q[12]=u*g+f*i+Z*s+V*m,Q[13]=u*B+f*o+Z*G+V*d,Q[14]=u*C+f*a+Z*F+V*T,Q[15]=u*E+f*D+Z*J+V*z,Q}function Jo(Q,A){return Q[0]=A[0],Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=A[1],Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=A[2],Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,Q}function Yo(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=B+B,a=C+C,D=E+E,s=B*o,G=B*a,F=B*D,J=C*a,m=C*D,d=E*D,T=i*o,z=i*a,u=i*D,f=g[0],Z=g[1],V=g[2];return Q[0]=(1-(J+d))*f,Q[1]=(G+u)*f,Q[2]=(F-z)*f,Q[3]=0,Q[4]=(G-u)*Z,Q[5]=(1-(s+d))*Z,Q[6]=(m+T)*Z,Q[7]=0,Q[8]=(F+z)*V,Q[9]=(m-T)*V,Q[10]=(1-(s+J))*V,Q[11]=0,Q[12]=I[0],Q[13]=I[1],Q[14]=I[2],Q[15]=1,Q}function Ko(Q,A,I,g,B){var C=1/Math.tan(A/2);if(Q[0]=C/I,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=C,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=-1,Q[12]=0,Q[13]=0,Q[15]=0,B!=null&&B!==1/0){var E=1/(g-B);Q[10]=(B+g)*E,Q[14]=2*B*g*E}else Q[10]=-1,Q[14]=-2*g;return Q}var Mo=Ko;function Ho(Q,A,I,g,B,C,E){var i=1/(A-I),o=1/(g-B),a=1/(C-E);return Q[0]=-2*i,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=-2*o,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=2*a,Q[11]=0,Q[12]=(A+I)*i,Q[13]=(B+g)*o,Q[14]=(E+C)*a,Q[15]=1,Q}var qo=Ho;function lo(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=g[0],o=g[1],a=g[2],D=B-I[0],s=C-I[1],G=E-I[2],F=D*D+s*s+G*G;F>0&&(F=1/Math.sqrt(F),D*=F,s*=F,G*=F);var J=o*G-a*s,m=a*D-i*G,d=i*s-o*D;return F=J*J+m*m+d*d,F>0&&(F=1/Math.sqrt(F),J*=F,m*=F,d*=F),Q[0]=J,Q[1]=m,Q[2]=d,Q[3]=0,Q[4]=s*d-G*m,Q[5]=G*J-D*d,Q[6]=D*m-s*J,Q[7]=0,Q[8]=D,Q[9]=s,Q[10]=G,Q[11]=0,Q[12]=B,Q[13]=C,Q[14]=E,Q[15]=1,Q}function fo(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=Q[3],E=Q[4],i=Q[5],o=Q[6],a=Q[7],D=Q[8],s=Q[9],G=Q[10],F=Q[11],J=Q[12],m=Q[13],d=Q[14],T=Q[15],z=A[0],u=A[1],f=A[2],Z=A[3],V=A[4],CA=A[5],sA=A[6],DA=A[7],hA=A[8],yA=A[9],uA=A[10],fA=A[11],RA=A[12],pI=A[13],kI=A[14],mI=A[15];return Math.abs(I-z)<=JA*Math.max(1,Math.abs(I),Math.abs(z))&&Math.abs(g-u)<=JA*Math.max(1,Math.abs(g),Math.abs(u))&&Math.abs(B-f)<=JA*Math.max(1,Math.abs(B),Math.abs(f))&&Math.abs(C-Z)<=JA*Math.max(1,Math.abs(C),Math.abs(Z))&&Math.abs(E-V)<=JA*Math.max(1,Math.abs(E),Math.abs(V))&&Math.abs(i-CA)<=JA*Math.max(1,Math.abs(i),Math.abs(CA))&&Math.abs(o-sA)<=JA*Math.max(1,Math.abs(o),Math.abs(sA))&&Math.abs(a-DA)<=JA*Math.max(1,Math.abs(a),Math.abs(DA))&&Math.abs(D-hA)<=JA*Math.max(1,Math.abs(D),Math.abs(hA))&&Math.abs(s-yA)<=JA*Math.max(1,Math.abs(s),Math.abs(yA))&&Math.abs(G-uA)<=JA*Math.max(1,Math.abs(G),Math.abs(uA))&&Math.abs(F-fA)<=JA*Math.max(1,Math.abs(F),Math.abs(fA))&&Math.abs(J-RA)<=JA*Math.max(1,Math.abs(J),Math.abs(RA))&&Math.abs(m-pI)<=JA*Math.max(1,Math.abs(m),Math.abs(pI))&&Math.abs(d-kI)<=JA*Math.max(1,Math.abs(d),Math.abs(kI))&&Math.abs(T-mI)<=JA*Math.max(1,Math.abs(T),Math.abs(mI))}function dA(){var Q=new OA(3);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q}function dI(Q){var A=new OA(3);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A}function GQ(Q){var A=Q[0],I=Q[1],g=Q[2];return Math.sqrt(A*A+I*I+g*g)}function SA(Q,A,I){var g=new OA(3);return g[0]=Q,g[1]=A,g[2]=I,g}function wQ(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q}function Qg(Q,A,I,g){return Q[0]=A,Q[1]=I,Q[2]=g,Q}function gB(Q,A,I){return Q[0]=A[0]+I[0],Q[1]=A[1]+I[1],Q[2]=A[2]+I[2],Q}function po(Q,A,I){return Q[0]=A[0]-I[0],Q[1]=A[1]-I[1],Q[2]=A[2]-I[2],Q}function mo(Q,A,I){return Q[0]=A[0]*I[0],Q[1]=A[1]*I[1],Q[2]=A[2]*I[2],Q}function BB(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q}function $C(Q,A,I,g){return Q[0]=A[0]+I[0]*g,Q[1]=A[1]+I[1]*g,Q[2]=A[2]+I[2]*g,Q}function AE(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1],B=A[2]-Q[2];return I*I+g*g+B*B}function uo(Q,A){var I=A[0],g=A[1],B=A[2],C=I*I+g*g+B*B;return C>0&&(C=1/Math.sqrt(C)),Q[0]=A[0]*C,Q[1]=A[1]*C,Q[2]=A[2]*C,Q}function IE(Q,A){return Q[0]*A[0]+Q[1]*A[1]+Q[2]*A[2]}function FQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return Q[0]=B*o-C*i,Q[1]=C*E-g*o,Q[2]=g*i-B*E,Q}function eQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[3]*g+I[7]*B+I[11]*C+I[15];return E=E||1,Q[0]=(I[0]*g+I[4]*B+I[8]*C+I[12])/E,Q[1]=(I[1]*g+I[5]*B+I[9]*C+I[13])/E,Q[2]=(I[2]*g+I[6]*B+I[10]*C+I[14])/E,Q}function xo(Q){return Q[0]=0,Q[1]=0,Q[2]=0,Q}function rQ(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=JA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(g-E)<=JA*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(B-i)<=JA*Math.max(1,Math.abs(B),Math.abs(i))}var nQ=po,Wo=GQ;(function(){var Q=dA();return function(A,I,g,B,C,E){var i,o;for(I||(I=3),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2];return A}})();function cg(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0,Q[3]=0),Q}function To(Q){var A=new OA(4);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A[3]=Q[3],A}function dB(Q,A,I,g){var B=new OA(4);return B[0]=Q,B[1]=A,B[2]=I,B[3]=g,B}function bo(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[3],Q}function Zo(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q[3]=A[3]*I,Q}function Po(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=I*I+g*g+B*B+C*C;return E>0&&(E=1/Math.sqrt(E)),Q[0]=I*E,Q[1]=g*E,Q[2]=B*E,Q[3]=C*E,Q}function QB(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3];return Q[0]=I[0]*g+I[4]*B+I[8]*C+I[12]*E,Q[1]=I[1]*g+I[5]*B+I[9]*C+I[13]*E,Q[2]=I[2]*g+I[6]*B+I[10]*C+I[14]*E,Q[3]=I[3]*g+I[7]*B+I[11]*C+I[15]*E,Q}(function(){var Q=cg();return function(A,I,g,B,C,E){var i,o;for(I||(I=4),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],Q[3]=A[i+3],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2],A[i+3]=Q[3];return A}})();function SQ(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q[3]=1,Q}function Vo(Q,A,I){I=I*.5;var g=Math.sin(I);return Q[0]=g*A[0],Q[1]=g*A[1],Q[2]=g*A[2],Q[3]=Math.cos(I),Q}function Oo(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=I[0],o=I[1],a=I[2],D=I[3];return Q[0]=g*D+E*i+B*a-C*o,Q[1]=B*D+E*o+C*i-g*a,Q[2]=C*D+E*a+g*o-B*i,Q[3]=E*D-g*i-B*o-C*a,Q}function NQ(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=I[0],a=I[1],D=I[2],s=I[3],G,F,J,m,d;return F=B*o+C*a+E*D+i*s,F<0&&(F=-F,o=-o,a=-a,D=-D,s=-s),1-F>JA?(G=Math.acos(F),J=Math.sin(G),m=Math.sin((1-g)*G)/J,d=Math.sin(g*G)/J):(m=1-g,d=g),Q[0]=m*B+d*o,Q[1]=m*C+d*a,Q[2]=m*E+d*D,Q[3]=m*i+d*s,Q}function gE(Q,A){var I=A[0]+A[4]+A[8],g;if(I>0)g=Math.sqrt(I+1),Q[3]=.5*g,g=.5/g,Q[0]=(A[5]-A[7])*g,Q[1]=(A[6]-A[2])*g,Q[2]=(A[1]-A[3])*g;else{var B=0;A[4]>A[0]&&(B=1),A[8]>A[B*3+B]&&(B=2);var C=(B+1)%3,E=(B+2)%3;g=Math.sqrt(A[B*3+B]-A[C*3+C]-A[E*3+E]+1),Q[B]=.5*g,g=.5/g,Q[3]=(A[C*3+E]-A[E*3+C])*g,Q[C]=(A[C*3+B]+A[B*3+C])*g,Q[E]=(A[E*3+B]+A[B*3+E])*g}return Q}var vo=To,Xo=bo,RQ=Po;(function(){var Q=dA(),A=SA(1,0,0),I=SA(0,1,0);return function(g,B,C){var E=IE(B,C);return E<-.999999?(FQ(Q,A,B),Wo(Q)<1e-6&&FQ(Q,I,B),uo(Q,Q),Vo(g,Q,Math.PI),g):E>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(FQ(Q,B,C),g[0]=Q[0],g[1]=Q[1],g[2]=Q[2],g[3]=1+E,RQ(g,g))}})(),(function(){var Q=SQ(),A=SQ();return function(I,g,B,C,E,i){return NQ(Q,g,E,i),NQ(A,B,C,i),NQ(I,Q,A,2*i*(1-i)),I}})(),(function(){var Q=_C();return function(A,I,g,B){return Q[0]=g[0],Q[3]=g[1],Q[6]=g[2],Q[1]=B[0],Q[4]=B[1],Q[7]=B[2],Q[2]=-I[0],Q[5]=-I[1],Q[8]=-I[2],RQ(A,gE(A,Q))}})();function BE(){var Q=new OA(2);return OA!=Float32Array&&(Q[0]=0,Q[1]=0),Q}function QE(Q){var A=new OA(2);return A[0]=Q[0],A[1]=Q[1],A}function WA(Q,A){var I=new OA(2);return I[0]=Q,I[1]=A,I}function jo(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1];return Math.sqrt(I*I+g*g)}function zo(Q){var A=Q[0],I=Q[1];return A*A+I*I}function _o(Q,A,I,g){var B=A[0],C=A[1];return Q[0]=B+g*(I[0]-B),Q[1]=C+g*(I[1]-C),Q}function CE(Q,A){return Q[0]===A[0]&&Q[1]===A[1]}function cQ(Q,A){var I=Q[0],g=Q[1],B=A[0],C=A[1];return Math.abs(I-B)<=JA*Math.max(1,Math.abs(I),Math.abs(B))&&Math.abs(g-C)<=JA*Math.max(1,Math.abs(g),Math.abs(C))}(function(){var Q=BE();return function(A,I,g,B,C,E){var i,o;for(I||(I=2),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1];return A}})();class WI{min;max;constructor(A,I){this.min=A?dI(A):SA(1/0,1/0,1/0),this.max=I?dI(I):SA(-1/0,-1/0,-1/0)}clone(){return new WI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:g}=this,B=[SA(I[0],I[1],I[2]),SA(I[0],I[1],g[2]),SA(I[0],g[1],I[2]),SA(I[0],g[1],g[2]),SA(g[0],I[1],I[2]),SA(g[0],I[1],g[2]),SA(g[0],g[1],I[2]),SA(g[0],g[1],g[2])];this.min=SA(1/0,1/0,1/0),this.max=SA(-1/0,-1/0,-1/0);const C=dA();for(const E of B)eQ(C,E,A),this.expandWithPoint(C)}}const EE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class Ug extends tQ{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],g="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=g,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,g=new WI,B=dA();for(let C=0;C<this.vertexData_.length;C+=this.stride)B[0]=this.vertexData_[C+I+0],B[1]=this.vertexData_[C+I+1],B[2]=this.vertexData_[C+I+2],g.expandWithPoint(B);this.boundingBox_=g}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class $o{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:g}=A,B=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(B,C),this.gl_.bufferData(B,g,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(D=>{const s=EE[D.type];this.gl_.vertexAttribPointer(s,D.itemSize,this.gl_.FLOAT,!1,i,D.offset),this.gl_.enableVertexAttribArray(s)});const o={vao:I,vbo:C},{indexData:a}=A;if(a.length){const D=this.gl_.ELEMENT_ARRAY_BUFFER,s=this.gl_.createBuffer();if(!s)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(D,s),this.gl_.bufferData(D,a,this.gl_.STATIC_DRAW),o.ebo=s}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class Aa{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}bindTexture(A,I){if(this.alreadyActive(A))return;if(I<0||I>=this.maxTextureUnits_)throw new Error(`Texture index ${I} must be in [0, ${this.maxTextureUnits_-1}]`);this.gl_.activeTexture(this.gl_.TEXTURE0+I);const g=this.getTextureType(A),B=this.getDataFormatInfo(A.dataFormat,A.dataType);this.textures_.has(A)||this.generateTexture(A,B,g);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(g,C),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,g),this.uploadTextureData(A,B,g),A.needsUpdate=!1),this.currentTexture_=A}disposeTexture(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),this.currentTexture_===A&&(this.currentTexture_=null);const g=this.getDataFormatInfo(A.dataFormat,A.dataType),B=this.computeStorageBytes(A,g);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-B),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.disposeTexture(A);this.gpuTextureBytes_=0,this.textureCount_=0}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,g){const B=this.gl_.createTexture();if(!B)throw new Error("Failed to create texture");if(this.gl_.bindTexture(g,B),this.isTexture2D(A))this.gl_.texStorage2D(g,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(g,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,B),this.gl_.bindTexture(g,null)}configureTextureParameters(A,I){const g=this.gl_,B=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);g.pixelStorei(g.UNPACK_ALIGNMENT,A.unpackAlignment),g.texParameteri(I,g.TEXTURE_MIN_FILTER,B),g.texParameteri(I,g.TEXTURE_MAG_FILTER,C),g.texParameteri(I,g.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),g.texParameteri(I,g.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),g.texParameteri(I,g.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,g){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(g,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(g,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:g,dataType:B}=I;if(g==="scalar"&&B!=="float"&&A!=="nearest")return AA.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}computeStorageBytes(A,I){const g=this.bytesPerTexel(I),B=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),o=0;for(let a=0;a<B;a++)o+=E*i*C*g,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class gI{min;max;constructor(A,I){this.min=A?QE(A):WA(1/0,1/0),this.max=I?QE(I):WA(-1/0,-1/0)}clone(){return new gI(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1])}static equals(A,I){return CE(A.min,I.min)&&CE(A.max,I.max)}floor(){return new gI(WA(Math.floor(this.min[0]),Math.floor(this.min[1])),WA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],g=this.max[0]-this.min[0],B=this.max[1]-this.min[1];return{x:A,y:I,width:g,height:B}}}class Ia{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW)}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"premultiplied":this.setBlendFunc(this.gl_.ONE_MINUS_DST_ALPHA,this.gl_.ONE);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&gI.equals(I,this.currentViewport_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.viewport(g,B,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&gI.equals(I,this.currentScissor_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.scissor(g,B,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}setStencilTest(A){A?this.enable(this.gl_.STENCIL_TEST):this.disable(this.gl_.STENCIL_TEST)}}const ga=Jo(CI(),[1,-1,1]);class UQ extends vC{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;currentViewportSize_=[0,0];constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0,stencil:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,AA.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new Ro(I),this.bindings_=new $o(I),this.textures_=new Aa(I),this.state_=new Ia(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0;const{opaque:I,transparent:g}=A.layerManager.partitionLayers();for(const D of[...I,...g])D.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new gI(WA(0,0),WA(this.width,this.height)),E=gI.equals(B.floor(),C.floor()),i=gI.intersects(B,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(B);else{AA.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(B),this.clear();const o=B.toRect();this.currentViewportSize_=[o.width,o.height];const a=A.camera.frustum;this.state_.setDepthMask(!0);for(const D of I)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.state_.setDepthMask(!1);for(const D of g)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.renderedObjects_=this.renderedObjectsPerFrame_}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilFunc(this.gl_.EQUAL,0,255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.INCR)}renderLayer(A,I,g){if(A.objects.length===0)return;this.state_.setBlendingMode(A.blendMode);const B=A.hasMultipleLODs();this.state_.setStencilTest(B),B&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{g.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,g){const B=A.objects[I];if(B.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),!B.programName)return;this.state_.setCullFaceMode(B.cullFaceMode),this.state_.setDepthTesting(B.depthTest),this.state_.setDepthMask(B.depthTest),this.bindings_.bindGeometry(B.geometry),B.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(B.programName);if(this.drawGeometry(B.geometry,B,A,C,g),B.wireframeEnabled){this.bindings_.bindGeometry(B.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",B.wireframeColor.rgb),this.drawGeometry(B.wireframeGeometry,B,A,E,g)}}drawGeometry(A,I,g,B,C){const E=xI(CI(),C.viewMatrix,I.transform.matrix),i=xI(CI(),ga,C.projectionMatrix),o=this.currentViewportSize_,a=I.getUniforms(),s={...g.getUniforms(),...a};for(const J of B.uniformNames)switch(J){case"ModelView":B.setUniform(J,E);break;case"Projection":B.setUniform(J,i);break;case"Resolution":B.setUniform(J,o);break;case"u_opacity":B.setUniform(J,g.opacity);break;case"CameraPositionModel":{const m=HB(CI(),E),d=dB(0,0,0,1),T=QB(cg(),d,m);B.setUniform(J,SA(T[0],T[1],T[2]));break}default:J in s&&B.setUniform(J,s[J])}const G=this.glGetPrimitive(A.primitive),F=A.indexData;F.length?this.gl_.drawElements(G,F.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(G,0,A.vertexCount)}glGetPrimitive(A){switch(A){case"points":return this.gl_.POINTS;case"triangles":return this.gl_.TRIANGLES;case"lines":return this.gl_.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const g=new gI(WA(0,0),WA(A,I));this.state_.setViewport(g)}clear(){this.gl_.clearColor(...this.backgroundColor.rgba),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}const Ba=16;class Qa{device_;slotSize_;buffer_;capacity_=Ba;cursor_=0;version_=0;clear_=[];constructor(A,I){const g=A.limits.minUniformBufferOffsetAlignment;this.device_=A,this.slotSize_=Math.ceil(I/g)*g,this.buffer_=this.createBuffer()}clear(){for(const A of this.clear_)A.destroy();this.clear_.length=0,this.cursor_=0}write(A){return this.cursor_>=this.capacity_&&this.resize(),this.device_.queue.writeBuffer(this.buffer_,this.cursor_*this.slotSize_,A),this.cursor_++,(this.cursor_-1)*this.slotSize_}get buffer(){return this.buffer_}get version(){return this.version_}resize(){const A=this.buffer_;this.capacity_*=2,this.buffer_=this.createBuffer();const I=this.device_.createCommandEncoder();I.copyBufferToBuffer(A,0,this.buffer_,0,A.size),this.device_.queue.submit([I.finish()]),this.clear_.push(A),this.version_++}createBuffer(){return this.device_.createBuffer({size:this.capacity_*this.slotSize_,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC})}}const Ca=0,Ea=1;class ia{device_;uniformBindings_=[];textureBindings_=[];constructor(A){this.device_=A}clearUniformBindings(){for(const A of this.uniformBindings_)A.buffer.clear()}setUniforms(A,I){const g=I.shaderModule.layouts.uniforms,B=I.uniformsData;let C=this.uniformBindings_.find(o=>o.layout===g);if(!C){const o=new Qa(this.device_,B.byteLength),a=this.createUniformsBindGroup(g,o,B.byteLength);C={layout:g,buffer:o,group:a,version:o.version},this.uniformBindings_.push(C)}const E=C.buffer.write(B);C.version!==C.buffer.version&&(C.group=this.createUniformsBindGroup(g,C.buffer,B.byteLength),C.version=C.buffer.version),A.setBindGroup(Ca,C.group,[E])}setTexture(A,I,g){const B=I.shaderModule.layouts.textures;if(!B)throw new Error("setTexture called on pipeline without a texture layout");let C=this.textureBindings_.find(E=>E.layout===B&&E.texture===g);if(!C){const E=this.createTexturesBindGroup(B,g);C={layout:B,texture:g,group:E},this.textureBindings_.push(C)}A.setBindGroup(Ea,C.group)}createUniformsBindGroup(A,I,g){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:{buffer:I.buffer,size:g}}]})}createTexturesBindGroup(A,I){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:I.createView()}]})}}class oa{device_;buffers_;constructor(A){this.device_=A,this.buffers_=[]}get(A){const I=this.buffers_.find(o=>o.geometry===A);if(I)return I;const g=this.device_.createBuffer({size:A.vertexData.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(g.getMappedRange()).set(A.vertexData),g.unmap();let B=null;A.indexData.byteLength>0&&(B=this.device_.createBuffer({size:A.indexData.byteLength,usage:GPUBufferUsage.INDEX,mappedAtCreation:!0}),new Uint32Array(B.getMappedRange()).set(A.indexData),B.unmap());const{attributes:C,attributesKey:E}=Da(A),i={geometry:A,vertexBuffer:g,indexBuffer:B,attributes:C,attributesKey:E};return this.buffers_.push(i),i}dispose(A){const I=this.buffers_.findIndex(B=>B.geometry===A);if(I===-1)return;const g=this.buffers_[I];g.vertexBuffer.destroy(),g.indexBuffer?.destroy(),this.buffers_.splice(I,1)}disposeAll(){for(const A of this.buffers_)A.vertexBuffer.destroy(),A.indexBuffer?.destroy();this.buffers_.length=0}}function aa(Q){switch(Q){case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("Unsupported vertex format size")}}function Da(Q){const A=[];let I="";for(const g of Q.attributes)A.push({shaderLocation:EE[g.type],offset:g.offset,format:aa(g.itemSize)}),I+=`${g.type},${g.offset},${g.itemSize}|`;return{attributes:A,attributesKey:I}}function sa(Q){return Q===1||Q===2||Q===4||Q===8}function kg(Q){if(Q instanceof Int8Array)return"byte";if(Q instanceof Int16Array)return"short";if(Q instanceof Int32Array)return"int";if(Q instanceof Uint8Array)return"unsigned_byte";if(Q instanceof Uint16Array)return"unsigned_short";if(Q instanceof Uint32Array)return"unsigned_int";if(Q instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function ha(Q){switch(Q.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function ya(Q){switch(Q.dataType){case"byte":case"unsigned_byte":return 1;case"short":case"unsigned_short":return 2;case"int":case"unsigned_int":case"float":return 4}}function ta(Q){if(Q.dataFormat==="rgb"||Q.dataFormat==="rgba")return[0,1];switch(Q.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class kQ extends tQ{dataFormat="rgba";dataType="unsigned_byte";maxFilter="nearest";minFilter="nearest";mipmapLevels=1;unpackAlignment=4;wrapR="clamp_to_edge";wrapS="clamp_to_edge";wrapT="clamp_to_edge";needsUpdate=!0;get type(){return"Texture"}}class Ga{device_;textures_;constructor(A){this.device_=A,this.textures_=[]}get(A){const I=this.textures_.find(C=>C.entry===A);if(I)return A.needsUpdate&&this.upload(A,I.texture),I.texture;const g={width:A.width,height:A.height},B=this.device_.createTexture({size:g,format:wa(A),usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});return this.upload(A,B),this.textures_.push({entry:A,texture:B}),B}upload(A,I){const g={width:A.width,height:A.height},B=ha(A),C=ya(A),E=A.width*B*C;this.device_.queue.writeTexture({texture:I},A.data,{bytesPerRow:E},g),A.needsUpdate=!1}dispose(A){const I=this.textures_.findIndex(g=>g.entry===A);I!==-1&&(this.textures_[I].texture.destroy(),this.textures_.splice(I,1))}disposeAll(){for(const A of this.textures_)A.texture.destroy();this.textures_.length=0}}function wa(Q){if(Q.dataFormat==="rgb")throw new Error("RGB texture format is not supported in WebGPU");if(Q.dataFormat==="scalar")switch(Q.dataType){case"byte":return"r8snorm";case"unsigned_byte":return"r8unorm";case"short":return"r16sint";case"unsigned_short":return"r16uint";case"int":return"r32sint";case"unsigned_int":return"r32uint";case"float":return"r32float"}switch(Q.dataType){case"byte":return"rgba8snorm";case"unsigned_byte":return"rgba8unorm";case"short":return"rgba16sint";case"unsigned_short":return"rgba16uint";case"int":return"rgba32sint";case"unsigned_int":return"rgba32uint";case"float":return"rgba32float"}}const LQ=(Q,A)=>((Q+A-1)/A|0)*A;function Fa(Q){return Object.keys(Q)}function ea(Q,A){return new Array(Q).fill(0).map((I,g)=>A(g))}const iE=Q=>ArrayBuffer.isView(Q)&&!(Q instanceof DataView),oE=Q=>Q,rA=oE({i32:{numElements:1,align:4,size:4,type:"i32",View:Int32Array},u32:{numElements:1,align:4,size:4,type:"u32",View:Uint32Array},f32:{numElements:1,align:4,size:4,type:"f32",View:Float32Array},f16:{numElements:1,align:2,size:2,type:"u16",View:Uint16Array},vec2f:{numElements:2,align:8,size:8,type:"f32",View:Float32Array},vec2i:{numElements:2,align:8,size:8,type:"i32",View:Int32Array},vec2u:{numElements:2,align:8,size:8,type:"u32",View:Uint32Array},vec2h:{numElements:2,align:4,size:4,type:"u16",View:Uint16Array},vec3i:{numElements:3,align:16,size:12,type:"i32",View:Int32Array},vec3u:{numElements:3,align:16,size:12,type:"u32",View:Uint32Array},vec3f:{numElements:3,align:16,size:12,type:"f32",View:Float32Array},vec3h:{numElements:3,align:8,size:6,type:"u16",View:Uint16Array},vec4i:{numElements:4,align:16,size:16,type:"i32",View:Int32Array},vec4u:{numElements:4,align:16,size:16,type:"u32",View:Uint32Array},vec4f:{numElements:4,align:16,size:16,type:"f32",View:Float32Array},vec4h:{numElements:4,align:8,size:8,type:"u16",View:Uint16Array},mat2x2f:{numElements:4,align:8,size:16,type:"f32",View:Float32Array},mat2x2h:{numElements:4,align:4,size:8,type:"u16",View:Uint16Array},mat3x2f:{numElements:6,align:8,size:24,type:"f32",View:Float32Array},mat3x2h:{numElements:6,align:4,size:12,type:"u16",View:Uint16Array},mat4x2f:{numElements:8,align:8,size:32,type:"f32",View:Float32Array},mat4x2h:{numElements:8,align:4,size:16,type:"u16",View:Uint16Array},mat2x3f:{numElements:8,align:16,size:32,pad:[3,1],type:"f32",View:Float32Array},mat2x3h:{numElements:8,align:8,size:16,pad:[3,1],type:"u16",View:Uint16Array},mat3x3f:{numElements:12,align:16,size:48,pad:[3,1],type:"f32",View:Float32Array},mat3x3h:{numElements:12,align:8,size:24,pad:[3,1],type:"u16",View:Uint16Array},mat4x3f:{numElements:16,align:16,size:64,pad:[3,1],type:"f32",View:Float32Array},mat4x3h:{numElements:16,align:8,size:32,pad:[3,1],type:"u16",View:Uint16Array},mat2x4f:{numElements:8,align:16,size:32,type:"f32",View:Float32Array},mat2x4h:{numElements:8,align:8,size:16,type:"u16",View:Uint16Array},mat3x4f:{numElements:12,align:16,size:48,pad:[3,1],type:"f32",View:Float32Array},mat3x4h:{numElements:12,align:8,size:24,pad:[3,1],type:"u16",View:Uint16Array},mat4x4f:{numElements:16,align:16,size:64,type:"f32",View:Float32Array},mat4x4h:{numElements:16,align:8,size:32,type:"u16",View:Uint16Array},bool:{numElements:0,align:1,size:0,type:"bool",View:Uint32Array}}),Lg=oE({...rA,"atomic<i32>":rA.i32,"atomic<u32>":rA.u32,"vec2<i32>":rA.vec2i,"vec2<u32>":rA.vec2u,"vec2<f32>":rA.vec2f,"vec2<f16>":rA.vec2h,"vec3<i32>":rA.vec3i,"vec3<u32>":rA.vec3u,"vec3<f32>":rA.vec3f,"vec3<f16>":rA.vec3h,"vec4<i32>":rA.vec4i,"vec4<u32>":rA.vec4u,"vec4<f32>":rA.vec4f,"vec4<f16>":rA.vec4h,"mat2x2<f32>":rA.mat2x2f,"mat2x2<f16>":rA.mat2x2h,"mat3x2<f32>":rA.mat3x2f,"mat3x2<f16>":rA.mat3x2h,"mat4x2<f32>":rA.mat4x2f,"mat4x2<f16>":rA.mat4x2h,"mat2x3<f32>":rA.mat2x3f,"mat2x3<f16>":rA.mat2x3h,"mat3x3<f32>":rA.mat3x3f,"mat3x3<f16>":rA.mat3x3h,"mat4x3<f32>":rA.mat4x3f,"mat4x3<f16>":rA.mat4x3h,"mat2x4<f32>":rA.mat2x4f,"mat2x4<f16>":rA.mat2x4h,"mat3x4<f32>":rA.mat3x4f,"mat3x4<f16>":rA.mat3x4h,"mat4x4<f32>":rA.mat4x4f,"mat4x4<f16>":rA.mat4x4h}),ra=Fa(Lg);function na(Q=[],A){const I=new Set;for(const g of ra){const B=Lg[g];I.has(B)||(I.add(B),B.flatten=Q.includes(g)?A:!A)}}na();function Sa(Q){const A=Q;if(A.elementType)return A.size;{const g=Q,B=A.numElements||1;if(g.fields)return Q.size*B;{const C=Q,{align:E}=Lg[C.type];return B>1?LQ(Q.size,E)*B:Q.size}}}function aE(Q,A,I,g){const{size:B,type:C}=Q;try{const{View:E,align:i,size:o}=Lg[C],a=g!==void 0,D=a?LQ(B,i):o,s=D/E.BYTES_PER_ELEMENT,G=a?g===0?(A.byteLength-I)/D:g:1;return new E(A,I,s*G)}catch{throw new Error(`unknown type: ${C}`)}}function Na(Q){return!Q.fields&&!Q.elementType}function Ra(Q,A,I){const g=I||0,B=new ArrayBuffer(Sa(Q)),C=(E,i)=>{const o=E,a=o.elementType;if(a){if(Na(a)&&Lg[a.type].flatten)return aE(a,B,i,o.numElements);{const{size:D}=DE(E),s=o.numElements===0?(B.byteLength-i)/D:o.numElements;return ea(s,G=>C(a,i+D*G))}}else{if(typeof E=="string")throw Error("unreachable");{const D=E.fields;if(D){const s={};for(const[G,{type:F,offset:J}]of Object.entries(D))s[G]=C(F,i+J);return s}else return aE(E,B,i)}}};return{views:C(Q,g),arrayBuffer:B}}function JQ(Q,A){if(Q!==void 0)if(iE(A)){const I=A;if(I.length===1&&typeof Q=="number")I[0]=Q;else if(Array.isArray(Q[0])||iE(Q[0])){const g=Q[0].length,B=g===3?4:g;for(let C=0;C<Q.length;++C){const E=C*B;I.set(Q[C],E)}}else I.set(Q)}else if(Array.isArray(A)){const I=A;Q.forEach((g,B)=>{JQ(g,I[B])})}else{const I=A;for(const[g,B]of Object.entries(Q)){const C=I[g];C&&JQ(B,C)}}}function ca(Q,A,I=0){const g=Q,B=g.group===void 0?Q:g.typeDefinition,C=Ra(B,A,I);return{...C,set(E){JQ(E,C.views)}}}function YQ(Q){const I=Q.elementType;if(I)return YQ(I);const B=Q.fields;if(B)return Object.values(B).reduce((i,{type:o})=>Math.max(i,YQ(o)),0);const{type:C}=Q,{align:E}=Lg[C];return E}function DE(Q){const I=Q.elementType;if(I){const C=I.size,E=YQ(I);return{unalignedSize:C,align:E,size:LQ(C,E)}}const B=Q.fields;if(B){const C=Object.values(B).pop();if(C.type.size===0)return DE(C.type)}return{size:0,unalignedSize:0,align:1}}class wI{constructor(A,I){this.name=A,this.attributes=I,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class sE{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class TI extends wI{constructor(A,I){super(A,I),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class bI extends wI{constructor(A,I){super(A,I),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class KQ extends wI{constructor(A,I,g){super(A,g),this.format=I}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class Cg extends wI{constructor(A,I,g,B){super(A,g),this.format=I,this.access=B}get isTemplate(){return!0}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}var pA;(Q=>{Q[Q.Uniform=0]="Uniform",Q[Q.Storage=1]="Storage",Q[Q.Immediate=2]="Immediate",Q[Q.Texture=3]="Texture",Q[Q.Sampler=4]="Sampler",Q[Q.StorageTexture=5]="StorageTexture"})(pA||(pA={}));class CB{constructor(A,I,g,B,C,E,i){this.relations=null,this.name=A,this.type=I,this.group=g,this.binding=B,this.attributes=C,this.resourceType=E,this.access=i}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class Ua{constructor(A,I){this.name=A,this.type=I}}class ka{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B,this.interpolation=null}}class hE{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B}}class La{constructor(A,I,g,B){this.name=A,this.type=I,this.attributes=g,this.id=B}}class Ja{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g}}class Ya{constructor(A,I=null,g){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=A,this.stage=I,this.attributes=g}}class Ka{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function Ma(Q){var A=(32768&Q)>>15,I=(31744&Q)>>10,g=1023&Q;return I==0?(A?-1:1)*Math.pow(2,-14)*(g/Math.pow(2,10)):I==31?g?NaN:1/0*(A?-1:1):(A?-1:1)*Math.pow(2,I-15)*(1+g/Math.pow(2,10))}const yE=new Float32Array(1),Ha=new Int32Array(yE.buffer),BI=new Uint16Array(1);function da(Q){yE[0]=Q;const A=Ha[0],I=A>>31&1;let g=A>>23&255,B=8388607&A;if(g===255)return BI[0]=I<<15|31744|(B!==0?512:0),BI[0];if(g===0){if(B===0)return BI[0]=I<<15,BI[0];B|=8388608;let C=113;for(;!(8388608&B);)B<<=1,C--;return g=127-C,B&=8388607,g>0?(B=(B>>126-g)+(B>>127-g&1),BI[0]=I<<15|g<<10|B>>13,BI[0]):(BI[0]=I<<15,BI[0])}return g=g-127+15,g>=31?(BI[0]=I<<15|31744,BI[0]):g<=0?g<-10?(BI[0]=I<<15,BI[0]):(B=(8388608|B)>>1-g,BI[0]=I<<15|B>>13,BI[0]):(B>>=13,BI[0]=I<<15|g<<10|B,BI[0])}const MQ=new Uint32Array(1),tE=new Float32Array(MQ.buffer,0,1);function GE(Q){const A=112+(Q>>6&31)<<23|(63&Q)<<17;return MQ[0]=A,tE[0]}function qa(Q,A,I,g,B,C,E,i,o){const a=g*(E>>=B)*(C>>=B)+I*E+A*i;switch(o){case"r8unorm":return[cA(Q,a,"8unorm",1)[0]];case"r8snorm":return[cA(Q,a,"8snorm",1)[0]];case"r8uint":return[cA(Q,a,"8uint",1)[0]];case"r8sint":return[cA(Q,a,"8sint",1)[0]];case"rg8unorm":{const D=cA(Q,a,"8unorm",2);return[D[0],D[1]]}case"rg8snorm":{const D=cA(Q,a,"8snorm",2);return[D[0],D[1]]}case"rg8uint":{const D=cA(Q,a,"8uint",2);return[D[0],D[1]]}case"rg8sint":{const D=cA(Q,a,"8sint",2);return[D[0],D[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const D=cA(Q,a,"8unorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8snorm":{const D=cA(Q,a,"8snorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8uint":{const D=cA(Q,a,"8uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba8sint":{const D=cA(Q,a,"8sint",4);return[D[0],D[1],D[2],D[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const D=cA(Q,a,"8unorm",4);return[D[2],D[1],D[0],D[3]]}case"r16uint":return[cA(Q,a,"16uint",1)[0]];case"r16sint":return[cA(Q,a,"16sint",1)[0]];case"r16float":return[cA(Q,a,"16float",1)[0]];case"rg16uint":{const D=cA(Q,a,"16uint",2);return[D[0],D[1]]}case"rg16sint":{const D=cA(Q,a,"16sint",2);return[D[0],D[1]]}case"rg16float":{const D=cA(Q,a,"16float",2);return[D[0],D[1]]}case"rgba16uint":{const D=cA(Q,a,"16uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16sint":{const D=cA(Q,a,"16sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16float":{const D=cA(Q,a,"16float",4);return[D[0],D[1],D[2],D[3]]}case"r32uint":return[cA(Q,a,"32uint",1)[0]];case"r32sint":return[cA(Q,a,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[cA(Q,a,"32float",1)[0]];case"rg32uint":{const D=cA(Q,a,"32uint",2);return[D[0],D[1]]}case"rg32sint":{const D=cA(Q,a,"32sint",2);return[D[0],D[1]]}case"rg32float":{const D=cA(Q,a,"32float",2);return[D[0],D[1]]}case"rgba32uint":{const D=cA(Q,a,"32uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32sint":{const D=cA(Q,a,"32sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32float":{const D=cA(Q,a,"32float",4);return[D[0],D[1],D[2],D[3]]}case"rg11b10ufloat":{const D=new Uint32Array(Q.buffer,a,1)[0],s=(4192256&D)>>11,G=(4290772992&D)>>22;return[GE(2047&D),GE(s),(function(F){const J=112+(F>>5&31)<<23|(31&F)<<18;return MQ[0]=J,tE[0]})(G),1]}}return null}function cA(Q,A,I,g){const B=[0,0,0,0];for(let C=0;C<g;++C)switch(I){case"8unorm":B[C]=Q[A]/255,A++;break;case"8snorm":B[C]=Q[A]/255*2-1,A++;break;case"8uint":B[C]=Q[A],A++;break;case"8sint":B[C]=Q[A]-127,A++;break;case"16uint":B[C]=Q[A]|Q[A+1]<<8,A+=2;break;case"16sint":B[C]=(Q[A]|Q[A+1]<<8)-32768,A+=2;break;case"16float":B[C]=Ma(Q[A]|Q[A+1]<<8),A+=2;break;case"32uint":case"32sint":B[C]=Q[A]|Q[A+1]<<8|Q[A+2]<<16|Q[A+3]<<24,A+=4;break;case"32float":B[C]=new Float32Array(Q.buffer,A,1)[0],A+=4}return B}function UA(Q,A,I,g,B){for(let C=0;C<g;++C)switch(I){case"8unorm":Q[A]=255*B[C],A++;break;case"8snorm":Q[A]=.5*(B[C]+1)*255,A++;break;case"8uint":Q[A]=B[C],A++;break;case"8sint":Q[A]=B[C]+127,A++;break;case"16uint":new Uint16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16sint":new Int16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16float":{const E=da(B[C]);new Uint16Array(Q.buffer,A,1)[0]=E,A+=2;break}case"32uint":new Uint32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32sint":new Int32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32float":new Float32Array(Q.buffer,A,1)[0]=B[C],A+=4}return B}const HQ={r8unorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8snorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8uint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8sint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg8unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8snorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"rgba8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8snorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},bgra8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bgra8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r16uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16float:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg16uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba16uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r32uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg32uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba32uint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32sint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32float:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rg11b10ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},stencil8:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!1,hasStencil:!0,channels:1},depth16unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},depth24plus:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,depthOnlyFormat:"depth32float",channels:1},"depth24plus-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,depthOnlyFormat:"depth32float",channels:1},depth32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},"depth32float-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,stencilOnlyFormat:"depth32float",channels:1},rgb9e5ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bc1-rgba-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc1-rgba-unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc4-r-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc4-r-snorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc5-rg-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc5-rg-snorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc6h-rgb-ufloat":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc6h-rgb-float":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"eac-r11unorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-r11snorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-rg11unorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"eac-rg11snorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"astc-4x4-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-4x4-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x5-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-5x5-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x6-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-6x6-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-8x5-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x5-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x6-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x6-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x8-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-8x8-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-10x5-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x5-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x6-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x6-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x8-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x8-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x10-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-10x10-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x12-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4},"astc-12x12-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4}};class FI{constructor(){this.id=FI._id++,this.line=0}get isAstNode(){return!0}get astNodeType(){return""}search(A){A(this)}searchBlock(A,I){if(A){I(qB.instance);for(const g of A)g instanceof Array?this.searchBlock(g,I):g.search(I);I(lB.instance)}}constEvaluate(A,I){throw new Error("Cannot evaluate node")}constEvaluateString(A){var I,g;return(g=(I=this.constEvaluate(A))===null||I===void 0?void 0:I.toString())!==null&&g!==void 0?g:""}}FI._id=0;class qB extends FI{}qB.instance=new qB;class lB extends FI{}lB.instance=new lB;const wE=new Set(["all","any","select","arrayLength","abs","acos","acosh","asin","asinh","atan","atanh","atan2","ceil","clamp","cos","cosh","countLeadingZeros","countOneBits","countTrailingZeros","cross","degrees","determinant","distance","dot","dot4U8Packed","dot4I8Packed","exp","exp2","extractBits","faceForward","firstLeadingBit","firstTrailingBit","floor","fma","fract","frexp","insertBits","inverseSqrt","ldexp","length","log","log2","max","min","mix","modf","normalize","pow","quantizeToF16","radians","reflect","refract","reverseBits","round","saturate","sign","sin","sinh","smoothstep","sqrt","step","tan","tanh","transpose","trunc","dpdx","dpdxCoarse","dpdxFine","dpdy","dpdyCoarse","dpdyFine","fwidth","fwidthCoarse","fwidthFine","textureDimensions","textureGather","textureGatherCompare","textureLoad","textureNumLayers","textureNumLevels","textureNumSamples","textureSample","textureSampleBias","textureSampleCompare","textureSampleCompareLevel","textureSampleGrad","textureSampleLevel","textureSampleBaseClampToEdge","textureStore","atomicLoad","atomicStore","atomicAdd","atomicSub","atomicMax","atomicMin","atomicAnd","atomicOr","atomicXor","atomicExchange","atomicCompareExchangeWeak","pack4x8snorm","pack4x8unorm","pack4xI8","pack4xU8","pack4x8Clamp","pack4xU8Clamp","pack2x16snorm","pack2x16unorm","pack2x16float","unpack4x8snorm","unpack4x8unorm","unpack4xI8","unpack4xU8","unpack2x16snorm","unpack2x16unorm","unpack2x16float","storageBarrier","textureBarrier","workgroupBarrier","workgroupUniformLoad","subgroupAdd","subgroupExclusiveAdd","subgroupInclusiveAdd","subgroupAll","subgroupAnd","subgroupAny","subgroupBallot","subgroupBroadcast","subgroupBroadcastFirst","subgroupElect","subgroupMax","subgroupMin","subgroupMul","subgroupExclusiveMul","subgroupInclusiveMul","subgroupOr","subgroupShuffle","subgroupShuffleDown","subgroupShuffleUp","subgroupShuffleXor","subgroupXor","quadBroadcast","quadSwapDiagonal","quadSwapX","quadSwapY"]);class qA extends FI{}class EB extends qA{constructor(A,I,g,B,C,E){super(),this.calls=new Set,this.name=A,this.args=I,this.returnType=g,this.body=B,this.startLine=C,this.endLine=E}get astNodeType(){return"function"}search(A){if(this.attributes)for(const I of this.attributes)A(I);A(this);for(const I of this.args)A(I);this.searchBlock(this.body,A)}}class FE extends qA{constructor(A){super(),this.expression=A}get astNodeType(){return"staticAssert"}search(A){this.expression.search(A)}}class eE extends qA{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"while"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class dQ extends qA{constructor(A,I){super(),this.body=A,this.loopId=I}get astNodeType(){return"continuing"}search(A){this.searchBlock(this.body,A)}}class rE extends qA{constructor(A,I,g,B){super(),this.init=A,this.condition=I,this.increment=g,this.body=B}get astNodeType(){return"for"}search(A){var I,g,B;(I=this.init)===null||I===void 0||I.search(A),(g=this.condition)===null||g===void 0||g.search(A),(B=this.increment)===null||B===void 0||B.search(A),this.searchBlock(this.body,A)}}class YI extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"var"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class qQ extends qA{constructor(A,I,g){super(),this.attributes=null,this.name=A,this.type=I,this.value=g}get astNodeType(){return"override"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class iB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"let"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class fB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"const"}constEvaluate(A,I){return this.value.constEvaluate(A,I)}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}var Jg,oB,M,R;(Q=>{Q.increment="++",Q.decrement="--"})(Jg||(Jg={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for IncrementOperator");return Q[I]}})(Jg||(Jg={}));class nE extends qA{constructor(A,I){super(),this.operator=A,this.variable=I}get astNodeType(){return"increment"}search(A){this.variable.search(A)}}(Q=>{Q.assign="=",Q.addAssign="+=",Q.subtractAssign="-=",Q.multiplyAssign="*=",Q.divideAssign="/=",Q.moduloAssign="%=",Q.andAssign="&=",Q.orAssign="|=",Q.xorAssign="^=",Q.shiftLeftAssign="<<=",Q.shiftRightAssign=">>="})(oB||(oB={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for AssignOperator");return I}})(oB||(oB={}));class SE extends qA{constructor(A,I,g){super(),this.operator=A,this.variable=I,this.value=g}get astNodeType(){return"assign"}search(A){this.variable.search(A),this.value.search(A)}}class lQ extends qA{constructor(A,I){super(),this.name=A,this.args=I}get astNodeType(){return"call"}isBuiltin(){return wE.has(this.name)}search(A){for(const I of this.args)I.search(A);A(this)}}class NE extends qA{constructor(A,I){super(),this.body=A,this.continuing=I}get astNodeType(){return"loop"}search(A){var I;this.searchBlock(this.body,A),(I=this.continuing)===null||I===void 0||I.search(A)}}class RE extends qA{constructor(A,I){super(),this.condition=A,this.cases=I}get astNodeType(){return"switch"}search(A){A(this);for(const I of this.cases)I.search(A)}}class cE extends qA{constructor(A,I,g,B){super(),this.condition=A,this.body=I,this.elseif=g,this.else=B}get astNodeType(){return"if"}search(A){this.condition.search(A),this.searchBlock(this.body,A),this.searchBlock(this.elseif,A),this.searchBlock(this.else,A)}}class UE extends qA{constructor(A){super(),this.value=A}get astNodeType(){return"return"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class la extends qA{constructor(A){super(),this.name=A}get astNodeType(){return"enable"}}class fa extends qA{constructor(A){super(),this.extensions=A}get astNodeType(){return"requires"}}class kE extends qA{constructor(A,I){super(),this.severity=A,this.rule=I}get astNodeType(){return"diagnostic"}}class fQ extends qA{constructor(A,I){super(),this.name=A,this.type=I}get astNodeType(){return"alias"}}class pa extends qA{get astNodeType(){return"discard"}}class LE extends qA{constructor(){super(...arguments),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class JE extends qA{constructor(){super(...arguments),this.loopId=-1}get astNodeType(){return"continue"}}class l extends qA{constructor(A){super(),this.attributes=null,this.name=A}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(A){let I=A[0];if(I.name==="f32")return I;for(let g=1;g<A.length;++g){const B=l._priority.get(I.name);l._priority.get(A[g].name)<B&&(I=A[g])}return I.name==="x32"?l.i32:I}getTypeName(){return this.name}}l.x32=new l("x32"),l.f32=new l("f32"),l.i32=new l("i32"),l.u32=new l("u32"),l.f16=new l("f16"),l.bool=new l("bool"),l.void=new l("void"),l._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class YE extends l{constructor(A){super(A)}}class qI extends l{constructor(A,I,g,B){super(A),this.members=I,this.startLine=g,this.endLine=B}get astNodeType(){return"struct"}get isStruct(){return!0}getMemberIndex(A){for(let I=0;I<this.members.length;I++)if(this.members[I].name===A)return I;return-1}search(A){for(const I of this.members)A(I)}}class L extends l{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"template"}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}L.vec2f=new L("vec2",l.f32,null),L.vec3f=new L("vec3",l.f32,null),L.vec4f=new L("vec4",l.f32,null),L.vec2i=new L("vec2",l.i32,null),L.vec3i=new L("vec3",l.i32,null),L.vec4i=new L("vec4",l.i32,null),L.vec2u=new L("vec2",l.u32,null),L.vec3u=new L("vec3",l.u32,null),L.vec4u=new L("vec4",l.u32,null),L.vec2h=new L("vec2",l.f16,null),L.vec3h=new L("vec3",l.f16,null),L.vec4h=new L("vec4",l.f16,null),L.vec2b=new L("vec2",l.bool,null),L.vec3b=new L("vec3",l.bool,null),L.vec4b=new L("vec4",l.bool,null),L.mat2x2f=new L("mat2x2",l.f32,null),L.mat2x3f=new L("mat2x3",l.f32,null),L.mat2x4f=new L("mat2x4",l.f32,null),L.mat3x2f=new L("mat3x2",l.f32,null),L.mat3x3f=new L("mat3x3",l.f32,null),L.mat3x4f=new L("mat3x4",l.f32,null),L.mat4x2f=new L("mat4x2",l.f32,null),L.mat4x3f=new L("mat4x3",l.f32,null),L.mat4x4f=new L("mat4x4",l.f32,null),L.mat2x2h=new L("mat2x2",l.f16,null),L.mat2x3h=new L("mat2x3",l.f16,null),L.mat2x4h=new L("mat2x4",l.f16,null),L.mat3x2h=new L("mat3x2",l.f16,null),L.mat3x3h=new L("mat3x3",l.f16,null),L.mat3x4h=new L("mat3x4",l.f16,null),L.mat4x2h=new L("mat4x2",l.f16,null),L.mat4x3h=new L("mat4x3",l.f16,null),L.mat4x4h=new L("mat4x4",l.f16,null),L.mat2x2i=new L("mat2x2",l.i32,null),L.mat2x3i=new L("mat2x3",l.i32,null),L.mat2x4i=new L("mat2x4",l.i32,null),L.mat3x2i=new L("mat3x2",l.i32,null),L.mat3x3i=new L("mat3x3",l.i32,null),L.mat3x4i=new L("mat3x4",l.i32,null),L.mat4x2i=new L("mat4x2",l.i32,null),L.mat4x3i=new L("mat4x3",l.i32,null),L.mat4x4i=new L("mat4x4",l.i32,null),L.mat2x2u=new L("mat2x2",l.u32,null),L.mat2x3u=new L("mat2x3",l.u32,null),L.mat2x4u=new L("mat2x4",l.u32,null),L.mat3x2u=new L("mat3x2",l.u32,null),L.mat3x3u=new L("mat3x3",l.u32,null),L.mat3x4u=new L("mat3x4",l.u32,null),L.mat4x2u=new L("mat4x2",l.u32,null),L.mat4x3u=new L("mat4x3",l.u32,null),L.mat4x4u=new L("mat4x4",l.u32,null);class pB extends l{constructor(A,I,g,B){super(A),this.storage=I,this.type=g,this.access=B}get astNodeType(){return"pointer"}}class aB extends l{constructor(A,I,g,B){super(A),this.attributes=I,this.format=g,this.count=B}get astNodeType(){return"array"}get isArray(){return!0}}class DB extends l{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"sampler"}}class NI extends FI{constructor(){super(),this.postfix=null,this.hasParen=!1}}class Eg extends NI{constructor(A){super(),this.value=A}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class KI extends NI{constructor(A,I){super(),this.type=A,this.args=I}get astNodeType(){return"createExpr"}search(A){if(A(this),this.args)for(const I of this.args)I.search(A)}constEvaluate(A,I){return I&&(I[0]=this.type),A.evalExpression(this,A.context)}}class pQ extends NI{constructor(A,I){super(),this.cachedReturnValue=null,this.name=A,this.args=I}get astNodeType(){return"callExpr"}setCachedReturnValue(A){this.cachedReturnValue=A}get isBuiltin(){return wE.has(this.name)}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){for(const I of this.args)I.search(A);A(this)}}class EI extends NI{constructor(A){super(),this.name=A}get astNodeType(){return"varExpr"}search(A){A(this),this.postfix&&this.postfix.search(A)}constEvaluate(A,I){return A.evalExpression(this,A.context)}}class KE extends NI{constructor(A,I){super(),this.name=A,this.initializer=I}get astNodeType(){return"constExpr"}constEvaluate(A,I){const g=A.evalExpression(this.initializer,A.context);return g!==null&&this.postfix?g.getSubData(A,this.postfix,A.context):g}search(A){this.initializer.search(A)}}class vA extends NI{constructor(A,I){super(),this.value=A,this.type=I}get astNodeType(){return"literalExpr"}constEvaluate(A,I){return I!==void 0&&(I[0]=this.type),this.value}get isScalar(){return this.value instanceof U}get isVector(){return this.value instanceof e||this.value instanceof EA}get scalarValue(){return this.value instanceof U?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof e||this.value instanceof EA?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class ME extends NI{constructor(A,I){super(),this.type=A,this.value=I}get astNodeType(){return"bitcastExpr"}search(A){this.value.search(A)}}class Yg extends NI{constructor(A){super(),this.index=A}search(A){this.index.search(A)}}class HE extends NI{constructor(){super()}}class TA extends HE{constructor(A,I){super(),this.operator=A,this.right=I}get astNodeType(){return"unaryOp"}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.right.search(A)}}class RI extends HE{constructor(A,I,g){super(),this.operator=A,this.left=I,this.right=g}get astNodeType(){return"binaryOp"}_getPromotedType(A,I){return A.name===I.name?A:A.name==="f32"||I.name==="f32"?l.f32:A.name==="u32"||I.name==="u32"?l.u32:l.i32}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.left.search(A),this.right.search(A)}}class dE extends FI{constructor(A){super(),this.body=A}search(A){A(this),this.searchBlock(this.body,A)}}class mB extends NI{get astNodeType(){return"default"}}class qE extends dE{constructor(A,I){super(I),this.selectors=A}get astNodeType(){return"case"}search(A){this.searchBlock(this.body,A)}}class lE extends dE{constructor(A){super(A)}get astNodeType(){return"default"}search(A){this.searchBlock(this.body,A)}}class fE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"argument"}}class ma extends FI{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"elseif"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class pE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"member"}}class mE extends FI{constructor(A,I){super(),this.name=A,this.value=I}get astNodeType(){return"attribute"}}class cI{constructor(A,I){this.parent=null,this.typeInfo=A,this.parent=I,this.id=cI._id++}setDataValue(A,I,g,B){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(A,I,g){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}cI._id=0;class uE extends cI{constructor(A,I){super(A,I)}clone(){return this}toString(){return this.typeInfo.name}}class mQ extends cI{constructor(){super(new wI("void",null),null)}clone(){return this}toString(){return"void"}}mQ.void=new mQ;class Kg extends cI{constructor(A){super(new KQ("pointer",A.typeInfo,null),null),this.reference=A}clone(){return this}setDataValue(A,I,g,B){this.reference.setDataValue(A,I,g,B)}getSubData(A,I,g){return I?this.reference.getSubData(A,I,g):this}toString(){return`&${this.reference.toString()}`}}class U extends cI{constructor(A,I,g=null){super(I,g),A instanceof Int32Array||A instanceof Uint32Array||A instanceof Float32Array?this.data=A:this.typeInfo.name==="x32"?A-Math.floor(A)!==0?this.data=new Float32Array([A]):this.data=A>=0?new Uint32Array([A]):new Int32Array([A]):this.typeInfo.name==="i32"||this.typeInfo.name==="bool"?this.data=new Int32Array([A]):this.typeInfo.name==="u32"?this.data=new Uint32Array([A]):this.typeInfo.name==="f32"||this.typeInfo.name==="f16"?this.data=new Float32Array([A]):console.error("ScalarData2: Invalid type",I)}clone(){if(this.data instanceof Float32Array)return new U(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new U(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new U(new Uint32Array(this.data),this.typeInfo,null);throw new Error("ScalarData: Invalid data type")}get value(){return this.data[0]}set value(A){this.data[0]=A}setDataValue(A,I,g,B){if(g)return void console.error("SetDataValue: Scalar data does not support postfix",g);if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);let C=I.data[0];this.typeInfo.name==="i32"||this.typeInfo.name==="u32"?C=Math.floor(C):this.typeInfo.name==="bool"&&(C=C?1:0),this.data[0]=C}getSubData(A,I,g){return I?(console.error("getSubData: Scalar data does not support postfix",I),null):this}toString(){return`${this.value}`}}function ua(Q,A,I){const g=A.length;return g===2?I==="f32"?new e(new Float32Array(A),Q.getTypeInfo("vec2f")):I==="i32"||I==="bool"?new e(new Int32Array(A),Q.getTypeInfo("vec2i")):I==="u32"?new e(new Uint32Array(A),Q.getTypeInfo("vec2u")):I==="f16"?new e(new Float32Array(A),Q.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${I}`),null):g===3?I==="f32"?new e(new Float32Array(A),Q.getTypeInfo("vec3f")):I==="i32"||I==="bool"?new e(new Int32Array(A),Q.getTypeInfo("vec3i")):I==="u32"?new e(new Uint32Array(A),Q.getTypeInfo("vec3u")):I==="f16"?new e(new Float32Array(A),Q.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${I}`),null):g===4?I==="f32"?new e(new Float32Array(A),Q.getTypeInfo("vec4f")):I==="i32"||I==="bool"?new e(new Int32Array(A),Q.getTypeInfo("vec4i")):I==="u32"?new e(new Uint32Array(A),Q.getTypeInfo("vec4u")):I==="f16"?new e(new Float32Array(A),Q.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${I}`),null):(console.error(`getSubData: Invalid vector size ${A.length}`),null)}class e extends cI{constructor(A,I,g=null){if(super(I,g),A instanceof Float32Array||A instanceof Uint32Array||A instanceof Int32Array)this.data=A;else{const B=this.typeInfo.name;B==="vec2f"||B==="vec3f"||B==="vec4f"?this.data=new Float32Array(A):B==="vec2i"||B==="vec3i"||B==="vec4i"?this.data=new Int32Array(A):B==="vec2u"||B==="vec3u"||B==="vec4u"?this.data=new Uint32Array(A):B==="vec2h"||B==="vec3h"||B==="vec4h"?this.data=new Float32Array(A):B==="vec2b"||B==="vec3b"||B==="vec4b"?this.data=new Int32Array(A):B==="vec2"||B==="vec3"||B==="vec4"?this.data=new Float32Array(A):console.error(`VectorData: Invalid type ${B}`)}}clone(){if(this.data instanceof Float32Array)return new e(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new e(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new e(new Uint32Array(this.data),this.typeInfo,null);throw new Error("VectorData: Invalid data type")}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set vector postfix"):I instanceof e?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;let B=A.getTypeInfo("f32");if(this.typeInfo instanceof Cg)B=this.typeInfo.format||B;else{const E=this.typeInfo.name;E==="vec2f"||E==="vec3f"||E==="vec4f"?B=A.getTypeInfo("f32"):E==="vec2i"||E==="vec3i"||E==="vec4i"?B=A.getTypeInfo("i32"):E==="vec2b"||E==="vec3b"||E==="vec4b"?B=A.getTypeInfo("bool"):E==="vec2u"||E==="vec3u"||E==="vec4u"?B=A.getTypeInfo("u32"):E==="vec2h"||E==="vec3h"||E==="vec4h"?B=A.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${E}`)}let C=this;for(;I!==null&&C!==null;){if(I instanceof Yg){const E=I.index;let i=-1;if(E instanceof vA){if(!(E.value instanceof U))return console.error(`GetSubData: Invalid array index ${E.value}`),null;i=E.value.value}else{const o=A.evalExpression(E,g);if(!(o instanceof U))return console.error("GetSubData: Unknown index type",E),null;i=o.value}if(i<0||i>=C.data.length)return console.error("GetSubData: Index out of range",i),null;if(C.data instanceof Float32Array){const o=new Float32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Int32Array){const o=new Int32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Uint32Array){const o=new Uint32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}throw new Error("GetSubData: Invalid data type")}if(!(I instanceof Eg))return console.error("GetSubData: Unknown postfix",I),null;{const E=I.value.toLowerCase();if(E.length===1){let o=0;if(E==="x"||E==="r")o=0;else if(E==="y"||E==="g")o=1;else if(E==="z"||E==="b")o=2;else{if(E!=="w"&&E!=="a")return console.error(`GetSubData: Unknown member ${E}`),null;o=3}if(this.data instanceof Float32Array){let a=new Float32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Int32Array){let a=new Int32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Uint32Array){let a=new Uint32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}}const i=[];for(const o of E)o==="x"||o==="r"?i.push(this.data[0]):o==="y"||o==="g"?i.push(this.data[1]):o==="z"||o==="b"?i.push(this.data[2]):o==="w"||o==="a"?i.push(this.data[3]):console.error(`GetDataValue: Unknown member ${o}`);C=ua(A,i,B.name)}I=I.postfix}return C}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class EA extends cI{constructor(A,I,g=null){super(I,g),A instanceof Float32Array?this.data=A:this.data=new Float32Array(A)}clone(){return new EA(new Float32Array(this.data),this.typeInfo,null)}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set matrix postfix"):I instanceof EA?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;const B=this.typeInfo.name;if(A.getTypeInfo("f32"),this.typeInfo instanceof Cg)this.typeInfo.format;else if(B.endsWith("f"))A.getTypeInfo("f32");else if(B.endsWith("i"))A.getTypeInfo("i32");else if(B.endsWith("u"))A.getTypeInfo("u32");else{if(!B.endsWith("h"))return console.error(`GetDataValue: Unknown type ${B}`),null;A.getTypeInfo("f16")}if(I instanceof Yg){const C=I.index;let E=-1;if(C instanceof vA){if(!(C.value instanceof U))return console.error(`GetDataValue: Invalid array index ${C.value}`),null;E=C.value.value}else{const a=A.evalExpression(C,g);if(!(a instanceof U))return console.error("GetDataValue: Unknown index type",C),null;E=a.value}if(E<0||E>=this.data.length)return console.error("GetDataValue: Index out of range",E),null;const i=B.endsWith("h")?"h":"f";let o;if(B==="mat2x2"||B==="mat2x2f"||B==="mat2x2h"||B==="mat3x2"||B==="mat3x2f"||B==="mat3x2h"||B==="mat4x2"||B==="mat4x2f"||B==="mat4x2h")o=new e(new Float32Array(this.data.buffer,this.data.byteOffset+2*E*4,2),A.getTypeInfo(`vec2${i}`));else if(B==="mat2x3"||B==="mat2x3f"||B==="mat2x3h"||B==="mat3x3"||B==="mat3x3f"||B==="mat3x3h"||B==="mat4x3"||B==="mat4x3f"||B==="mat4x3h")o=new e(new Float32Array(this.data.buffer,this.data.byteOffset+3*E*4,3),A.getTypeInfo(`vec3${i}`));else{if(B!=="mat2x4"&&B!=="mat2x4f"&&B!=="mat2x4h"&&B!=="mat3x4"&&B!=="mat3x4f"&&B!=="mat3x4h"&&B!=="mat4x4"&&B!=="mat4x4f"&&B!=="mat4x4h")return console.error(`GetDataValue: Unknown type ${B}`),null;o=new e(new Float32Array(this.data.buffer,this.data.byteOffset+4*E*4,4),A.getTypeInfo(`vec4${i}`))}return I.postfix?o.getSubData(A,I.postfix,g):o}return console.error("GetDataValue: Invalid postfix",I),null}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class lA extends cI{constructor(A,I,g=0,B=null){super(I,B),this.buffer=A instanceof ArrayBuffer?A:A.buffer,this.offset=g}clone(){const A=new Uint8Array(new Uint8Array(this.buffer,this.offset,this.typeInfo.size));return new lA(A.buffer,this.typeInfo,0,null)}setDataValue(A,I,g,B){if(I===null)return void console.log("setDataValue: NULL data.");let C=this.offset,E=this.typeInfo;for(;g;){if(g instanceof Yg)if(E instanceof bI){const i=g.index;if(i instanceof vA){if(!(i.value instanceof U))return void console.error(`SetDataValue: Invalid index type ${i.value}`);C+=i.value.value*E.stride}else{const o=A.evalExpression(i,B);if(!(o instanceof U))return void console.error("SetDataValue: Unknown index type",i);C+=o.value*E.stride}E=E.format}else console.error(`SetDataValue: Type ${E.getTypeName()} is not an array`);else{if(!(g instanceof Eg))return void console.error("SetDataValue: Unknown postfix type",g);{const i=g.value;if(E instanceof TI){let o=!1;for(const a of E.members)if(a.name===i){C+=a.offset,E=a.type,o=!0;break}if(!o)return void console.error(`SetDataValue: Member ${i} not found`)}else if(E instanceof wI){const o=E.getTypeName();let a=0;if(i==="x"||i==="r")a=0;else if(i==="y"||i==="g")a=1;else if(i==="z"||i==="b")a=2;else{if(i!=="w"&&i!=="a")return void console.error(`SetDataValue: Unknown member ${i}`);a=3}if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);const D=I.value;return o==="vec2f"?void(new Float32Array(this.buffer,C,2)[a]=D):o==="vec3f"?void(new Float32Array(this.buffer,C,3)[a]=D):o==="vec4f"?void(new Float32Array(this.buffer,C,4)[a]=D):o==="vec2i"?void(new Int32Array(this.buffer,C,2)[a]=D):o==="vec3i"?void(new Int32Array(this.buffer,C,3)[a]=D):o==="vec4i"?void(new Int32Array(this.buffer,C,4)[a]=D):o==="vec2u"?void(new Uint32Array(this.buffer,C,2)[a]=D):o==="vec3u"?void(new Uint32Array(this.buffer,C,3)[a]=D):o==="vec4u"?void(new Uint32Array(this.buffer,C,4)[a]=D):void console.error(`SetDataValue: Type ${o} is not a struct`)}}}g=g.postfix}this.setData(A,I,E,C,B)}setData(A,I,g,B,C){const E=g.getTypeName();if(E!=="f32"&&E!=="f16")if(E!=="i32"&&E!=="atomic<i32>"&&E!=="x32")if(E!=="u32"&&E!=="atomic<u32>")if(E!=="bool"){if(E==="vec2f"||E==="vec2h"){const i=new Float32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3f"||E==="vec3h"){const i=new Float32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4f"||E==="vec4h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2i"){const i=new Int32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3i"){const i=new Int32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4i"){const i=new Int32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2u"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3u"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4u"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2b"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3b"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4b"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof e?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x2f"||E==="mat2x2h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x3f"||E==="mat2x3h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat2x4f"||E==="mat2x4h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat3x2f"||E==="mat3x2h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat3x3f"||E==="mat3x3h"){const i=new Float32Array(this.buffer,B,9);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8]))}if(E==="mat3x4f"||E==="mat3x4h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x2f"||E==="mat4x2h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat4x3f"||E==="mat4x3h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x4f"||E==="mat4x4h"){const i=new Float32Array(this.buffer,B,16);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11],i[12]=I.data[12],i[13]=I.data[13],i[14]=I.data[14],i[15]=I.data[15]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11],i[12]=I[12],i[13]=I[13],i[14]=I[14],i[15]=I[15]))}if(I instanceof lA){if(g===I.typeInfo)return void new Uint8Array(this.buffer,B,I.buffer.byteLength).set(new Uint8Array(I.buffer));console.error("SetDataValue: Type mismatch",E,I.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${E}`)}else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Uint32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Float32Array(this.buffer,B,1)[0]=I.value)}getSubData(A,I,g){var B,C,E;if(I===null)return this;let i=this.offset,o=this.typeInfo;for(;I;){if(I instanceof Yg){const D=I.index,s=D instanceof NI?A.evalExpression(D,g):D;let G=0;if(s instanceof U?G=s.value:typeof s=="number"?G=s:console.error("GetDataValue: Invalid index type",D),o instanceof bI)i+=G*o.stride,o=o.format;else{const F=o.getTypeName();F==="mat4x4"||F==="mat4x4f"||F==="mat4x4h"?(i+=16*G,o=A.getTypeInfo("vec4f")):F==="mat4x3"||F==="mat4x3f"||F==="mat4x3h"?(i+=12*G,o=A.getTypeInfo("vec3f")):F==="mat4x2"||F==="mat4x2f"||F==="mat4x2h"?(i+=8*G,o=A.getTypeInfo("vec2f")):F==="mat3x4"||F==="mat3x4f"||F==="mat3x4h"?(i+=12*G,o=A.getTypeInfo("vec4f")):F==="mat3x3"||F==="mat3x3f"||F==="mat3x3h"?(i+=9*G,o=A.getTypeInfo("vec3f")):F==="mat3x2"||F==="mat3x2f"||F==="mat3x2h"?(i+=6*G,o=A.getTypeInfo("vec2f")):F==="mat2x4"||F==="mat2x4f"||F==="mat2x4h"?(i+=8*G,o=A.getTypeInfo("vec4f")):F==="mat2x3"||F==="mat2x3f"||F==="mat2x3h"?(i+=6*G,o=A.getTypeInfo("vec3f")):F==="mat2x2"||F==="mat2x2f"||F==="mat2x2h"?(i+=4*G,o=A.getTypeInfo("vec2f")):F==="vec2f"||F==="vec3f"||F==="vec4f"?(i+=4*G,o=A.getTypeInfo("f32")):F==="vec2h"||F==="vec3h"||F==="vec4h"?(i+=2*G,o=A.getTypeInfo("f16")):F==="vec2b"||F==="vec3b"||F==="vec4b"?(i+=1*G,o=A.getTypeInfo("bool")):F==="vec2i"||F==="vec3i"||F==="vec4i"?(i+=4*G,o=A.getTypeInfo("i32")):F==="vec2u"||F==="vec3u"||F==="vec4u"?(i+=4*G,o=A.getTypeInfo("u32")):console.error(`getDataValue: Type ${o.getTypeName()} is not an array`)}}else{if(!(I instanceof Eg))return console.error("GetDataValue: Unknown postfix type",I),null;{const D=I.value;if(o instanceof TI){let s=!1;for(const G of o.members)if(G.name===D){i+=G.offset,o=G.type,s=!0;break}if(!s)return console.error(`GetDataValue: Member ${D} not found`),null}else if(o instanceof wI){const s=o.getTypeName();if(s==="vec2f"||s==="vec3f"||s==="vec4f"||s==="vec2i"||s==="vec3i"||s==="vec4i"||s==="vec2u"||s==="vec3u"||s==="vec4u"||s==="vec2b"||s==="vec3b"||s==="vec4b"||s==="vec2h"||s==="vec3h"||s==="vec4h"||s==="vec2"||s==="vec3"||s==="vec4"){if(D.length>0&&D.length<5){let G="f";const F=[];for(let J=0;J<D.length;++J){const m=D[J].toLowerCase();let d=0;if(m==="x"||m==="r")d=0;else if(m==="y"||m==="g")d=1;else if(m==="z"||m==="b")d=2;else{if(m!=="w"&&m!=="a")return console.error(`Unknown member ${D}`),null;d=3}if(D.length===1){if(s.endsWith("f"))return this.buffer.byteLength<i+4*d+4?(console.log("Insufficient buffer data"),null):new U(new Float32Array(this.buffer,i+4*d,1),A.getTypeInfo("f32"),this);if(s.endsWith("h"))return new U(new Float32Array(this.buffer,i+4*d,1),A.getTypeInfo("f16"),this);if(s.endsWith("i"))return new U(new Int32Array(this.buffer,i+4*d,1),A.getTypeInfo("i32"),this);if(s.endsWith("b"))return new U(new Int32Array(this.buffer,i+4*d,1),A.getTypeInfo("bool"),this);if(s.endsWith("u"))return new U(new Uint32Array(this.buffer,i+4*d,1),A.getTypeInfo("i32"),this)}if(s==="vec2f")F.push(new Float32Array(this.buffer,i,2)[d]);else if(s==="vec3f"){if(i+12>=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const T=new Float32Array(this.buffer,i,3);F.push(T[d])}else if(s==="vec4f")F.push(new Float32Array(this.buffer,i,4)[d]);else if(s==="vec2i")G="i",F.push(new Int32Array(this.buffer,i,2)[d]);else if(s==="vec3i")G="i",F.push(new Int32Array(this.buffer,i,3)[d]);else if(s==="vec4i")G="i",F.push(new Int32Array(this.buffer,i,4)[d]);else if(s==="vec2u"){G="u";const T=new Uint32Array(this.buffer,i,2);F.push(T[d])}else s==="vec3u"?(G="u",F.push(new Uint32Array(this.buffer,i,3)[d])):s==="vec4u"&&(G="u",F.push(new Uint32Array(this.buffer,i,4)[d]))}return F.length===2?o=A.getTypeInfo(`vec2${G}`):F.length===3?o=A.getTypeInfo(`vec3${G}`):F.length===4?o=A.getTypeInfo(`vec4${G}`):console.error(`GetDataValue: Invalid vector length ${F.length}`),new e(F,o,null)}return console.error(`GetDataValue: Unknown member ${D}`),null}return console.error(`GetDataValue: Type ${s} is not a struct`),null}}}I=I.postfix}const a=o.getTypeName();return a==="f32"?new U(new Float32Array(this.buffer,i,1),o,this):a==="i32"?new U(new Int32Array(this.buffer,i,1),o,this):a==="u32"?new U(new Uint32Array(this.buffer,i,1),o,this):a==="vec2f"?new e(new Float32Array(this.buffer,i,2),o,this):a==="vec3f"?new e(new Float32Array(this.buffer,i,3),o,this):a==="vec4f"?new e(new Float32Array(this.buffer,i,4),o,this):a==="vec2i"?new e(new Int32Array(this.buffer,i,2),o,this):a==="vec3i"?new e(new Int32Array(this.buffer,i,3),o,this):a==="vec4i"?new e(new Int32Array(this.buffer,i,4),o,this):a==="vec2u"?new e(new Uint32Array(this.buffer,i,2),o,this):a==="vec3u"?new e(new Uint32Array(this.buffer,i,3),o,this):a==="vec4u"?new e(new Uint32Array(this.buffer,i,4),o,this):o instanceof Cg&&o.name==="atomic"?((B=o.format)===null||B===void 0?void 0:B.name)==="u32"?new U(new Uint32Array(this.buffer,i,1)[0],o.format,this):((C=o.format)===null||C===void 0?void 0:C.name)==="i32"?new U(new Int32Array(this.buffer,i,1)[0],o.format,this):(console.error(`GetDataValue: Invalid atomic format ${(E=o.format)===null||E===void 0?void 0:E.name}`),null):new lA(this.buffer,o,i,this)}toArray(){const A=this.typeInfo.getTypeName();return A==="f32"||A==="f16"?new Float32Array(this.buffer,this.offset,1):A==="i32"||A==="atomic<i32>"||A==="x32"?new Int32Array(this.buffer,this.offset,1):A==="u32"||A==="atomic<u32>"?new Uint32Array(this.buffer,this.offset,1):A==="bool"?new Int32Array(this.buffer,this.offset,1):A==="vec2f"||A==="vec2h"?new Float32Array(this.buffer,this.offset,2):A==="vec3f"||A==="vec3h"?new Float32Array(this.buffer,this.offset,3):A==="vec4f"||A==="vec4h"?new Float32Array(this.buffer,this.offset,4):A==="vec2i"?new Int32Array(this.buffer,this.offset,2):A==="vec3i"?new Int32Array(this.buffer,this.offset,3):A==="vec4i"?new Int32Array(this.buffer,this.offset,4):A==="vec2u"?new Uint32Array(this.buffer,this.offset,2):A==="vec3u"?new Uint32Array(this.buffer,this.offset,3):A==="vec4u"?new Uint32Array(this.buffer,this.offset,4):A==="vec2b"?new Uint32Array(this.buffer,this.offset,2):A==="vec3b"?new Uint32Array(this.buffer,this.offset,3):A==="vec4b"?new Uint32Array(this.buffer,this.offset,4):A==="mat2x2f"||A==="mat2x2h"?new Float32Array(this.buffer,this.offset,4):A==="mat2x3f"||A==="mat2x3h"?new Float32Array(this.buffer,this.offset,6):A==="mat2x4f"||A==="mat2x4h"?new Float32Array(this.buffer,this.offset,8):A==="mat3x2f"||A==="mat3x2h"?new Float32Array(this.buffer,this.offset,6):A==="mat3x3f"||A==="mat3x3h"?new Float32Array(this.buffer,this.offset,9):A==="mat3x4f"||A==="mat3x4h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x2f"||A==="mat4x2h"?new Float32Array(this.buffer,this.offset,8):A==="mat4x3f"||A==="mat4x3h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x4f"||A==="mat4x4h"?new Float32Array(this.buffer,this.offset,16):null}toString(){let A="";if(this.typeInfo instanceof bI)if(this.typeInfo.format.name==="f32"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="i32"){const I=new Int32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="u32"){const I=new Uint32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="vec2f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}]`;for(let g=1;g<I.length/2;++g)A+=`, [${I[2*g]}, ${I[2*g+1]}]`}else if(this.typeInfo.format.name==="vec3f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}]`}else if(this.typeInfo.format.name==="vec4f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}, ${I[3]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}, ${I[g+3]}]`}else A="[...]";else this.typeInfo instanceof TI?A+="{...}":A="[...]";return A}}class lI extends cI{constructor(A,I,g,B){super(I,null),this.data=A,this.descriptor=g,this.view=B}clone(){return new lI(this.data,this.typeInfo,this.descriptor,this.view)}get width(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>0?(A=g[0])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.width)!==null&&I!==void 0?I:0}get height(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>1?(A=g[1])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.height)!==null&&I!==void 0?I:0}get depthOrArrayLayers(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>2?(A=g[2])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.depthOrArrayLayers)!==null&&I!==void 0?I:0}get format(){var A;return this.descriptor&&(A=this.descriptor.format)!==null&&A!==void 0?A:"rgba8unorm"}get sampleCount(){var A;return this.descriptor&&(A=this.descriptor.sampleCount)!==null&&A!==void 0?A:1}get mipLevelCount(){var A;return this.descriptor&&(A=this.descriptor.mipLevelCount)!==null&&A!==void 0?A:1}get dimension(){var A;return this.descriptor&&(A=this.descriptor.dimension)!==null&&A!==void 0?A:"2d"}getMipLevelSize(A){if(A>=this.mipLevelCount)return[0,0,0];const I=[this.width,this.height,this.depthOrArrayLayers];for(let g=0;g<I.length;++g)I[g]=Math.max(1,I[g]>>A);return I}get texelByteSize(){const A=this.format,I=HQ[A];return I?I.isDepthStencil?4:I.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const A=this.format,I=HQ[A];return!!I&&I.isDepthStencil}getGpuSize(){const A=this.format,I=HQ[A],g=this.width;if(!A||g<=0||!I)return-1;const B=this.height,C=this.depthOrArrayLayers,E=this.dimension;return g/I.blockWidth*(E==="1d"?1:B/I.blockHeight)*I.bytesPerBlock*C}getPixel(A,I,g=0,B=0){const C=this.texelByteSize,E=this.bytesPerRow,i=this.height,o=this.data[B];return qa(new Uint8Array(o),A,I,g,B,i,E,C,this.format)}setPixel(A,I,g,B,C){const E=this.texelByteSize,i=this.bytesPerRow,o=this.height,a=this.data[B];(function(D,s,G,F,J,m,d,T,z,u){const f=F*(d>>=J)*(m>>=J)+G*d+s*T;switch(z){case"r8unorm":return void UA(D,f,"8unorm",1,u);case"r8snorm":return void UA(D,f,"8snorm",1,u);case"r8uint":return void UA(D,f,"8uint",1,u);case"r8sint":return void UA(D,f,"8sint",1,u);case"rg8unorm":return void UA(D,f,"8unorm",2,u);case"rg8snorm":return void UA(D,f,"8snorm",2,u);case"rg8uint":return void UA(D,f,"8uint",2,u);case"rg8sint":return void UA(D,f,"8sint",2,u);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void UA(D,f,"8unorm",4,u);case"rgba8snorm":return void UA(D,f,"8snorm",4,u);case"rgba8uint":return void UA(D,f,"8uint",4,u);case"rgba8sint":return void UA(D,f,"8sint",4,u);case"r16uint":return void UA(D,f,"16uint",1,u);case"r16sint":return void UA(D,f,"16sint",1,u);case"r16float":return void UA(D,f,"16float",1,u);case"rg16uint":return void UA(D,f,"16uint",2,u);case"rg16sint":return void UA(D,f,"16sint",2,u);case"rg16float":return void UA(D,f,"16float",2,u);case"rgba16uint":return void UA(D,f,"16uint",4,u);case"rgba16sint":return void UA(D,f,"16sint",4,u);case"rgba16float":return void UA(D,f,"16float",4,u);case"r32uint":return void UA(D,f,"32uint",1,u);case"r32sint":return void UA(D,f,"32sint",1,u);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void UA(D,f,"32float",1,u);case"rg32uint":return void UA(D,f,"32uint",2,u);case"rg32sint":return void UA(D,f,"32sint",2,u);case"rg32float":return void UA(D,f,"32float",2,u);case"rgba32uint":return void UA(D,f,"32uint",4,u);case"rgba32sint":return void UA(D,f,"32sint",4,u);case"rgba32float":return void UA(D,f,"32float",4,u);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}})(new Uint8Array(a),A,I,g,B,o,i,E,this.format,C)}}(Q=>{Q[Q.token=0]="token",Q[Q.keyword=1]="keyword",Q[Q.reserved=2]="reserved"})(R||(R={}));class c{constructor(A,I,g){this.name=A,this.type=I,this.rule=g}toString(){return this.name}}class y{}M=y,y.none=new c("",R.reserved,""),y.eof=new c("EOF",R.token,""),y.reserved={asm:new c("asm",R.reserved,"asm"),bf16:new c("bf16",R.reserved,"bf16"),do:new c("do",R.reserved,"do"),enum:new c("enum",R.reserved,"enum"),f16:new c("f16",R.reserved,"f16"),f64:new c("f64",R.reserved,"f64"),handle:new c("handle",R.reserved,"handle"),i8:new c("i8",R.reserved,"i8"),i16:new c("i16",R.reserved,"i16"),i64:new c("i64",R.reserved,"i64"),mat:new c("mat",R.reserved,"mat"),premerge:new c("premerge",R.reserved,"premerge"),regardless:new c("regardless",R.reserved,"regardless"),typedef:new c("typedef",R.reserved,"typedef"),u8:new c("u8",R.reserved,"u8"),u16:new c("u16",R.reserved,"u16"),u64:new c("u64",R.reserved,"u64"),unless:new c("unless",R.reserved,"unless"),using:new c("using",R.reserved,"using"),vec:new c("vec",R.reserved,"vec"),void:new c("void",R.reserved,"void")},y.keywords={array:new c("array",R.keyword,"array"),atomic:new c("atomic",R.keyword,"atomic"),bool:new c("bool",R.keyword,"bool"),f32:new c("f32",R.keyword,"f32"),i32:new c("i32",R.keyword,"i32"),mat2x2:new c("mat2x2",R.keyword,"mat2x2"),mat2x3:new c("mat2x3",R.keyword,"mat2x3"),mat2x4:new c("mat2x4",R.keyword,"mat2x4"),mat3x2:new c("mat3x2",R.keyword,"mat3x2"),mat3x3:new c("mat3x3",R.keyword,"mat3x3"),mat3x4:new c("mat3x4",R.keyword,"mat3x4"),mat4x2:new c("mat4x2",R.keyword,"mat4x2"),mat4x3:new c("mat4x3",R.keyword,"mat4x3"),mat4x4:new c("mat4x4",R.keyword,"mat4x4"),ptr:new c("ptr",R.keyword,"ptr"),sampler:new c("sampler",R.keyword,"sampler"),sampler_comparison:new c("sampler_comparison",R.keyword,"sampler_comparison"),struct:new c("struct",R.keyword,"struct"),texture_1d:new c("texture_1d",R.keyword,"texture_1d"),texture_2d:new c("texture_2d",R.keyword,"texture_2d"),texture_2d_array:new c("texture_2d_array",R.keyword,"texture_2d_array"),texture_3d:new c("texture_3d",R.keyword,"texture_3d"),texture_cube:new c("texture_cube",R.keyword,"texture_cube"),texture_cube_array:new c("texture_cube_array",R.keyword,"texture_cube_array"),texture_multisampled_2d:new c("texture_multisampled_2d",R.keyword,"texture_multisampled_2d"),texture_storage_1d:new c("texture_storage_1d",R.keyword,"texture_storage_1d"),texture_storage_2d:new c("texture_storage_2d",R.keyword,"texture_storage_2d"),texture_storage_2d_array:new c("texture_storage_2d_array",R.keyword,"texture_storage_2d_array"),texture_storage_3d:new c("texture_storage_3d",R.keyword,"texture_storage_3d"),texture_depth_2d:new c("texture_depth_2d",R.keyword,"texture_depth_2d"),texture_depth_2d_array:new c("texture_depth_2d_array",R.keyword,"texture_depth_2d_array"),texture_depth_cube:new c("texture_depth_cube",R.keyword,"texture_depth_cube"),texture_depth_cube_array:new c("texture_depth_cube_array",R.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new c("texture_depth_multisampled_2d",R.keyword,"texture_depth_multisampled_2d"),texture_external:new c("texture_external",R.keyword,"texture_external"),u32:new c("u32",R.keyword,"u32"),vec2:new c("vec2",R.keyword,"vec2"),vec3:new c("vec3",R.keyword,"vec3"),vec4:new c("vec4",R.keyword,"vec4"),bitcast:new c("bitcast",R.keyword,"bitcast"),block:new c("block",R.keyword,"block"),break:new c("break",R.keyword,"break"),case:new c("case",R.keyword,"case"),continue:new c("continue",R.keyword,"continue"),continuing:new c("continuing",R.keyword,"continuing"),default:new c("default",R.keyword,"default"),diagnostic:new c("diagnostic",R.keyword,"diagnostic"),discard:new c("discard",R.keyword,"discard"),else:new c("else",R.keyword,"else"),enable:new c("enable",R.keyword,"enable"),fallthrough:new c("fallthrough",R.keyword,"fallthrough"),false:new c("false",R.keyword,"false"),fn:new c("fn",R.keyword,"fn"),for:new c("for",R.keyword,"for"),function:new c("function",R.keyword,"function"),if:new c("if",R.keyword,"if"),let:new c("let",R.keyword,"let"),const:new c("const",R.keyword,"const"),loop:new c("loop",R.keyword,"loop"),while:new c("while",R.keyword,"while"),private:new c("private",R.keyword,"private"),read:new c("read",R.keyword,"read"),read_write:new c("read_write",R.keyword,"read_write"),return:new c("return",R.keyword,"return"),requires:new c("requires",R.keyword,"requires"),storage:new c("storage",R.keyword,"storage"),immediate:new c("immediate",R.keyword,"immediate"),switch:new c("switch",R.keyword,"switch"),true:new c("true",R.keyword,"true"),alias:new c("alias",R.keyword,"alias"),type:new c("type",R.keyword,"type"),uniform:new c("uniform",R.keyword,"uniform"),var:new c("var",R.keyword,"var"),override:new c("override",R.keyword,"override"),workgroup:new c("workgroup",R.keyword,"workgroup"),write:new c("write",R.keyword,"write"),r8unorm:new c("r8unorm",R.keyword,"r8unorm"),r8snorm:new c("r8snorm",R.keyword,"r8snorm"),r8uint:new c("r8uint",R.keyword,"r8uint"),r8sint:new c("r8sint",R.keyword,"r8sint"),r16uint:new c("r16uint",R.keyword,"r16uint"),r16sint:new c("r16sint",R.keyword,"r16sint"),r16float:new c("r16float",R.keyword,"r16float"),rg8unorm:new c("rg8unorm",R.keyword,"rg8unorm"),rg8snorm:new c("rg8snorm",R.keyword,"rg8snorm"),rg8uint:new c("rg8uint",R.keyword,"rg8uint"),rg8sint:new c("rg8sint",R.keyword,"rg8sint"),r32uint:new c("r32uint",R.keyword,"r32uint"),r32sint:new c("r32sint",R.keyword,"r32sint"),r32float:new c("r32float",R.keyword,"r32float"),rg16uint:new c("rg16uint",R.keyword,"rg16uint"),rg16sint:new c("rg16sint",R.keyword,"rg16sint"),rg16float:new c("rg16float",R.keyword,"rg16float"),rgba8unorm:new c("rgba8unorm",R.keyword,"rgba8unorm"),rgba8unorm_srgb:new c("rgba8unorm_srgb",R.keyword,"rgba8unorm_srgb"),rgba8snorm:new c("rgba8snorm",R.keyword,"rgba8snorm"),rgba8uint:new c("rgba8uint",R.keyword,"rgba8uint"),rgba8sint:new c("rgba8sint",R.keyword,"rgba8sint"),bgra8unorm:new c("bgra8unorm",R.keyword,"bgra8unorm"),bgra8unorm_srgb:new c("bgra8unorm_srgb",R.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new c("rgb10a2unorm",R.keyword,"rgb10a2unorm"),rg11b10float:new c("rg11b10float",R.keyword,"rg11b10float"),rg32uint:new c("rg32uint",R.keyword,"rg32uint"),rg32sint:new c("rg32sint",R.keyword,"rg32sint"),rg32float:new c("rg32float",R.keyword,"rg32float"),rgba16uint:new c("rgba16uint",R.keyword,"rgba16uint"),rgba16sint:new c("rgba16sint",R.keyword,"rgba16sint"),rgba16float:new c("rgba16float",R.keyword,"rgba16float"),rgba32uint:new c("rgba32uint",R.keyword,"rgba32uint"),rgba32sint:new c("rgba32sint",R.keyword,"rgba32sint"),rgba32float:new c("rgba32float",R.keyword,"rgba32float"),static_assert:new c("static_assert",R.keyword,"static_assert"),const_assert:new c("const_assert",R.keyword,"const_assert")},y.tokens={decimal_float_literal:new c("decimal_float_literal",R.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new c("hex_float_literal",R.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new c("int_literal",R.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new c("uint_literal",R.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new c("name",R.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new c("ident",R.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new c("and",R.token,"&"),and_and:new c("and_and",R.token,"&&"),arrow:new c("arrow ",R.token,"->"),attr:new c("attr",R.token,"@"),forward_slash:new c("forward_slash",R.token,"/"),bang:new c("bang",R.token,"!"),bracket_left:new c("bracket_left",R.token,"["),bracket_right:new c("bracket_right",R.token,"]"),brace_left:new c("brace_left",R.token,"{"),brace_right:new c("brace_right",R.token,"}"),colon:new c("colon",R.token,":"),comma:new c("comma",R.token,","),equal:new c("equal",R.token,"="),equal_equal:new c("equal_equal",R.token,"=="),not_equal:new c("not_equal",R.token,"!="),greater_than:new c("greater_than",R.token,">"),greater_than_equal:new c("greater_than_equal",R.token,">="),shift_right:new c("shift_right",R.token,">>"),less_than:new c("less_than",R.token,"<"),less_than_equal:new c("less_than_equal",R.token,"<="),shift_left:new c("shift_left",R.token,"<<"),modulo:new c("modulo",R.token,"%"),minus:new c("minus",R.token,"-"),minus_minus:new c("minus_minus",R.token,"--"),period:new c("period",R.token,"."),plus:new c("plus",R.token,"+"),plus_plus:new c("plus_plus",R.token,"++"),or:new c("or",R.token,"|"),or_or:new c("or_or",R.token,"||"),paren_left:new c("paren_left",R.token,"("),paren_right:new c("paren_right",R.token,")"),semicolon:new c("semicolon",R.token,";"),star:new c("star",R.token,"*"),tilde:new c("tilde",R.token,"~"),underscore:new c("underscore",R.token,"_"),xor:new c("xor",R.token,"^"),plus_equal:new c("plus_equal",R.token,"+="),minus_equal:new c("minus_equal",R.token,"-="),times_equal:new c("times_equal",R.token,"*="),division_equal:new c("division_equal",R.token,"/="),modulo_equal:new c("modulo_equal",R.token,"%="),and_equal:new c("and_equal",R.token,"&="),or_equal:new c("or_equal",R.token,"|="),xor_equal:new c("xor_equal",R.token,"^="),shift_right_equal:new c("shift_right_equal",R.token,">>="),shift_left_equal:new c("shift_left_equal",R.token,"<<=")},y.simpleTokens={"@":M.tokens.attr,"{":M.tokens.brace_left,"}":M.tokens.brace_right,":":M.tokens.colon,",":M.tokens.comma,"(":M.tokens.paren_left,")":M.tokens.paren_right,";":M.tokens.semicolon},y.literalTokens={"&":M.tokens.and,"&&":M.tokens.and_and,"->":M.tokens.arrow,"/":M.tokens.forward_slash,"!":M.tokens.bang,"[":M.tokens.bracket_left,"]":M.tokens.bracket_right,"=":M.tokens.equal,"==":M.tokens.equal_equal,"!=":M.tokens.not_equal,">":M.tokens.greater_than,">=":M.tokens.greater_than_equal,">>":M.tokens.shift_right,"<":M.tokens.less_than,"<=":M.tokens.less_than_equal,"<<":M.tokens.shift_left,"%":M.tokens.modulo,"-":M.tokens.minus,"--":M.tokens.minus_minus,".":M.tokens.period,"+":M.tokens.plus,"++":M.tokens.plus_plus,"|":M.tokens.or,"||":M.tokens.or_or,"*":M.tokens.star,"~":M.tokens.tilde,_:M.tokens.underscore,"^":M.tokens.xor,"+=":M.tokens.plus_equal,"-=":M.tokens.minus_equal,"*=":M.tokens.times_equal,"/=":M.tokens.division_equal,"%=":M.tokens.modulo_equal,"&=":M.tokens.and_equal,"|=":M.tokens.or_equal,"^=":M.tokens.xor_equal,">>=":M.tokens.shift_right_equal,"<<=":M.tokens.shift_left_equal},y.regexTokens={decimal_float_literal:M.tokens.decimal_float_literal,hex_float_literal:M.tokens.hex_float_literal,int_literal:M.tokens.int_literal,uint_literal:M.tokens.uint_literal,ident:M.tokens.ident},y.storage_class=[M.keywords.function,M.keywords.private,M.keywords.workgroup,M.keywords.uniform,M.keywords.storage,M.keywords.immediate],y.access_mode=[M.keywords.read,M.keywords.write,M.keywords.read_write],y.sampler_type=[M.keywords.sampler,M.keywords.sampler_comparison],y.sampled_texture_type=[M.keywords.texture_1d,M.keywords.texture_2d,M.keywords.texture_2d_array,M.keywords.texture_3d,M.keywords.texture_cube,M.keywords.texture_cube_array],y.multisampled_texture_type=[M.keywords.texture_multisampled_2d],y.storage_texture_type=[M.keywords.texture_storage_1d,M.keywords.texture_storage_2d,M.keywords.texture_storage_2d_array,M.keywords.texture_storage_3d],y.depth_texture_type=[M.keywords.texture_depth_2d,M.keywords.texture_depth_2d_array,M.keywords.texture_depth_cube,M.keywords.texture_depth_cube_array,M.keywords.texture_depth_multisampled_2d],y.texture_external_type=[M.keywords.texture_external],y.any_texture_type=[...M.sampled_texture_type,...M.multisampled_texture_type,...M.storage_texture_type,...M.depth_texture_type,...M.texture_external_type],y.texel_format=[M.keywords.r8unorm,M.keywords.r8snorm,M.keywords.r8uint,M.keywords.r8sint,M.keywords.r16uint,M.keywords.r16sint,M.keywords.r16float,M.keywords.rg8unorm,M.keywords.rg8snorm,M.keywords.rg8uint,M.keywords.rg8sint,M.keywords.r32uint,M.keywords.r32sint,M.keywords.r32float,M.keywords.rg16uint,M.keywords.rg16sint,M.keywords.rg16float,M.keywords.rgba8unorm,M.keywords.rgba8unorm_srgb,M.keywords.rgba8snorm,M.keywords.rgba8uint,M.keywords.rgba8sint,M.keywords.bgra8unorm,M.keywords.bgra8unorm_srgb,M.keywords.rgb10a2unorm,M.keywords.rg11b10float,M.keywords.rg32uint,M.keywords.rg32sint,M.keywords.rg32float,M.keywords.rgba16uint,M.keywords.rgba16sint,M.keywords.rgba16float,M.keywords.rgba32uint,M.keywords.rgba32sint,M.keywords.rgba32float],y.const_literal=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.keywords.true,M.keywords.false],y.literal_or_ident=[M.tokens.ident,M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.tokens.name],y.element_count_expression=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.ident],y.template_types=[M.keywords.vec2,M.keywords.vec3,M.keywords.vec4,M.keywords.mat2x2,M.keywords.mat2x3,M.keywords.mat2x4,M.keywords.mat3x2,M.keywords.mat3x3,M.keywords.mat3x4,M.keywords.mat4x2,M.keywords.mat4x3,M.keywords.mat4x4,M.keywords.atomic,M.keywords.bitcast,...M.any_texture_type],y.attribute_name=[M.tokens.ident,M.keywords.block,M.keywords.diagnostic],y.assignment_operators=[M.tokens.equal,M.tokens.plus_equal,M.tokens.minus_equal,M.tokens.times_equal,M.tokens.division_equal,M.tokens.modulo_equal,M.tokens.and_equal,M.tokens.or_equal,M.tokens.xor_equal,M.tokens.shift_right_equal,M.tokens.shift_left_equal],y.increment_operators=[M.tokens.plus_plus,M.tokens.minus_minus];class xE{constructor(A,I,g,B,C){this.type=A,this.lexeme=I,this.line=g,this.start=B,this.end=C}toString(){return this.lexeme}isTemplateType(){return y.template_types.includes(this.type)}isArrayType(){return this.type===y.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class uB{constructor(A){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=A??""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new xE(y.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let A=this._advance();if(A==`
|
|
419
419
|
`)return this._line++,!0;if(this._isWhitespace(A))return!0;if(A=="/"){if(this._peekAhead()=="/"){for(;A!=`
|
|
420
420
|
`;){if(this._isAtEnd())return!0;A=this._advance()}return this._line++,!0}if(this._peekAhead()=="*"){this._advance();let E=1;for(;E>0;){if(this._isAtEnd())return!0;if(A=this._advance(),A==`
|
|
421
421
|
`)this._line++;else if(A=="*"){if(this._peekAhead()=="/"&&(this._advance(),E--,E==0))return!0}else A=="/"&&this._peekAhead()=="*"&&(this._advance(),E++)}return!0}}const I=y.simpleTokens[A];if(I)return this._addToken(I),!0;let g=y.none;const B=this._isAlpha(A),C=A==="_";if(this._isAlphaNumeric(A)){let E=this._peekAhead();for(;this._isAlphaNumeric(E);)A+=this._advance(),E=this._peekAhead()}if(B){const E=y.keywords[A];if(E)return this._addToken(E),!0}if(B||C)return this._addToken(y.tokens.ident),!0;for(;;){let E=this._findType(A);const i=this._peekAhead();if(A=="-"&&this._tokens.length>0){if(i=="=")return this._current++,A+=i,this._addToken(y.tokens.minus_equal),!0;if(i=="-")return this._current++,A+=i,this._addToken(y.tokens.minus_minus),!0;const o=this._tokens.length-1;if((y.literal_or_ident.includes(this._tokens[o].type)||this._tokens[o].type==y.tokens.paren_right)&&i!=">")return this._addToken(E),!0}if(A==">"&&(i==">"||i=="=")){let o=!1,a=this._tokens.length-1;for(let D=0;D<5&&a>=0&&!y.assignment_operators.includes(this._tokens[a].type);++D,--a)if(this._tokens[a].type===y.tokens.less_than){a>0&&this._tokens[a-1].isArrayOrTemplateType()&&(o=!0);break}if(o)return this._addToken(E),!0}if(E===y.none){let o=A,a=0;const D=2;for(let s=0;s<D;++s)if(o+=this._peekAhead(s),E=this._findType(o),E!==y.none){a=s;break}if(E===y.none)return g!==y.none&&(this._current--,this._addToken(g),!0);A=o,this._current+=a+1}if(g=E,this._isAtEnd())break;A+=this._advance()}return g!==y.none&&(this._addToken(g),!0)}_findType(A){for(const g in y.regexTokens){const B=y.regexTokens[g];if(this._match(A,B.rule))return B}return y.literalTokens[A]||y.none}_match(A,I){const g=I.exec(A);return g&&g.index==0&&g[0]==A}_isAtEnd(){return this._current>=this._source.length}_isAlpha(A){return!this._isNumeric(A)&&!this._isWhitespace(A)&&A!=="_"&&!uB._operators.has(A)}_isNumeric(A){return A>="0"&&A<="9"}_isAlphaNumeric(A){return this._isAlpha(A)||this._isNumeric(A)||A==="_"}_isWhitespace(A){return A==" "||A==" "||A=="\r"}_advance(A=0){const I=this._source[this._current];return this._current+=A+1,I??"\0"}_peekAhead(A=0){return this._current+A>=this._source.length?"\0":this._source[this._current+A]}_addToken(A){const I=this._source.substring(this._start,this._current);this._tokens.push(new xE(A,I,this._line,this._start,this._current))}}function X(Q){return Array.isArray(Q)||Q?.buffer instanceof ArrayBuffer}uB._operators=new Set([".","(",")","[","]","{","}",",",";",":","=","!","<",">","+","-","*","/","%","&","|","^","~","@","#","?","'","`",'"',"\\",`
|
|
@@ -541,7 +541,7 @@ fn vert(@location(0) aPos: vec3f) -> @builtin(position) vec4f {
|
|
|
541
541
|
@fragment
|
|
542
542
|
fn frag() -> @location(0) vec4f {
|
|
543
543
|
return vec4f(uniforms.color, uniforms.opacity);
|
|
544
|
-
}`;class hD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=wD(A),g=this.device_.createShaderModule({code:I});await yD(A,g);const B=CD(I),C=AD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];tD(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&GD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(F=>F.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:FD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=ca(B.defs.uniforms.uniforms),G={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(G),G}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function yD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)AA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function tD(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function GD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function wD(Q){switch(Q){case"image_scalar_u32":return oD;case"image_scalar_i32":return aD;case"image_scalar_f32":return DD;case"wireframe":return sD}}function FD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const eD=Lo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function rD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new nD(Q,await A.requestDevice());return await I.compileShaders(),I}class nD extends vC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=CI();currentModelView_=CI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new ia(I),this.geometryBuffers_=new oa(I),this.texturePool_=new Ga(I),this.pipelines_=new hD(I,this.colorFormat_,this.depthFormat_),AA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const{opaque:I,transparent:g}=A.layerManager.partitionLayers();for(const o of[...I,...g])o.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new gI(WA(0,0),WA(this.width,this.height));if(!gI.intersects(B,C)){AA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!gI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.transparent?A.blendMode:"none",this.currentOpacity_=A.opacity,A.objects.forEach((s,G)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,G,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:SD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),xI(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}setUniformsForObject(A,I,g){xI(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms();I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.Color,valueOffset:B.ValueOffset,valueScale:B.ValueScale,opacity:this.currentOpacity_}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){xI(this.currentProjection_,eD,A)}}function SD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}const ND=8;class RD{maxConcurrent_;pending_=[];running_=new Map;constructor(A=ND){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),AA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),AA.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>{const g=A.chunk.priority??Number.MAX_SAFE_INTEGER,B=I.chunk.priority??Number.MAX_SAFE_INTEGER;return g===B?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):g-B});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&AA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}function ZB(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const ZE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function cD(Q){if(ZE.some(I=>Q instanceof I))return!0;const A=ZE.map(I=>I.name);return AA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function UD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function ZI(Q,A,I){return Math.max(A,Math.min(I,Q))}const PB=Symbol("INTERNAL_POLICY_KEY");class kD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,AA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=zo(WA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.camera;if(g.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=g.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,o=I.getBoxRelativeTo(i).toRect().width,a=E/o,D=Math.log2(1/a);this.setLOD(D);const s=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(s)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const F=this.timeIndex(A);if(!this.store_.hasChunksAtTime(F)){AA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const J=BE();_o(J,C.min,C.max,.5);const[m,d]=this.getZBounds(A),T=new WI(SA(C.min[0],C.min[1],m),SA(C.max[0],C.max[1],d));this.chunkViewStates_.forEach(vQ);const z=this.channelsOfInterest(A),u=this.fallbackLOD(),f=this.getPaddedBounds(T),Z=this.currentLOD_===u?[this.currentLOD_]:[this.currentLOD_,u];for(const V of Z){const CA=V===this.currentLOD_,sA=V===u;this.iterateChunksInBox(F,V,z,f,(DA,hA)=>{const yA=WI.intersects(hA,T),uA=CA&&!yA,fA=this.computePriority(sA,CA,yA,uA,!0);fA!==null&&this.chunkViewStates_.set(DA,{visible:yA,prefetch:uA,priority:fA,orderKey:this.squareDistance2D(DA,J)})})}this.markTimeChunksForPrefetchImage(F,A,T,J),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=s,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){const g=xI(CI(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(g)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const C=this.timeIndex(A);if(!this.store_.hasChunksAtTime(C)){AA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(vQ);const E=this.channelsOfInterest(A),i=this.fallbackLOD(),o=a=>{const D=a.lod===i,s=a.lod===this.currentLOD_,G=this.computePriority(D,s,!0,!1,!0);G!==null&&this.chunkViewStates_.set(a,{visible:!0,prefetch:!1,priority:G,orderKey:0})};this.iterateAllChunksAtLod(C,this.currentLOD_,E,o),this.currentLOD_!==i&&this.iterateAllChunksAtLod(C,i,E,o),this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=g}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.state!=="loaded"))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(vQ)}setImageSourcePolicy(A,I){if(I!==PB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,AA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=ZI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=A+1;D<=E;++D)this.iterateChunksInBox(D,i,a,g,s=>{const G=this.squareDistance2D(s,B),F=ZI(G/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),J=D-A+F;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:o,orderKey:J})})}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(g-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=A+1;o<=B;++o)this.iterateAllChunksAtLod(o,C,i,a=>{const D=o-A;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:E,orderKey:D})})}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,G=E?E.chunkSize*E.scale:1,F=B.translation,J=C.translation,m=E?.translation??0,d=Math.max(0,Math.floor((A.min[0]-F)/D)),T=Math.min(i,Math.ceil((A.max[0]-F)/D)),z=Math.max(0,Math.floor((A.min[1]-J)/s)),u=Math.min(o,Math.ceil((A.max[1]-J)/s)),f=E?Math.max(0,Math.floor((A.min[2]-m)/G)):0,Z=E?Math.min(a,Math.ceil((A.max[2]-m)/G)):1;return d>=T||z>=u||f>=Z?null:{xMin:d,xMax:T,yMin:z,yMax:u,zMin:f,zMax:Z}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const G=D[s];for(let F=E.xMin;F<E.xMax;++F){const J=G[F];C(J,this.getChunkAabb(J))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new WI(SA(A.offset.x,A.offset.y,A.offset.z),SA(A.offset.x+A.shape.x*A.scale.x,A.offset.y+A.shape.y*A.scale.y,A.offset.z+A.shape.z*A.scale.z))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:UD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!cQ(this.lastViewBounds2D_.min,A.min)||!cQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!fo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!cQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new WI(SA(A.min[0]-E,A.min[1]-i,A.min[2]-o),SA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}squareDistance2D(A,I){const g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function vQ(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class LD{chunks_;loader_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.loader_=A,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,G=Math.ceil(E.size/a),F=Math.ceil(i.size/D),J=o?Math.ceil(o.size/s):1,m=new Array(I);this.chunks_[C]=m;for(let d=0;d<I;++d){const T=new Array(g);m[d]=T;for(let z=0;z<g;++z){const u=new Array(J);T[z]=u;for(let f=0;f<J;++f){const Z=o!==void 0?o.translation+f*s*o.scale:0,V=new Array(F);u[f]=V;for(let CA=0;CA<F;++CA){const sA=i.translation+CA*D*i.scale,DA=new Array(G);V[CA]=DA;for(let hA=0;hA<G;++hA){const yA=E.translation+hA*a*E.scale;DA[hA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-hA*a),y:Math.min(D,i.size-CA*D),z:Math.min(s,(o?.size??1)-f*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:hA,y:CA,z:f,c:z,t:d},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:yA,y:sA,z:Z}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}createView(A){const I=new kD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const a of this.views_){const D=a.chunkViewStates.get(A);D&&(D.visible&&(I=!0),D.prefetch&&(g=!0),D.priority!==null&&(B===null||D.priority<B)&&(B=D.priority,C=D.orderKey),!D.visible&&!D.prefetch&&D.priority===null&&a.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);A.data=void 0,A.state="unloaded",A.orderKey=null,AA.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!ZB(B,2,.02)||!ZB(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&AA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class JD{stores_=new Map;pendingStores_=new Map;queue_=new RD;get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}async addView(A,I){return(await this.getOrCreateStore(A)).createView(I)}async getOrCreateStore(A){const I=this.stores_.get(A);if(I)return I;const g=this.pendingStores_.get(A);if(g)return g;const C=(async()=>{const i=await A.open();return new LD(i)})();this.pendingStores_.set(A,C);const E=await C;return this.stores_.set(A,E),this.pendingStores_.delete(A),E}update(){for(const[A,I]of this.stores_){const g=I.updateAndCollectChunkChanges();for(const B of g)B.priority===null?this.queue_.cancel(B):B.state==="queued"&&this.queue_.enqueue(B,C=>I.loadChunkData(B,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var sB=function(Q=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var G=0;G<I.children.length;G++)I.children[G].style.display=G===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new sB.Panel("FPS","#0ff","#002",Q)),a=g(new sB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new sB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var G=performance.memory;D.update(G.usedJSHeapSize/1048576,G.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};sB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),G=E(3*i*g),F=E(15*i*g),J=E(74*i*g),m=E(30*i*g),d=document.createElement("canvas");d.width=o,d.height=a,d.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var T=d.getContext("2d");return T.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",T.textBaseline="top",T.fillStyle=I,T.fillRect(0,0,o,a),T.fillStyle=A,T.fillText(Q,D,s),T.fillRect(G,F,J,m),T.fillStyle=I,T.globalAlpha=.9,T.fillRect(G,F,J,m),{dom:d,update:function(z,u){B=Math.min(B,z),C=Math.max(C,z),T.fillStyle=I,T.globalAlpha=1,T.fillRect(0,0,o,F),T.fillStyle=A,T.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),T.drawImage(d,G+i,F,J-i,m,G,F,J-i,m),T.fillRect(G+J-i,F,i,m),T.fillStyle=I,T.globalAlpha=.9,T.fillRect(G+J-i,F,i,E((1-z/u)*m))}}};function YD({scale:Q}={scale:1.5}){const A=new sB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}class PE{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const g of this.layers)g.transparent?I.push(g):A.push(g);return{opaque:A,transparent:I}}add(A){this.layers_=[...this.layers_,A],A.onAttached(this.context_),this.notifyLayersChanged()}remove(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.removeByIndex(I)}removeByIndex(A){const I=this.layers_[A];I&&I.onDetached(this.context_),this.layers_=this.layers_.filter((g,B)=>B!==A),this.notifyLayersChanged()}removeAll(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[],this.notifyLayersChanged()}get layers(){return this.layers_}notifyLayersChanged(){for(const A of this.callbacks_)A()}addLayersChangeCallback(A){return this.callbacks_.push(A),()=>{this.removeLayersChangeCallback(A)}}removeLayersChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove not found: ${A}`);this.callbacks_.splice(I,1)}}const XQ=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function KD(Q){return XQ.includes(Q)}class MD{propagationStopped_=!1;type;event;worldPos;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class HD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){AA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,XQ.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){AA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,XQ.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!KD(A.type)){AA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new MD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class VE{id;element;camera;layerManager;events;cameraControls;constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.layerManager=A.layerManager,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new HD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=WA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layerManager.layers)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.layerManager.add(I)}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),G=Math.floor(I.width),F=Math.floor(I.height);return new gI(WA(D,s),WA(D+G,s+F))}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return SA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new gI(WA(g,B),WA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){AA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function jQ(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function dD(Q){for(let A=0;A<Q.length;A++)jQ(Q[A],Q.slice(0,A))}function zQ(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??zC("viewport"),layerManager:new PE(I)}});return dD(g),g.map(B=>new VE(B))}class qD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){AA.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){AA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){AA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){AA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class _Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await rD(A.canvas):new UQ(A.canvas);return new _Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new UQ(this.canvas),this.chunkManager_=new JD,this.context_={chunkManager:this.chunkManager_},this.viewports_=zQ(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=YD());const g=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&g.push(B.element);this.sizeObserver_=new qD(g,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=zQ([A],this.canvas,this.context_);return jQ(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),AA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(AA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),AA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(AA.info("Idetik","Idetik runtime starting"),this.running)AA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(AA.info("Idetik","Idetik runtime stopping"),!this.running)AA.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}}class lD extends Ug{constructor(A){if(super(),A.primitive!="triangles"){AA.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){AA.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],B=(E,i)=>{const o=Math.min(E,i),a=Math.max(E,i);I.has({i0:o,i1:a})||(I.add({i0:o,i1:a}),g.push(o,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],a=C[E+2];B(i,o),B(o,a),B(a,i)}this.indexData_=new Uint32Array(g)}}const fD=SA(0,1,0);class pD{dirty_=!0;matrix_=CI();rotation_=SQ();translation_=dA();scale_=SA(1,1,1);addRotation(A){Oo(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){Xo(this.rotation_,A),this.dirty_=!0}get rotation(){return vo(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){wQ(this.translation_,A),this.dirty_=!0}get translation(){return dI(this.translation_)}addScale(A){mo(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){wQ(this.scale_,A),this.dirty_=!0}targetTo(A){rQ(this.translation_,A)&&(A=dI(A),A[2]+=JA);const I=lo(CI(),this.translation_,A,fD),g=ko(_C(),I);gE(this.rotation_,g),RQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return dI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return HB(CI(),this.matrix)}computeMatrix(){Yo(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Mg extends tQ{wireframeEnabled=!1;wireframeColor=eA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new pD;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const g=this.textures_[A];g!==void 0&&this.staleTextures_.push(g),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new lD(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class og{normal;signedDistance;constructor(A=SA(0,1,0),I=0){this.normal=dI(A),this.signedDistance=I}set(A,I){this.normal=dI(A),this.signedDistance=I}signedDistanceToPoint(A){return IE(this.normal,A)+this.signedDistance}normalize(){const A=GQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class OE{planes_;constructor(A){this.planes_=[new og(dA(),0),new og(dA(),0),new og(dA(),0),new og(dA(),0),new og(dA(),0),new og(dA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=dA();this.planes_[0].set(Qg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(Qg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(Qg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(Qg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(Qg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(Qg(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const g of this.planes_)g.normalize()}intersectsWithBox3(A){const I=dA();for(const g of this.planes_){const B=g.normal;if(I[0]=B[0]>0?A.max[0]:A.min[0],I[1]=B[1]>0?A.max[1]:A.min[1],I[2]=B[2]>0?A.max[2]:A.min[2],g.signedDistanceToPoint(I)<0)return!1}return!0}}class vE extends Mg{projectionMatrix_=CI();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return SA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return SA(A[4],A[5],A[6])}get frustum(){return new OE(xI(CI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=dB(A[0],A[1],A[2],1),g=HB(CI(),this.projectionMatrix_),B=QB(cg(),I,g);Zo(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return SA(C[0],C[1],C[2])}}const XE=1.77,jE=128,zE=128/XE;class mD extends vE{width_=jE;height_=zE;viewportAspectRatio_=XE;viewportSize_=[jE,zE];constructor(A,I,g,B,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,B,g),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,g,B){this.width_=Math.abs(I-A),this.height_=Math.abs(B-g),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(g+B);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=dB(-1,-1,0,1),I=dB(1,1,0,1);const g=xI(CI(),this.projectionMatrix,this.viewMatrix),B=HB(CI(),g);return A=QB(cg(),A,B),I=QB(cg(),I,B),new gI(WA(A[0],A[1]),WA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,g=A/I;let B=.5*A,C=.5*I;this.viewportAspectRatio_>g?B*=this.viewportAspectRatio_/g:C*=g/this.viewportAspectRatio_,this.viewportSize_=[2*B,2*C],qo(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const uD=60,xD=1.77,VB=.1,$Q=180-VB;class WD extends vE{fov_;aspectRatio_;constructor(A={}){const{fov:I=uD,aspectRatio:g=xD,near:B=.1,far:C=1e4,position:E=SA(0,0,0)}=A;if(I<VB||I>$Q)throw new Error(`Invalid field of view: ${I}, must be in [${VB}, ${$Q}] degrees`);super(),this.fov_=I,this.aspectRatio_=g,this.near_=B,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(VB,Math.min($Q,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){Mo(this.projectionMatrix_,Uo(this.fov),this.aspectRatio_,this.near_,this.far_)}}const _E=0;class TD{camera_;dragActive_=!1;dragStart_=dA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const g=dI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=nQ(dA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==_E||(this.dragStart_=dI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=nQ(dA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==_E||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class AC{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}toVec3(){const A=Math.cos(this.theta);return SA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const IC=-1,$E=0,bD=1,Ai=.009,ZD=.001,PD=9e-4,VD=.5,OD=60;class vD{camera_;orbitVelocity_=new AC(0,0,0);panVelocity_=dA();currPos_;currCenter_=dA();dampingFactor_;currMouseButton_=IC;constructor(A,I){this.camera_=A,this.currPos_=new AC(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&wQ(this.currCenter_,I.target),this.dampingFactor_=ZI(I?.dampingFactor??VD,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&rQ(this.panVelocity_,SA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,gB(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-JA;this.currPos_.theta=ZI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*OD);this.orbitVelocity_.phi*=g,this.orbitVelocity_.theta*=g,this.orbitVelocity_.radius*=g,BB(this.panVelocity_,this.panVelocity_,g),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==IC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===$E&&!I.shiftKey,E=this.currMouseButton_===$E&&I.shiftKey||this.currMouseButton_===bD;C&&this.orbit(g,B),E&&this.pan(g,B)}onWheel(A){const I=A.event;I.preventDefault();const g=I.deltaY??0;this.zoom(g)}onPointerEnd(A){this.currMouseButton_=IC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*Ai,this.orbitVelocity_.theta+=I*Ai}pan(A,I){const g=this.currPos_.radius*ZD,B=dA();$C(B,B,this.camera_.right,A),$C(B,B,this.camera_.up,I),BB(B,B,g),nQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*PD}updateCamera(){const A=gB(dA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<JA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<JA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<JA&&(this.orbitVelocity_.radius=0),GQ(this.panVelocity_)<JA&&xo(this.panVelocity_)}}class hB{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:g="normal"}={}){(I<0||I>1)&&AA.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=ZI(I,0,1),this.blendMode=g}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&AA.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=ZI(A,0,1)}onEvent(A){}async onAttached(A){}onDetached(A){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}getUniforms(){return{}}}class XD extends Ug{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*10),g=A.length>=3&&rQ(A[0],A[A.length-1]);let B=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[B++]=i[0],I[B++]=i[1],I[B++]=i[2];const o=C===0?g?A[A.length-2]:A[C]:A[C-1];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const a=C===A.length-1?g?A[1]:A[C]:A[C+1];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let g=0;for(let B=0;B<2*A;B+=2)I[g++]=B+0,I[g++]=B+1,I[g++]=B+2,I[g++]=B+2,I[g++]=B+1,I[g++]=B+3;return I}}class jD extends Mg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=eA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=eA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width}}}class zD extends hB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(gC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(gC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(gC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function gC(Q){const{end:A,width:I,color:g}=Q,B=new XD([[0,0,0],A]);return new jD({geometry:B,color:g,width:I})}const Ii=32;function yB(Q,{visible:A,color:I,contrastLimits:g}){return A===void 0&&(A=!0),I===void 0?I=eA.WHITE:I=eA.from(I),Q!==null?g=_D(g,Q):g===void 0&&(AA.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g}}function BC(Q,A){if(A.length>Ii)throw new Error(`Maximum number of channels is ${Ii}`);return A.map(I=>yB(Q,I))}function gi(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function _D(Q,A){if(Q===void 0)return ta(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Bi extends Ug{constructor(A,I,g,B){super();const C=[],E=[],i=g,o=B,a=i+1,D=o+1,s=A/i,G=I/o;for(let F=0;F<D;++F){const J=F*G;for(let m=0;m<a;++m){const d=m*s,T=m/i,z=F/o,u=[d,J,0],f=[0,0,1],Z=[T,z];C.push(...u,...f,...Z)}}for(let F=0;F<o;++F)for(let J=0;J<i;++J){const m=J+a*F,d=J+a*(F+1),T=J+1+a*(F+1),z=J+1+a*F;E.push(m,d,z),E.push(d,T,z)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class $D extends Mg{channels_;constructor(A,I,g,B=[]){super(),this.geometry=new Bi(A,I,1,1),this.setTexture(0,g),this.channels_=BC(g,B),this.programName=As(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=BC(this.textures[0],A)}setChannelProperty(A,I,g){const B=yB(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=B}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g}=this.channels_[0]??yB(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-g[0],ValueScale:1/(g[1]-g[0])}}}function As(Q){switch(Q.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}class Hg extends kQ{data_;width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==g){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new Hg(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}function Qi(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return WA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=WA(C.clientX,C.clientY);if(jo(A,E)<B){if(!g)return null;const o=Q.worldPos;if(o){const a=I(o);a!==null&&g({world:o,value:a})}return null}return A}case"pointercancel":return null;default:return A}}class QC{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&AA.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),AA.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class CC extends hB{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new QC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new eA(.6,.3,.3),new eA(.3,.6,.4),new eA(.4,.4,.7),new eA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,channelProps:B,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=C}async onAttached(A){if(this.chunkStoreView_)throw new Error("ImageLayer cannot be attached to multiple contexts simultaneously.");this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_);const I=this.chunkStoreView_.channelCount;if(gi(this.channelProps_,I),I>1&&this.sliceCoords_.c!==void 0&&this.sliceCoords_.c.length>1)throw new Error(`ImageLayer requires exactly one channel in sliceCoords.c for multi-channel sources (found ${I} channels). Use one layer per channel.`)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getImageForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>CC.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,g]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const B=this.slicePlane(I,A);B&&g.textures[0].updateWithChunk(I,B)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=Qi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,PB))}slicePlane(A,I){if(!A.data)return;const g=(I-A.offset.z)/A.scale.z,B=Math.round(g),C=ZI(B,0,A.shape.z-1);ZB(g,C,1+1e-6)||AA.error("ImageLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(OB(A));return g?(g.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(g,A),g.setChannelProps(this.getChannelPropsForChunk(A)),g):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new $D(A.shape.x,A.shape.y,Hg.createWithChunk(A,this.getDataForImage(A)),this.getChannelPropsForChunk(A));return this.updateImageChunk(I,A),I}getDataForImage(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){AA.warn("ImageLayer","No data for image");return}return I}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1,A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[g,B]of this.visibleChunks_){if(g.lod!==I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}for(const[g,B]of this.visibleChunks_){if(g.lod===I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}return null}getValueFromChunk(A,I,g){if(!A.data)return null;const B=eQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,o=E*A.shape.x+C;return i[o]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(OB(I),g),this.visibleChunks_.delete(I))}}}function OB(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}`,`align${Q.rowAlignmentBytes}`].join(":")}class Is extends Ug{constructor(A,I,g,B,C,E){super();const i=[],o=[],a=Math.floor(B),D=Math.floor(C),s=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,s,D,1,i,o),this.buildFace("z","y","x",1,-1,g,I,A,s,D,-1,i,o),this.buildFace("x","z","y",1,1,A,g,I,a,s,1,i,o),this.buildFace("x","z","y",1,-1,A,g,I,a,s,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,g,a,D,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,g,a,D,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,g,B,C,E,i,o,a,D,s,G,F){const J=E/a,m=i/D,d=E/2,T=i/2,z=o/2*s,u=a+1,f=D+1,Z=G.length/8;for(let V=0;V<f;V++){const CA=-T+V*m;for(let sA=0;sA<u;sA++){const DA=-d+sA*J,hA={x:0,y:0,z:0};hA[A]=DA*B,hA[I]=CA*C,hA[g]=z;const yA={x:0,y:0,z:0};yA[g]=s;const uA=sA/a,fA=1-V/D;G.push(hA.x,hA.y,hA.z,yA.x,yA.y,yA.z,uA,fA)}}for(let V=0;V<D;V++)for(let CA=0;CA<a;CA++){const sA=Z+CA+u*V,DA=Z+CA+u*(V+1),hA=Z+(CA+1)+u*(V+1),yA=Z+(CA+1)+u*V;F.push(sA,DA,yA,DA,hA,yA)}}}class dg extends kQ{data_;width_;height_;depth_;constructor(A,I,g,B){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=kg(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const g=new dg(I,A.shape.x,A.shape.y,A.shape.z);return g.unpackAlignment=A.rowAlignmentBytes,g}}class gs extends Mg{voxelScale=SA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new Is(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=dg.createWithChunk(I),B=this.textures.length;this.setTexture(B,g),this.channelToTextureIndex_.set(A,B);const C=Bs(g.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${g.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const g=this.textures[A];if(!(g instanceof dg)){const B=dg.createWithChunk(I);this.setTexture(A,B);return}g.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],B=[1,1,1,1],C=[],E=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let i=0;i<E&&C.length<4;i++){const o=this.channelToTextureIndex_.get(i);if(o===void 0||!this.loadedChannels_.has(i))continue;const a=this.textures[o],D=yB(a,this.channels_[i]||{});if(!D.visible)continue;const s=C.length;I[s*3]=D.color.rgb[0],I[s*3+1]=D.color.rgb[1],I[s*3+2]=D.color.rgb[2],C.push(o),g[s]=-D.contrastLimits[0],B[s]=1/(D.contrastLimits[1]-D.contrastLimits[0]),A[s]=1}return C.reduce((i,o,a)=>(i[`Channel${a}Sampler`]=o,i),{Visible:A,"Color[0]":I,ValueOffset:g,ValueScale:B,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=BC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=yB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Bs(Q){switch(Q){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function Qs(Q,A){const I=A.position,g=dA(),B=dA();return Q.sort((C,E)=>{gB(g,C.boundingBox.max,C.boundingBox.min),BB(g,g,.5),gB(B,E.boundingBox.max,E.boundingBox.min),BB(B,B,.5);const i=AE(I,g),o=AE(I,B);return i-o}),Q}const Cs=2;class Es extends hB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new QC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,PB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:g,channelProps:B}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=g,this.initialChannelProps_=B,this.channelProps_=B,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const B=as(I[0]),C=this.pool_.acquire(B)??new gs;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,B);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}async onAttached(A){this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.sourcePolicy_),gi(this.channelProps_,this.chunkStoreView_.channelCount)}onDetached(A){if(this.chunkStoreView_){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0}}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=os(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i),this.addObject(i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length,this.state!=="ready"&&this.setState("ready")}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),Qg(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveVolume(A){A.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!this.chunkStoreView_)return;if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.viewport);const I=A.viewport.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?Cs:1,this.updateChunks(),Qs(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function is(Q){const{x:A,y:I,z:g,t:B}=Q.chunkIndex;return`${A}:${I}:${g}:${B}`}function os(Q){const A=new Map;for(const I of Q){const g=is(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function as(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}const Ds=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function ss(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!Ds.has(Q.dataType))throw new Error(`Image data type must be unsigned, instead found: ${Q.dataType}`);return Q}class hs extends Mg{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new Bi(A.width,A.height,1,1),this.setTexture(0,ss(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const g=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,g),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(B=>B.rgba).map(B=>Math.round(B*255))),g=new Hg(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,eA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,eA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),B=A.size,C=new Uint32Array(B*2);return C.set(I,0),C.set(g,B),new Hg(C,B,2)}}const ys=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function ts(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,eA.from(I)]))}function Gs(Q){return Q=Q??ys,Q.map(eA.from)}class Ci{lookupTable;cycle;constructor(A={}){this.lookupTable=ts(A.lookupTable),this.cycle=Gs(A.cycle)}}class EC extends hB{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new QC;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,colorMap:B={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.colorMap_=new Ci(B),this.onPickValue_=C,this.outlineSelected_=E}async onAttached(A){if(this.chunkStoreView_)throw new Error("LabelLayer cannot be attached to multiple contexts simultaneously.");if(this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getLabelForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>EC.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,g]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const B=this.slicePlane(I,A);B&&g.textures[0].updateWithChunk(I,B)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=Qi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new Ci(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,PB))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[g,B]of this.visibleChunks_){if(g.lod!==I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}for(const[g,B]of this.visibleChunks_){if(g.lod===I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}return null}getValueFromChunk(A,I,g){if(!A.data)return null;const B=eQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,o=E*A.shape.x+C;return i[o]}return null}slicePlane(A,I){if(!A.data)return;const g=(I-A.offset.z)/A.scale.z,B=Math.round(g),C=ZI(B,0,A.shape.z-1);ZB(g,C,1+1e-6)||AA.error("LabelLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getLabelForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(OB(A));return g?(g.textures[0].updateWithChunk(A,this.getDataForLabel(A)),this.updateLabelChunk(g,A),g.setColorMap(this.colorMap_),g.setSelectedValue(this.selectedValue_),g):this.createLabel(A)}createLabel(A){const I=new hs({width:A.shape.x,height:A.shape.y,imageData:Hg.createWithChunk(A,this.getDataForLabel(A)),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(I,A),I}getDataForLabel(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){AA.warn("LabelLayer","No data for label");return}return I}updateLabelChunk(A,I){A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(OB(I),g),this.visibleChunks_.delete(I))}}}function ws(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function Ei(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function ii(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class tB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,ws(this.#I,I))}async get(A,I={}){let g=Ei(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return ii(C)}async getRange(A,I,g={}){let B=Ei(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return ii(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class GB extends Error{}class qg extends GB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class XA extends GB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class Fs extends GB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class es extends GB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class iC extends GB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function ag(Q){return()=>{throw new iC(`${Q} encode`)}}class oC{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new XA("keepbits must be zero or positive")}static fromConfig(A,I){return new oC(A,I)}encode=ag("bitround");decode(A){return A}}function aC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class oi{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):aC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class DC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(aC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class wB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(aC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new wB(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function rs(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function ns(Q,A){return new SharedArrayBuffer(Q)}function FB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new XA("Failed to decode JSON",{cause:I})}}function ai(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function lg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?wB:DC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:oi}[Q];if(!I)throw new XA(`Unknown or unsupported dataType: ${Q}`);return I}function Dg(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function Ss({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new XA(`Unknown chunk key encoding: ${Q}`)}function Di(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new XA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new XA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function Ns(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function Rs(Q,A={}){let I=[],g=Di(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!Ns(C))throw new XA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=Di(o).dataType;if(!sC(a,"number")&&!sC(a,"bigint"))throw new XA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function cs(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function sC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function Us(Q){return Q?.name==="sharding_indexed"}function si(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function hi(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function yi(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const ti=ks();function ks(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function Gi(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class vB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=lg(I.dataType),this.#B=I.shape,this.#A=Dg(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new vB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return ti&&this.#Q==="big"&&ai(I,Gi(this.#I)),I}decode(A){return ti&&this.#Q==="big"&&ai(A,Gi(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const wi={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},Fi={float16:2,float32:4,float64:8};function XB(Q){return Q in Fi}function hC(Q){return Q==="int64"||Q==="uint64"}function Ls(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new iC("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function jB(Q,A){if(hC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new XA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!XB(Q)&&!Number.isInteger(A))throw new XA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!XB(Q))throw new XA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in wi?wi[A]:Ls(A,Fi[Q])}const ei=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),yC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},tC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function ri(Q,A,I){return Q.map(([g,B])=>({src:jB(A,g),tgt:jB(I,B)}))}function Js(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Ys(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function Ks(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function ni(Q){switch(Q){case"nearest-even":return Ys;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return Ks}}function GC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function wC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class FC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=lg(A),this.#g=Si(I,A,g,B,C),this.#B=Si(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!ei.has(g))throw new XA(`cast_value codec does not support array data type: ${g}`);if(!ei.has(B))throw new XA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?ri(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?ri(A.scalar_map.encode,g,B):[];return new FC(g,B,C,A.out_of_range,E,i)}encode=ag("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function Si(Q,A,I,g,B){const C=XB(Q),E=hC(Q),i=XB(A),o=hC(A);let a;if(C&&i){if(I!=="nearest-even")throw new XA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=ni(I),G=GC(...yC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return G(s(F))}}else if(C&&o){const s=ni(I),G=wC(...tC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return G(BigInt(s(F)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=GC(...yC[A],g);else if(!C&&!E&&o){const s=wC(...tC[A],g);a=G=>s(BigInt(G))}else if(E&&!i&&!o){const s=GC(...yC[A],g);a=G=>s(Number(G))}else if(E&&o)a=wC(...tC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const G=Js(s,B);return G!==void 0?G:a(s)}}class eC{kind="bytes_to_bytes";static fromConfig(){return new eC}encode=ag("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}const Ms=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function Ni(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class rC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!Ms.has(I.dataType))throw new XA(`Delta codec does not support data type: ${I.dataType}`);return new rC(lg(I.dataType))}encode(A){Ni(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){Ni(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class nC{kind="bytes_to_bytes";static fromConfig(A){return new nC}encode=ag("gzip");async decode(A){const I=await yi(A,{format:"gzip"});return new Uint8Array(I)}}function Hs(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function ds(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class SC{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new SC(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(Hs),i&&o.push(ds);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(G,F)=>{let J=F;for(let m of o)J=m(G,J);return J});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,G=>{const F=`0000${G.charCodeAt(0).toString(16)}`;return`\\u${F.substring(F.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=FB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=Dg(B,"C");return{data:g,shape:B,stride:C}}}const qs=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class NC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!qs.has(I.dataType))throw new XA(`scale_offset codec does not support data type: ${I.dataType}`);return new NC(jB(I.dataType,A.scale??1),jB(I.dataType,A.offset??0),lg(I.dataType))}encode=ag("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class RC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(lg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new RC(A,I)}encode(A){return ls(A,this.#A)}decode(A){return fs(A,this.#A)}}function ls(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function fs(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function Ri(Q){return Q instanceof oi||Q instanceof DC||Q instanceof wB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function ps(Q,A){let I;return Q.data instanceof DC||Q.data instanceof wB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:Dg(Q.shape,A)}}function ms(Q,A){let I=ps(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=Ri(Q.data),i=Ri(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function us(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function xs(Q,A){let I=us(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class cC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new cC(A,I)}encode(A){return xs(A,this.#I)?A:ms(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:Dg(A.shape,this.#A)}}}class zB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=Dg(A,"C")}static fromConfig(A,I){return new zB(I.shape)}encode=ag("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class UC{kind="bytes_to_bytes";static fromConfig(A){return new UC}encode=ag("zlib");async decode(A){const I=await yi(A,{format:"deflate"});return new Uint8Array(I)}}function Ws(){let Q=()=>Promise.resolve().then(()=>ny).then(C=>C.default),A=()=>Promise.resolve().then(()=>ky).then(C=>C.default),I=()=>Promise.resolve().then(()=>Hy).then(C=>C.default),g=()=>nC,B=()=>UC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>cC).set("bytes",()=>vB).set("crc32c",()=>eC).set("vlen-utf8",()=>zB).set("json2",()=>SC).set("bitround",()=>oC).set("cast_value",()=>FC).set("scale_offset",()=>NC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>zB).set("numcodecs.shuffle",()=>RC).set("numcodecs.delta",()=>rC)}const Ts=Ws();function kC(Q){let A;function I(){return A||(A=bs(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new es({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E}}}async function bs(Q){let A=Q.codecs.map(async E=>{let i=await Ts.get(E.name)?.();if(!i)throw new Fs(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Zs(C))throw new XA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:vB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Zs(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ci=18446744073709551615n;function Ps(Q,A,I,g){if(!Q.store.getRange)throw new iC("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((D,s)=>D/g.chunk_shape[s]),E=kC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=4,o=16*C.reduce((D,s)=>D*s,1),a={};return async(D,s)=>{let G=D.map((Z,V)=>Math.floor(Z/C[V])),F=Q.resolve(I(G)).path;F in a||(a[F]=(async()=>{let Z=await B(F,{suffixLength:o+i},s);return Z?await E.decode(Z):null})().catch(Z=>{throw delete a[F],Z}));let J=await a[F];if(J===null)return;let{data:m,shape:d,stride:T}=J,z=D.map((Z,V)=>Z%d[V]).reduce((Z,V,CA)=>Z+V*T[CA],0),u=m[z],f=m[z+1];if(!(u===ci&&f===ci))return B(F,{offset:Number(u),length:Number(f)},s)}}class eI{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new eI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class LC extends eI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Ui(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const _B=Symbol("zarrita.context");function Vs(Q,A){let{configuration:I}=A.codecs.find(Us)??{},g={encodeChunkKey:Ss(A.chunk_key_encoding),TypedArray:lg(A.data_type),fillValue:A.fill_value};if(I){let C=Ui(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:kC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return Dg(E,C)},getChunkBytes:Ps(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Ui(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:kC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return Dg(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let $B=class extends eI{kind="array";#A;[_B];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:si(g)},this[_B]=Vs(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[_B].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&rs();let B=this[_B],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=ns(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return sC(this.dtype,A)}};function Os(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function vs(Q,...A){return Os(Q,A)}async function ki(Q){let A=Q.store.arrayExtensions;return A?.length?await vs(Q,...A):Q}let AQ=Xs();function Xs(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function js(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?FB(I):{}}async function zs(Q,A={}){let I="store"in Q?Q:new eI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await js(I,g)),g?.throwIfAborted(),A.kind==="array"?Li(I,B,g):A.kind==="group"?Ji(I,B,g):Li(I,B,g).catch(C=>(hi(C,qg,XA),Ji(I,B,g)))}async function Li(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new qg("v2 array",{path:g});return AQ.increment(Q.store,"v2"),ki(new $B(Q.store,Q.path,Rs(FB(B),A)))}async function Ji(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new qg("v2 group",{path:g});return AQ.increment(Q.store,"v2"),new LC(Q.store,Q.path,cs(FB(B),A))}async function _s(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new qg("v3 array or group",{path:g});let C=FB(B);return C.node_type==="array"&&(C.fill_value=si(C)),C.node_type==="array"?ki(new $B(I,Q.path,C)):new LC(I,Q.path,C)}async function $s(Q,A={}){let I="store"in Q?Q:new eI(Q),g=await _s(I,A.signal);if(AQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof $B||A.kind==="group"&&g instanceof LC)return g;let B=g instanceof $B?"array":"group";throw new qg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=AQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(hi(E,qg,XA),C(Q,A)))}rI.v2=zs,rI.v3=$s;async function Ah(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class JC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Ah(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function eB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function Ih(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function gh(Q){let A;switch(Q.type){case"fetch":{const g=new tB(Q.url);A=new eI(g);break}case"filesystem":{A=new eI(new JC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return Ih(I,Q.zarrVersion)}function Bh(Q,A,I){if(Q.store instanceof tB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof JC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function Qh(Q,A,I,g){return Ch(Q,A,I,g)}function Ch(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let Z=A.length-1;Z>=0;Z--){if(I[Z]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[Z]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,G=E.c!==void 0?I[E.c]:0,F=E.t!==void 0?I[E.t]:0,J=D*F+a*G,m=o.x===B.x&&o.y===B.y&&o.z===B.z;if(J===0&&Q.length===s&&m)return Q;const T=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,u=I[E.y];let f=0;for(let Z=0;Z<B.z;Z++){const V=J+Z*z;for(let CA=0;CA<B.y;CA++){const sA=V+CA*u,DA=sA+B.x;T.set(Q.subarray(sA,DA),f),f+=B.x}}return T}const Yi=`function Zg(B, A) {
|
|
544
|
+
}`;class hD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=wD(A),g=this.device_.createShaderModule({code:I});await yD(A,g);const B=CD(I),C=AD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];tD(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&GD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(F=>F.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:FD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=ca(B.defs.uniforms.uniforms),G={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(G),G}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function yD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)AA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function tD(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function GD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function wD(Q){switch(Q){case"image_scalar_u32":return oD;case"image_scalar_i32":return aD;case"image_scalar_f32":return DD;case"wireframe":return sD}}function FD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const eD=Lo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function rD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new nD(Q,await A.requestDevice());return await I.compileShaders(),I}class nD extends vC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=CI();currentModelView_=CI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new ia(I),this.geometryBuffers_=new oa(I),this.texturePool_=new Ga(I),this.pipelines_=new hD(I,this.colorFormat_,this.depthFormat_),AA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const{opaque:I,transparent:g}=A.layerManager.partitionLayers();for(const o of[...I,...g])o.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new gI(WA(0,0),WA(this.width,this.height));if(!gI.intersects(B,C)){AA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!gI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentOpacity_=A.opacity,A.objects.forEach((s,G)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,G,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:SD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),xI(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}setUniformsForObject(A,I,g){xI(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms();I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.Color,valueOffset:B.ValueOffset,valueScale:B.ValueScale,opacity:this.currentOpacity_}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){xI(this.currentProjection_,eD,A)}}function SD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}const ND=8;class RD{maxConcurrent_;pending_=[];running_=new Map;constructor(A=ND){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),AA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),AA.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>{const g=A.chunk.priority??Number.MAX_SAFE_INTEGER,B=I.chunk.priority??Number.MAX_SAFE_INTEGER;return g===B?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):g-B});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&AA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}function ZB(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const ZE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function cD(Q){if(ZE.some(I=>Q instanceof I))return!0;const A=ZE.map(I=>I.name);return AA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function UD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function ZI(Q,A,I){return Math.max(A,Math.min(I,Q))}const PB=Symbol("INTERNAL_POLICY_KEY");class kD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,AA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=zo(WA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.camera;if(g.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=g.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,o=I.getBoxRelativeTo(i).toRect().width,a=E/o,D=Math.log2(1/a);this.setLOD(D);const s=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(s)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const F=this.timeIndex(A);if(!this.store_.hasChunksAtTime(F)){AA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const J=BE();_o(J,C.min,C.max,.5);const[m,d]=this.getZBounds(A),T=new WI(SA(C.min[0],C.min[1],m),SA(C.max[0],C.max[1],d));this.chunkViewStates_.forEach(vQ);const z=this.channelsOfInterest(A),u=this.fallbackLOD(),f=this.getPaddedBounds(T),Z=this.currentLOD_===u?[this.currentLOD_]:[this.currentLOD_,u];for(const V of Z){const CA=V===this.currentLOD_,sA=V===u;this.iterateChunksInBox(F,V,z,f,(DA,hA)=>{const yA=WI.intersects(hA,T),uA=CA&&!yA,fA=this.computePriority(sA,CA,yA,uA,!0);fA!==null&&this.chunkViewStates_.set(DA,{visible:yA,prefetch:uA,priority:fA,orderKey:this.squareDistance2D(DA,J)})})}this.markTimeChunksForPrefetchImage(F,A,T,J),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=s,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){const g=xI(CI(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(g)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const C=this.timeIndex(A);if(!this.store_.hasChunksAtTime(C)){AA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(vQ);const E=this.channelsOfInterest(A),i=this.fallbackLOD(),o=a=>{const D=a.lod===i,s=a.lod===this.currentLOD_,G=this.computePriority(D,s,!0,!1,!0);G!==null&&this.chunkViewStates_.set(a,{visible:!0,prefetch:!1,priority:G,orderKey:0})};this.iterateAllChunksAtLod(C,this.currentLOD_,E,o),this.currentLOD_!==i&&this.iterateAllChunksAtLod(C,i,E,o),this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=g}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.state!=="loaded"))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(vQ)}setImageSourcePolicy(A,I){if(I!==PB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,AA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=ZI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=A+1;D<=E;++D)this.iterateChunksInBox(D,i,a,g,s=>{const G=this.squareDistance2D(s,B),F=ZI(G/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),J=D-A+F;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:o,orderKey:J})})}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(g-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=A+1;o<=B;++o)this.iterateAllChunksAtLod(o,C,i,a=>{const D=o-A;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:E,orderKey:D})})}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,G=E?E.chunkSize*E.scale:1,F=B.translation,J=C.translation,m=E?.translation??0,d=Math.max(0,Math.floor((A.min[0]-F)/D)),T=Math.min(i,Math.ceil((A.max[0]-F)/D)),z=Math.max(0,Math.floor((A.min[1]-J)/s)),u=Math.min(o,Math.ceil((A.max[1]-J)/s)),f=E?Math.max(0,Math.floor((A.min[2]-m)/G)):0,Z=E?Math.min(a,Math.ceil((A.max[2]-m)/G)):1;return d>=T||z>=u||f>=Z?null:{xMin:d,xMax:T,yMin:z,yMax:u,zMin:f,zMax:Z}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const G=D[s];for(let F=E.xMin;F<E.xMax;++F){const J=G[F];C(J,this.getChunkAabb(J))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new WI(SA(A.offset.x,A.offset.y,A.offset.z),SA(A.offset.x+A.shape.x*A.scale.x,A.offset.y+A.shape.y*A.scale.y,A.offset.z+A.shape.z*A.scale.z))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:UD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!cQ(this.lastViewBounds2D_.min,A.min)||!cQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!fo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!cQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new WI(SA(A.min[0]-E,A.min[1]-i,A.min[2]-o),SA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}squareDistance2D(A,I){const g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function vQ(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class LD{chunks_;loader_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.loader_=A,this.dimensions_=this.loader_.getSourceDimensionMap(),this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,G=Math.ceil(E.size/a),F=Math.ceil(i.size/D),J=o?Math.ceil(o.size/s):1,m=new Array(I);this.chunks_[C]=m;for(let d=0;d<I;++d){const T=new Array(g);m[d]=T;for(let z=0;z<g;++z){const u=new Array(J);T[z]=u;for(let f=0;f<J;++f){const Z=o!==void 0?o.translation+f*s*o.scale:0,V=new Array(F);u[f]=V;for(let CA=0;CA<F;++CA){const sA=i.translation+CA*D*i.scale,DA=new Array(G);V[CA]=DA;for(let hA=0;hA<G;++hA){const yA=E.translation+hA*a*E.scale;DA[hA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-hA*a),y:Math.min(D,i.size-CA*D),z:Math.min(s,(o?.size??1)-f*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:hA,y:CA,z:f,c:z,t:d},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:yA,y:sA,z:Z}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}createView(A){const I=new kD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const a of this.views_){const D=a.chunkViewStates.get(A);D&&(D.visible&&(I=!0),D.prefetch&&(g=!0),D.priority!==null&&(B===null||D.priority<B)&&(B=D.priority,C=D.orderKey),!D.visible&&!D.prefetch&&D.priority===null&&a.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);A.data=void 0,A.state="unloaded",A.orderKey=null,AA.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!ZB(B,2,.02)||!ZB(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&AA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class JD{stores_=new Map;pendingStores_=new Map;queue_=new RD;get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}async addView(A,I){return(await this.getOrCreateStore(A)).createView(I)}async getOrCreateStore(A){const I=this.stores_.get(A);if(I)return I;const g=this.pendingStores_.get(A);if(g)return g;const C=(async()=>{const i=await A.open();return new LD(i)})();this.pendingStores_.set(A,C);const E=await C;return this.stores_.set(A,E),this.pendingStores_.delete(A),E}update(){for(const[A,I]of this.stores_){const g=I.updateAndCollectChunkChanges();for(const B of g)B.priority===null?this.queue_.cancel(B):B.state==="queued"&&this.queue_.enqueue(B,C=>I.loadChunkData(B,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var sB=function(Q=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var G=0;G<I.children.length;G++)I.children[G].style.display=G===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new sB.Panel("FPS","#0ff","#002",Q)),a=g(new sB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new sB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var G=performance.memory;D.update(G.usedJSHeapSize/1048576,G.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};sB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),G=E(3*i*g),F=E(15*i*g),J=E(74*i*g),m=E(30*i*g),d=document.createElement("canvas");d.width=o,d.height=a,d.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var T=d.getContext("2d");return T.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",T.textBaseline="top",T.fillStyle=I,T.fillRect(0,0,o,a),T.fillStyle=A,T.fillText(Q,D,s),T.fillRect(G,F,J,m),T.fillStyle=I,T.globalAlpha=.9,T.fillRect(G,F,J,m),{dom:d,update:function(z,u){B=Math.min(B,z),C=Math.max(C,z),T.fillStyle=I,T.globalAlpha=1,T.fillRect(0,0,o,F),T.fillStyle=A,T.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),T.drawImage(d,G+i,F,J-i,m,G,F,J-i,m),T.fillRect(G+J-i,F,i,m),T.fillStyle=I,T.globalAlpha=.9,T.fillRect(G+J-i,F,i,E((1-z/u)*m))}}};function YD({scale:Q}={scale:1.5}){const A=new sB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}class PE{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const g of this.layers)g.blendMode==="none"?A.push(g):I.push(g);return{opaque:A,transparent:I}}add(A){this.layers_=[...this.layers_,A],A.onAttached(this.context_),this.notifyLayersChanged()}remove(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.removeByIndex(I)}removeByIndex(A){const I=this.layers_[A];I&&I.onDetached(this.context_),this.layers_=this.layers_.filter((g,B)=>B!==A),this.notifyLayersChanged()}removeAll(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[],this.notifyLayersChanged()}get layers(){return this.layers_}notifyLayersChanged(){for(const A of this.callbacks_)A()}addLayersChangeCallback(A){return this.callbacks_.push(A),()=>{this.removeLayersChangeCallback(A)}}removeLayersChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove not found: ${A}`);this.callbacks_.splice(I,1)}}const XQ=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function KD(Q){return XQ.includes(Q)}class MD{propagationStopped_=!1;type;event;worldPos;clipPos;constructor(A,I){this.type=A,this.event=I}get propagationStopped(){return this.propagationStopped_}stopPropagation(){this.propagationStopped_=!0}}class HD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){AA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,XQ.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){AA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,XQ.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!KD(A.type)){AA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new MD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class VE{id;element;camera;layerManager;events;cameraControls;constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.layerManager=A.layerManager,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new HD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=WA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layerManager.layers)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.layerManager.add(I)}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),G=Math.floor(I.width),F=Math.floor(I.height);return new gI(WA(D,s),WA(D+G,s+F))}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return SA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new gI(WA(g,B),WA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){AA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function jQ(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function dD(Q){for(let A=0;A<Q.length;A++)jQ(Q[A],Q.slice(0,A))}function zQ(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??zC("viewport"),layerManager:new PE(I)}});return dD(g),g.map(B=>new VE(B))}class qD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){AA.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){AA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){AA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){AA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class _Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await rD(A.canvas):new UQ(A.canvas);return new _Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new UQ(this.canvas),this.chunkManager_=new JD,this.context_={chunkManager:this.chunkManager_},this.viewports_=zQ(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=YD());const g=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&g.push(B.element);this.sizeObserver_=new qD(g,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=zQ([A],this.canvas,this.context_);return jQ(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),AA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(AA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),AA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(AA.info("Idetik","Idetik runtime starting"),this.running)AA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(AA.info("Idetik","Idetik runtime stopping"),!this.running)AA.warn("Idetik","Idetik runtime not started");else{this.sizeObserver_.disconnect();for(const A of this.viewports_)A.events.disconnect();cancelAnimationFrame(this.lastAnimationId_),this.lastAnimationId_=void 0}}}class lD extends Ug{constructor(A){if(super(),A.primitive!="triangles"){AA.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){AA.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],B=(E,i)=>{const o=Math.min(E,i),a=Math.max(E,i);I.has({i0:o,i1:a})||(I.add({i0:o,i1:a}),g.push(o,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],a=C[E+2];B(i,o),B(o,a),B(a,i)}this.indexData_=new Uint32Array(g)}}const fD=SA(0,1,0);class pD{dirty_=!0;matrix_=CI();rotation_=SQ();translation_=dA();scale_=SA(1,1,1);addRotation(A){Oo(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){Xo(this.rotation_,A),this.dirty_=!0}get rotation(){return vo(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){wQ(this.translation_,A),this.dirty_=!0}get translation(){return dI(this.translation_)}addScale(A){mo(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){wQ(this.scale_,A),this.dirty_=!0}targetTo(A){rQ(this.translation_,A)&&(A=dI(A),A[2]+=JA);const I=lo(CI(),this.translation_,A,fD),g=ko(_C(),I);gE(this.rotation_,g),RQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return dI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return HB(CI(),this.matrix)}computeMatrix(){Yo(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Mg extends tQ{wireframeEnabled=!1;wireframeColor=eA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new pD;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const g=this.textures_[A];g!==void 0&&this.staleTextures_.push(g),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new lD(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class og{normal;signedDistance;constructor(A=SA(0,1,0),I=0){this.normal=dI(A),this.signedDistance=I}set(A,I){this.normal=dI(A),this.signedDistance=I}signedDistanceToPoint(A){return IE(this.normal,A)+this.signedDistance}normalize(){const A=GQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class OE{planes_;constructor(A){this.planes_=[new og(dA(),0),new og(dA(),0),new og(dA(),0),new og(dA(),0),new og(dA(),0),new og(dA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=dA();this.planes_[0].set(Qg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(Qg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(Qg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(Qg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(Qg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(Qg(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const g of this.planes_)g.normalize()}intersectsWithBox3(A){const I=dA();for(const g of this.planes_){const B=g.normal;if(I[0]=B[0]>0?A.max[0]:A.min[0],I[1]=B[1]>0?A.max[1]:A.min[1],I[2]=B[2]>0?A.max[2]:A.min[2],g.signedDistanceToPoint(I)<0)return!1}return!0}}class vE extends Mg{projectionMatrix_=CI();near_=0;far_=0;update(){this.updateProjectionMatrix()}get projectionMatrix(){return this.projectionMatrix_}get viewMatrix(){return this.transform.inverse}get right(){const A=this.transform.matrix;return SA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return SA(A[4],A[5],A[6])}get frustum(){return new OE(xI(CI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=dB(A[0],A[1],A[2],1),g=HB(CI(),this.projectionMatrix_),B=QB(cg(),I,g);Zo(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return SA(C[0],C[1],C[2])}}const XE=1.77,jE=128,zE=128/XE;class mD extends vE{width_=jE;height_=zE;viewportAspectRatio_=XE;viewportSize_=[jE,zE];constructor(A,I,g,B,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,B,g),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,g,B){this.width_=Math.abs(I-A),this.height_=Math.abs(B-g),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(g+B);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=dB(-1,-1,0,1),I=dB(1,1,0,1);const g=xI(CI(),this.projectionMatrix,this.viewMatrix),B=HB(CI(),g);return A=QB(cg(),A,B),I=QB(cg(),I,B),new gI(WA(A[0],A[1]),WA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,g=A/I;let B=.5*A,C=.5*I;this.viewportAspectRatio_>g?B*=this.viewportAspectRatio_/g:C*=g/this.viewportAspectRatio_,this.viewportSize_=[2*B,2*C],qo(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const uD=60,xD=1.77,VB=.1,$Q=180-VB;class WD extends vE{fov_;aspectRatio_;constructor(A={}){const{fov:I=uD,aspectRatio:g=xD,near:B=.1,far:C=1e4,position:E=SA(0,0,0)}=A;if(I<VB||I>$Q)throw new Error(`Invalid field of view: ${I}, must be in [${VB}, ${$Q}] degrees`);super(),this.fov_=I,this.aspectRatio_=g,this.near_=B,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(VB,Math.min($Q,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){Mo(this.projectionMatrix_,Uo(this.fov),this.aspectRatio_,this.near_,this.far_)}}const _E=0;class TD{camera_;dragActive_=!1;dragStart_=dA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const g=dI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=nQ(dA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==_E||(this.dragStart_=dI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=nQ(dA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==_E||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class AC{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}toVec3(){const A=Math.cos(this.theta);return SA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const IC=-1,$E=0,bD=1,Ai=.009,ZD=.001,PD=9e-4,VD=.5,OD=60;class vD{camera_;orbitVelocity_=new AC(0,0,0);panVelocity_=dA();currPos_;currCenter_=dA();dampingFactor_;currMouseButton_=IC;constructor(A,I){this.camera_=A,this.currPos_=new AC(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&wQ(this.currCenter_,I.target),this.dampingFactor_=ZI(I?.dampingFactor??VD,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&rQ(this.panVelocity_,SA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,gB(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-JA;this.currPos_.theta=ZI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*OD);this.orbitVelocity_.phi*=g,this.orbitVelocity_.theta*=g,this.orbitVelocity_.radius*=g,BB(this.panVelocity_,this.panVelocity_,g),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==IC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===$E&&!I.shiftKey,E=this.currMouseButton_===$E&&I.shiftKey||this.currMouseButton_===bD;C&&this.orbit(g,B),E&&this.pan(g,B)}onWheel(A){const I=A.event;I.preventDefault();const g=I.deltaY??0;this.zoom(g)}onPointerEnd(A){this.currMouseButton_=IC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*Ai,this.orbitVelocity_.theta+=I*Ai}pan(A,I){const g=this.currPos_.radius*ZD,B=dA();$C(B,B,this.camera_.right,A),$C(B,B,this.camera_.up,I),BB(B,B,g),nQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*PD}updateCamera(){const A=gB(dA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<JA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<JA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<JA&&(this.orbitVelocity_.radius=0),GQ(this.panVelocity_)<JA&&xo(this.panVelocity_)}}class hB{objects_=[];state_="initialized";callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){(A<0||A>1)&&AA.warn("Layer",`Layer opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=ZI(A,0,1),this.blendMode=I}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&AA.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=ZI(A,0,1)}onEvent(A){}async onAttached(A){}onDetached(A){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}getUniforms(){return{}}}class XD extends Ug{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*10),g=A.length>=3&&rQ(A[0],A[A.length-1]);let B=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[B++]=i[0],I[B++]=i[1],I[B++]=i[2];const o=C===0?g?A[A.length-2]:A[C]:A[C-1];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const a=C===A.length-1?g?A[1]:A[C]:A[C+1];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let g=0;for(let B=0;B<2*A;B+=2)I[g++]=B+0,I[g++]=B+1,I[g++]=B+2,I[g++]=B+2,I[g++]=B+1,I[g++]=B+3;return I}}class jD extends Mg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=eA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=eA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width}}}class zD extends hB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(gC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(gC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(gC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function gC(Q){const{end:A,width:I,color:g}=Q,B=new XD([[0,0,0],A]);return new jD({geometry:B,color:g,width:I})}const Ii=32;function yB(Q,{visible:A,color:I,contrastLimits:g}){return A===void 0&&(A=!0),I===void 0?I=eA.WHITE:I=eA.from(I),Q!==null?g=_D(g,Q):g===void 0&&(AA.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g}}function BC(Q,A){if(A.length>Ii)throw new Error(`Maximum number of channels is ${Ii}`);return A.map(I=>yB(Q,I))}function gi(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function _D(Q,A){if(Q===void 0)return ta(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Bi extends Ug{constructor(A,I,g,B){super();const C=[],E=[],i=g,o=B,a=i+1,D=o+1,s=A/i,G=I/o;for(let F=0;F<D;++F){const J=F*G;for(let m=0;m<a;++m){const d=m*s,T=m/i,z=F/o,u=[d,J,0],f=[0,0,1],Z=[T,z];C.push(...u,...f,...Z)}}for(let F=0;F<o;++F)for(let J=0;J<i;++J){const m=J+a*F,d=J+a*(F+1),T=J+1+a*(F+1),z=J+1+a*F;E.push(m,d,z),E.push(d,T,z)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class $D extends Mg{channels_;constructor(A,I,g,B=[]){super(),this.geometry=new Bi(A,I,1,1),this.setTexture(0,g),this.channels_=BC(g,B),this.programName=As(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=BC(this.textures[0],A)}setChannelProperty(A,I,g){const B=yB(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=B}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g}=this.channels_[0]??yB(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-g[0],ValueScale:1/(g[1]-g[0])}}}function As(Q){switch(Q.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}class Hg extends kQ{data_;width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==g){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new Hg(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}function Qi(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return WA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=WA(C.clientX,C.clientY);if(jo(A,E)<B){if(!g)return null;const o=Q.worldPos;if(o){const a=I(o);a!==null&&g({world:o,value:a})}return null}return A}case"pointercancel":return null;default:return A}}class QC{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&AA.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),AA.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class CC extends hB{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new QC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new eA(.6,.3,.3),new eA(.3,.6,.4),new eA(.4,.4,.7),new eA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,channelProps:B,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=C}async onAttached(A){if(this.chunkStoreView_)throw new Error("ImageLayer cannot be attached to multiple contexts simultaneously.");this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_);const I=this.chunkStoreView_.channelCount;if(gi(this.channelProps_,I),I>1&&this.sliceCoords_.c!==void 0&&this.sliceCoords_.c.length>1)throw new Error(`ImageLayer requires exactly one channel in sliceCoords.c for multi-channel sources (found ${I} channels). Use one layer per channel.`)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getImageForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>CC.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,g]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const B=this.slicePlane(I,A);B&&g.textures[0].updateWithChunk(I,B)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=Qi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get chunkStoreView(){return this.chunkStoreView_}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,PB))}slicePlane(A,I){if(!A.data)return;const g=(I-A.offset.z)/A.scale.z,B=Math.round(g),C=ZI(B,0,A.shape.z-1);ZB(g,C,1+1e-6)||AA.error("ImageLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(OB(A));return g?(g.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(g,A),g.setChannelProps(this.getChannelPropsForChunk(A)),g):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new $D(A.shape.x,A.shape.y,Hg.createWithChunk(A,this.getDataForImage(A)),this.getChannelPropsForChunk(A));return this.updateImageChunk(I,A),I}getDataForImage(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){AA.warn("ImageLayer","No data for image");return}return I}updateImageChunk(A,I){this.debugMode_?(A.wireframeEnabled=!0,A.wireframeColor=this.wireframeColors_[I.lod%this.wireframeColors_.length]):A.wireframeEnabled=!1,A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[g,B]of this.visibleChunks_){if(g.lod!==I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}for(const[g,B]of this.visibleChunks_){if(g.lod===I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}return null}getValueFromChunk(A,I,g){if(!A.data)return null;const B=eQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,o=E*A.shape.x+C;return i[o]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(OB(I),g),this.visibleChunks_.delete(I))}}}function OB(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}`,`align${Q.rowAlignmentBytes}`].join(":")}class Is extends Ug{constructor(A,I,g,B,C,E){super();const i=[],o=[],a=Math.floor(B),D=Math.floor(C),s=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,s,D,1,i,o),this.buildFace("z","y","x",1,-1,g,I,A,s,D,-1,i,o),this.buildFace("x","z","y",1,1,A,g,I,a,s,1,i,o),this.buildFace("x","z","y",1,-1,A,g,I,a,s,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,g,a,D,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,g,a,D,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,g,B,C,E,i,o,a,D,s,G,F){const J=E/a,m=i/D,d=E/2,T=i/2,z=o/2*s,u=a+1,f=D+1,Z=G.length/8;for(let V=0;V<f;V++){const CA=-T+V*m;for(let sA=0;sA<u;sA++){const DA=-d+sA*J,hA={x:0,y:0,z:0};hA[A]=DA*B,hA[I]=CA*C,hA[g]=z;const yA={x:0,y:0,z:0};yA[g]=s;const uA=sA/a,fA=1-V/D;G.push(hA.x,hA.y,hA.z,yA.x,yA.y,yA.z,uA,fA)}}for(let V=0;V<D;V++)for(let CA=0;CA<a;CA++){const sA=Z+CA+u*V,DA=Z+CA+u*(V+1),hA=Z+(CA+1)+u*(V+1),yA=Z+(CA+1)+u*V;F.push(sA,DA,yA,DA,hA,yA)}}}class dg extends kQ{data_;width_;height_;depth_;constructor(A,I,g,B){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=kg(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const g=new dg(I,A.shape.x,A.shape.y,A.shape.z);return g.unpackAlignment=A.rowAlignmentBytes,g}}class gs extends Mg{voxelScale=SA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new Is(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=dg.createWithChunk(I),B=this.textures.length;this.setTexture(B,g),this.channelToTextureIndex_.set(A,B);const C=Bs(g.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${g.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const g=this.textures[A];if(!(g instanceof dg)){const B=dg.createWithChunk(I);this.setTexture(A,B);return}g.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],B=[1,1,1,1],C=[],E=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let i=0;i<E&&C.length<4;i++){const o=this.channelToTextureIndex_.get(i);if(o===void 0||!this.loadedChannels_.has(i))continue;const a=this.textures[o],D=yB(a,this.channels_[i]||{});if(!D.visible)continue;const s=C.length;I[s*3]=D.color.rgb[0],I[s*3+1]=D.color.rgb[1],I[s*3+2]=D.color.rgb[2],C.push(o),g[s]=-D.contrastLimits[0],B[s]=1/(D.contrastLimits[1]-D.contrastLimits[0]),A[s]=1}return C.reduce((i,o,a)=>(i[`Channel${a}Sampler`]=o,i),{Visible:A,"Color[0]":I,ValueOffset:g,ValueScale:B,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=BC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=yB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Bs(Q){switch(Q){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function Qs(Q,A){const I=A.position,g=dA(),B=dA();return Q.sort((C,E)=>{gB(g,C.boundingBox.max,C.boundingBox.min),BB(g,g,.5),gB(B,E.boundingBox.max,E.boundingBox.min),BB(B,B,.5);const i=AE(I,g),o=AE(I,B);return i-o}),Q}const Cs=2;class Es extends hB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new QC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,PB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:g,channelProps:B}){super({blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=g,this.initialChannelProps_=B,this.channelProps_=B,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const B=as(I[0]),C=this.pool_.acquire(B)??new gs;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,B);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}async onAttached(A){this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.sourcePolicy_),gi(this.channelProps_,this.chunkStoreView_.channelCount)}onDetached(A){if(this.chunkStoreView_){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0}}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=os(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i),this.addObject(i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length,this.state!=="ready"&&this.setState("ready")}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),Qg(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveVolume(A){A.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!this.chunkStoreView_)return;if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.viewport);const I=A.viewport.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?Cs:1,this.updateChunks(),Qs(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function is(Q){const{x:A,y:I,z:g,t:B}=Q.chunkIndex;return`${A}:${I}:${g}:${B}`}function os(Q){const A=new Map;for(const I of Q){const g=is(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function as(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}const Ds=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function ss(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!Ds.has(Q.dataType))throw new Error(`Image data type must be unsigned, instead found: ${Q.dataType}`);return Q}class hs extends Mg{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new Bi(A.width,A.height,1,1),this.setTexture(0,ss(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const g=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,g),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(B=>B.rgba).map(B=>Math.round(B*255))),g=new Hg(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,eA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,eA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),B=A.size,C=new Uint32Array(B*2);return C.set(I,0),C.set(g,B),new Hg(C,B,2)}}const ys=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function ts(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,eA.from(I)]))}function Gs(Q){return Q=Q??ys,Q.map(eA.from)}class Ci{lookupTable;cycle;constructor(A={}){this.lookupTable=ts(A.lookupTable),this.cycle=Gs(A.cycle)}}class EC extends hB{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new QC;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,colorMap:B={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.colorMap_=new Ci(B),this.onPickValue_=C,this.outlineSelected_=E}async onAttached(A){if(this.chunkStoreView_)throw new Error("LabelLayer cannot be attached to multiple contexts simultaneously.");if(this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}update(A){!A||!this.chunkStoreView_||(this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getLabelForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>EC.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,g]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const B=this.slicePlane(I,A);B&&g.textures[0].updateWithChunk(I,B)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=Qi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new Ci(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,PB))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[g,B]of this.visibleChunks_){if(g.lod!==I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}for(const[g,B]of this.visibleChunks_){if(g.lod===I)continue;const C=this.getValueFromChunk(g,B,A);if(C!==null)return C}return null}getValueFromChunk(A,I,g){if(!A.data)return null;const B=eQ(dA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C>=0&&C<A.shape.x&&E>=0&&E<A.shape.y){const i=this.sliceCoords_.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data,o=E*A.shape.x+C;return i[o]}return null}slicePlane(A,I){if(!A.data)return;const g=(I-A.offset.z)/A.scale.z,B=Math.round(g),C=ZI(B,0,A.shape.z-1);ZB(g,C,1+1e-6)||AA.error("LabelLayer","slicePlane zValue outside extent");const E=A.shape.x*A.shape.y,i=E*C;return A.data.slice(i,i+E)}getLabelForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(OB(A));return g?(g.textures[0].updateWithChunk(A,this.getDataForLabel(A)),this.updateLabelChunk(g,A),g.setColorMap(this.colorMap_),g.setSelectedValue(this.selectedValue_),g):this.createLabel(A)}createLabel(A){const I=new hs({width:A.shape.x,height:A.shape.y,imageData:Hg.createWithChunk(A,this.getDataForLabel(A)),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return this.updateLabelChunk(I,A),I}getDataForLabel(A){const I=this.sliceCoords_?.z!==void 0?this.slicePlane(A,this.sliceCoords_.z):A.data;if(!I){AA.warn("LabelLayer","No data for label");return}return I}updateLabelChunk(A,I){A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(OB(I),g),this.visibleChunks_.delete(I))}}}function ws(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function Ei(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function ii(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class tB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,ws(this.#I,I))}async get(A,I={}){let g=Ei(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return ii(C)}async getRange(A,I,g={}){let B=Ei(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return ii(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class GB extends Error{}class qg extends GB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class XA extends GB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class Fs extends GB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class es extends GB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class iC extends GB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function ag(Q){return()=>{throw new iC(`${Q} encode`)}}class oC{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new XA("keepbits must be zero or positive")}static fromConfig(A,I){return new oC(A,I)}encode=ag("bitround");decode(A){return A}}function aC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class oi{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):aC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class DC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(aC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class wB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(aC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new wB(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function rs(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function ns(Q,A){return new SharedArrayBuffer(Q)}function FB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new XA("Failed to decode JSON",{cause:I})}}function ai(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function lg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?wB:DC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:oi}[Q];if(!I)throw new XA(`Unknown or unsupported dataType: ${Q}`);return I}function Dg(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function Ss({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new XA(`Unknown chunk key encoding: ${Q}`)}function Di(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new XA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new XA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function Ns(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function Rs(Q,A={}){let I=[],g=Di(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!Ns(C))throw new XA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=Di(o).dataType;if(!sC(a,"number")&&!sC(a,"bigint"))throw new XA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function cs(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function sC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function Us(Q){return Q?.name==="sharding_indexed"}function si(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function hi(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function yi(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const ti=ks();function ks(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function Gi(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class vB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=lg(I.dataType),this.#B=I.shape,this.#A=Dg(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new vB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return ti&&this.#Q==="big"&&ai(I,Gi(this.#I)),I}decode(A){return ti&&this.#Q==="big"&&ai(A,Gi(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const wi={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},Fi={float16:2,float32:4,float64:8};function XB(Q){return Q in Fi}function hC(Q){return Q==="int64"||Q==="uint64"}function Ls(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new iC("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function jB(Q,A){if(hC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new XA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!XB(Q)&&!Number.isInteger(A))throw new XA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!XB(Q))throw new XA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in wi?wi[A]:Ls(A,Fi[Q])}const ei=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),yC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},tC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function ri(Q,A,I){return Q.map(([g,B])=>({src:jB(A,g),tgt:jB(I,B)}))}function Js(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Ys(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function Ks(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function ni(Q){switch(Q){case"nearest-even":return Ys;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return Ks}}function GC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function wC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class FC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=lg(A),this.#g=Si(I,A,g,B,C),this.#B=Si(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!ei.has(g))throw new XA(`cast_value codec does not support array data type: ${g}`);if(!ei.has(B))throw new XA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?ri(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?ri(A.scalar_map.encode,g,B):[];return new FC(g,B,C,A.out_of_range,E,i)}encode=ag("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function Si(Q,A,I,g,B){const C=XB(Q),E=hC(Q),i=XB(A),o=hC(A);let a;if(C&&i){if(I!=="nearest-even")throw new XA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=ni(I),G=GC(...yC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return G(s(F))}}else if(C&&o){const s=ni(I),G=wC(...tC[A],g);a=F=>{if(!Number.isFinite(F))throw new Error(`Cannot cast ${F} to integer type without scalar_map`);return G(BigInt(s(F)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=GC(...yC[A],g);else if(!C&&!E&&o){const s=wC(...tC[A],g);a=G=>s(BigInt(G))}else if(E&&!i&&!o){const s=GC(...yC[A],g);a=G=>s(Number(G))}else if(E&&o)a=wC(...tC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const G=Js(s,B);return G!==void 0?G:a(s)}}class eC{kind="bytes_to_bytes";static fromConfig(){return new eC}encode=ag("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}const Ms=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function Ni(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class rC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!Ms.has(I.dataType))throw new XA(`Delta codec does not support data type: ${I.dataType}`);return new rC(lg(I.dataType))}encode(A){Ni(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){Ni(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class nC{kind="bytes_to_bytes";static fromConfig(A){return new nC}encode=ag("gzip");async decode(A){const I=await yi(A,{format:"gzip"});return new Uint8Array(I)}}function Hs(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function ds(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class SC{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new SC(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(Hs),i&&o.push(ds);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(G,F)=>{let J=F;for(let m of o)J=m(G,J);return J});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,G=>{const F=`0000${G.charCodeAt(0).toString(16)}`;return`\\u${F.substring(F.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=FB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=Dg(B,"C");return{data:g,shape:B,stride:C}}}const qs=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class NC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!qs.has(I.dataType))throw new XA(`scale_offset codec does not support data type: ${I.dataType}`);return new NC(jB(I.dataType,A.scale??1),jB(I.dataType,A.offset??0),lg(I.dataType))}encode=ag("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class RC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(lg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new RC(A,I)}encode(A){return ls(A,this.#A)}decode(A){return fs(A,this.#A)}}function ls(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function fs(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function Ri(Q){return Q instanceof oi||Q instanceof DC||Q instanceof wB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function ps(Q,A){let I;return Q.data instanceof DC||Q.data instanceof wB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:Dg(Q.shape,A)}}function ms(Q,A){let I=ps(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=Ri(Q.data),i=Ri(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function us(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function xs(Q,A){let I=us(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class cC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new cC(A,I)}encode(A){return xs(A,this.#I)?A:ms(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:Dg(A.shape,this.#A)}}}class zB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=Dg(A,"C")}static fromConfig(A,I){return new zB(I.shape)}encode=ag("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class UC{kind="bytes_to_bytes";static fromConfig(A){return new UC}encode=ag("zlib");async decode(A){const I=await yi(A,{format:"deflate"});return new Uint8Array(I)}}function Ws(){let Q=()=>Promise.resolve().then(()=>ny).then(C=>C.default),A=()=>Promise.resolve().then(()=>ky).then(C=>C.default),I=()=>Promise.resolve().then(()=>Hy).then(C=>C.default),g=()=>nC,B=()=>UC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>cC).set("bytes",()=>vB).set("crc32c",()=>eC).set("vlen-utf8",()=>zB).set("json2",()=>SC).set("bitround",()=>oC).set("cast_value",()=>FC).set("scale_offset",()=>NC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>zB).set("numcodecs.shuffle",()=>RC).set("numcodecs.delta",()=>rC)}const Ts=Ws();function kC(Q){let A;function I(){return A||(A=bs(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new es({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E}}}async function bs(Q){let A=Q.codecs.map(async E=>{let i=await Ts.get(E.name)?.();if(!i)throw new Fs(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Zs(C))throw new XA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:vB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Zs(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ci=18446744073709551615n;function Ps(Q,A,I,g){if(!Q.store.getRange)throw new iC("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((D,s)=>D/g.chunk_shape[s]),E=kC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=4,o=16*C.reduce((D,s)=>D*s,1),a={};return async(D,s)=>{let G=D.map((Z,V)=>Math.floor(Z/C[V])),F=Q.resolve(I(G)).path;F in a||(a[F]=(async()=>{let Z=await B(F,{suffixLength:o+i},s);return Z?await E.decode(Z):null})().catch(Z=>{throw delete a[F],Z}));let J=await a[F];if(J===null)return;let{data:m,shape:d,stride:T}=J,z=D.map((Z,V)=>Z%d[V]).reduce((Z,V,CA)=>Z+V*T[CA],0),u=m[z],f=m[z+1];if(!(u===ci&&f===ci))return B(F,{offset:Number(u),length:Number(f)},s)}}class eI{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new eI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class LC extends eI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Ui(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const _B=Symbol("zarrita.context");function Vs(Q,A){let{configuration:I}=A.codecs.find(Us)??{},g={encodeChunkKey:Ss(A.chunk_key_encoding),TypedArray:lg(A.data_type),fillValue:A.fill_value};if(I){let C=Ui(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:kC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return Dg(E,C)},getChunkBytes:Ps(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Ui(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:kC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return Dg(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let $B=class extends eI{kind="array";#A;[_B];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:si(g)},this[_B]=Vs(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[_B].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&rs();let B=this[_B],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=ns(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return sC(this.dtype,A)}};function Os(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function vs(Q,...A){return Os(Q,A)}async function ki(Q){let A=Q.store.arrayExtensions;return A?.length?await vs(Q,...A):Q}let AQ=Xs();function Xs(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function js(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?FB(I):{}}async function zs(Q,A={}){let I="store"in Q?Q:new eI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await js(I,g)),g?.throwIfAborted(),A.kind==="array"?Li(I,B,g):A.kind==="group"?Ji(I,B,g):Li(I,B,g).catch(C=>(hi(C,qg,XA),Ji(I,B,g)))}async function Li(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new qg("v2 array",{path:g});return AQ.increment(Q.store,"v2"),ki(new $B(Q.store,Q.path,Rs(FB(B),A)))}async function Ji(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new qg("v2 group",{path:g});return AQ.increment(Q.store,"v2"),new LC(Q.store,Q.path,cs(FB(B),A))}async function _s(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new qg("v3 array or group",{path:g});let C=FB(B);return C.node_type==="array"&&(C.fill_value=si(C)),C.node_type==="array"?ki(new $B(I,Q.path,C)):new LC(I,Q.path,C)}async function $s(Q,A={}){let I="store"in Q?Q:new eI(Q),g=await _s(I,A.signal);if(AQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof $B||A.kind==="group"&&g instanceof LC)return g;let B=g instanceof $B?"array":"group";throw new qg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=AQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(hi(E,qg,XA),C(Q,A)))}rI.v2=zs,rI.v3=$s;async function Ah(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class JC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Ah(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function eB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function Ih(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function gh(Q){let A;switch(Q.type){case"fetch":{const g=new tB(Q.url);A=new eI(g);break}case"filesystem":{A=new eI(new JC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return Ih(I,Q.zarrVersion)}function Bh(Q,A,I){if(Q.store instanceof tB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof JC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function Qh(Q,A,I,g){return Ch(Q,A,I,g)}function Ch(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let Z=A.length-1;Z>=0;Z--){if(I[Z]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[Z]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,G=E.c!==void 0?I[E.c]:0,F=E.t!==void 0?I[E.t]:0,J=D*F+a*G,m=o.x===B.x&&o.y===B.y&&o.z===B.z;if(J===0&&Q.length===s&&m)return Q;const T=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,u=I[E.y];let f=0;for(let Z=0;Z<B.z;Z++){const V=J+Z*z;for(let CA=0;CA<B.y;CA++){const sA=V+CA*u,DA=sA+B.x;T.set(Q.subarray(sA,DA),f),f+=B.x}}return T}const Yi=`function Zg(B, A) {
|
|
545
545
|
return {
|
|
546
546
|
...B,
|
|
547
547
|
...A,
|