copper3d 3.6.12 → 3.7.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.
Files changed (52) hide show
  1. package/dist/Loader/copperDicomLoader.js +6 -1
  2. package/dist/Loader/copperDicomLoader.js.map +1 -1
  3. package/dist/Loader/copperRaw4DVolumeLoader.d.ts +10 -0
  4. package/dist/Loader/copperRaw4DVolumeLoader.js +270 -0
  5. package/dist/Loader/copperRaw4DVolumeLoader.js.map +1 -0
  6. package/dist/Loader/mhdParser.d.ts +83 -0
  7. package/dist/Loader/mhdParser.js +130 -0
  8. package/dist/Loader/mhdParser.js.map +1 -0
  9. package/dist/Scene/commonSceneMethod.d.ts +1 -0
  10. package/dist/Scene/commonSceneMethod.js +4 -19
  11. package/dist/Scene/commonSceneMethod.js.map +1 -1
  12. package/dist/Scene/copperMScene.js +2 -15
  13. package/dist/Scene/copperMScene.js.map +1 -1
  14. package/dist/Scene/copperScene.d.ts +7 -1
  15. package/dist/Scene/copperScene.js +14 -2
  16. package/dist/Scene/copperScene.js.map +1 -1
  17. package/dist/Scene/preRenderRegistry.d.ts +33 -0
  18. package/dist/Scene/preRenderRegistry.js +44 -0
  19. package/dist/Scene/preRenderRegistry.js.map +1 -0
  20. package/dist/Utils/colormapData.d.ts +9 -0
  21. package/dist/Utils/colormapData.js +39 -0
  22. package/dist/Utils/colormapData.js.map +1 -0
  23. package/dist/Utils/surfaceAnnotation/SurfaceAnnotator.d.ts +9 -0
  24. package/dist/Utils/surfaceAnnotation/SurfaceAnnotator.js +56 -12
  25. package/dist/Utils/surfaceAnnotation/SurfaceAnnotator.js.map +1 -1
  26. package/dist/Utils/texture2d.d.ts +2 -0
  27. package/dist/Utils/texture2d.js +7 -1
  28. package/dist/Utils/texture2d.js.map +1 -1
  29. package/dist/Utils/volumeColormap.d.ts +6 -0
  30. package/dist/Utils/volumeColormap.js +14 -0
  31. package/dist/Utils/volumeColormap.js.map +1 -0
  32. package/dist/Utils/volumeShader.d.ts +7 -0
  33. package/dist/Utils/volumeShader.js +98 -0
  34. package/dist/Utils/volumeShader.js.map +1 -0
  35. package/dist/bundle.esm.js +697 -84
  36. package/dist/bundle.umd.js +697 -84
  37. package/dist/index.d.ts +2 -2
  38. package/dist/index.js.map +1 -1
  39. package/dist/types/Loader/copperRaw4DVolumeLoader.d.ts +10 -0
  40. package/dist/types/Loader/mhdParser.d.ts +83 -0
  41. package/dist/types/Scene/commonSceneMethod.d.ts +1 -0
  42. package/dist/types/Scene/copperScene.d.ts +7 -1
  43. package/dist/types/Scene/preRenderRegistry.d.ts +33 -0
  44. package/dist/types/Utils/colormapData.d.ts +9 -0
  45. package/dist/types/Utils/surfaceAnnotation/SurfaceAnnotator.d.ts +9 -0
  46. package/dist/types/Utils/texture2d.d.ts +2 -0
  47. package/dist/types/Utils/volumeColormap.d.ts +6 -0
  48. package/dist/types/Utils/volumeShader.d.ts +7 -0
  49. package/dist/types/index.d.ts +2 -2
  50. package/dist/types/types/types.d.ts +82 -2
  51. package/dist/types/types.d.ts +82 -2
  52. package/package.json +1 -1
@@ -41154,6 +41154,50 @@ void main() {
41154
41154
  return xp;
41155
41155
  }
41156
41156
 
41157
+ /**
41158
+ * Registry of per-frame callbacks, keyed by a stable id.
41159
+ *
41160
+ * Deliberately dependency-free (no three.js) so it can be unit-tested under
41161
+ * `node --experimental-strip-types --test`.
41162
+ *
41163
+ * It replaces an object literal that was duplicated across `commonSceneMethod` and
41164
+ * `copperMScene` and carried three bugs, one of which silently corrupted callers:
41165
+ *
41166
+ * 1. `index` was never incremented, so `addPreRenderCallbackFunction` always returned 0.
41167
+ * Callers who stored that value and later removed it deleted somebody else's callback.
41168
+ * 2. `add` guarded with `if (!fn.id)`, and the very first id was 0 — falsy — so the first
41169
+ * callback looked unregistered forever and could be added twice.
41170
+ * 3. `remove(id)` spliced `cache` at the raw id, treating the id as an array index. Removing
41171
+ * one callback shifted every later one down, so every previously handed-out id then
41172
+ * pointed at its neighbour.
41173
+ *
41174
+ * Here ids come from a monotonic counter, are never reused, and are held in an array parallel
41175
+ * to `cache` — so a removal cannot invalidate anyone else's id.
41176
+ */
41177
+ function createPreRenderRegistry() {
41178
+ return {
41179
+ index: 0,
41180
+ cache: [],
41181
+ ids: [],
41182
+ add(fn) {
41183
+ const existing = this.cache.indexOf(fn);
41184
+ if (existing !== -1)
41185
+ return this.ids[existing];
41186
+ const id = this.index++;
41187
+ this.cache.push(fn);
41188
+ this.ids.push(id);
41189
+ return id;
41190
+ },
41191
+ remove(id) {
41192
+ const at = this.ids.indexOf(id);
41193
+ if (at === -1)
41194
+ return;
41195
+ this.cache.splice(at, 1);
41196
+ this.ids.splice(at, 1);
41197
+ },
41198
+ };
41199
+ }
41200
+
41157
41201
  /* eslint no-bitwise: 0 */
