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

81.89% Statements 647/790
67.52% Branches 237/351
85.45% Functions 94/110
81.2% Lines 579/713

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 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546                                                                                                                                          1x                                                                                                                                                                                               3483x 81x 81x 81x 81x   81x 34x             47x 47x 47x   47x 47x   47x         47x 47x 47x   47x     81x 81x 81x 81x 81x   81x       136x       81x     38x   38x                                                     1120x 1043x   77x                     77x   77x 2x     75x       75x 75x 75x                               1043x 1043x   1043x   1043x               4x 4x 4x 4x   51x 51x       51x     59x       59x                                   1303x   1303x 47x       1256x     1256x             1256x                           49x 49x   49x     49x   49x   2x     49x                     83x             83x   83x     83x 83x   83x       83x         83x 83x   83x 5x       83x   83x     83x 49x     83x                                                   49x         49x 44x     15x           5x               5x     5x                   5x         2x   2x             2x 2x 2x       3x 9x   3x 3x     3x                 3x   3x         3x                                     199x     199x 138x     199x 134x     199x 97x     199x 86x 5x                   3x                       1x   1x   1x       1x   1x                 1503x 99x   1404x                       493x 493x     493x           81x   81x                 1x 1x                       99x 99x       297x 297x       99x 1x         1x             99x           99x       99x 99x   99x   99x                                                                                                                                                                                                                               138x 37x 37x     101x       6x   6x 1x   5x       6x   6x                 6x       97x 34x 34x     63x       134x 35x 35x     99x       1x   1x 1x 1x         5x     5x 5x 5x       63x   63x 46x     17x     17x 17x     17x 17x       34x   34x 34x         34x       35x   35x       35x 35x       99x   99x 46x     53x           53x               53x 53x 53x   53x 3x   53x         37x   37x 34x     3x 2x   2x 2x 2x         2x 2x   1x 1x         1x             1x 1x     3x 3x 3x         3x 3x         101x 101x 46x     55x     55x 55x   55x 55x 47x 47x 47x     55x         55x 55x   55x 55x   55x 54x         54x                   5x   3x   3x   3x 3x     3x 3x     3x                             83x 83x         2x     83x                                 83x           83x 83x     83x         83x         83x         83x 83x   83x   83x         83x 83x 83x 83x           83x 83x     83x         83x                                             147x   147x 49x                                                 49x   49x   47x 47x             2x   2x         49x           49x   49x 49x 49x 49x 49x                         960x   80x   80x 80x 80x 80x 80x 80x 80x 80x   80x   80x   80x 34x 34x     80x   80x             80x                                   50x 46x     12x 12x 4x 4x 4x 4x     4x                                     50x 50x   50x       50x       50x 50x 50x   50x                                     50x         50x                     1260x                               34x 34x                   34x       34x   34x               34x   34x   34x   34x             34x 34x     34x   34x                 34x         34x     34x   34x               34x       34x 34x                                         34x 34x   34x                   34x   34x 34x 34x 34x                       34x                 50x 50x               50x         50x   50x               50x 50x     50x       50x 50x                           50x 50x   50x                   50x   50x 50x 50x   50x                       50x           50x   50x                                                     50x         50x       50x 50x   1x               1x   1x             1x       1x     1x       1x         1x 1x         1x       1x             1x 1x   1x     49x                 49x       49x                       49x     49x 49x 49x 49x     49x   49x     49x       49x   49x         49x     49x   49x           49x   49x       49x   49x           3x   49x             49x 49x 49x 49x         3x 3x   49x 49x 49x   49x 49x       49x     49x 49x 49x   49x 5x               1215x               81x 81x       81x                     180x 180x 34x   146x     180x 180x 180x       34x   34x 34x                                                 146x               146x 146x                     1x 1x   1x 1x   1x 1x   1x     1x           1x   1x   1x           1x 1x               1x           1x 1x                     11x             1x                           3x 3x 3x                         1x 1x     1x   1x 1x         1x           1x   1x     1x         1x         50x               50x   50x           5x   5x                     5x   5x     5x                       920x 597x     323x                       559x 274x     285x       656x       1968x     656x   656x     656x 656x     656x 656x   656x         325x   325x 325x   325x   325x           325x       325x       323x           323x 323x 323x   323x     323x   323x 323x   323x 323x       323x           323x   323x               323x   323x       285x           285x 285x 285x   285x     285x   285x 285x 285x           285x   285x           285x   285x 285x         285x                 14x                                   5x               1545x                                   64x 64x 64x                       3963x       3963x                 981x       981x               981x       981x                 49x       49x                 49x       49x               49x       49x                   49x       49x             49x       49x                   82x   82x 82x               34x           34x 34x         34x         34x                         1x 1x                                                         1x   1x 1x   1x 1x   1x                                 137x   137x       137x         137x         137x       137x       137x       137x           137x          
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import type { vtkImageData as vtkImageDataType } from '@kitware/vtk.js/Common/DataModel/ImageData';
import _cloneDeep from 'lodash.clonedeep';
import vtkCamera from '@kitware/vtk.js/Rendering/Core/Camera';
import { vec2, vec3, mat4 } from 'gl-matrix';
import vtkImageMapper from '@kitware/vtk.js/Rendering/Core/ImageMapper';
import vtkImageSlice from '@kitware/vtk.js/Rendering/Core/ImageSlice';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
import * as metaData from '../metaData';
import Viewport from './Viewport';
import eventTarget from '../eventTarget';
import Events from '../enums/Events';
import {
  triggerEvent,
  isEqual,
  invertRgbTransferFunction,
  windowLevel as windowLevelUtil,
  imageIdToURI,
  isImageActor,
  actorIsA,
} from '../utilities';
import {
  Point2,
  Point3,
  VOIRange,
  ICamera,
  IImage,
  IImageData,
  CPUIImageData,
  PTScaling,
  Scaling,
  StackViewportProperties,
  FlipDirection,
  ActorEntry,
  CPUFallbackEnabledElement,
  CPUFallbackColormapData,
  EventTypes,
  IStackViewport,
  VolumeActor,
  Mat3,
} from '../types';
import { ViewportInput } from '../types/IViewport';
import drawImageSync from './helpers/cpuFallback/drawImageSync';
import { getColormap } from './helpers/cpuFallback/colors/index';
 
import { loadAndCacheImage } from '../loaders/imageLoader';
import imageLoadPoolManager from '../requestPool/imageLoadPoolManager';
import InterpolationType from '../enums/InterpolationType';
import canvasToPixel from './helpers/cpuFallback/rendering/canvasToPixel';
import pixelToCanvas from './helpers/cpuFallback/rendering/pixelToCanvas';
import getDefaultViewport from './helpers/cpuFallback/rendering/getDefaultViewport';
import calculateTransform from './helpers/cpuFallback/rendering/calculateTransform';
import resize from './helpers/cpuFallback/rendering/resize';
 
import resetCamera from './helpers/cpuFallback/rendering/resetCamera';
import { Transform } from './helpers/cpuFallback/rendering/transform';
import { getShouldUseCPURendering } from '../init';
import RequestType from '../enums/RequestType';
import {
  StackViewportNewStackEventDetail,
  StackViewportScrollEventDetail,
  VoiModifiedEventDetail,
} from '../types/EventTypes';
import cache from '../cache';
import correctShift from './helpers/cpuFallback/rendering/correctShift';
import { ImageActor } from '../types/IActor';
import isRgbaSourceRgbDest from './helpers/isRgbaSourceRgbDest';
 
const EPSILON = 1; // Slice Thickness
 
interface ImagePixelModule {
  bitsAllocated: number;
  bitsStored: number;
  samplesPerPixel: number;
  highBit: number;
  photometricInterpretation: string;
  pixelRepresentation: string;
  windowWidth: number;
  windowCenter: number;
  modality: string;
}
 
interface ImageDataMetaData {
  bitsAllocated: number;
  numComps: number;
  origin: Point3;
  direction: Mat3;
  dimensions: Point3;
  spacing: Point3;
  numVoxels: number;
  imagePlaneModule: unknown;
  imagePixelModule: ImagePixelModule;
}
 
interface ImagePlaneModule {
  columnCosines?: Point3;
  columnPixelSpacing?: number;
  imageOrientationPatient?: Float32Array;
  imagePositionPatient?: Point3;
  pixelSpacing?: Point2;
  rowCosines?: Point3;
  rowPixelSpacing?: number;
  sliceLocation?: number;
  sliceThickness?: number;
  frameOfReferenceUID: string;
  columns: number;
  rows: number;
}
 
// TODO This needs to be exposed as its published to consumers.
type CalibrationEvent = {
  rowScale: number;
  columnScale: number;
};
 
/**
 * An object representing a single stack viewport, which is a camera
 * looking into an internal viewport, and an associated target output `canvas`.
 *
 * StackViewports can be rendered using both GPU and a fallback CPU is the GPU
 * is not available (or low performance). Read more about StackViewports in
 * the documentation section of this website.
 */
class StackViewport extends Viewport implements IStackViewport {
  private imageIds: Array<string>;
  // current imageIdIndex that is rendered in the viewport
  private currentImageIdIndex: number;
  // the imageIdIndex that is targeted to be loaded with scrolling but has not initiated loading yet
  private targetImageIdIndex: number;
  // setTimeout if the image is debounced to be loaded
  private debouncedTimeout: number;
 
  // Viewport Properties
  private voiRange: VOIRange;
  private initialVOIRange: VOIRange;
  private invert = false;
  private interpolationType: InterpolationType;
 
  // Helpers
  private _imageData: vtkImageDataType;
  private cameraFocalPointOnRender: Point3; // we use focalPoint since flip manipulates the position and makes it useless to track
  private stackInvalidated = false; // if true -> new actor is forced to be created for the stack
  private voiApplied = false;
  private rotationCache = 0;
  private _publishCalibratedEvent = false;
  private _calibrationEvent: CalibrationEvent;
  private _cpuFallbackEnabledElement?: CPUFallbackEnabledElement;
  // CPU fallback
  private useCPURendering: boolean;
  private cpuImagePixelData: number[];
  private cpuRenderingInvalidated: boolean;
  private csImage: IImage;
 
  // TODO: These should not be here and will be nuked
  public modality: string; // this is needed for tools
  public scaling: Scaling;
 
