All files / packages/core/src/RenderingEngine Viewport.ts

62.85% Statements 330/525
51.35% Branches 152/296
64.47% Functions 49/76
62.47% Lines 323/517

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854                                                                                                                                1x                         1x                                   180x   180x 180x         180x                                 180x     180x                       180x 180x 180x 180x 180x 180x 180x 180x 180x 180x   180x 180x         180x 180x     180x 180x                 180x     180x               180x   180x       180x       180x 180x     180x 180x 180x                                         224x       3x   221x                 30107x                 23200x   23200x       23200x             229x   229x                                                                                             2x   2x       2x 2x   2x 2x 2x       2x       2x 6x   2x 2x   2x           2x 2x   2x 2x         2x 2x   2x           2x           1x       1x               1x             1x           1x         2x 1x     1x   1x             1x             1x             1x     2x       393x   393x 236x                 1355x               3792x                                 777x                                                         139x 139x     139x               22x 22x       22x 22x 22x               22x 22x                           161x 161x             161x     161x                       161x 161x   161x             161x       161x         161x 161x 161x       161x             139x 139x 139x             72x 72x 72x               470x 470x 470x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               391x               391x         391x 391x 391x 391x           391x 234x   234x 234x 234x 234x 234x 234x     391x 391x 391x           391x 391x 391x   391x 234x         702x   234x   234x       391x   391x   391x 391x   391x     391x                 391x     391x     391x       391x           391x           391x   391x         391x 391x           391x                 391x   391x   391x 391x     391x 369x     391x             391x   391x   391x                   391x                   760x                   391x                       24x 24x   24x 24x     24x     24x     24x                               8x 8x 8x 8x 8x         8x                                                                           369x 369x 369x 369x     369x                                                                                                         54x               15924x   15924x               7481x   7481x                                             1464x 1464x 1464x                     1464x             1464x       985x     985x 1x       1464x   985x     985x 1x       1464x 1058x     1464x 453x             1464x 787x     1464x 787x     1464x 776x     1464x 773x     1464x 391x       1464x 1464x   1464x 1071x 1071x   1071x 1071x   1071x 787x           787x       1071x 1058x         1071x 83x 83x 2x     81x 81x     81x       2x 2x         1462x 369x     1462x                             1853x 1281x                 1281x               161x 161x 161x                   242x         242x       266x       266x 266x       266x       266x 266x       266x   266x           266x                             357x 231x     126x         126x   126x 126x 126x 126x   126x         126x 126x 126x                                                           391x 391x   391x   391x         3128x     391x 391x 391x 3128x 3128x 780x   3128x 783x       391x               3128x     391x 391x 391x 3128x 3128x 626x   3128x 563x       391x                             14x 14x           14x                           123x             123x 123x 123x                     123x                                                                                                                                                                   269x 269x       782x                                 393x 369x     24x 22x         2x         2x 2x 2x   2x           2x         2x             2x                                                                                                                             391x 391x 391x           391x 391x          
import type { vtkCamera } from '@kitware/vtk.js/Rendering/Core/Camera';
import vtkMatrixBuilder from '@kitware/vtk.js/Common/Core/MatrixBuilder';
import vtkMath from '@kitware/vtk.js/Common/Core/Math';
import vtkPlane from '@kitware/vtk.js/Common/DataModel/Plane';
 
import { vec2, vec3 } from 'gl-matrix';
import _cloneDeep from 'lodash.clonedeep';
 
import Events from '../enums/Events';
import ViewportStatus from '../enums/ViewportStatus';
import ViewportType from '../enums/ViewportType';
import renderingEngineCache from './renderingEngineCache';
import {
  triggerEvent,
  planar,
  isImageActor,
  actorIsA,
  isEqual,
} from '../utilities';
import hasNaNValues from '../utilities/hasNaNValues';
import { RENDERING_DEFAULTS } from '../constants';
import type {
  ICamera,
  ActorEntry,
  IRenderingEngine,
  ViewportInputOptions,
  Point2,
  Point3,
  FlipDirection,
  EventTypes,
  DisplayArea,
  ViewPresentation,
  ViewReference,
  ViewportProperties,
} from '../types';
import type {
  ViewportInput,
  IViewport,
  ViewReferenceSpecifier,
  ReferenceCompatibleOptions,
  ViewPresentationSelector,
} from '../types/IViewport';
import type { vtkSlabCamera } from './vtkClasses/vtkSlabCamera';
import { getConfiguration } from '../init';
import IImageCalibration from '../types/IImageCalibration';
import { InterpolationType } from '../enums';
 
/**
 * An object representing a single viewport, which is a camera
 * looking into a viewport, and an associated target output `HTMLDivElement`.
 * Viewport is a base class that can be extended to create a specific
 * viewport type. Both VolumeViewport and StackViewport are subclasses
 * of Viewport. Common logic for all viewports is contained in Viewport class
 * which is camera properties/methods, vtk.js actors, and other common
 * logic.
 */
class Viewport implements IViewport {
  /**
   * CameraViewPresentation is a view preentation selector that has all the
   * camera related presentation selections, and would typically be used for
   * choosing presentation information between two viewports showing the same
   * type of orientation of a view, such as the CT, PT and fusion views in the
   * same orientation view.
   */
  public static readonly CameraViewPresentation: ViewPresentationSelector = {
    rotation: true,
    pan: true,
    zoom: true,
    displayArea: true,
  };
 
  /**
   * TransferViewPresentation is a view presentation selector that selects all
   * the transfer function related attributes.  It would typically be used for
   * synchronizing different orientations of the same series, or for
   * synchronizing two views of the same type of series such as a CT.
   */
  public static readonly TransferViewPresentation: ViewPresentationSelector = {
    windowLevel: true,
    paletteLut: true,
  };
 
  /** unique identifier for the viewport */
  readonly id: string;
  /** HTML element in DOM that is used for rendering the viewport */
  readonly element: HTMLDivElement;
  /** an internal canvas that is created on the provided HTML element */
  readonly canvas: HTMLCanvasElement;
  /** RenderingEngine id that the viewport belongs to */
  readonly renderingEngineId: string;
  /** Type of viewport */
  readonly type: ViewportType;
  /**
   * The amount by which the images are inset in a viewport by default.
   */
  protected insetImageMultiplier = 1.1;
 
  protected flipHorizontal = false;
  protected flipVertical = false;
  public isDisabled: boolean;
  /** Record the rendering status, mostly for testing purposes, but can also
   * be useful for knowing things like whether the viewport is initialized
   */
  public viewportStatus: ViewportStatus = ViewportStatus.NO_DATA;
 
  /** sx of viewport on the offscreen canvas */
  sx: number;
  /** sy of viewport on the offscreen canvas */
  sy: number;
  /** sWidth of viewport on the offscreen canvas */
  sWidth: number;
  /** sHeight of viewport on the offscreen canvas */
  sHeight: number;
  /** a Map containing the actor uid and actors */
  _actors: Map<string, any>;
  /** Default options for the viewport which includes orientation, viewPlaneNormal and backgroundColor */
  readonly defaultOptions: Record<string, any>;
  /** options for the viewport which includes orientation axis, backgroundColor and displayArea */
  options: ViewportInputOptions;
  /** informs if a new actor was added before a resetCameraClippingRange phase */
  _suppressCameraModifiedEvents = false;
  /** A flag representing if viewport methods should fire events or not */
  readonly suppressEvents: boolean;
  protected hasPixelSpacing = true;
  protected calibration: IImageCalibration;
  /** The camera that is initially defined on the reset for
   * the relative pan/zoom
   */
  protected initialCamera: ICamera;
  /** The camera that is defined for resetting displayArea to ensure absolute displayArea
   * settings
   */
  protected fitToCanvasCamera: ICamera;
 
