copper3d 3.10.2 → 3.10.3

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/dist/Utils/segmentation/DrawToolCore.js +1 -0
  2. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  3. package/dist/Utils/segmentation/NrrdTools.d.ts +13 -1
  4. package/dist/Utils/segmentation/NrrdTools.js +15 -0
  5. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  6. package/dist/Utils/segmentation/RenderingUtils.d.ts +32 -0
  7. package/dist/Utils/segmentation/RenderingUtils.js +107 -12
  8. package/dist/Utils/segmentation/RenderingUtils.js.map +1 -1
  9. package/dist/Utils/segmentation/core/MarchingSquares.d.ts +26 -0
  10. package/dist/Utils/segmentation/core/MarchingSquares.js +113 -0
  11. package/dist/Utils/segmentation/core/MarchingSquares.js.map +1 -1
  12. package/dist/Utils/segmentation/core/index.d.ts +2 -2
  13. package/dist/Utils/segmentation/core/index.js +1 -1
  14. package/dist/Utils/segmentation/core/index.js.map +1 -1
  15. package/dist/Utils/segmentation/core/types.d.ts +10 -0
  16. package/dist/Utils/segmentation/core/types.js.map +1 -1
  17. package/dist/Utils/segmentation/coreTools/GuiState.js +2 -0
  18. package/dist/Utils/segmentation/coreTools/GuiState.js.map +1 -1
  19. package/dist/Utils/segmentation/tools/DrawingTool.d.ts +19 -2
  20. package/dist/Utils/segmentation/tools/DrawingTool.js +30 -6
  21. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  22. package/dist/Utils/segmentation/tools/ToolHost.d.ts +7 -1
  23. package/dist/bundle.esm.js +270 -20
  24. package/dist/bundle.umd.js +270 -20
  25. package/dist/index.d.ts +2 -2
  26. package/dist/types/Utils/segmentation/NrrdTools.d.ts +13 -1
  27. package/dist/types/Utils/segmentation/RenderingUtils.d.ts +32 -0
  28. package/dist/types/Utils/segmentation/core/MarchingSquares.d.ts +26 -0
  29. package/dist/types/Utils/segmentation/core/index.d.ts +2 -2
  30. package/dist/types/Utils/segmentation/core/types.d.ts +10 -0
  31. package/dist/types/Utils/segmentation/tools/DrawingTool.d.ts +19 -2
  32. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +7 -1
  33. package/dist/types/index.d.ts +2 -2
  34. package/package.json +1 -1
@@ -107910,6 +107910,50 @@ void main() {
107910
107910
  /* 14 (TL+TR+BR, !BL) */ [[[0, 0], [1, 0], [1, 1], [0.5, 1], [0, 0.5]]],
107911
107911
  /* 15 (full) */ [[[0, 0], [1, 0], [1, 1], [0, 1]]],
107912
107912
  ];
