copper3d 3.9.3 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +95 -5
  2. package/dist/Loader/copperNrrdLoader.d.ts +74 -0
  3. package/dist/Loader/copperNrrdLoader.js +182 -8
  4. package/dist/Loader/copperNrrdLoader.js.map +1 -1
  5. package/dist/Loader/nrrdWorker.d.ts +1 -0
  6. package/dist/Loader/nrrdWorker.js +29 -0
  7. package/dist/Loader/nrrdWorker.js.map +1 -0
  8. package/dist/Loader/nrrdWorkerCore.d.ts +87 -0
  9. package/dist/Loader/nrrdWorkerCore.js +223 -0
  10. package/dist/Loader/nrrdWorkerCore.js.map +1 -0
  11. package/dist/Utils/segmentation/NrrdTools.d.ts +54 -0
  12. package/dist/Utils/segmentation/NrrdTools.js +94 -0
  13. package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
  14. package/dist/Utils/segmentation/tools/DataLoader.d.ts +48 -1
  15. package/dist/Utils/segmentation/tools/DataLoader.js +128 -30
  16. package/dist/Utils/segmentation/tools/DataLoader.js.map +1 -1
  17. package/dist/Utils/segmentation/tools/DragSliceTool.js +10 -3
  18. package/dist/Utils/segmentation/tools/DragSliceTool.js.map +1 -1
  19. package/dist/Utils/segmentation/tools/ToolHost.d.ts +9 -1
  20. package/dist/bundle.esm.js +424 -47
  21. package/dist/bundle.umd.js +425 -46
  22. package/dist/index.d.ts +5 -3
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/types/Loader/copperNrrdLoader.d.ts +74 -0
  26. package/dist/types/Loader/nrrdWorker.d.ts +1 -0
  27. package/dist/types/Loader/nrrdWorkerCore.d.ts +87 -0
  28. package/dist/types/Utils/segmentation/NrrdTools.d.ts +54 -0
  29. package/dist/types/Utils/segmentation/tools/DataLoader.d.ts +48 -1
  30. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +9 -1
  31. package/dist/types/index.d.ts +5 -3
  32. package/package.json +1 -1