  constructor(props: ViewportInput) {
    this.id = props.id;
    this.renderingEngineId = props.renderingEngineId;
    this.type = props.type;
    this.element = props.element;
    this.canvas = props.canvas;
    this.sx = props.sx;
    this.sy = props.sy;
    this.sWidth = props.sWidth;
    this.sHeight = props.sHeight;
    this._actors = new Map();
    // Set data attributes for render events
    this.element.setAttribute('data-viewport-uid', this.id);
    this.element.setAttribute(
      'data-rendering-engine-uid',
      this.renderingEngineId
    );
 
    this.defaultOptions = _cloneDeep(props.defaultOptions);
    this.suppressEvents = props.defaultOptions.suppressEvents
      ? props.defaultOptions.suppressEvents
      : false;
    this.options = _cloneDeep(props.defaultOptions);
    this.isDisabled = false;
  }
 
  getRotation: () => number;
  getFrameOfReferenceUID: () => string;
  canvasToWorld: (canvasPos: Point2) => Point3;
  worldToCanvas: (worldPos: Point3) => Point2;
  customRenderViewportToCanvas: () => unknown;
  resize: () => void;
  getProperties: () => ViewportProperties = () => ({});
  updateRenderingPipeline: () => void;
  getNumberOfSlices: () => number;
  protected setRotation = (_rotation: number) => {
    /*empty*/
  };
 
  static get useCustomRenderingPipeline(): boolean {
    return false;
  }
 
  private viewportWidgets = new Map() as Map<string, any>;
 
  public addWidget = (widgetId, widget) => {
    this.viewportWidgets.set(widgetId, widget);
  };
 
  public getWidget = (id) => {
    return this.viewportWidgets.get(id);
  };
 
  public getWidgets = () => {
    return Array.from(this.viewportWidgets.values());
  };
 
  public removeWidgets = () => {
    const widgets = this.getWidgets();
    widgets.forEach((widget) => {
      if (widget.getEnabled()) {
        widget.setEnabled(false);
      }
      if (widget.getActor && widget.getRenderer) {
        const actor = widget.getActor();
        const renderer = widget.getRenderer();
        if (renderer && actor) {
          renderer.removeActor(actor);
        }
      }
    });
  };
 
  /**
   * Indicate that the image has been rendered.
   * This will set the viewportStatus to RENDERED if there is image data
   * available to actually be rendered - otherwise, the rendering simply showed
   * the background image.
   */
  public setRendered() {
    if (
      this.viewportStatus === ViewportStatus.NO_DATA ||
      this.viewportStatus === ViewportStatus.LOADING
    ) {
      return;
    }
    this.viewportStatus = ViewportStatus.RENDERED;
  }
 
  /**
   * Returns the rendering engine driving the `Viewport`.
   *
   * @returns The RenderingEngine instance.
   */
  public getRenderingEngine(): IRenderingEngine {
    return renderingEngineCache.get(this.renderingEngineId);
  }
 
  /**
   * Returns the `vtkRenderer` responsible for rendering the `Viewport`.
   *
   * @returns The `vtkRenderer` for the `Viewport`.
   */
  public getRenderer(): any {
    const renderingEngine = this.getRenderingEngine();
 
    Iif (!renderingEngine || renderingEngine.hasBeenDestroyed) {
      throw new Error('Rendering engine has been destroyed');
    }
 
    return renderingEngine.offscreenMultiRenderWindow.getRenderer(this.id);
  }
 
  /**
   * Renders the `Viewport` using the `RenderingEngine`.
   */
  public render(): void {
    const renderingEngine = this.getRenderingEngine();
 
    renderingEngine.renderViewport(this.id);
  }
 
  /**
   * Sets new options and (TODO) applies them.
   *
   * @param options - The viewport options to set.
   * @param immediate - If `true`, renders the viewport after the options are set.
   */
  public setOptions(options: ViewportInputOptions, immediate = false): void {
    this.options = <ViewportInputOptions>_cloneDeep(options);
 
    // TODO When this is needed we need to move the camera position.
    // We can steal some logic from the tools we build to do this.
    if (this.options?.displayArea) {
      this.setDisplayArea(this.options?.displayArea);
    }
    if (immediate) {
      this.render();
    }
  }
 
  /**
   * Resets the options the `Viewport`'s `defaultOptions`
   *
   * @param immediate - If `true`, renders the viewport after the options are reset.
   */
  public reset(immediate = false) {
    this.options = _cloneDeep(this.defaultOptions);
 
    // TODO When this is needed we need to move the camera position.
    // We can steal some logic from the tools we build to do this.
 
    if (immediate) {
      this.render();
    }
  }
 
  /**
   * Flip the viewport on horizontal or vertical axis, this method
   * works with vtk-js backed rendering pipeline.
   *
   * @param flipOptions - Flip options specifying the axis of flip
   *    * flipOptions.flipHorizontal - Flip the viewport on horizontal axis
   *    * flipOptions.flipVertical - Flip the viewport on vertical axis
   */
  protected flip({ flipHorizontal, flipVertical }: FlipDirection): void {
    const imageData = this.getDefaultImageData();
 
    Iif (!imageData) {
      return;
    }
 
    const camera = this.getCamera();
    const { viewPlaneNormal, viewUp, focalPoint, position } = camera;
 
    const viewRight = vec3.cross(vec3.create(), viewPlaneNormal, viewUp);
    let viewUpToSet = vec3.copy(vec3.create(), viewUp);
    const viewPlaneNormalToSet = vec3.negate(vec3.create(), viewPlaneNormal);
 
    // for both flip horizontal and vertical we need to move the camera to the
    // other side of the image
    const distance = vec3.distance(position, focalPoint);
 
    // If the pan has been applied, we need to be able
    // apply the pan back
    const dimensions = imageData.getDimensions();
    const middleIJK = dimensions.map((d) => Math.floor(d / 2));
 
    const idx = [middleIJK[0], middleIJK[1], middleIJK[2]];
    const centeredFocalPoint = imageData.indexToWorld(idx, vec3.create());
 
    const resetFocalPoint = this._getFocalPointForResetCamera(
      centeredFocalPoint as Point3,
      camera,
      { resetPan: true, resetToCenter: false }
    );
 
    const panDir = vec3.subtract(vec3.create(), focalPoint, resetFocalPoint);
    const panValue = vec3.length(panDir);
 
    const getPanDir = (mirrorVec) => {
      const panDirMirror = vec3.scale(
        vec3.create(),
        mirrorVec,
        2 * vec3.dot(panDir, mirrorVec)
      );
      vec3.subtract(panDirMirror, panDirMirror, panDir);
      vec3.normalize(panDirMirror, panDirMirror);
 
      return panDirMirror;
    };
 
    // Flipping horizontal mean that the camera should move
    // to the other side of the image but looking at the
    // same direction and same focal point
    if (flipHorizontal) {
      // we need to apply the pan value to the new focal point but in the direction
      // that is mirrored on the viewUp for the flip horizontal and
      // viewRight for the flip vertical
 
      // mirror the pan direction based on the viewUp
      const panDirMirror = getPanDir(viewUpToSet);
 
      // move focal point from the resetFocalPoint to the newFocalPoint
      // based on the panDirMirror and panValue
      const newFocalPoint = vec3.scaleAndAdd(
        vec3.create(),
        resetFocalPoint,
        panDirMirror,
        panValue
      );
 
      // move the camera position also the same way as the focal point
      const newPosition = vec3.scaleAndAdd(
        vec3.create(),
        newFocalPoint,
        viewPlaneNormalToSet,
        distance
      );
 
      this.setCamera({
        viewPlaneNormal: viewPlaneNormalToSet as Point3,
        position: newPosition as Point3,
        focalPoint: newFocalPoint as Point3,
      });
 
      this.flipHorizontal = !this.flipHorizontal;
    }
 
    // Flipping vertical mean that the camera should negate the view up
    // and also move to the other side of the image but looking at the
    if (flipVertical) {
      viewUpToSet = vec3.negate(viewUpToSet, viewUp);
 
      // we need to apply the pan value to the new focal point but in the direction
      const panDirMirror = getPanDir(viewRight);
 
      const newFocalPoint = vec3.scaleAndAdd(
        vec3.create(),
        resetFocalPoint,
        panDirMirror,
        panValue
      );
 
      const newPosition = vec3.scaleAndAdd(
        vec3.create(),
        newFocalPoint,
        viewPlaneNormalToSet,
        distance
      );
 
      this.setCamera({
        focalPoint: newFocalPoint as Point3,
        viewPlaneNormal: viewPlaneNormalToSet as Point3,
        viewUp: viewUpToSet as Point3,
        position: newPosition as Point3,
      });
 
      this.flipVertical = !this.flipVertical;
    }
 
    this.render();
  }
 