  // Camera properties
  private initialViewUp: Point3;
 
  /**
   * Constructor for the StackViewport class
   * @param props - ViewportInput
   */
  constructor(props: ViewportInput) {
    super(props);
    this.scaling = {};
    this.modality = null;
    this.useCPURendering = getShouldUseCPURendering();
 
    if (this.useCPURendering) {
      this._cpuFallbackEnabledElement = {
        canvas: this.canvas,
        renderingTools: {},
        transform: new Transform(),
        viewport: {},
      };
    } else {
      const renderer = this.getRenderer();
      const camera = vtkCamera.newInstance();
      renderer.setActiveCamera(camera);
 
      const viewPlaneNormal = <Point3>[0, 0, -1];
      this.initialViewUp = <Point3>[0, -1, 0];
 
      camera.setDirectionOfProjection(
        -viewPlaneNormal[0],
        -viewPlaneNormal[1],
        -viewPlaneNormal[2]
      );
      camera.setViewUp(...this.initialViewUp);
      camera.setParallelProjection(true);
      camera.setThicknessFromFocalPoint(0.1);
      // @ts-ignore: vtkjs incorrect typing
      camera.setFreezeFocalPoint(true);
    }
 
    this.imageIds = [];
    this.currentImageIdIndex = 0;
    this.targetImageIdIndex = 0;
    this.cameraFocalPointOnRender = [0, 0, 0];
    this.resetCamera();
 
    this.initializeElementDisabledHandler();
  }
 
  static get useCustomRenderingPipeline(): boolean {
    return getShouldUseCPURendering();
  }
 
  private initializeElementDisabledHandler() {
    eventTarget.addEventListener(
      Events.ELEMENT_DISABLED,
      function elementDisabledHandler() {
        clearTimeout(this.debouncedTimeout);
 
        eventTarget.removeEventListener(
          Events.ELEMENT_DISABLED,
          elementDisabledHandler
        );
      }
    );
  }
 
  /**
   * Resizes the viewport - only used in CPU fallback for StackViewport. The
   * GPU resizing happens inside the RenderingEngine.
   */
  public resize = (): void => {
    // GPU viewport resize is handled inside the RenderingEngine
    if (this.useCPURendering) {
      this._resizeCPU();
    }
  };
 
  /**
   * Returns the image and its properties that is being shown inside the
   * stack viewport. It returns, the image dimensions, image direction,
   * image scalar data, vtkImageData object, metadata, and scaling (e.g., PET suvbw)
   *
   * @returns IImageData: dimensions, direction, scalarData, vtkImageData, metadata, scaling
   */
  public getImageData(): IImageData | CPUIImageData {
    if (this.useCPURendering) {
      return this.getImageDataCPU();
    } else {
      return this.getImageDataGPU();
    }
  }
 
  private _resizeCPU = (): void => {
    if (this._cpuFallbackEnabledElement.viewport) {
      resize(this._cpuFallbackEnabledElement);
    }
  };
 
