@idetik/core 0.20.0 → 0.20.1
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
|
@@ -457,7 +457,7 @@ void main() {
|
|
|
457
457
|
fragColor = vec4(color.rgb, alpha);
|
|
458
458
|
}`;const bC={projectedLine:{vertex:lC,fragment:pC},points:{vertex:WC,fragment:mC},wireframe:{vertex:TC,fragment:xC},floatScalarImage:{vertex:tI,fragment:IB},floatScalarImageArray:{vertex:tI,fragment:gB},intScalarImage:{vertex:tI,fragment:IB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:tI,fragment:gB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:tI,fragment:IB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:tI,fragment:gB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:tI,fragment:ZC},floatVolume:{vertex:BB,fragment:QB},intVolume:{vertex:BB,fragment:QB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:BB,fragment:QB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},EQ={debug:10,info:20,warn:30,error:40},uC={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function PC(){const g=typeof process<"u"&&typeof process.env?.NODE_ENV=="string"?process.env.NODE_ENV:void 0;if(g==="production"||g==="development"||g==="test")return g;if(typeof window<"u"){const{NODE_ENV:A}=window;if(A==="production"||A==="development"||A==="test")return A}return"development"}class P{static logLevel_=PC()==="production"?"warn":"debug";static setLogLevel(A){P.logLevel_=A}static debug(A,I,...B){P.log("debug",A,I,...B)}static info(A,I,...B){P.log("info",A,I,...B)}static warn(A,I,...B){P.log("warn",A,I,...B)}static error(A,I,...B){P.log("error",A,I,...B)}static log(A,I,B,...Q){if(EQ[A]<EQ[P.logLevel_])return;const C=new Date().toISOString(),E=uC[A],i=`[${C}][${A.toUpperCase()}][${I}]`,s=[`${E}${i}`,B,...Q];switch(A){case"debug":console.debug(...s);break;case"info":console.info(...s);break;case"warn":console.warn(...s);break;case"error":console.error(...s);break}}}class VC{gl_;program_;uniformInfo_=new Map;constructor(A,I,B){this.gl_=A;const Q=A.createProgram();if(!Q)throw new Error("Failed to create WebGL shader program");this.program_=Q;const C=[];try{C.push(this.addShader(I,A.VERTEX_SHADER)),C.push(this.addShader(B,A.FRAGMENT_SHADER)),this.link(),this.preprocessUniformLocations()}catch(E){throw A.deleteProgram(Q),E}finally{C.forEach(E=>this.gl_.deleteShader(E))}}setUniform(A,I){const[B,Q]=this.uniformInfo_.get(A)??[];if(!B||!Q)throw new Error(`Uniform "${A}" not found in shader program`);const C=Q.type;switch(C){case this.gl_.BOOL:case this.gl_.FLOAT:typeof I=="number"?this.gl_.uniform1f(B,I):this.gl_.uniform1fv(B,I);break;case this.gl_.INT:typeof I=="number"?this.gl_.uniform1i(B,I):this.gl_.uniform1iv(B,I);break;case this.gl_.FLOAT_VEC2:this.gl_.uniform2fv(B,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(B,I);break;case this.gl_.FLOAT_VEC4:this.gl_.uniform4fv(B,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(B,!1,I);break;case this.gl_.UNSIGNED_INT:this.gl_.uniform1ui(B,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(B,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 B=this.gl_.getActiveUniform(this.program_,I);if(B){if(!XC.has(B.type))throw new Error(`Unsupported uniform type "${B.type}" (GLenum) found in shader program for uniform "${B.name}"`);const Q=this.gl_.getUniformLocation(this.program_,B.name);Q&&(this.uniformInfo_.set(B.name,[Q,B]),P.debug("WebGLShaderProgram","Uniform found:",B.name,B.type,B.size))}}}addShader(A,I){const B=this.gl_.createShader(I);if(!B)throw new Error(`Failed to create a new shader of type ${I}`);if(this.gl_.shaderSource(B,A),this.gl_.compileShader(B),!this.gl_.getShaderParameter(B,this.gl_.COMPILE_STATUS)){const Q=this.gl_.getShaderInfoLog(B);throw this.gl_.deleteShader(B),new Error(`Error compiling shader: ${Q}`)}return this.gl_.attachShader(this.program_,B),B}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 OC=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]:[],XC=new Set(OC),CB="#pragma inject_defines";class vC{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=bC[A],Q=iQ(B.vertex,B.vertexDefines),C=iQ(B.fragment,B.fragmentDefines);I=new VC(this.gl_,Q,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 iQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(CB))throw new Error(`Shader source does not contain "${CB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
459
459
|
`),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
|
|
460
|
-
${Q}`;return g.replace(CB,C)}const fg={};function DQ(g){const A=g??"";return fg[A]=(fg[A]??0)+1,g?`${g}-${fg[A]}`:String(fg[A])}class EB{id=DQ()}var FA=1e-6,nA=typeof Float32Array<"u"?Float32Array:Array,jC=Math.PI/180;function zC(g){return g*jC}function oQ(){var g=new nA(9);return nA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function _C(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[4],g[4]=A[5],g[5]=A[6],g[6]=A[8],g[7]=A[9],g[8]=A[10],g}function uA(){var g=new nA(16);return nA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function lg(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],s=A[6],G=A[7],w=A[8],c=A[9],L=A[10],Y=A[11],K=A[12],e=A[13],M=A[14],l=A[15],V=I*i-B*E,W=I*s-Q*E,O=I*G-C*E,m=B*s-Q*i,T=B*G-C*i,CA=Q*G-C*s,iA=w*e-c*K,BA=w*M-L*K,hA=w*l-Y*K,GA=c*M-L*e,eA=c*l-Y*e,kA=L*l-Y*M,aA=V*kA-W*eA+O*GA+m*hA-T*BA+CA*iA;return aA?(aA=1/aA,g[0]=(i*kA-s*eA+G*GA)*aA,g[1]=(Q*eA-B*kA-C*GA)*aA,g[2]=(e*CA-M*T+l*m)*aA,g[3]=(L*T-c*CA-Y*m)*aA,g[4]=(s*hA-E*kA-G*BA)*aA,g[5]=(I*kA-Q*hA+C*BA)*aA,g[6]=(M*O-K*CA-l*W)*aA,g[7]=(w*CA-L*O+Y*W)*aA,g[8]=(E*eA-i*hA+G*iA)*aA,g[9]=(B*hA-I*eA-C*iA)*aA,g[10]=(K*T-e*O+l*V)*aA,g[11]=(c*O-w*T-Y*V)*aA,g[12]=(i*BA-E*GA-s*iA)*aA,g[13]=(I*GA-B*BA+Q*iA)*aA,g[14]=(e*W-K*m-M*V)*aA,g[15]=(w*m-c*W+L*V)*aA,g):null}function sg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],s=A[5],G=A[6],w=A[7],c=A[8],L=A[9],Y=A[10],K=A[11],e=A[12],M=A[13],l=A[14],V=A[15],W=I[0],O=I[1],m=I[2],T=I[3];return g[0]=W*B+O*i+m*c+T*e,g[1]=W*Q+O*s+m*L+T*M,g[2]=W*C+O*G+m*Y+T*l,g[3]=W*E+O*w+m*K+T*V,W=I[4],O=I[5],m=I[6],T=I[7],g[4]=W*B+O*i+m*c+T*e,g[5]=W*Q+O*s+m*L+T*M,g[6]=W*C+O*G+m*Y+T*l,g[7]=W*E+O*w+m*K+T*V,W=I[8],O=I[9],m=I[10],T=I[11],g[8]=W*B+O*i+m*c+T*e,g[9]=W*Q+O*s+m*L+T*M,g[10]=W*C+O*G+m*Y+T*l,g[11]=W*E+O*w+m*K+T*V,W=I[12],O=I[13],m=I[14],T=I[15],g[12]=W*B+O*i+m*c+T*e,g[13]=W*Q+O*s+m*L+T*M,g[14]=W*C+O*G+m*Y+T*l,g[15]=W*E+O*w+m*K+T*V,g}function $C(g,A){return g[0]=A[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=A[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=A[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function AE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],s=Q+Q,G=C+C,w=E+E,c=Q*s,L=Q*G,Y=Q*w,K=C*G,e=C*w,M=E*w,l=i*s,V=i*G,W=i*w,O=B[0],m=B[1],T=B[2];return g[0]=(1-(K+M))*O,g[1]=(L+W)*O,g[2]=(Y-V)*O,g[3]=0,g[4]=(L-W)*m,g[5]=(1-(c+M))*m,g[6]=(e+l)*m,g[7]=0,g[8]=(Y+V)*T,g[9]=(e-l)*T,g[10]=(1-(c+K))*T,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function IE(g,A,I,B,Q){var C=1/Math.tan(A/2);if(g[0]=C/I,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=C,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=-1,g[12]=0,g[13]=0,g[15]=0,Q!=null&&Q!==1/0){var E=1/(B-Q);g[10]=(Q+B)*E,g[14]=2*Q*B*E}else g[10]=-1,g[14]=-2*B;return g}var gE=IE;function BE(g,A,I,B,Q,C,E){var i=1/(A-I),s=1/(B-Q),G=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*s,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*G,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*s,g[14]=(E+C)*G,g[15]=1,g}var QE=BE;function CE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],s=B[1],G=B[2],w=Q-I[0],c=C-I[1],L=E-I[2],Y=w*w+c*c+L*L;Y>0&&(Y=1/Math.sqrt(Y),w*=Y,c*=Y,L*=Y);var K=s*L-G*c,e=G*w-i*L,M=i*c-s*w;return Y=K*K+e*e+M*M,Y>0&&(Y=1/Math.sqrt(Y),K*=Y,e*=Y,M*=Y),g[0]=K,g[1]=e,g[2]=M,g[3]=0,g[4]=c*M-L*e,g[5]=L*K-w*M,g[6]=w*e-c*K,g[7]=0,g[8]=w,g[9]=c,g[10]=L,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function EE(g,A){var I=g[0],B=g[1],Q=g[2],C=g[3],E=g[4],i=g[5],s=g[6],G=g[7],w=g[8],c=g[9],L=g[10],Y=g[11],K=g[12],e=g[13],M=g[14],l=g[15],V=A[0],W=A[1],O=A[2],m=A[3],T=A[4],CA=A[5],iA=A[6],BA=A[7],hA=A[8],GA=A[9],eA=A[10],kA=A[11],aA=A[12],QI=A[13],_A=A[14],CI=A[15];return Math.abs(I-V)<=FA*Math.max(1,Math.abs(I),Math.abs(V))&&Math.abs(B-W)<=FA*Math.max(1,Math.abs(B),Math.abs(W))&&Math.abs(Q-O)<=FA*Math.max(1,Math.abs(Q),Math.abs(O))&&Math.abs(C-m)<=FA*Math.max(1,Math.abs(C),Math.abs(m))&&Math.abs(E-T)<=FA*Math.max(1,Math.abs(E),Math.abs(T))&&Math.abs(i-CA)<=FA*Math.max(1,Math.abs(i),Math.abs(CA))&&Math.abs(s-iA)<=FA*Math.max(1,Math.abs(s),Math.abs(iA))&&Math.abs(G-BA)<=FA*Math.max(1,Math.abs(G),Math.abs(BA))&&Math.abs(w-hA)<=FA*Math.max(1,Math.abs(w),Math.abs(hA))&&Math.abs(c-GA)<=FA*Math.max(1,Math.abs(c),Math.abs(GA))&&Math.abs(L-eA)<=FA*Math.max(1,Math.abs(L),Math.abs(eA))&&Math.abs(Y-kA)<=FA*Math.max(1,Math.abs(Y),Math.abs(kA))&&Math.abs(K-aA)<=FA*Math.max(1,Math.abs(K),Math.abs(aA))&&Math.abs(e-QI)<=FA*Math.max(1,Math.abs(e),Math.abs(QI))&&Math.abs(M-_A)<=FA*Math.max(1,Math.abs(M),Math.abs(_A))&&Math.abs(l-CI)<=FA*Math.max(1,Math.abs(l),Math.abs(CI))}function NA(){var g=new nA(3);return nA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function gI(g){var A=new nA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function iB(g){var A=g[0],I=g[1],B=g[2];return Math.sqrt(A*A+I*I+B*B)}function DA(g,A,I){var B=new nA(3);return B[0]=g,B[1]=A,B[2]=I,B}function DB(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function cI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function yg(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function iE(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function DE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function hg(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function aQ(g,A,I,B){return g[0]=A[0]+I[0]*B,g[1]=A[1]+I[1]*B,g[2]=A[2]+I[2]*B,g}function sQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.sqrt(I*I+B*B+Q*Q)}function yQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return I*I+B*B+Q*Q}function oE(g,A){var I=A[0],B=A[1],Q=A[2],C=I*I+B*B+Q*Q;return C>0&&(C=1/Math.sqrt(C)),g[0]=A[0]*C,g[1]=A[1]*C,g[2]=A[2]*C,g}function hQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function oB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],s=I[2];return g[0]=Q*s-C*i,g[1]=C*E-B*s,g[2]=B*i-Q*E,g}function aB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[3]*B+I[7]*Q+I[11]*C+I[15];return E=E||1,g[0]=(I[0]*B+I[4]*Q+I[8]*C+I[12])/E,g[1]=(I[1]*B+I[5]*Q+I[9]*C+I[13])/E,g[2]=(I[2]*B+I[6]*Q+I[10]*C+I[14])/E,g}function aE(g){return g[0]=0,g[1]=0,g[2]=0,g}function GQ(g,A){var I=g[0],B=g[1],Q=g[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=FA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=FA*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=FA*Math.max(1,Math.abs(Q),Math.abs(i))}var sB=iE,sE=iB;(function(){var g=NA();return function(A,I,B,Q,C,E){var i,s;for(I||(I=3),B||(B=0),Q?s=Math.min(Q*I+B,A.length):s=A.length,i=B;i<s;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2];return A}})();function mI(){var g=new nA(4);return nA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function yE(g){var A=new nA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function pg(g,A,I,B){var Q=new nA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function hE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function GE(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g[3]=A[3]*I,g}function FE(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=I*I+B*B+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),g[0]=I*E,g[1]=B*E,g[2]=Q*E,g[3]=C*E,g}function Gg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3];return g[0]=I[0]*B+I[4]*Q+I[8]*C+I[12]*E,g[1]=I[1]*B+I[5]*Q+I[9]*C+I[13]*E,g[2]=I[2]*B+I[6]*Q+I[10]*C+I[14]*E,g[3]=I[3]*B+I[7]*Q+I[11]*C+I[15]*E,g}(function(){var g=mI();return function(A,I,B,Q,C,E){var i,s;for(I||(I=4),B||(B=0),Q?s=Math.min(Q*I+B,A.length):s=A.length,i=B;i<s;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],g[3]=A[i+3],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2],A[i+3]=g[3];return A}})();function yB(){var g=new nA(4);return nA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function wE(g,A,I){I=I*.5;var B=Math.sin(I);return g[0]=B*A[0],g[1]=B*A[1],g[2]=B*A[2],g[3]=Math.cos(I),g}function SE(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],s=I[1],G=I[2],w=I[3];return g[0]=B*w+E*i+Q*G-C*s,g[1]=Q*w+E*s+C*i-B*G,g[2]=C*w+E*G+B*s-Q*i,g[3]=E*w-B*i-Q*s-C*G,g}function hB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],s=I[0],G=I[1],w=I[2],c=I[3],L,Y,K,e,M;return Y=Q*s+C*G+E*w+i*c,Y<0&&(Y=-Y,s=-s,G=-G,w=-w,c=-c),1-Y>FA?(L=Math.acos(Y),K=Math.sin(L),e=Math.sin((1-B)*L)/K,M=Math.sin(B*L)/K):(e=1-B,M=B),g[0]=e*Q+M*s,g[1]=e*C+M*G,g[2]=e*E+M*w,g[3]=e*i+M*c,g}function FQ(g,A){var I=A[0]+A[4]+A[8],B;if(I>0)B=Math.sqrt(I+1),g[3]=.5*B,B=.5/B,g[0]=(A[5]-A[7])*B,g[1]=(A[6]-A[2])*B,g[2]=(A[1]-A[3])*B;else{var Q=0;A[4]>A[0]&&(Q=1),A[8]>A[Q*3+Q]&&(Q=2);var C=(Q+1)%3,E=(Q+2)%3;B=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),g[Q]=.5*B,B=.5/B,g[3]=(A[C*3+E]-A[E*3+C])*B,g[C]=(A[C*3+Q]+A[Q*3+C])*B,g[E]=(A[E*3+Q]+A[Q*3+E])*B}return g}var RE=yE,NE=hE,GB=FE;(function(){var g=NA(),A=DA(1,0,0),I=DA(0,1,0);return function(B,Q,C){var E=hQ(Q,C);return E<-.999999?(oB(g,A,Q),sE(g)<1e-6&&oB(g,I,Q),oE(g,g),wE(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(oB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,GB(B,B))}})(),(function(){var g=yB(),A=yB();return function(I,B,Q,C,E,i){return hB(g,B,E,i),hB(A,Q,C,i),hB(I,g,A,2*i*(1-i)),I}})(),(function(){var g=oQ();return function(A,I,B,Q){return g[0]=B[0],g[3]=B[1],g[6]=B[2],g[1]=Q[0],g[4]=Q[1],g[7]=Q[2],g[2]=-I[0],g[5]=-I[1],g[8]=-I[2],GB(A,FQ(A,g))}})();function wQ(){var g=new nA(2);return nA!=Float32Array&&(g[0]=0,g[1]=0),g}function SQ(g){var A=new nA(2);return A[0]=g[0],A[1]=g[1],A}function HA(g,A){var I=new nA(2);return I[0]=g,I[1]=A,I}function UE(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.sqrt(I*I+B*B)}function kE(g){var A=g[0],I=g[1];return A*A+I*I}function tE(g,A,I,B){var Q=A[0],C=A[1];return g[0]=Q+B*(I[0]-Q),g[1]=C+B*(I[1]-C),g}function RQ(g,A){return g[0]===A[0]&&g[1]===A[1]}function FB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=FA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=FA*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=wQ();return function(A,I,B,Q,C,E){var i,s;for(I||(I=2),B||(B=0),Q?s=Math.min(Q*I+B,A.length):s=A.length,i=B;i<s;i+=I)g[0]=A[i],g[1]=A[i+1],C(g,g,E),A[i]=g[0],A[i+1]=g[1];return A}})();class iI{min;max;constructor(A,I){this.min=A?gI(A):DA(1/0,1/0,1/0),this.max=I?gI(I):DA(-1/0,-1/0,-1/0)}clone(){return new iI(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:B}=this,Q=[DA(I[0],I[1],I[2]),DA(I[0],I[1],B[2]),DA(I[0],B[1],I[2]),DA(I[0],B[1],B[2]),DA(B[0],I[1],I[2]),DA(B[0],I[1],B[2]),DA(B[0],B[1],I[2]),DA(B[0],B[1],B[2])];this.min=DA(1/0,1/0,1/0),this.max=DA(-1/0,-1/0,-1/0);const C=NA();for(const E of Q)aB(C,E,A),this.expandWithPoint(C)}}const cE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class TI extends EB{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],B="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=B,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,B=new iI,Q=NA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class LE{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:B}=A,Q=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(Q,C),this.gl_.bufferData(Q,B,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(w=>{const c=cE[w.type];this.gl_.vertexAttribPointer(c,w.itemSize,this.gl_.FLOAT,!1,i,w.offset),this.gl_.enableVertexAttribArray(c)});const s={vao:I,vbo:C},{indexData:G}=A;if(G.length){const w=this.gl_.ELEMENT_ARRAY_BUFFER,c=this.gl_.createBuffer();if(!c)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(w,c),this.gl_.bufferData(w,G,this.gl_.STATIC_DRAW),s.ebo=c}this.buffers_.set(A,s),this.gl_.bindVertexArray(null)}}class JE{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 B=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);this.textures_.has(A)||this.generateTexture(A,Q,B);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(B,C),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),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 B=this.getDataFormatInfo(A.dataFormat,A.dataType),Q=this.computeStorageBytes(A,B);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-Q),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,B){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(B,Q),this.isTexture2D(A))this.gl_.texStorage2D(B,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(B,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,Q),this.gl_.bindTexture(B,null)}configureTextureParameters(A,I){const B=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);B.pixelStorei(B.UNPACK_ALIGNMENT,A.unpackAlignment),B.texParameteri(I,B.TEXTURE_MIN_FILTER,Q),B.texParameteri(I,B.TEXTURE_MAG_FILTER,C),B.texParameteri(I,B.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),B.texParameteri(I,B.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),B.texParameteri(I,B.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,B){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(B,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(B,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:B,dataType:Q}=I;if(B==="scalar"&&Q!=="float"&&A!=="nearest")return P.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 B=this.bytesPerTexel(I),Q=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),s=0;for(let G=0;G<Q;G++)s+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return s}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 PA{min;max;constructor(A,I){this.min=A?SQ(A):HA(1/0,1/0),this.max=I?SQ(I):HA(-1/0,-1/0)}clone(){return new PA(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 RQ(A.min,I.min)&&RQ(A.max,I.max)}floor(){return new PA(HA(Math.floor(this.min[0]),Math.floor(this.min[1])),HA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],B=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:B,height:Q}}}class YE{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_&&PA.equals(I,this.currentViewport_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(B,Q,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_&&PA.equals(I,this.currentScissor_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(B,Q,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 rE=$C(uA(),[1,-1,1]);class NQ extends fC{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=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,P.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new vC(I),this.bindings_=new LE(I),this.textures_=new JE(I),this.state_=new YE(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0;const{opaque:I,transparent:B}=A.layerManager.partitionLayers();for(const G of[...I,...B])G.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const Q=A.getBoxRelativeTo(this.canvas),C=new PA(HA(0,0),HA(this.width,this.height)),E=PA.equals(Q.floor(),C.floor()),i=PA.intersects(Q,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(Q);else{P.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.clear();const s=A.camera.frustum;this.state_.setDepthMask(!0);for(const G of I)G.state==="ready"&&this.renderLayer(G,A.camera,s);this.state_.setDepthMask(!1);for(const G of B)G.state==="ready"&&this.renderLayer(G,A.camera,s);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,B){if(A.objects.length===0)return;this.state_.setBlendingMode(A.transparent?A.blendMode:"none");const Q=A.hasMultipleLODs();this.state_.setStencilTest(Q),Q&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{B.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];if(Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),!Q.programName)return;this.state_.setCullFaceMode(Q.cullFaceMode),this.state_.setDepthTesting(Q.depthTest),this.state_.setDepthMask(Q.depthTest),this.bindings_.bindGeometry(Q.geometry),Q.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(Q.programName);if(this.drawGeometry(Q.geometry,Q,A,C,B),Q.wireframeEnabled){this.bindings_.bindGeometry(Q.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",Q.wireframeColor.rgb),this.drawGeometry(Q.wireframeGeometry,Q,A,E,B)}}drawGeometry(A,I,B,Q,C){const E=sg(uA(),C.viewMatrix,I.transform.matrix),i=sg(uA(),rE,C.projectionMatrix),s=[this.canvas.width,this.canvas.height],G=I.getUniforms(),c={...B.getUniforms(),...G};for(const K of Q.uniformNames)switch(K){case"ModelView":Q.setUniform(K,E);break;case"Projection":Q.setUniform(K,i);break;case"Resolution":Q.setUniform(K,s);break;case"u_opacity":Q.setUniform(K,B.opacity);break;case"CameraPositionModel":{const e=lg(uA(),E),M=pg(0,0,0,1),l=Gg(mI(),M,e);Q.setUniform(K,DA(l[0],l[1],l[2]));break}default:K in c&&Q.setUniform(K,c[K])}const L=this.glGetPrimitive(A.primitive),Y=A.indexData;Y.length?this.gl_.drawElements(L,Y.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(L,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 B=new PA(HA(0,0),HA(A,I));this.state_.setViewport(B)}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 KE=8;class ME{maxConcurrent_;pending_=[];running_=new Map;constructor(A=KE){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(B=>B.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(Q=>Q.chunk===A);if(I>=0){this.pending_.splice(I,1),P.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),P.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 B=A.chunk.priority??Number.MAX_SAFE_INTEGER,Q=I.chunk.priority??Number.MAX_SAFE_INTEGER;return B===Q?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):B-Q});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:B}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>B(Q.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&P.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const UQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function nE(g){if(UQ.some(I=>g instanceof I))return!0;const A=UQ.map(I=>I.name);return P.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function HE(g){let A=1/0,I=-1/0;for(let B=0;B<g.length;B++){const Q=g[B];Q<A&&(A=Q),Q>I&&(I=Q)}return{min:A,max:I}}function kQ(g){const A={};for(const I of g){if(!I.dataRange)continue;const B=I.chunkIndex.c,Q=A[B];Q?(Q.min=Math.min(Q.min,I.dataRange.min),Q.max=Math.max(Q.max,I.dataRange.max)):A[B]={min:I.dataRange.min,max:I.dataRange.max}}return A}function eE(g,A){return Math.round((A-g.translation)/g.scale)}function Wg(g,A,I=1e-6){return Math.abs(g-A)<=I}function DI(g,A,I){return Math.max(A,Math.min(I,g))}const mg=Symbol("INTERNAL_POLICY_KEY");class qE{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,P.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const B=this.store_.dimensions,Q=B.x.lods[0],C=B.y.lods[0];this.sourceMaxSquareDistance2D_=kE(HA(Q.size*Q.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}getChunksAtTime(A){return this.store_.getChunksAtTime(A)}getTimeIndex(A){return this.store_.getTimeIndex(A)}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I),Q=B.filter(i=>i.lod===this.currentLOD_&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),C=this.fallbackLOD();if(this.currentLOD_===C)return Q;const E=B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded");return[...Q,...E]}updateChunksForImage(A,I){const B=I.camera;if(B.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=B.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,s=I.getBoxRelativeTo(i).toRect().width,G=E/s,w=Math.log2(1/G);this.setLOD(w);const c=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(c)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const Y=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(Y).length===0){P.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const e=wQ();tE(e,C.min,C.max,.5);const[M,l]=this.getZBounds(A),V=new iI(DA(C.min[0],C.min[1],M),DA(C.max[0],C.max[1],l));this.chunkViewStates_.forEach(wB),this.updateChunksAtTimeIndex(Y,A,V,e),A.t!==void 0&&this.markTimeChunksForPrefetchImage(Y,A,V,e),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=c,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){const B=sg(uA(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(B)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const C=this.store_.getTimeIndex(A),E=this.store_.getChunksAtTime(C);if(E.length===0){P.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(wB);const i=this.fallbackLOD();for(const s of E){const G=s.lod===this.currentLOD_,w=s.lod===i;if(!G&&!w||!this.isChunkChannelInSlice(s,A))continue;const c=this.computePriority(w,G,!0,!1,!0);this.chunkViewStates_.set(s,{visible:!0,prefetch:!1,priority:c,orderKey:0})}A.t!==void 0&&this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=B}allVisibleFallbackLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.fallbackLOD(),Q=this.store_.getChunksAtTime(I).filter(C=>C.visible&&C.lod===B);return Q.length>0&&Q.every(C=>C.state==="loaded")}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(wB)}setImageSourcePolicy(A,I){if(I!==mg)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,P.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const B=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(B)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),s=Math.max(0,Math.min(i,this.policy_.lod.min)),G=Math.max(s,Math.min(i,this.policy_.lod.max)),w=DI(E,s,G);w!==this.currentLOD_&&(this.currentLOD_=w)}isChunkChannelInSlice(A,I){return I.c===void 0?!0:I.c.length===0?!1:I.c.includes(A.chunkIndex.c)}updateChunksAtTimeIndex(A,I,B,Q){const C=this.getPaddedBounds(B),E=this.store_.getChunksAtTime(A),i=this.fallbackLOD();for(const s of E){const G=s.lod===this.currentLOD_,w=s.lod===i;if(!G&&!w)continue;const c=this.isChunkChannelInSlice(s,I);if(!c)continue;const L=this.isChunkWithinBounds(s,B),Y=!L&&c&&G&&this.isChunkWithinBounds(s,C),K=L&&c,e=this.computePriority(w,G,L,Y,c);if(e!==null){const M=this.squareDistance2D(s,Q);this.chunkViewStates_.set(s,{visible:K,prefetch:Y,priority:e,orderKey:M})}}}markTimeChunksForPrefetchImage(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),s=this.policy_.priorityMap.prefetchTime;for(let G=A+1;G<=E;++G)for(const w of this.store_.getChunksAtTime(G)){if(w.lod!==i||!this.isChunkChannelInSlice(w,I)||!this.isChunkWithinBounds(w,B))continue;const c=this.squareDistance2D(w,Q),L=DI(c/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),Y=G-A+L;this.chunkViewStates_.set(w,{visible:!1,prefetch:!0,priority:s,orderKey:Y})}}markTimeChunksForPrefetchVolume(A,I){const B=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(B-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime;for(let i=A+1;i<=Q;++i)for(const s of this.store_.getChunksAtTime(i)){if(s.lod!==C||!this.isChunkChannelInSlice(s,I))continue;const G=i-A;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:E,orderKey:G})}}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}isChunkWithinBounds(A,I){const B=new iI(DA(A.offset.x,A.offset.y,A.offset.z),DA(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));return iI.intersects(B,I)}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const w=I.lods[this.currentLOD_];return[w.translation,w.translation+w.size*w.scale]}const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),s=B.chunkSize,G=Math.max(0,Math.min(Math.floor(i/s),Math.ceil(Q/s)-1));return[E+G*s*C,E+(G+1)*s*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!FB(this.lastViewBounds2D_.min,A.min)||!FB(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!EE(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!FB(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,B)=>I===A[B])}getPaddedBounds(A){const I=this.store_.dimensions,B=I.x.lods[this.currentLOD_],Q=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=B.chunkSize*B.scale*this.policy_.prefetch.x,i=Q.chunkSize*Q.scale*this.policy_.prefetch.y;let s=0;return C&&(s=C.chunkSize*C.scale*this.policy_.prefetch.z),new iI(DA(A.min[0]-E,A.min[1]-i,A.min[2]-s),DA(A.max[0]+E,A.max[1]+i,A.max[2]+s))}squareDistance2D(A,I){const B={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},Q=B.x-I[0],C=B.y-I[1];return Q*Q+C*C}}function wB(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class dE{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:B}=this.getAndValidateChannelDimension();this.chunks_=Array.from({length:I},()=>[]);for(let Q=0;Q<I;++Q){const C=this.chunks_[Q];for(let E=0;E<this.dimensions_.numLods;++E){const i=this.dimensions_.x.lods[E],s=this.dimensions_.y.lods[E],G=this.dimensions_.z?.lods[E],w=i.chunkSize,c=s.chunkSize,L=G?.chunkSize??1,Y=Math.ceil(i.size/w),K=Math.ceil(s.size/c),e=Math.ceil((G?.size??1)/L);for(let M=0;M<B;++M)for(let l=0;l<Y;++l){const V=i.translation+l*i.chunkSize*i.scale;for(let W=0;W<K;++W){const O=s.translation+W*s.chunkSize*s.scale;for(let m=0;m<e;++m){const T=G!==void 0?G.translation+m*L*G.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(w,i.size-l*w),y:Math.min(c,s.size-W*c),z:Math.min(L,(G?.size??1)-m*L),c:1},rowAlignmentBytes:1,chunkIndex:{x:l,y:W,z:m,c:M,t:Q},scale:{x:i.scale,y:s.scale,z:G?.scale??1},offset:{x:V,y:O,z:T}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:eE(this.dimensions_.t.lods[0],A.t)}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 qE(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[B,Q]of I.chunkViewStates)A.add(B);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,B=!1,Q=null,C=null;for(const G of this.views_){const w=G.chunkViewStates.get(A);w&&(w.visible&&(I=!0),w.prefetch&&(B=!0),w.priority!==null&&(Q===null||w.priority<Q)&&(Q=w.priority,C=w.orderKey),!w.visible&&!w.prefetch&&w.priority===null&&G.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=B,A.priority=Q,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,P.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let B=1;B<this.dimensions_.numLods;B++){const Q=A.lods[B].scale/A.lods[B-1].scale,C=I.lods[B].scale/I.lods[B-1].scale;if(!Wg(Q,2,.02)||!Wg(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${B-1} → ${B}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[B-1].scale}, ${I.lods[B-1].scale}] → [${A.lods[B].scale}, ${I.lods[B].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const B=this.dimensions_.t?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${B.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&&P.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 B=this.dimensions_.c?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class fE{stores_=new Map;pendingStores_=new Map;queue_=new ME;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 B=this.pendingStores_.get(A);if(B)return B;const C=(async()=>{const i=await A.open();return new dE(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 B=I.updateAndCollectChunkChanges();for(const Q of B)Q.priority===null?this.queue_.cancel(Q):Q.state==="queued"&&this.queue_.enqueue(Q,C=>I.loadChunkData(Q,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var Fg=function(g=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(c){c.preventDefault(),Q(++A%I.children.length)},!1);function B(c){return I.appendChild(c.dom),c}function Q(c){for(var L=0;L<I.children.length;L++)I.children[L].style.display=L===c?"block":"none";A=c}var C=(performance||Date).now(),E=C,i=0,s=B(new Fg.Panel("FPS","#0ff","#002",g)),G=B(new Fg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var w=B(new Fg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var c=(performance||Date).now();if(G.update(c-C,200),c>=E+1e3&&(s.update(i*1e3/(c-E),100),E=c,i=0,w)){var L=performance.memory;w.update(L.usedJSHeapSize/1048576,L.jsHeapSizeLimit/1048576)}return c},update:function(){C=this.end()},domElement:I,setMode:Q}};Fg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),s=E(80*i*B),G=E(48*i*B),w=E(3*i*B),c=E(2*i*B),L=E(3*i*B),Y=E(15*i*B),K=E(74*i*B),e=E(30*i*B),M=document.createElement("canvas");M.width=s,M.height=G,M.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var l=M.getContext("2d");return l.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",l.textBaseline="top",l.fillStyle=I,l.fillRect(0,0,s,G),l.fillStyle=A,l.fillText(g,w,c),l.fillRect(L,Y,K,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(L,Y,K,e),{dom:M,update:function(V,W){Q=Math.min(Q,V),C=Math.max(C,V),l.fillStyle=I,l.globalAlpha=1,l.fillRect(0,0,s,Y),l.fillStyle=A,l.fillText(E(V)+" "+g+" ("+E(Q)+"-"+E(C)+")",w,c),l.drawImage(M,L+i,Y,K-i,e,L,Y,K-i,e),l.fillRect(L+K-i,Y,i,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(L+K-i,Y,i,E((1-V/W)*e))}}};function lE({scale:g}={scale:1.5}){const A=new Fg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class tQ{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const B of this.layers)B.transparent?I.push(B):A.push(B);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((B,Q)=>Q!==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 SB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function pE(g){return SB.includes(g)}class WE{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 mE{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){P.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,SB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){P.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,SB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!pE(A.type)){P.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new WE(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class cQ{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 mE(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=HA(B,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const B of this.layerManager.layers)if(B.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(),B=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=B.left*Q,E=B.top*Q,i=B.height*Q,s=I.x-C,G=I.y-E,w=Math.floor(s),c=Math.floor(i-G-I.height),L=Math.floor(I.width),Y=Math.floor(I.height);return new PA(HA(w,c),HA(w+L,c+Y))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return DA(2*(B-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const B=this.clientToClip(A,I);return this.camera.clipToWorld(B)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,B=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new PA(HA(B,Q),HA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){P.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const B=A/I;this.camera.setAspectRatio(B)}}function RB(g,A){for(const I of A){if(I.id===g.id)throw new Error(`Duplicate viewport ID "${g.id}". Each viewport must have a unique ID.`);if(I.element===g.element){const B=g.element.tagName.toLowerCase()+(g.element.id?`#${g.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${g.id}" both use ${B}`)}}}function TE(g){for(let A=0;A<g.length;A++)RB(g[A],g.slice(0,A))}function NB(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??DQ("viewport"),layerManager:new tQ(I)}});return TE(B),B.map(Q=>new cQ(Q))}class xE{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){P.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_){P.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)){P.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){P.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class ZE{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new NQ(this.canvas),this.chunkManager_=new fE,this.context_={chunkManager:this.chunkManager_},this.viewports_=NB(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=lE());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new xE(I,()=>{this.renderer_.updateSize();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]=NB([A],this.canvas,this.context_);return RB(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),P.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(P.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),P.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(P.info("Idetik","Idetik runtime starting"),this.running)P.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;for(const B of this.viewports_)B.cameraControls?.onUpdate(I),this.renderer_.render(B);this.chunkManager_.update();for(const B of this.overlays)B.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(B=>this.animate(B))}stop(){if(P.info("Idetik","Idetik runtime stopping"),!this.running)P.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 bE extends TI{constructor(A){if(super(),A.primitive!="triangles"){P.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){P.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const s=Math.min(E,i),G=Math.max(E,i);I.has({i0:s,i1:G})||(I.add({i0:s,i1:G}),B.push(s,G))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],s=C[E+1],G=C[E+2];Q(i,s),Q(s,G),Q(G,i)}this.indexData_=new Uint32Array(B)}}const uE=DA(0,1,0);class PE{dirty_=!0;matrix_=uA();rotation_=yB();translation_=NA();scale_=DA(1,1,1);addRotation(A){SE(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){NE(this.rotation_,A),this.dirty_=!0}get rotation(){return RE(this.rotation_)}addTranslation(A){yg(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){DB(this.translation_,A),this.dirty_=!0}get translation(){return gI(this.translation_)}addScale(A){DE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){DB(this.scale_,A),this.dirty_=!0}targetTo(A){GQ(this.translation_,A)&&(A=gI(A),A[2]+=FA);const I=CE(uA(),this.translation_,A,uE),B=_C(oQ(),I);FQ(this.rotation_,B),GB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return gI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return lg(uA(),this.matrix)}computeMatrix(){AE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class xI extends EB{wireframeEnabled=!1;wireframeColor=QA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new PE;geometry_=new TI;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const B=this.textures_[A];B!==void 0&&this.staleTextures_.push(B),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new bE(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 LI{normal;signedDistance;constructor(A=DA(0,1,0),I=0){this.normal=gI(A),this.signedDistance=I}set(A,I){this.normal=gI(A),this.signedDistance=I}signedDistanceToPoint(A){return hQ(this.normal,A)+this.signedDistance}normalize(){const A=iB(this.normal);if(A>0){const I=1/A;hg(this.normal,this.normal,I),this.signedDistance*=I}}}class LQ{planes_;constructor(A){this.planes_=[new LI(NA(),0),new LI(NA(),0),new LI(NA(),0),new LI(NA(),0),new LI(NA(),0),new LI(NA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=NA();this.planes_[0].set(cI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(cI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(cI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(cI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(cI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(cI(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=NA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class JQ extends xI{projectionMatrix_=uA();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 DA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return DA(A[4],A[5],A[6])}get frustum(){return new LQ(sg(uA(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=pg(A[0],A[1],A[2],1),B=lg(uA(),this.projectionMatrix_),Q=Gg(mI(),I,B);GE(Q,Q,1/Q[3]);const C=Gg(mI(),Q,this.transform.matrix);return DA(C[0],C[1],C[2])}}const YQ=1.77,rQ=128,KQ=128/YQ;class VE extends JQ{width_=rQ;height_=KQ;viewportAspectRatio_=YQ;viewportSize_=[rQ,KQ];constructor(A,I,B,Q,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,Q,B),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,B,Q){this.width_=Math.abs(I-A),this.height_=Math.abs(Q-B),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(B+Q);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=pg(-1,-1,0,1),I=pg(1,1,0,1);const B=sg(uA(),this.projectionMatrix,this.viewMatrix),Q=lg(uA(),B);return A=Gg(mI(),A,Q),I=Gg(mI(),I,Q),new PA(HA(A[0],A[1]),HA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],QE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const OE=60,XE=1.77,Tg=.1,UB=180-Tg;class vE extends JQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=OE,aspectRatio:B=XE,near:Q=.1,far:C=1e4,position:E=DA(0,0,0)}=A;if(I<Tg||I>UB)throw new Error(`Invalid field of view: ${I}, must be in [${Tg}, ${UB}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,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(Tg,Math.min(UB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){gE(this.projectionMatrix_,zC(this.fov),this.aspectRatio_,this.near_,this.far_)}}const MQ=0;class jE{camera_;dragActive_=!1;dragStart_=NA();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 B=gI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=sB(NA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==MQ||(this.dragStart_=gI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=sB(NA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==MQ||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class kB{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return DA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const tB=-1,nQ=0,zE=1,HQ=.009,_E=.001,$E=9e-4,Ai=.5,Ii=60;class gi{camera_;orbitVelocity_=new kB(0,0,0);panVelocity_=NA();currPos_;currCenter_=NA();dampingFactor_;currMouseButton_=tB;constructor(A,I){this.camera_=A,this.currPos_=new kB(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&DB(this.currCenter_,I.target),this.dampingFactor_=DI(I?.dampingFactor??Ai,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&&GQ(this.panVelocity_,DA(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,yg(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-FA;this.currPos_.theta=DI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const B=Math.pow(1-this.dampingFactor_,A*Ii);this.orbitVelocity_.phi*=B,this.orbitVelocity_.theta*=B,this.orbitVelocity_.radius*=B,hg(this.panVelocity_,this.panVelocity_,B),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==tB)return;const I=A.event,B=I.movementX??0,Q=I.movementY??0,C=this.currMouseButton_===nQ&&!I.shiftKey,E=this.currMouseButton_===nQ&&I.shiftKey||this.currMouseButton_===zE;C&&this.orbit(B,Q),E&&this.pan(B,Q)}onWheel(A){const I=A.event;I.preventDefault();const B=I.deltaY??0;this.zoom(B)}onPointerEnd(A){this.currMouseButton_=tB;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*HQ,this.orbitVelocity_.theta+=I*HQ}pan(A,I){const B=this.currPos_.radius*_E,Q=NA();aQ(Q,Q,this.camera_.right,A),aQ(Q,Q,this.camera_.up,I),hg(Q,Q,B),sB(this.panVelocity_,this.panVelocity_,Q)}zoom(A){this.orbitVelocity_.radius+=A*$E}updateCamera(){const A=yg(NA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<FA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<FA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<FA&&(this.orbitVelocity_.radius=0),iB(this.panVelocity_)<FA&&aE(this.panVelocity_)}}class wg{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&P.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=DI(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&P.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=DI(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(B=>B(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 Bi extends TI{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}),this.addAttribute({type:"path_proportion",itemSize:1,offset:10*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*11);let B=0,Q=0;const C=A.reduce((E,i,s)=>E+sQ(i,A[s+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const s=A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2];const G=A[E-1]??A[E];I[B++]=G[0],I[B++]=G[1],I[B++]=G[2];const w=A[E+1]??A[E];I[B++]=w[0],I[B++]=w[1],I[B++]=w[2],I[B++]=i,I[B++]=Q}Q+=sQ(A[E],A[E+1]??A[E])/C}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class Qi extends xI{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=QA.from(I),this.width_=B,this.taperOffset_=Q??this.taperOffset_,this.taperPower_=C??this.taperPower_,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=QA.from(A)}get width(){return this.width_}set width(A){this.width_=A}get taperOffset(){return this.taperOffset_}set taperOffset(A){this.taperOffset_=A}get taperPower(){return this.taperPower_}set taperPower(A){this.taperPower_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width,TaperOffset:this.taperOffset,TaperPower:this.taperPower}}}class Ci extends wg{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(cB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(cB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(cB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function cB(g){const{end:A,width:I,color:B}=g,Q=new Bi([[0,0,0],A]);return new Qi({geometry:Q,color:B,width:I})}function Ei(g){return g===1||g===2||g===4||g===8}function ZI(g){if(g instanceof Int8Array)return"byte";if(g instanceof Int16Array)return"short";if(g instanceof Int32Array)return"int";if(g instanceof Uint8Array)return"unsigned_byte";if(g instanceof Uint16Array)return"unsigned_short";if(g instanceof Uint32Array)return"unsigned_int";if(g instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function ii(g){if(g.dataFormat==="rgb"||g.dataFormat==="rgba")return[0,1];switch(g.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 LB extends EB{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"}}const eQ=32;function Sg(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=QA.WHITE:I=QA.from(I),g!==null?B=Di(B,g):B===void 0&&(P.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function JB(g,A){if(A.length>eQ)throw new Error(`Maximum number of channels is ${eQ}`);if(g?.type==="Texture2DArray"){const I=g.depth;if(A.length!==I)throw new Error(`Number of channels (${A.length}) must match depth of texture (${I}).`)}return A.map(I=>Sg(g,I))}function qQ(g,A){if(g&&g.length!==A)throw new Error(`channelProps length (${g.length}) must match source channel count (${A}).`)}function Di(g,A){if(g===void 0)return ii(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class dQ extends TI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,s=Q,G=i+1,w=s+1,c=A/i,L=I/s;for(let Y=0;Y<w;++Y){const K=Y*L;for(let e=0;e<G;++e){const M=e*c,l=e/i,V=Y/s,W=[M,K,0],O=[0,0,1],m=[l,V];C.push(...W,...O,...m)}}for(let Y=0;Y<s;++Y)for(let K=0;K<i;++K){const e=K+G*Y,M=K+G*(Y+1),l=K+1+G*(Y+1),V=K+1+G*Y;E.push(e,M,V),E.push(M,l,V)}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 oi extends xI{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new dQ(A,I,1,1),this.setTexture(0,B),this.channels_=JB(B,Q),this.programName=ai(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=JB(this.textures[0],A)}setChannelProperty(A,I,B){const Q=Sg(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");if(A.type==="Texture2D"){const{color:I,contrastLimits:B}=this.channels_[0]??Sg(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0]),ChannelCount:1}}else{const I=[],B=[],Q=[],C=[];return this.channels_.forEach(E=>{I.push(E.visible),B.push(...E.color.rgb),Q.push(-E.contrastLimits[0]),C.push(1/(E.contrastLimits[1]-E.contrastLimits[0]))}),{ImageSampler:0,"Visible[0]":I,"Color[0]":B,"ValueOffset[0]":Q,"ValueScale[0]":C,ChannelCount:this.channels_.length}}}}function ai(g){if(g.type==="Texture2D")return si(g.dataType);if(g.type==="Texture2DArray")return yi(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function si(g){switch(g){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function yi(g){switch(g){case"byte":case"int":case"short":return"intScalarImageArray";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImageArray";case"float":return"floatScalarImageArray"}}class xg extends LB{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=ZI(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}set data(A){this.data_=A,this.needsUpdate=!0}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===B)return;const Q=A.shape.x,C=A.shape.y,E=B.length/(Q*C);if(this.width!=Q||this.height!=C||this.depth_!=E||this.dataType!=ZI(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new xg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function fQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return HA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=HA(C.clientX,C.clientY);if(UE(A,E)<Q){if(!B)return null;const s=g.worldPos;if(s){const G=I(s);G!==null&&B({world:s,value:G})}return null}return A}case"pointercancel":return null;default:return A}}class YB{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&P.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),P.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class rB extends wg{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new YB;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new QA(.6,.3,.3),new QA(.3,.6,.4),new QA(.4,.4,.7),new QA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,channelProps:Q,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.channelProps_=Q,this.initialChannelProps_=Q,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(qQ(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.sliceCoords_)&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getImageForChunk(Q);this.visibleChunks_.set(Q,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_>rB.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=fQ(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,mg))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=DI(Q,0,A.shape.z-1);Wg(B,C,1+1e-6)||P.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 B=this.pool_.acquire(Zg(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),B.setChannelProps(this.getChannelPropsForChunk(A)),B):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new oi(A.shape.x,A.shape.y,xg.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){P.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[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=aB(NA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[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,s=E*A.shape.x+C;return i[s]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,B)=>{I.setChannelProps(this.getChannelPropsForChunk(B))}),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)}getVisibleDataRange(){return kQ(this.visibleChunks_.keys())}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(Zg(I),B),this.visibleChunks_.delete(I))}}}function Zg(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hi extends TI{constructor(A,I,B,Q,C,E){super();const i=[],s=[],G=Math.floor(Q),w=Math.floor(C),c=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,c,w,1,i,s),this.buildFace("z","y","x",1,-1,B,I,A,c,w,-1,i,s),this.buildFace("x","z","y",1,1,A,B,I,G,c,1,i,s),this.buildFace("x","z","y",1,-1,A,B,I,G,c,-1,i,s),this.buildFace("x","y","z",1,-1,A,I,B,G,w,1,i,s),this.buildFace("x","y","z",-1,-1,A,I,B,G,w,-1,i,s),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(s),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,B,Q,C,E,i,s,G,w,c,L,Y){const K=E/G,e=i/w,M=E/2,l=i/2,V=s/2*c,W=G+1,O=w+1,m=L.length/8;for(let T=0;T<O;T++){const CA=-l+T*e;for(let iA=0;iA<W;iA++){const BA=-M+iA*K,hA={x:0,y:0,z:0};hA[A]=BA*Q,hA[I]=CA*C,hA[B]=V;const GA={x:0,y:0,z:0};GA[B]=c;const eA=iA/G,kA=1-T/w;L.push(hA.x,hA.y,hA.z,GA.x,GA.y,GA.z,eA,kA)}}for(let T=0;T<w;T++)for(let CA=0;CA<G;CA++){const iA=m+CA+W*T,BA=m+CA+W*(T+1),hA=m+(CA+1)+W*(T+1),GA=m+(CA+1)+W*T;Y.push(iA,BA,GA,BA,hA,GA)}}}class bI extends LB{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=ZI(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=Q}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!=ZI(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 B=new bI(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class Gi extends xI{voxelScale=DA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new hi(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,B=this.channelToTextureIndex_.get(I);B!==void 0?this.updateChannelTexture(B,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const B=bI.createWithChunk(I),Q=this.textures.length;this.setTexture(Q,B),this.channelToTextureIndex_.set(A,Q);const C=Fi(B.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: ${B.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const B=this.textures[A];if(!(B instanceof bI)){const Q=bI.createWithChunk(I);this.setTexture(A,Q);return}B.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],B=[0,0,0,0],Q=[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 s=this.channelToTextureIndex_.get(i);if(s===void 0||!this.loadedChannels_.has(i))continue;const G=this.textures[s],w=Sg(G,this.channels_[i]||{});if(!w.visible)continue;const c=C.length;I[c*3]=w.color.rgb[0],I[c*3+1]=w.color.rgb[1],I[c*3+2]=w.color.rgb[2],C.push(s),B[c]=-w.contrastLimits[0],Q[c]=1/(w.contrastLimits[1]-w.contrastLimits[0]),A[c]=1}return C.reduce((i,s,G)=>(i[`Channel${G}Sampler`]=s,i),{Visible:A,"Color[0]":I,ValueOffset:B,ValueScale:Q,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const B=this.channelToTextureIndex_.get(A);if(B!==void 0)return this.textures[B]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=JB(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,B){const Q=Sg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:B});this.channels_[A]=Q}}function Fi(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function wi(g,A){const I=A.position,B=NA(),Q=NA();return g.sort((C,E)=>{yg(B,C.boundingBox.max,C.boundingBox.min),hg(B,B,.5),yg(Q,E.boundingBox.max,E.boundingBox.min),hg(Q,Q,.5);const i=yQ(I,B),s=yQ(I,Q);return i-s}),g}const Si=2;class Ri extends wg{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new YB;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;visibleChunks_=[];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,mg))}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)}getVisibleDataRange(){return kQ(this.visibleChunks_)}constructor({source:A,sliceCoords:I,policy:B,channelProps:Q}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=B,this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const B=this.currentVolumes_.get(A);if(B){for(const E of I)B.updateVolumeWithChunk(E);return B}const Q=ki(I[0]),C=this.pool_.acquire(Q)??new Gi;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);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_),qQ(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(this.sliceCoords_);this.visibleChunks_=A;const I=this.sliceCoords_.t??-1,B=Ui(A);if(this.lastLoadedTime_!==I||B.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)B.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of B){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 B={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([B.x,B.y,B.z]),cI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={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+Q.x,I.offset.y+Q.y,I.offset.z+Q.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?Si:1,this.updateChunks(),wi(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function Ni(g){const{x:A,y:I,z:B,t:Q}=g.chunkIndex;return`${A}:${I}:${B}:${Q}`}function Ui(g){const A=new Map;for(const I of g){const B=Ni(I);let Q=A.get(B);Q||(Q=[],A.set(B,Q)),Q.push(I)}return A}function ki(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class Rg extends LB{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=ZI(A),this.data_=A,this.width_=I,this.height_=B}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 B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==B){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=ZI(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new Rg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const ti=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function ci(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!ti.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class Li extends xI{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new dQ(A.width,A.height,1,1),this.setTexture(0,ci(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),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(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new Rg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,QA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,QA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new Rg(C,Q,2)}}const Ji=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Yi(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,QA.from(I)]))}function ri(g){return g=g??Ji,g.map(QA.from)}class lQ{lookupTable;cycle;constructor(A={}){this.lookupTable=Yi(A.lookupTable),this.cycle=ri(A.cycle)}}class KB extends wg{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new YB;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:B,colorMap:Q={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.colorMap_=new lQ(Q),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.sliceCoords_)&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getLabelForChunk(Q);this.visibleChunks_.set(Q,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>KB.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=fQ(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 lQ(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,mg))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=aB(NA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[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,s=E*A.shape.x+C;return i[s]}return null}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=DI(Q,0,A.shape.z-1);Wg(B,C,1+1e-6)||P.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 B=this.pool_.acquire(Zg(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForLabel(A)),this.updateLabelChunk(B,A),B.setColorMap(this.colorMap_),B.setSelectedValue(this.selectedValue_),B):this.createLabel(A)}createLabel(A){const I=new Li({width:A.shape.x,height:A.shape.y,imageData:Rg.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){P.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 B=this.visibleChunks_.get(I);B&&(this.pool_.release(Zg(I),B),this.visibleChunks_.delete(I))}}}function pQ(g,A,I,B={}){return A!==void 0&&I!==void 0&&(B={...B,headers:{...B.headers,Range:`bytes=${A}-${A+I-1}`}}),fetch(g,B)}function Ki(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function WQ(g,A){const I=typeof g=="string"?new URL(g):g;I.pathname.endsWith("/")||(I.pathname+="/");const B=new URL(A.slice(1),I);return B.search=I.search,B}async function mQ(g){if(g.status!==404){if(g.status===200||g.status===206)return new Uint8Array(await g.arrayBuffer());throw new Error(`Unexpected response status ${g.status} ${g.statusText}`)}}async function Mi(g,A,I,B){if(B)return fetch(g,{...I,headers:{...I.headers,Range:`bytes=-${A}`}});let Q=await fetch(g,{...I,method:"HEAD"});if(!Q.ok)return Q;let C=Q.headers.get("Content-Length"),E=Number(C);return pQ(g,E-A,E,I)}class uI{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return Ki(this.#A,A)}async get(A,I={}){let B=WQ(this.url,A).href,Q=await fetch(B,this.#g(I));return mQ(Q)}async getRange(A,I,B={}){let Q=WQ(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await Mi(Q,I.suffixLength,C,this.#I):E=await pQ(Q,I.offset,I.length,C),mQ(E)}}class TQ{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):A instanceof ArrayBuffer?this.#A=new Uint8Array(A,I,B):this.#A=new Uint8Array(Array.from(A,Q=>Q?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 MB{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q=Q*A),this._data=new Uint8Array(I,B,Q);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 B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class Ng{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new Ng(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 B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Ug(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function xQ(g,A){const I=A/2,B=A-1;let Q=0;for(let C=0;C<g.length;C+=A)for(let E=0;E<I;E+=1)Q=g[C+E],g[C+E]=g[C+B-E],g[C+B-E]=Q}function ZQ(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?Ng:MB).bind(null,Number(Q))}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:TQ}[g];return rA(I,`Unknown or unsupported data_type: ${g}`),I}function JI(g,A){const I=g.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),rA(I===A.length,"Order length must match the number of dimensions.");let B=1,Q=new Array(I);for(let C=A.length-1;C>=0;C--)Q[A[C]]=B,B*=g[A[C]];return Q}function ni({name:g,configuration:A}){if(g==="default"){const I=A?.separator??"/";return B=>["c",...B].join(I)}if(g==="v2"){const I=A?.separator??".";return B=>B.join(I)||"0"}throw new Error(`Unknown chunk key encoding: ${g}`)}function Hi(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(/^([<|>])(.*)$/);rA(A,`Invalid dtype: ${g}`);let[,I,B]=A,Q={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);return rA(Q,`Unsupported or unknown dtype: ${g}`),I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function ei(g,A={}){let I=[],B=Hi(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}}),"endian"in B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}});for(let{id:Q,...C}of g.filters??[])I.push({name:Q,configuration:C});if(g.compressor){let{id:Q,...C}=g.compressor;I.push({name:Q,configuration:C})}return{zarr_format:3,node_type:"array",shape:g.shape,data_type:B.data_type,chunk_grid:{name:"regular",configuration:{chunk_shape:g.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:g.dimension_separator??"."}},codecs:I,fill_value:g.fill_value,attributes:A}}function qi(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function di(g,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return g===A;let I=g==="bool";if(A==="boolean")return I;let B=g.startsWith("v2:U")||g.startsWith("v2:S");if(A==="string")return B;let Q=g==="int64"||g==="uint64";if(A==="bigint")return Q;let C=g==="v2:object";return A==="object"?C:!B&&!Q&&!I&&!C}function fi(g){return g?.name==="sharding_indexed"}function bQ(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}function uQ(g,...A){if(!A.some(I=>g instanceof I))throw g}function rA(g,A=""){if(!g)throw new Error(A)}async function PQ(g,{format:A,signal:I}){const B=g instanceof Response?g:new Response(g);rA(B.body,"Response does not contain body.");try{return await new Response(B.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}class nB{kind="array_to_array";constructor(A,I){rA(A.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(A,I){return new nB(A,I)}encode(A){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(A){return A}}const VQ=li();function li(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function OQ(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class bg{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=ZQ(I.data_type),this.#Q=I.shape,this.#A=JI(I.shape,"C");const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new bg(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return VQ&&this.#B==="big"&&xQ(I,OQ(this.#I)),I}decode(A){return VQ&&this.#B==="big"&&xQ(A,OQ(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class HB{kind="bytes_to_bytes";static fromConfig(){return new HB}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}class eB{kind="bytes_to_bytes";static fromConfig(A){return new eB}encode(A){throw new Error("Gzip encoding is not enabled by default. Please register a custom codec with `numcodecs/gzip`.")}async decode(A){const I=await PQ(A,{format:"gzip"});return new Uint8Array(I)}}function pi(g,A){return rA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),rA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),rA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Wi(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class qB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:B=!1,ensure_ascii:Q=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:s,strict:G=!0}=A;let w=A.separators;w||(s?w=[", ",": "]:w=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:s,separators:w,sort_keys:i},this.#I={strict:G}}static fromConfig(A){return new qB(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;rA(B==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const s=[];rA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||s.push(pi),i&&s.push(Wi);const G=Array.from(A.data);G.push("|O"),G.push(A.shape);let w;s.length&&(w=(L,Y)=>{let K=Y;for(let e of s)K=e(L,K);return K});let c=JSON.stringify(G,w,I);return Q&&(c=c.replace(/[\u007F-\uFFFF]/g,L=>{const Y=`0000${L.charCodeAt(0).toString(16)}`;return`\\u${Y.substring(Y.length-4)}`})),new TextEncoder().encode(c)}decode(A){const{strict:I}=this.#I;rA(I,"JsonCodec does not yet support non-strict decoding.");const B=Ug(A),Q=B.pop();B.pop(),rA(Q,"0D not implemented for JsonCodec.");const C=JI(Q,"C");return{data:B,shape:Q,stride:C}}}function XQ(g){return g instanceof TQ||g instanceof MB||g instanceof Ng?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function mi(g,A){let I;return g.data instanceof MB||g.data instanceof Ng?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:JI(g.shape,A)}}function Ti(g,A){let I=mi(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=XQ(g.data),i=XQ(I.data);for(let s=0;s<Q;s++){let G=0;for(let w=0;w<B;w++)G+=C[w]*I.stride[w];i[G]=E[s],C[0]+=1;for(let w=0;w<B;w++)if(C[w]===g.shape[w]){if(w+1===B)break;C[w]=0,C[w+1]+=1}}return I}function xi(g){let A=g.shape.length;return rA(A===g.stride.length,"Shape and stride must have the same length."),g.stride.map((I,B)=>({stride:I,index:B})).sort((I,B)=>B.stride-I.stride).map(I=>I.index)}function Zi(g,A){let I=xi(g);return rA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class dB{kind="array_to_array";#A;#I;constructor(A,I){let B=A.order??"C",Q=I.shape.length,C=new Array(Q),E=new Array(Q);if(B==="C")for(let i=0;i<Q;++i)C[i]=i,E[i]=i;else if(B==="F")for(let i=0;i<Q;++i)C[i]=Q-i-1,E[i]=Q-i-1;else C=B,C.forEach((i,s)=>{rA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=s});this.#A=C,this.#I=E}static fromConfig(A,I){return new dB(A,I)}encode(A){return Zi(A,this.#I)?A:Ti(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:JI(A.shape,this.#A)}}}class fB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=JI(A,"C")}static fromConfig(A,I){return new fB(I.shape)}encode(A){throw new Error("Method not implemented.")}decode(A){let I=new TextDecoder,B=new DataView(A.buffer),Q=Array(B.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=B.getUint32(C,!0);C+=4,Q[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:Q,shape:this.#A,stride:this.#I}}}class lB{kind="bytes_to_bytes";static fromConfig(A){return new lB}encode(A){throw new Error("Zlib encoding is not enabled by default. Please register a codec with `numcodecs/zlib`.")}async decode(A){const I=await PQ(A,{format:"deflate"});return new Uint8Array(I)}}function bi(){return new Map().set("blosc",()=>Promise.resolve().then(()=>No).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Jo).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>Ho).then(g=>g.default)).set("gzip",()=>eB).set("zlib",()=>lB).set("transpose",()=>dB).set("bytes",()=>bg).set("crc32c",()=>HB).set("vlen-utf8",()=>fB).set("json2",()=>qB).set("bitround",()=>nB)}const ui=bi();function pB(g){let A;return{async encode(I){A||(A=await vQ(g));for(const Q of A.array_to_array)I=await Q.encode(I);let B=await A.array_to_bytes.encode(I);for(const Q of A.bytes_to_bytes)B=await Q.encode(B);return B},async decode(I){A||(A=await vQ(g));for(let Q=A.bytes_to_bytes.length-1;Q>=0;Q--)I=await A.bytes_to_bytes[Q].decode(I);let B=await A.array_to_bytes.decode(I);for(let Q=A.array_to_array.length-1;Q>=0;Q--)B=await A.array_to_array[Q].decode(B);return B}}}async function vQ(g){let A=g.codecs.map(async C=>{let E=await ui.get(C.name)?.();return rA(E,`Unknown codec: ${C.name}`),{Codec:E,meta:C}}),I=[],B,Q=[];for await(let{Codec:C,meta:E}of A){let i=C.fromConfig(E.configuration,g);switch(i.kind){case"array_to_array":I.push(i);break;case"array_to_bytes":B=i;break;default:Q.push(i)}}return B||(rA(Pi(g),`Cannot encode ${g.data_type} to bytes without a codec`),B=bg.fromConfig({endian:"little"},g)),{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function Pi(g){return g.data_type!=="v2:object"}class kg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class WB extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}const jQ=18446744073709551615n;function Vi(g,A,I,B){rA(g.store.getRange,"Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((s,G)=>s/B.chunk_shape[G]),E=pB({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async s=>{let G=s.map((V,W)=>Math.floor(V/C[W])),w=g.resolve(I(G)).path,c;if(w in i)c=i[w];else{let V=4,W=16*C.reduce((m,T)=>m*T,1),O=await Q(w,{suffixLength:W+V});c=i[w]=O?await E.decode(O):null}if(c===null)return;let{data:L,shape:Y,stride:K}=c,e=s.map((V,W)=>V%Y[W]).reduce((V,W,O)=>V+W*K[O],0),M=L[e],l=L[e+1];if(!(M===jQ&&l===jQ))return Q(w,{offset:Number(M),length:Number(l)})}}class TA{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 TA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class mB extends TA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function zQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const ug=Symbol("zarrita.context");function Oi(g,A){let{configuration:I}=A.codecs.find(fi)??{},B={encode_chunk_key:ni(A.chunk_key_encoding),TypedArray:ZQ(A.data_type),fill_value:A.fill_value};if(I){let C=zQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:pB({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E){return JI(E,C)},get_chunk_bytes:Vi(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=zQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:pB({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C){return JI(C,Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),s=g.resolve(i).path;return g.store.get(s,E)}}}let Pg=class extends TA{kind="array";#A;[ug];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:bQ(B)},this[ug]=Oi(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[ug].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[ug],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,s)=>i*s,1),E=new B.TypedArray(C);return E.fill(B.fill_value),{data:E,shape:B.chunk_shape,stride:B.get_strides(B.chunk_shape)}}return B.codec.decode(Q)}is(A){return di(this.dtype,A)}},Vg=Xi();function Xi(){let g=new WeakMap;function A(I){let B=g.get(I)??{v2:0,v3:0};return g.set(I,B),B}return{increment(I,B){A(I)[B]+=1},version_max(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function vi(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Ug(A):{}}async function ji(g,A={}){let I="store"in g?g:new TA(g),B={};return(A.attrs??!0)&&(B=await vi(I)),A.kind==="array"?_Q(I,B):A.kind==="group"?$Q(I,B):_Q(I,B).catch(Q=>(uQ(Q,kg),$Q(I,B)))}async function _Q(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new kg("v2 array",{cause:new WB(I)});return Vg.increment(g.store,"v2"),new Pg(g.store,g.path,ei(Ug(B),A))}async function $Q(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new kg("v2 group",{cause:new WB(I)});return Vg.increment(g.store,"v2"),new mB(g.store,g.path,qi(Ug(B),A))}async function zi(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new kg("v3 array or group",{cause:new WB(I)});let Q=Ug(B);return Q.node_type==="array"&&(Q.fill_value=bQ(Q)),Q.node_type==="array"?new Pg(A,g.path,Q):new mB(A,g.path,Q)}async function _i(g,A={}){let I="store"in g?g:new TA(g),B=await zi(I);if(Vg.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof Pg||A.kind==="group"&&B instanceof mB)return B;let Q=B instanceof Pg?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function XA(g,A={}){let I="store"in g?g.store:g,B=Vg.version_max(I),Q=B==="v2"?XA.v2:XA.v3,C=B==="v2"?XA.v3:XA.v2;return Q(g,A).catch(E=>(uQ(E,kg),C(g,A)))}XA.v2=ji,XA.v3=_i;async function $i(g,A){const I=A.split("/"),B=I.pop();if(!B)throw new Error("Invalid path");for(const Q of I)g=await g.getDirectoryHandle(Q);return g.getFileHandle(B)}class TB{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await $i(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function AD(){if(typeof window>"u")return;const g=window.location.hostname;if(!(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.startsWith("127."))){const I="S3FetchStore is only allowed in local development environments. ";throw new Error(I)}}class xB extends uI{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){AD(),super(A.url,{overrides:A.overrides,useSuffixRequest:A.useSuffixRequest}),this.credentials=A.credentials,this.region=A.region,this.overrides=A.overrides,this.useSuffixRequest=A.useSuffixRequest}async get(A,I){if(this.credentials&&this.region){const Q=`${this.url.toString().replace(/\/$/,"")}${A}`,C=await this.generateAuthHeaders(Q,"GET"),E={...I,headers:{...I?.headers,...C}};return super.get(A,E)}return super.get(A,I)}async getRange(A,I,B){if(this.credentials&&this.region){const C=`${this.url.toString().replace(/\/$/,"")}${A}`,E=await this.generateAuthHeaders(C,"HEAD"),i=await this.generateAuthHeaders(C,"GET"),s=globalThis.fetch,G=async(c,L)=>{const K=(L?.method||"GET")==="HEAD"?E:i,e={...L,headers:{...L?.headers,...K}};return s(c,e)},w=globalThis.fetch;globalThis.fetch=G;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=w}}return super.getRange(A,I,B)}async generateAuthHeaders(A,I="GET"){if(!this.credentials||!this.region)return{};const{accessKeyId:B,secretAccessKey:Q,sessionToken:C}=this.credentials,E=this.region,i="s3",s=this.getAmzDate(),G=s.slice(0,8),w=new URL(A),c=w.host,L=w.pathname,Y=w.search.slice(1),K=`host:${c}
|
|
460
|
+
${Q}`;return g.replace(CB,C)}const fg={};function DQ(g){const A=g??"";return fg[A]=(fg[A]??0)+1,g?`${g}-${fg[A]}`:String(fg[A])}class EB{id=DQ()}var FA=1e-6,nA=typeof Float32Array<"u"?Float32Array:Array,jC=Math.PI/180;function zC(g){return g*jC}function oQ(){var g=new nA(9);return nA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[5]=0,g[6]=0,g[7]=0),g[0]=1,g[4]=1,g[8]=1,g}function _C(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[4],g[4]=A[5],g[5]=A[6],g[6]=A[8],g[7]=A[9],g[8]=A[10],g}function uA(){var g=new nA(16);return nA!=Float32Array&&(g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=0,g[12]=0,g[13]=0,g[14]=0),g[0]=1,g[5]=1,g[10]=1,g[15]=1,g}function lg(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],s=A[6],G=A[7],w=A[8],c=A[9],L=A[10],Y=A[11],K=A[12],e=A[13],M=A[14],l=A[15],V=I*i-B*E,W=I*s-Q*E,O=I*G-C*E,m=B*s-Q*i,T=B*G-C*i,CA=Q*G-C*s,iA=w*e-c*K,BA=w*M-L*K,hA=w*l-Y*K,GA=c*M-L*e,eA=c*l-Y*e,kA=L*l-Y*M,aA=V*kA-W*eA+O*GA+m*hA-T*BA+CA*iA;return aA?(aA=1/aA,g[0]=(i*kA-s*eA+G*GA)*aA,g[1]=(Q*eA-B*kA-C*GA)*aA,g[2]=(e*CA-M*T+l*m)*aA,g[3]=(L*T-c*CA-Y*m)*aA,g[4]=(s*hA-E*kA-G*BA)*aA,g[5]=(I*kA-Q*hA+C*BA)*aA,g[6]=(M*O-K*CA-l*W)*aA,g[7]=(w*CA-L*O+Y*W)*aA,g[8]=(E*eA-i*hA+G*iA)*aA,g[9]=(B*hA-I*eA-C*iA)*aA,g[10]=(K*T-e*O+l*V)*aA,g[11]=(c*O-w*T-Y*V)*aA,g[12]=(i*BA-E*GA-s*iA)*aA,g[13]=(I*GA-B*BA+Q*iA)*aA,g[14]=(e*W-K*m-M*V)*aA,g[15]=(w*m-c*W+L*V)*aA,g):null}function sg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],s=A[5],G=A[6],w=A[7],c=A[8],L=A[9],Y=A[10],K=A[11],e=A[12],M=A[13],l=A[14],V=A[15],W=I[0],O=I[1],m=I[2],T=I[3];return g[0]=W*B+O*i+m*c+T*e,g[1]=W*Q+O*s+m*L+T*M,g[2]=W*C+O*G+m*Y+T*l,g[3]=W*E+O*w+m*K+T*V,W=I[4],O=I[5],m=I[6],T=I[7],g[4]=W*B+O*i+m*c+T*e,g[5]=W*Q+O*s+m*L+T*M,g[6]=W*C+O*G+m*Y+T*l,g[7]=W*E+O*w+m*K+T*V,W=I[8],O=I[9],m=I[10],T=I[11],g[8]=W*B+O*i+m*c+T*e,g[9]=W*Q+O*s+m*L+T*M,g[10]=W*C+O*G+m*Y+T*l,g[11]=W*E+O*w+m*K+T*V,W=I[12],O=I[13],m=I[14],T=I[15],g[12]=W*B+O*i+m*c+T*e,g[13]=W*Q+O*s+m*L+T*M,g[14]=W*C+O*G+m*Y+T*l,g[15]=W*E+O*w+m*K+T*V,g}function $C(g,A){return g[0]=A[0],g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=A[1],g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=A[2],g[11]=0,g[12]=0,g[13]=0,g[14]=0,g[15]=1,g}function AE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],s=Q+Q,G=C+C,w=E+E,c=Q*s,L=Q*G,Y=Q*w,K=C*G,e=C*w,M=E*w,l=i*s,V=i*G,W=i*w,O=B[0],m=B[1],T=B[2];return g[0]=(1-(K+M))*O,g[1]=(L+W)*O,g[2]=(Y-V)*O,g[3]=0,g[4]=(L-W)*m,g[5]=(1-(c+M))*m,g[6]=(e+l)*m,g[7]=0,g[8]=(Y+V)*T,g[9]=(e-l)*T,g[10]=(1-(c+K))*T,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function IE(g,A,I,B,Q){var C=1/Math.tan(A/2);if(g[0]=C/I,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=C,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[11]=-1,g[12]=0,g[13]=0,g[15]=0,Q!=null&&Q!==1/0){var E=1/(B-Q);g[10]=(Q+B)*E,g[14]=2*Q*B*E}else g[10]=-1,g[14]=-2*B;return g}var gE=IE;function BE(g,A,I,B,Q,C,E){var i=1/(A-I),s=1/(B-Q),G=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*s,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*G,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*s,g[14]=(E+C)*G,g[15]=1,g}var QE=BE;function CE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],s=B[1],G=B[2],w=Q-I[0],c=C-I[1],L=E-I[2],Y=w*w+c*c+L*L;Y>0&&(Y=1/Math.sqrt(Y),w*=Y,c*=Y,L*=Y);var K=s*L-G*c,e=G*w-i*L,M=i*c-s*w;return Y=K*K+e*e+M*M,Y>0&&(Y=1/Math.sqrt(Y),K*=Y,e*=Y,M*=Y),g[0]=K,g[1]=e,g[2]=M,g[3]=0,g[4]=c*M-L*e,g[5]=L*K-w*M,g[6]=w*e-c*K,g[7]=0,g[8]=w,g[9]=c,g[10]=L,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function EE(g,A){var I=g[0],B=g[1],Q=g[2],C=g[3],E=g[4],i=g[5],s=g[6],G=g[7],w=g[8],c=g[9],L=g[10],Y=g[11],K=g[12],e=g[13],M=g[14],l=g[15],V=A[0],W=A[1],O=A[2],m=A[3],T=A[4],CA=A[5],iA=A[6],BA=A[7],hA=A[8],GA=A[9],eA=A[10],kA=A[11],aA=A[12],QI=A[13],_A=A[14],CI=A[15];return Math.abs(I-V)<=FA*Math.max(1,Math.abs(I),Math.abs(V))&&Math.abs(B-W)<=FA*Math.max(1,Math.abs(B),Math.abs(W))&&Math.abs(Q-O)<=FA*Math.max(1,Math.abs(Q),Math.abs(O))&&Math.abs(C-m)<=FA*Math.max(1,Math.abs(C),Math.abs(m))&&Math.abs(E-T)<=FA*Math.max(1,Math.abs(E),Math.abs(T))&&Math.abs(i-CA)<=FA*Math.max(1,Math.abs(i),Math.abs(CA))&&Math.abs(s-iA)<=FA*Math.max(1,Math.abs(s),Math.abs(iA))&&Math.abs(G-BA)<=FA*Math.max(1,Math.abs(G),Math.abs(BA))&&Math.abs(w-hA)<=FA*Math.max(1,Math.abs(w),Math.abs(hA))&&Math.abs(c-GA)<=FA*Math.max(1,Math.abs(c),Math.abs(GA))&&Math.abs(L-eA)<=FA*Math.max(1,Math.abs(L),Math.abs(eA))&&Math.abs(Y-kA)<=FA*Math.max(1,Math.abs(Y),Math.abs(kA))&&Math.abs(K-aA)<=FA*Math.max(1,Math.abs(K),Math.abs(aA))&&Math.abs(e-QI)<=FA*Math.max(1,Math.abs(e),Math.abs(QI))&&Math.abs(M-_A)<=FA*Math.max(1,Math.abs(M),Math.abs(_A))&&Math.abs(l-CI)<=FA*Math.max(1,Math.abs(l),Math.abs(CI))}function NA(){var g=new nA(3);return nA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function gI(g){var A=new nA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function iB(g){var A=g[0],I=g[1],B=g[2];return Math.sqrt(A*A+I*I+B*B)}function DA(g,A,I){var B=new nA(3);return B[0]=g,B[1]=A,B[2]=I,B}function DB(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function cI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function yg(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function iE(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function DE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function hg(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function aQ(g,A,I,B){return g[0]=A[0]+I[0]*B,g[1]=A[1]+I[1]*B,g[2]=A[2]+I[2]*B,g}function sQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.sqrt(I*I+B*B+Q*Q)}function yQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return I*I+B*B+Q*Q}function oE(g,A){var I=A[0],B=A[1],Q=A[2],C=I*I+B*B+Q*Q;return C>0&&(C=1/Math.sqrt(C)),g[0]=A[0]*C,g[1]=A[1]*C,g[2]=A[2]*C,g}function hQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function oB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],s=I[2];return g[0]=Q*s-C*i,g[1]=C*E-B*s,g[2]=B*i-Q*E,g}function aB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[3]*B+I[7]*Q+I[11]*C+I[15];return E=E||1,g[0]=(I[0]*B+I[4]*Q+I[8]*C+I[12])/E,g[1]=(I[1]*B+I[5]*Q+I[9]*C+I[13])/E,g[2]=(I[2]*B+I[6]*Q+I[10]*C+I[14])/E,g}function aE(g){return g[0]=0,g[1]=0,g[2]=0,g}function GQ(g,A){var I=g[0],B=g[1],Q=g[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=FA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=FA*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=FA*Math.max(1,Math.abs(Q),Math.abs(i))}var sB=iE,sE=iB;(function(){var g=NA();return function(A,I,B,Q,C,E){var i,s;for(I||(I=3),B||(B=0),Q?s=Math.min(Q*I+B,A.length):s=A.length,i=B;i<s;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2];return A}})();function mI(){var g=new nA(4);return nA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function yE(g){var A=new nA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function pg(g,A,I,B){var Q=new nA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function hE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function GE(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g[3]=A[3]*I,g}function FE(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=I*I+B*B+Q*Q+C*C;return E>0&&(E=1/Math.sqrt(E)),g[0]=I*E,g[1]=B*E,g[2]=Q*E,g[3]=C*E,g}function Gg(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3];return g[0]=I[0]*B+I[4]*Q+I[8]*C+I[12]*E,g[1]=I[1]*B+I[5]*Q+I[9]*C+I[13]*E,g[2]=I[2]*B+I[6]*Q+I[10]*C+I[14]*E,g[3]=I[3]*B+I[7]*Q+I[11]*C+I[15]*E,g}(function(){var g=mI();return function(A,I,B,Q,C,E){var i,s;for(I||(I=4),B||(B=0),Q?s=Math.min(Q*I+B,A.length):s=A.length,i=B;i<s;i+=I)g[0]=A[i],g[1]=A[i+1],g[2]=A[i+2],g[3]=A[i+3],C(g,g,E),A[i]=g[0],A[i+1]=g[1],A[i+2]=g[2],A[i+3]=g[3];return A}})();function yB(){var g=new nA(4);return nA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function wE(g,A,I){I=I*.5;var B=Math.sin(I);return g[0]=B*A[0],g[1]=B*A[1],g[2]=B*A[2],g[3]=Math.cos(I),g}function SE(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],s=I[1],G=I[2],w=I[3];return g[0]=B*w+E*i+Q*G-C*s,g[1]=Q*w+E*s+C*i-B*G,g[2]=C*w+E*G+B*s-Q*i,g[3]=E*w-B*i-Q*s-C*G,g}function hB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],s=I[0],G=I[1],w=I[2],c=I[3],L,Y,K,e,M;return Y=Q*s+C*G+E*w+i*c,Y<0&&(Y=-Y,s=-s,G=-G,w=-w,c=-c),1-Y>FA?(L=Math.acos(Y),K=Math.sin(L),e=Math.sin((1-B)*L)/K,M=Math.sin(B*L)/K):(e=1-B,M=B),g[0]=e*Q+M*s,g[1]=e*C+M*G,g[2]=e*E+M*w,g[3]=e*i+M*c,g}function FQ(g,A){var I=A[0]+A[4]+A[8],B;if(I>0)B=Math.sqrt(I+1),g[3]=.5*B,B=.5/B,g[0]=(A[5]-A[7])*B,g[1]=(A[6]-A[2])*B,g[2]=(A[1]-A[3])*B;else{var Q=0;A[4]>A[0]&&(Q=1),A[8]>A[Q*3+Q]&&(Q=2);var C=(Q+1)%3,E=(Q+2)%3;B=Math.sqrt(A[Q*3+Q]-A[C*3+C]-A[E*3+E]+1),g[Q]=.5*B,B=.5/B,g[3]=(A[C*3+E]-A[E*3+C])*B,g[C]=(A[C*3+Q]+A[Q*3+C])*B,g[E]=(A[E*3+Q]+A[Q*3+E])*B}return g}var RE=yE,NE=hE,GB=FE;(function(){var g=NA(),A=DA(1,0,0),I=DA(0,1,0);return function(B,Q,C){var E=hQ(Q,C);return E<-.999999?(oB(g,A,Q),sE(g)<1e-6&&oB(g,I,Q),oE(g,g),wE(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(oB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,GB(B,B))}})(),(function(){var g=yB(),A=yB();return function(I,B,Q,C,E,i){return hB(g,B,E,i),hB(A,Q,C,i),hB(I,g,A,2*i*(1-i)),I}})(),(function(){var g=oQ();return function(A,I,B,Q){return g[0]=B[0],g[3]=B[1],g[6]=B[2],g[1]=Q[0],g[4]=Q[1],g[7]=Q[2],g[2]=-I[0],g[5]=-I[1],g[8]=-I[2],GB(A,FQ(A,g))}})();function wQ(){var g=new nA(2);return nA!=Float32Array&&(g[0]=0,g[1]=0),g}function SQ(g){var A=new nA(2);return A[0]=g[0],A[1]=g[1],A}function HA(g,A){var I=new nA(2);return I[0]=g,I[1]=A,I}function UE(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.sqrt(I*I+B*B)}function kE(g){var A=g[0],I=g[1];return A*A+I*I}function tE(g,A,I,B){var Q=A[0],C=A[1];return g[0]=Q+B*(I[0]-Q),g[1]=C+B*(I[1]-C),g}function RQ(g,A){return g[0]===A[0]&&g[1]===A[1]}function FB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=FA*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=FA*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=wQ();return function(A,I,B,Q,C,E){var i,s;for(I||(I=2),B||(B=0),Q?s=Math.min(Q*I+B,A.length):s=A.length,i=B;i<s;i+=I)g[0]=A[i],g[1]=A[i+1],C(g,g,E),A[i]=g[0],A[i+1]=g[1];return A}})();class iI{min;max;constructor(A,I){this.min=A?gI(A):DA(1/0,1/0,1/0),this.max=I?gI(I):DA(-1/0,-1/0,-1/0)}clone(){return new iI(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:B}=this,Q=[DA(I[0],I[1],I[2]),DA(I[0],I[1],B[2]),DA(I[0],B[1],I[2]),DA(I[0],B[1],B[2]),DA(B[0],I[1],I[2]),DA(B[0],I[1],B[2]),DA(B[0],B[1],I[2]),DA(B[0],B[1],B[2])];this.min=DA(1/0,1/0,1/0),this.max=DA(-1/0,-1/0,-1/0);const C=NA();for(const E of Q)aB(C,E,A),this.expandWithPoint(C)}}const cE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class TI extends EB{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],B="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=B,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,B=new iI,Q=NA();for(let C=0;C<this.vertexData_.length;C+=this.stride)Q[0]=this.vertexData_[C+I+0],Q[1]=this.vertexData_[C+I+1],Q[2]=this.vertexData_[C+I+2],B.expandWithPoint(Q);this.boundingBox_=B}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class LE{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:B}=A,Q=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(Q,C),this.gl_.bufferData(Q,B,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(w=>{const c=cE[w.type];this.gl_.vertexAttribPointer(c,w.itemSize,this.gl_.FLOAT,!1,i,w.offset),this.gl_.enableVertexAttribArray(c)});const s={vao:I,vbo:C},{indexData:G}=A;if(G.length){const w=this.gl_.ELEMENT_ARRAY_BUFFER,c=this.gl_.createBuffer();if(!c)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(w,c),this.gl_.bufferData(w,G,this.gl_.STATIC_DRAW),s.ebo=c}this.buffers_.set(A,s),this.gl_.bindVertexArray(null)}}class JE{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 B=this.getTextureType(A),Q=this.getDataFormatInfo(A.dataFormat,A.dataType);this.textures_.has(A)||this.generateTexture(A,Q,B);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(B,C),A.needsUpdate&&A.data!==null&&(this.configureTextureParameters(A,B),this.uploadTextureData(A,Q,B),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 B=this.getDataFormatInfo(A.dataFormat,A.dataType),Q=this.computeStorageBytes(A,B);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-Q),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,B){const Q=this.gl_.createTexture();if(!Q)throw new Error("Failed to create texture");if(this.gl_.bindTexture(B,Q),this.isTexture2D(A))this.gl_.texStorage2D(B,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(B,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,Q),this.gl_.bindTexture(B,null)}configureTextureParameters(A,I){const B=this.gl_,Q=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);B.pixelStorei(B.UNPACK_ALIGNMENT,A.unpackAlignment),B.texParameteri(I,B.TEXTURE_MIN_FILTER,Q),B.texParameteri(I,B.TEXTURE_MAG_FILTER,C),B.texParameteri(I,B.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),B.texParameteri(I,B.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),B.texParameteri(I,B.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,B){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(B,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(B,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:B,dataType:Q}=I;if(B==="scalar"&&Q!=="float"&&A!=="nearest")return P.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 B=this.bytesPerTexel(I),Q=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),s=0;for(let G=0;G<Q;G++)s+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return s}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 PA{min;max;constructor(A,I){this.min=A?SQ(A):HA(1/0,1/0),this.max=I?SQ(I):HA(-1/0,-1/0)}clone(){return new PA(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 RQ(A.min,I.min)&&RQ(A.max,I.max)}floor(){return new PA(HA(Math.floor(this.min[0]),Math.floor(this.min[1])),HA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],B=this.max[0]-this.min[0],Q=this.max[1]-this.min[1];return{x:A,y:I,width:B,height:Q}}}class YE{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_&&PA.equals(I,this.currentViewport_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.viewport(B,Q,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_&&PA.equals(I,this.currentScissor_))return;const{x:B,y:Q,width:C,height:E}=I.toRect();this.gl_.scissor(B,Q,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 rE=$C(uA(),[1,-1,1]);class NQ extends fC{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=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,P.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new vC(I),this.bindings_=new LE(I),this.textures_=new JE(I),this.state_=new YE(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0;const{opaque:I,transparent:B}=A.layerManager.partitionLayers();for(const G of[...I,...B])G.update({viewport:A});if(getComputedStyle(A.element).visibility==="hidden")return;const Q=A.getBoxRelativeTo(this.canvas),C=new PA(HA(0,0),HA(this.width,this.height)),E=PA.equals(Q.floor(),C.floor()),i=PA.intersects(Q,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(Q);else{P.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(Q),this.clear();const s=A.camera.frustum;this.state_.setDepthMask(!0);for(const G of I)G.state==="ready"&&this.renderLayer(G,A.camera,s);this.state_.setDepthMask(!1);for(const G of B)G.state==="ready"&&this.renderLayer(G,A.camera,s);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,B){if(A.objects.length===0)return;this.state_.setBlendingMode(A.transparent?A.blendMode:"none");const Q=A.hasMultipleLODs();this.state_.setStencilTest(Q),Q&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{B.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];if(Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),!Q.programName)return;this.state_.setCullFaceMode(Q.cullFaceMode),this.state_.setDepthTesting(Q.depthTest),this.state_.setDepthMask(Q.depthTest),this.bindings_.bindGeometry(Q.geometry),Q.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(Q.programName);if(this.drawGeometry(Q.geometry,Q,A,C,B),Q.wireframeEnabled){this.bindings_.bindGeometry(Q.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",Q.wireframeColor.rgb),this.drawGeometry(Q.wireframeGeometry,Q,A,E,B)}}drawGeometry(A,I,B,Q,C){const E=sg(uA(),C.viewMatrix,I.transform.matrix),i=sg(uA(),rE,C.projectionMatrix),s=[this.canvas.width,this.canvas.height],G=I.getUniforms(),c={...B.getUniforms(),...G};for(const K of Q.uniformNames)switch(K){case"ModelView":Q.setUniform(K,E);break;case"Projection":Q.setUniform(K,i);break;case"Resolution":Q.setUniform(K,s);break;case"u_opacity":Q.setUniform(K,B.opacity);break;case"CameraPositionModel":{const e=lg(uA(),E),M=pg(0,0,0,1),l=Gg(mI(),M,e);Q.setUniform(K,DA(l[0],l[1],l[2]));break}default:K in c&&Q.setUniform(K,c[K])}const L=this.glGetPrimitive(A.primitive),Y=A.indexData;Y.length?this.gl_.drawElements(L,Y.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(L,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 B=new PA(HA(0,0),HA(A,I));this.state_.setViewport(B)}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 KE=8;class ME{maxConcurrent_;pending_=[];running_=new Map;constructor(A=KE){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(B=>B.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(Q=>Q.chunk===A);if(I>=0){this.pending_.splice(I,1),P.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),P.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 B=A.chunk.priority??Number.MAX_SAFE_INTEGER,Q=I.chunk.priority??Number.MAX_SAFE_INTEGER;return B===Q?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):B-Q});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:B}=A;I.state="loading";const Q=new AbortController,C=Promise.resolve().then(()=>B(Q.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&P.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const UQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function nE(g){if(UQ.some(I=>g instanceof I))return!0;const A=UQ.map(I=>I.name);return P.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function HE(g){let A=1/0,I=-1/0;for(let B=0;B<g.length;B++){const Q=g[B];Q<A&&(A=Q),Q>I&&(I=Q)}return{min:A,max:I}}function kQ(g){const A={};for(const I of g){if(!I.dataRange)continue;const B=I.chunkIndex.c,Q=A[B];Q?(Q.min=Math.min(Q.min,I.dataRange.min),Q.max=Math.max(Q.max,I.dataRange.max)):A[B]={min:I.dataRange.min,max:I.dataRange.max}}return A}function eE(g,A){return Math.round((A-g.translation)/g.scale)}function Wg(g,A,I=1e-6){return Math.abs(g-A)<=I}function DI(g,A,I){return Math.max(A,Math.min(I,g))}const mg=Symbol("INTERNAL_POLICY_KEY");class qE{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,P.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const B=this.store_.dimensions,Q=B.x.lods[0],C=B.y.lods[0];this.sourceMaxSquareDistance2D_=kE(HA(Q.size*Q.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}getChunksAtTime(A){return this.store_.getChunksAtTime(A)}getTimeIndex(A){return this.store_.getTimeIndex(A)}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I),Q=B.filter(i=>i.lod===this.currentLOD_&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),C=this.fallbackLOD();if(this.currentLOD_===C)return Q;const E=B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded");return[...Q,...E]}updateChunksForImage(A,I){const B=I.camera;if(B.type!=="OrthographicCamera")throw new Error("ChunkStoreView currently supports only orthographic cameras. Update the implementation before using a perspective camera.");const C=B.getWorldViewRect(),E=Math.abs(C.max[0]-C.min[0]),i=I.element,s=I.getBoxRelativeTo(i).toRect().width,G=E/s,w=Math.log2(1/G);this.setLOD(w);const c=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(c)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const Y=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(Y).length===0){P.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const e=wQ();tE(e,C.min,C.max,.5);const[M,l]=this.getZBounds(A),V=new iI(DA(C.min[0],C.min[1],M),DA(C.max[0],C.max[1],l));this.chunkViewStates_.forEach(wB),this.updateChunksAtTimeIndex(Y,A,V,e),A.t!==void 0&&this.markTimeChunksForPrefetchImage(Y,A,V,e),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=c,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){const B=sg(uA(),I.camera.projectionMatrix,I.camera.viewMatrix);if(!(this.policyChanged_||this.hasViewProjectionChanged(B)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const C=this.store_.getTimeIndex(A),E=this.store_.getChunksAtTime(C);if(E.length===0){P.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(wB);const i=this.fallbackLOD();for(const s of E){const G=s.lod===this.currentLOD_,w=s.lod===i;if(!G&&!w||!this.isChunkChannelInSlice(s,A))continue;const c=this.computePriority(w,G,!0,!1,!0);this.chunkViewStates_.set(s,{visible:!0,prefetch:!1,priority:c,orderKey:0})}A.t!==void 0&&this.markTimeChunksForPrefetchVolume(C,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=B}allVisibleFallbackLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.fallbackLOD(),Q=this.store_.getChunksAtTime(I).filter(C=>C.visible&&C.lod===B);return Q.length>0&&Q.every(C=>C.state==="loaded")}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(wB)}setImageSourcePolicy(A,I){if(I!==mg)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,P.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const B=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(B)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),s=Math.max(0,Math.min(i,this.policy_.lod.min)),G=Math.max(s,Math.min(i,this.policy_.lod.max)),w=DI(E,s,G);w!==this.currentLOD_&&(this.currentLOD_=w)}isChunkChannelInSlice(A,I){return I.c===void 0?!0:I.c.length===0?!1:I.c.includes(A.chunkIndex.c)}updateChunksAtTimeIndex(A,I,B,Q){const C=this.getPaddedBounds(B),E=this.store_.getChunksAtTime(A),i=this.fallbackLOD();for(const s of E){const G=s.lod===this.currentLOD_,w=s.lod===i;if(!G&&!w)continue;const c=this.isChunkChannelInSlice(s,I);if(!c)continue;const L=this.isChunkWithinBounds(s,B),Y=!L&&c&&G&&this.isChunkWithinBounds(s,C),K=L&&c,e=this.computePriority(w,G,L,Y,c);if(e!==null){const M=this.squareDistance2D(s,Q);this.chunkViewStates_.set(s,{visible:K,prefetch:Y,priority:e,orderKey:M})}}}markTimeChunksForPrefetchImage(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),s=this.policy_.priorityMap.prefetchTime;for(let G=A+1;G<=E;++G)for(const w of this.store_.getChunksAtTime(G)){if(w.lod!==i||!this.isChunkChannelInSlice(w,I)||!this.isChunkWithinBounds(w,B))continue;const c=this.squareDistance2D(w,Q),L=DI(c/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),Y=G-A+L;this.chunkViewStates_.set(w,{visible:!1,prefetch:!0,priority:s,orderKey:Y})}}markTimeChunksForPrefetchVolume(A,I){const B=this.store_.dimensions.t?.lods[0].size??1,Q=Math.min(B-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime;for(let i=A+1;i<=Q;++i)for(const s of this.store_.getChunksAtTime(i)){if(s.lod!==C||!this.isChunkChannelInSlice(s,I))continue;const G=i-A;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:E,orderKey:G})}}computePriority(A,I,B,Q,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&B?E.fallbackVisible:I&&B?E.visibleCurrent:A?E.fallbackBackground:I&&Q?E.prefetchSpace:null}isChunkWithinBounds(A,I){const B=new iI(DA(A.offset.x,A.offset.y,A.offset.z),DA(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));return iI.intersects(B,I)}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const w=I.lods[this.currentLOD_];return[w.translation,w.translation+w.size*w.scale]}const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),s=B.chunkSize,G=Math.max(0,Math.min(Math.floor(i/s),Math.ceil(Q/s)-1));return[E+G*s*C,E+(G+1)*s*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!FB(this.lastViewBounds2D_.min,A.min)||!FB(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!EE(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!FB(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,B)=>I===A[B])}getPaddedBounds(A){const I=this.store_.dimensions,B=I.x.lods[this.currentLOD_],Q=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=B.chunkSize*B.scale*this.policy_.prefetch.x,i=Q.chunkSize*Q.scale*this.policy_.prefetch.y;let s=0;return C&&(s=C.chunkSize*C.scale*this.policy_.prefetch.z),new iI(DA(A.min[0]-E,A.min[1]-i,A.min[2]-s),DA(A.max[0]+E,A.max[1]+i,A.max[2]+s))}squareDistance2D(A,I){const B={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},Q=B.x-I[0],C=B.y-I[1];return Q*Q+C*C}}function wB(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class dE{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:B}=this.getAndValidateChannelDimension();this.chunks_=Array.from({length:I},()=>[]);for(let Q=0;Q<I;++Q){const C=this.chunks_[Q];for(let E=0;E<this.dimensions_.numLods;++E){const i=this.dimensions_.x.lods[E],s=this.dimensions_.y.lods[E],G=this.dimensions_.z?.lods[E],w=i.chunkSize,c=s.chunkSize,L=G?.chunkSize??1,Y=Math.ceil(i.size/w),K=Math.ceil(s.size/c),e=Math.ceil((G?.size??1)/L);for(let M=0;M<B;++M)for(let l=0;l<Y;++l){const V=i.translation+l*i.chunkSize*i.scale;for(let W=0;W<K;++W){const O=s.translation+W*s.chunkSize*s.scale;for(let m=0;m<e;++m){const T=G!==void 0?G.translation+m*L*G.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(w,i.size-l*w),y:Math.min(c,s.size-W*c),z:Math.min(L,(G?.size??1)-m*L),c:1},rowAlignmentBytes:1,chunkIndex:{x:l,y:W,z:m,c:M,t:Q},scale:{x:i.scale,y:s.scale,z:G?.scale??1},offset:{x:V,y:O,z:T}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:eE(this.dimensions_.t.lods[0],A.t)}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 qE(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[B,Q]of I.chunkViewStates)A.add(B);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,B=!1,Q=null,C=null;for(const G of this.views_){const w=G.chunkViewStates.get(A);w&&(w.visible&&(I=!0),w.prefetch&&(B=!0),w.priority!==null&&(Q===null||w.priority<Q)&&(Q=w.priority,C=w.orderKey),!w.visible&&!w.prefetch&&w.priority===null&&G.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=B,A.priority=Q,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,P.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let B=1;B<this.dimensions_.numLods;B++){const Q=A.lods[B].scale/A.lods[B-1].scale,C=I.lods[B].scale/I.lods[B-1].scale;if(!Wg(Q,2,.02)||!Wg(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${B-1} → ${B}: expected (2× in X and Y), but got (${Q.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[B-1].scale}, ${I.lods[B-1].scale}] → [${A.lods[B].scale}, ${I.lods[B].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const B=this.dimensions_.t?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${B.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&&P.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 B=this.dimensions_.c?.lods[A-1];if(B&&I.size!==B.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${B.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class fE{stores_=new Map;pendingStores_=new Map;queue_=new ME;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 B=this.pendingStores_.get(A);if(B)return B;const C=(async()=>{const i=await A.open();return new dE(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 B=I.updateAndCollectChunkChanges();for(const Q of B)Q.priority===null?this.queue_.cancel(Q):Q.state==="queued"&&this.queue_.enqueue(Q,C=>I.loadChunkData(Q,C))}this.queue_.flush();for(const[A,I]of this.stores_)I.canDispose()&&this.stores_.delete(A)}}var Fg=function(g=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(c){c.preventDefault(),Q(++A%I.children.length)},!1);function B(c){return I.appendChild(c.dom),c}function Q(c){for(var L=0;L<I.children.length;L++)I.children[L].style.display=L===c?"block":"none";A=c}var C=(performance||Date).now(),E=C,i=0,s=B(new Fg.Panel("FPS","#0ff","#002",g)),G=B(new Fg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var w=B(new Fg.Panel("MB","#f08","#201",g));return Q(0),{REVISION:16,dom:I,addPanel:B,showPanel:Q,begin:function(){C=(performance||Date).now()},end:function(){i++;var c=(performance||Date).now();if(G.update(c-C,200),c>=E+1e3&&(s.update(i*1e3/(c-E),100),E=c,i=0,w)){var L=performance.memory;w.update(L.usedJSHeapSize/1048576,L.jsHeapSizeLimit/1048576)}return c},update:function(){C=this.end()},domElement:I,setMode:Q}};Fg.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),s=E(80*i*B),G=E(48*i*B),w=E(3*i*B),c=E(2*i*B),L=E(3*i*B),Y=E(15*i*B),K=E(74*i*B),e=E(30*i*B),M=document.createElement("canvas");M.width=s,M.height=G,M.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var l=M.getContext("2d");return l.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",l.textBaseline="top",l.fillStyle=I,l.fillRect(0,0,s,G),l.fillStyle=A,l.fillText(g,w,c),l.fillRect(L,Y,K,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(L,Y,K,e),{dom:M,update:function(V,W){Q=Math.min(Q,V),C=Math.max(C,V),l.fillStyle=I,l.globalAlpha=1,l.fillRect(0,0,s,Y),l.fillStyle=A,l.fillText(E(V)+" "+g+" ("+E(Q)+"-"+E(C)+")",w,c),l.drawImage(M,L+i,Y,K-i,e,L,Y,K-i,e),l.fillRect(L+K-i,Y,i,e),l.fillStyle=I,l.globalAlpha=.9,l.fillRect(L+K-i,Y,i,E((1-V/W)*e))}}};function lE({scale:g}={scale:1.5}){const A=new Fg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class tQ{layers_=[];callbacks_=[];context_;constructor(A){this.context_=A}partitionLayers(){const A=[],I=[];for(const B of this.layers)B.transparent?I.push(B):A.push(B);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((B,Q)=>Q!==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 SB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function pE(g){return SB.includes(g)}class WE{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 mE{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){P.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,SB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){P.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,SB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!pE(A.type)){P.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new WE(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class cQ{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 mE(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=HA(B,Q);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const B of this.layerManager.layers)if(B.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(),B=A.getBoundingClientRect(),Q=window.devicePixelRatio||1,C=B.left*Q,E=B.top*Q,i=B.height*Q,s=I.x-C,G=I.y-E,w=Math.floor(s),c=Math.floor(i-G-I.height),L=Math.floor(I.width),Y=Math.floor(I.height);return new PA(HA(w,c),HA(w+L,c+Y))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return DA(2*(B-C.x)/C.width-1,2*(Q-C.y)/C.height-1,I)}clientToWorld(A,I=0){const B=this.clientToClip(A,I);return this.camera.clipToWorld(B)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,B=A.left*I,Q=A.top*I,C=A.width*I,E=A.height*I;return new PA(HA(B,Q),HA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){P.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const B=A/I;this.camera.setAspectRatio(B)}}function RB(g,A){for(const I of A){if(I.id===g.id)throw new Error(`Duplicate viewport ID "${g.id}". Each viewport must have a unique ID.`);if(I.element===g.element){const B=g.element.tagName.toLowerCase()+(g.element.id?`#${g.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${g.id}" both use ${B}`)}}}function TE(g){for(let A=0;A<g.length;A++)RB(g[A],g.slice(0,A))}function NB(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??DQ("viewport"),layerManager:new tQ(I)}});return TE(B),B.map(Q=>new cQ(Q))}class xE{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){P.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_){P.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)){P.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){P.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class ZE{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){this.canvas=A.canvas,this.renderer_=new NQ(this.canvas),this.chunkManager_=new fE,this.context_={chunkManager:this.chunkManager_},this.viewports_=NB(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=lE());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new xE(I,()=>{this.renderer_.updateSize();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]=NB([A],this.canvas,this.context_);return RB(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),P.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(P.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),P.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(P.info("Idetik","Idetik runtime starting"),this.running)P.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;for(const B of this.viewports_)B.cameraControls?.onUpdate(I),this.renderer_.render(B);this.chunkManager_.update();for(const B of this.overlays)B.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(B=>this.animate(B))}stop(){if(P.info("Idetik","Idetik runtime stopping"),!this.running)P.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 bE extends TI{constructor(A){if(super(),A.primitive!="triangles"){P.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){P.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,B=[],Q=(E,i)=>{const s=Math.min(E,i),G=Math.max(E,i);I.has({i0:s,i1:G})||(I.add({i0:s,i1:G}),B.push(s,G))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],s=C[E+1],G=C[E+2];Q(i,s),Q(s,G),Q(G,i)}this.indexData_=new Uint32Array(B)}}const uE=DA(0,1,0);class PE{dirty_=!0;matrix_=uA();rotation_=yB();translation_=NA();scale_=DA(1,1,1);addRotation(A){SE(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){NE(this.rotation_,A),this.dirty_=!0}get rotation(){return RE(this.rotation_)}addTranslation(A){yg(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){DB(this.translation_,A),this.dirty_=!0}get translation(){return gI(this.translation_)}addScale(A){DE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){DB(this.scale_,A),this.dirty_=!0}targetTo(A){GQ(this.translation_,A)&&(A=gI(A),A[2]+=FA);const I=CE(uA(),this.translation_,A,uE),B=_C(oQ(),I);FQ(this.rotation_,B),GB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return gI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return lg(uA(),this.matrix)}computeMatrix(){AE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class xI extends EB{wireframeEnabled=!1;wireframeColor=QA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new PE;geometry_=new TI;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const B=this.textures_[A];B!==void 0&&this.staleTextures_.push(B),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new bE(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 LI{normal;signedDistance;constructor(A=DA(0,1,0),I=0){this.normal=gI(A),this.signedDistance=I}set(A,I){this.normal=gI(A),this.signedDistance=I}signedDistanceToPoint(A){return hQ(this.normal,A)+this.signedDistance}normalize(){const A=iB(this.normal);if(A>0){const I=1/A;hg(this.normal,this.normal,I),this.signedDistance*=I}}}class LQ{planes_;constructor(A){this.planes_=[new LI(NA(),0),new LI(NA(),0),new LI(NA(),0),new LI(NA(),0),new LI(NA(),0),new LI(NA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=NA();this.planes_[0].set(cI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(cI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(cI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(cI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(cI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(cI(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const B of this.planes_)B.normalize()}intersectsWithBox3(A){const I=NA();for(const B of this.planes_){const Q=B.normal;if(I[0]=Q[0]>0?A.max[0]:A.min[0],I[1]=Q[1]>0?A.max[1]:A.min[1],I[2]=Q[2]>0?A.max[2]:A.min[2],B.signedDistanceToPoint(I)<0)return!1}return!0}}class JQ extends xI{projectionMatrix_=uA();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 DA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return DA(A[4],A[5],A[6])}get frustum(){return new LQ(sg(uA(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=pg(A[0],A[1],A[2],1),B=lg(uA(),this.projectionMatrix_),Q=Gg(mI(),I,B);GE(Q,Q,1/Q[3]);const C=Gg(mI(),Q,this.transform.matrix);return DA(C[0],C[1],C[2])}}const YQ=1.77,rQ=128,KQ=128/YQ;class VE extends JQ{width_=rQ;height_=KQ;viewportAspectRatio_=YQ;viewportSize_=[rQ,KQ];constructor(A,I,B,Q,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,Q,B),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,B,Q){this.width_=Math.abs(I-A),this.height_=Math.abs(Q-B),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(B+Q);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=pg(-1,-1,0,1),I=pg(1,1,0,1);const B=sg(uA(),this.projectionMatrix,this.viewMatrix),Q=lg(uA(),B);return A=Gg(mI(),A,Q),I=Gg(mI(),I,Q),new PA(HA(A[0],A[1]),HA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,B=A/I;let Q=.5*A,C=.5*I;this.viewportAspectRatio_>B?Q*=this.viewportAspectRatio_/B:C*=B/this.viewportAspectRatio_,this.viewportSize_=[2*Q,2*C],QE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const OE=60,XE=1.77,Tg=.1,UB=180-Tg;class vE extends JQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=OE,aspectRatio:B=XE,near:Q=.1,far:C=1e4,position:E=DA(0,0,0)}=A;if(I<Tg||I>UB)throw new Error(`Invalid field of view: ${I}, must be in [${Tg}, ${UB}] degrees`);super(),this.fov_=I,this.aspectRatio_=B,this.near_=Q,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(Tg,Math.min(UB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){gE(this.projectionMatrix_,zC(this.fov),this.aspectRatio_,this.near_,this.far_)}}const MQ=0;class jE{camera_;dragActive_=!1;dragStart_=NA();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 B=gI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=sB(NA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==MQ||(this.dragStart_=gI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=sB(NA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==MQ||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class kB{radius;phi;theta;constructor(A,I,B){this.radius=A,this.phi=I,this.theta=B}toVec3(){const A=Math.cos(this.theta);return DA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const tB=-1,nQ=0,zE=1,HQ=.009,_E=.001,$E=9e-4,Ai=.5,Ii=60;class gi{camera_;orbitVelocity_=new kB(0,0,0);panVelocity_=NA();currPos_;currCenter_=NA();dampingFactor_;currMouseButton_=tB;constructor(A,I){this.camera_=A,this.currPos_=new kB(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&DB(this.currCenter_,I.target),this.dampingFactor_=DI(I?.dampingFactor??Ai,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&&GQ(this.panVelocity_,DA(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,yg(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-FA;this.currPos_.theta=DI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const B=Math.pow(1-this.dampingFactor_,A*Ii);this.orbitVelocity_.phi*=B,this.orbitVelocity_.theta*=B,this.orbitVelocity_.radius*=B,hg(this.panVelocity_,this.panVelocity_,B),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==tB)return;const I=A.event,B=I.movementX??0,Q=I.movementY??0,C=this.currMouseButton_===nQ&&!I.shiftKey,E=this.currMouseButton_===nQ&&I.shiftKey||this.currMouseButton_===zE;C&&this.orbit(B,Q),E&&this.pan(B,Q)}onWheel(A){const I=A.event;I.preventDefault();const B=I.deltaY??0;this.zoom(B)}onPointerEnd(A){this.currMouseButton_=tB;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*HQ,this.orbitVelocity_.theta+=I*HQ}pan(A,I){const B=this.currPos_.radius*_E,Q=NA();aQ(Q,Q,this.camera_.right,A),aQ(Q,Q,this.camera_.up,I),hg(Q,Q,B),sB(this.panVelocity_,this.panVelocity_,Q)}zoom(A){this.orbitVelocity_.radius+=A*$E}updateCamera(){const A=yg(NA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<FA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<FA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<FA&&(this.orbitVelocity_.radius=0),iB(this.panVelocity_)<FA&&aE(this.panVelocity_)}}class wg{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&P.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=DI(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&P.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=DI(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(B=>B(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 Bi extends TI{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}),this.addAttribute({type:"path_proportion",itemSize:1,offset:10*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*11);let B=0,Q=0;const C=A.reduce((E,i,s)=>E+sQ(i,A[s+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const s=A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2];const G=A[E-1]??A[E];I[B++]=G[0],I[B++]=G[1],I[B++]=G[2];const w=A[E+1]??A[E];I[B++]=w[0],I[B++]=w[1],I[B++]=w[2],I[B++]=i,I[B++]=Q}Q+=sQ(A[E],A[E+1]??A[E])/C}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let B=0;for(let Q=0;Q<2*A;Q+=2)I[B++]=Q+0,I[B++]=Q+1,I[B++]=Q+2,I[B++]=Q+2,I[B++]=Q+1,I[B++]=Q+3;return I}}class Qi extends xI{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=QA.from(I),this.width_=B,this.taperOffset_=Q??this.taperOffset_,this.taperPower_=C??this.taperPower_,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=QA.from(A)}get width(){return this.width_}set width(A){this.width_=A}get taperOffset(){return this.taperOffset_}set taperOffset(A){this.taperOffset_=A}get taperPower(){return this.taperPower_}set taperPower(A){this.taperPower_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width,TaperOffset:this.taperOffset,TaperPower:this.taperPower}}}class Ci extends wg{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(cB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(cB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(cB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function cB(g){const{end:A,width:I,color:B}=g,Q=new Bi([[0,0,0],A]);return new Qi({geometry:Q,color:B,width:I})}function Ei(g){return g===1||g===2||g===4||g===8}function ZI(g){if(g instanceof Int8Array)return"byte";if(g instanceof Int16Array)return"short";if(g instanceof Int32Array)return"int";if(g instanceof Uint8Array)return"unsigned_byte";if(g instanceof Uint16Array)return"unsigned_short";if(g instanceof Uint32Array)return"unsigned_int";if(g instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function ii(g){if(g.dataFormat==="rgb"||g.dataFormat==="rgba")return[0,1];switch(g.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 LB extends EB{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"}}const eQ=32;function Sg(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=QA.WHITE:I=QA.from(I),g!==null?B=Di(B,g):B===void 0&&(P.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function JB(g,A){if(A.length>eQ)throw new Error(`Maximum number of channels is ${eQ}`);if(g?.type==="Texture2DArray"){const I=g.depth;if(A.length!==I)throw new Error(`Number of channels (${A.length}) must match depth of texture (${I}).`)}return A.map(I=>Sg(g,I))}function qQ(g,A){if(g&&g.length!==A)throw new Error(`channelProps length (${g.length}) must match source channel count (${A}).`)}function Di(g,A){if(g===void 0)return ii(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class dQ extends TI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,s=Q,G=i+1,w=s+1,c=A/i,L=I/s;for(let Y=0;Y<w;++Y){const K=Y*L;for(let e=0;e<G;++e){const M=e*c,l=e/i,V=Y/s,W=[M,K,0],O=[0,0,1],m=[l,V];C.push(...W,...O,...m)}}for(let Y=0;Y<s;++Y)for(let K=0;K<i;++K){const e=K+G*Y,M=K+G*(Y+1),l=K+1+G*(Y+1),V=K+1+G*Y;E.push(e,M,V),E.push(M,l,V)}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 oi extends xI{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new dQ(A,I,1,1),this.setTexture(0,B),this.channels_=JB(B,Q),this.programName=ai(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=JB(this.textures[0],A)}setChannelProperty(A,I,B){const Q=Sg(this.textures[0],{...this.channels_[A],[I]:B});this.channels_[A]=Q}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");if(A.type==="Texture2D"){const{color:I,contrastLimits:B}=this.channels_[0]??Sg(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0]),ChannelCount:1}}else{const I=[],B=[],Q=[],C=[];return this.channels_.forEach(E=>{I.push(E.visible),B.push(...E.color.rgb),Q.push(-E.contrastLimits[0]),C.push(1/(E.contrastLimits[1]-E.contrastLimits[0]))}),{ImageSampler:0,"Visible[0]":I,"Color[0]":B,"ValueOffset[0]":Q,"ValueScale[0]":C,ChannelCount:this.channels_.length}}}}function ai(g){if(g.type==="Texture2D")return si(g.dataType);if(g.type==="Texture2DArray")return yi(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function si(g){switch(g){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function yi(g){switch(g){case"byte":case"int":case"short":return"intScalarImageArray";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImageArray";case"float":return"floatScalarImageArray"}}class xg extends LB{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=ZI(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=A.length/(I*B)}get type(){return"Texture2DArray"}set data(A){this.data_=A,this.needsUpdate=!0}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===B)return;const Q=A.shape.x,C=A.shape.y,E=B.length/(Q*C);if(this.width!=Q||this.height!=C||this.depth_!=E||this.dataType!=ZI(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new xg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function fQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return HA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=HA(C.clientX,C.clientY);if(UE(A,E)<Q){if(!B)return null;const s=g.worldPos;if(s){const G=I(s);G!==null&&B({world:s,value:G})}return null}return A}case"pointercancel":return null;default:return A}}class YB{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&P.debug("RenderablePool","Renderable object acquired"),B}release(A,I){let B=this.bins_.get(A);B||(B=[],this.bins_.set(A,B)),B.push(I),P.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class rB extends wg{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new YB;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new QA(.6,.3,.3),new QA(.3,.6,.4),new QA(.4,.4,.7),new QA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:B,channelProps:Q,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.channelProps_=Q,this.initialChannelProps_=Q,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(qQ(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.sliceCoords_)&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getImageForChunk(Q);this.visibleChunks_.set(Q,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_>rB.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=fQ(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,mg))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=DI(Q,0,A.shape.z-1);Wg(B,C,1+1e-6)||P.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 B=this.pool_.acquire(Zg(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),B.setChannelProps(this.getChannelPropsForChunk(A)),B):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new oi(A.shape.x,A.shape.y,xg.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){P.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[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=aB(NA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[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,s=E*A.shape.x+C;return i[s]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,B)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[B.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,B)=>{I.setChannelProps(this.getChannelPropsForChunk(B))}),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)}getVisibleDataRange(){return kQ(this.visibleChunks_.keys())}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(Zg(I),B),this.visibleChunks_.delete(I))}}}function Zg(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hi extends TI{constructor(A,I,B,Q,C,E){super();const i=[],s=[],G=Math.floor(Q),w=Math.floor(C),c=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,c,w,1,i,s),this.buildFace("z","y","x",1,-1,B,I,A,c,w,-1,i,s),this.buildFace("x","z","y",1,1,A,B,I,G,c,1,i,s),this.buildFace("x","z","y",1,-1,A,B,I,G,c,-1,i,s),this.buildFace("x","y","z",1,-1,A,I,B,G,w,1,i,s),this.buildFace("x","y","z",-1,-1,A,I,B,G,w,-1,i,s),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(s),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,B,Q,C,E,i,s,G,w,c,L,Y){const K=E/G,e=i/w,M=E/2,l=i/2,V=s/2*c,W=G+1,O=w+1,m=L.length/8;for(let T=0;T<O;T++){const CA=-l+T*e;for(let iA=0;iA<W;iA++){const BA=-M+iA*K,hA={x:0,y:0,z:0};hA[A]=BA*Q,hA[I]=CA*C,hA[B]=V;const GA={x:0,y:0,z:0};GA[B]=c;const eA=iA/G,kA=1-T/w;L.push(hA.x,hA.y,hA.z,GA.x,GA.y,GA.z,eA,kA)}}for(let T=0;T<w;T++)for(let CA=0;CA<G;CA++){const iA=m+CA+W*T,BA=m+CA+W*(T+1),hA=m+(CA+1)+W*(T+1),GA=m+(CA+1)+W*T;Y.push(iA,BA,GA,BA,hA,GA)}}}class bI extends LB{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=ZI(A),this.data_=A,this.width_=I,this.height_=B,this.depth_=Q}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!=ZI(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 B=new bI(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class Gi extends xI{voxelScale=DA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new hi(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,B=this.channelToTextureIndex_.get(I);B!==void 0?this.updateChannelTexture(B,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const B=bI.createWithChunk(I),Q=this.textures.length;this.setTexture(Q,B),this.channelToTextureIndex_.set(A,Q);const C=Fi(B.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: ${B.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const B=this.textures[A];if(!(B instanceof bI)){const Q=bI.createWithChunk(I);this.setTexture(A,Q);return}B.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],B=[0,0,0,0],Q=[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 s=this.channelToTextureIndex_.get(i);if(s===void 0||!this.loadedChannels_.has(i))continue;const G=this.textures[s],w=Sg(G,this.channels_[i]||{});if(!w.visible)continue;const c=C.length;I[c*3]=w.color.rgb[0],I[c*3+1]=w.color.rgb[1],I[c*3+2]=w.color.rgb[2],C.push(s),B[c]=-w.contrastLimits[0],Q[c]=1/(w.contrastLimits[1]-w.contrastLimits[0]),A[c]=1}return C.reduce((i,s,G)=>(i[`Channel${G}Sampler`]=s,i),{Visible:A,"Color[0]":I,ValueOffset:B,ValueScale:Q,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const B=this.channelToTextureIndex_.get(A);if(B!==void 0)return this.textures[B]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=JB(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,B){const Q=Sg(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:B});this.channels_[A]=Q}}function Fi(g){switch(g){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function wi(g,A){const I=A.position,B=NA(),Q=NA();return g.sort((C,E)=>{yg(B,C.boundingBox.max,C.boundingBox.min),hg(B,B,.5),yg(Q,E.boundingBox.max,E.boundingBox.min),hg(Q,Q,.5);const i=yQ(I,B),s=yQ(I,Q);return i-s}),g}const Si=2;class Ri extends wg{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new YB;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;visibleChunks_=[];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,mg))}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)}getVisibleDataRange(){return kQ(this.visibleChunks_)}constructor({source:A,sliceCoords:I,policy:B,channelProps:Q}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=B,this.initialChannelProps_=Q,this.channelProps_=Q,this.setState("initialized")}getOrCreateVolume(A,I){const B=this.currentVolumes_.get(A);if(B){for(const E of I)B.updateVolumeWithChunk(E);return B}const Q=ki(I[0]),C=this.pool_.acquire(Q)??new Gi;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,Q);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_),qQ(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(this.sliceCoords_);this.visibleChunks_=A;const I=this.sliceCoords_.t??-1,B=Ui(A);if(this.lastLoadedTime_!==I||B.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)B.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of B){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 B={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([B.x,B.y,B.z]),cI(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const Q={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+Q.x,I.offset.y+Q.y,I.offset.z+Q.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?Si:1,this.updateChunks(),wi(this.objects,A.viewport.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function Ni(g){const{x:A,y:I,z:B,t:Q}=g.chunkIndex;return`${A}:${I}:${B}:${Q}`}function Ui(g){const A=new Map;for(const I of g){const B=Ni(I);let Q=A.get(B);Q||(Q=[],A.set(B,Q)),Q.push(I)}return A}function ki(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class Rg extends LB{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=ZI(A),this.data_=A,this.width_=I,this.height_=B}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 B=I??A.data;if(!B)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==B){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=ZI(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new Rg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const ti=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function ci(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!ti.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class Li extends xI{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new dQ(A.width,A.height,1,1),this.setTexture(0,ci(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),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(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new Rg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,QA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,QA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new Rg(C,Q,2)}}const Ji=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Yi(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,QA.from(I)]))}function ri(g){return g=g??Ji,g.map(QA.from)}class lQ{lookupTable;cycle;constructor(A={}){this.lookupTable=Yi(A.lookupTable),this.cycle=ri(A.cycle)}}class KB extends wg{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new YB;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:B,colorMap:Q={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=B,this.sliceCoords_=I,this.colorMap_=new lQ(Q),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.sliceCoords_)&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=new Set(A),B=Array.from(this.visibleChunks_.keys()).filter(Q=>!I.has(Q));this.releaseAndRemoveChunks(B),this.clearObjects();for(const Q of A){if(Q.state!=="loaded")continue;const C=this.getLabelForChunk(Q);this.visibleChunks_.set(Q,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>KB.STALE_PRESENTATION_MS_}resliceIfZChanged(){const A=this.sliceCoords_.z;if(!(A===void 0||this.zPrevPointWorld_===A)){for(const[I,B]of this.visibleChunks_){if(I.state!=="loaded"||!I.data)continue;const Q=this.slicePlane(I,A);Q&&B.textures[0].updateWithChunk(I,Q)}this.zPrevPointWorld_=A}}onEvent(A){this.pointerDownPos_=fQ(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 lQ(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,mg))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const[B,Q]of this.visibleChunks_){if(B.lod!==I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}for(const[B,Q]of this.visibleChunks_){if(B.lod===I)continue;const C=this.getValueFromChunk(B,Q,A);if(C!==null)return C}return null}getValueFromChunk(A,I,B){if(!A.data)return null;const Q=aB(NA(),B,I.transform.inverse),C=Math.floor(Q[0]),E=Math.floor(Q[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,s=E*A.shape.x+C;return i[s]}return null}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=DI(Q,0,A.shape.z-1);Wg(B,C,1+1e-6)||P.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 B=this.pool_.acquire(Zg(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForLabel(A)),this.updateLabelChunk(B,A),B.setColorMap(this.colorMap_),B.setSelectedValue(this.selectedValue_),B):this.createLabel(A)}createLabel(A){const I=new Li({width:A.shape.x,height:A.shape.y,imageData:Rg.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){P.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 B=this.visibleChunks_.get(I);B&&(this.pool_.release(Zg(I),B),this.visibleChunks_.delete(I))}}}function pQ(g,A,I,B={}){return A!==void 0&&I!==void 0&&(B={...B,headers:{...B.headers,Range:`bytes=${A}-${A+I-1}`}}),fetch(g,B)}function Ki(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function WQ(g,A){const I=typeof g=="string"?new URL(g):g;I.pathname.endsWith("/")||(I.pathname+="/");const B=new URL(A.slice(1),I);return B.search=I.search,B}async function mQ(g){if(g.status!==404){if(g.status===200||g.status===206)return new Uint8Array(await g.arrayBuffer());throw new Error(`Unexpected response status ${g.status} ${g.statusText}`)}}async function Mi(g,A,I,B){if(B)return fetch(g,{...I,headers:{...I.headers,Range:`bytes=-${A}`}});let Q=await fetch(g,{...I,method:"HEAD"});if(!Q.ok)return Q;let C=Q.headers.get("Content-Length"),E=Number(C);return pQ(g,E-A,E,I)}class uI{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return Ki(this.#A,A)}async get(A,I={}){let B=WQ(this.url,A).href,Q=await fetch(B,this.#g(I));return mQ(Q)}async getRange(A,I,B={}){let Q=WQ(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await Mi(Q,I.suffixLength,C,this.#I):E=await pQ(Q,I.offset,I.length,C),mQ(E)}}class TQ{#A;constructor(A,I,B){typeof A=="number"?this.#A=new Uint8Array(A):A instanceof ArrayBuffer?this.#A=new Uint8Array(A,I,B):this.#A=new Uint8Array(Array.from(A,Q=>Q?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 MB{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q=Q*A),this._data=new Uint8Array(I,B,Q);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 B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class Ng{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new Ng(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 B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Ug(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function xQ(g,A){const I=A/2,B=A-1;let Q=0;for(let C=0;C<g.length;C+=A)for(let E=0;E<I;E+=1)Q=g[C+E],g[C+E]=g[C+B-E],g[C+B-E]=Q}function ZQ(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?Ng:MB).bind(null,Number(Q))}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:TQ}[g];return rA(I,`Unknown or unsupported data_type: ${g}`),I}function JI(g,A){const I=g.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),rA(I===A.length,"Order length must match the number of dimensions.");let B=1,Q=new Array(I);for(let C=A.length-1;C>=0;C--)Q[A[C]]=B,B*=g[A[C]];return Q}function ni({name:g,configuration:A}){if(g==="default"){const I=A?.separator??"/";return B=>["c",...B].join(I)}if(g==="v2"){const I=A?.separator??".";return B=>B.join(I)||"0"}throw new Error(`Unknown chunk key encoding: ${g}`)}function Hi(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(/^([<|>])(.*)$/);rA(A,`Invalid dtype: ${g}`);let[,I,B]=A,Q={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);return rA(Q,`Unsupported or unknown dtype: ${g}`),I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function ei(g,A={}){let I=[],B=Hi(g.dtype);g.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}}),"endian"in B&&B.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}});for(let{id:Q,...C}of g.filters??[])I.push({name:Q,configuration:C});if(g.compressor){let{id:Q,...C}=g.compressor;I.push({name:Q,configuration:C})}return{zarr_format:3,node_type:"array",shape:g.shape,data_type:B.data_type,chunk_grid:{name:"regular",configuration:{chunk_shape:g.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:g.dimension_separator??"."}},codecs:I,fill_value:g.fill_value,attributes:A}}function qi(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function di(g,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return g===A;let I=g==="bool";if(A==="boolean")return I;let B=g.startsWith("v2:U")||g.startsWith("v2:S");if(A==="string")return B;let Q=g==="int64"||g==="uint64";if(A==="bigint")return Q;let C=g==="v2:object";return A==="object"?C:!B&&!Q&&!I&&!C}function fi(g){return g?.name==="sharding_indexed"}function bQ(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}function uQ(g,...A){if(!A.some(I=>g instanceof I))throw g}function rA(g,A=""){if(!g)throw new Error(A)}async function PQ(g,{format:A,signal:I}){const B=g instanceof Response?g:new Response(g);rA(B.body,"Response does not contain body.");try{return await new Response(B.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}class nB{kind="array_to_array";constructor(A,I){rA(A.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(A,I){return new nB(A,I)}encode(A){throw new Error("`BitroundCodec.encode` is not implemented. Please open an issue at https://github.com/manzt/zarrita.js/issues.")}decode(A){return A}}const VQ=li();function li(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function OQ(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class bg{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=ZQ(I.data_type),this.#Q=I.shape,this.#A=JI(I.shape,"C");const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new bg(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return VQ&&this.#B==="big"&&xQ(I,OQ(this.#I)),I}decode(A){return VQ&&this.#B==="big"&&xQ(A,OQ(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class HB{kind="bytes_to_bytes";static fromConfig(){return new HB}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}class eB{kind="bytes_to_bytes";static fromConfig(A){return new eB}encode(A){throw new Error("Gzip encoding is not enabled by default. Please register a custom codec with `numcodecs/gzip`.")}async decode(A){const I=await PQ(A,{format:"gzip"});return new Uint8Array(I)}}function pi(g,A){return rA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),rA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),rA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Wi(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class qB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:B=!1,ensure_ascii:Q=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:s,strict:G=!0}=A;let w=A.separators;w||(s?w=[", ",": "]:w=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:s,separators:w,sort_keys:i},this.#I={strict:G}}static fromConfig(A){return new qB(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;rA(B==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const s=[];rA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||s.push(pi),i&&s.push(Wi);const G=Array.from(A.data);G.push("|O"),G.push(A.shape);let w;s.length&&(w=(L,Y)=>{let K=Y;for(let e of s)K=e(L,K);return K});let c=JSON.stringify(G,w,I);return Q&&(c=c.replace(/[\u007F-\uFFFF]/g,L=>{const Y=`0000${L.charCodeAt(0).toString(16)}`;return`\\u${Y.substring(Y.length-4)}`})),new TextEncoder().encode(c)}decode(A){const{strict:I}=this.#I;rA(I,"JsonCodec does not yet support non-strict decoding.");const B=Ug(A),Q=B.pop();B.pop(),rA(Q,"0D not implemented for JsonCodec.");const C=JI(Q,"C");return{data:B,shape:Q,stride:C}}}function XQ(g){return g instanceof TQ||g instanceof MB||g instanceof Ng?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function mi(g,A){let I;return g.data instanceof MB||g.data instanceof Ng?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:JI(g.shape,A)}}function Ti(g,A){let I=mi(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=XQ(g.data),i=XQ(I.data);for(let s=0;s<Q;s++){let G=0;for(let w=0;w<B;w++)G+=C[w]*I.stride[w];i[G]=E[s],C[0]+=1;for(let w=0;w<B;w++)if(C[w]===g.shape[w]){if(w+1===B)break;C[w]=0,C[w+1]+=1}}return I}function xi(g){let A=g.shape.length;return rA(A===g.stride.length,"Shape and stride must have the same length."),g.stride.map((I,B)=>({stride:I,index:B})).sort((I,B)=>B.stride-I.stride).map(I=>I.index)}function Zi(g,A){let I=xi(g);return rA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class dB{kind="array_to_array";#A;#I;constructor(A,I){let B=A.order??"C",Q=I.shape.length,C=new Array(Q),E=new Array(Q);if(B==="C")for(let i=0;i<Q;++i)C[i]=i,E[i]=i;else if(B==="F")for(let i=0;i<Q;++i)C[i]=Q-i-1,E[i]=Q-i-1;else C=B,C.forEach((i,s)=>{rA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=s});this.#A=C,this.#I=E}static fromConfig(A,I){return new dB(A,I)}encode(A){return Zi(A,this.#I)?A:Ti(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:JI(A.shape,this.#A)}}}class fB{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=JI(A,"C")}static fromConfig(A,I){return new fB(I.shape)}encode(A){throw new Error("Method not implemented.")}decode(A){let I=new TextDecoder,B=new DataView(A.buffer),Q=Array(B.getUint32(0,!0)),C=4;for(let E=0;E<Q.length;E++){let i=B.getUint32(C,!0);C+=4,Q[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:Q,shape:this.#A,stride:this.#I}}}class lB{kind="bytes_to_bytes";static fromConfig(A){return new lB}encode(A){throw new Error("Zlib encoding is not enabled by default. Please register a codec with `numcodecs/zlib`.")}async decode(A){const I=await PQ(A,{format:"deflate"});return new Uint8Array(I)}}function bi(){return new Map().set("blosc",()=>Promise.resolve().then(()=>No).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Jo).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>Ho).then(g=>g.default)).set("gzip",()=>eB).set("zlib",()=>lB).set("transpose",()=>dB).set("bytes",()=>bg).set("crc32c",()=>HB).set("vlen-utf8",()=>fB).set("json2",()=>qB).set("bitround",()=>nB)}const ui=bi();function pB(g){let A;return{async encode(I){A||(A=await vQ(g));for(const Q of A.array_to_array)I=await Q.encode(I);let B=await A.array_to_bytes.encode(I);for(const Q of A.bytes_to_bytes)B=await Q.encode(B);return B},async decode(I){A||(A=await vQ(g));for(let Q=A.bytes_to_bytes.length-1;Q>=0;Q--)I=await A.bytes_to_bytes[Q].decode(I);let B=await A.array_to_bytes.decode(I);for(let Q=A.array_to_array.length-1;Q>=0;Q--)B=await A.array_to_array[Q].decode(B);return B}}}async function vQ(g){let A=g.codecs.map(async C=>{let E=await ui.get(C.name)?.();return rA(E,`Unknown codec: ${C.name}`),{Codec:E,meta:C}}),I=[],B,Q=[];for await(let{Codec:C,meta:E}of A){let i=C.fromConfig(E.configuration,g);switch(i.kind){case"array_to_array":I.push(i);break;case"array_to_bytes":B=i;break;default:Q.push(i)}}return B||(rA(Pi(g),`Cannot encode ${g.data_type} to bytes without a codec`),B=bg.fromConfig({endian:"little"},g)),{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function Pi(g){return g.data_type!=="v2:object"}class kg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class WB extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}const jQ=18446744073709551615n;function Vi(g,A,I,B){rA(g.store.getRange,"Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((s,G)=>s/B.chunk_shape[G]),E=pB({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async s=>{let G=s.map((V,W)=>Math.floor(V/C[W])),w=g.resolve(I(G)).path,c;if(w in i)c=i[w];else{let V=4,W=16*C.reduce((m,T)=>m*T,1),O=await Q(w,{suffixLength:W+V});c=i[w]=O?await E.decode(O):null}if(c===null)return;let{data:L,shape:Y,stride:K}=c,e=s.map((V,W)=>V%Y[W]).reduce((V,W,O)=>V+W*K[O],0),M=L[e],l=L[e+1];if(!(M===jQ&&l===jQ))return Q(w,{offset:Number(M),length:Number(l)})}}class TA{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 TA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class mB extends TA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function zQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const ug=Symbol("zarrita.context");function Oi(g,A){let{configuration:I}=A.codecs.find(fi)??{},B={encode_chunk_key:ni(A.chunk_key_encoding),TypedArray:ZQ(A.data_type),fill_value:A.fill_value};if(I){let C=zQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:pB({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E){return JI(E,C)},get_chunk_bytes:Vi(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=zQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:pB({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C){return JI(C,Q)},async get_chunk_bytes(C,E){let i=B.encode_chunk_key(C),s=g.resolve(i).path;return g.store.get(s,E)}}}let Pg=class extends TA{kind="array";#A;[ug];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:bQ(B)},this[ug]=Oi(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[ug].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[ug],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,s)=>i*s,1),E=new B.TypedArray(C);return E.fill(B.fill_value),{data:E,shape:B.chunk_shape,stride:B.get_strides(B.chunk_shape)}}return B.codec.decode(Q)}is(A){return di(this.dtype,A)}},Vg=Xi();function Xi(){let g=new WeakMap;function A(I){let B=g.get(I)??{v2:0,v3:0};return g.set(I,B),B}return{increment(I,B){A(I)[B]+=1},version_max(I){let B=A(I);return B.v3>B.v2?"v3":"v2"}}}async function vi(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Ug(A):{}}async function ji(g,A={}){let I="store"in g?g:new TA(g),B={};return(A.attrs??!0)&&(B=await vi(I)),A.kind==="array"?_Q(I,B):A.kind==="group"?$Q(I,B):_Q(I,B).catch(Q=>(uQ(Q,kg),$Q(I,B)))}async function _Q(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new kg("v2 array",{cause:new WB(I)});return Vg.increment(g.store,"v2"),new Pg(g.store,g.path,ei(Ug(B),A))}async function $Q(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new kg("v2 group",{cause:new WB(I)});return Vg.increment(g.store,"v2"),new mB(g.store,g.path,qi(Ug(B),A))}async function zi(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new kg("v3 array or group",{cause:new WB(I)});let Q=Ug(B);return Q.node_type==="array"&&(Q.fill_value=bQ(Q)),Q.node_type==="array"?new Pg(A,g.path,Q):new mB(A,g.path,Q)}async function _i(g,A={}){let I="store"in g?g:new TA(g),B=await zi(I);if(Vg.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof Pg||A.kind==="group"&&B instanceof mB)return B;let Q=B instanceof Pg?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function XA(g,A={}){let I="store"in g?g.store:g,B=Vg.version_max(I),Q=B==="v2"?XA.v2:XA.v3,C=B==="v2"?XA.v3:XA.v2;return Q(g,A).catch(E=>(uQ(E,kg),C(g,A)))}XA.v2=ji,XA.v3=_i;async function $i(g,A){const I=A.split("/"),B=I.pop();if(!B)throw new Error("Invalid path");for(const Q of I)g=await g.getDirectoryHandle(Q);return g.getFileHandle(B)}class TB{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await $i(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function AD(){if(typeof window>"u")return;const g=window.location.hostname;if(!(g==="localhost"||g==="127.0.0.1"||g==="0.0.0.0"||g.startsWith("127."))){const I="S3FetchStore is only allowed in local development environments. ";throw new Error(I)}}class xB extends uI{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){AD(),super(A.url,{overrides:A.overrides,useSuffixRequest:A.useSuffixRequest}),this.credentials=A.credentials,this.region=A.region,this.overrides=A.overrides,this.useSuffixRequest=A.useSuffixRequest}async get(A,I){if(this.credentials&&this.region){const Q=`${this.url.toString().replace(/\/$/,"")}${A}`,C=await this.generateAuthHeaders(Q,"GET"),E={...I,headers:{...I?.headers,...C}};return super.get(A,E)}return super.get(A,I)}async getRange(A,I,B){if(this.credentials&&this.region){const C=`${this.url.toString().replace(/\/$/,"")}${A}`,E=await this.generateAuthHeaders(C,"HEAD"),i=await this.generateAuthHeaders(C,"GET"),s=globalThis.fetch,G=async(c,L)=>{const K=(L?.method||"GET")==="HEAD"?E:i,e={...L,headers:{...L?.headers,...K}};return s(c,e)},w=globalThis.fetch;globalThis.fetch=G;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=w}}return super.getRange(A,I,B)}async generateAuthHeaders(A,I="GET"){if(!this.credentials||!this.region)return{};const{accessKeyId:B,secretAccessKey:Q,sessionToken:C}=this.credentials,E=this.region,i="s3",s=this.getAmzDate(),G=s.slice(0,8),w=new URL(A),c=w.host,L=w.pathname,Y=w.search.slice(1),K=`host:${c}
|
|
461
461
|
x-amz-content-sha256:UNSIGNED-PAYLOAD
|
|
462
462
|
x-amz-date:${s}
|
|
463
463
|
`+(C?`x-amz-security-token:${C}
|