@vitessce/comparative 0.0.1 → 3.9.4

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -18
  3. package/dist/OrbitControls-DWelGoKt.js +6202 -0
  4. package/dist/ReactNeuroglancer-BXqSFHUD.js +43478 -0
  5. package/dist/blosc-DKW2fp0s.js +716 -0
  6. package/dist/chunk-INHXZS53-DiyuLb3Z.js +14 -0
  7. package/dist/deflate-DYtYzuI-.js +10 -0
  8. package/dist/higlass-BBW7WDEo.js +92988 -0
  9. package/dist/index-CMozjas4.js +6178 -0
  10. package/dist/index-Ce5JOk5t.js +283191 -0
  11. package/dist/index-Dmp8XDxB.js +3100 -0
  12. package/dist/index.min.js +43 -0
  13. package/dist/jpeg-BCnMyPcM.js +533 -0
  14. package/dist/lerc-IcvUBGkp.js +1032 -0
  15. package/dist/lz4-D5NbssRf.js +640 -0
  16. package/dist/lzw-BuqKQps7.js +84 -0
  17. package/dist/packbits-D-hnPOOn.js +24 -0
  18. package/dist/pako.esm-D68R8YXe.js +1071 -0
  19. package/dist/raw-CjTblrBX.js +9 -0
  20. package/dist/troika-three-text.esm-DZiaLX4L.js +4192 -0
  21. package/dist/webimage-CAVBEZTP.js +19 -0
  22. package/dist/zstd-DoGJTjDa.js +603 -0
  23. package/dist-tsc/BiomarkerSelect.d.ts +2 -0
  24. package/dist-tsc/BiomarkerSelect.d.ts.map +1 -0
  25. package/dist-tsc/BiomarkerSelect.js +65 -0
  26. package/dist-tsc/ComparativeConfig.d.ts +12 -0
  27. package/dist-tsc/ComparativeConfig.d.ts.map +1 -0
  28. package/dist-tsc/ComparativeConfig.js +326 -0
  29. package/dist-tsc/ControlledComparative.d.ts +30 -0
  30. package/dist-tsc/ControlledComparative.d.ts.map +1 -0
  31. package/dist-tsc/ControlledComparative.js +95 -0
  32. package/dist-tsc/UncontrolledComparative.d.ts +10 -0
  33. package/dist-tsc/UncontrolledComparative.d.ts.map +1 -0
  34. package/dist-tsc/UncontrolledComparative.js +50 -0
  35. package/dist-tsc/index.d.ts +7 -0
  36. package/dist-tsc/index.d.ts.map +1 -0
  37. package/dist-tsc/index.js +14 -0
  38. package/package.json +53 -16
  39. package/src/BiomarkerSelect.jsx +107 -0
  40. package/src/ComparativeConfig.jsx +562 -0
  41. package/src/ControlledComparative.jsx +140 -0
  42. package/src/UncontrolledComparative.jsx +88 -0
  43. package/src/index.js +18 -0
  44. package/dist/index.d.ts +0 -4
  45. package/dist/index.js +0 -9