  private getDefaultImageData(): any {
    const actorEntry = this.getDefaultActor();
 
    if (actorEntry && isImageActor(actorEntry)) {
      return actorEntry.actor.getMapper().getInputData();
    }
  }
 
  /**
   * Get the default actor
   * @returns An actor entry.
   */
  public getDefaultActor(): ActorEntry {
    return this.getActors()[0];
  }
 
  /**
   * Get all the actors in the viewport
   * @returns An array of ActorEntry objects.
   */
  public getActors(): Array<ActorEntry> {
    return Array.from(this._actors.values());
  }
 
  /**
   * Returns an array of unique identifiers for all the actors in the viewport.
   * @returns An array of strings
   */
  public getActorUIDs(): Array<string> {
    return Array.from(this._actors.keys());
  }
 
  /**
   * Get an actor by its UID
   * @param actorUID - The unique ID of the actor.
   * @returns An ActorEntry object.
   */
  public getActor(actorUID: string): ActorEntry {
    return this._actors.get(actorUID);
  }
 
  /**
   * Get an actor UID by its index
   * @param index - array index.
   * @returns actorUID
   */
  public getActorUIDByIndex(index: number): string {
    const actor = this.getActors()[index];
    if (actor) {
      return actor.uid;
    }
  }
 
  /**
   * Get an actor by its index
   * @param index - array index.
   * @returns actorUID
   */
  public getActorByIndex(index: number): ActorEntry {
    return this.getActors()[index];
  }
 
  /**
   * It removes all actors from the viewport and then adds the actors from the array.
   * @param actors - An array of ActorEntry objects.
   */
  public setActors(actors: Array<ActorEntry>): void {
    this.removeAllActors();
    const resetCameraPanAndZoom = true;
    // when we set the actor we need to reset the camera to initialize the
    // camera focal point with the bounds of the actors.
    this.addActors(actors, resetCameraPanAndZoom);
  }
 
  /**
   * Remove the actor from the viewport
   * @param actorUID - The unique identifier for the actor.
   */
  _removeActor(actorUID: string): void {
    const actorEntry = this.getActor(actorUID);
    Iif (!actorEntry) {
      console.warn(`Actor ${actorUID} does not exist for this viewport`);
      return;
    }
    const renderer = this.getRenderer();
    renderer.removeViewProp(actorEntry.actor); // removeActor not implemented in vtk?
    this._actors.delete(actorUID);
  }
 
  /**
   * Remove the actors with the given UIDs from the viewport
   * @param actorUIDs - An array of actor UIDs to remove.
   */
  public removeActors(actorUIDs: Array<string>): void {
    actorUIDs.forEach((actorUID) => {
      this._removeActor(actorUID);
    });
  }
 
  /**
   * Add a list of actors (actor entries) to the viewport
   * @param resetCameraPanAndZoom - force reset pan and zoom of the camera,
   *        default value is false.
   * @param actors - An array of ActorEntry objects.
   */
  public addActors(
    actors: Array<ActorEntry>,
    resetCameraPanAndZoom = false
  ): void {
    const renderingEngine = this.getRenderingEngine();
    Iif (!renderingEngine || renderingEngine.hasBeenDestroyed) {
      console.warn(
        'Viewport::addActors::Rendering engine has not been initialized or has been destroyed'
      );
      return;
    }
 
    actors.forEach((actor) => this.addActor(actor));
 
    // set the clipping planes for the actors
    this.resetCamera(resetCameraPanAndZoom, resetCameraPanAndZoom);
  }
 
  /**
   * Add an actor to the viewport including its id, its actor and slabThickness
   * if defined
   * @param actorEntry - ActorEntry
   *    * actorEntry.uid - The unique identifier for the actor.
   *    * actorEntry.actor - The volume actor.
   *    * actorEntry.slabThickness - The slab thickness.
   */
  public addActor(actorEntry: ActorEntry): void {
    const { uid: actorUID, actor } = actorEntry;
    const renderingEngine = this.getRenderingEngine();
 
    Iif (!renderingEngine || renderingEngine.hasBeenDestroyed) {
      console.warn(
        `Cannot add actor UID of ${actorUID} Rendering Engine has been destroyed`
      );
      return;
    }
 
    Iif (!actorUID || !actor) {
      throw new Error('Actors should have uid and vtk Actor properties');
    }
 
    Iif (this.getActor(actorUID)) {
      console.warn(`Actor ${actorUID} already exists for this viewport`);
      return;
    }
 
    const renderer = this.getRenderer();
    renderer?.addActor(actor);
    this._actors.set(actorUID, Object.assign({}, actorEntry));
 
    // when we add an actor we should update the camera clipping range and
    // clipping planes as well
    this.updateCameraClippingPlanesAndRange();
  }
 
  /**
   * Remove all actors from the renderer
   */
  public removeAllActors(): void {
    this.getRenderer()?.removeAllViewProps();
    this._actors = new Map();
    return;
  }
 
  /**
   * Reset the camera to the default viewport camera without firing events
   */
  protected resetCameraNoEvent(): void {
    this._suppressCameraModifiedEvents = true;
    this.resetCamera();
    this._suppressCameraModifiedEvents = false;
  }
 
  /**
   * Sets the camera to the default viewport camera without firing events
   * @param camera - The camera to use for the viewport.
   */
  protected setCameraNoEvent(camera: ICamera): void {
    this._suppressCameraModifiedEvents = true;
    this.setCamera(camera);
    this._suppressCameraModifiedEvents = false;
  }
 
  /**
   * Calculates the intersections between the volume's boundaries and the viewplane.
   * 1) Determine the viewplane using the camera's ViewplaneNormal and focalPoint.
   * 2) Using volumeBounds, calculate the line equation for the 3D volume's 12 edges.
   * 3) Intersect each edge to the viewPlane and see whether the intersection point is inside the volume bounds.
   * 4) Return list of intersection points
   * It should be noted that intersection points may range from 3 to 6 points.
   * Orthogonal views have four points of intersection.
   *
   * @param imageData - vtkImageData
   * @param focalPoint - camera focal point
   * @param normal - view plane normal
   * @returns intersections list
   */
  private _getViewImageDataIntersections(imageData, focalPoint, normal) {
    // Viewplane equation: Ax+By+Cz=D
    const A = normal[0];
    const B = normal[1];
    const C = normal[2];
    const D = A * focalPoint[0] + B * focalPoint[1] + C * focalPoint[2];
 
    // Computing the edges of the 3D cube
    const bounds = imageData.getBounds();
    const edges = this._getEdges(bounds);
 
    const intersections = [];
 
    for (const edge of edges) {
      // start point: [x0, y0, z0], end point: [x1, y1, z1]
      const [[x0, y0, z0], [x1, y1, z1]] = edge;
      // Check if the edge is parallel to plane
      if (A * (x1 - x0) + B * (y1 - y0) + C * (z1 - z0) === 0) {
        continue;
      }
      const intersectionPoint = planar.linePlaneIntersection(
        [x0, y0, z0],
        [x1, y1, z1],
        [A, B, C, D]
      );
 
      if (this._isInBounds(intersectionPoint, bounds)) {
        intersections.push(intersectionPoint);
      }
    }
 
    return intersections;
  }
 
  /**
   * Sets the interpolation type.  No-op in the base.
   */
  protected setInterpolationType(_interpolationType: InterpolationType, _arg?) {
    // No-op - just done to allow setting on the base viewport
  }
 