@@ -0,0 +1,87 @@
1
+ /** A message this module hands back to the caller, in the exact shape `postMessage` expects
2
+ * (payload + a transfer list containing every `Transferable` inside it). */
3
+ export type WorkerEmit = (message: NrrdWorkerMessage, transfer?: Transferable[]) => void;
4
+ export interface NrrdLoadCommand {
5
+ cmd: "load";
6
+ id: string;
7
+ url: string;
8
+ segmentation: boolean;
9
+ knownMinMax?: [number, number];
10
+ }
11
+ export interface NrrdAbortCommand {
12
+ cmd: "abort";
13
+ id: string;
14
+ }
15
+ export type NrrdWorkerCommand = NrrdLoadCommand | NrrdAbortCommand;
16
+ /** Everything `rehydrateVolume` (main thread, `copperNrrdLoader.ts`) needs to reconstruct a
17
+ * real `Volume` -- values already computed by the real `NRRDLoader.parse()` above, copied
18
+ * out verbatim, never re-derived. `buffer` is the volume's own pixel data, transferable. */
19
+ export interface NrrdWorkerPayload {
20
+ xLength: number;
21
+ yLength: number;
22
+ zLength: number;
23
+ /** `headerObject.type`, e.g. "short" -- accepted by `Volume`'s own constructor switch. */
24
+ type: string;
25
+ header: Record<string, unknown>;
26
+ spacing: [number, number, number];
27
+ axisOrder: string[];
28
+ RASDimensions: [number, number, number];
29
+ segmentation: boolean;
30
+ min: number;
31
+ max: number;
32
+ windowLow: number;
33
+ windowHigh: number;
34
+ lowerThreshold: number;
35
+ upperThreshold: number;
36
+ matrixElements: number[];
37
+ inverseMatrixElements: number[];
38
+ buffer: ArrayBuffer;
39
+ }
40
+ export type NrrdWorkerMessage = {
41
+ id: string;
42
+ type: "progress";
43
+ loaded: number;
44
+ total: number;
45
+ } | {
46
+ id: string;
47
+ type: "loaded";
48
+ payload: NrrdWorkerPayload;
49
+ } | {
50
+ id: string;
51
+ type: "error";
52
+ name: string;
53
+ message: string;
54
+ };
55
+ interface PendingUrlFetch {
56
+ bufferPromise: Promise<ArrayBuffer>;
57
+ controller: AbortController;
58
+ attached: number;
59
+ }
60
+ export interface NrrdWorkerState {
61
+ pendingByUrl: Map<string, PendingUrlFetch>;
62
+ /** Which URL each still-attached caller id belongs to, so `handleAbortMessage` can find its
63
+ * shared entry, and so a load whose buffer arrives after the caller already detached can
64
+ * tell it has nothing left to do. */
65
+ callerToUrl: Map<string, string>;
66
+ }
67
+ export declare function createNrrdWorkerState(): NrrdWorkerState;
68
+ /**
69
+ * Handles one `{cmd: "load"}` command. Dedupes the underlying fetch by URL exactly like
70
+ * `copperNrrdLoader.ts`'s old `sharedFetchNrrdArrayBuffer` did (one real request per URL,
71
+ * shared by every attached caller) -- only the transport moved, not the sharing rule. Once
72
+ * the shared bytes arrive, this caller runs its OWN `loader.parse()` with its OWN
73
+ * `knownMinMax`, independently of every other attached caller -- parsing is cheap relative to
74
+ * fetch+gunzip and was never shared even before this change (see `copperNrrdLoader.ts`'s doc
75
+ * comment on `sharedFetchNrrdArrayBuffer`), so a second caller's different `knownMinMax` can
76
+ * never be silently handed the first caller's window.
77
+ */
78
+ export declare function handleLoadMessage(state: NrrdWorkerState, msg: NrrdLoadCommand, emit: WorkerEmit): Promise<void>;
79
+ /**
80
+ * Handles one `{cmd: "abort"}` command. The caller's own promise on the main thread is
81
+ * already rejected by the time this arrives (see `copperNrrdLoader.ts`'s `loadViaWorker` --
82
+ * it rejects locally the instant the caller's `AbortSignal` fires, exactly like the old
83
+ * `sharedFetchNrrdArrayBuffer` did). This only updates the shared bookkeeping: the real
84
+ * network transfer stops only once every attached caller has dropped off.
85
+ */
86
+ export declare function handleAbortMessage(state: NrrdWorkerState, msg: NrrdAbortCommand): void;
87
+ export {};
@@ -0,0 +1,223 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { NRRDLoader } from "three/examples/jsm/loaders/NRRDLoader";
11
+ import { Volume } from "three/examples/jsm/misc/Volume.js";
12
+ /**
13
+ * Runs entirely off the main thread: fetch, gunzip (via `NRRDLoader.parse`'s own
14
+ * `fflate.gunzipSync`) and the NRRD header/typed-array parse. This module has no DOM
15
+ * dependency -- `NRRDLoader.parse` and `Volume` only touch `ArrayBuffer`s and three's math
16
+ * classes (`Matrix4`, `Vector3`), never `document` -- so it is safe to import both inside a
17
+ * Web Worker and, for tests, inside the main jsdom realm (see `__tests__/helpers/
18
+ * fakeNrrdWorker.ts`, which drives this same module in-process instead of through a real
19
+ * `postMessage` boundary).
20
+ *
21
+ * Structured as plain functions over an explicit `NrrdWorkerState`, with an injected `emit`
22
+ * callback instead of a bare `self.postMessage`, so the real worker entry (`nrrdWorker.ts`)
23
+ * and the in-process test double can share the exact same logic.
24
+ */
25
+ const loader = new NRRDLoader();
26
+ /**
27
+ * Mirrors `copperNrrdLoader.ts`'s own `installMinMaxOverride` -- same lever, same reason
28
+ * (three exposes no hook between "Volume built" and "computeMinMax() called", only the
29
+ * method itself), just installed against *this* module's own `Volume` class. Worker and main
30
+ * thread each get their own bundle of `three/examples/jsm/misc/Volume.js`, so patching the
31
+ * prototype here never touches the main thread's copy.
32
+ */
33
+ let pendingMinMax = null;
34
+ const MINMAX_OVERRIDE_INSTALLED = Symbol("copper-worker-minmax-override");
35
+ function installMinMaxOverride() {
36
+ const proto = Volume.prototype;
37
+ if (proto[MINMAX_OVERRIDE_INSTALLED])
38
+ return;
39
+ const original = proto.computeMinMax;
40
+ proto.computeMinMax = function computeMinMaxOrSupplied() {
41
+ if (pendingMinMax) {
42
+ const [min, max] = pendingMinMax;
43
+ this.min = min;
44
+ this.max = max;
45
+ return pendingMinMax;
46
+ }
47
+ return original.call(this);
48
+ };
49
+ proto[MINMAX_OVERRIDE_INSTALLED] = true;
50
+ }
51
+ export function createNrrdWorkerState() {
52
+ installMinMaxOverride();
53
+ return { pendingByUrl: new Map(), callerToUrl: new Map() };
54
+ }
55
+ /**
56
+ * Fetches `url` to completion, reporting `{loaded, total}` progress. No abort handling of its
57
+ * own -- the caller passes a signal it controls (the shared per-URL `AbortController`).
58
+ */
59
+ function fetchRawBuffer(url, signal, onProgress) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ const response = yield fetch(url, { signal });
62
+ if (!response.ok) {
63
+ throw new Error(`Failed to fetch ${url}: ${response.status} ${response.statusText}`);
64
+ }
65
+ const total = Number(response.headers.get("content-length")) || 0;
66
+ if (!response.body) {
67
+ return response.arrayBuffer();
68
+ }
69
+ const reader = response.body.getReader();
70
+ const chunks = [];
71
+ let loaded = 0;
72
+ for (;;) {
73
+ const { done, value } = yield reader.read();
74
+ if (done)
75
+ break;
76
+ chunks.push(value);
77
+ loaded += value.byteLength;
78
+ onProgress(loaded, total);
79
+ }
80
+ const merged = new Uint8Array(loaded);
81
+ let offset = 0;
82
+ for (const chunk of chunks) {
83
+ merged.set(chunk, offset);
84
+ offset += chunk.byteLength;
85
+ }
86
+ return merged.buffer;
87
+ });
88
+ }
89
+ /** Turns a real, just-parsed `Volume` into a transferable, structured-clone-safe payload.
90
+ * Every field is a value the real `NRRDLoader.parse()` already computed -- this only unwraps
91
+ * it from class instances (`Matrix4`) and non-cloneable fields (`header.__array`, a
92
+ * constructor function) that cannot cross the worker/main-thread boundary as-is. */
93
+ function buildPayload(volume) {
94
+ const header = Object.assign({}, volume.header);
95
+ delete header.__array;
96
+ return {
97
+ xLength: volume.xLength,
98
+ yLength: volume.yLength,
99
+ zLength: volume.zLength,
100
+ type: volume.header.type,
101
+ header,
102
+ spacing: volume.spacing,
103
+ axisOrder: volume.axisOrder,
104
+ RASDimensions: volume.RASDimensions,
105
+ segmentation: volume.segmentation,
106
+ min: volume.min,
107
+ max: volume.max,
108
+ windowLow: volume.windowLow,
109
+ windowHigh: volume.windowHigh,
110
+ lowerThreshold: volume.lowerThreshold,
111
+ upperThreshold: volume.upperThreshold,
112
+ matrixElements: Array.from(volume.matrix.elements),
113
+ inverseMatrixElements: Array.from(volume.inverseMatrix.elements),
114
+ buffer: volume.data.buffer,
115
+ };
116
+ }
117
+ function errorMessage(err) {
118
+ if (err instanceof Error)
119
+ return { name: err.name, message: err.message };
120
+ return { name: "Error", message: String(err) };
121
+ }
122
+ /**
123
+ * Handles one `{cmd: "load"}` command. Dedupes the underlying fetch by URL exactly like
124
+ * `copperNrrdLoader.ts`'s old `sharedFetchNrrdArrayBuffer` did (one real request per URL,
125
+ * shared by every attached caller) -- only the transport moved, not the sharing rule. Once
126
+ * the shared bytes arrive, this caller runs its OWN `loader.parse()` with its OWN
127
+ * `knownMinMax`, independently of every other attached caller -- parsing is cheap relative to
128
+ * fetch+gunzip and was never shared even before this change (see `copperNrrdLoader.ts`'s doc
129
+ * comment on `sharedFetchNrrdArrayBuffer`), so a second caller's different `knownMinMax` can
130
+ * never be silently handed the first caller's window.
131
+ */
132
+ export function handleLoadMessage(state, msg, emit) {
133
+ return __awaiter(this, void 0, void 0, function* () {
134
+ const { id, url, segmentation, knownMinMax } = msg;
135
+ let entry = state.pendingByUrl.get(url);
136
+ if (!entry) {
137
+ const controller = new AbortController();
138
+ const bufferPromise = fetchRawBuffer(url, controller.signal, (loaded, total) => {
139
+ for (const [callerId, callerUrl] of state.callerToUrl) {
140
+ if (callerUrl === url)
141
+ emit({ id: callerId, type: "progress", loaded, total });
142
+ }
143
+ }).finally(() => {
144
+ if (state.pendingByUrl.get(url) === entry)
145
+ state.pendingByUrl.delete(url);
146
+ });
147
+ entry = { bufferPromise, controller, attached: 0 };
148
+ state.pendingByUrl.set(url, entry);
149
+ }
150
+ entry.attached++;
151
+ state.callerToUrl.set(id, url);
152
+ const detach = () => {
153
+ entry.attached--;
154
+ if (entry.attached <= 0) {
155
+ entry.controller.abort();
156
+ if (state.pendingByUrl.get(url) === entry)
157
+ state.pendingByUrl.delete(url);
158
+ }
159
+ };
160
+ let buffer;
161
+ try {
162
+ buffer = yield entry.bufferPromise;
163
+ }
164
+ catch (err) {
165
+ // A caller already detached (via an explicit abort message) has its own `attached`
166
+ // decrement done there -- doing it again here would double-count. Its promise on the
167
+ // main thread was also already rejected locally, so there is nothing left to emit.
168
+ const stillAttached = state.callerToUrl.has(id);
169
+ if (stillAttached) {
170
+ detach();
171
+ state.callerToUrl.delete(id);
172
+ emit(Object.assign({ id, type: "error" }, errorMessage(err)));
173
+ }
174
+ return;
175
+ }
176
+ const stillAttached = state.callerToUrl.has(id);
177
+ if (stillAttached) {
178
+ detach();
179
+ state.callerToUrl.delete(id);
180
+ }
181
+ if (!stillAttached)
182
+ return; // detached (aborted) while the fetch was in flight
183
+ try {
184
+ pendingMinMax = knownMinMax !== null && knownMinMax !== void 0 ? knownMinMax : null;
185
+ let volume;
186
+ try {
187
+ loader.setSegmentation(segmentation);
188
+ volume = loader.parse(buffer);
189
+ }
190
+ finally {
191
+ pendingMinMax = null;
192
+ }
193
+ const payload = buildPayload(volume);
194
+ emit({ id, type: "loaded", payload }, [payload.buffer]);
195
+ }
196
+ catch (err) {
197
+ emit(Object.assign({ id, type: "error" }, errorMessage(err)));
198
+ }
199
+ });
200
+ }
201
+ /**
202
+ * Handles one `{cmd: "abort"}` command. The caller's own promise on the main thread is
203
+ * already rejected by the time this arrives (see `copperNrrdLoader.ts`'s `loadViaWorker` --
204
+ * it rejects locally the instant the caller's `AbortSignal` fires, exactly like the old
205
+ * `sharedFetchNrrdArrayBuffer` did). This only updates the shared bookkeeping: the real
206
+ * network transfer stops only once every attached caller has dropped off.
207
+ */
208
+ export function handleAbortMessage(state, msg) {
209
+ const url = state.callerToUrl.get(msg.id);
210
+ if (!url)
211
+ return;
212
+ state.callerToUrl.delete(msg.id);
213
+ const entry = state.pendingByUrl.get(url);
214
+ if (!entry)
215
+ return;
216
+ entry.attached--;
217
+ if (entry.attached <= 0) {
218
+ entry.controller.abort();
219
+ if (state.pendingByUrl.get(url) === entry)
220
+ state.pendingByUrl.delete(url);
221
+ }
222
+ }
223
+ //# sourceMappingURL=nrrdWorkerCore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nrrdWorkerCore.js","sourceRoot":"","sources":["../../src/Loader/nrrdWorkerCore.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,uCAAuC,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAE3D;;;;;;;;;;;;GAYG;AAEH,MAAM,MAAM,GAAQ,IAAI,UAAU,EAAE,CAAC;AAErC;;;;;;GAMG;AACH,IAAI,aAAa,GAA4B,IAAI,CAAC;AAClD,MAAM,yBAAyB,GAAG,MAAM,CAAC,+BAA+B,CAAC,CAAC;AAE1E,SAAS,qBAAqB;IAC5B,MAAM,KAAK,GAAG,MAAM,CAAC,SAAgB,CAAC;IACtC,IAAI,KAAK,CAAC,yBAAyB,CAAC;QAAE,OAAO;IAC7C,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC;IACrC,KAAK,CAAC,aAAa,GAAG,SAAS,uBAAuB;QACpD,IAAI,aAAa,EAAE,CAAC;YAClB,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,aAAa,CAAC;YACjC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;YACf,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;YACf,OAAO,aAAa,CAAC;QACvB,CAAC;QACD,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC;IACF,KAAK,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC;AAiED,MAAM,UAAU,qBAAqB;IACnC,qBAAqB,EAAE,CAAC;IACxB,OAAO,EAAE,YAAY,EAAE,IAAI,GAAG,EAAE,EAAE,WAAW,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC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
+ * How a message reaches the reader. Defaults to the console: this package ships without
51
+ * a UI and must not import the host application's, or it cannot be built on its own.
52
+ * A host that has a toast or a banner assigns this after construction.
53
+ */
54
+ notifyUser: (message: string, level: "error" | "warning" | "info") => void;
49
55
  /** Stored closure callbacks from gui.ts setupGui() */