107913
+ /**
107914
+ * Per-cell boundary segments for the same 16 cases — the region's edge, without the region.
107915
+ *
107916
+ * Each entry is the cut line of the corresponding `CELL_POLYGONS` entry: the one edge of that
107917
+ * polygon which does not lie on the cell's border. Filling the polygons and stroking these
107918
+ * therefore describe the same silhouette, which is what lets the renderer swap fill for
107919
+ * outline without the mask's edge appearing to move.
107920
+ *
107921
+ * Endpoints are the midpoints of the cell's sides —
107922
+ * T = (0.5, 0) R = (1, 0.5) B = (0.5, 1) L = (0, 0.5)
107923
+ * — in the same cell-local 0..1 space as `CELL_POLYGONS`, so the caller adds (i, j) + SHIFT
107924
+ * identically for both.
107925
+ *
107926
+ * Cases 0 and 15 emit nothing. 15 is the whole reason an outline is cheap: solid interior has
107927
+ * no boundary, so the segment count follows the perimeter rather than the area.
107928
+ *
107929
+ * Saddles (5 and 10) follow `CELL_POLYGONS`' convention — the two in-corners are disconnected
107930
+ * (4-connectivity) — because the other reading would run a boundary straight through mask the
107931
+ * fill considers solid.
107932
+ */
107933
+ const CELL_SEGMENTS = [
107934
+ /* 0 (empty) */ [],
107935
+ /* 1 (BL) */ [[[0, 0.5], [0.5, 1]]],
107936
+ /* 2 (BR) */ [[[0.5, 1], [1, 0.5]]],
107937
+ /* 3 (BR+BL) */ [[[0, 0.5], [1, 0.5]]],
107938
+ /* 4 (TR) */ [[[0.5, 0], [1, 0.5]]],
107939
+ /* 5 (TR+BL saddle) */ [
107940
+ [[0.5, 0], [1, 0.5]],
107941
+ [[0, 0.5], [0.5, 1]],
107942
+ ],
107943
+ /* 6 (TR+BR) */ [[[0.5, 0], [0.5, 1]]],
107944
+ /* 7 (TR+BR+BL, !TL) */ [[[0.5, 0], [0, 0.5]]],
107945
+ /* 8 (TL) */ [[[0.5, 0], [0, 0.5]]],
107946
+ /* 9 (TL+BL) */ [[[0.5, 0], [0.5, 1]]],
107947
+ /* 10 (TL+BR saddle) */ [
107948
+ [[0.5, 0], [0, 0.5]],
107949
+ [[0.5, 1], [1, 0.5]],
107950
+ ],
107951
+ /* 11 (TL+BR+BL, !TR) */ [[[0.5, 0], [1, 0.5]]],
107952
+ /* 12 (TL+TR) */ [[[1, 0.5], [0, 0.5]]],
107953
+ /* 13 (TL+TR+BL, !BR) */ [[[1, 0.5], [0.5, 1]]],
107954
+ /* 14 (TL+TR+BR, !BL) */ [[[0.5, 1], [0, 0.5]]],
107955
+ /* 15 (full) */ [],
107956
+ ];
107913
107957
  /**
107914
107958
  * Emit polygons covering the voxels where `labels === targetLabel`.
107915
107959
  * Pure geometry function — no Canvas dependency. Consumers can build a Path2D
@@ -108031,6 +108075,75 @@ void main() {
108031
108075
  }
108032
108076
  return path;
108033
108077
  }
108078
+ /**
108079
+ * Emit the boundary of the region where `labels === targetLabel`, as open two-point segments.
108080
+ *
108081
+ * The counterpart to {@link extractLabelPolygons}: that one covers the region, this one traces
108082
+ * its edge. Both walk the same cells with the same sampling, the same out-of-bounds rule and
108083
+ * the same `+0.5` shift, so a renderer can fill one and stroke the other and have the mask end
108084
+ * in exactly the same place either way.
108085
+ *
108086
+ * Segments are emitted per cell and left unjoined. Canvas rasterises a whole `Path2D` in one
108087
+ * compositing pass, so segments meeting at a shared endpoint produce no seam and no doubled
108088
+ * alpha where their round caps overlap — joining them into polylines would buy nothing and
108089
+ * cost a chaining pass.
108090
+ *
108091
+ * Cost follows the perimeter, not the area: solid interior is case 15, which has no boundary.
108092
+ *
108093
+ * Parameters match {@link extractLabelContours}.
108094
+ */
108095
+ function extractLabelBoundarySegments(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox) {
108096
+ var _a, _b, _c, _d;
108097
+ const out = [];
108098
+ const i0 = Math.max(-1, ((_a = bbox === null || bbox === void 0 ? void 0 : bbox.x0) !== null && _a !== void 0 ? _a : 0) - 1);
108099
+ const j0 = Math.max(-1, ((_b = bbox === null || bbox === void 0 ? void 0 : bbox.y0) !== null && _b !== void 0 ? _b : 0) - 1);
108100
+ const i1 = Math.min(width, (_c = bbox === null || bbox === void 0 ? void 0 : bbox.x1) !== null && _c !== void 0 ? _c : width);
108101
+ const j1 = Math.min(height, (_d = bbox === null || bbox === void 0 ? void 0 : bbox.y1) !== null && _d !== void 0 ? _d : height);
108102
+ const sample = (x, y) => {
108103
+ if (x < 0 || x >= width || y < 0 || y >= height)
108104
+ return false;
108105
+ return labels[(y * width + x) * stride + channelOffset] === targetLabel;
108106
+ };
108107
+ // Same convention as extractLabelPolygons: samples sit at voxel centres.
108108
+ const SHIFT = 0.5;
108109
+ for (let j = j0; j < j1; j++) {
108110
+ for (let i = i0; i < i1; i++) {
108111
+ const code = (sample(i, j) ? 8 : 0) |
108112
+ (sample(i + 1, j) ? 4 : 0) |
108113
+ (sample(i + 1, j + 1) ? 2 : 0) |
108114
+ (sample(i, j + 1) ? 1 : 0);
108115
+ // Nothing here, or nothing but mask: neither has an edge in this cell.
108116
+ if (code === 0 || code === 15)
108117
+ continue;
108118
+ const segments = CELL_SEGMENTS[code];
108119
+ for (let s = 0; s < segments.length; s++) {
108120
+ const [a, b] = segments[s];
108121
+ out.push([
108122
+ [i + a[0] + SHIFT, j + a[1] + SHIFT],
108123
+ [i + b[0] + SHIFT, j + b[1] + SHIFT],
108124
+ ]);
108125
+ }
108126
+ }
108127
+ }
108128
+ return out;
108129
+ }
108130
+ /**
108131
+ * {@link extractLabelBoundarySegments} as a `Path2D`, ready to stroke.
108132
+ *
108133
+ * The outline counterpart to {@link extractLabelContours}. Stroke this; do not stroke the
108134
+ * contour path — that one is per-cell polygons whose union is the silhouette, and stroking it
108135
+ * draws every internal cell edge as well, covering the mask in a grid.
108136
+ */
108137
+ function extractLabelOutline(labels, width, height, targetLabel, stride = 1, channelOffset = 0, bbox) {
108138
+ const segments = extractLabelBoundarySegments(labels, width, height, targetLabel, stride, channelOffset, bbox);
108139
+ const path = new Path2D();
108140
+ for (let s = 0; s < segments.length; s++) {
108141
+ const [a, b] = segments[s];
108142
+ path.moveTo(a[0], a[1]);
108143
+ path.lineTo(b[0], b[1]);
108144
+ }
108145
+ return path;
108146
+ }
108034
108147
  /**
108035
108148
  * Detect the distinct non-zero labels present in a slice region.
108036
108149
  *
@@ -109468,6 +109581,14 @@ void main() {
109468
109581
  }
109469
109582
  }
109470
109583
 
109584
+ /**
109585
+ * Outline stroke width, in screen pixels.
109586
+ *
109587
+ * Screen pixels rather than voxels so magnifying the image does not thicken the line over the
109588
+ * boundary the clinician magnified it to see. Thin enough to sit on an edge, thick enough to
109589
+ * stay visible against bright tissue.
109590
+ */
109591
+ const OUTLINE_WIDTH_PX = 1.5;
109471
109592
  /**
109472
109593
  * RenderingUtils — Rendering / slice-buffer helper methods.
109473
109594
  *
@@ -109499,6 +109620,12 @@ void main() {
109499
109620
  * applied at fill time and intentionally *not* cached, so toggling them
109500
109621
  * needs no recompute.
109501
109622
  *
109623
+ * The render mode is not in the key either. Fill paths and outline paths
109624
+ * are built lazily and side by side under the same entry, so switching
109625
+ * mode costs one extraction per visible label the first time and is a
109626
+ * cache hit every time after — and a session that never leaves fill mode
109627
+ * never builds an outline.
109628
+ *
109502
109629
  * One entry per layer (the current slice). Switching slice/axis or
109503
109630
  * editing overwrites it.
109504
109631
  */
@@ -109585,6 +109712,22 @@ void main() {
109585
109712
  return null; // Volume not ready
109586
109713
  }