  private getImageDataGPU(): IImageData | undefined {
    const defaultActor = this.getDefaultActor();
 
    if (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
 
    const { actor } = defaultActor;
    const vtkImageData = actor.getMapper().getInputData();
    return {
      dimensions: vtkImageData.getDimensions(),
      spacing: vtkImageData.getSpacing(),
      origin: vtkImageData.getOrigin(),
      direction: vtkImageData.getDirection(),
      scalarData: vtkImageData.getPointData().getScalars().getData(),
      imageData: actor.getMapper().getInputData(),
      metadata: { Modality: this.modality },
      scaling: this.scaling,
      hasPixelSpacing: this.hasPixelSpacing,
      preScale: {
        ...this.csImage.preScale,
      },
    };
  }
 
  private getImageDataCPU(): CPUIImageData | undefined {
    const { metadata } = this._cpuFallbackEnabledElement;
 
    const spacing = metadata.spacing;
 
    return {
      dimensions: metadata.dimensions,
      spacing,
      origin: metadata.origin,
      direction: metadata.direction,
      metadata: { Modality: this.modality },
      scaling: this.scaling,
      imageData: {
        getDirection: () => metadata.direction,
        getDimensions: () => metadata.dimensions,
        getScalarData: () => this.cpuImagePixelData,
        getSpacing: () => spacing,
        worldToIndex: (point: Point3) => {
          const canvasPoint = this.worldToCanvasCPU(point);
          const pixelCoord = canvasToPixel(
            this._cpuFallbackEnabledElement,
            canvasPoint
          );
          return [pixelCoord[0], pixelCoord[1], 0];
        },
        indexToWorld: (point: Point3) => {
          const canvasPoint = pixelToCanvas(this._cpuFallbackEnabledElement, [
            point[0],
            point[1],
          ]);
          return this.canvasToWorldCPU(canvasPoint);
        },
      },
      scalarData: this.cpuImagePixelData,
      hasPixelSpacing: this.hasPixelSpacing,
      preScale: {
        ...this.csImage.preScale,
      },
    };
  }
 
  /**
   * Returns the frame of reference UID, if the image doesn't have imagePlaneModule
   * metadata, it returns undefined, otherwise, frameOfReferenceUID is returned.
   * @returns frameOfReferenceUID : string representing frame of reference id
   */
  public getFrameOfReferenceUID = (): string | undefined => {
    // Get the current image that is displayed in the viewport
    const imageId = this.getCurrentImageId();
 
    if (!imageId) {
      return;
    }
 
    // Use the metadata provider to grab its imagePlaneModule metadata
    const imagePlaneModule = metaData.get('imagePlaneModule', imageId);
 
    // If nothing exists, return undefined
    Iif (!imagePlaneModule) {
      return;
    }
 
    // Otherwise, provide the FrameOfReferenceUID so we can map
    // annotations made on VolumeViewports back to StackViewports
    // and vice versa
    return imagePlaneModule.frameOfReferenceUID;
  };
 
  /**
   * Creates imageMapper based on the provided vtkImageData and also creates
   * the imageSliceActor and connects it to the imageMapper.
   * For color stack images, it sets the independent components to be false which
   * is required in vtk.
   *
   * @param imageData - vtkImageData for the viewport
   * @returns actor vtkActor
   */
 
  private createActorMapper = (imageData) => {
    const mapper = vtkImageMapper.newInstance();
    mapper.setInputData(imageData);
 
    const actor = vtkImageSlice.newInstance();
 
    // @ts-ignore: vtkjs incorrect typing
    actor.setMapper(mapper);
 
    if (imageData.getPointData().getNumberOfComponents() > 1) {
      // @ts-ignore: vtkjs incorrect typing
      actor.getProperty().setIndependentComponents(false);
    }
 
    return actor;
  };
 
  /**
   * Retrieves the metadata from the metadata provider, and optionally adds the
   * scaling to the viewport if modality is PET and scaling metadata is provided.
   *
   * @param imageId - a string representing the imageId for the image
   * @returns imagePlaneModule and imagePixelModule containing the metadata for the image
   */
  private buildMetadata(imageId: string) {
    const {
      pixelRepresentation,
      bitsAllocated,
      bitsStored,
      highBit,
      photometricInterpretation,
      samplesPerPixel,
    } = metaData.get('imagePixelModule', imageId);
 
    const voiLutModule = metaData.get('voiLutModule', imageId);
 
    let windowWidth, windowCenter;
    Eif (voiLutModule) {
      ({ windowWidth, windowCenter } = voiLutModule);
 
      Iif (Array.isArray(windowWidth)) {
        windowWidth = windowWidth[0];
      }
 
      Iif (Array.isArray(windowCenter)) {
        windowCenter = windowCenter[0];
      }
    }
 
    const { modality } = metaData.get('generalSeriesModule', imageId);
    const imageIdScalingFactor = metaData.get('scalingModule', imageId);
 
    if (modality === 'PT' && imageIdScalingFactor) {
      this._addScalingToViewport(imageIdScalingFactor);
    }
 
    // todo: some tools rely on the modality
    this.modality = modality;
 
    let imagePlaneModule = this._getImagePlaneModule(imageId);
 
    // Todo: for now, it gives error for getImageData
    if (!this.useCPURendering) {
      imagePlaneModule = this.calibrateIfNecessary(imageId, imagePlaneModule);
    }
 
    return {
      imagePlaneModule,
      imagePixelModule: {
        bitsAllocated,
        bitsStored,
        samplesPerPixel,
        highBit,
        photometricInterpretation,
        pixelRepresentation,
        windowWidth,
        windowCenter,
        modality,
      },
    };
  }
 
  /**
   * Checks the metadataProviders to see if a calibratedPixelSpacing is
   * given. If so, checks the actor to see if it needs to be modified, and
   * set the flags for imageCalibration if a new actor needs to be created
   *
   * @param imageId - imageId
   * @param imagePlaneModule - imagePlaneModule
   * @returns modified imagePlaneModule with the calibrated spacings
   */
  private calibrateIfNecessary(imageId, imagePlaneModule) {
    const calibratedPixelSpacing = metaData.get(
      'calibratedPixelSpacing',
      imageId
    );
 
    if (!calibratedPixelSpacing) {
      return imagePlaneModule;
    }
 
    const [calibratedRowSpacing, calibratedColumnSpacing] =
      calibratedPixelSpacing;
 
    // Todo: This is necessary in general, but breaks an edge case when an image
    // is calibrated to some other spacing, and it gets calibrated BACK to the
    // original spacing.
    Iif (
      imagePlaneModule.rowPixelSpacing === calibratedRowSpacing &&
      imagePlaneModule.columnPixelSpacing === calibratedColumnSpacing
    ) {
      return imagePlaneModule;
    }
 
    // Check if there is already an actor
    const imageDataMetadata = this.getImageData();
 
    // If no actor (first load) and calibration matches the dicom header
    Iif (
      !imageDataMetadata &&
      imagePlaneModule.rowPixelSpacing === calibratedRowSpacing &&
      imagePlaneModule.columnPixelSpacing === calibratedColumnSpacing
    ) {
      return imagePlaneModule;
    }
 
    // If no actor (first load) and calibration doesn't match headers
    // -> needs calibration
    if (
      !imageDataMetadata &&
      (imagePlaneModule.rowPixelSpacing !== calibratedRowSpacing ||
        imagePlaneModule.columnPixelSpacing !== calibratedColumnSpacing)
    ) {
      this._publishCalibratedEvent = true;
 
      this._calibrationEvent = <CalibrationEvent>{
        rowScale: calibratedRowSpacing / imagePlaneModule.rowPixelSpacing,
        columnScale:
          calibratedColumnSpacing / imagePlaneModule.columnPixelSpacing,
      };
 
      // modify imagePlaneModule for actor to use calibrated spacing
      imagePlaneModule.rowPixelSpacing = calibratedRowSpacing;
      imagePlaneModule.columnPixelSpacing = calibratedColumnSpacing;
      return imagePlaneModule;
    }
 
    // If there is already an actor, check if calibration is needed for the current actor
    const { imageData } = imageDataMetadata;
    const [columnPixelSpacing, rowPixelSpacing] = imageData.getSpacing();
 
    imagePlaneModule.rowPixelSpacing = calibratedRowSpacing;
    imagePlaneModule.columnPixelSpacing = calibratedColumnSpacing;
 
    // If current actor spacing matches the calibrated spacing
    Iif (
      rowPixelSpacing === calibratedRowSpacing &&
      columnPixelSpacing === calibratedPixelSpacing
    ) {
      // No calibration is required
      return imagePlaneModule;
    }
 
    // Calibration is required
    this._publishCalibratedEvent = true;
 
    this._calibrationEvent = <CalibrationEvent>{
      rowScale: calibratedRowSpacing / rowPixelSpacing,
      columnScale: calibratedColumnSpacing / columnPixelSpacing,
    };
 
    return imagePlaneModule;
  }
 
  /**
   * Sets the properties for the viewport on the default actor. Properties include
   * setting the VOI, inverting the colors and setting the interpolation type, rotation
   * @param voiRange - Sets the lower and upper voi
   * @param invert - Inverts the colors
   * @param interpolationType - Changes the interpolation type (1:linear, 0: nearest)
   * @param rotation - image rotation in degrees
   */
  public setProperties(
    {
      voiRange,
      invert,
      interpolationType,
      rotation,
    }: StackViewportProperties = {},
    suppressEvents = false
  ): void {
    // if voi is not applied for the first time, run the setVOI function
    // which will apply the default voi
    if (typeof voiRange !== 'undefined' || !this.voiApplied) {
      this.setVOI(voiRange, suppressEvents);
    }
 
    if (typeof invert !== 'undefined') {
      this.setInvertColor(invert);
    }
 
    if (typeof interpolationType !== 'undefined') {
      this.setInterpolationType(interpolationType);
    }
 
    if (typeof rotation !== 'undefined') {
      if (this.rotationCache !== rotation) {
        this.setRotation(this.rotationCache, rotation);
      }
    }
  }
 
  /**
   * Retrieve the viewport properties
   * @returns viewport properties including voi, invert, interpolation type, rotation, flip
   */
  public getProperties = (): StackViewportProperties => {
    return {
      voiRange: this.voiRange,
      rotation: this.rotationCache,
      interpolationType: this.interpolationType,
      invert: this.invert,
    };
  };
 
  /**
   * Reset the viewport properties to the default values
   */
  public resetProperties(): void {
    this.cpuRenderingInvalidated = true;
 
    this.fillWithBackgroundColor();
 
    Iif (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
    }
 
    this._resetProperties();
 
    this.render();
  }
 
  /**
   * If the user has selected CPU rendering, return the CPU camera, otherwise
   * return the default camera
   * @returns The camera object.
   */
  public getCamera(): ICamera {
    if (this.useCPURendering) {
      return this.getCameraCPU();
    } else {
      return super.getCamera();
    }
  }
 
  /**
   * Set the camera based on the provided camera object.
   * @param cameraInterface - The camera interface that will be used to
   * render the scene.
   */
  public setCamera(
    cameraInterface: ICamera,
    storeAsInitialCamera = false
  ): void {
    Iif (this.useCPURendering) {
      this.setCameraCPU(cameraInterface);
    } else {
      super.setCamera(cameraInterface, storeAsInitialCamera);
    }
  }
 
  private _resetProperties() {
    // to force the default voi to be applied on the next render
    this.voiApplied = false;
 
    this.setProperties({
      voiRange: this.initialVOIRange,
      rotation: 0,
      interpolationType: InterpolationType.LINEAR,
      invert: false,
    });
  }
 
  private _setPropertiesFromCache(): void {
    const suppressEvents = true;
    this.setProperties(
      {
        voiRange: this.voiRange,
        rotation: this.rotation,
        interpolationType: this.interpolationType,
        invert: this.invert,
      },
      suppressEvents
    );
  }
 
  private getCameraCPU(): Partial<ICamera> {
    const { metadata, viewport } = this._cpuFallbackEnabledElement;
    const { direction } = metadata;
 
    // focalPoint and position of CPU camera is just a placeholder since
    // tools need focalPoint to be defined
    const viewPlaneNormal = direction.slice(6, 9).map((x) => -x) as Point3;
    let viewUp = direction.slice(3, 6).map((x) => -x) as Point3;
 
    // If camera is rotated, we need the correct rotated viewUp along the
    // viewPlaneNormal vector
    if (this.rotation) {
      const rotationMatrix = mat4.fromRotation(
        mat4.create(),
        (this.rotation * Math.PI) / 180,
        viewPlaneNormal
      );
      viewUp = vec3.transformMat4(
        vec3.create(),
        viewUp,
        rotationMatrix
      ) as Point3;
    }
 
    const canvasCenter: Point2 = [
      this.element.clientWidth / 2,
      this.element.clientHeight / 2,
    ];
 
    // Focal point is the center of the canvas in world coordinate by construction
    const canvasCenterWorld = this.canvasToWorld(canvasCenter);
 
    // parallel scale is half of the viewport height in the world units (mm)
 
    const topLeftWorld = this.canvasToWorld([0, 0]);
    const bottomLeftWorld = this.canvasToWorld([0, this.element.clientHeight]);
 
    const parallelScale = vec3.distance(topLeftWorld, bottomLeftWorld) / 2;
 
    return {
      parallelProjection: true,
      focalPoint: canvasCenterWorld,
      position: [0, 0, 0],
      parallelScale,
      scale: viewport.scale,
      viewPlaneNormal: [
        viewPlaneNormal[0],
        viewPlaneNormal[1],
        viewPlaneNormal[2],
      ],
      viewUp: [viewUp[0], viewUp[1], viewUp[2]],
      flipHorizontal: this.flipHorizontal,
      flipVertical: this.flipVertical,
    };
  }
 
  private setCameraCPU(cameraInterface: ICamera): void {
    const { viewport, image } = this._cpuFallbackEnabledElement;
    const previousCamera = this.getCameraCPU();
 
    const { focalPoint, parallelScale, scale, flipHorizontal, flipVertical } =
      cameraInterface;
 
    const { clientHeight } = this.element;
 
    if (focalPoint) {
      const focalPointCanvas = this.worldToCanvasCPU(focalPoint);
      const focalPointPixel = canvasToPixel(
        this._cpuFallbackEnabledElement,
        focalPointCanvas
      );
 
      const prevFocalPointCanvas = this.worldToCanvasCPU(
        previousCamera.focalPoint
      );
      const prevFocalPointPixel = canvasToPixel(
        this._cpuFallbackEnabledElement,
        prevFocalPointCanvas
      );
 
      const deltaPixel = vec2.create();
      vec2.subtract(
        deltaPixel,
        vec2.fromValues(focalPointPixel[0], focalPointPixel[1]),
        vec2.fromValues(prevFocalPointPixel[0], prevFocalPointPixel[1])
      );
 
      const shift = correctShift(
        { x: deltaPixel[0], y: deltaPixel[1] },
        viewport
      );
 
      viewport.translation.x -= shift.x;
      viewport.translation.y -= shift.y;
    }
 
    if (parallelScale) {
      // We need to convert he parallelScale which has a physical meaning to
      // camera scale factor (since CPU works with scale). Since parallelScale represents
      // half of the height of the viewport in the world unit (mm), we can use that
      // to compute the scale factor which is the ratio of the viewport height in pixels
      // to the current rendered image height.
      const { rowPixelSpacing } = image;
      const scale = (clientHeight * rowPixelSpacing * 0.5) / parallelScale;
 
      viewport.scale = scale;
      viewport.parallelScale = parallelScale;
    }
 
    if (scale) {
      const { rowPixelSpacing } = image;
      viewport.scale = scale;
      viewport.parallelScale = (clientHeight * rowPixelSpacing * 0.5) / scale;
    }
 
    if (flipHorizontal !== undefined || flipVertical !== undefined) {
      this.setFlipCPU({ flipHorizontal, flipVertical });
    }
 
    // re-calculate the transforms
    this._cpuFallbackEnabledElement.transform = calculateTransform(
      this._cpuFallbackEnabledElement
    );
 
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera: this.getCamera(),
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      rotation: this.rotation,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  }
 
  private setFlipCPU({ flipHorizontal, flipVertical }: FlipDirection): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    if (flipHorizontal !== undefined) {
      viewport.hflip = flipHorizontal;
      this.flipHorizontal = viewport.hflip;
    }
 
    if (flipVertical !== undefined) {
      viewport.vflip = flipVertical;
      this.flipVertical = viewport.vflip;
    }
  }
 
  private setVOI(voiRange: VOIRange, suppressEvents?: boolean): void {
    if (this.useCPURendering) {
      this.setVOICPU(voiRange, suppressEvents);
      return;
    }
 
    this.setVOIGPU(voiRange, suppressEvents);
  }
 
  private setRotation(rotationCache: number, rotation: number): void {
    const previousCamera = this.getCamera();
 
    if (this.useCPURendering) {
      this.setRotationCPU(rotationCache, rotation);
    } else {
      this.setRotationGPU(rotationCache, rotation);
    }
 
    // New camera after rotation
    const camera = this.getCamera();
 
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      rotation: this.rotation,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  }
 
  private setInterpolationType(interpolationType: InterpolationType): void {
    if (this.useCPURendering) {
      this.setInterpolationTypeCPU(interpolationType);
      return;
    }
 
    this.setInterpolationTypeGPU(interpolationType);
  }
 