  /**
   * Sets the camera to an initial bounds. If
   * resetPan and resetZoom are true it places the focal point at the center of
   * the volume (or slice); otherwise, only the camera zoom and camera Pan or Zoom
   * is reset for the current view.
   * @param displayArea - The display area of interest.
   * @param suppressEvents - If true, don't fire displayArea event.
   */
  public setDisplayArea(
    displayArea: DisplayArea,
    suppressEvents = false
  ): void {
    if (!displayArea) {
      return;
    }
    const { storeAsInitialCamera, type: areaType } = displayArea;
 
    // Instead of storing the camera itself, if initial camera is set,
    // then store the display area as the baseline display area.
    if (storeAsInitialCamera) {
      this.options.displayArea = displayArea;
    }
 
    // make calculations relative to the fitToCanvasCamera view
    const { _suppressCameraModifiedEvents } = this;
    this._suppressCameraModifiedEvents = true;
 
    // This should only apply for storeAsInitialCamera, but the calculations
    // currently don't quite work otherwise.
    // TODO - fix so that the store works for existing transforms
    this.setCamera(this.fitToCanvasCamera);
 
    if (areaType === 'SCALE') {
      this.setDisplayAreaScale(displayArea);
    } else {
      this.setInterpolationType(
        this.getProperties().interpolationType || InterpolationType.LINEAR
      );
      this.setDisplayAreaFit(displayArea);
    }
 
    // Set the initial camera if appropriate
    if (storeAsInitialCamera) {
      this.initialCamera = this.getCamera();
    }
 
    // Restore event firing
    this._suppressCameraModifiedEvents = _suppressCameraModifiedEvents;
    if (!suppressEvents && !_suppressCameraModifiedEvents) {
      const eventDetail: EventTypes.DisplayAreaModifiedEventDetail = {
        viewportId: this.id,
        displayArea: displayArea,
        storeAsInitialCamera: storeAsInitialCamera,
      };
 
      triggerEvent(this.element, Events.DISPLAY_AREA_MODIFIED, eventDetail);
      this.setCamera(this.getCamera());
    }
  }
 
  /**
   * Sets the viewport to pixel scaling mode.  Pixel scaling displays
   * 1 image pixel as 1 (or scale) physical screen pixels.  That is,
   * a 1024x512 image will be displayed with scale=2, as 2048x1024
   * physical image pixels.
   *
   * @param displayArea - display area to set
   *    * displayArea.scale - the number of physical pixels to display
   *        each image pixel in.  Values `< 1` mean smaller than physical,
   *        while values `> 1` mean more than one pixel.  Default is 1
   *        Suggest using whole numbers or integer fractions (eg `1/3`)
   */
  protected setDisplayAreaScale(displayArea: DisplayArea): void {
    const { scale = 1 } = displayArea;
    const canvas = this.canvas;
    const height = canvas.height;
    const width = canvas.width;
    if (height < 8 || width < 8) {
      return;
    }
    const imageData = this.getDefaultImageData();
    const spacingWorld = imageData.getSpacing();
    const spacing = spacingWorld[1];
    // Need nearest interpolation for scale
    this.setInterpolationType(InterpolationType.NEAREST);
    this.setCamera({ parallelScale: (height * spacing) / (2 * scale) });
 
    // If this is scale, then image area isn't allowed, so just delete it to be safe
    delete displayArea.imageArea;
    // Apply the pan values from the display area.
    this.setDisplayAreaFit(displayArea);
 
    // Need to ensure the focal point is aligned with the canvas size/position
    // so that we don't get half pixel rendering, which causes additional
    // moire patterns to be displayed.
    // This is based on the canvas size having the center pixel be at a fractional
    // position when the size is even, so matching a fractional position on the
    // focal point to the center of an image pixel.
    const { focalPoint, position, viewUp, viewPlaneNormal } = this.getCamera();
    const focalChange = vec3.create();
    if (canvas.height % 2) {
      vec3.scaleAndAdd(focalChange, focalChange, viewUp, scale * 0.5 * spacing);
    }
    if (canvas.width % 2) {
      const viewRight = vec3.cross(vec3.create(), viewUp, viewPlaneNormal);
      vec3.scaleAndAdd(
        focalChange,
        focalChange,
        viewRight,
        scale * 0.5 * spacing
      );
    }
    if (!focalChange[0] && !focalChange[1] && !focalChange[2]) {
      return;
    }
    this.setCamera({
      focalPoint: <Point3>vec3.add(vec3.create(), focalPoint, focalChange),
      position: <Point3>vec3.add(vec3.create(), position, focalChange),
    });
  }
 
  /**
   * This applies a display area with a fit of the provided area to the
   * available area.
   * The zoom level is controlled by the imageArea parameter, which is a pair
   * of percentage width in the horizontal and vertical dimension is scaled
   * to fit the displayable area.  Both values are taken into account, and the
   * scaling is set so that both fractions of the image area are visible.
   *
   * The panning is controlled by the imageCanvasPoint, which has two
   * values, teh imagePoint and the canvasPoint.  They are fractional
   * values of the image and canvas respectively, with the panning set to
   * display the image pixel at the given fraction on top of the canvas at the
   * given percentage.  The default points are 0.5.
   *
   * For example, if the zoom level is [2,1], then the image is displayed
   * such that at least twice the width is visible, and the height is visible.
   * That will result in the image width being black, divided up on the left
   * and right according to the imageCanvasPoint
   *
   * Then, if the imagePoint is [1,0] and the canvas point is [1,0], then
   * the right most edge of the image, at the top of the image, will be
   * displayed at the right most edge of the canvas, at the top.
   *
   */
  protected setDisplayAreaFit(displayArea: DisplayArea) {
    const { imageArea, imageCanvasPoint } = displayArea;
 
    const devicePixelRatio = window?.devicePixelRatio || 1;
    const imageData = this.getDefaultImageData();
    if (!imageData) {
      return;
    }
    const canvasWidth = this.sWidth / devicePixelRatio;
    const canvasHeight = this.sHeight / devicePixelRatio;
    const dimensions = imageData.getDimensions();
    const canvasZero = this.worldToCanvas(imageData.indexToWorld([0, 0, 0]));
    const canvasEdge = this.worldToCanvas(
      imageData.indexToWorld([
        dimensions[0] - 1,
        dimensions[1] - 1,
        dimensions[2],
      ])
    );
 
    const canvasImage = [
      Math.abs(canvasEdge[0] - canvasZero[0]),
      Math.abs(canvasEdge[1] - canvasZero[1]),
    ];
    const [imgWidth, imgHeight] = canvasImage;
 
    if (imageArea) {
      const [areaX, areaY] = imageArea;
      const requireX = Math.abs((areaX * imgWidth) / canvasWidth);
      const requireY = Math.abs((areaY * imgHeight) / canvasHeight);
 
      const initZoom = this.getZoom();
      const fitZoom = this.getZoom(this.fitToCanvasCamera);
      const absZoom = Math.min(1 / requireX, 1 / requireY);
      const applyZoom = (absZoom * initZoom) / fitZoom;
      this.setZoom(applyZoom, false);
    }
 
    // getting the image info
    // getting the image info
    if (imageCanvasPoint) {
      const { imagePoint, canvasPoint = imagePoint || [0.5, 0.5] } =
        imageCanvasPoint;
      const [canvasX, canvasY] = canvasPoint;
      const canvasPanX = canvasWidth * (canvasX - 0.5);
      const canvasPanY = canvasHeight * (canvasY - 0.5);
 
      const [imageX, imageY] = imagePoint || canvasPoint;
      const useZoom = 1;
      const imagePanX = useZoom * imgWidth * (0.5 - imageX);
      const imagePanY = useZoom * imgHeight * (0.5 - imageY);
 
      const newPositionX = imagePanX + canvasPanX;
      const newPositionY = imagePanY + canvasPanY;
 
      const deltaPoint2: Point2 = [newPositionX, newPositionY];
      // Use getPan from current for the setting
      vec2.add(deltaPoint2, deltaPoint2, this.getPan());
      // The pan is part of the display area settings, not the initial camera, so
      // don't store as initial camera here - that breaks rotation and other changes.
      this.setPan(deltaPoint2, false);
    }
  }
 
  public getDisplayArea(): DisplayArea | undefined {
    return this.options?.displayArea;
  }
 
