@idetik/core 0.27.2 → 0.27.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +11 -11
- package/dist/index.js +297 -297
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +137 -137
- package/dist/index.umd.cjs.map +1 -1
- package/dist/types/src/layers/volume_layer.d.ts.map +1 -1
- package/dist/types/src/objects/renderable/image_renderable.d.ts +5 -5
- package/dist/types/src/objects/renderable/image_renderable.d.ts.map +1 -1
- package/dist/types/src/objects/renderable/label_image_renderable.d.ts +4 -4
- package/dist/types/src/objects/renderable/projected_line.d.ts +2 -2
- package/package.json +1 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
(function(RA,FA){typeof exports=="object"&&typeof module<"u"?FA(exports):typeof define=="function"&&define.amd?define(["exports"],FA):(RA=typeof globalThis<"u"?globalThis:RA||self,FA(RA["idetik-core"]={}))})(this,(function(RA){"use strict";class FA{static RED=new FA(1,0,0);static GREEN=new FA(0,1,0);static BLUE=new FA(0,0,1);static YELLOW=new FA(1,1,0);static MAGENTA=new FA(1,0,1);static CYAN=new FA(0,1,1);static BLACK=new FA(0,0,0);static WHITE=new FA(1,1,1);static TRANSPARENT=new FA(0,0,0,0);rgba_;constructor(A,I,g,B){if(A<0||A>1||I<0||I>1||g<0||g>1)throw new Error("RGB values must be in the range [0, 1]");if(B!==void 0&&(B<0||B>1))throw new Error("Alpha value must be in the range [0, 1]");this.rgba_=[A,I,g,B??1]}get rgb(){return[this.rgba_[0],this.rgba_[1],this.rgba_[2]]}get rgba(){return this.rgba_}get r(){return this.rgba_[0]}get g(){return this.rgba_[1]}get b(){return this.rgba_[2]}get a(){return this.rgba_[3]}get rgbHex(){return`#${this.toHexComponent(this.r)}${this.toHexComponent(this.g)}${this.toHexComponent(this.b)}`}get packed(){return Math.round(this.r*255)<<24|Math.round(this.g*255)<<16|Math.round(this.b*255)<<8|Math.round(this.a*255)}static from(A){if(A instanceof FA)return A;if(Array.isArray(A))return new FA(A[0],A[1],A[2],A[3]);if(typeof A=="string")return FA.fromRgbHex(A);throw new Error("Unsupported color format")}static fromRgbHex(A){const I=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(A);if(!I)throw new Error("Invalid RGB hex, use form '#RRGGBB'");return new FA(parseInt(I[1],16)/255,parseInt(I[2],16)/255,parseInt(I[3],16)/255,1)}toHexComponent(A){const I=Math.round(A*255).toString(16).padStart(2,"0");return I.length===1?"0"+I:I}}class OC{canvas_;width_=0;height_=0;backgroundColor_=new FA(0,0,0,0);renderedObjects_=0;constructor(A){this.canvas_=A,this.updateRendererSize()}beginFrame(){}updateSize(){this.updateRendererSize(),this.resize(this.width_,this.height_)}updateRendererSize(){this.width_=this.canvas.clientWidth*window.devicePixelRatio,this.height_=this.canvas.clientHeight*window.devicePixelRatio,this.canvas.width!==this.width_&&(this.canvas.width=this.width_),this.canvas.height!==this.height_&&(this.canvas.height=this.height_)}get canvas(){return this.canvas_}get width(){return this.width_}get height(){return this.height_}get backgroundColor(){return this.backgroundColor_}get renderedObjects(){return this.renderedObjects_}set backgroundColor(A){this.backgroundColor_=FA.from(A)}}var Fo=`#version 300 es
|
|
2
2
|
|
|
3
|
-
layout (location = 0) in vec3
|
|
4
|
-
layout (location = 3) in vec3
|
|
5
|
-
layout (location = 4) in vec3
|
|
6
|
-
layout (location = 5) in float
|
|
3
|
+
layout (location = 0) in vec3 a_position;
|
|
4
|
+
layout (location = 3) in vec3 a_prevPosition;
|
|
5
|
+
layout (location = 4) in vec3 a_nextPosition;
|
|
6
|
+
layout (location = 5) in float a_direction;
|
|
7
7
|
|
|
8
|
-
uniform mat4
|
|
9
|
-
uniform mat4
|
|
10
|
-
uniform vec2
|
|
11
|
-
uniform float
|
|
8
|
+
uniform mat4 u_projection;
|
|
9
|
+
uniform mat4 u_modelView;
|
|
10
|
+
uniform vec2 u_resolution;
|
|
11
|
+
uniform float u_lineWidth;
|
|
12
12
|
|
|
13
13
|
void main() {
|
|
14
|
-
mat4 projModelView =
|
|
14
|
+
mat4 projModelView = u_projection * u_modelView;
|
|
15
15
|
|
|
16
|
-
vec4 prevPos = projModelView * vec4(
|
|
17
|
-
vec4 currPos = projModelView * vec4(
|
|
18
|
-
vec4 nextPos = projModelView * vec4(
|
|
16
|
+
vec4 prevPos = projModelView * vec4(a_prevPosition, 1.0);
|
|
17
|
+
vec4 currPos = projModelView * vec4(a_position, 1.0);
|
|
18
|
+
vec4 nextPos = projModelView * vec4(a_nextPosition, 1.0);
|
|
19
19
|
|
|
20
|
-
vec2 aspectVec = vec2(
|
|
20
|
+
vec2 aspectVec = vec2(u_resolution.x / u_resolution.y, 1.0);
|
|
21
21
|
vec2 prevScreen = (prevPos.xy / prevPos.w) * aspectVec;
|
|
22
22
|
vec2 currScreen = (currPos.xy / currPos.w) * aspectVec;
|
|
23
23
|
vec2 nextScreen = (nextPos.xy / nextPos.w) * aspectVec;
|
|
24
24
|
|
|
25
25
|
|
|
26
|
-
float d = sign(
|
|
26
|
+
float d = sign(a_direction);
|
|
27
27
|
|
|
28
28
|
|
|
29
29
|
vec2 normal;
|
|
@@ -50,7 +50,7 @@ void main() {
|
|
|
50
50
|
|
|
51
51
|
|
|
52
52
|
vec4 offset = vec4(
|
|
53
|
-
(normal *
|
|
53
|
+
(normal * u_lineWidth / u_resolution) * miterLength * d,
|
|
54
54
|
0.0,
|
|
55
55
|
0.0
|
|
56
56
|
);
|
|
@@ -64,25 +64,25 @@ precision mediump float;
|
|
|
64
64
|
|
|
65
65
|
layout (location = 0) out vec4 fragColor;
|
|
66
66
|
|
|
67
|
-
uniform vec3
|
|
67
|
+
uniform vec3 u_lineColor;
|
|
68
68
|
uniform float u_opacity;
|
|
69
69
|
|
|
70
70
|
void main() {
|
|
71
|
-
fragColor = vec4(
|
|
71
|
+
fragColor = vec4(u_lineColor, u_opacity);
|
|
72
72
|
}`,KB=`#version 300 es
|
|
73
73
|
|
|
74
|
-
layout (location = 0) in vec3
|
|
75
|
-
layout (location = 1) in vec3
|
|
76
|
-
layout (location = 2) in vec2
|
|
74
|
+
layout (location = 0) in vec3 a_position;
|
|
75
|
+
layout (location = 1) in vec3 a_normal;
|
|
76
|
+
layout (location = 2) in vec2 a_uv;
|
|
77
77
|
|
|
78
|
-
uniform mat4
|
|
79
|
-
uniform mat4
|
|
78
|
+
uniform mat4 u_projection;
|
|
79
|
+
uniform mat4 u_modelView;
|
|
80
80
|
|
|
81
|
-
out vec2
|
|
81
|
+
out vec2 v_texCoords;
|
|
82
82
|
|
|
83
83
|
void main() {
|
|
84
|
-
|
|
85
|
-
gl_Position =
|
|
84
|
+
v_texCoords = a_uv;
|
|
85
|
+
gl_Position = u_projection * u_modelView * vec4(a_position, 1.0);
|
|
86
86
|
}`,yQ=`#version 300 es
|
|
87
87
|
#pragma inject_defines
|
|
88
88
|
|
|
@@ -91,75 +91,75 @@ precision mediump float;
|
|
|
91
91
|
layout (location = 0) out vec4 fragColor;
|
|
92
92
|
|
|
93
93
|
#if defined TEXTURE_DATA_TYPE_INT
|
|
94
|
-
uniform mediump isampler3D
|
|
94
|
+
uniform mediump isampler3D u_imageSampler;
|
|
95
95
|
#elif defined TEXTURE_DATA_TYPE_UINT
|
|
96
|
-
uniform mediump usampler3D
|
|
96
|
+
uniform mediump usampler3D u_imageSampler;
|
|
97
97
|
#else
|
|
98
|
-
uniform mediump sampler3D
|
|
98
|
+
uniform mediump sampler3D u_imageSampler;
|
|
99
99
|
#endif
|
|
100
100
|
|
|
101
|
-
uniform vec3
|
|
102
|
-
uniform float
|
|
103
|
-
uniform float
|
|
101
|
+
uniform vec3 u_color;
|
|
102
|
+
uniform float u_valueOffset;
|
|
103
|
+
uniform float u_valueScale;
|
|
104
104
|
uniform float u_opacity;
|
|
105
|
-
uniform float
|
|
105
|
+
uniform float u_zTexCoord;
|
|
106
106
|
|
|
107
|
-
in vec2
|
|
107
|
+
in vec2 v_texCoords;
|
|
108
108
|
|
|
109
109
|
void main() {
|
|
110
|
-
float texel = float(texture(
|
|
111
|
-
float value = (texel +
|
|
112
|
-
fragColor = vec4(value *
|
|
110
|
+
float texel = float(texture(u_imageSampler, vec3(v_texCoords, u_zTexCoord)).r);
|
|
111
|
+
float value = (texel + u_valueOffset) * u_valueScale;
|
|
112
|
+
fragColor = vec4(value * u_color, u_opacity);
|
|
113
113
|
}`,ro=`#version 300 es
|
|
114
114
|
|
|
115
115
|
precision mediump float;
|
|
116
116
|
|
|
117
|
-
layout (location = 0) in vec3
|
|
118
|
-
layout (location = 6) in vec4
|
|
119
|
-
layout (location = 7) in float
|
|
120
|
-
layout (location = 8) in float
|
|
117
|
+
layout (location = 0) in vec3 a_position;
|
|
118
|
+
layout (location = 6) in vec4 a_color;
|
|
119
|
+
layout (location = 7) in float a_size;
|
|
120
|
+
layout (location = 8) in float a_marker;
|
|
121
121
|
|
|
122
|
-
uniform mat4
|
|
123
|
-
uniform mat4
|
|
122
|
+
uniform mat4 u_projection;
|
|
123
|
+
uniform mat4 u_modelView;
|
|
124
124
|
|
|
125
|
-
out vec4
|
|
126
|
-
flat out uint
|
|
125
|
+
out vec4 v_color;
|
|
126
|
+
flat out uint v_marker;
|
|
127
127
|
|
|
128
128
|
void main() {
|
|
129
|
-
gl_Position =
|
|
130
|
-
gl_PointSize =
|
|
131
|
-
|
|
132
|
-
|
|
129
|
+
gl_Position = u_projection * u_modelView * vec4(a_position, 1.0);
|
|
130
|
+
gl_PointSize = a_size;
|
|
131
|
+
v_color = a_color;
|
|
132
|
+
v_marker = uint(a_marker);
|
|
133
133
|
}`,no=`#version 300 es
|
|
134
134
|
|
|
135
135
|
precision mediump float;
|
|
136
136
|
|
|
137
137
|
layout (location = 0) out vec4 fragColor;
|
|
138
138
|
|
|
139
|
-
uniform mediump sampler2DArray
|
|
139
|
+
uniform mediump sampler2DArray u_markerAtlas;
|
|
140
140
|
|
|
141
|
-
in vec4
|
|
142
|
-
flat in uint
|
|
141
|
+
in vec4 v_color;
|
|
142
|
+
flat in uint v_marker;
|
|
143
143
|
|
|
144
144
|
uniform float u_opacity;
|
|
145
145
|
|
|
146
146
|
void main() {
|
|
147
|
-
float alpha = texture(
|
|
147
|
+
float alpha = texture(u_markerAtlas, vec3(gl_PointCoord, v_marker)).r;
|
|
148
148
|
float alpha_threshold = 1e-2;
|
|
149
149
|
if (alpha < alpha_threshold) {
|
|
150
150
|
discard;
|
|
151
151
|
}
|
|
152
|
-
fragColor = vec4(
|
|
152
|
+
fragColor = vec4(v_color.rgb, u_opacity * alpha * v_color.a);
|
|
153
153
|
}`,So=`#version 300 es
|
|
154
154
|
|
|
155
|
-
layout (location = 0) in vec3
|
|
156
|
-
layout (location = 1) in vec3
|
|
155
|
+
layout (location = 0) in vec3 a_position;
|
|
156
|
+
layout (location = 1) in vec3 a_normal;
|
|
157
157
|
|
|
158
|
-
uniform mat4
|
|
159
|
-
uniform mat4
|
|
158
|
+
uniform mat4 u_projection;
|
|
159
|
+
uniform mat4 u_modelView;
|
|
160
160
|
|
|
161
161
|
void main() {
|
|
162
|
-
gl_Position =
|
|
162
|
+
gl_Position = u_projection * u_modelView * vec4(a_position, 1.0);
|
|
163
163
|
}`,No=`#version 300 es
|
|
164
164
|
|
|
165
165
|
precision mediump float;
|
|
@@ -175,15 +175,15 @@ void main() {
|
|
|
175
175
|
|
|
176
176
|
precision highp float;
|
|
177
177
|
|
|
178
|
-
layout (location = 0) in vec3
|
|
178
|
+
layout (location = 0) in vec3 a_position;
|
|
179
179
|
|
|
180
|
-
uniform mat4
|
|
181
|
-
uniform mat4
|
|
182
|
-
out highp vec3
|
|
180
|
+
uniform mat4 u_projection;
|
|
181
|
+
uniform mat4 u_modelView;
|
|
182
|
+
out highp vec3 v_positionModel;
|
|
183
183
|
|
|
184
184
|
void main() {
|
|
185
|
-
|
|
186
|
-
gl_Position =
|
|
185
|
+
v_positionModel = a_position;
|
|
186
|
+
gl_Position = u_projection * u_modelView * vec4(a_position, 1.0);
|
|
187
187
|
}`,GQ=`#version 300 es
|
|
188
188
|
#pragma inject_defines
|
|
189
189
|
precision highp float;
|
|
@@ -192,41 +192,41 @@ layout (location = 0) out vec4 fragColor;
|
|
|
192
192
|
|
|
193
193
|
#if defined TEXTURE_DATA_TYPE_INT
|
|
194
194
|
precision mediump isampler3D;
|
|
195
|
-
uniform isampler3D
|
|
196
|
-
uniform isampler3D
|
|
197
|
-
uniform isampler3D
|
|
198
|
-
uniform isampler3D
|
|
195
|
+
uniform isampler3D u_channel0Sampler;
|
|
196
|
+
uniform isampler3D u_channel1Sampler;
|
|
197
|
+
uniform isampler3D u_channel2Sampler;
|
|
198
|
+
uniform isampler3D u_channel3Sampler;
|
|
199
199
|
#elif defined TEXTURE_DATA_TYPE_UINT
|
|
200
200
|
precision mediump usampler3D;
|
|
201
|
-
uniform usampler3D
|
|
202
|
-
uniform usampler3D
|
|
203
|
-
uniform usampler3D
|
|
204
|
-
uniform usampler3D
|
|
201
|
+
uniform usampler3D u_channel0Sampler;
|
|
202
|
+
uniform usampler3D u_channel1Sampler;
|
|
203
|
+
uniform usampler3D u_channel2Sampler;
|
|
204
|
+
uniform usampler3D u_channel3Sampler;
|
|
205
205
|
#else
|
|
206
206
|
precision mediump sampler3D;
|
|
207
|
-
uniform sampler3D
|
|
208
|
-
uniform sampler3D
|
|
209
|
-
uniform sampler3D
|
|
210
|
-
uniform sampler3D
|
|
207
|
+
uniform sampler3D u_channel0Sampler;
|
|
208
|
+
uniform sampler3D u_channel1Sampler;
|
|
209
|
+
uniform sampler3D u_channel2Sampler;
|
|
210
|
+
uniform sampler3D u_channel3Sampler;
|
|
211
211
|
#endif
|
|
212
212
|
|
|
213
|
-
uniform highp vec3
|
|
214
|
-
uniform vec3
|
|
215
|
-
in highp vec3
|
|
213
|
+
uniform highp vec3 u_cameraPositionModel;
|
|
214
|
+
uniform vec3 u_voxelScale;
|
|
215
|
+
in highp vec3 v_positionModel;
|
|
216
216
|
|
|
217
217
|
vec3 boundingboxMin = vec3(-0.50);
|
|
218
218
|
vec3 boundingboxMax = vec3(0.50);
|
|
219
219
|
|
|
220
|
-
uniform bool
|
|
221
|
-
uniform float
|
|
222
|
-
uniform float
|
|
223
|
-
uniform float
|
|
220
|
+
uniform bool u_debugShowDegenerateRays;
|
|
221
|
+
uniform float u_relativeStepSize;
|
|
222
|
+
uniform float u_opacityMultiplier;
|
|
223
|
+
uniform float u_earlyTerminationAlpha;
|
|
224
224
|
|
|
225
|
-
uniform vec4
|
|
226
|
-
uniform vec4
|
|
227
|
-
uniform vec4
|
|
228
|
-
uniform vec4
|
|
229
|
-
uniform vec3
|
|
225
|
+
uniform vec4 u_visible;
|
|
226
|
+
uniform vec4 u_valueOffset;
|
|
227
|
+
uniform vec4 u_valueScale;
|
|
228
|
+
uniform vec4 u_channelOpacity;
|
|
229
|
+
uniform vec3 u_color[4];
|
|
230
230
|
|
|
231
231
|
vec2 findBoxIntersectionsAlongRay(vec3 rayOrigin, vec3 rayDir, vec3 boxMin, vec3 boxMax) {
|
|
232
232
|
vec3 reciprocalRayDir = 1.0 / rayDir;
|
|
@@ -247,19 +247,19 @@ vec2 findBoxIntersectionsAlongRay(vec3 rayOrigin, vec3 rayDir, vec3 boxMin, vec3
|
|
|
247
247
|
vec4 sampleChannels(vec3 uvw) {
|
|
248
248
|
vec4 c = vec4(0.0);
|
|
249
249
|
|
|
250
|
-
if (bool(
|
|
251
|
-
if (bool(
|
|
252
|
-
if (bool(
|
|
253
|
-
if (bool(
|
|
250
|
+
if (bool(u_visible.x)) c.x = float(texture(u_channel0Sampler, uvw).r);
|
|
251
|
+
if (bool(u_visible.y)) c.y = float(texture(u_channel1Sampler, uvw).r);
|
|
252
|
+
if (bool(u_visible.z)) c.z = float(texture(u_channel2Sampler, uvw).r);
|
|
253
|
+
if (bool(u_visible.w)) c.w = float(texture(u_channel3Sampler, uvw).r);
|
|
254
254
|
|
|
255
|
-
return (c +
|
|
255
|
+
return (c + u_valueOffset) * u_valueScale;
|
|
256
256
|
}
|
|
257
257
|
|
|
258
258
|
vec3 getTextureSize() {
|
|
259
|
-
if (bool(
|
|
260
|
-
else if (bool(
|
|
261
|
-
else if (bool(
|
|
262
|
-
else if (bool(
|
|
259
|
+
if (bool(u_visible.x)) return vec3(textureSize(u_channel0Sampler, 0));
|
|
260
|
+
else if (bool(u_visible.y)) return vec3(textureSize(u_channel1Sampler, 0));
|
|
261
|
+
else if (bool(u_visible.z)) return vec3(textureSize(u_channel2Sampler, 0));
|
|
262
|
+
else if (bool(u_visible.w)) return vec3(textureSize(u_channel3Sampler, 0));
|
|
263
263
|
return vec3(1.0);
|
|
264
264
|
}
|
|
265
265
|
|
|
@@ -267,20 +267,20 @@ void main() {
|
|
|
267
267
|
|
|
268
268
|
|
|
269
269
|
|
|
270
|
-
vec3 RayDirModel = normalize(
|
|
270
|
+
vec3 RayDirModel = normalize(v_positionModel - u_cameraPositionModel);
|
|
271
271
|
|
|
272
|
-
vec2 rayIntersections = findBoxIntersectionsAlongRay(
|
|
272
|
+
vec2 rayIntersections = findBoxIntersectionsAlongRay(u_cameraPositionModel, RayDirModel, boundingboxMin, boundingboxMax);
|
|
273
273
|
float tEnter = rayIntersections.x;
|
|
274
274
|
float tExit = rayIntersections.y;
|
|
275
275
|
|
|
276
|
-
if (
|
|
276
|
+
if (u_debugShowDegenerateRays && (tExit == tEnter)) {
|
|
277
277
|
fragColor = vec4(1.0, 0.0, 0.0, 1.0);
|
|
278
278
|
return;
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
-
vec3 entryPoint =
|
|
281
|
+
vec3 entryPoint = u_cameraPositionModel + RayDirModel * tEnter;
|
|
282
282
|
entryPoint = clamp(entryPoint + 0.5, 0.0, 1.0);
|
|
283
|
-
vec3 exitPoint =
|
|
283
|
+
vec3 exitPoint = u_cameraPositionModel + RayDirModel * tExit;
|
|
284
284
|
exitPoint = clamp(exitPoint + 0.5, 0.0, 1.0);
|
|
285
285
|
|
|
286
286
|
|
|
@@ -290,16 +290,16 @@ void main() {
|
|
|
290
290
|
vec3 textureSize = getTextureSize();
|
|
291
291
|
vec3 rayInVoxels = rayWithinModel * textureSize;
|
|
292
292
|
float rayLengthInVoxels = length(rayInVoxels);
|
|
293
|
-
int numSamples = max(int(ceil(rayLengthInVoxels /
|
|
293
|
+
int numSamples = max(int(ceil(rayLengthInVoxels / u_relativeStepSize)), 1);
|
|
294
294
|
vec3 stepIncrement = rayWithinModel / float(numSamples);
|
|
295
295
|
|
|
296
296
|
|
|
297
297
|
|
|
298
298
|
|
|
299
299
|
|
|
300
|
-
vec3 stepInWorldSpace = stepIncrement * textureSize *
|
|
300
|
+
vec3 stepInWorldSpace = stepIncrement * textureSize * u_voxelScale;
|
|
301
301
|
float worldSpaceStepSize = length(stepInWorldSpace);
|
|
302
|
-
float intensityScale =
|
|
302
|
+
float intensityScale = u_opacityMultiplier * worldSpaceStepSize;
|
|
303
303
|
|
|
304
304
|
|
|
305
305
|
vec3 position = entryPoint;
|
|
@@ -307,14 +307,14 @@ void main() {
|
|
|
307
307
|
|
|
308
308
|
vec3 sampleColor = vec3(0.0);
|
|
309
309
|
float sampleAlpha, blendedSampleAlpha;
|
|
310
|
-
for (int i = 0; i < numSamples && accumulatedColor.a <
|
|
310
|
+
for (int i = 0; i < numSamples && accumulatedColor.a < u_earlyTerminationAlpha; i++) {
|
|
311
311
|
|
|
312
312
|
vec4 sampleValues = sampleChannels(position);
|
|
313
313
|
|
|
314
314
|
for (int ch = 0; ch < 4; ch++) {
|
|
315
|
-
if (!bool(
|
|
316
|
-
sampleColor =
|
|
317
|
-
sampleAlpha = clamp(sampleValues[ch] * intensityScale *
|
|
315
|
+
if (!bool(u_visible[ch]) || sampleValues[ch] == 0.0) continue;
|
|
316
|
+
sampleColor = u_color[ch];
|
|
317
|
+
sampleAlpha = clamp(sampleValues[ch] * intensityScale * u_channelOpacity[ch], 0.0, 1.0);
|
|
318
318
|
blendedSampleAlpha = (1.0 - accumulatedColor.a) * sampleAlpha;
|
|
319
319
|
|
|
320
320
|
|
|
@@ -333,16 +333,16 @@ precision highp int;
|
|
|
333
333
|
|
|
334
334
|
layout (location = 0) out vec4 fragColor;
|
|
335
335
|
|
|
336
|
-
uniform highp usampler3D
|
|
337
|
-
uniform mediump sampler2D
|
|
338
|
-
uniform highp usampler2D
|
|
336
|
+
uniform highp usampler3D u_imageSampler;
|
|
337
|
+
uniform mediump sampler2D u_colorCycleSampler;
|
|
338
|
+
uniform highp usampler2D u_colorLookupTableSampler;
|
|
339
339
|
|
|
340
340
|
uniform float u_opacity;
|
|
341
341
|
uniform float u_outlineSelected;
|
|
342
342
|
uniform float u_selectedValue;
|
|
343
|
-
uniform float
|
|
343
|
+
uniform float u_zTexCoord;
|
|
344
344
|
|
|
345
|
-
in vec2
|
|
345
|
+
in vec2 v_texCoords;
|
|
346
346
|
|
|
347
347
|
vec4 unpackRgba(uint packed) {
|
|
348
348
|
uint r = (packed >> 24u) & 0xFFu;
|
|
@@ -353,23 +353,23 @@ vec4 unpackRgba(uint packed) {
|
|
|
353
353
|
}
|
|
354
354
|
|
|
355
355
|
bool isEdgePixel(uint centerValue) {
|
|
356
|
-
vec2 texSize = vec2(textureSize(
|
|
356
|
+
vec2 texSize = vec2(textureSize(u_imageSampler, 0).xy);
|
|
357
357
|
vec2 texelSize = 1.0 / texSize;
|
|
358
|
-
|
|
358
|
+
|
|
359
359
|
|
|
360
360
|
for (int dx = -1; dx <= 1; dx++) {
|
|
361
361
|
for (int dy = -1; dy <= 1; dy++) {
|
|
362
362
|
if (dx == 0 && dy == 0) continue;
|
|
363
|
+
|
|
364
|
+
vec2 neighborCoords = v_texCoords + vec2(float(dx), float(dy)) * texelSize;
|
|
365
|
+
|
|
363
366
|
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (neighborCoords.x < 0.0 || neighborCoords.x > 1.0 ||
|
|
367
|
+
if (neighborCoords.x < 0.0 || neighborCoords.x > 1.0 ||
|
|
368
368
|
neighborCoords.y < 0.0 || neighborCoords.y > 1.0) {
|
|
369
369
|
continue;
|
|
370
370
|
}
|
|
371
|
-
|
|
372
|
-
uint neighborValue = texture(
|
|
371
|
+
|
|
372
|
+
uint neighborValue = texture(u_imageSampler, vec3(neighborCoords, u_zTexCoord)).r;
|
|
373
373
|
if (neighborValue != centerValue) {
|
|
374
374
|
return true;
|
|
375
375
|
}
|
|
@@ -379,11 +379,11 @@ bool isEdgePixel(uint centerValue) {
|
|
|
379
379
|
}
|
|
380
380
|
|
|
381
381
|
void main() {
|
|
382
|
-
uint texel = texture(
|
|
383
|
-
|
|
382
|
+
uint texel = texture(u_imageSampler, vec3(v_texCoords, u_zTexCoord)).r;
|
|
383
|
+
|
|
384
384
|
|
|
385
385
|
bool isSelectedValue = u_outlineSelected > 0.5 && u_selectedValue >= 0.0 && float(texel) == u_selectedValue;
|
|
386
|
-
|
|
386
|
+
|
|
387
387
|
|
|
388
388
|
if (isSelectedValue) {
|
|
389
389
|
if (isEdgePixel(texel)) {
|
|
@@ -393,32 +393,32 @@ void main() {
|
|
|
393
393
|
}
|
|
394
394
|
}
|
|
395
395
|
|
|
396
|
-
uint mapLength = uint(textureSize(
|
|
396
|
+
uint mapLength = uint(textureSize(u_colorLookupTableSampler, 0).x);
|
|
397
397
|
for (uint i = 0u; i < mapLength; ++i) {
|
|
398
|
-
uint key = texelFetch(
|
|
398
|
+
uint key = texelFetch(u_colorLookupTableSampler, ivec2(i, 0), 0).r;
|
|
399
399
|
if (texel == key) {
|
|
400
|
-
uint value = texelFetch(
|
|
400
|
+
uint value = texelFetch(u_colorLookupTableSampler, ivec2(i, 1), 0).r;
|
|
401
401
|
vec4 color = unpackRgba(value);
|
|
402
|
-
|
|
402
|
+
|
|
403
403
|
|
|
404
404
|
float alpha = isSelectedValue ? u_opacity * color.a * 0.9 : u_opacity * color.a;
|
|
405
|
-
|
|
405
|
+
|
|
406
406
|
fragColor = vec4(color.rgb, alpha);
|
|
407
407
|
return;
|
|
408
408
|
}
|
|
409
409
|
}
|
|
410
410
|
|
|
411
|
-
uint cycleLength = uint(textureSize(
|
|
411
|
+
uint cycleLength = uint(textureSize(u_colorCycleSampler, 0).x);
|
|
412
412
|
uint index = uint(texel - 1u) % cycleLength;
|
|
413
|
-
vec4 color = texelFetch(
|
|
414
|
-
|
|
413
|
+
vec4 color = texelFetch(u_colorCycleSampler, ivec2(index, 0), 0);
|
|
414
|
+
|
|
415
415
|
|
|
416
416
|
float alpha = isSelectedValue ? u_opacity * color.a * 0.9 : u_opacity * color.a;
|
|
417
|
-
|
|
417
|
+
|
|
418
418
|
fragColor = vec4(color.rgb, alpha);
|
|
419
419
|
}`;const co={projectedLine:{vertex:Fo,fragment:eo},points:{vertex:ro,fragment:no},wireframe:{vertex:So,fragment:No},floatScalarImage:{vertex:KB,fragment:yQ},intScalarImage:{vertex:KB,fragment:yQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintScalarImage:{vertex:KB,fragment:yQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])},labelImage:{vertex:KB,fragment:Ro},floatVolume:{vertex:tQ,fragment:GQ},intVolume:{vertex:tQ,fragment:GQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_INT","1"]])},uintVolume:{vertex:tQ,fragment:GQ,fragmentDefines:new Map([["TEXTURE_DATA_TYPE_UINT","1"]])}},vC={debug:10,info:20,warn:30,error:40},Uo={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"};function ko(){const Q=typeof process<"u"&&typeof process.env?.NODE_ENV=="string"?process.env.NODE_ENV:void 0;if(Q==="production"||Q==="development"||Q==="test")return Q;if(typeof window<"u"){const{NODE_ENV:A}=window;if(A==="production"||A==="development"||A==="test")return A}return"development"}class gA{static logLevel_=ko()==="production"?"warn":"debug";static setLogLevel(A){gA.logLevel_=A}static debug(A,I,...g){gA.log("debug",A,I,...g)}static info(A,I,...g){gA.log("info",A,I,...g)}static warn(A,I,...g){gA.log("warn",A,I,...g)}static error(A,I,...g){gA.log("error",A,I,...g)}static log(A,I,g,...B){if(vC[A]<vC[gA.logLevel_])return;const C=new Date().toISOString(),E=Uo[A],i=`[${C}][${A.toUpperCase()}][${I}]`,o=[`${E}${i}`,g,...B];switch(A){case"debug":console.debug(...o);break;case"info":console.info(...o);break;case"warn":console.warn(...o);break;case"error":console.error(...o);break}}}class Lo{gl_;program_;uniformInfo_=new Map;constructor(A,I,g){this.gl_=A;const B=A.createProgram();if(!B)throw new Error("Failed to create WebGL shader program");this.program_=B;const C=[];try{C.push(this.addShader(I,A.VERTEX_SHADER)),C.push(this.addShader(g,A.FRAGMENT_SHADER)),this.link(),this.preprocessUniformLocations()}catch(E){throw A.deleteProgram(B),E}finally{C.forEach(E=>this.gl_.deleteShader(E))}}setUniform(A,I){const[g,B]=this.uniformInfo_.get(A)??[];if(!g||!B)throw new Error(`Uniform "${A}" not found in shader program`);const C=B.type;switch(C){case this.gl_.BOOL:case this.gl_.FLOAT:typeof I=="number"?this.gl_.uniform1f(g,I):this.gl_.uniform1fv(g,I);break;case this.gl_.INT:typeof I=="number"?this.gl_.uniform1i(g,I):this.gl_.uniform1iv(g,I);break;case this.gl_.FLOAT_VEC2:this.gl_.uniform2fv(g,I);break;case this.gl_.FLOAT_VEC3:this.gl_.uniform3fv(g,I);break;case this.gl_.FLOAT_VEC4:this.gl_.uniform4fv(g,I);break;case this.gl_.FLOAT_MAT4:this.gl_.uniformMatrix4fv(g,!1,I);break;case this.gl_.UNSIGNED_INT:this.gl_.uniform1ui(g,I);break;case this.gl_.SAMPLER_2D:case this.gl_.SAMPLER_CUBE:case this.gl_.SAMPLER_3D:case this.gl_.SAMPLER_2D_ARRAY:case this.gl_.SAMPLER_2D_SHADOW:case this.gl_.SAMPLER_CUBE_SHADOW:case this.gl_.SAMPLER_2D_ARRAY_SHADOW:case this.gl_.INT_SAMPLER_2D:case this.gl_.INT_SAMPLER_3D:case this.gl_.INT_SAMPLER_CUBE:case this.gl_.INT_SAMPLER_2D_ARRAY:case this.gl_.UNSIGNED_INT_SAMPLER_2D:case this.gl_.UNSIGNED_INT_SAMPLER_3D:case this.gl_.UNSIGNED_INT_SAMPLER_CUBE:case this.gl_.UNSIGNED_INT_SAMPLER_2D_ARRAY:this.gl_.uniform1i(g,I);break;default:{const E=C;throw new Error(`Unhandled uniform type: ${E}`)}}}preprocessUniformLocations(){const A=this.gl_.getProgramParameter(this.program_,this.gl_.ACTIVE_UNIFORMS);for(let I=0;I<A;I++){const g=this.gl_.getActiveUniform(this.program_,I);if(g){if(!Yo.has(g.type))throw new Error(`Unsupported uniform type "${g.type}" (GLenum) found in shader program for uniform "${g.name}"`);const B=this.gl_.getUniformLocation(this.program_,g.name);B&&(this.uniformInfo_.set(g.name,[B,g]),gA.debug("WebGLShaderProgram","Uniform found:",g.name,g.type,g.size))}}}addShader(A,I){const g=this.gl_.createShader(I);if(!g)throw new Error(`Failed to create a new shader of type ${I}`);if(this.gl_.shaderSource(g,A),this.gl_.compileShader(g),!this.gl_.getShaderParameter(g,this.gl_.COMPILE_STATUS)){const B=this.gl_.getShaderInfoLog(g);throw this.gl_.deleteShader(g),new Error(`Error compiling shader: ${B}`)}return this.gl_.attachShader(this.program_,g),g}link(){if(this.gl_.linkProgram(this.program_),!this.getParameter(this.gl_.LINK_STATUS)){const A=this.gl_.getProgramInfoLog(this.program_);throw new Error(`Error linking program: ${A}`)}}use(){this.gl_.useProgram(this.program_)}getParameter(A){return this.gl_.getProgramParameter(this.program_,A)}get uniformNames(){return Array.from(this.uniformInfo_.keys())}}const Jo=typeof window<"u"?[WebGL2RenderingContext.BOOL,WebGL2RenderingContext.FLOAT,WebGL2RenderingContext.INT,WebGL2RenderingContext.FLOAT_VEC2,WebGL2RenderingContext.FLOAT_VEC3,WebGL2RenderingContext.FLOAT_VEC4,WebGL2RenderingContext.FLOAT_MAT4,WebGL2RenderingContext.SAMPLER_2D,WebGL2RenderingContext.SAMPLER_CUBE,WebGL2RenderingContext.SAMPLER_3D,WebGL2RenderingContext.SAMPLER_2D_ARRAY,WebGL2RenderingContext.SAMPLER_2D_SHADOW,WebGL2RenderingContext.SAMPLER_CUBE_SHADOW,WebGL2RenderingContext.SAMPLER_2D_ARRAY_SHADOW,WebGL2RenderingContext.INT,WebGL2RenderingContext.INT_SAMPLER_2D,WebGL2RenderingContext.INT_SAMPLER_3D,WebGL2RenderingContext.INT_SAMPLER_CUBE,WebGL2RenderingContext.INT_SAMPLER_2D_ARRAY,WebGL2RenderingContext.UNSIGNED_INT,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_3D,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_CUBE,WebGL2RenderingContext.UNSIGNED_INT_SAMPLER_2D_ARRAY]:[],Yo=new Set(Jo),wQ="#pragma inject_defines";class Ko{gl_;programs_=new Map;constructor(A){this.gl_=A}use(A){let I=this.programs_.get(A);if(I===void 0){const g=co[A],B=XC(g.vertex,g.vertexDefines),C=XC(g.fragment,g.fragmentDefines);I=new Lo(this.gl_,B,C),I.use();const E=this.gl_.getError();if(E!==this.gl_.NO_ERROR)throw new Error(`Error using WebGL program: ${E}`);this.programs_.set(A,I)}else I.use();return I}}function XC(Q,A){if(A===void 0||A.size==0)return Q;if(!Q.includes(wQ))throw new Error(`Shader source does not contain "${wQ}" directive`);const I=Array.from(A.entries()).map(([E,i])=>`#define ${E} ${i}`).join(`
|
|
420
420
|
`),B=`#line __LINE__ + ${1-A.size}`,C=`${I}
|
|
421
|
-
${B}`;return Q.replace(wQ,C)}const MB={};function jC(Q){const A=Q??"";return MB[A]=(MB[A]??0)+1,Q?`${Q}-${MB[A]}`:String(MB[A])}class FQ{id=jC()}var JA=1e-6,OA=typeof Float32Array<"u"?Float32Array:Array,Mo=Math.PI/180;function Ho(Q){return Q*Mo}function zC(){var Q=new OA(9);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[5]=0,Q[6]=0,Q[7]=0),Q[0]=1,Q[4]=1,Q[8]=1,Q}function qo(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[4],Q[4]=A[5],Q[5]=A[6],Q[6]=A[8],Q[7]=A[9],Q[8]=A[10],Q}function hI(){var Q=new OA(16);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0),Q[0]=1,Q[5]=1,Q[10]=1,Q[15]=1,Q}function lo(Q,A,I,g,B,C,E,i,o,a,D,s,y,e,Y,u){var H=new OA(16);return H[0]=Q,H[1]=A,H[2]=I,H[3]=g,H[4]=B,H[5]=C,H[6]=E,H[7]=i,H[8]=o,H[9]=a,H[10]=D,H[11]=s,H[12]=y,H[13]=e,H[14]=Y,H[15]=u,H}function dB(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=A[4],i=A[5],o=A[6],a=A[7],D=A[8],s=A[9],y=A[10],e=A[11],Y=A[12],u=A[13],H=A[14],W=A[15],z=I*i-g*E,x=I*o-B*E,l=I*a-C*E,Z=g*o-B*i,v=g*a-C*i,CA=B*a-C*o,sA=D*u-s*Y,DA=D*H-y*Y,yA=D*W-e*Y,wA=s*H-y*u,zA=s*W-e*u,uA=y*W-e*H,NA=z*uA-x*zA+l*wA+Z*yA-v*DA+CA*sA;return NA?(NA=1/NA,Q[0]=(i*uA-o*zA+a*wA)*NA,Q[1]=(B*zA-g*uA-C*wA)*NA,Q[2]=(u*CA-H*v+W*Z)*NA,Q[3]=(y*v-s*CA-e*Z)*NA,Q[4]=(o*yA-E*uA-a*DA)*NA,Q[5]=(I*uA-B*yA+C*DA)*NA,Q[6]=(H*l-Y*CA-W*x)*NA,Q[7]=(D*CA-y*l+e*x)*NA,Q[8]=(E*zA-i*yA+a*sA)*NA,Q[9]=(g*yA-I*zA-C*sA)*NA,Q[10]=(Y*v-u*l+W*z)*NA,Q[11]=(s*l-D*v-e*z)*NA,Q[12]=(i*DA-E*wA-o*sA)*NA,Q[13]=(I*wA-g*DA+B*sA)*NA,Q[14]=(u*x-Y*Z-H*z)*NA,Q[15]=(D*Z-s*x+y*z)*NA,Q):null}function Rg(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=A[4],o=A[5],a=A[6],D=A[7],s=A[8],y=A[9],e=A[10],Y=A[11],u=A[12],H=A[13],W=A[14],z=A[15],x=I[0],l=I[1],Z=I[2],v=I[3];return Q[0]=x*g+l*i+Z*s+v*u,Q[1]=x*B+l*o+Z*y+v*H,Q[2]=x*C+l*a+Z*e+v*W,Q[3]=x*E+l*D+Z*Y+v*z,x=I[4],l=I[5],Z=I[6],v=I[7],Q[4]=x*g+l*i+Z*s+v*u,Q[5]=x*B+l*o+Z*y+v*H,Q[6]=x*C+l*a+Z*e+v*W,Q[7]=x*E+l*D+Z*Y+v*z,x=I[8],l=I[9],Z=I[10],v=I[11],Q[8]=x*g+l*i+Z*s+v*u,Q[9]=x*B+l*o+Z*y+v*H,Q[10]=x*C+l*a+Z*e+v*W,Q[11]=x*E+l*D+Z*Y+v*z,x=I[12],l=I[13],Z=I[14],v=I[15],Q[12]=x*g+l*i+Z*s+v*u,Q[13]=x*B+l*o+Z*y+v*H,Q[14]=x*C+l*a+Z*e+v*W,Q[15]=x*E+l*D+Z*Y+v*z,Q}function fo(Q,A){return Q[0]=A[0],Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=A[1],Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=A[2],Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,Q}function po(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=B+B,a=C+C,D=E+E,s=B*o,y=B*a,e=B*D,Y=C*a,u=C*D,H=E*D,W=i*o,z=i*a,x=i*D,l=g[0],Z=g[1],v=g[2];return Q[0]=(1-(Y+H))*l,Q[1]=(y+x)*l,Q[2]=(e-z)*l,Q[3]=0,Q[4]=(y-x)*Z,Q[5]=(1-(s+H))*Z,Q[6]=(u+W)*Z,Q[7]=0,Q[8]=(e+z)*v,Q[9]=(u-W)*v,Q[10]=(1-(s+Y))*v,Q[11]=0,Q[12]=I[0],Q[13]=I[1],Q[14]=I[2],Q[15]=1,Q}function uo(Q,A,I,g,B){var C=1/Math.tan(A/2);if(Q[0]=C/I,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=C,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=-1,Q[12]=0,Q[13]=0,Q[15]=0,B!=null&&B!==1/0){var E=1/(g-B);Q[10]=(B+g)*E,Q[14]=2*B*g*E}else Q[10]=-1,Q[14]=-2*g;return Q}var mo=uo;function xo(Q,A,I,g,B,C,E){var i=1/(A-I),o=1/(g-B),a=1/(C-E);return Q[0]=-2*i,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=-2*o,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=2*a,Q[11]=0,Q[12]=(A+I)*i,Q[13]=(B+g)*o,Q[14]=(E+C)*a,Q[15]=1,Q}var To=xo;function Wo(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=g[0],o=g[1],a=g[2],D=B-I[0],s=C-I[1],y=E-I[2],e=D*D+s*s+y*y;e>0&&(e=1/Math.sqrt(e),D*=e,s*=e,y*=e);var Y=o*y-a*s,u=a*D-i*y,H=i*s-o*D;return e=Y*Y+u*u+H*H,e>0&&(e=1/Math.sqrt(e),Y*=e,u*=e,H*=e),Q[0]=Y,Q[1]=u,Q[2]=H,Q[3]=0,Q[4]=s*H-y*u,Q[5]=y*Y-D*H,Q[6]=D*u-s*Y,Q[7]=0,Q[8]=D,Q[9]=s,Q[10]=y,Q[11]=0,Q[12]=B,Q[13]=C,Q[14]=E,Q[15]=1,Q}function bo(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=Q[3],E=Q[4],i=Q[5],o=Q[6],a=Q[7],D=Q[8],s=Q[9],y=Q[10],e=Q[11],Y=Q[12],u=Q[13],H=Q[14],W=Q[15],z=A[0],x=A[1],l=A[2],Z=A[3],v=A[4],CA=A[5],sA=A[6],DA=A[7],yA=A[8],wA=A[9],zA=A[10],uA=A[11],NA=A[12],mI=A[13],kI=A[14],xI=A[15];return Math.abs(I-z)<=JA*Math.max(1,Math.abs(I),Math.abs(z))&&Math.abs(g-x)<=JA*Math.max(1,Math.abs(g),Math.abs(x))&&Math.abs(B-l)<=JA*Math.max(1,Math.abs(B),Math.abs(l))&&Math.abs(C-Z)<=JA*Math.max(1,Math.abs(C),Math.abs(Z))&&Math.abs(E-v)<=JA*Math.max(1,Math.abs(E),Math.abs(v))&&Math.abs(i-CA)<=JA*Math.max(1,Math.abs(i),Math.abs(CA))&&Math.abs(o-sA)<=JA*Math.max(1,Math.abs(o),Math.abs(sA))&&Math.abs(a-DA)<=JA*Math.max(1,Math.abs(a),Math.abs(DA))&&Math.abs(D-yA)<=JA*Math.max(1,Math.abs(D),Math.abs(yA))&&Math.abs(s-wA)<=JA*Math.max(1,Math.abs(s),Math.abs(wA))&&Math.abs(y-zA)<=JA*Math.max(1,Math.abs(y),Math.abs(zA))&&Math.abs(e-uA)<=JA*Math.max(1,Math.abs(e),Math.abs(uA))&&Math.abs(Y-NA)<=JA*Math.max(1,Math.abs(Y),Math.abs(NA))&&Math.abs(u-mI)<=JA*Math.max(1,Math.abs(u),Math.abs(mI))&&Math.abs(H-kI)<=JA*Math.max(1,Math.abs(H),Math.abs(kI))&&Math.abs(W-xI)<=JA*Math.max(1,Math.abs(W),Math.abs(xI))}function HA(){var Q=new OA(3);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q}function HI(Q){var A=new OA(3);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A}function eQ(Q){var A=Q[0],I=Q[1],g=Q[2];return Math.sqrt(A*A+I*I+g*g)}function nA(Q,A,I){var g=new OA(3);return g[0]=Q,g[1]=A,g[2]=I,g}function rQ(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q}function Bg(Q,A,I,g){return Q[0]=A,Q[1]=I,Q[2]=g,Q}function gB(Q,A,I){return Q[0]=A[0]+I[0],Q[1]=A[1]+I[1],Q[2]=A[2]+I[2],Q}function Zo(Q,A,I){return Q[0]=A[0]-I[0],Q[1]=A[1]-I[1],Q[2]=A[2]-I[2],Q}function Po(Q,A,I){return Q[0]=A[0]*I[0],Q[1]=A[1]*I[1],Q[2]=A[2]*I[2],Q}function BB(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q}function _C(Q,A,I,g){return Q[0]=A[0]+I[0]*g,Q[1]=A[1]+I[1]*g,Q[2]=A[2]+I[2]*g,Q}function $C(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1],B=A[2]-Q[2];return I*I+g*g+B*B}function Vo(Q,A){var I=A[0],g=A[1],B=A[2],C=I*I+g*g+B*B;return C>0&&(C=1/Math.sqrt(C)),Q[0]=A[0]*C,Q[1]=A[1]*C,Q[2]=A[2]*C,Q}function AE(Q,A){return Q[0]*A[0]+Q[1]*A[1]+Q[2]*A[2]}function nQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return Q[0]=B*o-C*i,Q[1]=C*E-g*o,Q[2]=g*i-B*E,Q}function SQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[3]*g+I[7]*B+I[11]*C+I[15];return E=E||1,Q[0]=(I[0]*g+I[4]*B+I[8]*C+I[12])/E,Q[1]=(I[1]*g+I[5]*B+I[9]*C+I[13])/E,Q[2]=(I[2]*g+I[6]*B+I[10]*C+I[14])/E,Q}function Oo(Q){return Q[0]=0,Q[1]=0,Q[2]=0,Q}function NQ(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=JA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(g-E)<=JA*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(B-i)<=JA*Math.max(1,Math.abs(B),Math.abs(i))}var RQ=Zo,vo=eQ;(function(){var Q=HA();return function(A,I,g,B,C,E){var i,o;for(I||(I=3),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2];return A}})();function cg(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0,Q[3]=0),Q}function Xo(Q){var A=new OA(4);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A[3]=Q[3],A}function HB(Q,A,I,g){var B=new OA(4);return B[0]=Q,B[1]=A,B[2]=I,B[3]=g,B}function jo(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[3],Q}function zo(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q[3]=A[3]*I,Q}function _o(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=I*I+g*g+B*B+C*C;return E>0&&(E=1/Math.sqrt(E)),Q[0]=I*E,Q[1]=g*E,Q[2]=B*E,Q[3]=C*E,Q}function QB(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3];return Q[0]=I[0]*g+I[4]*B+I[8]*C+I[12]*E,Q[1]=I[1]*g+I[5]*B+I[9]*C+I[13]*E,Q[2]=I[2]*g+I[6]*B+I[10]*C+I[14]*E,Q[3]=I[3]*g+I[7]*B+I[11]*C+I[15]*E,Q}(function(){var Q=cg();return function(A,I,g,B,C,E){var i,o;for(I||(I=4),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],Q[3]=A[i+3],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2],A[i+3]=Q[3];return A}})();function cQ(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q[3]=1,Q}function $o(Q,A,I){I=I*.5;var g=Math.sin(I);return Q[0]=g*A[0],Q[1]=g*A[1],Q[2]=g*A[2],Q[3]=Math.cos(I),Q}function Aa(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=I[0],o=I[1],a=I[2],D=I[3];return Q[0]=g*D+E*i+B*a-C*o,Q[1]=B*D+E*o+C*i-g*a,Q[2]=C*D+E*a+g*o-B*i,Q[3]=E*D-g*i-B*o-C*a,Q}function UQ(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=I[0],a=I[1],D=I[2],s=I[3],y,e,Y,u,H;return e=B*o+C*a+E*D+i*s,e<0&&(e=-e,o=-o,a=-a,D=-D,s=-s),1-e>JA?(y=Math.acos(e),Y=Math.sin(y),u=Math.sin((1-g)*y)/Y,H=Math.sin(g*y)/Y):(u=1-g,H=g),Q[0]=u*B+H*o,Q[1]=u*C+H*a,Q[2]=u*E+H*D,Q[3]=u*i+H*s,Q}function IE(Q,A){var I=A[0]+A[4]+A[8],g;if(I>0)g=Math.sqrt(I+1),Q[3]=.5*g,g=.5/g,Q[0]=(A[5]-A[7])*g,Q[1]=(A[6]-A[2])*g,Q[2]=(A[1]-A[3])*g;else{var B=0;A[4]>A[0]&&(B=1),A[8]>A[B*3+B]&&(B=2);var C=(B+1)%3,E=(B+2)%3;g=Math.sqrt(A[B*3+B]-A[C*3+C]-A[E*3+E]+1),Q[B]=.5*g,g=.5/g,Q[3]=(A[C*3+E]-A[E*3+C])*g,Q[C]=(A[C*3+B]+A[B*3+C])*g,Q[E]=(A[E*3+B]+A[B*3+E])*g}return Q}var Ia=Xo,ga=jo,kQ=_o;(function(){var Q=HA(),A=nA(1,0,0),I=nA(0,1,0);return function(g,B,C){var E=AE(B,C);return E<-.999999?(nQ(Q,A,B),vo(Q)<1e-6&&nQ(Q,I,B),Vo(Q,Q),$o(g,Q,Math.PI),g):E>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(nQ(Q,B,C),g[0]=Q[0],g[1]=Q[1],g[2]=Q[2],g[3]=1+E,kQ(g,g))}})(),(function(){var Q=cQ(),A=cQ();return function(I,g,B,C,E,i){return UQ(Q,g,E,i),UQ(A,B,C,i),UQ(I,Q,A,2*i*(1-i)),I}})(),(function(){var Q=zC();return function(A,I,g,B){return Q[0]=g[0],Q[3]=g[1],Q[6]=g[2],Q[1]=B[0],Q[4]=B[1],Q[7]=B[2],Q[2]=-I[0],Q[5]=-I[1],Q[8]=-I[2],kQ(A,IE(A,Q))}})();function gE(){var Q=new OA(2);return OA!=Float32Array&&(Q[0]=0,Q[1]=0),Q}function BE(Q){var A=new OA(2);return A[0]=Q[0],A[1]=Q[1],A}function xA(Q,A){var I=new OA(2);return I[0]=Q,I[1]=A,I}function Ba(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1];return Math.sqrt(I*I+g*g)}function Qa(Q){var A=Q[0],I=Q[1];return A*A+I*I}function Ca(Q,A,I,g){var B=A[0],C=A[1];return Q[0]=B+g*(I[0]-B),Q[1]=C+g*(I[1]-C),Q}function QE(Q,A){return Q[0]===A[0]&&Q[1]===A[1]}function LQ(Q,A){var I=Q[0],g=Q[1],B=A[0],C=A[1];return Math.abs(I-B)<=JA*Math.max(1,Math.abs(I),Math.abs(B))&&Math.abs(g-C)<=JA*Math.max(1,Math.abs(g),Math.abs(C))}(function(){var Q=gE();return function(A,I,g,B,C,E){var i,o;for(I||(I=2),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1];return A}})();class Qg{min;max;constructor(A,I){this.min=A?HI(A):nA(1/0,1/0,1/0),this.max=I?HI(I):nA(-1/0,-1/0,-1/0)}clone(){return new Qg(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:g}=this,B=[nA(I[0],I[1],I[2]),nA(I[0],I[1],g[2]),nA(I[0],g[1],I[2]),nA(I[0],g[1],g[2]),nA(g[0],I[1],I[2]),nA(g[0],I[1],g[2]),nA(g[0],g[1],I[2]),nA(g[0],g[1],g[2])];this.min=nA(1/0,1/0,1/0),this.max=nA(-1/0,-1/0,-1/0);const C=HA();for(const E of B)SQ(C,E,A),this.expandWithPoint(C)}}const CE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class Ug extends FQ{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],g="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=g,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,g=new Qg,B=HA();for(let C=0;C<this.vertexData_.length;C+=this.stride)B[0]=this.vertexData_[C+I+0],B[1]=this.vertexData_[C+I+1],B[2]=this.vertexData_[C+I+2],g.expandWithPoint(B);this.boundingBox_=g}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class Ea{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:g}=A,B=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(B,C),this.gl_.bufferData(B,g,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(D=>{const s=CE[D.type];this.gl_.vertexAttribPointer(s,D.itemSize,this.gl_.FLOAT,!1,i,D.offset),this.gl_.enableVertexAttribArray(s)});const o={vao:I,vbo:C},{indexData:a}=A;if(a.length){const D=this.gl_.ELEMENT_ARRAY_BUFFER,s=this.gl_.createBuffer();if(!s)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(D,s),this.gl_.bufferData(D,a,this.gl_.STATIC_DRAW),o.ebo=s}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class ia{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;readFramebuffer_=null;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}get gpuTextureBytes(){return this.gpuTextureBytes_}get textureCount(){return this.textureCount_}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}]`);const g=this.textures_.get(A);g&&!A.needsUpdate?(this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.gl_.bindTexture(this.getTextureType(A),g)):this.uploadTexture(A,I),this.currentTexture_=A}readTexel(A,I,g,B){const C=this.gl_,E=this.textures_.get(A);if(!E)throw new Error("readTexel called on a texture that is not resident");this.readFramebuffer_??=C.createFramebuffer(),C.bindFramebuffer(C.READ_FRAMEBUFFER,this.readFramebuffer_),C.framebufferTextureLayer(C.READ_FRAMEBUFFER,C.COLOR_ATTACHMENT0,E,0,B);const{format:i,type:o,out:a}=this.readbackParams(A.dataType);return C.readPixels(I,g,1,1,i,o,a),C.bindFramebuffer(C.READ_FRAMEBUFFER,null),a[0]}readbackParams(A){const I=this.gl_;switch(A){case"byte":case"short":case"int":return{format:I.RGBA_INTEGER,type:I.INT,out:new Int32Array(4)};case"unsigned_byte":case"unsigned_short":case"unsigned_int":return{format:I.RGBA_INTEGER,type:I.UNSIGNED_INT,out:new Uint32Array(4)};case"float":return{format:I.RGBA,type:I.FLOAT,out:new Float32Array(4)}}}uploadTexture(A,I=0){if(this.textures_.has(A)&&!A.needsUpdate)return;if(A.data===null)throw new Error("Cannot upload a texture that has no CPU data");const g=this.getTextureType(A),B=this.getDataFormatInfo(A.dataFormat,A.dataType);this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.textures_.has(A)||this.generateTexture(A,B,g);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(g,C),this.configureTextureParameters(A,g),this.uploadTextureData(A,B,g),A.needsUpdate=!1}dispose(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),A.readTexel=void 0,this.currentTexture_===A&&(this.currentTexture_=null);const g=this.getDataFormatInfo(A.dataFormat,A.dataType),B=this.computeStorageBytes(A,g);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-B),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.dispose(A);this.gpuTextureBytes_=0,this.textureCount_=0}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,g){const B=this.gl_.createTexture();if(!B)throw new Error("Failed to create texture");if(this.gl_.bindTexture(g,B),this.isTexture2D(A))this.gl_.texStorage2D(g,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(g,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,B),this.gl_.bindTexture(g,null),A.readTexel=(C,E,i)=>Promise.resolve(this.readTexel(A,C,E,i))}configureTextureParameters(A,I){const g=this.gl_,B=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);g.pixelStorei(g.UNPACK_ALIGNMENT,A.unpackAlignment),g.texParameteri(I,g.TEXTURE_MIN_FILTER,B),g.texParameteri(I,g.TEXTURE_MAG_FILTER,C),g.texParameteri(I,g.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),g.texParameteri(I,g.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),g.texParameteri(I,g.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,g){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(g,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(g,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:g,dataType:B}=I;if(g==="scalar"&&B!=="float"&&A!=="nearest")return gA.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}computeStorageBytes(A,I){const g=this.bytesPerTexel(I),B=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),o=0;for(let a=0;a<B;a++)o+=E*i*C*g,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class QI{min;max;constructor(A,I){this.min=A?BE(A):xA(1/0,1/0),this.max=I?BE(I):xA(-1/0,-1/0)}clone(){return new QI(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 QE(A.min,I.min)&&QE(A.max,I.max)}floor(){return new QI(xA(Math.floor(this.min[0]),Math.floor(this.min[1])),xA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],g=this.max[0]-this.min[0],B=this.max[1]-this.min[1];return{x:A,y:I,width:g,height:B}}}class oa{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW)}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"premultiplied":this.setBlendFunc(this.gl_.ONE_MINUS_DST_ALPHA,this.gl_.ONE);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&QI.equals(I,this.currentViewport_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.viewport(g,B,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&QI.equals(I,this.currentScissor_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.scissor(g,B,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}setStencilTest(A){A?this.enable(this.gl_.STENCIL_TEST):this.disable(this.gl_.STENCIL_TEST)}}const aa=fo(hI(),[1,-1,1]);class EE extends OC{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;currentViewportSize_=[0,0];constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0,stencil:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,gA.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),I.getExtension("EXT_color_buffer_float"),this.programs_=new Ko(I),this.bindings_=new Ea(I),this.textures_=new ia(I),this.state_=new oa(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}get gpuTextureBytes(){return this.textures_.gpuTextureBytes}get gpuTextureCount(){return this.textures_.textureCount}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0;const I=[],g=[];for(const D of A.layers)(D.blendMode==="none"?I:g).push(D);for(const D of[...I,...g])D.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new QI(xA(0,0),xA(this.width,this.height)),E=QI.equals(B.floor(),C.floor()),i=QI.intersects(B,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(B);else{gA.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(B),this.clear();const o=B.toRect();this.currentViewportSize_=[o.width,o.height];const a=A.camera.frustum;this.state_.setDepthMask(!0);for(const D of I)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.state_.setDepthMask(!1);for(const D of g)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.renderedObjects_=this.renderedObjectsPerFrame_}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilFunc(this.gl_.EQUAL,0,255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.INCR)}renderLayer(A,I,g){if(A.objects.length===0)return;this.state_.setBlendingMode(A.blendMode);const B=A.hasMultipleLODs();this.state_.setStencilTest(B),B&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{g.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,g){const B=A.objects[I];if(B.popStaleTextures().forEach(E=>{this.textures_.dispose(E)}),!B.programName)return;this.state_.setCullFaceMode(B.cullFaceMode),this.state_.setDepthTesting(B.depthTest),this.state_.setDepthMask(B.depthTest),this.bindings_.bindGeometry(B.geometry),B.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(B.programName);if(this.drawGeometry(B.geometry,B,A,C,g),B.wireframeEnabled){this.bindings_.bindGeometry(B.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",B.wireframeColor.rgb),this.drawGeometry(B.wireframeGeometry,B,A,E,g)}}drawGeometry(A,I,g,B,C){const E=Rg(hI(),C.viewMatrix,I.transform.matrix),i=Rg(hI(),aa,C.projectionMatrix),o=this.currentViewportSize_,a=I.getUniforms(),s={...g.getUniforms(),...a};for(const Y of B.uniformNames)switch(Y){case"ModelView":B.setUniform(Y,E);break;case"Projection":B.setUniform(Y,i);break;case"Resolution":B.setUniform(Y,o);break;case"u_opacity":B.setUniform(Y,g.opacity*(a.Opacity??1));break;case"CameraPositionModel":{const u=dB(hI(),E),H=HB(0,0,0,1),W=QB(cg(),H,u);B.setUniform(Y,nA(W[0],W[1],W[2]));break}default:Y in s&&B.setUniform(Y,s[Y])}const y=this.glGetPrimitive(A.primitive),e=A.indexData;e.length?this.gl_.drawElements(y,e.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(y,0,A.vertexCount)}uploadTexture(A){this.textures_.uploadTexture(A)}disposeTexture(A){this.textures_.dispose(A)}glGetPrimitive(A){switch(A){case"points":return this.gl_.POINTS;case"triangles":return this.gl_.TRIANGLES;case"lines":return this.gl_.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const g=new QI(xA(0,0),xA(A,I));this.state_.setViewport(g)}clear(){this.gl_.clearColor(...this.backgroundColor.rgba),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}const Da=16;class sa{device_;slotSize_;buffer_;capacity_=Da;cursor_=0;version_=0;clear_=[];constructor(A,I){const g=A.limits.minUniformBufferOffsetAlignment;this.device_=A,this.slotSize_=Math.ceil(I/g)*g,this.buffer_=this.createBuffer()}clear(){for(const A of this.clear_)A.destroy();this.clear_.length=0,this.cursor_=0}write(A){return this.cursor_>=this.capacity_&&this.resize(),this.device_.queue.writeBuffer(this.buffer_,this.cursor_*this.slotSize_,A),this.cursor_++,(this.cursor_-1)*this.slotSize_}get buffer(){return this.buffer_}get version(){return this.version_}resize(){const A=this.buffer_;this.capacity_*=2,this.buffer_=this.createBuffer();const I=this.device_.createCommandEncoder();I.copyBufferToBuffer(A,0,this.buffer_,0,A.size),this.device_.queue.submit([I.finish()]),this.clear_.push(A),this.version_++}createBuffer(){return this.device_.createBuffer({size:this.capacity_*this.slotSize_,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC})}}const ha=0,ya=1;class ta{device_;uniformBindings_=[];textureBindings_=[];constructor(A){this.device_=A}clearUniformBindings(){for(const A of this.uniformBindings_)A.buffer.clear()}setUniforms(A,I){const g=I.shaderModule.layouts.uniforms,B=I.uniformsData;let C=this.uniformBindings_.find(o=>o.layout===g);if(!C){const o=new sa(this.device_,B.byteLength),a=this.createUniformsBindGroup(g,o,B.byteLength);C={layout:g,buffer:o,group:a,version:o.version},this.uniformBindings_.push(C)}const E=C.buffer.write(B);C.version!==C.buffer.version&&(C.group=this.createUniformsBindGroup(g,C.buffer,B.byteLength),C.version=C.buffer.version),A.setBindGroup(ha,C.group,[E])}setTexture(A,I,g){const B=I.shaderModule.layouts.textures;if(!B)throw new Error("setTexture called on pipeline without a texture layout");let C=this.textureBindings_.find(E=>E.layout===B&&E.texture===g);if(!C){const E=this.createTexturesBindGroup(B,g);C={layout:B,texture:g,group:E},this.textureBindings_.push(C)}A.setBindGroup(ya,C.group)}createUniformsBindGroup(A,I,g){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:{buffer:I.buffer,size:g}}]})}createTexturesBindGroup(A,I){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:I.createView()}]})}}class Ga{device_;buffers_;constructor(A){this.device_=A,this.buffers_=[]}get(A){const I=this.buffers_.find(o=>o.geometry===A);if(I)return I;const g=this.device_.createBuffer({size:A.vertexData.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(g.getMappedRange()).set(A.vertexData),g.unmap();let B=null;A.indexData.byteLength>0&&(B=this.device_.createBuffer({size:A.indexData.byteLength,usage:GPUBufferUsage.INDEX,mappedAtCreation:!0}),new Uint32Array(B.getMappedRange()).set(A.indexData),B.unmap());const{attributes:C,attributesKey:E}=Fa(A),i={geometry:A,vertexBuffer:g,indexBuffer:B,attributes:C,attributesKey:E};return this.buffers_.push(i),i}dispose(A){const I=this.buffers_.findIndex(B=>B.geometry===A);if(I===-1)return;const g=this.buffers_[I];g.vertexBuffer.destroy(),g.indexBuffer?.destroy(),this.buffers_.splice(I,1)}disposeAll(){for(const A of this.buffers_)A.vertexBuffer.destroy(),A.indexBuffer?.destroy();this.buffers_.length=0}}function wa(Q){switch(Q){case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("Unsupported vertex format size")}}function Fa(Q){const A=[];let I="";for(const g of Q.attributes)A.push({shaderLocation:CE[g.type],offset:g.offset,format:wa(g.itemSize)}),I+=`${g.type},${g.offset},${g.itemSize}|`;return{attributes:A,attributesKey:I}}function ea(Q){return Q===1||Q===2||Q===4||Q===8}function kg(Q){if(Q instanceof Int8Array)return"byte";if(Q instanceof Int16Array)return"short";if(Q instanceof Int32Array)return"int";if(Q instanceof Uint8Array)return"unsigned_byte";if(Q instanceof Uint16Array)return"unsigned_short";if(Q instanceof Uint32Array)return"unsigned_int";if(Q instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function ra(Q){switch(Q.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function na(Q){switch(Q.dataType){case"byte":case"unsigned_byte":return 1;case"short":case"unsigned_short":return 2;case"int":case"unsigned_int":case"float":return 4}}function Sa(Q){if(Q.dataFormat==="rgb"||Q.dataFormat==="rgba")return[0,1];switch(Q.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class JQ extends FQ{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;readTexel;get type(){return"Texture"}}class qI extends JQ{data_;width_;height_;depth_;constructor(A,I,g,B){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=kg(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const g=new qI(I,A.shape.x,A.shape.y,A.shape.z);return g.unpackAlignment=A.rowAlignmentBytes,g}}class Na{device_;textures_;constructor(A){this.device_=A,this.textures_=[]}get(A){let I=this.textures_.find(g=>g.entry===A);if(I&&!A.needsUpdate)return I.texture;if(A.data===null)throw new Error("Cannot upload a texture that has no CPU data");if(!I){const g=this.device_.createTexture({size:iE(A),dimension:A instanceof qI?"3d":"2d",format:ca(A),usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC});this.textures_.push({entry:A,texture:g}),I=this.textures_[this.textures_.length-1]}return this.upload(A,I.texture),A.readTexel=(g,B,C)=>this.readTexel(I.texture,A.dataType,g,B,C),I.texture}async readTexel(A,I,g,B,C){const E=this.device_.createBuffer({size:256,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),i=this.device_.createCommandEncoder();i.copyTextureToBuffer({texture:A,origin:{x:g,y:B,z:C}},{buffer:E,bytesPerRow:256},{width:1,height:1,depthOrArrayLayers:1}),this.device_.queue.submit([i.finish()]),await E.mapAsync(GPUMapMode.READ);const o=Ra(new DataView(E.getMappedRange()),I);return E.unmap(),E.destroy(),o}upload(A,I){const g=ra(A),B=na(A),C=A.width*g*B;this.device_.queue.writeTexture({texture:I},A.data,{bytesPerRow:C,rowsPerImage:A.height},iE(A)),A.needsUpdate=!1}dispose(A){const I=this.textures_.findIndex(g=>g.entry===A);I!==-1&&(this.textures_[I].texture.destroy(),this.textures_.splice(I,1),A.readTexel=void 0)}disposeAll(){for(const A of this.textures_)A.texture.destroy();this.textures_.length=0}}function iE(Q){return{width:Q.width,height:Q.height,depthOrArrayLayers:Q instanceof qI?Q.depth:1}}function Ra(Q,A){switch(A){case"byte":return Q.getInt8(0);case"unsigned_byte":return Q.getUint8(0);case"short":return Q.getInt16(0,!0);case"unsigned_short":return Q.getUint16(0,!0);case"int":return Q.getInt32(0,!0);case"unsigned_int":return Q.getUint32(0,!0);case"float":return Q.getFloat32(0,!0)}}function ca(Q){if(Q.dataFormat==="rgb")throw new Error("RGB texture format is not supported in WebGPU");if(Q.dataFormat==="scalar")switch(Q.dataType){case"byte":return"r8snorm";case"unsigned_byte":return"r8unorm";case"short":return"r16sint";case"unsigned_short":return"r16uint";case"int":return"r32sint";case"unsigned_int":return"r32uint";case"float":return"r32float"}switch(Q.dataType){case"byte":return"rgba8snorm";case"unsigned_byte":return"rgba8unorm";case"short":return"rgba16sint";case"unsigned_short":return"rgba16uint";case"int":return"rgba32sint";case"unsigned_int":return"rgba32uint";case"float":return"rgba32float"}}const YQ=(Q,A)=>((Q+A-1)/A|0)*A;function Ua(Q){return Object.keys(Q)}function ka(Q,A){return new Array(Q).fill(0).map((I,g)=>A(g))}const oE=Q=>ArrayBuffer.isView(Q)&&!(Q instanceof DataView),aE=Q=>Q,eA=aE({i32:{numElements:1,align:4,size:4,type:"i32",View:Int32Array},u32:{numElements:1,align:4,size:4,type:"u32",View:Uint32Array},f32:{numElements:1,align:4,size:4,type:"f32",View:Float32Array},f16:{numElements:1,align:2,size:2,type:"u16",View:Uint16Array},vec2f:{numElements:2,align:8,size:8,type:"f32",View:Float32Array},vec2i:{numElements:2,align:8,size:8,type:"i32",View:Int32Array},vec2u:{numElements:2,align:8,size:8,type:"u32",View:Uint32Array},vec2h:{numElements:2,align:4,size:4,type:"u16",View:Float16Array},vec3i:{numElements:3,align:16,size:12,type:"i32",View:Int32Array},vec3u:{numElements:3,align:16,size:12,type:"u32",View:Uint32Array},vec3f:{numElements:3,align:16,size:12,type:"f32",View:Float32Array},vec3h:{numElements:3,align:8,size:6,type:"u16",View:Float16Array},vec4i:{numElements:4,align:16,size:16,type:"i32",View:Int32Array},vec4u:{numElements:4,align:16,size:16,type:"u32",View:Uint32Array},vec4f:{numElements:4,align:16,size:16,type:"f32",View:Float32Array},vec4h:{numElements:4,align:8,size:8,type:"u16",View:Float16Array},mat2x2f:{numElements:4,align:8,size:16,type:"f32",View:Float32Array},mat2x2h:{numElements:4,align:4,size:8,type:"u16",View:Float16Array},mat3x2f:{numElements:6,align:8,size:24,type:"f32",View:Float32Array},mat3x2h:{numElements:6,align:4,size:12,type:"u16",View:Float16Array},mat4x2f:{numElements:8,align:8,size:32,type:"f32",View:Float32Array},mat4x2h:{numElements:8,align:4,size:16,type:"u16",View:Float16Array},mat2x3f:{numElements:8,align:16,size:32,pad:[3,1],type:"f32",View:Float32Array},mat2x3h:{numElements:8,align:8,size:16,pad:[3,1],type:"u16",View:Float16Array},mat3x3f:{numElements:12,align:16,size:48,pad:[3,1],type:"f32",View:Float32Array},mat3x3h:{numElements:12,align:8,size:24,pad:[3,1],type:"u16",View:Float16Array},mat4x3f:{numElements:16,align:16,size:64,pad:[3,1],type:"f32",View:Float32Array},mat4x3h:{numElements:16,align:8,size:32,pad:[3,1],type:"u16",View:Float16Array},mat2x4f:{numElements:8,align:16,size:32,type:"f32",View:Float32Array},mat2x4h:{numElements:8,align:8,size:16,type:"u16",View:Float16Array},mat3x4f:{numElements:12,align:16,size:48,type:"f32",View:Float32Array},mat3x4h:{numElements:12,align:8,size:24,type:"u16",View:Float16Array},mat4x4f:{numElements:16,align:16,size:64,type:"f32",View:Float32Array},mat4x4h:{numElements:16,align:8,size:32,type:"u16",View:Float16Array},bool:{numElements:0,align:1,size:0,type:"bool",View:Uint32Array}}),Lg=aE({...eA,"atomic<i32>":eA.i32,"atomic<u32>":eA.u32,"vec2<i32>":eA.vec2i,"vec2<u32>":eA.vec2u,"vec2<f32>":eA.vec2f,"vec2<f16>":eA.vec2h,"vec3<i32>":eA.vec3i,"vec3<u32>":eA.vec3u,"vec3<f32>":eA.vec3f,"vec3<f16>":eA.vec3h,"vec4<i32>":eA.vec4i,"vec4<u32>":eA.vec4u,"vec4<f32>":eA.vec4f,"vec4<f16>":eA.vec4h,"mat2x2<f32>":eA.mat2x2f,"mat2x2<f16>":eA.mat2x2h,"mat3x2<f32>":eA.mat3x2f,"mat3x2<f16>":eA.mat3x2h,"mat4x2<f32>":eA.mat4x2f,"mat4x2<f16>":eA.mat4x2h,"mat2x3<f32>":eA.mat2x3f,"mat2x3<f16>":eA.mat2x3h,"mat3x3<f32>":eA.mat3x3f,"mat3x3<f16>":eA.mat3x3h,"mat4x3<f32>":eA.mat4x3f,"mat4x3<f16>":eA.mat4x3h,"mat2x4<f32>":eA.mat2x4f,"mat2x4<f16>":eA.mat2x4h,"mat3x4<f32>":eA.mat3x4f,"mat3x4<f16>":eA.mat3x4h,"mat4x4<f32>":eA.mat4x4f,"mat4x4<f16>":eA.mat4x4h}),La=Ua(Lg);function Ja(Q=[],A){const I=new Set;for(const g of La){const B=Lg[g];I.has(B)||(I.add(B),B.flatten=Q.includes(g)?A:!A)}}Ja();function Ya(Q){const A=Q;if(A.elementType)return A.size;{const g=Q,B=A.numElements||1;if(g.fields)return Q.size*B;{const C=Q,{align:E}=Lg[C.type];return B>1?YQ(Q.size,E)*B:Q.size}}}function DE(Q,A,I,g){const{size:B,type:C}=Q;try{const{View:E,align:i,size:o}=Lg[C],a=g!==void 0,D=a?YQ(B,i):o,s=D/E.BYTES_PER_ELEMENT,y=a?g===0?(A.byteLength-I)/D:g:1;return new E(A,I,s*y)}catch{throw new Error(`unknown type: ${C}`)}}function Ka(Q){return!Q.fields&&!Q.elementType}function Ma(Q,A,I){const g=I||0,B=new ArrayBuffer(Ya(Q)),C=(E,i)=>{const o=E,a=o.elementType;if(a){if(Ka(a)&&Lg[a.type].flatten)return DE(a,B,i,o.numElements);{const{size:D}=sE(E),s=o.numElements===0?(B.byteLength-i)/D:o.numElements;return ka(s,y=>C(a,i+D*y))}}else{if(typeof E=="string")throw Error("unreachable");{const D=E.fields;if(D){const s={};for(const[y,{type:e,offset:Y}]of Object.entries(D))s[y]=C(e,i+Y);return s}else return DE(E,B,i)}}};return{views:C(Q,g),arrayBuffer:B}}function KQ(Q,A){if(Q!==void 0)if(oE(A)){const I=A;if(I.length===1&&typeof Q=="number")I[0]=Q;else if(Array.isArray(Q[0])||oE(Q[0])){const g=Q[0].length,B=g===3?4:g;for(let C=0;C<Q.length;++C){const E=C*B;I.set(Q[C],E)}}else I.set(Q)}else if(Array.isArray(A)){const I=A;Q.forEach((g,B)=>{KQ(g,I[B])})}else{const I=A;for(const[g,B]of Object.entries(Q)){const C=I[g];C&&KQ(B,C)}}}function da(Q,A,I=0){const g=Q,B=g.group===void 0?Q:g.typeDefinition,C=Ma(B,A,I);return{...C,set(E){KQ(E,C.views)}}}function MQ(Q){const I=Q.elementType;if(I)return MQ(I);const B=Q.fields;if(B)return Object.values(B).reduce((i,{type:o})=>Math.max(i,MQ(o)),0);const{type:C}=Q,{align:E}=Lg[C];return E}function sE(Q){const I=Q.elementType;if(I){const C=I.size,E=MQ(I);return{unalignedSize:C,align:E,size:YQ(C,E)}}const B=Q.fields;if(B){const C=Object.values(B).pop();if(C.type.size===0)return sE(C.type)}return{size:0,unalignedSize:0,align:1}}class wI{constructor(A,I){this.name=A,this.attributes=I,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class hE{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class WI extends wI{constructor(A,I){super(A,I),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class bI extends wI{constructor(A,I){super(A,I),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class dQ extends wI{constructor(A,I,g){super(A,g),this.format=I}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class Cg extends wI{constructor(A,I,g,B){super(A,g),this.format=I,this.access=B}get isTemplate(){return!0}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}var fA;(Q=>{Q[Q.Uniform=0]="Uniform",Q[Q.Storage=1]="Storage",Q[Q.Immediate=2]="Immediate",Q[Q.Texture=3]="Texture",Q[Q.Sampler=4]="Sampler",Q[Q.StorageTexture=5]="StorageTexture"})(fA||(fA={}));class CB{constructor(A,I,g,B,C,E,i){this.relations=null,this.name=A,this.type=I,this.group=g,this.binding=B,this.attributes=C,this.resourceType=E,this.access=i}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class Ha{constructor(A,I){this.name=A,this.type=I}}class qa{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B,this.interpolation=null}}class yE{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B}}class la{constructor(A,I,g,B){this.name=A,this.type=I,this.attributes=g,this.id=B}}class fa{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g}}class pa{constructor(A,I=null,g){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=A,this.stage=I,this.attributes=g}}class ua{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function ma(Q){var A=(32768&Q)>>15,I=(31744&Q)>>10,g=1023&Q;return I==0?(A?-1:1)*Math.pow(2,-14)*(g/Math.pow(2,10)):I==31?g?NaN:1/0*(A?-1:1):(A?-1:1)*Math.pow(2,I-15)*(1+g/Math.pow(2,10))}const tE=new Float32Array(1),xa=new Int32Array(tE.buffer),gI=new Uint16Array(1);function Ta(Q){tE[0]=Q;const A=xa[0],I=A>>31&1;let g=A>>23&255,B=8388607&A;if(g===255)return gI[0]=I<<15|31744|(B!==0?512:0),gI[0];if(g===0){if(B===0)return gI[0]=I<<15,gI[0];B|=8388608;let C=113;for(;!(8388608&B);)B<<=1,C--;return g=127-C,B&=8388607,g>0?(B=(B>>126-g)+(B>>127-g&1),gI[0]=I<<15|g<<10|B>>13,gI[0]):(gI[0]=I<<15,gI[0])}return g=g-127+15,g>=31?(gI[0]=I<<15|31744,gI[0]):g<=0?g<-10?(gI[0]=I<<15,gI[0]):(B=(8388608|B)>>1-g,gI[0]=I<<15|B>>13,gI[0]):(B>>=13,gI[0]=I<<15|g<<10|B,gI[0])}const HQ=new Uint32Array(1),GE=new Float32Array(HQ.buffer,0,1);function wE(Q){const A=112+(Q>>6&31)<<23|(63&Q)<<17;return HQ[0]=A,GE[0]}function Wa(Q,A,I,g,B,C,E,i,o){const a=g*(E>>=B)*(C>>=B)+I*E+A*i;switch(o){case"r8unorm":return[cA(Q,a,"8unorm",1)[0]];case"r8snorm":return[cA(Q,a,"8snorm",1)[0]];case"r8uint":return[cA(Q,a,"8uint",1)[0]];case"r8sint":return[cA(Q,a,"8sint",1)[0]];case"rg8unorm":{const D=cA(Q,a,"8unorm",2);return[D[0],D[1]]}case"rg8snorm":{const D=cA(Q,a,"8snorm",2);return[D[0],D[1]]}case"rg8uint":{const D=cA(Q,a,"8uint",2);return[D[0],D[1]]}case"rg8sint":{const D=cA(Q,a,"8sint",2);return[D[0],D[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const D=cA(Q,a,"8unorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8snorm":{const D=cA(Q,a,"8snorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8uint":{const D=cA(Q,a,"8uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba8sint":{const D=cA(Q,a,"8sint",4);return[D[0],D[1],D[2],D[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const D=cA(Q,a,"8unorm",4);return[D[2],D[1],D[0],D[3]]}case"r16uint":return[cA(Q,a,"16uint",1)[0]];case"r16sint":return[cA(Q,a,"16sint",1)[0]];case"r16float":return[cA(Q,a,"16float",1)[0]];case"rg16uint":{const D=cA(Q,a,"16uint",2);return[D[0],D[1]]}case"rg16sint":{const D=cA(Q,a,"16sint",2);return[D[0],D[1]]}case"rg16float":{const D=cA(Q,a,"16float",2);return[D[0],D[1]]}case"rgba16uint":{const D=cA(Q,a,"16uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16sint":{const D=cA(Q,a,"16sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16float":{const D=cA(Q,a,"16float",4);return[D[0],D[1],D[2],D[3]]}case"r32uint":return[cA(Q,a,"32uint",1)[0]];case"r32sint":return[cA(Q,a,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[cA(Q,a,"32float",1)[0]];case"rg32uint":{const D=cA(Q,a,"32uint",2);return[D[0],D[1]]}case"rg32sint":{const D=cA(Q,a,"32sint",2);return[D[0],D[1]]}case"rg32float":{const D=cA(Q,a,"32float",2);return[D[0],D[1]]}case"rgba32uint":{const D=cA(Q,a,"32uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32sint":{const D=cA(Q,a,"32sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32float":{const D=cA(Q,a,"32float",4);return[D[0],D[1],D[2],D[3]]}case"rg11b10ufloat":{const D=new Uint32Array(Q.buffer,a,1)[0],s=(4192256&D)>>11,y=(4290772992&D)>>22;return[wE(2047&D),wE(s),(function(e){const Y=112+(e>>5&31)<<23|(31&e)<<18;return HQ[0]=Y,GE[0]})(y),1]}}return null}function cA(Q,A,I,g){const B=[0,0,0,0];for(let C=0;C<g;++C)switch(I){case"8unorm":B[C]=Q[A]/255,A++;break;case"8snorm":B[C]=Q[A]/255*2-1,A++;break;case"8uint":B[C]=Q[A],A++;break;case"8sint":B[C]=Q[A]-127,A++;break;case"16uint":B[C]=Q[A]|Q[A+1]<<8,A+=2;break;case"16sint":B[C]=(Q[A]|Q[A+1]<<8)-32768,A+=2;break;case"16float":B[C]=ma(Q[A]|Q[A+1]<<8),A+=2;break;case"32uint":case"32sint":B[C]=Q[A]|Q[A+1]<<8|Q[A+2]<<16|Q[A+3]<<24,A+=4;break;case"32float":B[C]=new Float32Array(Q.buffer,A,1)[0],A+=4}return B}function UA(Q,A,I,g,B){for(let C=0;C<g;++C)switch(I){case"8unorm":Q[A]=255*B[C],A++;break;case"8snorm":Q[A]=.5*(B[C]+1)*255,A++;break;case"8uint":Q[A]=B[C],A++;break;case"8sint":Q[A]=B[C]+127,A++;break;case"16uint":new Uint16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16sint":new Int16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16float":{const E=Ta(B[C]);new Uint16Array(Q.buffer,A,1)[0]=E,A+=2;break}case"32uint":new Uint32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32sint":new Int32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32float":new Float32Array(Q.buffer,A,1)[0]=B[C],A+=4}return B}const qQ={r8unorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8snorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8uint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8sint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg8unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8snorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"rgba8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8snorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},bgra8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bgra8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r16uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16float:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg16uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba16uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r32uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg32uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba32uint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32sint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32float:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rg11b10ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},stencil8:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!1,hasStencil:!0,channels:1},depth16unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},depth24plus:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,depthOnlyFormat:"depth32float",channels:1},"depth24plus-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,depthOnlyFormat:"depth32float",channels:1},depth32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},"depth32float-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,stencilOnlyFormat:"depth32float",channels:1},rgb9e5ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bc1-rgba-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc1-rgba-unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc4-r-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc4-r-snorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc5-rg-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc5-rg-snorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc6h-rgb-ufloat":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc6h-rgb-float":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"eac-r11unorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-r11snorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-rg11unorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"eac-rg11snorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"astc-4x4-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-4x4-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x5-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-5x5-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x6-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-6x6-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-8x5-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x5-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x6-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x6-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x8-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-8x8-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-10x5-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x5-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x6-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x6-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x8-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x8-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x10-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-10x10-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x12-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4},"astc-12x12-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4}};class FI{constructor(){this.id=FI._id++,this.line=0}get isAstNode(){return!0}get astNodeType(){return""}search(A){A(this)}searchBlock(A,I){if(A){I(qB.instance);for(const g of A)g instanceof Array?this.searchBlock(g,I):g.search(I);I(lB.instance)}}constEvaluate(A,I){throw new Error("Cannot evaluate node")}constEvaluateString(A){var I,g;return(g=(I=this.constEvaluate(A))===null||I===void 0?void 0:I.toString())!==null&&g!==void 0?g:""}}FI._id=0;class qB extends FI{}qB.instance=new qB;class lB extends FI{}lB.instance=new lB;const FE=new Set(["all","any","select","arrayLength","abs","acos","acosh","asin","asinh","atan","atanh","atan2","ceil","clamp","cos","cosh","countLeadingZeros","countOneBits","countTrailingZeros","cross","degrees","determinant","distance","dot","dot4U8Packed","dot4I8Packed","exp","exp2","extractBits","faceForward","firstLeadingBit","firstTrailingBit","floor","fma","fract","frexp","insertBits","inverseSqrt","ldexp","length","log","log2","max","min","mix","modf","normalize","pow","quantizeToF16","radians","reflect","refract","reverseBits","round","saturate","sign","sin","sinh","smoothstep","sqrt","step","tan","tanh","transpose","trunc","dpdx","dpdxCoarse","dpdxFine","dpdy","dpdyCoarse","dpdyFine","fwidth","fwidthCoarse","fwidthFine","textureDimensions","textureGather","textureGatherCompare","textureLoad","textureNumLayers","textureNumLevels","textureNumSamples","textureSample","textureSampleBias","textureSampleCompare","textureSampleCompareLevel","textureSampleGrad","textureSampleLevel","textureSampleBaseClampToEdge","textureStore","atomicLoad","atomicStore","atomicAdd","atomicSub","atomicMax","atomicMin","atomicAnd","atomicOr","atomicXor","atomicExchange","atomicCompareExchangeWeak","pack4x8snorm","pack4x8unorm","pack4xI8","pack4xU8","pack4x8Clamp","pack4xU8Clamp","pack2x16snorm","pack2x16unorm","pack2x16float","unpack4x8snorm","unpack4x8unorm","unpack4xI8","unpack4xU8","unpack2x16snorm","unpack2x16unorm","unpack2x16float","storageBarrier","textureBarrier","workgroupBarrier","workgroupUniformLoad","subgroupAdd","subgroupExclusiveAdd","subgroupInclusiveAdd","subgroupAll","subgroupAnd","subgroupAny","subgroupBallot","subgroupBroadcast","subgroupBroadcastFirst","subgroupElect","subgroupMax","subgroupMin","subgroupMul","subgroupExclusiveMul","subgroupInclusiveMul","subgroupOr","subgroupShuffle","subgroupShuffleDown","subgroupShuffleUp","subgroupShuffleXor","subgroupXor","quadBroadcast","quadSwapDiagonal","quadSwapX","quadSwapY"]);class qA extends FI{}class EB extends qA{constructor(A,I,g,B,C,E){super(),this.calls=new Set,this.name=A,this.args=I,this.returnType=g,this.body=B,this.startLine=C,this.endLine=E}get astNodeType(){return"function"}search(A){if(this.attributes)for(const I of this.attributes)A(I);A(this);for(const I of this.args)A(I);this.searchBlock(this.body,A)}}class eE extends qA{constructor(A){super(),this.expression=A}get astNodeType(){return"staticAssert"}search(A){this.expression.search(A)}}class rE extends qA{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"while"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class lQ extends qA{constructor(A,I){super(),this.body=A,this.loopId=I}get astNodeType(){return"continuing"}search(A){this.searchBlock(this.body,A)}}class nE extends qA{constructor(A,I,g,B){super(),this.init=A,this.condition=I,this.increment=g,this.body=B}get astNodeType(){return"for"}search(A){var I,g,B;(I=this.init)===null||I===void 0||I.search(A),(g=this.condition)===null||g===void 0||g.search(A),(B=this.increment)===null||B===void 0||B.search(A),this.searchBlock(this.body,A)}}class YI extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"var"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class fQ extends qA{constructor(A,I,g){super(),this.attributes=null,this.name=A,this.type=I,this.value=g}get astNodeType(){return"override"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class iB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"let"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class fB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"const"}constEvaluate(A,I){return this.value.constEvaluate(A,I)}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}var Jg,oB,M,R;(Q=>{Q.increment="++",Q.decrement="--"})(Jg||(Jg={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for IncrementOperator");return Q[I]}})(Jg||(Jg={}));class SE extends qA{constructor(A,I){super(),this.operator=A,this.variable=I}get astNodeType(){return"increment"}search(A){this.variable.search(A)}}(Q=>{Q.assign="=",Q.addAssign="+=",Q.subtractAssign="-=",Q.multiplyAssign="*=",Q.divideAssign="/=",Q.moduloAssign="%=",Q.andAssign="&=",Q.orAssign="|=",Q.xorAssign="^=",Q.shiftLeftAssign="<<=",Q.shiftRightAssign=">>="})(oB||(oB={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for AssignOperator");return I}})(oB||(oB={}));class NE extends qA{constructor(A,I,g){super(),this.operator=A,this.variable=I,this.value=g}get astNodeType(){return"assign"}search(A){this.variable.search(A),this.value.search(A)}}class pQ extends qA{constructor(A,I){super(),this.name=A,this.args=I}get astNodeType(){return"call"}isBuiltin(){return FE.has(this.name)}search(A){for(const I of this.args)I.search(A);A(this)}}class RE extends qA{constructor(A,I){super(),this.body=A,this.continuing=I}get astNodeType(){return"loop"}search(A){var I;this.searchBlock(this.body,A),(I=this.continuing)===null||I===void 0||I.search(A)}}class cE extends qA{constructor(A,I){super(),this.condition=A,this.cases=I}get astNodeType(){return"switch"}search(A){A(this);for(const I of this.cases)I.search(A)}}class UE extends qA{constructor(A,I,g,B){super(),this.condition=A,this.body=I,this.elseif=g,this.else=B}get astNodeType(){return"if"}search(A){this.condition.search(A),this.searchBlock(this.body,A),this.searchBlock(this.elseif,A),this.searchBlock(this.else,A)}}class kE extends qA{constructor(A){super(),this.value=A}get astNodeType(){return"return"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class ba extends qA{constructor(A){super(),this.name=A}get astNodeType(){return"enable"}}class Za extends qA{constructor(A){super(),this.extensions=A}get astNodeType(){return"requires"}}class LE extends qA{constructor(A,I){super(),this.severity=A,this.rule=I}get astNodeType(){return"diagnostic"}}class uQ extends qA{constructor(A,I){super(),this.name=A,this.type=I}get astNodeType(){return"alias"}}class Pa extends qA{get astNodeType(){return"discard"}}class JE extends qA{constructor(){super(...arguments),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class YE extends qA{constructor(){super(...arguments),this.loopId=-1}get astNodeType(){return"continue"}}class f extends qA{constructor(A){super(),this.attributes=null,this.name=A}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(A){let I=A[0];if(I.name==="f32")return I;for(let g=1;g<A.length;++g){const B=f._priority.get(I.name);f._priority.get(A[g].name)<B&&(I=A[g])}return I.name==="x32"?f.i32:I}getTypeName(){return this.name}}f.x32=new f("x32"),f.f32=new f("f32"),f.i32=new f("i32"),f.u32=new f("u32"),f.f16=new f("f16"),f.bool=new f("bool"),f.void=new f("void"),f._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class KE extends f{constructor(A){super(A)}}class lI extends f{constructor(A,I,g,B){super(A),this.members=I,this.startLine=g,this.endLine=B}get astNodeType(){return"struct"}get isStruct(){return!0}getMemberIndex(A){for(let I=0;I<this.members.length;I++)if(this.members[I].name===A)return I;return-1}search(A){for(const I of this.members)A(I)}}class L extends f{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"template"}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}L.vec2f=new L("vec2",f.f32,null),L.vec3f=new L("vec3",f.f32,null),L.vec4f=new L("vec4",f.f32,null),L.vec2i=new L("vec2",f.i32,null),L.vec3i=new L("vec3",f.i32,null),L.vec4i=new L("vec4",f.i32,null),L.vec2u=new L("vec2",f.u32,null),L.vec3u=new L("vec3",f.u32,null),L.vec4u=new L("vec4",f.u32,null),L.vec2h=new L("vec2",f.f16,null),L.vec3h=new L("vec3",f.f16,null),L.vec4h=new L("vec4",f.f16,null),L.vec2b=new L("vec2",f.bool,null),L.vec3b=new L("vec3",f.bool,null),L.vec4b=new L("vec4",f.bool,null),L.mat2x2f=new L("mat2x2",f.f32,null),L.mat2x3f=new L("mat2x3",f.f32,null),L.mat2x4f=new L("mat2x4",f.f32,null),L.mat3x2f=new L("mat3x2",f.f32,null),L.mat3x3f=new L("mat3x3",f.f32,null),L.mat3x4f=new L("mat3x4",f.f32,null),L.mat4x2f=new L("mat4x2",f.f32,null),L.mat4x3f=new L("mat4x3",f.f32,null),L.mat4x4f=new L("mat4x4",f.f32,null),L.mat2x2h=new L("mat2x2",f.f16,null),L.mat2x3h=new L("mat2x3",f.f16,null),L.mat2x4h=new L("mat2x4",f.f16,null),L.mat3x2h=new L("mat3x2",f.f16,null),L.mat3x3h=new L("mat3x3",f.f16,null),L.mat3x4h=new L("mat3x4",f.f16,null),L.mat4x2h=new L("mat4x2",f.f16,null),L.mat4x3h=new L("mat4x3",f.f16,null),L.mat4x4h=new L("mat4x4",f.f16,null),L.mat2x2i=new L("mat2x2",f.i32,null),L.mat2x3i=new L("mat2x3",f.i32,null),L.mat2x4i=new L("mat2x4",f.i32,null),L.mat3x2i=new L("mat3x2",f.i32,null),L.mat3x3i=new L("mat3x3",f.i32,null),L.mat3x4i=new L("mat3x4",f.i32,null),L.mat4x2i=new L("mat4x2",f.i32,null),L.mat4x3i=new L("mat4x3",f.i32,null),L.mat4x4i=new L("mat4x4",f.i32,null),L.mat2x2u=new L("mat2x2",f.u32,null),L.mat2x3u=new L("mat2x3",f.u32,null),L.mat2x4u=new L("mat2x4",f.u32,null),L.mat3x2u=new L("mat3x2",f.u32,null),L.mat3x3u=new L("mat3x3",f.u32,null),L.mat3x4u=new L("mat3x4",f.u32,null),L.mat4x2u=new L("mat4x2",f.u32,null),L.mat4x3u=new L("mat4x3",f.u32,null),L.mat4x4u=new L("mat4x4",f.u32,null);class pB extends f{constructor(A,I,g,B){super(A),this.storage=I,this.type=g,this.access=B}get astNodeType(){return"pointer"}}class aB extends f{constructor(A,I,g,B){super(A),this.attributes=I,this.format=g,this.count=B}get astNodeType(){return"array"}get isArray(){return!0}}class DB extends f{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"sampler"}}class NI extends FI{constructor(){super(),this.postfix=null,this.hasParen=!1}}class Eg extends NI{constructor(A){super(),this.value=A}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class KI extends NI{constructor(A,I){super(),this.type=A,this.args=I}get astNodeType(){return"createExpr"}search(A){if(A(this),this.args)for(const I of this.args)I.search(A)}constEvaluate(A,I){return I&&(I[0]=this.type),A.evalExpression(this,A.context)}}class mQ extends NI{constructor(A,I){super(),this.cachedReturnValue=null,this.name=A,this.args=I}get astNodeType(){return"callExpr"}setCachedReturnValue(A){this.cachedReturnValue=A}get isBuiltin(){return FE.has(this.name)}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){for(const I of this.args)I.search(A);A(this)}}class CI extends NI{constructor(A){super(),this.name=A}get astNodeType(){return"varExpr"}search(A){A(this),this.postfix&&this.postfix.search(A)}constEvaluate(A,I){return A.evalExpression(this,A.context)}}class ME extends NI{constructor(A,I){super(),this.name=A,this.initializer=I}get astNodeType(){return"constExpr"}constEvaluate(A,I){const g=A.evalExpression(this.initializer,A.context);return g!==null&&this.postfix?g.getSubData(A,this.postfix,A.context):g}search(A){this.initializer.search(A)}}class vA extends NI{constructor(A,I){super(),this.value=A,this.type=I}get astNodeType(){return"literalExpr"}constEvaluate(A,I){return I!==void 0&&(I[0]=this.type),this.value}get isScalar(){return this.value instanceof U}get isVector(){return this.value instanceof F||this.value instanceof EA}get scalarValue(){return this.value instanceof U?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof F||this.value instanceof EA?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class dE extends NI{constructor(A,I){super(),this.type=A,this.value=I}get astNodeType(){return"bitcastExpr"}search(A){this.value.search(A)}}class Yg extends NI{constructor(A){super(),this.index=A}search(A){this.index.search(A)}}class HE extends NI{constructor(){super()}}class TA extends HE{constructor(A,I){super(),this.operator=A,this.right=I}get astNodeType(){return"unaryOp"}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.right.search(A)}}class RI extends HE{constructor(A,I,g){super(),this.operator=A,this.left=I,this.right=g}get astNodeType(){return"binaryOp"}_getPromotedType(A,I){return A.name===I.name?A:A.name==="f32"||I.name==="f32"?f.f32:A.name==="u32"||I.name==="u32"?f.u32:f.i32}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.left.search(A),this.right.search(A)}}class qE extends FI{constructor(A){super(),this.body=A}search(A){A(this),this.searchBlock(this.body,A)}}class uB extends NI{get astNodeType(){return"default"}}class lE extends qE{constructor(A,I){super(I),this.selectors=A}get astNodeType(){return"case"}search(A){this.searchBlock(this.body,A)}}class fE extends qE{constructor(A){super(A)}get astNodeType(){return"default"}search(A){this.searchBlock(this.body,A)}}class pE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"argument"}}class Va extends FI{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"elseif"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class uE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"member"}}class mE extends FI{constructor(A,I){super(),this.name=A,this.value=I}get astNodeType(){return"attribute"}}class cI{constructor(A,I){this.parent=null,this.typeInfo=A,this.parent=I,this.id=cI._id++}setDataValue(A,I,g,B){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(A,I,g){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}cI._id=0;class xE extends cI{constructor(A,I){super(A,I)}clone(){return this}toString(){return this.typeInfo.name}}class xQ extends cI{constructor(){super(new wI("void",null),null)}clone(){return this}toString(){return"void"}}xQ.void=new xQ;class Kg extends cI{constructor(A){super(new dQ("pointer",A.typeInfo,null),null),this.reference=A}clone(){return this}setDataValue(A,I,g,B){this.reference.setDataValue(A,I,g,B)}getSubData(A,I,g){return I?this.reference.getSubData(A,I,g):this}toString(){return`&${this.reference.toString()}`}}class U extends cI{constructor(A,I,g=null){super(I,g),A instanceof Int32Array||A instanceof Uint32Array||A instanceof Float32Array?this.data=A:this.typeInfo.name==="x32"?A-Math.floor(A)!==0?this.data=new Float32Array([A]):this.data=A>=0?new Uint32Array([A]):new Int32Array([A]):this.typeInfo.name==="i32"||this.typeInfo.name==="bool"?this.data=new Int32Array([A]):this.typeInfo.name==="u32"?this.data=new Uint32Array([A]):this.typeInfo.name==="f32"||this.typeInfo.name==="f16"?this.data=new Float32Array([A]):console.error("ScalarData2: Invalid type",I)}clone(){if(this.data instanceof Float32Array)return new U(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new U(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new U(new Uint32Array(this.data),this.typeInfo,null);throw new Error("ScalarData: Invalid data type")}get value(){return this.data[0]}set value(A){this.data[0]=A}setDataValue(A,I,g,B){if(g)return void console.error("SetDataValue: Scalar data does not support postfix",g);if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);let C=I.data[0];this.typeInfo.name==="i32"||this.typeInfo.name==="u32"?C=Math.floor(C):this.typeInfo.name==="bool"&&(C=C?1:0),this.data[0]=C}getSubData(A,I,g){return I?(console.error("getSubData: Scalar data does not support postfix",I),null):this}toString(){return`${this.value}`}}function Oa(Q,A,I){const g=A.length;return g===2?I==="f32"?new F(new Float32Array(A),Q.getTypeInfo("vec2f")):I==="i32"||I==="bool"?new F(new Int32Array(A),Q.getTypeInfo("vec2i")):I==="u32"?new F(new Uint32Array(A),Q.getTypeInfo("vec2u")):I==="f16"?new F(new Float32Array(A),Q.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${I}`),null):g===3?I==="f32"?new F(new Float32Array(A),Q.getTypeInfo("vec3f")):I==="i32"||I==="bool"?new F(new Int32Array(A),Q.getTypeInfo("vec3i")):I==="u32"?new F(new Uint32Array(A),Q.getTypeInfo("vec3u")):I==="f16"?new F(new Float32Array(A),Q.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${I}`),null):g===4?I==="f32"?new F(new Float32Array(A),Q.getTypeInfo("vec4f")):I==="i32"||I==="bool"?new F(new Int32Array(A),Q.getTypeInfo("vec4i")):I==="u32"?new F(new Uint32Array(A),Q.getTypeInfo("vec4u")):I==="f16"?new F(new Float32Array(A),Q.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${I}`),null):(console.error(`getSubData: Invalid vector size ${A.length}`),null)}class F extends cI{constructor(A,I,g=null){if(super(I,g),A instanceof Float32Array||A instanceof Uint32Array||A instanceof Int32Array)this.data=A;else{const B=this.typeInfo.name;B==="vec2f"||B==="vec3f"||B==="vec4f"?this.data=new Float32Array(A):B==="vec2i"||B==="vec3i"||B==="vec4i"?this.data=new Int32Array(A):B==="vec2u"||B==="vec3u"||B==="vec4u"?this.data=new Uint32Array(A):B==="vec2h"||B==="vec3h"||B==="vec4h"?this.data=new Float32Array(A):B==="vec2b"||B==="vec3b"||B==="vec4b"?this.data=new Int32Array(A):B==="vec2"||B==="vec3"||B==="vec4"?this.data=new Float32Array(A):console.error(`VectorData: Invalid type ${B}`)}}clone(){if(this.data instanceof Float32Array)return new F(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new F(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new F(new Uint32Array(this.data),this.typeInfo,null);throw new Error("VectorData: Invalid data type")}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set vector postfix"):I instanceof F?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;let B=A.getTypeInfo("f32");if(this.typeInfo instanceof Cg)B=this.typeInfo.format||B;else{const E=this.typeInfo.name;E==="vec2f"||E==="vec3f"||E==="vec4f"?B=A.getTypeInfo("f32"):E==="vec2i"||E==="vec3i"||E==="vec4i"?B=A.getTypeInfo("i32"):E==="vec2b"||E==="vec3b"||E==="vec4b"?B=A.getTypeInfo("bool"):E==="vec2u"||E==="vec3u"||E==="vec4u"?B=A.getTypeInfo("u32"):E==="vec2h"||E==="vec3h"||E==="vec4h"?B=A.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${E}`)}let C=this;for(;I!==null&&C!==null;){if(I instanceof Yg){const E=I.index;let i=-1;if(E instanceof vA){if(!(E.value instanceof U))return console.error(`GetSubData: Invalid array index ${E.value}`),null;i=E.value.value}else{const o=A.evalExpression(E,g);if(!(o instanceof U))return console.error("GetSubData: Unknown index type",E),null;i=o.value}if(i<0||i>=C.data.length)return console.error("GetSubData: Index out of range",i),null;if(C.data instanceof Float32Array){const o=new Float32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Int32Array){const o=new Int32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Uint32Array){const o=new Uint32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}throw new Error("GetSubData: Invalid data type")}if(!(I instanceof Eg))return console.error("GetSubData: Unknown postfix",I),null;{const E=I.value.toLowerCase();if(E.length===1){let o=0;if(E==="x"||E==="r")o=0;else if(E==="y"||E==="g")o=1;else if(E==="z"||E==="b")o=2;else{if(E!=="w"&&E!=="a")return console.error(`GetSubData: Unknown member ${E}`),null;o=3}if(this.data instanceof Float32Array){let a=new Float32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Int32Array){let a=new Int32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Uint32Array){let a=new Uint32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}}const i=[];for(const o of E)o==="x"||o==="r"?i.push(this.data[0]):o==="y"||o==="g"?i.push(this.data[1]):o==="z"||o==="b"?i.push(this.data[2]):o==="w"||o==="a"?i.push(this.data[3]):console.error(`GetDataValue: Unknown member ${o}`);C=Oa(A,i,B.name)}I=I.postfix}return C}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class EA extends cI{constructor(A,I,g=null){super(I,g),A instanceof Float32Array?this.data=A:this.data=new Float32Array(A)}clone(){return new EA(new Float32Array(this.data),this.typeInfo,null)}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set matrix postfix"):I instanceof EA?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;const B=this.typeInfo.name;if(A.getTypeInfo("f32"),this.typeInfo instanceof Cg)this.typeInfo.format;else if(B.endsWith("f"))A.getTypeInfo("f32");else if(B.endsWith("i"))A.getTypeInfo("i32");else if(B.endsWith("u"))A.getTypeInfo("u32");else{if(!B.endsWith("h"))return console.error(`GetDataValue: Unknown type ${B}`),null;A.getTypeInfo("f16")}if(I instanceof Yg){const C=I.index;let E=-1;if(C instanceof vA){if(!(C.value instanceof U))return console.error(`GetDataValue: Invalid array index ${C.value}`),null;E=C.value.value}else{const a=A.evalExpression(C,g);if(!(a instanceof U))return console.error("GetDataValue: Unknown index type",C),null;E=a.value}if(E<0||E>=this.data.length)return console.error("GetDataValue: Index out of range",E),null;const i=B.endsWith("h")?"h":"f";let o;if(B==="mat2x2"||B==="mat2x2f"||B==="mat2x2h"||B==="mat3x2"||B==="mat3x2f"||B==="mat3x2h"||B==="mat4x2"||B==="mat4x2f"||B==="mat4x2h")o=new F(new Float32Array(this.data.buffer,this.data.byteOffset+2*E*4,2),A.getTypeInfo(`vec2${i}`));else if(B==="mat2x3"||B==="mat2x3f"||B==="mat2x3h"||B==="mat3x3"||B==="mat3x3f"||B==="mat3x3h"||B==="mat4x3"||B==="mat4x3f"||B==="mat4x3h")o=new F(new Float32Array(this.data.buffer,this.data.byteOffset+3*E*4,3),A.getTypeInfo(`vec3${i}`));else{if(B!=="mat2x4"&&B!=="mat2x4f"&&B!=="mat2x4h"&&B!=="mat3x4"&&B!=="mat3x4f"&&B!=="mat3x4h"&&B!=="mat4x4"&&B!=="mat4x4f"&&B!=="mat4x4h")return console.error(`GetDataValue: Unknown type ${B}`),null;o=new F(new Float32Array(this.data.buffer,this.data.byteOffset+4*E*4,4),A.getTypeInfo(`vec4${i}`))}return I.postfix?o.getSubData(A,I.postfix,g):o}return console.error("GetDataValue: Invalid postfix",I),null}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class lA extends cI{constructor(A,I,g=0,B=null){super(I,B),this.buffer=A instanceof ArrayBuffer?A:A.buffer,this.offset=g}clone(){const A=new Uint8Array(new Uint8Array(this.buffer,this.offset,this.typeInfo.size));return new lA(A.buffer,this.typeInfo,0,null)}setDataValue(A,I,g,B){if(I===null)return void console.log("setDataValue: NULL data.");let C=this.offset,E=this.typeInfo;for(;g;){if(g instanceof Yg)if(E instanceof bI){const i=g.index;if(i instanceof vA){if(!(i.value instanceof U))return void console.error(`SetDataValue: Invalid index type ${i.value}`);C+=i.value.value*E.stride}else{const o=A.evalExpression(i,B);if(!(o instanceof U))return void console.error("SetDataValue: Unknown index type",i);C+=o.value*E.stride}E=E.format}else console.error(`SetDataValue: Type ${E.getTypeName()} is not an array`);else{if(!(g instanceof Eg))return void console.error("SetDataValue: Unknown postfix type",g);{const i=g.value;if(E instanceof WI){let o=!1;for(const a of E.members)if(a.name===i){C+=a.offset,E=a.type,o=!0;break}if(!o)return void console.error(`SetDataValue: Member ${i} not found`)}else if(E instanceof wI){const o=E.getTypeName();let a=0;if(i==="x"||i==="r")a=0;else if(i==="y"||i==="g")a=1;else if(i==="z"||i==="b")a=2;else{if(i!=="w"&&i!=="a")return void console.error(`SetDataValue: Unknown member ${i}`);a=3}if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);const D=I.value;return o==="vec2f"?void(new Float32Array(this.buffer,C,2)[a]=D):o==="vec3f"?void(new Float32Array(this.buffer,C,3)[a]=D):o==="vec4f"?void(new Float32Array(this.buffer,C,4)[a]=D):o==="vec2i"?void(new Int32Array(this.buffer,C,2)[a]=D):o==="vec3i"?void(new Int32Array(this.buffer,C,3)[a]=D):o==="vec4i"?void(new Int32Array(this.buffer,C,4)[a]=D):o==="vec2u"?void(new Uint32Array(this.buffer,C,2)[a]=D):o==="vec3u"?void(new Uint32Array(this.buffer,C,3)[a]=D):o==="vec4u"?void(new Uint32Array(this.buffer,C,4)[a]=D):void console.error(`SetDataValue: Type ${o} is not a struct`)}}}g=g.postfix}this.setData(A,I,E,C,B)}setData(A,I,g,B,C){const E=g.getTypeName();if(E!=="f32"&&E!=="f16")if(E!=="i32"&&E!=="atomic<i32>"&&E!=="x32")if(E!=="u32"&&E!=="atomic<u32>")if(E!=="bool"){if(E==="vec2f"||E==="vec2h"){const i=new Float32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3f"||E==="vec3h"){const i=new Float32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4f"||E==="vec4h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2i"){const i=new Int32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3i"){const i=new Int32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4i"){const i=new Int32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2u"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3u"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4u"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2b"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3b"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4b"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x2f"||E==="mat2x2h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x3f"||E==="mat2x3h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat2x4f"||E==="mat2x4h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat3x2f"||E==="mat3x2h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat3x3f"||E==="mat3x3h"){const i=new Float32Array(this.buffer,B,9);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8]))}if(E==="mat3x4f"||E==="mat3x4h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x2f"||E==="mat4x2h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat4x3f"||E==="mat4x3h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x4f"||E==="mat4x4h"){const i=new Float32Array(this.buffer,B,16);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11],i[12]=I.data[12],i[13]=I.data[13],i[14]=I.data[14],i[15]=I.data[15]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11],i[12]=I[12],i[13]=I[13],i[14]=I[14],i[15]=I[15]))}if(I instanceof lA){if(g===I.typeInfo)return void new Uint8Array(this.buffer,B,I.buffer.byteLength).set(new Uint8Array(I.buffer));console.error("SetDataValue: Type mismatch",E,I.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${E}`)}else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Uint32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Float32Array(this.buffer,B,1)[0]=I.value)}getSubData(A,I,g){var B,C,E;if(I===null)return this;let i=this.offset,o=this.typeInfo;for(;I;){if(I instanceof Yg){const D=I.index,s=D instanceof NI?A.evalExpression(D,g):D;let y=0;if(s instanceof U?y=s.value:typeof s=="number"?y=s:console.error("GetDataValue: Invalid index type",D),o instanceof bI)i+=y*o.stride,o=o.format;else{const e=o.getTypeName();e==="mat4x4"||e==="mat4x4f"||e==="mat4x4h"?(i+=16*y,o=A.getTypeInfo("vec4f")):e==="mat4x3"||e==="mat4x3f"||e==="mat4x3h"?(i+=12*y,o=A.getTypeInfo("vec3f")):e==="mat4x2"||e==="mat4x2f"||e==="mat4x2h"?(i+=8*y,o=A.getTypeInfo("vec2f")):e==="mat3x4"||e==="mat3x4f"||e==="mat3x4h"?(i+=12*y,o=A.getTypeInfo("vec4f")):e==="mat3x3"||e==="mat3x3f"||e==="mat3x3h"?(i+=9*y,o=A.getTypeInfo("vec3f")):e==="mat3x2"||e==="mat3x2f"||e==="mat3x2h"?(i+=6*y,o=A.getTypeInfo("vec2f")):e==="mat2x4"||e==="mat2x4f"||e==="mat2x4h"?(i+=8*y,o=A.getTypeInfo("vec4f")):e==="mat2x3"||e==="mat2x3f"||e==="mat2x3h"?(i+=6*y,o=A.getTypeInfo("vec3f")):e==="mat2x2"||e==="mat2x2f"||e==="mat2x2h"?(i+=4*y,o=A.getTypeInfo("vec2f")):e==="vec2f"||e==="vec3f"||e==="vec4f"?(i+=4*y,o=A.getTypeInfo("f32")):e==="vec2h"||e==="vec3h"||e==="vec4h"?(i+=2*y,o=A.getTypeInfo("f16")):e==="vec2b"||e==="vec3b"||e==="vec4b"?(i+=1*y,o=A.getTypeInfo("bool")):e==="vec2i"||e==="vec3i"||e==="vec4i"?(i+=4*y,o=A.getTypeInfo("i32")):e==="vec2u"||e==="vec3u"||e==="vec4u"?(i+=4*y,o=A.getTypeInfo("u32")):console.error(`getDataValue: Type ${o.getTypeName()} is not an array`)}}else{if(!(I instanceof Eg))return console.error("GetDataValue: Unknown postfix type",I),null;{const D=I.value;if(o instanceof WI){let s=!1;for(const y of o.members)if(y.name===D){i+=y.offset,o=y.type,s=!0;break}if(!s)return console.error(`GetDataValue: Member ${D} not found`),null}else if(o instanceof wI){const s=o.getTypeName();if(s==="vec2f"||s==="vec3f"||s==="vec4f"||s==="vec2i"||s==="vec3i"||s==="vec4i"||s==="vec2u"||s==="vec3u"||s==="vec4u"||s==="vec2b"||s==="vec3b"||s==="vec4b"||s==="vec2h"||s==="vec3h"||s==="vec4h"||s==="vec2"||s==="vec3"||s==="vec4"){if(D.length>0&&D.length<5){let y="f";const e=[];for(let Y=0;Y<D.length;++Y){const u=D[Y].toLowerCase();let H=0;if(u==="x"||u==="r")H=0;else if(u==="y"||u==="g")H=1;else if(u==="z"||u==="b")H=2;else{if(u!=="w"&&u!=="a")return console.error(`Unknown member ${D}`),null;H=3}if(D.length===1){if(s.endsWith("f"))return this.buffer.byteLength<i+4*H+4?(console.log("Insufficient buffer data"),null):new U(new Float32Array(this.buffer,i+4*H,1),A.getTypeInfo("f32"),this);if(s.endsWith("h"))return new U(new Float32Array(this.buffer,i+4*H,1),A.getTypeInfo("f16"),this);if(s.endsWith("i"))return new U(new Int32Array(this.buffer,i+4*H,1),A.getTypeInfo("i32"),this);if(s.endsWith("b"))return new U(new Int32Array(this.buffer,i+4*H,1),A.getTypeInfo("bool"),this);if(s.endsWith("u"))return new U(new Uint32Array(this.buffer,i+4*H,1),A.getTypeInfo("i32"),this)}if(s==="vec2f")e.push(new Float32Array(this.buffer,i,2)[H]);else if(s==="vec3f"){if(i+12>=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const W=new Float32Array(this.buffer,i,3);e.push(W[H])}else if(s==="vec4f")e.push(new Float32Array(this.buffer,i,4)[H]);else if(s==="vec2i")y="i",e.push(new Int32Array(this.buffer,i,2)[H]);else if(s==="vec3i")y="i",e.push(new Int32Array(this.buffer,i,3)[H]);else if(s==="vec4i")y="i",e.push(new Int32Array(this.buffer,i,4)[H]);else if(s==="vec2u"){y="u";const W=new Uint32Array(this.buffer,i,2);e.push(W[H])}else s==="vec3u"?(y="u",e.push(new Uint32Array(this.buffer,i,3)[H])):s==="vec4u"&&(y="u",e.push(new Uint32Array(this.buffer,i,4)[H]))}return e.length===2?o=A.getTypeInfo(`vec2${y}`):e.length===3?o=A.getTypeInfo(`vec3${y}`):e.length===4?o=A.getTypeInfo(`vec4${y}`):console.error(`GetDataValue: Invalid vector length ${e.length}`),new F(e,o,null)}return console.error(`GetDataValue: Unknown member ${D}`),null}return console.error(`GetDataValue: Type ${s} is not a struct`),null}}}I=I.postfix}const a=o.getTypeName();return a==="f32"?new U(new Float32Array(this.buffer,i,1),o,this):a==="i32"?new U(new Int32Array(this.buffer,i,1),o,this):a==="u32"?new U(new Uint32Array(this.buffer,i,1),o,this):a==="vec2f"?new F(new Float32Array(this.buffer,i,2),o,this):a==="vec3f"?new F(new Float32Array(this.buffer,i,3),o,this):a==="vec4f"?new F(new Float32Array(this.buffer,i,4),o,this):a==="vec2i"?new F(new Int32Array(this.buffer,i,2),o,this):a==="vec3i"?new F(new Int32Array(this.buffer,i,3),o,this):a==="vec4i"?new F(new Int32Array(this.buffer,i,4),o,this):a==="vec2u"?new F(new Uint32Array(this.buffer,i,2),o,this):a==="vec3u"?new F(new Uint32Array(this.buffer,i,3),o,this):a==="vec4u"?new F(new Uint32Array(this.buffer,i,4),o,this):o instanceof Cg&&o.name==="atomic"?((B=o.format)===null||B===void 0?void 0:B.name)==="u32"?new U(new Uint32Array(this.buffer,i,1)[0],o.format,this):((C=o.format)===null||C===void 0?void 0:C.name)==="i32"?new U(new Int32Array(this.buffer,i,1)[0],o.format,this):(console.error(`GetDataValue: Invalid atomic format ${(E=o.format)===null||E===void 0?void 0:E.name}`),null):new lA(this.buffer,o,i,this)}toArray(){const A=this.typeInfo.getTypeName();return A==="f32"||A==="f16"?new Float32Array(this.buffer,this.offset,1):A==="i32"||A==="atomic<i32>"||A==="x32"?new Int32Array(this.buffer,this.offset,1):A==="u32"||A==="atomic<u32>"?new Uint32Array(this.buffer,this.offset,1):A==="bool"?new Int32Array(this.buffer,this.offset,1):A==="vec2f"||A==="vec2h"?new Float32Array(this.buffer,this.offset,2):A==="vec3f"||A==="vec3h"?new Float32Array(this.buffer,this.offset,3):A==="vec4f"||A==="vec4h"?new Float32Array(this.buffer,this.offset,4):A==="vec2i"?new Int32Array(this.buffer,this.offset,2):A==="vec3i"?new Int32Array(this.buffer,this.offset,3):A==="vec4i"?new Int32Array(this.buffer,this.offset,4):A==="vec2u"?new Uint32Array(this.buffer,this.offset,2):A==="vec3u"?new Uint32Array(this.buffer,this.offset,3):A==="vec4u"?new Uint32Array(this.buffer,this.offset,4):A==="vec2b"?new Uint32Array(this.buffer,this.offset,2):A==="vec3b"?new Uint32Array(this.buffer,this.offset,3):A==="vec4b"?new Uint32Array(this.buffer,this.offset,4):A==="mat2x2f"||A==="mat2x2h"?new Float32Array(this.buffer,this.offset,4):A==="mat2x3f"||A==="mat2x3h"?new Float32Array(this.buffer,this.offset,6):A==="mat2x4f"||A==="mat2x4h"?new Float32Array(this.buffer,this.offset,8):A==="mat3x2f"||A==="mat3x2h"?new Float32Array(this.buffer,this.offset,6):A==="mat3x3f"||A==="mat3x3h"?new Float32Array(this.buffer,this.offset,9):A==="mat3x4f"||A==="mat3x4h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x2f"||A==="mat4x2h"?new Float32Array(this.buffer,this.offset,8):A==="mat4x3f"||A==="mat4x3h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x4f"||A==="mat4x4h"?new Float32Array(this.buffer,this.offset,16):null}toString(){let A="";if(this.typeInfo instanceof bI)if(this.typeInfo.format.name==="f32"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="i32"){const I=new Int32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="u32"){const I=new Uint32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="vec2f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}]`;for(let g=1;g<I.length/2;++g)A+=`, [${I[2*g]}, ${I[2*g+1]}]`}else if(this.typeInfo.format.name==="vec3f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}]`}else if(this.typeInfo.format.name==="vec4f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}, ${I[3]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}, ${I[g+3]}]`}else A="[...]";else this.typeInfo instanceof WI?A+="{...}":A="[...]";return A}}class fI extends cI{constructor(A,I,g,B){super(I,null),this.data=A,this.descriptor=g,this.view=B}clone(){return new fI(this.data,this.typeInfo,this.descriptor,this.view)}get width(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>0?(A=g[0])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.width)!==null&&I!==void 0?I:0}get height(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>1?(A=g[1])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.height)!==null&&I!==void 0?I:0}get depthOrArrayLayers(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>2?(A=g[2])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.depthOrArrayLayers)!==null&&I!==void 0?I:0}get format(){var A;return this.descriptor&&(A=this.descriptor.format)!==null&&A!==void 0?A:"rgba8unorm"}get sampleCount(){var A;return this.descriptor&&(A=this.descriptor.sampleCount)!==null&&A!==void 0?A:1}get mipLevelCount(){var A;return this.descriptor&&(A=this.descriptor.mipLevelCount)!==null&&A!==void 0?A:1}get dimension(){var A;return this.descriptor&&(A=this.descriptor.dimension)!==null&&A!==void 0?A:"2d"}getMipLevelSize(A){if(A>=this.mipLevelCount)return[0,0,0];const I=[this.width,this.height,this.depthOrArrayLayers];for(let g=0;g<I.length;++g)I[g]=Math.max(1,I[g]>>A);return I}get texelByteSize(){const A=this.format,I=qQ[A];return I?I.isDepthStencil?4:I.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const A=this.format,I=qQ[A];return!!I&&I.isDepthStencil}getGpuSize(){const A=this.format,I=qQ[A],g=this.width;if(!A||g<=0||!I)return-1;const B=this.height,C=this.depthOrArrayLayers,E=this.dimension;return g/I.blockWidth*(E==="1d"?1:B/I.blockHeight)*I.bytesPerBlock*C}getPixel(A,I,g=0,B=0){const C=this.texelByteSize,E=this.bytesPerRow,i=this.height,o=this.data[B];return Wa(new Uint8Array(o),A,I,g,B,i,E,C,this.format)}setPixel(A,I,g,B,C){const E=this.texelByteSize,i=this.bytesPerRow,o=this.height,a=this.data[B];(function(D,s,y,e,Y,u,H,W,z,x){const l=e*(H>>=Y)*(u>>=Y)+y*H+s*W;switch(z){case"r8unorm":return void UA(D,l,"8unorm",1,x);case"r8snorm":return void UA(D,l,"8snorm",1,x);case"r8uint":return void UA(D,l,"8uint",1,x);case"r8sint":return void UA(D,l,"8sint",1,x);case"rg8unorm":return void UA(D,l,"8unorm",2,x);case"rg8snorm":return void UA(D,l,"8snorm",2,x);case"rg8uint":return void UA(D,l,"8uint",2,x);case"rg8sint":return void UA(D,l,"8sint",2,x);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void UA(D,l,"8unorm",4,x);case"rgba8snorm":return void UA(D,l,"8snorm",4,x);case"rgba8uint":return void UA(D,l,"8uint",4,x);case"rgba8sint":return void UA(D,l,"8sint",4,x);case"r16uint":return void UA(D,l,"16uint",1,x);case"r16sint":return void UA(D,l,"16sint",1,x);case"r16float":return void UA(D,l,"16float",1,x);case"rg16uint":return void UA(D,l,"16uint",2,x);case"rg16sint":return void UA(D,l,"16sint",2,x);case"rg16float":return void UA(D,l,"16float",2,x);case"rgba16uint":return void UA(D,l,"16uint",4,x);case"rgba16sint":return void UA(D,l,"16sint",4,x);case"rgba16float":return void UA(D,l,"16float",4,x);case"r32uint":return void UA(D,l,"32uint",1,x);case"r32sint":return void UA(D,l,"32sint",1,x);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void UA(D,l,"32float",1,x);case"rg32uint":return void UA(D,l,"32uint",2,x);case"rg32sint":return void UA(D,l,"32sint",2,x);case"rg32float":return void UA(D,l,"32float",2,x);case"rgba32uint":return void UA(D,l,"32uint",4,x);case"rgba32sint":return void UA(D,l,"32sint",4,x);case"rgba32float":return void UA(D,l,"32float",4,x);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}})(new Uint8Array(a),A,I,g,B,o,i,E,this.format,C)}}(Q=>{Q[Q.token=0]="token",Q[Q.keyword=1]="keyword",Q[Q.reserved=2]="reserved"})(R||(R={}));class c{constructor(A,I,g){this.name=A,this.type=I,this.rule=g}toString(){return this.name}}class t{}M=t,t.none=new c("",R.reserved,""),t.eof=new c("EOF",R.token,""),t.reserved={asm:new c("asm",R.reserved,"asm"),bf16:new c("bf16",R.reserved,"bf16"),do:new c("do",R.reserved,"do"),enum:new c("enum",R.reserved,"enum"),f16:new c("f16",R.reserved,"f16"),f64:new c("f64",R.reserved,"f64"),handle:new c("handle",R.reserved,"handle"),i8:new c("i8",R.reserved,"i8"),i16:new c("i16",R.reserved,"i16"),i64:new c("i64",R.reserved,"i64"),mat:new c("mat",R.reserved,"mat"),premerge:new c("premerge",R.reserved,"premerge"),regardless:new c("regardless",R.reserved,"regardless"),typedef:new c("typedef",R.reserved,"typedef"),u8:new c("u8",R.reserved,"u8"),u16:new c("u16",R.reserved,"u16"),u64:new c("u64",R.reserved,"u64"),unless:new c("unless",R.reserved,"unless"),using:new c("using",R.reserved,"using"),vec:new c("vec",R.reserved,"vec"),void:new c("void",R.reserved,"void")},t.keywords={array:new c("array",R.keyword,"array"),atomic:new c("atomic",R.keyword,"atomic"),bool:new c("bool",R.keyword,"bool"),f32:new c("f32",R.keyword,"f32"),i32:new c("i32",R.keyword,"i32"),mat2x2:new c("mat2x2",R.keyword,"mat2x2"),mat2x3:new c("mat2x3",R.keyword,"mat2x3"),mat2x4:new c("mat2x4",R.keyword,"mat2x4"),mat3x2:new c("mat3x2",R.keyword,"mat3x2"),mat3x3:new c("mat3x3",R.keyword,"mat3x3"),mat3x4:new c("mat3x4",R.keyword,"mat3x4"),mat4x2:new c("mat4x2",R.keyword,"mat4x2"),mat4x3:new c("mat4x3",R.keyword,"mat4x3"),mat4x4:new c("mat4x4",R.keyword,"mat4x4"),ptr:new c("ptr",R.keyword,"ptr"),sampler:new c("sampler",R.keyword,"sampler"),sampler_comparison:new c("sampler_comparison",R.keyword,"sampler_comparison"),struct:new c("struct",R.keyword,"struct"),texture_1d:new c("texture_1d",R.keyword,"texture_1d"),texture_2d:new c("texture_2d",R.keyword,"texture_2d"),texture_2d_array:new c("texture_2d_array",R.keyword,"texture_2d_array"),texture_3d:new c("texture_3d",R.keyword,"texture_3d"),texture_cube:new c("texture_cube",R.keyword,"texture_cube"),texture_cube_array:new c("texture_cube_array",R.keyword,"texture_cube_array"),texture_multisampled_2d:new c("texture_multisampled_2d",R.keyword,"texture_multisampled_2d"),texture_storage_1d:new c("texture_storage_1d",R.keyword,"texture_storage_1d"),texture_storage_2d:new c("texture_storage_2d",R.keyword,"texture_storage_2d"),texture_storage_2d_array:new c("texture_storage_2d_array",R.keyword,"texture_storage_2d_array"),texture_storage_3d:new c("texture_storage_3d",R.keyword,"texture_storage_3d"),texture_depth_2d:new c("texture_depth_2d",R.keyword,"texture_depth_2d"),texture_depth_2d_array:new c("texture_depth_2d_array",R.keyword,"texture_depth_2d_array"),texture_depth_cube:new c("texture_depth_cube",R.keyword,"texture_depth_cube"),texture_depth_cube_array:new c("texture_depth_cube_array",R.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new c("texture_depth_multisampled_2d",R.keyword,"texture_depth_multisampled_2d"),texture_external:new c("texture_external",R.keyword,"texture_external"),u32:new c("u32",R.keyword,"u32"),vec2:new c("vec2",R.keyword,"vec2"),vec3:new c("vec3",R.keyword,"vec3"),vec4:new c("vec4",R.keyword,"vec4"),bitcast:new c("bitcast",R.keyword,"bitcast"),block:new c("block",R.keyword,"block"),break:new c("break",R.keyword,"break"),case:new c("case",R.keyword,"case"),continue:new c("continue",R.keyword,"continue"),continuing:new c("continuing",R.keyword,"continuing"),default:new c("default",R.keyword,"default"),diagnostic:new c("diagnostic",R.keyword,"diagnostic"),discard:new c("discard",R.keyword,"discard"),else:new c("else",R.keyword,"else"),enable:new c("enable",R.keyword,"enable"),fallthrough:new c("fallthrough",R.keyword,"fallthrough"),false:new c("false",R.keyword,"false"),fn:new c("fn",R.keyword,"fn"),for:new c("for",R.keyword,"for"),function:new c("function",R.keyword,"function"),if:new c("if",R.keyword,"if"),let:new c("let",R.keyword,"let"),const:new c("const",R.keyword,"const"),loop:new c("loop",R.keyword,"loop"),while:new c("while",R.keyword,"while"),private:new c("private",R.keyword,"private"),read:new c("read",R.keyword,"read"),read_write:new c("read_write",R.keyword,"read_write"),return:new c("return",R.keyword,"return"),requires:new c("requires",R.keyword,"requires"),storage:new c("storage",R.keyword,"storage"),immediate:new c("immediate",R.keyword,"immediate"),switch:new c("switch",R.keyword,"switch"),true:new c("true",R.keyword,"true"),alias:new c("alias",R.keyword,"alias"),type:new c("type",R.keyword,"type"),uniform:new c("uniform",R.keyword,"uniform"),var:new c("var",R.keyword,"var"),override:new c("override",R.keyword,"override"),workgroup:new c("workgroup",R.keyword,"workgroup"),write:new c("write",R.keyword,"write"),r8unorm:new c("r8unorm",R.keyword,"r8unorm"),r8snorm:new c("r8snorm",R.keyword,"r8snorm"),r8uint:new c("r8uint",R.keyword,"r8uint"),r8sint:new c("r8sint",R.keyword,"r8sint"),r16uint:new c("r16uint",R.keyword,"r16uint"),r16sint:new c("r16sint",R.keyword,"r16sint"),r16float:new c("r16float",R.keyword,"r16float"),rg8unorm:new c("rg8unorm",R.keyword,"rg8unorm"),rg8snorm:new c("rg8snorm",R.keyword,"rg8snorm"),rg8uint:new c("rg8uint",R.keyword,"rg8uint"),rg8sint:new c("rg8sint",R.keyword,"rg8sint"),r32uint:new c("r32uint",R.keyword,"r32uint"),r32sint:new c("r32sint",R.keyword,"r32sint"),r32float:new c("r32float",R.keyword,"r32float"),rg16uint:new c("rg16uint",R.keyword,"rg16uint"),rg16sint:new c("rg16sint",R.keyword,"rg16sint"),rg16float:new c("rg16float",R.keyword,"rg16float"),rgba8unorm:new c("rgba8unorm",R.keyword,"rgba8unorm"),rgba8unorm_srgb:new c("rgba8unorm_srgb",R.keyword,"rgba8unorm_srgb"),rgba8snorm:new c("rgba8snorm",R.keyword,"rgba8snorm"),rgba8uint:new c("rgba8uint",R.keyword,"rgba8uint"),rgba8sint:new c("rgba8sint",R.keyword,"rgba8sint"),bgra8unorm:new c("bgra8unorm",R.keyword,"bgra8unorm"),bgra8unorm_srgb:new c("bgra8unorm_srgb",R.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new c("rgb10a2unorm",R.keyword,"rgb10a2unorm"),rg11b10float:new c("rg11b10float",R.keyword,"rg11b10float"),rg32uint:new c("rg32uint",R.keyword,"rg32uint"),rg32sint:new c("rg32sint",R.keyword,"rg32sint"),rg32float:new c("rg32float",R.keyword,"rg32float"),rgba16uint:new c("rgba16uint",R.keyword,"rgba16uint"),rgba16sint:new c("rgba16sint",R.keyword,"rgba16sint"),rgba16float:new c("rgba16float",R.keyword,"rgba16float"),rgba32uint:new c("rgba32uint",R.keyword,"rgba32uint"),rgba32sint:new c("rgba32sint",R.keyword,"rgba32sint"),rgba32float:new c("rgba32float",R.keyword,"rgba32float"),static_assert:new c("static_assert",R.keyword,"static_assert"),const_assert:new c("const_assert",R.keyword,"const_assert")},t.tokens={decimal_float_literal:new c("decimal_float_literal",R.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new c("hex_float_literal",R.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new c("int_literal",R.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new c("uint_literal",R.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new c("name",R.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new c("ident",R.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new c("and",R.token,"&"),and_and:new c("and_and",R.token,"&&"),arrow:new c("arrow ",R.token,"->"),attr:new c("attr",R.token,"@"),forward_slash:new c("forward_slash",R.token,"/"),bang:new c("bang",R.token,"!"),bracket_left:new c("bracket_left",R.token,"["),bracket_right:new c("bracket_right",R.token,"]"),brace_left:new c("brace_left",R.token,"{"),brace_right:new c("brace_right",R.token,"}"),colon:new c("colon",R.token,":"),comma:new c("comma",R.token,","),equal:new c("equal",R.token,"="),equal_equal:new c("equal_equal",R.token,"=="),not_equal:new c("not_equal",R.token,"!="),greater_than:new c("greater_than",R.token,">"),greater_than_equal:new c("greater_than_equal",R.token,">="),shift_right:new c("shift_right",R.token,">>"),less_than:new c("less_than",R.token,"<"),less_than_equal:new c("less_than_equal",R.token,"<="),shift_left:new c("shift_left",R.token,"<<"),modulo:new c("modulo",R.token,"%"),minus:new c("minus",R.token,"-"),minus_minus:new c("minus_minus",R.token,"--"),period:new c("period",R.token,"."),plus:new c("plus",R.token,"+"),plus_plus:new c("plus_plus",R.token,"++"),or:new c("or",R.token,"|"),or_or:new c("or_or",R.token,"||"),paren_left:new c("paren_left",R.token,"("),paren_right:new c("paren_right",R.token,")"),semicolon:new c("semicolon",R.token,";"),star:new c("star",R.token,"*"),tilde:new c("tilde",R.token,"~"),underscore:new c("underscore",R.token,"_"),xor:new c("xor",R.token,"^"),plus_equal:new c("plus_equal",R.token,"+="),minus_equal:new c("minus_equal",R.token,"-="),times_equal:new c("times_equal",R.token,"*="),division_equal:new c("division_equal",R.token,"/="),modulo_equal:new c("modulo_equal",R.token,"%="),and_equal:new c("and_equal",R.token,"&="),or_equal:new c("or_equal",R.token,"|="),xor_equal:new c("xor_equal",R.token,"^="),shift_right_equal:new c("shift_right_equal",R.token,">>="),shift_left_equal:new c("shift_left_equal",R.token,"<<=")},t.simpleTokens={"@":M.tokens.attr,"{":M.tokens.brace_left,"}":M.tokens.brace_right,":":M.tokens.colon,",":M.tokens.comma,"(":M.tokens.paren_left,")":M.tokens.paren_right,";":M.tokens.semicolon},t.literalTokens={"&":M.tokens.and,"&&":M.tokens.and_and,"->":M.tokens.arrow,"/":M.tokens.forward_slash,"!":M.tokens.bang,"[":M.tokens.bracket_left,"]":M.tokens.bracket_right,"=":M.tokens.equal,"==":M.tokens.equal_equal,"!=":M.tokens.not_equal,">":M.tokens.greater_than,">=":M.tokens.greater_than_equal,">>":M.tokens.shift_right,"<":M.tokens.less_than,"<=":M.tokens.less_than_equal,"<<":M.tokens.shift_left,"%":M.tokens.modulo,"-":M.tokens.minus,"--":M.tokens.minus_minus,".":M.tokens.period,"+":M.tokens.plus,"++":M.tokens.plus_plus,"|":M.tokens.or,"||":M.tokens.or_or,"*":M.tokens.star,"~":M.tokens.tilde,_:M.tokens.underscore,"^":M.tokens.xor,"+=":M.tokens.plus_equal,"-=":M.tokens.minus_equal,"*=":M.tokens.times_equal,"/=":M.tokens.division_equal,"%=":M.tokens.modulo_equal,"&=":M.tokens.and_equal,"|=":M.tokens.or_equal,"^=":M.tokens.xor_equal,">>=":M.tokens.shift_right_equal,"<<=":M.tokens.shift_left_equal},t.regexTokens={decimal_float_literal:M.tokens.decimal_float_literal,hex_float_literal:M.tokens.hex_float_literal,int_literal:M.tokens.int_literal,uint_literal:M.tokens.uint_literal,ident:M.tokens.ident},t.storage_class=[M.keywords.function,M.keywords.private,M.keywords.workgroup,M.keywords.uniform,M.keywords.storage,M.keywords.immediate],t.access_mode=[M.keywords.read,M.keywords.write,M.keywords.read_write],t.sampler_type=[M.keywords.sampler,M.keywords.sampler_comparison],t.sampled_texture_type=[M.keywords.texture_1d,M.keywords.texture_2d,M.keywords.texture_2d_array,M.keywords.texture_3d,M.keywords.texture_cube,M.keywords.texture_cube_array],t.multisampled_texture_type=[M.keywords.texture_multisampled_2d],t.storage_texture_type=[M.keywords.texture_storage_1d,M.keywords.texture_storage_2d,M.keywords.texture_storage_2d_array,M.keywords.texture_storage_3d],t.depth_texture_type=[M.keywords.texture_depth_2d,M.keywords.texture_depth_2d_array,M.keywords.texture_depth_cube,M.keywords.texture_depth_cube_array,M.keywords.texture_depth_multisampled_2d],t.texture_external_type=[M.keywords.texture_external],t.any_texture_type=[...M.sampled_texture_type,...M.multisampled_texture_type,...M.storage_texture_type,...M.depth_texture_type,...M.texture_external_type],t.texel_format=[M.keywords.r8unorm,M.keywords.r8snorm,M.keywords.r8uint,M.keywords.r8sint,M.keywords.r16uint,M.keywords.r16sint,M.keywords.r16float,M.keywords.rg8unorm,M.keywords.rg8snorm,M.keywords.rg8uint,M.keywords.rg8sint,M.keywords.r32uint,M.keywords.r32sint,M.keywords.r32float,M.keywords.rg16uint,M.keywords.rg16sint,M.keywords.rg16float,M.keywords.rgba8unorm,M.keywords.rgba8unorm_srgb,M.keywords.rgba8snorm,M.keywords.rgba8uint,M.keywords.rgba8sint,M.keywords.bgra8unorm,M.keywords.bgra8unorm_srgb,M.keywords.rgb10a2unorm,M.keywords.rg11b10float,M.keywords.rg32uint,M.keywords.rg32sint,M.keywords.rg32float,M.keywords.rgba16uint,M.keywords.rgba16sint,M.keywords.rgba16float,M.keywords.rgba32uint,M.keywords.rgba32sint,M.keywords.rgba32float],t.const_literal=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.keywords.true,M.keywords.false],t.literal_or_ident=[M.tokens.ident,M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.tokens.name],t.element_count_expression=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.ident],t.template_types=[M.keywords.vec2,M.keywords.vec3,M.keywords.vec4,M.keywords.mat2x2,M.keywords.mat2x3,M.keywords.mat2x4,M.keywords.mat3x2,M.keywords.mat3x3,M.keywords.mat3x4,M.keywords.mat4x2,M.keywords.mat4x3,M.keywords.mat4x4,M.keywords.atomic,M.keywords.bitcast,...M.any_texture_type],t.attribute_name=[M.tokens.ident,M.keywords.block,M.keywords.diagnostic],t.assignment_operators=[M.tokens.equal,M.tokens.plus_equal,M.tokens.minus_equal,M.tokens.times_equal,M.tokens.division_equal,M.tokens.modulo_equal,M.tokens.and_equal,M.tokens.or_equal,M.tokens.xor_equal,M.tokens.shift_right_equal,M.tokens.shift_left_equal],t.increment_operators=[M.tokens.plus_plus,M.tokens.minus_minus];class TE{constructor(A,I,g,B,C){this.type=A,this.lexeme=I,this.line=g,this.start=B,this.end=C}toString(){return this.lexeme}isTemplateType(){return t.template_types.includes(this.type)}isArrayType(){return this.type===t.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class mB{constructor(A){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=A??""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new TE(t.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let A=this._advance();if(A==`
|
|
421
|
+
${B}`;return Q.replace(wQ,C)}const MB={};function jC(Q){const A=Q??"";return MB[A]=(MB[A]??0)+1,Q?`${Q}-${MB[A]}`:String(MB[A])}class FQ{id=jC()}var JA=1e-6,OA=typeof Float32Array<"u"?Float32Array:Array,Mo=Math.PI/180;function Ho(Q){return Q*Mo}function zC(){var Q=new OA(9);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[5]=0,Q[6]=0,Q[7]=0),Q[0]=1,Q[4]=1,Q[8]=1,Q}function qo(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[4],Q[4]=A[5],Q[5]=A[6],Q[6]=A[8],Q[7]=A[9],Q[8]=A[10],Q}function hI(){var Q=new OA(16);return OA!=Float32Array&&(Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0),Q[0]=1,Q[5]=1,Q[10]=1,Q[15]=1,Q}function lo(Q,A,I,g,B,C,E,i,o,a,D,s,y,e,Y,u){var H=new OA(16);return H[0]=Q,H[1]=A,H[2]=I,H[3]=g,H[4]=B,H[5]=C,H[6]=E,H[7]=i,H[8]=o,H[9]=a,H[10]=D,H[11]=s,H[12]=y,H[13]=e,H[14]=Y,H[15]=u,H}function dB(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=A[4],i=A[5],o=A[6],a=A[7],D=A[8],s=A[9],y=A[10],e=A[11],Y=A[12],u=A[13],H=A[14],W=A[15],z=I*i-g*E,x=I*o-B*E,l=I*a-C*E,Z=g*o-B*i,v=g*a-C*i,CA=B*a-C*o,sA=D*u-s*Y,DA=D*H-y*Y,yA=D*W-e*Y,wA=s*H-y*u,zA=s*W-e*u,uA=y*W-e*H,NA=z*uA-x*zA+l*wA+Z*yA-v*DA+CA*sA;return NA?(NA=1/NA,Q[0]=(i*uA-o*zA+a*wA)*NA,Q[1]=(B*zA-g*uA-C*wA)*NA,Q[2]=(u*CA-H*v+W*Z)*NA,Q[3]=(y*v-s*CA-e*Z)*NA,Q[4]=(o*yA-E*uA-a*DA)*NA,Q[5]=(I*uA-B*yA+C*DA)*NA,Q[6]=(H*l-Y*CA-W*x)*NA,Q[7]=(D*CA-y*l+e*x)*NA,Q[8]=(E*zA-i*yA+a*sA)*NA,Q[9]=(g*yA-I*zA-C*sA)*NA,Q[10]=(Y*v-u*l+W*z)*NA,Q[11]=(s*l-D*v-e*z)*NA,Q[12]=(i*DA-E*wA-o*sA)*NA,Q[13]=(I*wA-g*DA+B*sA)*NA,Q[14]=(u*x-Y*Z-H*z)*NA,Q[15]=(D*Z-s*x+y*z)*NA,Q):null}function Rg(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=A[4],o=A[5],a=A[6],D=A[7],s=A[8],y=A[9],e=A[10],Y=A[11],u=A[12],H=A[13],W=A[14],z=A[15],x=I[0],l=I[1],Z=I[2],v=I[3];return Q[0]=x*g+l*i+Z*s+v*u,Q[1]=x*B+l*o+Z*y+v*H,Q[2]=x*C+l*a+Z*e+v*W,Q[3]=x*E+l*D+Z*Y+v*z,x=I[4],l=I[5],Z=I[6],v=I[7],Q[4]=x*g+l*i+Z*s+v*u,Q[5]=x*B+l*o+Z*y+v*H,Q[6]=x*C+l*a+Z*e+v*W,Q[7]=x*E+l*D+Z*Y+v*z,x=I[8],l=I[9],Z=I[10],v=I[11],Q[8]=x*g+l*i+Z*s+v*u,Q[9]=x*B+l*o+Z*y+v*H,Q[10]=x*C+l*a+Z*e+v*W,Q[11]=x*E+l*D+Z*Y+v*z,x=I[12],l=I[13],Z=I[14],v=I[15],Q[12]=x*g+l*i+Z*s+v*u,Q[13]=x*B+l*o+Z*y+v*H,Q[14]=x*C+l*a+Z*e+v*W,Q[15]=x*E+l*D+Z*Y+v*z,Q}function fo(Q,A){return Q[0]=A[0],Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=A[1],Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=A[2],Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,Q}function po(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=B+B,a=C+C,D=E+E,s=B*o,y=B*a,e=B*D,Y=C*a,u=C*D,H=E*D,W=i*o,z=i*a,x=i*D,l=g[0],Z=g[1],v=g[2];return Q[0]=(1-(Y+H))*l,Q[1]=(y+x)*l,Q[2]=(e-z)*l,Q[3]=0,Q[4]=(y-x)*Z,Q[5]=(1-(s+H))*Z,Q[6]=(u+W)*Z,Q[7]=0,Q[8]=(e+z)*v,Q[9]=(u-W)*v,Q[10]=(1-(s+Y))*v,Q[11]=0,Q[12]=I[0],Q[13]=I[1],Q[14]=I[2],Q[15]=1,Q}function uo(Q,A,I,g,B){var C=1/Math.tan(A/2);if(Q[0]=C/I,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=C,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[11]=-1,Q[12]=0,Q[13]=0,Q[15]=0,B!=null&&B!==1/0){var E=1/(g-B);Q[10]=(B+g)*E,Q[14]=2*B*g*E}else Q[10]=-1,Q[14]=-2*g;return Q}var mo=uo;function xo(Q,A,I,g,B,C,E){var i=1/(A-I),o=1/(g-B),a=1/(C-E);return Q[0]=-2*i,Q[1]=0,Q[2]=0,Q[3]=0,Q[4]=0,Q[5]=-2*o,Q[6]=0,Q[7]=0,Q[8]=0,Q[9]=0,Q[10]=2*a,Q[11]=0,Q[12]=(A+I)*i,Q[13]=(B+g)*o,Q[14]=(E+C)*a,Q[15]=1,Q}var To=xo;function Wo(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=g[0],o=g[1],a=g[2],D=B-I[0],s=C-I[1],y=E-I[2],e=D*D+s*s+y*y;e>0&&(e=1/Math.sqrt(e),D*=e,s*=e,y*=e);var Y=o*y-a*s,u=a*D-i*y,H=i*s-o*D;return e=Y*Y+u*u+H*H,e>0&&(e=1/Math.sqrt(e),Y*=e,u*=e,H*=e),Q[0]=Y,Q[1]=u,Q[2]=H,Q[3]=0,Q[4]=s*H-y*u,Q[5]=y*Y-D*H,Q[6]=D*u-s*Y,Q[7]=0,Q[8]=D,Q[9]=s,Q[10]=y,Q[11]=0,Q[12]=B,Q[13]=C,Q[14]=E,Q[15]=1,Q}function bo(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=Q[3],E=Q[4],i=Q[5],o=Q[6],a=Q[7],D=Q[8],s=Q[9],y=Q[10],e=Q[11],Y=Q[12],u=Q[13],H=Q[14],W=Q[15],z=A[0],x=A[1],l=A[2],Z=A[3],v=A[4],CA=A[5],sA=A[6],DA=A[7],yA=A[8],wA=A[9],zA=A[10],uA=A[11],NA=A[12],mI=A[13],kI=A[14],xI=A[15];return Math.abs(I-z)<=JA*Math.max(1,Math.abs(I),Math.abs(z))&&Math.abs(g-x)<=JA*Math.max(1,Math.abs(g),Math.abs(x))&&Math.abs(B-l)<=JA*Math.max(1,Math.abs(B),Math.abs(l))&&Math.abs(C-Z)<=JA*Math.max(1,Math.abs(C),Math.abs(Z))&&Math.abs(E-v)<=JA*Math.max(1,Math.abs(E),Math.abs(v))&&Math.abs(i-CA)<=JA*Math.max(1,Math.abs(i),Math.abs(CA))&&Math.abs(o-sA)<=JA*Math.max(1,Math.abs(o),Math.abs(sA))&&Math.abs(a-DA)<=JA*Math.max(1,Math.abs(a),Math.abs(DA))&&Math.abs(D-yA)<=JA*Math.max(1,Math.abs(D),Math.abs(yA))&&Math.abs(s-wA)<=JA*Math.max(1,Math.abs(s),Math.abs(wA))&&Math.abs(y-zA)<=JA*Math.max(1,Math.abs(y),Math.abs(zA))&&Math.abs(e-uA)<=JA*Math.max(1,Math.abs(e),Math.abs(uA))&&Math.abs(Y-NA)<=JA*Math.max(1,Math.abs(Y),Math.abs(NA))&&Math.abs(u-mI)<=JA*Math.max(1,Math.abs(u),Math.abs(mI))&&Math.abs(H-kI)<=JA*Math.max(1,Math.abs(H),Math.abs(kI))&&Math.abs(W-xI)<=JA*Math.max(1,Math.abs(W),Math.abs(xI))}function HA(){var Q=new OA(3);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q}function HI(Q){var A=new OA(3);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A}function eQ(Q){var A=Q[0],I=Q[1],g=Q[2];return Math.sqrt(A*A+I*I+g*g)}function nA(Q,A,I){var g=new OA(3);return g[0]=Q,g[1]=A,g[2]=I,g}function rQ(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q}function Bg(Q,A,I,g){return Q[0]=A,Q[1]=I,Q[2]=g,Q}function gB(Q,A,I){return Q[0]=A[0]+I[0],Q[1]=A[1]+I[1],Q[2]=A[2]+I[2],Q}function Zo(Q,A,I){return Q[0]=A[0]-I[0],Q[1]=A[1]-I[1],Q[2]=A[2]-I[2],Q}function Po(Q,A,I){return Q[0]=A[0]*I[0],Q[1]=A[1]*I[1],Q[2]=A[2]*I[2],Q}function BB(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q}function _C(Q,A,I,g){return Q[0]=A[0]+I[0]*g,Q[1]=A[1]+I[1]*g,Q[2]=A[2]+I[2]*g,Q}function $C(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1],B=A[2]-Q[2];return I*I+g*g+B*B}function Vo(Q,A){var I=A[0],g=A[1],B=A[2],C=I*I+g*g+B*B;return C>0&&(C=1/Math.sqrt(C)),Q[0]=A[0]*C,Q[1]=A[1]*C,Q[2]=A[2]*C,Q}function AE(Q,A){return Q[0]*A[0]+Q[1]*A[1]+Q[2]*A[2]}function nQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[0],i=I[1],o=I[2];return Q[0]=B*o-C*i,Q[1]=C*E-g*o,Q[2]=g*i-B*E,Q}function SQ(Q,A,I){var g=A[0],B=A[1],C=A[2],E=I[3]*g+I[7]*B+I[11]*C+I[15];return E=E||1,Q[0]=(I[0]*g+I[4]*B+I[8]*C+I[12])/E,Q[1]=(I[1]*g+I[5]*B+I[9]*C+I[13])/E,Q[2]=(I[2]*g+I[6]*B+I[10]*C+I[14])/E,Q}function Oo(Q){return Q[0]=0,Q[1]=0,Q[2]=0,Q}function NQ(Q,A){var I=Q[0],g=Q[1],B=Q[2],C=A[0],E=A[1],i=A[2];return Math.abs(I-C)<=JA*Math.max(1,Math.abs(I),Math.abs(C))&&Math.abs(g-E)<=JA*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(B-i)<=JA*Math.max(1,Math.abs(B),Math.abs(i))}var RQ=Zo,vo=eQ;(function(){var Q=HA();return function(A,I,g,B,C,E){var i,o;for(I||(I=3),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2];return A}})();function cg(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0,Q[3]=0),Q}function Xo(Q){var A=new OA(4);return A[0]=Q[0],A[1]=Q[1],A[2]=Q[2],A[3]=Q[3],A}function HB(Q,A,I,g){var B=new OA(4);return B[0]=Q,B[1]=A,B[2]=I,B[3]=g,B}function jo(Q,A){return Q[0]=A[0],Q[1]=A[1],Q[2]=A[2],Q[3]=A[3],Q}function zo(Q,A,I){return Q[0]=A[0]*I,Q[1]=A[1]*I,Q[2]=A[2]*I,Q[3]=A[3]*I,Q}function _o(Q,A){var I=A[0],g=A[1],B=A[2],C=A[3],E=I*I+g*g+B*B+C*C;return E>0&&(E=1/Math.sqrt(E)),Q[0]=I*E,Q[1]=g*E,Q[2]=B*E,Q[3]=C*E,Q}function QB(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3];return Q[0]=I[0]*g+I[4]*B+I[8]*C+I[12]*E,Q[1]=I[1]*g+I[5]*B+I[9]*C+I[13]*E,Q[2]=I[2]*g+I[6]*B+I[10]*C+I[14]*E,Q[3]=I[3]*g+I[7]*B+I[11]*C+I[15]*E,Q}(function(){var Q=cg();return function(A,I,g,B,C,E){var i,o;for(I||(I=4),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],Q[2]=A[i+2],Q[3]=A[i+3],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1],A[i+2]=Q[2],A[i+3]=Q[3];return A}})();function cQ(){var Q=new OA(4);return OA!=Float32Array&&(Q[0]=0,Q[1]=0,Q[2]=0),Q[3]=1,Q}function $o(Q,A,I){I=I*.5;var g=Math.sin(I);return Q[0]=g*A[0],Q[1]=g*A[1],Q[2]=g*A[2],Q[3]=Math.cos(I),Q}function Aa(Q,A,I){var g=A[0],B=A[1],C=A[2],E=A[3],i=I[0],o=I[1],a=I[2],D=I[3];return Q[0]=g*D+E*i+B*a-C*o,Q[1]=B*D+E*o+C*i-g*a,Q[2]=C*D+E*a+g*o-B*i,Q[3]=E*D-g*i-B*o-C*a,Q}function UQ(Q,A,I,g){var B=A[0],C=A[1],E=A[2],i=A[3],o=I[0],a=I[1],D=I[2],s=I[3],y,e,Y,u,H;return e=B*o+C*a+E*D+i*s,e<0&&(e=-e,o=-o,a=-a,D=-D,s=-s),1-e>JA?(y=Math.acos(e),Y=Math.sin(y),u=Math.sin((1-g)*y)/Y,H=Math.sin(g*y)/Y):(u=1-g,H=g),Q[0]=u*B+H*o,Q[1]=u*C+H*a,Q[2]=u*E+H*D,Q[3]=u*i+H*s,Q}function IE(Q,A){var I=A[0]+A[4]+A[8],g;if(I>0)g=Math.sqrt(I+1),Q[3]=.5*g,g=.5/g,Q[0]=(A[5]-A[7])*g,Q[1]=(A[6]-A[2])*g,Q[2]=(A[1]-A[3])*g;else{var B=0;A[4]>A[0]&&(B=1),A[8]>A[B*3+B]&&(B=2);var C=(B+1)%3,E=(B+2)%3;g=Math.sqrt(A[B*3+B]-A[C*3+C]-A[E*3+E]+1),Q[B]=.5*g,g=.5/g,Q[3]=(A[C*3+E]-A[E*3+C])*g,Q[C]=(A[C*3+B]+A[B*3+C])*g,Q[E]=(A[E*3+B]+A[B*3+E])*g}return Q}var Ia=Xo,ga=jo,kQ=_o;(function(){var Q=HA(),A=nA(1,0,0),I=nA(0,1,0);return function(g,B,C){var E=AE(B,C);return E<-.999999?(nQ(Q,A,B),vo(Q)<1e-6&&nQ(Q,I,B),Vo(Q,Q),$o(g,Q,Math.PI),g):E>.999999?(g[0]=0,g[1]=0,g[2]=0,g[3]=1,g):(nQ(Q,B,C),g[0]=Q[0],g[1]=Q[1],g[2]=Q[2],g[3]=1+E,kQ(g,g))}})(),(function(){var Q=cQ(),A=cQ();return function(I,g,B,C,E,i){return UQ(Q,g,E,i),UQ(A,B,C,i),UQ(I,Q,A,2*i*(1-i)),I}})(),(function(){var Q=zC();return function(A,I,g,B){return Q[0]=g[0],Q[3]=g[1],Q[6]=g[2],Q[1]=B[0],Q[4]=B[1],Q[7]=B[2],Q[2]=-I[0],Q[5]=-I[1],Q[8]=-I[2],kQ(A,IE(A,Q))}})();function gE(){var Q=new OA(2);return OA!=Float32Array&&(Q[0]=0,Q[1]=0),Q}function BE(Q){var A=new OA(2);return A[0]=Q[0],A[1]=Q[1],A}function xA(Q,A){var I=new OA(2);return I[0]=Q,I[1]=A,I}function Ba(Q,A){var I=A[0]-Q[0],g=A[1]-Q[1];return Math.sqrt(I*I+g*g)}function Qa(Q){var A=Q[0],I=Q[1];return A*A+I*I}function Ca(Q,A,I,g){var B=A[0],C=A[1];return Q[0]=B+g*(I[0]-B),Q[1]=C+g*(I[1]-C),Q}function QE(Q,A){return Q[0]===A[0]&&Q[1]===A[1]}function LQ(Q,A){var I=Q[0],g=Q[1],B=A[0],C=A[1];return Math.abs(I-B)<=JA*Math.max(1,Math.abs(I),Math.abs(B))&&Math.abs(g-C)<=JA*Math.max(1,Math.abs(g),Math.abs(C))}(function(){var Q=gE();return function(A,I,g,B,C,E){var i,o;for(I||(I=2),g||(g=0),B?o=Math.min(B*I+g,A.length):o=A.length,i=g;i<o;i+=I)Q[0]=A[i],Q[1]=A[i+1],C(Q,Q,E),A[i]=Q[0],A[i+1]=Q[1];return A}})();class Qg{min;max;constructor(A,I){this.min=A?HI(A):nA(1/0,1/0,1/0),this.max=I?HI(I):nA(-1/0,-1/0,-1/0)}clone(){return new Qg(this.min,this.max)}isEmpty(){return this.max[0]<=this.min[0]||this.max[1]<=this.min[1]||this.max[2]<=this.min[2]}static intersects(A,I){return!(A.max[0]<=I.min[0]||A.min[0]>=I.max[0]||A.max[1]<=I.min[1]||A.min[1]>=I.max[1]||A.max[2]<=I.min[2]||A.min[2]>=I.max[2])}expandWithPoint(A){A[0]<this.min[0]&&(this.min[0]=A[0]),A[1]<this.min[1]&&(this.min[1]=A[1]),A[2]<this.min[2]&&(this.min[2]=A[2]),A[0]>this.max[0]&&(this.max[0]=A[0]),A[1]>this.max[1]&&(this.max[1]=A[1]),A[2]>this.max[2]&&(this.max[2]=A[2])}applyTransform(A){const{min:I,max:g}=this,B=[nA(I[0],I[1],I[2]),nA(I[0],I[1],g[2]),nA(I[0],g[1],I[2]),nA(I[0],g[1],g[2]),nA(g[0],I[1],I[2]),nA(g[0],I[1],g[2]),nA(g[0],g[1],I[2]),nA(g[0],g[1],g[2])];this.min=nA(1/0,1/0,1/0),this.max=nA(-1/0,-1/0,-1/0);const C=HA();for(const E of B)SQ(C,E,A),this.expandWithPoint(C)}}const CE={position:0,normal:1,uv:2,next_position:3,previous_position:4,direction:5,color:6,size:7,marker:8};class Ug extends FQ{boundingBox_=null;primitive_;attributes_;vertexData_;indexData_;constructor(A=[],I=[],g="triangles"){super(),this.vertexData_=new Float32Array(A),this.indexData_=new Uint32Array(I),this.primitive_=g,this.attributes_=[]}addAttribute(A){this.attributes_.push(A),this.boundingBox_=null}get vertexCount(){return this.vertexData_.byteLength/this.strideBytes}get stride(){return this.attributes_.reduce((A,I)=>A+I.itemSize,0)}get strideBytes(){return this.stride*Float32Array.BYTES_PER_ELEMENT}get primitive(){return this.primitive_}get vertexData(){return this.vertexData_}get indexData(){return this.indexData_}get attributes(){return this.attributes_}get boundingBox(){if(this.boundingBox_===null){const A=this.getAttribute("position");if(!A||this.vertexCount===0)throw new Error("Failed to generate bounding box");const I=(A.offset??0)/Float32Array.BYTES_PER_ELEMENT,g=new Qg,B=HA();for(let C=0;C<this.vertexData_.length;C+=this.stride)B[0]=this.vertexData_[C+I+0],B[1]=this.vertexData_[C+I+1],B[2]=this.vertexData_[C+I+2],g.expandWithPoint(B);this.boundingBox_=g}return this.boundingBox_}get type(){return"Geometry"}getAttribute(A){return this.attributes_.find(I=>I.type===A)}}class Ea{gl_;buffers_=new Map;currentGeometry_=null;constructor(A){this.gl_=A}bindGeometry(A){if(this.alreadyActive(A))return;this.buffers_.has(A)||this.generateBuffers(A);const I=this.buffers_.get(A);if(!I)throw new Error("Failed to retrieve buffer handles for object");this.gl_.bindVertexArray(I.vao),this.currentGeometry_=A}disposeObject(A){const I=this.buffers_.get(A);I&&(this.gl_.deleteVertexArray(I.vao),this.gl_.deleteBuffer(I.vbo),I.ebo&&this.gl_.deleteBuffer(I.ebo),this.buffers_.delete(A),this.currentGeometry_===A&&(this.currentGeometry_=null))}disposeAll(){for(const A of this.buffers_.keys())this.disposeObject(A)}alreadyActive(A){return this.currentGeometry_===A}generateBuffers(A){const I=this.gl_.createVertexArray();if(!I)throw new Error("Failed to create vertex array object (VAO)");this.gl_.bindVertexArray(I);const{vertexData:g}=A,B=this.gl_.ARRAY_BUFFER,C=this.gl_.createBuffer();if(!C)throw new Error("Failed to create vertex buffer (VBO)");this.gl_.bindBuffer(B,C),this.gl_.bufferData(B,g,this.gl_.STATIC_DRAW);const{attributes:E,strideBytes:i}=A;E.forEach(D=>{const s=CE[D.type];this.gl_.vertexAttribPointer(s,D.itemSize,this.gl_.FLOAT,!1,i,D.offset),this.gl_.enableVertexAttribArray(s)});const o={vao:I,vbo:C},{indexData:a}=A;if(a.length){const D=this.gl_.ELEMENT_ARRAY_BUFFER,s=this.gl_.createBuffer();if(!s)throw new Error("Failed to create index buffer (EBO)");this.gl_.bindBuffer(D,s),this.gl_.bufferData(D,a,this.gl_.STATIC_DRAW),o.ebo=s}this.buffers_.set(A,o),this.gl_.bindVertexArray(null)}}class ia{gl_;textures_=new Map;currentTexture_=null;maxTextureUnits_;gpuTextureBytes_=0;textureCount_=0;readFramebuffer_=null;constructor(A){this.gl_=A,this.maxTextureUnits_=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS)}get gpuTextureBytes(){return this.gpuTextureBytes_}get textureCount(){return this.textureCount_}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}]`);const g=this.textures_.get(A);g&&!A.needsUpdate?(this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.gl_.bindTexture(this.getTextureType(A),g)):this.uploadTexture(A,I),this.currentTexture_=A}readTexel(A,I,g,B){const C=this.gl_,E=this.textures_.get(A);if(!E)throw new Error("readTexel called on a texture that is not resident");this.readFramebuffer_??=C.createFramebuffer(),C.bindFramebuffer(C.READ_FRAMEBUFFER,this.readFramebuffer_),C.framebufferTextureLayer(C.READ_FRAMEBUFFER,C.COLOR_ATTACHMENT0,E,0,B);const{format:i,type:o,out:a}=this.readbackParams(A.dataType);return C.readPixels(I,g,1,1,i,o,a),C.bindFramebuffer(C.READ_FRAMEBUFFER,null),a[0]}readbackParams(A){const I=this.gl_;switch(A){case"byte":case"short":case"int":return{format:I.RGBA_INTEGER,type:I.INT,out:new Int32Array(4)};case"unsigned_byte":case"unsigned_short":case"unsigned_int":return{format:I.RGBA_INTEGER,type:I.UNSIGNED_INT,out:new Uint32Array(4)};case"float":return{format:I.RGBA,type:I.FLOAT,out:new Float32Array(4)}}}uploadTexture(A,I=0){if(this.textures_.has(A)&&!A.needsUpdate)return;if(A.data===null)throw new Error("Cannot upload a texture that has no CPU data");const g=this.getTextureType(A),B=this.getDataFormatInfo(A.dataFormat,A.dataType);this.gl_.activeTexture(this.gl_.TEXTURE0+I),this.textures_.has(A)||this.generateTexture(A,B,g);const C=this.textures_.get(A);if(!C)throw new Error("Failed to retrieve texture ID");this.gl_.bindTexture(g,C),this.configureTextureParameters(A,g),this.uploadTextureData(A,B,g),A.needsUpdate=!1}dispose(A){const I=this.textures_.get(A);if(I){this.gl_.deleteTexture(I),this.textures_.delete(A),A.readTexel=void 0,this.currentTexture_===A&&(this.currentTexture_=null);const g=this.getDataFormatInfo(A.dataFormat,A.dataType),B=this.computeStorageBytes(A,g);this.gpuTextureBytes_=Math.max(0,this.gpuTextureBytes_-B),this.textureCount_=Math.max(0,this.textureCount_-1)}}disposeAll(){for(const A of Array.from(this.textures_.keys()))this.dispose(A);this.gpuTextureBytes_=0,this.textureCount_=0}alreadyActive(A){return this.currentTexture_===A&&!A.needsUpdate}generateTexture(A,I,g){const B=this.gl_.createTexture();if(!B)throw new Error("Failed to create texture");if(this.gl_.bindTexture(g,B),this.isTexture2D(A))this.gl_.texStorage2D(g,A.mipmapLevels,I.internalFormat,A.width,A.height);else if(this.isTextureStorage3D(A))this.gl_.texStorage3D(g,A.mipmapLevels,I.internalFormat,A.width,A.height,A.depth);else throw new Error(`Unknown texture type ${A.type}`);this.gpuTextureBytes_+=this.computeStorageBytes(A,I),this.textureCount_+=1,this.textures_.set(A,B),this.gl_.bindTexture(g,null),A.readTexel=(C,E,i)=>Promise.resolve(this.readTexel(A,C,E,i))}configureTextureParameters(A,I){const g=this.gl_,B=this.getFilter(A.minFilter,A),C=this.getFilter(A.maxFilter,A);g.pixelStorei(g.UNPACK_ALIGNMENT,A.unpackAlignment),g.texParameteri(I,g.TEXTURE_MIN_FILTER,B),g.texParameteri(I,g.TEXTURE_MAG_FILTER,C),g.texParameteri(I,g.TEXTURE_WRAP_S,this.getWrapMode(A.wrapS)),g.texParameteri(I,g.TEXTURE_WRAP_T,this.getWrapMode(A.wrapT)),g.texParameteri(I,g.TEXTURE_WRAP_R,this.getWrapMode(A.wrapR))}uploadTextureData(A,I,g){const C={x:0,y:0,z:0};if(this.isTexture2D(A))this.gl_.texSubImage2D(g,0,C.x,C.y,A.width,A.height,I.format,I.type,A.data);else if(this.isTextureStorage3D(A))this.gl_.texSubImage3D(g,0,C.x,C.y,C.z,A.width,A.height,A.depth,I.format,I.type,A.data);else throw new Error("Attempting to upload data for an unsupported texture type")}getFilter(A,I){const{dataFormat:g,dataType:B}=I;if(g==="scalar"&&B!=="float"&&A!=="nearest")return gA.warn("WebGLTexture","Integer values are not filterable. Using gl.NEAREST instead."),this.gl_.NEAREST;switch(A){case"nearest":return this.gl_.NEAREST;case"linear":return this.gl_.LINEAR;default:throw new Error(`Unsupported texture filter: ${A}`)}}getTextureType(A){if(this.isTexture2D(A))return this.gl_.TEXTURE_2D;if(this.isTexture2DArray(A))return this.gl_.TEXTURE_2D_ARRAY;if(this.isTexture3D(A))return this.gl_.TEXTURE_3D;throw new Error(`Unknown texture type ${A.type}`)}getWrapMode(A){switch(A){case"repeat":return this.gl_.REPEAT;case"clamp_to_edge":return this.gl_.CLAMP_TO_EDGE;default:throw new Error(`Unsupported wrap mode: ${A}`)}}getDataFormatInfo(A,I){if(A==="rgba"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGBA8,format:this.gl_.RGBA,type:this.gl_.UNSIGNED_BYTE};if(A==="rgb"&&I==="unsigned_byte")return{internalFormat:this.gl_.RGB8,format:this.gl_.RGB,type:this.gl_.UNSIGNED_BYTE};if(A==="scalar")switch(I){case"byte":return{internalFormat:this.gl_.R8I,format:this.gl_.RED_INTEGER,type:this.gl_.BYTE};case"short":return{internalFormat:this.gl_.R16I,format:this.gl_.RED_INTEGER,type:this.gl_.SHORT};case"int":return{internalFormat:this.gl_.R32I,format:this.gl_.RED_INTEGER,type:this.gl_.INT};case"unsigned_byte":return{internalFormat:this.gl_.R8UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_BYTE};case"unsigned_short":return{internalFormat:this.gl_.R16UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_SHORT};case"unsigned_int":return{internalFormat:this.gl_.R32UI,format:this.gl_.RED_INTEGER,type:this.gl_.UNSIGNED_INT};case"float":return{internalFormat:this.gl_.R32F,format:this.gl_.RED,type:this.gl_.FLOAT};default:throw new Error(`Unsupported scalar type: ${I}`)}throw new Error(`Unsupported format/type: ${A}/${I}`)}computeStorageBytes(A,I){const g=this.bytesPerTexel(I),B=Math.max(1,A.mipmapLevels),C=this.isTextureStorage3D(A)?Math.max(1,A.depth):1;let E=Math.max(1,A.width),i=Math.max(1,A.height),o=0;for(let a=0;a<B;a++)o+=E*i*C*g,E=Math.max(1,E>>1),i=Math.max(1,i>>1);return o}bytesPerTexel(A){const I=this.gl_;if(A.format===I.RGB&&A.type===I.UNSIGNED_BYTE)return 3;if(A.format===I.RGBA&&A.type===I.UNSIGNED_BYTE)return 4;if(A.format===I.RED_INTEGER)switch(A.type){case I.BYTE:case I.UNSIGNED_BYTE:return 1;case I.SHORT:case I.UNSIGNED_SHORT:return 2;case I.INT:case I.UNSIGNED_INT:return 4}if(A.format===I.RED&&A.type===I.FLOAT)return 4;throw new Error("bytesPerTexel: unsupported format/type")}isTextureStorage3D(A){return this.isTexture2DArray(A)||this.isTexture3D(A)}isTexture2D(A){return A.type==="Texture2D"}isTexture2DArray(A){return A.type==="Texture2DArray"}isTexture3D(A){return A.type==="Texture3D"}}class QI{min;max;constructor(A,I){this.min=A?BE(A):xA(1/0,1/0),this.max=I?BE(I):xA(-1/0,-1/0)}clone(){return new QI(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 QE(A.min,I.min)&&QE(A.max,I.max)}floor(){return new QI(xA(Math.floor(this.min[0]),Math.floor(this.min[1])),xA(Math.floor(this.max[0]),Math.floor(this.max[1])))}toRect(){const A=this.min[0],I=this.min[1],g=this.max[0]-this.min[0],B=this.max[1]-this.min[1];return{x:A,y:I,width:g,height:B}}}class oa{gl_;enabledCapabilities_=new Map;depthMaskEnabled_=null;blendSrcFactor_=null;blendDstFactor_=null;currentBlendingMode_=null;currentViewport_=null;currentScissor_=null;currentCullingMode_=null;constructor(A){this.gl_=A,this.gl_.frontFace(this.gl_.CW)}enable(A){this.enabledCapabilities_.get(A)||(this.gl_.enable(A),this.enabledCapabilities_.set(A,!0))}disable(A){this.enabledCapabilities_.get(A)&&(this.gl_.disable(A),this.enabledCapabilities_.set(A,!1))}setBlendFunc(A,I){(this.blendSrcFactor_!==A||this.blendDstFactor_!==I)&&(this.gl_.blendFunc(A,I),this.blendSrcFactor_=A,this.blendDstFactor_=I)}setDepthTesting(A){A?this.enable(this.gl_.DEPTH_TEST):this.disable(this.gl_.DEPTH_TEST)}setBlending(A){A?this.enable(this.gl_.BLEND):this.disable(this.gl_.BLEND)}setDepthMask(A){this.depthMaskEnabled_!==A&&(this.gl_.depthMask(A),this.depthMaskEnabled_=A)}setBlendingMode(A){if(this.currentBlendingMode_!==A){if(A==="none")this.setBlending(!1);else switch(this.setBlending(!0),A){case"additive":this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE);break;case"multiply":this.setBlendFunc(this.gl_.DST_COLOR,this.gl_.ZERO);break;case"subtractive":this.setBlendFunc(this.gl_.ZERO,this.gl_.ONE_MINUS_SRC_COLOR);break;case"premultiplied":this.setBlendFunc(this.gl_.ONE_MINUS_DST_ALPHA,this.gl_.ONE);break;case"normal":default:this.setBlendFunc(this.gl_.SRC_ALPHA,this.gl_.ONE_MINUS_SRC_ALPHA);break}this.currentBlendingMode_=A}}setViewport(A){const I=A.floor();if(this.currentViewport_&&QI.equals(I,this.currentViewport_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.viewport(g,B,C,E),this.currentViewport_=I}setScissorTest(A){A?this.enable(this.gl_.SCISSOR_TEST):(this.disable(this.gl_.SCISSOR_TEST),this.currentScissor_=null)}setScissor(A){const I=A.floor();if(this.currentScissor_&&QI.equals(I,this.currentScissor_))return;const{x:g,y:B,width:C,height:E}=I.toRect();this.gl_.scissor(g,B,C,E),this.currentScissor_=I}setCullFace(A){A?this.enable(this.gl_.CULL_FACE):this.disable(this.gl_.CULL_FACE)}setCullFaceMode(A){if(this.currentCullingMode_!==A){if(A==="none")this.setCullFace(!1);else switch(this.setCullFace(!0),A){case"front":this.gl_.cullFace(this.gl_.FRONT);break;case"back":this.gl_.cullFace(this.gl_.BACK);break;case"both":this.gl_.cullFace(this.gl_.FRONT_AND_BACK);break}this.currentCullingMode_=A}}setStencilTest(A){A?this.enable(this.gl_.STENCIL_TEST):this.disable(this.gl_.STENCIL_TEST)}}const aa=fo(hI(),[1,-1,1]);class EE extends OC{gl_;programs_;bindings_;textures_;state_;renderedObjectsPerFrame_=0;currentViewportSize_=[0,0];constructor(A){super(A);const I=this.canvas.getContext("webgl2",{depth:!0,antialias:!0,stencil:!0});if(!I)throw new Error("Failed to initialize WebGL2 context");this.gl_=I,gA.info("WebGLRenderer",`WebGL version ${I.getParameter(I.VERSION)}`),I.getExtension("EXT_color_buffer_float"),this.programs_=new Ko(I),this.bindings_=new Ea(I),this.textures_=new ia(I),this.state_=new oa(I),this.initStencil(),this.resize(this.canvas.width,this.canvas.height)}get gpuTextureBytes(){return this.textures_.gpuTextureBytes}get gpuTextureCount(){return this.textures_.textureCount}render(A){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0;const I=[],g=[];for(const D of A.layers)(D.blendMode==="none"?I:g).push(D);for(const D of[...I,...g])D.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new QI(xA(0,0),xA(this.width,this.height)),E=QI.equals(B.floor(),C.floor()),i=QI.intersects(B,C);if(E)this.state_.setScissorTest(!1);else if(i)this.state_.setScissorTest(!0),this.state_.setScissor(B);else{gA.warn("WebGLRenderer",`Viewport ${A.id} is entirely outside canvas bounds, skipping render`);return}this.state_.setViewport(B),this.clear();const o=B.toRect();this.currentViewportSize_=[o.width,o.height];const a=A.camera.frustum;this.state_.setDepthMask(!0);for(const D of I)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.state_.setDepthMask(!1);for(const D of g)D.state==="ready"&&this.renderLayer(D,A.camera,a);this.renderedObjects_=this.renderedObjectsPerFrame_}initStencil(){this.gl_.clearStencil(0),this.gl_.stencilMask(255),this.gl_.stencilFunc(this.gl_.EQUAL,0,255),this.gl_.stencilOp(this.gl_.KEEP,this.gl_.KEEP,this.gl_.INCR)}renderLayer(A,I,g){if(A.objects.length===0)return;this.state_.setBlendingMode(A.blendMode);const B=A.hasMultipleLODs();this.state_.setStencilTest(B),B&&this.gl_.clear(this.gl_.STENCIL_BUFFER_BIT),A.objects.forEach((C,E)=>{g.intersectsWithBox3(C.boundingBox)&&(this.renderObject(A,E,I),this.renderedObjectsPerFrame_+=1)})}renderObject(A,I,g){const B=A.objects[I];if(B.popStaleTextures().forEach(E=>{this.textures_.dispose(E)}),!B.programName)return;this.state_.setCullFaceMode(B.cullFaceMode),this.state_.setDepthTesting(B.depthTest),this.state_.setDepthMask(B.depthTest),this.bindings_.bindGeometry(B.geometry),B.textures.forEach((E,i)=>{this.textures_.bindTexture(E,i)});const C=this.programs_.use(B.programName);if(this.drawGeometry(B.geometry,B,A,C,g),B.wireframeEnabled){this.bindings_.bindGeometry(B.wireframeGeometry);const E=this.programs_.use("wireframe");E.setUniform("u_color",B.wireframeColor.rgb),this.drawGeometry(B.wireframeGeometry,B,A,E,g)}}drawGeometry(A,I,g,B,C){const E=Rg(hI(),C.viewMatrix,I.transform.matrix),i=Rg(hI(),aa,C.projectionMatrix),o=this.currentViewportSize_,a=I.getUniforms(),s={...g.getUniforms(),...a};for(const Y of B.uniformNames)switch(Y){case"u_modelView":B.setUniform(Y,E);break;case"u_projection":B.setUniform(Y,i);break;case"u_resolution":B.setUniform(Y,o);break;case"u_opacity":B.setUniform(Y,g.opacity*(a.Opacity??1));break;case"u_cameraPositionModel":{const u=dB(hI(),E),H=HB(0,0,0,1),W=QB(cg(),H,u);B.setUniform(Y,nA(W[0],W[1],W[2]));break}default:Y in s&&B.setUniform(Y,s[Y])}const y=this.glGetPrimitive(A.primitive),e=A.indexData;e.length?this.gl_.drawElements(y,e.length,this.gl_.UNSIGNED_INT,0):this.gl_.drawArrays(y,0,A.vertexCount)}uploadTexture(A){this.textures_.uploadTexture(A)}disposeTexture(A){this.textures_.dispose(A)}glGetPrimitive(A){switch(A){case"points":return this.gl_.POINTS;case"triangles":return this.gl_.TRIANGLES;case"lines":return this.gl_.LINES;default:{const I=A;throw new Error(`Unknown Primitive type: ${I}`)}}}resize(A,I){const g=new QI(xA(0,0),xA(A,I));this.state_.setViewport(g)}clear(){this.gl_.clearColor(...this.backgroundColor.rgba),this.gl_.clear(this.gl_.COLOR_BUFFER_BIT|this.gl_.DEPTH_BUFFER_BIT),this.state_.setDepthTesting(!0),this.gl_.depthFunc(this.gl_.LEQUAL)}}const Da=16;class sa{device_;slotSize_;buffer_;capacity_=Da;cursor_=0;version_=0;clear_=[];constructor(A,I){const g=A.limits.minUniformBufferOffsetAlignment;this.device_=A,this.slotSize_=Math.ceil(I/g)*g,this.buffer_=this.createBuffer()}clear(){for(const A of this.clear_)A.destroy();this.clear_.length=0,this.cursor_=0}write(A){return this.cursor_>=this.capacity_&&this.resize(),this.device_.queue.writeBuffer(this.buffer_,this.cursor_*this.slotSize_,A),this.cursor_++,(this.cursor_-1)*this.slotSize_}get buffer(){return this.buffer_}get version(){return this.version_}resize(){const A=this.buffer_;this.capacity_*=2,this.buffer_=this.createBuffer();const I=this.device_.createCommandEncoder();I.copyBufferToBuffer(A,0,this.buffer_,0,A.size),this.device_.queue.submit([I.finish()]),this.clear_.push(A),this.version_++}createBuffer(){return this.device_.createBuffer({size:this.capacity_*this.slotSize_,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC})}}const ha=0,ya=1;class ta{device_;uniformBindings_=[];textureBindings_=[];constructor(A){this.device_=A}clearUniformBindings(){for(const A of this.uniformBindings_)A.buffer.clear()}setUniforms(A,I){const g=I.shaderModule.layouts.uniforms,B=I.uniformsData;let C=this.uniformBindings_.find(o=>o.layout===g);if(!C){const o=new sa(this.device_,B.byteLength),a=this.createUniformsBindGroup(g,o,B.byteLength);C={layout:g,buffer:o,group:a,version:o.version},this.uniformBindings_.push(C)}const E=C.buffer.write(B);C.version!==C.buffer.version&&(C.group=this.createUniformsBindGroup(g,C.buffer,B.byteLength),C.version=C.buffer.version),A.setBindGroup(ha,C.group,[E])}setTexture(A,I,g){const B=I.shaderModule.layouts.textures;if(!B)throw new Error("setTexture called on pipeline without a texture layout");let C=this.textureBindings_.find(E=>E.layout===B&&E.texture===g);if(!C){const E=this.createTexturesBindGroup(B,g);C={layout:B,texture:g,group:E},this.textureBindings_.push(C)}A.setBindGroup(ya,C.group)}createUniformsBindGroup(A,I,g){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:{buffer:I.buffer,size:g}}]})}createTexturesBindGroup(A,I){return this.device_.createBindGroup({layout:A,entries:[{binding:0,resource:I.createView()}]})}}class Ga{device_;buffers_;constructor(A){this.device_=A,this.buffers_=[]}get(A){const I=this.buffers_.find(o=>o.geometry===A);if(I)return I;const g=this.device_.createBuffer({size:A.vertexData.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});new Float32Array(g.getMappedRange()).set(A.vertexData),g.unmap();let B=null;A.indexData.byteLength>0&&(B=this.device_.createBuffer({size:A.indexData.byteLength,usage:GPUBufferUsage.INDEX,mappedAtCreation:!0}),new Uint32Array(B.getMappedRange()).set(A.indexData),B.unmap());const{attributes:C,attributesKey:E}=Fa(A),i={geometry:A,vertexBuffer:g,indexBuffer:B,attributes:C,attributesKey:E};return this.buffers_.push(i),i}dispose(A){const I=this.buffers_.findIndex(B=>B.geometry===A);if(I===-1)return;const g=this.buffers_[I];g.vertexBuffer.destroy(),g.indexBuffer?.destroy(),this.buffers_.splice(I,1)}disposeAll(){for(const A of this.buffers_)A.vertexBuffer.destroy(),A.indexBuffer?.destroy();this.buffers_.length=0}}function wa(Q){switch(Q){case 2:return"float32x2";case 3:return"float32x3";case 4:return"float32x4";default:throw new Error("Unsupported vertex format size")}}function Fa(Q){const A=[];let I="";for(const g of Q.attributes)A.push({shaderLocation:CE[g.type],offset:g.offset,format:wa(g.itemSize)}),I+=`${g.type},${g.offset},${g.itemSize}|`;return{attributes:A,attributesKey:I}}function ea(Q){return Q===1||Q===2||Q===4||Q===8}function kg(Q){if(Q instanceof Int8Array)return"byte";if(Q instanceof Int16Array)return"short";if(Q instanceof Int32Array)return"int";if(Q instanceof Uint8Array)return"unsigned_byte";if(Q instanceof Uint16Array)return"unsigned_short";if(Q instanceof Uint32Array)return"unsigned_int";if(Q instanceof Float32Array)return"float";throw new Error("Unsupported buffer type.")}function ra(Q){switch(Q.dataFormat){case"scalar":return 1;case"rgb":return 3;case"rgba":return 4}}function na(Q){switch(Q.dataType){case"byte":case"unsigned_byte":return 1;case"short":case"unsigned_short":return 2;case"int":case"unsigned_int":case"float":return 4}}function Sa(Q){if(Q.dataFormat==="rgb"||Q.dataFormat==="rgba")return[0,1];switch(Q.dataType){case"byte":return[-128,127];case"short":return[-32768,32767];case"int":return[-2147483648,2147483647];case"unsigned_byte":return[0,255];case"unsigned_short":return[0,65535];case"unsigned_int":return[0,4294967295];case"float":return[0,1]}}class JQ extends FQ{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;readTexel;get type(){return"Texture"}}class qI extends JQ{data_;width_;height_;depth_;constructor(A,I,g,B){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=B}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture3D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}get depth(){return this.depth_}updateWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==I){if(this.width!=A.shape.x||this.height!=A.shape.y||this.depth!=A.shape.z||this.dataType!=kg(I))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=I}}static createWithChunk(A){const I=A.data;if(!I)throw new Error("Unable to create texture, chunk data is not initialized.");const g=new qI(I,A.shape.x,A.shape.y,A.shape.z);return g.unpackAlignment=A.rowAlignmentBytes,g}}class Na{device_;textures_;constructor(A){this.device_=A,this.textures_=[]}get(A){let I=this.textures_.find(g=>g.entry===A);if(I&&!A.needsUpdate)return I.texture;if(A.data===null)throw new Error("Cannot upload a texture that has no CPU data");if(!I){const g=this.device_.createTexture({size:iE(A),dimension:A instanceof qI?"3d":"2d",format:ca(A),usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC});this.textures_.push({entry:A,texture:g}),I=this.textures_[this.textures_.length-1]}return this.upload(A,I.texture),A.readTexel=(g,B,C)=>this.readTexel(I.texture,A.dataType,g,B,C),I.texture}async readTexel(A,I,g,B,C){const E=this.device_.createBuffer({size:256,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),i=this.device_.createCommandEncoder();i.copyTextureToBuffer({texture:A,origin:{x:g,y:B,z:C}},{buffer:E,bytesPerRow:256},{width:1,height:1,depthOrArrayLayers:1}),this.device_.queue.submit([i.finish()]),await E.mapAsync(GPUMapMode.READ);const o=Ra(new DataView(E.getMappedRange()),I);return E.unmap(),E.destroy(),o}upload(A,I){const g=ra(A),B=na(A),C=A.width*g*B;this.device_.queue.writeTexture({texture:I},A.data,{bytesPerRow:C,rowsPerImage:A.height},iE(A)),A.needsUpdate=!1}dispose(A){const I=this.textures_.findIndex(g=>g.entry===A);I!==-1&&(this.textures_[I].texture.destroy(),this.textures_.splice(I,1),A.readTexel=void 0)}disposeAll(){for(const A of this.textures_)A.texture.destroy();this.textures_.length=0}}function iE(Q){return{width:Q.width,height:Q.height,depthOrArrayLayers:Q instanceof qI?Q.depth:1}}function Ra(Q,A){switch(A){case"byte":return Q.getInt8(0);case"unsigned_byte":return Q.getUint8(0);case"short":return Q.getInt16(0,!0);case"unsigned_short":return Q.getUint16(0,!0);case"int":return Q.getInt32(0,!0);case"unsigned_int":return Q.getUint32(0,!0);case"float":return Q.getFloat32(0,!0)}}function ca(Q){if(Q.dataFormat==="rgb")throw new Error("RGB texture format is not supported in WebGPU");if(Q.dataFormat==="scalar")switch(Q.dataType){case"byte":return"r8snorm";case"unsigned_byte":return"r8unorm";case"short":return"r16sint";case"unsigned_short":return"r16uint";case"int":return"r32sint";case"unsigned_int":return"r32uint";case"float":return"r32float"}switch(Q.dataType){case"byte":return"rgba8snorm";case"unsigned_byte":return"rgba8unorm";case"short":return"rgba16sint";case"unsigned_short":return"rgba16uint";case"int":return"rgba32sint";case"unsigned_int":return"rgba32uint";case"float":return"rgba32float"}}const YQ=(Q,A)=>((Q+A-1)/A|0)*A;function Ua(Q){return Object.keys(Q)}function ka(Q,A){return new Array(Q).fill(0).map((I,g)=>A(g))}const oE=Q=>ArrayBuffer.isView(Q)&&!(Q instanceof DataView),aE=Q=>Q,eA=aE({i32:{numElements:1,align:4,size:4,type:"i32",View:Int32Array},u32:{numElements:1,align:4,size:4,type:"u32",View:Uint32Array},f32:{numElements:1,align:4,size:4,type:"f32",View:Float32Array},f16:{numElements:1,align:2,size:2,type:"u16",View:Uint16Array},vec2f:{numElements:2,align:8,size:8,type:"f32",View:Float32Array},vec2i:{numElements:2,align:8,size:8,type:"i32",View:Int32Array},vec2u:{numElements:2,align:8,size:8,type:"u32",View:Uint32Array},vec2h:{numElements:2,align:4,size:4,type:"u16",View:Float16Array},vec3i:{numElements:3,align:16,size:12,type:"i32",View:Int32Array},vec3u:{numElements:3,align:16,size:12,type:"u32",View:Uint32Array},vec3f:{numElements:3,align:16,size:12,type:"f32",View:Float32Array},vec3h:{numElements:3,align:8,size:6,type:"u16",View:Float16Array},vec4i:{numElements:4,align:16,size:16,type:"i32",View:Int32Array},vec4u:{numElements:4,align:16,size:16,type:"u32",View:Uint32Array},vec4f:{numElements:4,align:16,size:16,type:"f32",View:Float32Array},vec4h:{numElements:4,align:8,size:8,type:"u16",View:Float16Array},mat2x2f:{numElements:4,align:8,size:16,type:"f32",View:Float32Array},mat2x2h:{numElements:4,align:4,size:8,type:"u16",View:Float16Array},mat3x2f:{numElements:6,align:8,size:24,type:"f32",View:Float32Array},mat3x2h:{numElements:6,align:4,size:12,type:"u16",View:Float16Array},mat4x2f:{numElements:8,align:8,size:32,type:"f32",View:Float32Array},mat4x2h:{numElements:8,align:4,size:16,type:"u16",View:Float16Array},mat2x3f:{numElements:8,align:16,size:32,pad:[3,1],type:"f32",View:Float32Array},mat2x3h:{numElements:8,align:8,size:16,pad:[3,1],type:"u16",View:Float16Array},mat3x3f:{numElements:12,align:16,size:48,pad:[3,1],type:"f32",View:Float32Array},mat3x3h:{numElements:12,align:8,size:24,pad:[3,1],type:"u16",View:Float16Array},mat4x3f:{numElements:16,align:16,size:64,pad:[3,1],type:"f32",View:Float32Array},mat4x3h:{numElements:16,align:8,size:32,pad:[3,1],type:"u16",View:Float16Array},mat2x4f:{numElements:8,align:16,size:32,type:"f32",View:Float32Array},mat2x4h:{numElements:8,align:8,size:16,type:"u16",View:Float16Array},mat3x4f:{numElements:12,align:16,size:48,type:"f32",View:Float32Array},mat3x4h:{numElements:12,align:8,size:24,type:"u16",View:Float16Array},mat4x4f:{numElements:16,align:16,size:64,type:"f32",View:Float32Array},mat4x4h:{numElements:16,align:8,size:32,type:"u16",View:Float16Array},bool:{numElements:0,align:1,size:0,type:"bool",View:Uint32Array}}),Lg=aE({...eA,"atomic<i32>":eA.i32,"atomic<u32>":eA.u32,"vec2<i32>":eA.vec2i,"vec2<u32>":eA.vec2u,"vec2<f32>":eA.vec2f,"vec2<f16>":eA.vec2h,"vec3<i32>":eA.vec3i,"vec3<u32>":eA.vec3u,"vec3<f32>":eA.vec3f,"vec3<f16>":eA.vec3h,"vec4<i32>":eA.vec4i,"vec4<u32>":eA.vec4u,"vec4<f32>":eA.vec4f,"vec4<f16>":eA.vec4h,"mat2x2<f32>":eA.mat2x2f,"mat2x2<f16>":eA.mat2x2h,"mat3x2<f32>":eA.mat3x2f,"mat3x2<f16>":eA.mat3x2h,"mat4x2<f32>":eA.mat4x2f,"mat4x2<f16>":eA.mat4x2h,"mat2x3<f32>":eA.mat2x3f,"mat2x3<f16>":eA.mat2x3h,"mat3x3<f32>":eA.mat3x3f,"mat3x3<f16>":eA.mat3x3h,"mat4x3<f32>":eA.mat4x3f,"mat4x3<f16>":eA.mat4x3h,"mat2x4<f32>":eA.mat2x4f,"mat2x4<f16>":eA.mat2x4h,"mat3x4<f32>":eA.mat3x4f,"mat3x4<f16>":eA.mat3x4h,"mat4x4<f32>":eA.mat4x4f,"mat4x4<f16>":eA.mat4x4h}),La=Ua(Lg);function Ja(Q=[],A){const I=new Set;for(const g of La){const B=Lg[g];I.has(B)||(I.add(B),B.flatten=Q.includes(g)?A:!A)}}Ja();function Ya(Q){const A=Q;if(A.elementType)return A.size;{const g=Q,B=A.numElements||1;if(g.fields)return Q.size*B;{const C=Q,{align:E}=Lg[C.type];return B>1?YQ(Q.size,E)*B:Q.size}}}function DE(Q,A,I,g){const{size:B,type:C}=Q;try{const{View:E,align:i,size:o}=Lg[C],a=g!==void 0,D=a?YQ(B,i):o,s=D/E.BYTES_PER_ELEMENT,y=a?g===0?(A.byteLength-I)/D:g:1;return new E(A,I,s*y)}catch{throw new Error(`unknown type: ${C}`)}}function Ka(Q){return!Q.fields&&!Q.elementType}function Ma(Q,A,I){const g=I||0,B=new ArrayBuffer(Ya(Q)),C=(E,i)=>{const o=E,a=o.elementType;if(a){if(Ka(a)&&Lg[a.type].flatten)return DE(a,B,i,o.numElements);{const{size:D}=sE(E),s=o.numElements===0?(B.byteLength-i)/D:o.numElements;return ka(s,y=>C(a,i+D*y))}}else{if(typeof E=="string")throw Error("unreachable");{const D=E.fields;if(D){const s={};for(const[y,{type:e,offset:Y}]of Object.entries(D))s[y]=C(e,i+Y);return s}else return DE(E,B,i)}}};return{views:C(Q,g),arrayBuffer:B}}function KQ(Q,A){if(Q!==void 0)if(oE(A)){const I=A;if(I.length===1&&typeof Q=="number")I[0]=Q;else if(Array.isArray(Q[0])||oE(Q[0])){const g=Q[0].length,B=g===3?4:g;for(let C=0;C<Q.length;++C){const E=C*B;I.set(Q[C],E)}}else I.set(Q)}else if(Array.isArray(A)){const I=A;Q.forEach((g,B)=>{KQ(g,I[B])})}else{const I=A;for(const[g,B]of Object.entries(Q)){const C=I[g];C&&KQ(B,C)}}}function da(Q,A,I=0){const g=Q,B=g.group===void 0?Q:g.typeDefinition,C=Ma(B,A,I);return{...C,set(E){KQ(E,C.views)}}}function MQ(Q){const I=Q.elementType;if(I)return MQ(I);const B=Q.fields;if(B)return Object.values(B).reduce((i,{type:o})=>Math.max(i,MQ(o)),0);const{type:C}=Q,{align:E}=Lg[C];return E}function sE(Q){const I=Q.elementType;if(I){const C=I.size,E=MQ(I);return{unalignedSize:C,align:E,size:YQ(C,E)}}const B=Q.fields;if(B){const C=Object.values(B).pop();if(C.type.size===0)return sE(C.type)}return{size:0,unalignedSize:0,align:1}}class wI{constructor(A,I){this.name=A,this.attributes=I,this.size=0}get isArray(){return!1}get isStruct(){return!1}get isTemplate(){return!1}get isPointer(){return!1}getTypeName(){return this.name}}class hE{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g,this.offset=0,this.size=0}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class WI extends wI{constructor(A,I){super(A,I),this.members=[],this.align=0,this.startLine=-1,this.endLine=-1,this.inUse=!1}get isStruct(){return!0}}class bI extends wI{constructor(A,I){super(A,I),this.count=0,this.stride=0}get isArray(){return!0}getTypeName(){return`array<${this.format.getTypeName()}, ${this.count}>`}}class dQ extends wI{constructor(A,I,g){super(A,g),this.format=I}get isPointer(){return!0}getTypeName(){return`&${this.format.getTypeName()}`}}class Cg extends wI{constructor(A,I,g,B){super(A,g),this.format=I,this.access=B}get isTemplate(){return!0}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}var fA;(Q=>{Q[Q.Uniform=0]="Uniform",Q[Q.Storage=1]="Storage",Q[Q.Immediate=2]="Immediate",Q[Q.Texture=3]="Texture",Q[Q.Sampler=4]="Sampler",Q[Q.StorageTexture=5]="StorageTexture"})(fA||(fA={}));class CB{constructor(A,I,g,B,C,E,i){this.relations=null,this.name=A,this.type=I,this.group=g,this.binding=B,this.attributes=C,this.resourceType=E,this.access=i}get isArray(){return this.type.isArray}get isStruct(){return this.type.isStruct}get isTemplate(){return this.type.isTemplate}get size(){return this.type.size}get align(){return this.type.isStruct?this.type.align:0}get members(){return this.type.isStruct?this.type.members:null}get format(){return this.type.isArray||this.type.isTemplate?this.type.format:null}get count(){return this.type.isArray?this.type.count:0}get stride(){return this.type.isArray?this.type.stride:this.size}}class Ha{constructor(A,I){this.name=A,this.type=I}}class qa{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B,this.interpolation=null}}class yE{constructor(A,I,g,B){this.name=A,this.type=I,this.locationType=g,this.location=B}}class la{constructor(A,I,g,B){this.name=A,this.type=I,this.attributes=g,this.id=B}}class fa{constructor(A,I,g){this.name=A,this.type=I,this.attributes=g}}class pa{constructor(A,I=null,g){this.stage=null,this.inputs=[],this.outputs=[],this.arguments=[],this.returnType=null,this.resources=[],this.overrides=[],this.startLine=-1,this.endLine=-1,this.inUse=!1,this.calls=new Set,this.name=A,this.stage=I,this.attributes=g}}class ua{constructor(){this.vertex=[],this.fragment=[],this.compute=[]}}function ma(Q){var A=(32768&Q)>>15,I=(31744&Q)>>10,g=1023&Q;return I==0?(A?-1:1)*Math.pow(2,-14)*(g/Math.pow(2,10)):I==31?g?NaN:1/0*(A?-1:1):(A?-1:1)*Math.pow(2,I-15)*(1+g/Math.pow(2,10))}const tE=new Float32Array(1),xa=new Int32Array(tE.buffer),gI=new Uint16Array(1);function Ta(Q){tE[0]=Q;const A=xa[0],I=A>>31&1;let g=A>>23&255,B=8388607&A;if(g===255)return gI[0]=I<<15|31744|(B!==0?512:0),gI[0];if(g===0){if(B===0)return gI[0]=I<<15,gI[0];B|=8388608;let C=113;for(;!(8388608&B);)B<<=1,C--;return g=127-C,B&=8388607,g>0?(B=(B>>126-g)+(B>>127-g&1),gI[0]=I<<15|g<<10|B>>13,gI[0]):(gI[0]=I<<15,gI[0])}return g=g-127+15,g>=31?(gI[0]=I<<15|31744,gI[0]):g<=0?g<-10?(gI[0]=I<<15,gI[0]):(B=(8388608|B)>>1-g,gI[0]=I<<15|B>>13,gI[0]):(B>>=13,gI[0]=I<<15|g<<10|B,gI[0])}const HQ=new Uint32Array(1),GE=new Float32Array(HQ.buffer,0,1);function wE(Q){const A=112+(Q>>6&31)<<23|(63&Q)<<17;return HQ[0]=A,GE[0]}function Wa(Q,A,I,g,B,C,E,i,o){const a=g*(E>>=B)*(C>>=B)+I*E+A*i;switch(o){case"r8unorm":return[cA(Q,a,"8unorm",1)[0]];case"r8snorm":return[cA(Q,a,"8snorm",1)[0]];case"r8uint":return[cA(Q,a,"8uint",1)[0]];case"r8sint":return[cA(Q,a,"8sint",1)[0]];case"rg8unorm":{const D=cA(Q,a,"8unorm",2);return[D[0],D[1]]}case"rg8snorm":{const D=cA(Q,a,"8snorm",2);return[D[0],D[1]]}case"rg8uint":{const D=cA(Q,a,"8uint",2);return[D[0],D[1]]}case"rg8sint":{const D=cA(Q,a,"8sint",2);return[D[0],D[1]]}case"rgba8unorm-srgb":case"rgba8unorm":{const D=cA(Q,a,"8unorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8snorm":{const D=cA(Q,a,"8snorm",4);return[D[0],D[1],D[2],D[3]]}case"rgba8uint":{const D=cA(Q,a,"8uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba8sint":{const D=cA(Q,a,"8sint",4);return[D[0],D[1],D[2],D[3]]}case"bgra8unorm-srgb":case"bgra8unorm":{const D=cA(Q,a,"8unorm",4);return[D[2],D[1],D[0],D[3]]}case"r16uint":return[cA(Q,a,"16uint",1)[0]];case"r16sint":return[cA(Q,a,"16sint",1)[0]];case"r16float":return[cA(Q,a,"16float",1)[0]];case"rg16uint":{const D=cA(Q,a,"16uint",2);return[D[0],D[1]]}case"rg16sint":{const D=cA(Q,a,"16sint",2);return[D[0],D[1]]}case"rg16float":{const D=cA(Q,a,"16float",2);return[D[0],D[1]]}case"rgba16uint":{const D=cA(Q,a,"16uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16sint":{const D=cA(Q,a,"16sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba16float":{const D=cA(Q,a,"16float",4);return[D[0],D[1],D[2],D[3]]}case"r32uint":return[cA(Q,a,"32uint",1)[0]];case"r32sint":return[cA(Q,a,"32sint",1)[0]];case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return[cA(Q,a,"32float",1)[0]];case"rg32uint":{const D=cA(Q,a,"32uint",2);return[D[0],D[1]]}case"rg32sint":{const D=cA(Q,a,"32sint",2);return[D[0],D[1]]}case"rg32float":{const D=cA(Q,a,"32float",2);return[D[0],D[1]]}case"rgba32uint":{const D=cA(Q,a,"32uint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32sint":{const D=cA(Q,a,"32sint",4);return[D[0],D[1],D[2],D[3]]}case"rgba32float":{const D=cA(Q,a,"32float",4);return[D[0],D[1],D[2],D[3]]}case"rg11b10ufloat":{const D=new Uint32Array(Q.buffer,a,1)[0],s=(4192256&D)>>11,y=(4290772992&D)>>22;return[wE(2047&D),wE(s),(function(e){const Y=112+(e>>5&31)<<23|(31&e)<<18;return HQ[0]=Y,GE[0]})(y),1]}}return null}function cA(Q,A,I,g){const B=[0,0,0,0];for(let C=0;C<g;++C)switch(I){case"8unorm":B[C]=Q[A]/255,A++;break;case"8snorm":B[C]=Q[A]/255*2-1,A++;break;case"8uint":B[C]=Q[A],A++;break;case"8sint":B[C]=Q[A]-127,A++;break;case"16uint":B[C]=Q[A]|Q[A+1]<<8,A+=2;break;case"16sint":B[C]=(Q[A]|Q[A+1]<<8)-32768,A+=2;break;case"16float":B[C]=ma(Q[A]|Q[A+1]<<8),A+=2;break;case"32uint":case"32sint":B[C]=Q[A]|Q[A+1]<<8|Q[A+2]<<16|Q[A+3]<<24,A+=4;break;case"32float":B[C]=new Float32Array(Q.buffer,A,1)[0],A+=4}return B}function UA(Q,A,I,g,B){for(let C=0;C<g;++C)switch(I){case"8unorm":Q[A]=255*B[C],A++;break;case"8snorm":Q[A]=.5*(B[C]+1)*255,A++;break;case"8uint":Q[A]=B[C],A++;break;case"8sint":Q[A]=B[C]+127,A++;break;case"16uint":new Uint16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16sint":new Int16Array(Q.buffer,A,1)[0]=B[C],A+=2;break;case"16float":{const E=Ta(B[C]);new Uint16Array(Q.buffer,A,1)[0]=E,A+=2;break}case"32uint":new Uint32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32sint":new Int32Array(Q.buffer,A,1)[0]=B[C],A+=4;break;case"32float":new Float32Array(Q.buffer,A,1)[0]=B[C],A+=4}return B}const qQ={r8unorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8snorm:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8uint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r8sint:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg8unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8snorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg8sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"rgba8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8snorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba8sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},bgra8unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bgra8unorm-srgb":{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r16uint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16sint:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r16float:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg16uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg16float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba16uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba16float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},r32uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32sint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},r32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:1},rg32uint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32sint:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rg32float:{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,channels:2},rgba32uint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32sint:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgba32float:{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2uint:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rgb10a2unorm:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},rg11b10ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},stencil8:{bytesPerBlock:1,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!1,hasStencil:!0,channels:1},depth16unorm:{bytesPerBlock:2,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},depth24plus:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,depthOnlyFormat:"depth32float",channels:1},"depth24plus-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,depthOnlyFormat:"depth32float",channels:1},depth32float:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!1,channels:1},"depth32float-stencil8":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!1,isDepthStencil:!0,hasDepth:!0,hasStencil:!0,stencilOnlyFormat:"depth32float",channels:1},rgb9e5ufloat:{bytesPerBlock:4,blockWidth:1,blockHeight:1,isCompressed:!1,channels:4},"bc1-rgba-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc1-rgba-unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc2-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc3-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc4-r-unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc4-r-snorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:1},"bc5-rg-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc5-rg-snorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:2},"bc6h-rgb-ufloat":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc6h-rgb-float":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"bc7-rgba-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgb8a1unorm-srgb":{bytesPerBlock:8,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"etc2-rgba8unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"eac-r11unorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-r11snorm":{bytesPerBlock:8,blockWidth:1,blockHeight:1,isCompressed:!0,channels:1},"eac-rg11unorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"eac-rg11snorm":{bytesPerBlock:16,blockWidth:1,blockHeight:1,isCompressed:!0,channels:2},"astc-4x4-unorm":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-4x4-unorm-srgb":{bytesPerBlock:16,blockWidth:4,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x4-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:4,isCompressed:!0,channels:4},"astc-5x5-unorm":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-5x5-unorm-srgb":{bytesPerBlock:16,blockWidth:5,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x5-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:5,isCompressed:!0,channels:4},"astc-6x6-unorm":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-6x6-unorm-srgb":{bytesPerBlock:16,blockWidth:6,blockHeight:6,isCompressed:!0,channels:4},"astc-8x5-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x5-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:5,isCompressed:!0,channels:4},"astc-8x6-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x6-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:6,isCompressed:!0,channels:4},"astc-8x8-unorm":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-8x8-unorm-srgb":{bytesPerBlock:16,blockWidth:8,blockHeight:8,isCompressed:!0,channels:4},"astc-10x5-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x5-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:5,isCompressed:!0,channels:4},"astc-10x6-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x6-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:6,isCompressed:!0,channels:4},"astc-10x8-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x8-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:8,isCompressed:!0,channels:4},"astc-10x10-unorm":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-10x10-unorm-srgb":{bytesPerBlock:16,blockWidth:10,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x10-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:10,isCompressed:!0,channels:4},"astc-12x12-unorm":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4},"astc-12x12-unorm-srgb":{bytesPerBlock:16,blockWidth:12,blockHeight:12,isCompressed:!0,channels:4}};class FI{constructor(){this.id=FI._id++,this.line=0}get isAstNode(){return!0}get astNodeType(){return""}search(A){A(this)}searchBlock(A,I){if(A){I(qB.instance);for(const g of A)g instanceof Array?this.searchBlock(g,I):g.search(I);I(lB.instance)}}constEvaluate(A,I){throw new Error("Cannot evaluate node")}constEvaluateString(A){var I,g;return(g=(I=this.constEvaluate(A))===null||I===void 0?void 0:I.toString())!==null&&g!==void 0?g:""}}FI._id=0;class qB extends FI{}qB.instance=new qB;class lB extends FI{}lB.instance=new lB;const FE=new Set(["all","any","select","arrayLength","abs","acos","acosh","asin","asinh","atan","atanh","atan2","ceil","clamp","cos","cosh","countLeadingZeros","countOneBits","countTrailingZeros","cross","degrees","determinant","distance","dot","dot4U8Packed","dot4I8Packed","exp","exp2","extractBits","faceForward","firstLeadingBit","firstTrailingBit","floor","fma","fract","frexp","insertBits","inverseSqrt","ldexp","length","log","log2","max","min","mix","modf","normalize","pow","quantizeToF16","radians","reflect","refract","reverseBits","round","saturate","sign","sin","sinh","smoothstep","sqrt","step","tan","tanh","transpose","trunc","dpdx","dpdxCoarse","dpdxFine","dpdy","dpdyCoarse","dpdyFine","fwidth","fwidthCoarse","fwidthFine","textureDimensions","textureGather","textureGatherCompare","textureLoad","textureNumLayers","textureNumLevels","textureNumSamples","textureSample","textureSampleBias","textureSampleCompare","textureSampleCompareLevel","textureSampleGrad","textureSampleLevel","textureSampleBaseClampToEdge","textureStore","atomicLoad","atomicStore","atomicAdd","atomicSub","atomicMax","atomicMin","atomicAnd","atomicOr","atomicXor","atomicExchange","atomicCompareExchangeWeak","pack4x8snorm","pack4x8unorm","pack4xI8","pack4xU8","pack4x8Clamp","pack4xU8Clamp","pack2x16snorm","pack2x16unorm","pack2x16float","unpack4x8snorm","unpack4x8unorm","unpack4xI8","unpack4xU8","unpack2x16snorm","unpack2x16unorm","unpack2x16float","storageBarrier","textureBarrier","workgroupBarrier","workgroupUniformLoad","subgroupAdd","subgroupExclusiveAdd","subgroupInclusiveAdd","subgroupAll","subgroupAnd","subgroupAny","subgroupBallot","subgroupBroadcast","subgroupBroadcastFirst","subgroupElect","subgroupMax","subgroupMin","subgroupMul","subgroupExclusiveMul","subgroupInclusiveMul","subgroupOr","subgroupShuffle","subgroupShuffleDown","subgroupShuffleUp","subgroupShuffleXor","subgroupXor","quadBroadcast","quadSwapDiagonal","quadSwapX","quadSwapY"]);class qA extends FI{}class EB extends qA{constructor(A,I,g,B,C,E){super(),this.calls=new Set,this.name=A,this.args=I,this.returnType=g,this.body=B,this.startLine=C,this.endLine=E}get astNodeType(){return"function"}search(A){if(this.attributes)for(const I of this.attributes)A(I);A(this);for(const I of this.args)A(I);this.searchBlock(this.body,A)}}class eE extends qA{constructor(A){super(),this.expression=A}get astNodeType(){return"staticAssert"}search(A){this.expression.search(A)}}class rE extends qA{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"while"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class lQ extends qA{constructor(A,I){super(),this.body=A,this.loopId=I}get astNodeType(){return"continuing"}search(A){this.searchBlock(this.body,A)}}class nE extends qA{constructor(A,I,g,B){super(),this.init=A,this.condition=I,this.increment=g,this.body=B}get astNodeType(){return"for"}search(A){var I,g,B;(I=this.init)===null||I===void 0||I.search(A),(g=this.condition)===null||g===void 0||g.search(A),(B=this.increment)===null||B===void 0||B.search(A),this.searchBlock(this.body,A)}}class YI extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"var"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class fQ extends qA{constructor(A,I,g){super(),this.attributes=null,this.name=A,this.type=I,this.value=g}get astNodeType(){return"override"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class iB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"let"}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}class fB extends qA{constructor(A,I,g,B,C){super(),this.attributes=null,this.name=A,this.type=I,this.storage=g,this.access=B,this.value=C}get astNodeType(){return"const"}constEvaluate(A,I){return this.value.constEvaluate(A,I)}search(A){var I;A(this),(I=this.value)===null||I===void 0||I.search(A)}}var Jg,oB,M,R;(Q=>{Q.increment="++",Q.decrement="--"})(Jg||(Jg={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for IncrementOperator");return Q[I]}})(Jg||(Jg={}));class SE extends qA{constructor(A,I){super(),this.operator=A,this.variable=I}get astNodeType(){return"increment"}search(A){this.variable.search(A)}}(Q=>{Q.assign="=",Q.addAssign="+=",Q.subtractAssign="-=",Q.multiplyAssign="*=",Q.divideAssign="/=",Q.moduloAssign="%=",Q.andAssign="&=",Q.orAssign="|=",Q.xorAssign="^=",Q.shiftLeftAssign="<<=",Q.shiftRightAssign=">>="})(oB||(oB={})),(Q=>{Q.parse=function(A){const I=A;if(I==="parse")throw new Error("Invalid value for AssignOperator");return I}})(oB||(oB={}));class NE extends qA{constructor(A,I,g){super(),this.operator=A,this.variable=I,this.value=g}get astNodeType(){return"assign"}search(A){this.variable.search(A),this.value.search(A)}}class pQ extends qA{constructor(A,I){super(),this.name=A,this.args=I}get astNodeType(){return"call"}isBuiltin(){return FE.has(this.name)}search(A){for(const I of this.args)I.search(A);A(this)}}class RE extends qA{constructor(A,I){super(),this.body=A,this.continuing=I}get astNodeType(){return"loop"}search(A){var I;this.searchBlock(this.body,A),(I=this.continuing)===null||I===void 0||I.search(A)}}class cE extends qA{constructor(A,I){super(),this.condition=A,this.cases=I}get astNodeType(){return"switch"}search(A){A(this);for(const I of this.cases)I.search(A)}}class UE extends qA{constructor(A,I,g,B){super(),this.condition=A,this.body=I,this.elseif=g,this.else=B}get astNodeType(){return"if"}search(A){this.condition.search(A),this.searchBlock(this.body,A),this.searchBlock(this.elseif,A),this.searchBlock(this.else,A)}}class kE extends qA{constructor(A){super(),this.value=A}get astNodeType(){return"return"}search(A){var I;(I=this.value)===null||I===void 0||I.search(A)}}class ba extends qA{constructor(A){super(),this.name=A}get astNodeType(){return"enable"}}class Za extends qA{constructor(A){super(),this.extensions=A}get astNodeType(){return"requires"}}class LE extends qA{constructor(A,I){super(),this.severity=A,this.rule=I}get astNodeType(){return"diagnostic"}}class uQ extends qA{constructor(A,I){super(),this.name=A,this.type=I}get astNodeType(){return"alias"}}class Pa extends qA{get astNodeType(){return"discard"}}class JE extends qA{constructor(){super(...arguments),this.condition=null,this.loopId=-1}get astNodeType(){return"break"}}class YE extends qA{constructor(){super(...arguments),this.loopId=-1}get astNodeType(){return"continue"}}class f extends qA{constructor(A){super(),this.attributes=null,this.name=A}get astNodeType(){return"type"}get isStruct(){return!1}get isArray(){return!1}static maxFormatType(A){let I=A[0];if(I.name==="f32")return I;for(let g=1;g<A.length;++g){const B=f._priority.get(I.name);f._priority.get(A[g].name)<B&&(I=A[g])}return I.name==="x32"?f.i32:I}getTypeName(){return this.name}}f.x32=new f("x32"),f.f32=new f("f32"),f.i32=new f("i32"),f.u32=new f("u32"),f.f16=new f("f16"),f.bool=new f("bool"),f.void=new f("void"),f._priority=new Map([["f32",0],["f16",1],["u32",2],["i32",3],["x32",3]]);class KE extends f{constructor(A){super(A)}}class lI extends f{constructor(A,I,g,B){super(A),this.members=I,this.startLine=g,this.endLine=B}get astNodeType(){return"struct"}get isStruct(){return!0}getMemberIndex(A){for(let I=0;I<this.members.length;I++)if(this.members[I].name===A)return I;return-1}search(A){for(const I of this.members)A(I)}}class L extends f{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"template"}getTypeName(){let A=this.name;if(this.format!==null){if(A==="vec2"||A==="vec3"||A==="vec4"||A==="mat2x2"||A==="mat2x3"||A==="mat2x4"||A==="mat3x2"||A==="mat3x3"||A==="mat3x4"||A==="mat4x2"||A==="mat4x3"||A==="mat4x4"){if(this.format.name==="f32")return A+="f",A;if(this.format.name==="i32")return A+="i",A;if(this.format.name==="u32")return A+="u",A;if(this.format.name==="bool")return A+="b",A;if(this.format.name==="f16")return A+="h",A}A+=`<${this.format.name}>`}else if(A==="vec2"||A==="vec3"||A==="vec4")return A;return A}}L.vec2f=new L("vec2",f.f32,null),L.vec3f=new L("vec3",f.f32,null),L.vec4f=new L("vec4",f.f32,null),L.vec2i=new L("vec2",f.i32,null),L.vec3i=new L("vec3",f.i32,null),L.vec4i=new L("vec4",f.i32,null),L.vec2u=new L("vec2",f.u32,null),L.vec3u=new L("vec3",f.u32,null),L.vec4u=new L("vec4",f.u32,null),L.vec2h=new L("vec2",f.f16,null),L.vec3h=new L("vec3",f.f16,null),L.vec4h=new L("vec4",f.f16,null),L.vec2b=new L("vec2",f.bool,null),L.vec3b=new L("vec3",f.bool,null),L.vec4b=new L("vec4",f.bool,null),L.mat2x2f=new L("mat2x2",f.f32,null),L.mat2x3f=new L("mat2x3",f.f32,null),L.mat2x4f=new L("mat2x4",f.f32,null),L.mat3x2f=new L("mat3x2",f.f32,null),L.mat3x3f=new L("mat3x3",f.f32,null),L.mat3x4f=new L("mat3x4",f.f32,null),L.mat4x2f=new L("mat4x2",f.f32,null),L.mat4x3f=new L("mat4x3",f.f32,null),L.mat4x4f=new L("mat4x4",f.f32,null),L.mat2x2h=new L("mat2x2",f.f16,null),L.mat2x3h=new L("mat2x3",f.f16,null),L.mat2x4h=new L("mat2x4",f.f16,null),L.mat3x2h=new L("mat3x2",f.f16,null),L.mat3x3h=new L("mat3x3",f.f16,null),L.mat3x4h=new L("mat3x4",f.f16,null),L.mat4x2h=new L("mat4x2",f.f16,null),L.mat4x3h=new L("mat4x3",f.f16,null),L.mat4x4h=new L("mat4x4",f.f16,null),L.mat2x2i=new L("mat2x2",f.i32,null),L.mat2x3i=new L("mat2x3",f.i32,null),L.mat2x4i=new L("mat2x4",f.i32,null),L.mat3x2i=new L("mat3x2",f.i32,null),L.mat3x3i=new L("mat3x3",f.i32,null),L.mat3x4i=new L("mat3x4",f.i32,null),L.mat4x2i=new L("mat4x2",f.i32,null),L.mat4x3i=new L("mat4x3",f.i32,null),L.mat4x4i=new L("mat4x4",f.i32,null),L.mat2x2u=new L("mat2x2",f.u32,null),L.mat2x3u=new L("mat2x3",f.u32,null),L.mat2x4u=new L("mat2x4",f.u32,null),L.mat3x2u=new L("mat3x2",f.u32,null),L.mat3x3u=new L("mat3x3",f.u32,null),L.mat3x4u=new L("mat3x4",f.u32,null),L.mat4x2u=new L("mat4x2",f.u32,null),L.mat4x3u=new L("mat4x3",f.u32,null),L.mat4x4u=new L("mat4x4",f.u32,null);class pB extends f{constructor(A,I,g,B){super(A),this.storage=I,this.type=g,this.access=B}get astNodeType(){return"pointer"}}class aB extends f{constructor(A,I,g,B){super(A),this.attributes=I,this.format=g,this.count=B}get astNodeType(){return"array"}get isArray(){return!0}}class DB extends f{constructor(A,I,g){super(A),this.format=I,this.access=g}get astNodeType(){return"sampler"}}class NI extends FI{constructor(){super(),this.postfix=null,this.hasParen=!1}}class Eg extends NI{constructor(A){super(),this.value=A}get astNodeType(){return"stringExpr"}toString(){return this.value}constEvaluateString(){return this.value}}class KI extends NI{constructor(A,I){super(),this.type=A,this.args=I}get astNodeType(){return"createExpr"}search(A){if(A(this),this.args)for(const I of this.args)I.search(A)}constEvaluate(A,I){return I&&(I[0]=this.type),A.evalExpression(this,A.context)}}class mQ extends NI{constructor(A,I){super(),this.cachedReturnValue=null,this.name=A,this.args=I}get astNodeType(){return"callExpr"}setCachedReturnValue(A){this.cachedReturnValue=A}get isBuiltin(){return FE.has(this.name)}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){for(const I of this.args)I.search(A);A(this)}}class CI extends NI{constructor(A){super(),this.name=A}get astNodeType(){return"varExpr"}search(A){A(this),this.postfix&&this.postfix.search(A)}constEvaluate(A,I){return A.evalExpression(this,A.context)}}class ME extends NI{constructor(A,I){super(),this.name=A,this.initializer=I}get astNodeType(){return"constExpr"}constEvaluate(A,I){const g=A.evalExpression(this.initializer,A.context);return g!==null&&this.postfix?g.getSubData(A,this.postfix,A.context):g}search(A){this.initializer.search(A)}}class vA extends NI{constructor(A,I){super(),this.value=A,this.type=I}get astNodeType(){return"literalExpr"}constEvaluate(A,I){return I!==void 0&&(I[0]=this.type),this.value}get isScalar(){return this.value instanceof U}get isVector(){return this.value instanceof F||this.value instanceof EA}get scalarValue(){return this.value instanceof U?this.value.value:(console.error("Value is not scalar."),0)}get vectorValue(){return this.value instanceof F||this.value instanceof EA?this.value.data:(console.error("Value is not a vector or matrix."),new Float32Array(0))}}class dE extends NI{constructor(A,I){super(),this.type=A,this.value=I}get astNodeType(){return"bitcastExpr"}search(A){this.value.search(A)}}class Yg extends NI{constructor(A){super(),this.index=A}search(A){this.index.search(A)}}class HE extends NI{constructor(){super()}}class TA extends HE{constructor(A,I){super(),this.operator=A,this.right=I}get astNodeType(){return"unaryOp"}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.right.search(A)}}class RI extends HE{constructor(A,I,g){super(),this.operator=A,this.left=I,this.right=g}get astNodeType(){return"binaryOp"}_getPromotedType(A,I){return A.name===I.name?A:A.name==="f32"||I.name==="f32"?f.f32:A.name==="u32"||I.name==="u32"?f.u32:f.i32}constEvaluate(A,I){return A.evalExpression(this,A.context)}search(A){this.left.search(A),this.right.search(A)}}class qE extends FI{constructor(A){super(),this.body=A}search(A){A(this),this.searchBlock(this.body,A)}}class uB extends NI{get astNodeType(){return"default"}}class lE extends qE{constructor(A,I){super(I),this.selectors=A}get astNodeType(){return"case"}search(A){this.searchBlock(this.body,A)}}class fE extends qE{constructor(A){super(A)}get astNodeType(){return"default"}search(A){this.searchBlock(this.body,A)}}class pE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"argument"}}class Va extends FI{constructor(A,I){super(),this.condition=A,this.body=I}get astNodeType(){return"elseif"}search(A){this.condition.search(A),this.searchBlock(this.body,A)}}class uE extends FI{constructor(A,I,g){super(),this.name=A,this.type=I,this.attributes=g}get astNodeType(){return"member"}}class mE extends FI{constructor(A,I){super(),this.name=A,this.value=I}get astNodeType(){return"attribute"}}class cI{constructor(A,I){this.parent=null,this.typeInfo=A,this.parent=I,this.id=cI._id++}setDataValue(A,I,g,B){console.error(`SetDataValue: Not implemented for ${this.constructor.name}`)}getSubData(A,I,g){return console.error(`GetDataValue: Not implemented for ${this.constructor.name}`),null}toString(){return`<${this.typeInfo.getTypeName()}>`}}cI._id=0;class xE extends cI{constructor(A,I){super(A,I)}clone(){return this}toString(){return this.typeInfo.name}}class xQ extends cI{constructor(){super(new wI("void",null),null)}clone(){return this}toString(){return"void"}}xQ.void=new xQ;class Kg extends cI{constructor(A){super(new dQ("pointer",A.typeInfo,null),null),this.reference=A}clone(){return this}setDataValue(A,I,g,B){this.reference.setDataValue(A,I,g,B)}getSubData(A,I,g){return I?this.reference.getSubData(A,I,g):this}toString(){return`&${this.reference.toString()}`}}class U extends cI{constructor(A,I,g=null){super(I,g),A instanceof Int32Array||A instanceof Uint32Array||A instanceof Float32Array?this.data=A:this.typeInfo.name==="x32"?A-Math.floor(A)!==0?this.data=new Float32Array([A]):this.data=A>=0?new Uint32Array([A]):new Int32Array([A]):this.typeInfo.name==="i32"||this.typeInfo.name==="bool"?this.data=new Int32Array([A]):this.typeInfo.name==="u32"?this.data=new Uint32Array([A]):this.typeInfo.name==="f32"||this.typeInfo.name==="f16"?this.data=new Float32Array([A]):console.error("ScalarData2: Invalid type",I)}clone(){if(this.data instanceof Float32Array)return new U(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new U(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new U(new Uint32Array(this.data),this.typeInfo,null);throw new Error("ScalarData: Invalid data type")}get value(){return this.data[0]}set value(A){this.data[0]=A}setDataValue(A,I,g,B){if(g)return void console.error("SetDataValue: Scalar data does not support postfix",g);if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);let C=I.data[0];this.typeInfo.name==="i32"||this.typeInfo.name==="u32"?C=Math.floor(C):this.typeInfo.name==="bool"&&(C=C?1:0),this.data[0]=C}getSubData(A,I,g){return I?(console.error("getSubData: Scalar data does not support postfix",I),null):this}toString(){return`${this.value}`}}function Oa(Q,A,I){const g=A.length;return g===2?I==="f32"?new F(new Float32Array(A),Q.getTypeInfo("vec2f")):I==="i32"||I==="bool"?new F(new Int32Array(A),Q.getTypeInfo("vec2i")):I==="u32"?new F(new Uint32Array(A),Q.getTypeInfo("vec2u")):I==="f16"?new F(new Float32Array(A),Q.getTypeInfo("vec2h")):(console.error(`getSubData: Unknown format ${I}`),null):g===3?I==="f32"?new F(new Float32Array(A),Q.getTypeInfo("vec3f")):I==="i32"||I==="bool"?new F(new Int32Array(A),Q.getTypeInfo("vec3i")):I==="u32"?new F(new Uint32Array(A),Q.getTypeInfo("vec3u")):I==="f16"?new F(new Float32Array(A),Q.getTypeInfo("vec3h")):(console.error(`getSubData: Unknown format ${I}`),null):g===4?I==="f32"?new F(new Float32Array(A),Q.getTypeInfo("vec4f")):I==="i32"||I==="bool"?new F(new Int32Array(A),Q.getTypeInfo("vec4i")):I==="u32"?new F(new Uint32Array(A),Q.getTypeInfo("vec4u")):I==="f16"?new F(new Float32Array(A),Q.getTypeInfo("vec4h")):(console.error(`getSubData: Unknown format ${I}`),null):(console.error(`getSubData: Invalid vector size ${A.length}`),null)}class F extends cI{constructor(A,I,g=null){if(super(I,g),A instanceof Float32Array||A instanceof Uint32Array||A instanceof Int32Array)this.data=A;else{const B=this.typeInfo.name;B==="vec2f"||B==="vec3f"||B==="vec4f"?this.data=new Float32Array(A):B==="vec2i"||B==="vec3i"||B==="vec4i"?this.data=new Int32Array(A):B==="vec2u"||B==="vec3u"||B==="vec4u"?this.data=new Uint32Array(A):B==="vec2h"||B==="vec3h"||B==="vec4h"?this.data=new Float32Array(A):B==="vec2b"||B==="vec3b"||B==="vec4b"?this.data=new Int32Array(A):B==="vec2"||B==="vec3"||B==="vec4"?this.data=new Float32Array(A):console.error(`VectorData: Invalid type ${B}`)}}clone(){if(this.data instanceof Float32Array)return new F(new Float32Array(this.data),this.typeInfo,null);if(this.data instanceof Int32Array)return new F(new Int32Array(this.data),this.typeInfo,null);if(this.data instanceof Uint32Array)return new F(new Uint32Array(this.data),this.typeInfo,null);throw new Error("VectorData: Invalid data type")}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set vector postfix"):I instanceof F?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;let B=A.getTypeInfo("f32");if(this.typeInfo instanceof Cg)B=this.typeInfo.format||B;else{const E=this.typeInfo.name;E==="vec2f"||E==="vec3f"||E==="vec4f"?B=A.getTypeInfo("f32"):E==="vec2i"||E==="vec3i"||E==="vec4i"?B=A.getTypeInfo("i32"):E==="vec2b"||E==="vec3b"||E==="vec4b"?B=A.getTypeInfo("bool"):E==="vec2u"||E==="vec3u"||E==="vec4u"?B=A.getTypeInfo("u32"):E==="vec2h"||E==="vec3h"||E==="vec4h"?B=A.getTypeInfo("f16"):console.error(`GetSubData: Unknown type ${E}`)}let C=this;for(;I!==null&&C!==null;){if(I instanceof Yg){const E=I.index;let i=-1;if(E instanceof vA){if(!(E.value instanceof U))return console.error(`GetSubData: Invalid array index ${E.value}`),null;i=E.value.value}else{const o=A.evalExpression(E,g);if(!(o instanceof U))return console.error("GetSubData: Unknown index type",E),null;i=o.value}if(i<0||i>=C.data.length)return console.error("GetSubData: Index out of range",i),null;if(C.data instanceof Float32Array){const o=new Float32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Int32Array){const o=new Int32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}if(C.data instanceof Uint32Array){const o=new Uint32Array(C.data.buffer,C.data.byteOffset+4*i,1);return new U(o,B)}throw new Error("GetSubData: Invalid data type")}if(!(I instanceof Eg))return console.error("GetSubData: Unknown postfix",I),null;{const E=I.value.toLowerCase();if(E.length===1){let o=0;if(E==="x"||E==="r")o=0;else if(E==="y"||E==="g")o=1;else if(E==="z"||E==="b")o=2;else{if(E!=="w"&&E!=="a")return console.error(`GetSubData: Unknown member ${E}`),null;o=3}if(this.data instanceof Float32Array){let a=new Float32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Int32Array){let a=new Int32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}if(this.data instanceof Uint32Array){let a=new Uint32Array(this.data.buffer,this.data.byteOffset+4*o,1);return new U(a,B,this)}}const i=[];for(const o of E)o==="x"||o==="r"?i.push(this.data[0]):o==="y"||o==="g"?i.push(this.data[1]):o==="z"||o==="b"?i.push(this.data[2]):o==="w"||o==="a"?i.push(this.data[3]):console.error(`GetDataValue: Unknown member ${o}`);C=Oa(A,i,B.name)}I=I.postfix}return C}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class EA extends cI{constructor(A,I,g=null){super(I,g),A instanceof Float32Array?this.data=A:this.data=new Float32Array(A)}clone(){return new EA(new Float32Array(this.data),this.typeInfo,null)}setDataValue(A,I,g,B){g instanceof Eg?console.error("TODO: Set matrix postfix"):I instanceof EA?this.data=I.data:console.error("SetDataValue: Invalid value",I)}getSubData(A,I,g){if(I===null)return this;const B=this.typeInfo.name;if(A.getTypeInfo("f32"),this.typeInfo instanceof Cg)this.typeInfo.format;else if(B.endsWith("f"))A.getTypeInfo("f32");else if(B.endsWith("i"))A.getTypeInfo("i32");else if(B.endsWith("u"))A.getTypeInfo("u32");else{if(!B.endsWith("h"))return console.error(`GetDataValue: Unknown type ${B}`),null;A.getTypeInfo("f16")}if(I instanceof Yg){const C=I.index;let E=-1;if(C instanceof vA){if(!(C.value instanceof U))return console.error(`GetDataValue: Invalid array index ${C.value}`),null;E=C.value.value}else{const a=A.evalExpression(C,g);if(!(a instanceof U))return console.error("GetDataValue: Unknown index type",C),null;E=a.value}if(E<0||E>=this.data.length)return console.error("GetDataValue: Index out of range",E),null;const i=B.endsWith("h")?"h":"f";let o;if(B==="mat2x2"||B==="mat2x2f"||B==="mat2x2h"||B==="mat3x2"||B==="mat3x2f"||B==="mat3x2h"||B==="mat4x2"||B==="mat4x2f"||B==="mat4x2h")o=new F(new Float32Array(this.data.buffer,this.data.byteOffset+2*E*4,2),A.getTypeInfo(`vec2${i}`));else if(B==="mat2x3"||B==="mat2x3f"||B==="mat2x3h"||B==="mat3x3"||B==="mat3x3f"||B==="mat3x3h"||B==="mat4x3"||B==="mat4x3f"||B==="mat4x3h")o=new F(new Float32Array(this.data.buffer,this.data.byteOffset+3*E*4,3),A.getTypeInfo(`vec3${i}`));else{if(B!=="mat2x4"&&B!=="mat2x4f"&&B!=="mat2x4h"&&B!=="mat3x4"&&B!=="mat3x4f"&&B!=="mat3x4h"&&B!=="mat4x4"&&B!=="mat4x4f"&&B!=="mat4x4h")return console.error(`GetDataValue: Unknown type ${B}`),null;o=new F(new Float32Array(this.data.buffer,this.data.byteOffset+4*E*4,4),A.getTypeInfo(`vec4${i}`))}return I.postfix?o.getSubData(A,I.postfix,g):o}return console.error("GetDataValue: Invalid postfix",I),null}toString(){let A=`${this.data[0]}`;for(let I=1;I<this.data.length;++I)A+=`, ${this.data[I]}`;return A}}class lA extends cI{constructor(A,I,g=0,B=null){super(I,B),this.buffer=A instanceof ArrayBuffer?A:A.buffer,this.offset=g}clone(){const A=new Uint8Array(new Uint8Array(this.buffer,this.offset,this.typeInfo.size));return new lA(A.buffer,this.typeInfo,0,null)}setDataValue(A,I,g,B){if(I===null)return void console.log("setDataValue: NULL data.");let C=this.offset,E=this.typeInfo;for(;g;){if(g instanceof Yg)if(E instanceof bI){const i=g.index;if(i instanceof vA){if(!(i.value instanceof U))return void console.error(`SetDataValue: Invalid index type ${i.value}`);C+=i.value.value*E.stride}else{const o=A.evalExpression(i,B);if(!(o instanceof U))return void console.error("SetDataValue: Unknown index type",i);C+=o.value*E.stride}E=E.format}else console.error(`SetDataValue: Type ${E.getTypeName()} is not an array`);else{if(!(g instanceof Eg))return void console.error("SetDataValue: Unknown postfix type",g);{const i=g.value;if(E instanceof WI){let o=!1;for(const a of E.members)if(a.name===i){C+=a.offset,E=a.type,o=!0;break}if(!o)return void console.error(`SetDataValue: Member ${i} not found`)}else if(E instanceof wI){const o=E.getTypeName();let a=0;if(i==="x"||i==="r")a=0;else if(i==="y"||i==="g")a=1;else if(i==="z"||i==="b")a=2;else{if(i!=="w"&&i!=="a")return void console.error(`SetDataValue: Unknown member ${i}`);a=3}if(!(I instanceof U))return void console.error("SetDataValue: Invalid value",I);const D=I.value;return o==="vec2f"?void(new Float32Array(this.buffer,C,2)[a]=D):o==="vec3f"?void(new Float32Array(this.buffer,C,3)[a]=D):o==="vec4f"?void(new Float32Array(this.buffer,C,4)[a]=D):o==="vec2i"?void(new Int32Array(this.buffer,C,2)[a]=D):o==="vec3i"?void(new Int32Array(this.buffer,C,3)[a]=D):o==="vec4i"?void(new Int32Array(this.buffer,C,4)[a]=D):o==="vec2u"?void(new Uint32Array(this.buffer,C,2)[a]=D):o==="vec3u"?void(new Uint32Array(this.buffer,C,3)[a]=D):o==="vec4u"?void(new Uint32Array(this.buffer,C,4)[a]=D):void console.error(`SetDataValue: Type ${o} is not a struct`)}}}g=g.postfix}this.setData(A,I,E,C,B)}setData(A,I,g,B,C){const E=g.getTypeName();if(E!=="f32"&&E!=="f16")if(E!=="i32"&&E!=="atomic<i32>"&&E!=="x32")if(E!=="u32"&&E!=="atomic<u32>")if(E!=="bool"){if(E==="vec2f"||E==="vec2h"){const i=new Float32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3f"||E==="vec3h"){const i=new Float32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4f"||E==="vec4h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2i"){const i=new Int32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3i"){const i=new Int32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4i"){const i=new Int32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2u"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3u"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4u"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="vec2b"){const i=new Uint32Array(this.buffer,B,2);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1]):(i[0]=I[0],i[1]=I[1]))}if(E==="vec3b"){const i=new Uint32Array(this.buffer,B,3);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2]):(i[0]=I[0],i[1]=I[1],i[2]=I[2]))}if(E==="vec4b"){const i=new Uint32Array(this.buffer,B,4);return void(I instanceof F?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x2f"||E==="mat2x2h"){const i=new Float32Array(this.buffer,B,4);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3]))}if(E==="mat2x3f"||E==="mat2x3h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat2x4f"||E==="mat2x4h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat3x2f"||E==="mat3x2h"){const i=new Float32Array(this.buffer,B,6);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5]))}if(E==="mat3x3f"||E==="mat3x3h"){const i=new Float32Array(this.buffer,B,9);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8]))}if(E==="mat3x4f"||E==="mat3x4h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x2f"||E==="mat4x2h"){const i=new Float32Array(this.buffer,B,8);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7]))}if(E==="mat4x3f"||E==="mat4x3h"){const i=new Float32Array(this.buffer,B,12);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11]))}if(E==="mat4x4f"||E==="mat4x4h"){const i=new Float32Array(this.buffer,B,16);return void(I instanceof EA?(i[0]=I.data[0],i[1]=I.data[1],i[2]=I.data[2],i[3]=I.data[3],i[4]=I.data[4],i[5]=I.data[5],i[6]=I.data[6],i[7]=I.data[7],i[8]=I.data[8],i[9]=I.data[9],i[10]=I.data[10],i[11]=I.data[11],i[12]=I.data[12],i[13]=I.data[13],i[14]=I.data[14],i[15]=I.data[15]):(i[0]=I[0],i[1]=I[1],i[2]=I[2],i[3]=I[3],i[4]=I[4],i[5]=I[5],i[6]=I[6],i[7]=I[7],i[8]=I[8],i[9]=I[9],i[10]=I[10],i[11]=I[11],i[12]=I[12],i[13]=I[13],i[14]=I[14],i[15]=I[15]))}if(I instanceof lA){if(g===I.typeInfo)return void new Uint8Array(this.buffer,B,I.buffer.byteLength).set(new Uint8Array(I.buffer));console.error("SetDataValue: Type mismatch",E,I.typeInfo.getTypeName())}else console.error(`SetData: Unknown type ${E}`)}else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Uint32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Int32Array(this.buffer,B,1)[0]=I.value);else I instanceof U&&(new Float32Array(this.buffer,B,1)[0]=I.value)}getSubData(A,I,g){var B,C,E;if(I===null)return this;let i=this.offset,o=this.typeInfo;for(;I;){if(I instanceof Yg){const D=I.index,s=D instanceof NI?A.evalExpression(D,g):D;let y=0;if(s instanceof U?y=s.value:typeof s=="number"?y=s:console.error("GetDataValue: Invalid index type",D),o instanceof bI)i+=y*o.stride,o=o.format;else{const e=o.getTypeName();e==="mat4x4"||e==="mat4x4f"||e==="mat4x4h"?(i+=16*y,o=A.getTypeInfo("vec4f")):e==="mat4x3"||e==="mat4x3f"||e==="mat4x3h"?(i+=12*y,o=A.getTypeInfo("vec3f")):e==="mat4x2"||e==="mat4x2f"||e==="mat4x2h"?(i+=8*y,o=A.getTypeInfo("vec2f")):e==="mat3x4"||e==="mat3x4f"||e==="mat3x4h"?(i+=12*y,o=A.getTypeInfo("vec4f")):e==="mat3x3"||e==="mat3x3f"||e==="mat3x3h"?(i+=9*y,o=A.getTypeInfo("vec3f")):e==="mat3x2"||e==="mat3x2f"||e==="mat3x2h"?(i+=6*y,o=A.getTypeInfo("vec2f")):e==="mat2x4"||e==="mat2x4f"||e==="mat2x4h"?(i+=8*y,o=A.getTypeInfo("vec4f")):e==="mat2x3"||e==="mat2x3f"||e==="mat2x3h"?(i+=6*y,o=A.getTypeInfo("vec3f")):e==="mat2x2"||e==="mat2x2f"||e==="mat2x2h"?(i+=4*y,o=A.getTypeInfo("vec2f")):e==="vec2f"||e==="vec3f"||e==="vec4f"?(i+=4*y,o=A.getTypeInfo("f32")):e==="vec2h"||e==="vec3h"||e==="vec4h"?(i+=2*y,o=A.getTypeInfo("f16")):e==="vec2b"||e==="vec3b"||e==="vec4b"?(i+=1*y,o=A.getTypeInfo("bool")):e==="vec2i"||e==="vec3i"||e==="vec4i"?(i+=4*y,o=A.getTypeInfo("i32")):e==="vec2u"||e==="vec3u"||e==="vec4u"?(i+=4*y,o=A.getTypeInfo("u32")):console.error(`getDataValue: Type ${o.getTypeName()} is not an array`)}}else{if(!(I instanceof Eg))return console.error("GetDataValue: Unknown postfix type",I),null;{const D=I.value;if(o instanceof WI){let s=!1;for(const y of o.members)if(y.name===D){i+=y.offset,o=y.type,s=!0;break}if(!s)return console.error(`GetDataValue: Member ${D} not found`),null}else if(o instanceof wI){const s=o.getTypeName();if(s==="vec2f"||s==="vec3f"||s==="vec4f"||s==="vec2i"||s==="vec3i"||s==="vec4i"||s==="vec2u"||s==="vec3u"||s==="vec4u"||s==="vec2b"||s==="vec3b"||s==="vec4b"||s==="vec2h"||s==="vec3h"||s==="vec4h"||s==="vec2"||s==="vec3"||s==="vec4"){if(D.length>0&&D.length<5){let y="f";const e=[];for(let Y=0;Y<D.length;++Y){const u=D[Y].toLowerCase();let H=0;if(u==="x"||u==="r")H=0;else if(u==="y"||u==="g")H=1;else if(u==="z"||u==="b")H=2;else{if(u!=="w"&&u!=="a")return console.error(`Unknown member ${D}`),null;H=3}if(D.length===1){if(s.endsWith("f"))return this.buffer.byteLength<i+4*H+4?(console.log("Insufficient buffer data"),null):new U(new Float32Array(this.buffer,i+4*H,1),A.getTypeInfo("f32"),this);if(s.endsWith("h"))return new U(new Float32Array(this.buffer,i+4*H,1),A.getTypeInfo("f16"),this);if(s.endsWith("i"))return new U(new Int32Array(this.buffer,i+4*H,1),A.getTypeInfo("i32"),this);if(s.endsWith("b"))return new U(new Int32Array(this.buffer,i+4*H,1),A.getTypeInfo("bool"),this);if(s.endsWith("u"))return new U(new Uint32Array(this.buffer,i+4*H,1),A.getTypeInfo("i32"),this)}if(s==="vec2f")e.push(new Float32Array(this.buffer,i,2)[H]);else if(s==="vec3f"){if(i+12>=this.buffer.byteLength)return console.log("Insufficient buffer data"),null;const W=new Float32Array(this.buffer,i,3);e.push(W[H])}else if(s==="vec4f")e.push(new Float32Array(this.buffer,i,4)[H]);else if(s==="vec2i")y="i",e.push(new Int32Array(this.buffer,i,2)[H]);else if(s==="vec3i")y="i",e.push(new Int32Array(this.buffer,i,3)[H]);else if(s==="vec4i")y="i",e.push(new Int32Array(this.buffer,i,4)[H]);else if(s==="vec2u"){y="u";const W=new Uint32Array(this.buffer,i,2);e.push(W[H])}else s==="vec3u"?(y="u",e.push(new Uint32Array(this.buffer,i,3)[H])):s==="vec4u"&&(y="u",e.push(new Uint32Array(this.buffer,i,4)[H]))}return e.length===2?o=A.getTypeInfo(`vec2${y}`):e.length===3?o=A.getTypeInfo(`vec3${y}`):e.length===4?o=A.getTypeInfo(`vec4${y}`):console.error(`GetDataValue: Invalid vector length ${e.length}`),new F(e,o,null)}return console.error(`GetDataValue: Unknown member ${D}`),null}return console.error(`GetDataValue: Type ${s} is not a struct`),null}}}I=I.postfix}const a=o.getTypeName();return a==="f32"?new U(new Float32Array(this.buffer,i,1),o,this):a==="i32"?new U(new Int32Array(this.buffer,i,1),o,this):a==="u32"?new U(new Uint32Array(this.buffer,i,1),o,this):a==="vec2f"?new F(new Float32Array(this.buffer,i,2),o,this):a==="vec3f"?new F(new Float32Array(this.buffer,i,3),o,this):a==="vec4f"?new F(new Float32Array(this.buffer,i,4),o,this):a==="vec2i"?new F(new Int32Array(this.buffer,i,2),o,this):a==="vec3i"?new F(new Int32Array(this.buffer,i,3),o,this):a==="vec4i"?new F(new Int32Array(this.buffer,i,4),o,this):a==="vec2u"?new F(new Uint32Array(this.buffer,i,2),o,this):a==="vec3u"?new F(new Uint32Array(this.buffer,i,3),o,this):a==="vec4u"?new F(new Uint32Array(this.buffer,i,4),o,this):o instanceof Cg&&o.name==="atomic"?((B=o.format)===null||B===void 0?void 0:B.name)==="u32"?new U(new Uint32Array(this.buffer,i,1)[0],o.format,this):((C=o.format)===null||C===void 0?void 0:C.name)==="i32"?new U(new Int32Array(this.buffer,i,1)[0],o.format,this):(console.error(`GetDataValue: Invalid atomic format ${(E=o.format)===null||E===void 0?void 0:E.name}`),null):new lA(this.buffer,o,i,this)}toArray(){const A=this.typeInfo.getTypeName();return A==="f32"||A==="f16"?new Float32Array(this.buffer,this.offset,1):A==="i32"||A==="atomic<i32>"||A==="x32"?new Int32Array(this.buffer,this.offset,1):A==="u32"||A==="atomic<u32>"?new Uint32Array(this.buffer,this.offset,1):A==="bool"?new Int32Array(this.buffer,this.offset,1):A==="vec2f"||A==="vec2h"?new Float32Array(this.buffer,this.offset,2):A==="vec3f"||A==="vec3h"?new Float32Array(this.buffer,this.offset,3):A==="vec4f"||A==="vec4h"?new Float32Array(this.buffer,this.offset,4):A==="vec2i"?new Int32Array(this.buffer,this.offset,2):A==="vec3i"?new Int32Array(this.buffer,this.offset,3):A==="vec4i"?new Int32Array(this.buffer,this.offset,4):A==="vec2u"?new Uint32Array(this.buffer,this.offset,2):A==="vec3u"?new Uint32Array(this.buffer,this.offset,3):A==="vec4u"?new Uint32Array(this.buffer,this.offset,4):A==="vec2b"?new Uint32Array(this.buffer,this.offset,2):A==="vec3b"?new Uint32Array(this.buffer,this.offset,3):A==="vec4b"?new Uint32Array(this.buffer,this.offset,4):A==="mat2x2f"||A==="mat2x2h"?new Float32Array(this.buffer,this.offset,4):A==="mat2x3f"||A==="mat2x3h"?new Float32Array(this.buffer,this.offset,6):A==="mat2x4f"||A==="mat2x4h"?new Float32Array(this.buffer,this.offset,8):A==="mat3x2f"||A==="mat3x2h"?new Float32Array(this.buffer,this.offset,6):A==="mat3x3f"||A==="mat3x3h"?new Float32Array(this.buffer,this.offset,9):A==="mat3x4f"||A==="mat3x4h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x2f"||A==="mat4x2h"?new Float32Array(this.buffer,this.offset,8):A==="mat4x3f"||A==="mat4x3h"?new Float32Array(this.buffer,this.offset,12):A==="mat4x4f"||A==="mat4x4h"?new Float32Array(this.buffer,this.offset,16):null}toString(){let A="";if(this.typeInfo instanceof bI)if(this.typeInfo.format.name==="f32"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="i32"){const I=new Int32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="u32"){const I=new Uint32Array(this.buffer,this.offset);A=`[${I[0]}`;for(let g=1;g<I.length;++g)A+=`, ${I[g]}`}else if(this.typeInfo.format.name==="vec2f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}]`;for(let g=1;g<I.length/2;++g)A+=`, [${I[2*g]}, ${I[2*g+1]}]`}else if(this.typeInfo.format.name==="vec3f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}]`}else if(this.typeInfo.format.name==="vec4f"){const I=new Float32Array(this.buffer,this.offset);A=`[${I[0]}, ${I[1]}, ${I[2]}, ${I[3]}]`;for(let g=4;g<I.length;g+=4)A+=`, [${I[g]}, ${I[g+1]}, ${I[g+2]}, ${I[g+3]}]`}else A="[...]";else this.typeInfo instanceof WI?A+="{...}":A="[...]";return A}}class fI extends cI{constructor(A,I,g,B){super(I,null),this.data=A,this.descriptor=g,this.view=B}clone(){return new fI(this.data,this.typeInfo,this.descriptor,this.view)}get width(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>0?(A=g[0])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.width)!==null&&I!==void 0?I:0}get height(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>1?(A=g[1])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.height)!==null&&I!==void 0?I:0}get depthOrArrayLayers(){var A,I;const g=this.descriptor.size;return g instanceof Array&&g.length>2?(A=g[2])!==null&&A!==void 0?A:0:g instanceof Object&&(I=g.depthOrArrayLayers)!==null&&I!==void 0?I:0}get format(){var A;return this.descriptor&&(A=this.descriptor.format)!==null&&A!==void 0?A:"rgba8unorm"}get sampleCount(){var A;return this.descriptor&&(A=this.descriptor.sampleCount)!==null&&A!==void 0?A:1}get mipLevelCount(){var A;return this.descriptor&&(A=this.descriptor.mipLevelCount)!==null&&A!==void 0?A:1}get dimension(){var A;return this.descriptor&&(A=this.descriptor.dimension)!==null&&A!==void 0?A:"2d"}getMipLevelSize(A){if(A>=this.mipLevelCount)return[0,0,0];const I=[this.width,this.height,this.depthOrArrayLayers];for(let g=0;g<I.length;++g)I[g]=Math.max(1,I[g]>>A);return I}get texelByteSize(){const A=this.format,I=qQ[A];return I?I.isDepthStencil?4:I.bytesPerBlock:0}get bytesPerRow(){return this.width*this.texelByteSize}get isDepthStencil(){const A=this.format,I=qQ[A];return!!I&&I.isDepthStencil}getGpuSize(){const A=this.format,I=qQ[A],g=this.width;if(!A||g<=0||!I)return-1;const B=this.height,C=this.depthOrArrayLayers,E=this.dimension;return g/I.blockWidth*(E==="1d"?1:B/I.blockHeight)*I.bytesPerBlock*C}getPixel(A,I,g=0,B=0){const C=this.texelByteSize,E=this.bytesPerRow,i=this.height,o=this.data[B];return Wa(new Uint8Array(o),A,I,g,B,i,E,C,this.format)}setPixel(A,I,g,B,C){const E=this.texelByteSize,i=this.bytesPerRow,o=this.height,a=this.data[B];(function(D,s,y,e,Y,u,H,W,z,x){const l=e*(H>>=Y)*(u>>=Y)+y*H+s*W;switch(z){case"r8unorm":return void UA(D,l,"8unorm",1,x);case"r8snorm":return void UA(D,l,"8snorm",1,x);case"r8uint":return void UA(D,l,"8uint",1,x);case"r8sint":return void UA(D,l,"8sint",1,x);case"rg8unorm":return void UA(D,l,"8unorm",2,x);case"rg8snorm":return void UA(D,l,"8snorm",2,x);case"rg8uint":return void UA(D,l,"8uint",2,x);case"rg8sint":return void UA(D,l,"8sint",2,x);case"rgba8unorm-srgb":case"rgba8unorm":case"bgra8unorm-srgb":case"bgra8unorm":return void UA(D,l,"8unorm",4,x);case"rgba8snorm":return void UA(D,l,"8snorm",4,x);case"rgba8uint":return void UA(D,l,"8uint",4,x);case"rgba8sint":return void UA(D,l,"8sint",4,x);case"r16uint":return void UA(D,l,"16uint",1,x);case"r16sint":return void UA(D,l,"16sint",1,x);case"r16float":return void UA(D,l,"16float",1,x);case"rg16uint":return void UA(D,l,"16uint",2,x);case"rg16sint":return void UA(D,l,"16sint",2,x);case"rg16float":return void UA(D,l,"16float",2,x);case"rgba16uint":return void UA(D,l,"16uint",4,x);case"rgba16sint":return void UA(D,l,"16sint",4,x);case"rgba16float":return void UA(D,l,"16float",4,x);case"r32uint":return void UA(D,l,"32uint",1,x);case"r32sint":return void UA(D,l,"32sint",1,x);case"depth16unorm":case"depth24plus":case"depth24plus-stencil8":case"depth32float":case"depth32float-stencil8":case"r32float":return void UA(D,l,"32float",1,x);case"rg32uint":return void UA(D,l,"32uint",2,x);case"rg32sint":return void UA(D,l,"32sint",2,x);case"rg32float":return void UA(D,l,"32float",2,x);case"rgba32uint":return void UA(D,l,"32uint",4,x);case"rgba32sint":return void UA(D,l,"32sint",4,x);case"rgba32float":return void UA(D,l,"32float",4,x);case"rg11b10ufloat":console.error("TODO: rg11b10ufloat not supported for writing")}})(new Uint8Array(a),A,I,g,B,o,i,E,this.format,C)}}(Q=>{Q[Q.token=0]="token",Q[Q.keyword=1]="keyword",Q[Q.reserved=2]="reserved"})(R||(R={}));class c{constructor(A,I,g){this.name=A,this.type=I,this.rule=g}toString(){return this.name}}class t{}M=t,t.none=new c("",R.reserved,""),t.eof=new c("EOF",R.token,""),t.reserved={asm:new c("asm",R.reserved,"asm"),bf16:new c("bf16",R.reserved,"bf16"),do:new c("do",R.reserved,"do"),enum:new c("enum",R.reserved,"enum"),f16:new c("f16",R.reserved,"f16"),f64:new c("f64",R.reserved,"f64"),handle:new c("handle",R.reserved,"handle"),i8:new c("i8",R.reserved,"i8"),i16:new c("i16",R.reserved,"i16"),i64:new c("i64",R.reserved,"i64"),mat:new c("mat",R.reserved,"mat"),premerge:new c("premerge",R.reserved,"premerge"),regardless:new c("regardless",R.reserved,"regardless"),typedef:new c("typedef",R.reserved,"typedef"),u8:new c("u8",R.reserved,"u8"),u16:new c("u16",R.reserved,"u16"),u64:new c("u64",R.reserved,"u64"),unless:new c("unless",R.reserved,"unless"),using:new c("using",R.reserved,"using"),vec:new c("vec",R.reserved,"vec"),void:new c("void",R.reserved,"void")},t.keywords={array:new c("array",R.keyword,"array"),atomic:new c("atomic",R.keyword,"atomic"),bool:new c("bool",R.keyword,"bool"),f32:new c("f32",R.keyword,"f32"),i32:new c("i32",R.keyword,"i32"),mat2x2:new c("mat2x2",R.keyword,"mat2x2"),mat2x3:new c("mat2x3",R.keyword,"mat2x3"),mat2x4:new c("mat2x4",R.keyword,"mat2x4"),mat3x2:new c("mat3x2",R.keyword,"mat3x2"),mat3x3:new c("mat3x3",R.keyword,"mat3x3"),mat3x4:new c("mat3x4",R.keyword,"mat3x4"),mat4x2:new c("mat4x2",R.keyword,"mat4x2"),mat4x3:new c("mat4x3",R.keyword,"mat4x3"),mat4x4:new c("mat4x4",R.keyword,"mat4x4"),ptr:new c("ptr",R.keyword,"ptr"),sampler:new c("sampler",R.keyword,"sampler"),sampler_comparison:new c("sampler_comparison",R.keyword,"sampler_comparison"),struct:new c("struct",R.keyword,"struct"),texture_1d:new c("texture_1d",R.keyword,"texture_1d"),texture_2d:new c("texture_2d",R.keyword,"texture_2d"),texture_2d_array:new c("texture_2d_array",R.keyword,"texture_2d_array"),texture_3d:new c("texture_3d",R.keyword,"texture_3d"),texture_cube:new c("texture_cube",R.keyword,"texture_cube"),texture_cube_array:new c("texture_cube_array",R.keyword,"texture_cube_array"),texture_multisampled_2d:new c("texture_multisampled_2d",R.keyword,"texture_multisampled_2d"),texture_storage_1d:new c("texture_storage_1d",R.keyword,"texture_storage_1d"),texture_storage_2d:new c("texture_storage_2d",R.keyword,"texture_storage_2d"),texture_storage_2d_array:new c("texture_storage_2d_array",R.keyword,"texture_storage_2d_array"),texture_storage_3d:new c("texture_storage_3d",R.keyword,"texture_storage_3d"),texture_depth_2d:new c("texture_depth_2d",R.keyword,"texture_depth_2d"),texture_depth_2d_array:new c("texture_depth_2d_array",R.keyword,"texture_depth_2d_array"),texture_depth_cube:new c("texture_depth_cube",R.keyword,"texture_depth_cube"),texture_depth_cube_array:new c("texture_depth_cube_array",R.keyword,"texture_depth_cube_array"),texture_depth_multisampled_2d:new c("texture_depth_multisampled_2d",R.keyword,"texture_depth_multisampled_2d"),texture_external:new c("texture_external",R.keyword,"texture_external"),u32:new c("u32",R.keyword,"u32"),vec2:new c("vec2",R.keyword,"vec2"),vec3:new c("vec3",R.keyword,"vec3"),vec4:new c("vec4",R.keyword,"vec4"),bitcast:new c("bitcast",R.keyword,"bitcast"),block:new c("block",R.keyword,"block"),break:new c("break",R.keyword,"break"),case:new c("case",R.keyword,"case"),continue:new c("continue",R.keyword,"continue"),continuing:new c("continuing",R.keyword,"continuing"),default:new c("default",R.keyword,"default"),diagnostic:new c("diagnostic",R.keyword,"diagnostic"),discard:new c("discard",R.keyword,"discard"),else:new c("else",R.keyword,"else"),enable:new c("enable",R.keyword,"enable"),fallthrough:new c("fallthrough",R.keyword,"fallthrough"),false:new c("false",R.keyword,"false"),fn:new c("fn",R.keyword,"fn"),for:new c("for",R.keyword,"for"),function:new c("function",R.keyword,"function"),if:new c("if",R.keyword,"if"),let:new c("let",R.keyword,"let"),const:new c("const",R.keyword,"const"),loop:new c("loop",R.keyword,"loop"),while:new c("while",R.keyword,"while"),private:new c("private",R.keyword,"private"),read:new c("read",R.keyword,"read"),read_write:new c("read_write",R.keyword,"read_write"),return:new c("return",R.keyword,"return"),requires:new c("requires",R.keyword,"requires"),storage:new c("storage",R.keyword,"storage"),immediate:new c("immediate",R.keyword,"immediate"),switch:new c("switch",R.keyword,"switch"),true:new c("true",R.keyword,"true"),alias:new c("alias",R.keyword,"alias"),type:new c("type",R.keyword,"type"),uniform:new c("uniform",R.keyword,"uniform"),var:new c("var",R.keyword,"var"),override:new c("override",R.keyword,"override"),workgroup:new c("workgroup",R.keyword,"workgroup"),write:new c("write",R.keyword,"write"),r8unorm:new c("r8unorm",R.keyword,"r8unorm"),r8snorm:new c("r8snorm",R.keyword,"r8snorm"),r8uint:new c("r8uint",R.keyword,"r8uint"),r8sint:new c("r8sint",R.keyword,"r8sint"),r16uint:new c("r16uint",R.keyword,"r16uint"),r16sint:new c("r16sint",R.keyword,"r16sint"),r16float:new c("r16float",R.keyword,"r16float"),rg8unorm:new c("rg8unorm",R.keyword,"rg8unorm"),rg8snorm:new c("rg8snorm",R.keyword,"rg8snorm"),rg8uint:new c("rg8uint",R.keyword,"rg8uint"),rg8sint:new c("rg8sint",R.keyword,"rg8sint"),r32uint:new c("r32uint",R.keyword,"r32uint"),r32sint:new c("r32sint",R.keyword,"r32sint"),r32float:new c("r32float",R.keyword,"r32float"),rg16uint:new c("rg16uint",R.keyword,"rg16uint"),rg16sint:new c("rg16sint",R.keyword,"rg16sint"),rg16float:new c("rg16float",R.keyword,"rg16float"),rgba8unorm:new c("rgba8unorm",R.keyword,"rgba8unorm"),rgba8unorm_srgb:new c("rgba8unorm_srgb",R.keyword,"rgba8unorm_srgb"),rgba8snorm:new c("rgba8snorm",R.keyword,"rgba8snorm"),rgba8uint:new c("rgba8uint",R.keyword,"rgba8uint"),rgba8sint:new c("rgba8sint",R.keyword,"rgba8sint"),bgra8unorm:new c("bgra8unorm",R.keyword,"bgra8unorm"),bgra8unorm_srgb:new c("bgra8unorm_srgb",R.keyword,"bgra8unorm_srgb"),rgb10a2unorm:new c("rgb10a2unorm",R.keyword,"rgb10a2unorm"),rg11b10float:new c("rg11b10float",R.keyword,"rg11b10float"),rg32uint:new c("rg32uint",R.keyword,"rg32uint"),rg32sint:new c("rg32sint",R.keyword,"rg32sint"),rg32float:new c("rg32float",R.keyword,"rg32float"),rgba16uint:new c("rgba16uint",R.keyword,"rgba16uint"),rgba16sint:new c("rgba16sint",R.keyword,"rgba16sint"),rgba16float:new c("rgba16float",R.keyword,"rgba16float"),rgba32uint:new c("rgba32uint",R.keyword,"rgba32uint"),rgba32sint:new c("rgba32sint",R.keyword,"rgba32sint"),rgba32float:new c("rgba32float",R.keyword,"rgba32float"),static_assert:new c("static_assert",R.keyword,"static_assert"),const_assert:new c("const_assert",R.keyword,"const_assert")},t.tokens={decimal_float_literal:new c("decimal_float_literal",R.token,/((-?[0-9]*\.[0-9]+|-?[0-9]+\.[0-9]*)((e|E)(\+|-)?[0-9]+)?[fh]?)|(-?[0-9]+(e|E)(\+|-)?[0-9]+[fh]?)|(-?[0-9]+[fh])/),hex_float_literal:new c("hex_float_literal",R.token,/-?0x((([0-9a-fA-F]*\.[0-9a-fA-F]+|[0-9a-fA-F]+\.[0-9a-fA-F]*)((p|P)(\+|-)?[0-9]+[fh]?)?)|([0-9a-fA-F]+(p|P)(\+|-)?[0-9]+[fh]?))/),int_literal:new c("int_literal",R.token,/-?0x[0-9a-fA-F]+|0i?|-?[1-9][0-9]*i?/),uint_literal:new c("uint_literal",R.token,/0x[0-9a-fA-F]+u|0u|[1-9][0-9]*u/),name:new c("name",R.token,/([_\p{XID_Start}][\p{XID_Continue}]+)|([\p{XID_Start}])/u),ident:new c("ident",R.token,/[_a-zA-Z][0-9a-zA-Z_]*/),and:new c("and",R.token,"&"),and_and:new c("and_and",R.token,"&&"),arrow:new c("arrow ",R.token,"->"),attr:new c("attr",R.token,"@"),forward_slash:new c("forward_slash",R.token,"/"),bang:new c("bang",R.token,"!"),bracket_left:new c("bracket_left",R.token,"["),bracket_right:new c("bracket_right",R.token,"]"),brace_left:new c("brace_left",R.token,"{"),brace_right:new c("brace_right",R.token,"}"),colon:new c("colon",R.token,":"),comma:new c("comma",R.token,","),equal:new c("equal",R.token,"="),equal_equal:new c("equal_equal",R.token,"=="),not_equal:new c("not_equal",R.token,"!="),greater_than:new c("greater_than",R.token,">"),greater_than_equal:new c("greater_than_equal",R.token,">="),shift_right:new c("shift_right",R.token,">>"),less_than:new c("less_than",R.token,"<"),less_than_equal:new c("less_than_equal",R.token,"<="),shift_left:new c("shift_left",R.token,"<<"),modulo:new c("modulo",R.token,"%"),minus:new c("minus",R.token,"-"),minus_minus:new c("minus_minus",R.token,"--"),period:new c("period",R.token,"."),plus:new c("plus",R.token,"+"),plus_plus:new c("plus_plus",R.token,"++"),or:new c("or",R.token,"|"),or_or:new c("or_or",R.token,"||"),paren_left:new c("paren_left",R.token,"("),paren_right:new c("paren_right",R.token,")"),semicolon:new c("semicolon",R.token,";"),star:new c("star",R.token,"*"),tilde:new c("tilde",R.token,"~"),underscore:new c("underscore",R.token,"_"),xor:new c("xor",R.token,"^"),plus_equal:new c("plus_equal",R.token,"+="),minus_equal:new c("minus_equal",R.token,"-="),times_equal:new c("times_equal",R.token,"*="),division_equal:new c("division_equal",R.token,"/="),modulo_equal:new c("modulo_equal",R.token,"%="),and_equal:new c("and_equal",R.token,"&="),or_equal:new c("or_equal",R.token,"|="),xor_equal:new c("xor_equal",R.token,"^="),shift_right_equal:new c("shift_right_equal",R.token,">>="),shift_left_equal:new c("shift_left_equal",R.token,"<<=")},t.simpleTokens={"@":M.tokens.attr,"{":M.tokens.brace_left,"}":M.tokens.brace_right,":":M.tokens.colon,",":M.tokens.comma,"(":M.tokens.paren_left,")":M.tokens.paren_right,";":M.tokens.semicolon},t.literalTokens={"&":M.tokens.and,"&&":M.tokens.and_and,"->":M.tokens.arrow,"/":M.tokens.forward_slash,"!":M.tokens.bang,"[":M.tokens.bracket_left,"]":M.tokens.bracket_right,"=":M.tokens.equal,"==":M.tokens.equal_equal,"!=":M.tokens.not_equal,">":M.tokens.greater_than,">=":M.tokens.greater_than_equal,">>":M.tokens.shift_right,"<":M.tokens.less_than,"<=":M.tokens.less_than_equal,"<<":M.tokens.shift_left,"%":M.tokens.modulo,"-":M.tokens.minus,"--":M.tokens.minus_minus,".":M.tokens.period,"+":M.tokens.plus,"++":M.tokens.plus_plus,"|":M.tokens.or,"||":M.tokens.or_or,"*":M.tokens.star,"~":M.tokens.tilde,_:M.tokens.underscore,"^":M.tokens.xor,"+=":M.tokens.plus_equal,"-=":M.tokens.minus_equal,"*=":M.tokens.times_equal,"/=":M.tokens.division_equal,"%=":M.tokens.modulo_equal,"&=":M.tokens.and_equal,"|=":M.tokens.or_equal,"^=":M.tokens.xor_equal,">>=":M.tokens.shift_right_equal,"<<=":M.tokens.shift_left_equal},t.regexTokens={decimal_float_literal:M.tokens.decimal_float_literal,hex_float_literal:M.tokens.hex_float_literal,int_literal:M.tokens.int_literal,uint_literal:M.tokens.uint_literal,ident:M.tokens.ident},t.storage_class=[M.keywords.function,M.keywords.private,M.keywords.workgroup,M.keywords.uniform,M.keywords.storage,M.keywords.immediate],t.access_mode=[M.keywords.read,M.keywords.write,M.keywords.read_write],t.sampler_type=[M.keywords.sampler,M.keywords.sampler_comparison],t.sampled_texture_type=[M.keywords.texture_1d,M.keywords.texture_2d,M.keywords.texture_2d_array,M.keywords.texture_3d,M.keywords.texture_cube,M.keywords.texture_cube_array],t.multisampled_texture_type=[M.keywords.texture_multisampled_2d],t.storage_texture_type=[M.keywords.texture_storage_1d,M.keywords.texture_storage_2d,M.keywords.texture_storage_2d_array,M.keywords.texture_storage_3d],t.depth_texture_type=[M.keywords.texture_depth_2d,M.keywords.texture_depth_2d_array,M.keywords.texture_depth_cube,M.keywords.texture_depth_cube_array,M.keywords.texture_depth_multisampled_2d],t.texture_external_type=[M.keywords.texture_external],t.any_texture_type=[...M.sampled_texture_type,...M.multisampled_texture_type,...M.storage_texture_type,...M.depth_texture_type,...M.texture_external_type],t.texel_format=[M.keywords.r8unorm,M.keywords.r8snorm,M.keywords.r8uint,M.keywords.r8sint,M.keywords.r16uint,M.keywords.r16sint,M.keywords.r16float,M.keywords.rg8unorm,M.keywords.rg8snorm,M.keywords.rg8uint,M.keywords.rg8sint,M.keywords.r32uint,M.keywords.r32sint,M.keywords.r32float,M.keywords.rg16uint,M.keywords.rg16sint,M.keywords.rg16float,M.keywords.rgba8unorm,M.keywords.rgba8unorm_srgb,M.keywords.rgba8snorm,M.keywords.rgba8uint,M.keywords.rgba8sint,M.keywords.bgra8unorm,M.keywords.bgra8unorm_srgb,M.keywords.rgb10a2unorm,M.keywords.rg11b10float,M.keywords.rg32uint,M.keywords.rg32sint,M.keywords.rg32float,M.keywords.rgba16uint,M.keywords.rgba16sint,M.keywords.rgba16float,M.keywords.rgba32uint,M.keywords.rgba32sint,M.keywords.rgba32float],t.const_literal=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.keywords.true,M.keywords.false],t.literal_or_ident=[M.tokens.ident,M.tokens.int_literal,M.tokens.uint_literal,M.tokens.decimal_float_literal,M.tokens.hex_float_literal,M.tokens.name],t.element_count_expression=[M.tokens.int_literal,M.tokens.uint_literal,M.tokens.ident],t.template_types=[M.keywords.vec2,M.keywords.vec3,M.keywords.vec4,M.keywords.mat2x2,M.keywords.mat2x3,M.keywords.mat2x4,M.keywords.mat3x2,M.keywords.mat3x3,M.keywords.mat3x4,M.keywords.mat4x2,M.keywords.mat4x3,M.keywords.mat4x4,M.keywords.atomic,M.keywords.bitcast,...M.any_texture_type],t.attribute_name=[M.tokens.ident,M.keywords.block,M.keywords.diagnostic],t.assignment_operators=[M.tokens.equal,M.tokens.plus_equal,M.tokens.minus_equal,M.tokens.times_equal,M.tokens.division_equal,M.tokens.modulo_equal,M.tokens.and_equal,M.tokens.or_equal,M.tokens.xor_equal,M.tokens.shift_right_equal,M.tokens.shift_left_equal],t.increment_operators=[M.tokens.plus_plus,M.tokens.minus_minus];class TE{constructor(A,I,g,B,C){this.type=A,this.lexeme=I,this.line=g,this.start=B,this.end=C}toString(){return this.lexeme}isTemplateType(){return t.template_types.includes(this.type)}isArrayType(){return this.type===t.keywords.array}isArrayOrTemplateType(){return this.isArrayType()||this.isTemplateType()}}class mB{constructor(A){this._tokens=[],this._start=0,this._current=0,this._line=1,this._source=A??""}scanTokens(){for(;!this._isAtEnd();)if(this._start=this._current,!this.scanToken())throw`Invalid syntax at line ${this._line}`;return this._tokens.push(new TE(t.eof,"",this._line,this._current,this._current)),this._tokens}scanToken(){let A=this._advance();if(A==`
|
|
422
422
|
`)return this._line++,!0;if(this._isWhitespace(A))return!0;if(A=="/"){if(this._peekAhead()=="/"){for(;A!=`
|
|
423
423
|
`;){if(this._isAtEnd())return!0;A=this._advance()}return this._line++,!0}if(this._peekAhead()=="*"){this._advance();let E=1;for(;E>0;){if(this._isAtEnd())return!0;if(A=this._advance(),A==`
|
|
424
424
|
`)this._line++;else if(A=="*"){if(this._peekAhead()=="/"&&(this._advance(),E--,E==0))return!0}else A=="/"&&this._peekAhead()=="*"&&(this._advance(),E++)}return!0}}const I=t.simpleTokens[A];if(I)return this._addToken(I),!0;let g=t.none;const B=this._isAlpha(A),C=A==="_";if(this._isAlphaNumeric(A)){let E=this._peekAhead();for(;this._isAlphaNumeric(E);)A+=this._advance(),E=this._peekAhead()}if(B){const E=t.keywords[A];if(E)return this._addToken(E),!0}if(B||C)return this._addToken(t.tokens.ident),!0;for(;;){let E=this._findType(A);const i=this._peekAhead();if(A=="-"&&this._tokens.length>0){if(i=="=")return this._current++,A+=i,this._addToken(t.tokens.minus_equal),!0;if(i=="-")return this._current++,A+=i,this._addToken(t.tokens.minus_minus),!0;const o=this._tokens.length-1;if((t.literal_or_ident.includes(this._tokens[o].type)||this._tokens[o].type==t.tokens.paren_right)&&i!=">")return this._addToken(E),!0}if(A==">"&&(i==">"||i=="=")){let o=!1,a=this._tokens.length-1;for(let D=0;D<5&&a>=0&&!t.assignment_operators.includes(this._tokens[a].type);++D,--a)if(this._tokens[a].type===t.tokens.less_than){a>0&&this._tokens[a-1].isArrayOrTemplateType()&&(o=!0);break}if(o)return this._addToken(E),!0}if(E===t.none){let o=A,a=0;const D=2;for(let s=0;s<D;++s)if(o+=this._peekAhead(s),E=this._findType(o),E!==t.none){a=s;break}if(E===t.none)return g!==t.none&&(this._current--,this._addToken(g),!0);A=o,this._current+=a+1}if(g=E,this._isAtEnd())break;A+=this._advance()}return g!==t.none&&(this._addToken(g),!0)}_findType(A){for(const g in t.regexTokens){const B=t.regexTokens[g];if(this._match(A,B.rule))return B}return t.literalTokens[A]||t.none}_match(A,I){const g=I.exec(A);return g&&g.index==0&&g[0]==A}_isAtEnd(){return this._current>=this._source.length}_isAlpha(A){return!this._isNumeric(A)&&!this._isWhitespace(A)&&A!=="_"&&!mB._operators.has(A)}_isNumeric(A){return A>="0"&&A<="9"}_isAlphaNumeric(A){return this._isAlpha(A)||this._isNumeric(A)||A==="_"}_isWhitespace(A){return A==" "||A==" "||A=="\r"}_advance(A=0){const I=this._source[this._current];return this._current+=A+1,I??"\0"}_peekAhead(A=0){return this._current+A>=this._source.length?"\0":this._source[this._current+A]}_addToken(A){const I=this._source.substring(this._start,this._current);this._tokens.push(new TE(A,I,this._line,this._start,this._current))}}function X(Q){return Array.isArray(Q)||Q?.buffer instanceof ArrayBuffer}mB._operators=new Set([".","(",")","[","]","{","}",",",";",":","=","!","<",">","+","-","*","/","%","&","|","^","~","@","#","?","'","`",'"',"\\",`
|
|
@@ -553,7 +553,7 @@ fn vert(@location(0) aPos: vec3f) -> @builtin(position) vec4f {
|
|
|
553
553
|
@fragment
|
|
554
554
|
fn frag() -> @location(0) vec4f {
|
|
555
555
|
return vec4f(uniforms.color, uniforms.opacity);
|
|
556
|
-
}`;class nD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=cD(A),g=this.device_.createShaderModule({code:I});await SD(A,g);const B=yD(I),C=oD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];ND(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&RD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(e=>e.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:UD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=da(B.defs.uniforms.uniforms),y={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(y),y}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function SD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)gA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function ND(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function RD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function cD(Q){switch(Q){case"image_scalar_u32":return wD;case"image_scalar_i32":return FD;case"image_scalar_f32":return eD;case"wireframe":return rD}}function UD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const kD=lo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function LD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new JD(Q,await A.requestDevice());return await I.compileShaders(),I}class JD extends OC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=hI();currentModelView_=hI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentLayerOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new ta(I),this.geometryBuffers_=new Ga(I),this.texturePool_=new Na(I),this.pipelines_=new nD(I,this.colorFormat_,this.depthFormat_),gA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const I=[],g=[];for(const o of A.layers)(o.blendMode==="none"?I:g).push(o);for(const o of[...I,...g])o.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new QI(xA(0,0),xA(this.width,this.height));if(!QI.intersects(B,C)){gA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!QI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentLayerOpacity_=A.opacity,A.objects.forEach((s,y)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,y,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:YD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),Rg(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentLayerOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}uploadTexture(A){this.texturePool_.get(A)}disposeTexture(A){this.texturePool_.dispose(A)}setUniformsForObject(A,I,g){Rg(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms(),C=B.Opacity??1;I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.Color,valueOffset:B.ValueOffset,valueScale:B.ValueScale,opacity:this.currentLayerOpacity_*C,zTexCoord:B.ZTexCoord}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){Rg(this.currentProjection_,kD,A)}get gpuTextureBytes(){return 0}get gpuTextureCount(){return 0}}function YD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}const KD=8;class MD{maxConcurrent_;pending_=[];running_=new Map;constructor(A=KD){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),gA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),gA.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>{const g=A.chunk.priority??Number.MAX_SAFE_INTEGER,B=I.chunk.priority??Number.MAX_SAFE_INTEGER;return g===B?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):g-B});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&gA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}let ZB=0,PB=0;function dD(Q,A){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=A,ZB+=A.byteLength,PB+=1}function HD(Q){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=void 0}function qD(){return{cpuChunkBytes:ZB,cpuChunkCount:PB}}function PE(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const VE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function lD(Q){if(VE.some(I=>Q instanceof I))return!0;const A=VE.map(I=>I.name);return gA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function fD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function pI(Q,A,I){return Math.max(A,Math.min(I,Q))}const VB=Symbol("INTERNAL_POLICY_KEY");class pD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=Qa(xA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.worldViewRect,C=Math.abs(g.max[0]-g.min[0])/I.bufferWidthPx,E=Math.log2(1/C);this.setLOD(E);const i=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(g)||this.zBoundsChanged(i)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const a=this.timeIndex(A);if(!this.store_.hasChunksAtTime(a)){gA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const D=gE();Ca(D,g.min,g.max,.5);const[s,y]=this.getZBounds(A),e=new Qg(nA(g.min[0],g.min[1],s),nA(g.max[0],g.max[1],y));this.chunkViewStates_.forEach(jQ);const Y=this.channelsOfInterest(A),u=this.fallbackLOD(),H=this.getPaddedBounds(e),W=this.currentLOD_===u?[this.currentLOD_]:[this.currentLOD_,u];for(const z of W){const x=z===this.currentLOD_,l=z===u;this.iterateChunksInBox(a,z,Y,H,(Z,v)=>{const CA=Qg.intersects(v,e),sA=x&&!CA,DA=this.computePriority(l,x,CA,sA,!0);DA!==null&&this.chunkViewStates_.set(Z,{visible:CA,prefetch:sA,priority:DA,orderKey:this.squareDistance2D(Z,D)})})}this.markTimeChunksForPrefetchImage(a,A,e,D),this.policyChanged_=!1,this.lastViewBounds2D_=g.clone(),this.lastZBounds_=i,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){if(!(this.policyChanged_||this.hasViewProjectionChanged(I)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const B=this.timeIndex(A);if(!this.store_.hasChunksAtTime(B)){gA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(jQ);const C=this.channelsOfInterest(A),E=this.fallbackLOD(),i=o=>{const a=o.lod===E,D=o.lod===this.currentLOD_,s=this.computePriority(a,D,!0,!1,!0);s!==null&&this.chunkViewStates_.set(o,{visible:!0,prefetch:!1,priority:s,orderKey:0})};this.iterateAllChunksAtLod(B,this.currentLOD_,C,i),this.currentLOD_!==E&&this.iterateAllChunksAtLod(B,E,C,i),this.markTimeChunksForPrefetchVolume(B,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.state!=="loaded"))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(jQ)}setImageSourcePolicy(A,I){if(I!==VB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=pI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=A+1;D<=E;++D)this.iterateChunksInBox(D,i,a,g,s=>{const y=this.squareDistance2D(s,B),e=pI(y/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),Y=D-A+e;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:o,orderKey:Y})})}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(g-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=A+1;o<=B;++o)this.iterateAllChunksAtLod(o,C,i,a=>{const D=o-A;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:E,orderKey:D})})}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,y=E?E.chunkSize*E.scale:1,e=B.translation,Y=C.translation,u=E?.translation??0,H=Math.max(0,Math.floor((A.min[0]-e)/D)),W=Math.min(i,Math.ceil((A.max[0]-e)/D)),z=Math.max(0,Math.floor((A.min[1]-Y)/s)),x=Math.min(o,Math.ceil((A.max[1]-Y)/s)),l=E?Math.max(0,Math.floor((A.min[2]-u)/y)):0,Z=E?Math.min(a,Math.ceil((A.max[2]-u)/y)):1;return H>=W||z>=x||l>=Z?null:{xMin:H,xMax:W,yMin:z,yMax:x,zMin:l,zMax:Z}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const y=D[s];for(let e=E.xMin;e<E.xMax;++e){const Y=y[e];C(Y,this.getChunkAabb(Y))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new Qg(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))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:fD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!LQ(this.lastViewBounds2D_.min,A.min)||!LQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!bo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!LQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new Qg(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 g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function jQ(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class uD{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,y=Math.ceil(E.size/a),e=Math.ceil(i.size/D),Y=o?Math.ceil(o.size/s):1,u=new Array(I);this.chunks_[C]=u;for(let H=0;H<I;++H){const W=new Array(g);u[H]=W;for(let z=0;z<g;++z){const x=new Array(Y);W[z]=x;for(let l=0;l<Y;++l){const Z=o!==void 0?o.translation+l*s*o.scale:0,v=new Array(e);x[l]=v;for(let CA=0;CA<e;++CA){const sA=i.translation+CA*D*i.scale,DA=new Array(y);v[CA]=DA;for(let yA=0;yA<y;++yA){const wA=E.translation+yA*a*E.scale;DA[yA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-yA*a),y:Math.min(D,i.size-CA*D),z:Math.min(s,(o?.size??1)-l*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:yA,y:CA,z:l,c:z,t:H},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:wA,y:sA,z:Z}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}addView(A){const I=new pD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const a of this.views_){const D=a.chunkViewStates.get(A);D&&(D.visible&&(I=!0),D.prefetch&&(g=!0),D.priority!==null&&(B===null||D.priority<B)&&(B=D.priority,C=D.orderKey),!D.visible&&!D.prefetch&&D.priority===null&&a.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);HD(A),A.state="unloaded",A.orderKey=null,gA.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!PE(B,2,.02)||!PE(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&gA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class mD{stores_=[];queue_=new MD;get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return qD()}addView(A,I){let g=this.stores_.find(B=>B.source===A)?.store;return g||(g=new uD(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:g})),g.addView(I)}update(){for(const{source:A,store:I}of this.stores_){const g=I.updateAndCollectChunkChanges();for(const B of g)B.priority===null?this.queue_.cancel(B):B.state==="queued"&&this.queue_.enqueue(B,C=>A.loader.loadChunkData(B,C))}this.queue_.flush();for(let A=this.stores_.length-1;A>=0;A--)this.stores_[A].store.canDispose()&&this.stores_.splice(A,1)}}var sB=function(Q=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var y=0;y<I.children.length;y++)I.children[y].style.display=y===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new sB.Panel("FPS","#0ff","#002",Q)),a=g(new sB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new sB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var y=performance.memory;D.update(y.usedJSHeapSize/1048576,y.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};sB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),y=E(3*i*g),e=E(15*i*g),Y=E(74*i*g),u=E(30*i*g),H=document.createElement("canvas");H.width=o,H.height=a,H.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var W=H.getContext("2d");return W.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",W.textBaseline="top",W.fillStyle=I,W.fillRect(0,0,o,a),W.fillStyle=A,W.fillText(Q,D,s),W.fillRect(y,e,Y,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y,e,Y,u),{dom:H,update:function(z,x){B=Math.min(B,z),C=Math.max(C,z),W.fillStyle=I,W.globalAlpha=1,W.fillRect(0,0,o,e),W.fillStyle=A,W.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),W.drawImage(H,y+i,e,Y-i,u,y,e,Y-i,u),W.fillRect(y+Y-i,e,i,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y+Y-i,e,i,E((1-z/x)*u))}}};function xD({scale:Q}={scale:1.5}){const A=new sB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}const zQ=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function TD(Q){return zQ.includes(Q)}class WD{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 bD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){gA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,zQ.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){gA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,zQ.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!TD(A.type)){gA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new WD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class ZD{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new bD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=xA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),y=Math.floor(I.width),e=Math.floor(I.height);return new QI(xA(D,s),xA(D+y,s+e))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return nA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new QI(xA(g,B),xA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){gA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function OE(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function PD(Q){for(let A=0;A<Q.length;A++)OE(Q[A],Q.slice(0,A))}function vE(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??jC("viewport"),context:I}});return PD(g),g.map(B=>new ZD(B))}class VD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){gA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){gA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class _Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await LD(A.canvas):new EE(A.canvas);return new _Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new EE(this.canvas),this.chunkManager_=new mD,this.context_={chunkManager:this.chunkManager_},this.viewports_=vE(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=xD());const g=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&g.push(B.element);this.sizeObserver_=new VD(g,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=vE([A],this.canvas,this.context_);return OE(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),gA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(gA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),gA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(gA.info("Idetik","Idetik runtime starting"),this.running)gA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(gA.info("Idetik","Idetik runtime stopping"),!this.running)gA.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}}}function OD(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function XE(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function jE(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class hB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,OD(this.#I,I))}async get(A,I={}){let g=XE(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return jE(C)}async getRange(A,I,g={}){let B=XE(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return jE(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class yB extends Error{}class Mg extends yB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class WA extends yB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class vD extends yB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class XD extends yB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class $Q extends yB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function og(Q){return()=>{throw new $Q(`${Q} encode`)}}class OB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new WA("keepbits must be zero or positive")}static fromConfig(A,I){return new OB(A,I)}encode=og("bitround");decode(A){return A}}function AC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class zE{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):AC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class IC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(AC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class tB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(AC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new tB(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function jD(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function zD(Q,A){return new SharedArrayBuffer(Q)}function GB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new WA("Failed to decode JSON",{cause:I})}}function _E(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function dg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?tB:IC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:zE}[Q];if(!I)throw new WA(`Unknown or unsupported dataType: ${Q}`);return I}function ag(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function _D({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new WA(`Unknown chunk key encoding: ${Q}`)}function $E(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new WA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new WA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function $D(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function As(Q,A={}){let I=[],g=$E(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!$D(C))throw new WA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=$E(o).dataType;if(!gC(a,"number")&&!gC(a,"bigint"))throw new WA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function Is(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function gC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function gs(Q){return Q?.name==="sharding_indexed"}function Ai(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function Ii(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function gi(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const Bi=Bs();function Bs(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function Qi(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class vB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=dg(I.dataType),this.#B=I.shape,this.#A=ag(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new vB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return Bi&&this.#Q==="big"&&_E(I,Qi(this.#I)),I}computeEncodedSize(A){return A}decode(A){return Bi&&this.#Q==="big"&&_E(A,Qi(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const Ci={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},Ei={float16:2,float32:4,float64:8};function XB(Q){return Q in Ei}function BC(Q){return Q==="int64"||Q==="uint64"}function Qs(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new $Q("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function jB(Q,A){if(BC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!XB(Q)&&!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!XB(Q))throw new WA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in Ci?Ci[A]:Qs(A,Ei[Q])}const ii=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),QC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},CC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function oi(Q,A,I){return Q.map(([g,B])=>({src:jB(A,g),tgt:jB(I,B)}))}function Cs(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Es(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function is(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function ai(Q){switch(Q){case"nearest-even":return Es;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return is}}function EC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function iC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class oC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=dg(A),this.#g=Di(I,A,g,B,C),this.#B=Di(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!ii.has(g))throw new WA(`cast_value codec does not support array data type: ${g}`);if(!ii.has(B))throw new WA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?oi(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?oi(A.scalar_map.encode,g,B):[];return new oC(g,B,C,A.out_of_range,E,i)}encode=og("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function Di(Q,A,I,g,B){const C=XB(Q),E=BC(Q),i=XB(A),o=BC(A);let a;if(C&&i){if(I!=="nearest-even")throw new WA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=ai(I),y=EC(...QC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(s(e))}}else if(C&&o){const s=ai(I),y=iC(...CC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(BigInt(s(e)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=EC(...QC[A],g);else if(!C&&!E&&o){const s=iC(...CC[A],g);a=y=>s(BigInt(y))}else if(E&&!i&&!o){const s=EC(...QC[A],g);a=y=>s(Number(y))}else if(E&&o)a=iC(...CC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const y=Cs(s,B);return y!==void 0?y:a(s)}}class aC{kind="bytes_to_bytes";static fromConfig(){return new aC}encode=og("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const os=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function si(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class DC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!os.has(I.dataType))throw new WA(`Delta codec does not support data type: ${I.dataType}`);return new DC(dg(I.dataType))}encode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class sC{kind="bytes_to_bytes";static fromConfig(A){return new sC}encode=og("gzip");async decode(A){const I=await gi(A,{format:"gzip"});return new Uint8Array(I)}}function as(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Ds(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class zB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new zB(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(as),i&&o.push(Ds);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(y,e)=>{let Y=e;for(let u of o)Y=u(y,Y);return Y});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,y=>{const e=`0000${y.charCodeAt(0).toString(16)}`;return`\\u${e.substring(e.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=GB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=ag(B,"C");return{data:g,shape:B,stride:C}}}const ss=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class hC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!ss.has(I.dataType))throw new WA(`scale_offset codec does not support data type: ${I.dataType}`);return new hC(jB(I.dataType,A.scale??1),jB(I.dataType,A.offset??0),dg(I.dataType))}encode=og("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class yC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(dg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new yC(A,I)}encode(A){return hs(A,this.#A)}decode(A){return ys(A,this.#A)}}function hs(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function ys(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function hi(Q){return Q instanceof zE||Q instanceof IC||Q instanceof tB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function ts(Q,A){let I;return Q.data instanceof IC||Q.data instanceof tB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:ag(Q.shape,A)}}function Gs(Q,A){let I=ts(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=hi(Q.data),i=hi(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function ws(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function Fs(Q,A){let I=ws(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class tC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new tC(A,I)}encode(A){return Fs(A,this.#I)?A:Gs(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:ag(A.shape,this.#A)}}}class _B{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=ag(A,"C")}static fromConfig(A,I){return new _B(I.shape)}encode=og("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class GC{kind="bytes_to_bytes";static fromConfig(A){return new GC}encode=og("zlib");async decode(A){const I=await gi(A,{format:"deflate"});return new Uint8Array(I)}}function es(){let Q=()=>Promise.resolve().then(()=>My).then(C=>C.default),A=()=>Promise.resolve().then(()=>py).then(C=>C.default),I=()=>Promise.resolve().then(()=>by).then(C=>C.default),g=()=>sC,B=()=>GC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>tC).set("bytes",()=>vB).set("crc32c",()=>aC).set("vlen-utf8",()=>_B).set("json2",()=>zB).set("bitround",()=>OB).set("cast_value",()=>oC).set("scale_offset",()=>hC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>_B).set("numcodecs.shuffle",()=>yC).set("numcodecs.delta",()=>DC).set("numcodecs.bitround",()=>OB).set("numcodecs.json2",()=>zB)}const rs=es();function wC(Q){let A;function I(){return A||(A=ns(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new XD({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E},async computeEncodedSize(B){let C=await I(),E=yi(C.arrayToBytes.name,C.arrayToBytes.codec,B);for(const{name:i,codec:o}of C.bytesToBytes)E=yi(i,o,E);return E}}}function yi(Q,A,I){if(!A.computeEncodedSize)throw new WA(`Codec "${Q}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function ns(Q){let A=Q.codecs.map(async E=>{let i=await rs.get(E.name)?.();if(!i)throw new vD(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Ss(C))throw new WA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:vB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Ss(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ti=18446744073709551615n;function Ns(Q,A,I,g){if(!Q.store.getRange)throw new $Q("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((a,D)=>a/g.chunk_shape[D]),E=wC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,D)=>a*D,1),o={};return async(a,D)=>{let s=a.map((l,Z)=>Math.floor(l/C[Z])),y=Q.resolve(I(s)).path;y in o||(o[y]=(async()=>{let l=await E.computeEncodedSize(i),Z=await B(y,{suffixLength:l},D);return Z?await E.decode(Z):null})().catch(l=>{throw delete o[y],l}));let e=await o[y];if(e===null)return;let{data:Y,shape:u,stride:H}=e,W=a.map((l,Z)=>l%u[Z]).reduce((l,Z,v)=>l+Z*H[v],0),z=Y[W],x=Y[W+1];if(!(z===ti&&x===ti))return B(y,{offset:Number(z),length:Number(x)},D)}}class eI{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new eI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class FC extends eI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Gi(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const $B=Symbol("zarrita.context");function Rs(Q,A){let{configuration:I}=A.codecs.find(gs)??{},g={encodeChunkKey:_D(A.chunk_key_encoding),TypedArray:dg(A.data_type),fillValue:A.fill_value};if(I){let C=Gi(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:wC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return ag(E,C)},getChunkBytes:Ns(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Gi(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:wC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return ag(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let AQ=class extends eI{kind="array";#A;[$B];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:Ai(g)},this[$B]=Rs(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[$B].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&jD();let B=this[$B],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=zD(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return gC(this.dtype,A)}};function cs(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function Us(Q,...A){return cs(Q,A)}async function wi(Q){let A=Q.store.arrayExtensions;return A?.length?await Us(Q,...A):Q}let IQ=ks();function ks(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function Ls(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?GB(I):{}}async function Js(Q,A={}){let I="store"in Q?Q:new eI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await Ls(I,g)),g?.throwIfAborted(),A.kind==="array"?Fi(I,B,g):A.kind==="group"?ei(I,B,g):Fi(I,B,g).catch(C=>(Ii(C,Mg,WA),ei(I,B,g)))}async function Fi(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 array",{path:g});return IQ.increment(Q.store,"v2"),wi(new AQ(Q.store,Q.path,As(GB(B),A)))}async function ei(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 group",{path:g});return IQ.increment(Q.store,"v2"),new FC(Q.store,Q.path,Is(GB(B),A))}async function Ys(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new Mg("v3 array or group",{path:g});let C=GB(B);return C.node_type==="array"&&(C.fill_value=Ai(C)),C.node_type==="array"?wi(new AQ(I,Q.path,C)):new FC(I,Q.path,C)}async function Ks(Q,A={}){let I="store"in Q?Q:new eI(Q),g=await Ys(I,A.signal);if(IQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof AQ||A.kind==="group"&&g instanceof FC)return g;let B=g instanceof AQ?"array":"group";throw new Mg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=IQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(Ii(E,Mg,WA),C(Q,A)))}rI.v2=Js,rI.v3=Ks;async function Ms(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class eC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Ms(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function wB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function ds(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function Hs(Q){let A;switch(Q.type){case"fetch":{const g=new hB(Q.url);A=new eI(g);break}case"filesystem":{A=new eI(new eC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return ds(I,Q.zarrVersion)}function qs(Q,A,I){if(Q.store instanceof hB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof eC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function ls(Q,A,I,g){return fs(Q,A,I,g)}function fs(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let Z=A.length-1;Z>=0;Z--){if(I[Z]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[Z]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,y=E.c!==void 0?I[E.c]:0,e=E.t!==void 0?I[E.t]:0,Y=D*e+a*y,u=o.x===B.x&&o.y===B.y&&o.z===B.z;if(Y===0&&Q.length===s&&u)return Q;const W=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,x=I[E.y];let l=0;for(let Z=0;Z<B.z;Z++){const v=Y+Z*z;for(let CA=0;CA<B.y;CA++){const sA=v+CA*x,DA=sA+B.x;W.set(Q.subarray(sA,DA),l),l+=B.x}}return W}const ri=`function xg(B, A) {
|
|
556
|
+
}`;class nD{colorFormat_;depthFormat_;device_;pipelines_;shaderModules_;constructor(A,I,g){this.colorFormat_=I,this.depthFormat_=g,this.device_=A,this.pipelines_=[],this.shaderModules_=[]}async compileShader(A){if(this.shaderModules_.some(a=>a.name===A))return;const I=cD(A),g=this.device_.createShaderModule({code:I});await SD(A,g);const B=yD(I),C=oD(B,{vertex:{entryPoint:"vert"},fragment:{entryPoint:"frag"}}),E=C[B.uniforms.uniforms.group];ND(E);const i=B.textures?.texture;let o;if(i){const a=C[i.group];A==="image_scalar_f32"&&RD(a),o=this.device_.createBindGroupLayout(a)}this.shaderModules_.push({name:A,module:g,defs:B,layouts:{uniforms:this.device_.createBindGroupLayout(E),textures:o}})}get(A,I){const g=this.getCachedPipeline(A);if(g)return g;const B=this.shaderModules_.find(e=>e.name===A.shaderName);if(!B)throw new Error("Shader module not found");const C=A.depthTest?"less-equal":"always",E=A.stencil?{compare:"equal",passOp:"increment-clamp"}:{},i={vertex:{module:B.module,entryPoint:"vert",buffers:[{attributes:I.attributes,arrayStride:I.geometry.strideBytes,stepMode:"vertex"}]},fragment:{module:B.module,entryPoint:"frag",targets:[{format:this.colorFormat_,blend:UD(A.blendMode)}]},primitive:{topology:A.topology,frontFace:"ccw",cullMode:A.cullMode},depthStencil:{format:this.depthFormat_,depthWriteEnabled:A.depthWrite,depthCompare:C,stencilFront:E,stencilBack:E,stencilReadMask:255,stencilWriteMask:255},multisample:{count:4}},o=[B.layouts.uniforms];B.layouts.textures&&o.push(B.layouts.textures);const a=this.device_.createPipelineLayout({bindGroupLayouts:o}),D=this.device_.createRenderPipeline({layout:a,...i}),s=da(B.defs.uniforms.uniforms),y={key:A,pipeline:D,uniformsView:s,uniformsData:new Float32Array(s.arrayBuffer),shaderModule:B};return this.pipelines_.push(y),y}getCachedPipeline(A){return this.pipelines_.find(I=>I.key.blendMode===A.blendMode&&I.key.cullMode===A.cullMode&&I.key.depthTest===A.depthTest&&I.key.depthWrite===A.depthWrite&&I.key.shaderName===A.shaderName&&I.key.stencil===A.stencil&&I.key.topology===A.topology&&I.key.vertexAttributesStr===A.vertexAttributesStr)}}async function SD(Q,A){const I=await A.getCompilationInfo();if(I.messages.some(g=>g.type==="error")){for(const g of I.messages)gA.error("WebGPUPipelines",`${g.type}: ${g.message}`);throw new Error(`Failed to compile WGSL shader ${Q}.wgsl`)}}function ND(Q){for(const A of Q.entries)A.buffer&&(A.buffer={...A.buffer,hasDynamicOffset:!0})}function RD(Q){for(const A of Q.entries)A.texture&&(A.texture={...A.texture,sampleType:"unfilterable-float"})}function cD(Q){switch(Q){case"image_scalar_u32":return wD;case"image_scalar_i32":return FD;case"image_scalar_f32":return eD;case"wireframe":return rD}}function UD(Q){let A,I;switch(Q){case"none":return;case"additive":A="src-alpha",I="one";break;case"multiply":A="dst",I="zero";break;case"subtractive":A="zero",I="one-minus-src";break;case"premultiplied":A="one-minus-dst-alpha",I="one";break;case"normal":A="src-alpha",I="one-minus-src-alpha";break}const g={srcFactor:A,dstFactor:I,operation:"add"};return{color:g,alpha:g}}const kD=lo(1,0,0,0,0,-1,0,0,0,0,.5,0,0,0,.5,1);async function LD(Q){if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser");const A=await navigator.gpu.requestAdapter();if(!A)throw new Error("Failed to obtain a WebGPU Adapter");const I=new JD(Q,await A.requestDevice());return await I.compileShaders(),I}class JD extends OC{bindings_;geometryBuffers_;pipelines_;texturePool_;colorFormat_;context_;depthFormat_;device_;currentProjection_=hI();currentModelView_=hI();colorMSAATexture_=null;depthStencilTexture_=null;passEncoder_=null;renderedObjectsPerFrame_=0;needsClear_=!0;currentDepthWrite_=!0;currentStencil_=!1;currentBlendMode_="none";currentLayerOpacity_=1;constructor(A,I){super(A),this.colorFormat_=navigator.gpu.getPreferredCanvasFormat(),this.depthFormat_="depth24plus-stencil8",this.device_=I;const g=A.getContext("webgpu");if(!g)throw new Error("Failed to initialize WebGPU context");g.configure({device:this.device_,format:this.colorFormat_,alphaMode:"premultiplied"}),this.context_=g,this.bindings_=new ta(I),this.geometryBuffers_=new Ga(I),this.texturePool_=new Na(I),this.pipelines_=new nD(I,this.colorFormat_,this.depthFormat_),gA.info("WebGPURenderer","WebGPU Initialized"),this.resize(this.width,this.height)}async compileShaders(){await Promise.all([this.pipelines_.compileShader("image_scalar_u32"),this.pipelines_.compileShader("image_scalar_i32"),this.pipelines_.compileShader("image_scalar_f32"),this.pipelines_.compileShader("wireframe")])}beginFrame(){this.renderedObjects_=0,this.renderedObjectsPerFrame_=0,this.needsClear_=!0}render(A){const I=[],g=[];for(const o of A.layers)(o.blendMode==="none"?I:g).push(o);for(const o of[...I,...g])o.update(A);if(getComputedStyle(A.element).visibility==="hidden")return;const B=A.getBoxRelativeTo(this.canvas),C=new QI(xA(0,0),xA(this.width,this.height));if(!QI.intersects(B,C)){gA.warn("WebGPURenderer",`Viewport ${A.id} is entirely outside canvas bounds`);return}const E=A.camera.frustum,i=!QI.equals(B.floor(),C.floor());this.bindings_.clearUniformBindings(),this.updateProjection(A.camera.projectionMatrix),this.currentDepthWrite_=!0;for(const o of I)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.currentDepthWrite_=!1;for(const o of g)o.state==="ready"&&this.renderLayer(o,A.camera,E,B,i);this.renderedObjects_=this.renderedObjectsPerFrame_}renderLayer(A,I,g,B,C){if(A.type!=="ImageLayer")throw new Error("Experimental WebGPU renderer only supports image layers");if(A.objects.length===0)return;const E=this.device_.createCommandEncoder();this.passEncoder_=this.beginRenderPass(E);const{x:i,y:o,width:a,height:D}=B.floor().toRect();this.passEncoder_.setViewport(i,o,a,D,0,1),C&&this.passEncoder_.setScissorRect(i,o,a,D),this.currentStencil_=A.hasMultipleLODs(),this.currentStencil_&&this.passEncoder_.setStencilReference(0),this.currentBlendMode_=A.blendMode,this.currentLayerOpacity_=A.opacity,A.objects.forEach((s,y)=>{g.intersectsWithBox3(s.boundingBox)&&(this.renderObject(A,y,I),this.renderedObjectsPerFrame_+=1)}),this.passEncoder_.end(),this.device_.queue.submit([E.finish()]),this.passEncoder_=null}renderObject(A,I,g){const B=A.objects[I];if(B.type!=="ImageRenderable")throw new Error("Experimental WebGPU renderer only supports image renderables");if(B.popStaleTextures().forEach(o=>{this.texturePool_.dispose(o)}),!B.programName)return;const C=this.passEncoder_,E=this.geometryBuffers_.get(B.geometry),i=this.pipelines_.get({shaderName:YD(B.textures[0]),depthWrite:this.currentDepthWrite_,depthTest:B.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"back",topology:"triangle-list",vertexAttributesStr:E.attributesKey},E);C.setPipeline(i.pipeline),this.setUniformsForObject(B,i,g),this.setTexturesForObject(B,i),C.setVertexBuffer(0,E.vertexBuffer),E.indexBuffer?(C.setIndexBuffer(E.indexBuffer,"uint32"),C.drawIndexed(B.geometry.indexData.length)):C.draw(B.geometry.vertexCount),B.wireframeEnabled&&this.renderWireframe(B,g)}renderWireframe(A,I){const g=A.wireframeGeometry;if(g.indexData.length===0)return;const B=this.passEncoder_,C=this.geometryBuffers_.get(g),E=this.pipelines_.get({shaderName:"wireframe",depthWrite:this.currentDepthWrite_,depthTest:A.depthTest,stencil:this.currentStencil_,blendMode:this.currentBlendMode_,cullMode:"none",topology:"line-list",vertexAttributesStr:C.attributesKey},C);B.setPipeline(E.pipeline),Rg(this.currentModelView_,I.viewMatrix,A.transform.matrix),E.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:A.wireframeColor.rgb,opacity:this.currentLayerOpacity_}),this.bindings_.setUniforms(B,E),B.setVertexBuffer(0,C.vertexBuffer),C.indexBuffer&&(B.setIndexBuffer(C.indexBuffer,"uint32"),B.drawIndexed(g.indexData.length))}resize(A,I){this.colorMSAATexture_&&this.colorMSAATexture_.destroy(),this.colorMSAATexture_=this.device_.createTexture({size:{width:A,height:I},format:this.colorFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT}),this.depthStencilTexture_&&this.depthStencilTexture_.destroy(),this.depthStencilTexture_=this.device_.createTexture({size:{width:A,height:I},format:this.depthFormat_,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})}beginRenderPass(A){const I=this.needsClear_?"clear":"load";return this.needsClear_=!1,A.beginRenderPass({colorAttachments:[{view:this.colorMSAATexture_.createView(),resolveTarget:this.context_.getCurrentTexture().createView(),loadOp:I,storeOp:"store",clearValue:{r:this.backgroundColor.r,g:this.backgroundColor.g,b:this.backgroundColor.b,a:this.backgroundColor.a}}],depthStencilAttachment:{view:this.depthStencilTexture_.createView(),depthLoadOp:I,depthStoreOp:"store",depthClearValue:1,stencilLoadOp:"clear",stencilStoreOp:"store",stencilClearValue:0}})}clear(){}uploadTexture(A){this.texturePool_.get(A)}disposeTexture(A){this.texturePool_.dispose(A)}setUniformsForObject(A,I,g){Rg(this.currentModelView_,g.viewMatrix,A.transform.matrix);const B=A.getUniforms(),C=B.Opacity??1;I.uniformsView.set({projection:this.currentProjection_,modelView:this.currentModelView_,color:B.u_color,valueOffset:B.u_valueOffset,valueScale:B.u_valueScale,opacity:this.currentLayerOpacity_*C,zTexCoord:B.u_zTexCoord}),this.bindings_.setUniforms(this.passEncoder_,I)}setTexturesForObject(A,I){if(A.textures.length>1)throw new Error("Experimental WebGPU renderer only supports single textures");this.bindings_.setTexture(this.passEncoder_,I,this.texturePool_.get(A.textures[0]))}updateProjection(A){Rg(this.currentProjection_,kD,A)}get gpuTextureBytes(){return 0}get gpuTextureCount(){return 0}}function YD(Q){switch(Q.dataType){case"byte":case"unsigned_byte":case"float":return"image_scalar_f32";case"short":case"int":return"image_scalar_i32";case"unsigned_short":case"unsigned_int":return"image_scalar_u32"}}const KD=8;class MD{maxConcurrent_;pending_=[];running_=new Map;constructor(A=KD){this.maxConcurrent_=Math.max(1,A)}enqueue(A,I){this.running_.has(A)||this.pending_.some(g=>g.chunk===A)||this.pending_.push({chunk:A,fn:I})}flush(){this.pump()}cancel(A){const I=this.pending_.findIndex(B=>B.chunk===A);if(I>=0){this.pending_.splice(I,1),gA.debug("ChunkQueue","Cancelled pending request");return}const g=this.running_.get(A);g&&(g.controller.abort(),gA.debug("ChunkQueue","Cancelled fetch request"))}get pendingCount(){return this.pending_.length}get runningCount(){return this.running_.size}pump(){if(!(this.running_.size>=this.maxConcurrent_||this.pending_.length===0))for(this.pending_.sort((A,I)=>{const g=A.chunk.priority??Number.MAX_SAFE_INTEGER,B=I.chunk.priority??Number.MAX_SAFE_INTEGER;return g===B?(A.chunk.orderKey??Number.MAX_SAFE_INTEGER)-(I.chunk.orderKey??Number.MAX_SAFE_INTEGER):g-B});this.running_.size<this.maxConcurrent_&&this.pending_.length>0;)this.start(this.pending_.shift())}start(A){const{chunk:I,fn:g}=A;I.state="loading";const B=new AbortController,C=Promise.resolve().then(()=>g(B.signal)).then(()=>{I.state==="loading"&&(I.state="loaded")},E=>{I.state==="loading"&&(I.state="unloaded"),E.name!=="AbortError"&&gA.error("ChunkQueue",String(E))}).finally(()=>{this.running_.delete(I),this.pump()});this.running_.set(I,{controller:B,promise:C})}}let ZB=0,PB=0;function dD(Q,A){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=A,ZB+=A.byteLength,PB+=1}function HD(Q){Q.data&&(ZB-=Q.data.byteLength,PB-=1),Q.data=void 0}function qD(){return{cpuChunkBytes:ZB,cpuChunkCount:PB}}function PE(Q,A,I=1e-6){return Math.abs(Q-A)<=I}const VE=[Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array];function lD(Q){if(VE.some(I=>Q instanceof I))return!0;const A=VE.map(I=>I.name);return gA.debug("Chunk",`Unsupported chunk data type: ${Q}. Supported data types: ${A}`),!1}function fD(Q,A){return Math.round((A-Q.translation)/Q.scale)}function pI(Q,A,I){return Math.max(A,Math.min(I,Q))}const VB=Symbol("INTERNAL_POLICY_KEY");class pD{store_;policy_;policyChanged_=!1;currentLOD_=0;lastViewBounds2D_=null;lastViewProjection_=null;lastZBounds_;lastTCoord_;lastCCoords_;sourceMaxSquareDistance2D_;chunkViewStates_=new Map;isDisposed_=!1;constructor(A,I){this.store_=A,this.policy_=I,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile);const g=this.store_.dimensions,B=g.x.lods[0],C=g.y.lods[0];this.sourceMaxSquareDistance2D_=Qa(xA(B.size*B.scale,C.size*C.scale))}get chunkViewStates(){return this.chunkViewStates_}get isDisposed(){return this.isDisposed_}get lodCount(){return this.store_.lodCount}get channelCount(){return this.store_.channelCount}getChunksToRender(){const A=this.fallbackLOD(),I=this.currentLOD_,g=[],B=[];for(const[C,E]of this.chunkViewStates_)!E.visible||C.state!=="loaded"||(C.lod===I?g.push(C):C.lod===A&&I!==A&&B.push(C));return[...g,...B]}updateChunksForImage(A,I){const g=I.worldViewRect,C=Math.abs(g.max[0]-g.min[0])/I.bufferWidthPx,E=Math.log2(1/C);this.setLOD(E);const i=this.getZBounds(A);if(!(this.policyChanged_||this.viewBounds2DChanged(g)||this.zBoundsChanged(i)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const a=this.timeIndex(A);if(!this.store_.hasChunksAtTime(a)){gA.warn("ChunkStoreView","updateChunkViewStates called with no chunks initialized"),this.chunkViewStates_.clear();return}const D=gE();Ca(D,g.min,g.max,.5);const[s,y]=this.getZBounds(A),e=new Qg(nA(g.min[0],g.min[1],s),nA(g.max[0],g.max[1],y));this.chunkViewStates_.forEach(jQ);const Y=this.channelsOfInterest(A),u=this.fallbackLOD(),H=this.getPaddedBounds(e),W=this.currentLOD_===u?[this.currentLOD_]:[this.currentLOD_,u];for(const z of W){const x=z===this.currentLOD_,l=z===u;this.iterateChunksInBox(a,z,Y,H,(Z,v)=>{const CA=Qg.intersects(v,e),sA=x&&!CA,DA=this.computePriority(l,x,CA,sA,!0);DA!==null&&this.chunkViewStates_.set(Z,{visible:CA,prefetch:sA,priority:DA,orderKey:this.squareDistance2D(Z,D)})})}this.markTimeChunksForPrefetchImage(a,A,e,D),this.policyChanged_=!1,this.lastViewBounds2D_=g.clone(),this.lastZBounds_=i,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0}updateChunksForVolume(A,I){if(!(this.policyChanged_||this.hasViewProjectionChanged(I)||this.lastTCoord_!==A.t||this.cCoordsChanged(A.c)))return;const B=this.timeIndex(A);if(!this.store_.hasChunksAtTime(B)){gA.warn("ChunkStoreView","updateChunksForVolume called with no chunks initialized"),this.chunkViewStates_.clear();return}this.currentLOD_=this.policy_.lod.min,this.chunkViewStates_.forEach(jQ);const C=this.channelsOfInterest(A),E=this.fallbackLOD(),i=o=>{const a=o.lod===E,D=o.lod===this.currentLOD_,s=this.computePriority(a,D,!0,!1,!0);s!==null&&this.chunkViewStates_.set(o,{visible:!0,prefetch:!1,priority:s,orderKey:0})};this.iterateAllChunksAtLod(B,this.currentLOD_,C,i),this.currentLOD_!==E&&this.iterateAllChunksAtLod(B,E,C,i),this.markTimeChunksForPrefetchVolume(B,A),this.policyChanged_=!1,this.lastTCoord_=A.t,this.lastCCoords_=A.c?[...A.c]:void 0,this.lastViewProjection_=I}allVisibleFallbackLODLoaded(){const A=this.fallbackLOD();let I=!1;for(const[g,B]of this.chunkViewStates_)if(!(!B.visible||g.lod!==A)&&(I=!0,g.state!=="loaded"))return!1;return I}get currentLOD(){return this.currentLOD_}maybeForgetChunk(A){const I=this.chunkViewStates_.get(A);I&&(I.visible||I.prefetch||I.priority!==null)||this.chunkViewStates_.delete(A)}dispose(){this.isDisposed_=!0,this.chunkViewStates_.forEach(jQ)}setImageSourcePolicy(A,I){if(I!==VB)throw new Error("Unauthorized policy mutation");this.policy_!==A&&(this.policy_=A,this.policyChanged_=!0,gA.info("ChunkStoreView","Using image source policy:",this.policy_.profile))}setLOD(A){const g=this.store_.dimensions.x.lods[0].scale,C=this.policy_.lod.bias-Math.log2(g)-A,E=Math.floor(C),i=this.store_.getLowestResLOD(),o=Math.max(0,Math.min(i,this.policy_.lod.min)),a=Math.max(o,Math.min(i,this.policy_.lod.max)),D=pI(E,o,a);D!==this.currentLOD_&&(this.currentLOD_=D)}markTimeChunksForPrefetchImage(A,I,g,B){const C=this.store_.dimensions.t?.lods[0].size??1,E=Math.min(C-1,A+this.policy_.prefetch.t),i=this.fallbackLOD(),o=this.policy_.priorityMap.prefetchTime,a=this.channelsOfInterest(I);for(let D=A+1;D<=E;++D)this.iterateChunksInBox(D,i,a,g,s=>{const y=this.squareDistance2D(s,B),e=pI(y/this.sourceMaxSquareDistance2D_,0,1-Number.EPSILON),Y=D-A+e;this.chunkViewStates_.set(s,{visible:!1,prefetch:!0,priority:o,orderKey:Y})})}markTimeChunksForPrefetchVolume(A,I){const g=this.store_.dimensions.t?.lods[0].size??1,B=Math.min(g-1,A+this.policy_.prefetch.t),C=this.fallbackLOD(),E=this.policy_.priorityMap.prefetchTime,i=this.channelsOfInterest(I);for(let o=A+1;o<=B;++o)this.iterateAllChunksAtLod(o,C,i,a=>{const D=o-A;this.chunkViewStates_.set(a,{visible:!1,prefetch:!0,priority:E,orderKey:D})})}computePriority(A,I,g,B,C){if(!C)return null;const E=this.policy_.priorityMap;return A&&g?E.fallbackVisible:I&&g?E.visibleCurrent:A?E.fallbackBackground:I&&B?E.prefetchSpace:null}channelsOfInterest(A){return A.c??Array.from({length:this.store_.channelCount},(I,g)=>g)}chunkIndexRange(A,I){const g=this.store_.dimensions,B=g.x.lods[I],C=g.y.lods[I],E=g.z?.lods[I],i=Math.ceil(B.size/B.chunkSize),o=Math.ceil(C.size/C.chunkSize),a=E?Math.ceil(E.size/E.chunkSize):1,D=B.chunkSize*B.scale,s=C.chunkSize*C.scale,y=E?E.chunkSize*E.scale:1,e=B.translation,Y=C.translation,u=E?.translation??0,H=Math.max(0,Math.floor((A.min[0]-e)/D)),W=Math.min(i,Math.ceil((A.max[0]-e)/D)),z=Math.max(0,Math.floor((A.min[1]-Y)/s)),x=Math.min(o,Math.ceil((A.max[1]-Y)/s)),l=E?Math.max(0,Math.floor((A.min[2]-u)/y)):0,Z=E?Math.min(a,Math.ceil((A.max[2]-u)/y)):1;return H>=W||z>=x||l>=Z?null:{xMin:H,xMax:W,yMin:z,yMax:x,zMin:l,zMax:Z}}iterateChunksInBox(A,I,g,B,C){const E=this.chunkIndexRange(B,I);if(E)for(const i of g){const o=this.store_.getChunkGrid(I,A,i);if(o)for(let a=E.zMin;a<E.zMax;++a){const D=o[a];for(let s=E.yMin;s<E.yMax;++s){const y=D[s];for(let e=E.xMin;e<E.xMax;++e){const Y=y[e];C(Y,this.getChunkAabb(Y))}}}}}iterateAllChunksAtLod(A,I,g,B){for(const C of g){const E=this.store_.getChunkGrid(I,A,C);if(E)for(const i of E)for(const o of i)for(const a of o)B(a,this.getChunkAabb(a))}}getChunkAabb(A){return new Qg(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))}fallbackLOD(){return Math.min(this.policy_.lod.max,this.store_.getLowestResLOD())}timeIndex(A){const I=this.store_.dimensions.t;return A.t===void 0||I===void 0?0:fD(I.lods[0],A.t)}getZBounds(A){const I=this.store_.dimensions.z;if(I===void 0)return[0,1];if(A.z===void 0){const D=I.lods[this.currentLOD_];return[D.translation,D.translation+D.size*D.scale]}const g=I.lods[this.currentLOD_],B=g.size,C=g.scale,E=g.translation,i=Math.floor((A.z-E)/C),o=g.chunkSize,a=Math.max(0,Math.min(Math.floor(i/o),Math.ceil(B/o)-1));return[E+a*o*C,E+(a+1)*o*C]}viewBounds2DChanged(A){return this.lastViewBounds2D_===null||!LQ(this.lastViewBounds2D_.min,A.min)||!LQ(this.lastViewBounds2D_.max,A.max)}hasViewProjectionChanged(A){return this.lastViewProjection_===null||!bo(this.lastViewProjection_,A)}zBoundsChanged(A){return!this.lastZBounds_||!LQ(this.lastZBounds_,A)}cCoordsChanged(A){return!this.lastCCoords_&&!A?!1:!this.lastCCoords_||!A||this.lastCCoords_.length!==A.length?!0:!this.lastCCoords_.every((I,g)=>I===A[g])}getPaddedBounds(A){const I=this.store_.dimensions,g=I.x.lods[this.currentLOD_],B=I.y.lods[this.currentLOD_],C=I.z?.lods[this.currentLOD_],E=g.chunkSize*g.scale*this.policy_.prefetch.x,i=B.chunkSize*B.scale*this.policy_.prefetch.y;let o=0;return C&&(o=C.chunkSize*C.scale*this.policy_.prefetch.z),new Qg(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 g={x:A.offset.x+.5*A.shape.x*A.scale.x,y:A.offset.y+.5*A.shape.y*A.scale.y},B=g.x-I[0],C=g.y-I[1];return B*B+C*C}}function jQ(Q){Q.visible=!1,Q.prefetch=!1,Q.priority=null,Q.orderKey=null}class uD{chunks_;lowestResLOD_;dimensions_;views_=[];hasHadViews_=!1;constructor(A){this.dimensions_=A,this.lowestResLOD_=this.dimensions_.numLods-1,this.validateXYScaleRatios();const{size:I}=this.getAndValidateTimeDimension(),{size:g}=this.getAndValidateChannelDimension(),B=this.dimensions_.numLods;this.chunks_=new Array(B);for(let C=0;C<B;++C){const E=this.dimensions_.x.lods[C],i=this.dimensions_.y.lods[C],o=this.dimensions_.z?.lods[C],a=E.chunkSize,D=i.chunkSize,s=o?.chunkSize??1,y=Math.ceil(E.size/a),e=Math.ceil(i.size/D),Y=o?Math.ceil(o.size/s):1,u=new Array(I);this.chunks_[C]=u;for(let H=0;H<I;++H){const W=new Array(g);u[H]=W;for(let z=0;z<g;++z){const x=new Array(Y);W[z]=x;for(let l=0;l<Y;++l){const Z=o!==void 0?o.translation+l*s*o.scale:0,v=new Array(e);x[l]=v;for(let CA=0;CA<e;++CA){const sA=i.translation+CA*D*i.scale,DA=new Array(y);v[CA]=DA;for(let yA=0;yA<y;++yA){const wA=E.translation+yA*a*E.scale;DA[yA]={state:"unloaded",lod:C,visible:!1,prefetch:!1,priority:null,orderKey:null,shape:{x:Math.min(a,E.size-yA*a),y:Math.min(D,i.size-CA*D),z:Math.min(s,(o?.size??1)-l*s),c:1},rowAlignmentBytes:1,chunkIndex:{x:yA,y:CA,z:l,c:z,t:H},scale:{x:E.scale,y:i.scale,z:o?.scale??1},offset:{x:wA,y:sA,z:Z}}}}}}}}}getChunkGrid(A,I,g){return this.chunks_[A]?.[I]?.[g]}hasChunksAtTime(A){return this.chunks_[0]?.[A]!==void 0}get lodCount(){return this.lowestResLOD_+1}get channelCount(){return this.dimensions_.c?.lods[0].size??1}get dimensions(){return this.dimensions_}getLowestResLOD(){return this.lowestResLOD_}addView(A){const I=new pD(this,A);return this.views_.push(I),this.hasHadViews_=!0,I}get views(){return this.views_}canDispose(){return this.hasHadViews_&&this.views_.length===0}updateAndCollectChunkChanges(){const A=new Set;for(const I of this.views_)for(const[g,B]of I.chunkViewStates)A.add(g);for(const I of A)this.aggregateChunkViewStates(I);return this.removeDisposedViews(),A}removeDisposedViews(){for(let A=this.views_.length-1;A>=0;A--)this.views_[A].isDisposed&&this.views_.splice(A,1)}aggregateChunkViewStates(A){let I=!1,g=!1,B=null,C=null;for(const a of this.views_){const D=a.chunkViewStates.get(A);D&&(D.visible&&(I=!0),D.prefetch&&(g=!0),D.priority!==null&&(B===null||D.priority<B)&&(B=D.priority,C=D.orderKey),!D.visible&&!D.prefetch&&D.priority===null&&a.maybeForgetChunk(A))}if(A.visible=I,A.prefetch=g,A.priority=B,A.orderKey=C,A.priority!==null&&A.state==="unloaded"){A.state="queued";return}if(A.priority===null&&A.state==="queued"){A.state="unloaded";return}if(A.state==="loaded"&&A.priority===null){if(A.visible||A.prefetch)throw new Error(`Chunk state inconsistency detected: priority is null but visible=${A.visible} or prefetch=${A.prefetch} for chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`);HD(A),A.state="unloaded",A.orderKey=null,gA.debug("ChunkStore",`Disposing chunk ${JSON.stringify(A.chunkIndex)} in LOD ${A.lod}`)}}validateXYScaleRatios(){const A=this.dimensions_.x,I=this.dimensions_.y;for(let g=1;g<this.dimensions_.numLods;g++){const B=A.lods[g].scale/A.lods[g-1].scale,C=I.lods[g].scale/I.lods[g-1].scale;if(!PE(B,2,.02)||!PE(C,2,.02))throw new Error(`Invalid downsampling factor between levels ${g-1} → ${g}: expected (2× in X and Y), but got (${B.toFixed(2)}×, ${C.toFixed(2)}×) from scale [${A.lods[g-1].scale}, ${I.lods[g-1].scale}] → [${A.lods[g].scale}, ${I.lods[g].scale}]`)}}getAndValidateTimeDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.t?.lods[A];if(!I)continue;const g=this.dimensions_.t?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in t. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.t?.lods[0].size??1}}getAndValidateChannelDimension(){for(let A=0;A<this.dimensions_.numLods;++A){const I=this.dimensions_.c?.lods[A];if(!I)continue;if(I.scale!==1&&gA.warn("ChunkStore",`Idetik does not make use of non-unity scale in c. Found ${I.scale} at LOD ${A}`),I.translation!==0)throw new Error(`ChunkStore does not support translation in c. Found ${I.translation} at LOD ${A}`);const g=this.dimensions_.c?.lods[A-1];if(g&&I.size!==g.size)throw new Error(`ChunkStore does not support downsampling in c. Found ${g.size} at LOD ${A-1} → ${I.size} at LOD ${A}`)}return{size:this.dimensions_.c?.lods[0].size??1}}}class mD{stores_=[];queue_=new MD;get queueStats(){return{pending:this.queue_.pendingCount,running:this.queue_.runningCount}}get memoryStats(){return qD()}addView(A,I){let g=this.stores_.find(B=>B.source===A)?.store;return g||(g=new uD(A.loader.getSourceDimensionMap()),this.stores_.push({source:A,store:g})),g.addView(I)}update(){for(const{source:A,store:I}of this.stores_){const g=I.updateAndCollectChunkChanges();for(const B of g)B.priority===null?this.queue_.cancel(B):B.state==="queued"&&this.queue_.enqueue(B,C=>A.loader.loadChunkData(B,C))}this.queue_.flush();for(let A=this.stores_.length-1;A>=0;A--)this.stores_[A].store.canDispose()&&this.stores_.splice(A,1)}}var sB=function(Q=1){var A=0,I=document.createElement("div");I.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",I.addEventListener("click",function(s){s.preventDefault(),B(++A%I.children.length)},!1);function g(s){return I.appendChild(s.dom),s}function B(s){for(var y=0;y<I.children.length;y++)I.children[y].style.display=y===s?"block":"none";A=s}var C=(performance||Date).now(),E=C,i=0,o=g(new sB.Panel("FPS","#0ff","#002",Q)),a=g(new sB.Panel("MS","#0f0","#020",Q));if(self.performance&&self.performance.memory)var D=g(new sB.Panel("MB","#f08","#201",Q));return B(0),{REVISION:16,dom:I,addPanel:g,showPanel:B,begin:function(){C=(performance||Date).now()},end:function(){i++;var s=(performance||Date).now();if(a.update(s-C,200),s>=E+1e3&&(o.update(i*1e3/(s-E),100),E=s,i=0,D)){var y=performance.memory;D.update(y.usedJSHeapSize/1048576,y.jsHeapSizeLimit/1048576)}return s},update:function(){C=this.end()},domElement:I,setMode:B}};sB.Panel=function(Q,A,I,g){var B=1/0,C=0,E=Math.round,i=E(window.devicePixelRatio||1),o=E(80*i*g),a=E(48*i*g),D=E(3*i*g),s=E(2*i*g),y=E(3*i*g),e=E(15*i*g),Y=E(74*i*g),u=E(30*i*g),H=document.createElement("canvas");H.width=o,H.height=a,H.style.cssText=`width:${E(g*80)}px;height:${E(g*48)}px`;var W=H.getContext("2d");return W.font="bold "+E(9*i*g)+"px Helvetica,Arial,sans-serif",W.textBaseline="top",W.fillStyle=I,W.fillRect(0,0,o,a),W.fillStyle=A,W.fillText(Q,D,s),W.fillRect(y,e,Y,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y,e,Y,u),{dom:H,update:function(z,x){B=Math.min(B,z),C=Math.max(C,z),W.fillStyle=I,W.globalAlpha=1,W.fillRect(0,0,o,e),W.fillStyle=A,W.fillText(E(z)+" "+Q+" ("+E(B)+"-"+E(C)+")",D,s),W.drawImage(H,y+i,e,Y-i,u,y,e,Y-i,u),W.fillRect(y+Y-i,e,i,u),W.fillStyle=I,W.globalAlpha=.9,W.fillRect(y+Y-i,e,i,E((1-z/x)*u))}}};function xD({scale:Q}={scale:1.5}){const A=new sB(Q);return A.showPanel(0),document.body.appendChild(A.dom),A}const zQ=["pointerdown","pointermove","pointerup","pointercancel","wheel"];function TD(Q){return zQ.includes(Q)}class WD{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 bD{listeners_=[];element_;isConnected_=!1;constructor(A){this.element_=A}addEventListener(A){this.listeners_.push(A)}connect(){if(this.isConnected_){gA.warn("EventDispatcher","Attempted to connect already connected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!0,zQ.forEach(A=>{this.element_.addEventListener(A,this.handleEvent,{passive:!1})})}disconnect(){if(!this.isConnected_){gA.debug("EventDispatcher","Attempted to disconnect already disconnected event dispatcher",`element id: ${this.element_.id}`);return}this.isConnected_=!1,zQ.forEach(A=>{this.element_.removeEventListener(A,this.handleEvent)})}handleEvent=A=>{if(!TD(A.type)){gA.error("EventDispatcher",`Unsupported event type ${A.type}`);return}const I=new WD(A.type,A);for(const g of this.listeners_)if(g(I),I.propagationStopped)break}}class ZD{id;element;camera;events;cameraControls;context_;layers_=[];constructor(A){this.id=A.id,this.element=A.element,this.camera=A.camera,this.context_=A.context,this.cameraControls=A.cameraControls,this.updateAspectRatio(),this.events=new bD(this.element),this.events.addEventListener(I=>{if(I.event instanceof PointerEvent||I.event instanceof WheelEvent){const{clientX:g,clientY:B}=I.event,C=xA(g,B);I.clipPos=this.clientToClip(C,0),I.worldPos=this.camera.clipToWorld(I.clipPos)}for(const g of this.layers_)if(g.onEvent(I),I.propagationStopped)return;this.cameraControls?.onEvent(I)});for(const I of A.layers??[])this.addLayer(I)}get layers(){return this.layers_}addLayer(A){A.onAttached(this.context_),this.layers_.push(A)}removeLayer(A){const I=this.layers_.indexOf(A);if(I===-1)throw new Error(`Layer to remove not found: ${A}`);this.layers_.splice(I,1),A.onDetached(this.context_)}removeAllLayers(){for(const A of this.layers_)A.onDetached(this.context_);this.layers_=[]}updateSize(){this.updateAspectRatio()}getBoxRelativeTo(A){const I=this.getBox().toRect(),g=A.getBoundingClientRect(),B=window.devicePixelRatio||1,C=g.left*B,E=g.top*B,i=g.height*B,o=I.x-C,a=I.y-E,D=Math.floor(o),s=Math.floor(i-a-I.height),y=Math.floor(I.width),e=Math.floor(I.height);return new QI(xA(D,s),xA(D+y,s+e))}getBufferRect(){return this.getBoxRelativeTo(this.element).toRect()}clientToClip(A,I=0){const[g,B]=A,C=this.element.getBoundingClientRect();return nA(2*(g-C.x)/C.width-1,2*(B-C.y)/C.height-1,I)}clientToWorld(A,I=0){const g=this.clientToClip(A,I);return this.camera.clipToWorld(g)}getBox(){const A=this.element.getBoundingClientRect(),I=window.devicePixelRatio||1,g=A.left*I,B=A.top*I,C=A.width*I,E=A.height*I;return new QI(xA(g,B),xA(g+C,B+E))}updateAspectRatio(){const{width:A,height:I}=this.getBox().toRect();if(A<=0||I<=0){gA.debug("Viewport",`Skipping aspect ratio update for viewport ${this.id}: invalid dimensions ${A}x${I}`);return}const g=A/I;this.camera.setAspectRatio(g)}}function OE(Q,A){for(const I of A){if(I.id===Q.id)throw new Error(`Duplicate viewport ID "${Q.id}". Each viewport must have a unique ID.`);if(I.element===Q.element){const g=Q.element.tagName.toLowerCase()+(Q.element.id?`#${Q.element.id}`:"[element has no id]");throw new Error(`Multiple viewports cannot share the same HTML element: viewports "${I.id}" and "${Q.id}" both use ${g}`)}}}function PD(Q){for(let A=0;A<Q.length;A++)OE(Q[A],Q.slice(0,A))}function vE(Q,A,I){const g=Q.map(B=>{const C=B.element??A;return{...B,element:C,id:B.id??C.id??jC("viewport"),context:I}});return PD(g),g.map(B=>new ZD(B))}class VD{elements_;resizeObserver_;mediaQuery_;onMediaQueryChange_;onChange_;constructor(A=[],I){this.elements_=[...A],this.onChange_=I}connect(){if(this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to connect already connected observer");return}this.resizeObserver_=new ResizeObserver(()=>{this.onChange_()});for(const A of this.elements_)this.resizeObserver_.observe(A);this.startDevicePixelRatioObserver()}startDevicePixelRatioObserver(){this.mediaQuery_=matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`),this.onMediaQueryChange_=()=>{this.onChange_(),this.startDevicePixelRatioObserver()},this.mediaQuery_.addEventListener("change",this.onMediaQueryChange_,{once:!0})}disconnect(){if(!this.resizeObserver_){gA.warn("PixelSizeObserver","Attempted to disconnect already disconnected observer");return}this.resizeObserver_?.disconnect(),this.mediaQuery_&&this.onMediaQueryChange_&&this.mediaQuery_.removeEventListener("change",this.onMediaQueryChange_)}observe(A){if(this.elements_.includes(A)){gA.warn("PixelSizeObserver","Element already being observed");return}this.elements_.push(A),this.resizeObserver_&&this.resizeObserver_.observe(A)}unobserve(A){const I=this.elements_.indexOf(A);if(I===-1){gA.warn("PixelSizeObserver","Element not being observed");return}this.elements_.splice(I,1),this.resizeObserver_&&this.resizeObserver_.unobserve(A)}}class _Q{chunkManager_;context_;renderer_;viewports_;canvas;overlays;stats_;sizeObserver_;lastAnimationId_;lastTimestamp_=0;static async create(A){const I=A.renderer==="webgpu-experimental"?await LD(A.canvas):new EE(A.canvas);return new _Q(A,I)}constructor(A,I){this.canvas=A.canvas,this.renderer_=I??new EE(this.canvas),this.chunkManager_=new mD,this.context_={chunkManager:this.chunkManager_},this.viewports_=vE(A.viewports??[],this.canvas,this.context_),this.overlays=A.overlays??[],A.showStats&&(this.stats_=xD());const g=[this.canvas];for(const B of this.viewports_)B.element!==this.canvas&&g.push(B.element);this.sizeObserver_=new VD(g,()=>{this.renderer_.updateSize(),this.renderer_.beginFrame();for(const B of this.viewports_)B.updateSize(),this.renderer_.render(B)})}get chunkQueueStats(){return this.chunkManager_.queueStats}get memoryStats(){const A=performance.memory;return{...this.chunkManager_.memoryStats,gpuTextureBytes:this.renderer_.gpuTextureBytes,gpuTextureCount:this.renderer_.gpuTextureCount,jsHeapUsedBytes:A?.usedJSHeapSize,jsHeapLimitBytes:A?.jsHeapSizeLimit}}get renderedObjects(){return this.renderer_.renderedObjects}get width(){return this.renderer_.width}get height(){return this.renderer_.height}get viewports(){return this.viewports_}get running(){return this.lastAnimationId_!==void 0}getViewport(A){return this.viewports_.find(I=>I.id===A)}addViewport(A){const[I]=vE([A],this.canvas,this.context_);return OE(I,this.viewports_),this.viewports_.push(I),this.running&&(I.events.connect(),I.element!==this.canvas&&this.sizeObserver_.observe(I.element)),gA.info("Idetik",`Added viewport "${I.id}"`),I}removeViewport(A){const I=this.viewports_.indexOf(A);return I===-1?(gA.warn("Idetik",`Viewport "${A.id}" not found, nothing to remove`),!1):(this.running&&(A.events.disconnect(),A.element!==this.canvas&&this.sizeObserver_.unobserve(A.element)),this.viewports_.splice(I,1),gA.info("Idetik",`Removed viewport "${A.id}"`),!0)}start(){if(gA.info("Idetik","Idetik runtime starting"),this.running)gA.warn("Idetik","Idetik runtime already started");else{for(const A of this.viewports_)A.events.connect();this.sizeObserver_.connect(),this.lastAnimationId_=requestAnimationFrame(A=>{this.lastTimestamp_=A,this.animate(A)})}return this}animate(A){this.stats_&&this.stats_.begin();const I=Math.min(A-this.lastTimestamp_,100)/1e3;this.lastTimestamp_=A,this.renderer_.beginFrame();for(const g of this.viewports_)g.cameraControls?.onUpdate(I),this.renderer_.render(g);this.chunkManager_.update();for(const g of this.overlays)g.update(this);this.stats_&&this.stats_.end(),this.lastAnimationId_=requestAnimationFrame(g=>this.animate(g))}stop(){if(gA.info("Idetik","Idetik runtime stopping"),!this.running)gA.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}}}function OD(Q,A){return{...Q,...A,headers:{...Q.headers,...A.headers}}}function XE(Q,A){const I=typeof Q=="string"?new URL(Q):Q;I.pathname.endsWith("/")||(I.pathname+="/");const g=new URL(A.slice(1),I);return g.search=I.search,g}async function jE(Q){if(Q.status!==404){if(Q.status===200||Q.status===206)return new Uint8Array(await Q.arrayBuffer());throw new Error(`Unexpected response status ${Q.status} ${Q.statusText}`)}}class hB{url;#A;#I;#g;constructor(A,I={}){this.url=A,this.#A=I.fetch??(g=>fetch(g)),this.#I=I.overrides??{},this.#g=I.useSuffixRequest??!1}#B(A,I){return new Request(A,OD(this.#I,I))}async get(A,I={}){let g=XE(this.url,A).href,B=this.#B(g,I),C=await this.#A(B);return jE(C)}async getRange(A,I,g={}){let B=XE(this.url,A),C;if("suffixLength"in I)C=await this.#Q(B,I.suffixLength,g);else{let E={...g,headers:{...g.headers,Range:`bytes=${I.offset}-${I.offset+I.length-1}`}},i=this.#B(B,E);C=await this.#A(i)}return jE(C)}async#Q(A,I,g){if(this.#g){let D={...g,headers:{...g.headers,Range:`bytes=-${I}`}};return this.#A(this.#B(A,D))}let B=this.#B(A,{...g,method:"HEAD"}),C=await this.#A(B);if(!C.ok)return C;let E=C.headers.get("Content-Length"),i=Number(E),o=i-I,a={...g,headers:{...g.headers,Range:`bytes=${o}-${i-1}`}};return this.#A(this.#B(A,a))}}class yB extends Error{}class Mg extends yB{_tag="NotFoundError";name="NotFoundError";path;found;constructor(A,I={}){super(`Not found: ${A}`,{cause:I.cause}),this.path=I.path,this.found=I.found}}class WA extends yB{_tag="InvalidMetadataError";name="InvalidMetadataError";path;constructor(A,I={}){super(A,{cause:I.cause}),this.path=I.path}}class vD extends yB{_tag="UnknownCodecError";name="UnknownCodecError";codec;constructor(A){super(`Unknown codec: ${A}`),this.codec=A}}class XD extends yB{_tag="CodecPipelineError";name="CodecPipelineError";direction;codec;chunkPath;constructor(A){const I=[`Failed to ${A.direction} chunk`,A.codec&&`via codec "${A.codec}"`,A.chunkPath&&`at ${A.chunkPath}`].filter(Boolean);super(I.join(" "),{cause:A.cause}),this.direction=A.direction,this.codec=A.codec,this.chunkPath=A.chunkPath}}class $Q extends yB{_tag="UnsupportedError";name="UnsupportedError";feature;constructor(A){super(`Unsupported: ${A}`),this.feature=A}}function og(Q){return()=>{throw new $Q(`${Q} encode`)}}class OB{kind="array_to_array";constructor(A,I){if(A.keepbits<0)throw new WA("keepbits must be zero or positive")}static fromConfig(A,I){return new OB(A,I)}encode=og("bitround");decode(A){return A}}function AC(Q){return Q instanceof ArrayBuffer||Q instanceof SharedArrayBuffer}class zE{#A;constructor(A,I,g){typeof A=="number"?this.#A=new Uint8Array(A):AC(A)?this.#A=new Uint8Array(A,I,g):this.#A=new Uint8Array(Array.from(A,B=>B?1:0))}get BYTES_PER_ELEMENT(){return 1}get byteOffset(){return this.#A.byteOffset}get byteLength(){return this.#A.byteLength}get buffer(){return this.#A.buffer}get length(){return this.#A.length}get(A){let I=this.#A[A];return typeof I=="number"?I!==0:I}set(A,I){this.#A[A]=I?1:0}fill(A){this.#A.fill(A?1:0)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class IC{_data;chars;#A;constructor(A,I,g,B){if(this.chars=A,this.#A=new TextEncoder,typeof I=="number")this._data=new Uint8Array(I*A);else if(AC(I))B&&(B=B*A),this._data=new Uint8Array(I,g,B);else{let C=Array.from(I);this._data=new Uint8Array(C.length*A);for(let E=0;E<C.length;E++)this.set(E,C[E])}}get BYTES_PER_ELEMENT(){return this.chars}get byteOffset(){return this._data.byteOffset}get byteLength(){return this._data.byteLength}get buffer(){return this._data.buffer}get length(){return this.byteLength/this.BYTES_PER_ELEMENT}get(A){const I=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);return new TextDecoder().decode(I).replace(/\x00/g,"")}set(A,I){const g=new Uint8Array(this.buffer,this.byteOffset+this.chars*A,this.chars);g.fill(0),g.set(this.#A.encode(I))}fill(A){const I=this.#A.encode(A);for(let g=0;g<this.length;g++)this._data.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}class tB{#A;chars;constructor(A,I,g,B){if(this.chars=A,typeof I=="number")this.#A=new Int32Array(I*A);else if(AC(I))B&&(B*=A),this.#A=new Int32Array(I,g,B);else{const C=I,E=new tB(A,1);this.#A=new Int32Array((function*(){for(let i of C)E.set(0,i),yield*E.#A})())}}get BYTES_PER_ELEMENT(){return this.#A.BYTES_PER_ELEMENT*this.chars}get byteLength(){return this.#A.byteLength}get byteOffset(){return this.#A.byteOffset}get buffer(){return this.#A.buffer}get length(){return this.#A.length/this.chars}get(A){const I=this.chars*A;let g="";for(let B=0;B<this.chars;B++)g+=String.fromCodePoint(this.#A[I+B]);return g.replace(/\u0000/g,"")}set(A,I){const g=this.chars*A,B=this.#A.subarray(g,g+this.chars);B.fill(0);for(let C=0;C<this.chars;C++)B[C]=I.codePointAt(C)??0}fill(A){this.set(0,A);let I=this.#A.subarray(0,this.chars);for(let g=1;g<this.length;g++)this.#A.set(I,g*this.chars)}*[Symbol.iterator](){for(let A=0;A<this.length;A++)yield this.get(A)}}function jD(){if(typeof SharedArrayBuffer>"u")throw new Error("SharedArrayBuffer is not available. In browsers, this requires Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers to be set.")}function zD(Q,A){return new SharedArrayBuffer(Q)}function GB(Q){const A=new TextDecoder().decode(Q);try{return JSON.parse(A)}catch(I){throw new WA("Failed to decode JSON",{cause:I})}}function _E(Q,A){const I=A/2,g=A-1;let B=0;for(let C=0;C<Q.length;C+=A)for(let E=0;E<I;E+=1)B=Q[C+E],Q[C+E]=Q[C+g-E],Q[C+g-E]=B}function dg(Q){if(Q==="v2:object")return globalThis.Array;let A=Q.match(/v2:([US])(\d+)/);if(A){let[,g,B]=A;return(g==="U"?tB:IC).bind(null,Number(B))}if(Q==="string")return globalThis.Array;let I={int8:Int8Array,int16:Int16Array,int32:Int32Array,int64:globalThis.BigInt64Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,uint64:globalThis.BigUint64Array,float16:globalThis.Float16Array,float32:Float32Array,float64:Float64Array,bool:zE}[Q];if(!I)throw new WA(`Unknown or unsupported dataType: ${Q}`);return I}function ag(Q,A){const I=Q.length;typeof A=="string"&&(A=A==="C"?Array.from({length:I},(C,E)=>E):Array.from({length:I},(C,E)=>I-1-E)),yI(I===A.length,"Order length must match the number of dimensions.");let g=1,B=new Array(I);for(let C=A.length-1;C>=0;C--)B[A[C]]=g,g*=Q[A[C]];return B}function _D({name:Q,configuration:A}){if(Q==="default"){const I=A?.separator??"/";return g=>["c",...g].join(I)}if(Q==="v2"){const I=A?.separator??".";return g=>g.join(I)||"0"}throw new WA(`Unknown chunk key encoding: ${Q}`)}function $E(Q){if(Q==="|O")return{dataType:"v2:object"};let A=Q.match(/^([<|>])(.*)$/);if(!A)throw new WA(`Invalid dtype: ${Q}`);let[,I,g]=A,B={b1:"bool",i1:"int8",u1:"uint8",i2:"int16",u2:"uint16",i4:"int32",u4:"uint32",i8:"int64",u8:"uint64",f2:"float16",f4:"float32",f8:"float64"}[g]??(g.startsWith("S")||g.startsWith("U")?`v2:${g}`:void 0);if(!B)throw new WA(`Unsupported or unknown dtype: ${Q}`);return I==="|"?{dataType:B}:{dataType:B,endian:I==="<"?"little":"big"}}function $D(Q){return(Q.id==="fixedscaleoffset"||Q.id==="numcodecs.fixedscaleoffset")&&typeof Q.scale=="number"&&typeof Q.offset=="number"&&(Q.astype===void 0||typeof Q.astype=="string")&&(Q.dtype===void 0||typeof Q.dtype=="string")}function As(Q,A={}){let I=[],g=$E(Q.dtype);Q.order==="F"&&I.push({name:"transpose",configuration:{order:"F"}});for(let C of Q.filters??[]){if(C.id==="fixedscaleoffset"||C.id==="numcodecs.fixedscaleoffset"){if(!$D(C))throw new WA(`Invalid fixedscaleoffset filter: ${JSON.stringify(C)}`);I.push({name:"scale_offset",configuration:{scale:C.scale,offset:C.offset}});let o=C.astype??C.dtype;if(o!==void 0&&o!==Q.dtype){let a=$E(o).dataType;if(!gC(a,"number")&&!gC(a,"bigint"))throw new WA(`fixedscaleoffset astype must be a numeric data type, got ${o}`);I.push({name:"cast_value",configuration:{data_type:a,rounding:"nearest-even",out_of_range:"wrap"}})}continue}let{id:E,...i}=C;I.push({name:`numcodecs.${E}`,configuration:i})}if("endian"in g&&g.endian==="big"&&I.push({name:"bytes",configuration:{endian:"big"}}),Q.compressor){let{id:C,...E}=Q.compressor;I.push({name:`numcodecs.${C}`,configuration:E})}let B;return globalThis.Array.isArray(A._ARRAY_DIMENSIONS)&&(B=A._ARRAY_DIMENSIONS),{zarr_format:3,node_type:"array",shape:Q.shape,data_type:g.dataType,chunk_grid:{name:"regular",configuration:{chunk_shape:Q.chunks}},chunk_key_encoding:{name:"v2",configuration:{separator:Q.dimension_separator??"."}},codecs:I,fill_value:Q.fill_value,dimension_names:B,attributes:A}}function Is(Q,A={}){return{zarr_format:3,node_type:"group",attributes:A}}function gC(Q,A){if(A!=="number"&&A!=="bigint"&&A!=="boolean"&&A!=="object"&&A!=="string")return Q===A;let I=Q==="bool";if(A==="boolean")return I;let g=Q.startsWith("v2:U")||Q.startsWith("v2:S")||Q==="string";if(A==="string")return g;let B=Q==="int64"||Q==="uint64";if(A==="bigint")return B;let C=Q==="v2:object";return A==="object"?C:!g&&!B&&!I&&!C}function gs(Q){return Q?.name==="sharding_indexed"}function Ai(Q){if((Q.data_type==="uint64"||Q.data_type==="int64")&&Q.fill_value!=null)return BigInt(Q.fill_value);let A=Q.data_type==="float16"||Q.data_type==="float32"||Q.data_type==="float64";if(typeof Q.fill_value=="string"&&A){let I={NaN:NaN,Infinity:1/0,"-Infinity":-1/0};if(Q.fill_value in I)return I[Q.fill_value]}return Q.fill_value}function Ii(Q,...A){if(!A.some(I=>Q instanceof I))throw Q}function yI(Q,A=""){if(!Q)throw new Error(A)}async function gi(Q,{format:A,signal:I}){let g;if(Q instanceof ArrayBuffer)g=new Response(Q);else{let B=new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength);g=new Response(B.slice().buffer)}yI(g.body,"Response does not contain body.");try{return await new Response(g.body.pipeThrough(new DecompressionStream(A),{signal:I})).arrayBuffer()}catch{throw I?.throwIfAborted(),new Error(`Failed to decode ${A}`)}}const Bi=Bs();function Bs(){const Q=new Uint32Array([305419896]);return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)[0]!==18}function Qi(Q){return"BYTES_PER_ELEMENT"in Q?Q.BYTES_PER_ELEMENT:4}class vB{kind="array_to_bytes";#A;#I;#g;#B;#Q;constructor(A,I){this.#Q=A?.endian,this.#I=dg(I.dataType),this.#B=I.shape,this.#A=ag(I.shape,"C");const g=new this.#I(0);this.#g=g.BYTES_PER_ELEMENT}static fromConfig(A,I){return new vB(A,I)}encode(A){let I=new Uint8Array(A.data.buffer);return Bi&&this.#Q==="big"&&_E(I,Qi(this.#I)),I}computeEncodedSize(A){return A}decode(A){return Bi&&this.#Q==="big"&&_E(A,Qi(this.#I)),{data:new this.#I(A.buffer,A.byteOffset,A.byteLength/this.#g),shape:this.#B,stride:this.#A}}}const Ci={NaN:NaN,Infinity:1/0,"-Infinity":-1/0},Ei={float16:2,float32:4,float64:8};function XB(Q){return Q in Ei}function BC(Q){return Q==="int64"||Q==="uint64"}function Qs(Q,A){const I=BigInt(Q),g=new ArrayBuffer(A),B=new DataView(g);if(A===2){if(typeof B.getFloat16!="function")throw new $Q("float16 hex-encoded scalar decoding (requires DataView.prototype.getFloat16)");return B.setUint16(0,Number(I)),B.getFloat16(0)}return A===4?(B.setUint32(0,Number(I)),B.getFloat32(0)):(B.setBigUint64(0,I),B.getFloat64(0))}function jB(Q,A){if(BC(Q)){if(typeof A!="number"||!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${JSON.stringify(A)}`);return BigInt(A)}if(typeof A=="number"){if(!XB(Q)&&!Number.isInteger(A))throw new WA(`Expected an integer value for data type "${Q}", got ${A}`);return A}if(!XB(Q))throw new WA(`String-encoded scalar "${A}" is not valid for non-float data type "${Q}"`);return A in Ci?Ci[A]:Qs(A,Ei[Q])}const ii=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]),QC={int8:[-128,2**7-1],uint8:[0,2**8-1],int16:[-32768,2**15-1],uint16:[0,2**16-1],int32:[-2147483648,2**31-1],uint32:[0,2**32-1]},CC={int64:[-(2n**63n),2n**63n-1n],uint64:[0n,2n**64n-1n]};function oi(Q,A,I){return Q.map(([g,B])=>({src:jB(A,g),tgt:jB(I,B)}))}function Cs(Q,A){for(const I of A)if(typeof I.src=="number"&&Number.isNaN(I.src)){if(typeof Q=="number"&&Number.isNaN(Q))return I.tgt}else if(Q===I.src)return I.tgt}function Es(Q){if(!Number.isFinite(Q))return Q;if(Math.abs(Q-Math.trunc(Q))===.5){const A=Math.floor(Q),I=Math.ceil(Q);return A%2===0?A:I}return Math.round(Q)}function is(Q){return Math.sign(Q)*Math.floor(Math.abs(Q)+.5)}function ai(Q){switch(Q){case"nearest-even":return Es;case"towards-zero":return Math.trunc;case"towards-positive":return Math.ceil;case"towards-negative":return Math.floor;case"nearest-away":return is}}function EC(Q,A,I){const g=A-Q+1;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}function iC(Q,A,I){const g=A-Q+1n;switch(I){case"clamp":return B=>B<Q?Q:B>A?A:B;case"wrap":return B=>B>=Q&&B<=A?B:((B-Q)%g+g)%g+Q;default:return B=>{if(B>=Q&&B<=A)return B;throw new Error(`Value ${B} out of range [${Q}, ${A}]. Set out_of_range='clamp' or out_of_range='wrap' to handle this.`)}}}class oC{kind="array_to_array";#A;#I;#g;#B;constructor(A,I,g,B,C,E){this.#A=I,this.#I=dg(A),this.#g=Di(I,A,g,B,C),this.#B=Di(A,I,g,B,E)}getEncodedMeta(A){let I=A.fillValue;return I!=null&&(I=this.#B(I)),{...A,dataType:this.#A,fillValue:I}}static fromConfig(A,I){const g=I.dataType,B=A.data_type;if(!ii.has(g))throw new WA(`cast_value codec does not support array data type: ${g}`);if(!ii.has(B))throw new WA(`cast_value codec does not support encoded data type: ${B}`);const C=A.rounding??"nearest-even",E=A.scalar_map?.decode?oi(A.scalar_map.decode,B,g):[],i=A.scalar_map?.encode?oi(A.scalar_map.encode,g,B):[];return new oC(g,B,C,A.out_of_range,E,i)}encode=og("cast_value");decode(A){const I=A.data,g=new this.#I(I.length);for(let B=0;B<I.length;B++)g[B]=this.#g(I[B]);return{data:g,shape:A.shape,stride:A.stride}}}function Di(Q,A,I,g,B){const C=XB(Q),E=BC(Q),i=XB(A),o=BC(A);let a;if(C&&i){if(I!=="nearest-even")throw new WA(`cast_value float -> float only supports "nearest-even" rounding, got "${I}"`);a=s=>s}else if(C&&!i&&!o){const s=ai(I),y=EC(...QC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(s(e))}}else if(C&&o){const s=ai(I),y=iC(...CC[A],g);a=e=>{if(!Number.isFinite(e))throw new Error(`Cannot cast ${e} to integer type without scalar_map`);return y(BigInt(s(e)))}}else if(!C&&!E&&i)a=s=>s;else if(E&&i)a=s=>Number(s);else if(!C&&!E&&!i&&!o)a=EC(...QC[A],g);else if(!C&&!E&&o){const s=iC(...CC[A],g);a=y=>s(BigInt(y))}else if(E&&!i&&!o){const s=EC(...QC[A],g);a=y=>s(Number(y))}else if(E&&o)a=iC(...CC[A],g);else throw new Error(`Unhandled type combination: ${Q} -> ${A}`);return B.length===0?a:s=>{const y=Cs(s,B);return y!==void 0?y:a(s)}}class aC{kind="bytes_to_bytes";static fromConfig(){return new aC}encode=og("crc32c");decode(A){return new Uint8Array(A.buffer,A.byteOffset,A.byteLength-4)}computeEncodedSize(A){return A+4}}const os=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);function si(Q,A){const I=Q.length;let g=I===0||A[I-1]===1;for(let C=I-2;C>=0&&g;C--)g=A[C]===A[C+1]*Q[C+1];if(g)return;let B=I===0||A[0]===1;for(let C=1;C<I&&B;C++)B=A[C]===A[C-1]*Q[C-1];if(!B)throw new Error(`DeltaCodec requires C- or Fortran-contiguous strides, got shape=${JSON.stringify(Q)} stride=${JSON.stringify(A)}`)}class DC{kind="array_to_array";#A;constructor(A){this.#A=A}static fromConfig(A,I){if(!os.has(I.dataType))throw new WA(`Delta codec does not support data type: ${I.dataType}`);return new DC(dg(I.dataType))}encode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=I[B]-I[B-1];return{data:g,shape:A.shape,stride:A.stride}}decode(A){si(A.shape,A.stride);const I=A.data,g=new this.#A(I.length);g[0]=I[0];for(let B=1;B<I.length;B++)g[B]=g[B-1]+I[B];return{data:g,shape:A.shape,stride:A.stride}}}class sC{kind="bytes_to_bytes";static fromConfig(A){return new sC}encode=og("gzip");async decode(A){const I=await gi(A,{format:"gzip"});return new Uint8Array(I)}}function as(Q,A){return yI(!Number.isNaN(A),"JsonCodec allow_nan is false but NaN was encountered during encoding."),yI(A!==Number.POSITIVE_INFINITY,"JsonCodec allow_nan is false but Infinity was encountered during encoding."),yI(A!==Number.NEGATIVE_INFINITY,"JsonCodec allow_nan is false but -Infinity was encountered during encoding."),A}function Ds(Q,A){return A instanceof Object&&!Array.isArray(A)?Object.keys(A).sort().reduce((I,g)=>(I[g]=A[g],I),{}):A}class zB{configuration;kind="array_to_bytes";#A;#I;constructor(A={}){this.configuration=A;const{encoding:I="utf-8",skipkeys:g=!1,ensure_ascii:B=!0,check_circular:C=!0,allow_nan:E=!0,sort_keys:i=!0,indent:o,strict:a=!0}=A;let D=A.separators;D||(o?D=[", ",": "]:D=[",",":"]),this.#A={encoding:I,skipkeys:g,ensure_ascii:B,check_circular:C,allow_nan:E,indent:o,separators:D,sort_keys:i},this.#I={strict:a}}static fromConfig(A){return new zB(A)}encode(A){const{indent:I,encoding:g,ensure_ascii:B,check_circular:C,allow_nan:E,sort_keys:i}=this.#A;yI(g==="utf-8","JsonCodec does not yet support non-utf-8 encoding.");const o=[];yI(C,"JsonCodec does not yet support skipping the check for circular references during encoding."),E||o.push(as),i&&o.push(Ds);const a=Array.from(A.data);a.push("|O"),a.push(A.shape);let D;o.length&&(D=(y,e)=>{let Y=e;for(let u of o)Y=u(y,Y);return Y});let s=JSON.stringify(a,D,I);return B&&(s=s.replace(/[\u007F-\uFFFF]/g,y=>{const e=`0000${y.charCodeAt(0).toString(16)}`;return`\\u${e.substring(e.length-4)}`})),new TextEncoder().encode(s)}decode(A){const{strict:I}=this.#I;yI(I,"JsonCodec does not yet support non-strict decoding.");const g=GB(A),B=g.pop();g.pop(),yI(B,"0D not implemented for JsonCodec.");const C=ag(B,"C");return{data:g,shape:B,stride:C}}}const ss=new Set(["int8","uint8","int16","uint16","int32","uint32","int64","uint64","float16","float32","float64"]);class hC{kind="array_to_array";#A;#I;#g;constructor(A,I,g){this.#I=A,this.#g=I,this.#A=g}static fromConfig(A,I){if(!ss.has(I.dataType))throw new WA(`scale_offset codec does not support data type: ${I.dataType}`);return new hC(jB(I.dataType,A.scale??1),jB(I.dataType,A.offset??0),dg(I.dataType))}encode=og("scale_offset");decode(A){const I=A.data,g=new this.#A(I.length);for(let B=0;B<I.length;B++)g[B]=I[B]/this.#I+this.#g;return{data:g,shape:A.shape,stride:A.stride}}}class yC{kind="bytes_to_bytes";#A;constructor(A,I){if(I){let g=new(dg(I.dataType))(0);yI("BYTES_PER_ELEMENT"in g,`Shuffle codec requires a fixed-size dtype, got "${I.dataType}"`),this.#A=g.BYTES_PER_ELEMENT}else this.#A=A.elementsize??4}static fromConfig(A,I){return new yC(A,I)}encode(A){return hs(A,this.#A)}decode(A){return ys(A,this.#A)}}function hs(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[C*g+E]=Q[E*A+C];return B}function ys(Q,A){let I=Q.length,g=Math.floor(I/A),B=new Uint8Array(I);for(let C=0;C<A;C++)for(let E=0;E<g;E++)B[E*A+C]=Q[C*g+E];return B}function hi(Q){return Q instanceof zE||Q instanceof IC||Q instanceof tB?new Proxy(Q,{get(I,g){return I.get(Number(g))},set(I,g,B){return I.set(Number(g),B),!0}}):Q}function ts(Q,A){let I;return Q.data instanceof IC||Q.data instanceof tB?I=new Q.constructor(Q.data.length,Q.data.chars):I=new Q.constructor(Q.data.length),{data:I,shape:Q.shape,stride:ag(Q.shape,A)}}function Gs(Q,A){let I=ts(Q,A),g=Q.shape.length,B=Q.data.length,C=Array(g).fill(0),E=hi(Q.data),i=hi(I.data);for(let o=0;o<B;o++){let a=0;for(let D=0;D<g;D++)a+=C[D]*I.stride[D];i[a]=E[o],C[0]+=1;for(let D=0;D<g;D++)if(C[D]===Q.shape[D]){if(D+1===g)break;C[D]=0,C[D+1]+=1}}return I}function ws(Q){let A=Q.shape.length;return yI(A===Q.stride.length,"Shape and stride must have the same length."),Q.stride.map((I,g)=>({stride:I,index:g})).sort((I,g)=>g.stride-I.stride).map(I=>I.index)}function Fs(Q,A){let I=ws(Q);return yI(I.length===A.length,"Orders must match"),I.every((g,B)=>g===A[B])}class tC{kind="array_to_array";#A;#I;constructor(A,I){let g=A.order??"C",B=I.shape.length,C=new Array(B),E=new Array(B);if(g==="C")for(let i=0;i<B;++i)C[i]=i,E[i]=i;else if(g==="F")for(let i=0;i<B;++i)C[i]=B-i-1,E[i]=B-i-1;else C=g,C.forEach((i,o)=>{yI(E[i]===void 0,`Invalid permutation: ${JSON.stringify(g)}`),E[i]=o});this.#A=C,this.#I=E}static fromConfig(A,I){return new tC(A,I)}encode(A){return Fs(A,this.#I)?A:Gs(A,this.#I)}decode(A){return{data:A.data,shape:A.shape,stride:ag(A.shape,this.#A)}}}class _B{kind="array_to_bytes";#A;#I;constructor(A){this.#A=A,this.#I=ag(A,"C")}static fromConfig(A,I){return new _B(I.shape)}encode=og("vlen-utf8");decode(A){let I=new TextDecoder,g=new DataView(A.buffer),B=Array(g.getUint32(0,!0)),C=4;for(let E=0;E<B.length;E++){let i=g.getUint32(C,!0);C+=4,B[E]=I.decode(A.buffer.slice(C,C+i)),C+=i}return{data:B,shape:this.#A,stride:this.#I}}}class GC{kind="bytes_to_bytes";static fromConfig(A){return new GC}encode=og("zlib");async decode(A){const I=await gi(A,{format:"deflate"});return new Uint8Array(I)}}function es(){let Q=()=>Promise.resolve().then(()=>My).then(C=>C.default),A=()=>Promise.resolve().then(()=>py).then(C=>C.default),I=()=>Promise.resolve().then(()=>by).then(C=>C.default),g=()=>sC,B=()=>GC;return new Map().set("blosc",Q).set("lz4",A).set("zstd",I).set("gzip",g).set("zlib",B).set("transpose",()=>tC).set("bytes",()=>vB).set("crc32c",()=>aC).set("vlen-utf8",()=>_B).set("json2",()=>zB).set("bitround",()=>OB).set("cast_value",()=>oC).set("scale_offset",()=>hC).set("numcodecs.blosc",Q).set("numcodecs.lz4",A).set("numcodecs.zstd",I).set("numcodecs.gzip",g).set("numcodecs.zlib",B).set("numcodecs.vlen-utf8",()=>_B).set("numcodecs.shuffle",()=>yC).set("numcodecs.delta",()=>DC).set("numcodecs.bitround",()=>OB).set("numcodecs.json2",()=>zB)}const rs=es();function wC(Q){let A;function I(){return A||(A=ns(Q)),A}async function g(B,C,E){try{return await E()}catch(i){throw new XD({direction:B,codec:C,cause:i})}}return{async encode(B){let C=await I();for(const{name:i,codec:o}of C.arrayToArray)B=await g("encode",i,()=>o.encode(B));let E=await g("encode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.encode(B));for(const{name:i,codec:o}of C.bytesToBytes)E=await g("encode",i,()=>o.encode(E));return E},async decode(B){let C=await I();for(let i=C.bytesToBytes.length-1;i>=0;i--){const{name:o,codec:a}=C.bytesToBytes[i];B=await g("decode",o,()=>a.decode(B))}let E=await g("decode",C.arrayToBytes.name,()=>C.arrayToBytes.codec.decode(B));for(let i=C.arrayToArray.length-1;i>=0;i--){const{name:o,codec:a}=C.arrayToArray[i];E=await g("decode",o,()=>a.decode(E))}return E},async computeEncodedSize(B){let C=await I(),E=yi(C.arrayToBytes.name,C.arrayToBytes.codec,B);for(const{name:i,codec:o}of C.bytesToBytes)E=yi(i,o,E);return E}}}function yi(Q,A,I){if(!A.computeEncodedSize)throw new WA(`Codec "${Q}" cannot compute its encoded size; it is not a fixed-size codec and cannot be used in a sharding index pipeline`);return A.computeEncodedSize(I)}async function ns(Q){let A=Q.codecs.map(async E=>{let i=await rs.get(E.name)?.();if(!i)throw new vD(E.name);return{Codec:i,meta:E}}),I=[],g,B=[],C={...Q};for await(let{Codec:E,meta:i}of A){let o=E.fromConfig(i.configuration,C);switch(o.kind){case"array_to_array":I.push({name:i.name,codec:o}),o.getEncodedMeta&&(C=o.getEncodedMeta(C));break;case"array_to_bytes":g={name:i.name,codec:o};break;default:B.push({name:i.name,codec:o})}}if(!g){if(!Ss(C))throw new WA(`Cannot encode ${C.dataType} to bytes without a codec`);g={name:"bytes",codec:vB.fromConfig({endian:"little"},C)}}return{arrayToArray:I,arrayToBytes:g,bytesToBytes:B}}function Ss(Q){return Q.dataType!=="v2:object"&&Q.dataType!=="string"}const ti=18446744073709551615n;function Ns(Q,A,I,g){if(!Q.store.getRange)throw new $Q("sharding requires a store with getRange");let B=Q.store.getRange.bind(Q.store),C=A.map((a,D)=>a/g.chunk_shape[D]),E=wC({dataType:"uint64",shape:[...C,2],codecs:g.index_codecs,fillValue:null}),i=16*C.reduce((a,D)=>a*D,1),o={};return async(a,D)=>{let s=a.map((l,Z)=>Math.floor(l/C[Z])),y=Q.resolve(I(s)).path;y in o||(o[y]=(async()=>{let l=await E.computeEncodedSize(i),Z=await B(y,{suffixLength:l},D);return Z?await E.decode(Z):null})().catch(l=>{throw delete o[y],l}));let e=await o[y];if(e===null)return;let{data:Y,shape:u,stride:H}=e,W=a.map((l,Z)=>l%u[Z]).reduce((l,Z,v)=>l+Z*H[v],0),z=Y[W],x=Y[W+1];if(!(z===ti&&x===ti))return B(y,{offset:Number(z),length:Number(x)},D)}}class eI{store;path;constructor(A,I="/"){this.store=A,this.path=I}resolve(A){let I=new URL(`file://${this.path.endsWith("/")?this.path:`${this.path}/`}`);return new eI(this.store,decodeURIComponent(new URL(A,I).pathname))}}class FC extends eI{kind="group";#A;constructor(A,I,g){super(A,I),this.#A=g}get attrs(){return this.#A.attributes}}function Gi(Q){return Q.find(I=>I.name==="transpose")?.configuration?.order??"C"}const $B=Symbol("zarrita.context");function Rs(Q,A){let{configuration:I}=A.codecs.find(gs)??{},g={encodeChunkKey:_D(A.chunk_key_encoding),TypedArray:dg(A.data_type),fillValue:A.fill_value};if(I){let C=Gi(I.codecs);return{...g,kind:"sharded",chunkShape:I.chunk_shape,codec:wC({dataType:A.data_type,shape:I.chunk_shape,codecs:I.codecs,fillValue:A.fill_value}),getStrides(E){return ag(E,C)},getChunkBytes:Ns(Q,A.chunk_grid.configuration.chunk_shape,g.encodeChunkKey,I)}}let B=Gi(A.codecs);return{...g,kind:"regular",chunkShape:A.chunk_grid.configuration.chunk_shape,codec:wC({dataType:A.data_type,shape:A.chunk_grid.configuration.chunk_shape,codecs:A.codecs,fillValue:A.fill_value}),getStrides(C){return ag(C,B)},async getChunkBytes(C,E){let i=g.encodeChunkKey(C),o=Q.resolve(i).path;return Q.store.get(o,E)}}}let AQ=class extends eI{kind="array";#A;[$B];constructor(A,I,g){super(A,I),this.#A={...g,fill_value:Ai(g)},this[$B]=Rs(this,this.#A)}get attrs(){return this.#A.attributes}get dimensionNames(){return this.#A.dimension_names}get fillValue(){return this.#A.fill_value}get shape(){return this.#A.shape}get chunks(){return this[$B].chunkShape}get dtype(){return this.#A.data_type}async getChunk(A,I,g){g?.useSharedArrayBuffer&&jD();let B=this[$B],C=await B.getChunkBytes(A,I);if(!C){let E=B.chunkShape.reduce((o,a)=>o*a,1),i;if(g?.useSharedArrayBuffer){let o=new B.TypedArray(0);if(!("BYTES_PER_ELEMENT"in o))console.warn("zarrita: useSharedArrayBuffer is not supported for non-buffer-backed data types."),i=new B.TypedArray(E);else{let a=zD(E*o.BYTES_PER_ELEMENT);i=new B.TypedArray(a,0,E)}}else i=new B.TypedArray(E);return i.fill(B.fillValue),{data:i,shape:B.chunkShape,stride:B.getStrides(B.chunkShape)}}return B.codec.decode(C)}is(A){return gC(this.dtype,A)}};function cs(Q,A){let I=Q;for(let g of A)I instanceof Promise?I=I.then(B=>g(B)):I=g(I);return I}function Us(Q,...A){return cs(Q,A)}async function wi(Q){let A=Q.store.arrayExtensions;return A?.length?await Us(Q,...A):Q}let IQ=ks();function ks(){let Q=new WeakMap;function A(I){let g=Q.get(I)??{v2:0,v3:0};return Q.set(I,g),g}return{increment(I,g){A(I)[g]+=1},versionMax(I){let g=A(I);return g.v3>g.v2?"v3":"v2"}}}async function Ls(Q,A){let I=await Q.store.get(Q.resolve(".zattrs").path,{signal:A});return I?GB(I):{}}async function Js(Q,A={}){let I="store"in Q?Q:new eI(Q),{signal:g}=A,B={};return(A.attrs??!0)&&(B=await Ls(I,g)),g?.throwIfAborted(),A.kind==="array"?Fi(I,B,g):A.kind==="group"?ei(I,B,g):Fi(I,B,g).catch(C=>(Ii(C,Mg,WA),ei(I,B,g)))}async function Fi(Q,A,I){let{path:g}=Q.resolve(".zarray"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 array",{path:g});return IQ.increment(Q.store,"v2"),wi(new AQ(Q.store,Q.path,As(GB(B),A)))}async function ei(Q,A,I){let{path:g}=Q.resolve(".zgroup"),B=await Q.store.get(g,{signal:I});if(!B)throw new Mg("v2 group",{path:g});return IQ.increment(Q.store,"v2"),new FC(Q.store,Q.path,Is(GB(B),A))}async function Ys(Q,A){let{store:I,path:g}=Q.resolve("zarr.json"),B=await Q.store.get(g,{signal:A});if(!B)throw new Mg("v3 array or group",{path:g});let C=GB(B);return C.node_type==="array"&&(C.fill_value=Ai(C)),C.node_type==="array"?wi(new AQ(I,Q.path,C)):new FC(I,Q.path,C)}async function Ks(Q,A={}){let I="store"in Q?Q:new eI(Q),g=await Ys(I,A.signal);if(IQ.increment(I.store,"v3"),A.kind===void 0||A.kind==="array"&&g instanceof AQ||A.kind==="group"&&g instanceof FC)return g;let B=g instanceof AQ?"array":"group";throw new Mg(`${A.kind} at ${I.path}`,{path:I.path,found:B})}async function rI(Q,A={}){let I="store"in Q?Q.store:Q,g=IQ.versionMax(I),B=g==="v2"?rI.v2:rI.v3,C=g==="v2"?rI.v3:rI.v2;return B(Q,A).catch(E=>(Ii(E,Mg,WA),C(Q,A)))}rI.v2=Js,rI.v3=Ks;async function Ms(Q,A){const I=A.split("/"),g=I.pop();if(!g)throw new Error("Invalid path");for(const B of I)Q=await Q.getDirectoryHandle(B);return Q.getFileHandle(g)}class eC{#A;constructor(A){this.#A=A}get directoryHandle(){return this.#A}async get(A){const I=await Ms(this.#A,A.slice(1)).catch(()=>{});if(!I)return;const B=await(await I.getFile()).arrayBuffer();return new Uint8Array(B)}}async function wB(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"group",attrs:!0})}catch{throw new Error(`Failed to open Zarr v2 group at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr v3 group at ${Q}`)}try{return rI(Q,{kind:"group"})}catch{throw new Error(`Failed to open Zarr group at ${Q}`)}}async function ds(Q,A){if(A==="v2")try{return rI.v2(Q,{kind:"array",attrs:!1})}catch{throw new Error(`Failed to open Zarr v2 array at ${Q}`)}if(A==="v3")try{return rI.v3(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr v3 array at ${Q}`)}try{return rI(Q,{kind:"array"})}catch{throw new Error(`Failed to open Zarr array at ${Q}`)}}async function Hs(Q){let A;switch(Q.type){case"fetch":{const g=new hB(Q.url);A=new eI(g);break}case"filesystem":{A=new eI(new eC(Q.directoryHandle),Q.path);break}default:{const g=Q;throw new Error(`Unsupported store type: ${g}`)}}const I=Q.arrayPath?A.resolve(Q.arrayPath):A;return ds(I,Q.zarrVersion)}function qs(Q,A,I){if(Q.store instanceof hB)return{type:"fetch",arrayPath:A,zarrVersion:I,url:Q.store.url.toString()};if(Q.store instanceof eC)return{type:"filesystem",arrayPath:A,zarrVersion:I,directoryHandle:Q.store.directoryHandle,path:Q.path};throw new Error(`Unsupported store type: ${Q.store.constructor.name}`)}function ls(Q,A,I,g){return fs(Q,A,I,g)}function fs(Q,A,I,g){const{targetShape:B,chunkIndex:C,dimIndices:E}=g;let i=1;for(let Z=A.length-1;Z>=0;Z--){if(I[Z]!==i)throw new Error(`Chunk data is not tightly packed, stride=${JSON.stringify(I)}, shape=${JSON.stringify(A)}`);i*=A[Z]}const o={x:A[E.x],y:A[E.y],z:E.z!==void 0?A[E.z]:B.z};if(o.x<B.x||o.y<B.y||o.z<B.z)throw new Error(`Received chunk too small: expected ${JSON.stringify(B)}, got ${JSON.stringify(o)}`);const a=g.cChunkSize?C.c%g.cChunkSize:0,D=g.tChunkSize?C.t%g.tChunkSize:0,s=B.x*B.y*B.z,y=E.c!==void 0?I[E.c]:0,e=E.t!==void 0?I[E.t]:0,Y=D*e+a*y,u=o.x===B.x&&o.y===B.y&&o.z===B.z;if(Y===0&&Q.length===s&&u)return Q;const W=new Q.constructor(s),z=E.z!==void 0?I[E.z]:0,x=I[E.y];let l=0;for(let Z=0;Z<B.z;Z++){const v=Y+Z*z;for(let CA=0;CA<B.y;CA++){const sA=v+CA*x,DA=sA+B.x;W.set(Q.subarray(sA,DA),l),l+=B.x}}return W}const ri=`function xg(B, A) {
|
|
557
557
|
return {
|
|
558
558
|
...B,
|
|
559
559
|
...A,
|
|
@@ -4210,7 +4210,7 @@ return ret;
|
|
|
4210
4210
|
`,ni=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",ri],{type:"text/javascript;charset=utf-8"});function ps(Q){let A;try{if(A=ni&&(self.URL||self.webkitURL).createObjectURL(ni),!A)throw"";const I=new Worker(A,{type:"module",name:Q?.name});return I.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(A)}),I}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(ri),{type:"module",name:Q?.name})}}const us=Math.max(1,navigator.hardwareConcurrency-2);let UI=[],ms=0,Si=0;const Dg=new Map,gQ=new Set;function Ni(Q){const A=UI.find(I=>I.worker===Q);return A||gA.error("ZarrWorker","Worker not found in pool - this should not happen"),A}function xs(Q,A){const{id:I,success:g}=Q.data,B=Dg.get(I);if(!B){gQ.has(I)?gQ.delete(I):gA.warn("ZarrWorker",`Received response for unknown message ID ${I}:`,Q.data);return}Dg.delete(I),B.abortListener&&B.abortSignal&&B.abortSignal.removeEventListener("abort",B.abortListener);const C=Ni(A);C&&C.pendingCount>0?C.pendingCount--:C&&gA.error("ZarrWorker","Received message but no pending tasks - this should not happen"),g&&Q.data.type==="getChunk"?B.resolve(Q.data.data):g||B.reject(new Error(Q.data.error||"Unknown worker error"))}function Ri(Q,A){if(Q instanceof MessageEvent){gA.error("ZarrWorker","Message serialization error occurred - worker remains active");return}gA.error("ZarrWorker","Worker failed - replacing worker and canceling its in-flight messages",Q.message);const I=Ni(A);if(I){const B=UI.indexOf(I);UI.splice(B,1)}const g=I?.workerId;if(g!==void 0)for(const[B,C]of Dg.entries())C.workerId===g&&(C.reject(new Error(`Worker error: ${Q.message}`)),Dg.delete(B));try{const B=ci();UI.push({worker:B,pendingCount:0,workerId:Si++}),gA.debug("ZarrWorker","Replacement worker created successfully")}catch(B){gA.error("ZarrWorker","Failed to create replacement worker",B)}}function ci(){const Q=new ps;return Q.addEventListener("message",A=>xs(A,Q)),Q.addEventListener("error",A=>Ri(A,Q)),Q.addEventListener("messageerror",A=>Ri(A,Q)),Q}function Ts(){if(UI.length===0)throw new Error("Worker pool is not initialized");return UI.sort((Q,A)=>Q.pendingCount-A.pendingCount)[0]}async function Ws(Q,A,I,g){return new Promise((B,C)=>{const E=Ts(),i=ms++,o={resolve:B,reject:C,workerId:E.workerId};if(Dg.set(i,o),g?.signal){const a=()=>{E.worker.postMessage({id:i,type:"cancel"}),Dg.delete(i),gQ.add(i),E.pendingCount--,C(new DOMException("Operation was aborted","AbortError"))};if(g.signal.aborted){a(),gQ.delete(i);return}g.signal.addEventListener("abort",a,{once:!0}),o.abortListener=a,o.abortSignal=g.signal}E.pendingCount++,E.worker.postMessage({id:i,type:"getChunk",arrayParams:Q,index:A,sliceSpec:I})})}function bs(){if(!(UI.length>0))try{for(let Q=0;Q<us;Q++){const A=ci();UI.push({worker:A,pendingCount:0,workerId:Si++})}gA.debug("ZarrWorker",`Initialized worker pool with ${UI.length} workers`)}catch{gA.warn("ZarrWorker","Failed to create workers - clearing pool"),Ps();return}}async function Zs(Q,A,I,g,B){bs();try{return await Ws(A,I,g,B)}catch(C){if(C instanceof DOMException&&C.name==="AbortError")throw C;gA.warn("ZarrWorker","Falling back to main thread",C);const E=await Q.getChunk(I,B);if(!lD(E.data))throw new Error(`Unsupported chunk data type: ${E.data.constructor.name}`);return ls(E.data,E.shape,E.stride,g)}}function Ps(){for(const Q of UI)Q.worker.terminate();UI=[],Dg.clear()}class Vs{metadata_;arrays_;arrayParams_;dimensions_;constructor(A){this.metadata_=A.metadata,this.arrays_=A.arrays,this.arrayParams_=A.arrayParams,this.dimensions_=Os(this.metadata_,this.arrays_)}getSourceDimensionMap(){return this.dimensions_}async loadChunkData(A,I){const g=[];if(g[this.dimensions_.x.index]=A.chunkIndex.x,g[this.dimensions_.y.index]=A.chunkIndex.y,this.dimensions_.z&&(g[this.dimensions_.z.index]=A.chunkIndex.z),this.dimensions_.c){const s=this.dimensions_.c.lods[A.lod];g[this.dimensions_.c.index]=Math.floor(A.chunkIndex.c/s.chunkSize)}if(this.dimensions_.t){const s=this.dimensions_.t.lods[A.lod];g[this.dimensions_.t.index]=Math.floor(A.chunkIndex.t/s.chunkSize)}const B=this.arrays_[A.lod],C=this.arrayParams_[A.lod],E=this.dimensions_.c?.lods[A.lod],i=this.dimensions_.t?.lods[A.lod],o={targetShape:A.shape,chunkIndex:{c:A.chunkIndex.c,t:A.chunkIndex.t},dimIndices:{x:this.dimensions_.x.index,y:this.dimensions_.y.index,z:this.dimensions_.z?.index,c:this.dimensions_.c?.index,t:this.dimensions_.t?.index},cChunkSize:E?.chunkSize,tChunkSize:i?.chunkSize},a=await Zs(B,C,g,o,{signal:I}),D=a.BYTES_PER_ELEMENT;if(!ea(D))throw new Error("Invalid row alignment value. Possible values are 1, 2, 4, or 8");A.rowAlignmentBytes=D,dD(A,a)}}function Os(Q,A){const I=Q.axes.map(s=>s.name),g=Q.axes.length,B=Ui(I,"x"),C=Ui(I,"y"),E=(s,y)=>{const e=[];for(let Y=0;Y<Q.datasets.length;Y++){const u=Q.datasets[Y],H=A[Y],W=u.coordinateTransformations[0].scale,z=u.coordinateTransformations.length===2?u.coordinateTransformations[1].translation:new Array(g).fill(0);e.push({size:H.shape[y],chunkSize:H.chunks[y],scale:W[y],translation:z[y]})}if(Q.axes[y].type==="space"&&Xs(e))for(const Y of e)Y.translation-=.5*Y.scale;return{name:s,index:y,unit:Q.axes[y].unit,lods:e}},i={x:E(I[B],B),y:E(I[C],C),numLods:A.length},o=BQ(I,"z");o!==-1&&(i.z=E(I[o],o));const a=BQ(I,"c");a!==-1&&(i.c=E(I[a],a));const D=BQ(I,"t");return D!==-1&&(i.t=E(I[D],D)),i}function vs(Q,A){return Q.toLowerCase()===A.toLowerCase()}function Ui(Q,A){const I=BQ(Q,A);if(I===-1)throw new Error(`Could not find "${A}" dimension in [${Q.join(", ")}]`);return I}function BQ(Q,A){return Q.findIndex(I=>vs(I,A))}function Xs(Q){if(Q.length<=1)return!1;for(let A=1;A<Q.length;A++){const I=.5*(Q[A].scale-Q[A-1].scale),g=Q[A].translation-Q[A-1].translation;if(Math.abs(g-I)>1e-6)return!1}return!0}var SA;(function(Q){Q.assertEqual=B=>{};function A(B){}Q.assertIs=A;function I(B){throw new Error}Q.assertNever=I,Q.arrayToEnum=B=>{const C={};for(const E of B)C[E]=E;return C},Q.getValidEnumValues=B=>{const C=Q.objectKeys(B).filter(i=>typeof B[B[i]]!="number"),E={};for(const i of C)E[i]=B[i];return Q.objectValues(E)},Q.objectValues=B=>Q.objectKeys(B).map(function(C){return B[C]}),Q.objectKeys=typeof Object.keys=="function"?B=>Object.keys(B):B=>{const C=[];for(const E in B)Object.prototype.hasOwnProperty.call(B,E)&&C.push(E);return C},Q.find=(B,C)=>{for(const E of B)if(C(E))return E},Q.isInteger=typeof Number.isInteger=="function"?B=>Number.isInteger(B):B=>typeof B=="number"&&Number.isFinite(B)&&Math.floor(B)===B;function g(B,C=" | "){return B.map(E=>typeof E=="string"?`'${E}'`:E).join(C)}Q.joinValues=g,Q.jsonStringifyReplacer=(B,C)=>typeof C=="bigint"?C.toString():C})(SA||(SA={}));var ki;(function(Q){Q.mergeShapes=(A,I)=>({...A,...I})})(ki||(ki={}));const $=SA.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ZI=Q=>{switch(typeof Q){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(Q)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(Q)?$.array:Q===null?$.null:Q.then&&typeof Q.then=="function"&&Q.catch&&typeof Q.catch=="function"?$.promise:typeof Map<"u"&&Q instanceof Map?$.map:typeof Set<"u"&&Q instanceof Set?$.set:typeof Date<"u"&&Q instanceof Date?$.date:$.object;default:return $.unknown}},P=SA.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class uI extends Error{get errors(){return this.issues}constructor(A){super(),this.issues=[],this.addIssue=g=>{this.issues=[...this.issues,g]},this.addIssues=(g=[])=>{this.issues=[...this.issues,...g]};const I=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,I):this.__proto__=I,this.name="ZodError",this.issues=A}format(A){const I=A||function(C){return C.message},g={_errors:[]},B=C=>{for(const E of C.issues)if(E.code==="invalid_union")E.unionErrors.map(B);else if(E.code==="invalid_return_type")B(E.returnTypeError);else if(E.code==="invalid_arguments")B(E.argumentsError);else if(E.path.length===0)g._errors.push(I(E));else{let i=g,o=0;for(;o<E.path.length;){const a=E.path[o];o===E.path.length-1?(i[a]=i[a]||{_errors:[]},i[a]._errors.push(I(E))):i[a]=i[a]||{_errors:[]},i=i[a],o++}}};return B(this),g}static assert(A){if(!(A instanceof uI))throw new Error(`Not a ZodError: ${A}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,SA.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(A=I=>I.message){const I={},g=[];for(const B of this.issues)if(B.path.length>0){const C=B.path[0];I[C]=I[C]||[],I[C].push(A(B))}else g.push(A(B));return{formErrors:g,fieldErrors:I}}get formErrors(){return this.flatten()}}uI.create=Q=>new uI(Q);const rC=(Q,A)=>{let I;switch(Q.code){case P.invalid_type:Q.received===$.undefined?I="Required":I=`Expected ${Q.expected}, received ${Q.received}`;break;case P.invalid_literal:I=`Invalid literal value, expected ${JSON.stringify(Q.expected,SA.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:I=`Unrecognized key(s) in object: ${SA.joinValues(Q.keys,", ")}`;break;case P.invalid_union:I="Invalid input";break;case P.invalid_union_discriminator:I=`Invalid discriminator value. Expected ${SA.joinValues(Q.options)}`;break;case P.invalid_enum_value:I=`Invalid enum value. Expected ${SA.joinValues(Q.options)}, received '${Q.received}'`;break;case P.invalid_arguments:I="Invalid function arguments";break;case P.invalid_return_type:I="Invalid function return type";break;case P.invalid_date:I="Invalid date";break;case P.invalid_string:typeof Q.validation=="object"?"includes"in Q.validation?(I=`Invalid input: must include "${Q.validation.includes}"`,typeof Q.validation.position=="number"&&(I=`${I} at one or more positions greater than or equal to ${Q.validation.position}`)):"startsWith"in Q.validation?I=`Invalid input: must start with "${Q.validation.startsWith}"`:"endsWith"in Q.validation?I=`Invalid input: must end with "${Q.validation.endsWith}"`:SA.assertNever(Q.validation):Q.validation!=="regex"?I=`Invalid ${Q.validation}`:I="Invalid";break;case P.too_small:Q.type==="array"?I=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at least":"more than"} ${Q.minimum} element(s)`:Q.type==="string"?I=`String must contain ${Q.exact?"exactly":Q.inclusive?"at least":"over"} ${Q.minimum} character(s)`:Q.type==="number"?I=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`:Q.type==="bigint"?I=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`:Q.type==="date"?I=`Date must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Q.minimum))}`:I="Invalid input";break;case P.too_big:Q.type==="array"?I=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at most":"less than"} ${Q.maximum} element(s)`:Q.type==="string"?I=`String must contain ${Q.exact?"exactly":Q.inclusive?"at most":"under"} ${Q.maximum} character(s)`:Q.type==="number"?I=`Number must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`:Q.type==="bigint"?I=`BigInt must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`:Q.type==="date"?I=`Date must be ${Q.exact?"exactly":Q.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Q.maximum))}`:I="Invalid input";break;case P.custom:I="Invalid input";break;case P.invalid_intersection_types:I="Intersection results could not be merged";break;case P.not_multiple_of:I=`Number must be a multiple of ${Q.multipleOf}`;break;case P.not_finite:I="Number must be finite";break;default:I=A.defaultError,SA.assertNever(Q)}return{message:I}};let js=rC;function zs(){return js}const _s=Q=>{const{data:A,path:I,errorMaps:g,issueData:B}=Q,C=[...I,...B.path||[]],E={...B,path:C};if(B.message!==void 0)return{...B,path:C,message:B.message};let i="";const o=g.filter(a=>!!a).slice().reverse();for(const a of o)i=a(E,{data:A,defaultError:i}).message;return{...B,path:C,message:i}};function j(Q,A){const I=zs(),g=_s({issueData:A,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,I,I===rC?void 0:rC].filter(B=>!!B)});Q.common.issues.push(g)}class tI{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(A,I){const g=[];for(const B of I){if(B.status==="aborted")return oA;B.status==="dirty"&&A.dirty(),g.push(B.value)}return{status:A.value,value:g}}static async mergeObjectAsync(A,I){const g=[];for(const B of I){const C=await B.key,E=await B.value;g.push({key:C,value:E})}return tI.mergeObjectSync(A,g)}static mergeObjectSync(A,I){const g={};for(const B of I){const{key:C,value:E}=B;if(C.status==="aborted"||E.status==="aborted")return oA;C.status==="dirty"&&A.dirty(),E.status==="dirty"&&A.dirty(),C.value!=="__proto__"&&(typeof E.value<"u"||B.alwaysSet)&&(g[C.value]=E.value)}return{status:A.value,value:g}}}const oA=Object.freeze({status:"aborted"}),FB=Q=>({status:"dirty",value:Q}),nI=Q=>({status:"valid",value:Q}),Li=Q=>Q.status==="aborted",Ji=Q=>Q.status==="dirty",Hg=Q=>Q.status==="valid",QQ=Q=>typeof Promise<"u"&&Q instanceof Promise;var AA;(function(Q){Q.errToObj=A=>typeof A=="string"?{message:A}:A||{},Q.toString=A=>typeof A=="string"?A:A?.message})(AA||(AA={}));class PI{constructor(A,I,g,B){this._cachedPath=[],this.parent=A,this.data=I,this._path=g,this._key=B}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Yi=(Q,A)=>{if(Hg(A))return{success:!0,data:A.value};if(!Q.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const I=new uI(Q.common.issues);return this._error=I,this._error}}};function tA(Q){if(!Q)return{};const{errorMap:A,invalid_type_error:I,required_error:g,description:B}=Q;if(A&&(I||g))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return A?{errorMap:A,description:B}:{errorMap:(E,i)=>{const{message:o}=Q;return E.code==="invalid_enum_value"?{message:o??i.defaultError}:typeof i.data>"u"?{message:o??g??i.defaultError}:E.code!=="invalid_type"?{message:i.defaultError}:{message:o??I??i.defaultError}},description:B}}class rA{get description(){return this._def.description}_getType(A){return ZI(A.data)}_getOrReturnCtx(A,I){return I||{common:A.parent.common,data:A.data,parsedType:ZI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}_processInputParams(A){return{status:new tI,ctx:{common:A.parent.common,data:A.data,parsedType:ZI(A.data),schemaErrorMap:this._def.errorMap,path:A.path,parent:A.parent}}}_parseSync(A){const I=this._parse(A);if(QQ(I))throw new Error("Synchronous parse encountered promise.");return I}_parseAsync(A){const I=this._parse(A);return Promise.resolve(I)}parse(A,I){const g=this.safeParse(A,I);if(g.success)return g.data;throw g.error}safeParse(A,I){const g={common:{issues:[],async:I?.async??!1,contextualErrorMap:I?.errorMap},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:ZI(A)},B=this._parseSync({data:A,path:g.path,parent:g});return Yi(g,B)}"~validate"(A){const I={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:ZI(A)};if(!this["~standard"].async)try{const g=this._parseSync({data:A,path:[],parent:I});return Hg(g)?{value:g.value}:{issues:I.common.issues}}catch(g){g?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),I.common={issues:[],async:!0}}return this._parseAsync({data:A,path:[],parent:I}).then(g=>Hg(g)?{value:g.value}:{issues:I.common.issues})}async parseAsync(A,I){const g=await this.safeParseAsync(A,I);if(g.success)return g.data;throw g.error}async safeParseAsync(A,I){const g={common:{issues:[],contextualErrorMap:I?.errorMap,async:!0},path:I?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:A,parsedType:ZI(A)},B=this._parse({data:A,path:g.path,parent:g}),C=await(QQ(B)?B:Promise.resolve(B));return Yi(g,C)}refine(A,I){const g=B=>typeof I=="string"||typeof I>"u"?{message:I}:typeof I=="function"?I(B):I;return this._refinement((B,C)=>{const E=A(B),i=()=>C.addIssue({code:P.custom,...g(B)});return typeof Promise<"u"&&E instanceof Promise?E.then(o=>o?!0:(i(),!1)):E?!0:(i(),!1)})}refinement(A,I){return this._refinement((g,B)=>A(g)?!0:(B.addIssue(typeof I=="function"?I(g,B):I),!1))}_refinement(A){return new pg({schema:this,typeName:aA.ZodEffects,effect:{type:"refinement",refinement:A}})}superRefine(A){return this._refinement(A)}constructor(A){this.spa=this.safeParseAsync,this._def=A,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:I=>this["~validate"](I)}}optional(){return vI.create(this,this._def)}nullable(){return ug.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dI.create(this)}promise(){return oQ.create(this,this._def)}or(A){return EQ.create([this,A],this._def)}and(A){return iQ.create(this,A,this._def)}transform(A){return new pg({...tA(this._def),schema:this,typeName:aA.ZodEffects,effect:{type:"transform",transform:A}})}default(A){const I=typeof A=="function"?A:()=>A;return new UC({...tA(this._def),innerType:this,defaultValue:I,typeName:aA.ZodDefault})}brand(){return new Sh({typeName:aA.ZodBranded,type:this,...tA(this._def)})}catch(A){const I=typeof A=="function"?A:()=>A;return new kC({...tA(this._def),innerType:this,catchValue:I,typeName:aA.ZodCatch})}describe(A){const I=this.constructor;return new I({...this._def,description:A})}pipe(A){return LC.create(this,A)}readonly(){return JC.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const $s=/^c[^\s-]{8,}$/i,Ah=/^[0-9a-z]+$/,Ih=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gh=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Bh=/^[a-z0-9_-]{21}$/i,Qh=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ch=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Eh=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ih="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let nC;const oh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ah=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Dh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sh=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hh=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yh=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ki="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",th=new RegExp(`^${Ki}$`);function Mi(Q){let A="[0-5]\\d";Q.precision?A=`${A}\\.\\d{${Q.precision}}`:Q.precision==null&&(A=`${A}(\\.\\d+)?`);const I=Q.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${A})${I}`}function Gh(Q){return new RegExp(`^${Mi(Q)}$`)}function wh(Q){let A=`${Ki}T${Mi(Q)}`;const I=[];return I.push(Q.local?"Z?":"Z"),Q.offset&&I.push("([+-]\\d{2}:?\\d{2})"),A=`${A}(${I.join("|")})`,new RegExp(`^${A}$`)}function Fh(Q,A){return!!((A==="v4"||!A)&&oh.test(Q)||(A==="v6"||!A)&&Dh.test(Q))}function eh(Q,A){if(!Qh.test(Q))return!1;try{const[I]=Q.split(".");if(!I)return!1;const g=I.replace(/-/g,"+").replace(/_/g,"/").padEnd(I.length+(4-I.length%4)%4,"="),B=JSON.parse(atob(g));return!(typeof B!="object"||B===null||"typ"in B&&B?.typ!=="JWT"||!B.alg||A&&B.alg!==A)}catch{return!1}}function rh(Q,A){return!!((A==="v4"||!A)&&ah.test(Q)||(A==="v6"||!A)&&sh.test(Q))}class VI extends rA{_parse(A){if(this._def.coerce&&(A.data=String(A.data)),this._getType(A)!==$.string){const C=this._getOrReturnCtx(A);return j(C,{code:P.invalid_type,expected:$.string,received:C.parsedType}),oA}const g=new tI;let B;for(const C of this._def.checks)if(C.kind==="min")A.data.length<C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:P.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),g.dirty());else if(C.kind==="max")A.data.length>C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:P.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!1,message:C.message}),g.dirty());else if(C.kind==="length"){const E=A.data.length>C.value,i=A.data.length<C.value;(E||i)&&(B=this._getOrReturnCtx(A,B),E?j(B,{code:P.too_big,maximum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}):i&&j(B,{code:P.too_small,minimum:C.value,type:"string",inclusive:!0,exact:!0,message:C.message}),g.dirty())}else if(C.kind==="email")Eh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"email",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="emoji")nC||(nC=new RegExp(ih,"u")),nC.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"emoji",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="uuid")gh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"uuid",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="nanoid")Bh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"nanoid",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="cuid")$s.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cuid",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="cuid2")Ah.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cuid2",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="ulid")Ih.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"ulid",code:P.invalid_string,message:C.message}),g.dirty());else if(C.kind==="url")try{new URL(A.data)}catch{B=this._getOrReturnCtx(A,B),j(B,{validation:"url",code:P.invalid_string,message:C.message}),g.dirty()}else C.kind==="regex"?(C.regex.lastIndex=0,C.regex.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"regex",code:P.invalid_string,message:C.message}),g.dirty())):C.kind==="trim"?A.data=A.data.trim():C.kind==="includes"?A.data.includes(C.value,C.position)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:{includes:C.value,position:C.position},message:C.message}),g.dirty()):C.kind==="toLowerCase"?A.data=A.data.toLowerCase():C.kind==="toUpperCase"?A.data=A.data.toUpperCase():C.kind==="startsWith"?A.data.startsWith(C.value)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:{startsWith:C.value},message:C.message}),g.dirty()):C.kind==="endsWith"?A.data.endsWith(C.value)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:{endsWith:C.value},message:C.message}),g.dirty()):C.kind==="datetime"?wh(C).test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:"datetime",message:C.message}),g.dirty()):C.kind==="date"?th.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:"date",message:C.message}),g.dirty()):C.kind==="time"?Gh(C).test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{code:P.invalid_string,validation:"time",message:C.message}),g.dirty()):C.kind==="duration"?Ch.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"duration",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="ip"?Fh(A.data,C.version)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"ip",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="jwt"?eh(A.data,C.alg)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"jwt",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="cidr"?rh(A.data,C.version)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"cidr",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="base64"?hh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"base64",code:P.invalid_string,message:C.message}),g.dirty()):C.kind==="base64url"?yh.test(A.data)||(B=this._getOrReturnCtx(A,B),j(B,{validation:"base64url",code:P.invalid_string,message:C.message}),g.dirty()):SA.assertNever(C);return{status:g.value,value:A.data}}_regex(A,I,g){return this.refinement(B=>A.test(B),{validation:I,code:P.invalid_string,...AA.errToObj(g)})}_addCheck(A){return new VI({...this._def,checks:[...this._def.checks,A]})}email(A){return this._addCheck({kind:"email",...AA.errToObj(A)})}url(A){return this._addCheck({kind:"url",...AA.errToObj(A)})}emoji(A){return this._addCheck({kind:"emoji",...AA.errToObj(A)})}uuid(A){return this._addCheck({kind:"uuid",...AA.errToObj(A)})}nanoid(A){return this._addCheck({kind:"nanoid",...AA.errToObj(A)})}cuid(A){return this._addCheck({kind:"cuid",...AA.errToObj(A)})}cuid2(A){return this._addCheck({kind:"cuid2",...AA.errToObj(A)})}ulid(A){return this._addCheck({kind:"ulid",...AA.errToObj(A)})}base64(A){return this._addCheck({kind:"base64",...AA.errToObj(A)})}base64url(A){return this._addCheck({kind:"base64url",...AA.errToObj(A)})}jwt(A){return this._addCheck({kind:"jwt",...AA.errToObj(A)})}ip(A){return this._addCheck({kind:"ip",...AA.errToObj(A)})}cidr(A){return this._addCheck({kind:"cidr",...AA.errToObj(A)})}datetime(A){return typeof A=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:A}):this._addCheck({kind:"datetime",precision:typeof A?.precision>"u"?null:A?.precision,offset:A?.offset??!1,local:A?.local??!1,...AA.errToObj(A?.message)})}date(A){return this._addCheck({kind:"date",message:A})}time(A){return typeof A=="string"?this._addCheck({kind:"time",precision:null,message:A}):this._addCheck({kind:"time",precision:typeof A?.precision>"u"?null:A?.precision,...AA.errToObj(A?.message)})}duration(A){return this._addCheck({kind:"duration",...AA.errToObj(A)})}regex(A,I){return this._addCheck({kind:"regex",regex:A,...AA.errToObj(I)})}includes(A,I){return this._addCheck({kind:"includes",value:A,position:I?.position,...AA.errToObj(I?.message)})}startsWith(A,I){return this._addCheck({kind:"startsWith",value:A,...AA.errToObj(I)})}endsWith(A,I){return this._addCheck({kind:"endsWith",value:A,...AA.errToObj(I)})}min(A,I){return this._addCheck({kind:"min",value:A,...AA.errToObj(I)})}max(A,I){return this._addCheck({kind:"max",value:A,...AA.errToObj(I)})}length(A,I){return this._addCheck({kind:"length",value:A,...AA.errToObj(I)})}nonempty(A){return this.min(1,AA.errToObj(A))}trim(){return new VI({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new VI({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new VI({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(A=>A.kind==="datetime")}get isDate(){return!!this._def.checks.find(A=>A.kind==="date")}get isTime(){return!!this._def.checks.find(A=>A.kind==="time")}get isDuration(){return!!this._def.checks.find(A=>A.kind==="duration")}get isEmail(){return!!this._def.checks.find(A=>A.kind==="email")}get isURL(){return!!this._def.checks.find(A=>A.kind==="url")}get isEmoji(){return!!this._def.checks.find(A=>A.kind==="emoji")}get isUUID(){return!!this._def.checks.find(A=>A.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(A=>A.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(A=>A.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(A=>A.kind==="cuid2")}get isULID(){return!!this._def.checks.find(A=>A.kind==="ulid")}get isIP(){return!!this._def.checks.find(A=>A.kind==="ip")}get isCIDR(){return!!this._def.checks.find(A=>A.kind==="cidr")}get isBase64(){return!!this._def.checks.find(A=>A.kind==="base64")}get isBase64url(){return!!this._def.checks.find(A=>A.kind==="base64url")}get minLength(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxLength(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}}VI.create=Q=>new VI({checks:[],typeName:aA.ZodString,coerce:Q?.coerce??!1,...tA(Q)});function nh(Q,A){const I=(Q.toString().split(".")[1]||"").length,g=(A.toString().split(".")[1]||"").length,B=I>g?I:g,C=Number.parseInt(Q.toFixed(B).replace(".","")),E=Number.parseInt(A.toFixed(B).replace(".",""));return C%E/10**B}class qg extends rA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(A){if(this._def.coerce&&(A.data=Number(A.data)),this._getType(A)!==$.number){const C=this._getOrReturnCtx(A);return j(C,{code:P.invalid_type,expected:$.number,received:C.parsedType}),oA}let g;const B=new tI;for(const C of this._def.checks)C.kind==="int"?SA.isInteger(A.data)||(g=this._getOrReturnCtx(A,g),j(g,{code:P.invalid_type,expected:"integer",received:"float",message:C.message}),B.dirty()):C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.too_small,minimum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),B.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.too_big,maximum:C.value,type:"number",inclusive:C.inclusive,exact:!1,message:C.message}),B.dirty()):C.kind==="multipleOf"?nh(A.data,C.value)!==0&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.not_multiple_of,multipleOf:C.value,message:C.message}),B.dirty()):C.kind==="finite"?Number.isFinite(A.data)||(g=this._getOrReturnCtx(A,g),j(g,{code:P.not_finite,message:C.message}),B.dirty()):SA.assertNever(C);return{status:B.value,value:A.data}}gte(A,I){return this.setLimit("min",A,!0,AA.toString(I))}gt(A,I){return this.setLimit("min",A,!1,AA.toString(I))}lte(A,I){return this.setLimit("max",A,!0,AA.toString(I))}lt(A,I){return this.setLimit("max",A,!1,AA.toString(I))}setLimit(A,I,g,B){return new qg({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:g,message:AA.toString(B)}]})}_addCheck(A){return new qg({...this._def,checks:[...this._def.checks,A]})}int(A){return this._addCheck({kind:"int",message:AA.toString(A)})}positive(A){return this._addCheck({kind:"min",value:0,inclusive:!1,message:AA.toString(A)})}negative(A){return this._addCheck({kind:"max",value:0,inclusive:!1,message:AA.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:0,inclusive:!0,message:AA.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:0,inclusive:!0,message:AA.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:AA.toString(I)})}finite(A){return this._addCheck({kind:"finite",message:AA.toString(A)})}safe(A){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:AA.toString(A)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:AA.toString(A)})}get minValue(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxValue(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}get isInt(){return!!this._def.checks.find(A=>A.kind==="int"||A.kind==="multipleOf"&&SA.isInteger(A.value))}get isFinite(){let A=null,I=null;for(const g of this._def.checks){if(g.kind==="finite"||g.kind==="int"||g.kind==="multipleOf")return!0;g.kind==="min"?(I===null||g.value>I)&&(I=g.value):g.kind==="max"&&(A===null||g.value<A)&&(A=g.value)}return Number.isFinite(I)&&Number.isFinite(A)}}qg.create=Q=>new qg({checks:[],typeName:aA.ZodNumber,coerce:Q?.coerce||!1,...tA(Q)});class eB extends rA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(A){if(this._def.coerce)try{A.data=BigInt(A.data)}catch{return this._getInvalidInput(A)}if(this._getType(A)!==$.bigint)return this._getInvalidInput(A);let g;const B=new tI;for(const C of this._def.checks)C.kind==="min"?(C.inclusive?A.data<C.value:A.data<=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.too_small,type:"bigint",minimum:C.value,inclusive:C.inclusive,message:C.message}),B.dirty()):C.kind==="max"?(C.inclusive?A.data>C.value:A.data>=C.value)&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.too_big,type:"bigint",maximum:C.value,inclusive:C.inclusive,message:C.message}),B.dirty()):C.kind==="multipleOf"?A.data%C.value!==BigInt(0)&&(g=this._getOrReturnCtx(A,g),j(g,{code:P.not_multiple_of,multipleOf:C.value,message:C.message}),B.dirty()):SA.assertNever(C);return{status:B.value,value:A.data}}_getInvalidInput(A){const I=this._getOrReturnCtx(A);return j(I,{code:P.invalid_type,expected:$.bigint,received:I.parsedType}),oA}gte(A,I){return this.setLimit("min",A,!0,AA.toString(I))}gt(A,I){return this.setLimit("min",A,!1,AA.toString(I))}lte(A,I){return this.setLimit("max",A,!0,AA.toString(I))}lt(A,I){return this.setLimit("max",A,!1,AA.toString(I))}setLimit(A,I,g,B){return new eB({...this._def,checks:[...this._def.checks,{kind:A,value:I,inclusive:g,message:AA.toString(B)}]})}_addCheck(A){return new eB({...this._def,checks:[...this._def.checks,A]})}positive(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:AA.toString(A)})}negative(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:AA.toString(A)})}nonpositive(A){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:AA.toString(A)})}nonnegative(A){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:AA.toString(A)})}multipleOf(A,I){return this._addCheck({kind:"multipleOf",value:A,message:AA.toString(I)})}get minValue(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A}get maxValue(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A}}eB.create=Q=>new eB({checks:[],typeName:aA.ZodBigInt,coerce:Q?.coerce??!1,...tA(Q)});class SC extends rA{_parse(A){if(this._def.coerce&&(A.data=!!A.data),this._getType(A)!==$.boolean){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.boolean,received:g.parsedType}),oA}return nI(A.data)}}SC.create=Q=>new SC({typeName:aA.ZodBoolean,coerce:Q?.coerce||!1,...tA(Q)});class CQ extends rA{_parse(A){if(this._def.coerce&&(A.data=new Date(A.data)),this._getType(A)!==$.date){const C=this._getOrReturnCtx(A);return j(C,{code:P.invalid_type,expected:$.date,received:C.parsedType}),oA}if(Number.isNaN(A.data.getTime())){const C=this._getOrReturnCtx(A);return j(C,{code:P.invalid_date}),oA}const g=new tI;let B;for(const C of this._def.checks)C.kind==="min"?A.data.getTime()<C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:P.too_small,message:C.message,inclusive:!0,exact:!1,minimum:C.value,type:"date"}),g.dirty()):C.kind==="max"?A.data.getTime()>C.value&&(B=this._getOrReturnCtx(A,B),j(B,{code:P.too_big,message:C.message,inclusive:!0,exact:!1,maximum:C.value,type:"date"}),g.dirty()):SA.assertNever(C);return{status:g.value,value:new Date(A.data.getTime())}}_addCheck(A){return new CQ({...this._def,checks:[...this._def.checks,A]})}min(A,I){return this._addCheck({kind:"min",value:A.getTime(),message:AA.toString(I)})}max(A,I){return this._addCheck({kind:"max",value:A.getTime(),message:AA.toString(I)})}get minDate(){let A=null;for(const I of this._def.checks)I.kind==="min"&&(A===null||I.value>A)&&(A=I.value);return A!=null?new Date(A):null}get maxDate(){let A=null;for(const I of this._def.checks)I.kind==="max"&&(A===null||I.value<A)&&(A=I.value);return A!=null?new Date(A):null}}CQ.create=Q=>new CQ({checks:[],coerce:Q?.coerce||!1,typeName:aA.ZodDate,...tA(Q)});class di extends rA{_parse(A){if(this._getType(A)!==$.symbol){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.symbol,received:g.parsedType}),oA}return nI(A.data)}}di.create=Q=>new di({typeName:aA.ZodSymbol,...tA(Q)});class Hi extends rA{_parse(A){if(this._getType(A)!==$.undefined){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.undefined,received:g.parsedType}),oA}return nI(A.data)}}Hi.create=Q=>new Hi({typeName:aA.ZodUndefined,...tA(Q)});class qi extends rA{_parse(A){if(this._getType(A)!==$.null){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.null,received:g.parsedType}),oA}return nI(A.data)}}qi.create=Q=>new qi({typeName:aA.ZodNull,...tA(Q)});class NC extends rA{constructor(){super(...arguments),this._any=!0}_parse(A){return nI(A.data)}}NC.create=Q=>new NC({typeName:aA.ZodAny,...tA(Q)});class li extends rA{constructor(){super(...arguments),this._unknown=!0}_parse(A){return nI(A.data)}}li.create=Q=>new li({typeName:aA.ZodUnknown,...tA(Q)});class OI extends rA{_parse(A){const I=this._getOrReturnCtx(A);return j(I,{code:P.invalid_type,expected:$.never,received:I.parsedType}),oA}}OI.create=Q=>new OI({typeName:aA.ZodNever,...tA(Q)});class fi extends rA{_parse(A){if(this._getType(A)!==$.undefined){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.void,received:g.parsedType}),oA}return nI(A.data)}}fi.create=Q=>new fi({typeName:aA.ZodVoid,...tA(Q)});class dI extends rA{_parse(A){const{ctx:I,status:g}=this._processInputParams(A),B=this._def;if(I.parsedType!==$.array)return j(I,{code:P.invalid_type,expected:$.array,received:I.parsedType}),oA;if(B.exactLength!==null){const E=I.data.length>B.exactLength.value,i=I.data.length<B.exactLength.value;(E||i)&&(j(I,{code:E?P.too_big:P.too_small,minimum:i?B.exactLength.value:void 0,maximum:E?B.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:B.exactLength.message}),g.dirty())}if(B.minLength!==null&&I.data.length<B.minLength.value&&(j(I,{code:P.too_small,minimum:B.minLength.value,type:"array",inclusive:!0,exact:!1,message:B.minLength.message}),g.dirty()),B.maxLength!==null&&I.data.length>B.maxLength.value&&(j(I,{code:P.too_big,maximum:B.maxLength.value,type:"array",inclusive:!0,exact:!1,message:B.maxLength.message}),g.dirty()),I.common.async)return Promise.all([...I.data].map((E,i)=>B.type._parseAsync(new PI(I,E,I.path,i)))).then(E=>tI.mergeArray(g,E));const C=[...I.data].map((E,i)=>B.type._parseSync(new PI(I,E,I.path,i)));return tI.mergeArray(g,C)}get element(){return this._def.type}min(A,I){return new dI({...this._def,minLength:{value:A,message:AA.toString(I)}})}max(A,I){return new dI({...this._def,maxLength:{value:A,message:AA.toString(I)}})}length(A,I){return new dI({...this._def,exactLength:{value:A,message:AA.toString(I)}})}nonempty(A){return this.min(1,A)}}dI.create=(Q,A)=>new dI({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:aA.ZodArray,...tA(A)});function lg(Q){if(Q instanceof bA){const A={};for(const I in Q.shape){const g=Q.shape[I];A[I]=vI.create(lg(g))}return new bA({...Q._def,shape:()=>A})}else return Q instanceof dI?new dI({...Q._def,type:lg(Q.element)}):Q instanceof vI?vI.create(lg(Q.unwrap())):Q instanceof ug?ug.create(lg(Q.unwrap())):Q instanceof sg?sg.create(Q.items.map(A=>lg(A))):Q}class bA extends rA{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const A=this._def.shape(),I=SA.objectKeys(A);return this._cached={shape:A,keys:I},this._cached}_parse(A){if(this._getType(A)!==$.object){const a=this._getOrReturnCtx(A);return j(a,{code:P.invalid_type,expected:$.object,received:a.parsedType}),oA}const{status:g,ctx:B}=this._processInputParams(A),{shape:C,keys:E}=this._getCached(),i=[];if(!(this._def.catchall instanceof OI&&this._def.unknownKeys==="strip"))for(const a in B.data)E.includes(a)||i.push(a);const o=[];for(const a of E){const D=C[a],s=B.data[a];o.push({key:{status:"valid",value:a},value:D._parse(new PI(B,s,B.path,a)),alwaysSet:a in B.data})}if(this._def.catchall instanceof OI){const a=this._def.unknownKeys;if(a==="passthrough")for(const D of i)o.push({key:{status:"valid",value:D},value:{status:"valid",value:B.data[D]}});else if(a==="strict")i.length>0&&(j(B,{code:P.unrecognized_keys,keys:i}),g.dirty());else if(a!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const a=this._def.catchall;for(const D of i){const s=B.data[D];o.push({key:{status:"valid",value:D},value:a._parse(new PI(B,s,B.path,D)),alwaysSet:D in B.data})}}return B.common.async?Promise.resolve().then(async()=>{const a=[];for(const D of o){const s=await D.key,y=await D.value;a.push({key:s,value:y,alwaysSet:D.alwaysSet})}return a}).then(a=>tI.mergeObjectSync(g,a)):tI.mergeObjectSync(g,o)}get shape(){return this._def.shape()}strict(A){return AA.errToObj,new bA({...this._def,unknownKeys:"strict",...A!==void 0?{errorMap:(I,g)=>{const B=this._def.errorMap?.(I,g).message??g.defaultError;return I.code==="unrecognized_keys"?{message:AA.errToObj(A).message??B}:{message:B}}}:{}})}strip(){return new bA({...this._def,unknownKeys:"strip"})}passthrough(){return new bA({...this._def,unknownKeys:"passthrough"})}extend(A){return new bA({...this._def,shape:()=>({...this._def.shape(),...A})})}merge(A){return new bA({unknownKeys:A._def.unknownKeys,catchall:A._def.catchall,shape:()=>({...this._def.shape(),...A._def.shape()}),typeName:aA.ZodObject})}setKey(A,I){return this.augment({[A]:I})}catchall(A){return new bA({...this._def,catchall:A})}pick(A){const I={};for(const g of SA.objectKeys(A))A[g]&&this.shape[g]&&(I[g]=this.shape[g]);return new bA({...this._def,shape:()=>I})}omit(A){const I={};for(const g of SA.objectKeys(this.shape))A[g]||(I[g]=this.shape[g]);return new bA({...this._def,shape:()=>I})}deepPartial(){return lg(this)}partial(A){const I={};for(const g of SA.objectKeys(this.shape)){const B=this.shape[g];A&&!A[g]?I[g]=B:I[g]=B.optional()}return new bA({...this._def,shape:()=>I})}required(A){const I={};for(const g of SA.objectKeys(this.shape))if(A&&!A[g])I[g]=this.shape[g];else{let C=this.shape[g];for(;C instanceof vI;)C=C._def.innerType;I[g]=C}return new bA({...this._def,shape:()=>I})}keyof(){return mi(SA.objectKeys(this.shape))}}bA.create=(Q,A)=>new bA({shape:()=>Q,unknownKeys:"strip",catchall:OI.create(),typeName:aA.ZodObject,...tA(A)}),bA.strictCreate=(Q,A)=>new bA({shape:()=>Q,unknownKeys:"strict",catchall:OI.create(),typeName:aA.ZodObject,...tA(A)}),bA.lazycreate=(Q,A)=>new bA({shape:Q,unknownKeys:"strip",catchall:OI.create(),typeName:aA.ZodObject,...tA(A)});class EQ extends rA{_parse(A){const{ctx:I}=this._processInputParams(A),g=this._def.options;function B(C){for(const i of C)if(i.result.status==="valid")return i.result;for(const i of C)if(i.result.status==="dirty")return I.common.issues.push(...i.ctx.common.issues),i.result;const E=C.map(i=>new uI(i.ctx.common.issues));return j(I,{code:P.invalid_union,unionErrors:E}),oA}if(I.common.async)return Promise.all(g.map(async C=>{const E={...I,common:{...I.common,issues:[]},parent:null};return{result:await C._parseAsync({data:I.data,path:I.path,parent:E}),ctx:E}})).then(B);{let C;const E=[];for(const o of g){const a={...I,common:{...I.common,issues:[]},parent:null},D=o._parseSync({data:I.data,path:I.path,parent:a});if(D.status==="valid")return D;D.status==="dirty"&&!C&&(C={result:D,ctx:a}),a.common.issues.length&&E.push(a.common.issues)}if(C)return I.common.issues.push(...C.ctx.common.issues),C.result;const i=E.map(o=>new uI(o));return j(I,{code:P.invalid_union,unionErrors:i}),oA}}get options(){return this._def.options}}EQ.create=(Q,A)=>new EQ({options:Q,typeName:aA.ZodUnion,...tA(A)});function RC(Q,A){const I=ZI(Q),g=ZI(A);if(Q===A)return{valid:!0,data:Q};if(I===$.object&&g===$.object){const B=SA.objectKeys(A),C=SA.objectKeys(Q).filter(i=>B.indexOf(i)!==-1),E={...Q,...A};for(const i of C){const o=RC(Q[i],A[i]);if(!o.valid)return{valid:!1};E[i]=o.data}return{valid:!0,data:E}}else if(I===$.array&&g===$.array){if(Q.length!==A.length)return{valid:!1};const B=[];for(let C=0;C<Q.length;C++){const E=Q[C],i=A[C],o=RC(E,i);if(!o.valid)return{valid:!1};B.push(o.data)}return{valid:!0,data:B}}else return I===$.date&&g===$.date&&+Q==+A?{valid:!0,data:Q}:{valid:!1}}class iQ extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A),B=(C,E)=>{if(Li(C)||Li(E))return oA;const i=RC(C.value,E.value);return i.valid?((Ji(C)||Ji(E))&&I.dirty(),{status:I.value,value:i.data}):(j(g,{code:P.invalid_intersection_types}),oA)};return g.common.async?Promise.all([this._def.left._parseAsync({data:g.data,path:g.path,parent:g}),this._def.right._parseAsync({data:g.data,path:g.path,parent:g})]).then(([C,E])=>B(C,E)):B(this._def.left._parseSync({data:g.data,path:g.path,parent:g}),this._def.right._parseSync({data:g.data,path:g.path,parent:g}))}}iQ.create=(Q,A,I)=>new iQ({left:Q,right:A,typeName:aA.ZodIntersection,...tA(I)});class sg extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.array)return j(g,{code:P.invalid_type,expected:$.array,received:g.parsedType}),oA;if(g.data.length<this._def.items.length)return j(g,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),oA;!this._def.rest&&g.data.length>this._def.items.length&&(j(g,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I.dirty());const C=[...g.data].map((E,i)=>{const o=this._def.items[i]||this._def.rest;return o?o._parse(new PI(g,E,g.path,i)):null}).filter(E=>!!E);return g.common.async?Promise.all(C).then(E=>tI.mergeArray(I,E)):tI.mergeArray(I,C)}get items(){return this._def.items}rest(A){return new sg({...this._def,rest:A})}}sg.create=(Q,A)=>{if(!Array.isArray(Q))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new sg({items:Q,typeName:aA.ZodTuple,rest:null,...tA(A)})};class pi extends rA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.map)return j(g,{code:P.invalid_type,expected:$.map,received:g.parsedType}),oA;const B=this._def.keyType,C=this._def.valueType,E=[...g.data.entries()].map(([i,o],a)=>({key:B._parse(new PI(g,i,g.path,[a,"key"])),value:C._parse(new PI(g,o,g.path,[a,"value"]))}));if(g.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const o of E){const a=await o.key,D=await o.value;if(a.status==="aborted"||D.status==="aborted")return oA;(a.status==="dirty"||D.status==="dirty")&&I.dirty(),i.set(a.value,D.value)}return{status:I.value,value:i}})}else{const i=new Map;for(const o of E){const a=o.key,D=o.value;if(a.status==="aborted"||D.status==="aborted")return oA;(a.status==="dirty"||D.status==="dirty")&&I.dirty(),i.set(a.value,D.value)}return{status:I.value,value:i}}}}pi.create=(Q,A,I)=>new pi({valueType:A,keyType:Q,typeName:aA.ZodMap,...tA(I)});class rB extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.parsedType!==$.set)return j(g,{code:P.invalid_type,expected:$.set,received:g.parsedType}),oA;const B=this._def;B.minSize!==null&&g.data.size<B.minSize.value&&(j(g,{code:P.too_small,minimum:B.minSize.value,type:"set",inclusive:!0,exact:!1,message:B.minSize.message}),I.dirty()),B.maxSize!==null&&g.data.size>B.maxSize.value&&(j(g,{code:P.too_big,maximum:B.maxSize.value,type:"set",inclusive:!0,exact:!1,message:B.maxSize.message}),I.dirty());const C=this._def.valueType;function E(o){const a=new Set;for(const D of o){if(D.status==="aborted")return oA;D.status==="dirty"&&I.dirty(),a.add(D.value)}return{status:I.value,value:a}}const i=[...g.data.values()].map((o,a)=>C._parse(new PI(g,o,g.path,a)));return g.common.async?Promise.all(i).then(o=>E(o)):E(i)}min(A,I){return new rB({...this._def,minSize:{value:A,message:AA.toString(I)}})}max(A,I){return new rB({...this._def,maxSize:{value:A,message:AA.toString(I)}})}size(A,I){return this.min(A,I).max(A,I)}nonempty(A){return this.min(1,A)}}rB.create=(Q,A)=>new rB({valueType:Q,minSize:null,maxSize:null,typeName:aA.ZodSet,...tA(A)});class ui extends rA{get schema(){return this._def.getter()}_parse(A){const{ctx:I}=this._processInputParams(A);return this._def.getter()._parse({data:I.data,path:I.path,parent:I})}}ui.create=(Q,A)=>new ui({getter:Q,typeName:aA.ZodLazy,...tA(A)});class cC extends rA{_parse(A){if(A.data!==this._def.value){const I=this._getOrReturnCtx(A);return j(I,{received:I.data,code:P.invalid_literal,expected:this._def.value}),oA}return{status:"valid",value:A.data}}get value(){return this._def.value}}cC.create=(Q,A)=>new cC({value:Q,typeName:aA.ZodLiteral,...tA(A)});function mi(Q,A){return new fg({values:Q,typeName:aA.ZodEnum,...tA(A)})}class fg extends rA{_parse(A){if(typeof A.data!="string"){const I=this._getOrReturnCtx(A),g=this._def.values;return j(I,{expected:SA.joinValues(g),received:I.parsedType,code:P.invalid_type}),oA}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(A.data)){const I=this._getOrReturnCtx(A),g=this._def.values;return j(I,{received:I.data,code:P.invalid_enum_value,options:g}),oA}return nI(A.data)}get options(){return this._def.values}get enum(){const A={};for(const I of this._def.values)A[I]=I;return A}get Values(){const A={};for(const I of this._def.values)A[I]=I;return A}get Enum(){const A={};for(const I of this._def.values)A[I]=I;return A}extract(A,I=this._def){return fg.create(A,{...this._def,...I})}exclude(A,I=this._def){return fg.create(this.options.filter(g=>!A.includes(g)),{...this._def,...I})}}fg.create=mi;class xi extends rA{_parse(A){const I=SA.getValidEnumValues(this._def.values),g=this._getOrReturnCtx(A);if(g.parsedType!==$.string&&g.parsedType!==$.number){const B=SA.objectValues(I);return j(g,{expected:SA.joinValues(B),received:g.parsedType,code:P.invalid_type}),oA}if(this._cache||(this._cache=new Set(SA.getValidEnumValues(this._def.values))),!this._cache.has(A.data)){const B=SA.objectValues(I);return j(g,{received:g.data,code:P.invalid_enum_value,options:B}),oA}return nI(A.data)}get enum(){return this._def.values}}xi.create=(Q,A)=>new xi({values:Q,typeName:aA.ZodNativeEnum,...tA(A)});class oQ extends rA{unwrap(){return this._def.type}_parse(A){const{ctx:I}=this._processInputParams(A);if(I.parsedType!==$.promise&&I.common.async===!1)return j(I,{code:P.invalid_type,expected:$.promise,received:I.parsedType}),oA;const g=I.parsedType===$.promise?I.data:Promise.resolve(I.data);return nI(g.then(B=>this._def.type.parseAsync(B,{path:I.path,errorMap:I.common.contextualErrorMap})))}}oQ.create=(Q,A)=>new oQ({type:Q,typeName:aA.ZodPromise,...tA(A)});class pg extends rA{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===aA.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(A){const{status:I,ctx:g}=this._processInputParams(A),B=this._def.effect||null,C={addIssue:E=>{j(g,E),E.fatal?I.abort():I.dirty()},get path(){return g.path}};if(C.addIssue=C.addIssue.bind(C),B.type==="preprocess"){const E=B.transform(g.data,C);if(g.common.async)return Promise.resolve(E).then(async i=>{if(I.value==="aborted")return oA;const o=await this._def.schema._parseAsync({data:i,path:g.path,parent:g});return o.status==="aborted"?oA:o.status==="dirty"||I.value==="dirty"?FB(o.value):o});{if(I.value==="aborted")return oA;const i=this._def.schema._parseSync({data:E,path:g.path,parent:g});return i.status==="aborted"?oA:i.status==="dirty"||I.value==="dirty"?FB(i.value):i}}if(B.type==="refinement"){const E=i=>{const o=B.refinement(i,C);if(g.common.async)return Promise.resolve(o);if(o instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(g.common.async===!1){const i=this._def.schema._parseSync({data:g.data,path:g.path,parent:g});return i.status==="aborted"?oA:(i.status==="dirty"&&I.dirty(),E(i.value),{status:I.value,value:i.value})}else return this._def.schema._parseAsync({data:g.data,path:g.path,parent:g}).then(i=>i.status==="aborted"?oA:(i.status==="dirty"&&I.dirty(),E(i.value).then(()=>({status:I.value,value:i.value}))))}if(B.type==="transform")if(g.common.async===!1){const E=this._def.schema._parseSync({data:g.data,path:g.path,parent:g});if(!Hg(E))return oA;const i=B.transform(E.value,C);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:I.value,value:i}}else return this._def.schema._parseAsync({data:g.data,path:g.path,parent:g}).then(E=>Hg(E)?Promise.resolve(B.transform(E.value,C)).then(i=>({status:I.value,value:i})):oA);SA.assertNever(B)}}pg.create=(Q,A,I)=>new pg({schema:Q,typeName:aA.ZodEffects,effect:A,...tA(I)}),pg.createWithPreprocess=(Q,A,I)=>new pg({schema:A,effect:{type:"preprocess",transform:Q},typeName:aA.ZodEffects,...tA(I)});class vI extends rA{_parse(A){return this._getType(A)===$.undefined?nI(void 0):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}vI.create=(Q,A)=>new vI({innerType:Q,typeName:aA.ZodOptional,...tA(A)});class ug extends rA{_parse(A){return this._getType(A)===$.null?nI(null):this._def.innerType._parse(A)}unwrap(){return this._def.innerType}}ug.create=(Q,A)=>new ug({innerType:Q,typeName:aA.ZodNullable,...tA(A)});class UC extends rA{_parse(A){const{ctx:I}=this._processInputParams(A);let g=I.data;return I.parsedType===$.undefined&&(g=this._def.defaultValue()),this._def.innerType._parse({data:g,path:I.path,parent:I})}removeDefault(){return this._def.innerType}}UC.create=(Q,A)=>new UC({innerType:Q,typeName:aA.ZodDefault,defaultValue:typeof A.default=="function"?A.default:()=>A.default,...tA(A)});class kC extends rA{_parse(A){const{ctx:I}=this._processInputParams(A),g={...I,common:{...I.common,issues:[]}},B=this._def.innerType._parse({data:g.data,path:g.path,parent:{...g}});return QQ(B)?B.then(C=>({status:"valid",value:C.status==="valid"?C.value:this._def.catchValue({get error(){return new uI(g.common.issues)},input:g.data})})):{status:"valid",value:B.status==="valid"?B.value:this._def.catchValue({get error(){return new uI(g.common.issues)},input:g.data})}}removeCatch(){return this._def.innerType}}kC.create=(Q,A)=>new kC({innerType:Q,typeName:aA.ZodCatch,catchValue:typeof A.catch=="function"?A.catch:()=>A.catch,...tA(A)});class Ti extends rA{_parse(A){if(this._getType(A)!==$.nan){const g=this._getOrReturnCtx(A);return j(g,{code:P.invalid_type,expected:$.nan,received:g.parsedType}),oA}return{status:"valid",value:A.data}}}Ti.create=Q=>new Ti({typeName:aA.ZodNaN,...tA(Q)});class Sh extends rA{_parse(A){const{ctx:I}=this._processInputParams(A),g=I.data;return this._def.type._parse({data:g,path:I.path,parent:I})}unwrap(){return this._def.type}}class LC extends rA{_parse(A){const{status:I,ctx:g}=this._processInputParams(A);if(g.common.async)return(async()=>{const C=await this._def.in._parseAsync({data:g.data,path:g.path,parent:g});return C.status==="aborted"?oA:C.status==="dirty"?(I.dirty(),FB(C.value)):this._def.out._parseAsync({data:C.value,path:g.path,parent:g})})();{const B=this._def.in._parseSync({data:g.data,path:g.path,parent:g});return B.status==="aborted"?oA:B.status==="dirty"?(I.dirty(),{status:"dirty",value:B.value}):this._def.out._parseSync({data:B.value,path:g.path,parent:g})}}static create(A,I){return new LC({in:A,out:I,typeName:aA.ZodPipeline})}}class JC extends rA{_parse(A){const I=this._def.innerType._parse(A),g=B=>(Hg(B)&&(B.value=Object.freeze(B.value)),B);return QQ(I)?I.then(B=>g(B)):g(I)}unwrap(){return this._def.innerType}}JC.create=(Q,A)=>new JC({innerType:Q,typeName:aA.ZodReadonly,...tA(A)});var aA;(function(Q){Q.ZodString="ZodString",Q.ZodNumber="ZodNumber",Q.ZodNaN="ZodNaN",Q.ZodBigInt="ZodBigInt",Q.ZodBoolean="ZodBoolean",Q.ZodDate="ZodDate",Q.ZodSymbol="ZodSymbol",Q.ZodUndefined="ZodUndefined",Q.ZodNull="ZodNull",Q.ZodAny="ZodAny",Q.ZodUnknown="ZodUnknown",Q.ZodNever="ZodNever",Q.ZodVoid="ZodVoid",Q.ZodArray="ZodArray",Q.ZodObject="ZodObject",Q.ZodUnion="ZodUnion",Q.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Q.ZodIntersection="ZodIntersection",Q.ZodTuple="ZodTuple",Q.ZodRecord="ZodRecord",Q.ZodMap="ZodMap",Q.ZodSet="ZodSet",Q.ZodFunction="ZodFunction",Q.ZodLazy="ZodLazy",Q.ZodLiteral="ZodLiteral",Q.ZodEnum="ZodEnum",Q.ZodEffects="ZodEffects",Q.ZodNativeEnum="ZodNativeEnum",Q.ZodOptional="ZodOptional",Q.ZodNullable="ZodNullable",Q.ZodDefault="ZodDefault",Q.ZodCatch="ZodCatch",Q.ZodPromise="ZodPromise",Q.ZodBranded="ZodBranded",Q.ZodPipeline="ZodPipeline",Q.ZodReadonly="ZodReadonly"})(aA||(aA={}));const kA=VI.create,GA=qg.create,Wi=SC.create,XI=NC.create;OI.create;const LA=dI.create,QA=bA.create;EQ.create,iQ.create,sg.create;const BI=cC.create,mg=fg.create;oQ.create,vI.create,ug.create;const Nh=QA({multiscales:LA(QA({name:kA().optional(),datasets:LA(QA({path:kA(),coordinateTransformations:LA(XI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(GA()).min(2)}),QA({type:BI("translation"),translation:LA(GA()).min(2)})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),version:BI("0.4").optional(),axes:LA(XI().superRefine((Q,A)=>{const I=[QA({name:kA(),type:mg(["channel","time","space"])}),QA({name:kA(),type:XI().refine(B=>!mg(["space","time","channel"]).safeParse(B).success,"Invalid input: Should NOT be valid against schema").optional()})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:LA(XI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(GA()).min(2)}),QA({type:BI("translation"),translation:LA(GA()).min(2)}),QA({type:BI("identity")})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:QA({channels:LA(QA({window:QA({end:GA(),max:GA(),min:GA(),start:GA()}),label:kA().optional(),family:kA().optional(),color:kA(),active:Wi().optional()})),rdefs:QA({defaultT:GA().optional(),defaultZ:GA().optional(),color:mg(["color","greyscale"]).optional(),projection:kA().optional()}).optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),Rh=QA({plate:QA({acquisitions:LA(QA({id:GA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:GA().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:kA().describe("The name of the acquisition").optional(),description:kA().describe("The description of the acquisition").optional(),starttime:GA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:GA().int().gte(0).describe("The end timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional()})).describe("The acquisitions for this plate").optional(),version:BI("0.4").describe("The version of the specification").optional(),field_count:GA().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:kA().describe("The name of the plate").optional(),columns:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:LA(QA({path:kA().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:GA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:GA().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}).optional()}).describe("JSON from OME-NGFF .zattrs"),ch=QA({well:QA({images:LA(QA({acquisition:GA().int().describe("A unique identifier within the context of the plate").optional(),path:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The path for this field of view subgroup")})).min(1).describe("The fields of view for this well"),version:BI("0.4").describe("The version of the specification").optional()}).optional()}).describe("JSON from OME-NGFF .zattrs"),Uh=QA({ome:QA({multiscales:LA(QA({name:kA().optional(),datasets:LA(QA({path:kA(),coordinateTransformations:LA(XI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(GA()).min(2)}),QA({type:BI("translation"),translation:LA(GA()).min(2)})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1)})).min(1),axes:LA(XI().superRefine((Q,A)=>{const I=[QA({name:kA(),type:mg(["channel","time","space"])}),QA({name:kA(),type:XI().refine(B=>!mg(["space","time","channel"]).safeParse(B).success,"Invalid input: Should NOT be valid against schema").optional()})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(2).max(5),coordinateTransformations:LA(XI().superRefine((Q,A)=>{const I=[QA({type:BI("scale"),scale:LA(GA()).min(2)}),QA({type:BI("translation"),translation:LA(GA()).min(2)}),QA({type:BI("identity")})],g=I.reduce((B,C)=>(E=>E.error?[...B,E.error]:B)(C.safeParse(Q)),[]);I.length-g.length!==1&&A.addIssue({path:A.path,code:"invalid_union",unionErrors:g,message:"Invalid input: Should pass single schema"})})).min(1).optional()})).min(1).describe("The multiscale datasets for this image"),omero:QA({channels:LA(QA({window:QA({end:GA(),max:GA(),min:GA(),start:GA()}).optional(),label:kA().optional(),family:kA().optional(),color:kA().optional(),active:Wi().optional()})),rdefs:QA({defaultT:GA().optional(),defaultZ:GA().optional(),color:mg(["color","greyscale"]).optional(),projection:kA().optional()}).optional()}).optional(),version:BI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),kh=QA({ome:QA({plate:QA({acquisitions:LA(QA({id:GA().int().gte(0).describe("A unique identifier within the context of the plate"),maximumfieldcount:GA().int().gt(0).describe("The maximum number of fields of view for the acquisition").optional(),name:kA().describe("The name of the acquisition").optional(),description:kA().describe("The description of the acquisition").optional(),starttime:GA().int().gte(0).describe("The start timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional(),endtime:GA().int().gte(0).describe("The end timestamp of the acquisition, expressed as epoch time i.e. the number seconds since the Epoch").optional()})).describe("The acquisitions for this plate").optional(),field_count:GA().int().gt(0).describe("The maximum number of fields per view across all wells").optional(),name:kA().describe("The name of the plate").optional(),columns:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The column name")})).min(1).describe("The columns of the plate"),rows:LA(QA({name:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The row name")})).min(1).describe("The rows of the plate"),wells:LA(QA({path:kA().regex(new RegExp("^[A-Za-z0-9]+/[A-Za-z0-9]+$")).describe("The path to the well subgroup"),rowIndex:GA().int().gte(0).describe("The index of the well in the rows list"),columnIndex:GA().int().gte(0).describe("The index of the well in the columns list")})).min(1).describe("The wells of the plate")}),version:BI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("The zarr.json attributes key"),Lh=QA({ome:QA({well:QA({images:LA(QA({acquisition:GA().int().describe("A unique identifier within the context of the plate").optional(),path:kA().regex(new RegExp("^[A-Za-z0-9]+$")).describe("The path for this field of view subgroup")})).min(1).describe("The fields of view for this well")}),version:BI("0.5").describe("The version of the OME-Zarr Metadata")}).describe("The versioned OME-Zarr Metadata namespace")}).describe("JSON from OME-Zarr zarr.json"),Jh=["0.4","0.5"],Yh=new Set(Jh);function Kh(Q){if(!("ome"in Q)||!(Q.ome instanceof Object))return;const A=Q.ome;if("version"in A&&typeof A.version=="string"&&Yh.has(A.version))return A.version}function YC(Q){const A=Kh(Q);return A===void 0?"0.4":A}function xg(Q){if(Q!==void 0)switch(Q){case"0.4":return"v2";case"0.5":return"v3"}}function bi(Q,A){const I={...Q};return delete I[A],I}async function Mh(Q,A){const I=new hB(Q),g=new eI(I),B=xg(A),C=await wB(g,B);try{return dh(C.attrs)}catch{throw Error(`Failed to parse OME-Zarr plate:
|
|
4211
4211
|
${JSON.stringify(C.attrs)}`)}}function dh(Q){switch(YC(Q)){case"0.5":return{...kh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...Hh(Rh.parse(Q)).ome,originalVersion:"0.4"}}}function Hh(Q){if(Q.plate===void 0)throw new Error("Plate metadata is missing in OME-Zarr v0.4 plate");return{ome:{plate:bi(Q.plate,"version"),version:"0.5"}}}function qh(Q){if(Q.well===void 0)throw new Error("Well metadata is missing in OME-Zarr v0.4 well");return{ome:{well:bi(Q.well,"version"),version:"0.5"}}}function lh(Q){switch(YC(Q)){case"0.5":return{...Lh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...qh(ch.parse(Q)).ome,originalVersion:"0.4"}}}async function fh(Q,A,I){const g=Q+"/"+A,B=new hB(g),C=new eI(B),E=xg(I),i=await wB(C,E);try{return lh(i.attrs)}catch{throw Error(`Failed to parse OME-Zarr well:
|
|
4212
4212
|
${JSON.stringify(i.attrs)}`)}}async function ph(Q){const A=xg(Q.version),I=await wB(Q.location,A);return KC(I.attrs).omero?.channels??[]}async function uh(Q){const A=xg(Q.version),I=await wB(Q.location,A);return KC(I.attrs).omero?.rdefs}function mh(Q){return{ome:{multiscales:Q.multiscales,omero:Q.omero,version:"0.5"}}}function xh(Q){switch(YC(Q)){case"0.5":return{...Uh.parse(Q).ome,originalVersion:"0.5"};case"0.4":return{...mh(Nh.parse(Q)).ome,originalVersion:"0.4"}}}function KC(Q){try{return xh(Q)}catch{throw Error(`Failed to parse OME-Zarr image:
|
|
4213
|
-
${JSON.stringify(Q)}`)}}class Tg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let g=xg(I);const B=await wB(A,g),C=KC(B.attrs),E=C.multiscales;if(E.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${E.length} images.`);const i=E[0];if(i.datasets.length===0)throw new Error("No datasets found in the multiscale image.");g||(g=xg(C.originalVersion));const o=i.datasets.map(y=>qs(A,y.path,g)),a=await Promise.all(o.map(y=>Hs(y))),D=a[0].shape,s=i.axes;if(s.length!==D.length)throw new Error(`Mismatch between number of axes (${s.length}) and array shape (${D.length})`);return new Vs({metadata:i,arrays:a,arrayParams:o})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}get loader(){return this.loader_}static async fromHttp(A){const I=new eI(new hB(A.url)),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}static async fromFileSystem(A){const I=new eI(new eC(A.directory),A.path),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}}class nB{objects_=[];state_="initialized";attached_=!1;callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){this.opacity_=pI(A,0,1),this.blendMode=I}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&gA.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=pI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}getUniforms(){return{}}}class Th extends Ug{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*10),g=A.length>=3&&NQ(A[0],A[A.length-1]);let B=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[B++]=i[0],I[B++]=i[1],I[B++]=i[2];const o=C===0?g?A[A.length-2]:A[C]:A[C-1];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const a=C===A.length-1?g?A[1]:A[C]:A[C+1];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let g=0;for(let B=0;B<2*A;B+=2)I[g++]=B+0,I[g++]=B+1,I[g++]=B+2,I[g++]=B+2,I[g++]=B+1,I[g++]=B+3;return I}}class Wh extends Ug{constructor(A){if(super(),A.primitive!="triangles"){gA.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){gA.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],B=(E,i)=>{const o=Math.min(E,i),a=Math.max(E,i);I.has({i0:o,i1:a})||(I.add({i0:o,i1:a}),g.push(o,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],a=C[E+2];B(i,o),B(o,a),B(a,i)}this.indexData_=new Uint32Array(g)}}const bh=nA(0,1,0);class Zh{dirty_=!0;matrix_=hI();rotation_=cQ();translation_=HA();scale_=nA(1,1,1);addRotation(A){Aa(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){ga(this.rotation_,A),this.dirty_=!0}get rotation(){return Ia(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){rQ(this.translation_,A),this.dirty_=!0}get translation(){return HI(this.translation_)}addScale(A){Po(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){rQ(this.scale_,A),this.dirty_=!0}targetTo(A){NQ(this.translation_,A)&&(A=HI(A),A[2]+=JA);const I=Wo(hI(),this.translation_,A,bh),g=qo(zC(),I);IE(this.rotation_,g),kQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return HI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return dB(hI(),this.matrix)}computeMatrix(){po(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Wg extends FQ{wireframeEnabled=!1;wireframeColor=FA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new Zh;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const g=this.textures_[A];g!==void 0&&this.staleTextures_.push(g),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new Wh(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class Zi extends Wg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=FA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=FA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{LineColor:this.color.rgb,LineWidth:this.width}}}class Ph extends nB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(MC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(MC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(MC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function MC(Q){const{end:A,width:I,color:g}=Q,B=new Th([[0,0,0],A]);return new Zi({geometry:B,color:g,width:I})}const Pi=32;function SB(Q,{visible:A,color:I,contrastLimits:g,opacity:B}){return A??=!0,I=I===void 0?FA.WHITE:FA.from(I),B=B===void 0?1:pI(B,0,1),Q!==null?g=Vh(g,Q):g===void 0&&(gA.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g,opacity:B}}function dC(Q,A){if(A.length>Pi)throw new Error(`Maximum number of channels is ${Pi}`);return A.map(I=>SB(Q,I))}function Vi(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function Vh(Q,A){if(Q===void 0)return Sa(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Oi extends Ug{constructor(A,I,g,B){super();const C=[],E=[],i=g,o=B,a=i+1,D=o+1,s=A/i,y=I/o;for(let e=0;e<D;++e){const Y=e*y;for(let u=0;u<a;++u){const H=u*s,W=u/i,z=e/o,x=[H,Y,0],l=[0,0,1],Z=[W,z];C.push(...x,...l,...Z)}}for(let e=0;e<o;++e)for(let Y=0;Y<i;++Y){const u=Y+a*e,H=Y+a*(e+1),W=Y+1+a*(e+1),z=Y+1+a*e;E.push(u,H,z),E.push(H,W,z)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class vi extends Wg{channels_;zTexCoord=.5;constructor(A,I,g,B=[]){super(),this.geometry=new Oi(A,I,1,1),this.setTexture(0,g),this.channels_=dC(g,B),this.programName=Oh(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=dC(this.textures[0],A)}setChannelProperty(A,I,g){const B=SB(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=B}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g,opacity:B}=this.channels_[0]??SB(A,{});return{ImageSampler:0,Color:I.rgb,ValueOffset:-g[0],ValueScale:1/(g[1]-g[0]),Opacity:B,ZTexCoord:this.zTexCoord}}}function Oh(Q){switch(Q.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function Xi(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return xA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=xA(C.clientX,C.clientY);if(Ba(A,E)<B){if(!g)return null;const o=Q.worldPos;return o&&I(o).then(a=>{a!==null&&g({world:o,value:a})}).catch(a=>{gA.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class HC{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&gA.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),gA.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class qC extends nB{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new HC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new FA(.6,.3,.3),new FA(.3,.6,.4),new FA(.4,.4,.7),new FA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,channelProps:B,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_);const I=this.chunkStoreView_.channelCount;if(Vi(this.channelProps_,I),I>1&&this.sliceCoords_.c!==void 0&&this.sliceCoords_.c.length>1)throw new Error(`ImageLayer requires exactly one channel in sliceCoords.c for multi-channel sources (found ${I} channels). Use one layer per channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Image rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)B.zTexCoord=this.zTexCoordForChunk(g)}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getImageForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>qC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(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,VB))}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(g,A),g):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new vi(A.shape.x,A.shape.y,qI.createWithChunk(A),this.getChannelPropsForChunk(A));return I.zTexCoord=this.zTexCoordForChunk(A),this.updateImageChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}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])}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(HA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}function aQ(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class vh extends Ug{constructor(A,I,g,B,C,E){super();const i=[],o=[],a=Math.floor(B),D=Math.floor(C),s=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,s,D,1,i,o),this.buildFace("z","y","x",1,-1,g,I,A,s,D,-1,i,o),this.buildFace("x","z","y",1,1,A,g,I,a,s,1,i,o),this.buildFace("x","z","y",1,-1,A,g,I,a,s,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,g,a,D,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,g,a,D,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,g,B,C,E,i,o,a,D,s,y,e){const Y=E/a,u=i/D,H=E/2,W=i/2,z=o/2*s,x=a+1,l=D+1,Z=y.length/8;for(let v=0;v<l;v++){const CA=-W+v*u;for(let sA=0;sA<x;sA++){const DA=-H+sA*Y,yA={x:0,y:0,z:0};yA[A]=DA*B,yA[I]=CA*C,yA[g]=z;const wA={x:0,y:0,z:0};wA[g]=s;const zA=sA/a,uA=1-v/D;y.push(yA.x,yA.y,yA.z,wA.x,wA.y,wA.z,zA,uA)}}for(let v=0;v<D;v++)for(let CA=0;CA<a;CA++){const sA=Z+CA+x*v,DA=Z+CA+x*(v+1),yA=Z+(CA+1)+x*(v+1),wA=Z+(CA+1)+x*v;e.push(sA,DA,wA,DA,yA,wA)}}}class ji extends Wg{voxelScale=nA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new vh(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=qI.createWithChunk(I),B=this.textures.length;this.setTexture(B,g),this.channelToTextureIndex_.set(A,B);const C=Xh(g.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${g.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const g=this.textures[A];if(!(g instanceof qI)){const B=qI.createWithChunk(I);this.setTexture(A,B);return}g.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],B=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let o=0;o<i&&E.length<4;o++){const a=this.channelToTextureIndex_.get(o);if(a===void 0||!this.loadedChannels_.has(o))continue;const D=this.textures[a],s=SB(D,this.channels_[o]||{});if(!s.visible)continue;const y=E.length;I[y*3]=s.color.rgb[0],I[y*3+1]=s.color.rgb[1],I[y*3+2]=s.color.rgb[2],E.push(a),g[y]=-s.contrastLimits[0],B[y]=1/(s.contrastLimits[1]-s.contrastLimits[0]),A[y]=1,C[y]=s.opacity}return E.reduce((o,a,D)=>(o[`Channel${D}Sampler`]=a,o),{Visible:A,"Color[0]":I,ValueOffset:g,ValueScale:B,ChannelOpacity:C,VoxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=dC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=SB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Xh(Q){switch(Q){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function jh(Q,A){const I=A.position,g=HA(),B=HA();return Q.sort((C,E)=>{gB(g,C.boundingBox.max,C.boundingBox.min),BB(g,g,.5),gB(B,E.boundingBox.max,E.boundingBox.min),BB(B,B,.5);const i=$C(I,g),o=$C(I,B);return i-o}),Q}const zh=2;class _h extends nB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new HC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:g,channelProps:B}){super({blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=g,this.initialChannelProps_=B,this.channelProps_=B,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const B=Iy(I[0]),C=this.pool_.acquire(B)??new ji;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,B);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.sourcePolicy_),Vi(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=Ay(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i),this.addObject(i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length,this.state!=="ready"&&this.setState("ready")}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),Bg(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveVolume(A){A.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?zh:1,this.updateChunks(),jh(this.objects,A.camera)}getUniforms(){return{DebugShowDegenerateRays:Number(this.debugShowDegenerateRays),RelativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,OpacityMultiplier:this.opacityMultiplier,EarlyTerminationAlpha:this.earlyTerminationAlpha}}}function $h(Q){const{x:A,y:I,z:g,t:B}=Q.chunkIndex;return`${A}:${I}:${g}:${B}`}function Ay(Q){const A=new Map;for(const I of Q){const g=$h(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function Iy(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class DQ extends JQ{data_;width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==g){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new DQ(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const gy=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function By(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!gy.has(Q.dataType))throw new Error(`Image data type must be unsigned, instead found: ${Q.dataType}`);return Q}class zi extends Wg{outlineSelected_;selectedValue_;zTexCoord=.5;constructor(A){super(),this.geometry=new Oi(A.width,A.height,1,1),this.setTexture(0,By(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const g=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,g),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{ImageSampler:0,ColorCycleSampler:1,ColorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,ZTexCoord:this.zTexCoord}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(B=>B.rgba).map(B=>Math.round(B*255))),g=new DQ(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,FA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,FA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),B=A.size,C=new Uint32Array(B*2);return C.set(I,0),C.set(g,B),new DQ(C,B,2)}}const Qy=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Cy(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,FA.from(I)]))}function Ey(Q){return Q=Q??Qy,Q.map(FA.from)}class lC{lookupTable;cycle;constructor(A={}){this.lookupTable=Cy(A.lookupTable),this.cycle=Ey(A.cycle)}}class fC extends nB{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new HC;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,colorMap:B={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.colorMap_=new lC(B),this.onPickValue_=C,this.outlineSelected_=E}attach(A){if(this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Label rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)B.zTexCoord=this.zTexCoordForChunk(g)}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getLabelForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>fC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new lC(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(HA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}getLabelForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setColorMap(this.colorMap_),g.setSelectedValue(this.selectedValue_),this.updateLabelChunk(g,A),g):this.createLabel(A)}createLabel(A){const I=new zi({width:A.shape.x,height:A.shape.y,imageData:qI.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.zTexCoord=this.zTexCoordForChunk(A),this.updateLabelChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}updateLabelChunk(A,I){A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}class pC extends JQ{data_;width_;height_;depth_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=A.length/(I*g)}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 g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===g)return;const B=A.shape.x,C=A.shape.y,E=g.length/(B*C);if(this.width!=B||this.height!=C||this.depth_!=E||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new pC(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const _i={circle:0,square:1,triangle:2};class iy extends Wg{constructor(A){super(),this.programName="points";const I=A.flatMap(B=>{const C=FA.from(B.color);return[B.position[0],B.position[1],B.position[2],C.r,C.g,C.b,C.a,B.size,_i[B.marker]]}),g=new Ug(I,[],"points");g.addAttribute({type:"position",itemSize:3,offset:0}),g.addAttribute({type:"color",itemSize:4,offset:g.strideBytes}),g.addAttribute({type:"size",itemSize:1,offset:g.strideBytes}),g.addAttribute({type:"marker",itemSize:1,offset:g.strideBytes}),this.geometry=g,this.setTexture(0,oy())}get type(){return"Points"}}let uC;function oy(){return uC||(uC=ay()),uC}function ay(){const Q=a=>{const D=new Float32Array(a*a);return D.fill(1),D},A=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)(s-a/2)**2+(y-a/2)**2<(a/2)**2&&(D[s*a+y]=1);return D},I=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)y>=(a-s)/2&&y<=(a+s)/2&&(D[s*a+y]=1);return D},C={circle:A(256),square:Q(256),triangle:I(256)},E=Object.keys(C).length,i=new Float32Array(E*65536);for(const[a,D]of Object.entries(C))i.set(D,_i[a]*65536);const o=new pC(i,256,256);return o.wrapR="clamp_to_edge",o.wrapS="clamp_to_edge",o.wrapT="clamp_to_edge",o}class $i{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}toVec3(){const A=Math.cos(this.theta);return nA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const mC=-1,Ao=0,Dy=1,Io=.009,sy=.001,hy=9e-4,yy=.5,ty=60;class Gy{camera_;orbitVelocity_=new $i(0,0,0);panVelocity_=HA();currPos_;currCenter_=HA();dampingFactor_;currMouseButton_=mC;constructor(A,I){this.camera_=A,this.currPos_=new $i(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&rQ(this.currCenter_,I.target),this.dampingFactor_=pI(I?.dampingFactor??yy,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&NQ(this.panVelocity_,nA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,gB(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-JA;this.currPos_.theta=pI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*ty);this.orbitVelocity_.phi*=g,this.orbitVelocity_.theta*=g,this.orbitVelocity_.radius*=g,BB(this.panVelocity_,this.panVelocity_,g),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==mC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===Ao&&!I.shiftKey,E=this.currMouseButton_===Ao&&I.shiftKey||this.currMouseButton_===Dy;C&&this.orbit(g,B),E&&this.pan(g,B)}onWheel(A){const I=A.event;I.preventDefault();const g=I.deltaY??0;this.zoom(g)}onPointerEnd(A){this.currMouseButton_=mC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*Io,this.orbitVelocity_.theta+=I*Io}pan(A,I){const g=this.currPos_.radius*sy,B=HA();_C(B,B,this.camera_.right,A),_C(B,B,this.camera_.up,I),BB(B,B,g),RQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*hy}updateCamera(){const A=gB(HA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<JA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<JA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<JA&&(this.orbitVelocity_.radius=0),eQ(this.panVelocity_)<JA&&Oo(this.panVelocity_)}}class bg{normal;signedDistance;constructor(A=nA(0,1,0),I=0){this.normal=HI(A),this.signedDistance=I}set(A,I){this.normal=HI(A),this.signedDistance=I}signedDistanceToPoint(A){return AE(this.normal,A)+this.signedDistance}normalize(){const A=eQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class wy{planes_;constructor(A){this.planes_=[new bg(HA(),0),new bg(HA(),0),new bg(HA(),0),new bg(HA(),0),new bg(HA(),0),new bg(HA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=HA();this.planes_[0].set(Bg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(Bg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(Bg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(Bg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(Bg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(Bg(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const g of this.planes_)g.normalize()}intersectsWithBox3(A){const I=HA();for(const g of this.planes_){const B=g.normal;if(I[0]=B[0]>0?A.max[0]:A.min[0],I[1]=B[1]>0?A.max[1]:A.min[1],I[2]=B[2]>0?A.max[2]:A.min[2],g.signedDistanceToPoint(I)<0)return!1}return!0}}class go extends Wg{projectionMatrix_=hI();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])}getViewProjection(){return Rg(hI(),this.projectionMatrix,this.viewMatrix)}get frustum(){return new wy(this.getViewProjection())}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=HB(A[0],A[1],A[2],1),g=dB(hI(),this.projectionMatrix_),B=QB(cg(),I,g);zo(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return nA(C[0],C[1],C[2])}}const Bo=1.77,Qo=128,Co=128/Bo;class Fy extends go{width_=Qo;height_=Co;viewportAspectRatio_=Bo;viewportSize_=[Qo,Co];constructor(A,I,g,B,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,B,g),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,g,B){this.width_=Math.abs(I-A),this.height_=Math.abs(B-g),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(g+B);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=HB(-1,-1,0,1),I=HB(1,1,0,1);const g=dB(hI(),this.getViewProjection());return A=QB(cg(),A,g),I=QB(cg(),I,g),new QI(xA(A[0],A[1]),xA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,g=A/I;let B=.5*A,C=.5*I;this.viewportAspectRatio_>g?B*=this.viewportAspectRatio_/g:C*=g/this.viewportAspectRatio_,this.viewportSize_=[2*B,2*C],To(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const Eo=0;class ey{camera_;dragActive_=!1;dragStart_=HA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const g=HI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=RQ(HA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==Eo||(this.dragStart_=HI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=RQ(HA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==Eo||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}const ry=60,ny=1.77,sQ=.1,xC=180-sQ;class Sy extends go{fov_;aspectRatio_;constructor(A={}){const{fov:I=ry,aspectRatio:g=ny,near:B=.1,far:C=1e4,position:E=nA(0,0,0)}=A;if(I<sQ||I>xC)throw new Error(`Invalid field of view: ${I}, must be in [${sQ}, ${xC}] degrees`);super(),this.fov_=I,this.aspectRatio_=g,this.near_=B,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(sQ,Math.min(xC,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){mo(this.projectionMatrix_,Ho(this.fov),this.aspectRatio_,this.near_,this.far_)}}const io=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function hQ(Q){Uy(Q);const A={x:Q.prefetch.x,y:Q.prefetch.y,z:Q.prefetch.z??0,t:Q.prefetch.t??0},I=Object.freeze(io.reduce((C,E)=>{const i=Q.priorityOrder.indexOf(E);return C[E]=i,C},{})),g={min:Q.lod?.min??0,max:Q.lod?.max??Number.MAX_SAFE_INTEGER,bias:Q.lod?.bias??.5},B={profile:Q.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...Q.priorityOrder]),priorityMap:I,lod:g};return Object.freeze(B)}function Ny(Q={}){return hQ(TC({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},Q))}function Ry(Q={}){return hQ(TC({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},Q))}function cy(Q={}){return hQ(TC({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},Q))}function Uy(Q){for(const[g,B]of Object.entries(Q.prefetch))if(B!==void 0&&B<0)throw new Error(`prefetch.${g} must be a non-negative number`);const A=Q.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=Q.priorityOrder;if(I.length!==io.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function TC(Q,A={}){return{profile:A.profile??Q.profile,prefetch:{...Q.prefetch,...A.prefetch??{}},lod:{...Q.lod,...A.lod??{}},priorityOrder:A.priorityOrder??Q.priorityOrder}}var WC=(()=>{for(var Q=new Uint8Array(128),A=0;A<64;A++)Q[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var g=I.length,B=new Uint8Array((g-(I[g-1]=="=")-(I[g-2]=="="))*3/4|0),C=0,E=0;C<g;){var i=Q[I.charCodeAt(C++)],o=Q[I.charCodeAt(C++)],a=Q[I.charCodeAt(C++)],D=Q[I.charCodeAt(C++)];B[E++]=i<<2|o>>4,B[E++]=o<<4|a>>2,B[E++]=a<<6|D}return B}})(),ky=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(Q={}){var A=Q,I,g;A.ready=new Promise((G,r)=>{I=G,g=r});var B=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,B),B=null,A.thisProgram&&(C=A.thisProgram);var o;A.wasmBinary&&(o=A.wasmBinary),typeof WebAssembly!="object"&&yA("no native wasm support detected");var a,D=!1,s,y,e,Y,u,H,W,z;function x(){var G=a.buffer;A.HEAP8=s=new Int8Array(G),A.HEAP16=e=new Int16Array(G),A.HEAPU8=y=new Uint8Array(G),A.HEAPU16=Y=new Uint16Array(G),A.HEAP32=u=new Int32Array(G),A.HEAPU32=H=new Uint32Array(G),A.HEAPF32=W=new Float32Array(G),A.HEAPF64=z=new Float64Array(G)}var l=[],Z=[],v=[];function CA(){var G=A.preRun.shift();l.unshift(G)}var sA=0,DA=null;function yA(G){throw A.onAbort?.(G),G="Aborted("+G+")",i(G),D=!0,G=new WebAssembly.RuntimeError(G+". Build with -sASSERTIONS for more info."),g(G),G}var wA=G=>G.startsWith("data:application/octet-stream;base64,"),zA=G=>G.startsWith("file://"),uA;if(uA="blosc_codec.wasm",!wA(uA)){var NA=uA;uA=A.locateFile?A.locateFile(NA,""):""+NA}function mI(G){return Promise.resolve().then(()=>{if(G==uA&&o)var r=new Uint8Array(o);else throw"both async and sync fetching of the wasm failed";return r})}function kI(G,r,N){return mI(G).then(d=>WebAssembly.instantiate(d,r)).then(d=>d).then(N,d=>{i(`failed to asynchronously prepare wasm: ${d}`),yA(d)})}function xI(G,r){var N=uA;return o||typeof WebAssembly.instantiateStreaming!="function"||wA(N)||zA(N)||typeof fetch!="function"?kI(N,G,r):fetch(N,{credentials:"same-origin"}).then(d=>WebAssembly.instantiateStreaming(d,G).then(r,function(h){return i(`wasm streaming compile failed: ${h}`),i("falling back to ArrayBuffer instantiation"),kI(N,G,r)}))}var jI=G=>{for(;0<G.length;)G.shift()(A)};function zI(G){this.H=G-24,this.N=function(r){H[this.H+4>>2]=r},this.M=function(r){H[this.H+8>>2]=r},this.I=function(r,N){this.J(),this.N(r),this.M(N)},this.J=function(){H[this.H+16>>2]=0}}var $A=0,ZA,MA=G=>{for(var r="";y[G];)r+=ZA[y[G++]];return r},XA={},KA={},mA={},PA,hg=G=>{throw new PA(G)},yg,GI=(G,r)=>{function N(J){if(J=r(J),J.length!==d.length)throw new yg("Mismatched type converter count");for(var k=0;k<d.length;++k)dA(d[k],J[k])}var d=[];d.forEach(function(J){mA[J]=G});var h=Array(G.length),w=[],S=0;G.forEach((J,k)=>{KA.hasOwnProperty(J)?h[k]=KA[J]:(w.push(J),XA.hasOwnProperty(J)||(XA[J]=[]),XA[J].push(()=>{h[k]=KA[J],++S,S===w.length&&N(h)}))}),w.length===0&&N(h)};function aI(G,r,N={}){var d=r.name;if(!G)throw new PA(`type "${d}" must have a positive integer typeid pointer`);if(KA.hasOwnProperty(G)){if(N.P)return;throw new PA(`Cannot register type '${d}' twice`)}KA[G]=r,delete mA[G],XA.hasOwnProperty(G)&&(r=XA[G],delete XA[G],r.forEach(h=>h()))}function dA(G,r,N={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");aI(G,r,N)}function DI(){this.F=[void 0],this.K=[]}var _A=new DI,TI=G=>{G>=_A.H&&--_A.get(G).L===0&&_A.J(G)},vg=G=>{switch(G){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return _A.I({L:1,value:G})}};function _I(G){return this.fromWireType(u[G>>2])}var tg=(G,r)=>{switch(r){case 4:return function(N){return this.fromWireType(W[N>>2])};case 8:return function(N){return this.fromWireType(z[N>>3])};default:throw new TypeError(`invalid float width (${r}): ${G}`)}},$I=(G,r)=>Object.defineProperty(r,"name",{value:G}),Xg=G=>{for(;G.length;){var r=G.pop();G.pop()(r)}};function jg(G){for(var r=1;r<G.length;++r)if(G[r]!==null&&G[r].G===void 0)return!0;return!1}function NB(G){var r=Function;if(!(r instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof r} which is not a function`);var N=$I(r.name||"unknownFunctionName",function(){});return N.prototype=r.prototype,N=new N,G=r.apply(N,G),G instanceof Object?G:N}var RB=(G,r)=>{if(A[G].C===void 0){var N=A[G];A[G]=function(){if(!A[G].C.hasOwnProperty(arguments.length))throw new PA(`Function '${r}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[G].C})!`);return A[G].C[arguments.length].apply(this,arguments)},A[G].C=[],A[G].C[N.O]=N}},Gg=(G,r,N)=>{if(A.hasOwnProperty(G)){if(N===void 0||A[G].C!==void 0&&A[G].C[N]!==void 0)throw new PA(`Cannot register public name '${G}' twice`);if(RB(G,G),A.hasOwnProperty(N))throw new PA(`Cannot register multiple overloads of a function with the same number of arguments (${N})!`);A[G].C[N]=r}else A[G]=r,N!==void 0&&(A[G].S=N)},wg=(G,r)=>{for(var N=[],d=0;d<G;d++)N.push(H[r+4*d>>2]);return N},Fg,zg=(G,r)=>{var N=[];return function(){if(N.length=0,Object.assign(N,arguments),G.includes("j")){var d=A["dynCall_"+G];d=N&&N.length?d.apply(null,[r].concat(N)):d.call(null,r)}else d=Fg.get(r).apply(null,N);return d}},_g=(G,r)=>{G=MA(G);var N=G.includes("j")?zg(G,r):Fg.get(r);if(typeof N!="function")throw new PA(`unknown function pointer with signature ${G}: ${r}`);return N},eg,rg=G=>{G=O(G);var r=MA(G);return p(G),r},cB=(G,r)=>{function N(w){h[w]||KA[w]||(mA[w]?mA[w].forEach(N):(d.push(w),h[w]=!0))}var d=[],h={};throw r.forEach(N),new eg(`${G}: `+d.map(rg).join([", "]))},UB=G=>{G=G.trim();const r=G.indexOf("(");return r!==-1?G.substr(0,r):G},$g=(G,r,N)=>{switch(r){case 1:return N?d=>s[d>>0]:d=>y[d>>0];case 2:return N?d=>e[d>>1]:d=>Y[d>>1];case 4:return N?d=>u[d>>2]:d=>H[d>>2];default:throw new TypeError(`invalid integer width (${r}): ${G}`)}};function ng(G){return this.fromWireType(H[G>>2])}for(var Ag=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Sg=(G,r,N)=>{var d=r+N;for(N=r;G[N]&&!(N>=d);)++N;if(16<N-r&&G.buffer&&Ag)return Ag.decode(G.subarray(r,N));for(d="";r<N;){var h=G[r++];if(h&128){var w=G[r++]&63;if((h&224)==192)d+=String.fromCharCode((h&31)<<6|w);else{var S=G[r++]&63;h=(h&240)==224?(h&15)<<12|w<<6|S:(h&7)<<18|w<<12|S<<6|G[r++]&63,65536>h?d+=String.fromCharCode(h):(h-=65536,d+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else d+=String.fromCharCode(h)}return d},AB=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,kB=(G,r)=>{for(var N=G>>1,d=N+r/2;!(N>=d)&&Y[N];)++N;if(N<<=1,32<N-G&&AB)return AB.decode(y.subarray(G,N));for(N="",d=0;!(d>=r/2);++d){var h=e[G+2*d>>1];if(h==0)break;N+=String.fromCharCode(h)}return N},LB=(G,r,N)=>{if(N??=2147483647,2>N)return 0;N-=2;var d=r;N=N<2*G.length?N/2:G.length;for(var h=0;h<N;++h)e[r>>1]=G.charCodeAt(h),r+=2;return e[r>>1]=0,r-d},JB=G=>2*G.length,IB=(G,r)=>{for(var N=0,d="";!(N>=r/4);){var h=u[G+4*N>>2];if(h==0)break;++N,65536<=h?(h-=65536,d+=String.fromCharCode(55296|h>>10,56320|h&1023)):d+=String.fromCharCode(h)}return d},Ig=(G,r,N)=>{if(N??=2147483647,4>N)return 0;var d=r;N=d+N-4;for(var h=0;h<G.length;++h){var w=G.charCodeAt(h);if(55296<=w&&57343>=w){var S=G.charCodeAt(++h);w=65536+((w&1023)<<10)|S&1023}if(u[r>>2]=w,r+=4,r+4>N)break}return u[r>>2]=0,r-d},Ng=G=>{for(var r=0,N=0;N<G.length;++N){var d=G.charCodeAt(N);55296<=d&&57343>=d&&++N,r+=4}return r},iI={},LI=()=>{if(!oI){var G={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"},r;for(r in iI)iI[r]===void 0?delete G[r]:G[r]=iI[r];var N=[];for(r in G)N.push(`${r}=${G[r]}`);oI=N}return oI},oI,pA=[null,[],[]],JI=Array(256),jA=0;256>jA;++jA)JI[jA]=String.fromCharCode(jA);ZA=JI,PA=A.BindingError=class extends Error{constructor(G){super(G),this.name="BindingError"}},yg=A.InternalError=class extends Error{constructor(G){super(G),this.name="InternalError"}},Object.assign(DI.prototype,{get(G){return this.F[G]},has(G){return this.F[G]!==void 0},I(G){var r=this.K.pop()||this.F.length;return this.F[r]=G,r},J(G){this.F[G]=void 0,this.K.push(G)}}),_A.F.push({value:void 0},{value:null},{value:!0},{value:!1}),_A.H=_A.F.length,A.count_emval_handles=()=>{for(var G=0,r=_A.H;r<_A.F.length;++r)_A.F[r]!==void 0&&++G;return G},eg=A.UnboundTypeError=((G,r)=>{var N=$I(r,function(d){this.name=r,this.message=d,d=Error(d).stack,d!==void 0&&(this.stack=this.toString()+`
|
|
4213
|
+
${JSON.stringify(Q)}`)}}class Tg{location;version;loader_;constructor(A){this.location=A.location,this.version=A.version,this.loader_=A.loader}static async openLoader(A,I){let g=xg(I);const B=await wB(A,g),C=KC(B.attrs),E=C.multiscales;if(E.length!==1)throw new Error(`Exactly one multiscale image is supported. Found ${E.length} images.`);const i=E[0];if(i.datasets.length===0)throw new Error("No datasets found in the multiscale image.");g||(g=xg(C.originalVersion));const o=i.datasets.map(y=>qs(A,y.path,g)),a=await Promise.all(o.map(y=>Hs(y))),D=a[0].shape,s=i.axes;if(s.length!==D.length)throw new Error(`Mismatch between number of axes (${s.length}) and array shape (${D.length})`);return new Vs({metadata:i,arrays:a,arrayParams:o})}getDimensions(){return this.loader_.getSourceDimensionMap()}getChannelCount(){return this.getDimensions().c?.lods[0].size??1}get loader(){return this.loader_}static async fromHttp(A){const I=new eI(new hB(A.url)),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}static async fromFileSystem(A){const I=new eI(new eC(A.directory),A.path),g=await Tg.openLoader(I,A.version);return new Tg({location:I,version:A.version,loader:g})}}class nB{objects_=[];state_="initialized";attached_=!1;callbacks_=[];opacity_;blendMode;constructor({opacity:A=1,blendMode:I="none"}={}){this.opacity_=pI(A,0,1),this.blendMode=I}get opacity(){return this.opacity_}set opacity(A){(A<0||A>1)&&gA.warn("Layer",`Opacity out of bounds: ${A} — clamping to [0.0, 1.0]`),this.opacity_=pI(A,0,1)}onEvent(A){}onAttached(A){if(this.attached_)throw new Error(`${this.type} cannot be attached to multiple viewports simultaneously.`);this.attach(A),this.attached_=!0}onDetached(A){this.attached_&&(this.detach(A),this.attached_=!1)}attach(A){}detach(A){}get objects(){return this.objects_}get state(){return this.state_}addStateChangeCallback(A){this.callbacks_.push(A)}removeStateChangeCallback(A){const I=this.callbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.callbacks_.splice(I,1)}hasMultipleLODs(){return!1}setState(A){const I=this.state_;this.state_=A,this.callbacks_.forEach(g=>g(A,I))}addObject(A){this.objects_.push(A)}removeObject(A){const I=this.objects_.indexOf(A);I!==-1&&this.objects_.splice(I,1)}clearObjects(){this.objects_=[]}getUniforms(){return{}}}class Th extends Ug{constructor(A){super(),this.vertexData_=this.createVertices(A),this.indexData_=this.createIndex(A.length),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"previous_position",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"next_position",itemSize:3,offset:6*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"direction",itemSize:1,offset:9*Float32Array.BYTES_PER_ELEMENT})}createVertices(A){const I=new Float32Array(2*A.length*10),g=A.length>=3&&NQ(A[0],A[A.length-1]);let B=0;for(const C of[...Array(A.length).keys()])for(const E of[-1,1]){const i=A[C];I[B++]=i[0],I[B++]=i[1],I[B++]=i[2];const o=C===0?g?A[A.length-2]:A[C]:A[C-1];I[B++]=o[0],I[B++]=o[1],I[B++]=o[2];const a=C===A.length-1?g?A[1]:A[C]:A[C+1];I[B++]=a[0],I[B++]=a[1],I[B++]=a[2],I[B++]=E}return I}createIndex(A){const I=new Uint32Array((A-1)*6);let g=0;for(let B=0;B<2*A;B+=2)I[g++]=B+0,I[g++]=B+1,I[g++]=B+2,I[g++]=B+2,I[g++]=B+1,I[g++]=B+3;return I}}class Wh extends Ug{constructor(A){if(super(),A.primitive!="triangles"){gA.warn("WireframeGeometry","Only indexed geometries are supported");return}if(A.indexData.length==0){gA.warn("WireframeGeometry","Only triangulated geometries are supported");return}this.primitive_="lines",this.vertexData_=A.vertexData,this.attributes_=A.attributes;const I=new Set,g=[],B=(E,i)=>{const o=Math.min(E,i),a=Math.max(E,i);I.has({i0:o,i1:a})||(I.add({i0:o,i1:a}),g.push(o,a))},C=A.indexData;for(let E=0;E<C.length;E+=3){const i=C[E],o=C[E+1],a=C[E+2];B(i,o),B(o,a),B(a,i)}this.indexData_=new Uint32Array(g)}}const bh=nA(0,1,0);class Zh{dirty_=!0;matrix_=hI();rotation_=cQ();translation_=HA();scale_=nA(1,1,1);addRotation(A){Aa(this.rotation_,this.rotation_,A),this.dirty_=!0}setRotation(A){ga(this.rotation_,A),this.dirty_=!0}get rotation(){return Ia(this.rotation_)}addTranslation(A){gB(this.translation_,this.translation_,A),this.dirty_=!0}setTranslation(A){rQ(this.translation_,A),this.dirty_=!0}get translation(){return HI(this.translation_)}addScale(A){Po(this.scale_,this.scale_,A),this.dirty_=!0}setScale(A){rQ(this.scale_,A),this.dirty_=!0}targetTo(A){NQ(this.translation_,A)&&(A=HI(A),A[2]+=JA);const I=Wo(hI(),this.translation_,A,bh),g=qo(zC(),I);IE(this.rotation_,g),kQ(this.rotation_,this.rotation_),this.dirty_=!0}get scale(){return HI(this.scale_)}get matrix(){return this.dirty_&&(this.computeMatrix(),this.dirty_=!1),this.matrix_}get inverse(){return dB(hI(),this.matrix)}computeMatrix(){po(this.matrix_,this.rotation_,this.translation_,this.scale_)}}class Wg extends FQ{wireframeEnabled=!1;wireframeColor=FA.WHITE;depthTest=!0;textures_=[];staleTextures_=[];transform_=new Zh;geometry_=new Ug;wireframeGeometry_=null;programName_=null;cullFaceMode_="none";setTexture(A,I){const g=this.textures_[A];g!==void 0&&this.staleTextures_.push(g),this.textures_[A]=I}popStaleTextures(){const A=this.staleTextures_;return this.staleTextures_=[],A}get geometry(){return this.geometry_}get wireframeGeometry(){return this.wireframeGeometry_??=new Wh(this.geometry),this.wireframeGeometry_}get textures(){return this.textures_}get transform(){return this.transform_}set geometry(A){this.geometry_=A,this.wireframeGeometry_=null}get programName(){return this.programName_}get boundingBox(){const A=this.geometry_.boundingBox.clone();return A.applyTransform(this.transform_.matrix),A}set programName(A){this.programName_=A}get cullFaceMode(){return this.cullFaceMode_}set cullFaceMode(A){this.cullFaceMode_=A}getUniforms(){return{}}}class Zi extends Wg{color_;width_;constructor({geometry:A,color:I,width:g}){super(),this.geometry=A,this.color_=FA.from(I),this.width_=g,this.programName="projectedLine"}get type(){return"ProjectedLine"}get color(){return this.color_}set color(A){this.color_=FA.from(A)}get width(){return this.width_}set width(A){this.width_=A}getUniforms(){return{u_lineColor:this.color.rgb,u_lineWidth:this.width}}}class Ph extends nB{type="AxesLayer";constructor(A){super();const{length:I,width:g}=A;this.addObject(MC({end:[I,0,0],width:g,color:[1,0,0]})),this.addObject(MC({end:[0,I,0],width:g,color:[0,1,0]})),this.addObject(MC({end:[0,0,I],width:g,color:[0,0,1]})),this.setState("ready")}update(){}}function MC(Q){const{end:A,width:I,color:g}=Q,B=new Th([[0,0,0],A]);return new Zi({geometry:B,color:g,width:I})}const Pi=32;function SB(Q,{visible:A,color:I,contrastLimits:g,opacity:B}){return A??=!0,I=I===void 0?FA.WHITE:FA.from(I),B=B===void 0?1:pI(B,0,1),Q!==null?g=Vh(g,Q):g===void 0&&(gA.debug("Channel","No texture provided, defaulting channel contrast limits to [0, 1]."),g=[0,1]),{visible:A,color:I,contrastLimits:g,opacity:B}}function dC(Q,A){if(A.length>Pi)throw new Error(`Maximum number of channels is ${Pi}`);return A.map(I=>SB(Q,I))}function Vi(Q,A){if(Q&&Q.length!==A)throw new Error(`channelProps length (${Q.length}) must match source channel count (${A}).`)}function Vh(Q,A){if(Q===void 0)return Sa(A);if(Q[1]<=Q[0])throw new Error(`Contrast limits must be strictly increasing: ${Q}.`);return Q}class Oi extends Ug{constructor(A,I,g,B){super();const C=[],E=[],i=g,o=B,a=i+1,D=o+1,s=A/i,y=I/o;for(let e=0;e<D;++e){const Y=e*y;for(let u=0;u<a;++u){const H=u*s,W=u/i,z=e/o,x=[H,Y,0],l=[0,0,1],Z=[W,z];C.push(...x,...l,...Z)}}for(let e=0;e<o;++e)for(let Y=0;Y<i;++Y){const u=Y+a*e,H=Y+a*(e+1),W=Y+1+a*(e+1),z=Y+1+a*e;E.push(u,H,z),E.push(H,W,z)}this.vertexData_=new Float32Array(C),this.indexData_=new Uint32Array(E),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}}class vi extends Wg{channels_;zTexCoord=.5;constructor(A,I,g,B=[]){super(),this.geometry=new Oi(A,I,1,1),this.setTexture(0,g),this.channels_=dC(g,B),this.programName=Oh(g)}get type(){return"ImageRenderable"}setChannelProps(A){this.channels_=dC(this.textures[0],A)}setChannelProperty(A,I,g){const B=SB(this.textures[0],{...this.channels_[A],[I]:g});this.channels_[A]=B}getUniforms(){const A=this.textures[0];if(!A)throw new Error("No texture set");const{color:I,contrastLimits:g,opacity:B}=this.channels_[0]??SB(A,{});return{u_imageSampler:0,u_color:I.rgb,u_valueOffset:-g[0],u_valueScale:1/(g[1]-g[0]),Opacity:B,u_zTexCoord:this.zTexCoord}}}function Oh(Q){switch(Q.dataType){case"byte":case"int":case"short":return"intScalarImage";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintScalarImage";case"float":return"floatScalarImage"}}function Xi(Q,A,I,g,B=3){switch(Q.type){case"pointerdown":{const C=Q.event;return xA(C.clientX,C.clientY)}case"pointerup":{if(!A)return A;const C=Q.event,E=xA(C.clientX,C.clientY);if(Ba(A,E)<B){if(!g)return null;const o=Q.worldPos;return o&&I(o).then(a=>{a!==null&&g({world:o,value:a})}).catch(a=>{gA.error("PointPicking",`Failed to read value: ${a}`)}),null}return A}case"pointercancel":return null;default:return A}}class HC{bins_=new Map;acquire(A){const g=this.bins_.get(A)?.pop();return g&&gA.debug("RenderablePool","Renderable object acquired"),g}release(A,I){let g=this.bins_.get(A);g||(g=[],this.bins_.set(A,g)),g.push(I),gA.debug("RenderablePool","Renderable object released")}clearAll(A){if(A)for(const I of this.bins_.values())I.forEach(A);this.bins_.clear()}}class qC extends nB{type="ImageLayer";source_;sliceCoords_;onPickValue_;visibleChunks_=new Map;pool_=new HC;initialChannelProps_;channelChangeCallbacks_=[];policy_;channelProps_;chunkStoreView_;pointerDownPos_=null;debugMode_=!1;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;wireframeColors_=[new FA(.6,.3,.3),new FA(.3,.6,.4),new FA(.4,.4,.7),new FA(.6,.5,.3)];constructor({source:A,sliceCoords:I,policy:g,channelProps:B,onPickValue:C,...E}){super(E),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.channelProps_=B,this.initialChannelProps_=B,this.onPickValue_=C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_);const I=this.chunkStoreView_.channelCount;if(Vi(this.channelProps_,I),I>1&&this.sliceCoords_.c!==void 0&&this.sliceCoords_.c.length>1)throw new Error(`ImageLayer requires exactly one channel in sliceCoords.c for multi-channel sources (found ${I} channels). Use one layer per channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Image rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)B.zTexCoord=this.zTexCoordForChunk(g)}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getImageForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}hasMultipleLODs(){return this.chunkStoreView_?this.chunkStoreView_.lodCount>1:!1}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>qC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(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,VB))}getImageForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setChannelProps(this.getChannelPropsForChunk(A)),this.updateImageChunk(g,A),g):this.createImage(A)}getChannelPropsForChunk(A){return this.channelProps_?[this.channelProps_[A.chunkIndex.c]??{}]:[{}]}createImage(A){const I=new vi(A.shape.x,A.shape.y,qI.createWithChunk(A),this.getChannelPropsForChunk(A));return I.zTexCoord=this.zTexCoordForChunk(A),this.updateImageChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}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])}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(HA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}get debugMode(){return this.debugMode_}set debugMode(A){this.debugMode_=A,this.visibleChunks_.forEach((I,g)=>{I.wireframeEnabled=this.debugMode_,this.debugMode_&&(I.wireframeColor=this.wireframeColors_[g.lod%this.wireframeColors_.length])})}get channelProps(){return this.channelProps_}setChannelProps(A){this.channelProps_=A,this.visibleChunks_.forEach((I,g)=>{I.setChannelProps(this.getChannelPropsForChunk(g))}),this.channelChangeCallbacks_.forEach(I=>{I()})}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===-1)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}function aQ(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class vh extends Ug{constructor(A,I,g,B,C,E){super();const i=[],o=[],a=Math.floor(B),D=Math.floor(C),s=Math.floor(E);this.buildFace("z","y","x",-1,-1,g,I,A,s,D,1,i,o),this.buildFace("z","y","x",1,-1,g,I,A,s,D,-1,i,o),this.buildFace("x","z","y",1,1,A,g,I,a,s,1,i,o),this.buildFace("x","z","y",1,-1,A,g,I,a,s,-1,i,o),this.buildFace("x","y","z",1,-1,A,I,g,a,D,1,i,o),this.buildFace("x","y","z",-1,-1,A,I,g,a,D,-1,i,o),this.vertexData_=new Float32Array(i),this.indexData_=new Uint32Array(o),this.addAttribute({type:"position",itemSize:3,offset:0}),this.addAttribute({type:"normal",itemSize:3,offset:3*Float32Array.BYTES_PER_ELEMENT}),this.addAttribute({type:"uv",itemSize:2,offset:6*Float32Array.BYTES_PER_ELEMENT})}buildFace(A,I,g,B,C,E,i,o,a,D,s,y,e){const Y=E/a,u=i/D,H=E/2,W=i/2,z=o/2*s,x=a+1,l=D+1,Z=y.length/8;for(let v=0;v<l;v++){const CA=-W+v*u;for(let sA=0;sA<x;sA++){const DA=-H+sA*Y,yA={x:0,y:0,z:0};yA[A]=DA*B,yA[I]=CA*C,yA[g]=z;const wA={x:0,y:0,z:0};wA[g]=s;const zA=sA/a,uA=1-v/D;y.push(yA.x,yA.y,yA.z,wA.x,wA.y,wA.z,zA,uA)}}for(let v=0;v<D;v++)for(let CA=0;CA<a;CA++){const sA=Z+CA+x*v,DA=Z+CA+x*(v+1),yA=Z+(CA+1)+x*(v+1),wA=Z+(CA+1)+x*v;e.push(sA,DA,wA,DA,yA,wA)}}}class ji extends Wg{voxelScale=nA(1,1,1);channels_;channelToTextureIndex_=new Map;loadedChannels_=new Set;constructor(){super(),this.geometry=new vh(1,1,1,1,1,1),this.cullFaceMode="front",this.depthTest=!1,this.channels_=[]}get type(){return"VolumeRenderable"}updateVolumeWithChunk(A){const I=A.chunkIndex.c,g=this.channelToTextureIndex_.get(I);g!==void 0?this.updateChannelTexture(g,A):this.addChannelTexture(I,A),this.loadedChannels_.add(I)}addChannelTexture(A,I){const g=qI.createWithChunk(I),B=this.textures.length;this.setTexture(B,g),this.channelToTextureIndex_.set(A,B);const C=Xh(g.dataType);if(this.programName&&this.programName!==C)throw new Error(`Volume renderable does not support multiple channels with different data types. Existing program: ${this.programName}, new channel data type: ${g.dataType} and program: ${C}`);this.programName=C}updateChannelTexture(A,I){const g=this.textures[A];if(!(g instanceof qI)){const B=qI.createWithChunk(I);this.setTexture(A,B);return}g.updateWithChunk(I)}clearLoadedChannels(){this.loadedChannels_=new Set}getUniforms(){const A=[0,0,0,0],I=[1,1,1,1,1,1,1,1,1,1,1,1],g=[0,0,0,0],B=[1,1,1,1],C=[1,1,1,1],E=[],i=Math.max(this.channels_.length,this.channelToTextureIndex_.size);for(let o=0;o<i&&E.length<4;o++){const a=this.channelToTextureIndex_.get(o);if(a===void 0||!this.loadedChannels_.has(o))continue;const D=this.textures[a],s=SB(D,this.channels_[o]||{});if(!s.visible)continue;const y=E.length;I[y*3]=s.color.rgb[0],I[y*3+1]=s.color.rgb[1],I[y*3+2]=s.color.rgb[2],E.push(a),g[y]=-s.contrastLimits[0],B[y]=1/(s.contrastLimits[1]-s.contrastLimits[0]),A[y]=1,C[y]=s.opacity}return E.reduce((o,a,D)=>(o[`u_channel${D}Sampler`]=a,o),{u_visible:A,"u_color[0]":I,u_valueOffset:g,u_valueScale:B,u_channelOpacity:C,u_voxelScale:[this.voxelScale[0],this.voxelScale[1],this.voxelScale[2]]})}getAvailableChannelTexture(A){if(A!==void 0){const g=this.channelToTextureIndex_.get(A);if(g!==void 0)return this.textures[g]}const I=this.channelToTextureIndex_.values().next().value;return I!==void 0?this.textures[I]:null}setChannelProps(A){this.channels_=dC(this.getAvailableChannelTexture(),A)}setChannelProperty(A,I,g){const B=SB(this.getAvailableChannelTexture(A),{...this.channels_[A],[I]:g});this.channels_[A]=B}}function Xh(Q){switch(Q){case"byte":case"int":case"short":return"intVolume";case"unsigned_short":case"unsigned_byte":case"unsigned_int":return"uintVolume";case"float":return"floatVolume"}}function jh(Q,A){const I=A.position,g=HA(),B=HA();return Q.sort((C,E)=>{gB(g,C.boundingBox.max,C.boundingBox.min),BB(g,g,.5),gB(B,E.boundingBox.max,E.boundingBox.min),BB(B,B,.5);const i=$C(I,g),o=$C(I,B);return i-o}),Q}const zh=2;class _h extends nB{type="VolumeLayer";source_;sliceCoords_;currentVolumes_=new Map;volumeToPoolKey_=new Map;pool_=new HC;initialChannelProps_;channelChangeCallbacks_=[];sourcePolicy_;chunkStoreView_;channelProps_;lastLoadedTime_=void 0;lastNumRenderedChannelChunks_=void 0;interactiveStepSizeScale_=1;debugShowWireframes_=!1;debugShowDegenerateRays=!1;relativeStepSize=1;opacityMultiplier=1;earlyTerminationAlpha=.99;get debugShowWireframes(){return this.debugShowWireframes_}set debugShowWireframes(A){if(this.debugShowWireframes_!==A){for(const I of this.currentVolumes_.values())I.wireframeEnabled=A;this.debugShowWireframes_=A}}set sourcePolicy(A){this.sourcePolicy_!==A&&(this.sourcePolicy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}setChannelProps(A){this.channelProps_=A;for(const I of this.currentVolumes_.values())I.setChannelProps(A);this.channelChangeCallbacks_.forEach(I=>{I()})}get channelProps(){return this.channelProps_}resetChannelProps(){this.initialChannelProps_!==void 0&&this.setChannelProps(this.initialChannelProps_)}addChannelChangeCallback(A){this.channelChangeCallbacks_.push(A)}removeChannelChangeCallback(A){const I=this.channelChangeCallbacks_.indexOf(A);if(I===void 0)throw new Error(`Callback to remove could not be found: ${A}`);this.channelChangeCallbacks_.splice(I,1)}constructor({source:A,sliceCoords:I,policy:g,channelProps:B}){super({blendMode:"premultiplied"}),this.source_=A,this.sliceCoords_=I,this.sourcePolicy_=g,this.initialChannelProps_=B,this.channelProps_=B,this.setState("initialized")}getOrCreateVolume(A,I){const g=this.currentVolumes_.get(A);if(g){for(const E of I)g.updateVolumeWithChunk(E);return g}const B=Iy(I[0]),C=this.pool_.acquire(B)??new ji;C.setChannelProps(this.channelProps_??[]),this.volumeToPoolKey_.set(C,B);for(const E of I)C.updateVolumeWithChunk(E);return this.updateVolumeTransform(C,I[0]),C}attach(A){this.chunkStoreView_=A.chunkManager.addView(this.source_,this.sourcePolicy_),Vi(this.channelProps_,this.chunkStoreView_.channelCount)}detach(A){for(const I of this.currentVolumes_.values())this.releaseAndRemoveVolume(I);this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}updateChunks(){if(!this.chunkStoreView_)return;const A=this.chunkStoreView_.getChunksToRender(),I=this.sliceCoords_.t??-1,g=Ay(A);if(this.lastLoadedTime_!==I||g.size!==this.currentVolumes_.size||this.lastNumRenderedChannelChunks_!==A.length){for(const[C,E]of this.currentVolumes_)g.has(C)||(this.releaseAndRemoveVolume(E),this.currentVolumes_.delete(C));this.clearObjects();for(const[C,E]of g){const i=this.getOrCreateVolume(C,E);i.wireframeEnabled=this.debugShowWireframes,this.currentVolumes_.set(C,i),this.addObject(i)}this.lastLoadedTime_=I,this.lastNumRenderedChannelChunks_=A.length,this.state!=="ready"&&this.setState("ready")}}updateVolumeTransform(A,I){const g={x:I.shape.x*I.scale.x,y:I.shape.y*I.scale.y,z:I.shape.z*I.scale.z};A.transform.setScale([g.x,g.y,g.z]),Bg(A.voxelScale,I.scale.x,I.scale.y,I.scale.z);const B={x:I.shape.x*I.scale.x/2,y:I.shape.y*I.scale.y/2,z:I.shape.z*I.scale.z/2};A.transform.setTranslation([I.offset.x+B.x,I.offset.y+B.y,I.offset.z+B.z])}releaseAndRemoveVolume(A){A.clearLoadedChannels(),this.pool_.release(this.volumeToPoolKey_.get(A),A),this.volumeToPoolKey_.delete(A)}update(A){if(!A||!this.chunkStoreView_)return;this.chunkStoreView_.updateChunksForVolume(this.sliceCoords_,A.camera.getViewProjection());const I=A.cameraControls?.isMoving??!1;this.interactiveStepSizeScale_=I?zh:1,this.updateChunks(),jh(this.objects,A.camera)}getUniforms(){return{u_debugShowDegenerateRays:Number(this.debugShowDegenerateRays),u_relativeStepSize:this.relativeStepSize*this.interactiveStepSizeScale_,u_opacityMultiplier:this.opacityMultiplier,u_earlyTerminationAlpha:this.earlyTerminationAlpha}}}function $h(Q){const{x:A,y:I,z:g,t:B}=Q.chunkIndex;return`${A}:${I}:${g}:${B}`}function Ay(Q){const A=new Map;for(const I of Q){const g=$h(I);let B=A.get(g);B||(B=[],A.set(g,B)),B.push(I)}return A}function Iy(Q){return[`lod${Q.lod}`,`shape${Q.shape.x}x${Q.shape.y}x${Q.shape.z}`,`align${Q.rowAlignmentBytes}`].join(":")}class DQ extends JQ{data_;width_;height_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g}set data(A){this.data_=A,this.needsUpdate=!0}get type(){return"Texture2D"}get data(){return this.data_}get width(){return this.width_}get height(){return this.height_}updateWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data!==g){if(this.width!=A.shape.x||this.height!=A.shape.y||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new DQ(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const gy=new Set(["unsigned_byte","unsigned_short","unsigned_int"]);function By(Q){if(Q.dataFormat!=="scalar")throw new Error(`Image data format must be scalar, instead found: ${Q.dataFormat}`);if(!gy.has(Q.dataType))throw new Error(`Image data type must be unsigned, instead found: ${Q.dataType}`);return Q}class zi extends Wg{outlineSelected_;selectedValue_;zTexCoord=.5;constructor(A){super(),this.geometry=new Oi(A.width,A.height,1,1),this.setTexture(0,By(A.imageData));const I=this.makeColorCycleTexture(A.colorMap.cycle);this.setTexture(1,I);const g=this.makeColorLookupTableTexture(A.colorMap.lookupTable);this.setTexture(2,g),this.outlineSelected_=A.outlineSelected??!1,this.selectedValue_=A.selectedValue??null,this.programName="labelImage"}get type(){return"LabelImageRenderable"}getUniforms(){return{u_imageSampler:0,u_colorCycleSampler:1,u_colorLookupTableSampler:2,u_outlineSelected:this.outlineSelected_?1:0,u_selectedValue:this.selectedValue_??-1,u_zTexCoord:this.zTexCoord}}setColorMap(A){this.setTexture(1,this.makeColorCycleTexture(A.cycle)),this.setTexture(2,this.makeColorLookupTableTexture(A.lookupTable))}setSelectedValue(A){this.selectedValue_=A}makeColorCycleTexture(A){const I=new Uint8Array(A.flatMap(B=>B.rgba).map(B=>Math.round(B*255))),g=new DQ(I,A.length,1);return g.dataFormat="rgba",g}makeColorLookupTableTexture(A){A===void 0?A=new Map([[0,FA.TRANSPARENT]]):A.has(0)||(A=new Map([[0,FA.TRANSPARENT],...A]));const I=Array.from(A.keys()),g=Array.from(A.values()).map(E=>E.packed),B=A.size,C=new Uint32Array(B*2);return C.set(I,0),C.set(g,B),new DQ(C,B,2)}}const Qy=[[1,.5,.5],[.5,1,.5],[.5,.5,1],[.5,1,1],[1,.5,1],[1,1,.5]];function Cy(Q){return Q=Q??new Map,new Map(Array.from(Q.entries()).map(([A,I])=>[A,FA.from(I)]))}function Ey(Q){return Q=Q??Qy,Q.map(FA.from)}class lC{lookupTable;cycle;constructor(A={}){this.lookupTable=Cy(A.lookupTable),this.cycle=Ey(A.cycle)}}class fC extends nB{type="LabelLayer";source_;sliceCoords_;onPickValue_;outlineSelected_;visibleChunks_=new Map;pool_=new HC;colorMap_;selectedValue_=null;policy_;chunkStoreView_;pointerDownPos_=null;static STALE_PRESENTATION_MS_=1e3;lastPresentationTimeStamp_;lastPresentationTimeCoord_;constructor({source:A,sliceCoords:I,policy:g,colorMap:B={},onPickValue:C,outlineSelected:E=!1,...i}){super(i),this.setState("initialized"),this.source_=A,this.policy_=g,this.sliceCoords_=I,this.colorMap_=new lC(B),this.onPickValue_=C,this.outlineSelected_=E}attach(A){if(this.chunkStoreView_=A.chunkManager.addView(this.source_,this.policy_),this.chunkStoreView_.channelCount>1)throw new Error(`LabelLayer does not support multi-channel sources (found ${this.chunkStoreView_.channelCount} channels). Label data must be single-channel.`)}detach(A){this.releaseAndRemoveChunks(this.visibleChunks_.keys()),this.clearObjects(),this.chunkStoreView_?.dispose(),this.chunkStoreView_=void 0}update(A){if(!A||!this.chunkStoreView_)return;const I=A.camera;if(I.type!=="OrthographicCamera")throw new Error("Label rendering currently supports only orthographic cameras. Update the implementation before using a perspective camera.");this.chunkStoreView_.updateChunksForImage(this.sliceCoords_,{worldViewRect:I.getWorldViewRect(),bufferWidthPx:A.getBufferRect().width}),this.updateChunks();for(const[g,B]of this.visibleChunks_)B.zTexCoord=this.zTexCoordForChunk(g)}updateChunks(){if(!this.chunkStoreView_||(this.state!=="ready"&&this.setState("ready"),this.visibleChunks_.size>0&&!this.chunkStoreView_.allVisibleFallbackLODLoaded()&&!this.isPresentationStale()))return;this.lastPresentationTimeStamp_=performance.now(),this.lastPresentationTimeCoord_=this.sliceCoords_.t;const A=this.chunkStoreView_.getChunksToRender(),I=new Set(A),g=Array.from(this.visibleChunks_.keys()).filter(B=>!I.has(B));this.releaseAndRemoveChunks(g),this.clearObjects();for(const B of A){if(B.state!=="loaded")continue;const C=this.getLabelForChunk(B);this.visibleChunks_.set(B,C),this.addObject(C)}}isPresentationStale(){return this.lastPresentationTimeStamp_===void 0?!1:performance.now()-this.lastPresentationTimeStamp_>fC.STALE_PRESENTATION_MS_}onEvent(A){this.pointerDownPos_=Xi(A,this.pointerDownPos_,I=>this.getValueAtWorld(I),this.outlineSelected_?I=>{this.setSelectedValue(I.value),this.onPickValue_?.(I)}:this.onPickValue_)}get colorMap(){return this.colorMap_}setColorMap(A){this.colorMap_=new lC(A),this.visibleChunks_.forEach(I=>{I.setColorMap(this.colorMap_)})}setSelectedValue(A){this.selectedValue_=A,this.visibleChunks_.forEach(I=>{I.setSelectedValue(this.selectedValue_)})}get sliceCoords(){return this.sliceCoords_}get source(){return this.source_}get imageSourcePolicy(){return this.policy_}set imageSourcePolicy(A){this.policy_!==A&&(this.policy_=A,this.chunkStoreView_&&this.chunkStoreView_.setImageSourcePolicy(A,VB))}get chunkStoreView(){return this.chunkStoreView_}get lastPresentationTimeCoord(){return this.lastPresentationTimeCoord_}async getValueAtWorld(A){const I=this.chunkStoreView_?.currentLOD??0;for(const g of[!0,!1])for(const[B,C]of this.visibleChunks_){if(B.lod===I!==g)continue;const E=await this.readValueFromChunk(B,C,A);if(E!==null)return E}return null}async readValueFromChunk(A,I,g){const B=SQ(HA(),g,I.transform.inverse),C=Math.floor(B[0]),E=Math.floor(B[1]);if(C<0||C>=A.shape.x||E<0||E>=A.shape.y)return null;const i=this.zSliceIndex(A);return await I.textures[0].readTexel?.(C,E,i)??null}getLabelForChunk(A){const I=this.visibleChunks_.get(A);if(I)return I;const g=this.pool_.acquire(aQ(A));return g?(g.textures[0].updateWithChunk(A),g.zTexCoord=this.zTexCoordForChunk(A),g.setColorMap(this.colorMap_),g.setSelectedValue(this.selectedValue_),this.updateLabelChunk(g,A),g):this.createLabel(A)}createLabel(A){const I=new zi({width:A.shape.x,height:A.shape.y,imageData:qI.createWithChunk(A),colorMap:this.colorMap_,outlineSelected:this.outlineSelected_,selectedValue:this.selectedValue_});return I.zTexCoord=this.zTexCoordForChunk(A),this.updateLabelChunk(I,A),I}zSliceIndex(A){const I=this.sliceCoords_.z;if(I===void 0)return 0;const g=(I-A.offset.z)/A.scale.z;return pI(Math.round(g),0,A.shape.z-1)}zTexCoordForChunk(A){return(this.zSliceIndex(A)+.5)/A.shape.z}updateLabelChunk(A,I){A.transform.setScale([I.scale.x,I.scale.y,1]),A.transform.setTranslation([I.offset.x,I.offset.y,0])}releaseAndRemoveChunks(A){for(const I of A){const g=this.visibleChunks_.get(I);g&&(this.pool_.release(aQ(I),g),this.visibleChunks_.delete(I))}}}class pC extends JQ{data_;width_;height_;depth_;constructor(A,I,g){super(),this.dataFormat="scalar",this.dataType=kg(A),this.data_=A,this.width_=I,this.height_=g,this.depth_=A.length/(I*g)}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 g=I??A.data;if(!g)throw new Error("Unable to update texture, chunk data is not initialized.");if(this.data===g)return;const B=A.shape.x,C=A.shape.y,E=g.length/(B*C);if(this.width!=B||this.height!=C||this.depth_!=E||this.dataType!=kg(g))throw new Error("Unable to update texture, texture buffer mismatch.");this.data=g}static createWithChunk(A,I){const g=I??A.data;if(!g)throw new Error("Unable to create texture, chunk data is not initialized.");const B=new pC(g,A.shape.x,A.shape.y);return B.unpackAlignment=A.rowAlignmentBytes,B}}const _i={circle:0,square:1,triangle:2};class iy extends Wg{constructor(A){super(),this.programName="points";const I=A.flatMap(B=>{const C=FA.from(B.color);return[B.position[0],B.position[1],B.position[2],C.r,C.g,C.b,C.a,B.size,_i[B.marker]]}),g=new Ug(I,[],"points");g.addAttribute({type:"position",itemSize:3,offset:0}),g.addAttribute({type:"color",itemSize:4,offset:g.strideBytes}),g.addAttribute({type:"size",itemSize:1,offset:g.strideBytes}),g.addAttribute({type:"marker",itemSize:1,offset:g.strideBytes}),this.geometry=g,this.setTexture(0,oy())}get type(){return"Points"}}let uC;function oy(){return uC||(uC=ay()),uC}function ay(){const Q=a=>{const D=new Float32Array(a*a);return D.fill(1),D},A=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)(s-a/2)**2+(y-a/2)**2<(a/2)**2&&(D[s*a+y]=1);return D},I=a=>{const D=new Float32Array(a*a);for(let s=0;s<a;s++)for(let y=0;y<a;y++)y>=(a-s)/2&&y<=(a+s)/2&&(D[s*a+y]=1);return D},C={circle:A(256),square:Q(256),triangle:I(256)},E=Object.keys(C).length,i=new Float32Array(E*65536);for(const[a,D]of Object.entries(C))i.set(D,_i[a]*65536);const o=new pC(i,256,256);return o.wrapR="clamp_to_edge",o.wrapS="clamp_to_edge",o.wrapT="clamp_to_edge",o}class $i{radius;phi;theta;constructor(A,I,g){this.radius=A,this.phi=I,this.theta=g}toVec3(){const A=Math.cos(this.theta);return nA(this.radius*Math.sin(this.phi)*A,-this.radius*Math.sin(this.theta),this.radius*Math.cos(this.phi)*A)}}const mC=-1,Ao=0,Dy=1,Io=.009,sy=.001,hy=9e-4,yy=.5,ty=60;class Gy{camera_;orbitVelocity_=new $i(0,0,0);panVelocity_=HA();currPos_;currCenter_=HA();dampingFactor_;currMouseButton_=mC;constructor(A,I){this.camera_=A,this.currPos_=new $i(I?.radius??1,I?.yaw??0,I?.pitch??0),I?.target&&rQ(this.currCenter_,I.target),this.dampingFactor_=pI(I?.dampingFactor??yy,0,1),this.updateCamera()}get isMoving(){return this.orbitVelocity_.phi!==0||this.orbitVelocity_.theta!==0||this.orbitVelocity_.radius!==0||this.panVelocity_[0]!==0||this.panVelocity_[1]!==0||this.panVelocity_[2]!==0}onEvent(A){switch(A.type){case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"wheel":this.onWheel(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){if(this.orbitVelocity_.phi===0&&this.orbitVelocity_.theta===0&&this.orbitVelocity_.radius===0&&NQ(this.panVelocity_,nA(0,0,0)))return;this.currPos_.phi+=this.orbitVelocity_.phi,this.currPos_.theta+=this.orbitVelocity_.theta,this.currPos_.radius+=this.orbitVelocity_.radius*this.currPos_.radius,gB(this.currCenter_,this.currCenter_,this.panVelocity_);const I=Math.PI/2-JA;this.currPos_.theta=pI(this.currPos_.theta,-I,I),this.currPos_.radius=Math.max(.01,this.currPos_.radius),this.updateCamera();const g=Math.pow(1-this.dampingFactor_,A*ty);this.orbitVelocity_.phi*=g,this.orbitVelocity_.theta*=g,this.orbitVelocity_.radius*=g,BB(this.panVelocity_,this.panVelocity_,g),this.cutoffLowVelocity()}onPointerDown(A){const I=A.event;this.currMouseButton_=I.button,I.target?.setPointerCapture?.(I.pointerId)}onPointerMove(A){if(this.currMouseButton_==mC)return;const I=A.event,g=I.movementX??0,B=I.movementY??0,C=this.currMouseButton_===Ao&&!I.shiftKey,E=this.currMouseButton_===Ao&&I.shiftKey||this.currMouseButton_===Dy;C&&this.orbit(g,B),E&&this.pan(g,B)}onWheel(A){const I=A.event;I.preventDefault();const g=I.deltaY??0;this.zoom(g)}onPointerEnd(A){this.currMouseButton_=mC;const I=A.event;I.target?.releasePointerCapture?.(I.pointerId)}orbit(A,I){this.orbitVelocity_.phi-=A*Io,this.orbitVelocity_.theta+=I*Io}pan(A,I){const g=this.currPos_.radius*sy,B=HA();_C(B,B,this.camera_.right,A),_C(B,B,this.camera_.up,I),BB(B,B,g),RQ(this.panVelocity_,this.panVelocity_,B)}zoom(A){this.orbitVelocity_.radius+=A*hy}updateCamera(){const A=gB(HA(),this.currCenter_,this.currPos_.toVec3());this.camera_.transform.setTranslation(A),this.camera_.transform.targetTo(this.currCenter_)}cutoffLowVelocity(){Math.abs(this.orbitVelocity_.phi)<JA&&(this.orbitVelocity_.phi=0),Math.abs(this.orbitVelocity_.theta)<JA&&(this.orbitVelocity_.theta=0),Math.abs(this.orbitVelocity_.radius)<JA&&(this.orbitVelocity_.radius=0),eQ(this.panVelocity_)<JA&&Oo(this.panVelocity_)}}class bg{normal;signedDistance;constructor(A=nA(0,1,0),I=0){this.normal=HI(A),this.signedDistance=I}set(A,I){this.normal=HI(A),this.signedDistance=I}signedDistanceToPoint(A){return AE(this.normal,A)+this.signedDistance}normalize(){const A=eQ(this.normal);if(A>0){const I=1/A;BB(this.normal,this.normal,I),this.signedDistance*=I}}}class wy{planes_;constructor(A){this.planes_=[new bg(HA(),0),new bg(HA(),0),new bg(HA(),0),new bg(HA(),0),new bg(HA(),0),new bg(HA(),0)],this.setWithViewProjection(A)}setWithViewProjection(A){const I=HA();this.planes_[0].set(Bg(I,A[3]+A[0],A[7]+A[4],A[11]+A[8]),A[15]+A[12]),this.planes_[1].set(Bg(I,A[3]-A[0],A[7]-A[4],A[11]-A[8]),A[15]-A[12]),this.planes_[2].set(Bg(I,A[3]-A[1],A[7]-A[5],A[11]-A[9]),A[15]-A[13]),this.planes_[3].set(Bg(I,A[3]+A[1],A[7]+A[5],A[11]+A[9]),A[15]+A[13]),this.planes_[4].set(Bg(I,A[3]+A[2],A[7]+A[6],A[11]+A[10]),A[15]+A[14]),this.planes_[5].set(Bg(I,A[3]-A[2],A[7]-A[6],A[11]-A[10]),A[15]-A[14]);for(const g of this.planes_)g.normalize()}intersectsWithBox3(A){const I=HA();for(const g of this.planes_){const B=g.normal;if(I[0]=B[0]>0?A.max[0]:A.min[0],I[1]=B[1]>0?A.max[1]:A.min[1],I[2]=B[2]>0?A.max[2]:A.min[2],g.signedDistanceToPoint(I)<0)return!1}return!0}}class go extends Wg{projectionMatrix_=hI();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])}getViewProjection(){return Rg(hI(),this.projectionMatrix,this.viewMatrix)}get frustum(){return new wy(this.getViewProjection())}pan(A){this.transform.addTranslation(A)}get position(){return this.transform.translation}clipToWorld(A){const I=HB(A[0],A[1],A[2],1),g=dB(hI(),this.projectionMatrix_),B=QB(cg(),I,g);zo(B,B,1/B[3]);const C=QB(cg(),B,this.transform.matrix);return nA(C[0],C[1],C[2])}}const Bo=1.77,Qo=128,Co=128/Bo;class Fy extends go{width_=Qo;height_=Co;viewportAspectRatio_=Bo;viewportSize_=[Qo,Co];constructor(A,I,g,B,C=0,E=100){super(),this.near_=C,this.far_=E,this.setFrame(A,I,B,g),this.updateProjectionMatrix()}get viewportSize(){return this.viewportSize_}setAspectRatio(A){this.viewportAspectRatio_=A,this.updateProjectionMatrix()}setFrame(A,I,g,B){this.width_=Math.abs(I-A),this.height_=Math.abs(B-g),this.updateProjectionMatrix();const C=.5*(A+I),E=.5*(g+B);this.transform.setTranslation([C,E,0]),this.transform.setScale([1,1,1]),this.transform.setRotation([0,0,0,1])}get type(){return"OrthographicCamera"}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);const I=1/A;this.transform.addScale([I,I,1])}getWorldViewRect(){let A=HB(-1,-1,0,1),I=HB(1,1,0,1);const g=dB(hI(),this.getViewProjection());return A=QB(cg(),A,g),I=QB(cg(),I,g),new QI(xA(A[0],A[1]),xA(I[0],I[1]))}updateProjectionMatrix(){const A=this.width_,I=this.height_,g=A/I;let B=.5*A,C=.5*I;this.viewportAspectRatio_>g?B*=this.viewportAspectRatio_/g:C*=g/this.viewportAspectRatio_,this.viewportSize_=[2*B,2*C],To(this.projectionMatrix_,-B,B,-C,C,this.near_,this.far_)}}const Eo=0;class ey{camera_;dragActive_=!1;dragStart_=HA();constructor(A){this.camera_=A}get isMoving(){return this.dragActive_}onEvent(A){switch(A.type){case"wheel":this.onWheel(A);break;case"pointerdown":this.onPointerDown(A);break;case"pointermove":this.onPointerMove(A);break;case"pointerup":case"pointercancel":this.onPointerEnd(A);break}}onUpdate(A){}onWheel(A){if(!A.worldPos||!A.clipPos)return;const I=A.event;I.preventDefault();const g=HI(A.worldPos),B=I.deltaY<0?1.05:.95;this.camera_.zoom(B);const C=this.camera_.clipToWorld(A.clipPos),E=RQ(HA(),g,C);this.camera_.pan(E)}onPointerDown(A){const I=A.event;!A.worldPos||I.button!==Eo||(this.dragStart_=HI(A.worldPos),this.dragActive_=!0,I.target?.setPointerCapture?.(I.pointerId))}onPointerMove(A){if(!this.dragActive_||!A.worldPos)return;const I=RQ(HA(),this.dragStart_,A.worldPos);this.camera_.pan(I)}onPointerEnd(A){const I=A.event;!this.dragActive_||I.button!==Eo||(this.dragActive_=!1,I.target?.releasePointerCapture?.(I.pointerId))}}const ry=60,ny=1.77,sQ=.1,xC=180-sQ;class Sy extends go{fov_;aspectRatio_;constructor(A={}){const{fov:I=ry,aspectRatio:g=ny,near:B=.1,far:C=1e4,position:E=nA(0,0,0)}=A;if(I<sQ||I>xC)throw new Error(`Invalid field of view: ${I}, must be in [${sQ}, ${xC}] degrees`);super(),this.fov_=I,this.aspectRatio_=g,this.near_=B,this.far_=C,this.transform.setTranslation(E),this.updateProjectionMatrix()}setAspectRatio(A){this.aspectRatio_=A,this.updateProjectionMatrix()}get type(){return"PerspectiveCamera"}get fov(){return this.fov_}zoom(A){if(A<=0)throw new Error(`Invalid zoom factor: ${A}`);this.fov_=Math.max(sQ,Math.min(xC,this.fov_/A)),this.updateProjectionMatrix()}updateProjectionMatrix(){mo(this.projectionMatrix_,Ho(this.fov),this.aspectRatio_,this.near_,this.far_)}}const io=["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"];function hQ(Q){Uy(Q);const A={x:Q.prefetch.x,y:Q.prefetch.y,z:Q.prefetch.z??0,t:Q.prefetch.t??0},I=Object.freeze(io.reduce((C,E)=>{const i=Q.priorityOrder.indexOf(E);return C[E]=i,C},{})),g={min:Q.lod?.min??0,max:Q.lod?.max??Number.MAX_SAFE_INTEGER,bias:Q.lod?.bias??.5},B={profile:Q.profile??"custom",prefetch:A,priorityOrder:Object.freeze([...Q.priorityOrder]),priorityMap:I,lod:g};return Object.freeze(B)}function Ny(Q={}){return hQ(TC({profile:"exploration",prefetch:{x:1,y:1,z:1,t:0},priorityOrder:["fallbackVisible","visibleCurrent","prefetchSpace","prefetchTime","fallbackBackground"]},Q))}function Ry(Q={}){return hQ(TC({profile:"playback",prefetch:{x:0,y:0,z:0,t:20},priorityOrder:["fallbackVisible","prefetchTime","visibleCurrent","fallbackBackground","prefetchSpace"]},Q))}function cy(Q={}){return hQ(TC({profile:"no-prefetch",prefetch:{x:0,y:0,z:0,t:0},priorityOrder:["fallbackVisible","visibleCurrent","fallbackBackground","prefetchSpace","prefetchTime"]},Q))}function Uy(Q){for(const[g,B]of Object.entries(Q.prefetch))if(B!==void 0&&B<0)throw new Error(`prefetch.${g} must be a non-negative number`);const A=Q.lod;if(A?.min!==void 0&&A?.max!==void 0&&A.min>A.max)throw new Error("lod.min must be <= lod.max");const I=Q.priorityOrder;if(I.length!==io.length||new Set(I).size!==I.length)throw new Error("priorityOrder must include all categories exactly once")}function TC(Q,A={}){return{profile:A.profile??Q.profile,prefetch:{...Q.prefetch,...A.prefetch??{}},lod:{...Q.lod,...A.lod??{}},priorityOrder:A.priorityOrder??Q.priorityOrder}}var WC=(()=>{for(var Q=new Uint8Array(128),A=0;A<64;A++)Q[A<26?A+65:A<52?A+71:A<62?A-4:A*4-205]=A;return I=>{for(var g=I.length,B=new Uint8Array((g-(I[g-1]=="=")-(I[g-2]=="="))*3/4|0),C=0,E=0;C<g;){var i=Q[I.charCodeAt(C++)],o=Q[I.charCodeAt(C++)],a=Q[I.charCodeAt(C++)],D=Q[I.charCodeAt(C++)];B[E++]=i<<2|o>>4,B[E++]=o<<4|a>>2,B[E++]=a<<6|D}return B}})(),ky=(typeof document<"u"&&document.currentScript&&document.currentScript.src,function(Q={}){var A=Q,I,g;A.ready=new Promise((G,r)=>{I=G,g=r});var B=Object.assign({},A),C="./this.program",E=A.print||console.log.bind(console),i=A.printErr||console.error.bind(console);Object.assign(A,B),B=null,A.thisProgram&&(C=A.thisProgram);var o;A.wasmBinary&&(o=A.wasmBinary),typeof WebAssembly!="object"&&yA("no native wasm support detected");var a,D=!1,s,y,e,Y,u,H,W,z;function x(){var G=a.buffer;A.HEAP8=s=new Int8Array(G),A.HEAP16=e=new Int16Array(G),A.HEAPU8=y=new Uint8Array(G),A.HEAPU16=Y=new Uint16Array(G),A.HEAP32=u=new Int32Array(G),A.HEAPU32=H=new Uint32Array(G),A.HEAPF32=W=new Float32Array(G),A.HEAPF64=z=new Float64Array(G)}var l=[],Z=[],v=[];function CA(){var G=A.preRun.shift();l.unshift(G)}var sA=0,DA=null;function yA(G){throw A.onAbort?.(G),G="Aborted("+G+")",i(G),D=!0,G=new WebAssembly.RuntimeError(G+". Build with -sASSERTIONS for more info."),g(G),G}var wA=G=>G.startsWith("data:application/octet-stream;base64,"),zA=G=>G.startsWith("file://"),uA;if(uA="blosc_codec.wasm",!wA(uA)){var NA=uA;uA=A.locateFile?A.locateFile(NA,""):""+NA}function mI(G){return Promise.resolve().then(()=>{if(G==uA&&o)var r=new Uint8Array(o);else throw"both async and sync fetching of the wasm failed";return r})}function kI(G,r,N){return mI(G).then(d=>WebAssembly.instantiate(d,r)).then(d=>d).then(N,d=>{i(`failed to asynchronously prepare wasm: ${d}`),yA(d)})}function xI(G,r){var N=uA;return o||typeof WebAssembly.instantiateStreaming!="function"||wA(N)||zA(N)||typeof fetch!="function"?kI(N,G,r):fetch(N,{credentials:"same-origin"}).then(d=>WebAssembly.instantiateStreaming(d,G).then(r,function(h){return i(`wasm streaming compile failed: ${h}`),i("falling back to ArrayBuffer instantiation"),kI(N,G,r)}))}var jI=G=>{for(;0<G.length;)G.shift()(A)};function zI(G){this.H=G-24,this.N=function(r){H[this.H+4>>2]=r},this.M=function(r){H[this.H+8>>2]=r},this.I=function(r,N){this.J(),this.N(r),this.M(N)},this.J=function(){H[this.H+16>>2]=0}}var $A=0,ZA,MA=G=>{for(var r="";y[G];)r+=ZA[y[G++]];return r},XA={},KA={},mA={},PA,hg=G=>{throw new PA(G)},yg,GI=(G,r)=>{function N(J){if(J=r(J),J.length!==d.length)throw new yg("Mismatched type converter count");for(var k=0;k<d.length;++k)dA(d[k],J[k])}var d=[];d.forEach(function(J){mA[J]=G});var h=Array(G.length),w=[],S=0;G.forEach((J,k)=>{KA.hasOwnProperty(J)?h[k]=KA[J]:(w.push(J),XA.hasOwnProperty(J)||(XA[J]=[]),XA[J].push(()=>{h[k]=KA[J],++S,S===w.length&&N(h)}))}),w.length===0&&N(h)};function aI(G,r,N={}){var d=r.name;if(!G)throw new PA(`type "${d}" must have a positive integer typeid pointer`);if(KA.hasOwnProperty(G)){if(N.P)return;throw new PA(`Cannot register type '${d}' twice`)}KA[G]=r,delete mA[G],XA.hasOwnProperty(G)&&(r=XA[G],delete XA[G],r.forEach(h=>h()))}function dA(G,r,N={}){if(!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");aI(G,r,N)}function DI(){this.F=[void 0],this.K=[]}var _A=new DI,TI=G=>{G>=_A.H&&--_A.get(G).L===0&&_A.J(G)},vg=G=>{switch(G){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return _A.I({L:1,value:G})}};function _I(G){return this.fromWireType(u[G>>2])}var tg=(G,r)=>{switch(r){case 4:return function(N){return this.fromWireType(W[N>>2])};case 8:return function(N){return this.fromWireType(z[N>>3])};default:throw new TypeError(`invalid float width (${r}): ${G}`)}},$I=(G,r)=>Object.defineProperty(r,"name",{value:G}),Xg=G=>{for(;G.length;){var r=G.pop();G.pop()(r)}};function jg(G){for(var r=1;r<G.length;++r)if(G[r]!==null&&G[r].G===void 0)return!0;return!1}function NB(G){var r=Function;if(!(r instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof r} which is not a function`);var N=$I(r.name||"unknownFunctionName",function(){});return N.prototype=r.prototype,N=new N,G=r.apply(N,G),G instanceof Object?G:N}var RB=(G,r)=>{if(A[G].C===void 0){var N=A[G];A[G]=function(){if(!A[G].C.hasOwnProperty(arguments.length))throw new PA(`Function '${r}' called with an invalid number of arguments (${arguments.length}) - expects one of (${A[G].C})!`);return A[G].C[arguments.length].apply(this,arguments)},A[G].C=[],A[G].C[N.O]=N}},Gg=(G,r,N)=>{if(A.hasOwnProperty(G)){if(N===void 0||A[G].C!==void 0&&A[G].C[N]!==void 0)throw new PA(`Cannot register public name '${G}' twice`);if(RB(G,G),A.hasOwnProperty(N))throw new PA(`Cannot register multiple overloads of a function with the same number of arguments (${N})!`);A[G].C[N]=r}else A[G]=r,N!==void 0&&(A[G].S=N)},wg=(G,r)=>{for(var N=[],d=0;d<G;d++)N.push(H[r+4*d>>2]);return N},Fg,zg=(G,r)=>{var N=[];return function(){if(N.length=0,Object.assign(N,arguments),G.includes("j")){var d=A["dynCall_"+G];d=N&&N.length?d.apply(null,[r].concat(N)):d.call(null,r)}else d=Fg.get(r).apply(null,N);return d}},_g=(G,r)=>{G=MA(G);var N=G.includes("j")?zg(G,r):Fg.get(r);if(typeof N!="function")throw new PA(`unknown function pointer with signature ${G}: ${r}`);return N},eg,rg=G=>{G=O(G);var r=MA(G);return p(G),r},cB=(G,r)=>{function N(w){h[w]||KA[w]||(mA[w]?mA[w].forEach(N):(d.push(w),h[w]=!0))}var d=[],h={};throw r.forEach(N),new eg(`${G}: `+d.map(rg).join([", "]))},UB=G=>{G=G.trim();const r=G.indexOf("(");return r!==-1?G.substr(0,r):G},$g=(G,r,N)=>{switch(r){case 1:return N?d=>s[d>>0]:d=>y[d>>0];case 2:return N?d=>e[d>>1]:d=>Y[d>>1];case 4:return N?d=>u[d>>2]:d=>H[d>>2];default:throw new TypeError(`invalid integer width (${r}): ${G}`)}};function ng(G){return this.fromWireType(H[G>>2])}for(var Ag=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Sg=(G,r,N)=>{var d=r+N;for(N=r;G[N]&&!(N>=d);)++N;if(16<N-r&&G.buffer&&Ag)return Ag.decode(G.subarray(r,N));for(d="";r<N;){var h=G[r++];if(h&128){var w=G[r++]&63;if((h&224)==192)d+=String.fromCharCode((h&31)<<6|w);else{var S=G[r++]&63;h=(h&240)==224?(h&15)<<12|w<<6|S:(h&7)<<18|w<<12|S<<6|G[r++]&63,65536>h?d+=String.fromCharCode(h):(h-=65536,d+=String.fromCharCode(55296|h>>10,56320|h&1023))}}else d+=String.fromCharCode(h)}return d},AB=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,kB=(G,r)=>{for(var N=G>>1,d=N+r/2;!(N>=d)&&Y[N];)++N;if(N<<=1,32<N-G&&AB)return AB.decode(y.subarray(G,N));for(N="",d=0;!(d>=r/2);++d){var h=e[G+2*d>>1];if(h==0)break;N+=String.fromCharCode(h)}return N},LB=(G,r,N)=>{if(N??=2147483647,2>N)return 0;N-=2;var d=r;N=N<2*G.length?N/2:G.length;for(var h=0;h<N;++h)e[r>>1]=G.charCodeAt(h),r+=2;return e[r>>1]=0,r-d},JB=G=>2*G.length,IB=(G,r)=>{for(var N=0,d="";!(N>=r/4);){var h=u[G+4*N>>2];if(h==0)break;++N,65536<=h?(h-=65536,d+=String.fromCharCode(55296|h>>10,56320|h&1023)):d+=String.fromCharCode(h)}return d},Ig=(G,r,N)=>{if(N??=2147483647,4>N)return 0;var d=r;N=d+N-4;for(var h=0;h<G.length;++h){var w=G.charCodeAt(h);if(55296<=w&&57343>=w){var S=G.charCodeAt(++h);w=65536+((w&1023)<<10)|S&1023}if(u[r>>2]=w,r+=4,r+4>N)break}return u[r>>2]=0,r-d},Ng=G=>{for(var r=0,N=0;N<G.length;++N){var d=G.charCodeAt(N);55296<=d&&57343>=d&&++N,r+=4}return r},iI={},LI=()=>{if(!oI){var G={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:C||"./this.program"},r;for(r in iI)iI[r]===void 0?delete G[r]:G[r]=iI[r];var N=[];for(r in G)N.push(`${r}=${G[r]}`);oI=N}return oI},oI,pA=[null,[],[]],JI=Array(256),jA=0;256>jA;++jA)JI[jA]=String.fromCharCode(jA);ZA=JI,PA=A.BindingError=class extends Error{constructor(G){super(G),this.name="BindingError"}},yg=A.InternalError=class extends Error{constructor(G){super(G),this.name="InternalError"}},Object.assign(DI.prototype,{get(G){return this.F[G]},has(G){return this.F[G]!==void 0},I(G){var r=this.K.pop()||this.F.length;return this.F[r]=G,r},J(G){this.F[G]=void 0,this.K.push(G)}}),_A.F.push({value:void 0},{value:null},{value:!0},{value:!1}),_A.H=_A.F.length,A.count_emval_handles=()=>{for(var G=0,r=_A.H;r<_A.F.length;++r)_A.F[r]!==void 0&&++G;return G},eg=A.UnboundTypeError=((G,r)=>{var N=$I(r,function(d){this.name=r,this.message=d,d=Error(d).stack,d!==void 0&&(this.stack=this.toString()+`
|
|
4214
4214
|
`+d.replace(/^Error(:[^\n]*)?\n/,""))});return N.prototype=Object.create(G.prototype),N.prototype.constructor=N,N.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},N})(Error,"UnboundTypeError");var n={p:(G,r,N)=>{throw new zI(G).I(r,N),$A=G,$A},o:()=>{},l:(G,r,N,d)=>{r=MA(r),dA(G,{name:r,fromWireType:function(h){return!!h},toWireType:function(h,w){return w?N:d},argPackAdvance:8,readValueFromPointer:function(h){return this.fromWireType(y[h])},G:null})},k:(G,r)=>{r=MA(r),dA(G,{name:r,fromWireType:N=>{if(!N)throw new PA("Cannot use deleted val. handle = "+N);var d=_A.get(N).value;return TI(N),d},toWireType:(N,d)=>vg(d),argPackAdvance:8,readValueFromPointer:_I,G:null})},i:(G,r,N)=>{r=MA(r),dA(G,{name:r,fromWireType:d=>d,toWireType:(d,h)=>h,argPackAdvance:8,readValueFromPointer:tg(r,N),G:null})},d:(G,r,N,d,h,w,S)=>{var J=wg(r,N);G=MA(G),G=UB(G),h=_g(d,h),Gg(G,function(){cB(`Cannot call ${G} due to unbound types`,J)},r-1),GI(J,function(k){var m=G,b=G;k=[k[0],null].concat(k.slice(1));var V=h,T=k.length;if(2>T)throw new PA("argTypes array size mismatch! Must at least get return value and 'this' types!");var BA=k[1]!==null&&!1,iA=jg(k),AI=k[0].name!=="void";V=[hg,V,w,Xg,k[0],k[1]];for(var hA=0;hA<T-2;++hA)V.push(k[hA+2]);if(!iA)for(hA=BA?1:2;hA<k.length;++hA)k[hA].G!==null&&V.push(k[hA].G);iA=jg(k),hA=k.length;var VA="",SI="";for(T=0;T<hA-2;++T)VA+=(T!==0?", ":"")+"arg"+T,SI+=(T!==0?", ":"")+"arg"+T+"Wired";VA=`
|
|
4215
4215
|
return function (${VA}) {
|
|
4216
4216
|
if (arguments.length !== ${hA-2}) {
|