  private setInvertColor(invert: boolean): void {
    if (this.useCPURendering) {
      this.setInvertColorCPU(invert);
      return;
    }
 
    this.setInvertColorGPU(invert);
  }
 
  private setRotationCPU(rotationCache: number, rotation: number): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    viewport.rotation = rotation;
    this.rotationCache = rotation;
    this.rotation = rotation;
  }
 
  private setRotationGPU(rotationCache: number, rotation: number): void {
    // Moving back to zero rotation, for new scrolled slice rotation is 0 after camera reset
    this.getVtkActiveCamera().roll(rotationCache);
 
    // rotating camera to the new value
    this.getVtkActiveCamera().roll(-rotation);
    this.rotationCache = rotation;
    this.rotation = rotation;
  }
 
  private setInterpolationTypeGPU(interpolationType: InterpolationType): void {
    const defaultActor = this.getDefaultActor();
 
    if (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const { actor } = defaultActor;
    const volumeProperty = actor.getProperty();
 
    // @ts-ignore
    volumeProperty.setInterpolationType(interpolationType);
    this.interpolationType = interpolationType;
  }
 
  private setInterpolationTypeCPU(interpolationType: InterpolationType): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    Eif (interpolationType === InterpolationType.LINEAR) {
      viewport.pixelReplication = false;
    } else {
      viewport.pixelReplication = true;
    }
 
    this.interpolationType = interpolationType;
  }
 
  private setInvertColorCPU(invert: boolean): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    Iif (!viewport) {
      return;
    }
 
    viewport.invert = invert;
    this.invert = invert;
  }
 
  private setInvertColorGPU(invert: boolean): void {
    const defaultActor = this.getDefaultActor();
 
    if (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
 
    // Duplicated logic to make sure typescript stops complaining
    // about vtkActor not having the correct property
    Iif (actorIsA(defaultActor, 'vtkVolume')) {
      const volumeActor = defaultActor.actor as VolumeActor;
      const tfunc = volumeActor.getProperty().getRGBTransferFunction(0);
 
      if ((!this.invert && invert) || (this.invert && !invert)) {
        invertRgbTransferFunction(tfunc);
      }
      this.invert = invert;
    } else Eif (actorIsA(defaultActor, 'vtkImageSlice')) {
      const imageSliceActor = defaultActor.actor as vtkImageSlice;
      const tfunc = imageSliceActor.getProperty().getRGBTransferFunction(0);
 
      if ((!this.invert && invert) || (this.invert && !invert)) {
        invertRgbTransferFunction(tfunc);
      }
      this.invert = invert;
    }
  }
 
  private setVOICPU(voiRange: VOIRange, suppressEvents?: boolean): void {
    const { viewport, image } = this._cpuFallbackEnabledElement;
 
    if (!viewport || !image) {
      return;
    }
 
    if (typeof voiRange === 'undefined') {
      const { windowWidth: ww, windowCenter: wc } = image;
 
      const wwToUse = Array.isArray(ww) ? ww[0] : ww;
      const wcToUse = Array.isArray(wc) ? wc[0] : wc;
      viewport.voi = {
        windowWidth: wwToUse,
        windowCenter: wcToUse,
      };
 
      const { lower, upper } = windowLevelUtil.toLowHighRange(wwToUse, wcToUse);
      voiRange = { lower, upper };
    } else {
      const { lower, upper } = voiRange;
      const { windowCenter, windowWidth } = windowLevelUtil.toWindowLevel(
        lower,
        upper
      );
 
      Iif (!viewport.voi) {
        viewport.voi = {
          windowWidth: 0,
          windowCenter: 0,
        };
      }
 
      viewport.voi.windowWidth = windowWidth;
      viewport.voi.windowCenter = windowCenter;
    }
 
    this.voiApplied = true;
    this.voiRange = voiRange;
    const eventDetail: VoiModifiedEventDetail = {
      viewportId: this.id,
      range: voiRange,
    };
 
    Eif (!suppressEvents) {
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
  }
 
  private setVOIGPU(voiRange: VOIRange, suppressEvents?: boolean): void {
    const defaultActor = this.getDefaultActor();
    if (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const { actor } = defaultActor;
    const imageActor = actor as ImageActor;
 
    let voiRangeToUse = voiRange;
    if (typeof voiRangeToUse === 'undefined') {
      const imageData = imageActor.getMapper().getInputData();
      const range = imageData.getPointData().getScalars().getRange();
      voiRangeToUse = { lower: range[0], upper: range[1] };
    }
 
    const { windowWidth, windowCenter } = windowLevelUtil.toWindowLevel(
      voiRangeToUse.lower,
      voiRangeToUse.upper
    );
 
    imageActor.getProperty().setColorWindow(windowWidth);
    imageActor.getProperty().setColorLevel(windowCenter);
 
    this.voiApplied = true;
    this.voiRange = voiRangeToUse;
 
    if (!suppressEvents) {
      const eventDetail: VoiModifiedEventDetail = {
        viewportId: this.id,
        range: voiRangeToUse,
      };
 
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
  }
 
  /**
   * Adds scaling parameters to the viewport to be used along all slices
   *
   * @param imageIdScalingFactor - suvbw, suvlbm, suvbsa
   */
  private _addScalingToViewport(imageIdScalingFactor) {
    if (!this.scaling.PET) {
      // These ratios are constant across all frames, so only need one.
      const { suvbw, suvlbm, suvbsa } = imageIdScalingFactor;
 
      const petScaling = <PTScaling>{};
 
      Eif (suvlbm) {
        petScaling.suvbwToSuvlbm = suvlbm / suvbw;
      }
 
      Eif (suvbsa) {
        petScaling.suvbwToSuvbsa = suvbsa / suvbw;
      }
 
      this.scaling.PET = petScaling;
    }
  }
 
  /**
   * Calculates number of components based on the dicom metadata
   *
   * @param photometricInterpretation - string dicom tag
   * @returns number representing number of components
   */
  private _getNumCompsFromPhotometricInterpretation(
    photometricInterpretation: string
  ): number {
    // TODO: this function will need to have more logic later
    // see http://dicom.nema.org/medical/Dicom/current/output/chtml/part03/sect_C.7.6.3.html#sect_C.7.6.3.1.2
    let numberOfComponents = 1;
    if (
      photometricInterpretation === 'RGB' ||
      photometricInterpretation.indexOf('YBR') !== -1 ||
      photometricInterpretation === 'PALETTE COLOR'
    ) {
      numberOfComponents = 3;
    }
 
    return numberOfComponents;
  }
 
  /**
   * Calculates image metadata based on the image object. It calculates normal
   * axis for the images, and output image metadata
   *
   * @param image - stack image containing cornerstone image
   * @returns image metadata: bitsAllocated, number of components, origin,
   *  direction, dimensions, spacing, number of voxels.
   */
  private _getImageDataMetadata(image: IImage): ImageDataMetaData {
    // TODO: Creating a single image should probably not require a metadata provider.
    // We should define the minimum we need to display an image and it should live on
    // the Image object itself. Additional stuff (e.g. pixel spacing, direction, origin, etc)
    // should be optional and used if provided through a metadata provider.
 
    const { imagePlaneModule, imagePixelModule } = this.buildMetadata(
      image.imageId
    );
 
    let rowCosines, columnCosines;
 
    rowCosines = <Point3>imagePlaneModule.rowCosines;
    columnCosines = <Point3>imagePlaneModule.columnCosines;
 
    // if null or undefined
    Iif (rowCosines == null || columnCosines == null) {
      rowCosines = <Point3>[1, 0, 0];
      columnCosines = <Point3>[0, 1, 0];
    }
 
    const rowCosineVec = vec3.fromValues(
      rowCosines[0],
      rowCosines[1],
      rowCosines[2]
    );
    const colCosineVec = vec3.fromValues(
      columnCosines[0],
      columnCosines[1],
      columnCosines[2]
    );
    const scanAxisNormal = vec3.create();
    vec3.cross(scanAxisNormal, rowCosineVec, colCosineVec);
 
    let origin = imagePlaneModule.imagePositionPatient;
    // if null or undefined
    Iif (origin == null) {
      origin = [0, 0, 0];
    }
 
    const xSpacing =
      imagePlaneModule.columnPixelSpacing || image.columnPixelSpacing;
    const ySpacing = imagePlaneModule.rowPixelSpacing || image.rowPixelSpacing;
    const xVoxels = image.columns;
    const yVoxels = image.rows;
 
    // Note: For rendering purposes, we use the EPSILON as the z spacing.
    // This is purely for internal implementation logic since we are still
    // technically rendering 3D objects with vtk.js, but the abstracted intention
    //  of the stack viewport is to render 2D images
    const zSpacing = EPSILON;
    const zVoxels = 1;
 
    const numComps =
      image.numComps ||
      this._getNumCompsFromPhotometricInterpretation(
        imagePixelModule.photometricInterpretation
      );
 
    return {
      bitsAllocated: imagePixelModule.bitsAllocated,
      numComps,
      origin,
      direction: [...rowCosineVec, ...colCosineVec, ...scanAxisNormal] as Mat3,
      dimensions: [xVoxels, yVoxels, zVoxels],
      spacing: [xSpacing, ySpacing, zSpacing],
      numVoxels: xVoxels * yVoxels * zVoxels,
      imagePlaneModule,
      imagePixelModule,
    };
  }
 
  /**
   * Converts the image direction to camera viewUp and viewplaneNormal
   *
   * @param imageDataDirection - vtkImageData direction
   * @returns viewplane normal and viewUp of the camera
   */
  private _getCameraOrientation(imageDataDirection: Mat3): {
    viewPlaneNormal: Point3;
    viewUp: Point3;
  } {
    const viewPlaneNormal = imageDataDirection.slice(6, 9).map((x) => -x);
 
    const viewUp = imageDataDirection.slice(3, 6).map((x) => -x);
    return {
      viewPlaneNormal: [
        viewPlaneNormal[0],
        viewPlaneNormal[1],
        viewPlaneNormal[2],
      ],
      viewUp: [viewUp[0], viewUp[1], viewUp[2]],
    };
  }
 
  /**
   * Creates vtkImagedata based on the image object, it creates
   * and empty scalar data for the image based on the metadata
   * tags (e.g., bitsAllocated)
   *
   * @param image - cornerstone Image object
   */
  private _createVTKImageData({
    origin,
    direction,
    dimensions,
    spacing,
    bitsAllocated,
    numComps,
    numVoxels,
  }): void {
    let pixelArray;
    switch (bitsAllocated) {
      case 8:
        pixelArray = new Uint8Array(numVoxels * numComps);
        break;
 
      case 16:
        pixelArray = new Float32Array(numVoxels * numComps);
 
        break;
      case 24:
        pixelArray = new Uint8Array(numVoxels * 3 * numComps);
 
        break;
      default:
        console.log('bit allocation not implemented');
    }
 
    const scalarArray = vtkDataArray.newInstance({
      name: 'Pixels',
      numberOfComponents: numComps,
      values: pixelArray,
    });
 
    this._imageData = vtkImageData.newInstance();
 
    this._imageData.setDimensions(dimensions);
    this._imageData.setSpacing(spacing);
    this._imageData.setDirection(direction);
    this._imageData.setOrigin(origin);
    this._imageData.getPointData().setScalars(scalarArray);
  }
 
  /**
   * Sets the imageIds to be visualized inside the stack viewport. It accepts
   * list of imageIds, the index of the first imageId to be viewed. It is a
   * asynchronous function that returns a promise resolving to imageId being
   * displayed in the stack viewport.
   *
   *
   * @param imageIds - list of strings, that represents list of image Ids
   * @param currentImageIdIndex - number representing the index of the initial image to be displayed
   */
  public async setStack(
    imageIds: Array<string>,
    currentImageIdIndex = 0
  ): Promise<string> {
    this.imageIds = imageIds;
    this.currentImageIdIndex = currentImageIdIndex;
    this.targetImageIdIndex = currentImageIdIndex;
    this.stackInvalidated = true;
    this.rotationCache = 0;
    this.flipVertical = false;
    this.flipHorizontal = false;
    this.voiApplied = false;
 
    this._resetProperties();
 
    this.fillWithBackgroundColor();
 
    if (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
      delete this._cpuFallbackEnabledElement.viewport.colormap;
    }
 
    const imageId = await this._setImageIdIndex(currentImageIdIndex);
 
    const eventDetail: StackViewportNewStackEventDetail = {
      imageIds,
      viewportId: this.id,
      element: this.element,
      currentImageIdIndex: currentImageIdIndex,
    };
 
    triggerEvent(eventTarget, Events.STACK_VIEWPORT_NEW_STACK, eventDetail);
 
    return imageId;
  }
 
  /**
   * It checks if the new image object matches the dimensions, spacing,
   * and direction of the previously displayed image in the viewport or not.
   * It returns a boolean
   *
   * @param image - Cornerstone Image object
   * @param imageData - vtkImageData
   * @returns boolean
   */
  private _checkVTKImageDataMatchesCornerstoneImage(
    image: IImage,
    imageData: vtkImageDataType
  ): boolean {
    if (!imageData) {
      return false;
    }
 
    const [xSpacing, ySpacing] = imageData.getSpacing();
    const [xVoxels, yVoxels] = imageData.getDimensions();
    const imagePlaneModule = this._getImagePlaneModule(image.imageId);
    const direction = imageData.getDirection();
    const rowCosines = direction.slice(0, 3);
    const columnCosines = direction.slice(3, 6);
 
    // using spacing, size, and direction only for now
    return (
      (xSpacing === image.rowPixelSpacing ||
        (image.rowPixelSpacing === null && xSpacing === 1.0)) &&
      (ySpacing === image.columnPixelSpacing ||
        (image.columnPixelSpacing === null && ySpacing === 1.0)) &&
      xVoxels === image.columns &&
      yVoxels === image.rows &&
      isEqual(imagePlaneModule.rowCosines, <Point3>rowCosines) &&
      isEqual(imagePlaneModule.columnCosines, <Point3>columnCosines)
    );
  }
 
  /**
   * It Updates the vtkImageData of the viewport with the new pixel data
   * from the provided image object.
   *
   * @param image - Cornerstone Image object
   */
  private _updateVTKImageDataFromCornerstoneImage(image: IImage): void {
    const imagePlaneModule = this._getImagePlaneModule(image.imageId);
    let origin = imagePlaneModule.imagePositionPatient;
 
    Iif (origin == null) {
      origin = [0, 0, 0];
    }
 
    this._imageData.setOrigin(origin);
 
    // 1. Update the pixel data in the vtkImageData object with the pixelData
    //    from the loaded Cornerstone image
    const pixelData = image.getPixelData();
    const scalars = this._imageData.getPointData().getScalars();
    const scalarData = scalars.getData() as Uint8Array | Float32Array;
 
    Iif (image.rgba || isRgbaSourceRgbDest(pixelData, scalarData)) {
      if (!image.rgba) {
        console.warn('rgba not specified but data looks rgba ish', image);
      }
      // if image is already cached with rgba for any reason (cpu fallback),
      // we need to convert it to rgb for the pixel data set
      // RGB case
      const numPixels = pixelData.length / 4;
 
      let rgbIndex = 0;
      let index = 0;
 
      for (let i = 0; i < numPixels; i++) {
        scalarData[index++] = pixelData[rgbIndex++]; // red
        scalarData[index++] = pixelData[rgbIndex++]; // green
        scalarData[index++] = pixelData[rgbIndex++]; // blue
        rgbIndex++; // skip alpha
      }
    } else {
      scalarData.set(pixelData);
    }
 
    // Trigger modified on the VTK Object so the texture is updated
    // TODO: evaluate directly changing things with texSubImage3D later
    this._imageData.modified();
  }
 
  /**
   * It uses imageLoadPoolManager to add request for the imageId. It loadsAndCache
   * the image and triggers the STACK_NEW_IMAGE when the request successfully retrieves
   * the image. Next, the volume actor gets updated with the new new retrieved image.
   *
   * @param imageId - string representing the imageId
   * @param imageIdIndex - index of the imageId in the imageId list
   */
  private async _loadAndDisplayImage(
    imageId: string,
    imageIdIndex: number
  ): Promise<string> {
    if (this.useCPURendering) {
      await this._loadAndDisplayImageCPU(imageId, imageIdIndex);
    } else {
      await this._loadAndDisplayImageGPU(imageId, imageIdIndex);
    }
 
    return imageId;
  }
 
  private _loadAndDisplayImageCPU(
    imageId: string,
    imageIdIndex: number
  ): Promise<string> {
    return new Promise((resolve, reject) => {
      // 1. Load the image using the Image Loader
      function successCallback(
        image: IImage,
        imageIdIndex: number,
        imageId: string
      ) {
        // Perform this check after the image has finished loading
        // in case the user has already scrolled away to another image.
        // In that case, do not render this image.
        Iif (this.currentImageIdIndex !== imageIdIndex) {
          return;
        }
 
        this.csImage = image;
 
        const eventDetail: EventTypes.StackNewImageEventDetail = {
          image,
          imageId,
          imageIdIndex,
          viewportId: this.id,
          renderingEngineId: this.renderingEngineId,
        };
 
        triggerEvent(this.element, Events.STACK_NEW_IMAGE, eventDetail);
 
        const metadata = this._getImageDataMetadata(image) as ImageDataMetaData;
 
        image.isPreScaled = image.preScale?.scaled;
 
        const viewport = getDefaultViewport(
          this.canvas,
          image,
          this.modality,
          this._cpuFallbackEnabledElement.viewport.colormap
        );
 
        this._cpuFallbackEnabledElement.image = image;
        this._cpuFallbackEnabledElement.metadata = {
          ...metadata,
        };
        this.cpuImagePixelData = image.getPixelData();
 
        const viewportSettingToUse = Object.assign(
          {},
          viewport,
          this._cpuFallbackEnabledElement.viewport
        );
 
        // Important: this.stackInvalidated is different than cpuRenderingInvalidated. The
        // former is being used to maintain the previous state of the viewport
        // in the same stack, the latter is used to trigger drawImageSync
        this._cpuFallbackEnabledElement.viewport = this.stackInvalidated
          ? viewport
          : viewportSettingToUse;
 
        // used the previous state of the viewport, then stackInvalidated is set to false
        this.stackInvalidated = false;
 
        // new viewport is set to the current viewport, then cpuRenderingInvalidated is set to true
        this.cpuRenderingInvalidated = true;
 
        this._cpuFallbackEnabledElement.transform = calculateTransform(
          this._cpuFallbackEnabledElement
        );
 
        // Todo: trigger an event to allow applications to hook into END of loading state
        // Currently we use loadHandlerManagers for this
 
        // Trigger the image to be drawn on the next animation frame
        this.render();
 
        // Update the viewport's currentImageIdIndex to reflect the newly
        // rendered image
        this.currentImageIdIndex = imageIdIndex;
        resolve(imageId);
      }
 
      function errorCallback(
        error: Error,
        imageIdIndex: number,
        imageId: string
      ) {
        const eventDetail = {
          error,
          imageIdIndex,
          imageId,
        };
 
        if (!this.suppressEvents) {
          triggerEvent(eventTarget, Events.IMAGE_LOAD_ERROR, eventDetail);
        }
 
        reject(error);
      }
 
      function sendRequest(imageId, imageIdIndex, options) {
        return loadAndCacheImage(imageId, options).then(
          (image) => {
            successCallback.call(this, image, imageIdIndex, imageId);
          },
          (error) => {
            errorCallback.call(this, error, imageIdIndex, imageId);
          }
        );
      }
 
      // Todo: Note that eventually all viewport data is converted into Float32Array,
      // we use it here for the purpose of scaling for now.
      const type = 'Float32Array';
 
      const priority = -5;
      const requestType = RequestType.Interaction;
      const additionalDetails = { imageId };
      const options = {
        targetBuffer: {
          type,
          offset: null,
          length: null,
        },
        preScale: {
          enabled: true,
        },
        useRGBA: true,
      };
 
      imageLoadPoolManager.addRequest(
        sendRequest.bind(this, imageId, imageIdIndex, options),
        requestType,
        additionalDetails,
        priority
      );
    });
  }
 
  private _loadAndDisplayImageGPU(imageId: string, imageIdIndex: number) {
    return new Promise((resolve, reject) => {
      // 1. Load the image using the Image Loader
      function successCallback(image, imageIdIndex, imageId) {
        // Todo: trigger an event to allow applications to hook into END of loading state
        // Currently we use loadHandlerManagers for this
        // Perform this check after the image has finished loading
        // in case the user has already scrolled away to another image.
        // In that case, do not render this image.
        Iif (this.currentImageIdIndex !== imageIdIndex) {
          return;
        }
 
        // cornerstone image
        this.csImage = image;
 
        const eventDetail: EventTypes.StackNewImageEventDetail = {
          image,
          imageId,
          imageIdIndex,
          viewportId: this.id,
          renderingEngineId: this.renderingEngineId,
        };
 
        triggerEvent(this.element, Events.STACK_NEW_IMAGE, eventDetail);
        this._updateActorToDisplayImageId(image);
 
        // Trigger the image to be drawn on the next animation frame
        this.render();
 
        // Update the viewport's currentImageIdIndex to reflect the newly
        // rendered image
        this.currentImageIdIndex = imageIdIndex;
        resolve(imageId);
      }
 
      function errorCallback(error, imageIdIndex, imageId) {
        const eventDetail = {
          error,
          imageIdIndex,
          imageId,
        };
 
        triggerEvent(eventTarget, Events.IMAGE_LOAD_ERROR, eventDetail);
        reject(error);
      }
 
      function sendRequest(imageId, imageIdIndex, options) {
        return loadAndCacheImage(imageId, options).then(
          (image) => {
            successCallback.call(this, image, imageIdIndex, imageId);
          },
          (error) => {
            errorCallback.call(this, error, imageIdIndex, imageId);
          }
        );
      }
 
      // Todo: Note that eventually all viewport data is converted into Float32Array,
      // we use it here for the purpose of scaling for now.
      const type = 'Float32Array';
 
      const priority = -5;
      const requestType = RequestType.Interaction;
      const additionalDetails = { imageId };
 
      const options = {
        targetBuffer: {
          type,
          offset: null,
          length: null,
        },
        preScale: {
          enabled: true,
        },
        useRGBA: false,
      };
 
      const eventDetail: EventTypes.PreStackNewImageEventDetail = {
        imageId,
        imageIdIndex,
        viewportId: this.id,
        renderingEngineId: this.renderingEngineId,
      };
      triggerEvent(this.element, Events.PRE_STACK_NEW_IMAGE, eventDetail);
 
      imageLoadPoolManager.addRequest(
        sendRequest.bind(this, imageId, imageIdIndex, options),
        requestType,
        additionalDetails,
        priority
      );
    });
  }
 
  /**
   * It updates the volume actor with the retrieved cornerstone image.
   * It first checks if the new image has the same dimensions, spacings, and
   * dimensions of the previous one: 1) If yes, it updates the pixel data 2) if not,
   * it creates a whole new volume actor for the image.
   * Note: Camera gets reset for both situations. Therefore, each image renders at
   * its exact 3D location in the space, and both image and camera moves while scrolling.
   *
   * @param image - Cornerstone image
   * @returns
   */
  private _updateActorToDisplayImageId(image) {
    // This function should do the following:
    // - Get the existing actor's vtkImageData that is being used to render the current image and check if we can reuse the vtkImageData that is in place (i.e. do the image dimensions and data type match?)
    // - If we can reuse it, replace the scalar data under the hood
    // - If we cannot reuse it, create a new actor, remove the old one, and reset the camera
 
    // 2. Check if we can reuse the existing vtkImageData object, if one is present.
    const sameImageData = this._checkVTKImageDataMatchesCornerstoneImage(
      image,
      this._imageData
    );
 
    const activeCamera = this.getRenderer().getActiveCamera();
 
    // Cache camera props so we can trigger one camera changed event after
    // The full transition.
    const previousCameraProps = _cloneDeep(this.getCamera());
    if (sameImageData && !this.stackInvalidated) {
      // 3a. If we can reuse it, replace the scalar data under the hood
      this._updateVTKImageDataFromCornerstoneImage(image);
 
      // Since the 3D location of the imageData is changing as we scroll, we need
      // to modify the camera position to render this properly. However, resetting
      // causes problem related to zoom and pan tools: upon rendering of a new slice
      // the pan and zoom will get reset. To solve this, 1) we store the camera
      // properties related to pan and zoom 2) reset the camera to correctly place
      // it in the space 3) restore the pan, zoom props.
      const cameraProps = this.getCamera();
 
      const panCache = vec3.subtract(
        vec3.create(),
        this.cameraFocalPointOnRender,
        cameraProps.focalPoint
      );
 
      // store rotation cache since reset camera will reset it
      const rotationCache = this.rotationCache;
 
      // Reset the camera to point to the new slice location, reset camera doesn't
      // modify the direction of projection and viewUp
      this.resetCameraNoEvent();
 
      // restore the rotation cache for the new slice
      this.setRotation(rotationCache, rotationCache);
 
      // set the flip back to the previous value since the restore camera props
      // rely on the correct flip value
      this.setCameraNoEvent({
        flipHorizontal: previousCameraProps.flipHorizontal,
        flipVertical: previousCameraProps.flipVertical,
      });
 
      const { focalPoint } = this.getCamera();
      this.cameraFocalPointOnRender = focalPoint;
 
      // This is necessary to initialize the clipping range and it is not related
      // to our custom slabThickness.
      // @ts-ignore: vtkjs incorrect typing
      activeCamera.setFreezeFocalPoint(true);
 
      // We shouldn't restore the focalPoint, position and parallelScale after reset
      // if it is the first render or we have completely re-created the vtkImageData
      this._restoreCameraProps(
        cameraProps,
        previousCameraProps,
        panCache as Point3
      );
 
      // Restore rotation for the new slice of the image
      this.rotationCache = 0;
      this._setPropertiesFromCache();
 
      return;
    }
 
    const {
      origin,
      direction,
      dimensions,
      spacing,
      bitsAllocated,
      numComps,
      numVoxels,
      imagePixelModule,
    } = this._getImageDataMetadata(image);
 
    // 3b. If we cannot reuse the vtkImageData object (either the first render
    // or the size has changed), create a new one
    this._createVTKImageData({
      origin,
      direction,
      dimensions,
      spacing,
      bitsAllocated,
      numComps,
      numVoxels,
    });
 
    // Set the scalar data of the vtkImageData object from the Cornerstone
    // Image's pixel data
    this._updateVTKImageDataFromCornerstoneImage(image);
 
    // Create a VTK Image Slice actor to display the vtkImageData object
    const actor = this.createActorMapper(this._imageData);
    const actors = [];
    actors.push({ uid: this.id, actor });
    this.setActors(actors);
    // Adjusting the camera based on slice axis. this is required if stack
    // contains various image orientations (axial ct, sagittal xray)
    const { viewPlaneNormal, viewUp } = this._getCameraOrientation(direction);
 
    this.setCameraNoEvent({ viewUp, viewPlaneNormal });
 
    // Setting this makes the following comment about resetCameraNoEvent not modifying viewUp true.
    this.initialViewUp = viewUp;
 
    // Reset the camera to point to the new slice location, reset camera doesn't
    // modify the direction of projection and viewUp
    this.resetCameraNoEvent();
 
    this.triggerCameraEvent(this.getCamera(), previousCameraProps);
 
    // This is necessary to initialize the clipping range and it is not related
    // to our custom slabThickness.
    // @ts-ignore: vtkjs incorrect typing
    activeCamera.setFreezeFocalPoint(true);
 
    // set voi for the first time
    const { windowCenter, windowWidth } = imagePixelModule;
    let voiRange =
      typeof windowCenter === 'number' && typeof windowWidth === 'number'
        ? windowLevelUtil.toLowHighRange(windowWidth, windowCenter)
        : undefined;
 
    // check if the image is already prescaled
    const isPreScaled =
      this.csImage.isPreScaled || this.csImage.preScale?.scaled;
 
    Iif (imagePixelModule.modality === 'PT' && isPreScaled) {
      voiRange = { lower: 0, upper: 5 };
    }
 
    this.initialVOIRange = voiRange;
 
    if (this.voiApplied && typeof voiRange === 'undefined') {
      // There are some cases when different frames within the same multi-frame
      // file are not hitting the actor cache because above
      // this.__checkVTKImageDataMatchesCornerstoneImage() call results in
      // "false".
      // In that case we want to keep the applied VOI range.
      voiRange = this.voiRange;
    }
    this.setProperties({ voiRange });
 
    // At the moment it appears that vtkImageSlice actors do not automatically
    // have an RGB Transfer Function created, so we need to create one.
    // Note: the 1024 here is what VTK would normally do to resample a color transfer function
    // before it is put into the GPU. Setting it with a length of 1024 allows us to
    // avoid that resampling step.
    const cfun = vtkColorTransferFunction.newInstance();
    let lower = 0;
    let upper = 1024;
    if (
      voiRange &&
      voiRange.lower !== undefined &&
      voiRange.upper !== undefined
    ) {
      lower = voiRange.lower;
      upper = voiRange.upper;
    }
    cfun.addRGBPoint(lower, 0.0, 0.0, 0.0);
    cfun.addRGBPoint(upper, 1.0, 1.0, 1.0);
    actor.getProperty().setRGBTransferFunction(0, cfun);
 
    let invert = false;
    Iif (imagePixelModule.photometricInterpretation === 'MONOCHROME1') {
      invert = true;
    }
 
    this.setProperties({ invert });
 
    // Saving position of camera on render, to cache the panning
    const { focalPoint } = this.getCamera();
    this.cameraFocalPointOnRender = focalPoint;
    this.stackInvalidated = false;
 
    if (this._publishCalibratedEvent) {
      this.triggerCalibrationEvent();
    }
  }
 
  /**
   * Loads the image based on the provided imageIdIndex
   * @param imageIdIndex - number represents imageId index
   */
  Eprivate async _setImageIdIndex(imageIdIndex: number): Promise<string> {
    if (imageIdIndex >= this.imageIds.length) {
      throw new Error(
        `ImageIdIndex provided ${imageIdIndex} is invalid, the stack only has ${this.imageIds.length} elements`
      );
    }
 
    // Update the state of the viewport to the new imageIdIndex;
    this.currentImageIdIndex = imageIdIndex;
    this.hasPixelSpacing = true;
 
    // Todo: trigger an event to allow applications to hook into START of loading state
    // Currently we use loadHandlerManagers for this
    const imageId = await this._loadAndDisplayImage(
      this.imageIds[imageIdIndex],
      imageIdIndex
    );
 
    return imageId;
  }
 
  /**
   * Centers Pan and resets the zoom for stack viewport.
   */
  public resetCamera(resetPan = true, resetZoom = true): boolean {
    if (this.useCPURendering) {
      this.resetCameraCPU(resetPan, resetZoom);
    } else {
      this.resetCameraGPU(resetPan, resetZoom);
    }
 
    this.rotation = 0;
    this.rotationCache = 0;
    return true;
  }
 
  private resetCameraCPU(resetPan, resetZoom) {
    const { image } = this._cpuFallbackEnabledElement;
 
    Eif (!image) {
      return;
    }
 
    resetCamera(this._cpuFallbackEnabledElement, resetPan, resetZoom);
 
    const { scale } = this._cpuFallbackEnabledElement.viewport;
 
    // canvas center is the focal point
    const { clientWidth, clientHeight } = this.element;
    const center: Point2 = [clientWidth / 2, clientHeight / 2];
 
    const centerWorld = this.canvasToWorldCPU(center);
 
    this.setCameraCPU({
      focalPoint: centerWorld,
      scale,
    });
  }
 
  private resetCameraGPU(resetPan, resetZoom): boolean {
    // Todo: we need to make the rotation a camera properties so that
    // we can reset it there, right now it is not possible to reset the rotation
    // without this
 
    // We do not know the ordering of various flips and rotations that have been applied, so just start like we were at the beginning.
    this.setCamera({
      flipHorizontal: false,
      flipVertical: false,
      viewUp: this.initialViewUp,
    });
 
    // For stack Viewport we since we have only one slice
    // it should be enough to reset the camera to the center of the image
    const resetToCenter = true;
    return super.resetCamera(resetPan, resetZoom, resetToCenter);
  }
 
  /**
   * It scrolls the stack of imageIds by the delta amount provided. If the debounce
   * flag is set, it will only scroll the stack if the delta is greater than the
   * debounceThreshold which is 40 milliseconds by default.
   * @param delta - number of indices to scroll, it can be positive or negative
   * @param debounce - whether to debounce the scroll event
   * @param loop - whether to loop the stack
   */
  public scroll(delta: number, debounce = true, loop = false): void {
    const imageIds = this.imageIds;
 
    const currentTargetImageIdIndex = this.targetImageIdIndex;
    const numberOfFrames = imageIds.length;
 
    let newTargetImageIdIndex = currentTargetImageIdIndex + delta;
    newTargetImageIdIndex = Math.max(0, newTargetImageIdIndex);
 
    Iif (loop) {
      newTargetImageIdIndex = newTargetImageIdIndex % numberOfFrames;
    } else {
      newTargetImageIdIndex = Math.min(
        numberOfFrames - 1,
        newTargetImageIdIndex
      );
    }
 
    this.targetImageIdIndex = newTargetImageIdIndex;
 
    const targetImageId = imageIds[newTargetImageIdIndex];
 
    const imageAlreadyLoaded = cache.isImageIdCached(targetImageId);
 
    // If image is already cached we want to scroll right away; however, if it is
    // not cached, we can debounce the scroll event to avoid firing multiple scroll
    // events for the images that might happen to be passing by (as a result of infinite
    // scrolling).
    Eif (imageAlreadyLoaded || !debounce) {
      this.setImageIdIndex(newTargetImageIdIndex);
    } else {
      clearTimeout(this.debouncedTimeout);
      this.debouncedTimeout = window.setTimeout(() => {
        this.setImageIdIndex(newTargetImageIdIndex);
      }, 40);
    }
 
    const eventData: StackViewportScrollEventDetail = {
      newImageIdIndex: newTargetImageIdIndex,
      imageId: targetImageId,
      direction: delta,
    };
 
    Eif (newTargetImageIdIndex !== currentTargetImageIdIndex) {
      triggerEvent(this.element, Events.STACK_VIEWPORT_SCROLL, eventData);
    }
  }
 
  /**
   * Loads the image based on the provided imageIdIndex. It is an Async function which
   * returns a promise that resolves to the imageId.
   *
   * @param imageIdIndex - number represents imageId index in the list of
   * provided imageIds in setStack
   */
  Epublic async setImageIdIndex(imageIdIndex: number): Promise<string> {
    // If we are already on this imageId index, stop here
    if (this.currentImageIdIndex === imageIdIndex) {
      return this.getCurrentImageId();
    }
 
    // Otherwise, get the imageId and attempt to display it
    const imageId = this._setImageIdIndex(imageIdIndex);
 
    return imageId;
  }
 
  /**
   * Calibrates the image with new metadata that has been added for imageId. To calibrate
   * a viewport, you should add your calibration data manually to
   * calibratedPixelSpacingMetadataProvider and call viewport.calibrateSpacing
   * for it get applied.
   *
   * @param imageId - imageId to be calibrated
   */
  public calibrateSpacing(imageId: string): void {
    const imageIdIndex = this.getImageIds().indexOf(imageId);
    this.stackInvalidated = true;
    this._loadAndDisplayImage(imageId, imageIdIndex);
  }
 
  /**
   * Restores the camera props such zooming and panning after an image is
   * changed, if needed (after scroll)
   *
   * @param parallelScale - camera parallel scale
   */
  private _restoreCameraProps(
    { parallelScale: prevScale }: ICamera,
    previousCamera: ICamera,
    panCache: Point3
  ): void {
    const renderer = this.getRenderer();
 
    // get the focalPoint and position after the reset
    const { position, focalPoint } = this.getCamera();
 
    const newPosition = vec3.subtract(vec3.create(), position, panCache);
    const newFocal = vec3.subtract(vec3.create(), focalPoint, panCache);
 
    // Restoring previous state x,y and scale, keeping the new z
    // we need to break the flip operations since they also work on the
    // camera position and focal point
    this.setCameraNoEvent({
      parallelScale: prevScale,
      position: newPosition as Point3,
      focalPoint: newFocal as Point3,
    });
 
    const camera = this.getCamera();
 
    this.triggerCameraEvent(camera, previousCamera);
 
    // Invoking render
    const RESET_CAMERA_EVENT = {
      type: 'ResetCameraEvent',
      renderer,
    };
 
    renderer.invokeEvent(RESET_CAMERA_EVENT);
  }
 
  private triggerCameraEvent(camera: ICamera, previousCamera: ICamera) {
    // Finally emit event for the full camera change cause during load image.
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
 
    Eif (!this.suppressEvents) {
      // For crosshairs to adapt to new viewport size
      triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
    }
  }
 
  private triggerCalibrationEvent() {
    // Update the indexToWorld and WorldToIndex for viewport
    const { imageData } = this.getImageData();
    // Finally emit event for the full camera change cause during load image.
    const eventDetail: EventTypes.ImageSpacingCalibratedEventDetail = {
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
      imageId: this.getCurrentImageId(),
      // Todo: why do we need to pass imageData? isn't' indexToWorld and worldToIndex enough?
      imageData: imageData as vtkImageData,
      worldToIndex: imageData.getWorldToIndex() as mat4,
      ...this._calibrationEvent,
    };
 
    Eif (!this.suppressEvents) {
      // Let the tools know the image spacing has been calibrated
      triggerEvent(this.element, Events.IMAGE_SPACING_CALIBRATED, eventDetail);
    }
 
    this._publishCalibratedEvent = false;
  }
 
  /**
   * canvasToWorld Returns the world coordinates of the given `canvasPos`
   * projected onto the plane defined by the `Viewport`'s camera.
   *
   * @param canvasPos - The position in canvas coordinates.
   * @returns The corresponding world coordinates.
   * @public
   */
  public canvasToWorld = (canvasPos: Point2): Point3 => {
    if (this.useCPURendering) {
      return this.canvasToWorldCPU(canvasPos);
    }
 
    return this.canvasToWorldGPU(canvasPos);
  };
 
  /**
   * Returns the canvas coordinates of the given `worldPos`
   * projected onto the `Viewport`'s `canvas`.
   *
   * @param worldPos - The position in world coordinates.
   * @returns The corresponding canvas coordinates.
   * @public
   */
  public worldToCanvas = (worldPos: Point3): Point2 => {
    if (this.useCPURendering) {
      return this.worldToCanvasCPU(worldPos);
    }
 
    return this.worldToCanvasGPU(worldPos);
  };
 
  private canvasToWorldCPU = (canvasPos: Point2): Point3 => {
    Iif (!this._cpuFallbackEnabledElement.image) {
      return;
    }
    // compute the pixel coordinate in the image
    const [px, py] = canvasToPixel(this._cpuFallbackEnabledElement, canvasPos);
 
    // convert pixel coordinate to world coordinate
    const { origin, spacing, direction } = this.getImageData();
 
    const worldPos = vec3.fromValues(0, 0, 0);
 
    // Calculate size of spacing vector in normal direction
    const iVector = direction.slice(0, 3) as Point3;
    const jVector = direction.slice(3, 6) as Point3;
 
    // Calculate the world coordinate of the pixel
    vec3.scaleAndAdd(worldPos, origin, iVector, px * spacing[0]);
    vec3.scaleAndAdd(worldPos, worldPos, jVector, py * spacing[1]);
 
    return [worldPos[0], worldPos[1], worldPos[2]] as Point3;
  };
 
  private worldToCanvasCPU = (worldPos: Point3): Point2 => {
    // world to pixel
    const { spacing, direction, origin } = this.getImageData();
 
    const iVector = direction.slice(0, 3) as Point3;
    const jVector = direction.slice(3, 6) as Point3;
 
    const diff = vec3.subtract(vec3.create(), worldPos, origin);
 
    const worldPoint: Point2 = [
      vec3.dot(diff, iVector) / spacing[0],
      vec3.dot(diff, jVector) / spacing[1],
    ];
 
    // pixel to canvas
    const canvasPoint = pixelToCanvas(
      this._cpuFallbackEnabledElement,
      worldPoint
    );
    return canvasPoint;
  };
 
  private canvasToWorldGPU = (canvasPos: Point2): Point3 => {
    const renderer = this.getRenderer();
 
    // Temporary setting the clipping range to the distance and distance + 0.1
    // in order to calculate the transformations correctly.
    // This is similar to the vtkSlabCamera isPerformingCoordinateTransformations
    // You can read more about it here there.
    const vtkCamera = this.getVtkActiveCamera();
    const crange = vtkCamera.getClippingRange();
    const distance = vtkCamera.getDistance();
 
    vtkCamera.setClippingRange(distance, distance + 0.1);
 
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
    const displayCoord = [
      canvasPosWithDPR[0] + this.sx,
      canvasPosWithDPR[1] + this.sy,
    ];
 
    // The y axis display coordinates are inverted with respect to canvas coords
    displayCoord[1] = size[1] - displayCoord[1];
 
    const worldCoord = openGLRenderWindow.displayToWorld(
      displayCoord[0],
      displayCoord[1],
      0,
      renderer
    );
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    return [worldCoord[0], worldCoord[1], worldCoord[2]];
  };
 
  private worldToCanvasGPU = (worldPos: Point3) => {
    const renderer = this.getRenderer();
 
    // Temporary setting the clipping range to the distance and distance + 0.1
    // in order to calculate the transformations correctly.
    // This is similar to the vtkSlabCamera isPerformingCoordinateTransformations
    // You can read more about it here there.
    const vtkCamera = this.getVtkActiveCamera();
    const crange = vtkCamera.getClippingRange();
    const distance = vtkCamera.getDistance();
 
    vtkCamera.setClippingRange(distance, distance + 0.1);
 
    const offscreenMultiRenderWindow =
      this.getRenderingEngine().offscreenMultiRenderWindow;
    const openGLRenderWindow =
      offscreenMultiRenderWindow.getOpenGLRenderWindow();
    const size = openGLRenderWindow.getSize();
    const displayCoord = openGLRenderWindow.worldToDisplay(
      ...worldPos,
      renderer
    );
 
    // The y axis display coordinates are inverted with respect to canvas coords
    displayCoord[1] = size[1] - displayCoord[1];
 
    const canvasCoord = <Point2>[
      displayCoord[0] - this.sx,
      displayCoord[1] - this.sy,
    ];
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasCoordWithDPR = <Point2>[
      canvasCoord[0] / devicePixelRatio,
      canvasCoord[1] / devicePixelRatio,
    ];
 
    return canvasCoordWithDPR;
  };
 
  /**
   * Returns the index of the imageId being renderer
   *
   * @returns currently shown imageId index
   */
  public getCurrentImageIdIndex = (): number => {
    return this.currentImageIdIndex;
  };
 
  /**
   *
   * Returns the imageIdIndex that is targeted to be loaded, in case of debounced
   * loading (with scroll), the targetImageIdIndex is the latest imageId
   * index that is requested to be loaded but debounced.
   */
  public getTargetImageIdIndex = (): number => {
    return this.targetImageIdIndex;
  };
 
  /**
   * Returns the list of image Ids for the current viewport
   * @returns list of strings for image Ids
   */
  public getImageIds = (): Array<string> => {
    return this.imageIds;
  };
 
  /**
   * Returns the currently rendered imageId
   * @returns string for imageId
   */
  public getCurrentImageId = (): string => {
    return this.imageIds[this.currentImageIdIndex];
  };
 
  /**
   * Returns true if the viewport contains the given imageId
   * @param imageId - imageId
   * @returns boolean if imageId is in viewport
   */
  public hasImageId = (imageId: string): boolean => {
    return this.imageIds.includes(imageId);
  };
 
  /**
   * Returns true if the viewport contains the given imageURI (no data loader scheme)
   * @param imageURI - imageURI
   * @returns boolean if imageURI is in viewport
   */
  public hasImageURI = (imageURI: string): boolean => {
    const imageIds = this.imageIds;
    for (let i = 0; i < imageIds.length; i++) {
      Eif (imageIdToURI(imageIds[i]) === imageURI) return true;
    }
 
    return false;
  };
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, returns the `vtkRenderer` responsible for rendering the `Viewport`.
   *
   * @returns The `vtkRenderer` for the `Viewport`.
   */
  public getRenderer() {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('getRenderer');
    }
 
    return super.getRenderer();
  }
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, return the default
   * actor which is the first actor in the renderer.
   * @returns An actor entry.
   */
  public getDefaultActor(): ActorEntry {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('getDefaultActor');
    }
 
    return super.getDefaultActor();
  }
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, return the actors in the viewport
   * @returns An array of ActorEntry objects.
   */
  public getActors(): Array<ActorEntry> {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('getActors');
    }
 
    return super.getActors();
  }
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, it returns the actor entry for the given actor UID.
   * @param actorUID - The unique ID of the actor you want to get.
   * @returns An ActorEntry object.
   */
  public getActor(actorUID: string): ActorEntry {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('getActor');
    }
 
    return super.getActor(actorUID);
  }
 
  /**
   * If the renderer is CPU-based, throw an error; otherwise, set the
   * actors in the viewport.
   * @param actors - An array of ActorEntry objects.
   */
  public setActors(actors: Array<ActorEntry>): void {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('setActors');
    }
 
    return super.setActors(actors);
  }
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, add a list of actors to the viewport
   * @param actors - An array of ActorEntry objects.
   */
  public addActors(actors: Array<ActorEntry>): void {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('addActors');
    }
 
    return super.addActors(actors);
  }
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, add the
   * actor to the viewport
   * @param actorEntry - The ActorEntry object that was created by the
   * user.
   */
  public addActor(actorEntry: ActorEntry): void {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('addActor');
    }
 
    return super.addActor(actorEntry);
  }
 
  /**
   * It throws an error if the renderer is CPU based. Otherwise, it removes the actors from the viewport.
   */
  public removeAllActors(): void {
    Iif (this.useCPURendering) {
      throw this.getCPUFallbackError('removeAllActors');
    }
 
    return super.removeAllActors();
  }
 
  private getCPUFallbackError(method: string): Error {
    return new Error(
      `method ${method} cannot be used during CPU Fallback mode`
    );
  }
 
  private fillWithBackgroundColor() {
    const renderingEngine = this.getRenderingEngine();
 
    Eif (renderingEngine) {
      renderingEngine.fillCanvasWithBackgroundColor(
        this.canvas,
        this.options.background
      );
    }
  }
 
  public customRenderViewportToCanvas = () => {
    Iif (!this.useCPURendering) {
      throw new Error(
        'Custom cpu rendering pipeline should only be hit in CPU rendering mode'
      );
    }
 
    Eif (this._cpuFallbackEnabledElement.image) {
      drawImageSync(
        this._cpuFallbackEnabledElement,
        this.cpuRenderingInvalidated
      );
      // reset flags
      this.cpuRenderingInvalidated = false;
    } else {
      this.fillWithBackgroundColor();
    }
 
    return {
      canvas: this.canvas,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
  };
 
  /**
   * Sets the colormap for the current viewport.
   * @param colormap - The colormap data to use.
   */
  public setColormap(colormap: CPUFallbackColormapData): void {
    Eif (this.useCPURendering) {
      this.setColormapCPU(colormap);
    } else {
      this.setColormapGPU(colormap);
    }
  }
 
  /**
   * It sets the colormap to the default colormap.
   */
  public unsetColormap(): void {
    if (this.useCPURendering) {
      this.unsetColormapCPU();
    } else {
      this.unsetColormapGPU();
    }
  }
 
  private unsetColormapCPU() {
    delete this._cpuFallbackEnabledElement.viewport.colormap;
    this._cpuFallbackEnabledElement.renderingTools = {};
 
    this.cpuRenderingInvalidated = true;
 
    this.fillWithBackgroundColor();
 
    this.render();
  }
 
  private setColormapCPU(colormapData: CPUFallbackColormapData) {
    const colormap = getColormap(colormapData.name, colormapData);
 
    this._cpuFallbackEnabledElement.viewport.colormap = colormap;
    this._cpuFallbackEnabledElement.renderingTools = {};
 
    this.fillWithBackgroundColor();
    this.cpuRenderingInvalidated = true;
 
    this.render();
  }
 
  private setColormapGPU(colormap: CPUFallbackColormapData) {
    // TODO -> vtk has full colormaps which are piecewise and frankly better?
    // Do we really want a pre defined 256 color map just for the sake of harmonization?
    throw new Error('setColorMapGPU not implemented.');
  }
 
  private unsetColormapGPU() {
    // TODO -> vtk has full colormaps which are piecewise and frankly better?
    // Do we really want a pre defined 256 color map just for the sake of harmonization?
    throw new Error('unsetColormapGPU not implemented.');
  }
 
  // create default values for imagePlaneModule if values are undefined
  private _getImagePlaneModule(imageId: string): ImagePlaneModule {
    const imagePlaneModule = metaData.get('imagePlaneModule', imageId);
 
    const newImagePlaneModule: ImagePlaneModule = {
      ...imagePlaneModule,
    };
 
    Iif (!newImagePlaneModule.columnPixelSpacing) {
      newImagePlaneModule.columnPixelSpacing = 1;
      this.hasPixelSpacing = false;
    }
 
    Iif (!newImagePlaneModule.rowPixelSpacing) {
      newImagePlaneModule.rowPixelSpacing = 1;
      this.hasPixelSpacing = false;
    }
 
    Iif (!newImagePlaneModule.columnCosines) {
      newImagePlaneModule.columnCosines = [0, 1, 0];
    }
 
    Iif (!newImagePlaneModule.rowCosines) {
      newImagePlaneModule.rowCosines = [1, 0, 0];
    }
 
    Iif (!newImagePlaneModule.imagePositionPatient) {
      newImagePlaneModule.imagePositionPatient = [0, 0, 0];
    }
 
    Iif (!newImagePlaneModule.imageOrientationPatient) {
      newImagePlaneModule.imageOrientationPatient = new Float32Array([
        1, 0, 0, 0, 1, 0,
      ]);
    }
 
    return newImagePlaneModule;
  }
}
 
export default StackViewport;