  /**
   * Resets the camera based on the rendering volume(s) bounds. If
   * resetPan and resetZoom are true it places the focal point at the center of
   * the volume (or slice); otherwise, only the camera zoom and camera Pan or Zoom
   * is reset for the current view.
   * @param resetPan - If true, the camera focal point is reset to the center of the volume (slice)
   * @param resetZoom - If true, the camera zoom is reset to the default zoom
   * @param storeAsInitialCamera - If true, reset camera is stored as the initial camera (to allow differences to
   *   be detected for pan/zoom values)
   * @returns boolean
   */
  public resetCamera(
    resetPan = true,
    resetZoom = true,
    resetToCenter = true,
    storeAsInitialCamera = true
  ): boolean {
    const renderer = this.getRenderer();
 
    // fix the flip right away, since we rely on the viewPlaneNormal and
    // viewUp for later. Basically, we need to flip back if flipHorizontal
    // is true or flipVertical is true
    // we should use resetCamera no event here, since we don't want to fire
    // camera modified events yet since a proper one will be fired later down
    // below
    this.setCameraNoEvent({
      flipHorizontal: false,
      flipVertical: false,
    });
 
    const previousCamera = _cloneDeep(this.getCamera());
    const bounds = renderer.computeVisiblePropBounds();
    const focalPoint = <Point3>[0, 0, 0];
    const imageData = this.getDefaultImageData();
 
    // The bounds are used to set the clipping view, which is then used to
    // figure out the center point of each image.  This needs to be the depth
    // center, so the bounds need to be extended by the spacing such that the
    // depth center is in the middle of each image.
    if (imageData) {
      const spc = imageData.getSpacing();
 
      bounds[0] = bounds[0] + spc[0] / 2;
      bounds[1] = bounds[1] - spc[0] / 2;
      bounds[2] = bounds[2] + spc[1] / 2;
      bounds[3] = bounds[3] - spc[1] / 2;
      bounds[4] = bounds[4] + spc[2] / 2;
      bounds[5] = bounds[5] - spc[2] / 2;
    }
 
    const activeCamera = this.getVtkActiveCamera();
    const viewPlaneNormal = <Point3>activeCamera.getViewPlaneNormal();
    const viewUp = <Point3>activeCamera.getViewUp();
 
    // Reset the perspective zoom factors, otherwise subsequent zooms will cause
    // the view angle to become very small and cause bad depth sorting.
    // todo: parallel projection only
 
    focalPoint[0] = (bounds[0] + bounds[1]) / 2.0;
    focalPoint[1] = (bounds[2] + bounds[3]) / 2.0;
    focalPoint[2] = (bounds[4] + bounds[5]) / 2.0;
 
    if (imageData) {
      const dimensions = imageData.getDimensions();
      // TODO: This should be the line below, but that causes issues with existing
      // tests.  Not doing that adds significant fuzziness on rendering, so at
      // some point it should be fixed.
      // const middleIJK = dimensions.map((d) => Math.floor((d-1) / 2));
      const middleIJK = dimensions.map((d) => Math.floor(d / 2));
 
      const idx = [middleIJK[0], middleIJK[1], middleIJK[2]];
      // Modifies the focal point in place, as this hits the vtk indexToWorld function
      imageData.indexToWorld(idx, focalPoint);
    }
 
    const { widthWorld, heightWorld } =
      this._getWorldDistanceViewUpAndViewRight(bounds, viewUp, viewPlaneNormal);
 
    const canvasSize = [this.sWidth, this.sHeight];
 
    const boundsAspectRatio = widthWorld / heightWorld;
    const canvasAspectRatio = canvasSize[0] / canvasSize[1];
 
    const scaleFactor = boundsAspectRatio / canvasAspectRatio;
 
    const parallelScale =
      scaleFactor < 1 // can fit full height, so use it.
        ? (this.insetImageMultiplier * heightWorld) / 2
        : (this.insetImageMultiplier * heightWorld * scaleFactor) / 2;
 
    // If we have just a single point, pick a radius of 1.0
    // compute the radius of the enclosing sphere
    // For 3D viewport, we should increase the radius to make sure the whole
    // volume is visible and we don't get clipping artifacts.
    const radius =
      Viewport.boundsRadius(bounds) *
      (this.type === ViewportType.VOLUME_3D ? 10 : 1);
 
    const distance = this.insetImageMultiplier * radius;
 
    const viewUpToSet: Point3 =
      Math.abs(vtkMath.dot(viewUp, viewPlaneNormal)) > 0.999
        ? [-viewUp[2], viewUp[0], viewUp[1]]
        : viewUp;
 
    const focalPointToSet = this._getFocalPointForResetCamera(
      focalPoint,
      previousCamera,
      { resetPan, resetToCenter }
    );
 
    const positionToSet: Point3 = [
      focalPointToSet[0] + distance * viewPlaneNormal[0],
      focalPointToSet[1] + distance * viewPlaneNormal[1],
      focalPointToSet[2] + distance * viewPlaneNormal[2],
    ];
 
    renderer.resetCameraClippingRange(bounds);
 
    const clippingRangeToUse: Point2 = [
      -RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE,
      RENDERING_DEFAULTS.MAXIMUM_RAY_DISTANCE,
    ];
 
    activeCamera.setPhysicalScale(radius);
    activeCamera.setPhysicalTranslation(
      -focalPointToSet[0],
      -focalPointToSet[1],
      -focalPointToSet[2]
    );
 
    this.setCamera({
      parallelScale: resetZoom ? parallelScale : previousCamera.parallelScale,
      focalPoint: focalPointToSet,
      position: positionToSet,
      viewAngle: 90,
      viewUp: viewUpToSet,
      clippingRange: clippingRangeToUse,
    });
 
    const modifiedCamera = _cloneDeep(this.getCamera());
 
    this.setFitToCanvasCamera(_cloneDeep(this.getCamera()));
 
    Eif (storeAsInitialCamera) {
      this.setInitialCamera(modifiedCamera);
    }
 
    if (resetZoom) {
      this.setZoom(1, storeAsInitialCamera);
    }
 
    const RESET_CAMERA_EVENT = {
      type: 'ResetCameraEvent',
      renderer,
    };
 
    // Here to let parallel/distributed compositing intercept
    // and do the right thing.
    renderer.invokeEvent(RESET_CAMERA_EVENT);
 
    this.triggerCameraModifiedEventIfNecessary(previousCamera, modifiedCamera);
 
    Iif (
      imageData &&
      this.options?.displayArea &&
      resetZoom &&
      resetPan &&
      resetToCenter
    ) {
      this.setDisplayArea(this.options?.displayArea);
    }
 
    return true;
  }
 
  /**
   * Sets the provided camera as the initial camera.
   * This allows computing differences applied later as compared to the initial
   * position, for things like zoom and pan.
   * @param camera - to store as the initial value.
   */
  protected setInitialCamera(camera: ICamera): void {
    this.initialCamera = camera;
  }
 
  /**
   * Sets the provided camera as the displayArea camera.
   * This allows computing differences applied later as compared to the initial
   * position, for things like zoom and pan.
   * @param camera - to store as the initial value.
   */
  protected setFitToCanvasCamera(camera: ICamera): void {
    this.fitToCanvasCamera = camera;
  }
 
  /**
   * Helper function to return the current canvas pan value.
   *
   * @returns a Point2 containing the current pan values
   * on the canvas,
   * computed from the current camera, where the initial pan
   * value is [0,0].
   */
  public getPan(initialCamera = this.initialCamera): Point2 {
    const activeCamera = this.getVtkActiveCamera();
    const focalPoint = activeCamera.getFocalPoint() as Point3;
 
    const zero3 = this.canvasToWorld([0, 0]);
    const initialCanvasFocal = this.worldToCanvas(
      <Point3>vec3.subtract([0, 0, 0], initialCamera.focalPoint, zero3)
    );
    const currentCanvasFocal = this.worldToCanvas(
      <Point3>vec3.subtract([0, 0, 0], focalPoint, zero3)
    );
    const result = <Point2>(
      vec2.subtract([0, 0], initialCanvasFocal, currentCanvasFocal)
    );
    return result;
  }
 
  public getCurrentImageIdIndex(): number {
    throw new Error('Not implemented');
  }
 
  public getReferenceId(_specifier?: ViewReferenceSpecifier): string {
    return null;
  }
 
