copper3d 3.11.4 → 3.11.5

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 (34) hide show
  1. package/README.md +45 -1
  2. package/ai-index/guides/nrrd-tools.md +100 -2
  3. package/ai-index/guides/segmentation-module.md +108 -2
  4. package/ai-index/manifest.json +5 -5
  5. package/ai-index/symbols.json +1 -1
  6. package/dist/Utils/segmentation/DragOperator.d.ts +6 -0
  7. package/dist/Utils/segmentation/DragOperator.js +9 -0
  8. package/dist/Utils/segmentation/DragOperator.js.map +1 -1
  9. package/dist/Utils/segmentation/NrrdTools.d.ts +38 -1
  10. package/dist/Utils/segmentation/NrrdTools.js +105 -2
  11. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  12. package/dist/Utils/segmentation/RenderingUtils.d.ts +5 -9
  13. package/dist/Utils/segmentation/RenderingUtils.js +10 -116
  14. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  15. package/dist/Utils/segmentation/contourPaint.d.ts +37 -0
  16. package/dist/Utils/segmentation/contourPaint.js +128 -0
  17. package/dist/Utils/segmentation/contourPaint.js.map +1 -0
  18. package/dist/Utils/segmentation/tools/DragSliceTool.js +5 -0
  19. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  20. package/dist/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  21. package/dist/Utils/segmentation/tools/MaskMirror.js +165 -0
  22. package/dist/Utils/segmentation/tools/MaskMirror.js.map +1 -0
  23. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js +5 -0
  24. package/dist/Utils/segmentation/tools/SliceRenderPipeline.js.map +1 -1
  25. package/dist/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  26. package/dist/bundle.esm.js +418 -112
  27. package/dist/bundle.umd.js +418 -112
  28. package/dist/types/Utils/segmentation/DragOperator.d.ts +6 -0
  29. package/dist/types/Utils/segmentation/NrrdTools.d.ts +38 -1
  30. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +5 -9
  31. package/dist/types/Utils/segmentation/contourPaint.d.ts +37 -0
  32. package/dist/types/Utils/segmentation/tools/MaskMirror.d.ts +42 -0
  33. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +10 -2
  34. package/package.json +1 -1
@@ -109313,6 +109313,11 @@ class DragSliceTool extends BaseTool {
109313
109313
  }
109314
109314
  let newIndex = view.currentSliceIndex + sliceModifyNum;
109315
109315
  if (newIndex != view.currentSliceIndex || view.showContrast) {
109316
+ // While a preview slice is shown the displayed slice has depth 1, so moving it would
109317
+ // paint blank; the host fetches the target slice instead.
109318
+ const target = Math.min(Math.max(newIndex, view.minIndex), view.maxIndex);
109319
+ if (this.callbacks.previewSliceMove(target))
109320
+ return;
109316
109321
  if (newIndex > view.maxIndex) {
109317
109322
  newIndex = view.maxIndex;
109318
109323
  view.contrastNum = this.ctx.protectedData.displaySlices.length - 1;
@@ -109441,6 +109446,7 @@ class DragOperator {
109441
109446
  };
109442
109447
  this.sensitiveArray = [];
109443
109448
  this.refreshSphereOverlayCb = null;
109449
+ this.previewSliceMoveCb = () => false;
109444
109450
  // EventRouter for centralized event handling
109445
109451
  this.eventRouter = null;
109446
109452
  this.configDragMode = () => {
@@ -109498,6 +109504,7 @@ class DragOperator {
109498
109504
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, targetCtx, w, h) => this.renderSliceToCanvas(layer, axis, sliceIndex, buffer, targetCtx, w, h),
109499
109505
  compositeAllLayers: () => this.compositeAllLayers(),
109500
109506
  refreshSphereOverlay: () => { var _a; return (_a = this.refreshSphereOverlayCb) === null || _a === void 0 ? void 0 : _a.call(this); },
109507
+ previewSliceMove: (index) => this.previewSliceMoveCb(index),
109501
109508
  }, this.showDragNumberDiv, dragEffectCanvases);
109502
109509
  }
