-
Notifications
You must be signed in to change notification settings - Fork 246
/
RenderingEngine.ts
1383 lines (1182 loc) · 41.8 KB
/
RenderingEngine.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 Events from '../enums/Events';
import renderingEngineCache from './renderingEngineCache';
import eventTarget from '../eventTarget';
import { triggerEvent, uuidv4 } from '../utilities';
import { vtkOffscreenMultiRenderWindow } from './vtkClasses';
import ViewportType from '../enums/ViewportType';
import VolumeViewport from './VolumeViewport';
import BaseVolumeViewport from './BaseVolumeViewport';
import StackViewport from './StackViewport';
import viewportTypeUsesCustomRenderingPipeline from './helpers/viewportTypeUsesCustomRenderingPipeline';
import getOrCreateCanvas from './helpers/getOrCreateCanvas';
import { getShouldUseCPURendering, isCornerstoneInitialized } from '../init';
import type IStackViewport from '../types/IStackViewport';
import type IRenderingEngine from '../types/IRenderingEngine';
import type IVolumeViewport from '../types/IVolumeViewport';
import type * as EventTypes from '../types/EventTypes';
import type {
ViewportInput,
PublicViewportInput,
InternalViewportInput,
NormalizedViewportInput,
} from '../types/IViewport';
import { OrientationAxis } from '../enums';
import VolumeViewport3D from './VolumeViewport3D';
type ViewportDisplayCoords = {
sxStartDisplayCoords: number;
syStartDisplayCoords: number;
sxEndDisplayCoords: number;
syEndDisplayCoords: number;
sx: number;
sy: number;
sWidth: number;
sHeight: number;
};
// Rendering engines seem to not like rendering things less than 2 pixels per side
const VIEWPORT_MIN_SIZE = 2;
/**
* A RenderingEngine takes care of the full pipeline of creating viewports and rendering
* them on a large offscreen canvas and transmitting this data back to the screen. This allows us
* to leverage the power of vtk.js whilst only using one WebGL context for the processing, and allowing
* us to share texture memory across on-screen viewports that show the same data.
*
* Instantiating a rendering engine:
* ```js
* const renderingEngine = new RenderingEngine('pet-ct-rendering-engine');
* ```
*
* There are various ways you can trigger a render on viewports. The simplest is to call `render()`
* on the rendering engine; however, it will trigger a render on all viewports. A more efficient
* way to do this is to call `renderViewports([viewportId])` on the rendering engine to
* trigger a render on a specific viewport(s). Each viewport also has a `.render` method which can be used to trigger a render on that
* viewport.
*
* Rendering engine uses `detect-gpu` external library to detect if GPU is available and
* it has minimum requirement to be able to render a volume with vtk.js. If GPU is not available
* RenderingEngine will throw an error if you try to render a volume; however, for StackViewports
* it is capable of falling back to CPU rendering for Stack images.
*
* By default RenderingEngine will use vtk.js enabled pipeline for rendering viewports,
* however, if a custom rendering pipeline is specified by a custom viewport, it will be used instead.
* We use this custom pipeline to render a StackViewport on CPU using Cornerstone-legacy cpu rendering pipeline.
*
* @public
*/
class RenderingEngine implements IRenderingEngine {
/** Unique identifier for renderingEngine */
readonly id: string;
/** A flag which tells if the renderingEngine has been destroyed */
public hasBeenDestroyed: boolean;
public offscreenMultiRenderWindow: any;
readonly offScreenCanvasContainer: any; // WebGL
private _viewports: Map<string, IStackViewport | IVolumeViewport>;
private _needsRender: Set<string> = new Set();
private _animationFrameSet = false;
private _animationFrameHandle: number | null = null;
private useCPURendering: boolean;
/**
* @param uid - Unique identifier for RenderingEngine
*/
constructor(id?: string) {
this.id = id ? id : uuidv4();
this.useCPURendering = getShouldUseCPURendering();
renderingEngineCache.set(this);
if (!isCornerstoneInitialized()) {
throw new Error(
'@cornerstonejs/core is not initialized, run init() first'
);
}
if (!this.useCPURendering) {
this.offscreenMultiRenderWindow =
vtkOffscreenMultiRenderWindow.newInstance();
this.offScreenCanvasContainer = document.createElement('div');
this.offscreenMultiRenderWindow.setContainer(
this.offScreenCanvasContainer
);
}
this._viewports = new Map();
this.hasBeenDestroyed = false;
}
/**
* Enables the requested viewport and add it to the viewports. It will
* properly create the Stack viewport or Volume viewport:
*
* 1) Checks if the viewport is defined already, if yes, remove it first
* 2) Checks if the viewport is using a custom rendering pipeline, if no,
* it calculates a new offscreen canvas with the new requested viewport
* 3) Adds the viewport
*
*
* ```
* renderingEngine.enableElement({
* viewportId: viewportId,
* type: ViewportType.ORTHOGRAPHIC,
* element,
* defaultOptions: {
* orientation: Enums.OrientationAxis.AXIAL,
* background: [1, 0, 1],
* },
* })
* ```
*
* @fires Events.ELEMENT_ENABLED
*
* @param viewportInputEntry - viewport specifications
*/
public enableElement(viewportInputEntry: PublicViewportInput): void {
const viewportInput = this._normalizeViewportInputEntry(viewportInputEntry);
this._throwIfDestroyed();
const { element, viewportId } = viewportInput;
// Throw error if no canvas
if (!element) {
throw new Error('No element provided');
}
// 1. Get the viewport from the list of available viewports.
const viewport = this.getViewport(viewportId);
// 1.a) If there is a found viewport, we remove the viewport and create a new viewport
if (viewport) {
console.log('Viewport already exists, disabling it first');
this.disableElement(viewportId);
console.log(`Viewport ${viewportId} disabled`);
}
// 2.a) See if viewport uses a custom rendering pipeline.
const { type } = viewportInput;
const viewportUsesCustomRenderingPipeline =
viewportTypeUsesCustomRenderingPipeline(type);
// 2.b) Retrieving the list of viewports for calculation of the new size for
// offScreen canvas.
// If the viewport being added uses a custom pipeline, or we aren't using
// GPU rendering, we don't need to resize the offscreen canvas.
if (!this.useCPURendering && !viewportUsesCustomRenderingPipeline) {
this.enableVTKjsDrivenViewport(viewportInput);
} else {
// 3 Add the requested viewport to rendering Engine
this.addCustomViewport(viewportInput);
}
// 5. Set the background color for the canvas
const canvas = getOrCreateCanvas(element);
const { background } = viewportInput.defaultOptions;
this.fillCanvasWithBackgroundColor(canvas, background);
}
/**
* Disables the requested viewportId from the rendering engine:
*
* 1) It removes the viewport from the the list of viewports
* 2) remove the renderer from the offScreen render window if using vtk.js driven
* rendering pipeline
* 3) resetting the viewport to remove the canvas attributes and canvas data
* 4) resize the offScreen appropriately (if using vtk.js driven rendering pipeline)
*
* @fires Events.ELEMENT_ENABLED
*
* @param viewportId - viewport Id
*
*/
public disableElement(viewportId: string): void {
this._throwIfDestroyed();
// 1. Getting the viewport to remove it
const viewport = this.getViewport(viewportId);
// 2 To throw if there is no viewport stored in rendering engine
if (!viewport) {
console.warn(`viewport ${viewportId} does not exist`);
return;
}
// 3. Reset the viewport to remove attributes, and reset the canvas
this._resetViewport(viewport);
// 4. Remove the related renderer from the offScreenMultiRenderWindow
if (
!viewportTypeUsesCustomRenderingPipeline(viewport.type) &&
!this.useCPURendering
) {
this.offscreenMultiRenderWindow.removeRenderer(viewportId);
}
// 5. Remove the requested viewport from the rendering engine
this._removeViewport(viewportId);
viewport.isDisabled = true;
// 6. Avoid rendering for the disabled viewport
this._needsRender.delete(viewportId);
// 7. Clear RAF if no viewport is left
const viewports = this.getViewports();
if (!viewports.length) {
this._clearAnimationFrame();
}
// 8. Resize the offScreen canvas to accommodate for the new size (after removal)
// Note: Resize should not reset pan and zoom when disabling an element.
// This is because we are only resizing the offscreen canvas to deal with the element
// which was removed, and do not wish to alter the current state of any other currently enabled element
const immediate = true;
const keepCamera = true;
this.resize(immediate, keepCamera);
}
/**
* It takes an array of viewport input objects including element, viewportId, type
* and defaultOptions. It will add the viewport to the rendering engine and enables them.
*
*
* ```typescript
*renderingEngine.setViewports([
* {
* viewportId: axialViewportId,
* type: ViewportType.ORTHOGRAPHIC,
* element: document.getElementById('axialDiv'),
* defaultOptions: {
* orientation: Enums.OrientationAxis.AXIAL,
* },
* },
* {
* viewportId: sagittalViewportId,
* type: ViewportType.ORTHOGRAPHIC,
* element: document.getElementById('sagittalDiv'),
* defaultOptions: {
* orientation: Enums.OrientationAxis.SAGITTAL,
* },
* },
* {
* viewportId: customOrientationViewportId,
* type: ViewportType.ORTHOGRAPHIC,
* element: document.getElementById('customOrientationDiv'),
* defaultOptions: {
* orientation: { viewPlaneNormal: [0, 0, 1], viewUp: [0, 1, 0] },
* },
* },
* ])
* ```
*
* @fires Events.ELEMENT_ENABLED
*
* @param viewportInputEntries - Array<PublicViewportInput>
*/
public setViewports(
publicViewportInputEntries: Array<PublicViewportInput>
): void {
const viewportInputEntries = this._normalizeViewportInputEntries(
publicViewportInputEntries
);
this._throwIfDestroyed();
this._reset();
// 1. Split viewports based on whether they use vtk.js or a custom pipeline.
const vtkDrivenViewportInputEntries: NormalizedViewportInput[] = [];
const customRenderingViewportInputEntries: NormalizedViewportInput[] = [];
viewportInputEntries.forEach((vpie) => {
if (
!this.useCPURendering &&
!viewportTypeUsesCustomRenderingPipeline(vpie.type)
) {
vtkDrivenViewportInputEntries.push(vpie);
} else {
customRenderingViewportInputEntries.push(vpie);
}
});
this.setVtkjsDrivenViewports(vtkDrivenViewportInputEntries);
this.setCustomViewports(customRenderingViewportInputEntries);
}
/**
* Resizes the offscreen viewport and recalculates translations to on screen canvases.
* It is up to the parent app to call the resize of the on-screen canvas changes.
* This is left as an app level concern as one might want to debounce the changes, or the like.
*
* @param immediate - Whether all of the viewports should be rendered immediately.
* @param keepCamera - Whether to keep the camera for other viewports while resizing the offscreen canvas
*/
public resize(immediate = true, keepCamera = true): void {
this._throwIfDestroyed();
// 1. Get the viewports' canvases
const viewports = this._getViewportsAsArray();
const vtkDrivenViewports = [];
const customRenderingViewports = [];
viewports.forEach((vpie) => {
if (!viewportTypeUsesCustomRenderingPipeline(vpie.type)) {
vtkDrivenViewports.push(vpie);
} else {
customRenderingViewports.push(vpie);
}
});
if (vtkDrivenViewports.length) {
this._resizeVTKViewports(vtkDrivenViewports, keepCamera, immediate);
}
if (customRenderingViewports.length) {
this._resizeUsingCustomResizeHandler(
customRenderingViewports,
keepCamera,
immediate
);
}
}
/**
* Returns the viewport by Id
*
* @returns viewport
*/
public getViewport(viewportId: string): IStackViewport | IVolumeViewport {
return this._viewports.get(viewportId);
}
/**
* getViewports Returns an array of all `Viewport`s on the `RenderingEngine` instance.
*
* @returns Array of viewports
*/
public getViewports(): Array<IStackViewport | IVolumeViewport> {
this._throwIfDestroyed();
return this._getViewportsAsArray();
}
/**
* Filters all the available viewports and return the stack viewports
* @returns stack viewports registered on the rendering Engine
*/
public getStackViewports(): Array<IStackViewport> {
this._throwIfDestroyed();
const viewports = this.getViewports();
const isStackViewport = (
viewport: IStackViewport | IVolumeViewport
): viewport is StackViewport => {
return viewport instanceof StackViewport;
};
return viewports.filter(isStackViewport);
}
/**
* Return all the viewports that are volume viewports
* @returns An array of VolumeViewport objects.
*/
public getVolumeViewports(): Array<IVolumeViewport> {
this._throwIfDestroyed();
const viewports = this.getViewports();
const isVolumeViewport = (
viewport: IStackViewport | IVolumeViewport
): viewport is BaseVolumeViewport => {
return viewport instanceof BaseVolumeViewport;
};
return viewports.filter(isVolumeViewport);
}
/**
* Renders all viewports on the next animation frame.
*
* @fires Events.IMAGE_RENDERED
*/
public render(): void {
const viewports = this.getViewports();
const viewportIds = viewports.map((vp) => vp.id);
this._setViewportsToBeRenderedNextFrame(viewportIds);
}
/**
* Renders any viewports viewing the given Frame Of Reference.
*
* @param FrameOfReferenceUID - The unique identifier of the
* Frame Of Reference.
*/
public renderFrameOfReference = (FrameOfReferenceUID: string): void => {
const viewports = this._getViewportsAsArray();
const viewportIdsWithSameFrameOfReferenceUID = viewports.map((vp) => {
if (vp.getFrameOfReferenceUID() === FrameOfReferenceUID) {
return vp.id;
}
});
return this.renderViewports(viewportIdsWithSameFrameOfReferenceUID);
};
/**
* Renders the provided Viewport IDs.
*
*/
public renderViewports(viewportIds: Array<string>): void {
this._setViewportsToBeRenderedNextFrame(viewportIds);
}
/**
* Renders only a specific `Viewport` on the next animation frame.
*
* @param viewportId - The Id of the viewport.
*/
public renderViewport(viewportId: string): void {
this._setViewportsToBeRenderedNextFrame([viewportId]);
}
/**
* destroy the rendering engine. It will remove all the viewports and,
* if the rendering engine is using the GPU, it will also destroy the GPU
* resources.
*/
public destroy(): void {
if (this.hasBeenDestroyed) {
return;
}
// remove vtk rendered first before resetting the viewport
if (!this.useCPURendering) {
const viewports = this._getViewportsAsArray();
viewports.forEach((vp) => {
this.offscreenMultiRenderWindow.removeRenderer(vp.id);
});
// Free up WebGL resources
this.offscreenMultiRenderWindow.delete();
// Make sure all references go stale and are garbage collected.
delete this.offscreenMultiRenderWindow;
}
this._reset();
renderingEngineCache.delete(this.id);
this.hasBeenDestroyed = true;
}
/**
* Fill the canvas with the background color
* @param canvas - The canvas element to draw on.
* @param backgroundColor - An array of three numbers between 0 and 1 that
* specify the red, green, and blue values of the background color.
*/
public fillCanvasWithBackgroundColor(
canvas: HTMLCanvasElement,
backgroundColor: [number, number, number]
): void {
const ctx = canvas.getContext('2d');
// Default to black if no background color is set
let fillStyle;
if (backgroundColor) {
const rgb = backgroundColor.map((f) => Math.floor(255 * f));
fillStyle = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
} else {
fillStyle = 'black';
}
// We draw over the previous stack with the background color while we
// wait for the next stack to load
ctx.fillStyle = fillStyle;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
private _normalizeViewportInputEntry(
viewportInputEntry: PublicViewportInput
) {
const { type, defaultOptions } = viewportInputEntry;
let options = defaultOptions;
if (!options || Object.keys(options).length === 0) {
options = {
background: [0, 0, 0],
orientation: null,
displayArea: null,
};
if (type === ViewportType.ORTHOGRAPHIC) {
options = {
...options,
orientation: OrientationAxis.AXIAL,
};
}
}
return {
...viewportInputEntry,
defaultOptions: options,
};
}
private _normalizeViewportInputEntries(
viewportInputEntries: Array<PublicViewportInput>
): Array<NormalizedViewportInput> {
const normalizedViewportInputs = [];
viewportInputEntries.forEach((viewportInput) => {
normalizedViewportInputs.push(
this._normalizeViewportInputEntry(viewportInput)
);
});
return normalizedViewportInputs;
}
private _resizeUsingCustomResizeHandler(
customRenderingViewports: StackViewport[],
keepCamera = true,
immediate = true
) {
// 1. If viewport has a custom resize method, call it here.
customRenderingViewports.forEach((vp) => {
if (typeof vp.resize === 'function') vp.resize();
});
// 3. Reset viewport cameras
customRenderingViewports.forEach((vp) => {
const prevCamera = vp.getCamera();
vp.resetCamera();
if (keepCamera) {
vp.setCamera(prevCamera);
}
});
// 2. If render is immediate: Render all
if (immediate === true) {
this.render();
}
}
private _resizeVTKViewports(
vtkDrivenViewports: Array<IStackViewport | IVolumeViewport>,
keepCamera = true,
immediate = true
) {
const canvasesDrivenByVtkJs = vtkDrivenViewports.map((vp) => vp.canvas);
if (canvasesDrivenByVtkJs.length) {
// 1. Recalculate and resize the offscreen canvas size
const { offScreenCanvasWidth, offScreenCanvasHeight } =
this._resizeOffScreenCanvas(canvasesDrivenByVtkJs);
// 2. Recalculate the viewports location on the off screen canvas
this._resize(
vtkDrivenViewports,
offScreenCanvasWidth,
offScreenCanvasHeight
);
}
// 3. Reset viewport cameras
vtkDrivenViewports.forEach((vp: IStackViewport | IVolumeViewport) => {
const canvas = getOrCreateCanvas(vp.element);
const rect = canvas.getBoundingClientRect();
const devicePixelRatio = window.devicePixelRatio || 1;
canvas.width = rect.width * devicePixelRatio;
canvas.height = rect.height * devicePixelRatio;
const prevCamera = vp.getCamera();
vp.resetCamera();
if (keepCamera) {
vp.setCamera(prevCamera);
}
});
// 4. If render is immediate: Render all
if (immediate === true) {
this.render();
}
}
/**
* Enables a viewport to be driven by the offscreen vtk.js rendering engine.
*
* @param viewportInputEntry - Information object used to
* construct and enable the viewport.
*/
private enableVTKjsDrivenViewport(
viewportInputEntry: NormalizedViewportInput
) {
const viewports = this._getViewportsAsArray();
const viewportsDrivenByVtkJs = viewports.filter(
(vp) => viewportTypeUsesCustomRenderingPipeline(vp.type) === false
);
const canvasesDrivenByVtkJs = viewportsDrivenByVtkJs.map((vp) => vp.canvas);
const canvas = getOrCreateCanvas(viewportInputEntry.element);
canvasesDrivenByVtkJs.push(canvas);
const devicePixelRatio = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * devicePixelRatio;
canvas.height = rect.height * devicePixelRatio;
// 2.c Calculating the new size for offScreen Canvas
const { offScreenCanvasWidth, offScreenCanvasHeight } =
this._resizeOffScreenCanvas(canvasesDrivenByVtkJs);
// 2.d Re-position previous viewports on the offScreen Canvas based on the new
// offScreen canvas size
const xOffset = this._resize(
viewportsDrivenByVtkJs,
offScreenCanvasWidth,
offScreenCanvasHeight
);
const internalViewportEntry = { ...viewportInputEntry, canvas };
// 3 Add the requested viewport to rendering Engine
this.addVtkjsDrivenViewport(internalViewportEntry, {
offScreenCanvasWidth,
offScreenCanvasHeight,
xOffset,
});
}
/**
* Disables the requested viewportId from the rendering engine:
* 1) It removes the viewport from the the list of viewports
* 2) remove the renderer from the offScreen render window
* 3) resetting the viewport to remove the canvas attributes and canvas data
* 4) resize the offScreen appropriately
*
* @param viewportId - viewport Id
*
*/
private _removeViewport(viewportId: string): void {
// 1. Get the viewport
const viewport = this.getViewport(viewportId);
if (!viewport) {
console.warn(`viewport ${viewportId} does not exist`);
return;
}
// 2. Delete the viewports from the the viewports
this._viewports.delete(viewportId);
}
/**
* Adds a viewport driven by vtk.js to the `RenderingEngine`.
*
* @param viewportInputEntry - Information object used to construct and enable the viewport.
* @param options - Options object used to configure the viewport.
* @param options.offScreenCanvasWidth - The width of the offscreen canvas.
* @param options.offScreenCanvasHeight - The height of the offscreen canvas.
* @param options.xOffset - The x offset of the viewport on the offscreen canvas.
*/
private addVtkjsDrivenViewport(
viewportInputEntry: InternalViewportInput,
offscreenCanvasProperties?: {
offScreenCanvasWidth: number;
offScreenCanvasHeight: number;
xOffset: number;
}
): void {
const { element, canvas, viewportId, type, defaultOptions } =
viewportInputEntry;
// Make the element not focusable, we use this for modifier keys to work
element.tabIndex = -1;
const { offScreenCanvasWidth, offScreenCanvasHeight, xOffset } =
offscreenCanvasProperties;
// 1. Calculate the size of location of the viewport on the offScreen canvas
const {
sxStartDisplayCoords,
syStartDisplayCoords,
sxEndDisplayCoords,
syEndDisplayCoords,
sx,
sy,
sWidth,
sHeight,
} = this._getViewportCoordsOnOffScreenCanvas(
viewportInputEntry,
offScreenCanvasWidth,
offScreenCanvasHeight,
xOffset
);
// 2. Add a renderer to the offScreenMultiRenderWindow
this.offscreenMultiRenderWindow.addRenderer({
viewport: [
sxStartDisplayCoords,
syStartDisplayCoords,
sxEndDisplayCoords,
syEndDisplayCoords,
],
id: viewportId,
background: defaultOptions.background
? defaultOptions.background
: [0, 0, 0],
});
// 3. ViewportInput to be passed to a stack/volume viewport
const viewportInput = <ViewportInput>{
id: viewportId,
element, // div
renderingEngineId: this.id,
type,
canvas,
sx,
sy,
sWidth,
sHeight,
defaultOptions: defaultOptions || {},
};
// 4. Create a proper viewport based on the type of the viewport
let viewport;
if (type === ViewportType.STACK) {
// 4.a Create stack viewport
viewport = new StackViewport(viewportInput);
} else if (
type === ViewportType.ORTHOGRAPHIC ||
type === ViewportType.PERSPECTIVE
) {
// 4.b Create a volume viewport
viewport = new VolumeViewport(viewportInput);
} else if (type === ViewportType.VOLUME_3D) {
viewport = new VolumeViewport3D(viewportInput);
} else {
throw new Error(`Viewport Type ${type} is not supported`);
}
// 5. Storing the viewports
this._viewports.set(viewportId, viewport);
const eventDetail: EventTypes.ElementEnabledEventDetail = {
element,
viewportId,
renderingEngineId: this.id,
};
if (!viewport.suppressEvents) {
triggerEvent(eventTarget, Events.ELEMENT_ENABLED, eventDetail);
}
}
/**
* Adds a viewport using a custom rendering pipeline to the `RenderingEngine`.
*
* @param viewportInputEntry - Information object used to
* construct and enable the viewport.
*/
private addCustomViewport(viewportInputEntry: PublicViewportInput): void {
const { element, viewportId, type, defaultOptions } = viewportInputEntry;
// Make the element not focusable, we use this for modifier keys to work
element.tabIndex = -1;
const canvas = getOrCreateCanvas(element);
// Add a viewport with no offset
const { clientWidth, clientHeight } = canvas;
// Set the canvas to be same resolution as the client.
// Note: This ignores devicePixelRatio for now. We may want to change it in the
// future but it has no benefit for the Cornerstone CPU rendering pathway at the
// moment anyway.
if (canvas.width !== clientWidth || canvas.height !== clientHeight) {
canvas.width = clientWidth;
canvas.height = clientHeight;
}
const viewportInput = <ViewportInput>{
id: viewportId,
renderingEngineId: this.id,
element, // div
type,
canvas,
sx: 0, // No offset, uses own renderer
sy: 0,
sWidth: clientWidth,
sHeight: clientHeight,
defaultOptions: defaultOptions || {},
};
// 4. Create a proper viewport based on the type of the viewport
if (type !== ViewportType.STACK) {
// In the future these will need to be pluggable, but we aren't there yet
// and these are just Stacks for now.
throw new Error('Support for fully custom viewports not yet implemented');
}
// 4.a Create stack viewport
const viewport = new StackViewport(viewportInput);
// 5. Storing the viewports
this._viewports.set(viewportId, viewport);
const eventDetail: EventTypes.ElementEnabledEventDetail = {
element,
viewportId,
renderingEngineId: this.id,
};
triggerEvent(eventTarget, Events.ELEMENT_ENABLED, eventDetail);
}
/**
* Sets multiple viewports using custom rendering
* pipelines to the `RenderingEngine`.
*
* @param viewportInputEntries - An array of information
* objects used to construct and enable the viewports.
*/
private setCustomViewports(viewportInputEntries: PublicViewportInput[]) {
viewportInputEntries.forEach((vpie) => this.addCustomViewport(vpie));
}
/**
* Sets multiple vtk.js driven viewports to
* the `RenderingEngine`.
*
* @param viewportInputEntries - An array of information
* objects used to construct and enable the viewports.
*/
private setVtkjsDrivenViewports(
viewportInputEntries: NormalizedViewportInput[]
) {
// Deal with vtkjs driven viewports
if (viewportInputEntries.length) {
// 1. Getting all the canvases from viewports calculation of the new offScreen size
const vtkDrivenCanvases = viewportInputEntries.map((vp) =>
getOrCreateCanvas(vp.element)
);
// Ensure the canvas size includes any scaling due to device pixel ratio
vtkDrivenCanvases.forEach((canvas) => {
const devicePixelRatio = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * devicePixelRatio;
canvas.height = rect.height * devicePixelRatio;
});
// 2. Set canvas size based on height and sum of widths
const { offScreenCanvasWidth, offScreenCanvasHeight } =
this._resizeOffScreenCanvas(vtkDrivenCanvases);
/*
TODO: Commenting this out until we can mock the Canvas usage in the tests (or use jsdom?)
if (!offScreenCanvasWidth || !offScreenCanvasHeight) {
throw new Error('Invalid offscreen canvas width or height')
}*/
// 3. Adding the viewports based on the viewportInputEntry definition to the
// rendering engine.
let xOffset = 0;
for (let i = 0; i < viewportInputEntries.length; i++) {
const vtkDrivenViewportInputEntry = viewportInputEntries[i];
const canvas = vtkDrivenCanvases[i];
const internalViewportEntry = {
...vtkDrivenViewportInputEntry,
canvas,
};
this.addVtkjsDrivenViewport(internalViewportEntry, {
offScreenCanvasWidth,
offScreenCanvasHeight,
xOffset,
});
// Incrementing the xOffset which provides the horizontal location of each
// viewport on the offScreen canvas
xOffset += canvas.width;
}
}
}
/**
* Resizes the offscreen canvas based on the provided vtk.js driven canvases.
*
* @param canvases - An array of HTML Canvas
*/
private _resizeOffScreenCanvas(
canvasesDrivenByVtkJs: Array<HTMLCanvasElement>
): { offScreenCanvasWidth: number; offScreenCanvasHeight: number } {
const { offScreenCanvasContainer, offscreenMultiRenderWindow } = this;
const devicePixelRatio = window.devicePixelRatio || 1;
// 1. Calculated the height of the offScreen canvas to be the maximum height
// between canvases
const offScreenCanvasHeight = Math.max(
...canvasesDrivenByVtkJs.map(
(canvas) => canvas.clientHeight * devicePixelRatio
)
);
// 2. Calculating the width of the offScreen canvas to be the sum of all
let offScreenCanvasWidth = 0;
canvasesDrivenByVtkJs.forEach((canvas) => {
offScreenCanvasWidth += canvas.clientWidth * devicePixelRatio;
});
offScreenCanvasContainer.width = offScreenCanvasWidth;
offScreenCanvasContainer.height = offScreenCanvasHeight;
// 3. Resize command
offscreenMultiRenderWindow.resize();
return { offScreenCanvasWidth, offScreenCanvasHeight };
}
/**
* Recalculates and updates the viewports location on the offScreen canvas upon its resize
*
* @param viewports - An array of viewports
* @param offScreenCanvasWidth - new offScreen canvas width
* @param offScreenCanvasHeight - new offScreen canvas height
*
* @returns _xOffset the final offset which will be used for the next viewport
*/
private _resize(
viewportsDrivenByVtkJs: Array<IStackViewport | IVolumeViewport>,
offScreenCanvasWidth: number,
offScreenCanvasHeight: number
): number {
// Redefine viewport properties
let _xOffset = 0;
const devicePixelRatio = window.devicePixelRatio || 1;
for (let i = 0; i < viewportsDrivenByVtkJs.length; i++) {
const viewport = viewportsDrivenByVtkJs[i];
const {
sxStartDisplayCoords,
syStartDisplayCoords,
sxEndDisplayCoords,
syEndDisplayCoords,
sx,
sy,
sWidth,
sHeight,
} = this._getViewportCoordsOnOffScreenCanvas(
viewport,
offScreenCanvasWidth,
offScreenCanvasHeight,
_xOffset
);
_xOffset += viewport.canvas.clientWidth * devicePixelRatio;
viewport.sx = sx;
viewport.sy = sy;
viewport.sWidth = sWidth;
viewport.sHeight = sHeight;
// Updating the renderer for the viewport
const renderer = this.offscreenMultiRenderWindow.getRenderer(viewport.id);
renderer.setViewport([
sxStartDisplayCoords,
syStartDisplayCoords,
sxEndDisplayCoords,