50
56
  private guiCallbacks;
51
57
  constructor(container: HTMLDivElement, options?: {
@@ -118,6 +124,23 @@ export declare class NrrdTools {
118
124
  setSliceOrientation(axisTo: "x" | "y" | "z"): void;
119
125
  addSkip(index: number): void;
120
126
  removeSkip(index: number): void;
127
+ /**
128
+ * Batched form of `addSkip`/`removeSkip` for reconciling many positions at once (e.g. a
129
+ * case load's initial phase selection, see `useCaseManagement.reconcileSkips`) without
130
+ * paying `resetDisplaySlicesStatus()`'s full display/canvas/mask refresh once per position.
131
+ *
132
+ * Calling `addSkip`/`removeSkip` in a loop is correct but wasteful here: every entry but
133
+ * the last is immediately superseded (this always runs synchronously, with nothing reading
134
+ * the display in between, and the caller's own follow-up -- `landOn`'s `setContrastIndex`
135
+ * -- overwrites `contrastNum` again right after). Measured at over 1 second of main-thread
136
+ * time for a 5-phase series once per-volume extraction stopped dominating the case-load
137
+ * block (narrower `axes`, see copperNrrdLoader) -- this was always there, just smaller than
138
+ * the cost it used to sit next to.
139
+ */
140
+ setSkips(entries: Array<{
141
+ index: number;
142
+ skip: boolean;
143
+ }>): void;
121
144
  /**
122
145
  * Move to a specific contrast without moving the slice.
123
146
  *
@@ -129,6 +152,37 @@ export declare class NrrdTools {
129
152
  setSliceMoving(step: number): void;
130
153
  setMainAreaSize(factor: number): void;
131
154
  switchAllSlicesArrayData(allSlices: Array<nrrdSliceType>): void;
155
+ /**
156
+ * Batched form of `setSkips` + `setContrastIndex` for a load that ends by reconciling skip
157
+ * state and landing on a phase in the same turn (see
158
+ * `useCaseManagement.handleAllImagesLoaded`). Calling them separately is correct but
159
+ * wasteful: each pays `resetDisplaySlicesStatus()`'s full display/canvas/mask refresh, and
160
+ * with nothing reading the display in between, only the second call's paint was ever
161
+ * visible -- measured at two ~300ms refreshes back-to-back once `setSkips` had already
162
+ * absorbed the earlier per-phase `addSkip`/`removeSkip` loop cost.
163
+ *
164
+ * `contrastIndex` is set before the single `resetDisplaySlicesStatus()` call, not after:
165
+ * the resulting `displaySlices` length/order depends only on `skipSlicesDic`, which is
166
+ * already written by the time it runs, so the callbacks inside that one refresh
167
+ * (`repraintCurrentContrastSlice` etc.) paint the target contrast directly. The clamp
168
+ * below still runs after, against the freshly rebuilt `displaySlices`, for parity with
169
+ * `setContrastIndex`'s own bounds check.
170
+ */
171
+ commitSkipsAndContrast(skipEntries: Array<{
172
+ index: number;
173
+ skip: boolean;
174
+ }>, contrastIndex: number): void;
175
+ /**
176
+ * Case-load completion, fully batched: swap in the acquisition-ordered slice array,
177
+ * reconcile skip state, and land on the target contrast -- one `resetDisplaySlicesStatus()`
178
+ * instead of three (`switchAllSlicesArrayData` + `setSkips` + `setContrastIndex` used to
179
+ * each pay their own full refresh here; see `commitSkipsAndContrast` above for why only
180
+ * the batched form's single refresh is needed).
181
+ */
182
+ commitSeriesLoad(allSlices: Array<nrrdSliceType>, skipEntries: Array<{
183
+ index: number;
184
+ skip: boolean;
185
+ }>, contrastIndex: number): void;
132
186
  /**
133
187
  * Swap slice data while preserving current slice index, zoom, and pan position.
134
188
  * Used for register/origin image switching where the view state should persist.
@@ -8,6 +8,7 @@ import { GaussianSmoother } from "./core/GaussianSmoother";
8
8
  import { LayerChannelManager } from "./tools/LayerChannelManager";
9
9
  import { SliceRenderPipeline } from "./tools/SliceRenderPipeline";
10
10
  import { DataLoader } from "./tools/DataLoader";
11
+ import { ensureAxisExtracted } from "../../Loader/copperNrrdLoader";
11
12
  /**
12
13
  * Core NRRD annotation tool for medical image segmentation.
13
14
  *
@@ -38,6 +39,19 @@ export class NrrdTools {
38
39
  this._pendingSliceStep = 0;
39
40
  /** Whether calculator mode is active (not part of gui_states interface) */
40
41
  this._calculatorActive = false;
42
+ /**
43
+ * How a message reaches the reader. Defaults to the console: this package ships without
44
+ * a UI and must not import the host application's, or it cannot be built on its own.
45
+ * A host that has a toast or a banner assigns this after construction.
46
+ */
47
+ this.notifyUser = (message, level) => {
48
+ if (level === "error")
49
+ console.error(message);
50
+ else if (level === "warning")
51
+ console.warn(message);
52
+ else
53
+ console.info(message);
54
+ };
41
55
  /** Stored closure callbacks from gui.ts setupGui() */
42
56
  this.guiCallbacks = null;
43
57
  // ═══════════════════════════════════════════════════════════════════════════
@@ -130,6 +144,7 @@ export class NrrdTools {
130
144
  syncLayerSliceData: (index, mode) => this.drawCore.syncLayerSliceData(index, mode),
131
145
  reloadMasksFromVolume: () => this.reloadMasksFromVolume(),
132
146
  resetZoom: () => this.executeAction("resetZoom"),
147
+ notifyUser: (message, level) => this.notifyUser(message, level),
133
148
  });
134
149
  }
135
150
  // ═══════════════════════════════════════════════════════════════════════════
@@ -645,6 +660,14 @@ export class NrrdTools {
645
660
  this.state.nrrd_states.interaction.isCursorSelect = false;
646
661
  }
647
662
  }