109503
109510
  setShowDragNumberDiv(sliceIndexContainer) {
@@ -109511,6 +109518,13 @@ class DragOperator {
109511
109518
  setRefreshSphereOverlay(cb) {
109512
109519
  this.refreshSphereOverlayCb = cb;
109513
109520
  }
109521
+ /**
109522
+ * Set the callback that may consume a slice move while a preview slice is shown.
109523
+ * Called by NrrdTools; until then every move proceeds normally.
109524
+ */
109525
+ setPreviewSliceMove(cb) {
109526
+ this.previewSliceMoveCb = cb;
109527
+ }
109514
109528
  /**
109515
109529
  * Set the EventRouter reference for centralized event handling.
109516
109530
  * Called by NrrdTools/DrawToolCore after EventRouter is initialized.
@@ -109597,6 +109611,125 @@ class DragOperator {
109597
109611
  * stay visible against bright tissue.
109598
109612
  */
109599
109613
  const OUTLINE_WIDTH_PX = 1.5;
109614
+ /**
109615
+ * Populate one cache entry's paths for one render mode.
109616
+ *
109617
+ * Split out because the two modes are built at different times: whichever is in use when
109618
+ * a slice is first drawn, and the other one only if the clinician switches while still on
109619
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
109620
+ * sessions never turn on.
109621
+ */
109622
+ function buildPaths(entry, data, stride, outline) {
109623
+ const target = outline ? entry.outlines : entry.fills;
109624
+ for (const lbl of entry.labels) {
109625
+ target.set(lbl, outline
109626
+ ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109627
+ : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109628
+ }
109629
+ }
109630
+ /**
109631
+ * The cached contours for `slot` under `key`, extracting on a miss. One entry per slot: a new
109632
+ * key overwrites it. `readSlice` is called only when extraction is needed.
109633
+ */
109634
+ function contourEntry(cache, slot, key, readSlice, outline) {
109635
+ // Cache miss → run the expensive extraction once. Hits (zoom,
109636
+ // recomposite, contrast toggle) skip straight to the draw.
109637
+ let entry = cache.get(slot);
109638
+ if (!entry || entry.key !== key) {
109639
+ const slice = readSlice();
109640
+ entry = {
109641
+ key,
109642
+ W: slice.width,
109643
+ H: slice.height,
109644
+ labels: findLabelsInSlice(slice.data, slice.width, slice.height, slice.stride, 0),
109645
+ fills: new Map(),
109646
+ outlines: new Map(),
109647
+ };
109648
+ cache.set(slot, entry);
109649
+ buildPaths(entry, slice.data, slice.stride, outline);
109650
+ }
109651
+ else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109652
+ // The mode changed since this slice was last drawn, so the other set of
109653
+ // paths is cached and this one is not. Re-read the slice and build it; from
109654
+ // here on both are present and toggling is a pure cache hit.
109655
+ const slice = readSlice();
109656
+ buildPaths(entry, slice.data, slice.stride, outline);
109657
+ }
109658
+ return entry;
109659
+ }
109660
+ /** Paint an entry's visible labels onto `targetCtx`, scaled from voxels to `scaledWidth × scaledHeight`. */
109661
+ function paintContours(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis) {
109662
+ if (entry.labels.length === 0)
109663
+ return;
109664
+ targetCtx.save();
109665
+ // A throw (a missing colour, say) must not leave the transform on the target.
109666
+ try {
109667
+ drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis);
109668
+ }
109669
+ finally {
109670
+ targetCtx.restore();
109671
+ }
109672
+ }
109673
+ function drawPaths(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, colorOf, channelVis) {
109674
+ const { W, H, labels } = entry;
109675
+ const paths = outline ? entry.outlines : entry.fills;
109676
+ // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109677
+ // it off to match the rest of the pipeline.
109678
+ targetCtx.imageSmoothingEnabled = false;
109679
+ if (outline) {
109680
+ // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109681
+ // in the path instead. `lineWidth` is then measured in screen pixels, which
109682
+ // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109683
+ // thickens the line with the zoom, exactly when the clinician has magnified
109684
+ // the image to look at the boundary — and because voxels are rarely isotropic
109685
+ // (sx !== sy), it also comes out thicker in one axis than the other.
109686
+ const matrix = new DOMMatrix();
109687
+ if (axis === "y") {
109688
+ matrix.scaleSelf(1, -1);
109689
+ matrix.translateSelf(0, -scaledHeight);
109690
+ }
109691
+ matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109692
+ targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109693
+ // Segments are emitted per cell and meet at shared endpoints; round caps
109694
+ // close those joins. Canvas composites a whole Path2D in one pass, so the
109695
+ // overlap costs no doubled alpha.
109696
+ targetCtx.lineJoin = "round";
109697
+ targetCtx.lineCap = "round";
109698
+ for (const lbl of labels) {
109699
+ if (channelVis && channelVis[lbl] === false)
109700
+ continue;
109701
+ const path = paths.get(lbl);
109702
+ if (!path)
109703
+ continue;
109704
+ const color = colorOf(lbl);
109705
+ targetCtx.strokeStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109706
+ const display = new Path2D();
109707
+ display.addPath(path, matrix);
109708
+ targetCtx.stroke(display);
109709
+ }
109710
+ return;
109711
+ }
109712
+ // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109713
+ // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109714
+ // so the flip operates in display coordinates.
109715
+ if (axis === "y") {
109716
+ targetCtx.scale(1, -1);
109717
+ targetCtx.translate(0, -scaledHeight);
109718
+ }
109719
+ // Voxel coord (x ∈ [0, W], y ∈ [0, H]) → display coord.
109720
+ targetCtx.scale(scaledWidth / W, scaledHeight / H);
109721
+ for (const lbl of labels) {
109722
+ if (channelVis && channelVis[lbl] === false)
109723
+ continue;
109724
+ const path = paths.get(lbl);
109725
+ if (!path)
109726
+ continue;
109727
+ const color = colorOf(lbl);
109728
+ targetCtx.fillStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109729
+ targetCtx.fill(path, "nonzero");
109730
+ }
109731
+ }
109732
+
109600
109733
  /**
109601
109734
  * RenderingUtils — Rendering / slice-buffer helper methods.
109602
109735
  *
@@ -109611,6 +109744,10 @@ class RenderingUtils {
109611
109744
  constructor(state) {
109612
109745
  /** Injected callback — set by owner after construction. */
109613
109746
  this.setEmptyCanvasSize = () => { };
109747
+ /** Set while this viewer draws another viewer's masks; painted after this viewer's own layers. */
109748
+ this.mirror = null;
109749
+ /** Called after every composite. The owner refreshes the viewers mirroring this one. */
109750
+ this.onComposited = null;
109614
109751
  // Reusable ImageData buffer for zero-allocation slice rendering
109615
109752
  this._reusableSliceBuffer = null;
109616
109753
  this._reusableBufferWidth = 0;
@@ -109720,22 +109857,6 @@ class RenderingUtils {
109720
109857
  return null; // Volume not ready
109721
109858
  }
109722
109859
  }