41158
41202
  /**
41159
41203
  * Volume of Interest Lookup Table Function
@@ -41254,6 +41298,7 @@ void main() {
41254
41298
  const loader$1 = new FileLoader().setResponseType("arraybuffer");
41255
41299
  function copperDicomLoader(url, callback) {
41256
41300
  loader$1.load(url, (arrayBuffer) => {
41301
+ var _a;
41257
41302
  var dicomFileAsBuffer = new Uint8Array(arrayBuffer);
41258
41303
  const dataSet = dicomParser.parseDicom(dicomFileAsBuffer);
41259
41304
  // const dataSet = dicomParser.parseDicom(dicomFileAsBuffer, {
@@ -41283,7 +41328,7 @@ void main() {
41283
41328
  windowCenter = parseInt(tags["x00281050"]); //window center
41284
41329
  windowWidth = parseInt(tags["x00281051"]); //window width
41285
41330
  }
41286
- catch (_a) {
41331
+ catch (_b) {
41287
41332
  w = dataSet.uint16("x00280011");
41288
41333
  h = dataSet.uint16("x00280010");
41289
41334
  invert = dataSet.string("x00280004") === "MONOCHROME1" ? true : false;
@@ -41305,6 +41350,9 @@ void main() {
41305
41350
  const ipp = parseDS(dataSet.string("x00200032")); // ImagePositionPatient
41306
41351
  const iop = parseDS(dataSet.string("x00200037")); // ImageOrientationPatient
41307
41352
  const spacing = parseDS(dataSet.string("x00280030")); // PixelSpacing
41353
+ // FrameOfReferenceUID: two series share a world coordinate system only if this matches.
41354
+ // It is the only field that lets another modality prove it is already registered to this one.
41355
+ const frameOfReferenceUID = (_a = dataSet.string("x00200052")) !== null && _a !== void 0 ? _a : undefined;
41308
41356
  let instanceNumber = parseInt(dataSet.string("x00200013"));
41309
41357
  if (Number.isNaN(instanceNumber))
41310
41358
  instanceNumber = undefined;
@@ -41333,6 +41381,7 @@ void main() {
41333
41381
  imagePositionPatient: ipp,
41334
41382
  imageOrientationPatient: iop,
41335
41383
  pixelSpacing: spacing,
41384
+ frameOfReferenceUID,
41336
41385
  corners,
41337
41386
  };
41338
41387
  callback && callback(copperVolume);
@@ -41405,7 +41454,7 @@ void main() {
41405
41454
 
41406
41455
  var vert_2d = "out vec2 vUv;\n\nvoid main() {\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n // Use the geometry's own UVs; DICOM rows are top-down so flip v.\n vUv = vec2( uv.x, 1.0 - uv.y );\n\n}\n";
41407
41456
 
41408
- var frag_2d = "precision highp float;\nprecision highp int;\nprecision highp sampler2DArray;\n\nuniform sampler2DArray diffuse;\nin vec2 vUv;\nuniform int depth;\nuniform float uOpacity;\n\nout vec4 outColor;\n\nvoid main() {\n\n vec4 color = texture( diffuse, vec3( vUv, depth ) );\n\n // lighten a bit\n outColor = vec4( color.rrr * 1.5, uOpacity );\n\n}";
41457
+ var frag_2d = "precision highp float;\nprecision highp int;\nprecision highp sampler2DArray;\n\nuniform sampler2DArray diffuse;\nin vec2 vUv;\nuniform int depth;\nuniform float uOpacity;\n// Post-window gain. Defaults to 1.5, the value this shader used to hard-code.\n// It cannot lift true black (0 * gain == 0), but it does clip the top of the\n// range, so 1.0 is the faithful setting. Blacks that look grey are almost always\n// a window whose lower bound sits below 0, not this gain.\nuniform float uBrightness;\n\nout vec4 outColor;\n\nvoid main() {\n\n vec4 color = texture( diffuse, vec3( vUv, depth ) );\n\n outColor = vec4( color.rrr * uBrightness, uOpacity );\n\n}";
41409
41458
 
41410
41459
  let planeWidth = 80;
41411
41460
  let planeHeight = 80;
@@ -41430,6 +41479,7 @@ void main() {
41430
41479
  diffuse: { value: texture },
41431
41480
  depth: { value: 1 },
41432
41481
  uOpacity: { value: 1 },
41482
+ uBrightness: { value: 1.5 },
41433
41483
  },
41434
41484
  vertexShader: vert_2d,
41435
41485
  fragmentShader: frag_2d,
@@ -41472,6 +41522,7 @@ void main() {
41472
41522
  diffuse: { value: texture },
41473
41523
  depth: { value: 0 },
41474
41524
  uOpacity: { value: 1 },
41525
+ uBrightness: { value: 1.5 },
41475
41526
  },
41476
41527
  vertexShader: vert_2d,
41477
41528
  fragmentShader: frag_2d,
@@ -41504,7 +41555,11 @@ void main() {
41504
41555
  copperVolume.windowWidth = width;
41505
41556
  updateTexture(copperVolume);
41506
41557
  }
41507
- return { mesh, copperVolume, updateTexture, setFrame, setWindow };
41558
+ /** Post-window gain. 1.0 is faithful; the historical default is 1.5. */
41559
+ function setBrightness(v) {
41560
+ material.uniforms.uBrightness.value = v;
41561
+ }
41562
+ return { mesh, copperVolume, updateTexture, setFrame, setWindow, setBrightness };
41508
41563
  }
41509
41564
 
41510
41565
  /*!
@@ -49505,22 +49560,7 @@ void main() {
49505
49560
  }
49506
49561
  this.controls = new Copper3dTrackballControls(this.camera, this.container);
49507
49562
  this.controls.dispose();
49508
- this.preRenderCallbackFunctions = {
49509
- index: 0,
49510
- cache: [],
49511
- add(fn) {
49512
- if (!fn.id) {
49513
- fn.id = this.cache.length;
49514
- this.cache.push(fn);
49515
- return;
49516
- }
49517
- },
49518
- remove(id) {
49519
- if (this.cache[id]) {
49520
- this.cache.splice(id, 1);
49521
- }
49522
- },
49523
- };
49563
+ this.preRenderCallbackFunctions = createPreRenderRegistry();
49524
49564
  }
49525
49565
  createDemoMesh() {
49526
49566
  const geometry = new BoxGeometry();
@@ -49546,10 +49586,9 @@ void main() {
49546
49586
  this.sort = false;
49547
49587
  }
49548
49588
  }
49589
+ /** Registers a per-frame callback and returns its id, for removePreRenderCallbackFunction. */
49549
49590
  addPreRenderCallbackFunction(callbackFunction) {
49550
- this.preRenderCallbackFunctions.add(callbackFunction);
49551
- const id = this.preRenderCallbackFunctions.index;
49552
- return id;
49591
+ return this.preRenderCallbackFunctions.add(callbackFunction);
49553
49592
  }