@@ -0,0 +1,3100 @@
1
+ import { aw as n, ax as we, ay as se, ar as ue, as as ze, az as _e, l as he, aA as ke, aB as Ie, m as re, aC as le, e as C, V as b, ag as Z, ae as De, aq as D, aD as Me, aE as Pe, av as Ae, W as Be, ad as Ne, z as Ue, aF as Le, aG as X, ao as B, aH as Oe, am as Fe } from "./index-Ce5JOk5t.js";
2
+ import { useRef as M, useState as fe, useMemo as de, useEffect as $, Suspense as Ve } from "react";
3
+ import { u as ve, a as Ge, O as me, C as qe } from "./OrbitControls-DWelGoKt.js";
4
+ const S = 32, A = 64, V = 64, ce = 4, oe = A * V * ce, ge = A * S, xe = V * S, pe = ce * S, F = {
5
+ NOT_STARTED: "not_started",
6
+ IN_PROGRESS: "in_progress",
7
+ COMPLETE: "complete",
8
+ FAILED: "failed"
9
+ };
10
+ function z(h) {
11
+ se(le.DEBUG) && console.warn(`%cDM: ${h}`, "background: blue; color: white; padding: 2px; border-radius: 3px;");
12
+ }
13
+ function Ze(h) {
14
+ return h.map((t) => {
15
+ const { dims: e } = t;
16
+ return [
17
+ // Other spatial-accelerated code assumes TCZYX dimension order
18
+ e.t,
19
+ // TODO: standardize lowercase/uppercase dim names at store-level
20
+ e.c,
21
+ // TODO: handle case when dimension(s) are missing
22
+ e.z,
23
+ e.y,
24
+ e.x
25
+ ];
26
+ });
27
+ }
28
+ function Xe(h) {
29
+ return h.map((t) => {
30
+ const e = [
31
+ t.depth,
32
+ // z
33
+ t.height,
34
+ // y
35
+ t.width
36
+ // x
37
+ ];
38
+ return [
39
+ Math.ceil((e[0] || 1) / S),
40
+ Math.ceil((e[1] || 1) / S),
41
+ Math.ceil((e[2] || 1) / S)
42
+ ];
43
+ });
44
+ }
45
+ function je(h, t) {
46
+ n.debug("_initMRMCPT", h, t);
47
+ const e = {
48
+ channelOffsets: [
49
+ [0, 0, 1],
50
+ [0, 1, 0],
51
+ [0, 1, 1],
52
+ [1, 0, 0],
53
+ [1, 0, 1],
54
+ [1, 1, 0],
55
+ [1, 1, 1]
56
+ ],
57
+ anchors: [],
58
+ offsets: [],
59
+ xExtent: 0,
60
+ // includes the offset inclusive
61
+ yExtent: 0,
62
+ // includes the offset inclusive
63
+ zExtent: 0,
64
+ // includes the offset inclusive
65
+ z0Extent: 0,
66
+ // l0 z extent
67
+ zTotal: 0
68
+ // original z extent plus the l0 z extent times the channel count
69
+ };
70
+ e.xExtent = 1, e.yExtent = 1, e.zExtent = 1;
71
+ const i = h[0][0];
72
+ e.z0Extent = i, e.lowestDataRes = h.length - 1;
73
+ for (let c = h.length - 1; c > 0; c--)
74
+ e.anchors.push([
75
+ e.xExtent,
76
+ e.yExtent,
77
+ e.zExtent
78
+ ]), e.xExtent += h[c][2], e.yExtent += h[c][1], e.zExtent += h[c][0];
79
+ e.anchors.push([0, 0, e.zExtent]), e.anchors.reverse(), e.zTotal = e.zExtent + t * i;
80
+ const a = new Uint8Array(ge * xe * pe);
81
+ a.fill(0);
82
+ const r = new Uint32Array(e.xExtent * e.yExtent * e.zTotal);
83
+ r.fill(0);
84
+ const o = new ue(a, ge, xe, pe);
85
+ o.format = ze, o.type = _e, o.internalFormat = "R8", o.minFilter = he, o.magFilter = he, o.generateMipmaps = !1, o.needsUpdate = !0;
86
+ const l = new ue(r, e.xExtent, e.yExtent, e.zTotal);
87
+ return l.format = ke, l.type = Ie, l.internalFormat = "R32UI", l.minFilter = re, l.magFilter = re, l.generateMipmaps = !1, l.needsUpdate = !0, n.debug("_initMRMCPT", e, l, o), {
88
+ PT: e,
89
+ ptTHREE: l,
90
+ bcTHREE: o
91
+ };
92
+ }
93
+ function Ye(h, t, e, i, a) {
94
+ const r = (o) => Math.max(0, Math.min(127, Math.floor(o / 2)));
95
+ return (1 << 31 | 1 << 30 | r(h) << 23 | r(t) << 16 | (e & 63) << 10 | (i & 63) << 4 | a & 15) >>> 0;
96
+ }
97
+ function He(h, t, e, i) {
98
+ const { PT_zExtent: a, PT_z0Extent: r, PT_anchors: o } = i;
99
+ let l = -1, c = -1, s = -1, g = -1, p = -1;
100
+ if (e >= a)
101
+ c = 0, s = h, g = t, p = (e - a) % r, l = Math.floor((e - a) / r);
102
+ else
103
+ for (let u = 1; u < o.length; u++)
104
+ if (!(h < o[u][0] && t < o[u][1] && e < o[u][2])) {
105
+ c = u;
106
+ const d = [0, 0, 0];
107
+ h >= o[u][0] && (d[0] = 1), t >= o[u][1] && (d[1] = 1), e >= o[u][2] && (d[2] = 1);
108
+ const v = d[0] << 2 | d[1] << 1 | d[2];
109
+ l = Math.max(1, Math.min(7, v)) - 1;
110
+ const f = d.map((x, _) => x * o[u][_]);
111
+ s = h - f[0], g = t - f[1], p = e - f[2];
112
+ break;
113
+ }
114
+ return {
115
+ channel: l,
116
+ resolution: c,
117
+ x: s,
118
+ y: g,
119
+ z: p
120
+ };
121
+ }
122
+ function Ke(h, t) {
123
+ const e = /* @__PURE__ */ new Map();
124
+ for (let a = 0; a < h.length; a += 4) {
125
+ const r = h[a], o = h[a + 1], l = h[a + 2], c = h[a + 3];
126
+ if ((r | o | l | c) === 0)
127
+ continue;
128
+ const s = (r << 24 | o << 16 | l << 8 | c) >>> 0;
129
+ e.set(s, (e.get(s) || 0) + 1);
130
+ }
131
+ return { requests: [...e.entries()].sort((a, r) => r[1] - a[1]).slice(0, t).map(([a]) => ({
132
+ x: a >> 22 & 1023,
133
+ y: a >> 12 & 1023,
134
+ z: a & 4095
135
+ })), origRequestCount: e.size };
136
+ }
137
+ class We {
138
+ constructor(t) {
139
+ z("CLASS INITIALIZING"), n.debug("VolumeDataManager constructor", { glParam: t, glParamContext: t.getContext?.() });
140
+ const e = t.getContext?.() || t, i = t;
141
+ e.domElement && e.getContext ? this.gl = e.getContext() : e.isWebGLRenderer ? this.gl = e.getContext() : this.gl = e, this.renderer = i, (!this.gl || typeof this.gl.getParameter != "function") && (n.debug("Unable to get WebGL context, using mock context"), this.gl = {
142
+ getParameter: (a) => ({
143
+ MAX_TEXTURE_SIZE: 4096,
144
+ MAX_3D_TEXTURE_SIZE: 256,
145
+ MAX_RENDERBUFFER_SIZE: 4096,
146
+ MAX_UNIFORM_BUFFER_BINDINGS: 16
147
+ })[a] || 0,
148
+ isContextLost: () => !1,
149
+ MAX_TEXTURE_SIZE: "MAX_TEXTURE_SIZE",
150
+ MAX_3D_TEXTURE_SIZE: "MAX_3D_TEXTURE_SIZE",
151
+ MAX_RENDERBUFFER_SIZE: "MAX_RENDERBUFFER_SIZE",
152
+ MAX_UNIFORM_BUFFER_BINDINGS: "MAX_UNIFORM_BUFFER_BINDINGS"
153
+ }), this._originalGlParam = t, this._isContextLost = !1, this._contextRestoredCallbacks = [], this.gl && this.gl.canvas && (this.gl.canvas.addEventListener("webglcontextlost", this._handleContextLost.bind(this)), this.gl.canvas.addEventListener("webglcontextrestored", this._handleContextRestored.bind(this))), n.debug("GL CONSTANTS"), n.debug(this.gl), n.debug(this.gl.TEXTURE0), n.debug(this.gl.textures), n.debug("RENDERER"), n.debug(this.renderer), this.deviceLimits = {
154
+ maxTextureSize: this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE),
155
+ max3DTextureSize: this.gl.getParameter(this.gl.MAX_3D_TEXTURE_SIZE),
156
+ maxRenderbufferSize: this.gl.getParameter(this.gl.MAX_RENDERBUFFER_SIZE),
157
+ maxUniformBufferBindings: this.gl.getParameter(this.gl.MAX_UNIFORM_BUFFER_BINDINGS)
158
+ }, this.zarrStore = {
159
+ resolutions: null,
160
+ // 6 (the number of resolutions aka. pyramid levels in the file)
161
+ chunkSize: [],
162
+ // [32, 32, 32]
163
+ shapes: [],
164
+ // [[795, 1024, 1024], ..., [64, 64, 64], [32, 32, 32]]
165
+ arrays: [],
166
+ // [array0, array1, array2, array3, array4, array5]
167
+ dtype: "",
168
+ // 'uint8'
169
+ physicalSizeTotal: [],
170
+ // [795 x 0.0688, 1024 x 0.03417, 1024 x 0.03417]
171
+ physicalSizeVoxel: [],
172
+ // [0.0688, 0.03417, 0.03417]
173
+ brickLayout: [],
174
+ // [[25, 32, 32],[13, 16, 16], ..., [2,2,2],[1,1,1]]
175
+ // store: '', // ref to this.store
176
+ // group: '', // ref to this.group
177
+ channelCount: 1,
178
+ // MAX 7 TODO: get from zarr metadata
179
+ scales: [],
180
+ // downsample ratios, [x,y,z] per resolution level
181
+ lowestDataRes: 0
182
+ // lowest resolution level with data
183
+ }, this.ptTHREE = null, this.bcTHREE = null, this.channels = {
184
+ maxChannels: 7,
185
+ // lower when dataset has fewer, dictates page table size
186
+ zarrMappings: [],
187
+ // stores the zarr channel index for every one of the up to 7 channels
188
+ colorMappings: [],
189
+ // stores the PT slot for every color
190
+ downsampleMin: [],
191
+ // stores the downsample min for every one of the up to 7 channels
192
+ downsampleMax: []
193
+ // stores the downsample max for every one of the up to 7 channels
194
+ }, this.PT = {
195
+ channelOffsets: [
196
+ [0, 0, 1],
197
+ [0, 1, 0],
198
+ [0, 1, 1],
199
+ [1, 0, 0],
200
+ [1, 0, 1],
201
+ [1, 1, 0],
202
+ [1, 1, 1]
203
+ ],
204
+ anchors: [],
205
+ offsets: [],
206
+ xExtent: 0,
207
+ // includes the offset inclusive
208
+ yExtent: 0,
209
+ // includes the offset inclusive
210
+ zExtent: 0,
211
+ // includes the offset inclusive
212
+ z0Extent: 0,
213
+ // l0 z extent
214
+ zTotal: 0
215
+ // original z extent plus the l0 z extent times the channel count
216
+ }, this.bricksEverLoaded = /* @__PURE__ */ new Set(), this.isBusy = !1, this.BCTimeStamps = new Array(oe).fill(0), this.BCMinMax = new Array(oe).fill([0, 0]), this.BCFull = !1, this.BCUnusedIndex = 0, this.bc2pt = new Array(oe).fill(null), this.LRUStack = [], this.triggerUsage = !0, this.triggerRequest = !1, this.timeStamp = 0, this.k = 40, this.noNewRequests = !1, this.manuallyStopped = !1, this.needsBailout = !1, this.initStatus = F.NOT_STARTED, this.initError = null, this._lastChannelConfig = null, this.currentRequestCount = 0, this.totalBricksRequested = 0, z("VolumeDataManager constructor complete");
217
+ }
218
+ /**
219
+ * Get loading progress information
220
+ * @returns {Object} Loading progress with bricksLoaded, totalBricks, isLoading, and percentage
221
+ */
222
+ getLoadingProgress() {
223
+ const t = this.bricksEverLoaded.size, e = !this.noNewRequests && this.currentRequestCount > 0, i = this.totalBricksRequested > 0 ? (this.totalBricksRequested - this.currentRequestCount) / this.totalBricksRequested * 100 : 0;
224
+ return {
225
+ bricksLoaded: t,
226
+ currentRequestCount: this.currentRequestCount,
227
+ totalBricksRequested: this.totalBricksRequested,
228
+ isLoading: e,
229
+ percentage: i,
230
+ noNewRequests: this.noNewRequests
231
+ };
232
+ }
233
+ /**
234
+ * Manually stop loading and render at highest resolution
235
+ */
236
+ stopLoading() {
237
+ n.debug("Manually stopping data loading"), this.noNewRequests = !0, this.manuallyStopped = !0, this.needsBailout = !0, this.currentRequestCount = 0, this.totalBricksRequested = 0;
238
+ }
239
+ /**
240
+ * Manually restart loading
241
+ */
242
+ restartLoading() {
243
+ n.debug("Manually restarting data loading"), this.noNewRequests = !1, this.manuallyStopped = !1, this.needsBailout = !1, this.triggerUsage = !0, this.currentRequestCount = 0, this.totalBricksRequested = 0;
244
+ }
245
+ /**
246
+ * Handle WebGL context loss
247
+ */
248
+ _handleContextLost(t) {
249
+ z("CONTEXT LOST"), n.warn("WebGL context lost, preventing default and setting flag"), t.preventDefault(), this._isContextLost = !0, this.channels && this.channels.zarrMappings && (this._lastChannelConfig = {
250
+ zarrMappings: [...this.channels.zarrMappings],
251
+ colorMappings: [...this.channels.colorMappings],
252
+ downsampleMin: [...this.channels.downsampleMin],
253
+ downsampleMax: [...this.channels.downsampleMax]
254
+ });
255
+ }
256
+ /**
257
+ * Handle WebGL context restoration
258
+ */
259
+ _handleContextRestored(t) {
260
+ if (z("CONTEXT RESTORED"), n.warn("WebGL context restored, reinitializing textures"), this._isContextLost = !1, this._originalGlParam && this._originalGlParam.getContext && (this.gl = this._originalGlParam.getContext()), this._lastChannelConfig && (this.channels.zarrMappings = [...this._lastChannelConfig.zarrMappings], this.channels.colorMappings = [...this._lastChannelConfig.colorMappings], this.channels.downsampleMin = [...this._lastChannelConfig.downsampleMin], this.channels.downsampleMax = [...this._lastChannelConfig.downsampleMax], n.debug("Restored channel configuration after context loss")), this.PT && this.zarrStore && this.zarrStore.brickLayout)
261
+ try {
262
+ this.initMRMCPT(), n.debug("Successfully reinitialized MRMCPT after context restoration");
263
+ } catch (e) {
264
+ n.error("Failed to reinitialize MRMCPT after context restoration:", e);
265
+ }
266
+ this._contextRestoredCallbacks.forEach((e) => {
267
+ try {
268
+ e();
269
+ } catch (i) {
270
+ n.error("Error in context restored callback:", i);
271
+ }
272
+ });
273
+ }
274
+ /**
275
+ * Check if WebGL context is lost
276
+ */
277
+ isContextLost() {
278
+ return this._isContextLost ? !0 : this.gl && typeof this.gl.isContextLost == "function" ? this.gl.isContextLost() : !1;
279
+ }
280
+ /**
281
+ * Register a callback to be called when context is restored
282
+ */
283
+ onContextRestored(t) {
284
+ typeof t == "function" && this._contextRestoredCallbacks.push(t);
285
+ }
286
+ initImages(t, e) {
287
+ z("INIT IMAGES"), this.images = t, this.imageLayerScopes = e;
288
+ }
289
+ /**
290
+ * Initialize the VolumeDataManager with Zarr store details and device limits
291
+ * This should be called ONCE at website initialization
292
+ * TODO(mark): merge this with the constructor?
293
+ * @returns {Promise<Object>} Object with Zarr store details and device limits
294
+ */
295
+ async init(t) {
296
+ if (z("INIT()"), this.initStatus !== F.NOT_STARTED)
297
+ return n.debug("VolumeDataManager init() was called more than once!"), this.initStatus === F.COMPLETE ? {
298
+ success: !0,
299
+ deviceLimits: this.deviceLimits,
300
+ zarrStore: this.zarrStore,
301
+ // physicalScale: this.physicalScale,
302
+ physicalSizeTotal: this.zarrStore.physicalSizeTotal,
303
+ physicalSizeVoxel: this.zarrStore.physicalSizeVoxel,
304
+ error: null
305
+ } : this.initStatus === F.FAILED ? {
306
+ success: !1,
307
+ error: this.initError || "Unknown initialization error"
308
+ } : {
309
+ success: !1,
310
+ pending: !0,
311
+ error: "Initialization in progress"
312
+ };
313
+ this.initStatus = F.IN_PROGRESS, z("INIT() IN PROGRESS");
314
+ try {
315
+ const e = this.images?.[this.imageLayerScopes?.[0]]?.image?.instance;
316
+ if (this.ngffMetadata = e.vivLoader.metadata, n.debug("ngffMetadata", this.ngffMetadata), !e || e.getType() !== "ome-zarr")
317
+ throw new Error("Invalid imageWrapper or not an OME-Zarr image");
318
+ const i = e.getMultiResolutionStats(), a = Ze(i), r = i.length;
319
+ this.zarrStore.resolutions = r;
320
+ const o = e.getData();
321
+ if (!Array.isArray(o) || o.length < 1)
322
+ throw new Error("Not a multiresolution loader");
323
+ if (!we(o[0].labels, ["t", "c", "z", "y", "x"]))
324
+ throw new Error("Expected OME-Zarr data with dimensions [t, c, z, y, x]");
325
+ n.debug("vivData", o);
326
+ const l = o.map((s) => s._data), c = new Array(r).fill(null);
327
+ if (l.length > 0) {
328
+ const s = l[0];
329
+ if (this.zarrStore = {
330
+ resolutions: r,
331
+ chunkSize: s.chunks,
332
+ shapes: a,
333
+ arrays: l,
334
+ dtype: s.dtype,
335
+ physicalSizeTotal: [],
336
+ // Will be populated if metadata exists
337
+ physicalSizeVoxel: [],
338
+ // Will be populated if metadata exists
339
+ brickLayout: [],
340
+ // Calculate from shapes and chunk sizes
341
+ // store: this.store,
342
+ // group: this.group,
343
+ channelCount: a[0][1],
344
+ scales: c
345
+ }, this.channels.colorMappings = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(-1), this.channels.zarrMappings = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(void 0), this.channels.downsampleMin = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(void 0), this.channels.downsampleMax = new Array(Math.min(this.zarrStore.channelCount, 7)).fill(void 0), s.meta && s.meta.physicalSizes) {
346
+ const { x: d, y: v, z: f } = s.meta.physicalSizes, x = f?.size || 1, _ = v?.size || 1, y = d?.size || 1;
347
+ this.zarrStore.physicalSizeVoxel = [x, _, y], s.shape && s.shape.length >= 5 && (this.zarrStore.physicalSizeTotal = [
348
+ (s.shape[2] || 1) * x,
349
+ (s.shape[3] || 1) * _,
350
+ (s.shape[4] || 1) * y
351
+ ]);
352
+ } else
353
+ this.zarrStore.physicalSizeVoxel = [1, 1, 1], this.zarrStore.physicalSizeTotal = [
354
+ s.shape[2] || 1,
355
+ s.shape[3] || 1,
356
+ s.shape[4] || 1
357
+ ];
358
+ const { multiscales: g } = this.ngffMetadata;
359
+ if (!g)
360
+ throw new Error("Expected multiscales metadata in group.attrs");
361
+ if (g?.[0]?.datasets?.[0]?.coordinateTransformations) {
362
+ for (let d = 0; d < r; d++)
363
+ if (g?.[0]?.datasets?.[d]?.coordinateTransformations?.[0]?.scale) {
364
+ const { scale: v } = g[0].datasets[d].coordinateTransformations[0];
365
+ c[d] = [v[4], v[3], v[2]];
366
+ }
367
+ } else {
368
+ n.error("no coordinateTransformations available, assuming downsampling ratio of 2 per dimension");
369
+ for (let d = 0; d < r; d++) {
370
+ const v = 2 ** d;
371
+ c[d] = [v, v, v];
372
+ }
373
+ }
374
+ this.zarrStore.scales = c;
375
+ const { coordinateTransformations: p } = this.ngffMetadata;
376
+ if (p?.[0]?.scale) {
377
+ const { scale: d } = p[0], v = d.length;
378
+ if (v >= 3) {
379
+ const f = d[v - 3], x = d[v - 2], _ = d[v - 1];
380
+ this.zarrStore.physicalSizeVoxel = [f, x, _], s.shape && s.shape.length >= 5 && (this.zarrStore.physicalSizeTotal = [
381
+ (s.shape[2] || 1) * f,
382
+ (s.shape[3] || 1) * x,
383
+ (s.shape[4] || 1) * _
384
+ ]);
385
+ }
386
+ }
387
+ this.zarrStore.brickLayout = Xe(e.getMultiResolutionStats()), n.debug("config", t);
388
+ const { omero: u } = this.ngffMetadata || {};
389
+ if (!u)
390
+ throw new Error("Expected omero metadata in ngffMetadata");
391
+ n.debug("omero", u), Object.keys(t).forEach((d, v) => {
392
+ const f = t[d].spatialTargetC;
393
+ this.channels.zarrMappings[v] = f, this.channels.colorMappings[v] = v, this.channels.downsampleMin[v] = u?.channels?.[f]?.window?.min || 0, this.channels.downsampleMax[v] = u?.channels?.[f]?.window?.max || 65535;
394
+ }), n.debug("zarrMappings after init", this.channels.zarrMappings), n.debug("colorMappings after init", this.channels.colorMappings), n.debug("downsampleMin after init", this.channels.downsampleMin), n.debug("downsampleMax after init", this.channels.downsampleMax), this.initMRMCPT();
395
+ }
396
+ return this.initStatus = F.COMPLETE, z("INIT() COMPLETE"), {
397
+ success: !0,
398
+ deviceLimits: this.deviceLimits,
399
+ zarrStore: this.zarrStore,
400
+ // physicalScale: this.physicalScale,
401
+ physicalSizeTotal: this.zarrStore.physicalSizeTotal,
402
+ physicalSizeVoxel: this.zarrStore.physicalSizeVoxel,
403
+ error: null
404
+ };
405
+ } catch (e) {
406
+ return z("INIT() FAILED"), n.error("Error initializing VolumeDataManager:", e), this.initStatus = F.FAILED, this.initError = e.message || "Unknown error", {
407
+ success: !1,
408
+ error: this.initError
409
+ };
410
+ }
411
+ }
412
+ /**
413
+ * Initialize the BrickCache and PageTable
414
+ * MRMCPT: multi-resolution multi-channel page table
415
+ *
416
+ * Depends on:
417
+ * - zarrStore.brickLayout
418
+ * - zarrMappings.length (zarrMappings: the zarr channel index for every one of the up to 7 channels)
419
+ * -
420
+ */
421
+ initMRMCPT() {
422
+ z("initMRMCPT");
423
+ const { PT: t, ptTHREE: e, bcTHREE: i } = je(this.zarrStore.brickLayout, this.channels.zarrMappings.length);
424
+ this.PT = t, this.ptTHREE = e, this.bcTHREE = i, z("initMRMCPT() COMPLETE");
425
+ }
426
+ async initTexture() {
427
+ const t = [
428
+ { x: 0, y: 0, z: 1 }
429
+ ];
430
+ z("initTexture - loading first brick"), await this.handleBrickRequests(t);
431
+ }
432
+ updateChannels(t) {
433
+ if (z("updateChannels"), n.debug("channelProps", t), n.debug("this.channels.zarrMappings", this.channels.zarrMappings), n.debug("this.channels.colorMappings", this.channels.colorMappings), n.debug("this.channels.downsampleMin", this.channels.downsampleMin), n.debug("this.channels.downsampleMax", this.channels.downsampleMax), this.channels.zarrMappings.length === 0) {
434
+ n.debug("channels not initialized yet");
435
+ return;
436
+ }
437
+ const e = Object.values(t).map((l) => l.spatialTargetC).filter((l) => l !== void 0), i = this.channels.zarrMappings.filter((l) => l !== void 0), a = [...new Set(e)].sort((l, c) => l - c), r = [...new Set(i)].sort((l, c) => l - c);
438
+ a.length === r.length && a.every((l, c) => l === r[c]) && n.debug("Channel mappings unchanged, skipping update"), n.debug("Channel mappings changed:", {
439
+ current: r,
440
+ requested: a
441
+ }), Object.entries(t).forEach(([l, c]) => {
442
+ const s = c.spatialTargetC;
443
+ n.debug(`UI channel "${l}" wants zarr channel ${s}`);
444
+ const g = this.channels.zarrMappings.indexOf(s);
445
+ if (g === -1) {
446
+ const p = this.channels.zarrMappings.findIndex((u) => u === void 0);
447
+ if (p !== -1)
448
+ this.channels.zarrMappings[p] = s, n.debug("channelData", c), n.debug("this.ngffMetadata?.omero?.channels", this.ngffMetadata?.omero?.channels), n.debug("targetZarrChannel", s), this.channels.downsampleMin[p] = this.ngffMetadata?.omero?.channels?.[s]?.window?.min || 0, this.channels.downsampleMax[p] = this.ngffMetadata?.omero?.channels?.[s]?.window?.max || 65535, n.debug(`Mapped zarr channel ${s} to slot ${p}`), n.debug("channels", this.channels);
449
+ else {
450
+ n.debug("No free slots found, looking for unused mapped channels");
451
+ const u = this.channels.zarrMappings.filter((f) => f !== void 0), d = e, v = u.filter((f) => !d.includes(f));
452
+ if (n.debug("Currently mapped:", u), n.debug("Still requested:", d), n.debug("Unused mapped channels:", v), v.length > 0) {
453
+ const f = this.channels.zarrMappings.findIndex((x) => v.includes(x));
454
+ if (f !== -1) {
455
+ const x = this.channels.zarrMappings[f];
456
+ this.channels.zarrMappings[f] = s, this.channels.downsampleMin[f] = this.ngffMetadata?.omero?.channels?.[s]?.window?.min || 0, this.channels.downsampleMax[f] = this.ngffMetadata?.omero?.channels?.[s]?.window?.max || 65535, n.debug(`Reused slot ${f}: ${x} -> ${s}`), this._purgeChannel(f);
457
+ } else
458
+ n.error("Could not find slot to reuse - this should not happen");
459
+ } else
460
+ n.error("All slots are full and all mapped channels are still in use");
461
+ }
462
+ } else
463
+ n.debug(`Zarr channel ${s} already mapped to slot ${g}`);
464
+ });
465
+ const o = Object.values(t).map((l) => {
466
+ const c = this.channels.zarrMappings.indexOf(l.spatialTargetC);
467
+ return c !== -1 ? c : -1;
468
+ });
469
+ for (; o.length < 7; )
470
+ o.push(-1);
471
+ n.debug("newColorMappings", o), this.channels.colorMappings = o, n.debug("updatedChannels", this.channels), this._lastChannelConfig = {
472
+ zarrMappings: [...this.channels.zarrMappings],
473
+ colorMappings: [...this.channels.colorMappings],
474
+ downsampleMin: [...this.channels.downsampleMin],
475
+ downsampleMax: [...this.channels.downsampleMax]
476
+ };
477
+ }
478
+ /**
479
+ * Try to load a resolution level
480
+ * @param {number} resolutionIndex - The resolution level to load
481
+ * @param {Array} arrays - Array to store the loaded arrays
482
+ * @returns {Promise} Promise resolving when the resolution is loaded or rejected
483
+ */
484
+ /*
485
+ async tryLoadResolution(resolutionIndex, arrays) {
486
+ logWithColor('tryLoadResolution');
487
+ log.debug(resolutionIndex, arrays);
488
+ try {
489
+ const array = await zarrita.open(this.group.resolve(String(resolutionIndex)));
490
+ // Create new arrays to avoid modifying parameters directly
491
+ const newArrays = [...arrays];
492
+ newArrays[resolutionIndex] = array;
493
+ // Update the original arrays
494
+ Object.assign(arrays, newArrays);
495
+ logWithColor('tryLoadResolution() COMPLETE');
496
+ return { success: true, level: resolutionIndex };
497
+ } catch (err) {
498
+ log.error(`Failed to load resolution ${resolutionIndex}:`, err);
499
+ return { success: false, level: resolutionIndex, error: err.message };
500
+ }
501
+ }
502
+ */
503
+ /**
504
+ * Get physical dimensions
505
+ * @returns {Array} Physical dimensions [X, Y, Z]
506
+ */
507
+ getPhysicalDimensionsXYZ() {
508
+ n.debug("getPhysicalDimensionsXYZ"), n.debug("this.zarrStore.physicalSizeTotal", this.zarrStore.physicalSizeTotal);
509
+ const t = [
510
+ this.zarrStore.physicalSizeTotal[2],
511
+ this.zarrStore.physicalSizeTotal[1],
512
+ this.zarrStore.physicalSizeTotal[0]
513
+ ];
514
+ return n.debug("out", t), t;
515
+ }
516
+ /**
517
+ * Get the maximum resolution
518
+ * @returns {number} Maximum resolution
519
+ */
520
+ getMaxResolutionXYZ() {
521
+ n.debug("getMaxResolutionXYZ"), n.debug("this.zarrStore.shapes", this.zarrStore.shapes);
522
+ const t = [
523
+ this.zarrStore.shapes[0][4],
524
+ this.zarrStore.shapes[0][3],
525
+ this.zarrStore.shapes[0][2]
526
+ ];
527
+ return n.debug("out", t), t;
528
+ }
529
+ getOriginalScaleXYZ() {
530
+ z("getOriginalScaleXYZ"), n.debug("this.zarrStore.physicalSizeVoxel", this.zarrStore.physicalSizeVoxel);
531
+ const t = [
532
+ this.zarrStore.physicalSizeVoxel[2],
533
+ this.zarrStore.physicalSizeVoxel[1],
534
+ this.zarrStore.physicalSizeVoxel[0]
535
+ ];
536
+ return n.debug("out", t), t;
537
+ }
538
+ getNormalizedScaleXYZ() {
539
+ n.debug("getNormalizedScaleXYZ");
540
+ const t = [
541
+ 1,
542
+ this.zarrStore.physicalSizeVoxel[1] / this.zarrStore.physicalSizeVoxel[2],
543
+ this.zarrStore.physicalSizeVoxel[0] / this.zarrStore.physicalSizeVoxel[0]
544
+ ];
545
+ return n.debug("out", t), t;
546
+ }
547
+ getBoxDimensionsXYZ() {
548
+ n.debug("getBoxDimensionsXYZ"), n.debug("this.zarrStore.shapes", this.zarrStore.shapes);
549
+ const t = [
550
+ 1,
551
+ this.zarrStore.shapes[0][3] / this.zarrStore.shapes[0][4],
552
+ this.zarrStore.shapes[0][2] / this.zarrStore.shapes[0][4]
553
+ ];
554
+ return n.debug("out", t), t;
555
+ }
556
+ /**
557
+ * Load a specific Zarr chunk based on [t,c,z,y,x] coordinates
558
+ * @param {number} t - Time point (default 0)
559
+ * @param {number} c - Channel (default 0)
560
+ * @param {number} z - Z coordinate
561
+ * @param {number} y - Y coordinate
562
+ * @param {number} x - X coordinate
563
+ * @param {number} resolution - Resolution level
564
+ * @returns {Promise<Uint8Array>} 32x32x32 chunk data
565
+ */
566
+ async loadZarrChunk(t = 0, e = 0, i, a, r, o) {
567
+ if (!this.zarrStore || !this.zarrStore.arrays[o])
568
+ throw new Error("Zarr store or resolution not initialized");
569
+ n.debug("loadZarrChunk", { t, c: e, z: i, y: a, x: r, resolution: o });
570
+ const c = await this.zarrStore.arrays[o].getChunk([t, e, i, a, r]);
571
+ if (!c)
572
+ throw new Error(`No chunk found at coordinates [${t},${e},${i},${a},${r}]`);
573
+ if (c.data.length !== S * S * S)
574
+ throw new Error(`Unexpected chunk size: ${c.data.length}`);
575
+ return c.data;
576
+ }
577
+ async processRequestData(t) {
578
+ if (this.isBusy) {
579
+ n.debug("processRequestData: already busy, skipping");
580
+ return;
581
+ }
582
+ if (this.noNewRequests) {
583
+ n.debug("processRequestData: loading stopped by user, skipping");
584
+ return;
585
+ }
586
+ if (this.isContextLost()) {
587
+ n.debug("processRequestData: WebGL context is lost, skipping");
588
+ return;
589
+ }
590
+ this.isBusy = !0, this.triggerRequest = !1;
591
+ const { requests: e, origRequestCount: i } = Ke(t, this.k);
592
+ e.length === 0 && (this.noNewRequests = !0), n.debug(`processRequestData: handling ${e.length} requests of ${i}`), await this.handleBrickRequests(e), this.triggerUsage = !0, this.isBusy = !1;
593
+ }
594
+ async processUsageData(t) {
595
+ if (this.isBusy) {
596
+ n.debug("processUsageData: already busy, skipping"), this.needsBailout = !0;
597
+ return;
598
+ }
599
+ if (this.isContextLost()) {
600
+ n.debug("processUsageData: WebGL context is lost, skipping");
601
+ return;
602
+ }
603
+ this.isBusy = !0, this.triggerUsage = !1;
604
+ const e = ++this.timeStamp, i = /* @__PURE__ */ new Set();
605
+ for (let a = 0; a < t.length; a += 4) {
606
+ const r = t[a], o = t[a + 1], l = t[a + 2];
607
+ if ((r | o | l) === 0)
608
+ continue;
609
+ const c = l * A * V + o * A + r;
610
+ c < this.BCTimeStamps.length && i.add(c);
611
+ }
612
+ Array.from(i).forEach((a) => {
613
+ this.BCTimeStamps[a] = e;
614
+ }), this.BCFull && this._buildLRU(), this.triggerRequest = !0, this.isBusy = !1;
615
+ }
616
+ // Helper method to update PT entries for evicted bricks
617
+ _evictBrick(t) {
618
+ const e = this.bc2pt[t];
619
+ if (!e)
620
+ return;
621
+ const [i, a] = this.BCMinMax[t] || [0, 0], r = (0 | 1 << 30 | Math.min(127, i >> 1) << 23 | Math.min(127, a >> 1) << 16) >>> 0;
622
+ this._updatePTEntry(e.x, e.y, e.z, r), this.bc2pt[t] = null;
623
+ }
624
+ _purgeChannel(t) {
625
+ if (n.debug("purging channel", t), n.debug("corresponding zarr channel", this.channels.zarrMappings[t]), !this.ptTHREE) {
626
+ n.error("pagetable texture not initialized");
627
+ return;
628
+ }
629
+ if (this.isContextLost()) {
630
+ n.warn("WebGL context is lost, skipping channel purge");
631
+ return;
632
+ }
633
+ this.channels.downsampleMin[t] = void 0, this.channels.downsampleMax[t] = void 0, this.channels.zarrMappings[t] = void 0;
634
+ const e = this.PT.channelOffsets[t];
635
+ n.debug("channelMask", e), n.error("TODO: not tested yet");
636
+ const { gl: i } = this, a = this.renderer.properties.get(this.ptTHREE).__webglTexture;
637
+ i.activeTexture(i.TEXTURE0), i.bindTexture(i.TEXTURE_3D, a);
638
+ for (let r = 0; r < this.zarrStore.resolutions; r++) {
639
+ const o = [
640
+ this.PT.anchors[r][2] * e[2],
641
+ this.PT.anchors[r][1] * e[1],
642
+ this.PT.anchors[r][0] * e[0]
643
+ ];
644
+ n.debug("anchor", o);
645
+ const l = this.zarrStore.brickLayout[r], c = l[0] * l[1] * l[2];
646
+ n.debug("extents", l), n.debug("size", c), i.texSubImage3D(i.TEXTURE_3D, 0, o[0], o[1], o[2], l[0], l[1], l[2], i.RED_INTEGER, i.UNSIGNED_INT, new Uint32Array(c));
647
+ }
648
+ i.bindTexture(i.TEXTURE_3D, null);
649
+ }
650
+ // Update a PT entry
651
+ _updatePTEntry(t, e, i, a) {
652
+ if (!this.ptTHREE)
653
+ return;
654
+ if (this.isContextLost()) {
655
+ n.warn("WebGL context is lost, skipping PT entry update");
656
+ return;
657
+ }
658
+ const { gl: r } = this, o = this.renderer.properties.get(this.ptTHREE).__webglTexture;
659
+ r.activeTexture(r.TEXTURE0), r.bindTexture(r.TEXTURE_3D, o), r.texSubImage3D(r.TEXTURE_3D, 0, t, e, i, 1, 1, 1, r.RED_INTEGER, r.UNSIGNED_INT, new Uint32Array([a])), r.bindTexture(r.TEXTURE_3D, null);
660
+ }
661
+ /* ------------------------------------------------------------- *
662
+ * 2. Allocate the next n free bricks in the brick cache *
663
+ * ------------------------------------------------------------- */
664
+ /**
665
+ *
666
+ * @param {number} n The number of slots to allocate
667
+ * @returns {{ bcIndex, x, y, z }[]} Array of brick cache coordinates for the allocated slots.
668
+ */
669
+ _allocateBCSlots(t) {
670
+ let e = [];
671
+ const i = A * V * ce;
672
+ if (!this.BCFull && this.BCUnusedIndex + t > i && (this.BCFull = !0, n.debug("BRICK CACHE FULL")), this.BCFull)
673
+ this.LRUStack.length < t && this._buildLRU(), e = this.LRUStack.splice(0, t).map((a) => {
674
+ this._evictBrick(a);
675
+ const r = Math.floor(a / (A * V)), o = a - r * A * V, l = Math.floor(o / A), c = o % A;
676
+ return { bcIndex: a, x: c, y: l, z: r };
677
+ });
678
+ else {
679
+ for (let a = 0; a < t; ++a) {
680
+ const r = (this.BCUnusedIndex + a) % i, o = Math.floor(r / (A * V)), l = r - o * A * V, c = Math.floor(l / A), s = l % A;
681
+ e.push({ bcIndex: r, x: s, y: c, z: o });
682
+ }
683
+ this.BCUnusedIndex += t;
684
+ }
685
+ return e;
686
+ }
687
+ /* ------------------------------------------------------------- *
688
+ * 4. Upload one brick + PT entry *
689
+ * ------------------------------------------------------------- */
690
+ async _uploadBrick(t, e) {
691
+ if (n.debug("uploading brick", t, e), this.isContextLost()) {
692
+ n.warn("WebGL context is lost, skipping brick upload");
693
+ return;
694
+ }
695
+ if (t.x >= this.PT.xExtent || t.y >= this.PT.yExtent || t.z >= this.PT.zTotal || t.x < 0 || t.y < 0 || t.z < 0) {
696
+ n.error("this.PT", this.PT), n.error("ptCoord out of bounds", t);
697
+ return;
698
+ }
699
+ const { channel: i, resolution: a, x: r, y: o, z: l } = He(t.x, t.y, t.z, { PT_zExtent: this.PT.zExtent, PT_z0Extent: this.PT.z0Extent, PT_anchors: this.PT.anchors });
700
+ if (!this.channels || !this.channels.zarrMappings || this.channels.zarrMappings.length === 0) {
701
+ n.error("Channel mappings not initialized, skipping brick upload");
702
+ return;
703
+ }
704
+ if (i < 0 || i >= this.channels.zarrMappings.length) {
705
+ n.error("Channel index out of bounds", { channel: i, mappingsLength: this.channels.zarrMappings.length });
706
+ return;
707
+ }
708
+ const c = this.channels.zarrMappings[i];
709
+ if (c === void 0 || c === -1)
710
+ if (n.warn("zarrChannel is undefined or -1", {
711
+ zarrChannel: c,
712
+ channel: i,
713
+ ptCoord: t,
714
+ channelMappings: this.channels.zarrMappings,
715
+ contextLost: this.isContextLost()
716
+ }), this._lastChannelConfig && this._lastChannelConfig.zarrMappings[i] !== void 0) {
717
+ n.warn("Attempting to use last known channel config"), this.channels.zarrMappings = [...this._lastChannelConfig.zarrMappings], this.channels.colorMappings = [...this._lastChannelConfig.colorMappings], this.channels.downsampleMin = [...this._lastChannelConfig.downsampleMin], this.channels.downsampleMax = [...this._lastChannelConfig.downsampleMax];
718
+ const y = this.channels.zarrMappings[i];
719
+ if (y !== void 0 && y !== -1)
720
+ n.debug("Successfully restored channel mapping, continuing with upload");
721
+ else {
722
+ n.error("Could not restore valid channel mapping, aborting brick upload");
723
+ return;
724
+ }
725
+ } else {
726
+ n.error("No fallback channel config available, aborting brick upload");
727
+ return;
728
+ }
729
+ n.debug("starting to load zarr chunk", { resolution: a, z: l, y: o, x: r, zarrChannel: c });
730
+ let s = await this.loadZarrChunk(0, c, l, o, r, a);
731
+ if (n.debug("chunk", s), s instanceof Uint16Array) {
732
+ if (n.debug("chunk is Uint16Array, converting to Uint8Array"), this.channels.downsampleMin[i] === void 0) {
733
+ const T = this.channels.zarrMappings[i];
734
+ n.debug("channelId was not found in this.channels.downsampleMin[channel]", T), this.channels.downsampleMin[i] = this.ngffMetadata?.omero?.channels?.[T]?.window?.min || 0, this.channels.downsampleMax[i] = this.ngffMetadata?.omero?.channels?.[T]?.window?.max || 65535, n.debug("this.channels.downsampleMin[channel]", this.channels.downsampleMin[i]), n.debug("this.channels.downsampleMax[channel]", this.channels.downsampleMax[i]);
735
+ }
736
+ const y = new Uint16Array(s.buffer), E = new Uint8Array(s.length), L = this.channels.downsampleMin[i], G = this.channels.downsampleMax[i], j = G - L;
737
+ for (let T = 0; T < y.length; T++) {
738
+ const U = y[T], N = Math.max(L, Math.min(G, U));
739
+ E[T] = (N - L) * 255 / j | 0;
740
+ }
741
+ s = E;
742
+ }
743
+ if (!(s instanceof Uint8Array))
744
+ throw new Error(`Unsupported chunk type: ${s.constructor.name}. Expected Uint8Array.`);
745
+ let g = 255, p = 0;
746
+ for (let y = 0; y < s.length; ++y) {
747
+ const E = s[y];
748
+ E < g && (g = E), E > p && (p = E);
749
+ }
750
+ const { gl: u } = this, d = this.renderer.properties.get(this.bcTHREE).__webglTexture;
751
+ u.activeTexture(u.TEXTURE2), u.bindTexture(u.TEXTURE_3D, d), u.pixelStorei(u.UNPACK_ALIGNMENT, 1), u.texSubImage3D(u.TEXTURE_3D, 0, e.x * S, e.y * S, e.z * S, S, S, S, u.RED, u.UNSIGNED_BYTE, s), u.pixelStorei(u.UNPACK_ALIGNMENT, 4), u.bindTexture(u.TEXTURE_3D, null);
752
+ const v = u.getError();
753
+ v !== u.NO_ERROR && n.error("WebGL error during brick upload:", v, s), i >= this.channels.zarrMappings.length && (n.debug("channel is out of bounds", i), g = 255, p = 255);
754
+ const f = Ye(g, p, e.x, e.y, e.z), x = this.renderer.properties.get(this.ptTHREE).__webglTexture;
755
+ u.activeTexture(u.TEXTURE0), u.bindTexture(u.TEXTURE_3D, x), u.texSubImage3D(u.TEXTURE_3D, 0, t.x, t.y, t.z, 1, 1, 1, u.RED_INTEGER, u.UNSIGNED_INT, new Uint32Array([f])), u.bindTexture(u.TEXTURE_3D, null);
756
+ const _ = u.getError();
757
+ _ !== u.NO_ERROR && n.error("WebGL error during pagetable upload:", _, s), this.BCTimeStamps[e.bcIndex] = this.timeStamp, this.BCMinMax[e.bcIndex] = [g, p], this.bc2pt[e.bcIndex] = t;
758
+ }
759
+ /* ------------------------------------------------------------- *
760
+ * 5. Public: handle a batch of PT requests (array of {x,y,z}) *
761
+ * ------------------------------------------------------------- */
762
+ async handleBrickRequests(t) {
763
+ if (t.length === 0)
764
+ return;
765
+ this.totalBricksRequested = t.length, this.currentRequestCount = t.length;
766
+ const e = this._allocateBCSlots(t.length);
767
+ n.debug("Handling brick requests:", { requestCount: t.length, slotCount: e.length }), n.debug("handleBrickRequests: starting for loop");
768
+ for (let i = 0; i < t.length; ++i) {
769
+ await this._uploadBrick(t[i], e[i]), this.currentRequestCount = t.length - i - 1;
770
+ const a = this.bricksEverLoaded.size;
771
+ if (this.bricksEverLoaded.add(`${t[i].x},${t[i].y},${t[i].z}`), a === this.bricksEverLoaded.size && n.debug("DUPLICATE BRICK LOADED", t[i]), this.needsBailout) {
772
+ n.debug("Bailing out of handleBrickRequests early due to needsBailout flag"), this.needsBailout = !1, this.currentRequestCount = 0;
773
+ break;
774
+ }
775
+ }
776
+ this.currentRequestCount = 0, n.debug("this.bricksEverLoaded", this.bricksEverLoaded);
777
+ }
778
+ /* --------------------------------------------------------- *
779
+ * Rebuild the LRUStack with the k least-recently-used bricks *
780
+ * --------------------------------------------------------- */
781
+ _buildLRU() {
782
+ const t = this.BCTimeStamps.map((e, i) => ({ index: i, time: e }));
783
+ this.LRUStack = t.sort((e, i) => e.time - i.time).slice(0, this.k).map((e) => e.index);
784
+ }
785
+ }
786
+ const $e = `//
787
+ // Output: Unnormalized ray direction from camera to each vertex
788
+ // Used by fragment shader for ray marching through the volume
789
+ out vec3 rayDirUnnorm;
790
+
791
+ // Output: Camera position transformed into volume's local coordinate system
792
+ // Used to calculate ray origins in the fragment shader
793
+ out vec3 cameraCorrected;
794
+
795
+ // Volume scale uniform (likely for anisotropic voxels)
796
+ uniform vec3 u_vol_scale;
797
+
798
+ // Volume size uniform
799
+ uniform vec3 u_size;
800
+
801
+ // Output: Vertex positions normalized to [0,1] range within volume bounds
802
+ // Standard coordinate system for volume sampling
803
+ varying vec3 worldSpaceCoords;
804
+
805
+ // Output: Texture coordinates for sampling volume data
806
+ varying vec2 vUv;
807
+
808
+ // Output: Final clip-space position (stored for fragment shader access)
809
+ varying vec4 glPosition;
810
+
811
+ // Volume bounding box size uniform
812
+ uniform highp vec3 boxSize;
813
+
814
+ void main()
815
+ {
816
+ // Transform vertex positions from [-0.5, 0.5] range to [0, 1] range
817
+ // This is the standard coordinate system for volume sampling
818
+ //
819
+ // Mathematical transformation:
820
+ // worldSpaceCoords = (position / boxSize) + 0.5
821
+ //
822
+ // Example:
823
+ // position = (-0.5, -0.5, -0.5) → worldSpaceCoords = (0, 0, 0)
824
+ // position = ( 0.0, 0.0, 0.0) → worldSpaceCoords = (0.5, 0.5, 0.5)
825
+ // position = ( 0.5, 0.5, 0.5) → worldSpaceCoords = (1, 1, 1)
826
+ worldSpaceCoords = position / boxSize + vec3(0.5, 0.5, 0.5); //move it from [-0.5;0.5] to [0,1]
827
+
828
+ // Transform camera position into volume's local coordinate system
829
+ // This gives us the ray origin in volume space
830
+ cameraCorrected = (inverse(modelMatrix) * vec4(cameraPosition, 1.)).xyz;
831
+
832
+ // Calculate unnormalized ray direction from camera to each vertex
833
+ // Used by fragment shader for ray marching through the volume
834
+ rayDirUnnorm = position - cameraCorrected;
835
+
836
+ // Apply standard MVP transformation to get clip-space coordinates
837
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
838
+
839
+ // Store clip-space position for fragment shader access
840
+ glPosition = gl_Position;
841
+
842
+ // Pass through texture coordinates for volume sampling
843
+ vUv = uv;
844
+ }
845
+ `, Qe = `//
846
+ // #include <packing>
847
+ precision highp float;
848
+ precision highp int;
849
+ precision highp sampler3D;
850
+ precision highp usampler3D;
851
+
852
+ // ========================================
853
+ // INPUT VARIABLES (from vertex shader)
854
+ // ========================================
855
+ // Unnormalized ray direction from camera
856
+ in vec3 rayDirUnnorm;
857
+ // Camera position in world space
858
+ in vec3 cameraCorrected;
859
+
860
+ // ========================================
861
+ // TEXTURE SAMPLERS
862
+ // ========================================
863
+ // 3D texture containing cached brick data (2048x2048x128)
864
+ // (2048*2048*128)/(32*32*32) = 16,384 bricks can be stored?
865
+ uniform sampler3D brickCacheTex;
866
+ // 3D texture containing page table entries (brick metadata)
867
+ uniform usampler3D pageTableTex;
868
+
869
+ // ========================================
870
+ // RENDERING PARAMETERS/CONSTANTS
871
+ // ========================================
872
+ // Rendering style: 0=MIP, 1=MinIP, 2=standard volume rendering, 3=DEBUG
873
+ uniform int u_renderstyle;
874
+ // Global opacity multiplier for volume rendering
875
+ uniform float opacity;
876
+
877
+ // ========================================
878
+ // CONTRAST LIMITS (per channel)
879
+ // per channel min/max values for value normalization
880
+ // ========================================
881
+ uniform vec2 clim0;
882
+ uniform vec2 clim1;
883
+ uniform vec2 clim2;
884
+ uniform vec2 clim3;
885
+ uniform vec2 clim4;
886
+ uniform vec2 clim5;
887
+ uniform vec2 clim6;
888
+
889
+ // ========================================
890
+ // CLIPPING PLANES
891
+ // e.g., for X-axis clipping: (min_x, max_x) or (-1, -1) if disabled
892
+ // ========================================
893
+ uniform vec2 xClip;
894
+ uniform vec2 yClip;
895
+ uniform vec2 zClip;
896
+
897
+ // ========================================
898
+ // CHANNEL COLORS AND OPACITIES
899
+ // rgb -- color values, a -- visibility (boolean)
900
+ // ========================================
901
+ uniform vec4 color0;
902
+ uniform vec4 color1;
903
+ uniform vec4 color2;
904
+ uniform vec4 color3;
905
+ uniform vec4 color4;
906
+ uniform vec4 color5;
907
+ uniform vec4 color6;
908
+
909
+ // maps colors to physical spaces
910
+ uniform int channelMapping[7];
911
+
912
+ // ========================================
913
+ // VOLUME AND RESOLUTION PARAMETERS
914
+ // ========================================
915
+ // Volume bounding box size in world space
916
+ uniform highp vec3 boxSize;
917
+ // Rendering resolution level (affects step size)
918
+ // stepsize, correlates with resolution
919
+ uniform int renderRes;
920
+ // Volume dimensions in voxels (x, y, z)
921
+ // resolution 0 voxel extents
922
+ uniform uvec3 voxelExtents;
923
+ // Global resolution range: (min_res, max_res)
924
+ // global range of requested resolutions
925
+ uniform ivec2 resGlobal;
926
+ // Maximum number of active channels
927
+ // max number of channels (relevant for the cache statistics)
928
+ // between 1 and 7
929
+ uniform int maxChannels;
930
+
931
+ // ========================================
932
+ // PER-CHANNEL RESOLUTION RANGES
933
+ // per color channel resolution range
934
+ // Each channel can have different available resolution levels
935
+ // e.g., for Channel 0: (min_res, max_res)
936
+ // ========================================
937
+ uniform ivec2 res0;
938
+ uniform ivec2 res1;
939
+ uniform ivec2 res2;
940
+ uniform ivec2 res3;
941
+ uniform ivec2 res4;
942
+ uniform ivec2 res5;
943
+ uniform ivec2 res6;
944
+ // Channel 7: unused
945
+ uniform ivec2 res7;
946
+
947
+ // ========================================
948
+ // LEVEL-OF-DETAIL PARAMETERS
949
+ // controls how fast we decrease the resolution
950
+ // ========================================
951
+ // LOD factor for distance-based resolution selection
952
+ uniform float lodFactor;
953
+
954
+ // ========================================
955
+ // ANCHOR POINTS (per resolution level)
956
+ // per resolution anchor point for pagetable
957
+ // ========================================
958
+ // Anchor points define the origin of page table for each resolution level
959
+ // Resolution 0 anchor point (highest detail)
960
+ uniform uvec3 anchor0;
961
+ uniform uvec3 anchor1;
962
+ uniform uvec3 anchor2;
963
+ uniform uvec3 anchor3;
964
+ uniform uvec3 anchor4;
965
+ uniform uvec3 anchor5;
966
+ uniform uvec3 anchor6;
967
+ uniform uvec3 anchor7;
968
+ uniform uvec3 anchor8;
969
+ uniform uvec3 anchor9;
970
+ // Resolution 9 anchor point (lowest detail)
971
+
972
+ // ========================================
973
+ // SCALE FACTORS (per resolution level)
974
+ // per resolution downsample factor
975
+ // ========================================
976
+ // Scale factors determine voxel size at each resolution level
977
+ // Resolution 0 scale factors (should be 1,1,1)
978
+ uniform vec3 scale0;
979
+ uniform vec3 scale1;
980
+ uniform vec3 scale2;
981
+ uniform vec3 scale3;
982
+ uniform vec3 scale4;
983
+ uniform vec3 scale5;
984
+ uniform vec3 scale6;
985
+ uniform vec3 scale7;
986
+ uniform vec3 scale8;
987
+ uniform vec3 scale9;
988
+ // Resolution 9 scale factors
989
+
990
+ // ========================================
991
+ // VARYING VARIABLES (unused but required)
992
+ // ========================================
993
+ // Fragment position (unused)
994
+ varying vec4 glPosition;
995
+ // World space coordinates (used for depth only)
996
+ varying vec3 worldSpaceCoords;
997
+
998
+ // ========================================
999
+ // OUTPUT VARIABLES (multiple render targets)
1000
+ // output buffers
1001
+ // ========================================
1002
+ // Final rendered color (sRGB)
1003
+ layout(location = 0) out vec4 gColor;
1004
+ // Brick loading requests (packed coordinates)
1005
+ layout(location = 1) out vec4 gRequest;
1006
+ // Brick usage tracking (for cache management)
1007
+ layout(location = 2) out vec4 gUsage;
1008
+
1009
+ // ========================================
1010
+ // CONSTANTS
1011
+ // ========================================
1012
+ // Size of each brick in voxels (32x32x32)
1013
+ const float BRICK_SIZE = 32.0;
1014
+ // Brick cache texture width
1015
+ const float BRICK_CACHE_SIZE_X = 2048.0;
1016
+ // Brick cache texture height
1017
+ const float BRICK_CACHE_SIZE_Y = 2048.0;
1018
+ // Brick cache texture depth
1019
+ const float BRICK_CACHE_SIZE_Z = 128.0;
1020
+ // Number of bricks in X (64)
1021
+ const float BRICK_CACHE_BRICKS_X = BRICK_CACHE_SIZE_X / BRICK_SIZE;
1022
+ // Number of bricks in Y (64)
1023
+ const float BRICK_CACHE_BRICKS_Y = BRICK_CACHE_SIZE_Y / BRICK_SIZE;
1024
+ // Number of bricks in Z (4)
1025
+ const float BRICK_CACHE_BRICKS_Z = BRICK_CACHE_SIZE_Z / BRICK_SIZE;
1026
+
1027
+ // ========================================
1028
+ // RAY-VOLUME INTERSECTION
1029
+ // calculating the intersection of the ray with the bounding box
1030
+ // ========================================
1031
+ // Calculates the intersection of a ray with the volume's bounding box
1032
+ // Returns (entry_time, exit_time) for the ray-box intersection
1033
+ // Handles clipping planes by adjusting the bounding box
1034
+ //
1035
+ // Parameters:
1036
+ // orig - vec3: Ray origin point in world space
1037
+ // dir - vec3: Ray direction vector (should be normalized)
1038
+ //
1039
+ // Returns:
1040
+ // vec2: (entry_time, exit_time) where:
1041
+ // - entry_time: Distance along ray to enter the volume
1042
+ // - exit_time: Distance along ray to exit the volume
1043
+ // - If no intersection: entry_time > exit_time
1044
+ vec2 intersect_hit(vec3 orig, vec3 dir) {
1045
+ // Start with full volume bounds
1046
+ vec3 boxMin = vec3(-0.5) * boxSize;
1047
+ vec3 boxMax = vec3(0.5) * boxSize;
1048
+
1049
+ // Apply clipping planes if they're active (xClip.x > -1.0 means active)
1050
+ if (xClip.x > -1.0) {
1051
+ boxMin.x = xClip.x - (boxSize.x / 2.0);
1052
+ if (xClip.y < boxSize.x)
1053
+ boxMax.x = xClip.y - (boxSize.x / 2.0);
1054
+ }
1055
+ if (yClip.x > -1.0) {
1056
+ boxMin.y = yClip.x - (boxSize.y / 2.0);
1057
+ if (yClip.y < boxSize.y)
1058
+ boxMax.y = yClip.y - (boxSize.y / 2.0);
1059
+ }
1060
+ if (zClip.x > -1.0) {
1061
+ boxMin.z = zClip.x - (boxSize.z / 2.0);
1062
+ if (zClip.y < boxSize.z)
1063
+ boxMax.z = zClip.y - (boxSize.z / 2.0);
1064
+ }
1065
+
1066
+ // Standard ray-box intersection algorithm
1067
+ vec3 invDir = 1.0 / dir;
1068
+ vec3 tmin0 = (boxMin - orig) * invDir;
1069
+ vec3 tmax0 = (boxMax - orig) * invDir;
1070
+ vec3 tmin = min(tmin0, tmax0);
1071
+ vec3 tmax = max(tmin0, tmax0);
1072
+ float t0 = max(tmin.x, max(tmin.y, tmin.z)); // Entry time
1073
+ float t1 = min(tmax.x, min(tmax.y, tmax.z)); // Exit time
1074
+ return vec2(t0, t1);
1075
+ }
1076
+
1077
+ // ========================================
1078
+ // UTILITY FUNCTIONS
1079
+ // ========================================
1080
+
1081
+ // Pseudo-random number generator for jittered sampling
1082
+ // random number generator based on the uv coordinate
1083
+ // Author @patriciogv - 2015
1084
+ // http://patriciogonzalezvivo.com
1085
+ //
1086
+ // Parameters:
1087
+ // None (uses gl_FragCoord.xy as input)
1088
+ //
1089
+ // Returns:
1090
+ // float: Random value between 0.0 and 1.0 based on fragment coordinates
1091
+ float random() {
1092
+ return fract(sin(dot(gl_FragCoord.xy, vec2(12.9898,78.233)))* 43758.5453123);
1093
+ }
1094
+
1095
+ // Convert from linear RGB to sRGB color space
1096
+ // Implements the standard sRGB transfer function for gamma correction
1097
+ //
1098
+ // Parameters:
1099
+ // x - float: Linear RGB value between 0.0 and 1.0
1100
+ //
1101
+ // Returns:
1102
+ // float: sRGB value between 0.0 and 1.0
1103
+ float linear_to_srgb(float x) {
1104
+ if (x <= 0.0031308f) {
1105
+ return 12.92f * x;
1106
+ }
1107
+ return 1.055f * pow(x, 1.f / 2.4f) - 0.055f;
1108
+ }
1109
+
1110
+ // Convert from linear RGB to sRGB color space (vector version)
1111
+ // Applies sRGB conversion to each RGB component while preserving alpha
1112
+ //
1113
+ // Parameters:
1114
+ // x - vec4: Linear RGBA color with components between 0.0 and 1.0
1115
+ //
1116
+ // Returns:
1117
+ // vec4: sRGB RGBA color with components between 0.0 and 1.0
1118
+ vec4 linear_to_srgb(vec4 x) {
1119
+ return vec4(linear_to_srgb(x.r), linear_to_srgb(x.g), linear_to_srgb(x.b), x.a);
1120
+ }
1121
+
1122
+ // ========================================
1123
+ // PAGE TABLE COORDINATE PACKING
1124
+ // transform the pagetable coordinate into a RGBA8 value
1125
+ // ========================================
1126
+ // Packs 3D page table coordinates into RGBA8 texture format
1127
+ // Uses 10 bits for X, 10 bits for Y, 12 bits for Z
1128
+ //
1129
+ // Parameters:
1130
+ // coord - uvec3: 3D coordinates to pack (X, Y, Z components)
1131
+ // - X coordinate: 10-bit unsigned integer (0-1023)
1132
+ // - Y coordinate: 10-bit unsigned integer (0-1023)
1133
+ // - Z coordinate: 12-bit unsigned integer (0-4095)
1134
+ //
1135
+ // Returns:
1136
+ // vec4: RGBA8 encoded coordinates with components between 0.0 and 1.0
1137
+ // - R: Upper 8 bits of packed 32-bit value
1138
+ // - G: Middle-upper 8 bits of packed 32-bit value
1139
+ // - B: Middle-lower 8 bits of packed 32-bit value
1140
+ // - A: Lower 8 bits of packed 32-bit value
1141
+ vec4 packPTCoordToRGBA8(uvec3 coord) {
1142
+
1143
+ uint x = coord.x & 0x3FFu; // 10 bits for X coordinate
1144
+ uint y = coord.y & 0x3FFu; // 10 bits for Y coordinate
1145
+ uint z = coord.z & 0xFFFu; // 12 bits for Z coordinate
1146
+
1147
+ // Pack into 32-bit integer
1148
+ uint packed =
1149
+ (x << 22u) |
1150
+ (y << 12u) |
1151
+ (z);
1152
+
1153
+ // Decompose into RGBA8 format
1154
+ return vec4(
1155
+ float((packed >> 24u) & 0xFFu) / 255.0,
1156
+ float((packed >> 16u) & 0xFFu) / 255.0,
1157
+ float((packed >> 8u) & 0xFFu) / 255.0,
1158
+ float(packed & 0xFFu) / 255.0
1159
+ );
1160
+ }
1161
+
1162
+ // ========================================
1163
+ // RESOLUTION AND ANCHOR POINT ACCESSORS
1164
+ // ========================================
1165
+
1166
+ // Get anchor point for a specific resolution level
1167
+ // Anchor points define the origin of the page table for each resolution
1168
+ //
1169
+ // Parameters:
1170
+ // index - int: Resolution level index (0-9, where 0 is highest resolution)
1171
+ //
1172
+ // Returns:
1173
+ // uvec3: 3D anchor point coordinates in the page table, or (-1, -1, -1) if invalid
1174
+ uvec3 getAnchorPoint(int index) {
1175
+ if (index == 0) return anchor0;
1176
+ if (index == 1) return anchor1;
1177
+ if (index == 2) return anchor2;
1178
+ if (index == 3) return anchor3;
1179
+ if (index == 4) return anchor4;
1180
+ if (index == 5) return anchor5;
1181
+ if (index == 6) return anchor6;
1182
+ if (index == 7) return anchor7;
1183
+ if (index == 8) return anchor8;
1184
+ if (index == 9) return anchor9;
1185
+ return uvec3(-1, -1, -1);
1186
+ }
1187
+
1188
+ // Find the lowest available resolution level
1189
+ // Returns the highest resolution index that has valid data
1190
+ //
1191
+ // Parameters:
1192
+ // None
1193
+ //
1194
+ // Returns:
1195
+ // int: Highest resolution level index (0-9) that has valid anchor point data
1196
+ // Returns 9 if no valid resolution levels are found
1197
+ int getLowestRes() {
1198
+ for (int i = 0; i < 10; i++) {
1199
+ if (getAnchorPoint(i) == uvec3(0,0,0)) {
1200
+ return i - 1;
1201
+ }
1202
+ }
1203
+ return 9;
1204
+ }
1205
+
1206
+ // Get the downsample factor for a resolution level
1207
+ // Scale factors determine the voxel size at each resolution
1208
+ //
1209
+ // Parameters:
1210
+ // index - int: Resolution level index (0-9, where 0 is highest resolution)
1211
+ //
1212
+ // Returns:
1213
+ // vec3: Scale factors (x, y, z) for the resolution level, or (-1, -1, -1) if invalid
1214
+ // Higher scale factors indicate larger voxels (lower resolution)
1215
+ vec3 getScale(int index) {
1216
+ if (index == 0) return scale0;
1217
+ if (index == 1) return scale1;
1218
+ if (index == 2) return scale2;
1219
+ if (index == 3) return scale3;
1220
+ if (index == 4) return scale4;
1221
+ if (index == 5) return scale5;
1222
+ if (index == 6) return scale6;
1223
+ if (index == 7) return scale7;
1224
+ if (index == 8) return scale8;
1225
+ if (index == 9) return scale9;
1226
+ return vec3(-1.0, -1.0, -1.0);
1227
+ }
1228
+
1229
+ // Get the resolution range for a color channel
1230
+ // Returns (min_res, max_res) for the channel
1231
+ //
1232
+ // Parameters:
1233
+ // index - int: Channel index (0-6)
1234
+ //
1235
+ // Returns:
1236
+ // ivec2: Resolution range as (min_resolution_level, max_resolution_level)
1237
+ // Returns (-1, -1) if channel index is invalid
1238
+ ivec2 getRes(int index) {
1239
+ if (index == 0) return res0;
1240
+ if (index == 1) return res1;
1241
+ if (index == 2) return res2;
1242
+ if (index == 3) return res3;
1243
+ if (index == 4) return res4;
1244
+ if (index == 5) return res5;
1245
+ if (index == 6) return res6;
1246
+ return ivec2(-1, -1);
1247
+ }
1248
+
1249
+ // Get the min/max values (contrast limits) for a color channel
1250
+ // Returns (min_value, max_value) for normalization
1251
+ //
1252
+ // Parameters:
1253
+ // index - int: Channel index (0-6)
1254
+ //
1255
+ // Returns:
1256
+ // vec2: Contrast limits as (min_value, max_value) for data normalization
1257
+ // Returns (-1.0, -1.0) if channel index is invalid
1258
+ vec2 getClim(int index) {
1259
+ if (index == 0) return clim0;
1260
+ if (index == 1) return clim1;
1261
+ if (index == 2) return clim2;
1262
+ if (index == 3) return clim3;
1263
+ if (index == 4) return clim4;
1264
+ if (index == 5) return clim5;
1265
+ if (index == 6) return clim6;
1266
+ return vec2(-1.0, -1.0);
1267
+ }
1268
+
1269
+ // ========================================
1270
+ // COORDINATE TRANSFORMATIONS
1271
+ // ========================================
1272
+
1273
+ // Convert normalized coordinates (0-1) to voxel coordinates.
1274
+ // get the voxel coordinate in the specified resolution from the normalized coordinate
1275
+ //
1276
+ // Parameters:
1277
+ // normalized - vec3: Normalized coordinates in range [0,1] for each axis
1278
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1279
+ //
1280
+ // Returns:
1281
+ // vec3: Voxel coordinates in the volume space at the specified resolution
1282
+ vec3 getVoxelFromNormalized(vec3 normalized, int res) {
1283
+ vec3 extents = (vec3(voxelExtents) / getScale(res)); // Voxel extents at this resolution
1284
+ vec3 voxel = normalized * extents;
1285
+ return voxel;
1286
+ }
1287
+
1288
+ // Convert voxel coordinates to normalized coordinates (0-1)
1289
+ // get the normalized coordinate based on the voxel coordinate in the specified resolution
1290
+ //
1291
+ // Parameters:
1292
+ // voxel - vec3: Voxel coordinates in the volume space
1293
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1294
+ //
1295
+ // Returns:
1296
+ // vec3: Normalized coordinates in range [0,1] for each axis
1297
+ vec3 getNormalizedFromVoxel(vec3 voxel, int res) {
1298
+ vec3 extents = (vec3(voxelExtents) / getScale(res)); // Voxel extents at this resolution
1299
+ vec3 normalized = voxel / extents;
1300
+ return normalized;
1301
+ }
1302
+
1303
+ // Convert normalized coordinates to brick coordinates.
1304
+ // get the brick coordinate in the specified resolution based on the normalized coordinate
1305
+ // needed for pagetable calculations
1306
+ //
1307
+ // Parameters:
1308
+ // normalized - vec3: Normalized coordinates in range [0,1] for each axis
1309
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1310
+ //
1311
+ // Returns:
1312
+ // vec3: Brick coordinates (each brick is 32x32x32 voxels)
1313
+ vec3 getBrickFromNormalized(vec3 normalized, int res) {
1314
+ vec3 voxel = getVoxelFromNormalized(normalized, res);
1315
+ vec3 brick = floor(voxel / 32.0); // Each brick is 32x32x32 voxels
1316
+ return brick;
1317
+ }
1318
+
1319
+ // Convert voxel coordinates to brick coordinates.
1320
+ // get the brick coordinate in the specified resolution based on the voxel coordinate
1321
+ //
1322
+ // Parameters:
1323
+ // voxel - vec3: Voxel coordinates in the volume space
1324
+ // res - int: Resolution level (0=highest detail, 9=lowest detail)
1325
+ //
1326
+ // Returns:
1327
+ // vec3: Brick coordinates (each brick is 32x32x32 voxels)
1328
+ vec3 getBrickFromVoxel(vec3 voxel, int res) {
1329
+ vec3 brick = floor(voxel / 32.0); // Each brick is 32x32x32 voxels
1330
+ return brick;
1331
+ }
1332
+
1333
+ // ========================================
1334
+ // CHANNEL-SPECIFIC ACCESSORS
1335
+ // ========================================
1336
+
1337
+ // Get channel offset in page table.
1338
+ // get the vector for the specified channel slot in the pagetable
1339
+ // Different channels are stored at different Z-offsets in the page table
1340
+ //
1341
+ // Parameters:
1342
+ // index - int: Channel index (0-6)
1343
+ //
1344
+ // Returns:
1345
+ // uvec3: 3D offset coordinates for the channel in the page table
1346
+ uvec3 getChannelOffset(int index) {
1347
+ if (index == 0) return uvec3(0, 0, 1);
1348
+ if (index == 1) return uvec3(0, 1, 0);
1349
+ if (index == 2) return uvec3(0, 1, 1);
1350
+ if (index == 3) return uvec3(1, 0, 0);
1351
+ if (index == 4) return uvec3(1, 0, 1);
1352
+ if (index == 5) return uvec3(1, 1, 0);
1353
+ if (index == 6) return uvec3(1, 1, 1);
1354
+ return uvec3(0, 0, 0);
1355
+ }
1356
+
1357
+ // Get color for a channel.
1358
+ // get the color per color channel
1359
+ //
1360
+ // Parameters:
1361
+ // index - int: Channel index (0-6)
1362
+ //
1363
+ // Returns:
1364
+ // vec3: RGB color values for the specified channel
1365
+ vec3 getChannelColor(int index) {
1366
+ if (index == 0) return color0.xyz;
1367
+ if (index == 1) return color1.xyz;
1368
+ if (index == 2) return color2.xyz;
1369
+ if (index == 3) return color3.xyz;
1370
+ if (index == 4) return color4.xyz;
1371
+ if (index == 5) return color5.xyz;
1372
+ if (index == 6) return color6.xyz;
1373
+ return vec3(0.0, 0.0, 0.0);
1374
+ }
1375
+
1376
+ // Get opacity for a channel
1377
+ // get the opacity (used as visibility) per color channel
1378
+ //
1379
+ // Parameters:
1380
+ // index - int: Channel index (0-6)
1381
+ //
1382
+ // Returns:
1383
+ // float: Opacity value (0.0-1.0) for the specified channel
1384
+ float getChannelOpacity(int index) {
1385
+ if (index == 0) return color0.w;
1386
+ if (index == 1) return color1.w;
1387
+ if (index == 2) return color2.w;
1388
+ if (index == 3) return color3.w;
1389
+ if (index == 4) return color4.w;
1390
+ if (index == 5) return color5.w;
1391
+ if (index == 6) return color6.w;
1392
+ return 0.0;
1393
+ }
1394
+
1395
+ // ========================================
1396
+ // PAGE TABLE DECODING
1397
+ // ========================================
1398
+
1399
+ /**
1400
+ * retrieving the brick based on:
1401
+ * location -- normalized coordinate
1402
+ * targetRes -- target resolution
1403
+ * channel -- physical channel slot
1404
+ * rnd -- random number for jittering requests
1405
+ * query -- whether to query the brick (we dont query for interblock interpolation)
1406
+ * colorIndex -- color index for querying the min max values
1407
+ *
1408
+ * returns:
1409
+ * w >= 0 -- xyz contains brick cache coordinate, w stores resolution
1410
+ * w == -1 -- not resident in any resolution, should be treated as empty
1411
+ * w == -2 -- empty (with respect to current transfer function)
1412
+ * w == -3 -- constant full (with respect to current transfer function)
1413
+ * w == -4 -- constant value within range, x stores that value
1414
+ *
1415
+ * bit layout:
1416
+ * [1] 31 | 0 — flag resident
1417
+ * [1] 30 | 1 — flag init
1418
+ * [7] 23…29 | 2…8 — min → 128
1419
+ * [7] 16…22 | 9…15 — max → 128
1420
+ * [6] 10…15 | 16…21 — x offset in brick cache → max 64
1421
+ * [6] 4…9 | 22…27 — y offset in brick cache → max 64
1422
+ * [4] 0…3 | 28…31 — z offset in brick cache → max 16, effectively 4
1423
+ */
1424
+
1425
+ /*
1426
+ Page table entry format (32 bits):
1427
+ [31] | 0 — flag resident (1=loaded in cache)
1428
+ [30] | 1 — flag init (1=initialized)
1429
+ [29:23] | 2…8 — min value (7 bits) → 128 levels
1430
+ [22:16] | 9…15 — max value (7 bits) → 128 levels
1431
+ [15:10] | 16…21 — x offset in brick cache (6 bits) → 64 bricks
1432
+ [9:4] | 22…27 — y offset in brick cache (6 bits) → 64 bricks
1433
+ [3:0] | 28…31 — z offset in brick cache (4 bits) → 16 bricks
1434
+ */
1435
+
1436
+ // Query page table to find brick location and status
1437
+ // Searches for a brick at the specified location across multiple resolution levels
1438
+ // and returns its cache coordinates and status information
1439
+ //
1440
+ // Parameters:
1441
+ // location - vec3: Normalized coordinates (0-1) within the volume
1442
+ // targetRes - int: Target resolution level to start searching from
1443
+ // channel - int: Channel index (0-6) to query
1444
+ // rnd - float: Random value (0-1) used for brick loading request selection
1445
+ // query - bool: Whether to allow brick loading requests (true) or just query (false)
1446
+ // colorIndex - int
1447
+ //
1448
+ // Returns:
1449
+ // ivec4: (x_offset, y_offset, z_offset, status) where:
1450
+ // - x_offset, y_offset, z_offset: Brick cache coordinates if found
1451
+ // - status: Resolution level (>=0) if found, or status code:
1452
+ // * -1: Not found at any resolution level
1453
+ // * -2: Empty brick (all values below threshold)
1454
+ // * -3: Constant full brick (all values above threshold)
1455
+ // * -4: Constant value brick (uniform value)
1456
+ // add maxres here
1457
+ ivec4 getBrickLocation(vec3 location, int targetRes, int channel, float rnd, bool query, int colorIndex) {
1458
+
1459
+ // min max for current color
1460
+ vec2 clim = getClim(colorIndex);
1461
+
1462
+ // resolution ranges, TODO: connect this back to color
1463
+ int channelMin = getRes(channel).x;
1464
+ int channelMax = getRes(channel).y;
1465
+
1466
+ // Clamp resolution to channel's available range
1467
+ int currentRes = clamp(targetRes, channelMin, channelMax);
1468
+ currentRes = clamp(currentRes, resGlobal.x, resGlobal.y);
1469
+ int lowestRes = clamp(resGlobal.y, channelMin, channelMax);
1470
+
1471
+ // Determine if this channel should request brick loading.
1472
+ // request the current channel based on probability
1473
+ bool requestChannel = false;
1474
+ if (int(floor(rnd * float(maxChannels))) == colorIndex) {
1475
+ requestChannel = true;
1476
+ }
1477
+
1478
+ // Try progressively lower resolutions until we find data.
1479
+ // loop through resolutions
1480
+ while (currentRes <= lowestRes) {
1481
+
1482
+ // Calculate page table coordinates for this brick
1483
+ uvec3 anchorPoint = getAnchorPoint(currentRes);
1484
+ vec3 brickLocation = getBrickFromNormalized(location, currentRes);
1485
+ uvec3 channelOffset = getChannelOffset(channel);
1486
+ vec3 coordinate = floor(vec3(anchorPoint * channelOffset)) + brickLocation;
1487
+
1488
+ // Special handling for resolution 0 (highest detail)
1489
+ if (currentRes == 0) {
1490
+ int zExtent = int(ceil(float(voxelExtents.z) / 32.0));
1491
+ coordinate = vec3(anchorPoint) + vec3(0.0, 0.0, zExtent * channel) + brickLocation;
1492
+ }
1493
+
1494
+ // Query the page table.
1495
+ // get PT entry
1496
+ uint ptEntry = texelFetch(pageTableTex, ivec3(coordinate), 0).r;
1497
+
1498
+ // Check if brick is initialized.
1499
+ // check if the PT entry is initialized
1500
+ uint isInit = (ptEntry >> 30u) & 1u;
1501
+ if (isInit == 0u) {
1502
+ currentRes++;
1503
+ // Request brick loading if needed
1504
+ if (requestChannel == true && (gRequest.a + gRequest.b + gRequest.g + gRequest.r == 0.0) && query == true) {
1505
+ gRequest = packPTCoordToRGBA8(uvec3(coordinate));
1506
+ }
1507
+ continue;
1508
+ }
1509
+
1510
+ // Extract min/max values from page table entry.
1511
+ // get the min max values of the brick
1512
+ uint umin = ((ptEntry >> 23u) & 0x7Fu);
1513
+ uint umax = ((ptEntry >> 16u) & 0x7Fu);
1514
+ float min = float(int(umin)) / 127.0;
1515
+ float max = float(int(umax)) / 127.0;
1516
+
1517
+ // Check if brick is empty (all values below threshold).
1518
+ // exit early if brick is constant
1519
+ if (float(max) <= clim.x) {
1520
+ return ivec4(0,0,0,-2);
1521
+ // EMPTY
1522
+ } else if (float(min) >= clim.y) {
1523
+ return ivec4(0,0,0,-3); // CONSTANT FULL
1524
+ } else if ((umax - umin) < 2u) {
1525
+ return ivec4(min,0,0,-4); // CONSTANT OTHER VALUE
1526
+ }
1527
+
1528
+ // Check if brick is resident in cache.
1529
+ // return brick cache location if resident
1530
+ // continue to next resolution if not resident
1531
+ uint isResident = (ptEntry >> 31u) & 1u;
1532
+ if (isResident == 0u) {
1533
+ currentRes++;
1534
+ // Request brick loading if needed
1535
+ if (requestChannel == true && (gRequest.a + gRequest.b + gRequest.g + gRequest.r == 0.0) && query == true) {
1536
+ gRequest = packPTCoordToRGBA8(uvec3(coordinate));
1537
+ }
1538
+ continue;
1539
+ } else {
1540
+ // Extract brick cache coordinates
1541
+ uint xBrickCache = (ptEntry >> 10u) & 0x3Fu;
1542
+ uint yBrickCache = (ptEntry >> 4u) & 0x3Fu;
1543
+ uint zBrickCache = ptEntry & 0xFu;
1544
+ uvec3 brickCacheCoord = uvec3(xBrickCache, yBrickCache, zBrickCache);
1545
+
1546
+ return ivec4(brickCacheCoord, currentRes);
1547
+ }
1548
+ }
1549
+
1550
+ // not resident in any resolution, should be treated as empty
1551
+ return ivec4(0,0,0,-1); // Not found
1552
+ }
1553
+
1554
+ // Request brick loading for a specific location and resolution.
1555
+ // Initiates a request to load a brick from disk into the brick cache.
1556
+ // set the brick request for the specified slot channel
1557
+ //
1558
+ // Parameters:
1559
+ // location - vec3: Normalized world space coordinates (0.0 to 1.0) where the brick is needed
1560
+ // targetRes - int: Target resolution level (0-9, where 0 is highest resolution)
1561
+ // channel - int: Channel index (0-6) for multi-channel datasets
1562
+ // rnd - float: Random value between 0.0 and 1.0 used for load balancing across channels
1563
+ //
1564
+ // Returns:
1565
+ // void: No return value, but sets gRequest output variable if conditions are met
1566
+ void setBrickRequest(vec3 location, int targetRes, int channel, float rnd) {
1567
+ uvec3 anchorPoint = getAnchorPoint(targetRes);
1568
+ vec3 brickLocation = getBrickFromNormalized(location, targetRes);
1569
+ uvec3 channelOffset = getChannelOffset(channel);
1570
+ vec3 coordinate = floor(vec3(anchorPoint * channelOffset)) + brickLocation;
1571
+
1572
+ // Special handling for resolution 0
1573
+ if (targetRes == 0) {
1574
+ int zExtent = int(ceil(float(voxelExtents.z) / 32.0));
1575
+ coordinate = vec3(anchorPoint) + vec3(0.0, 0.0, zExtent * channel) + brickLocation;
1576
+ }
1577
+
1578
+ // Pack coordinates and set request
1579
+ if (int(floor(rnd * float(maxChannels))) == channel) {
1580
+ gRequest = packPTCoordToRGBA8(uvec3(coordinate));
1581
+ }
1582
+ }
1583
+
1584
+ // Track brick usage for cache management.
1585
+ // Records which brick in the cache is being accessed for LRU (Least Recently Used) eviction.
1586
+ // set the usage for the specified brick
1587
+ //
1588
+ // Parameters:
1589
+ // brickCacheOffset - ivec3: 3D coordinates of the brick within the brick cache texture
1590
+ // t_hit_min_os - float: Ray entry time in object space (start of ray-volume intersection)
1591
+ // t_hit_max_os - float: Ray exit time in object space (end of ray-volume intersection)
1592
+ // t_os - float: Current sampling position along the ray in object space
1593
+ // rnd - float: Random value between 0.0 and 1.0 used for probabilistic usage tracking
1594
+ //
1595
+ // Returns:
1596
+ // void: No return value, but sets gUsage output variable to track cache access patterns
1597
+ void setUsage(ivec3 brickCacheOffset, float t_hit_min_os, float t_hit_max_os, float t_os, float rnd) {
1598
+ float normalized_t_os = (t_os - t_hit_min_os) / (t_hit_max_os - t_hit_min_os); // Normalize to 0-1
1599
+ if (normalized_t_os <= rnd || gUsage == vec4(0.0, 0.0, 0.0, 0.0)) {
1600
+ gUsage = vec4(vec3(brickCacheOffset) / 255.0, 1.0);
1601
+ }
1602
+ }
1603
+
1604
+ // ========================================
1605
+ // UTILITY FUNCTIONS
1606
+ // ========================================
1607
+
1608
+ // Get maximum component of a 3D vector.
1609
+ // get the max value of a vec3
1610
+ //
1611
+ // Parameters:
1612
+ // v - vec3: Input 3D vector
1613
+ //
1614
+ // Returns:
1615
+ // float: The maximum value among the x, y, and z components
1616
+ float vec3_max(vec3 v) {
1617
+ return max(v.x, max(v.y, v.z));
1618
+ }
1619
+
1620
+ // Get minimum component of a 3D vector.
1621
+ // get the min value of a vec3
1622
+ //
1623
+ // Parameters:
1624
+ // v - vec3: Input 3D vector
1625
+ //
1626
+ // Returns:
1627
+ // float: The minimum value among the x, y, and z components
1628
+ float vec3_min(vec3 v) {
1629
+ return min(v.x, min(v.y, v.z));
1630
+ }
1631
+
1632
+ // Calculate level-of-detail based on distance.
1633
+ // Uses logarithmic scaling to determine appropriate resolution level.
1634
+ // get the LOD based on the distance to the camera
1635
+ //
1636
+ // Parameters:
1637
+ // distance - float: Distance from camera to sampling point
1638
+ // highestRes - int: Highest available resolution level (typically 0)
1639
+ // lowestRes - int: Lowest available resolution level (typically 9)
1640
+ // lodFactor - float: Scaling factor that controls LOD sensitivity
1641
+ //
1642
+ // Returns:
1643
+ // int: Resolution level index (0-9) where 0 is highest resolution
1644
+ int getLOD(float distance, int highestRes, int lowestRes, float lodFactor) {
1645
+ int lod = int(log2(distance * lodFactor));
1646
+ return clamp(lod, highestRes, lowestRes);
1647
+ }
1648
+
1649
+ // Calculate step size for ray marching at a given resolution.
1650
+ // Determines optimal sampling step size based on voxel dimensions and ray direction.
1651
+ // get the voxel step in object space
1652
+ //
1653
+ // Parameters:
1654
+ // res - int: Resolution level index (0-9, where 0 is highest resolution)
1655
+ // osDir - vec3: Ray direction vector in object space (should be normalized)
1656
+ //
1657
+ // Returns:
1658
+ // float: Optimal step size in object space units for stable ray marching
1659
+ float voxelStepOS(int res, vec3 osDir) {
1660
+ vec3 voxelSize = getScale(res) / vec3(voxelExtents);
1661
+ vec3 dt_vec = voxelSize / abs(osDir);
1662
+ return min(dt_vec.x, min(dt_vec.y, dt_vec.z));
1663
+ }
1664
+
1665
+ // ========================================
1666
+ // INTERPOLATION FUNCTIONS
1667
+ // ========================================
1668
+
1669
+ // Linear interpolation between two values.
1670
+ // Performs smooth interpolation between two scalar values.
1671
+ //
1672
+ // Parameters:
1673
+ // v0 - float: First value to interpolate from
1674
+ // v1 - float: Second value to interpolate to
1675
+ // fx - float: Interpolation factor between 0.0 and 1.0
1676
+ //
1677
+ // Returns:
1678
+ // float: Interpolated value between v0 and v1 based on fx
1679
+ float lerp(float v0, float v1, float fx) {
1680
+ return mix(v0, v1, fx); // (1-fx)·v0 + fx·v1
1681
+ }
1682
+
1683
+ // Bilinear interpolation between four values
1684
+ // Performs 2D interpolation using four corner values arranged in a square
1685
+ //
1686
+ // Parameters:
1687
+ // v00 - float: Bottom-left corner value
1688
+ // v10 - float: Bottom-right corner value
1689
+ // v01 - float: Top-left corner value
1690
+ // v11 - float: Top-right corner value
1691
+ // f - vec2: 2D interpolation factors (x, y) between 0.0 and 1.0
1692
+ //
1693
+ // Returns:
1694
+ // float: Interpolated value from the four corner values
1695
+ float bilerp(float v00, float v10, float v01, float v11, vec2 f) {
1696
+ float c0 = mix(v00, v10, f.x); // Interpolate in X on bottom row
1697
+ float c1 = mix(v01, v11, f.x); // Interpolate in X on top row
1698
+ return mix(c0, c1, f.y); // Now interpolate those in Y
1699
+ }
1700
+
1701
+ // Trilinear interpolation between eight values
1702
+ // Performs 3D interpolation using eight corner values arranged in a cube
1703
+ //
1704
+ // Parameters:
1705
+ // v000 - float: Bottom-left-back corner value
1706
+ // v100 - float: Bottom-right-back corner value
1707
+ // v010 - float: Bottom-left-front corner value
1708
+ // v110 - float: Bottom-right-front corner value
1709
+ // v001 - float: Top-left-back corner value
1710
+ // v101 - float: Top-right-back corner value
1711
+ // v011 - float: Top-left-front corner value
1712
+ // v111 - float: Top-right-front corner value
1713
+ // f - vec3: 3D interpolation factors (x, y, z) between 0.0 and 1.0
1714
+ //
1715
+ // Returns:
1716
+ // float: Interpolated value from the eight corner values
1717
+ float trilerp(
1718
+ float v000, float v100, float v010, float v110,
1719
+ float v001, float v101, float v011, float v111,
1720
+ vec3 f) { // f = fract(coord)
1721
+ // Interpolate along X for each of the four bottom-face voxels
1722
+ float c00 = mix(v000, v100, f.x);
1723
+ float c10 = mix(v010, v110, f.x);
1724
+ float c01 = mix(v001, v101, f.x);
1725
+ float c11 = mix(v011, v111, f.x);
1726
+
1727
+ // Interpolate those along Y
1728
+ float c0 = mix(c00, c10, f.y);
1729
+ float c1 = mix(c01, c11, f.y);
1730
+
1731
+ // Final interpolation along Z
1732
+ return mix(c0, c1, f.z);
1733
+ }
1734
+
1735
+ // ========================================
1736
+ // BRICK CACHE SAMPLING
1737
+ // ========================================
1738
+
1739
+ // Sample a value from the brick cache texture.
1740
+ // Converts brick coordinates and voxel position to texture coordinates for sampling.
1741
+ // sample the brick cache based on the brick cache coordinate and the in-brick coordinate
1742
+ //
1743
+ // Parameters:
1744
+ // brickCacheCoord - vec3: 3D coordinates of the brick within the brick cache
1745
+ // voxelInBrick - vec3: 3D coordinates of the voxel within the brick (0-31 in each dimension)
1746
+ //
1747
+ // Returns:
1748
+ // float: Sampled voxel value from the brick cache texture (typically normalized 0.0-1.0)
1749
+ float sampleBrick(vec3 brickCacheCoord, vec3 voxelInBrick) {
1750
+ vec3 brickCacheCoordNormalized = vec3(
1751
+ (float(brickCacheCoord.x) * BRICK_SIZE + float(voxelInBrick.x)) / BRICK_CACHE_SIZE_X,
1752
+ (float(brickCacheCoord.y) * BRICK_SIZE + float(voxelInBrick.y)) / BRICK_CACHE_SIZE_Y,
1753
+ (float(brickCacheCoord.z) * BRICK_SIZE + float(voxelInBrick.z)) / BRICK_CACHE_SIZE_Z
1754
+ );
1755
+ return texture(brickCacheTex, brickCacheCoordNormalized).r;
1756
+ }
1757
+
1758
+ /**
1759
+ * main renderloop
1760
+ */
1761
+ void main(void) {
1762
+
1763
+ // ========================================
1764
+ // INITIALIZATION
1765
+ // ========================================
1766
+
1767
+ // Initialize all render targets (multiple output textures)
1768
+ gRequest = vec4(0,0,0,0); // Brick loading requests
1769
+ gUsage = vec4(0,0,0,0); // Brick usage tracking
1770
+ gColor = vec4(0.0, 0.0, 0.0, 0.0); // Final color output
1771
+
1772
+ // out color sums up our accumulated value before writing it into the gColor buffer
1773
+ vec4 outColor = vec4(0.0, 0.0, 0.0, 0.0); // Accumulated color
1774
+
1775
+ // Generate random number for jittered sampling (reduces artifacts)
1776
+ float rnd = random();
1777
+
1778
+ // Get the lowest available resolution level
1779
+ int lowestDataRes = getLowestRes();
1780
+
1781
+ // ========================================
1782
+ // RAY-VOLUME INTERSECTION
1783
+ // ========================================
1784
+
1785
+ // Normalize the view ray direction
1786
+ vec3 ws_rayDir = normalize(rayDirUnnorm);
1787
+
1788
+ // Calculate intersection with volume bounding box
1789
+ // Returns (entry_time, exit_time) for the ray-box intersection
1790
+ vec2 t_hit = intersect_hit(cameraCorrected, ws_rayDir);
1791
+ if (t_hit.x >= t_hit.y) { discard; } // Ray misses volume entirely
1792
+
1793
+ t_hit.x = max(t_hit.x, 0.0); // Clamp entry to 0 (no negative distances)
1794
+ float t = t_hit.x;
1795
+
1796
+ // Calculate distance from camera for LOD selection
1797
+ float distance = abs((cameraCorrected / boxSize).z + (ws_rayDir / boxSize).z * t );
1798
+
1799
+ // ========================================
1800
+ // COORDINATE SPACE CONVERSION
1801
+ // ========================================
1802
+
1803
+ // Convert from world space to object space (normalized 0-1 coordinates)
1804
+ float ws2os = length(ws_rayDir / boxSize); // Scale factor for conversion
1805
+ float t_hit_min_os = t_hit.x * ws2os; // Entry point in object space
1806
+ float t_hit_max_os = t_hit.y * ws2os; // Exit point in object space
1807
+ float t_os = t_hit_min_os; // Current position in object space
1808
+
1809
+ // Calculate effective LOD factor based on volume size.
1810
+ // voxel edge is the max extent of the volume
1811
+ float voxelEdge = float(max(voxelExtents.x, max(voxelExtents.y, voxelExtents.z)));
1812
+
1813
+ // calculate LOD factor based on the voxel edge
1814
+ float lodFactorEffective = lodFactor * voxelEdge / 256.0;
1815
+
1816
+ // ========================================
1817
+ // RESOLUTION AND SAMPLING SETUP
1818
+ // ========================================
1819
+
1820
+ // Determine target resolution based on distance (LOD)
1821
+ int targetRes = getLOD(t, 0, 9, lodFactorEffective);
1822
+
1823
+ // Set adaptive stepping resolution
1824
+ int stepResAdaptive = renderRes;
1825
+ int stepResEffective = clamp(stepResAdaptive, 0, lowestDataRes);
1826
+
1827
+ // Convert ray to object space coordinates
1828
+ vec3 os_rayDir = normalize(ws_rayDir / boxSize);
1829
+ vec3 os_rayOrigin = cameraCorrected / boxSize + vec3(0.5);
1830
+
1831
+ // Calculate step size based on current resolution
1832
+ float dt = voxelStepOS(stepResEffective, os_rayDir);
1833
+
1834
+ // ========================================
1835
+ // SAMPLING POSITION INITIALIZATION
1836
+ // ========================================
1837
+
1838
+ // Convert to normalized sampling coordinates (0-1 range)
1839
+ vec3 p = cameraCorrected + t_hit.x * ws_rayDir;
1840
+ p = p / boxSize + vec3(0.5); // Transform to 0-1 range
1841
+
1842
+ // Calculate step vector in normalized space
1843
+ vec3 dp = (os_rayDir * dt);
1844
+
1845
+ // Apply jittered sampling to reduce artifacts
1846
+ p += dp * (rnd);
1847
+ // Avoid boundary issues
1848
+ p = clamp(p, 0.0 + 0.0000028, 1.0 - 0.0000028);
1849
+
1850
+ // ========================================
1851
+ // RENDERING VARIABLES
1852
+ // ========================================
1853
+
1854
+ // Color accumulation for front-to-back compositing.
1855
+ // color accumulation variables, are calculated per 'slice'
1856
+ vec3 rgbCombo = vec3(0.0);
1857
+ float total = 0.0;
1858
+
1859
+ // For alpha blending.
1860
+ // alpha accumulation variable runs globally
1861
+ float alphaMultiplicator = 1.0;
1862
+
1863
+ // Request tracking (for brick loading).
1864
+ // if we have a request for a brick which not visible in lower
1865
+ // resolutions, we can overwrite it once
1866
+ bool overWrittenRequest = false;
1867
+
1868
+ // Current state tracking
1869
+ vec3 currentTargetResPTCoord = vec3(0,0,0);
1870
+ int currentLOD = targetRes;
1871
+
1872
+ // ========================================
1873
+ // CHANNEL-SPECIFIC CONSTANTS
1874
+ // ========================================
1875
+
1876
+ // Pre-compute channel properties for efficiency.
1877
+ // constants per color channel
1878
+ vec3 [] c_color = vec3[7](getChannelColor(0), getChannelColor(1), getChannelColor(2), getChannelColor(3), getChannelColor(4), getChannelColor(5), getChannelColor(6));
1879
+ float [] c_opacity = float[7](getChannelOpacity(0), getChannelOpacity(1), getChannelOpacity(2), getChannelOpacity(3), getChannelOpacity(4), getChannelOpacity(5), getChannelOpacity(6));
1880
+ // resolution ranges (currently) per color channel
1881
+ // TODO: figure out how to hook it up with frontend
1882
+ int [] c_res_min = int[7](getRes(0).x, getRes(1).x, getRes(2).x, getRes(3).x, getRes(4).x, getRes(5).x, getRes(6).x);
1883
+ int [] c_res_max = int[7](getRes(0).y, getRes(1).y, getRes(2).y, getRes(3).y, getRes(4).y, getRes(5).y, getRes(6).y);
1884
+ vec3 [] res_color = vec3[10](
1885
+ vec3(1.0, 0.0, 0.0),
1886
+ vec3(0.0, 0.0, 1.0),
1887
+ vec3(0.0, 1.0, 0.0),
1888
+ vec3(1.0, 0.0, 1.0),
1889
+ vec3(0.0, 1.0, 1.0),
1890
+ vec3(1.0, 1.0, 0.0),
1891
+ vec3(1.0, 0.5, 0.5),
1892
+ vec3(0.5, 0.5, 1.0),
1893
+ vec3(0.5, 1.0, 0.5),
1894
+ vec3(0.5, 0.5, 0.5)
1895
+ );
1896
+
1897
+ // ========================================
1898
+ // PER-CHANNEL STATE ARRAYS
1899
+ // ========================================
1900
+
1901
+ // Current state for each channel.
1902
+ // current state variables per color channel
1903
+
1904
+ // current resolution
1905
+ int [] c_res_current = int[7](0,0,0,0,0,0,0);
1906
+ // current value
1907
+ float [] c_val_current = float[7](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
1908
+ // current brick cache coordinate
1909
+ vec3 [] c_brickCacheCoord_current = vec3[7](vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));
1910
+ // current voxel in current resolution
1911
+ vec3 [] c_voxel_current = vec3[7](vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));
1912
+ // current pagetable coordinate
1913
+ vec3 [] c_ptCoord_current = vec3[7](vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));
1914
+ // current render mode -- 0: empty (add 0), 1: constant (add current val), 2: voxel (query new voxel)
1915
+ // upon change of PT we re-query anyways
1916
+ int [] c_renderMode_current = int[7](-1, -1, -1, -1, -1, -1, -1);
1917
+
1918
+ // Adjacent brick caching for interpolation
1919
+ // current pagetable coordinate of the adjacent bricks in X, Y, Z or diagonal direction
1920
+ vec3 [] c_PT_X_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1921
+ vec3 [] c_PT_Y_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1922
+ vec3 [] c_PT_Z_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1923
+ vec3 [] c_PT_XYZ_adjacent = vec3[7](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1924
+ // corresponding brick coordinates of the adjacent bricks in X, Y, Z or diagonal direction
1925
+ vec4 [] c_brick_X_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1926
+ vec4 [] c_brick_Y_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1927
+ vec4 [] c_brick_Z_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1928
+ vec4 [] c_brick_XYZ_adjacent = vec4[7](vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0), vec4(-1.0));
1929
+
1930
+ // Min/max tracking for MIP/MinIP rendering.
1931
+ // min and max values of the current color
1932
+ // used for minimum/maximum intensity projection
1933
+ float [] c_minVal = float[7](-1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
1934
+ float [] c_maxVal = float[7](0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
1935
+
1936
+ // Per-resolution coordinate tracking
1937
+ vec3 [] r_ptCoord = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1938
+ vec3 [] r_voxel = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1939
+ vec3 [] r_prevPTCoord = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1940
+ vec3 [] r_prevVoxel = vec3[10](vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0), vec3(-1.0));
1941
+
1942
+ // resolution changed flag
1943
+ bool resolutionChanged = false;
1944
+ // number of repetitions (for debugging purposes)
1945
+ int reps = 0;
1946
+
1947
+ // ========================================
1948
+ // MAIN RAY-MARCHING LOOP
1949
+ // ========================================
1950
+
1951
+ // while we are 'in' the volume.
1952
+ // Continue marching until we exit the volume or reach maximum opacity.
1953
+ while (t_os < t_hit_max_os && t_os >= t_hit_min_os
1954
+ && vec3_max(p) < 1.0 && vec3_min(p) >= 0.0
1955
+ ) {
1956
+
1957
+ // Reset per-sample accumulation.
1958
+ // initialize slice values
1959
+ vec3 rgbCombo = vec3(0.0);
1960
+ float total = 0.0;
1961
+
1962
+ // Update target resolution based on current distance (with jitter).
1963
+ // calculate target resolution based on distance and lod factor
1964
+ targetRes = getLOD(t, 0, 9, lodFactorEffective * (0.999 + 0.002 * rnd));
1965
+
1966
+ // ========================================
1967
+ // RESOLUTION CHANGE HANDLING
1968
+ // ========================================
1969
+
1970
+ // if target resolution changed, update the current resolution and stepsize
1971
+ if (targetRes != currentLOD) {
1972
+ currentLOD = targetRes;
1973
+ stepResAdaptive++;
1974
+ stepResEffective = clamp(stepResAdaptive, 0, lowestDataRes);
1975
+
1976
+ // Adjust sampling position for new resolution
1977
+ p -= dp * rnd;
1978
+ dt = voxelStepOS(stepResEffective, os_rayDir);
1979
+ dp = os_rayDir * dt;
1980
+ p += dp * rnd;
1981
+ resolutionChanged = true;
1982
+
1983
+ // Check bounds after resolution change
1984
+ if (p.x < 0.0 || p.x >= 1.0 || p.y < 0.0 || p.y >= 1.0 || p.z < 0.0 || p.z >= 1.0) {
1985
+ break;
1986
+ }
1987
+ } else {
1988
+ resolutionChanged = false;
1989
+ }
1990
+
1991
+ // ========================================
1992
+ // UPDATE COORDINATES FOR ALL RESOLUTIONS
1993
+ // ========================================
1994
+
1995
+ // Calculate page table coordinates and voxel positions for all resolution levels
1996
+ for (int r = 0; r < 10; r++) {
1997
+ r_prevPTCoord[r] = r_ptCoord[r];
1998
+ r_prevVoxel[r] = r_voxel[r];
1999
+ r_ptCoord[r] = getBrickFromNormalized(p, r);
2000
+ r_voxel[r] = getVoxelFromNormalized(p, r);
2001
+ }
2002
+
2003
+ // ========================================
2004
+ // RENDER MODE DEFINITIONS
2005
+ // ========================================
2006
+ // 0: empty brick (no data)
2007
+ // 1: constant brick (uniform value)
2008
+ // 2: voxel brick (variable data)
2009
+
2010
+ // initialize the per channel slice values
2011
+ vec3 sliceColor = vec3(0.0);
2012
+ float sliceAlpha = 0.0;
2013
+
2014
+ // ========================================
2015
+ // MULTI-CHANNEL SAMPLING
2016
+ // ========================================
2017
+
2018
+ // Process each channel independently.
2019
+ // iterate over up to 7 channels by color
2020
+ for (int c = 0; c < 7; c++) {
2021
+ // Skip channels with zero opacity.
2022
+ // skip if opacity is 0 or if color is not mapped to a physical slot
2023
+ if (c_opacity[c] <= 0.000001) {
2024
+ continue;
2025
+ } else if (channelMapping[c] == -1) {
2026
+ continue;
2027
+ }
2028
+
2029
+ // physical slot in pagetable
2030
+ int slot = channelMapping[c];
2031
+
2032
+ // keep track of status
2033
+ bool newBrick = false;
2034
+ bool newVoxel = false;
2035
+ // best possible resolution
2036
+ int bestRes = clamp(targetRes, c_res_min[c], c_res_max[c]);
2037
+
2038
+ // Check if we need to load a new brick at a better resolution.
2039
+ // check if any new better resolution could be available, if so, we need to re-query the brick
2040
+ bool betterResChanged = false;
2041
+ for (int r = bestRes; r <= c_res_current[c]; r++ ) {
2042
+ if (r_ptCoord[r] != r_prevPTCoord[r]) {
2043
+ betterResChanged = true;
2044
+ break;
2045
+ }
2046
+ }
2047
+
2048
+ // Determine if we need to load new brick data.
2049
+ // check if we need to re-query the brick / voxel or reuse past 'val'
2050
+ if (r_ptCoord[bestRes] != r_prevPTCoord[bestRes]
2051
+ || c_renderMode_current[c] == -1
2052
+ || resolutionChanged == true
2053
+ || betterResChanged
2054
+ ) {
2055
+ newBrick = true;
2056
+ newVoxel = true;
2057
+ } else if (c_renderMode_current[c] == 2) {
2058
+ newVoxel = true;
2059
+ } else if (c_renderMode_current[c] == 0) {
2060
+ continue; // Skip empty bricks
2061
+ }
2062
+
2063
+ // ========================================
2064
+ // BRICK LOADING AND CACHING
2065
+ // ========================================
2066
+
2067
+ // check if a new brick is available in the best possible resolution
2068
+ if (newBrick) {
2069
+ // Query page table for brick location and status
2070
+ ivec4 brickCacheInfo = getBrickLocation(p, bestRes, slot, rnd, true, c);
2071
+ // check information about the newly queried brick
2072
+ // if the res is not at best res, possibly the same as previous brick
2073
+ if (brickCacheInfo.w == -1 || brickCacheInfo.w == -2) {
2074
+ // Empty brick - no data available.
2075
+ // we can skip the rest of the loop
2076
+ c_val_current[c] = 0.0;
2077
+ c_renderMode_current[c] = 0;
2078
+ c_minVal[c] = 0.0;
2079
+ continue;
2080
+ } else if (brickCacheInfo.w == -3) {
2081
+ // Solid brick - constant maximum value.
2082
+ // we set the value and do not need to query a voxel
2083
+ c_val_current[c] = 1.0;
2084
+ c_renderMode_current[c] = 1;
2085
+ c_maxVal[c] = 1.0;
2086
+ newVoxel = false;
2087
+ } else if (brickCacheInfo.w == -4) {
2088
+ // Constant brick - uniform value.
2089
+ // static value -- we set the value and do not need to query a voxel
2090
+ float val = float(brickCacheInfo.x);
2091
+ c_val_current[c] = max(0.0, (val - getClim(c).x) / (getClim(c).y - getClim(c).x));
2092
+ c_renderMode_current[c] = 1;
2093
+ newVoxel = false;
2094
+ } else if (brickCacheInfo.w >= 0) {
2095
+ // Voxel brick - variable data, load from cache.
2096
+ // new brick -- we set the coordinate and resolution and need to query a voxel
2097
+ c_res_current[c] = brickCacheInfo.w;
2098
+ c_ptCoord_current[c] = r_ptCoord[c_res_current[c]];
2099
+ c_brickCacheCoord_current[c] = vec3(brickCacheInfo.xyz);
2100
+ c_renderMode_current[c] = 2;
2101
+ newVoxel = true;
2102
+
2103
+ // Track brick usage for cache management.
2104
+ // we set the usage of the brick based on the channel and the relative distance into the cube
2105
+ if (int(floor(rnd * float(maxChannels))) == c) {
2106
+ setUsage(brickCacheInfo.xyz, t_hit_min_os, t_hit_max_os, t_os, rnd);
2107
+ }
2108
+ }
2109
+ }
2110
+
2111
+ // ========================================
2112
+ // VOXEL SAMPLING WITH INTERPOLATION
2113
+ // ========================================
2114
+
2115
+ // we need to query a new voxel e.g. sample the brick cache
2116
+ if (newVoxel) {
2117
+ c_voxel_current[c] = r_voxel[c_res_current[c]];
2118
+
2119
+ // we clamp the coordinate to be inside the brick and sample the volume
2120
+ reps++;
2121
+
2122
+ // Calculate position within the brick (0-31 range)
2123
+ vec3 voxelInBrick = mod(c_voxel_current[c], 32.0);
2124
+ vec3 clampedVoxelInBrick = clamp(voxelInBrick, 0.5, 31.5);
2125
+ // Sample the brick cache texture
2126
+ float val = sampleBrick(c_brickCacheCoord_current[c].xyz, clampedVoxelInBrick);
2127
+
2128
+ // ========================================
2129
+ // HIGH-QUALITY INTERPOLATION (renderRes == 0)
2130
+ // ========================================
2131
+
2132
+ // interblock interpolation
2133
+ if (renderRes == 0) {
2134
+ // calculate what axis we need to interpolate
2135
+
2136
+ // Check if we're near brick boundaries (need interpolation)
2137
+ bvec3 clampedMin = lessThan(voxelInBrick, clampedVoxelInBrick);
2138
+ bvec3 clampedMax = greaterThan(voxelInBrick, clampedVoxelInBrick);
2139
+ bvec3 clamped = bvec3(clampedMin.x || clampedMax.x, clampedMin.y || clampedMax.y, clampedMin.z || clampedMax.z);
2140
+ vec3 diff = voxelInBrick - clampedVoxelInBrick;
2141
+
2142
+ if (any(clampedMin) || any(clampedMax)) {
2143
+ int boundaryAxes = int(clamped.x) + int(clamped.y) + int(clamped.z);
2144
+ float f = 0.0;
2145
+
2146
+ if (boundaryAxes == 1) {
2147
+ // Linear interpolation across one boundary
2148
+ vec3 otherGlobalVoxelPos = vec3(0,0,0);
2149
+ vec3 otherP = vec3(0,0,0);
2150
+ float otherVoxelVal = 0.0;
2151
+
2152
+ // Determine which axis we're interpolating across
2153
+ if (clampedMin.x) {
2154
+ otherGlobalVoxelPos = c_voxel_current[c] - vec3(1.0, 0.0, 0.0);
2155
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2156
+ f = abs(diff.x);
2157
+ } else if (clampedMax.x) {
2158
+ otherGlobalVoxelPos = c_voxel_current[c] + vec3(1.0, 0.0, 0.0);
2159
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2160
+ f = abs(diff.x);
2161
+ } else if (clampedMin.y) {
2162
+ otherGlobalVoxelPos = c_voxel_current[c] - vec3(0.0, 1.0, 0.0);
2163
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2164
+ f = abs(diff.y);
2165
+ } else if (clampedMax.y) {
2166
+ otherGlobalVoxelPos = c_voxel_current[c] + vec3(0.0, 1.0, 0.0);
2167
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2168
+ f = abs(diff.y);
2169
+ } else if (clampedMin.z) {
2170
+ otherGlobalVoxelPos = c_voxel_current[c] - vec3(0.0, 0.0, 1.0);
2171
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2172
+ f = abs(diff.z);
2173
+ } else if (clampedMax.z) {
2174
+ otherGlobalVoxelPos = c_voxel_current[c] + vec3(0.0, 0.0, 1.0);
2175
+ otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2176
+ f = abs(diff.z);
2177
+ }
2178
+
2179
+ // Sample the neighboring voxel
2180
+ vec3 otherPTcoord = getBrickFromNormalized(otherP, c_res_current[c]);
2181
+ otherPTcoord = getBrickFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2182
+ vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0);
2183
+ otherVoxelInBrick -= diff;
2184
+
2185
+ // Check if neighbor is outside volume bounds
2186
+ if (otherP.x < 0.0 || otherP.x >= 1.0 || otherP.y < 0.0 || otherP.y >= 1.0 || otherP.z < 0.0 || otherP.z >= 1.0) {
2187
+ otherVoxelVal = val;
2188
+ } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz && c_brick_XYZ_adjacent[c].w >= 0.0) {
2189
+ // Use cached adjacent brick
2190
+ otherVoxelVal = sampleBrick(c_brick_XYZ_adjacent[c].xyz, otherVoxelInBrick);
2191
+ } else {
2192
+ // Load new adjacent brick
2193
+ ivec4 otherBrickCacheInfo = ivec4(-1);
2194
+ if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz) {
2195
+ otherBrickCacheInfo = ivec4(c_brick_XYZ_adjacent[c]);
2196
+ } else {
2197
+ otherBrickCacheInfo = getBrickLocation(otherP, c_res_current[c], slot, rnd, false, c);
2198
+ }
2199
+ if (otherBrickCacheInfo.w == -1 || otherBrickCacheInfo.w == -2) {
2200
+ otherVoxelVal = val;
2201
+ } else if (otherBrickCacheInfo.w == -3) {
2202
+ otherVoxelVal = 1.0;
2203
+ } else if (otherBrickCacheInfo.w == -4) {
2204
+ otherVoxelVal = float(otherBrickCacheInfo.x);
2205
+ } else {
2206
+ // TODO: we do not recalculate the voxelInBrick based on the resolution
2207
+ otherVoxelVal = sampleBrick(vec3(otherBrickCacheInfo.xyz), otherVoxelInBrick);
2208
+ }
2209
+ c_PT_XYZ_adjacent[c] = getBrickFromVoxel(otherGlobalVoxelPos, c_res_current[c]);
2210
+ c_brick_XYZ_adjacent[c] = vec4(otherBrickCacheInfo);
2211
+ }
2212
+
2213
+ // Perform linear interpolation
2214
+ float originalVal = val;
2215
+ val = lerp(originalVal, otherVoxelVal, f);
2216
+ } else if (boundaryAxes == 2) {
2217
+ // Bilinear interpolation across two boundaries
2218
+ vec3 offA = vec3(0.0);
2219
+ vec3 offB = vec3(0.0);
2220
+ vec2 f = vec2(0.0);
2221
+
2222
+ // Determine which two axes we're interpolating across
2223
+ if (clamped.x && clamped.y) {
2224
+ offA.x = clampedMin.x ? -1.0 : 1.0;
2225
+ offB.y = clampedMin.y ? -1.0 : 1.0;
2226
+ f = vec2(abs(diff.x), abs(diff.y));
2227
+ } else if (clamped.x && clamped.z) {
2228
+ offA.x = clampedMin.x ? -1.0 : 1.0;
2229
+ offB.z = clampedMin.z ? -1.0 : 1.0;
2230
+ f = vec2(abs(diff.x), abs(diff.z));
2231
+ } else if (clamped.y && clamped.z) {
2232
+ offA.y = clampedMin.y ? -1.0 : 1.0;
2233
+ offB.z = clampedMin.z ? -1.0 : 1.0;
2234
+ f = vec2(abs(diff.y), abs(diff.z));
2235
+ }
2236
+
2237
+ // Macro for sampling at offset positions
2238
+ #define SAMPLE_AT_OFFSET(OFF, DEST) { vec3 otherGlobalVoxelPos = c_voxel_current[c] + (OFF); vec3 otherP = getNormalizedFromVoxel( otherGlobalVoxelPos, c_res_current[c]); if ( any(lessThan(otherP, vec3(0.0))) || any(greaterThanEqual(otherP, vec3(1.0))) ) { DEST = val; } else { vec3 otherPTcoord = getBrickFromNormalized( otherP, c_res_current[c]); vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0) - diff; bool matched = false; if (otherPTcoord == c_PT_X_adjacent[c].xyz && c_brick_X_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_X_adjacent[c].xyz, otherVoxelInBrick); matched = true; } else if (otherPTcoord == c_PT_Y_adjacent[c].xyz && c_brick_Y_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Y_adjacent[c].xyz, otherVoxelInBrick); matched = true; } else if (otherPTcoord == c_PT_Z_adjacent[c].xyz && c_brick_Z_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Z_adjacent[c].xyz, otherVoxelInBrick); matched = true; } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz && c_brick_XYZ_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_XYZ_adjacent[c].xyz, otherVoxelInBrick); matched = true; } ivec4 info = ivec4(-1); if (otherPTcoord == c_PT_X_adjacent[c].xyz) { info = ivec4(c_brick_X_adjacent[c]); } else if (otherPTcoord == c_PT_Y_adjacent[c].xyz) { info = ivec4(c_brick_Y_adjacent[c]); } else if (otherPTcoord == c_PT_Z_adjacent[c].xyz) { info = ivec4(c_brick_Z_adjacent[c]); } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz) { info = ivec4(c_brick_XYZ_adjacent[c]); } else { info = getBrickLocation(otherP, c_res_current[c], slot, rnd, false, c); } if (!matched) { if (info.w == -1 || info.w == -2) { DEST = val; } else if (info.w == -3) { DEST = 1.0; } else if (info.w == -4) { DEST = float(info.x); } else { DEST = sampleBrick(vec3(info.xyz), otherVoxelInBrick); } if (abs((OFF).x) > 0.5 && abs((OFF).y) < 0.5 && abs((OFF).z) < 0.5) { c_PT_X_adjacent[c] = otherPTcoord; c_brick_X_adjacent[c] = vec4(info); } else if (abs((OFF).y) > 0.5 && abs((OFF).x) < 0.5 && abs((OFF).z) < 0.5) { c_PT_Y_adjacent[c] = otherPTcoord; c_brick_Y_adjacent[c] = vec4(info); } else if (abs((OFF).z) > 0.5 && abs((OFF).x) < 0.5 && abs((OFF).y) < 0.5) { c_PT_Z_adjacent[c] = otherPTcoord; c_brick_Z_adjacent[c] = vec4(info); } else { c_PT_XYZ_adjacent[c] = otherPTcoord; c_brick_XYZ_adjacent[c] = vec4(info); } } } }
2239
+
2240
+ // Sample the four corners for bilinear interpolation
2241
+ float v00 = val;
2242
+ float v10; float v01; float v11;
2243
+ SAMPLE_AT_OFFSET(offA, v10);
2244
+ SAMPLE_AT_OFFSET(offB, v01);
2245
+ SAMPLE_AT_OFFSET(offA + offB, v11);
2246
+
2247
+ val = bilerp(v00, v10, v01, v11, f);
2248
+
2249
+ #undef SAMPLE_AT_OFFSET
2250
+
2251
+ } else if (boundaryAxes == 3) {
2252
+ // Trilinear interpolation across all three boundaries
2253
+
2254
+ vec3 offA = vec3(0.0);
2255
+ vec3 offB = vec3(0.0);
2256
+ vec3 offC = vec3(0.0);
2257
+ vec3 f = vec3(0.0);
2258
+
2259
+ offA.x = clampedMin.x ? -1.0 : 1.0;
2260
+ offB.y = clampedMin.y ? -1.0 : 1.0;
2261
+ offC.z = clampedMin.z ? -1.0 : 1.0;
2262
+
2263
+ f = vec3(abs(diff.x), abs(diff.y), abs(diff.z));
2264
+
2265
+ // Macro for sampling at offset positions
2266
+ #define SAMPLE_AT_OFFSET(OFF, DEST) { vec3 otherGlobalVoxelPos = c_voxel_current[c] + (OFF); vec3 otherP = getNormalizedFromVoxel(otherGlobalVoxelPos, c_res_current[c]); if (any(lessThan(otherP, vec3(0.0))) || any(greaterThanEqual(otherP, vec3(1.0)))) { DEST = val; } else { vec3 otherPTcoord = getBrickFromNormalized(otherP, c_res_current[c]); vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0) - diff; if (otherPTcoord == c_PT_X_adjacent[c] && c_brick_X_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_X_adjacent[c].xyz, otherVoxelInBrick); } else if (otherPTcoord == c_PT_Y_adjacent[c].xyz && c_brick_Y_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Y_adjacent[c].xyz, otherVoxelInBrick); } else if (otherPTcoord == c_PT_Z_adjacent[c].xyz && c_brick_Z_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_Z_adjacent[c].xyz, otherVoxelInBrick); } else if (otherPTcoord == c_PT_XYZ_adjacent[c].xyz && c_brick_XYZ_adjacent[c].w >= 0.0) { DEST = sampleBrick(c_brick_XYZ_adjacent[c].xyz, otherVoxelInBrick); } else { ivec4 otherBrickCacheInfo = getBrickLocation(otherP, c_res_current[c], slot, rnd, false, c); vec3 otherVoxelInBrick = mod(otherGlobalVoxelPos, 32.0) - diff; if (otherBrickCacheInfo.w == -1 || otherBrickCacheInfo.w == -2) { DEST = val; } else if (otherBrickCacheInfo.w == -3) { DEST = 1.0; } else if (otherBrickCacheInfo.w == -4) { DEST = float(otherBrickCacheInfo.x); } else { DEST = sampleBrick(vec3(otherBrickCacheInfo.xyz), otherVoxelInBrick); } } } }
2267
+
2268
+ // Sample all eight corners for trilinear interpolation
2269
+ float v000 = val;
2270
+ float v100; float v010; float v001; float v110; float v101; float v011; float v111;
2271
+ SAMPLE_AT_OFFSET(offA, v100);
2272
+ SAMPLE_AT_OFFSET(offB, v010);
2273
+ SAMPLE_AT_OFFSET(offC, v001);
2274
+ SAMPLE_AT_OFFSET(offA + offB, v110);
2275
+ SAMPLE_AT_OFFSET(offA + offC, v101);
2276
+ SAMPLE_AT_OFFSET(offB + offC, v011);
2277
+ SAMPLE_AT_OFFSET(offA + offB + offC, v111);
2278
+
2279
+ val = trilerp(v000, v100, v010, v001, v110, v101, v011, v111, f);
2280
+
2281
+ #undef SAMPLE_AT_OFFSET
2282
+
2283
+ }
2284
+
2285
+ } else {
2286
+ // No boundary interpolation needed - clear adjacent brick cache.
2287
+ // no adjacent bricks -> reset the adjacent trackers
2288
+ c_PT_X_adjacent[c] = c_PT_Y_adjacent[c] = c_PT_Z_adjacent[c] = c_PT_XYZ_adjacent[c] = vec3(-1.0);
2289
+ c_brick_X_adjacent[c] = c_brick_Y_adjacent[c] = c_brick_Z_adjacent[c] = c_brick_XYZ_adjacent[c] = vec4(-1.0);
2290
+ }
2291
+ }
2292
+
2293
+ // ========================================
2294
+ // VALUE NORMALIZATION AND TRACKING
2295
+ // ========================================
2296
+
2297
+ // Normalize value to 0-1 range using channel-specific contrast limits.
2298
+ // we normalize the (accumulated) value to the range of the color channel
2299
+ c_val_current[c] = max(0.0, (val - getClim(c).x) / (getClim(c).y - getClim(c).x));
2300
+
2301
+ // Track min/max values for MIP/MinIP rendering.
2302
+ // update the min and max values for the min/max projection
2303
+ if (c_minVal[c] == -1.0) {
2304
+ c_minVal[c] = c_val_current[c];
2305
+ } else {
2306
+ c_minVal[c] = min(c_minVal[c], c_val_current[c]);
2307
+ }
2308
+ c_maxVal[c] = max(c_maxVal[c], c_val_current[c]);
2309
+
2310
+ }
2311
+
2312
+ // ========================================
2313
+ // BRICK REQUEST GENERATION
2314
+ // ========================================
2315
+
2316
+ // Request higher resolution bricks if we're using lower resolution than optimal.
2317
+ // potentially overwrite brick request
2318
+ if (!overWrittenRequest
2319
+ && c_res_current[c] != bestRes
2320
+ && c_val_current[c] > 0.0
2321
+ && c_renderMode_current[c] == 2
2322
+ && int(floor(rnd * float(maxChannels))) == c) {
2323
+ setBrickRequest(p, bestRes, slot, rnd);
2324
+ overWrittenRequest = true;
2325
+ }
2326
+
2327
+ // ========================================
2328
+ // CHANNEL COMPOSITING
2329
+ // ========================================
2330
+
2331
+ // Accumulate this channel's contribution.
2332
+ // sum up the values onto the slice values
2333
+ total += c_val_current[c];
2334
+ if (u_renderstyle == 3) {
2335
+ rgbCombo += c_val_current[c] * res_color[targetRes];
2336
+ } else if (u_renderstyle == 4) {
2337
+ rgbCombo += c_val_current[c] * res_color[c_res_current[c]];
2338
+ } else {
2339
+ rgbCombo += c_val_current[c] * c_color[c];
2340
+ }
2341
+
2342
+ }
2343
+
2344
+ // ========================================
2345
+ // FRONT-TO-BACK COMPOSITING
2346
+ // ========================================
2347
+
2348
+ // Clamp total intensity and calculate alpha.
2349
+ // add the calculated slice to the total color
2350
+ total = clamp(total, 0.0, 1.0);
2351
+ sliceAlpha = total * opacity * dt * 32.0; // Scale by step size and brick size
2352
+ sliceColor = rgbCombo;
2353
+
2354
+ // Front-to-back alpha blending
2355
+ outColor.rgb += sliceAlpha * alphaMultiplicator * sliceColor;
2356
+ outColor.a += sliceAlpha * alphaMultiplicator;
2357
+ alphaMultiplicator *= (1.0 - sliceAlpha);
2358
+
2359
+ // Early termination for opaque regions (standard rendering only).
2360
+ // check if we can exit early
2361
+ if (outColor.a > 0.99 && u_renderstyle == 0) { break; }
2362
+
2363
+ // ========================================
2364
+ // ADVANCE RAY POSITION
2365
+ // ========================================
2366
+
2367
+ // Move to next sample position
2368
+ t += dt;
2369
+ p += dp;
2370
+ t_os += dt;
2371
+ }
2372
+
2373
+ // ========================================
2374
+ // RENDERING STYLE POST-PROCESSING
2375
+ // ========================================
2376
+
2377
+ if (u_renderstyle == 1) {
2378
+ // Minimum Intensity Projection (MinIP)
2379
+ // Shows the minimum value encountered along each ray
2380
+ outColor = vec4(0.0);
2381
+ for (int c = 0; c < 7; c++) {
2382
+ if (c_color[c] != vec3(0.0, 0.0, 0.0)) {
2383
+ outColor.rgb += c_minVal[c] * c_color[c];
2384
+ outColor.a += c_minVal[c];
2385
+ }
2386
+ }
2387
+ } else if (u_renderstyle == 0) {
2388
+ // Maximum Intensity Projection (MIP)
2389
+ // Shows the maximum value encountered along each ray
2390
+ outColor = vec4(0.0);
2391
+ for (int c = 0; c < 7; c++) {
2392
+ if (c_color[c] != vec3(0.0, 0.0, 0.0)) {
2393
+ outColor.rgb += c_maxVal[c] * c_color[c];
2394
+ }
2395
+ }
2396
+ outColor.a = 1.0;
2397
+ }
2398
+
2399
+ // ========================================
2400
+ // FINAL OUTPUT
2401
+ // ========================================
2402
+
2403
+ // Convert from linear to sRGB color space and set all render targets
2404
+ gColor = vec4(linear_to_srgb(outColor.r),
2405
+ linear_to_srgb(outColor.g),
2406
+ linear_to_srgb(outColor.b),
2407
+ outColor.a);
2408
+
2409
+ }
2410
+ `, Je = {
2411
+ uniforms: {
2412
+ u_size: { value: new C(1, 1, 1) },
2413
+ clim0: { value: new b(0.2, 0.8) },
2414
+ clim1: { value: new b(0.2, 0.8) },
2415
+ clim2: { value: new b(0.2, 0.8) },
2416
+ clim3: { value: new b(0.2, 0.8) },
2417
+ clim4: { value: new b(0.2, 0.8) },
2418
+ clim5: { value: new b(0.2, 0.8) },
2419
+ clim6: { value: new b(0.2, 0.8) },
2420
+ clim7: { value: new b(0.2, 0.8) },
2421
+ xClip: { value: new b(0, 1e6) },
2422
+ yClip: { value: new b(0, 1e6) },
2423
+ zClip: { value: new b(0, 1e6) },
2424
+ u_window_size: { value: new b(1, 1) },
2425
+ u_vol_scale: { value: new C(1, 1, 1) },
2426
+ // Set renderstyle to 3 or 4 for debugging modes
2427
+ u_renderstyle: { value: 2 },
2428
+ brickCacheTex: { type: "sampler3D", value: null },
2429
+ pageTableTex: { type: "usampler3D", value: null },
2430
+ color0: { value: new Z(0, 0, 0) },
2431
+ color1: { value: new Z(0, 0, 0) },
2432
+ color2: { value: new Z(0, 0, 0) },
2433
+ color3: { value: new Z(0, 0, 0) },
2434
+ color4: { value: new Z(0, 0, 0) },
2435
+ color5: { value: new Z(0, 0, 0) },
2436
+ color6: { value: new Z(0, 0, 0) },
2437
+ channelMapping: {
2438
+ value: [-1, -1, -1, -1, -1, -1, -1]
2439
+ },
2440
+ resGlobal: { value: new b(0, 9) },
2441
+ res0: { value: new b(0, 9) },
2442
+ res1: { value: new b(0, 9) },
2443
+ res2: { value: new b(0, 9) },
2444
+ res3: { value: new b(0, 9) },
2445
+ res4: { value: new b(0, 9) },
2446
+ res5: { value: new b(0, 9) },
2447
+ res6: { value: new b(0, 9) },
2448
+ maxChannels: { value: 0 },
2449
+ lodFactor: { value: 1 },
2450
+ near: { value: 0.1 },
2451
+ far: { value: 1e4 },
2452
+ opacity: { value: 1 },
2453
+ volumeCount: { value: 0 },
2454
+ boxSize: { value: new C(1, 1, 1) },
2455
+ renderRes: { value: 1e3 },
2456
+ voxelExtents: { value: new C(1, 1, 1) },
2457
+ anchor0: { value: new C(0, 0, 0) },
2458
+ anchor1: { value: new C(0, 0, 0) },
2459
+ anchor2: { value: new C(0, 0, 0) },
2460
+ anchor3: { value: new C(0, 0, 0) },
2461
+ anchor4: { value: new C(0, 0, 0) },
2462
+ anchor5: { value: new C(0, 0, 0) },
2463
+ anchor6: { value: new C(0, 0, 0) },
2464
+ anchor7: { value: new C(0, 0, 0) },
2465
+ anchor8: { value: new C(0, 0, 0) },
2466
+ anchor9: { value: new C(0, 0, 0) },
2467
+ scale0: { value: new C(1, 1, 1) },
2468
+ scale1: { value: new C(2, 2, 2) },
2469
+ scale2: { value: new C(4, 4, 4) },
2470
+ scale3: { value: new C(8, 8, 8) },
2471
+ scale4: { value: new C(16, 16, 16) },
2472
+ scale5: { value: new C(32, 32, 32) },
2473
+ scale6: { value: new C(64, 64, 64) },
2474
+ scale7: { value: new C(128, 128, 128) },
2475
+ scale8: { value: new C(256, 256, 256) },
2476
+ scale9: { value: new C(512, 512, 512) }
2477
+ },
2478
+ vertexShader: $e,
2479
+ fragmentShader: Qe
2480
+ };
2481
+ function P(h) {
2482
+ se(le.DEBUG) && console.warn(`%cRM: ${h}`, "background: orange; color: white; padding: 2px; border-radius: 3px;");
2483
+ }
2484
+ function ne(h, t) {
2485
+ return h / t[1];
2486
+ }
2487
+ class et {
2488
+ constructor() {
2489
+ P("Initializing VolumeRenderManager"), this.uniforms = null, this.shader = null, this.meshScale = [1, 1, 1], this.geometrySize = [1, 1, 1], this.boxSize = [1, 1, 1], this.zarrInit = !1, this.channelsVisible = [], this.channelTargetC = [], this.zarrStoreNumResolutions = null, this.channelMaxResolutionIndex = [], this.colors = [], this.contrastLimits = [], this.layerTransparency = 1, this.xSlice = new b(-1, 1e5), this.ySlice = new b(-1, 1e5), this.zSlice = new b(-1, 1e5), this.originalScale = [1, 1, 1], this.physicalDimensions = [1, 1, 1], this.maxResolution = [1, 1, 1], this.maxRange = 255, this.maxRangeSet = !1, this.initializeShader();
2490
+ }
2491
+ /**
2492
+ * Initialize shader and uniform objects
2493
+ */
2494
+ initializeShader() {
2495
+ P("Initializing shader"), this.shader = Je, this.uniforms = De.clone(this.shader.uniforms);
2496
+ }
2497
+ /**
2498
+ * Extract rendering settings from coordination props
2499
+ * @param {Object} props - Component props
2500
+ * @returns {Object} Extracted rendering settings
2501
+ */
2502
+ extractRenderingSettingsFromProps(t) {
2503
+ const { images: e = {}, imageLayerScopes: i = [], imageLayerCoordination: a = [{}], imageChannelScopesByLayer: r = {}, imageChannelCoordination: o = [{}], spatialRenderingMode: l } = t, c = i[0];
2504
+ if (!c)
2505
+ return P("Extracting rendering settings from props - no layer scope"), {
2506
+ valid: !1
2507
+ };
2508
+ const s = r[c], g = a[0][c], p = o[0][c], u = e[c]?.image?.instance?.getData();
2509
+ if (!u)
2510
+ return P("Extracting rendering settings from props - no image data"), {
2511
+ valid: !1
2512
+ };
2513
+ if (!p[s?.[0]][D.SPATIAL_CHANNEL_WINDOW])
2514
+ return P("Extracting rendering settings from props - no channel window set"), {
2515
+ valid: !1
2516
+ };
2517
+ const d = e[c].image.instance, v = l === "3D", f = g[D.PHOTOMETRIC_INTERPRETATION] === "RGB", x = g[D.SPATIAL_LAYER_VISIBLE], _ = g[D.SPATIAL_LAYER_OPACITY], y = f ? [
2518
+ [255, 0, 0],
2519
+ [0, 255, 0],
2520
+ [0, 0, 255]
2521
+ ] : s.map((k) => p[k][D.SPATIAL_CHANNEL_COLOR]), E = f ? [
2522
+ [0, 255],
2523
+ [0, 255],
2524
+ [0, 255]
2525
+ ] : s.map((k) => p[k][D.SPATIAL_CHANNEL_WINDOW] || [0, 255]);
2526
+ this.maxRangeSet || (this.maxRange = Math.max(...E.map((k) => k[1])), this.maxRangeSet = !0);
2527
+ const L = f ? [
2528
+ x && !0,
2529
+ x && !0,
2530
+ x && !0
2531
+ ] : s.map((k) => x && p[k][D.SPATIAL_CHANNEL_VISIBLE]), G = f ? [
2532
+ x && !0,
2533
+ x && !0,
2534
+ x && !0
2535
+ ] : s.map((k) => x && d.getChannelIndex(p[k][D.SPATIAL_TARGET_C])), j = f ? [
2536
+ x && null,
2537
+ x && null,
2538
+ x && null
2539
+ ] : s.map((k) => p[k][D.SPATIAL_MAX_RESOLUTION]);
2540
+ let T = g[D.SPATIAL_SLICE_X], U = g[D.SPATIAL_SLICE_Y], N = g[D.SPATIAL_SLICE_Z];
2541
+ const Y = g[D.SPATIAL_LOD_FACTOR] ?? 1;
2542
+ T = T !== null ? T : new b(-1, 1e5), U = U !== null ? U : new b(-1, 1e5), N = N !== null ? N : new b(-1, 1e5);
2543
+ const ie = e[c].image.loaders[0].channels;
2544
+ return P("Extracting rendering settings from props - success"), {
2545
+ valid: !0,
2546
+ channelsVisible: L,
2547
+ allChannels: ie,
2548
+ channelTargetC: G,
2549
+ channelMaxResolutionIndex: j,
2550
+ data: u,
2551
+ colors: y,
2552
+ contrastLimits: E,
2553
+ is3dMode: v,
2554
+ layerTransparency: _,
2555
+ xSlice: T,
2556
+ ySlice: U,
2557
+ zSlice: N,
2558
+ lodFactor: Y
2559
+ };
2560
+ }
2561
+ /**
2562
+ * Update the render settings from the given props
2563
+ * @param {Object} props - Component props
2564
+ * @returns {boolean} True if settings were successfully updated
2565
+ */
2566
+ updateFromProps(t) {
2567
+ const e = this.extractRenderingSettingsFromProps(t);
2568
+ return e.valid ? (this.channelsVisible = e.channelsVisible, this.channelTargetC = e.channelTargetC, this.channelMaxResolutionIndex = e.channelMaxResolutionIndex, this.colors = e.colors, this.contrastLimits = e.contrastLimits, this.renderingMode = e.renderingMode, this.layerTransparency = e.layerTransparency, this.xSlice = e.xSlice, this.ySlice = e.ySlice, this.zSlice = e.zSlice, this.uniforms.lodFactor.value = e.lodFactor, P(`lodFactor ${e.lodFactor}`), this.shader.uniforms.lodFactor.value = e.lodFactor, P("Updating from props - success"), !0) : (P("Updating from props - invalid settings"), !1);
2569
+ }
2570
+ /**
2571
+ * Update the rendering based on the current volume data from the data manager
2572
+ * @param {object} volumeDataManagerProps - Params derived from the volume data manager
2573
+ * @returns {Object|null} Updated rendering settings or null if rendering is not possible
2574
+ */
2575
+ updateRendering({ zarrStoreShapes: t, originalScaleXYZ: e, physicalDimensionsXYZ: i, maxResolutionXYZ: a, boxDimensionsXYZ: r, normalizedScaleXYZ: o, bcTHREE: l, ptTHREE: c }) {
2576
+ if (P("Updating rendering"), this.channelTargetC.findIndex((v, f) => this.channelsVisible[f]), !Array.isArray(t) || t.length === 0)
2577
+ return null;
2578
+ const s = t[0], g = {
2579
+ xLength: s[4] || 1,
2580
+ yLength: s[3] || 1,
2581
+ zLength: s[2] || 1
2582
+ }, p = [], u = [], d = [];
2583
+ if (this.channelTargetC.forEach((v, f) => {
2584
+ this.channelsVisible[f];
2585
+ {
2586
+ const _ = [0, this.maxRange ? this.maxRange : 255];
2587
+ u.push([
2588
+ this.colors[f][0] / 255,
2589
+ this.colors[f][1] / 255,
2590
+ this.colors[f][2] / 255,
2591
+ this.channelsVisible[f] ? 1 : 0
2592
+ ]), n.debug("colorsSave", u), this.contrastLimits[f][0] === 0 && this.contrastLimits[f][1] === 255 ? d.push([
2593
+ ne(_[0], _),
2594
+ ne(_[1], _)
2595
+ ]) : d.push([
2596
+ ne(this.contrastLimits[f][0], _),
2597
+ ne(this.contrastLimits[f][1], _)
2598
+ ]);
2599
+ }
2600
+ }), !this.zarrInit) {
2601
+ this.originalScale = e, this.physicalDimensions = i, this.maxResolution = a;
2602
+ const v = r;
2603
+ this.normalizedScale = o, this.meshScale = [
2604
+ this.originalScale[0] / this.originalScale[0],
2605
+ this.originalScale[1] / this.originalScale[0],
2606
+ this.originalScale[2] / this.originalScale[0]
2607
+ ], this.geometrySize = v, this.boxSize = v, n.debug("this.boxSize", this.boxSize), n.debug("this.geometrySize", this.geometrySize), n.debug("this.meshScale", this.meshScale), n.debug("this.originalScale", this.originalScale), n.debug("this.physicalDimensions", this.physicalDimensions), n.debug("this.maxResolution", this.maxResolution), n.debug("scaledResolution", v), this.zarrInit = !0;
2608
+ }
2609
+ return this.updateUniforms(
2610
+ p,
2611
+ g,
2612
+ // Pass dimensions object instead of volume
2613
+ this.renderingMode,
2614
+ d,
2615
+ u,
2616
+ this.layerTransparency,
2617
+ this.xSlice,
2618
+ this.ySlice,
2619
+ this.zSlice,
2620
+ l,
2621
+ c
2622
+ ), {
2623
+ uniforms: this.uniforms,
2624
+ shader: this.shader,
2625
+ meshScale: this.meshScale,
2626
+ geometrySize: this.geometrySize,
2627
+ boxSize: this.boxSize
2628
+ };
2629
+ }
2630
+ /**
2631
+ * Update shader uniforms with current rendering values
2632
+ * @param {Array} textures - List of 3D textures
2633
+ * @param {Object} dimensions - Dimensions object
2634
+ * @param {number} renderstyle - Rendering mode value
2635
+ * @param {Array} contrastLimits - List of contrast limits for each channel
2636
+ * @param {Array} colors - List of colors for each channel
2637
+ * @param {number} layerTransparency - Overall transparency value
2638
+ * @param {Vector2} xSlice - X clipping plane
2639
+ * @param {Vector2} ySlice - Y clipping plane
2640
+ * @param {Vector2} zSlice - Z clipping plane
2641
+ */
2642
+ updateUniforms(t, e, i, a, r, o, l, c, s, g, p) {
2643
+ P("Updating uniforms"), this.uniforms.boxSize.value.set(this.boxSize[0], this.boxSize[1], this.boxSize[2]), this.uniforms.brickCacheTex.value = g, this.uniforms.pageTableTex.value = p, this.uniforms.near.value = 0.1, this.uniforms.far.value = 3e3, this.uniforms.opacity.value = o, this.uniforms.volumeCount.value = t.length, this.uniforms.u_size.value.set(e.xLength, e.yLength, e.zLength), this.uniforms.u_window_size.value.set(0, 0), this.uniforms.u_vol_scale.value.set(1 / e.xLength, 1 / e.yLength, 1 / e.zLength * 2), this.uniforms.clim0.value.set(a.length > 0 ? a[0][0] : null, a.length > 0 ? a[0][1] : null), this.uniforms.clim1.value.set(a.length > 1 ? a[1][0] : null, a.length > 1 ? a[1][1] : null), this.uniforms.clim2.value.set(a.length > 2 ? a[2][0] : null, a.length > 2 ? a[2][1] : null), this.uniforms.clim3.value.set(a.length > 3 ? a[3][0] : null, a.length > 3 ? a[3][1] : null), this.uniforms.clim4.value.set(a.length > 4 ? a[4][0] : null, a.length > 4 ? a[4][1] : null), this.uniforms.clim5.value.set(a.length > 5 ? a[5][0] : null, a.length > 5 ? a[5][1] : null), this.uniforms.clim6.value.set(a.length > 6 ? a[6][0] : null, a.length > 6 ? a[6][1] : null), this.uniforms.xClip.value.set(l[0] * (1 / this.maxResolution[0]) * this.boxSize[0], l[1] * (1 / this.maxResolution[0]) * this.boxSize[0]), this.uniforms.yClip.value.set(c[0] * (1 / this.maxResolution[1]) * this.boxSize[1], c[1] * (1 / this.maxResolution[1]) * this.boxSize[1]), this.uniforms.zClip.value.set(s[0] * (1 / this.maxResolution[2]) * this.boxSize[2], s[1] * (1 / this.maxResolution[2]) * this.boxSize[2]), this.uniforms.color0.value.set(r.length > 0 ? r[0][0] : null, r.length > 0 ? r[0][1] : null, r.length > 0 ? r[0][2] : null, r.length > 0 ? r[0][3] : null), this.uniforms.color1.value.set(r.length > 1 ? r[1][0] : null, r.length > 1 ? r[1][1] : null, r.length > 1 ? r[1][2] : null, r.length > 1 ? r[1][3] : null), this.uniforms.color2.value.set(r.length > 2 ? r[2][0] : null, r.length > 2 ? r[2][1] : null, r.length > 2 ? r[2][2] : null, r.length > 2 ? r[2][3] : null), this.uniforms.color3.value.set(r.length > 3 ? r[3][0] : null, r.length > 3 ? r[3][1] : null, r.length > 3 ? r[3][2] : null, r.length > 3 ? r[3][3] : null), this.uniforms.color4.value.set(r.length > 4 ? r[4][0] : null, r.length > 4 ? r[4][1] : null, r.length > 4 ? r[4][2] : null, r.length > 4 ? r[4][3] : null), this.uniforms.color5.value.set(r.length > 5 ? r[5][0] : null, r.length > 5 ? r[5][1] : null, r.length > 5 ? r[5][2] : null, r.length > 5 ? r[5][3] : null), this.uniforms.color6.value.set(r.length > 6 ? r[6][0] : null, r.length > 6 ? r[6][1] : null, r.length > 6 ? r[6][2] : null, r.length > 6 ? r[6][3] : null);
2644
+ for (let u = 0; u < 7; u++)
2645
+ typeof this.channelMaxResolutionIndex[u] == "number" && this.uniforms[`res${u}`].value.set(Math.max(1, this.channelMaxResolutionIndex[u]), this.zarrStoreNumResolutions - 1);
2646
+ }
2647
+ /**
2648
+ * Sets the processing render target
2649
+ * @param {WebGLMultipleRenderTargets} mrt - Multiple render targets object with 3 attachments
2650
+ */
2651
+ /*
2652
+ setProcessingTargets(mrt) {
2653
+ logWithColor('setting processing targets');
2654
+ this.mrt = mrt;
2655
+ }
2656
+ */
2657
+ setChannelMapping(t) {
2658
+ P("setting channel mapping"), n.debug("channelMapping", t), this.uniforms.channelMapping.value = t;
2659
+ }
2660
+ // Only called on initialization of the
2661
+ // VolumeDataManager and VolumeRenderManager for a particular image.
2662
+ setZarrUniforms(t, e) {
2663
+ P("setting zarr uniforms"), n.debug("zarrStore", t), n.debug("PT", e);
2664
+ for (let i = 0; i <= 9; i++)
2665
+ e.anchors && e.anchors[i] ? this.uniforms[`anchor${i}`].value.set(e.anchors[i][0] || 0, e.anchors[i][1] || 0, e.anchors[i][2] || 0) : (n.debug("anchor", i, "does not exist"), this.uniforms[`anchor${i}`].value.set(0, 0, 0)), t.scales && t.scales[i] ? this.uniforms[`scale${i}`].value.set(t.scales[i][0] || 1, t.scales[i][1] || 1, t.scales[i][2] || 1) : n.debug("scale", i, "does not exist");
2666
+ n.debug("zarrStore.brickLayout", t.brickLayout), this.zarrStoreNumResolutions = t.brickLayout.length;
2667
+ for (let i = 0; i < 7; i++)
2668
+ this.uniforms[`res${i}`].value.set(
2669
+ // TODO(mark) make this dependent on the per-channel maxResolution slider value.
2670
+ 1,
2671
+ t.brickLayout.length - 1
2672
+ );
2673
+ this.uniforms.resGlobal.value.set(1, t.brickLayout.length - 1), this.uniforms.voxelExtents.value.set(t.shapes[0][4], t.shapes[0][3], t.shapes[0][2]), this.uniforms.maxChannels.value = Math.min(t.channelCount, 7), n.debug("this.channelsVisible", this.channelsVisible), n.debug("zarrStore.shapes[0]", t.shapes[0]), n.debug("PT", e), n.debug("uniforms", this.uniforms);
2674
+ }
2675
+ }
2676
+ const tt = `//
2677
+ varying vec2 vUv;
2678
+ void main() {
2679
+ vUv = uv;
2680
+ gl_Position = vec4(position, 1.0);
2681
+ }
2682
+ `, nt = `//
2683
+ // Input texture to blur
2684
+ uniform sampler2D tDiffuse;
2685
+ // Resolution of the texture (width, height)
2686
+ uniform vec2 resolution;
2687
+ // Blur strength: 1=no blur, 2-3=3x3 kernel, 4-5=5x5 kernel, 6+=7x7 kernel
2688
+ uniform int gaussian;
2689
+ // Texture coordinates for current pixel
2690
+ varying vec2 vUv;
2691
+
2692
+ /**
2693
+ * No blur - returns the original pixel color
2694
+ */
2695
+ vec4 noGaussian() {
2696
+ vec4 color = texture2D(tDiffuse, vUv);
2697
+ return color;
2698
+ }
2699
+
2700
+ /**
2701
+ * Applies 3x3 Gaussian blur kernel
2702
+ * Samples 9 pixels in a 3x3 grid around the current pixel
2703
+ * Weights are based on 2D Gaussian distribution
2704
+ */
2705
+ vec4 gaussian3(vec2 texel) {
2706
+ vec4 color = vec4(0.0);
2707
+
2708
+ // Top row: weights [0.0625, 0.125, 0.0625]
2709
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -1.0)) * 0.0625;
2710
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -1.0)) * 0.125;
2711
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -1.0)) * 0.0625;
2712
+
2713
+ // Middle row: weights [0.125, 0.25, 0.125] (center pixel gets highest weight)
2714
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 0.0)) * 0.125;
2715
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 0.0)) * 0.25;
2716
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 0.0)) * 0.125;
2717
+
2718
+ // Bottom row: weights [0.0625, 0.125, 0.0625]
2719
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 1.0)) * 0.0625;
2720
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 1.0)) * 0.125;
2721
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 1.0)) * 0.0625;
2722
+
2723
+ return color;
2724
+ }
2725
+
2726
+ /**
2727
+ * Applies 5x5 Gaussian blur kernel
2728
+ * Samples 25 pixels in a 5x5 grid around the current pixel
2729
+ * Weights sum to 1.0 (273/273) for proper normalization
2730
+ */
2731
+ vec4 gaussian5(vec2 texel) {
2732
+ vec4 color = vec4(0.0);
2733
+
2734
+ // Row 1: weights [1/273, 4/273, 7/273, 4/273, 1/273]
2735
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -2.0)) * 1.0/273.0;
2736
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -2.0)) * 4.0/273.0;
2737
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -2.0)) * 7.0/273.0;
2738
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -2.0)) * 4.0/273.0;
2739
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -2.0)) * 1.0/273.0;
2740
+
2741
+ // Row 2: weights [4/273, 16/273, 26/273, 16/273, 4/273]
2742
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -1.0)) * 4.0/273.0;
2743
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -1.0)) * 16.0/273.0;
2744
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -1.0)) * 26.0/273.0;
2745
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -1.0)) * 16.0/273.0;
2746
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -1.0)) * 4.0/273.0;
2747
+
2748
+ // Row 3 (center): weights [7/273, 26/273, 41/273, 26/273, 7/273]
2749
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 0.0)) * 7.0/273.0;
2750
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 0.0)) * 26.0/273.0;
2751
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 0.0)) * 41.0/273.0; // Center pixel
2752
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 0.0)) * 26.0/273.0;
2753
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 0.0)) * 7.0/273.0;
2754
+
2755
+ // Row 4: weights [4/273, 16/273, 26/273, 16/273, 4/273]
2756
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 1.0)) * 4.0/273.0;
2757
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 1.0)) * 16.0/273.0;
2758
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 1.0)) * 26.0/273.0;
2759
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 1.0)) * 16.0/273.0;
2760
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 1.0)) * 4.0/273.0;
2761
+
2762
+ // Row 5: weights [1/273, 4/273, 7/273, 4/273, 1/273]
2763
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 2.0)) * 1.0/273.0;
2764
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 2.0)) * 4.0/273.0;
2765
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 2.0)) * 7.0/273.0;
2766
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 2.0)) * 4.0/273.0;
2767
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 2.0)) * 1.0/273.0;
2768
+
2769
+ return color;
2770
+ }
2771
+
2772
+ /**
2773
+ * Applies 7x7 Gaussian blur kernel
2774
+ * Samples 49 pixels in a 7x7 grid around the current pixel
2775
+ * Weights sum to 1.0 (1003/1003) for proper normalization
2776
+ * Creates the strongest blur effect
2777
+ */
2778
+ vec4 gaussian7(vec2 texel) {
2779
+ vec4 color = vec4(0.0);
2780
+
2781
+ // Row 1: weights [0, 0, 1/1003, 2/1003, 1/1003, 0, 0]
2782
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -3.0)) * 1.0/1003.0;
2783
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -3.0)) * 2.0/1003.0;
2784
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -3.0)) * 1.0/1003.0;
2785
+
2786
+ // Row 2: weights [0, 3/1003, 13/1003, 22/1003, 13/1003, 3/1003, 0]
2787
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -2.0)) * 3.0/1003.0;
2788
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -2.0)) * 13.0/1003.0;
2789
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -2.0)) * 22.0/1003.0;
2790
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -2.0)) * 13.0/1003.0;
2791
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -2.0)) * 3.0/1003.0;
2792
+
2793
+ // Row 3: weights [1/1003, 13/1003, 59/1003, 97/1003, 59/1003, 13/1003, 1/1003]
2794
+ color += texture2D(tDiffuse, vUv + texel * vec2(-3.0, -1.0)) * 1.0/1003.0;
2795
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, -1.0)) * 13.0/1003.0;
2796
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, -1.0)) * 59.0/1003.0;
2797
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, -1.0)) * 97.0/1003.0;
2798
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, -1.0)) * 59.0/1003.0;
2799
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, -1.0)) * 13.0/1003.0;
2800
+ color += texture2D(tDiffuse, vUv + texel * vec2( 3.0, -1.0)) * 1.0/1003.0;
2801
+
2802
+ // Row 4 (center): weights [2/1003, 22/1003, 97/1003, 159/1003, 97/1003, 22/1003, 2/1003]
2803
+ color += texture2D(tDiffuse, vUv + texel * vec2(-3.0, 0.0)) * 2.0/1003.0;
2804
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 0.0)) * 22.0/1003.0;
2805
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 0.0)) * 97.0/1003.0;
2806
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 0.0)) * 159.0/1003.0; // Center pixel
2807
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 0.0)) * 97.0/1003.0;
2808
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 0.0)) * 22.0/1003.0;
2809
+ color += texture2D(tDiffuse, vUv + texel * vec2( 3.0, 0.0)) * 2.0/1003.0;
2810
+
2811
+ // Row 5: weights [1/1003, 13/1003, 59/1003, 97/1003, 59/1003, 13/1003, 1/1003]
2812
+ color += texture2D(tDiffuse, vUv + texel * vec2(-3.0, 1.0)) * 1.0/1003.0;
2813
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 1.0)) * 13.0/1003.0;
2814
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 1.0)) * 59.0/1003.0;
2815
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 1.0)) * 97.0/1003.0;
2816
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 1.0)) * 59.0/1003.0;
2817
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 1.0)) * 13.0/1003.0;
2818
+ color += texture2D(tDiffuse, vUv + texel * vec2( 3.0, 1.0)) * 1.0/1003.0;
2819
+
2820
+ // Row 6: weights [0, 3/1003, 13/1003, 22/1003, 13/1003, 3/1003, 0]
2821
+ color += texture2D(tDiffuse, vUv + texel * vec2(-2.0, 2.0)) * 3.0/1003.0;
2822
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 2.0)) * 13.0/1003.0;
2823
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 2.0)) * 22.0/1003.0;
2824
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 2.0)) * 13.0/1003.0;
2825
+ color += texture2D(tDiffuse, vUv + texel * vec2( 2.0, 2.0)) * 3.0/1003.0;
2826
+
2827
+ // Row 7: weights [0, 0, 1/1003, 2/1003, 1/1003, 0, 0]
2828
+ color += texture2D(tDiffuse, vUv + texel * vec2(-1.0, 3.0)) * 1.0/1003.0;
2829
+ color += texture2D(tDiffuse, vUv + texel * vec2( 0.0, 3.0)) * 2.0/1003.0;
2830
+ color += texture2D(tDiffuse, vUv + texel * vec2( 1.0, 3.0)) * 1.0/1003.0;
2831
+
2832
+ return color;
2833
+ }
2834
+
2835
+ /**
2836
+ * Main fragment shader function
2837
+ * Determines which blur kernel to apply based on the 'gaussian' uniform
2838
+ */
2839
+ void main() {
2840
+ // Calculate the size of one texel (pixel) in texture coordinates
2841
+ vec2 texel = 1.0 / resolution;
2842
+
2843
+ // Initialize output color (this line appears to be unused/debug code)
2844
+ vec4 color = vec4(1.0, 0.0, 0.0, 0.0);
2845
+
2846
+ // TODO: remove these variables since not used
2847
+ bool left = vUv.x < 0.5;
2848
+ bool top = vUv.y < 0.5;
2849
+
2850
+ if (gaussian > 1 && gaussian <= 3) {
2851
+ // Apply 3x3 Gaussian blur for values 2-3
2852
+ color = gaussian3(texel);
2853
+ } else if (gaussian > 3 && gaussian <= 5) {
2854
+ // Apply 5x5 Gaussian blur for values 4-5
2855
+ color = gaussian5(texel);
2856
+ } else if (gaussian > 5) {
2857
+ // Apply 7x7 Gaussian blur for values 6 and above
2858
+ color = gaussian7(texel);
2859
+ } else {
2860
+ // No blur for value 1 or less
2861
+ color = noGaussian();
2862
+ }
2863
+
2864
+ // Output the final blurred color
2865
+ gl_FragColor = color;
2866
+ }
2867
+ `;
2868
+ function be(h, t) {
2869
+ const e = h.properties?.get(t);
2870
+ return e?.framebuffer || e?.__webglFramebuffer || t.__webglFramebuffer;
2871
+ }
2872
+ function Q(h) {
2873
+ se(le.DEBUG) && console.warn(`%cV: ${h}`, "background: deeppink; color: white; padding: 2px; border-radius: 3px;");
2874
+ }
2875
+ function rt(h, t, e, { mrtRef: i }) {
2876
+ h.setRenderTarget(i.current), h.clear(!0, !0, !0), h.render(e, t);
2877
+ }
2878
+ function it(h, { screenSceneRef: t, screenCameraRef: e }) {
2879
+ h.setRenderTarget(null), h.clear(!0, !0, !0), h.render(t.current, e.current);
2880
+ }
2881
+ function at(h, { frameRef: t, dataManager: e, mrtRef: i, bufRequest: a, bufUsage: r }) {
2882
+ const o = h.getContext(), l = t.current;
2883
+ e.noNewRequests === !0 && !e.manuallyStopped && l % 100 === 0 && l < 500 && (e.noNewRequests = !1), e.triggerRequest === !0 && e.noNewRequests === !1 ? (o.bindFramebuffer(o.READ_FRAMEBUFFER, be(h, i.current)), o.readBuffer(o.COLOR_ATTACHMENT1), o.readPixels(0, 0, i.current.width, i.current.height, o.RGBA, o.UNSIGNED_BYTE, a.current), e.processRequestData(a.current)) : e.triggerUsage === !0 && e.noNewRequests === !1 && (o.bindFramebuffer(o.READ_FRAMEBUFFER, be(h, i.current)), o.readBuffer(o.COLOR_ATTACHMENT2), o.readPixels(0, 0, i.current.width, i.current.height, o.RGBA, o.UNSIGNED_BYTE, r.current), e.processUsageData(r.current));
2884
+ }
2885
+ function ot(h, t) {
2886
+ const { invalidate: e, isInteracting: i, dataManager: a, spatialRenderingModeChanging: r, meshRef: o, stillRef: l, screenQuadRef: c, lastSampleRef: s, frameRef: g, lastFrameCountRef: p } = t;
2887
+ if (c.current && (l.current ? c.current.material.uniforms.gaussian.value = 0 : c.current.material.uniforms.gaussian.value = 7), i) {
2888
+ a.manuallyStopped || (a.noNewRequests = !1, a.triggerUsage = !0);
2889
+ return;
2890
+ }
2891
+ if (r)
2892
+ return;
2893
+ const u = o.current?.material?.uniforms, d = u?.renderRes?.value ?? a?.PT?.lowestDataRes;
2894
+ if (a.noNewRequests) {
2895
+ d !== 0 ? (u && (u.renderRes.value = 0), n.debug("Adaptive Quality: No new requests. Setting renderSpeed to 0 (best quality)."), l.current = !1, c.current.material.uniforms.gaussian.value = 7, e()) : l.current || (n.debug("Adaptive Quality: No new requests and already at best quality. Setting stillRef to true."), l.current = !0, c.current.material.uniforms.gaussian.value = 0);
2896
+ return;
2897
+ }
2898
+ l.current && (l.current = !1, e());
2899
+ const v = h.getElapsedTime();
2900
+ if (v - s.current < 1)
2901
+ return;
2902
+ const f = v - s.current, x = g.current - p.current;
2903
+ let _ = 0;
2904
+ f > 0 && (_ = x / f), s.current = v, p.current = g.current;
2905
+ const y = _ > 100 && d > 0, E = _ < 30 && d < a.PT.lowestDataRes;
2906
+ if (y || E) {
2907
+ const L = d + (E ? 1 : -1);
2908
+ u && (u.renderRes.value = L), e();
2909
+ }
2910
+ }
2911
+ function st(h) {
2912
+ const {
2913
+ images: t,
2914
+ imageLayerScopes: e,
2915
+ imageLayerCoordination: i,
2916
+ imageChannelScopesByLayer: a,
2917
+ imageChannelCoordination: r,
2918
+ // onInitComplete,
2919
+ spatialRenderingMode: o,
2920
+ spatialRenderingModeChanging: l,
2921
+ onVolumeLoadingUpdate: c
2922
+ } = h, {
2923
+ gl: s
2924
+ // scene,
2925
+ // camera
2926
+ } = ve(), g = ve((R) => R.invalidate), p = M(null), u = M(null), d = M(null), v = M(null), f = M(null), [x, _] = fe({
2927
+ uniforms: null,
2928
+ shader: null,
2929
+ meshScale: [1, 1, 1],
2930
+ geometrySize: [1, 1, 1]
2931
+ }), y = o === "3D", E = M(null), L = M(null), G = M(null), [j, T] = fe(!1), U = M(null), N = M(!1), Y = M(0), ie = M(0), k = M(0), m = de(() => new We(s), [s]), w = de(() => new et(), []);
2932
+ $(() => {
2933
+ Q("useEffect MRT target matching canvas");
2934
+ const { width: R, height: I } = s.domElement, q = new Me(R, I, 3);
2935
+ q.texture.forEach((W) => {
2936
+ W.format = Pe, W.type = _e, W.minFilter = re, W.magFilter = re, W.generateMipmaps = !1;
2937
+ });
2938
+ const O = new Ae(), ee = new Be(-1, 1, 1, -1, 0.1, 10);
2939
+ ee.position.z = 1;
2940
+ const te = new Ne({
2941
+ uniforms: {
2942
+ // Bind the first render target texture as the input of the gaussian blur shader.
2943
+ tDiffuse: { value: q.texture[0] },
2944
+ resolution: { value: new b(R, I) },
2945
+ gaussian: { value: 7 }
2946
+ },
2947
+ vertexShader: tt,
2948
+ fragmentShader: nt,
2949
+ transparent: !0
2950
+ }), K = new Ue(new Le(2, 2), te);
2951
+ return O.add(K), E.current = O, L.current = ee, G.current = K, d.current = new Uint8Array(R * I * 4), v.current = new Uint8Array(R * I * 4), f.current = q, () => {
2952
+ q.dispose(), te.dispose(), K.geometry.dispose();
2953
+ };
2954
+ }, [s]);
2955
+ const ae = e?.[0], Ce = t?.[ae];
2956
+ a?.[ae];
2957
+ const J = r?.[0]?.[ae];
2958
+ $(() => {
2959
+ Q("useEffect INIT");
2960
+ let R = !1;
2961
+ if (!m || !w) {
2962
+ n.debug("dataManager or renderManager not initialized yet");
2963
+ return;
2964
+ }
2965
+ if (!Ce) {
2966
+ n.debug("no first image layer yet");
2967
+ return;
2968
+ }
2969
+ if (!J) {
2970
+ n.debug("no firstImageLayerChannelCoordination yet");
2971
+ return;
2972
+ }
2973
+ return (async () => {
2974
+ if (m.initStatus === F.COMPLETE) {
2975
+ n.debug("dataManager already initialized, skipping");
2976
+ return;
2977
+ }
2978
+ if (m.initImages(t, e), await m.init(J), R) {
2979
+ n.debug("Initialization useEffect has rerun, aborting remaining initialization");
2980
+ return;
2981
+ }
2982
+ n.debug("dataManager initialized"), w.setZarrUniforms(m.zarrStore, m.PT), w.setChannelMapping(m.channels.colorMappings), n.debug("rm.uniforms", w.uniforms), g();
2983
+ })(), () => {
2984
+ R = !0;
2985
+ };
2986
+ }, [m, w, t, e]), $(() => {
2987
+ if (o === "3D" && m && w) {
2988
+ Q("useEffect spatialRenderingMode");
2989
+ const I = {
2990
+ images: t,
2991
+ imageLayerScopes: e,
2992
+ imageLayerCoordination: i,
2993
+ imageChannelScopesByLayer: a,
2994
+ imageChannelCoordination: r,
2995
+ spatialRenderingMode: o
2996
+ };
2997
+ if (w.updateFromProps(I)) {
2998
+ const { zarrInit: q } = w;
2999
+ q || (m.ptTHREE.needsUpdate = !1, m.bcTHREE.needsUpdate = !1, m.renderer.initTexture(m.bcTHREE), m.renderer.initTexture(m.ptTHREE), m.initTexture());
3000
+ const O = w.updateRendering({
3001
+ zarrStoreShapes: m.zarrStore.shapes,
3002
+ originalScaleXYZ: m.getOriginalScaleXYZ(),
3003
+ physicalDimensionsXYZ: m.getPhysicalDimensionsXYZ(),
3004
+ maxResolutionXYZ: m.getMaxResolutionXYZ(),
3005
+ boxDimensionsXYZ: m.getBoxDimensionsXYZ(),
3006
+ normalizedScaleXYZ: m.getNormalizedScaleXYZ(),
3007
+ bcTHREE: m.bcTHREE,
3008
+ ptTHREE: m.ptTHREE
3009
+ });
3010
+ O && _(O);
3011
+ }
3012
+ }
3013
+ }, [m, w, t, e, i, a, r, o]), Ge((R, I, q) => {
3014
+ if (!f.current || !m || !w || !x.shader)
3015
+ return;
3016
+ const { gl: O, camera: ee, scene: te, clock: K } = R;
3017
+ N.current || rt(O, ee, te, { mrtRef: f }), it(O, { screenSceneRef: E, screenCameraRef: L }), at(O, { frameRef: Y, dataManager: m, mrtRef: f, bufRequest: d, bufUsage: v }), ot(K, {
3018
+ invalidate: g,
3019
+ isInteracting: j,
3020
+ dataManager: m,
3021
+ spatialRenderingModeChanging: l,
3022
+ meshRef: u,
3023
+ stillRef: N,
3024
+ screenQuadRef: G,
3025
+ lastSampleRef: ie,
3026
+ frameRef: Y,
3027
+ lastFrameCountRef: k
3028
+ }), Y.current += 1;
3029
+ }, 1);
3030
+ const H = X((R) => {
3031
+ if (Q("invalidateOnInteraction callback"), T(R), R) {
3032
+ const I = u.current?.material?.uniforms;
3033
+ I && (I.renderRes.value = m.PT.lowestDataRes), N.current = !1, g();
3034
+ }
3035
+ }), Re = X((R) => {
3036
+ H(!0);
3037
+ }), ye = X((R) => {
3038
+ clearTimeout(U.current), U.current = setTimeout(() => {
3039
+ H(!1);
3040
+ }, 300);
3041
+ });
3042
+ $(() => {
3043
+ Q("useEffect firstImageLayerChannelCoordination"), H(!0), n.debug("something about channels changed"), m.updateChannels(J), w.setChannelMapping(m.channels.colorMappings), clearTimeout(U.current), U.current = setTimeout(() => {
3044
+ H(!1);
3045
+ }, 300);
3046
+ }, [m, J, w, H]);
3047
+ const Ee = X(() => {
3048
+ m && m.stopLoading();
3049
+ }), Te = X(() => {
3050
+ m && m.restartLoading();
3051
+ }), Se = X(() => m ? m.getLoadingProgress() : null);
3052
+ return $(() => {
3053
+ if (!c)
3054
+ return;
3055
+ const R = setInterval(() => {
3056
+ const I = Se();
3057
+ c({
3058
+ loadingProgress: I,
3059
+ stillRef: N,
3060
+ onStopLoading: Ee,
3061
+ onRestartLoading: Te
3062
+ });
3063
+ }, 1e3);
3064
+ return () => clearInterval(R);
3065
+ }, [c, N]), !y || !m || !w ? null : x.shader ? B.jsxs("group", { children: [B.jsx(
3066
+ me,
3067
+ {
3068
+ // ref={mainOrbitControlsRef}
3069
+ enableDamping: !1,
3070
+ onStart: Re,
3071
+ onEnd: ye
3072
+ }
3073
+ ), B.jsxs("mesh", { ref: u, scale: x.meshScale, children: [B.jsx("boxGeometry", { args: x.geometrySize }), B.jsx("shaderMaterial", { uniforms: x.uniforms, vertexShader: x.shader.vertexShader, fragmentShader: x.shader.fragmentShader, side: Fe, transparent: !1, glslVersion: Oe })] })] }) : B.jsxs("group", { children: [B.jsxs("mesh", { children: [B.jsx("boxGeometry", { args: [1, 1, 1] }), B.jsx("meshBasicMaterial", { color: "#444", wireframe: !0 })] }), B.jsx(me, { ref: p })] });
3074
+ }
3075
+ function ft(h) {
3076
+ return B.jsx(qe, { frameloop: "always", style: {
3077
+ position: "absolute",
3078
+ top: 0,
3079
+ left: 0,
3080
+ width: "100%",
3081
+ height: "100%",
3082
+ padding: 0,
3083
+ margin: 0
3084
+ // backgroundColor: 'white',
3085
+ }, camera: {
3086
+ fov: 50,
3087
+ up: [0, 1, 0],
3088
+ position: [0, 0, 4],
3089
+ near: 0.01,
3090
+ far: 15
3091
+ }, gl: {
3092
+ antialias: !0,
3093
+ logarithmicDepthBuffer: !1,
3094
+ preserveDrawingBuffer: !1,
3095
+ autoClear: !1
3096
+ }, children: B.jsx(Ve, { fallback: "Initializing Volume View...", children: B.jsx(st, { ...h }) }) });
3097
+ }
3098
+ export {
3099
+ ft as SpatialWrapper
3100
+ };