663
+ // A narrowed-axes case load (see copperNrrdLoader's `axes` option) only extracts "z" up
664
+ // front; switching to sagittal/coronal is the first time anything needs the other planes.
665
+ // Extract them here, for every loaded contrast, before the display pipeline reads
666
+ // `slices[axisTo]` (SliceRenderPipeline.setDisplaySlicesBaseOnAxis) -- a no-op per slice
667
+ // that already has this axis.
668
+ for (const slice of this.state.protectedData.allSlicesArray) {
669
+ ensureAxisExtracted(slice, axisTo);
670
+ }
648
671
  this.state.protectedData.axis = axisTo;
649
672
  this.sliceRenderPipeline.resetDisplaySlicesStatus();
650
673
  }
@@ -664,6 +687,36 @@ export class NrrdTools {
664
687
  this.state.nrrd_states.view.contrastNum = 0;
665
688
  this.sliceRenderPipeline.resetDisplaySlicesStatus();
666
689
  }
690
+ /**
691
+ * Batched form of `addSkip`/`removeSkip` for reconciling many positions at once (e.g. a
692
+ * case load's initial phase selection, see `useCaseManagement.reconcileSkips`) without
693
+ * paying `resetDisplaySlicesStatus()`'s full display/canvas/mask refresh once per position.
694
+ *
695
+ * Calling `addSkip`/`removeSkip` in a loop is correct but wasteful here: every entry but
696
+ * the last is immediately superseded (this always runs synchronously, with nothing reading
697
+ * the display in between, and the caller's own follow-up -- `landOn`'s `setContrastIndex`
698
+ * -- overwrites `contrastNum` again right after). Measured at over 1 second of main-thread
699
+ * time for a 5-phase series once per-volume extraction stopped dominating the case-load
700
+ * block (narrower `axes`, see copperNrrdLoader) -- this was always there, just smaller than
701
+ * the cost it used to sit next to.
702
+ */
703
+ setSkips(entries) {
704
+ for (const { index, skip } of entries) {
705
+ if (skip) {
706
+ this.state.protectedData.skipSlicesDic[index] =
707
+ this.state.protectedData.backUpDisplaySlices[index];
708
+ this.state.nrrd_states.view.contrastNum =
709
+ index >= this.state.protectedData.displaySlices.length
710
+ ? this.state.protectedData.displaySlices.length
711
+ : index;
712
+ }
713
+ else {
714
+ this.state.protectedData.skipSlicesDic[index] = undefined;
715
+ this.state.nrrd_states.view.contrastNum = 0;
716
+ }
717
+ }
718
+ this.sliceRenderPipeline.resetDisplaySlicesStatus();
719
+ }
667
720
  /**
668
721
  * Move to a specific contrast without moving the slice.
669
722
  *
@@ -710,6 +763,47 @@ export class NrrdTools {
710
763
  this.state.protectedData.allSlicesArray = [...allSlices];
711
764
  this.sliceRenderPipeline.resetDisplaySlicesStatus();
712
765
  }
766
+ /**
767
+ * Batched form of `setSkips` + `setContrastIndex` for a load that ends by reconciling skip
768
+ * state and landing on a phase in the same turn (see
769
+ * `useCaseManagement.handleAllImagesLoaded`). Calling them separately is correct but
770
+ * wasteful: each pays `resetDisplaySlicesStatus()`'s full display/canvas/mask refresh, and
771
+ * with nothing reading the display in between, only the second call's paint was ever
772
+ * visible -- measured at two ~300ms refreshes back-to-back once `setSkips` had already
773
+ * absorbed the earlier per-phase `addSkip`/`removeSkip` loop cost.
774
+ *
775
+ * `contrastIndex` is set before the single `resetDisplaySlicesStatus()` call, not after:
776
+ * the resulting `displaySlices` length/order depends only on `skipSlicesDic`, which is
777
+ * already written by the time it runs, so the callbacks inside that one refresh
778
+ * (`repraintCurrentContrastSlice` etc.) paint the target contrast directly. The clamp
779
+ * below still runs after, against the freshly rebuilt `displaySlices`, for parity with
780
+ * `setContrastIndex`'s own bounds check.
781
+ */
782
+ commitSkipsAndContrast(skipEntries, contrastIndex) {
783
+ for (const { index, skip } of skipEntries) {
784
+ this.state.protectedData.skipSlicesDic[index] = skip
785
+ ? this.state.protectedData.backUpDisplaySlices[index]
786
+ : undefined;
787
+ }
788
+ this.state.nrrd_states.view.contrastNum = Math.max(contrastIndex, 0);
789
+ this.sliceRenderPipeline.resetDisplaySlicesStatus();
790
+ const last = this.state.protectedData.displaySlices.length - 1;
791
+ if (this.state.nrrd_states.view.contrastNum > last) {
792
+ this.state.nrrd_states.view.contrastNum = Math.max(0, last);
793
+ }
794
+ }
795
+ /**
796
+ * Case-load completion, fully batched: swap in the acquisition-ordered slice array,
797
+ * reconcile skip state, and land on the target contrast -- one `resetDisplaySlicesStatus()`
798
+ * instead of three (`switchAllSlicesArrayData` + `setSkips` + `setContrastIndex` used to
799
+ * each pay their own full refresh here; see `commitSkipsAndContrast` above for why only
800
+ * the batched form's single refresh is needed).
801
+ */
802
+ commitSeriesLoad(allSlices, skipEntries, contrastIndex) {
803
+ this.state.protectedData.allSlicesArray.length = 0;
804
+ this.state.protectedData.allSlicesArray = [...allSlices];
805
+ this.commitSkipsAndContrast(skipEntries, contrastIndex);
806
+ }
713
807
  /**
714
808
  * Swap slice data while preserving current slice index, zoom, and pan position.
715
809
  * Used for register/origin image switching where the view state should persist.