/
SplineROITool.ts
1238 lines (1052 loc) · 36.2 KB
/
SplineROITool.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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
getEnabledElement,
eventTarget,
triggerEvent,
utilities,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { vec3 } from 'gl-matrix';
import {
getChildAnnotations,
removeAnnotation,
} from '../../stateManagement/annotation/annotationState';
import {
drawHandles as drawHandlesSvg,
drawPolyline as drawPolylineSvg,
drawLinkedTextBox as drawLinkedTextBoxSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import {
Events,
MouseBindings,
KeyboardBindings,
ChangeTypes,
} from '../../enums';
import { resetElementCursor } from '../../cursors/elementCursor';
import type {
Annotation,
EventTypes,
ToolHandle,
TextBoxHandle,
PublicToolProps,
ToolProps,
AnnotationRenderContext,
} from '../../types';
import {
math,
throttle,
roundNumber,
triggerAnnotationRenderForViewportIds,
getCalibratedLengthUnitsAndScale,
} from '../../utilities';
import getMouseModifierKey from '../../eventDispatchers/shared/getMouseModifier';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import { getTextBoxCoordsCanvas } from '../../utilities/drawing';
import { ContourWindingDirection } from '../../types/ContourAnnotation';
import type { SplineROIAnnotation } from '../../types/ToolSpecificAnnotationTypes';
import type {
AnnotationModifiedEventDetail,
ContourAnnotationCompletedEventDetail,
} from '../../types/EventTypes';
import { ISpline } from '../../types/ISpline';
import { CardinalSpline } from './splines/CardinalSpline';
import { LinearSpline } from './splines/LinearSpline';
import { CatmullRomSpline } from './splines/CatmullRomSpline';
import { BSpline } from './splines/BSpline';
import ContourSegmentationBaseTool from '../base/ContourSegmentationBaseTool';
const SPLINE_MIN_POINTS = 3;
const SPLINE_CLICK_CLOSE_CURVE_DIST = 10;
const DEFAULT_SPLINE_CONFIG = {
resolution: 20,
controlPointAdditionDistance: 6,
controlPointDeletionDistance: 6,
showControlPointsConnectors: false,
controlPointAdditionEnabled: true,
controlPointDeletionEnabled: true,
};
enum SplineTypesEnum {
Cardinal = 'CARDINAL',
Linear = 'LINEAR',
CatmullRom = 'CATMULLROM',
BSpline = 'BSPLINE',
}
enum SplineToolActions {
AddControlPoint = 'addControlPoint',
DeleteControlPoint = 'deleteControlPoint',
}
class SplineROITool extends ContourSegmentationBaseTool {
static toolName;
static SplineTypes = SplineTypesEnum;
static Actions = SplineToolActions;
touchDragCallback: any;
mouseDragCallback: any;
_throttledCalculateCachedStats: any;
editData: {
annotation: SplineROIAnnotation;
viewportIdsToRender: Array<string>;
handleIndex?: number;
movingTextBox?: boolean;
newAnnotation?: boolean;
hasMoved?: boolean;
lastCanvasPoint?: Types.Point2;
contourHoleProcessingEnabled?: boolean;
} | null;
isDrawing: boolean;
isHandleOutsideImage = false;
fireChangeOnUpdate: {
annotationUID: string;
changeType: ChangeTypes;
contourHoleProcessingEnabled: boolean;
} = null;
constructor(
toolProps: PublicToolProps = {},
defaultToolProps: ToolProps = {
supportedInteractionTypes: ['Mouse', 'Touch'],
configuration: {
preventHandleOutsideImage: false,
calculateStats: true,
getTextLines: defaultGetTextLines,
/**
* Specify which modifier key is used to add a hole to a contour. The
* modifier must be pressed when the first point of a new contour is added.
*/
contourHoleAdditionModifierKey: KeyboardBindings.Shift,
/**
* The polyline may get processed in order to reduce the number of points
* for better performance and storage.
*/
decimate: {
enabled: false,
/** A maximum given distance 'epsilon' to decide if a point should or
* shouldn't be added the resulting polyline which will have a lower
* number of points for higher `epsilon` values.
*/
epsilon: 0.1,
},
spline: {
configuration: {
[SplineTypesEnum.Cardinal]: {
Class: CardinalSpline,
scale: 0.5,
},
[SplineTypesEnum.CatmullRom]: {
Class: CatmullRomSpline,
},
[SplineTypesEnum.Linear]: {
Class: LinearSpline,
},
[SplineTypesEnum.BSpline]: {
Class: BSpline,
controlPointAdditionEnabled: false,
controlPointDeletionEnabled: false,
showControlPointsConnectors: true,
},
},
type: SplineTypesEnum.CatmullRom,
drawPreviewEnabled: true,
lastControlPointDeletionKeys: ['Backspace', 'Delete'],
},
actions: {
[SplineToolActions.AddControlPoint]: {
method: 'addControlPointCallback',
bindings: [
{
mouseButton: MouseBindings.Primary,
modifierKey: KeyboardBindings.Shift,
},
],
},
[SplineToolActions.DeleteControlPoint]: {
method: 'deleteControlPointCallback',
bindings: [
{
mouseButton: MouseBindings.Primary,
modifierKey: KeyboardBindings.Ctrl,
},
],
},
},
},
}
) {
super(toolProps, defaultToolProps);
this._throttledCalculateCachedStats = throttle(
this._calculateCachedStats,
100,
{ trailing: true }
);
}
/**
* Based on the current position of the mouse and the current imageId to create
* a CircleROI Annotation and stores it in the annotationManager
*
* @param evt - EventTypes.NormalizedMouseEventType
* @returns The annotation object.
*
*/
addNewAnnotation(evt: EventTypes.InteractionEventType): SplineROIAnnotation {
const eventDetail = evt.detail;
const { currentPoints, element } = eventDetail;
const { canvas: canvasPos } = currentPoints;
const contourHoleProcessingEnabled =
getMouseModifierKey(evt.detail.event) ===
this.configuration.contourHoleAdditionModifierKey;
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
const annotation = this.createAnnotation(evt) as SplineROIAnnotation;
this.isDrawing = true;
this.addAnnotation(annotation, element);
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData = {
annotation,
viewportIdsToRender,
movingTextBox: false,
newAnnotation: true,
hasMoved: false,
lastCanvasPoint: canvasPos,
contourHoleProcessingEnabled,
};
this._activateDraw(element);
evt.preventDefault();
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
return annotation;
}
/**
* It returns if the canvas point is near the provided annotation in the provided
* element or not. A proximity is passed to the function to determine the
* proximity of the point to the annotation in number of pixels.
*
* @param element - HTML Element
* @param annotation - Annotation
* @param canvasCoords - Canvas coordinates
* @param proximity - Proximity to tool to consider
* @returns Boolean, whether the canvas point is near tool
*/
isPointNearTool = (
element: HTMLDivElement,
annotation: SplineROIAnnotation,
canvasCoords: Types.Point2,
proximity: number
): boolean => {
const { instance: spline } = annotation.data.spline;
return spline.isPointNearCurve(canvasCoords, proximity);
};
toolSelectedCallback = (
evt: EventTypes.InteractionEventType,
annotation: SplineROIAnnotation
): void => {
const eventDetail = evt.detail;
const { element } = eventDetail;
annotation.highlighted = true;
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData = {
annotation,
viewportIdsToRender,
movingTextBox: false,
};
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
this._activateModify(element);
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
evt.preventDefault();
};
handleSelectedCallback = (
evt: EventTypes.InteractionEventType,
annotation: SplineROIAnnotation,
handle: ToolHandle
): void => {
const eventDetail = evt.detail;
const { element } = eventDetail;
const { data } = annotation;
annotation.highlighted = true;
let movingTextBox = false;
let handleIndex;
if ((handle as TextBoxHandle).worldPosition) {
movingTextBox = true;
} else {
const { points } = data.handles;
handleIndex = points.findIndex((p) => p === handle);
}
// Find viewports to render on drag.
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData = {
annotation,
viewportIdsToRender,
handleIndex,
movingTextBox,
};
this._activateModify(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,
contourHoleProcessingEnabled,
} = this.editData;
const { data } = annotation;
annotation.autoGenerated = false;
data.handles.activeHandleIndex = null;
this._deactivateModify(element);
this._deactivateDraw(element);
resetElementCursor(element);
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
// Decide whether there's at least one point is outside image
const image = this.getTargetIdImage(
this.getTargetId(enabledElement.viewport),
enabledElement.renderingEngine
);
const { imageData, dimensions } = image;
this.isHandleOutsideImage = data.handles.points
.map((p) => utilities.transformWorldToIndex(imageData, p))
.some((index) => !utilities.indexWithinDimensions(index, dimensions));
if (
this.isHandleOutsideImage &&
this.configuration.preventHandleOutsideImage
) {
removeAnnotation(annotation.annotationUID);
}
const changeType = newAnnotation
? ChangeTypes.Completed
: ChangeTypes.HandlesUpdated;
if (!this.fireChangeOnUpdate) {
this.fireChangeOnUpdate = {
annotationUID: annotation.annotationUID,
changeType,
contourHoleProcessingEnabled,
};
} else {
this.fireChangeOnUpdate.annotationUID = annotation.annotationUID;
this.fireChangeOnUpdate.changeType = changeType;
}
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
this.editData = null;
this.isDrawing = false;
};
private _keyDownCallback = (evt: EventTypes.KeyDownEventType) => {
const eventDetail = evt.detail;
const { element } = eventDetail;
const key = eventDetail.key ?? '';
const { lastControlPointDeletionKeys } = this.configuration.spline;
const deleteLastPoint = lastControlPointDeletionKeys.includes(key);
if (!deleteLastPoint) {
return;
}
const { annotation } = this.editData;
const { data } = annotation;
if (data.handles.points.length === SPLINE_MIN_POINTS) {
this.cancel(element);
return;
} else {
const controlPointIndex = data.handles.points.length - 1;
this._deleteControlPointByIndex(element, annotation, controlPointIndex);
}
evt.preventDefault();
};
private _mouseMoveCallback = (evt: EventTypes.InteractionEventType): void => {
const { drawPreviewEnabled } = this.configuration.spline;
// Does not force a re-render if preview is not enabled
if (!drawPreviewEnabled) {
return;
}
const { element } = evt.detail;
const { renderingEngine } = getEnabledElement(element);
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData.lastCanvasPoint = evt.detail.currentPoints.canvas;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
evt.preventDefault();
};
private _mouseDownCallback = (evt: EventTypes.InteractionEventType): void => {
const doubleClick = evt.type === Events.MOUSE_DOUBLE_CLICK;
const { annotation, viewportIdsToRender } = this.editData;
const { data } = annotation;
if (data.contour.closed) {
return;
}
const eventDetail = evt.detail;
const { element } = eventDetail;
const { currentPoints } = eventDetail;
const { canvas: canvasPoint, world: worldPoint } = currentPoints;
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
let closeContour = data.handles.points.length >= 2 && doubleClick;
let addNewPoint = true;
// Check if user clicked on the first point to close the curve
if (data.handles.points.length >= 3) {
const { instance: spline } = data.spline;
const closestControlPoint = spline.getClosestControlPointWithinDistance(
canvasPoint,
SPLINE_CLICK_CLOSE_CURVE_DIST
);
if (closestControlPoint?.index === 0) {
addNewPoint = false;
closeContour = true;
}
}
if (addNewPoint) {
data.handles.points.push(worldPoint);
}
data.contour.closed = data.contour.closed || closeContour;
annotation.invalidated = true;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
if (data.contour.closed) {
this._endCallback(evt);
}
evt.preventDefault();
};
private _dragCallback = (evt: EventTypes.InteractionEventType): void => {
this.isDrawing = true;
const eventDetail = evt.detail;
const { element } = eventDetail;
const { annotation, viewportIdsToRender, handleIndex, movingTextBox } =
this.editData;
const { data } = annotation;
if (movingTextBox) {
// Drag mode - moving text box
const { deltaPoints } = eventDetail as EventTypes.MouseDragEventDetail;
const worldPosDelta = deltaPoints.world;
const { textBox } = data.handles;
const { worldPosition } = textBox;
worldPosition[0] += worldPosDelta[0];
worldPosition[1] += worldPosDelta[1];
worldPosition[2] += worldPosDelta[2];
textBox.hasMoved = true;
} else if (handleIndex === undefined) {
// Drag mode - moving handle
const { deltaPoints } = eventDetail as EventTypes.MouseDragEventDetail;
const worldPosDelta = deltaPoints.world;
this.moveAnnotation(annotation, worldPosDelta);
} else {
// Move mode - after double click, and mouse move to draw
const { currentPoints } = eventDetail;
const worldPos = currentPoints.world;
data.handles.points[handleIndex] = [...worldPos];
annotation.invalidated = true;
}
this.editData.hasMoved = true;
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
};
cancel(element: HTMLDivElement) {
// If it is not in mid-draw or mid-modify
if (!this.isDrawing) {
return;
}
this.isDrawing = false;
this._deactivateDraw(element);
this._deactivateModify(element);
resetElementCursor(element);
const { annotation, viewportIdsToRender, newAnnotation } = this.editData;
if (newAnnotation) {
removeAnnotation(annotation.annotationUID);
}
super.cancelAnnotation(annotation);
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
this.editData = null;
return annotation.annotationUID;
}
/**
* Triggers an annotation completed event.
*/
triggerAnnotationCompleted = (
annotation: SplineROIAnnotation,
contourHoleProcessingEnabled: boolean
): void => {
const eventType = Events.ANNOTATION_COMPLETED;
const eventDetail: ContourAnnotationCompletedEventDetail = {
annotation,
changeType: ChangeTypes.Completed,
contourHoleProcessingEnabled,
};
triggerEvent(eventTarget, eventType, eventDetail);
};
/**
* Triggers an annotation modified event.
*/
triggerAnnotationModified = (
annotation: SplineROIAnnotation,
enabledElement: Types.IEnabledElement,
changeType = ChangeTypes.StatsUpdated
): void => {
const { viewportId, renderingEngineId } = enabledElement;
const eventType = Events.ANNOTATION_MODIFIED;
const eventDetail: AnnotationModifiedEventDetail = {
annotation,
viewportId,
renderingEngineId,
changeType,
};
triggerEvent(eventTarget, eventType, eventDetail);
};
/**
* Triggers an annotation complete or modified event based on changeType.
*/
triggerChangeEvent = (
annotation: SplineROIAnnotation,
enabledElement: Types.IEnabledElement,
changeType = ChangeTypes.StatsUpdated,
contourHoleProcessingEnabled
): void => {
if (changeType === ChangeTypes.Completed) {
this.triggerAnnotationCompleted(annotation, contourHoleProcessingEnabled);
} else {
this.triggerAnnotationModified(annotation, enabledElement, changeType);
}
};
private _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);
};
private _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);
};
private _activateDraw = (element) => {
state.isInteractingWithTool = true;
element.addEventListener(Events.KEY_DOWN, this._keyDownCallback);
element.addEventListener(Events.MOUSE_MOVE, this._mouseMoveCallback);
element.addEventListener(Events.MOUSE_DOWN, this._mouseDownCallback);
element.addEventListener(
Events.MOUSE_DOUBLE_CLICK,
this._mouseDownCallback
);
element.addEventListener(Events.TOUCH_TAP, this._mouseDownCallback);
};
private _deactivateDraw = (element) => {
state.isInteractingWithTool = false;
element.removeEventListener(Events.KEY_DOWN, this._keyDownCallback);
element.removeEventListener(Events.MOUSE_MOVE, this._mouseMoveCallback);
element.removeEventListener(Events.MOUSE_DOWN, this._mouseDownCallback);
element.removeEventListener(
Events.MOUSE_DOUBLE_CLICK,
this._mouseDownCallback
);
element.removeEventListener(Events.TOUCH_TAP, this._mouseDownCallback);
};
protected isContourSegmentationTool(): boolean {
// Disable contour segmentation behavior because it shall be activated only
// for SplineContourSegmentationTool
return false;
}
/**
* Render an annotation instance
* @param renderContext - Render context that contains the annotation, enabledElement, etc.
* @returns True if the annotation is rendered or false otherwise
*/
protected renderAnnotationInstance(
renderContext: AnnotationRenderContext
): boolean {
const { enabledElement, targetId, svgDrawingHelper, annotationStyle } =
renderContext;
const { viewport } = enabledElement;
const { worldToCanvas } = viewport;
const { element } = viewport;
const annotation = renderContext.annotation as SplineROIAnnotation;
const { annotationUID, data, highlighted } = annotation;
const { handles } = data;
const { points: controlPoints, activeHandleIndex } = handles;
const newAnnotation = this.editData?.newAnnotation;
const {
lineWidth,
lineDash,
color,
locked: annotationLocked,
} = annotationStyle;
const canvasCoordinates = controlPoints.map((p) =>
worldToCanvas(p)
) as Types.Point2[];
const { drawPreviewEnabled } = this.configuration.spline;
const splineType = annotation.data.spline.type;
const splineConfig = this._getSplineConfig(splineType);
const spline = annotation.data.spline.instance;
const childAnnotations = getChildAnnotations(annotation);
const missingAnnotation = childAnnotations.findIndex((it) => !it);
if (missingAnnotation !== -1) {
// Child annotations go AWOL for a variety of reasons, so report is specifically here
throw new Error(
`Can't find annotation for child ${annotation.childAnnotationUIDs.join()}`
);
}
// Update current and all child annotations/splines
const splineAnnotationsGroup = [annotation, ...childAnnotations].filter(
(annotation) => this._isSplineROIAnnotation(annotation)
) as SplineROIAnnotation[];
splineAnnotationsGroup.forEach((annotation) => {
const spline = this._updateSplineInstance(element, annotation);
const splinePolylineCanvas = spline.getPolylinePoints();
this.updateContourPolyline(
annotation,
{
points: splinePolylineCanvas,
closed: data.contour.closed,
targetWindingDirection: ContourWindingDirection.Clockwise,
},
viewport
);
});
// Let the base class render the contour
super.renderAnnotationInstance(renderContext);
// If cachedStats does not exist, or the areaUnit is missing (as part of
// import/hydration etc.), force to recalculate the stats from the points
if (
!data.cachedStats[targetId] ||
data.cachedStats[targetId].areaUnit == null
) {
data.cachedStats[targetId] = {
Modality: null,
area: null,
areaUnit: null,
};
this._calculateCachedStats(annotation, element);
} else if (annotation.invalidated) {
this._throttledCalculateCachedStats(annotation, element);
}
let activeHandleCanvasCoords;
if (!annotationLocked && !this.editData && activeHandleIndex !== null) {
// Not locked or creating and hovering over handle, so render handle.
activeHandleCanvasCoords = [canvasCoordinates[activeHandleIndex]];
}
if (activeHandleCanvasCoords || newAnnotation || highlighted) {
const handleGroupUID = '0';
// Move this call to the base class (contour seg) in the near future
drawHandlesSvg(
svgDrawingHelper,
annotationUID,
handleGroupUID,
canvasCoordinates,
{
color,
lineWidth: Math.max(1, lineWidth),
handleRadius: '3',
}
);
}
if (
drawPreviewEnabled &&
spline.numControlPoints > 1 &&
this.editData?.lastCanvasPoint &&
!spline.closed
) {
const { lastCanvasPoint } = this.editData;
const previewPolylinePoints = spline.getPreviewPolylinePoints(
lastCanvasPoint,
SPLINE_CLICK_CLOSE_CURVE_DIST
);
drawPolylineSvg(
svgDrawingHelper,
annotationUID,
'previewSplineChange',
previewPolylinePoints,
{
color: '#9EA0CA',
lineDash,
lineWidth: 1,
}
);
}
if (splineConfig.showControlPointsConnectors) {
const controlPointsConnectors = [...canvasCoordinates];
// Connect the last point to the first one when the spline is closed
if (spline.closed) {
controlPointsConnectors.push(canvasCoordinates[0]);
}
drawPolylineSvg(
svgDrawingHelper,
annotationUID,
'controlPointsConnectors',
controlPointsConnectors,
{
color: 'rgba(255, 255, 255, 0.5)',
lineWidth: 1,
}
);
}
this._renderStats(
annotation,
viewport,
svgDrawingHelper,
annotationStyle.textbox
);
if (this.fireChangeOnUpdate?.annotationUID === annotationUID) {
this.triggerChangeEvent(
annotation,
enabledElement,
this.fireChangeOnUpdate.changeType,
this.fireChangeOnUpdate.contourHoleProcessingEnabled
);
this.fireChangeOnUpdate = null;
}
annotation.invalidated = false;
return true;
}
/**
* Creates new interpolated handles for the spline control given the
* polyline data. This allows creating the spline from polyline data
* directly.
*/
protected createInterpolatedSplineControl(annotation) {
if (annotation.data.handles.points?.length) {
// The interpolation itself created the handles
return;
}
const { polyline } = annotation.data.contour;
if (!polyline || !polyline.length) {
return;
}
annotation.data.handles.points = [];
const { points } = annotation.data.handles;
const increment = Math.max(10, Math.floor(polyline.length / 20));
for (let i = 0; i < polyline.length - increment; i += increment) {
points.push(polyline[i]);
}
points.push(polyline[polyline.length - 1]);
}
protected createAnnotation(evt: EventTypes.InteractionEventType): Annotation {
const contourAnnotation = super.createAnnotation(evt);
const { world: worldPos } = evt.detail.currentPoints;
const { type: splineType } = this.configuration.spline;
const splineConfig = this._getSplineConfig(splineType);
const spline = new splineConfig.Class();
const createSpline = () => ({
type: splineConfig.type,
instance: spline,
resolution: splineConfig.resolution,
});
// Add an action to create a new spline data on creating an interpolated
// instance.
let onInterpolationComplete;
if (this.configuration.interpolation?.enabled) {
onInterpolationComplete = (annotation) => {
annotation.data.spline ||= createSpline();
this.createInterpolatedSplineControl(annotation);
};
}
return <SplineROIAnnotation>utilities.deepMerge(contourAnnotation, {
data: {
handles: {
points: [[...worldPos]],
},
spline: createSpline(),
cachedStats: {},
},
onInterpolationComplete,
});
}
private _renderStats = (
annotation,
viewport,
svgDrawingHelper,
textboxStyle
) => {
const data = annotation.data;
const targetId = this.getTargetId(viewport);
if (!data.spline.instance.closed || !textboxStyle.visibility) {
return;
}
const textLines = this.configuration.getTextLines(data, targetId);
if (!textLines || textLines.length === 0) {
return;
}
const canvasCoordinates = data.handles.points.map((p) =>
viewport.worldToCanvas(p)
);
if (!data.handles.textBox.hasMoved) {
const canvasTextBoxCoords = getTextBoxCoordsCanvas(canvasCoordinates);
data.handles.textBox.worldPosition =
viewport.canvasToWorld(canvasTextBoxCoords);
}
const textBoxPosition = viewport.worldToCanvas(
data.handles.textBox.worldPosition
);
const textBoxUID = 'textBox';
const boundingBox = drawLinkedTextBoxSvg(
svgDrawingHelper,
annotation.annotationUID ?? '',
textBoxUID,
textLines,
textBoxPosition,
canvasCoordinates,
{},
textboxStyle
);
const { x: left, y: top, width, height } = boundingBox;
data.handles.textBox.worldBoundingBox = {
topLeft: viewport.canvasToWorld([left, top]),
topRight: viewport.canvasToWorld([left + width, top]),
bottomLeft: viewport.canvasToWorld([left, top + height]),
bottomRight: viewport.canvasToWorld([left + width, top + height]),
};
};
addControlPointCallback = (
evt: EventTypes.InteractionEventType,
annotation: SplineROIAnnotation
) => {
const { data } = annotation;
const splineType = data.spline.type;
const splineConfig = this._getSplineConfig(splineType);
const maxDist = splineConfig.controlPointAdditionDistance;
if (splineConfig.controlPointAdditionEnabled === false) {
return;
}
const eventDetail = evt.detail;
const { element } = eventDetail;
const enabledElement = getEnabledElement(element);
const { renderingEngine, viewport } = enabledElement;
const { canvasToWorld } = viewport;
const { instance: spline } = data.spline;
const canvasPos = evt.detail.currentPoints.canvas;
const closestPointInfo = spline.getClosestPoint(canvasPos);
if (closestPointInfo.distance > maxDist) {
return;
}
// Add a point at the `u` position from Parameter Space
const { index, point: canvasPoint } = spline.addControlPointAtU(
closestPointInfo.uValue
);
data.handles.points.splice(index, 0, canvasToWorld(canvasPoint));
annotation.invalidated = true;
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
};
private _deleteControlPointByIndex(
element: HTMLDivElement,
annotation: SplineROIAnnotation,
controlPointIndex: number
) {
const enabledElement = getEnabledElement(element);
const { points: controlPoints } = annotation.data.handles;
// There is no curve with only 2 points