/
ProbeTool.ts
676 lines (556 loc) · 19.8 KB
/
ProbeTool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
/* eslint-disable @typescript-eslint/no-empty-function */
import { vec2 } from 'gl-matrix';
import {
getEnabledElement,
VolumeViewport,
utilities as csUtils,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { AnnotationTool } from '../base';
import {
addAnnotation,
getAnnotations,
removeAnnotation,
} from '../../stateManagement/annotation/annotationState';
import {
triggerAnnotationCompleted,
triggerAnnotationModified,
} from '../../stateManagement/annotation/helpers/state';
import { getCalibratedProbeUnitsAndValue } from '../../utilities/getCalibratedUnits';
import {
drawHandles as drawHandlesSvg,
drawTextBox as drawTextBoxSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import { Events } from '../../enums';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import { roundNumber } from '../../utilities';
import {
resetElementCursor,
hideElementCursor,
} from '../../cursors/elementCursor';
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
import {
EventTypes,
ToolHandle,
PublicToolProps,
ToolProps,
SVGDrawingHelper,
} from '../../types';
import { ProbeAnnotation } from '../../types/ToolSpecificAnnotationTypes';
import { StyleSpecifier } from '../../types/AnnotationStyle';
import {
ModalityUnitOptions,
getModalityUnit,
} from '../../utilities/getModalityUnit';
import { isViewportPreScaled } from '../../utilities/viewport/isViewportPreScaled';
const { transformWorldToIndex } = csUtils;
/**
* ProbeTool let you get the underlying voxel value by putting a probe in that
* location. It will give index of the location and value of the voxel.
* You can use ProbeTool in all perpendicular views (axial, sagittal, coronal).
* Note: annotation tools in cornerstone3DTools exists in the exact location
* in the physical 3d space, as a result, by default, all annotations that are
* drawing in the same frameOfReference will get shared between viewports that
* are in the same frameOfReference. Probe tool's text box are dynamically
* generated based on the viewport's underlying Modality. For instance, if
* the viewport is displaying CT, the text box will shown the statistics in Hounsfield units,
* and if the viewport is displaying PET, the text box will show the statistics in
* SUV units.
*
* The resulting annotation's data (statistics) and metadata (the
* state of the viewport while drawing was happening) will get added to the
* ToolState manager and can be accessed from the ToolState by calling getAnnotations
* or similar methods.
*
* To use the ProbeTool, you first need to add it to cornerstoneTools, then create
* a toolGroup and add the ProbeTool to it. Finally, setToolActive on the toolGroup
*
* ```js
* cornerstoneTools.addTool(ProbeTool)
*
* const toolGroup = ToolGroupManager.createToolGroup('toolGroupId')
*
* toolGroup.addTool(ProbeTool.toolName)
*
* toolGroup.addViewport('viewportId', 'renderingEngineId')
*
* toolGroup.setToolActive(ProbeTool.toolName, {
* bindings: [
* {
* mouseButton: MouseBindings.Primary, // Left Click
* },
* ],
* })
* ```
*
* Read more in the Docs section of the website.
*
*/
class ProbeTool extends AnnotationTool {
static toolName;
touchDragCallback: any;
mouseDragCallback: any;
editData: {
annotation: any;
viewportIdsToRender: string[];
newAnnotation?: boolean;
} | null;
eventDispatchDetail: {
viewportId: string;
renderingEngineId: string;
};
isDrawing: boolean;
isHandleOutsideImage: boolean;
constructor(
toolProps: PublicToolProps = {},
defaultToolProps: ToolProps = {
supportedInteractionTypes: ['Mouse', 'Touch'],
configuration: {
shadow: true,
preventHandleOutsideImage: false,
getTextLines: defaultGetTextLines,
},
}
) {
super(toolProps, defaultToolProps);
}
// Not necessary for this tool but needs to be defined since it's an abstract
// method from the parent class.
isPointNearTool(): boolean {
return false;
}
toolSelectedCallback() {}
/**
* Based on the current position of the mouse and the current imageId to create
* a Probe Annotation and stores it in the annotationManager
*
* @param evt - EventTypes.NormalizedMouseEventType
* @returns The annotation object.
*
*/
addNewAnnotation = (
evt: EventTypes.InteractionEventType
): ProbeAnnotation => {
const eventDetail = evt.detail;
const { currentPoints, element } = eventDetail;
const worldPos = currentPoints.world;
const enabledElement = getEnabledElement(element);
const { viewport, renderingEngine } = enabledElement;
this.isDrawing = true;
const camera = viewport.getCamera();
const { viewPlaneNormal, viewUp } = camera;
const referencedImageId = this.getReferencedImageId(
viewport,
worldPos,
viewPlaneNormal,
viewUp
);
const FrameOfReferenceUID = viewport.getFrameOfReferenceUID();
const annotation = {
invalidated: true,
highlighted: true,
metadata: {
toolName: this.getToolName(),
viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
viewUp: <Types.Point3>[...viewUp],
FrameOfReferenceUID,
referencedImageId,
},
data: {
label: '',
handles: { points: [<Types.Point3>[...worldPos]] },
cachedStats: {},
},
};
addAnnotation(annotation, element);
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData = {
annotation,
newAnnotation: true,
viewportIdsToRender,
};
this._activateModify(element);
hideElementCursor(element);
evt.preventDefault();
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
return annotation;
};
/**
* It checks if the mouse click is near ProveTool, it overwrites the baseAnnotationTool
* getHandleNearImagePoint method.
*
* @param element - The element that the tool is attached to.
* @param annotation - The annotation object associated with the annotation
* @param canvasCoords - The coordinates of the mouse click on canvas
* @param proximity - The distance from the mouse cursor to the point
* that is considered "near".
* @returns The handle that is closest to the cursor, or null if the cursor
* is not near any of the handles.
*/
getHandleNearImagePoint(
element: HTMLDivElement,
annotation: ProbeAnnotation,
canvasCoords: Types.Point2,
proximity: number
): ToolHandle | undefined {
const enabledElement = getEnabledElement(element);
const { viewport } = enabledElement;
const { data } = annotation;
const point = data.handles.points[0];
const annotationCanvasCoordinate = viewport.worldToCanvas(point);
const near =
vec2.distance(canvasCoords, annotationCanvasCoordinate) < proximity;
if (near === true) {
return point;
}
}
handleSelectedCallback(
evt: EventTypes.InteractionEventType,
annotation: ProbeAnnotation
): void {
const eventDetail = evt.detail;
const { element } = eventDetail;
annotation.highlighted = true;
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
// Find viewports to render on drag.
this.editData = {
//handle, // This would be useful for other tools with more than one handle
annotation,
viewportIdsToRender,
};
this._activateModify(element);
hideElementCursor(element);
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
evt.preventDefault();
}
_endCallback = (evt: EventTypes.InteractionEventType): void => {
const eventDetail = evt.detail;
const { element } = eventDetail;
const { annotation, viewportIdsToRender, newAnnotation } = this.editData;
const { viewportId, renderingEngine } = getEnabledElement(element);
this.eventDispatchDetail = {
viewportId,
renderingEngineId: renderingEngine.id,
};
this._deactivateModify(element);
resetElementCursor(element);
this.editData = null;
this.isDrawing = false;
if (
this.isHandleOutsideImage &&
this.configuration.preventHandleOutsideImage
) {
removeAnnotation(annotation.annotationUID);
}
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
if (newAnnotation) {
triggerAnnotationCompleted(annotation);
}
};
_dragCallback = (evt) => {
this.isDrawing = true;
const eventDetail = evt.detail;
const { currentPoints, element } = eventDetail;
const worldPos = currentPoints.world;
const { annotation, viewportIdsToRender } = this.editData;
const { data } = annotation;
data.handles.points[0] = [...worldPos];
annotation.invalidated = true;
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
};
cancel = (element: HTMLDivElement) => {
// If it is mid-draw or mid-modify
if (this.isDrawing) {
this.isDrawing = false;
this._deactivateModify(element);
resetElementCursor(element);
const { annotation, viewportIdsToRender, newAnnotation } = this.editData;
const { data } = annotation;
annotation.highlighted = false;
data.handles.activeHandleIndex = null;
const { renderingEngine } = getEnabledElement(element);
triggerAnnotationRenderForViewportIds(
renderingEngine,
viewportIdsToRender
);
if (newAnnotation) {
triggerAnnotationCompleted(annotation);
}
this.editData = null;
return annotation.annotationUID;
}
};
_activateModify = (element) => {
state.isInteractingWithTool = true;
element.addEventListener(Events.MOUSE_UP, this._endCallback);
element.addEventListener(Events.MOUSE_DRAG, this._dragCallback);
element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
element.addEventListener(Events.TOUCH_END, this._endCallback);
element.addEventListener(Events.TOUCH_DRAG, this._dragCallback);
element.addEventListener(Events.TOUCH_TAP, this._endCallback);
};
_deactivateModify = (element) => {
state.isInteractingWithTool = false;
element.removeEventListener(Events.MOUSE_UP, this._endCallback);
element.removeEventListener(Events.MOUSE_DRAG, this._dragCallback);
element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
element.removeEventListener(Events.TOUCH_END, this._endCallback);
element.removeEventListener(Events.TOUCH_DRAG, this._dragCallback);
element.removeEventListener(Events.TOUCH_TAP, this._endCallback);
};
/**
* it is used to draw the probe annotation in each
* request animation frame. It calculates the updated cached statistics if
* data is invalidated and cache it.
*
* @param enabledElement - The Cornerstone's enabledElement.
* @param svgDrawingHelper - The svgDrawingHelper providing the context for drawing.
*/
renderAnnotation = (
enabledElement: Types.IEnabledElement,
svgDrawingHelper: SVGDrawingHelper
): boolean => {
let renderStatus = false;
const { viewport } = enabledElement;
const { element } = viewport;
let annotations = getAnnotations(this.getToolName(), element);
if (!annotations?.length) {
return renderStatus;
}
annotations = this.filterInteractableAnnotationsForElement(
element,
annotations
);
if (!annotations?.length) {
return renderStatus;
}
const targetId = this.getTargetId(viewport);
const renderingEngine = viewport.getRenderingEngine();
const styleSpecifier: StyleSpecifier = {
toolGroupId: this.toolGroupId,
toolName: this.getToolName(),
viewportId: enabledElement.viewport.id,
};
for (let i = 0; i < annotations.length; i++) {
const annotation = annotations[i] as ProbeAnnotation;
const annotationUID = annotation.annotationUID;
const data = annotation.data;
const point = data.handles.points[0];
const canvasCoordinates = viewport.worldToCanvas(point);
styleSpecifier.annotationUID = annotationUID;
const { color } = this.getAnnotationStyle({ annotation, styleSpecifier });
if (!data.cachedStats) {
data.cachedStats = {};
}
if (
!data.cachedStats[targetId] ||
data.cachedStats[targetId].value == null
) {
data.cachedStats[targetId] = {
Modality: null,
index: null,
value: null,
};
this._calculateCachedStats(annotation, renderingEngine, enabledElement);
} else if (annotation.invalidated) {
this._calculateCachedStats(annotation, renderingEngine, enabledElement);
// If the invalidated data is as a result of volumeViewport manipulation
// of the tools, we need to invalidate the related stackViewports data if
// they are not at the referencedImageId, so that
// when scrolling to the related slice in which the tool were manipulated
// we re-render the correct tool position. This is due to stackViewport
// which doesn't have the full volume at each time, and we are only working
// on one slice at a time.
if (viewport instanceof VolumeViewport) {
const { referencedImageId } = annotation.metadata;
// invalidate all the relevant stackViewports if they are not
// at the referencedImageId
for (const targetId in data.cachedStats) {
if (targetId.startsWith('imageId')) {
const viewports = renderingEngine.getStackViewports();
const invalidatedStack = viewports.find((vp) => {
// The stack viewport that contains the imageId but is not
// showing it currently
const referencedImageURI =
csUtils.imageIdToURI(referencedImageId);
const hasImageURI = vp.hasImageURI(referencedImageURI);
const currentImageURI = csUtils.imageIdToURI(
vp.getCurrentImageId()
);
return hasImageURI && currentImageURI !== referencedImageURI;
});
if (invalidatedStack) {
delete data.cachedStats[targetId];
}
}
}
}
}
// If rendering engine has been destroyed while rendering
if (!viewport.getRenderingEngine()) {
console.warn('Rendering Engine has been destroyed');
return renderStatus;
}
const handleGroupUID = '0';
drawHandlesSvg(
svgDrawingHelper,
annotationUID,
handleGroupUID,
[canvasCoordinates],
{ color }
);
renderStatus = true;
const options = this.getLinkedTextBoxStyle(styleSpecifier, annotation);
if (!options.visibility) {
continue;
}
const textLines = this.configuration.getTextLines(data, targetId);
if (textLines) {
const textCanvasCoordinates = [
canvasCoordinates[0] + 6,
canvasCoordinates[1] - 6,
];
const textUID = '0';
drawTextBoxSvg(
svgDrawingHelper,
annotationUID,
textUID,
textLines,
[textCanvasCoordinates[0], textCanvasCoordinates[1]],
options
);
}
}
return renderStatus;
};
_calculateCachedStats(annotation, renderingEngine, enabledElement) {
const data = annotation.data;
const { renderingEngineId, viewport } = enabledElement;
const { element } = viewport;
const worldPos = data.handles.points[0];
const { cachedStats } = data;
const targetIds = Object.keys(cachedStats);
for (let i = 0; i < targetIds.length; i++) {
const targetId = targetIds[i];
const modalityUnitOptions = {
isPreScaled: isViewportPreScaled(viewport, targetId),
isSuvScaled: this.isSuvScaled(
viewport,
targetId,
annotation.metadata.referencedImageId
),
};
const image = this.getTargetIdImage(targetId, renderingEngine);
// If image does not exists for the targetId, skip. This can be due
// to various reasons such as if the target was a volumeViewport, and
// the volumeViewport has been decached in the meantime.
if (!image) {
continue;
}
const { dimensions, imageData, metadata } = image;
const scalarData =
'getScalarData' in image ? image.getScalarData() : image.scalarData;
const modality = metadata.Modality;
const index = transformWorldToIndex(imageData, worldPos);
index[0] = Math.round(index[0]);
index[1] = Math.round(index[1]);
index[2] = Math.round(index[2]);
const samplesPerPixel =
scalarData.length / dimensions[2] / dimensions[1] / dimensions[0];
if (csUtils.indexWithinDimensions(index, dimensions)) {
this.isHandleOutsideImage = false;
const yMultiple = dimensions[0] * samplesPerPixel;
const zMultiple = dimensions[0] * dimensions[1] * samplesPerPixel;
const baseIndex =
index[2] * zMultiple +
index[1] * yMultiple +
index[0] * samplesPerPixel;
let value =
samplesPerPixel > 2
? [
scalarData[baseIndex],
scalarData[baseIndex + 1],
scalarData[baseIndex + 2],
]
: scalarData[baseIndex];
// Index[2] for stackViewport is always 0, but for visualization
// we reset it to be imageId index
if (targetId.startsWith('imageId:')) {
const imageId = targetId.split('imageId:')[1];
const imageURI = csUtils.imageIdToURI(imageId);
const viewports = csUtils.getViewportsWithImageURI(
imageURI,
renderingEngineId
);
const viewport = viewports[0];
index[2] = viewport.getCurrentImageIdIndex();
}
let modalityUnit;
if (modality === 'US') {
const calibratedResults = getCalibratedProbeUnitsAndValue(image, [
index,
]);
const hasEnhancedRegionValues = calibratedResults.values.every(
(value) => value !== null
);
value = hasEnhancedRegionValues ? calibratedResults.values : value;
modalityUnit = hasEnhancedRegionValues
? calibratedResults.units
: 'raw';
} else {
modalityUnit = getModalityUnit(
modality,
annotation.metadata.referencedImageId,
modalityUnitOptions
);
}
cachedStats[targetId] = {
index,
value,
Modality: modality,
modalityUnit,
};
} else {
this.isHandleOutsideImage = true;
cachedStats[targetId] = {
index,
Modality: modality,
};
}
annotation.invalidated = false;
// Dispatching annotation modified
triggerAnnotationModified(annotation, element);
}
return cachedStats;
}
}
function defaultGetTextLines(data, targetId): string[] {
const cachedVolumeStats = data.cachedStats[targetId];
const { index, value, modalityUnit } = cachedVolumeStats;
if (value === undefined) {
return;
}
const textLines = [];
textLines.push(`(${index[0]}, ${index[1]}, ${index[2]})`);
if (value instanceof Array && modalityUnit instanceof Array) {
for (let i = 0; i < value.length; i++) {
textLines.push(`${roundNumber(value[i])} ${modalityUnit[i]}`);
}
} else {
textLines.push(`${roundNumber(value)} ${modalityUnit}`);
}
return textLines;
}
ProbeTool.toolName = 'Probe';
export default ProbeTool;