copper3d 3.11.4 → 3.11.6

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 (51) hide show
  1. package/README.md +51 -1
  2. package/ai-index/guides/4D-MRI-LV-rendering.md +1 -1
  3. package/ai-index/guides/copper3d-rendering-optimization.md +37 -0
  4. package/ai-index/guides/load-callbacks.md +35 -0
  5. package/ai-index/guides/nrrd-tools.md +110 -2
  6. package/ai-index/guides/segmentation-module.md +108 -2
  7. package/ai-index/manifest.json +8 -8
  8. package/ai-index/symbols.json +1 -1
  9. package/dist/Loader/copperNrrdLoader.d.ts +33 -0
  10. package/dist/Loader/copperNrrdLoader.js +27 -5
  11. package/dist/Loader/copperNrrdLoader.js.map +1 -1
  12. package/dist/Renderer/copperRenderer.js +2 -2
  13. package/dist/Renderer/copperRenderer.js.map +1 -1
  14. package/dist/Scene/copperScene.d.ts +1 -1
  15. package/dist/Scene/copperScene.js +4 -1
  16. package/dist/Scene/copperScene.js.map +1 -1
  17. package/dist/Utils/segmentation/DragOperator.d.ts +6 -0
  18. package/dist/Utils/segmentation/DragOperator.js +9 -0
  19. package/dist/Utils/segmentation/DragOperator.js.map +1 -1
  20. package/dist/Utils/segmentation/NrrdTools.d.ts +38 -1
  21. package/dist/Utils/segmentation/NrrdTools.js +105 -2
  22. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  23. package/dist/Utils/segmentation/RenderingUtils.d.ts +7 -10
  24. package/dist/Utils/segmentation/RenderingUtils.js +14 -117
  25. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  26. package/dist/Utils/segmentation/contourPaint.d.ts +37 -0
  27. package/dist/Utils/segmentation/contourPaint.js +128 -0
  28. package/dist/Utils/segmentation/contourPaint.js.map +1 -0
  29. package/dist/Utils/segmentation/tools/DragSliceTool.js +5 -0
  30. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  31. package/dist/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  32. package/dist/Utils/segmentation/tools/MaskMirror.js +165 -0
  33. package/dist/Utils/segmentation/tools/MaskMirror.js.map +1 -0
  34. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +8 -0
  35. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  36. package/dist/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  37. package/dist/bundle.esm.js +459 -122
  38. package/dist/bundle.umd.js +459 -121
  39. package/dist/index.d.ts +2 -2
  40. package/dist/index.js +2 -2
  41. package/dist/index.js.map +1 -1
  42. package/dist/types/Loader/copperNrrdLoader.d.ts +33 -0
  43. package/dist/types/Scene/copperScene.d.ts +1 -1
  44. package/dist/types/Utils/segmentation/DragOperator.d.ts +6 -0
  45. package/dist/types/Utils/segmentation/NrrdTools.d.ts +38 -1
  46. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +7 -10
  47. package/dist/types/Utils/segmentation/contourPaint.d.ts +37 -0
  48. package/dist/types/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  49. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  50. package/dist/types/index.d.ts +2 -2
  51. package/package.json +1 -1