109723
- /**
109724
- * Populate one cache entry's paths for one render mode.
109725
- *
109726
- * Split out because the two modes are built at different times: whichever is in use when
109727
- * a slice is first drawn, and the other one only if the clinician switches while still on
109728
- * that slice. Building both eagerly would make every slice scrub pay for a mode most
109729
- * sessions never turn on.
109730
- */
109731
- buildPaths(entry, data, stride, outline) {
109732
- const target = outline ? entry.outlines : entry.fills;
109733
- for (const lbl of entry.labels) {
109734
- target.set(lbl, outline
109735
- ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109736
- : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109737
- }
109738
- }
109739
109860
  /**
109740
109861
  * Render a layer's slice onto the target canvas as vector contours.
109741
109862
  *
@@ -109773,96 +109894,8 @@ class RenderingUtils {
109773
109894
  const volume = this.getVolumeForLayer(layer);
109774
109895
  if (!volume)
109775
109896
  return;
109776
- const stride = volume.getChannels();
109777
- const cacheKey = `${axis}:${sliceIndex}:${volume.getVersion()}`;
109778
- // Cache miss → run the expensive extraction once. Hits (zoom,
109779
- // recomposite, contrast toggle) skip straight to the draw below.
109780
- let entry = this._contourCache.get(layer);
109781
- if (!entry || entry.key !== cacheKey) {
109782
- const slice = volume.getSliceUint8(sliceIndex, axis);
109783
- entry = {
109784
- key: cacheKey,
109785
- W: slice.width,
109786
- H: slice.height,
109787
- labels: findLabelsInSlice(slice.data, slice.width, slice.height, stride, 0),
109788
- fills: new Map(),
109789
- outlines: new Map(),
109790
- };
109791
- this._contourCache.set(layer, entry);
109792
- this.buildPaths(entry, slice.data, stride, outline);
109793
- }
109794
- else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109795
- // The mode changed since this slice was last drawn, so the other set of
109796
- // paths is cached and this one is not. Re-read the slice and build it; from
109797
- // here on both are present and toggling is a pure cache hit.
109798
- const slice = volume.getSliceUint8(sliceIndex, axis);
109799
- this.buildPaths(entry, slice.data, stride, outline);
109800
- }
109801
- if (entry.labels.length === 0)
109802
- return;
109803
- const { W, H, labels } = entry;
109804
- const paths = outline ? entry.outlines : entry.fills;
109805
- const channelVis = this.state.gui_states.layerChannel.channelVisibility[layer];
109806
- targetCtx.save();
109807
- // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109808
- // it off to match the rest of the pipeline.
109809
- targetCtx.imageSmoothingEnabled = false;
109810
- if (outline) {
109811
- // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109812
- // in the path instead. `lineWidth` is then measured in screen pixels, which
109813
- // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109814
- // thickens the line with the zoom, exactly when the clinician has magnified
109815
- // the image to look at the boundary — and because voxels are rarely isotropic
109816
- // (sx !== sy), it also comes out thicker in one axis than the other.
109817
- const matrix = new DOMMatrix();
109818
- if (axis === 'y') {
109819
- matrix.scaleSelf(1, -1);
109820
- matrix.translateSelf(0, -scaledHeight);
109821
- }
109822
- matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109823
- targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109824
- // Segments are emitted per cell and meet at shared endpoints; round caps
109825
- // close those joins. Canvas composites a whole Path2D in one pass, so the
109826
- // overlap costs no doubled alpha.
109827
- targetCtx.lineJoin = 'round';
109828
- targetCtx.lineCap = 'round';
109829
- for (const lbl of labels) {
109830
- if (channelVis && channelVis[lbl] === false)
109831
- continue;
109832
- const path = paths.get(lbl);
109833
- if (!path)
109834
- continue;
109835
- const color = volume.getChannelColor(lbl);
109836
- targetCtx.strokeStyle =
109837
- `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109838
- const display = new Path2D();
109839
- display.addPath(path, matrix);
109840
- targetCtx.stroke(display);
109841
- }
109842
- targetCtx.restore();
109843
- return;
109844
- }
109845
- // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109846
- // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109847
- // so the flip operates in display coordinates.
109848
- if (axis === 'y') {
109849
- targetCtx.scale(1, -1);
109850
- targetCtx.translate(0, -scaledHeight);
109851
- }
109852
- // Voxel coord (x ∈ [0, W], y ∈ [0, H]) → display coord.
109853
- targetCtx.scale(scaledWidth / W, scaledHeight / H);
109854
- for (const lbl of labels) {
109855
- if (channelVis && channelVis[lbl] === false)
109856
- continue;
109857
- const path = paths.get(lbl);
109858
- if (!path)
109859
- continue;
109860
- const color = volume.getChannelColor(lbl);
109861
- targetCtx.fillStyle =
109862
- `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109863
- targetCtx.fill(path, 'nonzero');
109864
- }
109865
- targetCtx.restore();
109897
+ const entry = contourEntry(this._contourCache, layer, `${axis}:${sliceIndex}:${volume.getVersion()}`, () => (Object.assign(Object.assign({}, volume.getSliceUint8(sliceIndex, axis)), { stride: volume.getChannels() })), outline);
109898
+ paintContours(entry, targetCtx, axis, scaledWidth, scaledHeight, outline, (lbl) => volume.getChannelColor(lbl), this.state.gui_states.layerChannel.channelVisibility[layer]);
109866
109899
  }
109867
109900
  catch (_a) {
109868
109901
  // Slice out of bounds or volume not ready — skip silently
@@ -109902,7 +109935,7 @@ class RenderingUtils {
109902
109935
  * Only draws layers whose visibility is enabled.
109903
109936
  */
109904
109937
  compositeAllLayers() {
109905
- var _a, _b;
109938
+ var _a, _b, _c, _d;
109906
109939
  const masterCtx = this.state.protectedData.ctxes.drawingLayerMasterCtx;
109907
109940
  const width = this.state.nrrd_states.view.changedWidth;
109908
109941
  const height = this.state.nrrd_states.view.changedHeight;
@@ -109919,6 +109952,8 @@ class RenderingUtils {
109919
109952
  masterCtx.restore();
109920
109953
  }
109921
109954
  }
109955
+ (_c = this.mirror) === null || _c === void 0 ? void 0 : _c.paint(masterCtx, width, height);
109956
+ (_d = this.onComposited) === null || _d === void 0 ? void 0 : _d.call(this);
109922
109957
  }