  /**
   * Sets the canvas pan value relative to the initial view position of 0,0
   * Modifies the camera to perform the pan.
   */
  public setPan(pan: Point2, storeAsInitialCamera = false): void {
    const previousCamera = this.getCamera();
    const { focalPoint, position } = previousCamera;
    const zero3 = this.canvasToWorld([0, 0]);
    const delta2 = vec2.subtract([0, 0], pan, this.getPan());
    Eif (
      Math.abs(delta2[0]) < 1 &&
      Math.abs(delta2[1]) < 1 &&
      !storeAsInitialCamera
    ) {
      return;
    }
    const delta = vec3.subtract(
      vec3.create(),
      this.canvasToWorld(<Point2>delta2),
      zero3
    );
    const newFocal = vec3.subtract(vec3.create(), focalPoint, delta);
    const newPosition = vec3.subtract(vec3.create(), position, delta);
    this.setCamera(
      {
        ...previousCamera,
        focalPoint: newFocal as Point3,
        position: newPosition as Point3,
      },
      storeAsInitialCamera
    );
  }
 
  /**
   * Returns a current zoom level relative to the initial parallel scale
   * originally applied to the image.  That is, on initial display,
   * the zoom level is 1.  Computed as a function of the camera.
   */
  public getZoom(compareCamera = this.initialCamera): number {
    const activeCamera = this.getVtkActiveCamera();
    const { parallelScale: initialParallelScale } = compareCamera;
    return initialParallelScale / activeCamera.getParallelScale();
  }
 
  /** Zooms the image using parallel scale by updating the camera value.
   * @param value - The relative parallel scale to apply.  It is relative
   * to the initial offsets value.
   * @param storeAsInitialCamera - can be set to true to reset the camera
   *   after applying this zoom as the initial camera.  A subsequent getZoom
   *   call will return "1", but the zoom will have been applied.
   */
  public setZoom(value: number, storeAsInitialCamera = false): void {
    const camera = this.getCamera();
    const { parallelScale: initialParallelScale } = this.initialCamera;
    const parallelScale = initialParallelScale / value;
    Iif (camera.parallelScale === parallelScale && !storeAsInitialCamera) {
      return;
    }
    this.setCamera(
      {
        ...camera,
        parallelScale,
      },
      storeAsInitialCamera
    );
  }
 
  /**
   * Because the focalPoint is always in the centre of the viewport,
   * we must do planar computations if the frame (image "slice") is to be preserved.
   * 1. Calculate the intersection of the view plane with the imageData
   * which results in points of intersection (minimum of 3, maximum of 6)
   * 2. Calculate average of the intersection points to get newFocalPoint
   * 3. Set the new focalPoint
   * @param imageData - imageData
   * @returns focalPoint
   */
  private _getFocalPointForViewPlaneReset(imageData) {
    // Todo: move some where else
    const { focalPoint, viewPlaneNormal: normal } = this.getCamera();
    const intersections = this._getViewImageDataIntersections(
      imageData,
      focalPoint,
      normal
    );
 
    let x = 0;
    let y = 0;
    let z = 0;
 
    intersections.forEach(([point_x, point_y, point_z]) => {
      x += point_x;
      y += point_y;
      z += point_z;
    });
 
    const newFocalPoint = <Point3>[
      x / intersections.length,
      y / intersections.length,
      z / intersections.length,
    ];
    // Set the focal point on the average of the intersection points
    return newFocalPoint;
  }
 
  /**
   * Gets the target output canvas for the `Viewport`.
   *
   * @returns an HTMLCanvasElement.
   */
  public getCanvas(): HTMLCanvasElement {
    return <HTMLCanvasElement>this.canvas;
  }
  /**
   * Gets the active vtkCamera for the viewport.
   *
   * @returns vtk driven camera
   */
  protected getVtkActiveCamera(): vtkCamera | vtkSlabCamera {
    const renderer = this.getRenderer();
 
    return renderer.getActiveCamera();
  }
 
  /**
   * Get the camera's current state
   * @returns The camera object.
   */
  public getCamera(): ICamera {
    const vtkCamera = this.getVtkActiveCamera();
 
    return {
      viewUp: <Point3>vtkCamera.getViewUp(),
      viewPlaneNormal: <Point3>vtkCamera.getViewPlaneNormal(),
      position: <Point3>vtkCamera.getPosition(),
      focalPoint: <Point3>vtkCamera.getFocalPoint(),
      parallelProjection: vtkCamera.getParallelProjection(),
      parallelScale: vtkCamera.getParallelScale(),
      viewAngle: vtkCamera.getViewAngle(),
      flipHorizontal: this.flipHorizontal,
      flipVertical: this.flipVertical,
    };
  }
 
  /**
   * Set the camera parameters
   * @param cameraInterface - ICamera
   * @param storeAsInitialCamera - to set the provided camera as the initial one,
   *    used to compute differences for things like pan and zoom.
   */
  public setCamera(
    cameraInterface: ICamera,
    storeAsInitialCamera = false
  ): void {
    const vtkCamera = this.getVtkActiveCamera();
    const previousCamera = _cloneDeep(this.getCamera());
    const updatedCamera = Object.assign({}, previousCamera, cameraInterface);
    const {
      viewUp,
      viewPlaneNormal,
      position,
      focalPoint,
      parallelScale,
      viewAngle,
      flipHorizontal,
      flipVertical,
      clippingRange,
    } = cameraInterface;
 
    // Note: Flip camera should be two separate calls since
    // for flip, we need to flip the viewportNormal, and if
    // flipHorizontal, and flipVertical are both true, that would
    // the logic would be incorrect. So instead, we handle flip Horizontal
    // and flipVertical separately.
    if (flipHorizontal !== undefined) {
      // flip if not flipped but requested to flip OR if flipped but requested to
      // not flip
      const flipH =
        (flipHorizontal && !this.flipHorizontal) ||
        (!flipHorizontal && this.flipHorizontal);
 
      if (flipH) {
        this.flip({ flipHorizontal: flipH });
      }
    }
 
    if (flipVertical !== undefined) {
      const flipV =
        (flipVertical && !this.flipVertical) ||
        (!flipVertical && this.flipVertical);
 
      if (flipV) {
        this.flip({ flipVertical: flipV });
      }
    }
 
    if (viewUp !== undefined) {
      vtkCamera.setViewUp(viewUp);
    }
 
    if (viewPlaneNormal !== undefined) {
      vtkCamera.setDirectionOfProjection(
        -viewPlaneNormal[0],
        -viewPlaneNormal[1],
        -viewPlaneNormal[2]
      );
    }
 
    if (position !== undefined) {
      vtkCamera.setPosition(...position);
    }
 
    if (focalPoint !== undefined) {
      vtkCamera.setFocalPoint(...focalPoint);
    }
 
    if (parallelScale !== undefined) {
      vtkCamera.setParallelScale(parallelScale);
    }
 
    if (viewAngle !== undefined) {
      vtkCamera.setViewAngle(viewAngle);
    }
 
    if (clippingRange !== undefined) {
      vtkCamera.setClippingRange(clippingRange);
    }
 
    // update clipping range only if focal point changed of a new actor is added
    const prevFocalPoint = previousCamera.focalPoint;
    const prevViewUp = previousCamera.viewUp;
 
    if ((prevFocalPoint && focalPoint) || (prevViewUp && viewUp)) {
      const currentViewPlaneNormal = <Point3>vtkCamera.getViewPlaneNormal();
      const currentViewUp = <Point3>vtkCamera.getViewUp();
 
      let cameraModifiedOutOfPlane = false;
      let viewUpHasChanged = false;
 
      if (focalPoint) {
        const deltaCamera = <Point3>[
          focalPoint[0] - prevFocalPoint[0],
          focalPoint[1] - prevFocalPoint[1],
          focalPoint[2] - prevFocalPoint[2],
        ];
 
        cameraModifiedOutOfPlane =
          Math.abs(vtkMath.dot(deltaCamera, currentViewPlaneNormal)) > 0;
      }
 
      if (viewUp) {
        viewUpHasChanged = !isEqual(currentViewUp, prevViewUp);
      }
 
      // only modify the clipping planes if the camera is modified out of plane
      // or a new actor is added and we need to update the clipping planes
      if (cameraModifiedOutOfPlane || viewUpHasChanged) {
        const actorEntry = this.getDefaultActor();
        if (!actorEntry?.actor) {
          return;
        }
 
        Eif (!actorIsA(actorEntry, 'vtkActor')) {
          this.updateClippingPlanesForActors(updatedCamera);
        }
 
        if (
          actorIsA(actorEntry, 'vtkImageSlice') ||
          this.type === ViewportType.VOLUME_3D
        ) {
          const renderer = this.getRenderer();
          renderer.resetCameraClippingRange();
        }
      }
    }
 
    if (storeAsInitialCamera) {
      this.setInitialCamera(updatedCamera);
    }
 
    this.triggerCameraModifiedEventIfNecessary(
      previousCamera,
      this.getCamera()
    );
  }
 
