@idetik/core 0.7.6 → 0.7.7
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.d.ts +2 -1
- package/dist/index.js +32 -29
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +1 -1
- package/dist/index.umd.cjs.map +1 -1
- package/dist/types/src/core/chunk_store_view.d.ts +2 -1
- package/dist/types/src/core/chunk_store_view.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -408,7 +408,7 @@ void main() {
|
|
|
408
408
|
fragColor = vec4(color.rgb, alpha);
|
|
409
409
|
}`;const oE={projectedLine:{vertex:gE,fragment:BE},points:{vertex:QE,fragment:CE},wireframe:{vertex:EE,fragment:iE},floatScalarImage:{vertex:cI,fragment:cB},floatScalarImageArray:{vertex:cI,fragment:LB},intScalarImage:{vertex:cI,fragment:cB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:cI,fragment:LB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:cI,fragment:cB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:cI,fragment:LB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:cI,fragment:DE},floatVolume:{vertex:JB,fragment:rB},intVolume:{vertex:JB,fragment:rB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:JB,fragment:rB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},LQ={debug:10,info:20,warn:30,error:40},aE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function sE(){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 V{static logLevel_=sE()==="production"?"warn":"debug";static setLogLevel(A){V.logLevel_=A}static debug(A,I,...B){V.log("debug",A,I,...B)}static info(A,I,...B){V.log("info",A,I,...B)}static warn(A,I,...B){V.log("warn",A,I,...B)}static error(A,I,...B){V.log("error",A,I,...B)}static log(A,I,B,...Q){if(LQ[A]<LQ[V.logLevel_])return;const C=new Date().toISOString(),E=aE[A],i=`[${C}][${A.toUpperCase()}][${I}]`,o=[`${E}${i}`,B,...Q];switch(A){case"debug":console.debug(...o);break;case"info":console.info(...o);break;case"warn":console.warn(...o);break;case"error":console.error(...o);break}}}class yE{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_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(!GE.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]),V.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 hE=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,WebGL2RenderingContext.INT,WebGL2RenderingContext.FLOAT_VEC2,WebGL2RenderingContext.FLOAT_VEC3,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]:[],GE=new Set(hE),YB="#pragma inject_defines";class FE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=oE[A],Q=JQ(B.vertex,B.vertexDefines),C=JQ(B.fragment,B.fragmentDefines);I=new yE(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 JQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(YB))throw new Error(`Shader source does not contain "${YB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
410
410
|
`),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
|
|
411
|
-
${Q}`;return g.replace(YB,C)}const HA=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function rQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(HA[g&255]+HA[g>>8&255]+HA[g>>16&255]+HA[g>>24&255]+"-"+HA[A&255]+HA[A>>8&255]+"-"+HA[A>>16&15|64]+HA[A>>24&255]+"-"+HA[I&63|128]+HA[I>>8&255]+"-"+HA[I>>16&255]+HA[I>>24&255]+HA[B&255]+HA[B>>8&255]+HA[B>>16&255]+HA[B>>24&255]).toLowerCase()}class nB{uuid=rQ()}var oI=1e-6,JA=typeof Float32Array<"u"?Float32Array:Array,wE=Math.PI/180;function SE(g){return g*wE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function YQ(){var g=new JA(9);return JA!=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 RE(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 PA(){var g=new JA(16);return JA!=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 zg(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],y=A[7],G=A[8],L=A[9],k=A[10],r=A[11],K=A[12],f=A[13],M=A[14],d=A[15],u=I*i-B*E,x=I*o-Q*E,X=I*y-C*E,O=B*o-Q*i,Z=B*y-C*i,DA=Q*y-C*o,oA=G*f-L*K,EA=G*M-k*K,sA=G*d-r*K,yA=L*M-k*f,fA=L*d-r*f,YA=k*d-r*M,iA=u*YA-x*fA+X*yA+O*sA-Z*EA+DA*oA;return iA?(iA=1/iA,g[0]=(i*YA-o*fA+y*yA)*iA,g[1]=(Q*fA-B*YA-C*yA)*iA,g[2]=(f*DA-M*Z+d*O)*iA,g[3]=(k*Z-L*DA-r*O)*iA,g[4]=(o*sA-E*YA-y*EA)*iA,g[5]=(I*YA-Q*sA+C*EA)*iA,g[6]=(M*X-K*DA-d*x)*iA,g[7]=(G*DA-k*X+r*x)*iA,g[8]=(E*fA-i*sA+y*oA)*iA,g[9]=(B*sA-I*fA-C*oA)*iA,g[10]=(K*Z-f*X+d*u)*iA,g[11]=(L*X-G*Z-r*u)*iA,g[12]=(i*EA-E*yA-o*oA)*iA,g[13]=(I*yA-B*EA+Q*oA)*iA,g[14]=(f*x-K*O-M*u)*iA,g[15]=(G*O-L*x+k*u)*iA,g):null}function _g(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],y=A[6],G=A[7],L=A[8],k=A[9],r=A[10],K=A[11],f=A[12],M=A[13],d=A[14],u=A[15],x=I[0],X=I[1],O=I[2],Z=I[3];return g[0]=x*B+X*i+O*L+Z*f,g[1]=x*Q+X*o+O*k+Z*M,g[2]=x*C+X*y+O*r+Z*d,g[3]=x*E+X*G+O*K+Z*u,x=I[4],X=I[5],O=I[6],Z=I[7],g[4]=x*B+X*i+O*L+Z*f,g[5]=x*Q+X*o+O*k+Z*M,g[6]=x*C+X*y+O*r+Z*d,g[7]=x*E+X*G+O*K+Z*u,x=I[8],X=I[9],O=I[10],Z=I[11],g[8]=x*B+X*i+O*L+Z*f,g[9]=x*Q+X*o+O*k+Z*M,g[10]=x*C+X*y+O*r+Z*d,g[11]=x*E+X*G+O*K+Z*u,x=I[12],X=I[13],O=I[14],Z=I[15],g[12]=x*B+X*i+O*L+Z*f,g[13]=x*Q+X*o+O*k+Z*M,g[14]=x*C+X*y+O*r+Z*d,g[15]=x*E+X*G+O*K+Z*u,g}function NE(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 UE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=Q+Q,y=C+C,G=E+E,L=Q*o,k=Q*y,r=Q*G,K=C*y,f=C*G,M=E*G,d=i*o,u=i*y,x=i*G,X=B[0],O=B[1],Z=B[2];return g[0]=(1-(K+M))*X,g[1]=(k+x)*X,g[2]=(r-u)*X,g[3]=0,g[4]=(k-x)*O,g[5]=(1-(L+M))*O,g[6]=(f+d)*O,g[7]=0,g[8]=(r+u)*Z,g[9]=(f-d)*Z,g[10]=(1-(L+K))*Z,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function tE(g,A,I,B,Q){var C=1/Math.tan(A/2),E;return 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?(E=1/(B-Q),g[10]=(Q+B)*E,g[14]=2*Q*B*E):(g[10]=-1,g[14]=-2*B),g}var kE=tE;function cE(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),y=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*o,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*y,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*y,g[15]=1,g}var LE=cE;function JE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],y=B[2],G=Q-I[0],L=C-I[1],k=E-I[2],r=G*G+L*L+k*k;r>0&&(r=1/Math.sqrt(r),G*=r,L*=r,k*=r);var K=o*k-y*L,f=y*G-i*k,M=i*L-o*G;return r=K*K+f*f+M*M,r>0&&(r=1/Math.sqrt(r),K*=r,f*=r,M*=r),g[0]=K,g[1]=f,g[2]=M,g[3]=0,g[4]=L*M-k*f,g[5]=k*K-G*M,g[6]=G*f-L*K,g[7]=0,g[8]=G,g[9]=L,g[10]=k,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function FA(){var g=new JA(3);return JA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function XA(g){var A=new JA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function nQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function CA(g,A,I){var B=new JA(3);return B[0]=g,B[1]=A,B[2]=I,B}function wg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function ZI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function $g(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function rE(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function YE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function AB(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function KQ(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 MQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.hypot(I,B,Q)}function eQ(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 nE(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 KB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return g[0]=Q*o-C*i,g[1]=C*E-B*o,g[2]=B*i-Q*E,g}function KE(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,y=i*E,G=3*C*i,L=3*o*E,k=o*C;return g[0]=A[0]*y+I[0]*G+B[0]*L+Q[0]*k,g[1]=A[1]*y+I[1]*G+B[1]*L+Q[1]*k,g[2]=A[2]*y+I[2]*G+B[2]*L+Q[2]*k,g}function IB(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 ME(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)<=oI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=oI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=oI*Math.max(1,Math.abs(Q),Math.abs(i))}var MB=rE,eE=nQ;(function(){var g=FA();return function(A,I,B,Q,C,E){var i,o;for(I||(I=3),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 bI(){var g=new JA(4);return JA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function HE(g){var A=new JA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function gB(g,A,I,B){var Q=new JA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function qE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function dE(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 Sg(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=bI();return function(A,I,B,Q,C,E){var i,o;for(I||(I=4),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 eB(){var g=new JA(4);return JA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function lE(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 pE(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],y=I[2],G=I[3];return g[0]=B*G+E*i+Q*y-C*o,g[1]=Q*G+E*o+C*i-B*y,g[2]=C*G+E*y+B*o-Q*i,g[3]=E*G-B*i-Q*o-C*y,g}function HB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],y=I[1],G=I[2],L=I[3],k,r,K,f,M;return r=Q*o+C*y+E*G+i*L,r<0&&(r=-r,o=-o,y=-y,G=-G,L=-L),1-r>oI?(k=Math.acos(r),K=Math.sin(k),f=Math.sin((1-B)*k)/K,M=Math.sin(B*k)/K):(f=1-B,M=B),g[0]=f*Q+M*o,g[1]=f*C+M*y,g[2]=f*E+M*G,g[3]=f*i+M*L,g}function qQ(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 WE=HE,mE=qE,qB=fE;(function(){var g=FA(),A=CA(1,0,0),I=CA(0,1,0);return function(B,Q,C){var E=HQ(Q,C);return E<-.999999?(KB(g,A,Q),eE(g)<1e-6&&KB(g,I,Q),nE(g,g),lE(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(KB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,qB(B,B))}})(),function(){var g=eB(),A=eB();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=YQ();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],qB(A,qQ(A,g))}}();function dQ(){var g=new JA(2);return JA!=Float32Array&&(g[0]=0,g[1]=0),g}function fQ(g){var A=new JA(2);return A[0]=g[0],A[1]=g[1],A}function rA(g,A){var I=new JA(2);return I[0]=g,I[1]=A,I}function TE(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function xE(g){var A=g[0],I=g[1];return A*A+I*I}function ZE(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 lQ(g,A){return g[0]===A[0]&&g[1]===A[1]}function dB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=oI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=oI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=dQ();return function(A,I,B,Q,C,E){var i,o;for(I||(I=2),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 aI{min;max;constructor(A,I){this.min=A?XA(A):CA(1/0,1/0,1/0),this.max=I?XA(I):CA(-1/0,-1/0,-1/0)}clone(){return new aI(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=[CA(I[0],I[1],I[2]),CA(I[0],I[1],B[2]),CA(I[0],B[1],I[2]),CA(I[0],B[1],B[2]),CA(B[0],I[1],I[2]),CA(B[0],I[1],B[2]),CA(B[0],B[1],I[2]),CA(B[0],B[1],B[2])];this.min=CA(1/0,1/0,1/0),this.max=CA(-1/0,-1/0,-1/0);const C=FA();for(const E of Q)IB(C,E,A),this.expandWithPoint(C)}}const bE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class uI extends nB{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 aI,Q=FA();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 uE{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(G=>{const L=bE[G.type];this.gl_.vertexAttribPointer(L,G.itemSize,this.gl_.FLOAT,!1,i,G.offset),this.gl_.enableVertexAttribArray(L)});const o={vao:I,vbo:C},{indexData:y}=A;if(y.length){const G=this.gl_.ELEMENT_ARRAY_BUFFER,L=this.gl_.createBuffer();if(!L)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(G,L),this.gl_.bufferData(G,y,this.gl_.STATIC_DRAW),o.ebo=L}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class PE{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}get textureInfo(){return{textures:this.textureCount_,totalBytes:this.gpuTextureBytes_}}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 V.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),o=0;for(let y=0;y<Q;y++)o+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class ZA{min;max;constructor(A,I){this.min=A?fQ(A):rA(1/0,1/0),this.max=I?fQ(I):rA(-1/0,-1/0)}clone(){return new ZA(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 lQ(A.min,I.min)&&lQ(A.max,I.max)}floor(){return new ZA(rA(Math.floor(this.min[0]),Math.floor(this.min[1])),rA(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 OE{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_&&ZA.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_&&ZA.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 VE=NE(PA(),[1,-1,1]);class pQ extends IE{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,V.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new FE(I),this.bindings_=new uE(I),this.textures_=new PE(I),this.state_=new OE(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new ZA(rA(0,0),rA(this.width,this.height));if(ZA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(ZA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{V.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.renderedObjectsPerFrame_=0,this.clear();const{opaque:Q,transparent:C}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const E=A.camera.frustum,i={viewport:A};for(const o of Q)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!1);for(const o of C)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}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];this.state_.setCullFaceMode(Q.cullFaceMode),this.state_.setDepthTesting(Q.depthTest),this.state_.setDepthMask(Q.depthTest),this.bindings_.bindGeometry(Q.geometry),Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),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=_g(PA(),C.viewMatrix,I.transform.matrix),i=_g(PA(),VE,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],y=I.getUniforms(),L={...B.getUniforms(),...y};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,o);break;case"u_opacity":Q.setUniform(K,B.opacity);break;case"CameraPositionModel":{const f=zg(PA(),E),M=gB(0,0,0,1),d=Sg(bI(),M,f);Q.setUniform(K,CA(d[0],d[1],d[2]));break}default:K in L&&Q.setUniform(K,L[K])}const k=this.glGetPrimitive(A.primitive),r=A.indexData;r.length?this.gl_.drawElements(k,r.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(k,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 ZA(rA(0,0),rA(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 XE=8;class jE{maxConcurrent_;pending_=[];running_=new Map;constructor(A=XE){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),V.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),V.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"&&V.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const WQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function mQ(g){if(WQ.some(I=>g instanceof I))return!0;const A=WQ.map(I=>I.name);return V.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function vE(g,A){return Math.round((A-g.translation)/g.scale)}function fB(g,A,I=1e-6){return Math.abs(g-A)<=I}function Rg(g,A,I){return Math.max(A,Math.min(I,g))}const lB=Symbol("INTERNAL_POLICY_KEY");class zE{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,V.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_=xE(rA(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}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.store_.getLowestResLOD();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]}updateChunkStatesForVolume(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I);if(B.length===0){V.warn("ChunkStoreView","updateChunkStatesForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.setLOD(0),this.chunkViewStates_.forEach(pB);for(const Q of B){if(Q.lod!==this.currentLOD_||!(A.c===void 0||A.c===Q.chunkIndex.c))continue;const E=this.policy_.priorityMap.visibleCurrent;this.chunkViewStates_.set(Q,{visible:!0,prefetch:!1,priority:E,orderKey:0})}this.lastTCoord_=A.t}updateChunkStates(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,o=I.getBoxRelativeTo(i).toRect().width,y=E/o,G=Math.log2(1/y);this.setLOD(G);const L=this.getZBounds(A);(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(L)||this.lastTCoord_!==A.t)&&(this.updateChunkViewStates(A,C),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=L,this.lastTCoord_=A.t)}allVisibleLowestLODLoaded(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I).filter(Q=>Q.visible&&Q.lod===this.store_.getLowestResLOD());return B.length>0&&B.every(Q=>Q.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(pB)}setImageSourcePolicy(A,I){if(I!==lB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,V.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(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),y=Math.max(o,Math.min(i,this.policy_.lod.max)),G=Rg(E,o,y);G!==this.currentLOD_&&(this.currentLOD_=G)}updateChunkViewStates(A,I){const B=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(B).length===0){V.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const C=dQ();ZE(C,I.min,I.max,.5);const[E,i]=this.getZBounds(A),o=new aI(CA(I.min[0],I.min[1],E),CA(I.max[0],I.max[1],i));this.chunkViewStates_.forEach(pB),this.updateChunksAtTimeIndex(B,A,o,C),A.t!==void 0&&this.markTimeChunksForPrefetch(B,A,o,C)}isChunkChannelInSlice(A,I){return I.c===void 0||I.c===A.chunkIndex.c}updateChunksAtTimeIndex(A,I,B,Q){const C=this.getPaddedBounds(B),E=this.store_.getChunksAtTime(A);for(const i of E){const o=this.isChunkWithinBounds(i,B),y=this.isChunkChannelInSlice(i,I),G=i.lod===this.currentLOD_,L=i.lod===this.store_.getLowestResLOD(),k=!o&&y&&G&&this.isChunkWithinBounds(i,C),r=o&&y,K=this.computePriority(L,G,o,k,y);if(K!==null){const f=this.squareDistance2D(i,Q);this.chunkViewStates_.set(i,{visible:r,prefetch:k,priority:K,orderKey:f})}}}markTimeChunksForPrefetch(A,I,B,Q){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t);for(let i=A+1;i<=E;++i)for(const o of this.store_.getChunksAtTime(i)){if(o.lod!==this.store_.getLowestResLOD()||!this.isChunkChannelInSlice(o,I)||!this.isChunkWithinBounds(o,B))continue;const y=this.policy_.priorityMap.prefetchTime,G=this.squareDistance2D(o,Q),L=Rg(G/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),k=i-A+L;this.chunkViewStates_.set(o,{visible:!1,prefetch:!0,priority:y,orderKey:k})}}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 aI(CA(A.offset.x,A.offset.y,A.offset.z),CA(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 aI.intersects(B,I)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const G=I.lods[this.currentLOD_];return[G.translation,G.translation+G.size*G.scale]}const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),o=B.chunkSize,y=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(Q/o)-1));return[E+y*o*C,E+(y+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!dB(this.lastViewBounds2D_.min,A.min)||!dB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!dB(this.lastZBounds_,A)}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 o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new aI(CA(A.min[0]-E,A.min[1]-i,A.min[2]-o),CA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}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 pB(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class _E{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],o=this.dimensions_.y.lods[E],y=this.dimensions_.z?.lods[E],G=i.chunkSize,L=o.chunkSize,k=y?.chunkSize??1,r=Math.ceil(i.size/G),K=Math.ceil(o.size/L),f=Math.ceil((y?.size??1)/k);for(let M=0;M<B;++M)for(let d=0;d<r;++d){const u=i.translation+d*i.chunkSize*i.scale;for(let x=0;x<K;++x){const X=o.translation+x*o.chunkSize*o.scale;for(let O=0;O<f;++O){const Z=y!==void 0?y.translation+O*k*y.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(G,i.size-d*G),y:Math.min(L,o.size-x*L),z:Math.min(k,(y?.size??1)-O*k),c:1},rowAlignmentBytes:1,chunkIndex:{x:d,y:x,z:O,c:M,t:Q},scale:{x:i.scale,y:o.scale,z:y?.scale??1},offset:{x:u,y:X,z:Z}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:vE(this.dimensions_.t.lods[0],A.t)}get lodCount(){return this.lowestResLOD_+1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}createView(A){const I=new zE(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 y of this.views_){const G=y.chunkViewStates.get(A);G&&(G.visible&&(I=!0),G.prefetch&&(B=!0),G.priority!==null&&(Q===null||G.priority<Q)&&(Q=G.priority,C=G.orderKey),!G.visible&&!G.prefetch&&G.priority===null&&y.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,V.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(!fB(Q,2,.02)||!fB(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;if(I.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in t. Found ${I.chunkSize} at LOD ${A}`);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.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in c. Found ${I.chunkSize} at LOD ${A}`);if(I.scale!==1)throw new Error(`ChunkStore does not support scale in c. Found ${I.scale} at LOD ${A}`);if(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 $E{stores_=new Map;pendingStores_=new Map;queue_=new jE;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 _E(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 Ng=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(L){L.preventDefault(),Q(++A%I.children.length)},!1);function B(L){return I.appendChild(L.dom),L}function Q(L){for(var k=0;k<I.children.length;k++)I.children[k].style.display=k===L?"block":"none";A=L}var C=(performance||Date).now(),E=C,i=0,o=B(new Ng.Panel("FPS","#0ff","#002",g)),y=B(new Ng.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var G=B(new Ng.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 L=(performance||Date).now();if(y.update(L-C,200),L>=E+1e3&&(o.update(i*1e3/(L-E),100),E=L,i=0,G)){var k=performance.memory;G.update(k.usedJSHeapSize/1048576,k.jsHeapSizeLimit/1048576)}return L},update:function(){C=this.end()},domElement:I,setMode:Q}};Ng.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*B),y=E(48*i*B),G=E(3*i*B),L=E(2*i*B),k=E(3*i*B),r=E(15*i*B),K=E(74*i*B),f=E(30*i*B),M=document.createElement("canvas");M.width=o,M.height=y,M.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var d=M.getContext("2d");return d.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",d.textBaseline="top",d.fillStyle=I,d.fillRect(0,0,o,y),d.fillStyle=A,d.fillText(g,G,L),d.fillRect(k,r,K,f),d.fillStyle=I,d.globalAlpha=.9,d.fillRect(k,r,K,f),{dom:M,update:function(u,x){Q=Math.min(Q,u),C=Math.max(C,u),d.fillStyle=I,d.globalAlpha=1,d.fillRect(0,0,o,r),d.fillStyle=A,d.fillText(E(u)+" "+g+" ("+E(Q)+"-"+E(C)+")",G,L),d.drawImage(M,k+i,r,K-i,f,k,r,K-i,f),d.fillRect(k+K-i,r,i,f),d.fillStyle=I,d.globalAlpha=.9,d.fillRect(k+K-i,r,i,E((1-u/x)*f))}}};function Ai({scale:g}={scale:1.5}){const A=new Ng(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 WB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function Ii(g){return WB.includes(g)}class gi{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 Bi{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){V.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,WB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){V.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,WB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!Ii(A.type)){V.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new gi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class xQ{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 Bi(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=rA(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,o=I.x-C,y=I.y-E,G=Math.floor(o),L=Math.floor(i-y-I.height),k=Math.floor(I.width),r=Math.floor(I.height);return new ZA(rA(G,L),rA(G+k,L+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return CA(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 ZA(rA(B,Q),rA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){V.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 Qi(g){const A=new Map,I=new Set;for(const B of g){if(I.has(B.id))throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.add(B.id),A.has(B.element)){const Q=A.get(B.element),C=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${Q}" and "${B.id}" both use ${C}`)}A.set(B.element,B.id)}}function ZQ(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??rQ(),layerManager:new TQ(I)}});return Qi(B),B.map(Q=>new xQ(Q))}class Ci{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=A,this.onChange_=I}connect(){if(this.resizeObserver_){V.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_){V.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class Ei{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){if(this.canvas=A.canvas,A.viewports.length===0)throw new Error("At least one viewport config must be specified.");this.renderer_=new pQ(this.canvas),this.chunkManager_=new $E,this.context_={chunkManager:this.chunkManager_},this.viewports_=ZQ(A.viewports,this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Ai());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new Ci(I,()=>{this.renderer_.updateSize();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get textureInfo(){return this.renderer_.textureInfo}get viewports(){return this.viewports_}getViewport(A){return this.viewports_.find(I=>I.id===A)}start(){if(V.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}else V.warn("Idetik","Idetik runtime already started");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(V.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)V.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 ii extends uI{constructor(A){if(super(),A.primitive!="triangles"){V.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){V.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 o=Math.min(E,i),y=Math.max(E,i);I.has({i0:o,i1:y})||(I.add({i0:o,i1:y}),B.push(o,y))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],y=C[E+2];Q(i,o),Q(o,y),Q(y,i)}this.indexData_=new Uint32Array(B)}}const Di=CA(0,1,0);class oi{dirty_=!0;matrix_=PA();rotation_=eB();translation_=FA();scale_=CA(1,1,1);addRotation(A){pE(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){mE(this.rotation_,A),this.dirty_=!0}get rotation(){return WE(this.rotation_)}addTranslation(A){$g(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){wg(this.translation_,A),this.dirty_=!0}get translation(){return XA(this.translation_)}addScale(A){YE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){wg(this.scale_,A),this.dirty_=!0}targetTo(A){ME(this.translation_,A)&&(A=XA(A),A[2]+=oI);const I=JE(PA(),this.translation_,A,Di),B=RE(YQ(),I);qQ(this.rotation_,B),qB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return XA(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return zg(PA(),this.matrix)}computeMatrix(){UE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class PI extends nB{wireframeEnabled=!1;wireframeColor=QA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new oi;geometry_=new uI;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 ii(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(){if(this.programName_===null)throw new Error("Program name not set");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=CA(0,1,0),I=0){this.normal=XA(A),this.signedDistance=I}set(A,I){this.normal=XA(A),this.signedDistance=I}signedDistanceToPoint(A){return HQ(this.normal,A)+this.signedDistance}normalize(){const A=nQ(this.normal);if(A>0){const I=1/A;AB(this.normal,this.normal,I),this.signedDistance*=I}}}class bQ{planes_;constructor(A){this.planes_=[new LI(FA(),0),new LI(FA(),0),new LI(FA(),0),new LI(FA(),0),new LI(FA(),0),new LI(FA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=FA();this.planes_[0].set(ZI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(ZI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(ZI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(ZI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(ZI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(ZI(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=FA();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 uQ extends PI{projectionMatrix_=PA();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 CA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return CA(A[4],A[5],A[6])}get frustum(){return new bQ(_g(PA(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=gB(A[0],A[1],A[2],1),B=zg(PA(),this.projectionMatrix_),Q=Sg(bI(),I,B);dE(Q,Q,1/Q[3]);const C=Sg(bI(),Q,this.transform.matrix);return CA(C[0],C[1],C[2])}}const PQ=1.77,OQ=128,VQ=128/PQ;class ai extends uQ{width_=OQ;height_=VQ;viewportAspectRatio_=PQ;viewportSize_=[OQ,VQ];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=gB(-1,-1,0,1),I=gB(1,1,0,1);const B=_g(PA(),this.projectionMatrix,this.viewMatrix),Q=zg(PA(),B);return A=Sg(bI(),A,Q),I=Sg(bI(),I,Q),new ZA(rA(A[0],A[1]),rA(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],LE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const si=60,yi=1.77,BB=.1,mB=180-BB;class hi extends uQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=si,aspectRatio:B=yi,near:Q=.1,far:C=1e4,position:E=CA(0,0,0)}=A;if(I<BB||I>mB)throw new Error(`Invalid field of view: ${I}, must be in [${BB}, ${mB}] 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(BB,Math.min(mB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){kE(this.projectionMatrix_,SE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const XQ=0;class Gi{camera_;dragActive_=!1;dragStart_=FA();constructor(A){this.camera_=A}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=XA(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=MB(FA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==XQ||(this.dragStart_=XA(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=MB(FA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==XQ||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class QI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&V.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Rg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&V.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Rg(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 QB extends uI{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,o)=>E+MQ(i,A[o+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const o=A[E];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const y=A[E-1]??A[E];I[B++]=y[0],I[B++]=y[1],I[B++]=y[2];const G=A[E+1]??A[E];I[B++]=G[0],I[B++]=G[1],I[B++]=G[2],I[B++]=i,I[B++]=Q}Q+=MQ(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 TB extends PI{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 Fi extends QI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(xB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(xB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(xB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function xB(g){const{end:A,width:I,color:B}=g,Q=new QB([[0,0,0],A]);return new TB({geometry:Q,color:B,width:I})}class wi extends QI{type="ProjectedLineLayer";paths_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){const{path:I,color:B,width:Q}=A;this.paths_.push(I);const C=new QB(I);this.addObject(new TB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Si(this.paths_.flat())}}function Si(g){function A(o){const y=g.map(G=>G[o]);return[Math.min(...y),Math.max(...y)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}class Ri extends QI{type="TracksLayer";tracks_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){this.tracks_.push(A);let I;if(A.interpolation){const i=Ui({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new QB(i)}else I=new QB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new TB({geometry:I,color:B,width:Q,taperOffset:C,taperPower:E}))}setTimeIndex(A){for(const[I,B]of this.tracks_.entries()){if(!B.time)continue;let Q=.5;A<B.time[0]?Q=-1.5:A>B.time[B.time.length-1]&&(Q=1.5);const C=B.time.findIndex(i=>i===A);B.time&&C!==-1&&(Q=C/(B.time.length-1));const E=this.objects[I];E.taperOffset=Q}}update(){}get extent(){const A=this.tracks_.map(I=>I.path);return Ni(A.flat())}}function Ni(g){function A(o){const y=g.map(G=>G[o]);return[Math.min(...y),Math.max(...y)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}function Ui({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=ti(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],o=XA(B[C]);KQ(o,E,o,I);const y=XA(B[C+1]);KQ(y,i,y,-I);for(let G=0;G<A;G++){const L=G/A,k=Q[C*A+G]=FA();KE(k,E,o,y,i,L)}}return Q}function ti(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=FA(),B=FA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=FA(),Q!==0&&wg(I,B),Q!==g.length-1&&MB(B,E,C),Q===0?wg(A[Q],B):Q==g.length-1?wg(A[Q],I):($g(A[Q],I,B),AB(A[Q],A[Q],.5))}return A}class jQ extends uI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,y=i+1,G=o+1,L=A/i,k=I/o;for(let r=0;r<G;++r){const K=r*k;for(let f=0;f<y;++f){const M=f*L,d=f/i,u=r/o,x=[M,K,0],X=[0,0,1],O=[d,u];C.push(...x,...X,...O)}}for(let r=0;r<o;++r)for(let K=0;K<i;++K){const f=K+y*r,M=K+y*(r+1),d=K+1+y*(r+1),u=K+1+y*r;E.push(f,M,u),E.push(M,d,u)}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})}}function vQ(g){return g===1||g===2||g===4||g===8}function OI(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 ki(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 ZB extends nB{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 zQ=32;function bB(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=ci(B,g):B===void 0&&(V.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function _Q(g,A){if(A.length>zQ)throw new Error(`Maximum number of channels is ${zQ}`);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=>bB(g,I))}function ci(g,A){if(g===void 0)return ki(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class uB extends PI{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new jQ(A,I,1,1),this.setTexture(0,B),this.channels_=_Q(B,Q),this.programName=Li(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=_Q(this.textures[0],A)}setChannelProperty(A,I,B){const Q=bB(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]??bB(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 Li(g){if(g.type==="Texture2D")return Ji(g.dataType);if(g.type==="Texture2DArray")return ri(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function Ji(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 ri(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 VI extends ZB{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=OI(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!=OI(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 VI(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function PB(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return rA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=rA(C.clientX,C.clientY);if(TE(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const y=I(o);y!==null&&B({world:o,value:y})}return null}return A}case"pointercancel":return null;default:return A}}class $Q{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&V.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),V.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class OB extends QI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new $Q;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("ChunkedImageLayer cannot be attached to multiple contexts simultaneously.");this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_)}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_.updateChunkStates(this.sliceCoords_,A.viewport),this.updateChunks(),this.resliceIfZChanged())}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleLowestLODLoaded(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_>OB.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_=PB(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,lB))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Rg(Q,0,A.shape.z-1);fB(B,C,1+1e-6)||V.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(AC(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),this.channelProps_&&B.setChannelProps(this.channelProps_),B):this.createImage(A)}createImage(A){const I=new uB(A.shape.x,A.shape.y,VI.createWithChunk(A,this.getDataForImage(A)),this.channelProps_??[{}]);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){V.warn("ChunkedImageLayer","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=IB(FA(),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,o=E*A.shape.x+C;return i[o]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,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=>{I.setChannelProps(A)}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(AC(I),B),this.visibleChunks_.delete(I))}}}function AC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class Yi extends uI{constructor(A,I,B,Q,C,E){super();const i=[],o=[],y=Math.floor(Q),G=Math.floor(C),L=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,L,G,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,L,G,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,y,L,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,y,L,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,y,G,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,y,G,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,o,y,G,L,k,r){const K=E/y,f=i/G,M=E/2,d=i/2,u=o/2*L,x=y+1,X=G+1,O=k.length/8;for(let Z=0;Z<X;Z++){const DA=-d+Z*f;for(let oA=0;oA<x;oA++){const EA=-M+oA*K,sA={x:0,y:0,z:0};sA[A]=EA*Q,sA[I]=DA*C,sA[B]=u;const yA={x:0,y:0,z:0};yA[B]=L;const fA=oA/y,YA=1-Z/G;k.push(sA.x,sA.y,sA.z,yA.x,yA.y,yA.z,fA,YA)}}for(let Z=0;Z<G;Z++)for(let DA=0;DA<y;DA++){const oA=O+DA+x*Z,EA=O+DA+x*(Z+1),sA=O+(DA+1)+x*(Z+1),yA=O+(DA+1)+x*Z;r.push(oA,EA,yA,EA,sA,yA)}}}class ni extends PI{constructor(A){super(),this.geometry=new Yi(1,1,1,1,1,1),this.setTexture(0,A),this.programName=Ki(A.dataType),this.cullFaceMode="front",this.depthTest=!1}get type(){return"VolumeRenderable"}}function Ki(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"}}class CB extends ZB{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=OI(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!=OI(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 CB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class Mi extends QI{type="VolumeLayer";source_;sliceCoords_;currentChunks_=new Map;pool_=new $Q;sourcePolicy_;chunkStoreView_;lastLoadedTime_=void 0;debugShowWireframes_=!1;debugShowDegenerateRays=!1;color=CA(1,1,1);samplesPerUnit=128;maxIntensity=255;opacityMultiplier=.1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentChunks_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,lB))}createVolume(A){const I=new ni(CB.createWithChunk(A));return this.updateVolumeChunk(I,A),I}constructor({source:A,sliceCoords:I,policy:B}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=B,this.setState("initialized")}getVolumeForChunk(A){const I=this.currentChunks_.get(A);if(I)return I;const B=this.pool_.acquire(IC(A));return B?(B.textures[0].updateWithChunk(A),this.updateVolumeChunk(B,A),B):this.createVolume(A)}async onAttached(A){this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.sourcePolicy_)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.currentChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=this.sliceCoords_.t??-1;if(!(this.lastLoadedTime_!==I||A.length!==this.currentChunks_.size))return;const Q=new Set(A),C=Array.from(this.currentChunks_.keys()).filter(E=>!Q.has(E));this.releaseAndRemoveChunks(C),this.clearObjects();for(const E of A){const i=this.getVolumeForChunk(E);i.wireframeEnabled=this.debugShowWireframes,this.currentChunks_.set(E,i),this.addObject(i)}this.lastLoadedTime_=I,this.state!=="ready"&&this.setState("ready")}updateVolumeChunk(A,I){A.transform.setScale([I.shape.x*I.scale.x,I.shape.y*I.scale.y,I.shape.z*I.scale.z]);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveChunks(A){for(const I of A){const B=this.currentChunks_.get(I);B&&(this.pool_.release(IC(I),B),this.currentChunks_.delete(I))}}update(A){if(this.chunkStoreView_){if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.reorderObjects(A.viewport.camera),this.chunkStoreView_.updateChunkStatesForVolume(this.sliceCoords_),this.updateChunks()}}reorderObjects(A){const I=A.position,B=FA(),Q=FA();this.objects.sort((C,E)=>{$g(B,C.boundingBox.max,C.boundingBox.min),AB(B,B,.5),$g(Q,E.boundingBox.max,E.boundingBox.min),AB(Q,Q,.5);const i=eQ(I,B),y=eQ(I,Q)-i;return Math.abs(y)<oI?0:y})}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),SamplesPerUnit:this.samplesPerUnit,MaxIntensity:this.maxIntensity,OpacityMultiplier:this.opacityMultiplier,VolumeColor:this.color,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function IC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class ei extends QI{type="ImageLayer";source_;region_;lod_;onPickValue_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;image_;chunk_;extent_;pointerDownPos_=null;constructor({source:A,region:I,channelProps:B,onPickValue:Q,lod:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.region_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=Q,this.lod_=C}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}onEvent(A){this.pointerDownPos_=PB(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),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===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.extent_={x:Q.shape.x*Q.scale.x,y:Q.shape.y*Q.scale.y},this.image_=this.createImage(Q),this.chunk_=Q,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new uB(A.shape.x,A.shape.y,VI.createWithChunk(A),this.channelProps);return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.chunk_?.data)return null;const I=IB(FA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B>=0&&B<this.chunk_.shape.x&&Q>=0&&Q<this.chunk_.shape.y){const C=Q*this.chunk_.shape.x+B;return this.chunk_.data[C]}return null}}class Ug extends ZB{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=OI(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!=OI(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 Ug(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const Hi=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function qi(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,QA.from(I)]))}function di(g){return g=g??Hi,g.map(QA.from)}class gC{lookupTable;cycle;constructor(A={}){this.lookupTable=qi(A.lookupTable),this.cycle=di(A.cycle)}}const fi=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function li(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!fi.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class pi extends PI{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new jQ(A.width,A.height,1,1),this.setTexture(0,li(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 Ug(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 Ug(C,Q,2)}}class Wi extends QI{type="LabelImageLayer";source_;region_;lod_;colorMap_;onPickValue_;outlineSelected_;image_;imageChunk_;pointerDownPos_=null;selectedValue_=null;constructor({source:A,region:I,colorMap:B={},onPickValue:Q,lod:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.region_=I,this.colorMap_=new gC(B),this.onPickValue_=Q,this.lod_=C,this.outlineSelected_=E}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new gC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=PB(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.image_=this.createImage(Q),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new pi({width:A.shape.x,height:A.shape.y,imageData:Ug.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.imageChunk_?.data)return null;const I=IB(FA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B<0||B>=this.imageChunk_.shape.x||Q<0||Q>=this.imageChunk_.shape.y)return null;const C=Q*this.imageChunk_.shape.x+B;return this.imageChunk_.data[C]}}class EB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,EB.prototype)}}class mi{maxConcurrent_;pending_=[];abortController_=new AbortController;numRunning_=0;constructor(A){if(A<=0)throw Error(`maxConcurrent (${A}) must be positive`);this.maxConcurrent_=A}async submit(A){return this.abortController_.signal.throwIfAborted(),new Promise((I,B)=>{const Q=async()=>{try{this.abortController_.signal.throwIfAborted();const C=await A();I(C)}catch(C){B(C)}finally{this.numRunning_--,this.maybeRunNext()}};this.pending_.push(Q),this.maybeRunNext()})}maybeRunNext(){if(this.numRunning_>=this.maxConcurrent_)return;const A=this.pending_.shift();A!==void 0&&(this.numRunning_++,A())}get abortSignal(){return this.abortController_.signal}shutdown(){this.abortController_.abort(new EB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class Ti{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new mi(16);lod_;loader_=null;seriesAttributes_;loadingToken_=null;dataChunks_=[];constructor(A){this.source_=A.source,this.region_=A.region,this.lod_=A.lod,this.seriesDimensionName_=A.seriesDimensionName;const I=A.region.find(B=>B.dimension==A.seriesDimensionName);if(I===void 0)throw new Error(`Series dimension '${A.seriesDimensionName}' not in region ${JSON.stringify(A.region)}`);if(I.index.type==="point")throw new Error("Series dimension index in region must be an interval or 'full', not a point value");this.seriesIndex_=I.index}async setPosition(A){const I=await this.loadSeriesAttributes(),B=Math.round((A-I.start)/I.scale);return await this.setIndex(B)}async setIndex(A){const I=this.loadingToken_;if(I){if(I.index===A&&!I.canceled)return V.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};V.debug("ImageSeriesLoader",`Cancelling setIndex request for index ${I.index}, new requested index is ${A}`),I.canceled=!0}let B=this.dataChunks_[A];if(B===void 0){const Q={canceled:!1,index:A};if(this.loadingToken_=Q,B=await this.loadChunkAtIndex(A,Q),Q.canceled)return{success:!1,reason:"canceled"}}return{success:!0,chunk:B}}shutdown(){this.scheduler_.shutdown()}async loadSeriesAttributes(){if(this.seriesAttributes_)return this.seriesAttributes_;const I=(await this.getLoader()).getSourceDimensionMap(),B=this.lod_??I.numLods-1,Q=[I.x,I.y,I.z,I.c,I.t].filter(k=>k!==void 0),C=Q.find(k=>k.name===this.seriesDimensionName_);if(!C){const k=Q.map(r=>r.name).join(", ");throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${k}`)}const E=C.lods[B].scale,i=C.lods[B].size*E,o=this.seriesIndex_.type==="full",y=o?0:this.seriesIndex_.start,G=o?i:this.seriesIndex_.stop,L=Math.round((G-y)/E);return this.dataChunks_=new Array(L),this.seriesAttributes_={start:y,stop:G,scale:E,length:L},this.seriesAttributes_}async loadChunkAtIndex(A,I){const B=await this.loadSeriesAttributes();if(A<0||A>=B.length)throw new Error(`Requested index ${A} is out of bounds [0, ${B.length-1}]`);const Q=B.start+A*B.scale,C=this.region_.filter(y=>y.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=this.lod_??E.getSourceDimensionMap().numLods-1,o=await E.loadRegion(C,i,this.scheduler_);return this.dataChunks_[A]=o,I&&I.canceled&&(this.loadingToken_=null),o}async preloadAllChunks(){const{length:A}=await this.loadSeriesAttributes(),I=[];for(let Q=0;Q<A;Q++)I.push(this.loadChunkAtIndex(Q));const B=await Promise.allSettled(I);for(const Q of B)if(Q.status==="rejected"){if(Q.reason instanceof EB)return Promise.reject(Q.reason);V.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class xi extends QI{type="ImageSeriesLayer";seriesLoader_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;texture_=null;image_;extent_;constructor({source:A,region:I,seriesDimensionName:B,channelProps:Q,lod:C,...E}){super(E),this.setState("initialized"),this.channelProps_=Q,this.initialChannelProps_=Q,this.seriesLoader_=new Ti({source:A,region:I,seriesDimensionName:B,lod:C})}update(){this.state==="initialized"&&(this.setState("loading"),this.seriesLoader_.loadSeriesAttributes())}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),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===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async setPosition(A){const I=await this.seriesLoader_.setPosition(A);return this.processIndexResult(I)}async setIndex(A){const I=await this.seriesLoader_.setIndex(A);return this.processIndexResult(I)}close(){this.seriesLoader_.shutdown()}async preloadSeries(){return this.seriesLoader_.preloadAllChunks()}get extent(){return this.extent_}processIndexResult(A){return A.chunk&&(this.setData(A.chunk),this.setState("ready")),A}setData(A){!this.texture_||!this.image_?(this.texture_=VI.createWithChunk(A),this.image_=this.createImage(A,this.texture_,this.channelProps_),this.addObject(this.image_),this.extent_={x:A.shape.x*A.scale.x,y:A.shape.y*A.scale.y}):A.data&&this.texture_.updateWithChunk(A)}createImage(A,I,B){const Q=new uB(A.shape.x,A.shape.y,I,B);return Q.transform.setScale([A.scale.x,A.scale.y,1]),Q.transform.setTranslation([A.offset.x,A.offset.y,0]),Q}}function BC(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 Zi(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function QC(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 CC(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 bi(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 BC(g,E-A,E,I)}class XI{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return Zi(this.#A,A)}async get(A,I={}){let B=QC(this.url,A).href,Q=await fetch(B,this.#g(I));return CC(Q)}async getRange(A,I,B={}){let Q=QC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await bi(Q,I.suffixLength,C,this.#I):E=await BC(Q,I.offset,I.length,C),CC(E)}}class EC{#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 VB{_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 tg{#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 tg(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 kg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function iC(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 DC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?tg:VB).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:EC}[g];return kA(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)),kA(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 ui({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 Pi(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(/^([<|>])(.*)$/);kA(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 kA(Q,`Unsupported or unknown dtype: ${g}`),I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function Oi(g,A={}){let I=[],B=Pi(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 Vi(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function Xi(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 ji(g){return g?.name==="sharding_indexed"}function oC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}function aC(g,...A){if(!A.some(I=>g instanceof I))throw g}function kA(g,A=""){if(!g)throw new Error(A)}async function sC(g,{format:A,signal:I}){const B=g instanceof Response?g:new Response(g);kA(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 XB{kind="array_to_array";constructor(A,I){kA(A.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(A,I){return new XB(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 yC=vi();function vi(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function hC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class iB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=DC(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 iB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return yC&&this.#B==="big"&&iC(I,hC(this.#I)),I}decode(A){return yC&&this.#B==="big"&&iC(A,hC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class jB{kind="bytes_to_bytes";static fromConfig(){return new jB}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}class vB{kind="bytes_to_bytes";static fromConfig(A){return new vB}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 sC(A,{format:"gzip"});return new Uint8Array(I)}}function zi(g,A){return kA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),kA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),kA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function _i(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class zB{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:o,strict:y=!0}=A;let G=A.separators;G||(o?G=[", ",": "]:G=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:G,sort_keys:i},this.#I={strict:y}}static fromConfig(A){return new zB(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;kA(B==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];kA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(zi),i&&o.push(_i);const y=Array.from(A.data);y.push("|O"),y.push(A.shape);let G;o.length&&(G=(k,r)=>{let K=r;for(let f of o)K=f(k,K);return K});let L=JSON.stringify(y,G,I);return Q&&(L=L.replace(/[\u007F-\uFFFF]/g,k=>{const r=`0000${k.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(L)}decode(A){const{strict:I}=this.#I;kA(I,"JsonCodec does not yet support non-strict decoding.");const B=kg(A),Q=B.pop();B.pop(),kA(Q,"0D not implemented for JsonCodec.");const C=JI(Q,"C");return{data:B,shape:Q,stride:C}}}function GC(g){return g instanceof EC||g instanceof VB||g instanceof tg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function $i(g,A){let I;return g.data instanceof VB||g.data instanceof tg?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 AD(g,A){let I=$i(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=GC(g.data),i=GC(I.data);for(let o=0;o<Q;o++){let y=0;for(let G=0;G<B;G++)y+=C[G]*I.stride[G];i[y]=E[o],C[0]+=1;for(let G=0;G<B;G++)if(C[G]===g.shape[G]){if(G+1===B)break;C[G]=0,C[G+1]+=1}}return I}function ID(g){let A=g.shape.length;return kA(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 gD(g,A){let I=ID(g);return kA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class _B{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,o)=>{kA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new _B(A,I)}encode(A){return gD(A,this.#I)?A:AD(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:JI(A.shape,this.#A)}}}class $B{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=JI(A,"C")}static fromConfig(A,I){return new $B(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 AQ{kind="bytes_to_bytes";static fromConfig(A){return new AQ}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 sC(A,{format:"deflate"});return new Uint8Array(I)}}function BD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>Ka).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>fa).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>xa).then(g=>g.default)).set("gzip",()=>vB).set("zlib",()=>AQ).set("transpose",()=>_B).set("bytes",()=>iB).set("crc32c",()=>jB).set("vlen-utf8",()=>$B).set("json2",()=>zB).set("bitround",()=>XB)}const QD=BD();function IQ(g){let A;return{async encode(I){A||(A=await FC(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 FC(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 FC(g){let A=g.codecs.map(async C=>{let E=await QD.get(C.name)?.();return kA(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||(kA(CD(g),`Cannot encode ${g.data_type} to bytes without a codec`),B=iB.fromConfig({endian:"little"},g)),{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function CD(g){return g.data_type!=="v2:object"}class cg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class gQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}const wC=18446744073709551615n;function ED(g,A,I,B){kA(g.store.getRange,"Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,y)=>o/B.chunk_shape[y]),E=IQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let y=o.map((u,x)=>Math.floor(u/C[x])),G=g.resolve(I(y)).path,L;if(G in i)L=i[G];else{let u=4,x=16*C.reduce((O,Z)=>O*Z,1),X=await Q(G,{suffixLength:x+u});L=i[G]=X?await E.decode(X):null}if(L===null)return;let{data:k,shape:r,stride:K}=L,f=o.map((u,x)=>u%r[x]).reduce((u,x,X)=>u+x*K[X],0),M=k[f],d=k[f+1];if(!(M===wC&&d===wC))return Q(G,{offset:Number(M),length:Number(d)})}}class WA{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 WA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class BQ extends WA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function SC(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const Lg=Symbol("zarrita.context");function iD(g){return g[Lg]}function DD(g,A){let{configuration:I}=A.codecs.find(ji)??{},B={encode_chunk_key:ui(A.chunk_key_encoding),TypedArray:DC(A.data_type),fill_value:A.fill_value};if(I){let C=SC(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:IQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E){return JI(E,C)},get_chunk_bytes:ED(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=SC(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:IQ({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),o=g.resolve(i).path;return g.store.get(o,E)}}}let DB=class extends WA{kind="array";#A;[Lg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:oC(B)},this[Lg]=DD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Lg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Lg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,o)=>i*o,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 Xi(this.dtype,A)}};function*oD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*aD(...g){if(g.length===0)return;const A=g.map(B=>B[Symbol.iterator]()),I=A.map(B=>B.next());if(I.some(B=>B.done))throw new Error("Input contains an empty iterator.");for(let B=0;;){if(I[B].done){if(A[B]=g[B][Symbol.iterator](),I[B]=A[B].next(),++B>=A.length)return}else yield I.map(({value:Q})=>Q),B=0;I[B]=A[B].next()}}function sD({start:g,stop:A,step:I},B){if(I===0)throw new Error("slice step cannot be zero");I=I??1;const Q=I<0,[C,E]=Q?[-1,B-1]:[0,B];return g===null?g=Q?E:C:g<0?(g+=B,g<C&&(g=C)):g>E&&(g=E),A===null?A=Q?C:E:A<0?(A+=B,A<C&&(A=C)):A>E&&(A=E),[g,A,I]}function oB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function yD(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class QQ extends Error{constructor(A){super(A),this.name="IndexError"}}function hD(g,A){throw new QQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function GD(g){throw new QQ(`index out of bounds for dimension with length ${g}`)}function FD(){throw new QQ("only slices with step >= 1 are supported")}function wD(g,A){g.length>A.length&&hD(g,A)}function SD(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&GD(A),g}class RD{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=SD(A,I),this.dim_sel=A,this.dim_len=I,this.dim_chunk_len=B,this.nitems=1}*[Symbol.iterator](){const A=Math.floor(this.dim_sel/this.dim_chunk_len),I=A*this.dim_chunk_len,B=this.dim_sel-I;yield{dim_chunk_ix:A,dim_chunk_sel:B}}}class RC{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){const[Q,C,E]=sD(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&FD(),this.dim_len=I,this.dim_chunk_len=B,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const A=Math.floor(this.start/this.dim_chunk_len),I=Math.ceil(this.stop/this.dim_chunk_len);for(const B of oD(A,I)){const Q=B*this.dim_chunk_len,C=Math.min(this.dim_len,(B+1)*this.dim_chunk_len),E=C-Q;let i=0,o=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(o+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else o=this.start-Q;const y=this.stop>C?E:this.stop-Q,G=[o,y,this.step],L=Math.ceil((y-o)/this.step),k=[i,i+L,1];yield{dim_chunk_ix:B,dim_chunk_sel:G,dim_out_sel:k}}}}function ND(g,A){let I=[];return g===null?I=A.map(B=>oB(null)):Array.isArray(g)&&(I=g.map(B=>B??oB(null))),wD(I,A),I}class UD{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=ND(A,I).map((Q,C)=>new(typeof Q=="number"?RD:RC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof RC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of aD(...this.dim_indexers)){const I=A.map(Q=>Q.dim_chunk_ix),B=A.map(Q=>"dim_out_sel"in Q?{from:Q.dim_chunk_sel,to:Q.dim_out_sel}:{from:Q.dim_chunk_sel,to:null});yield{chunk_coords:I,mapping:B}}}}function tD(g,A){return"get"in g?g.get(A):g[A]}async function kD(g,A,I,B){let Q=iD(g),C=new UD({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,y)=>o*y,1)),C.shape,Q.get_strides(C.shape)),i=I.create_queue?.()??yD();for(const{chunk_coords:o,mapping:y}of C)i.add(async()=>{let{data:G,shape:L,stride:k}=await g.getChunk(o,I.opts),r=B.prepare(G,L,k);B.set_from_chunk(E,r,y)});return await i.onIdle(),C.shape.length===0?tD(E.data,0):E}function CQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return CQ(g,A+Q,C-Q)},set(Q,C=0){for(let E=0;E<Q.length;E++)g[A+C+E]=Q.get(E)},get(Q){return g[A+Q]}}}function EQ(g){return globalThis.Array.isArray(g.data)?{data:CQ(g.data),stride:g.stride,bytes_per_element:1}:{data:new Uint8Array(g.data.buffer,g.data.byteOffset,g.data.byteLength),stride:g.stride,bytes_per_element:g.data.BYTES_PER_ELEMENT}}function cD(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function LD(g,A){if(globalThis.Array.isArray(g.data))return CQ([A]);let I=cD(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const JD={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=EQ(g);iQ(B,A,LD(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=EQ(g);aB(B,EQ(A),B.bytes_per_element,I)}};async function rD(g,A=null,I={}){return kD(g,A,I,JD)}function NC(g,A,I){return I<0&&A<g?Math.floor((g-A-1)/-I)+1:g<A?Math.floor((A-g-1)/I)+1:0}function iQ(g,A,I,B){if(A.length===0){g.data.set(I,0);return}const[Q,...C]=A,[E,...i]=g.stride;if(typeof Q=="number"){const k=g.data.subarray(E*Q*B);iQ({data:k,stride:i},C,I,B);return}const[o,y,G]=Q,L=NC(o,y,G);if(C.length===0){for(let k=0;k<L;k++)g.data.set(I,E*(o+G*k)*B);return}for(let k=0;k<L;k++){const r=g.data.subarray(E*(o+G*k)*B);iQ({data:r,stride:i},C,I,B)}}function aB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...y]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}aB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let d=Q.from*I;g.data.set(A.data.subarray(d,d+I),0);return}aB(g,{data:A.data.subarray(o*Q.from*I),stride:y},I,C);return}const[G,L,k]=Q.to,[r,K,f]=Q.from,M=NC(G,L,k);if(C.length===0){if(k===1&&f===1&&E===1&&o===1){let d=r*I,u=M*I;g.data.set(A.data.subarray(d,d+u),G*I);return}for(let d=0;d<M;d++){let u=o*(r+f*d)*I;g.data.set(A.data.subarray(u,u+I),E*(G+k*d)*I)}return}for(let d=0;d<M;d++)aB({data:g.data.subarray(E*(G+d*k)*I),stride:i},{data:A.data.subarray(o*(r+d*f)*I),stride:y},I,C)}let sB=YD();function YD(){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 nD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?kg(A):{}}async function KD(g,A={}){let I="store"in g?g:new WA(g),B={};return(A.attrs??!0)&&(B=await nD(I)),A.kind==="array"?UC(I,B):A.kind==="group"?tC(I,B):UC(I,B).catch(Q=>(aC(Q,cg),tC(I,B)))}async function UC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new cg("v2 array",{cause:new gQ(I)});return sB.increment(g.store,"v2"),new DB(g.store,g.path,Oi(kg(B),A))}async function tC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new cg("v2 group",{cause:new gQ(I)});return sB.increment(g.store,"v2"),new BQ(g.store,g.path,Vi(kg(B),A))}async function MD(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new cg("v3 array or group",{cause:new gQ(I)});let Q=kg(B);return Q.node_type==="array"&&(Q.fill_value=oC(Q)),Q.node_type==="array"?new DB(A,g.path,Q):new BQ(A,g.path,Q)}async function eD(g,A={}){let I="store"in g?g:new WA(g),B=await MD(I);if(sB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof DB||A.kind==="group"&&B instanceof BQ)return B;let Q=B instanceof DB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function OA(g,A={}){let I="store"in g?g.store:g,B=sB.version_max(I),Q=B==="v2"?OA.v2:OA.v3,C=B==="v2"?OA.v3:OA.v2;return Q(g,A).catch(E=>(aC(E,cg),C(g,A)))}OA.v2=KD,OA.v3=eD;async function HD(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 DQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await HD(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function qD(){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 oQ extends XI{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){qD(),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"),o=globalThis.fetch,y=async(L,k)=>{const K=(k?.method||"GET")==="HEAD"?E:i,f={...k,headers:{...k?.headers,...K}};return o(L,f)},G=globalThis.fetch;globalThis.fetch=y;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=G}}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",o=this.getAmzDate(),y=o.slice(0,8),G=new URL(A),L=G.host,k=G.pathname,r=G.search.slice(1),K=`host:${L}
|
|
411
|
+
${Q}`;return g.replace(YB,C)}const HA=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function rQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(HA[g&255]+HA[g>>8&255]+HA[g>>16&255]+HA[g>>24&255]+"-"+HA[A&255]+HA[A>>8&255]+"-"+HA[A>>16&15|64]+HA[A>>24&255]+"-"+HA[I&63|128]+HA[I>>8&255]+"-"+HA[I>>16&255]+HA[I>>24&255]+HA[B&255]+HA[B>>8&255]+HA[B>>16&255]+HA[B>>24&255]).toLowerCase()}class nB{uuid=rQ()}var oI=1e-6,JA=typeof Float32Array<"u"?Float32Array:Array,wE=Math.PI/180;function SE(g){return g*wE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function YQ(){var g=new JA(9);return JA!=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 RE(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 PA(){var g=new JA(16);return JA!=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 zg(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],y=A[7],G=A[8],L=A[9],k=A[10],r=A[11],K=A[12],f=A[13],M=A[14],d=A[15],u=I*i-B*E,x=I*o-Q*E,X=I*y-C*E,O=B*o-Q*i,Z=B*y-C*i,DA=Q*y-C*o,oA=G*f-L*K,EA=G*M-k*K,sA=G*d-r*K,yA=L*M-k*f,fA=L*d-r*f,YA=k*d-r*M,iA=u*YA-x*fA+X*yA+O*sA-Z*EA+DA*oA;return iA?(iA=1/iA,g[0]=(i*YA-o*fA+y*yA)*iA,g[1]=(Q*fA-B*YA-C*yA)*iA,g[2]=(f*DA-M*Z+d*O)*iA,g[3]=(k*Z-L*DA-r*O)*iA,g[4]=(o*sA-E*YA-y*EA)*iA,g[5]=(I*YA-Q*sA+C*EA)*iA,g[6]=(M*X-K*DA-d*x)*iA,g[7]=(G*DA-k*X+r*x)*iA,g[8]=(E*fA-i*sA+y*oA)*iA,g[9]=(B*sA-I*fA-C*oA)*iA,g[10]=(K*Z-f*X+d*u)*iA,g[11]=(L*X-G*Z-r*u)*iA,g[12]=(i*EA-E*yA-o*oA)*iA,g[13]=(I*yA-B*EA+Q*oA)*iA,g[14]=(f*x-K*O-M*u)*iA,g[15]=(G*O-L*x+k*u)*iA,g):null}function _g(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],y=A[6],G=A[7],L=A[8],k=A[9],r=A[10],K=A[11],f=A[12],M=A[13],d=A[14],u=A[15],x=I[0],X=I[1],O=I[2],Z=I[3];return g[0]=x*B+X*i+O*L+Z*f,g[1]=x*Q+X*o+O*k+Z*M,g[2]=x*C+X*y+O*r+Z*d,g[3]=x*E+X*G+O*K+Z*u,x=I[4],X=I[5],O=I[6],Z=I[7],g[4]=x*B+X*i+O*L+Z*f,g[5]=x*Q+X*o+O*k+Z*M,g[6]=x*C+X*y+O*r+Z*d,g[7]=x*E+X*G+O*K+Z*u,x=I[8],X=I[9],O=I[10],Z=I[11],g[8]=x*B+X*i+O*L+Z*f,g[9]=x*Q+X*o+O*k+Z*M,g[10]=x*C+X*y+O*r+Z*d,g[11]=x*E+X*G+O*K+Z*u,x=I[12],X=I[13],O=I[14],Z=I[15],g[12]=x*B+X*i+O*L+Z*f,g[13]=x*Q+X*o+O*k+Z*M,g[14]=x*C+X*y+O*r+Z*d,g[15]=x*E+X*G+O*K+Z*u,g}function NE(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 UE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=Q+Q,y=C+C,G=E+E,L=Q*o,k=Q*y,r=Q*G,K=C*y,f=C*G,M=E*G,d=i*o,u=i*y,x=i*G,X=B[0],O=B[1],Z=B[2];return g[0]=(1-(K+M))*X,g[1]=(k+x)*X,g[2]=(r-u)*X,g[3]=0,g[4]=(k-x)*O,g[5]=(1-(L+M))*O,g[6]=(f+d)*O,g[7]=0,g[8]=(r+u)*Z,g[9]=(f-d)*Z,g[10]=(1-(L+K))*Z,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function tE(g,A,I,B,Q){var C=1/Math.tan(A/2),E;return 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?(E=1/(B-Q),g[10]=(Q+B)*E,g[14]=2*Q*B*E):(g[10]=-1,g[14]=-2*B),g}var kE=tE;function cE(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),y=1/(C-E);return g[0]=-2*i,g[1]=0,g[2]=0,g[3]=0,g[4]=0,g[5]=-2*o,g[6]=0,g[7]=0,g[8]=0,g[9]=0,g[10]=2*y,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*y,g[15]=1,g}var LE=cE;function JE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],y=B[2],G=Q-I[0],L=C-I[1],k=E-I[2],r=G*G+L*L+k*k;r>0&&(r=1/Math.sqrt(r),G*=r,L*=r,k*=r);var K=o*k-y*L,f=y*G-i*k,M=i*L-o*G;return r=K*K+f*f+M*M,r>0&&(r=1/Math.sqrt(r),K*=r,f*=r,M*=r),g[0]=K,g[1]=f,g[2]=M,g[3]=0,g[4]=L*M-k*f,g[5]=k*K-G*M,g[6]=G*f-L*K,g[7]=0,g[8]=G,g[9]=L,g[10]=k,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function FA(){var g=new JA(3);return JA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function XA(g){var A=new JA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function nQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function CA(g,A,I){var B=new JA(3);return B[0]=g,B[1]=A,B[2]=I,B}function wg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function ZI(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function $g(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function rE(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function YE(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function AB(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function KQ(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 MQ(g,A){var I=A[0]-g[0],B=A[1]-g[1],Q=A[2]-g[2];return Math.hypot(I,B,Q)}function eQ(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 nE(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 KB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return g[0]=Q*o-C*i,g[1]=C*E-B*o,g[2]=B*i-Q*E,g}function KE(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,y=i*E,G=3*C*i,L=3*o*E,k=o*C;return g[0]=A[0]*y+I[0]*G+B[0]*L+Q[0]*k,g[1]=A[1]*y+I[1]*G+B[1]*L+Q[1]*k,g[2]=A[2]*y+I[2]*G+B[2]*L+Q[2]*k,g}function IB(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 ME(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)<=oI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=oI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=oI*Math.max(1,Math.abs(Q),Math.abs(i))}var MB=rE,eE=nQ;(function(){var g=FA();return function(A,I,B,Q,C,E){var i,o;for(I||(I=3),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 bI(){var g=new JA(4);return JA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function HE(g){var A=new JA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function gB(g,A,I,B){var Q=new JA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function qE(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function dE(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 Sg(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=bI();return function(A,I,B,Q,C,E){var i,o;for(I||(I=4),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 eB(){var g=new JA(4);return JA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function lE(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 pE(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],y=I[2],G=I[3];return g[0]=B*G+E*i+Q*y-C*o,g[1]=Q*G+E*o+C*i-B*y,g[2]=C*G+E*y+B*o-Q*i,g[3]=E*G-B*i-Q*o-C*y,g}function HB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],y=I[1],G=I[2],L=I[3],k,r,K,f,M;return r=Q*o+C*y+E*G+i*L,r<0&&(r=-r,o=-o,y=-y,G=-G,L=-L),1-r>oI?(k=Math.acos(r),K=Math.sin(k),f=Math.sin((1-B)*k)/K,M=Math.sin(B*k)/K):(f=1-B,M=B),g[0]=f*Q+M*o,g[1]=f*C+M*y,g[2]=f*E+M*G,g[3]=f*i+M*L,g}function qQ(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 WE=HE,mE=qE,qB=fE;(function(){var g=FA(),A=CA(1,0,0),I=CA(0,1,0);return function(B,Q,C){var E=HQ(Q,C);return E<-.999999?(KB(g,A,Q),eE(g)<1e-6&&KB(g,I,Q),nE(g,g),lE(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(KB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,qB(B,B))}})(),function(){var g=eB(),A=eB();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=YQ();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],qB(A,qQ(A,g))}}();function dQ(){var g=new JA(2);return JA!=Float32Array&&(g[0]=0,g[1]=0),g}function fQ(g){var A=new JA(2);return A[0]=g[0],A[1]=g[1],A}function rA(g,A){var I=new JA(2);return I[0]=g,I[1]=A,I}function TE(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function xE(g){var A=g[0],I=g[1];return A*A+I*I}function ZE(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 lQ(g,A){return g[0]===A[0]&&g[1]===A[1]}function dB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=oI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=oI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=dQ();return function(A,I,B,Q,C,E){var i,o;for(I||(I=2),B||(B=0),Q?o=Math.min(Q*I+B,A.length):o=A.length,i=B;i<o;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 aI{min;max;constructor(A,I){this.min=A?XA(A):CA(1/0,1/0,1/0),this.max=I?XA(I):CA(-1/0,-1/0,-1/0)}clone(){return new aI(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=[CA(I[0],I[1],I[2]),CA(I[0],I[1],B[2]),CA(I[0],B[1],I[2]),CA(I[0],B[1],B[2]),CA(B[0],I[1],I[2]),CA(B[0],I[1],B[2]),CA(B[0],B[1],I[2]),CA(B[0],B[1],B[2])];this.min=CA(1/0,1/0,1/0),this.max=CA(-1/0,-1/0,-1/0);const C=FA();for(const E of Q)IB(C,E,A),this.expandWithPoint(C)}}const bE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class uI extends nB{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 aI,Q=FA();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 uE{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(G=>{const L=bE[G.type];this.gl_.vertexAttribPointer(L,G.itemSize,this.gl_.FLOAT,!1,i,G.offset),this.gl_.enableVertexAttribArray(L)});const o={vao:I,vbo:C},{indexData:y}=A;if(y.length){const G=this.gl_.ELEMENT_ARRAY_BUFFER,L=this.gl_.createBuffer();if(!L)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(G,L),this.gl_.bufferData(G,y,this.gl_.STATIC_DRAW),o.ebo=L}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class PE{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}get textureInfo(){return{textures:this.textureCount_,totalBytes:this.gpuTextureBytes_}}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 V.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),o=0;for(let y=0;y<Q;y++)o+=E*i*C*B,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class ZA{min;max;constructor(A,I){this.min=A?fQ(A):rA(1/0,1/0),this.max=I?fQ(I):rA(-1/0,-1/0)}clone(){return new ZA(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 lQ(A.min,I.min)&&lQ(A.max,I.max)}floor(){return new ZA(rA(Math.floor(this.min[0]),Math.floor(this.min[1])),rA(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 OE{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_&&ZA.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_&&ZA.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 VE=NE(PA(),[1,-1,1]);class pQ extends IE{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,V.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),this.programs_=new FE(I),this.bindings_=new uE(I),this.textures_=new PE(I),this.state_=new OE(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new ZA(rA(0,0),rA(this.width,this.height));if(ZA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(ZA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{V.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(I),this.renderedObjectsPerFrame_=0,this.clear();const{opaque:Q,transparent:C}=A.layerManager.partitionLayers();this.state_.setDepthMask(!0);const E=A.camera.frustum,i={viewport:A};for(const o of Q)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!1);for(const o of C)o.update(i),o.state==="ready"&&this.renderLayer(o,A.camera,E);this.state_.setDepthMask(!0),this.renderedObjects_=this.renderedObjectsPerFrame_}get textureInfo(){return this.textures_.textureInfo}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];this.state_.setCullFaceMode(Q.cullFaceMode),this.state_.setDepthTesting(Q.depthTest),this.state_.setDepthMask(Q.depthTest),this.bindings_.bindGeometry(Q.geometry),Q.popStaleTextures().forEach(E=>{this.textures_.disposeTexture(E)}),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=_g(PA(),C.viewMatrix,I.transform.matrix),i=_g(PA(),VE,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],y=I.getUniforms(),L={...B.getUniforms(),...y};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,o);break;case"u_opacity":Q.setUniform(K,B.opacity);break;case"CameraPositionModel":{const f=zg(PA(),E),M=gB(0,0,0,1),d=Sg(bI(),M,f);Q.setUniform(K,CA(d[0],d[1],d[2]));break}default:K in L&&Q.setUniform(K,L[K])}const k=this.glGetPrimitive(A.primitive),r=A.indexData;r.length?this.gl_.drawElements(k,r.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(k,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 ZA(rA(0,0),rA(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 XE=8;class jE{maxConcurrent_;pending_=[];running_=new Map;constructor(A=XE){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),V.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),V.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"&&V.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const WQ=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function mQ(g){if(WQ.some(I=>g instanceof I))return!0;const A=WQ.map(I=>I.name);return V.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function vE(g,A){return Math.round((A-g.translation)/g.scale)}function fB(g,A,I=1e-6){return Math.abs(g-A)<=I}function Rg(g,A,I){return Math.max(A,Math.min(I,g))}const lB=Symbol("INTERNAL_POLICY_KEY");class zE{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,V.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_=xE(rA(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}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]}updateChunkStatesForVolume(A){const I=this.store_.getTimeIndex(A),B=this.store_.getChunksAtTime(I);if(B.length===0){V.warn("ChunkStoreView","updateChunkStatesForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.setLOD(0),this.chunkViewStates_.forEach(pB);for(const Q of B){if(Q.lod!==this.currentLOD_||!(A.c===void 0||A.c===Q.chunkIndex.c))continue;const E=this.policy_.priorityMap.visibleCurrent;this.chunkViewStates_.set(Q,{visible:!0,prefetch:!1,priority:E,orderKey:0})}this.lastTCoord_=A.t}updateChunkStates(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,o=I.getBoxRelativeTo(i).toRect().width,y=E/o,G=Math.log2(1/y);this.setLOD(G);const L=this.getZBounds(A);(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(L)||this.lastTCoord_!==A.t)&&(this.updateChunkViewStates(A,C),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=L,this.lastTCoord_=A.t)}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(pB)}setImageSourcePolicy(A,I){if(I!==lB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,V.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(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),y=Math.max(o,Math.min(i,this.policy_.lod.max)),G=Rg(E,o,y);G!==this.currentLOD_&&(this.currentLOD_=G)}updateChunkViewStates(A,I){const B=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(B).length===0){V.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const C=dQ();ZE(C,I.min,I.max,.5);const[E,i]=this.getZBounds(A),o=new aI(CA(I.min[0],I.min[1],E),CA(I.max[0],I.max[1],i));this.chunkViewStates_.forEach(pB),this.updateChunksAtTimeIndex(B,A,o,C),A.t!==void 0&&this.markTimeChunksForPrefetch(B,A,o,C)}isChunkChannelInSlice(A,I){return I.c===void 0||I.c===A.chunkIndex.c}updateChunksAtTimeIndex(A,I,B,Q){const C=this.getPaddedBounds(B),E=this.store_.getChunksAtTime(A),i=this.fallbackLOD();for(const o of E){const y=this.isChunkWithinBounds(o,B),G=this.isChunkChannelInSlice(o,I),L=o.lod===this.currentLOD_,k=o.lod===i,r=!y&&G&&L&&this.isChunkWithinBounds(o,C),K=y&&G,f=this.computePriority(k,L,y,r,G);if(f!==null){const M=this.squareDistance2D(o,Q);this.chunkViewStates_.set(o,{visible:K,prefetch:r,priority:f,orderKey:M})}}}markTimeChunksForPrefetch(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();for(let o=A+1;o<=E;++o)for(const y of this.store_.getChunksAtTime(o)){if(y.lod!==i||!this.isChunkChannelInSlice(y,I)||!this.isChunkWithinBounds(y,B))continue;const G=this.policy_.priorityMap.prefetchTime,L=this.squareDistance2D(y,Q),k=Rg(L/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),r=o-A+k;this.chunkViewStates_.set(y,{visible:!1,prefetch:!0,priority:G,orderKey:r})}}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 aI(CA(A.offset.x,A.offset.y,A.offset.z),CA(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 aI.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 G=I.lods[this.currentLOD_];return[G.translation,G.translation+G.size*G.scale]}const B=I.lods[this.currentLOD_],Q=B.size,C=B.scale,E=B.translation,i=Math.floor((A.z-E)/C),o=B.chunkSize,y=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(Q/o)-1));return[E+y*o*C,E+(y+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!dB(this.lastViewBounds2D_.min,A.min)||!dB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!dB(this.lastZBounds_,A)}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 o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new aI(CA(A.min[0]-E,A.min[1]-i,A.min[2]-o),CA(A.max[0]+E,A.max[1]+i,A.max[2]+o))}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 pB(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class _E{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],o=this.dimensions_.y.lods[E],y=this.dimensions_.z?.lods[E],G=i.chunkSize,L=o.chunkSize,k=y?.chunkSize??1,r=Math.ceil(i.size/G),K=Math.ceil(o.size/L),f=Math.ceil((y?.size??1)/k);for(let M=0;M<B;++M)for(let d=0;d<r;++d){const u=i.translation+d*i.chunkSize*i.scale;for(let x=0;x<K;++x){const X=o.translation+x*o.chunkSize*o.scale;for(let O=0;O<f;++O){const Z=y!==void 0?y.translation+O*k*y.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(G,i.size-d*G),y:Math.min(L,o.size-x*L),z:Math.min(k,(y?.size??1)-O*k),c:1},rowAlignmentBytes:1,chunkIndex:{x:d,y:x,z:O,c:M,t:Q},scale:{x:i.scale,y:o.scale,z:y?.scale??1},offset:{x:u,y:X,z:Z}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:vE(this.dimensions_.t.lods[0],A.t)}get lodCount(){return this.lowestResLOD_+1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}loadChunkData(A,I){return this.loader_.loadChunkData(A,I)}createView(A){const I=new zE(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 y of this.views_){const G=y.chunkViewStates.get(A);G&&(G.visible&&(I=!0),G.prefetch&&(B=!0),G.priority!==null&&(Q===null||G.priority<Q)&&(Q=G.priority,C=G.orderKey),!G.visible&&!G.prefetch&&G.priority===null&&y.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,V.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(!fB(Q,2,.02)||!fB(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;if(I.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in t. Found ${I.chunkSize} at LOD ${A}`);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.chunkSize!==1)throw new Error(`ChunkStore only supports a chunk size of 1 in c. Found ${I.chunkSize} at LOD ${A}`);if(I.scale!==1)throw new Error(`ChunkStore does not support scale in c. Found ${I.scale} at LOD ${A}`);if(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 $E{stores_=new Map;pendingStores_=new Map;queue_=new jE;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 _E(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 Ng=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(L){L.preventDefault(),Q(++A%I.children.length)},!1);function B(L){return I.appendChild(L.dom),L}function Q(L){for(var k=0;k<I.children.length;k++)I.children[k].style.display=k===L?"block":"none";A=L}var C=(performance||Date).now(),E=C,i=0,o=B(new Ng.Panel("FPS","#0ff","#002",g)),y=B(new Ng.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var G=B(new Ng.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 L=(performance||Date).now();if(y.update(L-C,200),L>=E+1e3&&(o.update(i*1e3/(L-E),100),E=L,i=0,G)){var k=performance.memory;G.update(k.usedJSHeapSize/1048576,k.jsHeapSizeLimit/1048576)}return L},update:function(){C=this.end()},domElement:I,setMode:Q}};Ng.Panel=function(g,A,I,B){var Q=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*B),y=E(48*i*B),G=E(3*i*B),L=E(2*i*B),k=E(3*i*B),r=E(15*i*B),K=E(74*i*B),f=E(30*i*B),M=document.createElement("canvas");M.width=o,M.height=y,M.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var d=M.getContext("2d");return d.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",d.textBaseline="top",d.fillStyle=I,d.fillRect(0,0,o,y),d.fillStyle=A,d.fillText(g,G,L),d.fillRect(k,r,K,f),d.fillStyle=I,d.globalAlpha=.9,d.fillRect(k,r,K,f),{dom:M,update:function(u,x){Q=Math.min(Q,u),C=Math.max(C,u),d.fillStyle=I,d.globalAlpha=1,d.fillRect(0,0,o,r),d.fillStyle=A,d.fillText(E(u)+" "+g+" ("+E(Q)+"-"+E(C)+")",G,L),d.drawImage(M,k+i,r,K-i,f,k,r,K-i,f),d.fillRect(k+K-i,r,i,f),d.fillStyle=I,d.globalAlpha=.9,d.fillRect(k+K-i,r,i,E((1-u/x)*f))}}};function Ai({scale:g}={scale:1.5}){const A=new Ng(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 WB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function Ii(g){return WB.includes(g)}class gi{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 Bi{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){V.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,WB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){V.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,WB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!Ii(A.type)){V.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new gi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class xQ{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 Bi(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=rA(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,o=I.x-C,y=I.y-E,G=Math.floor(o),L=Math.floor(i-y-I.height),k=Math.floor(I.width),r=Math.floor(I.height);return new ZA(rA(G,L),rA(G+k,L+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return CA(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 ZA(rA(B,Q),rA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){V.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 Qi(g){const A=new Map,I=new Set;for(const B of g){if(I.has(B.id))throw new Error(`Duplicate viewport ID "${B.id}". Each viewport must have a unique ID.`);if(I.add(B.id),A.has(B.element)){const Q=A.get(B.element),C=B.element.tagName.toLowerCase()+(B.element.id?`#${B.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${Q}" and "${B.id}" both use ${C}`)}A.set(B.element,B.id)}}function ZQ(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??rQ(),layerManager:new TQ(I)}});return Qi(B),B.map(Q=>new xQ(Q))}class Ci{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=A,this.onChange_=I}connect(){if(this.resizeObserver_){V.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_){V.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class Ei{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;constructor(A){if(this.canvas=A.canvas,A.viewports.length===0)throw new Error("At least one viewport config must be specified.");this.renderer_=new pQ(this.canvas),this.chunkManager_=new $E,this.context_={chunkManager:this.chunkManager_},this.viewports_=ZQ(A.viewports,this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Ai());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new Ci(I,()=>{this.renderer_.updateSize();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get textureInfo(){return this.renderer_.textureInfo}get viewports(){return this.viewports_}getViewport(A){return this.viewports_.find(I=>I.id===A)}start(){if(V.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}else V.warn("Idetik","Idetik runtime already started");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(V.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)V.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 ii extends uI{constructor(A){if(super(),A.primitive!="triangles"){V.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){V.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 o=Math.min(E,i),y=Math.max(E,i);I.has({i0:o,i1:y})||(I.add({i0:o,i1:y}),B.push(o,y))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],y=C[E+2];Q(i,o),Q(o,y),Q(y,i)}this.indexData_=new Uint32Array(B)}}const Di=CA(0,1,0);class oi{dirty_=!0;matrix_=PA();rotation_=eB();translation_=FA();scale_=CA(1,1,1);addRotation(A){pE(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){mE(this.rotation_,A),this.dirty_=!0}get rotation(){return WE(this.rotation_)}addTranslation(A){$g(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){wg(this.translation_,A),this.dirty_=!0}get translation(){return XA(this.translation_)}addScale(A){YE(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){wg(this.scale_,A),this.dirty_=!0}targetTo(A){ME(this.translation_,A)&&(A=XA(A),A[2]+=oI);const I=JE(PA(),this.translation_,A,Di),B=RE(YQ(),I);qQ(this.rotation_,B),qB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return XA(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return zg(PA(),this.matrix)}computeMatrix(){UE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class PI extends nB{wireframeEnabled=!1;wireframeColor=QA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new oi;geometry_=new uI;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 ii(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(){if(this.programName_===null)throw new Error("Program name not set");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=CA(0,1,0),I=0){this.normal=XA(A),this.signedDistance=I}set(A,I){this.normal=XA(A),this.signedDistance=I}signedDistanceToPoint(A){return HQ(this.normal,A)+this.signedDistance}normalize(){const A=nQ(this.normal);if(A>0){const I=1/A;AB(this.normal,this.normal,I),this.signedDistance*=I}}}class bQ{planes_;constructor(A){this.planes_=[new LI(FA(),0),new LI(FA(),0),new LI(FA(),0),new LI(FA(),0),new LI(FA(),0),new LI(FA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=FA();this.planes_[0].set(ZI(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(ZI(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(ZI(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(ZI(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(ZI(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(ZI(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=FA();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 uQ extends PI{projectionMatrix_=PA();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 CA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return CA(A[4],A[5],A[6])}get frustum(){return new bQ(_g(PA(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=gB(A[0],A[1],A[2],1),B=zg(PA(),this.projectionMatrix_),Q=Sg(bI(),I,B);dE(Q,Q,1/Q[3]);const C=Sg(bI(),Q,this.transform.matrix);return CA(C[0],C[1],C[2])}}const PQ=1.77,OQ=128,VQ=128/PQ;class ai extends uQ{width_=OQ;height_=VQ;viewportAspectRatio_=PQ;viewportSize_=[OQ,VQ];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=gB(-1,-1,0,1),I=gB(1,1,0,1);const B=_g(PA(),this.projectionMatrix,this.viewMatrix),Q=zg(PA(),B);return A=Sg(bI(),A,Q),I=Sg(bI(),I,Q),new ZA(rA(A[0],A[1]),rA(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],LE(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const si=60,yi=1.77,BB=.1,mB=180-BB;class hi extends uQ{fov_;aspectRatio_;constructor(A={}){const{fov:I=si,aspectRatio:B=yi,near:Q=.1,far:C=1e4,position:E=CA(0,0,0)}=A;if(I<BB||I>mB)throw new Error(`Invalid field of view: ${I}, must be in [${BB}, ${mB}] 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(BB,Math.min(mB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){kE(this.projectionMatrix_,SE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const XQ=0;class Gi{camera_;dragActive_=!1;dragStart_=FA();constructor(A){this.camera_=A}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=XA(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=MB(FA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==XQ||(this.dragStart_=XA(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=MB(FA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==XQ||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class QI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&V.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Rg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&V.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Rg(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 QB extends uI{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,o)=>E+MQ(i,A[o+1]??i),0);for(const E of[...Array(A.length).keys()]){for(const i of[-1,1]){const o=A[E];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const y=A[E-1]??A[E];I[B++]=y[0],I[B++]=y[1],I[B++]=y[2];const G=A[E+1]??A[E];I[B++]=G[0],I[B++]=G[1],I[B++]=G[2],I[B++]=i,I[B++]=Q}Q+=MQ(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 TB extends PI{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 Fi extends QI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(xB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(xB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(xB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function xB(g){const{end:A,width:I,color:B}=g,Q=new QB([[0,0,0],A]);return new TB({geometry:Q,color:B,width:I})}class wi extends QI{type="ProjectedLineLayer";paths_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){const{path:I,color:B,width:Q}=A;this.paths_.push(I);const C=new QB(I);this.addObject(new TB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Si(this.paths_.flat())}}function Si(g){function A(o){const y=g.map(G=>G[o]);return[Math.min(...y),Math.max(...y)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}class Ri extends QI{type="TracksLayer";tracks_=[];constructor(A=[]){super(),A.forEach(I=>this.addLine(I)),this.setState("ready")}addLine(A){this.tracks_.push(A);let I;if(A.interpolation){const i=Ui({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new QB(i)}else I=new QB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new TB({geometry:I,color:B,width:Q,taperOffset:C,taperPower:E}))}setTimeIndex(A){for(const[I,B]of this.tracks_.entries()){if(!B.time)continue;let Q=.5;A<B.time[0]?Q=-1.5:A>B.time[B.time.length-1]&&(Q=1.5);const C=B.time.findIndex(i=>i===A);B.time&&C!==-1&&(Q=C/(B.time.length-1));const E=this.objects[I];E.taperOffset=Q}}update(){}get extent(){const A=this.tracks_.map(I=>I.path);return Ni(A.flat())}}function Ni(g){function A(o){const y=g.map(G=>G[o]);return[Math.min(...y),Math.max(...y)]}const[I,B]=A(0),[Q,C]=A(1),[E,i]=A(2);return{xMin:I,xMax:B,yMin:Q,yMax:C,zMin:E,zMax:i}}function Ui({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=ti(g),Q=Array((g.length-1)*A);for(let C=0;C<g.length-1;C++){const E=g[C],i=g[C+1],o=XA(B[C]);KQ(o,E,o,I);const y=XA(B[C+1]);KQ(y,i,y,-I);for(let G=0;G<A;G++){const L=G/A,k=Q[C*A+G]=FA();KE(k,E,o,y,i,L)}}return Q}function ti(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=FA(),B=FA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=FA(),Q!==0&&wg(I,B),Q!==g.length-1&&MB(B,E,C),Q===0?wg(A[Q],B):Q==g.length-1?wg(A[Q],I):($g(A[Q],I,B),AB(A[Q],A[Q],.5))}return A}class jQ extends uI{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,y=i+1,G=o+1,L=A/i,k=I/o;for(let r=0;r<G;++r){const K=r*k;for(let f=0;f<y;++f){const M=f*L,d=f/i,u=r/o,x=[M,K,0],X=[0,0,1],O=[d,u];C.push(...x,...X,...O)}}for(let r=0;r<o;++r)for(let K=0;K<i;++K){const f=K+y*r,M=K+y*(r+1),d=K+1+y*(r+1),u=K+1+y*r;E.push(f,M,u),E.push(M,d,u)}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})}}function vQ(g){return g===1||g===2||g===4||g===8}function OI(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 ki(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 ZB extends nB{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 zQ=32;function bB(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=ci(B,g):B===void 0&&(V.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function _Q(g,A){if(A.length>zQ)throw new Error(`Maximum number of channels is ${zQ}`);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=>bB(g,I))}function ci(g,A){if(g===void 0)return ki(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class uB extends PI{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new jQ(A,I,1,1),this.setTexture(0,B),this.channels_=_Q(B,Q),this.programName=Li(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=_Q(this.textures[0],A)}setChannelProperty(A,I,B){const Q=bB(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]??bB(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 Li(g){if(g.type==="Texture2D")return Ji(g.dataType);if(g.type==="Texture2DArray")return ri(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function Ji(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 ri(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 VI extends ZB{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=OI(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!=OI(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 VI(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function PB(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return rA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=rA(C.clientX,C.clientY);if(TE(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const y=I(o);y!==null&&B({world:o,value:y})}return null}return A}case"pointercancel":return null;default:return A}}class $Q{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&V.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),V.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class OB extends QI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new $Q;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("ChunkedImageLayer cannot be attached to multiple contexts simultaneously.");this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.policy_)}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_.updateChunkStates(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_>OB.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_=PB(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,lB))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Rg(Q,0,A.shape.z-1);fB(B,C,1+1e-6)||V.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(AC(A));return B?(B.textures[0].updateWithChunk(A,this.getDataForImage(A)),this.updateImageChunk(B,A),this.channelProps_&&B.setChannelProps(this.channelProps_),B):this.createImage(A)}createImage(A){const I=new uB(A.shape.x,A.shape.y,VI.createWithChunk(A,this.getDataForImage(A)),this.channelProps_??[{}]);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){V.warn("ChunkedImageLayer","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=IB(FA(),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,o=E*A.shape.x+C;return i[o]}return null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,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=>{I.setChannelProps(A)}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const B=this.visibleChunks_.get(I);B&&(this.pool_.release(AC(I),B),this.visibleChunks_.delete(I))}}}function AC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class Yi extends uI{constructor(A,I,B,Q,C,E){super();const i=[],o=[],y=Math.floor(Q),G=Math.floor(C),L=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,L,G,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,L,G,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,y,L,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,y,L,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,y,G,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,y,G,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,B,Q,C,E,i,o,y,G,L,k,r){const K=E/y,f=i/G,M=E/2,d=i/2,u=o/2*L,x=y+1,X=G+1,O=k.length/8;for(let Z=0;Z<X;Z++){const DA=-d+Z*f;for(let oA=0;oA<x;oA++){const EA=-M+oA*K,sA={x:0,y:0,z:0};sA[A]=EA*Q,sA[I]=DA*C,sA[B]=u;const yA={x:0,y:0,z:0};yA[B]=L;const fA=oA/y,YA=1-Z/G;k.push(sA.x,sA.y,sA.z,yA.x,yA.y,yA.z,fA,YA)}}for(let Z=0;Z<G;Z++)for(let DA=0;DA<y;DA++){const oA=O+DA+x*Z,EA=O+DA+x*(Z+1),sA=O+(DA+1)+x*(Z+1),yA=O+(DA+1)+x*Z;r.push(oA,EA,yA,EA,sA,yA)}}}class ni extends PI{constructor(A){super(),this.geometry=new Yi(1,1,1,1,1,1),this.setTexture(0,A),this.programName=Ki(A.dataType),this.cullFaceMode="front",this.depthTest=!1}get type(){return"VolumeRenderable"}}function Ki(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"}}class CB extends ZB{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=OI(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!=OI(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 CB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class Mi extends QI{type="VolumeLayer";source_;sliceCoords_;currentChunks_=new Map;pool_=new $Q;sourcePolicy_;chunkStoreView_;lastLoadedTime_=void 0;debugShowWireframes_=!1;debugShowDegenerateRays=!1;color=CA(1,1,1);samplesPerUnit=128;maxIntensity=255;opacityMultiplier=.1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentChunks_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,lB))}createVolume(A){const I=new ni(CB.createWithChunk(A));return this.updateVolumeChunk(I,A),I}constructor({source:A,sliceCoords:I,policy:B}){super({transparent:!0,blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=B,this.setState("initialized")}getVolumeForChunk(A){const I=this.currentChunks_.get(A);if(I)return I;const B=this.pool_.acquire(IC(A));return B?(B.textures[0].updateWithChunk(A),this.updateVolumeChunk(B,A),B):this.createVolume(A)}async onAttached(A){this.chunkStoreView_=await A.chunkManager.addView(this.source_,this.sourcePolicy_)}onDetached(A){this.chunkStoreView_&&(this.releaseAndRemoveChunks(this.currentChunks_.keys()),this.clearObjects(),this.chunkStoreView_.dispose(),this.chunkStoreView_=void 0)}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(this.sliceCoords_),I=this.sliceCoords_.t??-1;if(!(this.lastLoadedTime_!==I||A.length!==this.currentChunks_.size))return;const Q=new Set(A),C=Array.from(this.currentChunks_.keys()).filter(E=>!Q.has(E));this.releaseAndRemoveChunks(C),this.clearObjects();for(const E of A){const i=this.getVolumeForChunk(E);i.wireframeEnabled=this.debugShowWireframes,this.currentChunks_.set(E,i),this.addObject(i)}this.lastLoadedTime_=I,this.state!=="ready"&&this.setState("ready")}updateVolumeChunk(A,I){A.transform.setScale([I.shape.x*I.scale.x,I.shape.y*I.scale.y,I.shape.z*I.scale.z]);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveChunks(A){for(const I of A){const B=this.currentChunks_.get(I);B&&(this.pool_.release(IC(I),B),this.currentChunks_.delete(I))}}update(A){if(this.chunkStoreView_){if(A===void 0)throw new Error("RenderContext is required for the VolumeLayer update as camera information is used to reorder the chunks.");this.reorderObjects(A.viewport.camera),this.chunkStoreView_.updateChunkStatesForVolume(this.sliceCoords_),this.updateChunks()}}reorderObjects(A){const I=A.position,B=FA(),Q=FA();this.objects.sort((C,E)=>{$g(B,C.boundingBox.max,C.boundingBox.min),AB(B,B,.5),$g(Q,E.boundingBox.max,E.boundingBox.min),AB(Q,Q,.5);const i=eQ(I,B),y=eQ(I,Q)-i;return Math.abs(y)<oI?0:y})}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),SamplesPerUnit:this.samplesPerUnit,MaxIntensity:this.maxIntensity,OpacityMultiplier:this.opacityMultiplier,VolumeColor:this.color,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function IC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}x${g.shape.z}`,`align${g.rowAlignmentBytes}`].join(":")}class ei extends QI{type="ImageLayer";source_;region_;lod_;onPickValue_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;image_;chunk_;extent_;pointerDownPos_=null;constructor({source:A,region:I,channelProps:B,onPickValue:Q,lod:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.region_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=Q,this.lod_=C}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}onEvent(A){this.pointerDownPos_=PB(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.onPickValue_)}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),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===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.extent_={x:Q.shape.x*Q.scale.x,y:Q.shape.y*Q.scale.y},this.image_=this.createImage(Q),this.chunk_=Q,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new uB(A.shape.x,A.shape.y,VI.createWithChunk(A),this.channelProps);return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.chunk_?.data)return null;const I=IB(FA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B>=0&&B<this.chunk_.shape.x&&Q>=0&&Q<this.chunk_.shape.y){const C=Q*this.chunk_.shape.x+B;return this.chunk_.data[C]}return null}}class Ug extends ZB{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=OI(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!=OI(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 Ug(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const Hi=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function qi(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,QA.from(I)]))}function di(g){return g=g??Hi,g.map(QA.from)}class gC{lookupTable;cycle;constructor(A={}){this.lookupTable=qi(A.lookupTable),this.cycle=di(A.cycle)}}const fi=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function li(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!fi.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class pi extends PI{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new jQ(A.width,A.height,1,1),this.setTexture(0,li(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 Ug(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 Ug(C,Q,2)}}class Wi extends QI{type="LabelImageLayer";source_;region_;lod_;colorMap_;onPickValue_;outlineSelected_;image_;imageChunk_;pointerDownPos_=null;selectedValue_=null;constructor({source:A,region:I,colorMap:B={},onPickValue:Q,lod:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.region_=I,this.colorMap_=new gC(B),this.onPickValue_=Q,this.lod_=C,this.outlineSelected_=E}update(){switch(this.state){case"initialized":this.load(this.region_);break;case"loading":case"ready":break;default:{const A=this.state;throw new Error(`Unhandled LayerState case: ${A}`)}}}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new gC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=PB(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}async load(A){if(this.state!=="initialized")throw new Error("Trying to load chunks more than once.");this.setState("loading");const I=await this.source_.open(),B=this.lod_??I.getSourceDimensionMap().numLods-1,Q=await I.loadRegion(A,B);this.image_=this.createImage(Q),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new pi({width:A.shape.x,height:A.shape.y,imageData:Ug.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.transform.setScale([A.scale.x,A.scale.y,1]),I.transform.setTranslation([A.offset.x,A.offset.y,0]),I}getValueAtWorld(A){if(!this.image_||!this.imageChunk_?.data)return null;const I=IB(FA(),A,this.image_.transform.inverse),B=Math.floor(I[0]),Q=Math.floor(I[1]);if(B<0||B>=this.imageChunk_.shape.x||Q<0||Q>=this.imageChunk_.shape.y)return null;const C=Q*this.imageChunk_.shape.x+B;return this.imageChunk_.data[C]}}class EB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,EB.prototype)}}class mi{maxConcurrent_;pending_=[];abortController_=new AbortController;numRunning_=0;constructor(A){if(A<=0)throw Error(`maxConcurrent (${A}) must be positive`);this.maxConcurrent_=A}async submit(A){return this.abortController_.signal.throwIfAborted(),new Promise((I,B)=>{const Q=async()=>{try{this.abortController_.signal.throwIfAborted();const C=await A();I(C)}catch(C){B(C)}finally{this.numRunning_--,this.maybeRunNext()}};this.pending_.push(Q),this.maybeRunNext()})}maybeRunNext(){if(this.numRunning_>=this.maxConcurrent_)return;const A=this.pending_.shift();A!==void 0&&(this.numRunning_++,A())}get abortSignal(){return this.abortController_.signal}shutdown(){this.abortController_.abort(new EB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class Ti{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new mi(16);lod_;loader_=null;seriesAttributes_;loadingToken_=null;dataChunks_=[];constructor(A){this.source_=A.source,this.region_=A.region,this.lod_=A.lod,this.seriesDimensionName_=A.seriesDimensionName;const I=A.region.find(B=>B.dimension==A.seriesDimensionName);if(I===void 0)throw new Error(`Series dimension '${A.seriesDimensionName}' not in region ${JSON.stringify(A.region)}`);if(I.index.type==="point")throw new Error("Series dimension index in region must be an interval or 'full', not a point value");this.seriesIndex_=I.index}async setPosition(A){const I=await this.loadSeriesAttributes(),B=Math.round((A-I.start)/I.scale);return await this.setIndex(B)}async setIndex(A){const I=this.loadingToken_;if(I){if(I.index===A&&!I.canceled)return V.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};V.debug("ImageSeriesLoader",`Cancelling setIndex request for index ${I.index}, new requested index is ${A}`),I.canceled=!0}let B=this.dataChunks_[A];if(B===void 0){const Q={canceled:!1,index:A};if(this.loadingToken_=Q,B=await this.loadChunkAtIndex(A,Q),Q.canceled)return{success:!1,reason:"canceled"}}return{success:!0,chunk:B}}shutdown(){this.scheduler_.shutdown()}async loadSeriesAttributes(){if(this.seriesAttributes_)return this.seriesAttributes_;const I=(await this.getLoader()).getSourceDimensionMap(),B=this.lod_??I.numLods-1,Q=[I.x,I.y,I.z,I.c,I.t].filter(k=>k!==void 0),C=Q.find(k=>k.name===this.seriesDimensionName_);if(!C){const k=Q.map(r=>r.name).join(", ");throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${k}`)}const E=C.lods[B].scale,i=C.lods[B].size*E,o=this.seriesIndex_.type==="full",y=o?0:this.seriesIndex_.start,G=o?i:this.seriesIndex_.stop,L=Math.round((G-y)/E);return this.dataChunks_=new Array(L),this.seriesAttributes_={start:y,stop:G,scale:E,length:L},this.seriesAttributes_}async loadChunkAtIndex(A,I){const B=await this.loadSeriesAttributes();if(A<0||A>=B.length)throw new Error(`Requested index ${A} is out of bounds [0, ${B.length-1}]`);const Q=B.start+A*B.scale,C=this.region_.filter(y=>y.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=this.lod_??E.getSourceDimensionMap().numLods-1,o=await E.loadRegion(C,i,this.scheduler_);return this.dataChunks_[A]=o,I&&I.canceled&&(this.loadingToken_=null),o}async preloadAllChunks(){const{length:A}=await this.loadSeriesAttributes(),I=[];for(let Q=0;Q<A;Q++)I.push(this.loadChunkAtIndex(Q));const B=await Promise.allSettled(I);for(const Q of B)if(Q.status==="rejected"){if(Q.reason instanceof EB)return Promise.reject(Q.reason);V.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class xi extends QI{type="ImageSeriesLayer";seriesLoader_;initialChannelProps_;channelChangeCallbacks_=[];channelProps_;texture_=null;image_;extent_;constructor({source:A,region:I,seriesDimensionName:B,channelProps:Q,lod:C,...E}){super(E),this.setState("initialized"),this.channelProps_=Q,this.initialChannelProps_=Q,this.seriesLoader_=new Ti({source:A,region:I,seriesDimensionName:B,lod:C})}update(){this.state==="initialized"&&(this.setState("loading"),this.seriesLoader_.loadSeriesAttributes())}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.image_?.setChannelProps(A),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===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}async setPosition(A){const I=await this.seriesLoader_.setPosition(A);return this.processIndexResult(I)}async setIndex(A){const I=await this.seriesLoader_.setIndex(A);return this.processIndexResult(I)}close(){this.seriesLoader_.shutdown()}async preloadSeries(){return this.seriesLoader_.preloadAllChunks()}get extent(){return this.extent_}processIndexResult(A){return A.chunk&&(this.setData(A.chunk),this.setState("ready")),A}setData(A){!this.texture_||!this.image_?(this.texture_=VI.createWithChunk(A),this.image_=this.createImage(A,this.texture_,this.channelProps_),this.addObject(this.image_),this.extent_={x:A.shape.x*A.scale.x,y:A.shape.y*A.scale.y}):A.data&&this.texture_.updateWithChunk(A)}createImage(A,I,B){const Q=new uB(A.shape.x,A.shape.y,I,B);return Q.transform.setScale([A.scale.x,A.scale.y,1]),Q.transform.setTranslation([A.offset.x,A.offset.y,0]),Q}}function BC(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 Zi(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function QC(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 CC(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 bi(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 BC(g,E-A,E,I)}class XI{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return Zi(this.#A,A)}async get(A,I={}){let B=QC(this.url,A).href,Q=await fetch(B,this.#g(I));return CC(Q)}async getRange(A,I,B={}){let Q=QC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await bi(Q,I.suffixLength,C,this.#I):E=await BC(Q,I.offset,I.length,C),CC(E)}}class EC{#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 VB{_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 tg{#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 tg(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 kg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function iC(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 DC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(/v2:([US])(\d+)/);if(A){let[,B,Q]=A;return(B==="U"?tg:VB).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:EC}[g];return kA(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)),kA(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 ui({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 Pi(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(/^([<|>])(.*)$/);kA(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 kA(Q,`Unsupported or unknown dtype: ${g}`),I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function Oi(g,A={}){let I=[],B=Pi(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 Vi(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function Xi(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 ji(g){return g?.name==="sharding_indexed"}function oC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}function aC(g,...A){if(!A.some(I=>g instanceof I))throw g}function kA(g,A=""){if(!g)throw new Error(A)}async function sC(g,{format:A,signal:I}){const B=g instanceof Response?g:new Response(g);kA(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 XB{kind="array_to_array";constructor(A,I){kA(A.keepbits>=0,"keepbits must be zero or positive")}static fromConfig(A,I){return new XB(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 yC=vi();function vi(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function hC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class iB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=DC(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 iB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return yC&&this.#B==="big"&&iC(I,hC(this.#I)),I}decode(A){return yC&&this.#B==="big"&&iC(A,hC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class jB{kind="bytes_to_bytes";static fromConfig(){return new jB}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}class vB{kind="bytes_to_bytes";static fromConfig(A){return new vB}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 sC(A,{format:"gzip"});return new Uint8Array(I)}}function zi(g,A){return kA(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),kA(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),kA(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function _i(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class zB{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:o,strict:y=!0}=A;let G=A.separators;G||(o?G=[", ",": "]:G=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:G,sort_keys:i},this.#I={strict:y}}static fromConfig(A){return new zB(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;kA(B==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];kA(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(zi),i&&o.push(_i);const y=Array.from(A.data);y.push("|O"),y.push(A.shape);let G;o.length&&(G=(k,r)=>{let K=r;for(let f of o)K=f(k,K);return K});let L=JSON.stringify(y,G,I);return Q&&(L=L.replace(/[\u007F-\uFFFF]/g,k=>{const r=`0000${k.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(L)}decode(A){const{strict:I}=this.#I;kA(I,"JsonCodec does not yet support non-strict decoding.");const B=kg(A),Q=B.pop();B.pop(),kA(Q,"0D not implemented for JsonCodec.");const C=JI(Q,"C");return{data:B,shape:Q,stride:C}}}function GC(g){return g instanceof EC||g instanceof VB||g instanceof tg?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function $i(g,A){let I;return g.data instanceof VB||g.data instanceof tg?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 AD(g,A){let I=$i(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=GC(g.data),i=GC(I.data);for(let o=0;o<Q;o++){let y=0;for(let G=0;G<B;G++)y+=C[G]*I.stride[G];i[y]=E[o],C[0]+=1;for(let G=0;G<B;G++)if(C[G]===g.shape[G]){if(G+1===B)break;C[G]=0,C[G+1]+=1}}return I}function ID(g){let A=g.shape.length;return kA(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 gD(g,A){let I=ID(g);return kA(I.length===A.length,"Orders must match"),I.every((B,Q)=>B===A[Q])}class _B{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,o)=>{kA(E[i]===void 0,`Invalid permutation: ${JSON.stringify(B)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new _B(A,I)}encode(A){return gD(A,this.#I)?A:AD(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:JI(A.shape,this.#A)}}}class $B{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=JI(A,"C")}static fromConfig(A,I){return new $B(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 AQ{kind="bytes_to_bytes";static fromConfig(A){return new AQ}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 sC(A,{format:"deflate"});return new Uint8Array(I)}}function BD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>Ka).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>fa).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>xa).then(g=>g.default)).set("gzip",()=>vB).set("zlib",()=>AQ).set("transpose",()=>_B).set("bytes",()=>iB).set("crc32c",()=>jB).set("vlen-utf8",()=>$B).set("json2",()=>zB).set("bitround",()=>XB)}const QD=BD();function IQ(g){let A;return{async encode(I){A||(A=await FC(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 FC(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 FC(g){let A=g.codecs.map(async C=>{let E=await QD.get(C.name)?.();return kA(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||(kA(CD(g),`Cannot encode ${g.data_type} to bytes without a codec`),B=iB.fromConfig({endian:"little"},g)),{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function CD(g){return g.data_type!=="v2:object"}class cg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class gQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}const wC=18446744073709551615n;function ED(g,A,I,B){kA(g.store.getRange,"Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,y)=>o/B.chunk_shape[y]),E=IQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let y=o.map((u,x)=>Math.floor(u/C[x])),G=g.resolve(I(y)).path,L;if(G in i)L=i[G];else{let u=4,x=16*C.reduce((O,Z)=>O*Z,1),X=await Q(G,{suffixLength:x+u});L=i[G]=X?await E.decode(X):null}if(L===null)return;let{data:k,shape:r,stride:K}=L,f=o.map((u,x)=>u%r[x]).reduce((u,x,X)=>u+x*K[X],0),M=k[f],d=k[f+1];if(!(M===wC&&d===wC))return Q(G,{offset:Number(M),length:Number(d)})}}class WA{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 WA(this.store,decodeURIComponent(new URL(A,I).pathname))}}class BQ extends WA{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}function SC(g){return g.find(I=>I.name==="transpose")?.configuration?.order??"C"}const Lg=Symbol("zarrita.context");function iD(g){return g[Lg]}function DD(g,A){let{configuration:I}=A.codecs.find(ji)??{},B={encode_chunk_key:ui(A.chunk_key_encoding),TypedArray:DC(A.data_type),fill_value:A.fill_value};if(I){let C=SC(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:IQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E){return JI(E,C)},get_chunk_bytes:ED(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=SC(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:IQ({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),o=g.resolve(i).path;return g.store.get(o,E)}}}let DB=class extends WA{kind="array";#A;[Lg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:oC(B)},this[Lg]=DD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Lg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Lg],Q=await B.get_chunk_bytes(A,I);if(!Q){let C=B.chunk_shape.reduce((i,o)=>i*o,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 Xi(this.dtype,A)}};function*oD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*aD(...g){if(g.length===0)return;const A=g.map(B=>B[Symbol.iterator]()),I=A.map(B=>B.next());if(I.some(B=>B.done))throw new Error("Input contains an empty iterator.");for(let B=0;;){if(I[B].done){if(A[B]=g[B][Symbol.iterator](),I[B]=A[B].next(),++B>=A.length)return}else yield I.map(({value:Q})=>Q),B=0;I[B]=A[B].next()}}function sD({start:g,stop:A,step:I},B){if(I===0)throw new Error("slice step cannot be zero");I=I??1;const Q=I<0,[C,E]=Q?[-1,B-1]:[0,B];return g===null?g=Q?E:C:g<0?(g+=B,g<C&&(g=C)):g>E&&(g=E),A===null?A=Q?C:E:A<0?(A+=B,A<C&&(A=C)):A>E&&(A=E),[g,A,I]}function oB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function yD(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class QQ extends Error{constructor(A){super(A),this.name="IndexError"}}function hD(g,A){throw new QQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function GD(g){throw new QQ(`index out of bounds for dimension with length ${g}`)}function FD(){throw new QQ("only slices with step >= 1 are supported")}function wD(g,A){g.length>A.length&&hD(g,A)}function SD(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&GD(A),g}class RD{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=SD(A,I),this.dim_sel=A,this.dim_len=I,this.dim_chunk_len=B,this.nitems=1}*[Symbol.iterator](){const A=Math.floor(this.dim_sel/this.dim_chunk_len),I=A*this.dim_chunk_len,B=this.dim_sel-I;yield{dim_chunk_ix:A,dim_chunk_sel:B}}}class RC{start;stop;step;dim_len;dim_chunk_len;nitems;nchunks;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){const[Q,C,E]=sD(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&FD(),this.dim_len=I,this.dim_chunk_len=B,this.nitems=Math.max(0,Math.ceil((this.stop-this.start)/this.step)),this.nchunks=Math.ceil(this.dim_len/this.dim_chunk_len)}*[Symbol.iterator](){const A=Math.floor(this.start/this.dim_chunk_len),I=Math.ceil(this.stop/this.dim_chunk_len);for(const B of oD(A,I)){const Q=B*this.dim_chunk_len,C=Math.min(this.dim_len,(B+1)*this.dim_chunk_len),E=C-Q;let i=0,o=0;if(this.start<Q){const r=(Q-this.start)%this.step;r&&(o+=this.step-r),i=Math.ceil((Q-this.start)/this.step)}else o=this.start-Q;const y=this.stop>C?E:this.stop-Q,G=[o,y,this.step],L=Math.ceil((y-o)/this.step),k=[i,i+L,1];yield{dim_chunk_ix:B,dim_chunk_sel:G,dim_out_sel:k}}}}function ND(g,A){let I=[];return g===null?I=A.map(B=>oB(null)):Array.isArray(g)&&(I=g.map(B=>B??oB(null))),wD(I,A),I}class UD{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=ND(A,I).map((Q,C)=>new(typeof Q=="number"?RD:RC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof RC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of aD(...this.dim_indexers)){const I=A.map(Q=>Q.dim_chunk_ix),B=A.map(Q=>"dim_out_sel"in Q?{from:Q.dim_chunk_sel,to:Q.dim_out_sel}:{from:Q.dim_chunk_sel,to:null});yield{chunk_coords:I,mapping:B}}}}function tD(g,A){return"get"in g?g.get(A):g[A]}async function kD(g,A,I,B){let Q=iD(g),C=new UD({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,y)=>o*y,1)),C.shape,Q.get_strides(C.shape)),i=I.create_queue?.()??yD();for(const{chunk_coords:o,mapping:y}of C)i.add(async()=>{let{data:G,shape:L,stride:k}=await g.getChunk(o,I.opts),r=B.prepare(G,L,k);B.set_from_chunk(E,r,y)});return await i.onIdle(),C.shape.length===0?tD(E.data,0):E}function CQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return CQ(g,A+Q,C-Q)},set(Q,C=0){for(let E=0;E<Q.length;E++)g[A+C+E]=Q.get(E)},get(Q){return g[A+Q]}}}function EQ(g){return globalThis.Array.isArray(g.data)?{data:CQ(g.data),stride:g.stride,bytes_per_element:1}:{data:new Uint8Array(g.data.buffer,g.data.byteOffset,g.data.byteLength),stride:g.stride,bytes_per_element:g.data.BYTES_PER_ELEMENT}}function cD(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function LD(g,A){if(globalThis.Array.isArray(g.data))return CQ([A]);let I=cD(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const JD={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=EQ(g);iQ(B,A,LD(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=EQ(g);aB(B,EQ(A),B.bytes_per_element,I)}};async function rD(g,A=null,I={}){return kD(g,A,I,JD)}function NC(g,A,I){return I<0&&A<g?Math.floor((g-A-1)/-I)+1:g<A?Math.floor((A-g-1)/I)+1:0}function iQ(g,A,I,B){if(A.length===0){g.data.set(I,0);return}const[Q,...C]=A,[E,...i]=g.stride;if(typeof Q=="number"){const k=g.data.subarray(E*Q*B);iQ({data:k,stride:i},C,I,B);return}const[o,y,G]=Q,L=NC(o,y,G);if(C.length===0){for(let k=0;k<L;k++)g.data.set(I,E*(o+G*k)*B);return}for(let k=0;k<L;k++){const r=g.data.subarray(E*(o+G*k)*B);iQ({data:r,stride:i},C,I,B)}}function aB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...y]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}aB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let d=Q.from*I;g.data.set(A.data.subarray(d,d+I),0);return}aB(g,{data:A.data.subarray(o*Q.from*I),stride:y},I,C);return}const[G,L,k]=Q.to,[r,K,f]=Q.from,M=NC(G,L,k);if(C.length===0){if(k===1&&f===1&&E===1&&o===1){let d=r*I,u=M*I;g.data.set(A.data.subarray(d,d+u),G*I);return}for(let d=0;d<M;d++){let u=o*(r+f*d)*I;g.data.set(A.data.subarray(u,u+I),E*(G+k*d)*I)}return}for(let d=0;d<M;d++)aB({data:g.data.subarray(E*(G+d*k)*I),stride:i},{data:A.data.subarray(o*(r+d*f)*I),stride:y},I,C)}let sB=YD();function YD(){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 nD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?kg(A):{}}async function KD(g,A={}){let I="store"in g?g:new WA(g),B={};return(A.attrs??!0)&&(B=await nD(I)),A.kind==="array"?UC(I,B):A.kind==="group"?tC(I,B):UC(I,B).catch(Q=>(aC(Q,cg),tC(I,B)))}async function UC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new cg("v2 array",{cause:new gQ(I)});return sB.increment(g.store,"v2"),new DB(g.store,g.path,Oi(kg(B),A))}async function tC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new cg("v2 group",{cause:new gQ(I)});return sB.increment(g.store,"v2"),new BQ(g.store,g.path,Vi(kg(B),A))}async function MD(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new cg("v3 array or group",{cause:new gQ(I)});let Q=kg(B);return Q.node_type==="array"&&(Q.fill_value=oC(Q)),Q.node_type==="array"?new DB(A,g.path,Q):new BQ(A,g.path,Q)}async function eD(g,A={}){let I="store"in g?g:new WA(g),B=await MD(I);if(sB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof DB||A.kind==="group"&&B instanceof BQ)return B;let Q=B instanceof DB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function OA(g,A={}){let I="store"in g?g.store:g,B=sB.version_max(I),Q=B==="v2"?OA.v2:OA.v3,C=B==="v2"?OA.v3:OA.v2;return Q(g,A).catch(E=>(aC(E,cg),C(g,A)))}OA.v2=KD,OA.v3=eD;async function HD(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 DQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await HD(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}function qD(){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 oQ extends XI{credentials;region;signingKeyCache_=new Map;overrides;useSuffixRequest;constructor(A){qD(),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"),o=globalThis.fetch,y=async(L,k)=>{const K=(k?.method||"GET")==="HEAD"?E:i,f={...k,headers:{...k?.headers,...K}};return o(L,f)},G=globalThis.fetch;globalThis.fetch=y;try{return await super.getRange(A,I,B)}finally{globalThis.fetch=G}}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",o=this.getAmzDate(),y=o.slice(0,8),G=new URL(A),L=G.host,k=G.pathname,r=G.search.slice(1),K=`host:${L}
|
|
412
412
|
x-amz-content-sha256:UNSIGNED-PAYLOAD
|
|
413
413
|
x-amz-date:${o}
|
|
414
414
|
`+(C?`x-amz-security-token:${C}
|