109923
109958
  }
109924
109959
 
@@ -115119,6 +115154,11 @@ class SliceRenderPipeline extends BaseTool {
115119
115154
  if (this.ctx.gui_states.mode.sphere) {
115120
115155
  return;
115121
115156
  }
115157
+ // A mirroring viewer has no layers of its own; its mirror paints in the composite.
115158
+ if (this.callbacks.hasMaskMirror()) {
115159
+ this.callbacks.compositeAllLayers();
115160
+ return;
115161
+ }
115122
115162
  const axis = this.ctx.protectedData.axis;
115123
115163
  let sliceIndex = this.ctx.nrrd_states.view.currentSliceIndex;
115124
115164
  // Clamp sliceIndex to valid range for current axis
@@ -115352,6 +115392,170 @@ class SliceRenderPipeline extends BaseTool {
115352
115392
  }
115353
115393
  }
115354
115394
 
115395
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
115396
+ /** A slice's width and height for `axis`, as `getSliceUint8` lays it out. */
115397
+ function sliceDims(dims, axis) {
115398
+ const [w, h, d] = [dims[0], dims[1], dims[2]];
115399
+ return axis === "z" ? [w, h] : axis === "y" ? [w, d] : [d, h];
115400
+ }
115401
+ /** Whether `m` is the identity within `tol`. No matrix counts as the identity. */
115402
+ function isIdentity(m, tol = 1e-9) {
115403
+ if (!m)
115404
+ return true;
115405
+ for (let i = 0; i < 16; i++) {
115406
+ if (Math.abs(m[i] - IDENTITY[i]) > tol)
115407
+ return false;
115408
+ }
115409
+ return true;
115410
+ }
115411
+ /** Whether the 3×3 part of a row-major 4×4 is diagonal: each axis maps onto its own axis. */
115412
+ function isDiagonal(m, tol = 1e-9) {
115413
+ for (const i of [1, 2, 4, 6, 8, 9]) {
115414
+ if (Math.abs(m[i]) > tol)
115415
+ return false;
115416
+ }
115417
+ return true;
115418
+ }
115419
+ /**
115420
+ * For each mirror index along one axis, the inclusive source index range it covers, clamped
115421
+ * to the source's extent; `lo > hi` when it covers none. A mirror voxel no larger than a
115422
+ * source voxel covers the one nearest its centre; a larger one covers every source voxel
115423
+ * whose centre lies within it.
115424
+ */
115425
+ function coveredRanges(s, t, count, extent) {
115426
+ const lo = new Int32Array(count);
115427
+ const hi = new Int32Array(count);
115428
+ const half = Math.abs(s) / 2;
115429
+ for (let i = 0; i < count; i++) {
115430
+ const c = s * i + t;
115431
+ let a, b;
115432
+ if (Math.abs(s) <= 1) {
115433
+ a = b = Math.round(c);
115434
+ }
115435
+ else {
115436
+ a = Math.ceil(c - half - 1e-9);
115437
+ b = Math.floor(c + half - 1e-9);
115438
+ }
115439
+ lo[i] = Math.max(a, 0);
115440
+ hi[i] = Math.min(b, extent - 1);
115441
+ }
115442
+ return { lo, hi };
115443
+ }
115444
+ /**
115445
+ * The source's labels on this viewer's slice `index` along `axis`. A cell mapping outside
115446
+ * the source is 0. On the same grid with the identity, it is the source's own slice.
115447
+ *
115448
+ * With a diagonal transform (the axes agree, only scale and offset differ), a mirror voxel
115449
+ * coarser than the source shows the first label found among every source voxel it spans, so
115450
+ * a finding thinner than the mirror's slice still appears on the slice that contains it.
115451
+ * Any other transform samples the nearest source voxel.
115452
+ */
115453
+ function mirrorSliceLabels(source, mirrorDims, axis, index, m) {
115454
+ const sd = source.getDimensions();
115455
+ if (isIdentity(m) && sd.width === mirrorDims[0] && sd.height === mirrorDims[1] && sd.depth === mirrorDims[2]) {
115456
+ const s = source.getSliceUint8(index, axis);
115457
+ return { data: s.data, width: s.width, height: s.height, stride: source.getChannels() };
115458
+ }
115459
+ const mat = m !== null && m !== void 0 ? m : IDENTITY;
115460
+ const [W, H] = sliceDims(mirrorDims, axis);
115461
+ const raw = source.getRawData();
115462
+ const nch = source.getChannels();
115463
+ const out = new Uint8Array(W * H);
115464
+ if (isDiagonal(mat)) {
115465
+ const rx = coveredRanges(mat[0], mat[3], mirrorDims[0], sd.width);
115466
+ const ry = coveredRanges(mat[5], mat[7], mirrorDims[1], sd.height);
115467
+ const rz = coveredRanges(mat[10], mat[11], mirrorDims[2], sd.depth);
115468
+ for (let v = 0; v < H; v++) {
115469
+ for (let u = 0; u < W; u++) {
115470
+ const x = axis === "x" ? index : u;
115471
+ const y = axis === "y" ? index : v;
115472
+ const z = axis === "z" ? index : axis === "y" ? v : u;
115473
+ let label = 0;
115474
+ for (let sz = rz.lo[z]; sz <= rz.hi[z] && !label; sz++) {
115475
+ for (let sy = ry.lo[y]; sy <= ry.hi[y] && !label; sy++) {
115476
+ for (let sx = rx.lo[x]; sx <= rx.hi[x] && !label; sx++) {
115477
+ label = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
115478
+ }
115479
+ }
115480
+ }
115481
+ out[v * W + u] = label;
115482
+ }
115483
+ }
115484
+ return { data: out, width: W, height: H, stride: 1 };
115485
+ }
115486
+ for (let v = 0; v < H; v++) {
115487
+ for (let u = 0; u < W; u++) {
115488
+ // Slice cell (u, v) -> this viewer's voxel, per getSliceUint8's layout.
115489
+ const x = axis === "x" ? index : u;
115490
+ const y = axis === "y" ? index : v;
115491
+ const z = axis === "z" ? index : axis === "y" ? v : u;
115492
+ const sx = Math.round(mat[0] * x + mat[1] * y + mat[2] * z + mat[3]);
115493
+ const sy = Math.round(mat[4] * x + mat[5] * y + mat[6] * z + mat[7]);
115494
+ const sz = Math.round(mat[8] * x + mat[9] * y + mat[10] * z + mat[11]);
115495
+ if (sx < 0 || sy < 0 || sz < 0 || sx >= sd.width || sy >= sd.height || sz >= sd.depth)
115496
+ continue;
115497
+ out[v * W + u] = raw[((sz * sd.height + sy) * sd.width + sx) * nch];
115498
+ }
115499
+ }
115500
+ return { data: out, width: W, height: H, stride: 1 };
115501
+ }
115502
+ /**
115503
+ * One viewer drawing another's masks. Holds no mask data: every paint reads the source's
115504
+ * volumes and display state. A new transform means a new instance, so the cache never holds
115505
+ * contours from another transform.
115506
+ */
115507
+ class MaskMirror {
115508
+ constructor(self, source, matrix) {
115509
+ this.self = self;
115510
+ this.source = source;
115511
+ this.matrix = matrix;
115512
+ /** One contour entry per source layer, for the slice last painted. */
115513
+ this.cache = new Map();
115514
+ /** The source volume each cache entry was built from; a case load replaces the object. */
115515
+ this.cachedVolumes = new Map();
115516
+ }
115517
+ /** Paint every visible source layer onto `ctx` for this viewer's current axis and slice. */
115518
+ paint(ctx, width, height) {
115519
+ var _a, _b;
115520
+ // The source hides its own layers in sphere mode, so the mirror shows none either.
115521
+ if (this.source.gui_states.mode.sphere)
115522
+ return;
115523
+ const dims = this.self.nrrd_states.image.dimensions;
115524
+ if (!dims || dims.length !== 3)
115525
+ return;
115526
+ const axis = this.self.protectedData.axis;
115527
+ const index = this.self.nrrd_states.view.currentSliceIndex;
115528
+ const lc = this.source.gui_states.layerChannel;
115529
+ const outline = this.source.gui_states.drawing.maskRenderMode === "outline";
115530
+ for (const layerId of this.source.nrrd_states.image.layers) {
115531
+ if (!lc.layerVisibility[layerId])
115532
+ continue;
115533
+ const volume = this.source.protectedData.maskData.volumes[layerId];
115534
+ if (!volume)
115535
+ continue;
115536
+ if (this.cachedVolumes.get(layerId) !== volume) {
115537
+ this.cache.delete(layerId);
115538
+ this.cachedVolumes.set(layerId, volume);
115539
+ }
115540
+ try {
115541
+ const entry = contourEntry(this.cache, layerId, `${axis}:${index}:${volume.getVersion()}`, () => mirrorSliceLabels(volume, dims, axis, index, this.matrix), outline);
115542
+ ctx.save();
115543
+ try {
115544
+ ctx.globalAlpha = (_b = (_a = lc.layerOpacity) === null || _a === void 0 ? void 0 : _a[layerId]) !== null && _b !== void 0 ? _b : 1;
115545
+ paintContours(entry, ctx, axis, width, height, outline, (l) => volume.getChannelColor(l), lc.channelVisibility[layerId]);
115546
+ }
115547
+ finally {
115548
+ // A throw must not leave this layer's alpha or transform on the master canvas.
115549
+ ctx.restore();
115550
+ }
115551
+ }
115552
+ catch (_c) {
115553
+ // The source is not ready for this slice: nothing to draw for this layer.
115554
+ }
115555
+ }
115556
+ }
115557
+ }
115558
+
115355
115559
  /**
115356
115560
  * NrrdTools.setMasksFromNIfTI forwards its `Map<string, Uint8Array>` argument
115357
115561
  * straight through to here with no second channel for metadata, so a caller that
@@ -115633,7 +115837,15 @@ class NrrdTools {
115633
115837
  // ═══════════════════════════════════════════════════════════════════════════
115634
115838
  constructor(container, options) {
115635
115839
  this._sliceRAFId = null;
115840
+ /** Viewers drawing this one's masks (see setMaskMirror). */
115841
+ this._mirrors = new Set();
115842
+ /** The viewer whose masks this one draws, if any. */
115843
+ this._mirrorSource = null;
115844
+ /** The pending frame that refreshes this viewer's mirrors. */
115845
+ this._mirrorFrame = null;
115636
115846
  this._pendingSliceStep = 0;