  /**
   * Trigger camera modified event
   * @param cameraInterface - ICamera
   * @param cameraInterface - ICamera
   */
  public triggerCameraModifiedEventIfNecessary(
    previousCamera: ICamera,
    updatedCamera: ICamera
  ): void {
    if (!this._suppressCameraModifiedEvents && !this.suppressEvents) {
      const eventDetail: EventTypes.CameraModifiedEventDetail = {
        previousCamera,
        camera: updatedCamera,
        element: this.element,
        viewportId: this.id,
        renderingEngineId: this.renderingEngineId,
        rotation: this.getRotation(),
      };
 
      triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
    }
  }
 
  /**
   * Updates the camera's clipping planes and range.
   */
  public updateCameraClippingPlanesAndRange(): void {
    const currentCamera = this.getCamera();
    this.updateClippingPlanesForActors(currentCamera);
    this.getRenderer().resetCameraClippingRange();
  }
 
  /**
   * Updates the actors clipping planes orientation from the camera properties
   * @param updatedCamera - ICamera
   */
  protected async updateClippingPlanesForActors(
    updatedCamera: ICamera
  ): Promise<void> {
    const actorEntries = this.getActors();
    // Todo: this was using an async and promise wait all because of the
    // new surface rendering use case, which broke the more important 3D
    // volume rendering, so reverting this back for now until I can figure
    // out a better way to handle this.
    actorEntries.map((actorEntry) => {
      // we assume that the first two clipping plane of the mapper are always
      // the 'camera' clipping. Update clipping planes only if the actor is
      // a vtkVolume
      Iif (!actorEntry.actor) {
        return;
      }
 
      const mapper = actorEntry.actor.getMapper();
      let vtkPlanes = actorEntry?.clippingFilter
        ? actorEntry.clippingFilter.getClippingPlanes()
        : mapper.getClippingPlanes();
 
      Iif (vtkPlanes.length === 0 && actorEntry?.clippingFilter) {
        vtkPlanes = [vtkPlane.newInstance(), vtkPlane.newInstance()];
      }
 
      let slabThickness = RENDERING_DEFAULTS.MINIMUM_SLAB_THICKNESS;
      Iif (actorEntry.slabThickness) {
        slabThickness = actorEntry.slabThickness;
      }
 
      const { viewPlaneNormal, focalPoint } = updatedCamera;
 
      this.setOrientationOfClippingPlanes(
        vtkPlanes,
        slabThickness,
        viewPlaneNormal,
        focalPoint
      );
      triggerEvent(this.element, Events.CLIPPING_PLANES_UPDATED, {
        actorEntry,
        focalPoint,
        vtkPlanes,
        viewport: this,
      });
    });
  }
 
  public setOrientationOfClippingPlanes(
    vtkPlanes: Array<vtkPlane>,
    slabThickness: number,
    viewPlaneNormal: Point3,
    focalPoint: Point3
  ): void {
    if (vtkPlanes.length < 2) {
      return;
    }
 
    const scaledDistance = <Point3>[
      viewPlaneNormal[0],
      viewPlaneNormal[1],
      viewPlaneNormal[2],
    ];
    vtkMath.multiplyScalar(scaledDistance, slabThickness);
 
    vtkPlanes[0].setNormal(viewPlaneNormal);
    const newOrigin1 = <Point3>[0, 0, 0];
    vtkMath.subtract(focalPoint, scaledDistance, newOrigin1);
    vtkPlanes[0].setOrigin(newOrigin1);
 
    vtkPlanes[1].setNormal(
      -viewPlaneNormal[0],
      -viewPlaneNormal[1],
      -viewPlaneNormal[2]
    );
    const newOrigin2 = <Point3>[0, 0, 0];
    vtkMath.add(focalPoint, scaledDistance, newOrigin2);
    vtkPlanes[1].setOrigin(newOrigin2);
  }
 
  /**
   * Method to get the clipping planes of a given actor
   * @param actorEntry - The actor entry (a specific type you'll define dependent on your code)
   * @returns vtkPlanes - An array of vtkPlane objects associated with the given actor
   */
  public getClippingPlanesForActor(actorEntry?: ActorEntry): vtkPlane[] {
    if (!actorEntry) {
      actorEntry = this.getDefaultActor();
    }
 
    if (!actorEntry.actor) {
      throw new Error('Invalid actor entry: Actor is undefined');
    }
 
    const mapper = actorEntry.actor.getMapper();
    let vtkPlanes = actorEntry?.clippingFilter
      ? actorEntry.clippingFilter.getClippingPlanes()
      : mapper.getClippingPlanes();
 
    if (vtkPlanes.length === 0 && actorEntry?.clippingFilter) {
      vtkPlanes = [vtkPlane.newInstance(), vtkPlane.newInstance()];
    }
 
    return vtkPlanes;
  }
 
  private _getWorldDistanceViewUpAndViewRight(bounds, viewUp, viewPlaneNormal) {
    const viewUpCorners = this._getCorners(bounds);
    const viewRightCorners = this._getCorners(bounds);
 
    const viewRight = vec3.cross(vec3.create(), viewUp, viewPlaneNormal);
 
    let transform = vtkMatrixBuilder
      .buildFromDegree()
      .identity()
      .rotateFromDirections(viewUp, [1, 0, 0]);
 
    viewUpCorners.forEach((pt) => transform.apply(pt));
 
    // range is now maximum X distance
    let minY = Infinity;
    let maxY = -Infinity;
    for (let i = 0; i < 8; i++) {
      const y = viewUpCorners[i][0];
      if (y > maxY) {
        maxY = y;
      }
      if (y < minY) {
        minY = y;
      }
    }
 
    transform = vtkMatrixBuilder
      .buildFromDegree()
      .identity()
      .rotateFromDirections(
        [viewRight[0], viewRight[1], viewRight[2]],
        [1, 0, 0]
      );
 
    viewRightCorners.forEach((pt) => transform.apply(pt));
 
    // range is now maximum Y distance
    let minX = Infinity;
    let maxX = -Infinity;
    for (let i = 0; i < 8; i++) {
      const x = viewRightCorners[i][0];
      if (x > maxX) {
        maxX = x;
      }
      if (x < minX) {
        minX = x;
      }
    }
 
    return { widthWorld: maxX - minX, heightWorld: maxY - minY };
  }
 
  /**
   * Gets a view target specifying WHAT a view is displaying,
   * allowing for checking if a given image is displayed or could be displayed
   * in a given viewport.
   * See getViewPresentation for HOW a view is displayed.
   *
   * @param viewRefSpecifier - choose an alternate view to be specified, typically
   *      a different slice index in the same set of images.
   */
  public getViewReference(
    viewRefSpecifier: ViewReferenceSpecifier = {}
  ): ViewReference {
    const { focalPoint: cameraFocalPoint, viewPlaneNormal } = this.getCamera();
    const target: ViewReference = {
      FrameOfReferenceUID: this.getFrameOfReferenceUID(),
      cameraFocalPoint,
      viewPlaneNormal,
      sliceIndex: viewRefSpecifier.sliceIndex ?? this.getCurrentImageIdIndex(),
    };
    return target;
  }
 
