copper3d 4.1.0 → 4.1.2
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.
- package/README.md +0 -4
- package/ai-index/guides/nrrd-tools.md +10 -0
- package/ai-index/guides/orientation.md +8 -0
- package/ai-index/manifest.json +4 -4
- package/ai-index/symbols.json +1 -1
- package/dist/Scene/copperSceneOnDemond.d.ts +16 -0
- package/dist/Scene/copperSceneOnDemond.js +41 -0
- package/dist/Scene/copperSceneOnDemond.js.map +1 -1
- package/dist/Utils/segmentation/DrawToolCore.d.ts +18 -1
- package/dist/Utils/segmentation/DrawToolCore.js +31 -6
- package/dist/Utils/segmentation/DrawToolCore.js.map +1 -1
- package/dist/Utils/segmentation/NrrdTools.d.ts +3 -2
- package/dist/Utils/segmentation/NrrdTools.js +3 -2
- package/dist/Utils/segmentation/NrrdTools.js.map +1 -1
- package/dist/bundle.esm.mjs +95 -16
- package/dist/bundle.umd.js +99 -20
- package/dist/orientation.cjs +276 -0
- package/dist/orientation.mjs +262 -0
- package/dist/types/Scene/copperSceneOnDemond.d.ts +16 -0
- package/dist/types/Utils/segmentation/DrawToolCore.d.ts +18 -1
- package/dist/types/Utils/segmentation/NrrdTools.d.ts +3 -2
- package/package.json +6 -1
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The canonical voxel order, and the rule that puts any volume into it.
|
|
7
|
+
*
|
|
8
|
+
* Canonical order: voxel index i increases toward the patient's Left, j toward Posterior, k
|
|
9
|
+
* toward Superior. Axis codes use the TOWARD convention of DICOM, nibabel and SimpleITK, so "LPS"
|
|
10
|
+
* names that order (legacy ITK and ITK-SNAP call the same order "RAI").
|
|
11
|
+
*
|
|
12
|
+
* Each native axis is assigned the anatomical axis it is nearest to and flipped when it points the
|
|
13
|
+
* other way. That is a permutation and flips, never a resampling, so obliquity stays in the
|
|
14
|
+
* geometry instead of being snapped away. With the voxels in this order, the fixed per-axis display
|
|
15
|
+
* mapping (SliceRenderPipeline.flipDisplayImageByAxis) shows every volume in the radiological
|
|
16
|
+
* convention, whatever order its file stores.
|
|
17
|
+
*
|
|
18
|
+
* The backend (app/geometry/canonical.py) implements the same rule for everything it reads and
|
|
19
|
+
* writes. The app holds both to one fixture, annotator-backend/tests/fixtures/orientation_cases.json.
|
|
20
|
+
*
|
|
21
|
+
* Pure: no DOM and no three, so it runs inside the NRRD worker as well as on the main thread.
|
|
22
|
+
*/
|
|
23
|
+
/** A volume whose patient orientation cannot be established. It is refused, never guessed. */
|
|
24
|
+
class OrientationError extends Error {
|
|
25
|
+
constructor(code, detail) {
|
|
26
|
+
super(`${code}: ${detail}`);
|
|
27
|
+
this.name = "OrientationError";
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.detail = detail;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** A screen axis more than 1 degree off an anatomical axis also gets that axis's letter (the rule
|
|
33
|
+
* of 3D Slicer's GetDirectionLabel). */
|
|
34
|
+
const LABEL_TOL = Math.sin((1 * Math.PI) / 180);
|
|
35
|
+
/** At 45 degrees an axis is equally near two anatomical axes, so it has no nearest one. */
|
|
36
|
+
const AMBIGUOUS_COS = Math.cos((45 * Math.PI) / 180) + 1e-9;
|
|
37
|
+
/** NRRD space -> the per-component signs that turn its coordinates into LPS. */
|
|
38
|
+
const LPS_SIGNS = {
|
|
39
|
+
"left-posterior-superior": [1, 1, 1],
|
|
40
|
+
lps: [1, 1, 1],
|
|
41
|
+
"right-anterior-superior": [-1, -1, 1],
|
|
42
|
+
ras: [-1, -1, 1],
|
|
43
|
+
"left-anterior-superior": [1, -1, 1],
|
|
44
|
+
las: [1, -1, 1],
|
|
45
|
+
};
|
|
46
|
+
const TIME_SPACES = new Set(["rast", "last", "lpst"]);
|
|
47
|
+
const NON_ANATOMICAL_SPACES = new Set(["3d-right-handed", "3d-left-handed"]);
|
|
48
|
+
/** TOWARD letter -> [patient axis in LPS, sign]. */
|
|
49
|
+
const LETTERS = {
|
|
50
|
+
L: [0, 1], R: [0, -1], P: [1, 1], A: [1, -1], S: [2, 1], I: [2, -1],
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Each view's screen-right and screen-down steps in canonical index space, as
|
|
54
|
+
* SliceRenderPipeline.flipDisplayImageByAxis draws them. A layout change there changes this
|
|
55
|
+
* table in the same commit.
|
|
56
|
+
*/
|
|
57
|
+
const VIEW_LAYOUT = {
|
|
58
|
+
z: [[1, 0, 0], [0, 1, 0]], // axial: right = +i, down = +j
|
|
59
|
+
y: [[1, 0, 0], [0, 0, -1]], // coronal: right = +i, down = -k
|
|
60
|
+
x: [[0, 1, 0], [0, 0, -1]], // sagittal: right = +j, down = -k
|
|
61
|
+
};
|
|
62
|
+
/** The longest header looked for; NRRD headers are a few hundred bytes. */
|
|
63
|
+
const MAX_HEADER_BYTES = 64 * 1024;
|
|
64
|
+
/**
|
|
65
|
+
* The text header of an NRRD document: everything before the first blank line. Read here instead
|
|
66
|
+
* of taken from three's NRRDLoader, which fills in identity directions when a file has none and so
|
|
67
|
+
* makes "no orientation" indistinguishable from "identity".
|
|
68
|
+
*/
|
|
69
|
+
function nrrdHeaderText(buffer) {
|
|
70
|
+
const bytes = new Uint8Array(buffer, 0, Math.min(buffer.byteLength, MAX_HEADER_BYTES));
|
|
71
|
+
if (String.fromCharCode(...bytes.subarray(0, 4)) !== "NRRD")
|
|
72
|
+
throw new Error("not an NRRD document (no NRRD magic)");
|
|
73
|
+
for (let n = 0; n < bytes.length - 1; n++) {
|
|
74
|
+
if (bytes[n] !== 0x0a)
|
|
75
|
+
continue;
|
|
76
|
+
const blankLf = bytes[n + 1] === 0x0a;
|
|
77
|
+
const blankCrlf = bytes[n + 1] === 0x0d && bytes[n + 2] === 0x0a;
|
|
78
|
+
if (blankLf || blankCrlf) {
|
|
79
|
+
const end = n > 0 && bytes[n - 1] === 0x0d ? n - 1 : n;
|
|
80
|
+
return new TextDecoder("latin1").decode(bytes.subarray(0, end));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
throw new Error("NRRD header has no terminating blank line");
|
|
84
|
+
}
|
|
85
|
+
/** Reads the orientation fields from an NRRD header's text. Comments and `key:=value` pairs are skipped. */
|
|
86
|
+
function readNrrdOrientationFields(headerText) {
|
|
87
|
+
var _a;
|
|
88
|
+
const out = { space: null, sizes: [], spaceDirections: null, spaceOrigin: null };
|
|
89
|
+
for (const line of headerText.split(/\r?\n/)) {
|
|
90
|
+
if (line.startsWith("#"))
|
|
91
|
+
continue;
|
|
92
|
+
const colon = line.indexOf(":");
|
|
93
|
+
if (colon < 0 || line[colon + 1] === "=")
|
|
94
|
+
continue;
|
|
95
|
+
const name = line.slice(0, colon).trim().toLowerCase();
|
|
96
|
+
const value = line.slice(colon + 1).trim();
|
|
97
|
+
if (name === "space")
|
|
98
|
+
out.space = value;
|
|
99
|
+
else if (name === "sizes")
|
|
100
|
+
out.sizes = value.split(/\s+/).map((n) => parseInt(n, 10));
|
|
101
|
+
else if (name === "space directions")
|
|
102
|
+
out.spaceDirections = parseVectors(value);
|
|
103
|
+
else if (name === "space origin")
|
|
104
|
+
out.spaceOrigin = (_a = parseVectors(value)[0]) !== null && _a !== void 0 ? _a : null;
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
/** An NRRD's geometry in LPS. Throws OrientationError when its patient orientation cannot be established. */
|
|
109
|
+
function geometryFromNrrd(fields) {
|
|
110
|
+
var _a;
|
|
111
|
+
const space = (_a = fields.space) === null || _a === void 0 ? void 0 : _a.trim();
|
|
112
|
+
if (!space) {
|
|
113
|
+
throw new OrientationError("no_space", "the header has no 'space' field, so its patient orientation is unknown");
|
|
114
|
+
}
|
|
115
|
+
const name = space.toLowerCase();
|
|
116
|
+
if (name.endsWith("-time") || TIME_SPACES.has(name)) {
|
|
117
|
+
throw new OrientationError("time_space", `space '${space}' is a time series; only 3D volumes are supported`);
|
|
118
|
+
}
|
|
119
|
+
if (name === "scanner-xyz") {
|
|
120
|
+
throw new OrientationError("scanner_space", "space 'scanner-xyz' is in scanner coordinates, whose patient orientation depends on how the patient lay (breast MRI is acquired prone)");
|
|
121
|
+
}
|
|
122
|
+
if (NON_ANATOMICAL_SPACES.has(name)) {
|
|
123
|
+
throw new OrientationError("non_anatomical_space", `space '${space}' has no anatomical meaning`);
|
|
124
|
+
}
|
|
125
|
+
const signs = LPS_SIGNS[name];
|
|
126
|
+
if (!signs)
|
|
127
|
+
throw new OrientationError("unknown_space", `space '${space}' is not a recognised anatomical space`);
|
|
128
|
+
const vectors = fields.spaceDirections;
|
|
129
|
+
if (!vectors || vectors.length === 0)
|
|
130
|
+
throw new OrientationError("no_directions", "the header has no 'space directions'");
|
|
131
|
+
if (fields.sizes.length !== 3 || vectors.length !== 3 || vectors.some((v) => v === null || v.length !== 3)) {
|
|
132
|
+
throw new OrientationError("not_3d", `expected 3 spatial axes, got sizes [${fields.sizes.join(", ")}]`);
|
|
133
|
+
}
|
|
134
|
+
if (!fields.spaceOrigin || fields.spaceOrigin.length !== 3) {
|
|
135
|
+
throw new OrientationError("no_origin", "the header has no 'space origin', so the grid has no patient position");
|
|
136
|
+
}
|
|
137
|
+
// "+ 0" turns a negated zero into 0, so a converted axis compares equal to the literal.
|
|
138
|
+
const directions = vectors.map((v) => v.map((c, x) => c * signs[x] + 0));
|
|
139
|
+
const origin = fields.spaceOrigin.map((c, x) => c * signs[x] + 0);
|
|
140
|
+
return checked({ dims: [fields.sizes[0], fields.sizes[1], fields.sizes[2]], directions, origin });
|
|
141
|
+
}
|
|
142
|
+
/** The transform into the voxel order that `codes` names (TOWARD), e.g. "LPS" or "RAI". */
|
|
143
|
+
function orientationTransform(geometry, codes = "LPS") {
|
|
144
|
+
const target = parseCodes(codes);
|
|
145
|
+
const spacing = spacingOf(geometry);
|
|
146
|
+
const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
|
|
147
|
+
const nearest = units.map((u) => [0, 1, 2].reduce((best, x) => (Math.abs(u[x]) > Math.abs(u[best]) ? x : best), 0));
|
|
148
|
+
const strength = units.map((u, a) => Math.abs(u[nearest[a]]));
|
|
149
|
+
const obliquity = strength.map((s) => (Math.acos(Math.min(1, s)) * 180) / Math.PI);
|
|
150
|
+
if (strength.some((s) => s <= AMBIGUOUS_COS) || new Set(nearest).size !== 3) {
|
|
151
|
+
throw new OrientationError("ambiguous_oblique", `a voxel axis is ${Math.max(...obliquity).toFixed(1)} degrees from every anatomical axis, so it has no nearest one`);
|
|
152
|
+
}
|
|
153
|
+
const perm = [0, 0, 0];
|
|
154
|
+
const flip = [false, false, false];
|
|
155
|
+
const obliquityDeg = [0, 0, 0];
|
|
156
|
+
target.forEach(([patientAxis, sign], axis) => {
|
|
157
|
+
const native = nearest.indexOf(patientAxis);
|
|
158
|
+
perm[axis] = native;
|
|
159
|
+
flip[axis] = Math.sign(units[native][patientAxis]) !== sign;
|
|
160
|
+
obliquityDeg[axis] = obliquity[native];
|
|
161
|
+
});
|
|
162
|
+
return { perm, flip, obliquityDeg };
|
|
163
|
+
}
|
|
164
|
+
/** The transform into the canonical order (i->L, j->P, k->S). */
|
|
165
|
+
function canonicalTransform(geometry) {
|
|
166
|
+
return orientationTransform(geometry, "LPS");
|
|
167
|
+
}
|
|
168
|
+
function isIdentityTransform(transform) {
|
|
169
|
+
return transform.perm[0] === 0 && transform.perm[1] === 1 && transform.perm[2] === 2 && !transform.flip.some(Boolean);
|
|
170
|
+
}
|
|
171
|
+
/** The same grid described in the transform's voxel order. The origin moves to the new first voxel. */
|
|
172
|
+
function reorientedGeometry(geometry, transform) {
|
|
173
|
+
const origin = [...geometry.origin];
|
|
174
|
+
transform.perm.forEach((native, axis) => {
|
|
175
|
+
if (!transform.flip[axis])
|
|
176
|
+
return;
|
|
177
|
+
for (let x = 0; x < 3; x++)
|
|
178
|
+
origin[x] += (geometry.dims[native] - 1) * geometry.directions[native][x];
|
|
179
|
+
});
|
|
180
|
+
return {
|
|
181
|
+
dims: transform.perm.map((native) => geometry.dims[native]),
|
|
182
|
+
// "+ 0" turns a negated zero into 0 (see geometryFromNrrd).
|
|
183
|
+
directions: transform.perm.map((native, axis) => geometry.directions[native].map((c) => (transform.flip[axis] ? -c : c) + 0)),
|
|
184
|
+
origin,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Voxels (i fastest, as NRRD stores them) rewritten in the transform's order. The identity
|
|
189
|
+
* returns `data` itself, with no copy; any other transform returns a new array of the same type.
|
|
190
|
+
*/
|
|
191
|
+
function reorientVoxels(data, dims, transform) {
|
|
192
|
+
if (data.length !== dims[0] * dims[1] * dims[2]) {
|
|
193
|
+
throw new Error(`voxel count ${data.length} does not fill a ${dims.join("x")} grid`);
|
|
194
|
+
}
|
|
195
|
+
if (isIdentityTransform(transform))
|
|
196
|
+
return data;
|
|
197
|
+
const nativeStride = [1, dims[0], dims[0] * dims[1]];
|
|
198
|
+
const outDims = transform.perm.map((native) => dims[native]);
|
|
199
|
+
const step = transform.perm.map((native, axis) => (transform.flip[axis] ? -1 : 1) * nativeStride[native]);
|
|
200
|
+
let start = 0;
|
|
201
|
+
transform.perm.forEach((native, axis) => {
|
|
202
|
+
if (transform.flip[axis])
|
|
203
|
+
start += (dims[native] - 1) * nativeStride[native];
|
|
204
|
+
});
|
|
205
|
+
const out = new data.constructor(data.length);
|
|
206
|
+
let n = 0;
|
|
207
|
+
for (let c2 = 0, base2 = start; c2 < outDims[2]; c2++, base2 += step[2]) {
|
|
208
|
+
for (let c1 = 0, base1 = base2; c1 < outDims[1]; c1++, base1 += step[1]) {
|
|
209
|
+
for (let c0 = 0, index = base1; c0 < outDims[0]; c0++, index += step[0]) {
|
|
210
|
+
out[n++] = data[index];
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
/** The orientation letters at each screen edge of a view of a canonical grid. */
|
|
217
|
+
function viewLabels(axis, geometry) {
|
|
218
|
+
const spacing = spacingOf(geometry);
|
|
219
|
+
const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
|
|
220
|
+
const along = (step) => [0, 1, 2].map((x) => step[0] * units[0][x] + step[1] * units[1][x] + step[2] * units[2][x]);
|
|
221
|
+
const [rightStep, downStep] = VIEW_LAYOUT[axis];
|
|
222
|
+
const right = along(rightStep);
|
|
223
|
+
const down = along(downStep);
|
|
224
|
+
const negate = (v) => v.map((c) => -c);
|
|
225
|
+
return { left: letters(negate(right)), right: letters(right), top: letters(negate(down)), bottom: letters(down) };
|
|
226
|
+
}
|
|
227
|
+
function spacingOf(geometry) {
|
|
228
|
+
return geometry.directions.map((d) => Math.hypot(d[0], d[1], d[2]));
|
|
229
|
+
}
|
|
230
|
+
function letters(direction) {
|
|
231
|
+
return [0, 1, 2]
|
|
232
|
+
.filter((x) => Math.abs(direction[x]) > LABEL_TOL)
|
|
233
|
+
.sort((a, b) => Math.abs(direction[b]) - Math.abs(direction[a]))
|
|
234
|
+
.map((x) => (direction[x] > 0 ? "LPS" : "RAI")[x])
|
|
235
|
+
.join("");
|
|
236
|
+
}
|
|
237
|
+
function parseCodes(codes) {
|
|
238
|
+
if (codes.length !== 3 || [...codes].some((c) => !(c in LETTERS))) {
|
|
239
|
+
throw new Error(`not a three-letter orientation code: '${codes}'`);
|
|
240
|
+
}
|
|
241
|
+
const target = [...codes].map((c) => LETTERS[c]);
|
|
242
|
+
if (new Set(target.map(([patientAxis]) => patientAxis)).size !== 3) {
|
|
243
|
+
throw new Error(`orientation code '${codes}' names a patient axis twice`);
|
|
244
|
+
}
|
|
245
|
+
return target;
|
|
246
|
+
}
|
|
247
|
+
function parseVectors(text) {
|
|
248
|
+
const out = [];
|
|
249
|
+
for (const match of text.matchAll(/\(([^)]*)\)|none/gi)) {
|
|
250
|
+
out.push(match[1] === undefined ? null : match[1].split(",").map((c) => parseFloat(c)));
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
function checked(geometry) {
|
|
255
|
+
const values = [...geometry.directions.flat(), ...geometry.origin];
|
|
256
|
+
if (values.some((v) => !Number.isFinite(v))) {
|
|
257
|
+
throw new OrientationError("degenerate", "the geometry contains non-finite values");
|
|
258
|
+
}
|
|
259
|
+
const spacing = spacingOf(geometry);
|
|
260
|
+
if (spacing.some((s) => s <= 1e-12) || geometry.dims.some((n) => !(n >= 1))) {
|
|
261
|
+
throw new OrientationError("degenerate", `a voxel axis has no extent (dims [${geometry.dims.join(", ")}], spacing [${spacing.join(", ")}])`);
|
|
262
|
+
}
|
|
263
|
+
return geometry;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
exports.OrientationError = OrientationError;
|
|
267
|
+
exports.canonicalTransform = canonicalTransform;
|
|
268
|
+
exports.geometryFromNrrd = geometryFromNrrd;
|
|
269
|
+
exports.isIdentityTransform = isIdentityTransform;
|
|
270
|
+
exports.nrrdHeaderText = nrrdHeaderText;
|
|
271
|
+
exports.orientationTransform = orientationTransform;
|
|
272
|
+
exports.readNrrdOrientationFields = readNrrdOrientationFields;
|
|
273
|
+
exports.reorientVoxels = reorientVoxels;
|
|
274
|
+
exports.reorientedGeometry = reorientedGeometry;
|
|
275
|
+
exports.spacingOf = spacingOf;
|
|
276
|
+
exports.viewLabels = viewLabels;
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The canonical voxel order, and the rule that puts any volume into it.
|
|
3
|
+
*
|
|
4
|
+
* Canonical order: voxel index i increases toward the patient's Left, j toward Posterior, k
|
|
5
|
+
* toward Superior. Axis codes use the TOWARD convention of DICOM, nibabel and SimpleITK, so "LPS"
|
|
6
|
+
* names that order (legacy ITK and ITK-SNAP call the same order "RAI").
|
|
7
|
+
*
|
|
8
|
+
* Each native axis is assigned the anatomical axis it is nearest to and flipped when it points the
|
|
9
|
+
* other way. That is a permutation and flips, never a resampling, so obliquity stays in the
|
|
10
|
+
* geometry instead of being snapped away. With the voxels in this order, the fixed per-axis display
|
|
11
|
+
* mapping (SliceRenderPipeline.flipDisplayImageByAxis) shows every volume in the radiological
|
|
12
|
+
* convention, whatever order its file stores.
|
|
13
|
+
*
|
|
14
|
+
* The backend (app/geometry/canonical.py) implements the same rule for everything it reads and
|
|
15
|
+
* writes. The app holds both to one fixture, annotator-backend/tests/fixtures/orientation_cases.json.
|
|
16
|
+
*
|
|
17
|
+
* Pure: no DOM and no three, so it runs inside the NRRD worker as well as on the main thread.
|
|
18
|
+
*/
|
|
19
|
+
/** A volume whose patient orientation cannot be established. It is refused, never guessed. */
|
|
20
|
+
class OrientationError extends Error {
|
|
21
|
+
constructor(code, detail) {
|
|
22
|
+
super(`${code}: ${detail}`);
|
|
23
|
+
this.name = "OrientationError";
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.detail = detail;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** A screen axis more than 1 degree off an anatomical axis also gets that axis's letter (the rule
|
|
29
|
+
* of 3D Slicer's GetDirectionLabel). */
|
|
30
|
+
const LABEL_TOL = Math.sin((1 * Math.PI) / 180);
|
|
31
|
+
/** At 45 degrees an axis is equally near two anatomical axes, so it has no nearest one. */
|
|
32
|
+
const AMBIGUOUS_COS = Math.cos((45 * Math.PI) / 180) + 1e-9;
|
|
33
|
+
/** NRRD space -> the per-component signs that turn its coordinates into LPS. */
|
|
34
|
+
const LPS_SIGNS = {
|
|
35
|
+
"left-posterior-superior": [1, 1, 1],
|
|
36
|
+
lps: [1, 1, 1],
|
|
37
|
+
"right-anterior-superior": [-1, -1, 1],
|
|
38
|
+
ras: [-1, -1, 1],
|
|
39
|
+
"left-anterior-superior": [1, -1, 1],
|
|
40
|
+
las: [1, -1, 1],
|
|
41
|
+
};
|
|
42
|
+
const TIME_SPACES = new Set(["rast", "last", "lpst"]);
|
|
43
|
+
const NON_ANATOMICAL_SPACES = new Set(["3d-right-handed", "3d-left-handed"]);
|
|
44
|
+
/** TOWARD letter -> [patient axis in LPS, sign]. */
|
|
45
|
+
const LETTERS = {
|
|
46
|
+
L: [0, 1], R: [0, -1], P: [1, 1], A: [1, -1], S: [2, 1], I: [2, -1],
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Each view's screen-right and screen-down steps in canonical index space, as
|
|
50
|
+
* SliceRenderPipeline.flipDisplayImageByAxis draws them. A layout change there changes this
|
|
51
|
+
* table in the same commit.
|
|
52
|
+
*/
|
|
53
|
+
const VIEW_LAYOUT = {
|
|
54
|
+
z: [[1, 0, 0], [0, 1, 0]], // axial: right = +i, down = +j
|
|
55
|
+
y: [[1, 0, 0], [0, 0, -1]], // coronal: right = +i, down = -k
|
|
56
|
+
x: [[0, 1, 0], [0, 0, -1]], // sagittal: right = +j, down = -k
|
|
57
|
+
};
|
|
58
|
+
/** The longest header looked for; NRRD headers are a few hundred bytes. */
|
|
59
|
+
const MAX_HEADER_BYTES = 64 * 1024;
|
|
60
|
+
/**
|
|
61
|
+
* The text header of an NRRD document: everything before the first blank line. Read here instead
|
|
62
|
+
* of taken from three's NRRDLoader, which fills in identity directions when a file has none and so
|
|
63
|
+
* makes "no orientation" indistinguishable from "identity".
|
|
64
|
+
*/
|
|
65
|
+
function nrrdHeaderText(buffer) {
|
|
66
|
+
const bytes = new Uint8Array(buffer, 0, Math.min(buffer.byteLength, MAX_HEADER_BYTES));
|
|
67
|
+
if (String.fromCharCode(...bytes.subarray(0, 4)) !== "NRRD")
|
|
68
|
+
throw new Error("not an NRRD document (no NRRD magic)");
|
|
69
|
+
for (let n = 0; n < bytes.length - 1; n++) {
|
|
70
|
+
if (bytes[n] !== 0x0a)
|
|
71
|
+
continue;
|
|
72
|
+
const blankLf = bytes[n + 1] === 0x0a;
|
|
73
|
+
const blankCrlf = bytes[n + 1] === 0x0d && bytes[n + 2] === 0x0a;
|
|
74
|
+
if (blankLf || blankCrlf) {
|
|
75
|
+
const end = n > 0 && bytes[n - 1] === 0x0d ? n - 1 : n;
|
|
76
|
+
return new TextDecoder("latin1").decode(bytes.subarray(0, end));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
throw new Error("NRRD header has no terminating blank line");
|
|
80
|
+
}
|
|
81
|
+
/** Reads the orientation fields from an NRRD header's text. Comments and `key:=value` pairs are skipped. */
|
|
82
|
+
function readNrrdOrientationFields(headerText) {
|
|
83
|
+
var _a;
|
|
84
|
+
const out = { space: null, sizes: [], spaceDirections: null, spaceOrigin: null };
|
|
85
|
+
for (const line of headerText.split(/\r?\n/)) {
|
|
86
|
+
if (line.startsWith("#"))
|
|
87
|
+
continue;
|
|
88
|
+
const colon = line.indexOf(":");
|
|
89
|
+
if (colon < 0 || line[colon + 1] === "=")
|
|
90
|
+
continue;
|
|
91
|
+
const name = line.slice(0, colon).trim().toLowerCase();
|
|
92
|
+
const value = line.slice(colon + 1).trim();
|
|
93
|
+
if (name === "space")
|
|
94
|
+
out.space = value;
|
|
95
|
+
else if (name === "sizes")
|
|
96
|
+
out.sizes = value.split(/\s+/).map((n) => parseInt(n, 10));
|
|
97
|
+
else if (name === "space directions")
|
|
98
|
+
out.spaceDirections = parseVectors(value);
|
|
99
|
+
else if (name === "space origin")
|
|
100
|
+
out.spaceOrigin = (_a = parseVectors(value)[0]) !== null && _a !== void 0 ? _a : null;
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
/** An NRRD's geometry in LPS. Throws OrientationError when its patient orientation cannot be established. */
|
|
105
|
+
function geometryFromNrrd(fields) {
|
|
106
|
+
var _a;
|
|
107
|
+
const space = (_a = fields.space) === null || _a === void 0 ? void 0 : _a.trim();
|
|
108
|
+
if (!space) {
|
|
109
|
+
throw new OrientationError("no_space", "the header has no 'space' field, so its patient orientation is unknown");
|
|
110
|
+
}
|
|
111
|
+
const name = space.toLowerCase();
|
|
112
|
+
if (name.endsWith("-time") || TIME_SPACES.has(name)) {
|
|
113
|
+
throw new OrientationError("time_space", `space '${space}' is a time series; only 3D volumes are supported`);
|
|
114
|
+
}
|
|
115
|
+
if (name === "scanner-xyz") {
|
|
116
|
+
throw new OrientationError("scanner_space", "space 'scanner-xyz' is in scanner coordinates, whose patient orientation depends on how the patient lay (breast MRI is acquired prone)");
|
|
117
|
+
}
|
|
118
|
+
if (NON_ANATOMICAL_SPACES.has(name)) {
|
|
119
|
+
throw new OrientationError("non_anatomical_space", `space '${space}' has no anatomical meaning`);
|
|
120
|
+
}
|
|
121
|
+
const signs = LPS_SIGNS[name];
|
|
122
|
+
if (!signs)
|
|
123
|
+
throw new OrientationError("unknown_space", `space '${space}' is not a recognised anatomical space`);
|
|
124
|
+
const vectors = fields.spaceDirections;
|
|
125
|
+
if (!vectors || vectors.length === 0)
|
|
126
|
+
throw new OrientationError("no_directions", "the header has no 'space directions'");
|
|
127
|
+
if (fields.sizes.length !== 3 || vectors.length !== 3 || vectors.some((v) => v === null || v.length !== 3)) {
|
|
128
|
+
throw new OrientationError("not_3d", `expected 3 spatial axes, got sizes [${fields.sizes.join(", ")}]`);
|
|
129
|
+
}
|
|
130
|
+
if (!fields.spaceOrigin || fields.spaceOrigin.length !== 3) {
|
|
131
|
+
throw new OrientationError("no_origin", "the header has no 'space origin', so the grid has no patient position");
|
|
132
|
+
}
|
|
133
|
+
// "+ 0" turns a negated zero into 0, so a converted axis compares equal to the literal.
|
|
134
|
+
const directions = vectors.map((v) => v.map((c, x) => c * signs[x] + 0));
|
|
135
|
+
const origin = fields.spaceOrigin.map((c, x) => c * signs[x] + 0);
|
|
136
|
+
return checked({ dims: [fields.sizes[0], fields.sizes[1], fields.sizes[2]], directions, origin });
|
|
137
|
+
}
|
|
138
|
+
/** The transform into the voxel order that `codes` names (TOWARD), e.g. "LPS" or "RAI". */
|
|
139
|
+
function orientationTransform(geometry, codes = "LPS") {
|
|
140
|
+
const target = parseCodes(codes);
|
|
141
|
+
const spacing = spacingOf(geometry);
|
|
142
|
+
const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
|
|
143
|
+
const nearest = units.map((u) => [0, 1, 2].reduce((best, x) => (Math.abs(u[x]) > Math.abs(u[best]) ? x : best), 0));
|
|
144
|
+
const strength = units.map((u, a) => Math.abs(u[nearest[a]]));
|
|
145
|
+
const obliquity = strength.map((s) => (Math.acos(Math.min(1, s)) * 180) / Math.PI);
|
|
146
|
+
if (strength.some((s) => s <= AMBIGUOUS_COS) || new Set(nearest).size !== 3) {
|
|
147
|
+
throw new OrientationError("ambiguous_oblique", `a voxel axis is ${Math.max(...obliquity).toFixed(1)} degrees from every anatomical axis, so it has no nearest one`);
|
|
148
|
+
}
|
|
149
|
+
const perm = [0, 0, 0];
|
|
150
|
+
const flip = [false, false, false];
|
|
151
|
+
const obliquityDeg = [0, 0, 0];
|
|
152
|
+
target.forEach(([patientAxis, sign], axis) => {
|
|
153
|
+
const native = nearest.indexOf(patientAxis);
|
|
154
|
+
perm[axis] = native;
|
|
155
|
+
flip[axis] = Math.sign(units[native][patientAxis]) !== sign;
|
|
156
|
+
obliquityDeg[axis] = obliquity[native];
|
|
157
|
+
});
|
|
158
|
+
return { perm, flip, obliquityDeg };
|
|
159
|
+
}
|
|
160
|
+
/** The transform into the canonical order (i->L, j->P, k->S). */
|
|
161
|
+
function canonicalTransform(geometry) {
|
|
162
|
+
return orientationTransform(geometry, "LPS");
|
|
163
|
+
}
|
|
164
|
+
function isIdentityTransform(transform) {
|
|
165
|
+
return transform.perm[0] === 0 && transform.perm[1] === 1 && transform.perm[2] === 2 && !transform.flip.some(Boolean);
|
|
166
|
+
}
|
|
167
|
+
/** The same grid described in the transform's voxel order. The origin moves to the new first voxel. */
|
|
168
|
+
function reorientedGeometry(geometry, transform) {
|
|
169
|
+
const origin = [...geometry.origin];
|
|
170
|
+
transform.perm.forEach((native, axis) => {
|
|
171
|
+
if (!transform.flip[axis])
|
|
172
|
+
return;
|
|
173
|
+
for (let x = 0; x < 3; x++)
|
|
174
|
+
origin[x] += (geometry.dims[native] - 1) * geometry.directions[native][x];
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
dims: transform.perm.map((native) => geometry.dims[native]),
|
|
178
|
+
// "+ 0" turns a negated zero into 0 (see geometryFromNrrd).
|
|
179
|
+
directions: transform.perm.map((native, axis) => geometry.directions[native].map((c) => (transform.flip[axis] ? -c : c) + 0)),
|
|
180
|
+
origin,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Voxels (i fastest, as NRRD stores them) rewritten in the transform's order. The identity
|
|
185
|
+
* returns `data` itself, with no copy; any other transform returns a new array of the same type.
|
|
186
|
+
*/
|
|
187
|
+
function reorientVoxels(data, dims, transform) {
|
|
188
|
+
if (data.length !== dims[0] * dims[1] * dims[2]) {
|
|
189
|
+
throw new Error(`voxel count ${data.length} does not fill a ${dims.join("x")} grid`);
|
|
190
|
+
}
|
|
191
|
+
if (isIdentityTransform(transform))
|
|
192
|
+
return data;
|
|
193
|
+
const nativeStride = [1, dims[0], dims[0] * dims[1]];
|
|
194
|
+
const outDims = transform.perm.map((native) => dims[native]);
|
|
195
|
+
const step = transform.perm.map((native, axis) => (transform.flip[axis] ? -1 : 1) * nativeStride[native]);
|
|
196
|
+
let start = 0;
|
|
197
|
+
transform.perm.forEach((native, axis) => {
|
|
198
|
+
if (transform.flip[axis])
|
|
199
|
+
start += (dims[native] - 1) * nativeStride[native];
|
|
200
|
+
});
|
|
201
|
+
const out = new data.constructor(data.length);
|
|
202
|
+
let n = 0;
|
|
203
|
+
for (let c2 = 0, base2 = start; c2 < outDims[2]; c2++, base2 += step[2]) {
|
|
204
|
+
for (let c1 = 0, base1 = base2; c1 < outDims[1]; c1++, base1 += step[1]) {
|
|
205
|
+
for (let c0 = 0, index = base1; c0 < outDims[0]; c0++, index += step[0]) {
|
|
206
|
+
out[n++] = data[index];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return out;
|
|
211
|
+
}
|
|
212
|
+
/** The orientation letters at each screen edge of a view of a canonical grid. */
|
|
213
|
+
function viewLabels(axis, geometry) {
|
|
214
|
+
const spacing = spacingOf(geometry);
|
|
215
|
+
const units = geometry.directions.map((d, a) => d.map((c) => c / spacing[a]));
|
|
216
|
+
const along = (step) => [0, 1, 2].map((x) => step[0] * units[0][x] + step[1] * units[1][x] + step[2] * units[2][x]);
|
|
217
|
+
const [rightStep, downStep] = VIEW_LAYOUT[axis];
|
|
218
|
+
const right = along(rightStep);
|
|
219
|
+
const down = along(downStep);
|
|
220
|
+
const negate = (v) => v.map((c) => -c);
|
|
221
|
+
return { left: letters(negate(right)), right: letters(right), top: letters(negate(down)), bottom: letters(down) };
|
|
222
|
+
}
|
|
223
|
+
function spacingOf(geometry) {
|
|
224
|
+
return geometry.directions.map((d) => Math.hypot(d[0], d[1], d[2]));
|
|
225
|
+
}
|
|
226
|
+
function letters(direction) {
|
|
227
|
+
return [0, 1, 2]
|
|
228
|
+
.filter((x) => Math.abs(direction[x]) > LABEL_TOL)
|
|
229
|
+
.sort((a, b) => Math.abs(direction[b]) - Math.abs(direction[a]))
|
|
230
|
+
.map((x) => (direction[x] > 0 ? "LPS" : "RAI")[x])
|
|
231
|
+
.join("");
|
|
232
|
+
}
|
|
233
|
+
function parseCodes(codes) {
|
|
234
|
+
if (codes.length !== 3 || [...codes].some((c) => !(c in LETTERS))) {
|
|
235
|
+
throw new Error(`not a three-letter orientation code: '${codes}'`);
|
|
236
|
+
}
|
|
237
|
+
const target = [...codes].map((c) => LETTERS[c]);
|
|
238
|
+
if (new Set(target.map(([patientAxis]) => patientAxis)).size !== 3) {
|
|
239
|
+
throw new Error(`orientation code '${codes}' names a patient axis twice`);
|
|
240
|
+
}
|
|
241
|
+
return target;
|
|
242
|
+
}
|
|
243
|
+
function parseVectors(text) {
|
|
244
|
+
const out = [];
|
|
245
|
+
for (const match of text.matchAll(/\(([^)]*)\)|none/gi)) {
|
|
246
|
+
out.push(match[1] === undefined ? null : match[1].split(",").map((c) => parseFloat(c)));
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
function checked(geometry) {
|
|
251
|
+
const values = [...geometry.directions.flat(), ...geometry.origin];
|
|
252
|
+
if (values.some((v) => !Number.isFinite(v))) {
|
|
253
|
+
throw new OrientationError("degenerate", "the geometry contains non-finite values");
|
|
254
|
+
}
|
|
255
|
+
const spacing = spacingOf(geometry);
|
|
256
|
+
if (spacing.some((s) => s <= 1e-12) || geometry.dims.some((n) => !(n >= 1))) {
|
|
257
|
+
throw new OrientationError("degenerate", `a voxel axis has no extent (dims [${geometry.dims.join(", ")}], spacing [${spacing.join(", ")}])`);
|
|
258
|
+
}
|
|
259
|
+
return geometry;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export { OrientationError, canonicalTransform, geometryFromNrrd, isIdentityTransform, nrrdHeaderText, orientationTransform, readNrrdOrientationFields, reorientVoxels, reorientedGeometry, spacingOf, viewLabels };
|
|
@@ -12,6 +12,8 @@ export declare class copperSceneOnDemond extends baseScene {
|
|
|
12
12
|
controls: OrbitControls | Copper3dTrackballControls | TrackballControls;
|
|
13
13
|
renderRequested: boolean | undefined;
|
|
14
14
|
isResize: boolean;
|
|
15
|
+
/** Handle of the callback loop's next frame; null while the loop is not running. */
|
|
16
|
+
private callbackFrame;
|
|
15
17
|
/**
|
|
16
18
|
* `opt.controls` picks the controls class, as it already did on
|
|
17
19
|
* `copperScene`. New in 3.9.0 -- this class hardcoded `OrbitControls`
|
|
@@ -47,6 +49,20 @@ export declare class copperSceneOnDemond extends baseScene {
|
|
|
47
49
|
*/
|
|
48
50
|
setCameraPose(pose: Pose): void;
|
|
49
51
|
confirmResize: () => void;
|
|
52
|
+
/**
|
|
53
|
+
* Registers a per-frame callback, as on `copperScene` -- `nrrdTools.start` is the usual one.
|
|
54
|
+
*
|
|
55
|
+
* This scene draws only on demand, and before 4.1.2 nothing here ran the registry:
|
|
56
|
+
* registering returned an id and the callback never ran. Now the scene runs a
|
|
57
|
+
* `requestAnimationFrame` loop of its own while anything is registered, and none while
|
|
58
|
+
* nothing is. The loop calls the callbacks and nothing else -- it does not render the WebGL
|
|
59
|
+
* scene, so a callback that changes what the scene shows still asks for a frame with
|
|
60
|
+
* `requestRenderIfNotRequested`.
|
|
61
|
+
*/
|
|
62
|
+
addPreRenderCallbackFunction(callbackFunction: Function): number;
|
|
63
|
+
removePreRenderCallbackFunction(id: number): void;
|
|
64
|
+
private runCallbackFrame;
|
|
65
|
+
private stopCallbackLoop;
|
|
50
66
|
/**
|
|
51
67
|
* Releases what this scene attached OUTSIDE itself.
|
|
52
68
|
*
|
|
@@ -89,7 +89,24 @@ export declare class DrawToolCore {
|
|
|
89
89
|
* Only set to 'Scroll:Zoom' — Scroll:Slice never needs a swap.
|
|
90
90
|
*/
|
|
91
91
|
private wheelModeBeforeDrag;
|
|
92
|
-
|
|
92
|
+
/** The per-frame composite. `draw()` builds it (in `paintOnCanvas`); a no-op until then. */
|
|
93
|
+
private renderFrame;
|
|
94
|
+
private boundStart?;
|
|
95
|
+
/**
|
|
96
|
+
* The per-frame callback hosts register (`scene.addPreRenderCallbackFunction(nrrdTools.start)`).
|
|
97
|
+
*
|
|
98
|
+
* One function for the life of the instance. It used to BE the frame `draw()` installs, read
|
|
99
|
+
* at registration time, so a host that registered before `draw()` held the empty placeholder
|
|
100
|
+
* for good and the overlay never drew. A getter rather than a field so the prototype-built
|
|
101
|
+
* test doubles have it too.
|
|
102
|
+
*/
|
|
103
|
+
get start(): () => void;
|
|
104
|
+
/**
|
|
105
|
+
* Skips frames until the first slice has sized the canvases. Until then the master canvas is
|
|
106
|
+
* 0x0, and `drawImage` of a 0x0 source throws InvalidStateError -- every frame, from inside
|
|
107
|
+
* the scene's render, which then skips its own WebGL draw.
|
|
108
|
+
*/
|
|
109
|
+
private startFrame;
|
|
93
110
|
constructor(container: HTMLElement, state: CanvasState);
|
|
94
111
|
private initTools;
|
|
95
112
|
private initDrawToolCore;
|
|
@@ -480,8 +480,9 @@ export declare class NrrdTools {
|
|
|
480
480
|
private setShowInMainArea;
|
|
481
481
|
private clearDictionary;
|
|
482
482
|
/**
|
|
483
|
-
*
|
|
484
|
-
*
|
|
483
|
+
* The per-frame callback that draws the annotation overlay; register it with the scene.
|
|
484
|
+
* The same function every time, so it may be registered before `draw()`. It does nothing
|
|
485
|
+
* until `draw()` has run and the first slice has sized the canvases.
|
|
485
486
|
*/
|
|
486
487
|
get start(): () => void;
|
|
487
488
|
/**
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "copper3d",
|
|
3
3
|
"description": "A 3d visualisation package base on threejs provides multiple scenes and Nrrd image load funtion.",
|
|
4
|
-
"version": "4.1.
|
|
4
|
+
"version": "4.1.2",
|
|
5
5
|
"main": "dist/bundle.umd.js",
|
|
6
6
|
"module": "dist/bundle.esm.mjs",
|
|
7
7
|
"types": "dist/types/index.d.ts",
|
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
"import": "./dist/bundle.esm.mjs",
|
|
12
12
|
"require": "./dist/bundle.umd.js"
|
|
13
13
|
},
|
|
14
|
+
"./orientation": {
|
|
15
|
+
"types": "./dist/types/Utils/orientation.d.ts",
|
|
16
|
+
"import": "./dist/orientation.mjs",
|
|
17
|
+
"require": "./dist/orientation.cjs"
|
|
18
|
+
},
|
|
14
19
|
"./dist/css/*": "./dist/css/*",
|
|
15
20
|
"./package.json": "./package.json"
|
|
16
21
|
},
|