115847
+ /** Receives slice moves while a preview slice is shown; null when none is. */
115848
+ this._previewSliceMove = null;
115637
115849
  /** Whether calculator mode is active (not part of gui_states interface) */
115638
115850
  this._calculatorActive = false;
115639
115851
  /**
@@ -115666,6 +115878,8 @@ class NrrdTools {
115666
115878
  this.drawCore = new DrawToolCore(container, this.state);
115667
115879
  // Wire DrawToolCore's overridable methods to NrrdTools implementations
115668
115880
  this.wireDrawCoreMethods();
115881
+ // Every visible mask change ends in a composite; the viewers mirroring this one follow it.
115882
+ this.drawCore.renderer.onComposited = () => this.scheduleMirrorRefresh();
115669
115883
  // Wire RenderingUtils' setEmptyCanvasSize callback
115670
115884
  this.drawCore.renderer.setEmptyCanvasSize = (axis) => this.setEmptyCanvasSize(axis);
115671
115885
  this.init();
@@ -115676,6 +115890,7 @@ class NrrdTools {
115676
115890
  }
115677
115891
  // Wire sphere overlay refresh callback into DragOperator → DragSliceTool
115678
115892
  this.dragOperator.setRefreshSphereOverlay(() => this.refreshSphereOverlay());
115893
+ this.dragOperator.setPreviewSliceMove((index) => this.previewSliceMove(index));
115679
115894
  // Initialize extracted modules
115680
115895
  this.initNrrdToolsModules();
115681
115896
  }
@@ -115723,6 +115938,7 @@ class NrrdTools {
115723
115938
  });
115724
115939
  this.sliceRenderPipeline = new SliceRenderPipeline(toolCtx, {
115725
115940
  compositeAllLayers: () => this.drawCore.renderer.compositeAllLayers(),
115941
+ hasMaskMirror: () => this._mirrorSource !== null,
115726
115942
  getOrCreateSliceBuffer: (axis) => this.drawCore.renderer.getOrCreateSliceBuffer(axis),
115727
115943
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, targetCtx, w, h) => this.drawCore.renderer.renderSliceToCanvas(layer, axis, sliceIndex, buffer, targetCtx, w, h),
115728
115944
  getVolumeForLayer: (layer) => this.drawCore.renderer.getVolumeForLayer(layer),
@@ -116491,10 +116707,49 @@ class NrrdTools {
116491
116707
  * Used for register/origin image switching where the view state should persist.
116492
116708
  */
