copper3d 3.10.4 → 3.11.1

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 (31) hide show
  1. package/README.md +128 -0
  2. package/ai-index/guides/4D-MRI-LV-rendering.md +580 -0
  3. package/ai-index/guides/ai-assist-api.md +382 -0
  4. package/ai-index/guides/camera-framing.md +238 -0
  5. package/ai-index/guides/control-axes.md +124 -0
  6. package/ai-index/guides/copper3d-4D-API.md +219 -0
  7. package/ai-index/guides/copper3d-rendering-optimization.md +155 -0
  8. package/ai-index/guides/gltf-decoders.md +105 -0
  9. package/ai-index/guides/heart-sensor.md +137 -0
  10. package/ai-index/guides/load-callbacks.md +244 -0
  11. package/ai-index/guides/mcp-server.md +139 -0
  12. package/ai-index/guides/nrrd-tools.md +1888 -0
  13. package/ai-index/guides/on-demand-controls.md +154 -0
  14. package/ai-index/guides/rotation-pivot.md +197 -0
  15. package/ai-index/guides/scene-resources.md +227 -0
  16. package/ai-index/guides/segmentation-module.md +1539 -0
  17. package/ai-index/guides/surface-annotation-api.md +388 -0
  18. package/ai-index/guides/volume-display.md +194 -0
  19. package/ai-index/manifest.json +144 -0
  20. package/ai-index/symbols.json +1 -0
  21. package/dist/Utils/segmentation/DrawToolCore.d.ts +19 -0
  22. package/dist/Utils/segmentation/DrawToolCore.js +62 -36
  23. package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
  24. package/dist/Utils/segmentation/tools/DrawingTool.js +14 -2
  25. package/dist/Utils/segmentation/tools/DrawingTool.js.map +1 -1
  26. package/dist/Utils/segmentation/tools/ToolHost.d.ts +2 -1
  27. package/dist/bundle.esm.js +79 -41
  28. package/dist/bundle.umd.js +79 -41
  29. package/dist/types/Utils/segmentation/DrawToolCore.d.ts +19 -0
  30. package/dist/types/Utils/segmentation/tools/ToolHost.d.ts +2 -1
  31. package/package.json +7 -4