  /**
   * Find out if this viewport does or could show this view reference.
   *
   * @param options - allows specifying whether the view COULD display this with
   *                  some modification - either navigation or displaying as volume.
   * @returns true if the viewport could show this view reference
   */
  public isReferenceViewable(
    viewRef: ViewReference,
    options?: ReferenceCompatibleOptions
  ): boolean {
    Iif (
      viewRef.FrameOfReferenceUID &&
      viewRef.FrameOfReferenceUID !== this.getFrameOfReferenceUID()
    ) {
      return false;
    }
 
    const { viewPlaneNormal } = viewRef;
    const camera = this.getCamera();
    Iif (
      viewPlaneNormal &&
      !isEqual(viewPlaneNormal, camera.viewPlaneNormal) &&
      !isEqual(
        vec3.negate(camera.viewPlaneNormal, camera.viewPlaneNormal),
        viewPlaneNormal
      )
    ) {
      // Could navigate as a volume to the reference
      return options?.asVolume === true;
    }
    return true;
  }
 
  /**
   * Gets a view presentation information specifying HOW a viewport displays
   * something, but not what is being displayed.
   * See getViewReference to get information on WHAT is being displayed.
   *
   * This is intended to have information on how an image is presented to the user, without
   * specifying what image s displayed.  All of this information is available
   * externally, but this method combines the parts of this that are appropriate
   * for remember or applying to other views, without necessarily needing to know
   * what all the atributes are.  That differs from methods like getCamera which
   * fetch exact view details that are not likely to be identical between viewports
   * as they change sizes or apply to different images.
   *
   * Note that the results of this can be used on different viewports, for example,
   * the pan values can be applied to a volume viewport showing a CT, and a
   * stack viewport showing an ultrasound.
   *
   * The selector allows choosing which view presentation attributes to return.
   * Some default values are available from `Viewport.CameraViewPresentation` and
   * `Viewport.TransferViewPresentation`
   *
   * @param viewPresSel - select which attributes to display.
   */
  public getViewPresentation(
    viewPresSel: ViewPresentationSelector = {
      rotation: true,
      displayArea: true,
      zoom: true,
      pan: true,
    }
  ): ViewPresentation {
    const target: ViewPresentation = {};
 
    const { rotation, displayArea, zoom, pan } = viewPresSel;
    if (rotation) {
      target.rotation = this.getRotation();
    }
    if (displayArea) {
      target.displayArea = this.getDisplayArea();
    }
    const initZoom = this.getZoom();
 
    if (zoom) {
      target.zoom = initZoom;
    }
    if (pan) {
      target.pan = this.getPan();
      vec2.scale(target.pan, target.pan, 1 / initZoom);
    }
    return target;
  }
 
  /**
   * Sets the given view.  This can apply both the view reference and view presentation
   * without getting multiple event notifications on shared values like camera updates or
   * flickers as multiple changes are applied.
   *
   * @param viewRef - the basic positioning in terms of what image id/slice index/orientation to display
   *        * The viewRef must be applicable to the current stack or volume, otherwise an exception will be thrown
   * @param viewPres - the presentation information to apply to the current image (as chosen above)
   */
  public setView(viewRef?: ViewReference, viewPres?: ViewPresentation) {
    if (viewPres) {
      const { displayArea, zoom = this.getZoom(), pan, rotation } = viewPres;
      if (displayArea !== this.getDisplayArea()) {
        this.setDisplayArea(displayArea);
      }
      this.setZoom(zoom);
      if (pan) {
        this.setPan(vec2.scale([0, 0], pan, zoom) as Point2);
      }
      if (rotation >= 0) {
        this.setRotation(rotation);
      }
    }
  }
 
  protected _shouldUseNativeDataType() {
    const { useNorm16Texture, preferSizeOverAccuracy } =
      getConfiguration().rendering;
    return useNorm16Texture || preferSizeOverAccuracy;
  }
 
  _getCorners(bounds: Array<number>): Array<number>[] {
    return [
      [bounds[0], bounds[2], bounds[4]],
      [bounds[0], bounds[2], bounds[5]],
      [bounds[0], bounds[3], bounds[4]],
      [bounds[0], bounds[3], bounds[5]],
      [bounds[1], bounds[2], bounds[4]],
      [bounds[1], bounds[2], bounds[5]],
      [bounds[1], bounds[3], bounds[4]],
      [bounds[1], bounds[3], bounds[5]],
    ];
  }
 
  _getFocalPointForResetCamera(
    centeredFocalPoint: Point3,
    previousCamera: ICamera,
    { resetPan = true, resetToCenter = true }
  ): Point3 {
    if (resetToCenter && resetPan) {
      return centeredFocalPoint;
    }
 
    if (resetToCenter && !resetPan) {
      return hasNaNValues(previousCamera.focalPoint)
        ? centeredFocalPoint
        : previousCamera.focalPoint;
    }
 
    Eif (!resetToCenter && resetPan) {
      // this is an interesting case that means the reset camera should not
      // change the slice (default behavior is to go to the center of the
      // image), and rather just reset the pan on the slice that is currently
      // being viewed
      const oldCamera = previousCamera;
      const oldFocalPoint = oldCamera.focalPoint;
      const oldViewPlaneNormal = oldCamera.viewPlaneNormal;
 
      const vectorFromOldFocalPointToCenteredFocalPoint = vec3.subtract(
        vec3.create(),
        centeredFocalPoint,
        oldFocalPoint
      );
 
      const distanceFromOldFocalPointToCenteredFocalPoint = vec3.dot(
        vectorFromOldFocalPointToCenteredFocalPoint,
        oldViewPlaneNormal
      );
 
      const newFocalPoint = vec3.scaleAndAdd(
        vec3.create(),
        centeredFocalPoint,
        oldViewPlaneNormal,
        -1 * distanceFromOldFocalPointToCenteredFocalPoint
      );
 
      return [newFocalPoint[0], newFocalPoint[1], newFocalPoint[2]];
    }
 
    if (!resetPan && !resetToCenter) {
      // this means the reset camera should not change the slice and should not
      // touch the pan either.
      return hasNaNValues(previousCamera.focalPoint)
        ? centeredFocalPoint
        : previousCamera.focalPoint;
    }
  }
 
  /**
   * Determines whether or not the 3D point position is inside the boundaries of the 3D imageData.
   * @param point - 3D coordinate
   * @param bounds - Bounds of the image
   * @returns boolean
   */
  _isInBounds(point: Point3, bounds: number[]): boolean {
    const [xMin, xMax, yMin, yMax, zMin, zMax] = bounds;
    const [x, y, z] = point;
    if (x < xMin || x > xMax || y < yMin || y > yMax || z < zMin || z > zMax) {
      return false;
    }
    return true;
  }
 
  /**
   * Returns a list of edges for the imageData bounds, which are
   * the cube edges in the case of volumeViewport edges.
   * p1: front, bottom, left
   * p2: front, top, left
   * p3: back, bottom, left
   * p4: back, top, left
   * p5: front, bottom, right
   * p6: front, top, right
   * p7: back, bottom, right
   * p8: back, top, right
   * @param bounds - Bounds of the renderer
   * @returns Edges of the containing bounds
   */
  _getEdges(bounds: Array<number>): Array<[number[], number[]]> {
    const [p1, p2, p3, p4, p5, p6, p7, p8] = this._getCorners(bounds);
    return [
      [p1, p2],
      [p1, p5],
      [p1, p3],
      [p2, p4],
      [p2, p6],
      [p3, p4],
      [p3, p7],
      [p4, p8],
      [p5, p7],
      [p5, p6],
      [p6, p8],
      [p7, p8],
    ];
  }
 
  /**
   * Computes the bounds radius value
   */
  static boundsRadius(bounds: number[]) {
    const w1 = (bounds[1] - bounds[0]) ** 2;
    const w2 = (bounds[3] - bounds[2]) ** 2;
    const w3 = (bounds[5] - bounds[4]) ** 2;
 
    // If we have just a single point, pick a radius of 1.0
    // compute the radius of the enclosing sphere
    // For 3D viewport, we should increase the radius to make sure the whole
    // volume is visible and we don't get clipping artifacts.
    const radius = Math.sqrt(w1 + w2 + w3 || 1) * 0.5;
    return radius;
  }
}
 
export default Viewport;