109587
109714
  }
109715
+ /**
109716
+ * Populate one cache entry's paths for one render mode.
109717
+ *
109718
+ * Split out because the two modes are built at different times: whichever is in use when
109719
+ * a slice is first drawn, and the other one only if the clinician switches while still on
109720
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
109721
+ * sessions never turn on.
109722
+ */
109723
+ buildPaths(entry, data, stride, outline) {
109724
+ const target = outline ? entry.outlines : entry.fills;
109725
+ for (const lbl of entry.labels) {
109726
+ target.set(lbl, outline
109727
+ ? extractLabelOutline(data, entry.W, entry.H, lbl, stride, 0)
109728
+ : extractLabelContours(data, entry.W, entry.H, lbl, stride, 0));
109729
+ }
109730
+ }
109588
109731
  /**
109589
109732
  * Render a layer's slice onto the target canvas as vector contours.
109590
109733
  *
@@ -109597,6 +109740,27 @@ void main() {
109597
109740
  * is no longer used on this path — callers may pass any valid ImageData.
109598
109741
  */
109599
109742
  renderSliceToCanvas(layer, axis, sliceIndex, _buffer, targetCtx, scaledWidth, scaledHeight) {
109743
+ this.drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, this.state.gui_states.drawing.maskRenderMode === "outline");
109744
+ }
109745
+ /**
109746
+ * Render a layer's slice FILLED, whatever the clinician is currently looking at.
109747
+ *
109748
+ * For the tools that bake (`syncLayerSliceData` — pencil and eraser) the layer canvas is
109749
+ * not a picture of the mask, it is the input the mask is rebuilt from: the bake replaces
109750
+ * the whole slice in `MaskVolume` with whatever pixels it finds there.
109751
+ *
109752
+ * An outline is a lossy picture — it says where a mask ends, not what it contains — so
109753
+ * baking one back writes rings and erases every interior on that slice, taking every other
109754
+ * finding on the layer with it. One pencil stroke was enough.
109755
+ *
109756
+ * Hence a separate entry point rather than a flag threaded through the display path: a
109757
+ * render that is about to be read back has a different requirement from one that is about
109758
+ * to be looked at, and the two only coincided while there was one way to draw a mask.
109759
+ */
109760
+ renderSliceForBake(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight) {
109761
+ this.drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, false);
109762
+ }
109763
+ drawSlice(layer, axis, sliceIndex, targetCtx, scaledWidth, scaledHeight, outline) {
109600
109764
  try {
109601
109765
  const volume = this.getVolumeForLayer(layer);
109602
109766
  if (!volume)
@@ -109604,28 +109768,72 @@ void main() {
109604
109768
  const stride = volume.getChannels();
109605
109769
  const cacheKey = `${axis}:${sliceIndex}:${volume.getVersion()}`;
109606
109770
  // Cache miss → run the expensive extraction once. Hits (zoom,
109607
- // recomposite, contrast toggle) skip straight to the fill below.
109771
+ // recomposite, contrast toggle) skip straight to the draw below.
109608
109772
  let entry = this._contourCache.get(layer);
109609
109773
  if (!entry || entry.key !== cacheKey) {
109610
109774
  const slice = volume.getSliceUint8(sliceIndex, axis);
109611
- const W = slice.width;
109612
- const H = slice.height;
109613
- const labels = findLabelsInSlice(slice.data, W, H, stride, 0);
109614
- const paths = new Map();
109615
- for (const lbl of labels) {
109616
- paths.set(lbl, extractLabelContours(slice.data, W, H, lbl, stride, 0));
109617
- }
109618
- entry = { key: cacheKey, W, H, labels, paths };
109775
+ entry = {
109776
+ key: cacheKey,
109777
+ W: slice.width,
109778
+ H: slice.height,
109779
+ labels: findLabelsInSlice(slice.data, slice.width, slice.height, stride, 0),
109780
+ fills: new Map(),
109781
+ outlines: new Map(),
109782
+ };
109619
109783
  this._contourCache.set(layer, entry);
109784
+ this.buildPaths(entry, slice.data, stride, outline);
109785
+ }
109786
+ else if ((outline ? entry.outlines : entry.fills).size !== entry.labels.length) {
109787
+ // The mode changed since this slice was last drawn, so the other set of
109788
+ // paths is cached and this one is not. Re-read the slice and build it; from
109789
+ // here on both are present and toggling is a pure cache hit.
109790
+ const slice = volume.getSliceUint8(sliceIndex, axis);
109791
+ this.buildPaths(entry, slice.data, stride, outline);
109620
109792
  }
109621
109793
  if (entry.labels.length === 0)
109622
109794
  return;
109623
- const { W, H, labels, paths } = entry;
109795
+ const { W, H, labels } = entry;
109796
+ const paths = outline ? entry.outlines : entry.fills;
109624
109797
  const channelVis = this.state.gui_states.layerChannel.channelVisibility[layer];
109625
109798
  targetCtx.save();
109626
- // Vector fill — imageSmoothingEnabled is irrelevant here, but keep
109799
+ // Vector drawing — imageSmoothingEnabled is irrelevant here, but keep
109627
109800
  // it off to match the rest of the pipeline.
109628
109801
  targetCtx.imageSmoothingEnabled = false;
109802
+ if (outline) {
109803
+ // Stroke on an UNTRANSFORMED context, with the voxel→display mapping carried
109804
+ // in the path instead. `lineWidth` is then measured in screen pixels, which
109805
+ // is what the other two options get wrong: stroking under `ctx.scale(sx, sy)`
109806
+ // thickens the line with the zoom, exactly when the clinician has magnified
109807
+ // the image to look at the boundary — and because voxels are rarely isotropic
109808
+ // (sx !== sy), it also comes out thicker in one axis than the other.
109809
+ const matrix = new DOMMatrix();
109810
+ if (axis === 'y') {
109811
+ matrix.scaleSelf(1, -1);
109812
+ matrix.translateSelf(0, -scaledHeight);
109813
+ }
109814
+ matrix.scaleSelf(scaledWidth / W, scaledHeight / H);
109815
+ targetCtx.lineWidth = OUTLINE_WIDTH_PX;
109816
+ // Segments are emitted per cell and meet at shared endpoints; round caps
109817
+ // close those joins. Canvas composites a whole Path2D in one pass, so the
109818
+ // overlap costs no doubled alpha.
109819
+ targetCtx.lineJoin = 'round';
109820
+ targetCtx.lineCap = 'round';
109821
+ for (const lbl of labels) {
109822
+ if (channelVis && channelVis[lbl] === false)
109823
+ continue;
109824
+ const path = paths.get(lbl);
109825
+ if (!path)
109826
+ continue;
109827
+ const color = volume.getChannelColor(lbl);
109828
+ targetCtx.strokeStyle =
109829
+ `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`;
109830
+ const display = new Path2D();
109831
+ display.addPath(path, matrix);
109832
+ targetCtx.stroke(display);
109833
+ }
109834
+ targetCtx.restore();
109835
+ return;
109836
+ }
109629
109837
  // Coronal (axis='y') Z-flip: mirrors the flip applied by the write
109630
109838
  // path (syncLayerSliceData). Apply BEFORE the voxel→display scale
109631
109839
  // so the flip operates in display coordinates.
@@ -110843,6 +111051,11 @@ void main() {
110843
111051
  this.ctx.nrrd_states.interaction.drawStartPos.y = e.offsetY;
110844
111052
  // Capture pre-draw slice snapshot for undo
110845
111053
  this.capturePreDrawSnapshot();
111054
+ // The eraser works on canvas pixels and then bakes the canvas back into the volume, so
111055
+ // it needs the layer solid rather than outlined for the length of the stroke. The display
111056
+ // mode comes back at pointerup, via refreshLayerFromVolume.
111057
+ if (this.ctx.gui_states.mode.eraser)
111058
+ this.solidifyLayerForErase();
110846
111059
  // Brush mode: initialize voxel tracking and write first dot
110847
111060
  if (!this.ctx.gui_states.mode.pencil && !this.ctx.gui_states.mode.eraser) {
110848
111061
  const voxel = this.canvasToVoxel3D(e.offsetX, e.offsetY);
@@ -111255,17 +111468,36 @@ void main() {
111255
111468
  this.preDrawSlice = null;
111256
111469
  }
111257
111470
  /**
111258
- * Redraws persisted layer data onto ctx before new pencil fill.
111259
- * Delegates to the host's vector renderSliceToCanvas for consistency.
111471
+ * Redraws persisted layer data onto ctx before the new pencil fill.
111472
+ *
111473
+ * Uses the BAKE renderer, not the display one. What lands on this canvas is about to be
111474
+ * read straight back into the MaskVolume by `syncLayerSliceData`, which replaces the whole
111475
+ * slice -- so this render is the data, not a picture of it. Drawing outlines here would
111476
+ * bake rings and erase the interior of every mask on the layer.
111260
111477
  */
111261
111478
  redrawPreviousImageToLayerCtx(ctx) {
111262
111479
  const axis = this.ctx.protectedData.axis;
111263
111480
  const W = this.ctx.nrrd_states.view.changedWidth;
111264
111481
  const H = this.ctx.nrrd_states.view.changedHeight;
111265
- const buffer = this.callbacks.getOrCreateSliceBuffer(axis);
111266
- if (!buffer)
111267
- return;
111268
- this.callbacks.renderSliceToCanvas(this.ctx.gui_states.layerChannel.layer, axis, this.ctx.nrrd_states.view.currentSliceIndex, buffer, ctx, W, H);
111482
+ this.callbacks.renderSliceForBake(this.ctx.gui_states.layerChannel.layer, axis, this.ctx.nrrd_states.view.currentSliceIndex, ctx, W, H);
111483
+ }
111484
+ /**
111485
+ * Put the active layer's canvas into the solid state the eraser and the bake both need.
111486
+ *
111487
+ * The eraser removes pixels matching the active channel's colour, and `syncLayerSliceData`
111488
+ * then rebuilds the whole slice from what is left on the canvas. Against an outline there
111489
+ * is nothing to match inside a mask, so a drag over a lesion erases nothing -- and the bake
111490
+ * that follows writes the ring back and loses every interior on the layer.
111491
+ *
111492
+ * Unconditional rather than checked against the display mode: in fill mode this redraws
111493
+ * what is already on screen, and a mode-dependent branch here is one more thing that can
111494
+ * fall out of step with the renderer.
111495
+ */
111496
+ solidifyLayerForErase() {
111497
+ const target = this.callbacks.setCurrentLayer();
111498
+ target.canvas.width = target.canvas.width; // clear
111499
+ this.callbacks.renderSliceForBake(this.ctx.gui_states.layerChannel.layer, this.ctx.protectedData.axis, this.ctx.nrrd_states.view.currentSliceIndex, target.ctx, this.ctx.nrrd_states.view.changedWidth, this.ctx.nrrd_states.view.changedHeight);
111500
+ this.callbacks.compositeAllLayers();
111269
111501
  }
111270
111502
  /** Draw a line segment on a layer canvas (pencil mode only) */
111271
111503
  drawLinesOnLayer(ctx, x, y) {
@@ -113147,6 +113379,7 @@ void main() {
113147
113379
  getVolumeForLayer: (layer) => this.renderer.getVolumeForLayer(layer),
113148
113380
  pushUndoDelta: (delta) => this.undoManager.push(delta),
113149
113381
  renderSliceToCanvas: (layer, axis, sliceIndex, buffer, ctx, w, h) => this.renderer.renderSliceToCanvas(layer, axis, sliceIndex, buffer, ctx, w, h),
113382
+ renderSliceForBake: (layer, axis, sliceIndex, ctx, w, h) => this.renderer.renderSliceForBake(layer, axis, sliceIndex, ctx, w, h),
113150
113383
  getOrCreateSliceBuffer: (axis) => this.renderer.getOrCreateSliceBuffer(axis),
113151
113384
  });
113152
113385
  this.sphereBrushTool = new SphereBrushTool(toolCtx, {
@@ -114047,6 +114280,8 @@ void main() {
114047
114280
  fillColor: (_b = opts.defaultFillColor) !== null && _b !== void 0 ? _b : "#f50a33",
114048
114281
  brushColor: (_c = opts.defaultBrushColor) !== null && _c !== void 0 ? _c : "#f50a33",
114049
114282
  brushAndEraserSize: 10,
114283
+ // Filled is what every existing caller already gets; outline is opt-in.
114284
+ maskRenderMode: "fill",
114050
114285
  };
114051
114286
  this.viewConfig = {
114052
114287
  mainAreaSize: 3,
@@ -116237,6 +116472,21 @@ void main() {
116237
116472
  setLayerOpacity(layerId, opacity) { this.layerChannelManager.setLayerOpacity(layerId, opacity); }
116238
116473
  getLayerOpacity(layerId) { return this.layerChannelManager.getLayerOpacity(layerId); }
116239
116474
  getLayerOpacityMap() { return this.layerChannelManager.getLayerOpacityMap(); }
116475
+ /**
116476
+ * Fill every mask, or stroke only its boundary — for every layer and channel at once.
116477
+ *
116478
+ * A display decision, and nothing but: `MaskVolume` is not read differently and not written
116479
+ * at all, so what is stored, uploaded, exported and undone is the complete mask either way.
116480
+ *
116481
+ * Repaints immediately, the same way `setChannelVisible` does, because there is no other
116482
+ * event that would bring the change to the screen — a clinician who switched the mode and
116483
+ * then had to scrub a slice to see it would reasonably call that broken.
116484
+ */
116485
+ setMaskRenderMode(mode) {
116486
+ this.state.gui_states.drawing.maskRenderMode = mode;
116487
+ this.reloadMasksFromVolume();
116488
+ }
116489
+ getMaskRenderMode() { return this.state.gui_states.drawing.maskRenderMode; }
116240
116490
  // ═══════════════════════════════════════════════════════════════════════════
116241
116491
  // 8. Delegated — SliceRenderPipeline
116242
116492
  // ═══════════════════════════════════════════════════════════════════════════
@@ -117843,15 +118093,15 @@ void main() {
117843
118093
  }
117844
118094
 
117845
118095
  // import * as kiwrious from "copper3d_plugin_heart_k";
117846
- // "v3.10.2" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
118096
+ // "v3.10.3" is injected at build time by rollup @rollup/plugin-replace, sourced from package.json version.
117847
118097
  // When copper3d is consumed from local source (no rollup replace step), the identifier is undefined and
117848
118098
  // referencing it throws a ReferenceError — guard it so local loading still works.
117849
118099
  let _revision = "unknown";
117850
118100
  try {
117851
- _revision = "v3.10.2";
118101
+ _revision = "v3.10.3";
117852
118102
  }
117853
118103
  catch (_a) {
117854
- /* "v3.10.2" not injected (local source build) */
118104
+ /* "v3.10.3" not injected (local source build) */
117855
118105
  }
117856
118106
  const REVISION = _revision;
117857
118107
  // Expose on global so the version can be read in a production browser console via window.__COPPER3D_VERSION__
package/dist/index.d.ts CHANGED
@@ -55,7 +55,7 @@ import { nrrdMeshesType, nrrdSliceType, SensorDecodedValue_kiwrious, SensorReadR
55
55
  import { IPaintImage, ICommXYZ, IGUIStates, IGuiParameterSettings, INrrdStates, IGuiMeta } from "./Utils/segmentation/core/types";
56
56
  import { NrrdState } from "./Utils/segmentation/coreTools/NrrdState";
57
57
  import { GuiState } from "./Utils/segmentation/coreTools/GuiState";
58
- import type { ToolMode, IAnnotationCallbacks } from "./Utils/segmentation/core/types";
58
+ import type { ToolMode, IAnnotationCallbacks, MaskRenderMode } from "./Utils/segmentation/core/types";
59
59
  import { CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss } from "./Utils/segmentation/core/index";
60
60
  import type { LayerId, ChannelValue } from "./Utils/segmentation/core/index";
61
61
  import { MAX_ENGINE_CHANNEL } from "./Utils/segmentation/core/index";
@@ -63,5 +63,5 @@ import type { AiPromptTool, AiPromptPoint, AiPromptPayload, AiMaskResult } from
63
63
  import "./css/style.css";
64
64
  export declare const REVISION: string;
65
65
  export { copperRenderer, copperRendererOnDemond, copperMSceneRenderer, setHDRFilePath, addLabelToScene, convert3DPostoScreenPos, convertScreenPosto3DPos, addBoxHelper, fullScreenListenner, configKiwriousHeart, copperScene, copperSceneOnDemond, copperMScene, CameraViewPoint, kiwrious, loadKiwrious, NrrdTools, registerNiftiMaskGrid, loading, Copper3dTrackballControls, Copper3dOrbitControls, createTexture2D_NRRD, MeshNodeTool, throttle, removeGuiFolderChilden, MAX_ENGINE_CHANNEL, CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss, GaussianSmoother, SurfaceAnnotator, exposureExponent, DEFAULT_TARGET_GREY, disposeObject3D, disposeMaterial, collectFadeTargets, setFade, restoreFade, createSceneBudget, defaultBudgetBytes, disposeScene, removeSceneFromMap, fitDistance, fitView, isRotateEnabled, setRotateEnabled, isPanEnabled, setPanEnabled, isZoomEnabled, setZoomEnabled, beginGesture, isGestureActive, setCameraPose, addVolumeBoundingBox, VOLUME_BOUNDS_NAME, DEFAULT_AXES, ensureAxisExtracted, copperGltfLoader, setDracoDecoderPath, setKTX2TranscoderPath, easeInOutCubic, viewPointToPose, rotateAroundAxis, interpolateFlightPose, poseDistance, orbitStepPose, zoomPose, orbitSwingAngle, installFastSliceRepaint, };
66
- export type { positionType, screenPosType, optsType, NrrdHeaderLike, GltfLoadOpts, nrrdMeshesType, nrrdSliceType, SensorDecodedValue_kiwrious, SensorReadResult_kiwrious, HeartRateResult_kiwrious, loadingBarType, IPaintImage, exportPaintImageType, IOptVTKLoader, aligned4DSurfaceType, aligned4DOptsType, Aligned4DController, raw4DVolumeTransformType, raw4DVolumeOptsType, Raw4DVolumeController, ICommXYZ, IGUIStates, IGuiParameterSettings, INrrdStates, NrrdState, GuiState, IGuiMeta, ToolMode, IAnnotationCallbacks, LayerId, ChannelValue, AiPromptTool, AiPromptPoint, AiPromptPayload, AiMaskResult, SurfaceAnnotatorOptions, Annotation, AnnotationMode, ExportOptions, ExposureVolume, DisposableObject3D, DisposableMaterial, FadeTarget, FadeableMaterial, SceneBudget, DisposableScene, SceneDisposalHost, FitBounds, FitViewScene, AxisGatedControls, GestureAxes, PosableScene, BoundingBoxHost, VolumeBoundingBoxOpts, NrrdAxis, Pose, };
66
+ export type { positionType, screenPosType, optsType, NrrdHeaderLike, GltfLoadOpts, nrrdMeshesType, nrrdSliceType, SensorDecodedValue_kiwrious, SensorReadResult_kiwrious, HeartRateResult_kiwrious, loadingBarType, IPaintImage, exportPaintImageType, IOptVTKLoader, aligned4DSurfaceType, aligned4DOptsType, Aligned4DController, raw4DVolumeTransformType, raw4DVolumeOptsType, Raw4DVolumeController, ICommXYZ, IGUIStates, IGuiParameterSettings, INrrdStates, NrrdState, GuiState, IGuiMeta, ToolMode, IAnnotationCallbacks, MaskRenderMode, LayerId, ChannelValue, AiPromptTool, AiPromptPoint, AiPromptPayload, AiMaskResult, SurfaceAnnotatorOptions, Annotation, AnnotationMode, ExportOptions, ExposureVolume, DisposableObject3D, DisposableMaterial, FadeTarget, FadeableMaterial, SceneBudget, DisposableScene, SceneDisposalHost, FitBounds, FitViewScene, AxisGatedControls, GestureAxes, PosableScene, BoundingBoxHost, VolumeBoundingBoxOpts, NrrdAxis, Pose, };
67
67
  export type { CameraViewPreset } from "./Controls/orbitFraming";
@@ -1,6 +1,6 @@
1
1
  import { nrrdSliceType, storeExportPaintImageType, loadingBarType } from "../../types/types";
2
2
  import { GUI } from "dat.gui";
3
- import { IMaskData, IDragOpts, IKeyBoardSettings, ToolMode, IGuiMeta } from "./core/types";
3
+ import { IMaskData, IDragOpts, IKeyBoardSettings, ToolMode, IGuiMeta, MaskRenderMode } from "./core/types";
4
4
  import { DragOperator } from "./DragOperator";
5
5
  import type { ChannelValue, RGBAColor, ChannelColorMap } from "./core";
6
6
  import type { SphereType } from "./tools/SphereTool";
@@ -254,6 +254,18 @@ export declare class NrrdTools {
254
254
  setLayerOpacity(layerId: string, opacity: number): void;
255
255
  getLayerOpacity(layerId: string): number;
256
256
  getLayerOpacityMap(): Record<string, number>;
257
+ /**
258
+ * Fill every mask, or stroke only its boundary — for every layer and channel at once.
259
+ *
260
+ * A display decision, and nothing but: `MaskVolume` is not read differently and not written
261
+ * at all, so what is stored, uploaded, exported and undone is the complete mask either way.
262
+ *
263
+ * Repaints immediately, the same way `setChannelVisible` does, because there is no other
264
+ * event that would bring the change to the screen — a clinician who switched the mode and
265
+ * then had to scrub a slice to see it would reasonably call that broken.
266
+ */
267
+ setMaskRenderMode(mode: MaskRenderMode): void;
268
+ getMaskRenderMode(): MaskRenderMode;
257
269
  updateOriginAndChangedWH(): void;
258
270
  setSyncsliceNum(): void;
259
271
  resetPaintAreaUIPosition(l?: number, t?: number): void;
@@ -31,6 +31,12 @@ export declare class RenderingUtils {
31
31
  * applied at fill time and intentionally *not* cached, so toggling them
32
32
  * needs no recompute.
33
33
  *
34
+ * The render mode is not in the key either. Fill paths and outline paths
35
+ * are built lazily and side by side under the same entry, so switching
36
+ * mode costs one extraction per visible label the first time and is a
37
+ * cache hit every time after — and a session that never leaves fill mode
38
+ * never builds an outline.
39
+ *
34
40
  * One entry per layer (the current slice). Switching slice/axis or
35
41
  * editing overwrites it.
36
42
  */
@@ -67,6 +73,15 @@ export declare class RenderingUtils {
67
73
  * allocating a new ImageData per layer per slice switch.
68
74
  */
69
75
  getOrCreateSliceBuffer(axis: "x" | "y" | "z"): ImageData | null;
76
+ /**
77
+ * Populate one cache entry's paths for one render mode.
78
+ *
79
+ * Split out because the two modes are built at different times: whichever is in use when
80
+ * a slice is first drawn, and the other one only if the clinician switches while still on
81
+ * that slice. Building both eagerly would make every slice scrub pay for a mode most
82
+ * sessions never turn on.
83
+ */
84
+ private buildPaths;
70
85
  /**
71
86
  * Render a layer's slice onto the target canvas as vector contours.
72
87
  *
@@ -79,6 +94,23 @@ export declare class RenderingUtils {
79
94
  * is no longer used on this path — callers may pass any valid ImageData.
80
95
  */
81
96
  renderSliceToCanvas(layer: string, axis: "x" | "y" | "z", sliceIndex: number, _buffer: ImageData, targetCtx: CanvasRenderingContext2D, scaledWidth: number, scaledHeight: number): void;
97
+ /**
98
+ * Render a layer's slice FILLED, whatever the clinician is currently looking at.
99
+ *
100
+ * For the tools that bake (`syncLayerSliceData` — pencil and eraser) the layer canvas is
101
+ * not a picture of the mask, it is the input the mask is rebuilt from: the bake replaces
102
+ * the whole slice in `MaskVolume` with whatever pixels it finds there.
103
+ *
104
+ * An outline is a lossy picture — it says where a mask ends, not what it contains — so
105
+ * baking one back writes rings and erases every interior on that slice, taking every other
106
+ * finding on the layer with it. One pencil stroke was enough.
107
+ *
108
+ * Hence a separate entry point rather than a flag threaded through the display path: a
109
+ * render that is about to be read back has a different requirement from one that is about
110
+ * to be looked at, and the two only coincided while there was one way to draw a mask.
111
+ */
112
+ renderSliceForBake(layer: string, axis: "x" | "y" | "z", sliceIndex: number, targetCtx: CanvasRenderingContext2D, scaledWidth: number, scaledHeight: number): void;
113
+ private drawSlice;
82
114
  /**
83
115
  * Invalidate the reusable buffer (e.g. when switching datasets).
84
116
  */
@@ -66,6 +66,32 @@ export declare function extractLabelPolygons(labels: Uint8Array, width: number,
66
66
  * visited so the contour closes correctly at the bbox edges.
67
67
  */
68
68
  export declare function extractLabelContours(labels: Uint8Array, width: number, height: number, targetLabel: number, stride?: number, channelOffset?: number, bbox?: ContourBBox): Path2D;
69
+ /**
70
+ * Emit the boundary of the region where `labels === targetLabel`, as open two-point segments.
71
+ *
72
+ * The counterpart to {@link extractLabelPolygons}: that one covers the region, this one traces
73
+ * its edge. Both walk the same cells with the same sampling, the same out-of-bounds rule and
74
+ * the same `+0.5` shift, so a renderer can fill one and stroke the other and have the mask end
75
+ * in exactly the same place either way.
76
+ *
77
+ * Segments are emitted per cell and left unjoined. Canvas rasterises a whole `Path2D` in one
78
+ * compositing pass, so segments meeting at a shared endpoint produce no seam and no doubled
79
+ * alpha where their round caps overlap — joining them into polylines would buy nothing and
80
+ * cost a chaining pass.
81
+ *
82
+ * Cost follows the perimeter, not the area: solid interior is case 15, which has no boundary.
83
+ *
84
+ * Parameters match {@link extractLabelContours}.
85
+ */
86
+ export declare function extractLabelBoundarySegments(labels: Uint8Array, width: number, height: number, targetLabel: number, stride?: number, channelOffset?: number, bbox?: ContourBBox): ContourPolygon[];
87
+ /**
88
+ * {@link extractLabelBoundarySegments} as a `Path2D`, ready to stroke.
89
+ *
90
+ * The outline counterpart to {@link extractLabelContours}. Stroke this; do not stroke the
91
+ * contour path — that one is per-cell polygons whose union is the silhouette, and stroking it
92
+ * draws every internal cell edge as well, covering the mask in a grid.
93
+ */
94
+ export declare function extractLabelOutline(labels: Uint8Array, width: number, height: number, targetLabel: number, stride?: number, channelOffset?: number, bbox?: ContourBBox): Path2D;
69
95
  /**
70
96
  * Detect the distinct non-zero labels present in a slice region.
71
97
  *
@@ -67,10 +67,10 @@
67
67
  * const legacy = convertVolumeToIPaintImages(volume);
68
68
  * ```
69
69
  */
70
- export type { Dimensions, RGBAColor, ChannelColorMap, SliceRenderOptions, LayerId, ChannelValue, ICommXYZ, ICommXY, ISkipSlicesDictType, ToolMode, IDragPrameters, IDrawingEvents, IContrastEvents, IPaintImages, IPaintImage, ILayerRenderTarget, IDownloadImageConfig, INewMaskData, IMaskData, IProtected, IToolModeState, IDrawingConfig, IViewConfig, ILayerChannelState, IGUIStates, IGuiMeta, IGuiParameterSettings, IImageMetadata, IViewState, IInteractionState, ISphereState, IInternalFlags, INrrdStates, IAnnotationCallbacks, IConvertObjType, ICursorPage, IDragOpts, IDrawOpts, IKeyBoardSettings, } from './types';
70
+ export type { Dimensions, RGBAColor, ChannelColorMap, SliceRenderOptions, LayerId, ChannelValue, ICommXYZ, ICommXY, ISkipSlicesDictType, ToolMode, IDragPrameters, IDrawingEvents, IContrastEvents, IPaintImages, IPaintImage, ILayerRenderTarget, IDownloadImageConfig, INewMaskData, IMaskData, IProtected, IToolModeState, IDrawingConfig, IViewConfig, ILayerChannelState, IGUIStates, IGuiMeta, IGuiParameterSettings, IImageMetadata, IViewState, IInteractionState, ISphereState, IInternalFlags, INrrdStates, IAnnotationCallbacks, IConvertObjType, ICursorPage, IDragOpts, IDrawOpts, IKeyBoardSettings, MaskRenderMode, } from './types';
71
71
  export { RenderMode, MAX_ENGINE_CHANNEL, MASK_CHANNEL_COLORS, MASK_CHANNEL_CSS_COLORS, CHANNEL_COLORS, CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS, AI_CHANNEL_HEX_COLORS, rgbaToHex, rgbaToCss, } from './types';
72
72
  export { MaskVolume } from './MaskVolume';
73
73
  export type { MaskDelta, UndoEntry } from './UndoManager';
74
74
  export { UndoManager } from './UndoManager';
75
75
  export type { ContourBBox, ContourPolygon } from './MarchingSquares';
76
- export { extractLabelContours, extractLabelPolygons, findLabelsInSlice, } from './MarchingSquares';
76
+ export { extractLabelBoundarySegments, extractLabelContours, extractLabelOutline, extractLabelPolygons, findLabelsInSlice, } from './MarchingSquares';
@@ -240,6 +240,14 @@ export interface IToolModeState {
240
240
  activeSphereType: "tumour" | "skin" | "nipple" | "ribcage";
241
241
  }
242
242
  /** Drawing configuration — brush/pencil appearance and behavior */
243
+ /**
244
+ * How a mask is drawn onto the slice.
245
+ *
246
+ * `"fill"` paints the silhouette; `"outline"` strokes only its edge, leaving the interior
247
+ * clear so the image underneath stays readable. Purely a render-time choice — the mask stored
248
+ * in `MaskVolume`, uploaded, exported and undone is the same either way.
249
+ */
250
+ export type MaskRenderMode = "fill" | "outline";
243
251
  export interface IDrawingConfig {
244
252
  globalAlpha: number;
245
253
  lineWidth: number;
@@ -247,6 +255,8 @@ export interface IDrawingConfig {
247
255
  fillColor: string;
248
256
  brushColor: string;
249
257
  brushAndEraserSize: number;
258
+ /** Fill the mask or stroke only its boundary. Applies to every layer and channel at once. */
259
+ maskRenderMode: MaskRenderMode;
250
260
  }
251
261
  /** View configuration — UI layout and interaction parameters */
252
262
  export interface IViewConfig {
@@ -115,10 +115,27 @@ export declare class DrawingTool extends BaseTool {
115
115
  /** Push delta to UndoManager after drawing completes */
116
116
  private pushUndoDelta;
117
117
  /**
118
- * Redraws persisted layer data onto ctx before new pencil fill.
119
- * Delegates to the host's vector renderSliceToCanvas for consistency.
118
+ * Redraws persisted layer data onto ctx before the new pencil fill.
119
+ *
120
+ * Uses the BAKE renderer, not the display one. What lands on this canvas is about to be
121
+ * read straight back into the MaskVolume by `syncLayerSliceData`, which replaces the whole
122
+ * slice -- so this render is the data, not a picture of it. Drawing outlines here would
123
+ * bake rings and erase the interior of every mask on the layer.
120
124
  */
121
125
  private redrawPreviousImageToLayerCtx;
126
+ /**
127
+ * Put the active layer's canvas into the solid state the eraser and the bake both need.
128
+ *
129
+ * The eraser removes pixels matching the active channel's colour, and `syncLayerSliceData`
130
+ * then rebuilds the whole slice from what is left on the canvas. Against an outline there
131
+ * is nothing to match inside a mask, so a drag over a lesion erases nothing -- and the bake
132
+ * that follows writes the ring back and loses every interior on the layer.
133
+ *
134
+ * Unconditional rather than checked against the display mode: in fill mode this redraws
135
+ * what is already on screen, and a mode-dependent branch here is one more thing that can
136
+ * fall out of step with the renderer.
137
+ */
138
+ private solidifyLayerForErase;
122
139
  /** Draw a line segment on a layer canvas (pencil mode only) */
123
140
  private drawLinesOnLayer;
124
141
  /** Paint a segment on the current layer canvas and composite to master (pencil mode) */
@@ -18,6 +18,12 @@ export interface ToolHost {
18
18
  drawImageOnEmptyImage(canvas: HTMLCanvasElement): void;
19
19
  compositeAllLayers(): void;
20
20
  renderSliceToCanvas(layer: string, axis: "x" | "y" | "z", sliceIndex: number, buffer: ImageData, targetCtx: CanvasRenderingContext2D, scaledWidth: number, scaledHeight: number): void;
21
+ /**
22
+ * Render a layer's slice filled, whatever the display mode is. For tools that follow a
23
+ * render with `syncLayerSliceData`, which rebuilds the whole slice from the canvas: an
24
+ * outline would bake back as a ring and erase every mask interior on that slice.
25
+ */
26
+ renderSliceForBake(layer: string, axis: "x" | "y" | "z", sliceIndex: number, targetCtx: CanvasRenderingContext2D, scaledWidth: number, scaledHeight: number): void;
21
27
  getOrCreateSliceBuffer(axis: "x" | "y" | "z"): ImageData | null;
22
28
  flipDisplayImageByAxis(): void;
23
29
  redrawDisplayCanvas(): void;
@@ -71,7 +77,7 @@ export type ZoomHostDeps = Pick<ToolHost, 'resetPaintAreaUIPosition' | 'resizePa
71
77
  /** SphereTool host dependencies */
72
78
  export type SphereHostDeps = Pick<ToolHost, 'setEmptyCanvasSize' | 'drawImageOnEmptyImage' | 'enableCrosshair' | 'setUpSphereOrigins'>;
73
79
  /** DrawingTool host dependencies */
74
- export type DrawingHostDeps = Pick<ToolHost, 'setCurrentLayer' | 'compositeAllLayers' | 'syncLayerSliceData' | 'filterDrawedImage' | 'getVolumeForLayer' | 'pushUndoDelta' | 'renderSliceToCanvas' | 'getOrCreateSliceBuffer'>;
80
+ export type DrawingHostDeps = Pick<ToolHost, 'setCurrentLayer' | 'compositeAllLayers' | 'syncLayerSliceData' | 'filterDrawedImage' | 'getVolumeForLayer' | 'pushUndoDelta' | 'renderSliceToCanvas' | 'renderSliceForBake' | 'getOrCreateSliceBuffer'>;
75
81
  /** DragSliceTool host dependencies */
76
82
  export type DragSliceHostDeps = Pick<ToolHost, 'setSyncsliceNum' | 'setIsDrawFalse' | 'flipDisplayImageByAxis' | 'setEmptyCanvasSize' | 'getOrCreateSliceBuffer' | 'renderSliceToCanvas' | 'refreshSphereOverlay' | 'compositeAllLayers'>;
77
83
  /** LayerChannelManager host dependencies */