49554
49593
  removePreRenderCallbackFunction(id) {
49555
49594
  this.preRenderCallbackFunctions.remove(id);
@@ -57418,6 +57457,569 @@ void main() {
57418
57457
  return loader;
57419
57458
  }
57420
57459
 
57460
+ /******************************************************************************
57461
+ Copyright (c) Microsoft Corporation.
57462
+
57463
+ Permission to use, copy, modify, and/or distribute this software for any
57464
+ purpose with or without fee is hereby granted.
57465
+
57466
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
57467
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
57468
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
57469
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
57470
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
57471
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
57472
+ PERFORMANCE OF THIS SOFTWARE.
57473
+ ***************************************************************************** */
57474
+
57475
+ function __awaiter(thisArg, _arguments, P, generator) {
57476
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
57477
+ return new (P || (P = Promise))(function (resolve, reject) {
57478
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
57479
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
57480
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
57481
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
57482
+ });
57483
+ }
57484
+
57485
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
57486
+ var e = new Error(message);
57487
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
57488
+ };
57489
+
57490
+ /**
57491
+ * Minimal MetaImage (.mhd) header parser.
57492
+ *
57493
+ * Deliberately dependency-free (no three.js) so it can run under
57494
+ * `node --experimental-strip-types --test`.
57495
+ *
57496
+ * Only the subset the 4D ultrasound data uses is supported: 3D, uncompressed,
57497
+ * uint8. Anything else throws rather than silently mis-rendering.
57498
+ */
57499
+ /** Row-major identity — the value MetaImage writes when it has no real orientation. */
57500
+ const IDENTITY_MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1];
57501
+ function triple(raw, field) {
57502
+ const parts = raw.trim().split(/\s+/).map(Number);
57503
+ if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n))) {
57504
+ throw new Error(`mhd: ${field} must be 3 numbers, got "${raw}"`);
57505
+ }
57506
+ return [parts[0], parts[1], parts[2]];
57507
+ }
57508
+ function matrix3x3(raw) {
57509
+ const parts = raw.trim().split(/\s+/).map(Number);
57510
+ if (parts.length !== 9 || parts.some((n) => !Number.isFinite(n))) {
57511
+ throw new Error(`mhd: TransformMatrix must be 9 numbers, got "${raw}"`);
57512
+ }
57513
+ return parts;
57514
+ }
57515
+ /** Floating-point headers rarely round-trip exactly; compare with a tolerance. */
57516
+ const near = (a, b) => Math.abs(a - b) < 1e-6;
57517
+ function parseMhdHeader(text) {
57518
+ var _a, _b;
57519
+ const fields = new Map();
57520
+ for (const line of text.split(/\r?\n/)) {
57521
+ const eq = line.indexOf("=");
57522
+ if (eq === -1)
57523
+ continue;
57524
+ fields.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
57525
+ }
57526
+ const need = (key) => {
57527
+ const value = fields.get(key);
57528
+ if (value === undefined)
57529
+ throw new Error(`mhd: missing required field "${key}"`);
57530
+ return value;
57531
+ };
57532
+ const nDims = Number(need("NDims"));
57533
+ if (nDims !== 3)
57534
+ throw new Error(`mhd: only NDims=3 is supported, got ${nDims}`);
57535
+ if (need("CompressedData").toLowerCase() === "true") {
57536
+ throw new Error("mhd: CompressedData=True is not supported");
57537
+ }
57538
+ const elementType = need("ElementType");
57539
+ if (elementType !== "MET_UCHAR") {
57540
+ throw new Error(`mhd: only MET_UCHAR is supported, got ${elementType}`);
57541
+ }
57542
+ const spacing = triple(need("ElementSpacing"), "ElementSpacing");
57543
+ const offsetRaw = fields.get("Offset");
57544
+ const offset = offsetRaw === undefined ? [0, 0, 0] : triple(offsetRaw, "Offset");
57545
+ const matrixRaw = fields.get("TransformMatrix");
57546
+ const transformMatrix = matrixRaw === undefined ? IDENTITY_MATRIX : matrix3x3(matrixRaw);
57547
+ const hasOffset = !offset.every((v) => near(v, 0));
57548
+ const hasRotation = !transformMatrix.every((v, i) => near(v, IDENTITY_MATRIX[i]));
57549
+ return {
57550
+ dims: triple(need("DimSize"), "DimSize"),
57551
+ spacing,
57552
+ elementType,
57553
+ compressed: false,
57554
+ elementDataFile: need("ElementDataFile"),
57555
+ offset,
57556
+ transformMatrix,
57557
+ anatomicalOrientation: (_a = fields.get("AnatomicalOrientation")) !== null && _a !== void 0 ? _a : null,
57558
+ frameOfReferenceUID: (_b = fields.get("FrameOfReferenceUID")) !== null && _b !== void 0 ? _b : null,
57559
+ hasPose: hasOffset || hasRotation,
57560
+ hasRealSpacing: !spacing.every((v) => near(v, 1)),
57561
+ };
57562
+ }
57563
+ /**
57564
+ * Decide whether a header's pose may be trusted.
57565
+ *
57566
+ * Two independent things must hold, and the second is the one people forget:
57567
+ *
57568
+ * 1. the header must actually carry a pose (`hasPose`), and
57569
+ * 2. that pose must be expressed in the SAME world frame as the scene.
57570
+ *
57571
+ * DICOM proves (2) with FrameOfReferenceUID. MetaImage has no such field, so a producer must
57572
+ * carry the UID across as a custom line. When the caller names the scene's frame and the file
57573
+ * cannot match it, the pose is refused — a pose in another scanner's coordinate system is
57574
+ * worse than no pose at all, because it looks authoritative while being wrong.
57575
+ *
57576
+ * When the caller names no frame, a pose is honoured but reported as `unverified`: nobody
57577
+ * checked, and the UI should not claim otherwise.
57578
+ */
57579
+ function resolveRegistration(header, expectedFrameOfReferenceUID) {
57580
+ if (!header.hasPose) {
57581
+ return { registered: false, frameVerified: false, reason: "no-pose" };
57582
+ }
57583
+ if (!expectedFrameOfReferenceUID) {
57584
+ return { registered: true, frameVerified: false, reason: "unverified" };
57585
+ }
57586
+ if (!header.frameOfReferenceUID) {
57587
+ return { registered: false, frameVerified: false, reason: "frame-missing" };
57588
+ }
57589
+ if (header.frameOfReferenceUID !== expectedFrameOfReferenceUID) {
57590
+ return { registered: false, frameVerified: false, reason: "frame-mismatch" };
57591
+ }
57592
+ return { registered: true, frameVerified: true, reason: "verified" };
57593
+ }
57594
+ /**
57595
+ * voxel index -> world, as a column-major 4x4 (three.js `Matrix4.elements` order).
57596
+ *
57597
+ * ITK/MetaImage convention: `world = Offset + D · (Spacing ∘ index)`, with `D` the
57598
+ * row-major direction matrix from TransformMatrix.
57599
+ *
57600
+ * Only meaningful when `header.hasPose` — otherwise this is the identity scaled by
57601
+ * spacing, which places the volume at the world origin and means nothing.
57602
+ */
57603
+ function voxelToWorldMatrix(header) {
57604
+ const d = header.transformMatrix;
57605
+ const [sx, sy, sz] = header.spacing;
57606
+ const [ox, oy, oz] = header.offset;
57607
+ // Column-major: each of the first three columns is a scaled direction (a column of D).
57608
+ return [
57609
+ d[0] * sx, d[3] * sx, d[6] * sx, 0,
57610
+ d[1] * sy, d[4] * sy, d[7] * sy, 0,
57611
+ d[2] * sz, d[5] * sz, d[8] * sz, 0,
57612
+ ox, oy, oz, 1,
57613
+ ];
57614
+ }
57615
+ /** Number of voxels implied by the header — equals the .raw byte length for uint8. */
57616
+ function voxelCount(header) {
57617
+ return header.dims[0] * header.dims[1] * header.dims[2];
57618
+ }
57619
+
57620
+ /**
57621
+ * Blue -> orange transfer function for ultrasound volume rendering.
57622
+ *
57623
+ * Dependency-free (no three.js) so it can be unit-tested under Node.
57624
+ * The ALPHA channel is load-bearing: three's VolumeRenderShader1 samples this
57625
+ * ramp as RGBA, so alpha is what turns low-intensity speckle transparent and
57626
+ * gives the volume its cloud-like appearance.
57627
+ */
57628
+ /** Linear interpolation between two RGB stops. */
57629
+ function mix(a, b, t) {
57630
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
57631
+ }
57632
+ const DEEP_BLUE = [30, 60, 120];
57633
+ const PALE_BLUE = [150, 190, 230];
57634
+ const WARM_ORANGE = [255, 170, 90];
57635
+ /**
57636
+ * Fraction of the ramp spent going blue -> pale blue before turning orange.
57637
+ * Tuned against the data: under the default clim window a typical MIP sample lands
57638
+ * around 0.63 of the ramp, so a 0.6 span turned the whole cloud orange. At 0.75 only
57639
+ * the brightest ~0.1% of samples (raw > 139, the p99.9) read as warm highlights.
57640
+ */
57641
+ const BLUE_SPAN = 0.75;
57642
+ /** Alpha curve exponent. >1 keeps the low-intensity speckle transparent. */
57643
+ const ALPHA_GAMMA = 1.6;
57644
+ function buildBlueOrangeRGBA(size = 256) {
57645
+ const out = new Uint8Array(size * 4);
57646
+ for (let i = 0; i < size; i++) {
57647
+ const t = i / (size - 1);
57648
+ const [r, g, b] = t < BLUE_SPAN
57649
+ ? mix(DEEP_BLUE, PALE_BLUE, t / BLUE_SPAN)
57650
+ : mix(PALE_BLUE, WARM_ORANGE, (t - BLUE_SPAN) / (1 - BLUE_SPAN));
57651
+ out[i * 4 + 0] = Math.round(r);
57652
+ out[i * 4 + 1] = Math.round(g);
57653
+ out[i * 4 + 2] = Math.round(b);
57654
+ out[i * 4 + 3] = Math.round(Math.pow(t, ALPHA_GAMMA) * 255);
57655
+ }
57656
+ return out;
57657
+ }
57658
+
57659
+ /**
57660
+ * A 1-D RGBA colormap texture for VolumeRenderShader1's `u_cmdata` uniform.
57661
+ * Caller owns the texture and must dispose() it.
57662
+ */
57663
+ function createBlueOrangeColormap(size = 256) {
57664
+ const texture = new DataTexture(buildBlueOrangeRGBA(size), size, 1, RGBAFormat);
57665
+ texture.minFilter = texture.magFilter = LinearFilter;
57666
+ texture.wrapS = texture.wrapT = ClampToEdgeWrapping;
57667
+ texture.needsUpdate = true;
57668
+ return texture;
57669
+ }
57670
+
57671
+ /**
57672
+ * three's VolumeRenderShader1 offers only MIP and ISO, and no opacity control. Clone it and
57673
+ * splice in:
57674
+ *
57675
+ * - a `u_opacity` uniform, and
57676
+ * - a third render style, DVR (`u_renderstyle == 2`): front-to-back alpha compositing.
57677
+ *
57678
+ * Why DVR matters here: MIP takes the MAXIMUM sample along each ray, so a dark cavity
57679
+ * surrounded by bright tissue can never appear — the max always picks the bright speckle in
57680
+ * front of or behind it. Compositing accumulates colour and opacity instead, letting low
57681
+ * intensity stay transparent, which is what makes the LV chamber visible inside an echo.
57682
+ *
57683
+ * Every edit is asserted: if a future three.js release rewrites these lines we fail loudly at
57684
+ * construction rather than shipping a shader that silently ignores opacity, silently drops
57685
+ * DVR, or fails to compile.
57686
+ */
57687
+ /** Matches the trailing `if (gl_FragColor.a < 0.05) discard;` in main(), tabs and all. */
57688
+ const DISCARD_TEST = /if\s*\(\s*gl_FragColor\.a\s*<\s*0\.05\s*\)\s*discard;/;
57689
+ const CLIM_DECL = "uniform vec2 u_clim;";
57690
+ /** The forward declaration block, and the dispatch inside main(). */
57691
+ const CAST_ISO_PROTO = "void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);";
57692
+ const CAST_ISO_CALL = "cast_iso(start_loc, step, nsteps, view_ray);";
57693
+ /**
57694
+ * Front-to-back emission-absorption compositing.
57695
+ *
57696
+ * Two details matter, both established by rendering this dataset offline:
57697
+ *
57698
+ * - Emission is scaled by the windowed intensity `t`, not taken straight from the colormap.
57699
+ * The colormap's low end is a mid blue, so thousands of faint samples each deposit blue
57700
+ * and wash the interior out into a featureless shell. Weighting by `t` makes low-intensity
57701
+ * blood pool contribute almost nothing, which is what lets the chamber read as dark.
57702
+ * - `u_dvr_gain` then restores the brightness that the `t` weighting removed.
57703
+ *
57704
+ * Opacity per sample is `colour.a * u_dvr_density`; the colormap's alpha ramp is the transfer
57705
+ * function. Accumulation is premultiplied and un-premultiplied at the end, because three
57706
+ * blends with (srcAlpha, 1 - srcAlpha).
57707
+ */
57708
+ const CAST_DVR_BODY = `
57709
+
57710
+ void cast_dvr(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {
57711
+
57712
+ vec4 acc = vec4(0.0);
57713
+ vec3 loc = start_loc;
57714
+
57715
+ // Same hard-coded bound + inner break as cast_mip: GLSL cannot compare the
57716
+ // loop index against a non-constant expression.
57717
+ for (int iter=0; iter<MAX_STEPS; iter++) {
57718
+ if (iter >= nsteps)
57719
+ break;
57720
+
57721
+ float val = sample1(loc);
57722
+ float t = clamp((val - u_clim[0]) / (u_clim[1] - u_clim[0]), 0.0, 1.0);
57723
+ vec4 color = apply_colormap(val);
57724
+
57725
+ float a = color.a * u_dvr_density;
57726
+ vec3 emission = color.rgb * t * u_dvr_gain;
57727
+
57728
+ // Front-to-back: what is already accumulated occludes what is behind it.
57729
+ acc.rgb += (1.0 - acc.a) * emission * a;
57730
+ acc.a += (1.0 - acc.a) * a;
57731
+
57732
+ // Early ray termination: nothing behind an opaque accumulation matters.
57733
+ if (acc.a >= 0.95)
57734
+ break;
57735
+
57736
+ loc += step;
57737
+ }
57738
+
57739
+ // three blends with (srcAlpha, 1 - srcAlpha), so hand back straight alpha.
57740
+ if (acc.a > 0.001)
57741
+ acc.rgb /= acc.a;
57742
+
57743
+ gl_FragColor = acc;
57744
+ }`;
57745
+ /** Replace `find` once, throwing `message` if it was not present. */
57746
+ function spliceOnce(source, find, replace, message) {
57747
+ const out = source.replace(find, replace);
57748
+ if (out === source)
57749
+ throw new Error(`volumeShader: ${message} — three's VolumeShader changed`);
57750
+ return out;
57751
+ }
57752
+ function createVolumeShaderWithOpacity() {
57753
+ const uniforms = UniformsUtils.clone(VolumeRenderShader1.uniforms);
57754
+ uniforms.u_opacity = { value: 1.0 };
57755
+ uniforms.u_dvr_density = { value: 0.25 };
57756
+ uniforms.u_dvr_gain = { value: 2.5 };
57757
+ let fragmentShader = VolumeRenderShader1.fragmentShader;
57758
+ fragmentShader = spliceOnce(fragmentShader, CLIM_DECL, `${CLIM_DECL}\n uniform float u_opacity;\n uniform float u_dvr_density;\n uniform float u_dvr_gain;`, "could not declare u_opacity / u_dvr_density / u_dvr_gain");
57759
+ fragmentShader = spliceOnce(fragmentShader, CAST_ISO_PROTO, `${CAST_ISO_PROTO}\n\t\t\t\tvoid cast_dvr(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);`, "could not forward-declare cast_dvr");
57760
+ fragmentShader = spliceOnce(fragmentShader, CAST_ISO_CALL, `${CAST_ISO_CALL}\n\t\t\t\t\t\telse if (u_renderstyle == 2)\n\t\t\t\t\t\t\t\tcast_dvr(start_loc, step, nsteps, view_ray);`, "could not dispatch cast_dvr");
57761
+ fragmentShader = spliceOnce(fragmentShader, DISCARD_TEST, "gl_FragColor.a *= u_opacity;\n\t\t\t\t\t\tif (gl_FragColor.a < 0.01) discard;", "could not patch the discard test");
57762
+ // The fragment shader is one template literal ending in `}`; append the new function.
57763
+ fragmentShader = fragmentShader.trimEnd() + CAST_DVR_BODY;
57764
+ return { uniforms, vertexShader: VolumeRenderShader1.vertexShader, fragmentShader };
57765
+ }
57766
+
57767
+ /** u_renderstyle encoding. `dvr` is our addition — see Utils/volumeShader.ts. */
57768
+ const RENDER_STYLE = { mip: 0, iso: 1, dvr: 2 };
57769
+ /**
57770
+ * Starting window, measured from the data rather than guessed: this volume's maximum
57771
+ * sample is 178/255 = 0.698 and 65% of its voxels are zero. A window whose top sits
57772
+ * above the data maximum (the old [0.2, 0.9]) squeezes nearly every sample into the
57773
+ * colormap's transparent low end, producing a near-invisible cloud.
57774
+ *
57775
+ * The floor then matters differently per render style. Under DVR the LV blood pool sits at
57776
+ * roughly 0.13 normalised, so a floor near 0.10 is what makes the chamber go transparent and
57777
+ * become visible; MIP prefers a lower floor (~0.01) to keep the faint speckle. The default
57778
+ * serves DVR, which is the style that can actually show the heart.
57779
+ */
57780
+ const DEFAULT_CLIM = [0.1, 0.55];
57781
+ /** Resolve `ElementDataFile` relative to its .mhd URL. */
57782
+ function resolveRawUrl(mhdUrl, elementDataFile) {
57783
+ return mhdUrl.replace(/[^/]+$/, elementDataFile);
57784
+ }
57785
+ function loadFrame(mhdUrl) {
57786
+ return __awaiter(this, void 0, void 0, function* () {
57787
+ const headerResponse = yield fetch(mhdUrl);
57788
+ if (!headerResponse.ok) {
57789
+ throw new Error(`mhd fetch failed: ${mhdUrl} (${headerResponse.status})`);
57790
+ }
57791
+ const header = parseMhdHeader(yield headerResponse.text());
57792
+ const rawUrl = resolveRawUrl(mhdUrl, header.elementDataFile);
57793
+ const rawResponse = yield fetch(rawUrl);
57794
+ if (!rawResponse.ok) {
57795
+ throw new Error(`raw fetch failed: ${rawUrl} (${rawResponse.status})`);
57796
+ }
57797
+ const buffer = yield rawResponse.arrayBuffer();
57798
+ const expected = voxelCount(header);
57799
+ if (buffer.byteLength !== expected) {
57800
+ throw new Error(`raw size mismatch for ${rawUrl}: got ${buffer.byteLength}, expected ${expected}`);
57801
+ }
57802
+ return { data: new Uint8Array(buffer), dims: header.dims, header };
57803
+ });
57804
+ }
57805
+ /** uint8 volume -> single-channel 3D texture. 1 byte/voxel; do not widen to float. */
57806
+ function createVolumeTexture(frame) {
57807
+ const [width, height, depth] = frame.dims;
57808
+ const texture = new Data3DTexture(frame.data, width, height, depth);
57809
+ texture.format = RedFormat;
57810
+ texture.type = UnsignedByteType;
57811
+ texture.minFilter = texture.magFilter = LinearFilter;
57812
+ texture.unpackAlignment = 1;
57813
+ texture.needsUpdate = true;
57814
+ return texture;
57815
+ }
57816
+ /**
57817
+ * Load a 4D volume sequence (one .mhd/.raw pair per cardiac phase) and add it to `scene`
57818
+ * as a raycast volume.
57819
+ *
57820
+ * The returned controller runs NO clock of its own — drive it with setFrame()/setPhase()
57821
+ * so it can share a cardiac-phase clock with other modalities.
57822
+ */
57823
+ function loadRaw4DVolume(mhdUrls, scene, opts = {}, callback) {
57824
+ let loaded = 0;
57825
+ const jobs = mhdUrls.map((url) => loadFrame(url).then((frame) => {
57826
+ var _a;
57827
+ (_a = opts.onProgress) === null || _a === void 0 ? void 0 : _a.call(opts, ++loaded, mhdUrls.length);
57828
+ return frame;
57829
+ }));
57830
+ Promise.all(jobs)
57831
+ .then((frames) => {
57832
+ var _a, _b, _c, _d, _e, _f;
57833
+ if (frames.length === 0) {
57834
+ throw new Error("raw4DVolume: mhdUrls is empty");
57835
+ }
57836
+ const dims = frames[0].dims;
57837
+ for (const frame of frames) {
57838
+ if (frame.dims.join() !== dims.join()) {
57839
+ throw new Error(`raw4DVolume: frames disagree on dims (${frame.dims} vs ${dims})`);
57840
+ }
57841
+ }
57842
+ const [width, height, depth] = dims;
57843
+ const textures = frames.map(createVolumeTexture);
57844
+ const colormap = createBlueOrangeColormap();
57845
+ const { uniforms, vertexShader, fragmentShader } = createVolumeShaderWithOpacity();
57846
+ const clim = (_a = opts.clim) !== null && _a !== void 0 ? _a : DEFAULT_CLIM;
57847
+ uniforms.u_data.value = textures[0];
57848
+ uniforms.u_size.value.set(width, height, depth);
57849
+ uniforms.u_clim.value.set(clim[0], clim[1]);
57850
+ uniforms.u_renderstyle.value = RENDER_STYLE[(_b = opts.renderStyle) !== null && _b !== void 0 ? _b : "mip"];
57851
+ uniforms.u_renderthreshold.value = (_c = opts.isoThreshold) !== null && _c !== void 0 ? _c : 0.35;
57852
+ uniforms.u_cmdata.value = colormap;
57853
+ uniforms.u_opacity.value = (_d = opts.opacity) !== null && _d !== void 0 ? _d : 0.9;
57854
+ uniforms.u_dvr_density.value = (_e = opts.dvrDensity) !== null && _e !== void 0 ? _e : 0.25;
57855
+ uniforms.u_dvr_gain.value = (_f = opts.dvrGain) !== null && _f !== void 0 ? _f : 2.5;
57856
+ const material = new ShaderMaterial({
57857
+ uniforms,
57858
+ vertexShader,
57859
+ fragmentShader,
57860
+ // The volume shader marches from the back face inward.
57861
+ side: BackSide,
57862
+ transparent: true,
57863
+ depthWrite: false,
57864
+ // REQUIRED: the MRI plane and the VTK surfaces both write depth (neither sets
57865
+ // depthWrite:false). With depth testing on, back faces sitting behind them are
57866
+ // discarded — and since the ray march is bootstrapped by the back-face fragment,
57867
+ // those pixels cast no ray at all, slicing the cone away exactly over the heart.
57868
+ depthTest: false,
57869
+ });
57870
+ // The shader expects local coords spanning [-0.5, size-0.5] on each axis.
57871
+ const geometry = new BoxGeometry(width, height, depth);
57872
+ geometry.translate(width / 2 - 0.5, height / 2 - 0.5, depth / 2 - 0.5);
57873
+ const mesh = new Mesh(geometry, material);
57874
+ // Re-centre the box on the group origin so `root`'s transform rotates about the
57875
+ // volume's centre rather than its corner.
57876
+ mesh.position.set(-(width - 1) / 2, -(height - 1) / 2, -(depth - 1) / 2);
57877
+ // Draw after the MRI plane (0) and the surfaces (1..n) — see loadAligned4D.
57878
+ mesh.renderOrder = 10;
57879
+ const root = new Group();
57880
+ root.add(mesh);
57881
+ scene.add(root);
57882
+ const frameCount = textures.length;
57883
+ let disposed = false;
57884
+ // --- Path 1: the header actually places the volume, so trust it ------------------
57885
+ //
57886
+ // `mesh` is centred on the group origin, so a point at group-local `p` is voxel
57887
+ // index `p + half`. The header gives voxel -> world, hence root = V2W . T(half).
57888
+ //
57889
+ // A zero Offset with an identity TransformMatrix is NOT treated as a pose: it is
57890
+ // indistinguishable from "nobody filled this in", and silently trusting it would
57891
+ // place an unregistered volume at the world origin while claiming it is registered.
57892
+ //
57893
+ // A pose is equally worthless if it is expressed in a DIFFERENT world frame — same
57894
+ // patient, different scanner, different origin. DICOM proves a shared frame with
57895
+ // FrameOfReferenceUID; MetaImage has no such field, so a producer must carry it across as
57896
+ // a custom line. When the caller names the scene's frame, a missing or mismatched UID
57897
+ // means the header's placement must NOT be trusted.
57898
+ const header = frames[0].header;
57899
+ const expectedUID = opts.expectFrameOfReferenceUID;
57900
+ const { registered, frameVerified, reason } = resolveRegistration(header, expectedUID);
57901
+ if (reason === "frame-missing") {
57902
+ console.warn("raw4DVolume: the .mhd places the volume but declares no FrameOfReferenceUID, so " +
57903
+ "nothing shows it shares the scene's world frame. Treating it as UNREGISTERED. " +
57904
+ `Add 'FrameOfReferenceUID = ${expectedUID}' to the .mhd to accept its pose.`);
57905
+ }
57906
+ else if (reason === "frame-mismatch") {
57907
+ console.warn("raw4DVolume: the .mhd's FrameOfReferenceUID does not match the scene's, so its pose " +
57908
+ "describes a different coordinate system. Treating it as UNREGISTERED.\n" +
57909
+ ` volume: ${header.frameOfReferenceUID}\n scene : ${expectedUID}`);
57910
+ }
57911
+ else if (reason === "unverified") {
57912
+ console.warn("raw4DVolume: honouring the .mhd's pose, but no expected FrameOfReferenceUID was " +
57913
+ "supplied, so nothing verified that it shares the scene's world frame.");
57914
+ }
57915
+ if (registered) {
57916
+ const half = new Matrix4().makeTranslation((width - 1) / 2, (height - 1) / 2, (depth - 1) / 2);
57917
+ const voxelToWorld = new Matrix4().fromArray(voxelToWorldMatrix(header));
57918
+ root.matrixAutoUpdate = false;
57919
+ root.matrix.copy(voxelToWorld.multiply(half));
57920
+ root.matrixWorldNeedsUpdate = true;
57921
+ }
57922
+ let warnedManualOverride = false;
57923
+ const applyTransform = (t) => {
57924
+ if (registered) {
57925
+ if (!warnedManualOverride) {
57926
+ warnedManualOverride = true;
57927
+ console.warn("raw4DVolume: ignoring manual transform — this volume is placed by its .mhd " +
57928
+ "Offset/TransformMatrix. Strip those fields to pose it by hand.");
57929
+ }
57930
+ return;
57931
+ }
57932
+ if (t.position)
57933
+ root.position.set(t.position[0], t.position[1], t.position[2]);
57934
+ // quaternion wins: aligning the cone axis to an arbitrary world direction is
57935
+ // natural as a quaternion and awkward as Euler angles.
57936
+ if (t.quaternion) {
57937
+ root.quaternion.set(t.quaternion[0], t.quaternion[1], t.quaternion[2], t.quaternion[3]);
57938
+ }
57939
+ else if (t.rotation) {
57940
+ root.rotation.set(t.rotation[0], t.rotation[1], t.rotation[2]);
57941
+ }
57942
+ if (t.scale !== undefined) {
57943
+ typeof t.scale === "number"
57944
+ ? root.scale.setScalar(t.scale)
57945
+ : root.scale.set(t.scale[0], t.scale[1], t.scale[2]);
57946
+ }
57947
+ };
57948
+ // Callers may always pass a fallback pose; a registered header simply wins, quietly.
57949
+ if (!registered && opts.transform)
57950
+ applyTransform(opts.transform);
57951
+ const setFrame = (i) => {
57952
+ if (disposed)
57953
+ return;
57954
+ const index = ((i % frameCount) + frameCount) % frameCount;
57955
+ uniforms.u_data.value = textures[index];
57956
+ };
57957
+ const ctrl = {
57958
+ root,
57959
+ mesh,
57960
+ frameCount,
57961
+ registered,
57962
+ frameVerified,
57963
+ frameOfReferenceUID: header.frameOfReferenceUID,
57964
+ setFrame,
57965
+ setPhase: (p) => setFrame(Math.floor(p * frameCount)),
57966
+ setOpacity: (v) => {
57967
+ if (disposed)
57968
+ return;
57969
+ uniforms.u_opacity.value = v;
57970
+ },
57971
+ setClim: (lo, hi) => {
57972
+ if (disposed)
57973
+ return;
57974
+ // three's apply_colormap divides by (hi - lo); keep the span non-zero.
57975
+ uniforms.u_clim.value.set(lo, Math.max(hi, lo + 1e-3));
57976
+ },
57977
+ setRenderStyle: (s) => {
57978
+ if (disposed)
57979
+ return;
57980
+ uniforms.u_renderstyle.value = RENDER_STYLE[s];
57981
+ },
57982
+ setDvrDensity: (v) => {
57983
+ if (disposed)
57984
+ return;
57985
+ uniforms.u_dvr_density.value = v;
57986
+ },
57987
+ setDvrGain: (v) => {
57988
+ if (disposed)
57989
+ return;
57990
+ uniforms.u_dvr_gain.value = v;
57991
+ },
57992
+ setTransform: (t) => {
57993
+ if (disposed)
57994
+ return;
57995
+ applyTransform(t);
57996
+ },
57997
+ dispose: () => {
57998
+ if (disposed)
57999
+ return;
58000
+ disposed = true;
58001
+ scene.remove(root);
58002
+ root.remove(mesh);
58003
+ geometry.dispose();
58004
+ material.dispose();
58005
+ colormap.dispose();
58006
+ textures.forEach((t) => t.dispose());
58007
+ textures.length = 0;
58008
+ },
58009
+ };
58010
+ callback && callback(ctrl);
58011
+ })
58012
+ .catch((err) => {
58013
+ const error = err instanceof Error ? err : new Error(String(err));
58014
+ if (opts.onError) {
58015
+ opts.onError(error);
58016
+ }
58017
+ else {
58018
+ throw error;
58019
+ }
58020
+ });
58021
+ }
58022
+
57421
58023
  class VTKLoader extends Loader {
57422
58024
 
57423
58025
  constructor( manager ) {
@@ -61608,6 +62210,7 @@ void main() {
61608
62210
  this.editingId = null; // committed geodesic re-opened for editing (Task 1.5)
61609
62211
  this.geoClosed = false; // whether the active/edited geodesic is a closed loop
61610
62212
  this._projV = new Vector3();
62213
+ this.listenersOn = false;
61611
62214
  /** Block the OS right-click menu when the pointer is over the WebGL canvas (not the HTML panels). */
61612
62215
  this.onContextMenu = (e) => {
61613
62216
  if (this.insideContainer(e))
@@ -61895,16 +62498,7 @@ void main() {
61895
62498
  this.store.subscribe(() => this.reconcile());
61896
62499
  // Listen on window in the capture phase (capture=true): receive every pointer event before
61897
62500
  // copper's TrackballControls, so its setPointerCapture / event routing doesn't drop moves mid-drag.
61898
- window.addEventListener("pointerdown", this.onPointerDown, true);
61899
- window.addEventListener("pointermove", this.onPointerMove, true);
61900
- window.addEventListener("pointerup", this.onPointerUp, true);
61901
- window.addEventListener("keydown", this.onKeyDown);
61902
- window.addEventListener("keyup", this.onKeyUp);
61903
- window.addEventListener("resize", this.onResize);
61904
- // Suppress the browser's native context menu over the WebGL canvas in EVERY mode: right-click
61905
- // there is used for camera pan (and, in geodesic mode, delete-anchor), so the OS menu must
61906
- // never appear. Guarded by insideContainer → right-clicking the HTML panels keeps its menu.
61907
- window.addEventListener("contextmenu", this.onContextMenu, true);
62501
+ this.addListeners();
61908
62502
  this.applyCameraGating();
61909
62503
  }
61910
62504
  get freehandColor() {
@@ -62044,6 +62638,12 @@ void main() {
62044
62638
  setVisible(id, visible) {
62045
62639
  this.store.setVisible(id, visible);
62046
62640
  }
62641
+ /** Show/hide every annotation in this model in one reconcile (backs the per-model hide-all button). */
62642
+ setAllVisible(visible) {
62643
+ for (const a of this.store.list())
62644
+ a.visible = visible;
62645
+ this.store.touch(); // one notify → reconcile() applies object3D.visible
62646
+ }
62047
62647
  /**
62048
62648
  * Rebuild annotations from an exported payload (local-space points). Normals are taken from the
62049
62649
  * point when present ([x,y,z,nx,ny,nz]); otherwise recovered from the welded graph's nearest
@@ -62507,8 +63107,21 @@ void main() {
62507
63107
  const tag = t.tagName;
62508
63108
  return tag === "INPUT" || tag === "TEXTAREA" || t.isContentEditable;
62509
63109
  }
62510
- dispose() {
62511
- this.clearActiveGeo();
63110
+ addListeners() {
63111
+ if (this.listenersOn)
63112
+ return;
63113
+ window.addEventListener("pointerdown", this.onPointerDown, true);
63114
+ window.addEventListener("pointermove", this.onPointerMove, true);
63115
+ window.addEventListener("pointerup", this.onPointerUp, true);
63116
+ window.addEventListener("keydown", this.onKeyDown);
63117
+ window.addEventListener("keyup", this.onKeyUp);
63118
+ window.addEventListener("resize", this.onResize);
63119
+ window.addEventListener("contextmenu", this.onContextMenu, true);
63120
+ this.listenersOn = true;
63121
+ }
63122
+ removeListeners() {
63123
+ if (!this.listenersOn)
63124
+ return;
62512
63125
  window.removeEventListener("pointerdown", this.onPointerDown, true);
62513
63126
  window.removeEventListener("pointermove", this.onPointerMove, true);
62514
63127
  window.removeEventListener("pointerup", this.onPointerUp, true);
@@ -62516,6 +63129,39 @@ void main() {
62516
63129
  window.removeEventListener("keyup", this.onKeyUp);
62517
63130
  window.removeEventListener("resize", this.onResize);
62518
63131
  window.removeEventListener("contextmenu", this.onContextMenu, true);
63132
+ this.listenersOn = false;
63133
+ }
63134
+ /** Attach input listeners and make this annotator live. Idempotent. */
63135
+ activate() { this.addListeners(); }
63136
+ /** Detach input listeners so this annotator ignores input while its lines stay in the scene. Idempotent. */
63137
+ deactivate() {
63138
+ if (!this.listenersOn)
63139
+ return;
63140
+ // Finish or discard any in-progress geodesic so a dormant annotator leaves no half-state.
63141
+ if (this.editingId)
63142
+ this.recommitGeodesic();
63143
+ else if (this.activeGeo)
63144
+ this.clearActiveGeo();
63145
+ // Discard any in-progress freehand stroke — only onPointerUp commits it, and we are detaching
63146
+ // that listener; committing a half-drawn stroke on an active-model switch would be surprising.
63147
+ if (this.activeStroke && this.activeLine) {
63148
+ this.o.scene.remove(this.activeLine);
63149
+ this.disposeObject(this.activeLine);
63150
+ this.activeStroke = undefined;
63151
+ this.activeLine = undefined;
63152
+ }
63153
+ // Reset transient pointer state so a later activate() cannot commit stale drag/stroke data.
63154
+ this.draggingAnchor = -1;
63155
+ this.pointerDown = false;
63156
+ // Release draw-lock / space and un-gate the camera so a dormant model never leaves controls locked.
63157
+ this.drawLock = false;
63158
+ this.spaceHeld = false;
63159
+ this.applyCameraGating();
63160
+ this.removeListeners();
63161
+ }
63162
+ dispose() {
63163
+ this.clearActiveGeo();
63164
+ this.removeListeners();
62519
63165
  }
62520
63166
  }
62521
63167
  SurfaceAnnotator.TAP_MS = 250;
@@ -62834,12 +63480,12 @@ void main() {
62834
63480
  applyFrame();
62835
63481
  }
62836
63482
  };
62837
- this.addPreRenderCallbackFunction(tick);
62838
- const clockId = tick.id;
63483
+ const clockId = this.addPreRenderCallbackFunction(tick);
62839
63484
  const ctrl = {
62840
63485
  plane: tex.mesh,
62841
63486
  surfaceMeshes,
62842
63487
  frameCount,
63488
+ frameOfReferenceUID: stacked.frameOfReferenceUID,
62843
63489
  play: () => {
62844
63490
  playing = true;
62845
63491
  lastStep = performance.now();
@@ -62868,6 +63514,9 @@ void main() {
62868
63514
  setWindow: (center, width) => {
62869
63515
  tex.setWindow(center, width);
62870
63516
  },
63517
+ setPlaneBrightness: (v) => {
63518
+ tex.setBrightness(v);
63519
+ },
62871
63520
  setPlaneOpacity: (v) => {
62872
63521
  const m = tex.mesh.material;
62873
63522
  m.transparent = v < 1;
@@ -62909,6 +63558,14 @@ void main() {
62909
63558
  callback && callback(ctrl);
62910
63559
  });
62911
63560
  }
63561
+ /**
63562
+ * Load a 4D volume sequence (.mhd/.raw per cardiac phase) and render it as a raycast
63563
+ * volume. The returned controller runs no clock of its own — drive it with
63564
+ * setFrame()/setPhase() so it can share a cardiac-phase clock with other modalities.
63565
+ */
63566
+ loadRaw4DVolume(mhdUrls, opts, callback) {
63567
+ loadRaw4DVolume(mhdUrls, this.scene, opts, callback);
63568
+ }
62912
63569
  getPlayRate() {
62913
63570
  return this.playRate;
62914
63571
  }
@@ -63307,21 +63964,7 @@ void main() {
63307
63964
  this.controls.rotateSpeed = 0.02;
63308
63965
  this.controls.staticMoving = true;
63309
63966
  // this.controls = new OrbitControls(this.camera, this.container);
63310
- this.preRenderCallbackFunctions = {
63311
- index: 0,
63312
- cache: [],
63313
- add(fn) {
63314
- if (!fn.id) {
63315
- fn.id = ++this.index;
63316
- this.cache[fn.id] = fn;
63317
- return;
63318
- }
63319
- },
63320
- remove(id) {
63321
- if (this.cache[id])
63322
- delete this.cache[id];
63323
- },
63324
- };
63967
+ this.preRenderCallbackFunctions = createPreRenderRegistry();
63325
63968
  this.init();
63326
63969
  }
63327
63970
  init() {
@@ -63694,36 +64337,6 @@ void main() {
63694
64337
  }
63695
64338
  }
63696
64339
 
63697
- /******************************************************************************
63698
- Copyright (c) Microsoft Corporation.
63699
-
63700
- Permission to use, copy, modify, and/or distribute this software for any
63701
- purpose with or without fee is hereby granted.
63702
-
63703
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
63704
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
63705
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
63706
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
63707
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
63708
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
63709
- PERFORMANCE OF THIS SOFTWARE.
63710
- ***************************************************************************** */
63711
-
63712
- function __awaiter(thisArg, _arguments, P, generator) {
63713
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
63714
- return new (P || (P = Promise))(function (resolve, reject) {
63715
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
63716
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
63717
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
63718
- step((generator = generator.apply(thisArg, _arguments || [])).next());
63719
- });
63720
- }
63721
-
63722
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
63723
- var e = new Error(message);
63724
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
63725
- };
63726
-
63727
64340
  var bundle = createCommonjsModule(function (module, exports) {
63728
64341
  (function webpackUniversalModuleDefinition(root, factory) {
63729
64342
  module.exports = factory();
@@ -83951,15 +84564,15 @@ void main() {
83951
84564
  }
83952
84565
 
83953
84566
  // import * as kiwrious from "copper3d_plugin_heart_k";
83954
- // "v3.6.12" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
84567
+ // "v3.7.0" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
83955
84568
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
83956
84569
  // referencing it throws a ReferenceError — guard it so local loading still works.
83957
84570
  let _revision = "unknown";
83958
84571
  try {
83959
- _revision = "v3.6.12";
84572
+ _revision = "v3.7.0";
83960
84573
  }
83961
84574
  catch (_a) {
83962
- /* "v3.6.12" not injected (local source build) */
84575
+ /* "v3.7.0" not injected (local source build) */
83963
84576
  }
83964
84577
  const REVISION = _revision;
83965
84578
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__