@vitessce/dev 3.7.1 → 3.8.0

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