@idetik/core 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +14 -3
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +4 -3
- package/dist/index.umd.cjs.map +1 -1
- package/dist/types/src/objects/renderable/image_renderable.d.ts +2 -0
- package/dist/types/src/objects/renderable/image_renderable.d.ts.map +1 -1
- package/dist/types/src/renderers/webgl_shader_program.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -130,6 +130,7 @@ uniform mediump sampler2DArray ImageSampler;
|
|
|
130
130
|
#endif
|
|
131
131
|
|
|
132
132
|
#define MAX_CHANNELS 32
|
|
133
|
+
uniform uint ChannelCount;
|
|
133
134
|
uniform bool Visible[MAX_CHANNELS];
|
|
134
135
|
uniform vec3 Color[MAX_CHANNELS];
|
|
135
136
|
uniform float ValueOffset[MAX_CHANNELS];
|
|
@@ -140,7 +141,7 @@ in vec2 TexCoords;
|
|
|
140
141
|
|
|
141
142
|
void main() {
|
|
142
143
|
vec3 rgbColor = vec3(0, 0, 0);
|
|
143
|
-
for (
|
|
144
|
+
for (uint i = 0u; i < ChannelCount; i++) {
|
|
144
145
|
if (!Visible[i]) continue;
|
|
145
146
|
float texel = float(texture(ImageSampler, vec3(TexCoords, i)).r);
|
|
146
147
|
float value = (texel + ValueOffset[i]) * ValueScale[i];
|
|
@@ -341,9 +342,9 @@ void main() {
|
|
|
341
342
|
float alpha = isSelectedValue ? u_opacity * color.a * 0.9 : u_opacity * color.a;
|
|
342
343
|
|
|
343
344
|
fragColor = vec4(color.rgb, alpha);
|
|
344
|
-
}`;const pE={projectedLine:{vertex:ME,fragment:HE},points:{vertex:eE,fragment:qE},wireframe:{vertex:dE,fragment:fE},floatScalarImage:{vertex:dI,fragment:qB},floatScalarImageArray:{vertex:dI,fragment:dB},intScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:dI,fragment:lE},floatVolume:{vertex:fB,fragment:lB},intVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},xQ={debug:10,info:20,warn:30,error:40},WE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function mE(){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 j{static logLevel_=mE()==="production"?"warn":"debug";static setLogLevel(A){j.logLevel_=A}static debug(A,I,...B){j.log("debug",A,I,...B)}static info(A,I,...B){j.log("info",A,I,...B)}static warn(A,I,...B){j.log("warn",A,I,...B)}static error(A,I,...B){j.log("error",A,I,...B)}static log(A,I,B,...Q){if(xQ[A]<xQ[j.logLevel_])return;const C=new Date().toISOString(),E=WE[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 TE{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_.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_.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(!ZE.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]),j.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 xE=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,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_SAMPLER_2D,WebGL2RenderingContext.INT_SAMPLER_3D,WebGL2RenderingContext.INT_SAMPLER_CUBE,WebGL2RenderingContext.INT_SAMPLER_2D_ARRAY,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_3D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_CUBE,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D_ARRAY]:[],ZE=new Set(xE),pB="#pragma inject_defines";class bE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=pE[A],Q=ZQ(B.vertex,B.vertexDefines),C=ZQ(B.fragment,B.fragmentDefines);I=new TE(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 ZQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(pB))throw new Error(`Shader source does not contain "${pB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
345
|
+
}`;const pE={projectedLine:{vertex:ME,fragment:HE},points:{vertex:eE,fragment:qE},wireframe:{vertex:dE,fragment:fE},floatScalarImage:{vertex:dI,fragment:qB},floatScalarImageArray:{vertex:dI,fragment:dB},intScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},intScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:dI,fragment:qB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},uintScalarImageArray:{vertex:dI,fragment:dB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:dI,fragment:lE},floatVolume:{vertex:fB,fragment:lB},intVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:fB,fragment:lB,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},xQ={debug:10,info:20,warn:30,error:40},WE={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function mE(){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 j{static logLevel_=mE()==="production"?"warn":"debug";static setLogLevel(A){j.logLevel_=A}static debug(A,I,...B){j.log("debug",A,I,...B)}static info(A,I,...B){j.log("info",A,I,...B)}static warn(A,I,...B){j.log("warn",A,I,...B)}static error(A,I,...B){j.log("error",A,I,...B)}static log(A,I,B,...Q){if(xQ[A]<xQ[j.logLevel_])return;const C=new Date().toISOString(),E=WE[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 TE{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_.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_.INT:this.gl_.uniform1i(B,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(!ZE.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]),j.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 xE=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,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]:[],ZE=new Set(xE),pB="#pragma inject_defines";class bE{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const B=pE[A],Q=ZQ(B.vertex,B.vertexDefines),C=ZQ(B.fragment,B.fragmentDefines);I=new TE(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 ZQ(g,A){if(A===void 0||A.size==0)return g;if(!g.includes(pB))throw new Error(`Shader source does not contain "${pB}" directive`);const I=Array(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
345
346
|
`),Q=`#line __LINE__ + ${1-A.size}`,C=`${I}
|
|
346
|
-
${Q}`;return g.replace(pB,C)}const ZA=["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 bQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(ZA[g&255]+ZA[g>>8&255]+ZA[g>>16&255]+ZA[g>>24&255]+"-"+ZA[A&255]+ZA[A>>8&255]+"-"+ZA[A>>16&15|64]+ZA[A>>24&255]+"-"+ZA[I&63|128]+ZA[I>>8&255]+"-"+ZA[I>>16&255]+ZA[I>>24&255]+ZA[B&255]+ZA[B>>8&255]+ZA[B>>16&255]+ZA[B>>24&255]).toLowerCase()}class WB{uuid=bQ()}var fI=1e-6,lA=typeof Float32Array<"u"?Float32Array:Array,uE=Math.PI/180;function PE(g){return g*uE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function uQ(){var g=new lA(9);return lA!=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 OE(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 QI(){var g=new lA(16);return lA!=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 mB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],h=A[7],s=A[8],R=A[9],N=A[10],r=A[11],M=A[12],e=A[13],n=A[14],f=A[15],O=I*i-B*E,W=I*o-Q*E,u=I*h-C*E,b=B*o-Q*i,T=B*h-C*i,QA=Q*h-C*o,v=s*e-R*M,x=s*n-N*M,IA=s*f-r*M,AA=R*n-N*e,wA=R*f-r*e,kA=N*f-r*n,CA=O*kA-W*wA+u*AA+b*IA-T*x+QA*v;return CA?(CA=1/CA,g[0]=(i*kA-o*wA+h*AA)*CA,g[1]=(Q*wA-B*kA-C*AA)*CA,g[2]=(e*QA-n*T+f*b)*CA,g[3]=(N*T-R*QA-r*b)*CA,g[4]=(o*IA-E*kA-h*x)*CA,g[5]=(I*kA-Q*IA+C*x)*CA,g[6]=(n*u-M*QA-f*W)*CA,g[7]=(s*QA-N*u+r*W)*CA,g[8]=(E*wA-i*IA+h*v)*CA,g[9]=(B*IA-I*wA-C*v)*CA,g[10]=(M*T-e*u+f*O)*CA,g[11]=(R*u-s*T-r*O)*CA,g[12]=(i*x-E*AA-o*v)*CA,g[13]=(I*AA-B*x+Q*v)*CA,g[14]=(e*W-M*b-n*O)*CA,g[15]=(s*b-R*W+N*O)*CA,g):null}function DB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],h=A[6],s=A[7],R=A[8],N=A[9],r=A[10],M=A[11],e=A[12],n=A[13],f=A[14],O=A[15],W=I[0],u=I[1],b=I[2],T=I[3];return g[0]=W*B+u*i+b*R+T*e,g[1]=W*Q+u*o+b*N+T*n,g[2]=W*C+u*h+b*r+T*f,g[3]=W*E+u*s+b*M+T*O,W=I[4],u=I[5],b=I[6],T=I[7],g[4]=W*B+u*i+b*R+T*e,g[5]=W*Q+u*o+b*N+T*n,g[6]=W*C+u*h+b*r+T*f,g[7]=W*E+u*s+b*M+T*O,W=I[8],u=I[9],b=I[10],T=I[11],g[8]=W*B+u*i+b*R+T*e,g[9]=W*Q+u*o+b*N+T*n,g[10]=W*C+u*h+b*r+T*f,g[11]=W*E+u*s+b*M+T*O,W=I[12],u=I[13],b=I[14],T=I[15],g[12]=W*B+u*i+b*R+T*e,g[13]=W*Q+u*o+b*N+T*n,g[14]=W*C+u*h+b*r+T*f,g[15]=W*E+u*s+b*M+T*O,g}function VE(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 XE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=Q+Q,h=C+C,s=E+E,R=Q*o,N=Q*h,r=Q*s,M=C*h,e=C*s,n=E*s,f=i*o,O=i*h,W=i*s,u=B[0],b=B[1],T=B[2];return g[0]=(1-(M+n))*u,g[1]=(N+W)*u,g[2]=(r-O)*u,g[3]=0,g[4]=(N-W)*b,g[5]=(1-(R+n))*b,g[6]=(e+f)*b,g[7]=0,g[8]=(r+O)*T,g[9]=(e-f)*T,g[10]=(1-(R+M))*T,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function vE(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 jE=vE;function zE(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),h=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*h,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*h,g[15]=1,g}var _E=zE;function $E(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],h=B[2],s=Q-I[0],R=C-I[1],N=E-I[2],r=s*s+R*R+N*N;r>0&&(r=1/Math.sqrt(r),s*=r,R*=r,N*=r);var M=o*N-h*R,e=h*s-i*N,n=i*R-o*s;return r=M*M+e*e+n*n,r>0&&(r=1/Math.sqrt(r),M*=r,e*=r,n*=r),g[0]=M,g[1]=e,g[2]=n,g[3]=0,g[4]=R*n-N*e,g[5]=N*M-s*n,g[6]=s*e-R*M,g[7]=0,g[8]=s,g[9]=R,g[10]=N,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function rA(){var g=new lA(3);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function CI(g){var A=new lA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function PQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function NA(g,A,I){var B=new lA(3);return B[0]=g,B[1]=A,B[2]=I,B}function tg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function _I(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function OQ(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function Ai(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function Ii(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function VQ(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function XQ(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 vQ(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 gi(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 jQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function TB(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 Bi(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,h=i*E,s=3*C*i,R=3*o*E,N=o*C;return g[0]=A[0]*h+I[0]*s+B[0]*R+Q[0]*N,g[1]=A[1]*h+I[1]*s+B[1]*R+Q[1]*N,g[2]=A[2]*h+I[2]*s+B[2]*R+Q[2]*N,g}function oB(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 Qi(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)<=fI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=fI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=fI*Math.max(1,Math.abs(Q),Math.abs(i))}var xB=Ai,Ci=PQ;(function(){var g=rA();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 cg(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Ei(g){var A=new lA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function ZB(g,A,I,B){var Q=new lA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function ii(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function Di(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 oi(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 aB(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=cg();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 bB(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function ai(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 si(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],h=I[2],s=I[3];return g[0]=B*s+E*i+Q*h-C*o,g[1]=Q*s+E*o+C*i-B*h,g[2]=C*s+E*h+B*o-Q*i,g[3]=E*s-B*i-Q*o-C*h,g}function uB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],h=I[1],s=I[2],R=I[3],N,r,M,e,n;return r=Q*o+C*h+E*s+i*R,r<0&&(r=-r,o=-o,h=-h,s=-s,R=-R),1-r>fI?(N=Math.acos(r),M=Math.sin(N),e=Math.sin((1-B)*N)/M,n=Math.sin(B*N)/M):(e=1-B,n=B),g[0]=e*Q+n*o,g[1]=e*C+n*h,g[2]=e*E+n*s,g[3]=e*i+n*R,g}function zQ(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 yi=Ei,hi=ii,PB=oi;(function(){var g=rA(),A=NA(1,0,0),I=NA(0,1,0);return function(B,Q,C){var E=jQ(Q,C);return E<-.999999?(TB(g,A,Q),Ci(g)<1e-6&&TB(g,I,Q),gi(g,g),ai(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(TB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,PB(B,B))}})(),function(){var g=bB(),A=bB();return function(I,B,Q,C,E,i){return uB(g,B,E,i),uB(A,Q,C,i),uB(I,g,A,2*i*(1-i)),I}}(),function(){var g=uQ();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],PB(A,zQ(A,g))}}();function _Q(){var g=new lA(2);return lA!=Float32Array&&(g[0]=0,g[1]=0),g}function $Q(g){var A=new lA(2);return A[0]=g[0],A[1]=g[1],A}function pA(g,A){var I=new lA(2);return I[0]=g,I[1]=A,I}function Gi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function Fi(g){var A=g[0],I=g[1];return A*A+I*I}function wi(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 AC(g,A){return g[0]===A[0]&&g[1]===A[1]}function OB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=fI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=fI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=_Q();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 tI{min;max;constructor(A,I){this.min=A?CI(A):NA(1/0,1/0,1/0),this.max=I?CI(I):NA(-1/0,-1/0,-1/0)}clone(){return new tI(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=[NA(I[0],I[1],I[2]),NA(I[0],I[1],B[2]),NA(I[0],B[1],I[2]),NA(I[0],B[1],B[2]),NA(B[0],I[1],I[2]),NA(B[0],I[1],B[2]),NA(B[0],B[1],I[2]),NA(B[0],B[1],B[2])];this.min=NA(1/0,1/0,1/0),this.max=NA(-1/0,-1/0,-1/0);const C=rA();for(const E of Q)oB(C,E,A),this.expandWithPoint(C)}}const Si={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class $I extends WB{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 tI,Q=rA();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 Ri{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(s=>{const R=Si[s.type];this.gl_.vertexAttribPointer(R,s.itemSize,this.gl_.FLOAT,!1,i,s.offset),this.gl_.enableVertexAttribArray(R)});const o={vao:I,vbo:C},{indexData:h}=A;if(h.length){const s=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(s,R),this.gl_.bufferData(s,h,this.gl_.STATIC_DRAW),o.ebo=R}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class Ni{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 j.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 h=0;h<Q;h++)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 jA{min;max;constructor(A,I){this.min=A?$Q(A):pA(1/0,1/0),this.max=I?$Q(I):pA(-1/0,-1/0)}clone(){return new jA(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 AC(A.min,I.min)&&AC(A.max,I.max)}floor(){return new jA(pA(Math.floor(this.min[0]),Math.floor(this.min[1])),pA(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 Ui{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A}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"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_&&jA.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_&&jA.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}}}const ki=VE(QI(),[1,-1,1]);class IC extends KE{gl_=null;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;constructor(A){if(super(A),this.gl_=this.canvas.getContext("webgl2",{depth:!0,antialias:!0}),!this.gl_)throw new Error("Failed to initialize WebGL2 context");j.info("WebGLRenderer",`WebGL version ${this.gl.getParameter(this.gl.VERSION)}`),this.programs_=new bE(this.gl),this.bindings_=new Ri(this.gl),this.textures_=new Ni(this.gl),this.state_=new Ui(this.gl),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new jA(pA(0,0),pA(this.width,this.height));if(jA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(jA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{j.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}renderLayer(A,I,B){this.state_.setBlendingMode(A.transparent?A.blendMode:"none"),A.objects.forEach((Q,C)=>{B.intersectsWithBox3(Q.boundingBox)&&(this.renderObject(A,C,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];this.state_.setCullFaceMode(Q.cullFaceMode),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=DB(QI(),C.viewMatrix,I.transform.matrix),i=DB(QI(),ki,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],h=I.getUniforms();for(const N of Q.uniformNames)switch(N){case"ModelView":Q.setUniform(N,E);break;case"Projection":Q.setUniform(N,i);break;case"Resolution":Q.setUniform(N,o);break;case"u_opacity":Q.setUniform(N,B.opacity);break;default:N in h&&Q.setUniform(N,h[N])}const s=this.glGetPrimitive(A.primitive),R=A.indexData;R.length?this.gl.drawElements(s,R.length,this.gl.UNSIGNED_INT,0):this.gl.drawArrays(s,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 jA(pA(0,0),pA(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)}get gl(){return this.gl_}}const ti=8;class ci{maxConcurrent_;pending_=[];running_=new Map;constructor(A=ti){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),j.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),j.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"&&j.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const gC=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function BC(g){if(gC.some(I=>g instanceof I))return!0;const A=gC.map(I=>I.name);return j.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function Li(g,A){return Math.round((A-g.translation)/g.scale)}function VB(g,A,I=1e-6){return Math.abs(g-A)<=I}class Ji{chunks_;loader_;lowestResLOD_;dimensions_;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],h=this.dimensions_.z?.lods[E],s=i.chunkSize,R=o.chunkSize,N=h?.chunkSize??1,r=Math.ceil(i.size/s),M=Math.ceil(o.size/R),e=Math.ceil((h?.size??1)/N);for(let n=0;n<B;++n)for(let f=0;f<r;++f){const O=i.translation+f*i.chunkSize*i.scale;for(let W=0;W<M;++W){const u=o.translation+W*o.chunkSize*o.scale;for(let b=0;b<e;++b){const T=h!==void 0?h.translation+b*N*h.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(s,i.size-f*s),y:Math.min(R,o.size-W*R),z:Math.min(N,(h?.size??1)-b*N),c:1},rowAlignmentBytes:1,chunkIndex:{x:f,y:W,z:b,c:n,t:Q},scale:{x:i.scale,y:o.scale,z:h?.scale??1},offset:{x:O,y:u,z:T}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:Li(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)}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(!VB(Q,2,.02)||!VB(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}}}function Lg(g,A,I){return Math.max(A,Math.min(I,g))}const QC=Symbol("INTERNAL_POLICY_KEY");class ri{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;constructor(A,I){this.store_=A,this.policy_=I,j.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_=Fi(pA(Q.size*Q.scale,C.size*C.scale))}get store(){return this.store_}get chunkViewStates(){return this.chunkViewStates_}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();return this.currentLOD_===C?Q:[...B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),...Q]}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,h=E/o,s=Math.log2(1/h);this.setLOD(s);const R=this.getZBounds(A);(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(R)||this.lastTCoord_!==A.t)&&(this.updateChunkViewStates(A,C),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=R,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)}setImageSourcePolicy(A,I){if(I!==QC)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,j.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)),h=Math.max(o,Math.min(i,this.policy_.lod.max)),s=Lg(E,o,h);s!==this.currentLOD_&&(this.currentLOD_=s)}updateChunkViewStates(A,I){const B=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(B).length===0){j.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const C=_Q();wi(C,I.min,I.max,.5);const[E,i]=this.getZBounds(A),o=new tI(NA(I.min[0],I.min[1],E),NA(I.max[0],I.max[1],i));this.chunkViewStates_.forEach(Yi),this.updateChunksAtTimeIndex(B,A,o,C),A.t!==void 0&&this.markTimeChunksForPrefetch(B,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),h=this.isChunkChannelInSlice(i,I),s=i.lod===this.currentLOD_,R=i.lod===this.store_.getLowestResLOD(),N=!o&&h&&s&&this.isChunkWithinBounds(i,C),r=o&&h,M=this.computePriority(R,s,o,N,h);if(M!==null){const e=this.squareDistance2D(i,Q);this.chunkViewStates_.set(i,{visible:r,prefetch:N,priority:M,orderKey:e})}}}markTimeChunksForPrefetch(A,I,B){const Q=this.store_.dimensions.t?.lods[0].size??1,C=Math.min(Q-1,A+this.policy_.prefetch.t);for(let E=A+1;E<=C;++E)for(const i of this.store_.getChunksAtTime(E)){if(i.lod!==this.store_.getLowestResLOD()||!this.isChunkWithinBounds(i,I))continue;const o=this.policy_.priorityMap.prefetchTime,h=this.squareDistance2D(i,B),s=Lg(h/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),R=E-A+s;this.chunkViewStates_.set(i,{visible:!1,prefetch:!0,priority:o,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 tI(NA(A.offset.x,A.offset.y,A.offset.z),NA(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 tI.intersects(B,I)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0||A.z===void 0)return[0,1];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,h=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(Q/o)-1));return[E+h*o*C,E+(h+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!OB(this.lastViewBounds2D_.min,A.min)||!OB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!OB(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 tI(NA(A.min[0]-E,A.min[1]-i,A.min[2]-o),NA(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 Yi(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class ni{stores_=new Map;pendingStores_=new Map;views_=new Map;queue_=new ci;async addView(A,I){const B=await this.addSource(A),Q=new ri(B,I);return this.views_.set(B,(this.views_.get(B)??[]).concat(Q)),Q}removeView(A){const I=A.store,B=this.getSourceForStore(I),Q=this.views_.get(I);if(!Q)throw new Error("Cannot remove view: store not managed by ChunkManager");const C=Q.indexOf(A);if(C===-1)throw new Error(`Cannot remove view: view not found in store's view list (source: ${B})`);const E=Array.from(A.chunkViewStates.keys());Q.splice(C,1);for(const i of E)this.aggregateChunkViewStates(i,I);Q.length===0&&(this.stores_.delete(B),this.views_.delete(I))}async addSource(A){const I=this.stores_.get(A)??this.pendingStores_.get(A);if(I)return I;const Q=(async()=>{const C=await A.open(),E=new Ji(C);return this.stores_.set(A,E),this.pendingStores_.delete(A),E})();return this.pendingStores_.set(A,Q),Q}getSourceForStore(A){for(const[I,B]of this.stores_)if(B===A)return I;throw new Error("Source not found for the given store.")}update(){for(const[A,I]of this.stores_){const B=this.updateAndCollectChunkChanges(I);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()}updateAndCollectChunkChanges(A){const I=this.views_.get(A);if(!I)return new Set;const B=new Set;for(const Q of I)for(const[C,E]of Q.chunkViewStates)B.add(C);for(const Q of B)this.aggregateChunkViewStates(Q,A);return B}aggregateChunkViewStates(A,I){const B=this.views_.get(I);if(!B)return;let Q=!1,C=!1,E=null,i=null;for(const R of B){const N=R.chunkViewStates.get(A);N&&(N.visible&&(Q=!0),N.prefetch&&(C=!0),N.priority!==null&&(E===null||N.priority<E)&&(E=N.priority,i=N.orderKey),!N.visible&&!N.prefetch&&N.priority===null&&R.maybeForgetChunk(A))}if(A.visible=Q,A.prefetch=C,A.priority=E,A.orderKey=i,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}A.state==="loaded"&&!A.visible&&!A.prefetch&&(A.data=void 0,A.state="unloaded",A.priority=null,A.orderKey=null,A.prefetch=!1,j.debug("ChunkManager",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`))}}var Jg=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(R){R.preventDefault(),Q(++A%I.children.length)},!1);function B(R){return I.appendChild(R.dom),R}function Q(R){for(var N=0;N<I.children.length;N++)I.children[N].style.display=N===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,o=B(new Jg.Panel("FPS","#0ff","#002",g)),h=B(new Jg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var s=B(new Jg.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 R=(performance||Date).now();if(h.update(R-C,200),R>=E+1e3&&(o.update(i*1e3/(R-E),100),E=R,i=0,s)){var N=performance.memory;s.update(N.usedJSHeapSize/1048576,N.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};Jg.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),h=E(48*i*B),s=E(3*i*B),R=E(2*i*B),N=E(3*i*B),r=E(15*i*B),M=E(74*i*B),e=E(30*i*B),n=document.createElement("canvas");n.width=o,n.height=h,n.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var f=n.getContext("2d");return f.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=I,f.fillRect(0,0,o,h),f.fillStyle=A,f.fillText(g,s,R),f.fillRect(N,r,M,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N,r,M,e),{dom:n,update:function(O,W){Q=Math.min(Q,O),C=Math.max(C,O),f.fillStyle=I,f.globalAlpha=1,f.fillRect(0,0,o,r),f.fillStyle=A,f.fillText(E(O)+" "+g+" ("+E(Q)+"-"+E(C)+")",s,R),f.drawImage(n,N+i,r,M-i,e,N,r,M-i,e),f.fillRect(N+M-i,r,i,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N+M-i,r,i,E((1-O/W)*e))}}};function Ki({scale:g}={scale:1.5}){const A=new Jg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class CC{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 XB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function Mi(g){return XB.includes(g)}class Hi{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 ei{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){j.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,XB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){j.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,XB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!Mi(A.type)){j.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new Hi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class EC{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 ei(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=pA(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,h=I.y-E,s=Math.floor(o),R=Math.floor(i-h-I.height),N=Math.floor(I.width),r=Math.floor(I.height);return new jA(pA(s,R),pA(s+N,R+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return NA(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 jA(pA(B,Q),pA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){j.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 iC(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??bQ(),layerManager:new CC(I)}});return qi(B),B.map(Q=>new EC(Q))}class di{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;changed_=!1;constructor(A=[]){this.elements_=A}connect(){if(this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.changed_=!0});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}getAndResetChanged(){const A=this.changed_;return this.changed_=!1,A}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.changed_=!0,this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class fi{lastAnimationId_;chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;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 IC(this.canvas),this.chunkManager_=new ni,this.context_={chunkManager:this.chunkManager_},this.viewports_=iC(A.viewports,this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Ki());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new di(I)}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(j.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.animate()}else j.warn("Idetik","Idetik runtime already started");return this}animate(A){this.stats_&&this.stats_.begin(),this.sizeObserver_.getAndResetChanged()&&this.updateSize();for(const I of this.viewports_)this.renderer_.render(I);this.chunkManager_.update();for(const I of this.overlays)I.update(this,A);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(I=>this.animate(I))}stop(){if(j.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)j.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}}updateSize(){this.renderer_.updateSize();for(const A of this.viewports_)A.updateSize()}}class li extends $I{constructor(A){if(super(),A.primitive!="triangles"){j.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){j.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),h=Math.max(E,i);I.has({i0:o,i1:h})||(I.add({i0:o,i1:h}),B.push(o,h))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],h=C[E+2];Q(i,o),Q(o,h),Q(h,i)}this.indexData_=new Uint32Array(B)}}const pi=NA(0,1,0);class Wi{dirty_=!0;matrix_=QI();rotation_=bB();translation_=rA();scale_=NA(1,1,1);addRotation(A){si(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){hi(this.rotation_,A),this.dirty_=!0}get rotation(){return yi(this.rotation_)}addTranslation(A){OQ(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){tg(this.translation_,A),this.dirty_=!0}get translation(){return CI(this.translation_)}addScale(A){Ii(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){tg(this.scale_,A),this.dirty_=!0}targetTo(A){Qi(this.translation_,A)&&(A=CI(A),A[2]+=fI);const I=$E(QI(),this.translation_,A,pi),B=OE(uQ(),I);zQ(this.rotation_,B),PB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return CI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return mB(QI(),this.matrix)}computeMatrix(){XE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Ag extends WB{wireframeEnabled=!1;wireframeColor=hA.WHITE;textures_=[];staleTextures_=[];transform_=new Wi;geometry_=new $I;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 li(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=NA(0,1,0),I=0){this.normal=CI(A),this.signedDistance=I}set(A,I){this.normal=CI(A),this.signedDistance=I}signedDistanceToPoint(A){return jQ(this.normal,A)+this.signedDistance}normalize(){const A=PQ(this.normal);if(A>0){const I=1/A;VQ(this.normal,this.normal,I),this.signedDistance*=I}}}class DC{planes_;constructor(A){this.planes_=[new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=rA();this.planes_[0].set(_I(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(_I(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(_I(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(_I(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(_I(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(_I(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=rA();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 oC extends Ag{projectionMatrix_=QI();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 NA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return NA(A[4],A[5],A[6])}get frustum(){return new DC(DB(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=ZB(A[0],A[1],A[2],1),B=mB(QI(),this.projectionMatrix_),Q=aB(cg(),I,B);Di(Q,Q,1/Q[3]);const C=aB(cg(),Q,this.transform.matrix);return NA(C[0],C[1],C[2])}}const aC=1.77,sC=128,yC=128/aC;class mi extends oC{width_=sC;height_=yC;viewportAspectRatio_=aC;viewportSize_=[sC,yC];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=ZB(-1,-1,0,1),I=ZB(1,1,0,1);const B=DB(QI(),this.projectionMatrix,this.viewMatrix),Q=mB(QI(),B);return A=aB(cg(),A,Q),I=aB(cg(),I,Q),new jA(pA(A[0],A[1]),pA(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],_E(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Ti=60,xi=1.77,sB=.1,vB=180-sB;class Zi extends oC{fov_;aspectRatio_;constructor(A={}){const{fov:I=Ti,aspectRatio:B=xi,near:Q=.1,far:C=1e4,position:E=NA(0,0,0)}=A;if(I<sB||I>vB)throw new Error(`Invalid field of view: ${I}, must be in [${sB}, ${vB}] 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(sB,Math.min(vB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){jE(this.projectionMatrix_,PE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const hC=0;class bi{camera_;dragActive_=!1;dragStart_=rA();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}}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=CI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=xB(rA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==hC||(this.dragStart_=CI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=xB(rA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==hC||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class SI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&j.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Lg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&j.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Lg(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)}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_=[]}}class yB extends $I{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+vQ(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 h=A[E-1]??A[E];I[B++]=h[0],I[B++]=h[1],I[B++]=h[2];const s=A[E+1]??A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2],I[B++]=i,I[B++]=Q}Q+=vQ(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 jB extends Ag{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=hA.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_=hA.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 ui extends SI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(zB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(zB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(zB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function zB(g){const{end:A,width:I,color:B}=g,Q=new yB([[0,0,0],A]);return new jB({geometry:Q,color:B,width:I})}class Pi extends SI{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 yB(I);this.addObject(new jB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Oi(this.paths_.flat())}}function Oi(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}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 Vi extends SI{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=vi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new yB(i)}else I=new yB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new jB({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 Xi(A.flat())}}function Xi(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}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 vi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=ji(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=CI(B[C]);XQ(o,E,o,I);const h=CI(B[C+1]);XQ(h,i,h,-I);for(let s=0;s<A;s++){const R=s/A,N=Q[C*A+s]=rA();Bi(N,E,o,h,i,R)}}return Q}function ji(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=rA(),B=rA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=rA(),Q!==0&&tg(I,B),Q!==g.length-1&&xB(B,E,C),Q===0?tg(A[Q],B):Q==g.length-1?tg(A[Q],I):(OQ(A[Q],I,B),VQ(A[Q],A[Q],.5))}return A}class GC extends $I{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,h=i+1,s=o+1,R=A/i,N=I/o;for(let r=0;r<s;++r){const M=r*N;for(let e=0;e<h;++e){const n=e*R,f=e/i,O=r/o,W=[n,M,0],u=[0,0,1],b=[f,O];C.push(...W,...u,...b)}}for(let r=0;r<o;++r)for(let M=0;M<i;++M){const e=M+h*r,n=M+h*(r+1),f=M+1+h*(r+1),O=M+1+h*r;E.push(e,n,O),E.push(n,f,O)}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 FC(g){return g===1||g===2||g===4||g===8}function Ig(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 zi(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 _B extends WB{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 wC=32;function $B(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=hA.WHITE:I=hA.from(I),g!==null?B=_i(B,g):B===void 0&&(j.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function SC(g,A){if(A.length>wC)throw new Error(`Maximum number of channels is ${wC}`);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=>$B(g,I))}function _i(g,A){if(g===void 0)return zi(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AQ extends Ag{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new GC(A,I,1,1),this.setTexture(0,B),this.channels_=SC(B,Q),this.programName=$i(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=SC(this.textures[0],A)}setChannelProperty(A,I,B){const Q=$B(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]??$B(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-B[0],ValueScale:1/(B[1]-B[0])}}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}}}}function $i(g){if(g.type==="Texture2D")return AD(g.dataType);if(g.type==="Texture2DArray")return ID(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function AD(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 ID(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 gg extends _B{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 gg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function IQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return pA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=pA(C.clientX,C.clientY);if(Gi(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const h=I(o);h!==null&&B({world:o,value:h})}return null}return A}case"pointercancel":return null;default:return A}}class gD{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&j.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),j.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class gQ extends SI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new gD;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new hA(.6,.3,.3),new hA(.3,.6,.4),new hA(.4,.4,.7),new hA(.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.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_&&(A.chunkManager.removeView(this.chunkStoreView_),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)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>gQ.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_=IQ(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,QC))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Lg(Q,0,A.shape.z-1);VB(B,C,1+1e-6)||j.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(RC(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 AQ(A.shape.x,A.shape.y,gg.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){j.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=oB(rA(),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(RC(I),B),this.visibleChunks_.delete(I))}}}function RC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hB extends _B{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 hB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class BD extends $I{constructor(A,I,B,Q,C,E){super();const i=[],o=[],h=Math.floor(Q),s=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,s,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,R,s,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,h,R,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,h,R,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,h,s,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,h,s,-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,h,s,R,N,r){const M=E/h,e=i/s,n=E/2,f=i/2,O=o/2*R,W=h+1,u=s+1,b=N.length/8;for(let T=0;T<u;T++){const QA=-f+T*e;for(let v=0;v<W;v++){const x=-n+v*M,IA={x:0,y:0,z:0};IA[A]=x*Q,IA[I]=QA*C,IA[B]=O;const AA={x:0,y:0,z:0};AA[B]=R;const wA=v/h,kA=1-T/s;N.push(IA.x,IA.y,IA.z,AA.x,AA.y,AA.z,wA,kA)}}for(let T=0;T<s;T++)for(let QA=0;QA<h;QA++){const v=b+QA+W*T,x=b+QA+W*(T+1),IA=b+(QA+1)+W*(T+1),AA=b+(QA+1)+W*T;R===1?r.push(v,x,AA,x,IA,AA):r.push(v,AA,x,x,AA,IA)}}}class QD extends Ag{constructor(A,I,B,Q){super(),this.geometry=new BD(A,I,B,1,1,1),this.cullFaceMode="back",this.setTexture(0,Q),this.programName=CD(Q.dataType)}get type(){return"VolumeRenderable"}}function CD(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 ED extends SI{type="VolumeLayer";constructor(){super();const A=new Int8Array([127,0,0,127,127,0,0,127]),I=new hB(A,2,2,2);I.unpackAlignment=1;const B=new QD(1,1,1,I);B.wireframeEnabled=!0,this.addObject(B),this.setState("ready")}update(){}}class iD extends SI{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_=IQ(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=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.extent_={x:C.shape.x*C.scale.x,y:C.shape.y*C.scale.y},this.image_=this.createImage(C),this.chunk_=C,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new AQ(A.shape.x,A.shape.y,gg.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=oB(rA(),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 rg extends _B{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new rg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const DD=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function oD(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,hA.from(I)]))}function aD(g){return g=g??DD,g.map(hA.from)}class NC{lookupTable;cycle;constructor(A={}){this.lookupTable=oD(A.lookupTable),this.cycle=aD(A.cycle)}}const sD=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function yD(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!sD.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class hD extends Ag{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new GC(A.width,A.height,1,1),this.setTexture(0,yD(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new rg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,hA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,hA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new rg(C,Q,2)}}class GD extends SI{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 NC(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 NC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=IQ(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=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.image_=this.createImage(C),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new hD({width:A.shape.x,height:A.shape.y,imageData:rg.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=oB(rA(),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 GB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,GB.prototype)}}class FD{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 GB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class wD{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new FD(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 j.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};j.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()).getAttributes(),B=I[this.lod_??I.length-1],Q=B.dimensionNames.findIndex(R=>R===this.seriesDimensionName_);if(Q===-1)throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${B.dimensionNames}`);const C=B.scale[Q],E=B.shape[Q]*C,i=this.seriesIndex_.type==="full",o=i?0:this.seriesIndex_.start,h=i?E:this.seriesIndex_.stop,s=Math.round((h-o)/C);return this.dataChunks_=new Array(s),this.seriesAttributes_={start:o,stop:h,scale:C,length:s},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(s=>s.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=E.getAttributes(),o=this.lod_??i.length-1,h=await E.loadRegion(C,o,this.scheduler_);return this.dataChunks_[A]=h,I&&I.canceled&&(this.loadingToken_=null),h}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 GB)return Promise.reject(Q.reason);j.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class SD extends SI{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 wD({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_=gg.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 AQ(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}}class Yg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class BQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}class QQ{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new Error("keepbits must be zero or positive")}static fromConfig(A,I){return new QQ(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}}class UC{#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 CQ{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q=Q*A),this._data=new Uint8Array(I,B,Q);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class ng{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new ng(A,1);this.#A=new Int32Array(function*(){for(let i of C)E.set(0,i),yield*E.#A}())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Kg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function kC(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}const RD={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float32:Float32Array,float64:Float64Array,bool:UC},ND=/v2:([US])(\d+)/;function tC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(ND);if(A){let[,B,Q]=A;return(B==="U"?ng:CQ).bind(null,Number(Q))}let I=RD[g];if(!I)throw new Error(`Unknown or unsupported data_type: ${g}`);return I}function pI(g,A){return(A==="C"?UD:kD)(g)}function UD(g){const A=g.length,I=globalThis.Array(A);for(let B=A-1,Q=1;B>=0;B--)I[B]=Q,Q*=g[B];return I}function kD(g){const A=g.length,I=globalThis.Array(A);for(let B=0,Q=1;B<A;B++)I[B]=Q,Q*=g[B];return I}function tD({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 EQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order==="F"?"F":"C"}const cD=/^([<|>])(.*)$/;function LD(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(cD);if(!A)throw new Error(`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",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new Error(`Unsupported or unknown dtype: ${g}`);return I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function JD(g,A={}){let I=[],B=LD(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 rD(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function YD(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 nD(g){return g?.name==="sharding_indexed"}function cC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}const LC=KD();function KD(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function JC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class FB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=tC(I.data_type),this.#Q=I.shape,this.#A=pI(I.shape,EQ(I.codecs));const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new FB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return LC&&this.#B==="big"&&kC(I,JC(this.#I)),I}decode(A){return LC&&this.#B==="big"&&kC(A,JC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class iQ{kind="bytes_to_bytes";static fromConfig(){return new iQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}function MD(g,A){if(Number.isNaN(A))throw new Error("JsonCodec allow_nan is false but NaN was encountered during encoding.");if(A===Number.POSITIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but Infinity was encountered during encoding.");if(A===Number.NEGATIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but -Infinity was encountered during encoding.");return A}function HD(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class DQ{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:h=!0}=A;let s=A.separators;s||(o?s=[", ",": "]:s=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:s,sort_keys:i},this.#I={strict:h}}static fromConfig(A){return new DQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;if(B!=="utf-8")throw new Error("JsonCodec does not yet support non-utf-8 encoding.");const o=[];if(!C)throw new Error("JsonCodec does not yet support skipping the check for circular references during encoding.");E||o.push(MD),i&&o.push(HD);const h=Array.from(A.data);h.push("|O"),h.push(A.shape);let s;o.length&&(s=(N,r)=>{let M=r;for(let e of o)M=e(N,M);return M});let R=JSON.stringify(h,s,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,N=>{const r=`0000${N.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;if(!I)throw new Error("JsonCodec does not yet support non-strict decoding.");const B=Kg(A),Q=B.pop();if(B.pop(),!Q)throw new Error("0D not implemented for JsonCodec.");const C=pI(Q,"C");return{data:B,shape:Q,stride:C}}}function rC(g){return g instanceof UC||g instanceof CQ||g instanceof ng?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function eD(g,A){let I;return g.data instanceof CQ||g.data instanceof ng?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:pI(g.shape,A)}}function qD(g,A){let I=eD(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=rC(g.data),i=rC(I.data);for(let o=0;o<Q;o++){let h=0;for(let s=0;s<B;s++)h+=C[s]*I.stride[s];i[h]=E[o],C[0]+=1;for(let s=0;s<B;s++)if(C[s]===g.shape[s]){if(s+1===B)break;C[s]=0,C[s+1]+=1}}return I}function dD(g){if(!g.stride)return"C";let A=pI(g.shape,"C");return g.stride.every((I,B)=>I===A[B])?"C":"F"}class oQ{configuration;kind="array_to_array";constructor(A){this.configuration=A}static fromConfig(A){return new oQ(A)}encode(A){return dD(A)===this.configuration?.order?A:qD(A,this.configuration?.order??"C")}decode(A){return A}}class aQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=pI(A,"C")}static fromConfig(A,I){return new aQ(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}}}function fD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>ss).then(g=>g.default)).set("gzip",()=>Promise.resolve().then(()=>ls).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Zs).then(g=>g.default)).set("zlib",()=>Promise.resolve().then(()=>Ps).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>zs).then(g=>g.default)).set("transpose",()=>oQ).set("bytes",()=>FB).set("crc32c",()=>iQ).set("vlen-utf8",()=>aQ).set("json2",()=>DQ).set("bitround",()=>QQ)}const lD=fD();function sQ(g){let A;return{async encode(I){A||(A=await YC(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 YC(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 YC(g){let A=g.codecs.map(async C=>{let E=await lD.get(C.name)?.();if(!E)throw new Error(`Unknown codec: ${C.name}`);return{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)}}if(!B){if(!pD(g))throw new Error(`Cannot encode ${g.data_type} to bytes without a codec`);B=FB.fromConfig({endian:"little"},g)}return{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function pD(g){return g.data_type!=="v2:object"}const nC=18446744073709551615n;function WD(g,A,I,B){if(g.store.getRange===void 0)throw new Error("Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,h)=>o/B.chunk_shape[h]),E=sQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let h=o.map((O,W)=>Math.floor(O/C[W])),s=g.resolve(I(h)).path,R;if(s in i)R=i[s];else{let O=4,W=16*C.reduce((b,T)=>b*T,1),u=await Q(s,{suffixLength:W+O});R=i[s]=u?await E.decode(u):null}if(R===null)return;let{data:N,shape:r,stride:M}=R,e=o.map((O,W)=>O%r[W]).reduce((O,W,u)=>O+W*M[u],0),n=N[e],f=N[e+1];if(!(n===nC&&f===nC))return Q(s,{offset:Number(n),length:Number(f)})}}class II{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 II(this.store,new URL(A,I).pathname)}}class yQ extends II{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}const Mg=Symbol("zarrita.context");function mD(g){return g[Mg]}function TD(g,A){let{configuration:I}=A.codecs.find(nD)??{},B={encode_chunk_key:tD(A.chunk_key_encoding),TypedArray:tC(A.data_type),fill_value:A.fill_value};if(I){let C=EQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:sQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E,i){return pI(E,i??C)},get_chunk_bytes:WD(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=EQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:sQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C,E){return pI(C,E??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 wB=class extends II{kind="array";#A;[Mg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:cC(B)},this[Mg]=TD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Mg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Mg],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 YD(this.dtype,A)}},SB=xD();function xD(){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 ZD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Kg(A):{}}async function bD(g,A={}){let I="store"in g?g:new II(g),B={};return(A.attrs??!0)&&(B=await ZD(I)),A.kind==="array"?KC(I,B):A.kind==="group"?MC(I,B):KC(I,B).catch(Q=>{if(Q instanceof Yg)return MC(I,B);throw Q})}async function KC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new Yg("v2 array",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new wB(g.store,g.path,JD(Kg(B),A))}async function MC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new Yg("v2 group",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new yQ(g.store,g.path,rD(Kg(B),A))}async function uD(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new Yg("v3 array or group",{cause:new BQ(I)});let Q=Kg(B);return Q.node_type==="array"&&(Q.fill_value=cC(Q)),Q.node_type==="array"?new wB(A,g.path,Q):new yQ(A,g.path,Q)}async function PD(g,A={}){let I="store"in g?g:new II(g),B=await uD(I);if(SB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof wB||A.kind==="group"&&B instanceof yQ)return B;let Q=B instanceof wB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function gI(g,A={}){let I="store"in g?g.store:g,B=SB.version_max(I),Q=B==="v2"?gI.v2:gI.v3,C=B==="v2"?gI.v3:gI.v2;return Q(g,A).catch(E=>{if(E instanceof Yg)return C(g,A);throw E})}gI.v2=bD,gI.v3=PD;function HC(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 OD(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function eC(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 qC(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 VD(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 HC(g,E-A,E,I)}class Hg{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return OD(this.#A,A)}async get(A,I={}){let B=eC(this.url,A).href,Q=await fetch(B,this.#g(I));return qC(Q)}async getRange(A,I,B={}){let Q=eC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await VD(Q,I.suffixLength,C,this.#I):E=await HC(Q,I.offset,I.length,C),qC(E)}}function*XD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*vD(...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 jD({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 RB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function zD(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class hQ extends Error{constructor(A){super(A),this.name="IndexError"}}function _D(g,A){throw new hQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function $D(g){throw new hQ(`index out of bounds for dimension with length ${g}`)}function Ao(){throw new hQ("only slices with step >= 1 are supported")}function Io(g,A){g.length>A.length&&_D(g,A)}function go(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&$D(A),g}class Bo{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=go(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 dC{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]=jD(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&Ao(),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 XD(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 h=this.stop>C?E:this.stop-Q,s=[o,h,this.step],R=Math.ceil((h-o)/this.step),N=[i,i+R,1];yield{dim_chunk_ix:B,dim_chunk_sel:s,dim_out_sel:N}}}}function Qo(g,A){let I=[];return g===null?I=A.map(B=>RB(null)):Array.isArray(g)&&(I=g.map(B=>B??RB(null))),Io(I,A),I}class Co{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=Qo(A,I).map((Q,C)=>new(typeof Q=="number"?Bo:dC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof dC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of vD(...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 Eo(g,A){return"get"in g?g.get(A):g[A]}async function io(g,A,I,B){let Q=mD(g),C=new Co({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,h)=>o*h,1)),C.shape,Q.get_strides(C.shape,I.order)),i=I.create_queue?.()??zD();for(const{chunk_coords:o,mapping:h}of C)i.add(async()=>{let{data:s,shape:R,stride:N}=await g.getChunk(o,I.opts),r=B.prepare(s,R,N);B.set_from_chunk(E,r,h)});return await i.onIdle(),C.shape.length===0?Eo(E.data,0):E}function GQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return GQ(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 FQ(g){return globalThis.Array.isArray(g.data)?{data:GQ(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 Do(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function oo(g,A){if(globalThis.Array.isArray(g.data))return GQ([A]);let I=Do(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const ao={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=FQ(g);wQ(B,A,oo(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=FQ(g);NB(B,FQ(A),B.bytes_per_element,I)}};async function so(g,A=null,I={}){return io(g,A,I,ao)}function fC(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 wQ(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 N=g.data.subarray(E*Q*B);wQ({data:N,stride:i},C,I,B);return}const[o,h,s]=Q,R=fC(o,h,s);if(C.length===0){for(let N=0;N<R;N++)g.data.set(I,E*(o+s*N)*B);return}for(let N=0;N<R;N++){const r=g.data.subarray(E*(o+s*N)*B);wQ({data:r,stride:i},C,I,B)}}function NB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...h]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}NB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let f=Q.from*I;g.data.set(A.data.subarray(f,f+I),0);return}NB(g,{data:A.data.subarray(o*Q.from*I),stride:h},I,C);return}const[s,R,N]=Q.to,[r,M,e]=Q.from,n=fC(s,R,N);if(C.length===0){if(N===1&&e===1&&E===1&&o===1){let f=r*I,O=n*I;g.data.set(A.data.subarray(f,f+O),s*I);return}for(let f=0;f<n;f++){let O=o*(r+e*f)*I;g.data.set(A.data.subarray(O,O+I),E*(s+N*f)*I)}return}for(let f=0;f<n;f++)NB({data:g.data.subarray(E*(s+f*N)*I),stride:i},{data:A.data.subarray(o*(r+f*e)*I),stride:h},I,C)}async function yo(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 SQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await yo(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function eg(g,A){if(A==="v2")try{return gI.v2(g,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${g}`)}try{return gI(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${g}`)}}async function ho(g,A){if(A==="v2")try{return gI.v2(g,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${g}`)}try{return gI(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${g}`)}}async function Go(g){let A;switch(g.type){case"fetch":{A=new II(new Hg(g.url,g.fetchOptions));break}case"filesystem":{A=new II(new SQ(g.directoryHandle),g.path);break}default:{const B=g;throw new Error(`Unsupported store type: ${B}`)}}const I=g.arrayPath?A.resolve(g.arrayPath):A;return ho(I,g.zarrVersion)}function Fo(g,A,I){if(g.store instanceof Hg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:g.store.url.toString()};if(g.store instanceof SQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:g.store.directoryHandle,path:g.path};throw new Error(`Unsupported store type: ${g.store.constructor.name}`)}const lC=`class HI extends Error {
|
|
347
|
+
${Q}`;return g.replace(pB,C)}const ZA=["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 bQ(){const g=Math.random()*4294967295|0,A=Math.random()*4294967295|0,I=Math.random()*4294967295|0,B=Math.random()*4294967295|0;return(ZA[g&255]+ZA[g>>8&255]+ZA[g>>16&255]+ZA[g>>24&255]+"-"+ZA[A&255]+ZA[A>>8&255]+"-"+ZA[A>>16&15|64]+ZA[A>>24&255]+"-"+ZA[I&63|128]+ZA[I>>8&255]+"-"+ZA[I>>16&255]+ZA[I>>24&255]+ZA[B&255]+ZA[B>>8&255]+ZA[B>>16&255]+ZA[B>>24&255]).toLowerCase()}class WB{uuid=bQ()}var fI=1e-6,lA=typeof Float32Array<"u"?Float32Array:Array,uE=Math.PI/180;function PE(g){return g*uE}Math.hypot||(Math.hypot=function(){for(var g=0,A=arguments.length;A--;)g+=arguments[A]*arguments[A];return Math.sqrt(g)});function uQ(){var g=new lA(9);return lA!=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 OE(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 QI(){var g=new lA(16);return lA!=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 mB(g,A){var I=A[0],B=A[1],Q=A[2],C=A[3],E=A[4],i=A[5],o=A[6],h=A[7],s=A[8],R=A[9],N=A[10],r=A[11],M=A[12],e=A[13],n=A[14],f=A[15],O=I*i-B*E,W=I*o-Q*E,u=I*h-C*E,b=B*o-Q*i,T=B*h-C*i,QA=Q*h-C*o,v=s*e-R*M,x=s*n-N*M,IA=s*f-r*M,AA=R*n-N*e,wA=R*f-r*e,kA=N*f-r*n,CA=O*kA-W*wA+u*AA+b*IA-T*x+QA*v;return CA?(CA=1/CA,g[0]=(i*kA-o*wA+h*AA)*CA,g[1]=(Q*wA-B*kA-C*AA)*CA,g[2]=(e*QA-n*T+f*b)*CA,g[3]=(N*T-R*QA-r*b)*CA,g[4]=(o*IA-E*kA-h*x)*CA,g[5]=(I*kA-Q*IA+C*x)*CA,g[6]=(n*u-M*QA-f*W)*CA,g[7]=(s*QA-N*u+r*W)*CA,g[8]=(E*wA-i*IA+h*v)*CA,g[9]=(B*IA-I*wA-C*v)*CA,g[10]=(M*T-e*u+f*O)*CA,g[11]=(R*u-s*T-r*O)*CA,g[12]=(i*x-E*AA-o*v)*CA,g[13]=(I*AA-B*x+Q*v)*CA,g[14]=(e*W-M*b-n*O)*CA,g[15]=(s*b-R*W+N*O)*CA,g):null}function DB(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=A[4],o=A[5],h=A[6],s=A[7],R=A[8],N=A[9],r=A[10],M=A[11],e=A[12],n=A[13],f=A[14],O=A[15],W=I[0],u=I[1],b=I[2],T=I[3];return g[0]=W*B+u*i+b*R+T*e,g[1]=W*Q+u*o+b*N+T*n,g[2]=W*C+u*h+b*r+T*f,g[3]=W*E+u*s+b*M+T*O,W=I[4],u=I[5],b=I[6],T=I[7],g[4]=W*B+u*i+b*R+T*e,g[5]=W*Q+u*o+b*N+T*n,g[6]=W*C+u*h+b*r+T*f,g[7]=W*E+u*s+b*M+T*O,W=I[8],u=I[9],b=I[10],T=I[11],g[8]=W*B+u*i+b*R+T*e,g[9]=W*Q+u*o+b*N+T*n,g[10]=W*C+u*h+b*r+T*f,g[11]=W*E+u*s+b*M+T*O,W=I[12],u=I[13],b=I[14],T=I[15],g[12]=W*B+u*i+b*R+T*e,g[13]=W*Q+u*o+b*N+T*n,g[14]=W*C+u*h+b*r+T*f,g[15]=W*E+u*s+b*M+T*O,g}function VE(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 XE(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=Q+Q,h=C+C,s=E+E,R=Q*o,N=Q*h,r=Q*s,M=C*h,e=C*s,n=E*s,f=i*o,O=i*h,W=i*s,u=B[0],b=B[1],T=B[2];return g[0]=(1-(M+n))*u,g[1]=(N+W)*u,g[2]=(r-O)*u,g[3]=0,g[4]=(N-W)*b,g[5]=(1-(R+n))*b,g[6]=(e+f)*b,g[7]=0,g[8]=(r+O)*T,g[9]=(e-f)*T,g[10]=(1-(R+M))*T,g[11]=0,g[12]=I[0],g[13]=I[1],g[14]=I[2],g[15]=1,g}function vE(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 jE=vE;function zE(g,A,I,B,Q,C,E){var i=1/(A-I),o=1/(B-Q),h=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*h,g[11]=0,g[12]=(A+I)*i,g[13]=(Q+B)*o,g[14]=(E+C)*h,g[15]=1,g}var _E=zE;function $E(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=B[0],o=B[1],h=B[2],s=Q-I[0],R=C-I[1],N=E-I[2],r=s*s+R*R+N*N;r>0&&(r=1/Math.sqrt(r),s*=r,R*=r,N*=r);var M=o*N-h*R,e=h*s-i*N,n=i*R-o*s;return r=M*M+e*e+n*n,r>0&&(r=1/Math.sqrt(r),M*=r,e*=r,n*=r),g[0]=M,g[1]=e,g[2]=n,g[3]=0,g[4]=R*n-N*e,g[5]=N*M-s*n,g[6]=s*e-R*M,g[7]=0,g[8]=s,g[9]=R,g[10]=N,g[11]=0,g[12]=Q,g[13]=C,g[14]=E,g[15]=1,g}function rA(){var g=new lA(3);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g}function CI(g){var A=new lA(3);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A}function PQ(g){var A=g[0],I=g[1],B=g[2];return Math.hypot(A,I,B)}function NA(g,A,I){var B=new lA(3);return B[0]=g,B[1]=A,B[2]=I,B}function tg(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g}function _I(g,A,I,B){return g[0]=A,g[1]=I,g[2]=B,g}function OQ(g,A,I){return g[0]=A[0]+I[0],g[1]=A[1]+I[1],g[2]=A[2]+I[2],g}function Ai(g,A,I){return g[0]=A[0]-I[0],g[1]=A[1]-I[1],g[2]=A[2]-I[2],g}function Ii(g,A,I){return g[0]=A[0]*I[0],g[1]=A[1]*I[1],g[2]=A[2]*I[2],g}function VQ(g,A,I){return g[0]=A[0]*I,g[1]=A[1]*I,g[2]=A[2]*I,g}function XQ(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 vQ(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 gi(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 jQ(g,A){return g[0]*A[0]+g[1]*A[1]+g[2]*A[2]}function TB(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 Bi(g,A,I,B,Q,C){var E=1-C,i=E*E,o=C*C,h=i*E,s=3*C*i,R=3*o*E,N=o*C;return g[0]=A[0]*h+I[0]*s+B[0]*R+Q[0]*N,g[1]=A[1]*h+I[1]*s+B[1]*R+Q[1]*N,g[2]=A[2]*h+I[2]*s+B[2]*R+Q[2]*N,g}function oB(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 Qi(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)<=fI*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(B-E)<=fI*Math.max(1,Math.abs(B),Math.abs(E))&&Math.abs(Q-i)<=fI*Math.max(1,Math.abs(Q),Math.abs(i))}var xB=Ai,Ci=PQ;(function(){var g=rA();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 cg(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0,g[3]=0),g}function Ei(g){var A=new lA(4);return A[0]=g[0],A[1]=g[1],A[2]=g[2],A[3]=g[3],A}function ZB(g,A,I,B){var Q=new lA(4);return Q[0]=g,Q[1]=A,Q[2]=I,Q[3]=B,Q}function ii(g,A){return g[0]=A[0],g[1]=A[1],g[2]=A[2],g[3]=A[3],g}function Di(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 oi(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 aB(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=cg();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 bB(){var g=new lA(4);return lA!=Float32Array&&(g[0]=0,g[1]=0,g[2]=0),g[3]=1,g}function ai(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 si(g,A,I){var B=A[0],Q=A[1],C=A[2],E=A[3],i=I[0],o=I[1],h=I[2],s=I[3];return g[0]=B*s+E*i+Q*h-C*o,g[1]=Q*s+E*o+C*i-B*h,g[2]=C*s+E*h+B*o-Q*i,g[3]=E*s-B*i-Q*o-C*h,g}function uB(g,A,I,B){var Q=A[0],C=A[1],E=A[2],i=A[3],o=I[0],h=I[1],s=I[2],R=I[3],N,r,M,e,n;return r=Q*o+C*h+E*s+i*R,r<0&&(r=-r,o=-o,h=-h,s=-s,R=-R),1-r>fI?(N=Math.acos(r),M=Math.sin(N),e=Math.sin((1-B)*N)/M,n=Math.sin(B*N)/M):(e=1-B,n=B),g[0]=e*Q+n*o,g[1]=e*C+n*h,g[2]=e*E+n*s,g[3]=e*i+n*R,g}function zQ(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 yi=Ei,hi=ii,PB=oi;(function(){var g=rA(),A=NA(1,0,0),I=NA(0,1,0);return function(B,Q,C){var E=jQ(Q,C);return E<-.999999?(TB(g,A,Q),Ci(g)<1e-6&&TB(g,I,Q),gi(g,g),ai(B,g,Math.PI),B):E>.999999?(B[0]=0,B[1]=0,B[2]=0,B[3]=1,B):(TB(g,Q,C),B[0]=g[0],B[1]=g[1],B[2]=g[2],B[3]=1+E,PB(B,B))}})(),function(){var g=bB(),A=bB();return function(I,B,Q,C,E,i){return uB(g,B,E,i),uB(A,Q,C,i),uB(I,g,A,2*i*(1-i)),I}}(),function(){var g=uQ();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],PB(A,zQ(A,g))}}();function _Q(){var g=new lA(2);return lA!=Float32Array&&(g[0]=0,g[1]=0),g}function $Q(g){var A=new lA(2);return A[0]=g[0],A[1]=g[1],A}function pA(g,A){var I=new lA(2);return I[0]=g,I[1]=A,I}function Gi(g,A){var I=A[0]-g[0],B=A[1]-g[1];return Math.hypot(I,B)}function Fi(g){var A=g[0],I=g[1];return A*A+I*I}function wi(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 AC(g,A){return g[0]===A[0]&&g[1]===A[1]}function OB(g,A){var I=g[0],B=g[1],Q=A[0],C=A[1];return Math.abs(I-Q)<=fI*Math.max(1,Math.abs(I),Math.abs(Q))&&Math.abs(B-C)<=fI*Math.max(1,Math.abs(B),Math.abs(C))}(function(){var g=_Q();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 tI{min;max;constructor(A,I){this.min=A?CI(A):NA(1/0,1/0,1/0),this.max=I?CI(I):NA(-1/0,-1/0,-1/0)}clone(){return new tI(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=[NA(I[0],I[1],I[2]),NA(I[0],I[1],B[2]),NA(I[0],B[1],I[2]),NA(I[0],B[1],B[2]),NA(B[0],I[1],I[2]),NA(B[0],I[1],B[2]),NA(B[0],B[1],I[2]),NA(B[0],B[1],B[2])];this.min=NA(1/0,1/0,1/0),this.max=NA(-1/0,-1/0,-1/0);const C=rA();for(const E of Q)oB(C,E,A),this.expandWithPoint(C)}}const Si={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,path_proportion:6,color:7,size:8,marker:9};class $I extends WB{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 tI,Q=rA();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 Ri{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(s=>{const R=Si[s.type];this.gl_.vertexAttribPointer(R,s.itemSize,this.gl_.FLOAT,!1,i,s.offset),this.gl_.enableVertexAttribArray(R)});const o={vao:I,vbo:C},{indexData:h}=A;if(h.length){const s=this.gl_.ELEMENT_ARRAY_BUFFER,R=this.gl_.createBuffer();if(!R)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(s,R),this.gl_.bufferData(s,h,this.gl_.STATIC_DRAW),o.ebo=R}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class Ni{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 j.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 h=0;h<Q;h++)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 jA{min;max;constructor(A,I){this.min=A?$Q(A):pA(1/0,1/0),this.max=I?$Q(I):pA(-1/0,-1/0)}clone(){return new jA(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 AC(A.min,I.min)&&AC(A.max,I.max)}floor(){return new jA(pA(Math.floor(this.min[0]),Math.floor(this.min[1])),pA(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 Ui{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A}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"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_&&jA.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_&&jA.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}}}const ki=VE(QI(),[1,-1,1]);class IC extends KE{gl_=null;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;constructor(A){if(super(A),this.gl_=this.canvas.getContext("webgl2",{depth:!0,antialias:!0}),!this.gl_)throw new Error("Failed to initialize WebGL2 context");j.info("WebGLRenderer",`WebGL version ${this.gl.getParameter(this.gl.VERSION)}`),this.programs_=new bE(this.gl),this.bindings_=new Ri(this.gl),this.textures_=new Ni(this.gl),this.state_=new Ui(this.gl),this.resize(this.canvas.width,this.canvas.height)}render(A){const I=A.getBoxRelativeTo(this.canvas),B=new jA(pA(0,0),pA(this.width,this.height));if(jA.equals(I.floor(),B.floor()))this.state_.setScissorTest(!1);else if(jA.intersects(I,B))this.state_.setScissor(I),this.state_.setScissorTest(!0);else{j.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}renderLayer(A,I,B){this.state_.setBlendingMode(A.transparent?A.blendMode:"none"),A.objects.forEach((Q,C)=>{B.intersectsWithBox3(Q.boundingBox)&&(this.renderObject(A,C,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,B){const Q=A.objects[I];this.state_.setCullFaceMode(Q.cullFaceMode),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=DB(QI(),C.viewMatrix,I.transform.matrix),i=DB(QI(),ki,C.projectionMatrix),o=[this.canvas.width,this.canvas.height],h=I.getUniforms();for(const N of Q.uniformNames)switch(N){case"ModelView":Q.setUniform(N,E);break;case"Projection":Q.setUniform(N,i);break;case"Resolution":Q.setUniform(N,o);break;case"u_opacity":Q.setUniform(N,B.opacity);break;default:N in h&&Q.setUniform(N,h[N])}const s=this.glGetPrimitive(A.primitive),R=A.indexData;R.length?this.gl.drawElements(s,R.length,this.gl.UNSIGNED_INT,0):this.gl.drawArrays(s,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 jA(pA(0,0),pA(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)}get gl(){return this.gl_}}const ti=8;class ci{maxConcurrent_;pending_=[];running_=new Map;constructor(A=ti){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),j.debug("ChunkQueue","Cancelled pending request");return}const B=this.running_.get(A);B&&(B.controller.abort(),j.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"&&j.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:Q,promise:C})}}const gC=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function BC(g){if(gC.some(I=>g instanceof I))return!0;const A=gC.map(I=>I.name);return j.debug("Chunk",`Unsupported chunk data type: ${g}. Supported data types: ${A}`),!1}function Li(g,A){return Math.round((A-g.translation)/g.scale)}function VB(g,A,I=1e-6){return Math.abs(g-A)<=I}class Ji{chunks_;loader_;lowestResLOD_;dimensions_;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],h=this.dimensions_.z?.lods[E],s=i.chunkSize,R=o.chunkSize,N=h?.chunkSize??1,r=Math.ceil(i.size/s),M=Math.ceil(o.size/R),e=Math.ceil((h?.size??1)/N);for(let n=0;n<B;++n)for(let f=0;f<r;++f){const O=i.translation+f*i.chunkSize*i.scale;for(let W=0;W<M;++W){const u=o.translation+W*o.chunkSize*o.scale;for(let b=0;b<e;++b){const T=h!==void 0?h.translation+b*N*h.scale:0;C.push({state:"unloaded",lod:E,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(s,i.size-f*s),y:Math.min(R,o.size-W*R),z:Math.min(N,(h?.size??1)-b*N),c:1},rowAlignmentBytes:1,chunkIndex:{x:f,y:W,z:b,c:n,t:Q},scale:{x:i.scale,y:o.scale,z:h?.scale??1},offset:{x:O,y:u,z:T}})}}}}}}getChunksAtTime(A){return this.chunks_[A]}getTimeIndex(A){return A.t===void 0||this.dimensions_.t===void 0?0:Li(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)}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(!VB(Q,2,.02)||!VB(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}}}function Lg(g,A,I){return Math.max(A,Math.min(I,g))}const QC=Symbol("INTERNAL_POLICY_KEY");class ri{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastZBounds_;lastTCoord_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;constructor(A,I){this.store_=A,this.policy_=I,j.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_=Fi(pA(Q.size*Q.scale,C.size*C.scale))}get store(){return this.store_}get chunkViewStates(){return this.chunkViewStates_}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();return this.currentLOD_===C?Q:[...B.filter(i=>i.lod===C&&this.chunkViewStates_.get(i)?.visible===!0&&i.state==="loaded"),...Q]}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,h=E/o,s=Math.log2(1/h);this.setLOD(s);const R=this.getZBounds(A);(this.policyChanged_||this.viewBounds2DChanged(C)||this.zBoundsChanged(R)||this.lastTCoord_!==A.t)&&(this.updateChunkViewStates(A,C),this.policyChanged_=!1,this.lastViewBounds2D_=C.clone(),this.lastZBounds_=R,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)}setImageSourcePolicy(A,I){if(I!==QC)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,j.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)),h=Math.max(o,Math.min(i,this.policy_.lod.max)),s=Lg(E,o,h);s!==this.currentLOD_&&(this.currentLOD_=s)}updateChunkViewStates(A,I){const B=this.store_.getTimeIndex(A);if(this.store_.getChunksAtTime(B).length===0){j.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const C=_Q();wi(C,I.min,I.max,.5);const[E,i]=this.getZBounds(A),o=new tI(NA(I.min[0],I.min[1],E),NA(I.max[0],I.max[1],i));this.chunkViewStates_.forEach(Yi),this.updateChunksAtTimeIndex(B,A,o,C),A.t!==void 0&&this.markTimeChunksForPrefetch(B,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),h=this.isChunkChannelInSlice(i,I),s=i.lod===this.currentLOD_,R=i.lod===this.store_.getLowestResLOD(),N=!o&&h&&s&&this.isChunkWithinBounds(i,C),r=o&&h,M=this.computePriority(R,s,o,N,h);if(M!==null){const e=this.squareDistance2D(i,Q);this.chunkViewStates_.set(i,{visible:r,prefetch:N,priority:M,orderKey:e})}}}markTimeChunksForPrefetch(A,I,B){const Q=this.store_.dimensions.t?.lods[0].size??1,C=Math.min(Q-1,A+this.policy_.prefetch.t);for(let E=A+1;E<=C;++E)for(const i of this.store_.getChunksAtTime(E)){if(i.lod!==this.store_.getLowestResLOD()||!this.isChunkWithinBounds(i,I))continue;const o=this.policy_.priorityMap.prefetchTime,h=this.squareDistance2D(i,B),s=Lg(h/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),R=E-A+s;this.chunkViewStates_.set(i,{visible:!1,prefetch:!0,priority:o,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 tI(NA(A.offset.x,A.offset.y,A.offset.z),NA(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 tI.intersects(B,I)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0||A.z===void 0)return[0,1];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,h=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(Q/o)-1));return[E+h*o*C,E+(h+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!OB(this.lastViewBounds2D_.min,A.min)||!OB(this.lastViewBounds2D_.max,A.max)}zBoundsChanged(A){return!this.lastZBounds_||!OB(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 tI(NA(A.min[0]-E,A.min[1]-i,A.min[2]-o),NA(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 Yi(g){g.visible=!1,g.prefetch=!1,g.priority=null,g.orderKey=null}class ni{stores_=new Map;pendingStores_=new Map;views_=new Map;queue_=new ci;async addView(A,I){const B=await this.addSource(A),Q=new ri(B,I);return this.views_.set(B,(this.views_.get(B)??[]).concat(Q)),Q}removeView(A){const I=A.store,B=this.getSourceForStore(I),Q=this.views_.get(I);if(!Q)throw new Error("Cannot remove view: store not managed by ChunkManager");const C=Q.indexOf(A);if(C===-1)throw new Error(`Cannot remove view: view not found in store's view list (source: ${B})`);const E=Array.from(A.chunkViewStates.keys());Q.splice(C,1);for(const i of E)this.aggregateChunkViewStates(i,I);Q.length===0&&(this.stores_.delete(B),this.views_.delete(I))}async addSource(A){const I=this.stores_.get(A)??this.pendingStores_.get(A);if(I)return I;const Q=(async()=>{const C=await A.open(),E=new Ji(C);return this.stores_.set(A,E),this.pendingStores_.delete(A),E})();return this.pendingStores_.set(A,Q),Q}getSourceForStore(A){for(const[I,B]of this.stores_)if(B===A)return I;throw new Error("Source not found for the given store.")}update(){for(const[A,I]of this.stores_){const B=this.updateAndCollectChunkChanges(I);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()}updateAndCollectChunkChanges(A){const I=this.views_.get(A);if(!I)return new Set;const B=new Set;for(const Q of I)for(const[C,E]of Q.chunkViewStates)B.add(C);for(const Q of B)this.aggregateChunkViewStates(Q,A);return B}aggregateChunkViewStates(A,I){const B=this.views_.get(I);if(!B)return;let Q=!1,C=!1,E=null,i=null;for(const R of B){const N=R.chunkViewStates.get(A);N&&(N.visible&&(Q=!0),N.prefetch&&(C=!0),N.priority!==null&&(E===null||N.priority<E)&&(E=N.priority,i=N.orderKey),!N.visible&&!N.prefetch&&N.priority===null&&R.maybeForgetChunk(A))}if(A.visible=Q,A.prefetch=C,A.priority=E,A.orderKey=i,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}A.state==="loaded"&&!A.visible&&!A.prefetch&&(A.data=void 0,A.state="unloaded",A.priority=null,A.orderKey=null,A.prefetch=!1,j.debug("ChunkManager",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`))}}var Jg=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(R){R.preventDefault(),Q(++A%I.children.length)},!1);function B(R){return I.appendChild(R.dom),R}function Q(R){for(var N=0;N<I.children.length;N++)I.children[N].style.display=N===R?"block":"none";A=R}var C=(performance||Date).now(),E=C,i=0,o=B(new Jg.Panel("FPS","#0ff","#002",g)),h=B(new Jg.Panel("MS","#0f0","#020",g));if(self.performance&&self.performance.memory)var s=B(new Jg.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 R=(performance||Date).now();if(h.update(R-C,200),R>=E+1e3&&(o.update(i*1e3/(R-E),100),E=R,i=0,s)){var N=performance.memory;s.update(N.usedJSHeapSize/1048576,N.jsHeapSizeLimit/1048576)}return R},update:function(){C=this.end()},domElement:I,setMode:Q}};Jg.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),h=E(48*i*B),s=E(3*i*B),R=E(2*i*B),N=E(3*i*B),r=E(15*i*B),M=E(74*i*B),e=E(30*i*B),n=document.createElement("canvas");n.width=o,n.height=h,n.style.cssText=`width:${E(B*80)}px;height:${E(B*48)}px`;var f=n.getContext("2d");return f.font="bold "+E(9*i*B)+"px Helvetica,Arial,sans-serif",f.textBaseline="top",f.fillStyle=I,f.fillRect(0,0,o,h),f.fillStyle=A,f.fillText(g,s,R),f.fillRect(N,r,M,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N,r,M,e),{dom:n,update:function(O,W){Q=Math.min(Q,O),C=Math.max(C,O),f.fillStyle=I,f.globalAlpha=1,f.fillRect(0,0,o,r),f.fillStyle=A,f.fillText(E(O)+" "+g+" ("+E(Q)+"-"+E(C)+")",s,R),f.drawImage(n,N+i,r,M-i,e,N,r,M-i,e),f.fillRect(N+M-i,r,i,e),f.fillStyle=I,f.globalAlpha=.9,f.fillRect(N+M-i,r,i,E((1-O/W)*e))}}};function Ki({scale:g}={scale:1.5}){const A=new Jg(g);return A.showPanel(0),document.body.appendChild(A.dom),A}class CC{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 XB=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function Mi(g){return XB.includes(g)}class Hi{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 ei{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){j.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,XB.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){j.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,XB.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!Mi(A.type)){j.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new Hi(A.type,A);for(const B of this.listeners_)if(B(I),I.propagationStopped)break}}class EC{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 ei(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:B,clientY:Q}=I.event,C=pA(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,h=I.y-E,s=Math.floor(o),R=Math.floor(i-h-I.height),N=Math.floor(I.width),r=Math.floor(I.height);return new jA(pA(s,R),pA(s+N,R+r))}clientToClip(A,I=0){const[B,Q]=A,C=this.element.getBoundingClientRect();return NA(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 jA(pA(B,Q),pA(B+C,Q+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){j.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 iC(g,A,I){const B=g.map(Q=>{const C=Q.element??A;return{...Q,element:C,id:Q.id??C.id??bQ(),layerManager:new CC(I)}});return qi(B),B.map(Q=>new EC(Q))}class di{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;changed_=!1;constructor(A=[]){this.elements_=A}connect(){if(this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.changed_=!0});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}getAndResetChanged(){const A=this.changed_;return this.changed_=!1,A}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.changed_=!0,this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){j.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}}class fi{lastAnimationId_;chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;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 IC(this.canvas),this.chunkManager_=new ni,this.context_={chunkManager:this.chunkManager_},this.viewports_=iC(A.viewports,this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=Ki());const I=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&I.push(B.element);this.sizeObserver_=new di(I)}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(j.info("Idetik","Idetik runtime starting"),this.lastAnimationId_===void 0){for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.animate()}else j.warn("Idetik","Idetik runtime already started");return this}animate(A){this.stats_&&this.stats_.begin(),this.sizeObserver_.getAndResetChanged()&&this.updateSize();for(const I of this.viewports_)this.renderer_.render(I);this.chunkManager_.update();for(const I of this.overlays)I.update(this,A);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(I=>this.animate(I))}stop(){if(j.info("Idetik","Idetik runtime stopping"),this.lastAnimationId_===void 0)j.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}}updateSize(){this.renderer_.updateSize();for(const A of this.viewports_)A.updateSize()}}class li extends $I{constructor(A){if(super(),A.primitive!="triangles"){j.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){j.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),h=Math.max(E,i);I.has({i0:o,i1:h})||(I.add({i0:o,i1:h}),B.push(o,h))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],h=C[E+2];Q(i,o),Q(o,h),Q(h,i)}this.indexData_=new Uint32Array(B)}}const pi=NA(0,1,0);class Wi{dirty_=!0;matrix_=QI();rotation_=bB();translation_=rA();scale_=NA(1,1,1);addRotation(A){si(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){hi(this.rotation_,A),this.dirty_=!0}get rotation(){return yi(this.rotation_)}addTranslation(A){OQ(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){tg(this.translation_,A),this.dirty_=!0}get translation(){return CI(this.translation_)}addScale(A){Ii(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){tg(this.scale_,A),this.dirty_=!0}targetTo(A){Qi(this.translation_,A)&&(A=CI(A),A[2]+=fI);const I=$E(QI(),this.translation_,A,pi),B=OE(uQ(),I);zQ(this.rotation_,B),PB(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return CI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return mB(QI(),this.matrix)}computeMatrix(){XE(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Ag extends WB{wireframeEnabled=!1;wireframeColor=hA.WHITE;textures_=[];staleTextures_=[];transform_=new Wi;geometry_=new $I;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 li(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=NA(0,1,0),I=0){this.normal=CI(A),this.signedDistance=I}set(A,I){this.normal=CI(A),this.signedDistance=I}signedDistanceToPoint(A){return jQ(this.normal,A)+this.signedDistance}normalize(){const A=PQ(this.normal);if(A>0){const I=1/A;VQ(this.normal,this.normal,I),this.signedDistance*=I}}}class DC{planes_;constructor(A){this.planes_=[new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0),new lI(rA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=rA();this.planes_[0].set(_I(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(_I(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(_I(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(_I(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(_I(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(_I(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=rA();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 oC extends Ag{projectionMatrix_=QI();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 NA(A[0],A[1],A[2])}get up(){const A=this.transform.matrix;return NA(A[4],A[5],A[6])}get frustum(){return new DC(DB(QI(),this.projectionMatrix,this.viewMatrix))}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=ZB(A[0],A[1],A[2],1),B=mB(QI(),this.projectionMatrix_),Q=aB(cg(),I,B);Di(Q,Q,1/Q[3]);const C=aB(cg(),Q,this.transform.matrix);return NA(C[0],C[1],C[2])}}const aC=1.77,sC=128,yC=128/aC;class mi extends oC{width_=sC;height_=yC;viewportAspectRatio_=aC;viewportSize_=[sC,yC];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=ZB(-1,-1,0,1),I=ZB(1,1,0,1);const B=DB(QI(),this.projectionMatrix,this.viewMatrix),Q=mB(QI(),B);return A=aB(cg(),A,Q),I=aB(cg(),I,Q),new jA(pA(A[0],A[1]),pA(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],_E(this.projectionMatrix_,-Q,Q,-C,C,this.near_,this.far_)}}const Ti=60,xi=1.77,sB=.1,vB=180-sB;class Zi extends oC{fov_;aspectRatio_;constructor(A={}){const{fov:I=Ti,aspectRatio:B=xi,near:Q=.1,far:C=1e4,position:E=NA(0,0,0)}=A;if(I<sB||I>vB)throw new Error(`Invalid field of view: ${I}, must be in [${sB}, ${vB}] 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(sB,Math.min(vB,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){jE(this.projectionMatrix_,PE(this.fov),this.aspectRatio_,this.near_,this.far_)}}const hC=0;class bi{camera_;dragActive_=!1;dragStart_=rA();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}}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const B=CI(A.worldPos),Q=I.deltaY<0?1.05:.95;this.camera_.zoom(Q);const C=this.camera_.clipToWorld(A.clipPos),E=xB(rA(),B,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==hC||(this.dragStart_=CI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=xB(rA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==hC||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}class SI{objects_=[];state_="initialized";callbacks_=[];transparent;opacity_;blendMode;constructor({transparent:A=!1,opacity:I=1,blendMode:B="normal"}={}){(I<0||I>1)&&j.warn("Layer",`Layer opacity out of bounds: ${I} — clamping to [0.0, 1.0]`),this.transparent=A,this.opacity_=Lg(I,0,1),this.blendMode=B}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&j.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=Lg(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)}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_=[]}}class yB extends $I{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+vQ(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 h=A[E-1]??A[E];I[B++]=h[0],I[B++]=h[1],I[B++]=h[2];const s=A[E+1]??A[E];I[B++]=s[0],I[B++]=s[1],I[B++]=s[2],I[B++]=i,I[B++]=Q}Q+=vQ(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 jB extends Ag{color_;width_;taperOffset_=.5;taperPower_=0;constructor({geometry:A,color:I,width:B,taperOffset:Q,taperPower:C}){super(),this.geometry=A,this.color_=hA.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_=hA.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 ui extends SI{type="AxesLayer";constructor(A){super();const{length:I,width:B}=A;this.addObject(zB({end:[I,0,0],width:B,color:[1,0,0]})),this.addObject(zB({end:[0,I,0],width:B,color:[0,1,0]})),this.addObject(zB({end:[0,0,I],width:B,color:[0,0,1]})),this.setState("ready")}update(){}}function zB(g){const{end:A,width:I,color:B}=g,Q=new yB([[0,0,0],A]);return new jB({geometry:Q,color:B,width:I})}class Pi extends SI{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 yB(I);this.addObject(new jB({geometry:C,color:B,width:Q}))}update(){}get extent(){return Oi(this.paths_.flat())}}function Oi(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}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 Vi extends SI{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=vi({path:A.path,pointsPerSegment:A.interpolation.pointsPerSegment,tangentFactor:A.interpolation.tangentFactor});I=new yB(i)}else I=new yB(A.path);const{color:B,width:Q}=A,C=.5,E=1.5;this.addObject(new jB({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 Xi(A.flat())}}function Xi(g){function A(o){const h=g.map(s=>s[o]);return[Math.min(...h),Math.max(...h)]}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 vi({path:g,pointsPerSegment:A,tangentFactor:I=1/3}){const B=ji(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=CI(B[C]);XQ(o,E,o,I);const h=CI(B[C+1]);XQ(h,i,h,-I);for(let s=0;s<A;s++){const R=s/A,N=Q[C*A+s]=rA();Bi(N,E,o,h,i,R)}}return Q}function ji(g){if(g.length<2)throw new Error("Path must contain at least 2 points");const A=Array(g.length),I=rA(),B=rA();for(let Q=0;Q<g.length;Q++){const C=g[Q],E=g[Q+1]??g[Q];A[Q]=rA(),Q!==0&&tg(I,B),Q!==g.length-1&&xB(B,E,C),Q===0?tg(A[Q],B):Q==g.length-1?tg(A[Q],I):(OQ(A[Q],I,B),VQ(A[Q],A[Q],.5))}return A}class GC extends $I{constructor(A,I,B,Q){super();const C=[],E=[],i=B,o=Q,h=i+1,s=o+1,R=A/i,N=I/o;for(let r=0;r<s;++r){const M=r*N;for(let e=0;e<h;++e){const n=e*R,f=e/i,O=r/o,W=[n,M,0],u=[0,0,1],b=[f,O];C.push(...W,...u,...b)}}for(let r=0;r<o;++r)for(let M=0;M<i;++M){const e=M+h*r,n=M+h*(r+1),f=M+1+h*(r+1),O=M+1+h*r;E.push(e,n,O),E.push(n,f,O)}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 FC(g){return g===1||g===2||g===4||g===8}function Ig(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 zi(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 _B extends WB{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 wC=32;function $B(g,{visible:A,color:I,contrastLimits:B}){return A===void 0&&(A=!0),I===void 0?I=hA.WHITE:I=hA.from(I),g!==null?B=_i(B,g):B===void 0&&(j.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),B=[0,1]),{visible:A,color:I,contrastLimits:B}}function SC(g,A){if(A.length>wC)throw new Error(`Maximum number of channels is ${wC}`);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=>$B(g,I))}function _i(g,A){if(g===void 0)return zi(A);if(g[1]<=g[0])throw new Error(`Contrast limits must be strictly increasing: ${g}.`);return g}class AQ extends Ag{channels_;constructor(A,I,B,Q=[]){super(),this.geometry=new GC(A,I,1,1),this.setTexture(0,B),this.channels_=SC(B,Q),this.programName=$i(B)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=SC(this.textures[0],A)}setChannelProperty(A,I,B){const Q=$B(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]??$B(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 $i(g){if(g.type==="Texture2D")return AD(g.dataType);if(g.type==="Texture2DArray")return ID(g.dataType);throw new Error(`Unsupported image texture type: ${g.type}`)}function AD(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 ID(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 gg extends _B{data_;width_;height_;depth_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 gg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}function IQ(g,A,I,B,Q=3){switch(g.type){case"pointerdown":{const C=g.event;return pA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=g.event,E=pA(C.clientX,C.clientY);if(Gi(A,E)<Q){if(!B)return null;const o=g.worldPos;if(o){const h=I(o);h!==null&&B({world:o,value:h})}return null}return A}case"pointercancel":return null;default:return A}}class gD{bins_=new Map;acquire(A){const B=this.bins_.get(A)?.pop();return B&&j.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),j.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class gQ extends SI{type="ChunkedImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new gD;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;zPrevPointWorld_;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new hA(.6,.3,.3),new hA(.3,.6,.4),new hA(.4,.4,.7),new hA(.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.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_&&(A.chunkManager.removeView(this.chunkStoreView_),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)}}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>gQ.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_=IQ(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,QC))}slicePlane(A,I){if(!A.data)return;const B=(I-A.offset.z)/A.scale.z,Q=Math.round(B),C=Lg(Q,0,A.shape.z-1);VB(B,C,1+1e-6)||j.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(RC(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 AQ(A.shape.x,A.shape.y,gg.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){j.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=oB(rA(),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(RC(I),B),this.visibleChunks_.delete(I))}}}function RC(g){return[`lod${g.lod}`,`shape${g.shape.x}x${g.shape.y}`,`align${g.rowAlignmentBytes}`].join(":")}class hB extends _B{data_;width_;height_;depth_;constructor(A,I,B,Q){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(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 hB(I,A.shape.x,A.shape.y,A.shape.z);return B.unpackAlignment=A.rowAlignmentBytes,B}}class BD extends $I{constructor(A,I,B,Q,C,E){super();const i=[],o=[],h=Math.floor(Q),s=Math.floor(C),R=Math.floor(E);this.buildFace("z","y","x",-1,-1,B,I,A,R,s,1,i,o),this.buildFace("z","y","x",1,-1,B,I,A,R,s,-1,i,o),this.buildFace("x","z","y",1,1,A,B,I,h,R,1,i,o),this.buildFace("x","z","y",1,-1,A,B,I,h,R,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,B,h,s,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,B,h,s,-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,h,s,R,N,r){const M=E/h,e=i/s,n=E/2,f=i/2,O=o/2*R,W=h+1,u=s+1,b=N.length/8;for(let T=0;T<u;T++){const QA=-f+T*e;for(let v=0;v<W;v++){const x=-n+v*M,IA={x:0,y:0,z:0};IA[A]=x*Q,IA[I]=QA*C,IA[B]=O;const AA={x:0,y:0,z:0};AA[B]=R;const wA=v/h,kA=1-T/s;N.push(IA.x,IA.y,IA.z,AA.x,AA.y,AA.z,wA,kA)}}for(let T=0;T<s;T++)for(let QA=0;QA<h;QA++){const v=b+QA+W*T,x=b+QA+W*(T+1),IA=b+(QA+1)+W*(T+1),AA=b+(QA+1)+W*T;R===1?r.push(v,x,AA,x,IA,AA):r.push(v,AA,x,x,AA,IA)}}}class QD extends Ag{constructor(A,I,B,Q){super(),this.geometry=new BD(A,I,B,1,1,1),this.cullFaceMode="back",this.setTexture(0,Q),this.programName=CD(Q.dataType)}get type(){return"VolumeRenderable"}}function CD(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 ED extends SI{type="VolumeLayer";constructor(){super();const A=new Int8Array([127,0,0,127,127,0,0,127]),I=new hB(A,2,2,2);I.unpackAlignment=1;const B=new QD(1,1,1,I);B.wireframeEnabled=!0,this.addObject(B),this.setState("ready")}update(){}}class iD extends SI{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_=IQ(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=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.extent_={x:C.shape.x*C.scale.x,y:C.shape.y*C.scale.y},this.image_=this.createImage(C),this.chunk_=C,this.addObject(this.image_),this.setState("ready")}get extent(){return this.extent_}createImage(A){const I=new AQ(A.shape.x,A.shape.y,gg.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=oB(rA(),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 rg extends _B{data_;width_;height_;constructor(A,I,B){super(),this.dataFormat="scalar",this.dataType=Ig(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!=Ig(B))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=B}}static createWithChunk(A,I){const B=I??A.data;if(!B)throw new Error("Unable to create texture, chunk data is not initialized.");const Q=new rg(B,A.shape.x,A.shape.y);return Q.unpackAlignment=A.rowAlignmentBytes,Q}}const DD=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function oD(g){return g=g??new Map,new Map(Array.from(g.entries()).map(([A,I])=>[A,hA.from(I)]))}function aD(g){return g=g??DD,g.map(hA.from)}class NC{lookupTable;cycle;constructor(A={}){this.lookupTable=oD(A.lookupTable),this.cycle=aD(A.cycle)}}const sD=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function yD(g){if(g.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${g.dataFormat}`);if(!sD.has(g.dataType))throw new Error(`Image data type must be unsigned, instead found: ${g.dataType}`);return g}class hD extends Ag{outlineSelected_;selectedValue_;constructor(A){super(),this.geometry=new GC(A.width,A.height,1,1),this.setTexture(0,yD(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const B=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,B),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(Q=>Q.rgba).map(Q=>Math.round(Q*255))),B=new rg(I,A.length,1);return B.dataFormat="rgba",B}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,hA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,hA.TRANSPARENT],...A]));const I=Array.from(A.keys()),B=Array.from(A.values()).map(E=>E.packed),Q=A.size,C=new Uint32Array(Q*2);return C.set(I,0),C.set(B,Q),new rg(C,Q,2)}}class GD extends SI{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 NC(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 NC(A),this.image_&&this.image_.setColorMap(this.colorMap_)}setSelectedValue(A){this.selectedValue_=A,this.image_&&this.image_.setSelectedValue(this.selectedValue_)}onEvent(A){this.pointerDownPos_=IQ(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=I.getAttributes(),Q=this.lod_??B.length-1,C=await I.loadRegion(A,Q);this.image_=this.createImage(C),this.addObject(this.image_),this.setState("ready")}createImage(A){this.imageChunk_=A;const I=new hD({width:A.shape.x,height:A.shape.y,imageData:rg.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=oB(rA(),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 GB extends Error{constructor(A){super(A),this.name="AbortError",Object.setPrototypeOf(this,GB.prototype)}}class FD{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 GB("shutdown"))}get numRunning(){return this.numRunning_}get numPending(){return this.pending_.length}}class wD{source_;region_;seriesDimensionName_;seriesIndex_;scheduler_=new FD(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 j.debug("ImageSeriesLoader","Ignoring duplicate active setIndex request"),{success:!1,reason:"duplicate"};j.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()).getAttributes(),B=I[this.lod_??I.length-1],Q=B.dimensionNames.findIndex(R=>R===this.seriesDimensionName_);if(Q===-1)throw new Error(`Series dimension "${this.seriesDimensionName_}" not found in loader dimensions: ${B.dimensionNames}`);const C=B.scale[Q],E=B.shape[Q]*C,i=this.seriesIndex_.type==="full",o=i?0:this.seriesIndex_.start,h=i?E:this.seriesIndex_.stop,s=Math.round((h-o)/C);return this.dataChunks_=new Array(s),this.seriesAttributes_={start:o,stop:h,scale:C,length:s},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(s=>s.dimension!==this.seriesDimensionName_);C.push({dimension:this.seriesDimensionName_,index:{type:"point",value:Q}});const E=await this.getLoader(),i=E.getAttributes(),o=this.lod_??i.length-1,h=await E.loadRegion(C,o,this.scheduler_);return this.dataChunks_[A]=h,I&&I.canceled&&(this.loadingToken_=null),h}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 GB)return Promise.reject(Q.reason);j.error("ImageSeriesLoader",`Error loading slice: ${Q.reason}`)}}async getLoader(){return this.loader_??=await this.source_.open(),this.loader_}}class SD extends SI{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 wD({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_=gg.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 AQ(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}}class Yg extends Error{constructor(A,I={}){super(`Node not found: ${A}`,I),this.name="NodeNotFoundError"}}class BQ extends Error{constructor(A){super(`Missing key: ${A}`),this.name="KeyError"}}class QQ{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new Error("keepbits must be zero or positive")}static fromConfig(A,I){return new QQ(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}}class UC{#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 CQ{_data;chars;#A;constructor(A,I,B,Q){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q=Q*A),this._data=new Uint8Array(I,B,Q);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const B=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);B.fill(0),B.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let B=0;B<this.length;B++)this._data.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class ng{#A;chars;constructor(A,I,B,Q){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(I instanceof ArrayBuffer)Q&&(Q*=A),this.#A=new Int32Array(I,B,Q);else{const C=I,E=new ng(A,1);this.#A=new Int32Array(function*(){for(let i of C)E.set(0,i),yield*E.#A}())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let B="";for(let Q=0;Q<this.chars;Q++)B+=String.fromCodePoint(this.#A[I+Q]);return B.replace(/\u0000/g,"")}set(A,I){const B=this.chars*A,Q=this.#A.subarray(B,B+this.chars);Q.fill(0);for(let C=0;C<this.chars;C++)Q[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let B=1;B<this.length;B++)this.#A.set(I,B*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function Kg(g){const A=new TextDecoder().decode(g);return JSON.parse(A)}function kC(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}const RD={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float32:Float32Array,float64:Float64Array,bool:UC},ND=/v2:([US])(\d+)/;function tC(g){if(g==="v2:object")return globalThis.Array;let A=g.match(ND);if(A){let[,B,Q]=A;return(B==="U"?ng:CQ).bind(null,Number(Q))}let I=RD[g];if(!I)throw new Error(`Unknown or unsupported data_type: ${g}`);return I}function pI(g,A){return(A==="C"?UD:kD)(g)}function UD(g){const A=g.length,I=globalThis.Array(A);for(let B=A-1,Q=1;B>=0;B--)I[B]=Q,Q*=g[B];return I}function kD(g){const A=g.length,I=globalThis.Array(A);for(let B=0,Q=1;B<A;B++)I[B]=Q,Q*=g[B];return I}function tD({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 EQ(g){return g.find(I=>I.name==="transpose")?.configuration?.order==="F"?"F":"C"}const cD=/^([<|>])(.*)$/;function LD(g){if(g==="|O")return{data_type:"v2:object"};let A=g.match(cD);if(!A)throw new Error(`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",f4:"float32",f8:"float64"}[B]??(B.startsWith("S")||B.startsWith("U")?`v2:${B}`:void 0);if(!Q)throw new Error(`Unsupported or unknown dtype: ${g}`);return I==="|"?{data_type:Q}:{data_type:Q,endian:I==="<"?"little":"big"}}function JD(g,A={}){let I=[],B=LD(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 rD(g,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function YD(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 nD(g){return g?.name==="sharding_indexed"}function cC(g){return(g.data_type==="uint64"||g.data_type==="int64")&&g.fill_value!=null?BigInt(g.fill_value):g.fill_value}const LC=KD();function KD(){const g=new Uint32Array([305419896]);return new Uint8Array(g.buffer,g.byteOffset,g.byteLength)[0]!==18}function JC(g){return"BYTES_PER_ELEMENT"in g?g.BYTES_PER_ELEMENT:4}class FB{kind="array_to_bytes";#A;#I;#g;#Q;#B;constructor(A,I){this.#B=A?.endian,this.#I=tC(I.data_type),this.#Q=I.shape,this.#A=pI(I.shape,EQ(I.codecs));const B=new this.#I(0);this.#g=B.BYTES_PER_ELEMENT}static fromConfig(A,I){return new FB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return LC&&this.#B==="big"&&kC(I,JC(this.#I)),I}decode(A){return LC&&this.#B==="big"&&kC(A,JC(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#Q,stride:this.#A}}}class iQ{kind="bytes_to_bytes";static fromConfig(){return new iQ}encode(A){throw new Error("Not implemented")}decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}}function MD(g,A){if(Number.isNaN(A))throw new Error("JsonCodec allow_nan is false but NaN was encountered during encoding.");if(A===Number.POSITIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but Infinity was encountered during encoding.");if(A===Number.NEGATIVE_INFINITY)throw new Error("JsonCodec allow_nan is false but -Infinity was encountered during encoding.");return A}function HD(g,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,B)=>(I[B]=A[B],I),{}):A}class DQ{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:h=!0}=A;let s=A.separators;s||(o?s=[", ",": "]:s=[",",":"]),this.#A={encoding:I,skipkeys:B,ensure_ascii:Q,check_circular:C,allow_nan:E,indent:o,separators:s,sort_keys:i},this.#I={strict:h}}static fromConfig(A){return new DQ(A)}encode(A){const{indent:I,encoding:B,ensure_ascii:Q,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;if(B!=="utf-8")throw new Error("JsonCodec does not yet support non-utf-8 encoding.");const o=[];if(!C)throw new Error("JsonCodec does not yet support skipping the check for circular references during encoding.");E||o.push(MD),i&&o.push(HD);const h=Array.from(A.data);h.push("|O"),h.push(A.shape);let s;o.length&&(s=(N,r)=>{let M=r;for(let e of o)M=e(N,M);return M});let R=JSON.stringify(h,s,I);return Q&&(R=R.replace(/[\u007F-\uFFFF]/g,N=>{const r=`0000${N.charCodeAt(0).toString(16)}`;return`\\u${r.substring(r.length-4)}`})),new TextEncoder().encode(R)}decode(A){const{strict:I}=this.#I;if(!I)throw new Error("JsonCodec does not yet support non-strict decoding.");const B=Kg(A),Q=B.pop();if(B.pop(),!Q)throw new Error("0D not implemented for JsonCodec.");const C=pI(Q,"C");return{data:B,shape:Q,stride:C}}}function rC(g){return g instanceof UC||g instanceof CQ||g instanceof ng?new Proxy(g,{get(I,B){return I.get(Number(B))},set(I,B,Q){return I.set(Number(B),Q),!0}}):g}function eD(g,A){let I;return g.data instanceof CQ||g.data instanceof ng?I=new g.constructor(g.data.length,g.data.chars):I=new g.constructor(g.data.length),{data:I,shape:g.shape,stride:pI(g.shape,A)}}function qD(g,A){let I=eD(g,A),B=g.shape.length,Q=g.data.length,C=Array(B).fill(0),E=rC(g.data),i=rC(I.data);for(let o=0;o<Q;o++){let h=0;for(let s=0;s<B;s++)h+=C[s]*I.stride[s];i[h]=E[o],C[0]+=1;for(let s=0;s<B;s++)if(C[s]===g.shape[s]){if(s+1===B)break;C[s]=0,C[s+1]+=1}}return I}function dD(g){if(!g.stride)return"C";let A=pI(g.shape,"C");return g.stride.every((I,B)=>I===A[B])?"C":"F"}class oQ{configuration;kind="array_to_array";constructor(A){this.configuration=A}static fromConfig(A){return new oQ(A)}encode(A){return dD(A)===this.configuration?.order?A:qD(A,this.configuration?.order??"C")}decode(A){return A}}class aQ{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=pI(A,"C")}static fromConfig(A,I){return new aQ(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}}}function fD(){return new Map().set("blosc",()=>Promise.resolve().then(()=>ss).then(g=>g.default)).set("gzip",()=>Promise.resolve().then(()=>ls).then(g=>g.default)).set("lz4",()=>Promise.resolve().then(()=>Zs).then(g=>g.default)).set("zlib",()=>Promise.resolve().then(()=>Ps).then(g=>g.default)).set("zstd",()=>Promise.resolve().then(()=>zs).then(g=>g.default)).set("transpose",()=>oQ).set("bytes",()=>FB).set("crc32c",()=>iQ).set("vlen-utf8",()=>aQ).set("json2",()=>DQ).set("bitround",()=>QQ)}const lD=fD();function sQ(g){let A;return{async encode(I){A||(A=await YC(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 YC(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 YC(g){let A=g.codecs.map(async C=>{let E=await lD.get(C.name)?.();if(!E)throw new Error(`Unknown codec: ${C.name}`);return{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)}}if(!B){if(!pD(g))throw new Error(`Cannot encode ${g.data_type} to bytes without a codec`);B=FB.fromConfig({endian:"little"},g)}return{array_to_array:I,array_to_bytes:B,bytes_to_bytes:Q}}function pD(g){return g.data_type!=="v2:object"}const nC=18446744073709551615n;function WD(g,A,I,B){if(g.store.getRange===void 0)throw new Error("Store does not support range requests");let Q=g.store.getRange.bind(g.store),C=A.map((o,h)=>o/B.chunk_shape[h]),E=sQ({data_type:"uint64",shape:[...C,2],codecs:B.index_codecs}),i={};return async o=>{let h=o.map((O,W)=>Math.floor(O/C[W])),s=g.resolve(I(h)).path,R;if(s in i)R=i[s];else{let O=4,W=16*C.reduce((b,T)=>b*T,1),u=await Q(s,{suffixLength:W+O});R=i[s]=u?await E.decode(u):null}if(R===null)return;let{data:N,shape:r,stride:M}=R,e=o.map((O,W)=>O%r[W]).reduce((O,W,u)=>O+W*M[u],0),n=N[e],f=N[e+1];if(!(n===nC&&f===nC))return Q(s,{offset:Number(n),length:Number(f)})}}class II{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 II(this.store,new URL(A,I).pathname)}}class yQ extends II{kind="group";#A;constructor(A,I,B){super(A,I),this.#A=B}get attrs(){return this.#A.attributes}}const Mg=Symbol("zarrita.context");function mD(g){return g[Mg]}function TD(g,A){let{configuration:I}=A.codecs.find(nD)??{},B={encode_chunk_key:tD(A.chunk_key_encoding),TypedArray:tC(A.data_type),fill_value:A.fill_value};if(I){let C=EQ(I.codecs);return{...B,kind:"sharded",chunk_shape:I.chunk_shape,codec:sQ({data_type:A.data_type,shape:I.chunk_shape,codecs:I.codecs}),get_strides(E,i){return pI(E,i??C)},get_chunk_bytes:WD(g,A.chunk_grid.configuration.chunk_shape,B.encode_chunk_key,I)}}let Q=EQ(A.codecs);return{...B,kind:"regular",chunk_shape:A.chunk_grid.configuration.chunk_shape,codec:sQ({data_type:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs}),get_strides(C,E){return pI(C,E??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 wB=class extends II{kind="array";#A;[Mg];constructor(A,I,B){super(A,I),this.#A={...B,fill_value:cC(B)},this[Mg]=TD(this,B)}get attrs(){return this.#A.attributes}get shape(){return this.#A.shape}get chunks(){return this[Mg].chunk_shape}get dtype(){return this.#A.data_type}async getChunk(A,I){let B=this[Mg],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 YD(this.dtype,A)}},SB=xD();function xD(){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 ZD(g){let A=await g.store.get(g.resolve(".zattrs").path);return A?Kg(A):{}}async function bD(g,A={}){let I="store"in g?g:new II(g),B={};return(A.attrs??!0)&&(B=await ZD(I)),A.kind==="array"?KC(I,B):A.kind==="group"?MC(I,B):KC(I,B).catch(Q=>{if(Q instanceof Yg)return MC(I,B);throw Q})}async function KC(g,A){let{path:I}=g.resolve(".zarray"),B=await g.store.get(I);if(!B)throw new Yg("v2 array",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new wB(g.store,g.path,JD(Kg(B),A))}async function MC(g,A){let{path:I}=g.resolve(".zgroup"),B=await g.store.get(I);if(!B)throw new Yg("v2 group",{cause:new BQ(I)});return SB.increment(g.store,"v2"),new yQ(g.store,g.path,rD(Kg(B),A))}async function uD(g){let{store:A,path:I}=g.resolve("zarr.json"),B=await g.store.get(I);if(!B)throw new Yg("v3 array or group",{cause:new BQ(I)});let Q=Kg(B);return Q.node_type==="array"&&(Q.fill_value=cC(Q)),Q.node_type==="array"?new wB(A,g.path,Q):new yQ(A,g.path,Q)}async function PD(g,A={}){let I="store"in g?g:new II(g),B=await uD(I);if(SB.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&B instanceof wB||A.kind==="group"&&B instanceof yQ)return B;let Q=B instanceof wB?"array":"group";throw new Error(`Expected node of kind ${A.kind}, found ${Q}.`)}async function gI(g,A={}){let I="store"in g?g.store:g,B=SB.version_max(I),Q=B==="v2"?gI.v2:gI.v3,C=B==="v2"?gI.v3:gI.v2;return Q(g,A).catch(E=>{if(E instanceof Yg)return C(g,A);throw E})}gI.v2=bD,gI.v3=PD;function HC(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 OD(g,A){return{...g,...A,headers:{...g.headers,...A.headers}}}function eC(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 qC(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 VD(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 HC(g,E-A,E,I)}class Hg{url;#A;#I;constructor(A,I={}){this.url=A,this.#A=I.overrides??{},this.#I=I.useSuffixRequest??!1}#g(A){return OD(this.#A,A)}async get(A,I={}){let B=eC(this.url,A).href,Q=await fetch(B,this.#g(I));return qC(Q)}async getRange(A,I,B={}){let Q=eC(this.url,A),C=this.#g(B),E;return"suffixLength"in I?E=await VD(Q,I.suffixLength,C,this.#I):E=await HC(Q,I.offset,I.length,C),qC(E)}}function*XD(g,A,I=1){A===void 0&&(A=g,g=0);for(let B=g;B<A;B+=I)yield B}function*vD(...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 jD({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 RB(g,A,I=null){return A===void 0&&(A=g,g=null),{start:g,stop:A,step:I}}function zD(){const g=[];return{add:A=>g.push(A()),onIdle:()=>Promise.all(g)}}class hQ extends Error{constructor(A){super(A),this.name="IndexError"}}function _D(g,A){throw new hQ(`too many indicies for array; expected ${A.length}, got ${g.length}`)}function $D(g){throw new hQ(`index out of bounds for dimension with length ${g}`)}function Ao(){throw new hQ("only slices with step >= 1 are supported")}function Io(g,A){g.length>A.length&&_D(g,A)}function go(g,A){return g=Math.trunc(g),g<0&&(g=A+g),(g>=A||g<0)&&$D(A),g}class Bo{dim_sel;dim_len;dim_chunk_len;nitems;constructor({dim_sel:A,dim_len:I,dim_chunk_len:B}){A=go(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 dC{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]=jD(A,I);this.start=Q,this.stop=C,this.step=E,this.step<1&&Ao(),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 XD(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 h=this.stop>C?E:this.stop-Q,s=[o,h,this.step],R=Math.ceil((h-o)/this.step),N=[i,i+R,1];yield{dim_chunk_ix:B,dim_chunk_sel:s,dim_out_sel:N}}}}function Qo(g,A){let I=[];return g===null?I=A.map(B=>RB(null)):Array.isArray(g)&&(I=g.map(B=>B??RB(null))),Io(I,A),I}class Co{dim_indexers;shape;constructor({selection:A,shape:I,chunk_shape:B}){this.dim_indexers=Qo(A,I).map((Q,C)=>new(typeof Q=="number"?Bo:dC)({dim_sel:Q,dim_len:I[C],dim_chunk_len:B[C]})),this.shape=this.dim_indexers.filter(Q=>Q instanceof dC).map(Q=>Q.nitems)}*[Symbol.iterator](){for(const A of vD(...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 Eo(g,A){return"get"in g?g.get(A):g[A]}async function io(g,A,I,B){let Q=mD(g),C=new Co({selection:A,shape:g.shape,chunk_shape:g.chunks}),E=B.prepare(new Q.TypedArray(C.shape.reduce((o,h)=>o*h,1)),C.shape,Q.get_strides(C.shape,I.order)),i=I.create_queue?.()??zD();for(const{chunk_coords:o,mapping:h}of C)i.add(async()=>{let{data:s,shape:R,stride:N}=await g.getChunk(o,I.opts),r=B.prepare(s,R,N);B.set_from_chunk(E,r,h)});return await i.onIdle(),C.shape.length===0?Eo(E.data,0):E}function GQ(g,A=0,I){let B=I??g.length-A;return{length:B,subarray(Q,C=B){return GQ(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 FQ(g){return globalThis.Array.isArray(g.data)?{data:GQ(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 Do(g){return"chars"in g?g.constructor.bind(null,g.chars):g.constructor}function oo(g,A){if(globalThis.Array.isArray(g.data))return GQ([A]);let I=Do(g.data),B=new I([A]);return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}const ao={prepare(g,A,I){return{data:g,shape:A,stride:I}},set_scalar(g,A,I){let B=FQ(g);wQ(B,A,oo(g,I),B.bytes_per_element)},set_from_chunk(g,A,I){let B=FQ(g);NB(B,FQ(A),B.bytes_per_element,I)}};async function so(g,A=null,I={}){return io(g,A,I,ao)}function fC(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 wQ(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 N=g.data.subarray(E*Q*B);wQ({data:N,stride:i},C,I,B);return}const[o,h,s]=Q,R=fC(o,h,s);if(C.length===0){for(let N=0;N<R;N++)g.data.set(I,E*(o+s*N)*B);return}for(let N=0;N<R;N++){const r=g.data.subarray(E*(o+s*N)*B);wQ({data:r,stride:i},C,I,B)}}function NB(g,A,I,B){const[Q,...C]=B,[E,...i]=g.stride,[o,...h]=A.stride;if(Q.from===null){if(C.length===0){g.data.set(A.data.subarray(0,I),Q.to*I);return}NB({data:g.data.subarray(E*Q.to*I),stride:i},A,I,C);return}if(Q.to===null){if(C.length===0){let f=Q.from*I;g.data.set(A.data.subarray(f,f+I),0);return}NB(g,{data:A.data.subarray(o*Q.from*I),stride:h},I,C);return}const[s,R,N]=Q.to,[r,M,e]=Q.from,n=fC(s,R,N);if(C.length===0){if(N===1&&e===1&&E===1&&o===1){let f=r*I,O=n*I;g.data.set(A.data.subarray(f,f+O),s*I);return}for(let f=0;f<n;f++){let O=o*(r+e*f)*I;g.data.set(A.data.subarray(O,O+I),E*(s+N*f)*I)}return}for(let f=0;f<n;f++)NB({data:g.data.subarray(E*(s+f*N)*I),stride:i},{data:A.data.subarray(o*(r+f*e)*I),stride:h},I,C)}async function yo(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 SQ{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await yo(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const Q=await(await I.getFile()).arrayBuffer();return new Uint8Array(Q)}}async function eg(g,A){if(A==="v2")try{return gI.v2(g,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${g}`)}try{return gI(g,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${g}`)}}async function ho(g,A){if(A==="v2")try{return gI.v2(g,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${g}`)}if(A==="v3")try{return gI.v3(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${g}`)}try{return gI(g,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${g}`)}}async function Go(g){let A;switch(g.type){case"fetch":{A=new II(new Hg(g.url,g.fetchOptions));break}case"filesystem":{A=new II(new SQ(g.directoryHandle),g.path);break}default:{const B=g;throw new Error(`Unsupported store type: ${B}`)}}const I=g.arrayPath?A.resolve(g.arrayPath):A;return ho(I,g.zarrVersion)}function Fo(g,A,I){if(g.store instanceof Hg)return{type:"fetch",arrayPath:A,zarrVersion:I,url:g.store.url.toString()};if(g.store instanceof SQ)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:g.store.directoryHandle,path:g.path};throw new Error(`Unsupported store type: ${g.store.constructor.name}`)}const lC=`class HI extends Error {
|
|
347
348
|
constructor(A, I = {}) {
|
|
348
349
|
super(\`Node not found: \${A}\`, I), this.name = "NodeNotFoundError";
|
|
349
350
|
}
|