@@ -85673,7 +85673,20 @@ void main() {
85673
85673
  /** All three, which is what `loadNrrd` has always extracted. */
85674
85674
  const DEFAULT_AXES = ["x", "y", "z"];
85675
85675
  /**
85676
- * Work around a three.js regression (present from r175 through at least r185).
85676
+ * Post-extraction fixups every `VolumeSlice` needs. Run it on each slice right
85677
+ * after `Volume.extractSlice`; `undefined` (an axis not extracted) is skipped.
85678
+ *
85679
+ * ## Readback-friendly buffer
85680
+ *
85681
+ * Stock `VolumeSlice.repaint` reads `ctxBuffer` back with `getImageData` on
85682
+ * every repaint. three creates that context in the constructor without
85683
+ * `willReadFrequently`, so the canvas may live on the GPU and each repaint
85684
+ * copies it back to the CPU (Chrome warns once per such context). A context's
85685
+ * attributes are fixed by the first `getContext` call on its canvas, so the
85686
+ * buffer is replaced by a canvas whose context is created with the flag;
85687
+ * `updateGeometry` re-fetching it later gets that same context.
85688
+ *
85689
+ * ## three.js regression (present from r175 through at least r185)
85677
85690
  *
85678
85691
  * `VolumeSlice`'s constructor calls `updateGeometry()` and then `repaint()`, but
85679
85692
  * *afterwards* assigns the JSDoc default values:
@@ -85691,9 +85704,18 @@ void main() {
85691
85704
  * Recomputing the geometry right after extraction restores the correct values.
85692
85705
  * It is a harmless recompute on three <= r174, where the bug does not exist.
85693
85706
  */
85694
- function repairSliceGeometry(...slices) {
85707
+ function prepareVolumeSlices(...slices) {
85695
85708
  for (const slice of slices) {
85696
- if (slice && slice.iLength === 0 && typeof slice.updateGeometry === "function") {
85709
+ if (!slice)
85710
+ continue;
85711
+ if (slice.canvasBuffer) {
85712
+ const buffer = document.createElement("canvas");
85713
+ buffer.width = slice.canvasBuffer.width;
85714
+ buffer.height = slice.canvasBuffer.height;
85715
+ slice.canvasBuffer = buffer;
85716
+ slice.ctxBuffer = buffer.getContext("2d", { willReadFrequently: true });
85717
+ }
85718
+ if (slice.iLength === 0 && typeof slice.updateGeometry === "function") {
85697
85719
  slice.updateGeometry();
85698
85720
  }
85699
85721
  }
@@ -85722,7 +85744,7 @@ void main() {
85722
85744
  const axisIndex = axis === "x" ? 0 : axis === "y" ? 1 : 2;
85723
85745
  const initIndex = Math.floor(dimensions[axisIndex] / 2);
85724
85746
  const slice = volume.extractSlice(axis, initIndex * ratio[axisIndex]);
85725
- repairSliceGeometry(slice);
85747
+ prepareVolumeSlices(slice);
85726
85748
  slice.initIndex = initIndex;
85727
85749
  slice.MaxIndex = dimensions[axisIndex] - 1;
85728
85750
  slice.RSARatio = ratio[axisIndex];
@@ -85767,7 +85789,7 @@ void main() {
85767
85789
  const sliceX = wanted.x
85768
85790
  ? volume.extractSlice("x", initIndexX * ratio[0])
85769
85791
  : undefined;
85770
- repairSliceGeometry(sliceZ, sliceY, sliceX);
85792
+ prepareVolumeSlices(sliceZ, sliceY, sliceX);
85771
85793
  if (sliceZ) {
85772
85794
  sliceZ.initIndex = initIndexZ;
85773
85795
  sliceZ.MaxIndex = dimensions[2] - 1;
@@ -104543,7 +104565,7 @@ void main() {
104543
104565
  // rayster pick
104544
104566
  constructor(container, renderer, opt) {
104545
104567
  super(container, renderer, opt);
104546
- this.clock = new Clock();
104568
+ this.clock = new Timer();
104547
104569
  // isHalfed: boolean = false;
104548
104570
  this.mixer = null;
104549
104571
  this.playRate = 1.0;
@@ -105014,6 +105036,9 @@ void main() {
105014
105036
  }
105015
105037
  render(time) {
105016
105038
  this.controls.update();
105039
+ // Every frame, so a model's first mixer step is one frame long rather than
105040
+ // the time since this scene was built.
105041
+ this.clock.update();
105017
105042
  if (this.modelReady) {
105018
105043
  this.mixer && this.mixer.update(this.clock.getDelta() * this.playRate);
105019
105044
  // this.mixer && this.mixer.update((time as number) * this.playRate);
@@ -105041,7 +105066,7 @@ void main() {
105041
105066
  super(container, options);
105042
105067
  this.sceneMap = {};
105043
105068
  this.fps = 30;
105044
- this.renderClock = new Clock();
105069
+ this.renderClock = new Timer();
105045
105070
  this.delta = 0;
105046
105071
  this.interval = 1 / this.fps;
105047
105072
  this.preRenderCallbackFunctions = [];
@@ -105065,7 +105090,7 @@ void main() {
105065
105090
  if (this.delta === 0) {
105066
105091
  this.render();
105067
105092
  }
105068
- this.delta += this.renderClock.getDelta();
105093
+ this.delta += this.renderClock.update().getDelta();
105069
105094
  if (this.delta > this.interval) {
105070
105095
  this.render();
105071
105096
  if ((_c = this.options) === null || _c === void 0 ? void 0 : _c.performanceGui)
@@ -109321,6 +109346,11 @@ void main() {
109321
109346
  }
109322
109347
  let newIndex = view.currentSliceIndex + sliceModifyNum;
109323
109348
  if (newIndex != view.currentSliceIndex || view.showContrast) {
109349
+ // While a preview slice is shown the displayed slice has depth 1, so moving it would
109350
+ // paint blank; the host fetches the target slice instead.
109351
+ const target = Math.min(Math.max(newIndex, view.minIndex), view.maxIndex);
109352
+ if (this.callbacks.previewSliceMove(target))
109353
+ return;
109324
109354
  if (newIndex > view.maxIndex) {
109325
109355
  newIndex = view.maxIndex;
109326
109356
  view.contrastNum = this.ctx.protectedData.displaySlices.length - 1;
@@ -109449,6 +109479,7 @@ void main() {
109449
109479
  };
109450
109480
  this.sensitiveArray = [];
109451
109481
  this.refreshSphereOverlayCb = null;
109482
+ this.previewSliceMoveCb = () => false;
109452
109483
  // EventRouter for centralized event handling
109453
109484
  this.eventRouter = null;
109454
109485
  this.configDragMode = () => {
@@ -109506,6 +109537,7 @@ void main() {
109506
109537
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, targetCtx, w, h) => this.renderSliceToCanvas(layer, axis, sliceIndex, buffer, targetCtx, w, h),
109507
109538
  compositeAllLayers: () => this.compositeAllLayers(),
109508
109539
  refreshSphereOverlay: () => { var _a; return (_a = this.refreshSphereOverlayCb) === null || _a === void 0 ? void 0 : _a.call(this); },
109540
+ previewSliceMove: (index) => this.previewSliceMoveCb(index),
109509
109541
  }, this.showDragNumberDiv, dragEffectCanvases);
109510
109542
  }
109511
109543
  setShowDragNumberDiv(sliceIndexContainer) {
@@ -109519,6 +109551,13 @@ void main() {
109519
109551
  setRefreshSphereOverlay(cb) {
109520
109552
  this.refreshSphereOverlayCb = cb;
109521
109553
  }
109554
+ /**
109555
+ * Set the callback that may consume a slice move while a preview slice is shown.
109556
+ * Called by NrrdTools; until then every move proceeds normally.
109557
+ */
109558
+ setPreviewSliceMove(cb) {
109559
+ this.previewSliceMoveCb = cb;
109560
+ }
109522
109561
  /**
109523
109562
  * Set the EventRouter reference for centralized event handling.
109524
109563
  * Called by NrrdTools/DrawToolCore after EventRouter is initialized.
@@ -109605,6 +109644,125 @@ void main() {
109605
109644
  * stay visible against bright tissue.
109606
109645
  */
109607
109646
  const OUTLINE_WIDTH_PX = 1.5;
109647
+ /**
109648
+ * Populate one cache entry's paths for one render mode.
109649
+ *
109650
+ * Split out because the two modes are built at different times: whichever is in use when
109651
+ * a slice is first drawn, and the other one only if the clinician switches while still on
109652
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
109653
+ * sessions never turn on.
109654
+ */
109655
+ function buildPaths(entry, data, stride, outline) {
109656
+ const target = outline ? entry.outlines : entry.fills;
109657
+ for (const lbl of entry.labels) {
109658
+ target.set(lbl, outline
109659
+ ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109660
+ : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109661
+ }
109662
+ }
109663
+ /**
109664
+ * The cached contours for `slot` under `key`, extracting on a miss. One entry per slot: a new
109665
+ * key overwrites it. `readSlice` is called only when extraction is needed.
109666
+ */
109667
+ function contourEntry(cache, slot, key, readSlice, outline) {
109668
+ // Cache miss → run the expensive extraction once. Hits (zoom,
109669
+ // recomposite, contrast toggle) skip straight to the draw.
109670
+ let entry = cache.get(slot);
109671
+ if (!entry || entry.key !== key) {
109672
+ const slice = readSlice();
109673
+ entry = {
109674
+ key,
109675
+ W: slice.width,
109676
+ H: slice.height,
109677
+ labels: findLabelsInSlice(slice.data, slice.width, slice.height, slice.stride, 0),
109678
+ fills: new Map(),
109679
+ outlines: new Map(),
109680
+ };
109681
+ cache.set(slot, entry);
109682
+ buildPaths(entry, slice.data, slice.stride, outline);
109683
+ }
109684
+ else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109685
+ // The mode changed since this slice was last drawn, so the other set of
109686
+ // paths is cached and this one is not. Re-read the slice and build it; from
109687
+ // here on both are present and toggling is a pure cache hit.
109688
+ const slice = readSlice();
109689
+ buildPaths(entry, slice.data, slice.stride, outline);
109690
+ }
109691
+ return entry;
109692
+ }
109693
+ /** Paint an entry's visible labels onto `targetCtx`, scaled from voxels to `scaledWidth × scaledHeight`. */
109694
+ function paintContours(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis) {
109695
+ if (entry.labels.length === 0)
109696
+ return;
109697
+ targetCtx.save();
109698
+ // A throw (a missing colour, say) must not leave the transform on the target.
109699
+ try {
109700
+ drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis);
109701
+ }
109702
+ finally {
109703
+ targetCtx.restore();
109704
+ }
109705
+ }
109706
+ function drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis) {
109707
+ const { W, H, labels } = entry;
109708
+ const paths = outline ? entry.outlines : entry.fills;
109709
+ // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109710
+ // it off to match the rest of the pipeline.
109711
+ targetCtx.imageSmoothingEnabled = false;
109712
+ if (outline) {
109713
+ // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109714
+ // in the path instead. `lineWidth` is then measured in screen pixels, which
109715
+ // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109716
+ // thickens the line with the zoom, exactly when the clinician has magnified
109717
+ // the image to look at the boundary — and because voxels are rarely isotropic
109718
+ // (sx !== sy), it also comes out thicker in one axis than the other.
109719
+ const matrix = new DOMMatrix();
109720
+ if (axis === "y") {
109721
+ matrix.scaleSelf(1, -1);
109722
+ matrix.translateSelf(0, -scaledHeight);
109723
+ }
109724
+ matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109725
+ targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109726
+ // Segments are emitted per cell and meet at shared endpoints; round caps
109727
+ // close those joins. Canvas composites a whole Path2D in one pass, so the
109728
+ // overlap costs no doubled alpha.
109729
+ targetCtx.lineJoin = "round";
109730
+ targetCtx.lineCap = "round";
109731
+ for (const lbl of labels) {
109732
+ if (channelVis && channelVis[lbl] === false)
109733
+ continue;
109734
+ const path = paths.get(lbl);
109735
+ if (!path)
109736
+ continue;
109737
+ const color = colorOf(lbl);
109738
+ targetCtx.strokeStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109739
+ const display = new Path2D();
109740
+ display.addPath(path, matrix);
109741
+ targetCtx.stroke(display);
109742
+ }
109743
+ return;
109744
+ }
109745
+ // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109746
+ // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109747
+ // so the flip operates in display coordinates.
109748
+ if (axis === "y") {
109749
+ targetCtx.scale(1, -1);
109750
+ targetCtx.translate(0, -scaledHeight);
109751
+ }
109752
+ // Voxel coord (x ∈ [0, W], y ∈ [0, H]) → display coord.
109753
+ targetCtx.scale(scaledWidth / W, scaledHeight / H);
109754
+ for (const lbl of labels) {
109755
+ if (channelVis && channelVis[lbl] === false)
109756
+ continue;
109757
+ const path = paths.get(lbl);
109758
+ if (!path)
109759
+ continue;
109760
+ const color = colorOf(lbl);
109761
+ targetCtx.fillStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109762
+ targetCtx.fill(path, "nonzero");
109763
+ }
109764
+ }
109765
+
109608
109766
  /**
109609
109767
  * RenderingUtils — Rendering / slice-buffer helper methods.
109610
109768
  *
@@ -109619,6 +109777,10 @@ void main() {
109619
109777
  constructor(state) {
109620
109778
  /** Injected callback — set by owner after construction. */
109621
109779
  this.setEmptyCanvasSize = () => { };
109780
+ /** Set while this viewer draws another viewer's masks; painted after this viewer's own layers. */
109781
+ this.mirror = null;
109782
+ /** Called after every composite. The owner refreshes the viewers mirroring this one. */
109783
+ this.onComposited = null;
109622
109784
  // Reusable ImageData buffer for zero-allocation slice rendering
109623
109785
  this._reusableSliceBuffer = null;
109624
109786
  this._reusableBufferWidth = 0;
@@ -109653,7 +109815,8 @@ void main() {
109653
109815
  * Get MaskVolume for a specific layer
109654
109816
  *
109655
109817
  * @param layer - Layer name: "layer1", "layer2", or "layer3"
109656
- * @returns MaskVolume instance for the specified layer
109818
+ * @returns MaskVolume instance for the specified layer; `undefined` on a
109819
+ * read-only engine built with no layers, which has no volume to return
109657
109820
  */
109658
109821
  getVolumeForLayer(layer) {
109659
109822
  const { volumes } = this.state.protectedData.maskData;
@@ -109661,6 +109824,8 @@ void main() {
109661
109824
  if (vol)
109662
109825
  return vol;
109663
109826
  const firstLayerId = this.state.nrrd_states.image.layers[0];
109827
+ if (firstLayerId === undefined)
109828
+ return vol;
109664
109829
  console.warn(`RenderingUtils: unknown layer "${layer}", falling back to "${firstLayerId}"`);
109665
109830
  return volumes[firstLayerId];
109666
109831
  }
@@ -109728,22 +109893,6 @@ void main() {
109728
109893
  return null; // Volume not ready
109729
109894
  }
109730
109895
  }
109731
- /**
109732
- * Populate one cache entry's paths for one render mode.
109733
- *
109734
- * Split out because the two modes are built at different times: whichever is in use when
109735
- * a slice is first drawn, and the other one only if the clinician switches while still on
109736
- * that slice. Building both eagerly would make every slice scrub pay for a mode most
109737
- * sessions never turn on.
109738
- */
109739
- buildPaths(entry, data, stride, outline) {
109740
- const target = outline ? entry.outlines : entry.fills;
109741
- for (const lbl of entry.labels) {
109742
- target.set(lbl, outline
109743
- ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109744
- : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109745
- }
109746
- }
109747
109896
  /**
109748
109897
  * Render a layer's slice onto the target canvas as vector contours.
109749
109898
  *
@@ -109781,96 +109930,8 @@ void main() {
109781
109930
  const volume = this.getVolumeForLayer(layer);
109782
109931
  if (!volume)
109783
109932
  return;
109784
- const stride = volume.getChannels();
109785
- const cacheKey = `${axis}:${sliceIndex}:${volume.getVersion()}`;
109786
- // Cache miss → run the expensive extraction once. Hits (zoom,
109787
- // recomposite, contrast toggle) skip straight to the draw below.
109788
- let entry = this._contourCache.get(layer);
109789
- if (!entry || entry.key !== cacheKey) {
109790
- const slice = volume.getSliceUint8(sliceIndex, axis);
109791
- entry = {
109792
- key: cacheKey,
109793
- W: slice.width,
109794
- H: slice.height,
109795
- labels: findLabelsInSlice(slice.data, slice.width, slice.height, stride, 0),
109796
- fills: new Map(),
109797
- outlines: new Map(),
109798
- };
109799
- this._contourCache.set(layer, entry);
109800
- this.buildPaths(entry, slice.data, stride, outline);
109801
- }
109802
- else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109803
- // The mode changed since this slice was last drawn, so the other set of
109804
- // paths is cached and this one is not. Re-read the slice and build it; from
109805
- // here on both are present and toggling is a pure cache hit.
109806
- const slice = volume.getSliceUint8(sliceIndex, axis);
109807
- this.buildPaths(entry, slice.data, stride, outline);
109808
- }
109809
- if (entry.labels.length === 0)
109810
- return;
109811
- const { W, H, labels } = entry;
109812
- const paths = outline ? entry.outlines : entry.fills;
109813
- const channelVis = this.state.gui_states.layerChannel.channelVisibility[layer];
109814
- targetCtx.save();
109815
- // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109816
- // it off to match the rest of the pipeline.
109817
- targetCtx.imageSmoothingEnabled = false;
109818
- if (outline) {
109819
- // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109820
- // in the path instead. `lineWidth` is then measured in screen pixels, which
109821
- // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109822
- // thickens the line with the zoom, exactly when the clinician has magnified
109823
- // the image to look at the boundary — and because voxels are rarely isotropic
109824
- // (sx !== sy), it also comes out thicker in one axis than the other.
109825
- const matrix = new DOMMatrix();
109826
- if (axis === 'y') {
109827
- matrix.scaleSelf(1, -1);
109828
- matrix.translateSelf(0, -scaledHeight);
109829
- }
109830
- matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109831
- targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109832
- // Segments are emitted per cell and meet at shared endpoints; round caps
109833
- // close those joins. Canvas composites a whole Path2D in one pass, so the
109834
- // overlap costs no doubled alpha.
109835
- targetCtx.lineJoin = 'round';
109836
- targetCtx.lineCap = 'round';
109837
- for (const lbl of labels) {
109838
- if (channelVis && channelVis[lbl] === false)
109839
- continue;
109840
- const path = paths.get(lbl);
109841
- if (!path)
109842
- continue;
109843
- const color = volume.getChannelColor(lbl);
109844
- targetCtx.strokeStyle =
109845
- `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109846
- const display = new Path2D();
109847
- display.addPath(path, matrix);
109848
- targetCtx.stroke(display);
109849
- }
109850
- targetCtx.restore();
109851
- return;
109852
- }
109853
- // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109854
- // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109855
- // so the flip operates in display coordinates.
109856
- if (axis === 'y') {
109857
- targetCtx.scale(1, -1);
109858
- targetCtx.translate(0, -scaledHeight);
109859
- }
109860
- // Voxel coord (x ∈ [0, W], y ∈ [0, H]) → display coord.
109861
- targetCtx.scale(scaledWidth / W, scaledHeight / H);
109862
- for (const lbl of labels) {
109863
- if (channelVis && channelVis[lbl] === false)
109864
- continue;
109865
- const path = paths.get(lbl);
109866
- if (!path)
109867
- continue;
109868
- const color = volume.getChannelColor(lbl);
109869
- targetCtx.fillStyle =
109870
- `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109871
- targetCtx.fill(path, 'nonzero');
109872
- }
109873
- targetCtx.restore();
109933
+ const entry = contourEntry(this._contourCache, layer, `${axis}:${sliceIndex}:${volume.getVersion()}`, () => (Object.assign(Object.assign({}, volume.getSliceUint8(sliceIndex, axis)), { stride: volume.getChannels() })), outline);
109934
+ paintContours(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, (lbl) => volume.getChannelColor(lbl), this.state.gui_states.layerChannel.channelVisibility[layer]);
109874
109935
  }
109875
109936
  catch (_a) {
109876
109937
  // Slice out of bounds or volume not ready — skip silently
@@ -109910,7 +109971,7 @@ void main() {
109910
109971
  * Only draws layers whose visibility is enabled.
109911
109972
  */
109912
109973
  compositeAllLayers() {
109913
- var _a, _b;
109974
+ var _a, _b, _c, _d;
109914
109975
  const masterCtx = this.state.protectedData.ctxes.drawingLayerMasterCtx;
109915
109976
  const width = this.state.nrrd_states.view.changedWidth;
109916
109977
  const height = this.state.nrrd_states.view.changedHeight;
@@ -109927,6 +109988,8 @@ void main() {
109927
109988
  masterCtx.restore();
109928
109989
  }
109929
109990
  }
109991
+ (_c = this.mirror) === null || _c === void 0 ? void 0 : _c.paint(masterCtx, width, height);
109992
+ (_d = this.onComposited) === null || _d === void 0 ? void 0 : _d.call(this);
109930
109993
  }
109931
109994
  }
109932
109995
 
@@ -115127,6 +115190,14 @@ void main() {
115127
115190
  if (this.ctx.gui_states.mode.sphere) {
115128
115191
  return;
115129
115192
  }
115193
+ // A mirroring viewer has no layers of its own; its mirror paints in the composite.
115194
+ if (this.callbacks.hasMaskMirror()) {
115195
+ this.callbacks.compositeAllLayers();
115196
+ return;
115197
+ }
115198
+ // A read-only viewer has no layers and nothing to reload.
115199
+ if (this.ctx.nrrd_states.image.layers.length === 0)
115200
+ return;
115130
115201
  const axis = this.ctx.protectedData.axis;
115131
115202
  let sliceIndex = this.ctx.nrrd_states.view.currentSliceIndex;
115132
115203
  // Clamp sliceIndex to valid range for current axis
@@ -115360,6 +115431,170 @@ void main() {
115360
115431
  }
115361
115432
  }
115362
115433
 
115434
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
115435
+ /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
115436
+ function sliceDims(dims, axis) {
115437
+ const [w, h, d] = [dims[0], dims[1], dims[2]];
115438
+ return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [d, h];
115439
+ }
115440
+ /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
115441
+ function isIdentity(m, tol = 1e-9) {
115442
+ if (!m)
115443
+ return true;
115444
+ for (let i = 0; i < 16; i++) {
115445
+ if (Math.abs(m[i] - IDENTITY[i]) > tol)
115446
+ return false;
115447
+ }
115448
+ return true;
115449
+ }
115450
+ /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
115451
+ function isDiagonal(m, tol = 1e-9) {
115452
+ for (const i of [1, 2, 4, 6, 8, 9]) {
115453
+ if (Math.abs(m[i]) > tol)
115454
+ return false;
115455
+ }
115456
+ return true;
115457
+ }
115458
+ /**
115459
+ * For each mirror index along one axis, the inclusive source index range it covers, clamped
115460
+ * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
115461
+ * source voxel covers the one nearest its centre; a larger one covers every source voxel
115462
+ * whose centre lies within it.
115463
+ */
115464
+ function coveredRanges(s, t, count, extent) {
115465
+ const lo = new Int32Array(count);
115466
+ const hi = new Int32Array(count);
115467
+ const half = Math.abs(s) / 2;
115468
+ for (let i = 0; i < count; i++) {
115469
+ const c = s * i + t;
115470
+ let a, b;
115471
+ if (Math.abs(s) <= 1) {
115472
+ a = b = Math.round(c);
115473
+ }
115474
+ else {
115475
+ a = Math.ceil(c - half - 1e-9);
115476
+ b = Math.floor(c + half - 1e-9);
115477
+ }
115478
+ lo[i] = Math.max(a, 0);
115479
+ hi[i] = Math.min(b, extent - 1);
115480
+ }
115481
+ return { lo, hi };
115482
+ }
115483
+ /**
115484
+ * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
115485
+ * the source is 0. On the same grid with the identity, it is the source's own slice.
115486
+ *
115487
+ * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
115488
+ * coarser than the source shows the first label found among every source voxel it spans, so
115489
+ * a finding thinner than the mirror's slice still appears on the slice that contains it.
115490
+ * Any other transform samples the nearest source voxel.
115491
+ */
115492
+ function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
115493
+ const sd = source.getDimensions();
115494
+ if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
115495
+ const s = source.getSliceUint8(index, axis);
115496
+ return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
115497
+ }
115498
+ const mat = m !== null && m !== void 0 ? m : IDENTITY;
115499
+ const [W, H] = sliceDims(mirrorDims, axis);
115500
+ const raw = source.getRawData();
115501
+ const nch = source.getChannels();
115502
+ const out = new Uint8Array(W * H);
115503
+ if (isDiagonal(mat)) {
115504
+ const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
115505
+ const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
115506
+ const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
115507
+ for (let v = 0; v < H; v++) {
115508
+ for (let u = 0; u < W; u++) {
115509
+ const x = axis === "x" ? index : u;
115510
+ const y = axis === "y" ? index : v;
115511
+ const z = axis === "z" ? index : axis === "y" ? v : u;
115512
+ let label = 0;
115513
+ for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
115514
+ for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
115515
+ for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
115516
+ label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
115517
+ }
115518
+ }
115519
+ }
115520
+ out[v * W + u] = label;
115521
+ }
115522
+ }
115523
+ return { data: out, width: W, height: H, stride: 1 };
115524
+ }
115525
+ for (let v = 0; v < H; v++) {
115526
+ for (let u = 0; u < W; u++) {
115527
+ // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
115528
+ const x = axis === "x" ? index : u;
115529
+ const y = axis === "y" ? index : v;
115530
+ const z = axis === "z" ? index : axis === "y" ? v : u;
115531
+ const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
115532
+ const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
115533
+ const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
115534
+ if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
115535
+ continue;
115536
+ out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
115537
+ }
115538
+ }
115539
+ return { data: out, width: W, height: H, stride: 1 };
115540
+ }
115541
+ /**
115542
+ * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
115543
+ * volumes and display state. A new transform means a new instance, so the cache never holds
115544
+ * contours from another transform.
115545
+ */
115546
+ class MaskMirror {
115547
+ constructor(self, source, matrix) {
115548
+ this.self = self;
115549
+ this.source = source;
115550
+ this.matrix = matrix;
115551
+ /** One contour entry per source layer, for the slice last painted. */
115552
+ this.cache = new Map();
115553
+ /** The source volume each cache entry was built from; a case load replaces the object. */
115554
+ this.cachedVolumes = new Map();
115555
+ }
115556
+ /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
115557
+ paint(ctx, width, height) {
115558
+ var _a, _b;
115559
+ // The source hides its own layers in sphere mode, so the mirror shows none either.
115560
+ if (this.source.gui_states.mode.sphere)
115561
+ return;
115562
+ const dims = this.self.nrrd_states.image.dimensions;
115563
+ if (!dims || dims.length !== 3)
115564
+ return;
115565
+ const axis = this.self.protectedData.axis;
115566
+ const index = this.self.nrrd_states.view.currentSliceIndex;
115567
+ const lc = this.source.gui_states.layerChannel;
115568
+ const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
115569
+ for (const layerId of this.source.nrrd_states.image.layers) {
115570
+ if (!lc.layerVisibility[layerId])
115571
+ continue;
115572
+ const volume = this.source.protectedData.maskData.volumes[layerId];
115573
+ if (!volume)
115574
+ continue;
115575
+ if (this.cachedVolumes.get(layerId) !== volume) {
115576
+ this.cache.delete(layerId);
115577
+ this.cachedVolumes.set(layerId, volume);
115578
+ }
115579
+ try {
115580
+ const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
115581
+ ctx.save();
115582
+ try {
115583
+ ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
115584
+ paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
115585
+ }
115586
+ finally {
115587
+ // A throw must not leave this layer's alpha or transform on the master canvas.
115588
+ ctx.restore();
115589
+ }
115590
+ }
115591
+ catch (_c) {
115592
+ // The source is not ready for this slice: nothing to draw for this layer.
115593
+ }
115594
+ }
115595
+ }
115596
+ }
115597
+
115363
115598
  /**
115364
115599
  * NrrdTools.setMasksFromNIfTI forwards its `Map<string, Uint8Array>` argument
115365
115600
  * straight through to here with no second channel for metadata, so a caller that
@@ -115641,7 +115876,15 @@ void main() {
115641
115876
  // ═══════════════════════════════════════════════════════════════════════════
115642
115877
  constructor(container, options) {
115643
115878
  this._sliceRAFId = null;
115879
+ /** Viewers drawing this one's masks (see setMaskMirror). */
115880
+ this._mirrors = new Set();
115881
+ /** The viewer whose masks this one draws, if any. */
115882
+ this._mirrorSource = null;
115883
+ /** The pending frame that refreshes this viewer's mirrors. */
115884
+ this._mirrorFrame = null;
115644
115885
  this._pendingSliceStep = 0;
115886
+ /** Receives slice moves while a preview slice is shown; null when none is. */
115887
+ this._previewSliceMove = null;
115645
115888
  /** Whether calculator mode is active (not part of gui_states interface) */
115646
115889
  this._calculatorActive = false;
115647
115890
  /**
@@ -115674,6 +115917,8 @@ void main() {
115674
115917
  this.drawCore = new DrawToolCore(container, this.state);
115675
115918
  // Wire DrawToolCore's overridable methods to NrrdTools implementations
115676
115919
  this.wireDrawCoreMethods();
115920
+ // Every visible mask change ends in a composite; the viewers mirroring this one follow it.
115921
+ this.drawCore.renderer.onComposited = () => this.scheduleMirrorRefresh();
115677
115922
  // Wire RenderingUtils' setEmptyCanvasSize callback
115678
115923
  this.drawCore.renderer.setEmptyCanvasSize = (axis) => this.setEmptyCanvasSize(axis);
115679
115924
  this.init();
@@ -115684,6 +115929,7 @@ void main() {
115684
115929
  }
115685
115930
  // Wire sphere overlay refresh callback into DragOperator → DragSliceTool
115686
115931
  this.dragOperator.setRefreshSphereOverlay(() => this.refreshSphereOverlay());
115932
+ this.dragOperator.setPreviewSliceMove((index) => this.previewSliceMove(index));
115687
115933
  // Initialize extracted modules
115688
115934
  this.initNrrdToolsModules();
115689
115935
  }
@@ -115731,6 +115977,7 @@ void main() {
115731
115977
  });
115732
115978
  this.sliceRenderPipeline = new SliceRenderPipeline(toolCtx, {
115733
115979
  compositeAllLayers: () => this.drawCore.renderer.compositeAllLayers(),
115980
+ hasMaskMirror: () => this._mirrorSource !== null,
115734
115981
  getOrCreateSliceBuffer: (axis) => this.drawCore.renderer.getOrCreateSliceBuffer(axis),
115735
115982
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, targetCtx, w, h) => this.drawCore.renderer.renderSliceToCanvas(layer, axis, sliceIndex, buffer, targetCtx, w, h),
115736
115983
  getVolumeForLayer: (layer) => this.drawCore.renderer.getVolumeForLayer(layer),
@@ -116499,10 +116746,49 @@ void main() {
116499
116746
  * Used for register/origin image switching where the view state should persist.
116500
116747
  */
116501
116748
  switchSlicesPreservingView(allSlices) {
116749
+ this._previewSliceMove = null;
116502
116750
  this.state.protectedData.allSlicesArray.length = 0;
116503
116751
  this.state.protectedData.allSlicesArray = [...allSlices];
116504
116752
  this.sliceRenderPipeline.switchPreservingView();
116505
116753
  }
116754
+ /**
116755
+ * Show one slice of a volume before the volume itself has loaded: `header` is the full
116756
+ * volume's geometry, `slice` a depth-1 slice triple of plane `index` (built from one plane's
116757
+ * voxels), shown as slice `index` of the full stack. Geometry is re-initialised only when it
116758
+ * differs from the current one. Replaces whatever slice data is displayed; writes no mask.
116759
+ * The full volume later replaces it with `switchSlicesPreservingView`, keeping `index`.
116760
+ *
116761
+ * Until then every slice move (wheel, keys, drag, `setSliceMoving`) goes to `onSliceMove`
116762
+ * with its clamped target index instead of moving the displayed slice. Axial only; it does
116763
+ * not switch orientation.
116764
+ */
116765
+ showPreviewSlice(header, slice, index, onSliceMove) {
116766
+ const image = this.state.nrrd_states.image;
116767
+ const same = (a, b) => !!a && a.length === b.length && Array.from(b).every((v, i) => a[i] === v);
116768
+ if (!same(image.dimensions, header.dimensions) ||
116769
+ !same(image.voxelSpacing, header.spacing) ||
116770
+ !same(image.spaceOrigin, header.space_origin)) {
116771
+ this.dataLoader.initFromHeader(header);
116772
+ }
116773
+ slice.z.initIndex = index;
116774
+ this.state.protectedData.allSlicesArray.length = 0;
116775
+ // Take the index from `initIndex` rather than writing the full-stack index into the
116776
+ // depth-1 slice's own `index`, which would be out of range for it.
116777
+ this.sliceRenderPipeline.resetInitState();
116778
+ this.dataLoader.appendSlice(slice, 0);
116779
+ this._previewSliceMove = onSliceMove;
116780
+ }
116781
+ /** Whether a preview slice from `showPreviewSlice` is shown in place of a loaded volume. */
116782
+ isPreviewing() {
116783
+ return this._previewSliceMove !== null;
116784
+ }
116785
+ /** Hands a slice move to the preview's host; false when no preview is shown. */
116786
+ previewSliceMove(index) {
116787
+ if (!this._previewSliceMove)
116788
+ return false;
116789
+ this._previewSliceMove(index);
116790
+ return true;
116791
+ }
116506
116792
  appendLoadingbar(loadingbar) {
116507
116793
  this.state.protectedData.mainAreaContainer.appendChild(loadingbar);
116508
116794
  }
@@ -116614,7 +116900,10 @@ void main() {
116614
116900
  // ═══════════════════════════════════════════════════════════════════════════
116615
116901
  // 9. Delegated — DataLoader
116616
116902
  // ═══════════════════════════════════════════════════════════════════════════
116617
- setAllSlices(allSlices) { this.dataLoader.setAllSlices(allSlices); }
116903
+ setAllSlices(allSlices) {
116904
+ this._previewSliceMove = null;
116905
+ this.dataLoader.setAllSlices(allSlices);
116906
+ }
116618
116907
  setMasksData(masksData, loadingBar) { this.dataLoader.setMasksData(masksData, loadingBar); }
116619
116908
  setMasksFromNIfTI(layerVoxels, loadingBar) { this.dataLoader.setMasksFromNIfTI(layerVoxels, loadingBar); }
116620
116909
  // ═══════════════════════════════════════════════════════════════════════════
@@ -116880,6 +117169,7 @@ void main() {
116880
117169
  this.reloadMasksFromVolume();
116881
117170
  }
116882
117171
  reset() {
117172
+ this._previewSliceMove = null;
116883
117173
  this.state.protectedData.allSlicesArray.length = 0;
116884
117174
  this.state.protectedData.displaySlices.length = 0;
116885
117175
  this.drawCore.undoManager.clearAll();
@@ -116911,10 +117201,41 @@ void main() {
116911
117201
  this.state.nrrd_states.sphere.skinSphereOrigin = null;
116912
117202
  this.state.nrrd_states.sphere.nippleSphereOrigin = null;
116913
117203
  }
117204
+ /**
117205
+ * Draw `source`'s masks on this viewer, read live from it: its volumes, colours, channel and
117206
+ * layer visibility, opacity and render mode. `mirrorToSource` is a row-major 4×4 from this
117207
+ * viewer's voxel (x, y, z, 1) to the source's voxel; omitted means the identity. `null`
117208
+ * detaches. Display only — nothing is written to either viewer's masks.
117209
+ */
117210
+ setMaskMirror(source, mirrorToSource) {
117211
+ var _a, _b;
117212
+ (_a = this._mirrorSource) === null || _a === void 0 ? void 0 : _a._mirrors.delete(this);
117213
+ this._mirrorSource = source && source !== this ? source : null;
117214
+ this.drawCore.renderer.mirror = this._mirrorSource
117215
+ ? new MaskMirror(this.state, this._mirrorSource.state, mirrorToSource !== null && mirrorToSource !== void 0 ? mirrorToSource : null)
117216
+ : null;
117217
+ (_b = this._mirrorSource) === null || _b === void 0 ? void 0 : _b._mirrors.add(this);
117218
+ this.drawCore.renderer.compositeAllLayers();
117219
+ }
117220
+ /** The viewer whose masks this one draws, or null. */
117221
+ getMaskMirrorSource() {
117222
+ return this._mirrorSource;
117223
+ }
117224
+ /** Repaint every mirror of this viewer on the next frame; repeated calls coalesce. */
117225
+ scheduleMirrorRefresh() {
117226
+ if (this._mirrors.size === 0 || this._mirrorFrame !== null)
117227
+ return;
117228
+ this._mirrorFrame = requestAnimationFrame(() => {
117229
+ this._mirrorFrame = null;
117230
+ for (const m of this._mirrors)
117231
+ m.drawCore.renderer.compositeAllLayers();
117232
+ });
117233
+ }
116914
117234
  /**
116915
117235
  * Releases what this instance holds outside its own DOM subtree, so a viewer that is torn
116916
117236
  * down can be garbage-collected: the event router's listeners (its window `blur` listener
116917
- * reaches the whole engine graph), a pending slice step and the drawing-flag timer.
117237
+ * reaches the whole engine graph), a pending slice step, the drawing-flag timer and any
117238
+ * mask-mirror link.
116918
117239
  *
116919
117240
  * The instance must not be used afterwards. Safe to call more than once.
116920
117241
  */
@@ -116930,6 +117251,22 @@ void main() {
116930
117251
  window.clearTimeout(this.preTimer);
116931
117252
  this.preTimer = undefined;
116932
117253
  }
117254
+ // Release the mirror link from both ends, so neither viewer keeps the other alive.
117255
+ if (this._mirrorSource) {
117256
+ this._mirrorSource._mirrors.delete(this);
117257
+ this._mirrorSource = null;
117258
+ this.drawCore.renderer.mirror = null;
117259
+ }
117260
+ for (const m of this._mirrors) {
117261
+ m._mirrorSource = null;
117262
+ m.drawCore.renderer.mirror = null;
117263
+ m.drawCore.renderer.compositeAllLayers();
117264
+ }
117265
+ this._mirrors.clear();
117266
+ if (this._mirrorFrame !== null) {
117267
+ cancelAnimationFrame(this._mirrorFrame);
117268
+ this._mirrorFrame = null;
117269
+ }
116933
117270
  }
116934
117271
  // ═══════════════════════════════════════════════════════════════════════════
116935
117272
  // 12. Internal — Input Events
@@ -118234,15 +118571,15 @@ void main() {
118234
118571
  }
118235
118572
 
118236
118573
  // import * as kiwrious from "copper3d_plugin_heart_k";
118237
- // "v3.11.4" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118574
+ // "v3.11.6" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118238
118575
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
118239
118576
  // referencing it throws a ReferenceError — guard it so local loading still works.
118240
118577
  let _revision = "unknown";
118241
118578
  try {
118242
- _revision = "v3.11.4";
118579
+ _revision = "v3.11.6";
118243
118580
  }
118244
118581
  catch (_a) {
118245
- /* "v3.11.4" not injected (local source build) */
118582
+ /* "v3.11.6" not injected (local source build) */
118246
118583
  }
118247
118584
  const REVISION = _revision;
118248
118585
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__
@@ -118308,6 +118645,7 @@ void main() {
118308
118645
  exports.orbitStepPose = orbitStepPose;
118309
118646
  exports.orbitSwingAngle = orbitSwingAngle;
118310
118647
  exports.poseDistance = poseDistance;
118648
+ exports.prepareVolumeSlices = prepareVolumeSlices;
118311
118649
  exports.registerNiftiMaskGrid = registerNiftiMaskGrid;
118312
118650
  exports.removeGuiFolderChilden = removeGuiFolderChilden;
118313
118651
  exports.removeSceneFromMap = removeSceneFromMap;