116493
116709
  switchSlicesPreservingView(allSlices) {
116710
+ this._previewSliceMove = null;
116494
116711
  this.state.protectedData.allSlicesArray.length = 0;
116495
116712
  this.state.protectedData.allSlicesArray = [...allSlices];
116496
116713
  this.sliceRenderPipeline.switchPreservingView();
116497
116714
  }
116715
+ /**
116716
+ * Show one slice of a volume before the volume itself has loaded: `header` is the full
116717
+ * volume's geometry, `slice` a depth-1 slice triple of plane `index` (built from one plane's
116718
+ * voxels), shown as slice `index` of the full stack. Geometry is re-initialised only when it
116719
+ * differs from the current one. Replaces whatever slice data is displayed; writes no mask.
116720
+ * The full volume later replaces it with `switchSlicesPreservingView`, keeping `index`.
116721
+ *
116722
+ * Until then every slice move (wheel, keys, drag, `setSliceMoving`) goes to `onSliceMove`
116723
+ * with its clamped target index instead of moving the displayed slice. Axial only; it does
116724
+ * not switch orientation.
116725
+ */
116726
+ showPreviewSlice(header, slice, index, onSliceMove) {
116727
+ const image = this.state.nrrd_states.image;
116728
+ const same = (a, b) => !!a && a.length === b.length && Array.from(b).every((v, i) => a[i] === v);
116729
+ if (!same(image.dimensions, header.dimensions) ||
116730
+ !same(image.voxelSpacing, header.spacing) ||
116731
+ !same(image.spaceOrigin, header.space_origin)) {
116732
+ this.dataLoader.initFromHeader(header);
116733
+ }
116734
+ slice.z.initIndex = index;
116735
+ this.state.protectedData.allSlicesArray.length = 0;
116736
+ // Take the index from `initIndex` rather than writing the full-stack index into the
116737
+ // depth-1 slice's own `index`, which would be out of range for it.
116738
+ this.sliceRenderPipeline.resetInitState();
116739
+ this.dataLoader.appendSlice(slice, 0);
116740
+ this._previewSliceMove = onSliceMove;
116741
+ }
116742
+ /** Whether a preview slice from `showPreviewSlice` is shown in place of a loaded volume. */
116743
+ isPreviewing() {
116744
+ return this._previewSliceMove !== null;
116745
+ }
116746
+ /** Hands a slice move to the preview's host; false when no preview is shown. */
116747
+ previewSliceMove(index) {
116748
+ if (!this._previewSliceMove)
116749
+ return false;
116750
+ this._previewSliceMove(index);
116751
+ return true;
116752
+ }
116498
116753
  appendLoadingbar(loadingbar) {
116499
116754
  this.state.protectedData.mainAreaContainer.appendChild(loadingbar);
116500
116755
  }