@@ -0,0 +1,382 @@
1
+ # copper3d — AI Assist API (usage guide)
2
+
3
+ Public API for the **AI Assist** (interactive prompt segmentation) feature shipped in the
4
+ copper3d package. Everything is exposed on the `NrrdTools` instance plus a few exported
5
+ types and colour constants.
6
+
7
+ > 中文版:`ai-assist-api.zh.md`
8
+
9
+ ```ts
10
+ import { NrrdTools } from "copper3d";
11
+ import type { AiPromptPayload, AiMaskResult, AiPromptTool } from "copper3d";
12
+ ```
13
+
14
+ ---
15
+
16
+ ## Mental model
17
+
18
+ copper3d does **not** talk to your model/backend. It only:
19
+
20
+ 1. captures the user's **prompts** (point / box / scribble / lasso) on the current slice,
21
+ 2. fires your `onPrompt` callback with a serializable `AiPromptPayload`,
22
+ 3. and paints whatever **mask result** you hand back via `aiApplyMask` into an independent
23
+ **scratch volume** (rendered as an overlay).
24
+
25
+ You own the network call in between. Flow:
26
+
27
+ ```
28
+ user gesture ──▶ onPrompt(payload) ──▶ [your backend] ──▶ aiApplyMask(result)
29
+ ```
30
+
31
+ The scratch is a **sandbox**: nothing touches the real mask layers until you call
32
+ `aiCommitToLayer(...)` (merge). Entering AI mode hides the existing layer masks and shows
33
+ only the AI overlay; exiting restores them.
34
+
35
+ ### Segmentations (the colour/label model)
36
+
37
+ The scratch is a **single-channel** volume whose voxel value is a **label** (1–255). A
38
+ **Segmentation** = one label + a colour you choose. There is no fixed 8-colour palette any
39
+ more: the host app owns the list of segmentations (id / name / colour / label) and pushes
40
+ each colour into copper3d via `aiSetSegmentColor`. You can have any number of segmentations
41
+ (up to 255 labels).
42
+
43
+ ---
44
+
45
+ ## Quick start (end-to-end)
46
+
47
+ ```ts
48
+ const tools = new NrrdTools(container);
49
+ // … load your NRRD case into `tools` as usual …
50
+
51
+ // 1. Enter AI Assist (creates the scratch, hides layer masks, takes the canvas).
52
+ tools.enterAiAssistMode();
53
+
54
+ // 2. Configure the prompt tool + the active segmentation (label + colour).
55
+ tools.aiSetPromptTool("point"); // "point" | "box" | "scribble" | "lasso"
56
+ tools.aiSetPolarity(1); // 1 = foreground (include), 0 = background (exclude)
57
+ tools.aiSetSegmentColor(1, { r: 94, g: 200, b: 255, a: 255 }); // colour for label 1
58
+ tools.aiSetActiveSegment(1); // paint into label 1
59
+
60
+ // 3. Receive prompts → call YOUR model → paint the result back.
61
+ tools.aiOnPrompt(async (payload: AiPromptPayload) => {
62
+ const result: AiMaskResult = await myBackend.predict(payload);
63
+ tools.aiApplyMask(result);
64
+ });
65
+
66
+ // 4. Start a NEW segmentation (freezes the current one, switches to a new label/colour).
67
+ tools.aiSetSegmentColor(2, { r: 244, g: 63, b: 94, a: 255 });
68
+ tools.aiNewSegment(2);
69
+
70
+ // 5. Commit the AI overlay into a real mask layer (sandbox merge).
71
+ if (tools.aiHasData()) tools.aiCommitToLayer("layer1");
72
+
73
+ // 6. Leave AI mode (restores the layer masks).
74
+ tools.exitAiAssistMode();
75
+ ```
76
+
77
+ ---
78
+
79
+ ## API reference
80
+
81
+ ### Mode lifecycle
82
+
83
+ #### `enterAiAssistMode(): void`
84
+ Enter the AI sandbox. Hides all layer masks (snapshotting their visibility), creates the
85
+ scratch volume, and routes left-click to prompts. Right-drag still pans; wheel/slider still
86
+ scrub slices. **No fixed palette is applied** — push each segmentation's colour with
87
+ `aiSetSegmentColor` after entering. No-op if already active.
88
+
89
+ #### `exitAiAssistMode(): void`
90
+ Leave the sandbox: drop the scratch volume, restore normal tooling and the layer-mask
91
+ visibility captured on enter. If you merged first (`aiCommitToLayer`), the merged result is
92
+ already in the layer and reappears with the restored masks. No-op if not active.
93
+
94
+ #### `isAiAssistActive(): boolean`
95
+ `true` while AI mode is active.
96
+
97
+ ---
98
+
99
+ ### Prompt configuration
100
+
101
+ #### `aiSetPromptTool(tool: AiPromptTool): void`
102
+ Select the gesture: `"point"` (click seed), `"box"` (drag a rectangle), `"scribble"`
103
+ (drag a freehand stroke), `"lasso"` (click points → closed curve, see **Lasso**).
104
+ **Switching tool resets the current prompt set** (the next gesture starts a fresh prediction).
105
+
106
+ #### `aiSetPolarity(label: number): void`
107
+ `1` = foreground (include / add), `0` = background (exclude / carve). Anything ≠ 0 is
108
+ treated as foreground.
109
+
110
+ #### `aiSetScribbleSize(size: number): void`
111
+ Scribble brush radius in pixels (clamped 1–40). Drives both the live preview ring and the
112
+ `scribbleRadius` sent in the payload.
113
+
114
+ ---
115
+
116
+ ### Segmentations (label + colour)
117
+
118
+ A Segmentation is just a **label value** the AI paints into, plus a colour. (This replaces
119
+ the old fixed `aiSetChannel(1-8)` API.)
120
+
121
+ #### `aiSetActiveSegment(label: number): void`
122
+ Select the active segmentation by label value (1–255) — subsequent prompts paint into it.
123
+ **Switching label resets the current prompt set** (so the previous segmentation isn't
124
+ recoloured by an in-progress prediction).
125
+
126
+ #### `aiSetSegmentColor(label: number, color: { r: number; g: number; b: number; a: number }): void`
127
+ Set a segmentation's colour (its label's entry in the scratch volume's colorMap). The 2D
128
+ overlay repaints next frame. Call once per segmentation after `enterAiAssistMode`, and again
129
+ whenever the user recolours one.
130
+
131
+ #### `aiNewSegment(label: number): void` *(use this for a "New segmentation" button)*
132
+ Freeze the current regions (they persist through later predictions) **and** switch the
133
+ active label to `label`. Equivalent to `aiCommitRegion()` + `aiSetActiveSegment(label)`.
134
+
135
+ #### `aiClearSegment(label: number): void`
136
+ Delete a segmentation's painting: zero **every** voxel of that label in both the live scratch
137
+ and the frozen (committed) volume, so the region disappears from the view. Use this when the
138
+ host removes a segmentation from its list.
139
+
140
+ ```ts
141
+ // New-segmentation button:
142
+ const next = currentMaxLabel + 1;
143
+ tools.aiSetSegmentColor(next, nextColour);
144
+ tools.aiNewSegment(next);
145
+
146
+ // Delete a segmentation (host removes it from its list, then):
147
+ tools.aiClearSegment(label);
148
+ ```
149
+
150
+ ---
151
+
152
+ ### Lasso (closed-contour, click-to-place)
153
+
154
+ Lasso is **not** a freehand drag. The user **clicks points** around the target; copper3d
155
+ joins them with a **smooth closed curve** (Catmull-Rom, angularly ordered so it never
156
+ self-intersects) and fills it live. Nothing is sent to your model until **finish**.
157
+
158
+ - **Add point:** left-click empty space.
159
+ - **Delete point:** hover an existing vertex (it shows a red ✕) and left-click it.
160
+ - **Finish:** double-click, or call `aiFinishLasso()` (e.g. from a panel button / Enter key).
161
+ Needs ≥3 vertices; fires `onPrompt` with a densified contour in `payload.lasso`.
162
+ - **Undo/redo a vertex:** `aiLassoUndo()` / `aiLassoRedo()`.
163
+ - **Cancel:** `aiCancelLasso()` (e.g. Esc).
164
+
165
+ #### `aiOnLassoChange(cb: (count: number, editing: boolean) => void): void`
166
+ Register a callback fired whenever the lasso vertex set changes (add / delete / undo / redo /
167
+ finish / cancel). Drives a reactive "Finish lasso (N)" button in your UI.
168
+
169
+ #### `aiFinishLasso(): void`
170
+ Close + send the lasso (needs ≥3 vertices). Samples the closed curve into a dense contour and
171
+ fires `onPrompt` with it in `payload.lasso`, then clears the editing state.
172
+
173
+ #### `aiLassoUndo(): void` / `aiLassoRedo(): void`
174
+ Undo / redo the last vertex add or delete (vertex-level history, separate from mask undo).
175
+
176
+ #### `aiCancelLasso(): void`
177
+ Abandon the in-progress lasso.
178
+
179
+ #### `aiIsLassoEditing(): boolean` / `aiLassoVertCount(): number`
180
+ Whether vertices are being placed, and how many — for gating the Finish button + keyboard.
181
+
182
+ ```ts
183
+ tools.aiSetPromptTool("lasso");
184
+ tools.aiOnLassoChange((count, editing) => {
185
+ finishBtn.disabled = !editing || count < 3;
186
+ finishBtn.textContent = `Finish lasso (${count})`;
187
+ });
188
+ // Enter key → tools.aiFinishLasso(); Ctrl+Z → tools.aiLassoUndo(); Esc → tools.aiCancelLasso();
189
+ ```
190
+
191
+ > **Point tool feedback:** in `"point"` mode each click draws a seed marker and the cursor
192
+ > shows a crosshair; the markers auto-hide once a prediction lands (only the mask remains).
193
+
194
+ ---
195
+
196
+ ### Prompt ↔ result plumbing
197
+
198
+ #### `aiOnPrompt(cb: (payload: AiPromptPayload) => void): void`
199
+ Register the callback fired when a prompt gesture completes (point = on click; box / scribble =
200
+ on pointer-up; lasso = on finish). Inside it, call your model then `aiApplyMask`. The payload
201
+ carries the **cumulative** prompt set for the current region, so re-predict from the whole set
202
+ each time.
203
+
204
+ #### `aiApplyMask(result: AiMaskResult): void`
205
+ Paint a returned mask into the scratch volume (into the active segmentation's label); the
206
+ overlay repaints next frame. Supports 2D (single slice) and 3D (multi-slice) results.
207
+
208
+ ---
209
+
210
+ ### Region / sandbox management
211
+
212
+ #### `aiClearPrompts(): void`
213
+ Reset the in-progress prompt set (points/box/scribble/lasso). Used on slice/axis change. Does
214
+ **not** freeze.
215
+
216
+ #### `aiCommitRegion(): void`
217
+ **Freeze** everything painted so far so it survives later predictions — even on the same
218
+ label — without switching label. `aiNewSegment` calls this internally; use it directly if you
219
+ want a "freeze but stay on this segmentation" action.
220
+
221
+ #### `aiDiscard(): void`
222
+ Erase **everything** the AI painted since `enterAiAssistMode` (restores the empty snapshot,
223
+ including frozen regions). The host typically also resets its segmentation list to one.
224
+
225
+ #### `aiHasData(): boolean`
226
+ `true` if the scratch volume currently holds any painted voxels.
227
+
228
+ ---
229
+
230
+ ### Persisting / exporting the AI mask
231
+
232
+ #### `aiGetScratchSegments(): { axis: "z"; width: number; height: number; segments: { label: number; slices: { sliceIndex: number; rle: number[] }[] }[] } | null`
233
+ Serialize the scratch **per segmentation**: one binary per-slice RLE **per label** (no
234
+ binarize-merge), so a backend can write a **multi-label** NIfTI and colour a GLB per
235
+ segmentation. Returns `null` if there is no scratch. This is the path used to build a
236
+ per-segmentation-coloured 3D model.
237
+
238
+ ```ts
239
+ const vol = tools.aiGetScratchSegments();
240
+ if (vol && vol.segments.length) {
241
+ const segments = vol.segments.map((s) => ({
242
+ label: s.label,
243
+ color: colourForLabel(s.label), // [r,g,b] your app's chosen colour
244
+ slices: s.slices,
245
+ }));
246
+ await fetch("/api/ai/save-volume", {
247
+ method: "POST",
248
+ headers: { "Content-Type": "application/json" },
249
+ body: JSON.stringify({ caseId, axis: vol.axis, width: vol.width, height: vol.height, segments }),
250
+ });
251
+ }
252
+ ```
253
+
254
+ #### `aiGetScratchSlices(): { axis: "z"; width: number; height: number; slices: { sliceIndex: number; rle: number[] }[] } | null`
255
+ Legacy **binary** serialization (any non-zero label → 1), one RLE per non-empty z-slice. Kept
256
+ for single-mask backends; prefer `aiGetScratchSegments` for per-colour output.
257
+
258
+ #### `aiCommitToLayerMapped(targetLayer: string, mapping: Record<number, number>): void`
259
+ **Merge** the AI scratch into a real mask layer with an explicit **per-segmentation mapping**:
260
+ `{ scratch label → target channel }`. A label absent from `mapping` (or mapped to `0`) is
261
+ **discarded** (not merged). Several labels MAY map to the same channel — after merge the
262
+ **channel is the identity**, so the merged voxels take that channel's colour (not the AI
263
+ segmentation's sandbox colour).
264
+
265
+ **Union semantics:** an AI voxel only fills a target voxel that is currently **empty (0)** —
266
+ existing annotation is **never erased**. Where two labels mapped to different channels overlap
267
+ the same voxel, the first written wins (iteration order). Scans all z-slices (any-view voxels
268
+ captured); one undoable group.
269
+
270
+ ```ts
271
+ // seg label 1 → channel 2, label 3 → channel 2 (merged together), label 4 dropped:
272
+ tools.aiCommitToLayerMapped("layer3", { 1: 2, 3: 2 });
273
+ ```
274
+
275
+ #### `aiCommitToLayer(targetLayer: string = "layer1"): void`
276
+ Back-compat shim: merge with an **identity mapping** (each label → the same channel number)
277
+ via `aiCommitToLayerMapped`. Same **union** semantics (fills only empty voxels; existing
278
+ annotation preserved), one undoable group, scans all z-slices. This (or the mapped form) is the
279
+ only call that writes the AI result into the actual annotation layers.
280
+
281
+ ---
282
+
283
+ ## Types
284
+
285
+ ```ts
286
+ type AiPromptTool = "point" | "box" | "scribble" | "lasso";
287
+
288
+ interface AiPromptPoint {
289
+ x: number;
290
+ y: number;
291
+ z?: number;
292
+ label: number; // 1 = foreground, 0 = background
293
+ }
294
+
295
+ interface AiPromptPayload {
296
+ axis: "x" | "y" | "z";
297
+ sliceIndex: number;
298
+ width: number; // slice dimensions the prompt coords are in
299
+ height: number;
300
+ points: AiPromptPoint[];
301
+ box?: { x0: number; y0: number; x1: number; y1: number; label: number };
302
+ scribble?: AiPromptPoint[];
303
+ scribbleRadius?: number;
304
+ lasso?: AiPromptPoint[]; // ordered, densified closed contour (sent on finish)
305
+ }
306
+
307
+ interface AiMaskResult {
308
+ axis: "x" | "y" | "z";
309
+ sliceIndex: number;
310
+ width: number;
311
+ height: number;
312
+ rle: number[]; // 2D single-slice: alternating run lengths, 0-run first
313
+ sliceRange?: [number, number]; // 3D only: inclusive [lo, hi] slice span
314
+ slices?: number[][]; // 3D only: one RLE per slice in [lo, hi]
315
+ }
316
+ ```
317
+
318
+ **RLE format** (both directions): row-major over `width * height`, alternating run lengths
319
+ that **start with a 0-run** (`[zeros, ones, zeros, ones, …]`); the sum of runs equals
320
+ `width * height`. For a 3D result, leave `rle` empty and fill `sliceRange` + `slices`.
321
+
322
+ ---
323
+
324
+ ## Colour constants
325
+
326
+ ```ts
327
+ import { AI_CHANNEL_HEX_COLORS, AI_MASK_CHANNEL_COLORS } from "copper3d";
328
+ ```
329
+
330
+ These remain exported as an **optional default palette** reference, but are **no longer
331
+ applied automatically** on `enterAiAssistMode`. Segmentation colours are now free (any RGB)
332
+ and driven by the host via `aiSetSegmentColor(label, …)`. Use them only if you want a starting
333
+ palette; the host app is the source of truth for segmentation colours. The default palette
334
+ (`CHANNEL_HEX_COLORS` / `MASK_CHANNEL_COLORS`) is unchanged.
335
+
336
+ ---
337
+
338
+ ## What's new / updated in this release
339
+
340
+ ### Segmentations replace fixed channels
341
+ | Symbol | Kind | Purpose |
342
+ |---|---|---|
343
+ | `aiSetActiveSegment(label)` | method | Select the active segmentation (label) to paint into — **replaces `aiSetChannel`** |
344
+ | `aiSetSegmentColor(label, rgba)` | method | Set a segmentation's overlay colour (free colour, live 2D) |
345
+ | `aiNewSegment(label)` | method | "New segmentation": freeze current + switch to a new label |
346
+ | `aiClearSegment(label)` | method | Delete a segmentation's voxels (scratch + frozen) |
347
+ | `aiGetScratchSegments()` | method | Per-label serialization for a multi-label / per-colour 3D build |
348
+ | `aiCommitToLayerMapped(layer, mapping)` | method | Merge with an explicit per-segmentation `{label → channel}` map (many-to-one, discard); **union** (fills empty voxels only) |
349
+
350
+ ### Lasso (new prompt tool)
351
+ | Symbol | Kind | Purpose |
352
+ |---|---|---|
353
+ | `"lasso"` in `AiPromptTool` | type | Click-to-place closed-contour tool |
354
+ | `aiFinishLasso()` | method | Close + send the lasso (≥3 vertices) |
355
+ | `aiLassoUndo()` / `aiLassoRedo()` | method | Vertex-level undo/redo |
356
+ | `aiCancelLasso()` | method | Abandon the in-progress lasso |
357
+ | `aiIsLassoEditing()` / `aiLassoVertCount()` | method | Gate the Finish button / keyboard |
358
+ | `aiOnLassoChange(cb)` | method | Reactive vertex-count/editing callback |
359
+ | `AiPromptPayload.lasso` | field | Densified closed contour sent on finish |
360
+
361
+ ### Behaviour changes
362
+ - **`enterAiAssistMode` no longer applies a fixed AI palette** — push segmentation colours via `aiSetSegmentColor`.
363
+ - **`aiSetChannel` removed.** Use `aiSetActiveSegment` + `aiSetSegmentColor`.
364
+ - **Merge is now additive (union).** `aiCommitToLayer` / `aiCommitToLayerMapped` only fill **empty** target voxels — existing annotation is never overwritten (previously the merge overwrote). `aiCommitToLayer` is now an identity-mapping shim over `aiCommitToLayerMapped`.
365
+ - **Point tool** now draws a seed marker per click + a hover crosshair; markers hide once a prediction lands.
366
+ - **Lasso** is discrete click-to-place vertices → smooth, non-self-intersecting closed curve; sent only on finish.
367
+
368
+ ### Unchanged (already present) AI API
369
+ `enterAiAssistMode`, `exitAiAssistMode`, `isAiAssistActive`, `aiSetPromptTool`,
370
+ `aiSetPolarity`, `aiSetScribbleSize`, `aiOnPrompt`, `aiApplyMask`, `aiClearPrompts`,
371
+ `aiCommitRegion`, `aiDiscard`, `aiHasData`, `aiGetScratchSlices`, `aiCommitToLayer`.
372
+
373
+ ---
374
+
375
+ ## Notes & gotchas
376
+
377
+ - **One prompt set = one region.** Prompts accumulate; each prediction replaces the current region. Switching tool or segmentation starts a fresh set. Use `aiNewSegment()` to keep a region and start another.
378
+ - **Slice indices are integers.** The scratch steps by whole slice positions.
379
+ - **`aiApplyMask` expects the RLE format above** (0-run first). Mis-encoding shifts the mask.
380
+ - **`aiGetScratchSegments` / `aiGetScratchSlices` orientation** matches copper3d's own per-slice writer — if your backend writes a NIfTI from it, use the same axis/transpose convention to stay aligned.
381
+ - **Per-segmentation 3D colour is baked at build time** (the backend colours each label's mesh from the colour you send). Recolouring a segmentation after a build needs a rebuild to refresh the 3D.
382
+ - copper3d does not persist anything; `enter`/`exit` is per session. Treat the scratch as ephemeral until you `aiCommitToLayer` or export.
@@ -0,0 +1,238 @@
1
+ # copper3d — Camera Framing & Transitions
2
+
3
+ Framing a camera on its content, and moving it from one pose to another. All exported from
4
+ the package entry (`copper3d`).
5
+
6
+ ::: tip New in 3.8.0
7
+ Additive only. `computeFraming`, `resolveViewPose`, `resolveFarPlane`,
8
+ `Copper3dOrbitControls`, `loadView` and `loadGltf`'s own camera handling are unchanged —
9
+ call none of the below and the camera behaves exactly as it did in 3.7.x.
10
+ :::
11
+
12
+ ---
13
+
14
+ ## 1. `fitDistance()`
15
+
16
+ How far a perspective camera must sit from an object's centre for the whole object to fit
17
+ in frame.
18
+
19
+ ```ts
20
+ fitDistance(bounds: FitBounds, aspect: number, fovDeg: number, margin?: number): number
21
+ ```
22
+
23
+ | parameter | type | default | meaning |
24
+ |---|---|---|---|
25
+ | `bounds` | `FitBounds` | — | The object's axis-aligned size and centre, in scene units. |
26
+ | `aspect` | `number` | — | Viewport width / height. Zero or non-finite is treated as `1`. |
27
+ | `fovDeg` | `number` | — | The camera's **vertical** field of view, in degrees. |
28
+ | `margin` | `number` | `0.85` | Multiplier applied at the end. Smaller means larger on screen. |
29
+
30
+ ### How it differs from `computeFraming`
31
+
32
+ `computeFraming` (unchanged, still used by `Copper3dOrbitControls`) uses the bounding-box
33
+ diagonal and the vertical FOV alone. `fitDistance` differs in two ways.
34
+
35
+ **It takes aspect into account.** Below aspect 1 the *horizontal* field is the narrower of
36
+ the two, and it is the narrower one that has to contain the object. A camera framed on
37
+ vertical FOV alone under-frames every tall, narrow viewport — which is what happens the
38
+ moment a viewer is split into side-by-side panels.
39
+
40
+ **It fits the bounding sphere, not the box.** Fitting the facing box face plus half the
41
+ depth frames each object by whichever dimension happens to point at the camera. A thin
42
+ slab (a mammogram volume, 33 slices) barely moves the camera and fills its panel edge to
43
+ edge, while a near-cubic MRI volume of comparable overall extent is pushed back far enough
44
+ to look half the size beside it. A sphere has no orientation, so comparable objects get
45
+ comparable screen size — and orbiting can no longer push a corner out of frame.
46
+
47
+ ### About `margin`
48
+
49
+ It is deliberately **below 1**. A bounding sphere circumscribes the object — a cube's has
50
+ 1.73× its half-side — so fitting the sphere exactly leaves the object filling well under
51
+ half the frame. Letting the sphere overflow a little is what makes the object itself read
52
+ at a sensible size.
53
+
54
+ This is a tuning knob, not a correctness threshold. `1.35` and `1.05` both read as too
55
+ small against real panels; `0.75` was too large, with the volume's bounding cage pressed
56
+ against the panel edges.
57
+
58
+ ---
59
+
60
+ ## 2. `fitView()`
61
+
62
+ Re-frames a scene on its content, keeping the view preset's direction.
63
+
64
+ ```ts
65
+ // free function
66
+ fitView(
67
+ scene: FitViewScene,
68
+ preset: CameraViewPreset,
69
+ aspect: number,
70
+ bounds: FitBounds,
71
+ margin?: number
72
+ ): boolean
73
+
74
+ // or as a method
75
+ copperSceneOnDemond.fitView(preset, aspect, bounds, margin?)
76
+ ```
77
+
78
+ Returns `false` when there is nothing to do: an orthographic camera (no field of view to
79
+ fit against), or a preset whose eye sits exactly on its target. **Does not render** — the
80
+ caller decides when to draw, which matters under on-demand rendering.
81
+
82
+ ```ts
83
+ const { width, height } = container.getBoundingClientRect();
84
+ const [x, y, z] = volume.RASDimensions;
85
+
86
+ scene.fitView(preset, width / height, {
87
+ width: x, height: y, depth: z,
88
+ center: [0, 0, 0],
89
+ });
90
+ renderer.render();
91
+ ```
92
+
93
+ ### What it keeps and what it replaces
94
+
95
+ A view preset carries a hand-written `eyePosition`, which encodes two different things:
96
+ which way a reader should look at the data, and how far away. Only the first is a
97
+ decision. The second cannot survive a viewport a third as wide as the one it was authored
98
+ against, and hand-written values routinely leave the content filling a quarter of the
99
+ frame.
100
+
101
+ So the preset's **view direction and up vector are kept exactly as authored** — they are
102
+ often a clinical decision — and only the distance is recomputed from `fitDistance`.
103
+
104
+ ### It aims at the object's centre, not the preset's target
105
+
106
+ Presets normally target the origin. That is right for an NRRD volume, whose `RASDimensions`
107
+ describe a box centred there, and wrong for a GLB whose bounding box is not: framing one of
108
+ those from the origin pushes part of it out of frame, which a narrow viewport makes
109
+ obvious. Pass the real centre in `bounds.center` — `[0, 0, 0]` for a volume makes this a
110
+ no-op.
111
+
112
+ ### It syncs `controls.target`
113
+
114
+ **This is the load-bearing half.** Nothing syncs the controls' orbit pivot with
115
+ `camera.lookAt()`, so without it the user's next drag calls `controls.update()`, which
116
+ re-aims the camera at whatever `target` still held — silently undoing everything the
117
+ framing just did. `handleResize()` is called too, for the trackball variants that cache
118
+ the canvas's page box.
119
+
120
+ ---
121
+
122
+ ## 2a. `setCameraPose()` <Badge type="tip" text="3.9.0" />
123
+
124
+ ```ts
125
+ setCameraPose(scene: PosableScene, pose: Pose): void
126
+
127
+ // or as a method
128
+ copperSceneOnDemond.setCameraPose(pose)
129
+ ```
130
+
131
+ `fitView` re-frames on content. This is the general case: a pose you already
132
+ have — the end of a flight from `interpolateFlightPose`, a saved bookmark, a
133
+ `viewPointToPose(preset)` — written onto the camera.
134
+
135
+ ```ts
136
+ scene.setCameraPose(Copper.viewPointToPose(preset));
137
+ renderer.render();
138
+ ```
139
+
140
+ It is four assignments, and the fourth is the one everybody forgets:
141
+
142
+ ```ts
143
+ camera.position.set(...)
144
+ camera.up.set(...) // before lookAt, which builds the basis from it
145
+ camera.lookAt(...)
146
+ controls.target.set(...) // <- this one
147
+ ```
148
+
149
+ Leave the last line out and everything looks right until the user touches the
150
+ mouse: the first drag calls `controls.update()`, which re-aims the camera at
151
+ the stale `target`. The symptom — "the camera jumps back the moment I drag" —
152
+ points at the controls rather than at the code that caused it.
153
+
154
+ Does **not** render. The caller decides when to draw, which matters under
155
+ on-demand rendering where this may be one of several changes in a frame.
156
+
157
+ ---
158
+
159
+ ## 3. Pose interpolation — `Controls/cameraTransitions`
160
+
161
+ Pure numeric helpers for moving a camera. **Dependency-free**: plain numbers and
162
+ `[x, y, z]` tuples, no three.js objects in or out. That makes them unit-testable with no
163
+ WebGL, and usable by a consumer that has its own copy of three without anything crossing
164
+ that boundary.
165
+
166
+ ```ts
167
+ interface Pose {
168
+ position: [number, number, number];
169
+ up: [number, number, number];
170
+ /** The look-at point — the controls' orbit pivot, not the camera's position. */
171
+ target: [number, number, number];
172
+ }
173
+ ```
174
+
175
+ | function | signature | purpose |
176
+ |---|---|---|
177
+ | `easeInOutCubic` | `(t: number) => number` | Standard ease. Clamps out-of-range input. |
178
+ | `viewPointToPose` | `(vp: CameraViewPreset) => Pose` | Reads a view preset as a `Pose`. |
179
+ | `interpolateFlightPose` | `(from: Pose, to: Pose, t: number) => Pose` | Interpolates a camera between two poses. `t` is expected already eased. |
180
+ | `orbitStepPose` | `(pose: Pose, yawRad: number, pitchRad: number) => Pose` | Orbits around the pose's own pivot. |
181
+ | `zoomPose` | `(pose: Pose, factor: number, minDistance?: number) => Pose` | Scales the distance from the pivot. |
182
+ | `poseDistance` | `(pose: Pose) => number` | The orbit radius. |
183
+ | `rotateAroundAxis` | `(v, axis, angleRad) => [number, number, number]` | Rodrigues' rotation. |
184
+ | `orbitSwingAngle` | `(t: number, turns: number) => number` | Swing angle for an entrance orbit. |
185
+
186
+ ### Why `interpolateFlightPose` uses a quaternion, not two lerps
187
+
188
+ The pivot lerps from one target to the other, and the camera's **orientation** — both its
189
+ direction from the pivot and its up vector — is carried by a single rotation built from
190
+ the two poses' full orthonormal bases. Not by interpolating `dir` and `up` independently.
191
+
192
+ That is a correctness requirement. Real preset data routinely contains **antipodal up
193
+ vectors on the same view axis** — two views of one volume authored from opposite
194
+ conventions, e.g. `up: [0,-1,0]` at eye `[0,0,2000]` and `up: [0,1,0]` at eye `[0,0,650]`.
195
+ A plain `lerp(upFrom, upTo, t)` passes through the exact zero vector at `t = 0.5`, where
196
+ `normalize` has no correct answer and falls back to an axis parallel to the view
197
+ direction: **the camera holds upside-down for the first half of the flight, then snaps 180
198
+ degrees in a single frame.**
199
+
200
+ Composing the two bases into a relative rotation and converting that matrix to a
201
+ quaternion (largest-diagonal-term method) has no such degeneracy — for a valid rotation
202
+ matrix at least one branch's divisor is bounded away from zero. The same case becomes a
203
+ well-defined 180-degree roll about the shared axis: a smooth roll through the midpoint.
204
+ The same construction also covers two antipodal camera *positions* about one target, where
205
+ a vector-pair slerp flips back and forth near `t = 1`.
206
+
207
+ `from.position` is reproduced exactly at `t = 0` and `to.position` at `t = 1`. `up` is
208
+ likewise exact **when** each pose's own `up` is already perpendicular to its own view
209
+ direction; one that leans toward the view axis is silently squared up, which is by design
210
+ — it is not a meaningful camera roll.
211
+
212
+ ### `orbitStepPose` notes
213
+
214
+ The pivot and the orbit radius are both untouched, so a run of key presses can never walk
215
+ the camera away from what it is looking at. Pitch is applied about the **yawed** right
216
+ vector, not the original one — rotating about a stale axis makes a diagonal (left + up)
217
+ key combination drift off the sphere instead of tracing it.
218
+
219
+ ### `orbitSwingAngle` notes
220
+
221
+ `turns` is a **swing amplitude, not a net rotation**. `sin(t·π)` goes out and comes back to
222
+ zero, so the camera always ends exactly on the framed preset view (`t = 1` → angle 0)
223
+ however large `turns` is. Do not "fix" this into a net rotation; that ends the intro
224
+ off-preset.
225
+
226
+ ---
227
+
228
+ ## Types
229
+
230
+ ```ts
231
+ interface FitBounds {
232
+ width: number;
233
+ height: number;
234
+ depth: number;
235
+ /** The box's centre in scene units. `[0, 0, 0]` for an NRRD volume. */
236
+ center: [number, number, number];
237
+ }
238
+ ```