@@ -116606,7 +116861,10 @@ class NrrdTools {
116606
116861
  // ═══════════════════════════════════════════════════════════════════════════
116607
116862
  // 9. Delegated — DataLoader
116608
116863
  // ═══════════════════════════════════════════════════════════════════════════
116609
- setAllSlices(allSlices) { this.dataLoader.setAllSlices(allSlices); }
116864
+ setAllSlices(allSlices) {
116865
+ this._previewSliceMove = null;
116866
+ this.dataLoader.setAllSlices(allSlices);
116867
+ }
116610
116868
  setMasksData(masksData, loadingBar) { this.dataLoader.setMasksData(masksData, loadingBar); }
116611
116869
  setMasksFromNIfTI(layerVoxels, loadingBar) { this.dataLoader.setMasksFromNIfTI(layerVoxels, loadingBar); }
116612
116870
  // ═══════════════════════════════════════════════════════════════════════════
@@ -116872,6 +117130,7 @@ class NrrdTools {
116872
117130
  this.reloadMasksFromVolume();
116873
117131
  }
116874
117132
  reset() {
117133
+ this._previewSliceMove = null;
116875
117134
  this.state.protectedData.allSlicesArray.length = 0;
116876
117135
  this.state.protectedData.displaySlices.length = 0;
116877
117136
  this.drawCore.undoManager.clearAll();
@@ -116903,10 +117162,41 @@ class NrrdTools {
116903
117162
  this.state.nrrd_states.sphere.skinSphereOrigin = null;
116904
117163
  this.state.nrrd_states.sphere.nippleSphereOrigin = null;
116905
117164
  }
117165
+ /**
117166
+ * Draw `source`'s masks on this viewer, read live from it: its volumes, colours, channel and
117167
+ * layer visibility, opacity and render mode. `mirrorToSource` is a row-major 4×4 from this
117168
+ * viewer's voxel (x, y, z, 1) to the source's voxel; omitted means the identity. `null`
117169
+ * detaches. Display only — nothing is written to either viewer's masks.
117170
+ */
117171
+ setMaskMirror(source, mirrorToSource) {
117172
+ var _a, _b;
117173
+ (_a = this._mirrorSource) === null || _a === void 0 ? void 0 : _a._mirrors.delete(this);
117174
+ this._mirrorSource = source && source !== this ? source : null;
117175
+ this.drawCore.renderer.mirror = this._mirrorSource
117176
+ ? new MaskMirror(this.state, this._mirrorSource.state, mirrorToSource !== null && mirrorToSource !== void 0 ? mirrorToSource : null)
117177
+ : null;
117178
+ (_b = this._mirrorSource) === null || _b === void 0 ? void 0 : _b._mirrors.add(this);
117179
+ this.drawCore.renderer.compositeAllLayers();
117180
+ }
117181
+ /** The viewer whose masks this one draws, or null. */
117182
+ getMaskMirrorSource() {
117183
+ return this._mirrorSource;
117184
+ }
117185
+ /** Repaint every mirror of this viewer on the next frame; repeated calls coalesce. */
117186
+ scheduleMirrorRefresh() {
117187
+ if (this._mirrors.size === 0 || this._mirrorFrame !== null)
117188
+ return;
117189
+ this._mirrorFrame = requestAnimationFrame(() => {
117190
+ this._mirrorFrame = null;
117191
+ for (const m of this._mirrors)
117192
+ m.drawCore.renderer.compositeAllLayers();
117193
+ });
117194
+ }
116906
117195
  /**
116907
117196
  * Releases what this instance holds outside its own DOM subtree, so a viewer that is torn
116908
117197
  * down can be garbage-collected: the event router's listeners (its window `blur` listener
116909
- * reaches the whole engine graph), a pending slice step and the drawing-flag timer.
117198
+ * reaches the whole engine graph), a pending slice step, the drawing-flag timer and any
117199
+ * mask-mirror link.
116910
117200
  *
116911
117201
  * The instance must not be used afterwards. Safe to call more than once.
116912
117202
  */
@@ -116922,6 +117212,22 @@ class NrrdTools {
116922
117212
  window.clearTimeout(this.preTimer);
116923
117213
  this.preTimer = undefined;
116924
117214
  }
117215
+ // Release the mirror link from both ends, so neither viewer keeps the other alive.
117216
+ if (this._mirrorSource) {
117217
+ this._mirrorSource._mirrors.delete(this);
117218
+ this._mirrorSource = null;
117219
+ this.drawCore.renderer.mirror = null;
117220
+ }
117221
+ for (const m of this._mirrors) {
117222
+ m._mirrorSource = null;
117223
+ m.drawCore.renderer.mirror = null;
117224
+ m.drawCore.renderer.compositeAllLayers();
117225
+ }
117226
+ this._mirrors.clear();
117227
+ if (this._mirrorFrame !== null) {
117228
+ cancelAnimationFrame(this._mirrorFrame);
117229
+ this._mirrorFrame = null;
117230
+ }
116925
117231
  }
116926
117232
  // ═══════════════════════════════════════════════════════════════════════════
116927
117233
  // 12. Internal — Input Events
@@ -118226,15 +118532,15 @@ function installFastSliceRepaint(rawSlice_1) {
118226
118532
  }
118227
118533
 
118228
118534
  // import * as kiwrious from "copper3d_plugin_heart_k";
118229
- // "v3.11.4" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118535
+ // "v3.11.5" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118230
118536
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
118231
118537
  // referencing it throws a ReferenceError — guard it so local loading still works.
118232
118538
  let _revision = "unknown";
118233
118539
  try {
118234
- _revision = "v3.11.4";
118540
+ _revision = "v3.11.5";
118235
118541
  }
118236
118542
  catch (_a) {
118237
- /* "v3.11.4" not injected (local source build) */
118543
+ /* "v3.11.5" not injected (local source build) */
118238
118544
  }
118239
118545
  const REVISION = _revision;
118240
118546
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__