All files / core/src/RenderingEngine StackViewport.ts

58.58% Statements 611/1043
52.21% Branches 247/473
52.2% Functions 83/159
58.8% Lines 608/1034

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 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587                                                                                                                                                                                                          428x                                                     428x                     488x             488x     488x   488x           488x     488x 488x             488x     488x   488x 488x         488x 488x                                                   488x 488x 488x 488x 488x   488x       488x 488x 488x   488x                 4798x     488x         488x   488x   488x 11712x           11712x 11712x     11712x         1464x       10248x           488x                             976x 976x 976x   976x 976x   976x         976x 976x 976x 976x                                                                                                                                                                                                                                                                             488x                                 488x             488x             695x   695x       695x       695x 695x 695x   695x                                                                                                                                                           488x 38874x         488x                     488x 540x 540x   540x   540x   540x   540x       540x 44x     540x       488x                           544x 544x 544x 544x 544x   544x 224x     320x 320x 320x         320x                         20x     20x     20x 20x                     4x       4x 4x                                                         272x           272x                   272x 60x       272x 264x 264x     272x       272x 4x     272x                     488x                                     488x               12x   12x                   488x                         12x 12x 12x   12x   12x       12x   12x         12x               12x     12x   12x   12x   12x 12x 12x         12x   12x 24x 24x     12x 12x         12x         8x 8x   8x   8x       8x   8x     8x 8x       8x           8x     8x   8x 8x   8x         54x     38x 16x               16x     54x       54x 54x   54x 54x 54x                                                                                                                                                                                                                                                                                                                                                                               488x                       488x           32365x   32365x               32365x 32365x   32365x               32365x   32365x         488x 614x   614x     614x     614x         614x   614x               614x                                                                           614x 614x 614x 614x 614x   614x               614x         614x     614x 614x 614x 614x 614x       74x   74x       74x     74x 74x     74x   74x                                               576x   576x       576x           576x               576x 576x 576x   576x 4x     576x                                                                                                                         12x   12x       12x     12x   12x               836x   836x               58x     778x 778x       778x     778x   778x   778x                 778x   778x     778x     778x 498x       498x       498x       498x 498x       778x   778x     778x     778x 742x     778x       778x           778x                 4x           4x   4x   4x 4x     4x 4x     4x                               544x 544x                           544x   544x 4x     544x 544x 544x   544x 544x   544x 544x     544x                                             273x   273x       273x           273x   273x   273x   273x         273x     273x 273x   273x 273x   273x   113x 113x 113x 113x   113x       113x                                         273x                     38874x 38874x 758x   38116x 38116x 180x     37936x 37936x   37936x 37936x 37936x         37936x                                     1494x   1494x 498x                                   540x     540x           540x   540x 540x 540x 540x 540x   540x                                 498x 498x                                                     488x   488x   488x           488x 488x 1926x 1926x   488x 488x 488x           488x             488x 488x 488x 488x 488x 488x 488x   488x   488x         488x   488x             488x   488x             600x                                           552x 488x   64x 64x 64x 64x 64x 64x 64x     64x 64x       64x   64x 64x 64x 64x       64x         64x     64x               64x                   552x 552x   552x       552x     552x 552x 64x         552x                             558x                                                                                                                                                                                                                                                                                                                                 558x           558x 6x               552x 552x   552x     552x   552x 492x     552x   552x               552x 552x     552x       552x                                   558x 558x   558x             558x             558x   558x       558x   558x 558x                 558x 558x             558x       558x       558x           558x   558x 558x                                       488x                   488x 552x 552x                                                                                                                                             42x 42x 42x 42x     42x   42x               42x 42x 42x           42x 2x       42x                                         552x           552x         552x   54x   54x 54x                               54x 54x   54x                   498x         498x 498x                     498x     498x 498x 498x 10x   488x   498x       498x   498x 498x     498x       498x     498x   498x                 498x     498x   498x 498x       498x     498x     498x   498x   498x 318x         498x     498x   498x               498x   498x       498x 494x     4x       526x 522x     4x       4x       4x                   526x 526x 526x             526x 526x                 558x             558x 558x 558x       558x             558x 12x 12x 6x 6x 6x       558x                                                                             1600x               1600x 1600x                       66x   66x       66x 66x   66x   66x       66x           66x   66x   66x           66x 66x               66x           66x 26x                       112x     112x 42x       70x 70x   70x                                     498x               498x   498x           318x   318x                     318x   318x     318x                                                     488x                                               488x                                           488x 87641x           87641x 87641x 87641x   87641x   87641x 87641x 87641x     87641x           87641x             87641x         87641x           87641x             87641x   87641x     488x                                                                                           488x 105975x           105975x 105975x 105975x   105975x   105975x   105975x   105975x   105975x           105975x             105975x           105975x 105975x     105975x   105975x         105975x     488x                                                                                             472208x 472208x                                     28x   28x                   544x             544x               488x 46358x             488x 560x                                                                     920x 920x 920x     920x     920x 920x 647x   273x 273x 273x 273x 273x       273x 113x     160x 160x                                                                                                                                     560x 560x 560x 560x     560x 560x                 560x                 42x           42x 42x 42x 42x 42x         42x               1269x 1269x                 488x                                         488x 298x             488x     5752x               488x                 488x 23x                   508x   508x 508x             488x                                                                                                                   80x 80x 80x 80x     80x     80x           80x 80x       80x     80x 80x   80x         80x                     1160x   1160x         1160x   1160x             488x                                                                                                                       1600x 1600x 1600x                                                                                                                        
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
import type { vtkImageData as vtkImageDataType } from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkCamera from '@kitware/vtk.js/Rendering/Core/Camera';
import vtkColorTransferFunction from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction';
import vtkColorMaps from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkImageMapper from '@kitware/vtk.js/Rendering/Core/ImageMapper';
import vtkImageSlice from '@kitware/vtk.js/Rendering/Core/ImageSlice';
import { mat4, vec2, vec3 } from 'gl-matrix';
import eventTarget from '../eventTarget';
import * as metaData from '../metaData';
import { getImageDataMetadata as getImageDataMetadataUtil } from '../utilities/getImageDataMetadata';
import { coreLog } from '../utilities/logger';
 
import type {
  ActorEntry,
  CPUFallbackColormapData,
  CPUFallbackEnabledElement,
  CPUIImageData,
  ColormapPublic,
  EventTypes,
  FlipDirection,
  ICamera,
  IImage,
  IImageCalibration,
  IImageData,
  IImagesLoader,
  IStackInput,
  ImageLoadListener,
  Mat3,
  PTScaling,
  Point2,
  Point3,
  Scaling,
  StackViewportProperties,
  VOIRange,
  ViewReference,
  VolumeActor,
  ViewReferenceSpecifier,
  ReferenceCompatibleOptions,
  ViewportInput,
  ImagePixelModule,
  ImagePlaneModule,
  PixelDataTypedArray,
} from '../types';
import { actorIsA, isImageActor } from '../utilities/actorCheck';
import * as colormapUtils from '../utilities/colormap';
import {
  getTransferFunctionNodes,
  setTransferFunctionNodes,
} from '../utilities/transferFunctionUtils';
import * as windowLevelUtil from '../utilities/windowLevel';
import createLinearRGBTransferFunction from '../utilities/createLinearRGBTransferFunction';
import createSigmoidRGBTransferFunction from '../utilities/createSigmoidRGBTransferFunction';
import { updateVTKImageDataWithCornerstoneImage } from '../utilities/updateVTKImageDataWithCornerstoneImage';
import triggerEvent from '../utilities/triggerEvent';
import { isEqual } from '../utilities/isEqual';
import invertRgbTransferFunction from '../utilities/invertRgbTransferFunction';
import imageRetrieveMetadataProvider from '../utilities/imageRetrieveMetadataProvider';
import imageIdToURI from '../utilities/imageIdToURI';
 
import Viewport from './Viewport';
import drawImageSync from './helpers/cpuFallback/drawImageSync';
import { getImagePlaneModule } from '../utilities/buildMetadata';
 
import {
  Events,
  InterpolationType,
  MetadataModules,
  RequestType,
  VOILUTFunctionType,
  ViewportStatus,
} from '../enums';
import type { ImageLoaderOptions } from '../loaders/imageLoader';
import { loadAndCacheImage } from '../loaders/imageLoader';
import imageLoadPoolManager from '../requestPool/imageLoadPoolManager';
import calculateTransform from './helpers/cpuFallback/rendering/calculateTransform';
import canvasToPixel from './helpers/cpuFallback/rendering/canvasToPixel';
import getDefaultViewport from './helpers/cpuFallback/rendering/getDefaultViewport';
import pixelToCanvas from './helpers/cpuFallback/rendering/pixelToCanvas';
import resize from './helpers/cpuFallback/rendering/resize';
 
import cache from '../cache/cache';
import { getConfiguration, getShouldUseCPURendering } from '../init';
import { createProgressive } from '../loaders/ProgressiveRetrieveImages';
import type {
  StackViewportNewStackEventDetail,
  StackViewportScrollEventDetail,
  VoiModifiedEventDetail,
} from '../types/EventTypes';
import type { ImageActor } from '../types/IActor';
import correctShift from './helpers/cpuFallback/rendering/correctShift';
import resetCamera from './helpers/cpuFallback/rendering/resetCamera';
import { Transform } from './helpers/cpuFallback/rendering/transform';
import type vtkRenderer from '@kitware/vtk.js/Rendering/Core/Renderer';
import uuidv4 from '../utilities/uuidv4';
import getSpacingInNormalDirection from '../utilities/getSpacingInNormalDirection';
import getClosestImageId from '../utilities/getClosestImageId';
import { adjustInitialViewUp } from '../utilities/adjustInitialViewUp';
import { isContextPoolRenderingEngine } from './helpers/isContextPoolRenderingEngine';
 
const EPSILON = 1; // Slice Thickness
 
export interface ImageDataMetaData {
  bitsAllocated: number;
  numberOfComponents: number;
  origin: Point3;
  direction: Mat3;
  dimensions: Point3;
  spacing: Point3;
  numVoxels: number;
  imagePlaneModule: ImagePlaneModule;
  imagePixelModule: ImagePixelModule;
}
// TODO This needs to be exposed as its published to consumers.
interface CalibrationEvent {
  rowScale?: number;
  columnScale?: number;
  scale: number;
  calibration: IImageCalibration;
}
 
interface SetVOIOptions {
  suppressEvents?: boolean;
  forceRecreateLUTFunction?: boolean;
  voiUpdatedWithSetProperties?: boolean;
}
 
const log = coreLog.getLogger('RenderingEngine', 'StackViewport');
 
/**
 * 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 {
  private imageIds: string[] = [];
  /**
   * The imageKeyToIndexMap maps the imageId values to the position in the imageIds
   * array.  It also contains the imageURI equivalent of each imageId to map
   * to the position in the imageIds array.  This allows checking for whether
   * the imageId or URI is present without having to scan the imageIds array.
   */
  private imageKeyToIndexMap = new Map<string, number>();
 
  // current imageIdIndex that is rendered in the viewport
  private currentImageIdIndex = 0;
  // the imageIdIndex that is targeted to be loaded with scrolling but has not initiated loading yet
  private targetImageIdIndex = 0;
  // setTimeout if the image is debounced to be loaded
  private debouncedTimeout: number;
  /**
   * The progressive retrieval configuration used for this viewport.
   */
  protected imagesLoader: IImagesLoader = this;
 
  // Viewport Properties
  private globalDefaultProperties: StackViewportProperties = {};
  private perImageIdDefaultProperties = new Map<
    string,
    StackViewportProperties
  >();
 
  private colormap: ColormapPublic | CPUFallbackColormapData;
  private voiRange: VOIRange;
  private voiUpdatedWithSetProperties = false;
  private VOILUTFunction: VOILUTFunctionType;
  //
  private invert = false;
  // The initial invert of the image loaded as opposed to the invert status of the viewport itself (see above).
  private initialInvert = false;
  private initialTransferFunctionNodes = null;
  private interpolationType: InterpolationType;
 
  // Helpers
  private _imageData: vtkImageDataType;
  private stackInvalidated = false; // if true -> new actor is forced to be created for the stack
  private _publishCalibratedEvent = false;
  private _calibrationEvent: CalibrationEvent;
  private _cpuFallbackEnabledElement?: CPUFallbackEnabledElement;
  // CPU fallback
  private useCPURendering: boolean;
  private cpuImagePixelData: PixelDataTypedArray;
  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;
 
  // this flag is used to check
  // if the viewport used the same actor/mapper to render the image
  // or because of the new image inconsistency, a new actor/mapper was created
  public stackActorReInitialized: boolean;
 
  /**
   * Constructor for the StackViewport class
   * @param props - ViewportInput
   */
  constructor(props: ViewportInput) {
    super(props);
    this.scaling = {};
    this.modality = null;
    this.useCPURendering = getShouldUseCPURendering();
    this._configureRenderingPipeline();
 
    const result = this.useCPURendering
      ? this._resetCPUFallbackElement()
      : this._resetGPUViewport();
 
    this.currentImageIdIndex = 0;
    this.targetImageIdIndex = 0;
    this.resetCamera();
 
    this.initializeElementDisabledHandler();
  }
 
  public setUseCPURendering(value: boolean) {
    this.useCPURendering = value;
    this._configureRenderingPipeline(value);
  }
 
  static get useCustomRenderingPipeline(): boolean {
    return getShouldUseCPURendering();
  }
 
  public updateRenderingPipeline = () => {
    this._configureRenderingPipeline();
  };
 
  private _configureRenderingPipeline(value?: boolean) {
    const isContextPool = isContextPoolRenderingEngine();
 
    this.useCPURendering = value ?? getShouldUseCPURendering();
 
    for (const key in this.renderingPipelineFunctions) {
      Eif (
        Object.prototype.hasOwnProperty.call(
          this.renderingPipelineFunctions,
          key
        )
      ) {
        const functions = this.renderingPipelineFunctions[key];
        Iif (this.useCPURendering) {
          this[key] = functions.cpu;
        } else {
          if (
            typeof functions.gpu === 'object' &&
            functions.gpu.tiled &&
            functions.gpu.contextPool
          ) {
            this[key] = isContextPool
              ? functions.gpu.contextPool
              : functions.gpu.tiled;
          } else {
            this[key] = functions.gpu;
          }
        }
      }
    }
 
    const result = this.useCPURendering
      ? this._resetCPUFallbackElement()
      : this._resetGPUViewport();
  }
 
  private _resetCPUFallbackElement() {
    this._cpuFallbackEnabledElement = {
      canvas: this.canvas,
      renderingTools: {},
      transform: new Transform(),
      viewport: { rotation: 0 },
    };
  }
 
  private _resetGPUViewport() {
    const renderer = this.getRenderer();
    const camera = vtkCamera.newInstance();
    renderer.setActiveCamera(camera);
 
    const viewPlaneNormal = [0, 0, -1] as Point3;
    this.initialViewUp = [0, -1, 0] as Point3;
 
    camera.setDirectionOfProjection(
      -viewPlaneNormal[0],
      -viewPlaneNormal[1],
      -viewPlaneNormal[2]
    );
    camera.setViewUp(...this.initialViewUp);
    camera.setParallelProjection(true);
    camera.setThicknessFromFocalPoint(0.1);
    camera.setFreezeFocalPoint(true);
  }
 
  /**
   * 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 the user has selected CPU rendering, return the CPU camera, otherwise
   * return the default camera
   * @returns The camera object.
   */
  public getCamera: () => ICamera;
 
  /**
   * 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?: boolean
  ) => void;
 
  public getRotation: () => number;
 
  /**
   * It sets the colormap to the default colormap.
   */
  public unsetColormap: () => void;
 
  /**
   * Resets the camera for the stack viewport.
   * This method adjusts the camera to fit the image in the viewport,
   * potentially resetting pan, zoom, and other view parameters.
   *
   * @param options - Optional configuration for the reset operation
   * @param options.resetPan - Whether to reset the pan (default: true)
   * @param options.resetZoom - Whether to reset the zoom (default: true)
   * @returns boolean - True if the camera was reset successfully, false otherwise
   */
  public resetCamera: (options?: {
    resetPan?: boolean;
    resetZoom?: boolean;
    resetToCenter?: boolean;
    suppressEvents?: boolean;
  }) => boolean;
 
  /**
   * 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;
 
  /**
   * 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 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;
 
  /**
   * If the renderer is CPU based, throw an error. Otherwise, return the actors in the viewport
   * @returns An array of ActorEntry objects.
   */
  public getActors: () => ActorEntry[];
  /**
   * 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;
 
  /**
   * 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: ActorEntry[]) => void;
 
  /**
   * 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: ActorEntry[]) => void;
 
  /**
   * 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;
 
  /**
   * It throws an error if the renderer is CPU based. Otherwise, it removes the actors from the viewport.
   */
  public removeAllActors: () => void;
 
  private setVOI: (voiRange: VOIRange, options?: SetVOIOptions) => void;
 
  protected setInterpolationType: (
    interpolationType: InterpolationType
  ) => void;
 
  private setInvertColor: (invert: boolean) => void;
 
  /**
   * Sets the colormap for the current viewport.
   * @param colormap - The colormap data to use.
   */
  private setColormap: (
    colormap: CPUFallbackColormapData | ColormapPublic
  ) => void;
 
  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();
    }
  };
 
  private _resizeCPU = (): void => {
    if (this._cpuFallbackEnabledElement.viewport) {
      resize(this._cpuFallbackEnabledElement);
    }
  };
 
  private getImageDataGPU(): IImageData | undefined {
    const defaultActor = this.getDefaultActor();
 
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
 
    const { actor } = defaultActor;
    const vtkImageData = actor.getMapper().getInputData();
    const csImage = this.csImage;
 
    return {
      dimensions: vtkImageData.getDimensions(),
      spacing: vtkImageData.getSpacing(),
      origin: vtkImageData.getOrigin(),
      direction: vtkImageData.getDirection(),
      get scalarData() {
        return csImage?.voxelManager.getScalarData();
      },
      imageData: actor.getMapper().getInputData(),
      metadata: {
        Modality: this.modality,
        FrameOfReferenceUID: this.getFrameOfReferenceUID(),
      },
      scaling: this.scaling,
      hasPixelSpacing: this.hasPixelSpacing,
      calibration: { ...csImage?.calibration, ...this.calibration },
      preScale: {
        ...csImage?.preScale,
      },
      voxelManager: csImage?.voxelManager,
    };
  }
 
  private getImageDataCPU(): CPUIImageData | undefined {
    const { metadata } = this._cpuFallbackEnabledElement;
 
    if (!metadata) {
      return;
    }
 
    const spacing = metadata.spacing;
    const csImage = this.csImage;
    return {
      dimensions: metadata.dimensions,
      spacing,
      origin: metadata.origin,
      direction: metadata.direction,
      metadata: {
        Modality: this.modality,
        FrameOfReferenceUID: this.getFrameOfReferenceUID(),
      },
      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, destPoint?: Point3) => {
          const canvasPoint = pixelToCanvas(this._cpuFallbackEnabledElement, [
            point[0],
            point[1],
          ]);
          return this.canvasToWorldCPU(canvasPoint, destPoint);
        },
      },
      scalarData: this.cpuImagePixelData,
      hasPixelSpacing: this.hasPixelSpacing,
      calibration: { ...csImage?.calibration, ...this.calibration },
      preScale: {
        ...csImage?.preScale,
      },
      voxelManager: csImage?.voxelManager,
    };
  }
 
  /**
   * 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 = (sliceIndex?: number): string =>
    this.getImagePlaneReferenceData(sliceIndex)?.FrameOfReferenceUID;
 
  /**
   * Returns the raw/loaded image being shown inside the stack viewport.
   */
  public getCornerstoneImage = (): IImage => this.csImage;
 
  /**
   * 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();
 
    actor.setMapper(mapper);
 
    const { preferSizeOverAccuracy } = getConfiguration().rendering;
 
    Iif (preferSizeOverAccuracy) {
      mapper.setPreferSizeOverAccuracy(true);
    }
 
    if (imageData.getPointData().getScalars().getNumberOfComponents() > 1) {
      actor.getProperty().setIndependentComponents(false);
    }
 
    return actor;
  };
 
  /** Gets the number of slices */
  public getNumberOfSlices = (): number => {
    return this.imageIds.length;
  };
 
  /**
   * 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 calibration = metaData.get('calibratedPixelSpacing', imageId);
    const isUpdated = this.calibration !== calibration;
    const { scale } = calibration || {};
    this.hasPixelSpacing = scale > 0 || imagePlaneModule.rowPixelSpacing > 0;
    imagePlaneModule.calibration = calibration;
 
    if (!isUpdated) {
      return imagePlaneModule;
    }
 
    this.calibration = calibration;
    this._publishCalibratedEvent = true;
    this._calibrationEvent = {
      scale,
      calibration,
    } as CalibrationEvent;
 
    return imagePlaneModule;
  }
 
  /**
   * Update the default properties of the viewport and add properties by imageId if specified
   * @param ViewportProperties - The properties to set
   * @param imageId If given, we set the default properties only for this image index, if not
   * the default properties will be set for all imageIds
   */
  public setDefaultProperties(
    ViewportProperties: StackViewportProperties,
    imageId?: string
  ): void {
    Iif (imageId == null) {
      this.globalDefaultProperties = ViewportProperties;
    } else {
      this.perImageIdDefaultProperties.set(imageId, ViewportProperties);
 
      //If the viewport is the same imageIdI, we need to update the viewport
      Eif (this.getCurrentImageId() === imageId) {
        this.setProperties(ViewportProperties);
      }
    }
  }
 
  /**
   * Remove the global default properties of the viewport or remove default properties for an imageId if specified
   * @param imageId If given, we remove the default properties only for this imageID, if not
   * the global default properties will be removed
   */
  public clearDefaultProperties(imageId?: string): void {
    Iif (imageId == null) {
      this.globalDefaultProperties = {};
      this.resetProperties();
    } else {
      this.perImageIdDefaultProperties.delete(imageId);
      this.resetToDefaultProperties();
    }
  }
 
  /**
   Configures the properties of the viewport.
   This method allows customization of the viewport by setting attributes like
   VOI (Value of Interest), color inversion, interpolation type, and image rotation.
   If setProperties is called for the first time, the provided properties will
   become the default settings for all images in the stack in case the resetPropertiese need to be called
   @param properties - An object containing the properties to be set.
   @param properties.colormap - Specifies the colormap for the viewport.
   @param properties.voiRange - Defines the lower and upper Value of Interest (VOI) to be applied.
   @param properties.VOILUTFunction - Function to handle the application of a lookup table (LUT) to the VOI.
   @param properties.invert - A boolean value to toggle color inversion (true: inverted, false: not inverted).
   @param properties.interpolationType - Determines the interpolation method to be used (1: linear, 0: nearest-neighbor).
   @param properties.rotation - Specifies the image rotation angle in degrees.
   @param suppressEvents - A boolean value to control event suppression. If true, the related events will not be triggered. Default is false.
   */
  public setProperties(
    {
      colormap,
      voiRange,
      VOILUTFunction,
      invert,
      interpolationType,
    }: StackViewportProperties = {},
    suppressEvents = false
  ): void {
    this.viewportStatus = this.csImage
      ? ViewportStatus.PRE_RENDER
      : ViewportStatus.LOADING;
 
    // setting the global default properties to the viewport, since we can always
    // go back to the default properties by calling resetToDefaultProperties
    this.globalDefaultProperties = {
      colormap: this.globalDefaultProperties.colormap ?? colormap,
      voiRange: this.globalDefaultProperties.voiRange ?? voiRange,
      VOILUTFunction:
        this.globalDefaultProperties.VOILUTFunction ?? VOILUTFunction,
      invert: this.globalDefaultProperties.invert ?? invert,
      interpolationType:
        this.globalDefaultProperties.interpolationType ?? interpolationType,
    };
 
    if (typeof colormap !== 'undefined') {
      this.setColormap(colormap);
    }
    // if voi is not applied for the first time, run the setVOI function
    // which will apply the default voi based on the range
    if (typeof voiRange !== 'undefined') {
      const voiUpdatedWithSetProperties = true;
      this.setVOI(voiRange, { suppressEvents, voiUpdatedWithSetProperties });
    }
 
    Iif (typeof VOILUTFunction !== 'undefined') {
      this.setVOILUTFunction(VOILUTFunction, suppressEvents);
    }
 
    if (typeof invert !== 'undefined') {
      this.setInvertColor(invert);
    }
 
    Iif (typeof interpolationType !== 'undefined') {
      this.setInterpolationType(interpolationType);
    }
  }
 
  /**
   * Retrieve the viewport default properties
   * @param imageId If given, we retrieve the default properties of an image index if it exists
   * If not given,we return the global properties of the viewport
   * @returns viewport properties including voi, invert, interpolation type,
   */
  public getDefaultProperties = (imageId?: string): StackViewportProperties => {
    let imageProperties;
    if (imageId !== undefined) {
      imageProperties = this.perImageIdDefaultProperties.get(imageId);
    }
 
    if (imageProperties !== undefined) {
      return imageProperties;
    }
 
    return {
      ...this.globalDefaultProperties,
    };
  };
 
  /**
   * Retrieve the viewport properties
   * @returns viewport properties including voi, invert, interpolation type,
   */
  public getProperties = (): StackViewportProperties => {
    const {
      colormap,
      voiRange,
      VOILUTFunction,
      interpolationType,
      invert,
      voiUpdatedWithSetProperties,
    } = this;
 
    return {
      colormap,
      voiRange,
      VOILUTFunction,
      interpolationType,
      invert,
      isComputedVOI: !voiUpdatedWithSetProperties,
    };
  };
 
  public resetCameraForResize = (): boolean => {
    return this.resetCamera({
      resetPan: true,
      resetZoom: true,
      resetToCenter: true,
      suppressEvents: true,
    });
  };
 
  /**
   * Reset the viewport properties to the default values
   */
  public resetProperties(): void {
    this.cpuRenderingInvalidated = true;
    this.voiUpdatedWithSetProperties = false;
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    this.fillWithBackgroundColor();
 
    Iif (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
    }
 
    this._resetProperties();
 
    this.render();
  }
 
  private _resetProperties() {
    let voiRange;
    Iif (this._isCurrentImagePTPrescaled()) {
      // if not set via setProperties; if it is a PT image and is already prescaled,
      // use the default range for PT
      voiRange = this._getDefaultPTPrescaledVOIRange();
    } else {
      // if not set via setProperties; if it is not a PT image or is not prescaled,
      // use the voiRange for the current image from its metadata if found
      // otherwise, use the cached voiRange
      voiRange = this._getVOIRangeForCurrentImage();
    }
 
    this.setVOI(voiRange);
 
    this.setInvertColor(this.initialInvert);
 
    this.setInterpolationType(InterpolationType.LINEAR);
 
    Eif (!this.useCPURendering) {
      const transferFunction = this.getTransferFunction();
      setTransferFunctionNodes(
        transferFunction,
        this.initialTransferFunctionNodes
      );
 
      const nodes = getTransferFunctionNodes(transferFunction);
 
      const RGBPoints = nodes.reduce((acc, node) => {
        acc.push(node[0], node[1], node[2], node[3]);
        return acc;
      }, []);
 
      const defaultActor = this.getDefaultActor();
      const matchedColormap = colormapUtils.findMatchingColormap(
        RGBPoints,
        defaultActor.actor
      );
 
      this.setColormap(matchedColormap);
    }
  }
 
  public resetToDefaultProperties(): void {
    this.cpuRenderingInvalidated = true;
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    this.fillWithBackgroundColor();
 
    Iif (this.useCPURendering) {
      this._cpuFallbackEnabledElement.renderingTools = {};
    }
 
    const currentImageId = this.getCurrentImageId();
    const properties =
      this.perImageIdDefaultProperties.get(currentImageId) ||
      this.globalDefaultProperties;
 
    Eif (properties.colormap?.name) {
      this.setColormap(properties.colormap);
    }
 
    let voiRange;
    Iif (properties.voiRange == undefined) {
      // if not set via setProperties; if it is not a PT image or is not prescaled,
      // use the voiRange for the current image from its metadata if found
      // otherwise, use the cached voiRange
      voiRange = this._getVOIRangeForCurrentImage();
    } else {
      voiRange = properties.voiRange;
    }
 
    this.setVOI(voiRange);
 
    this.setInterpolationType(InterpolationType.LINEAR);
    this.setInvertColor(false);
 
    this.render();
  }
 
  private _getVOIFromCache(): VOIRange {
    let voiRange;
    if (this.voiUpdatedWithSetProperties) {
      // use the cached voiRange if the voiRange is locked (if the user has
      // manually set the voi with tools or setProperties api)
      voiRange = this.voiRange;
    } else Iif (this._isCurrentImagePTPrescaled()) {
      // if not set via setProperties; if it is a PT image and is already prescaled,
      // use the default range for PT
      voiRange = this._getDefaultPTPrescaledVOIRange();
    } else {
      // if not set via setProperties; if it is not a PT image or is not prescaled,
      // use the voiRange for the current image from its metadata if found
      // otherwise, use the cached voiRange
      voiRange = this._getVOIRangeForCurrentImage() ?? this.voiRange;
    }
 
    return voiRange;
  }
 
  private _setPropertiesFromCache(): void {
    const voiRange = this._getVOIFromCache();
    const { interpolationType, invert } = this;
 
    this.setVOI(voiRange);
    this.setInterpolationType(interpolationType);
    this.setInvertColor(invert);
  }
 
  private getCameraCPU(): Partial<ICamera> {
    const { metadata, viewport } = this._cpuFallbackEnabledElement;
 
    if (!metadata) {
      return {};
    }
 
    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 (viewport.rotation) {
      const rotationMatrix = mat4.fromRotation(
        mat4.create(),
        (viewport.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,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  }
 
  private getPanCPU(): Point2 {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    return [viewport.translation.x, viewport.translation.y];
  }
 
  private setPanCPU(pan: Point2): void {
    const camera = this.getCameraCPU();
 
    this.setCameraCPU({
      ...camera,
      focalPoint: [...pan.map((p) => -p), 0] as Point3,
    });
  }
 
  private getZoomCPU(): number {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    return viewport.scale;
  }
 
  private setZoomCPU(zoom: number): void {
    const camera = this.getCameraCPU();
 
    this.setCameraCPU({ ...camera, scale: zoom });
  }
 
  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 getRotationCPU = (): number => {
    const { viewport } = this._cpuFallbackEnabledElement;
    return viewport.rotation;
  };
 
  /**
   * Gets the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently.
   *
   * @returns the rotation resulting from the value set in setRotation AND taking into
   * account any flips that occurred subsequently.
   */
  private getRotationGPU = (): number => {
    const {
      viewUp: currentViewUp,
      viewPlaneNormal,
      flipVertical,
      flipHorizontal,
    } = this.getCameraNoRotation();
 
    const adjustedViewUp = adjustInitialViewUp(
      this.initialViewUp,
      flipHorizontal,
      flipVertical,
      viewPlaneNormal
    );
    // The angle between the initial and current view up vectors.
    // TODO: check with VTK about rounding errors here.
    const angleRad = vec3.angle(adjustedViewUp, currentViewUp);
    const initialToCurrentViewUpAngle = (angleRad * 180) / Math.PI;
 
    const initialToCurrentViewUpCross = vec3.cross(
      vec3.create(),
      adjustedViewUp,
      currentViewUp
    );
 
    // The sign of the dot product of the start/end view up cross product and
    // the viewPlaneNormal indicates a positive or negative rotation respectively.
    const normalDot = vec3.dot(initialToCurrentViewUpCross, viewPlaneNormal);
 
    return normalDot >= 0
      ? initialToCurrentViewUpAngle
      : (360 - initialToCurrentViewUpAngle) % 360;
  };
 
  protected setRotation = (rotation: number) => {
    const previousCamera = this.getCamera();
 
    Iif (this.useCPURendering) {
      this.setRotationCPU(rotation);
    } else {
      this.setRotationGPU(rotation);
    }
 
    Iif (this._suppressCameraModifiedEvents) {
      return;
    }
 
    // New camera after rotation
    const camera = this.getCamera();
 
    const eventDetail: EventTypes.CameraModifiedEventDetail = {
      previousCamera,
      camera,
      element: this.element,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
 
    triggerEvent(this.element, Events.CAMERA_MODIFIED, eventDetail);
  };
 
  private setVOILUTFunction(
    voiLUTFunction: VOILUTFunctionType,
    suppressEvents?: boolean
  ): void {
    if (this.useCPURendering) {
      throw new Error('VOI LUT function is not supported in CPU rendering');
    }
 
    // make sure the VOI LUT function is valid in the VOILUTFunctionType which is enum
    const newVOILUTFunction = this._getValidVOILUTFunction(voiLUTFunction);
 
    let forceRecreateLUTFunction = false;
    if (this.VOILUTFunction !== newVOILUTFunction) {
      forceRecreateLUTFunction = true;
    }
 
    this.VOILUTFunction = newVOILUTFunction;
 
    const { voiRange } = this.getProperties();
    this.setVOI(voiRange, { suppressEvents, forceRecreateLUTFunction });
  }
 
  private setRotationCPU(rotation: number): void {
    const { viewport } = this._cpuFallbackEnabledElement;
    viewport.rotation = rotation;
  }
 
  /**
   * The rotation that is being set is intended to be around the currently
   * display center of the image.  However, the roll operation does it around
   * another point which can result in the image disappearing.  The set/get
   * pan values move the center of rotation to the center of the image as
   * currently actually displayed.
   */
  private setRotationGPU(rotation: number): void {
    const panFit = this.getPan(this.fitToCanvasCamera);
    const pan = this.getPan();
    const panSub = vec2.sub([0, 0], panFit, pan) as Point2;
    this.setPan(panSub, false);
    const { flipVertical, flipHorizontal, viewPlaneNormal } = this.getCamera();
 
    const adjustedViewUp = adjustInitialViewUp(
      this.initialViewUp,
      flipHorizontal,
      flipVertical,
      viewPlaneNormal
    );
 
    // Reset camera to adjusted initial viewUp
    this.setCameraNoEvent({
      viewUp: adjustedViewUp as Point3,
    });
 
    // rotating camera to the new value
    this.getVtkActiveCamera().roll(-rotation);
 
    // Adjust the pan to bring the center back
    const afterPan = this.getPan();
    const afterPanFit = this.getPan(this.fitToCanvasCamera);
    const newCenter = vec2.sub([0, 0], afterPan, afterPanFit);
    const newOffset = vec2.add([0, 0], panFit, newCenter) as Point2;
    this.setPan(newOffset, false);
  }
 
  private setInterpolationTypeGPU(interpolationType: InterpolationType): void {
    const defaultActor = this.getDefaultActor();
 
    Iif (!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;
 
    viewport.pixelReplication =
      interpolationType === InterpolationType.LINEAR ? false : true;
 
    this.interpolationType = interpolationType;
  }
 
  private setInvertColorCPU(invert: boolean): void {
    const { viewport } = this._cpuFallbackEnabledElement;
 
    if (!viewport) {
      return;
    }
 
    viewport.invert = invert;
    this.invert = invert;
  }
 
  private setInvertColorGPU(invert: boolean): void {
    const defaultActor = this.getDefaultActor();
 
    Iif (!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, options: SetVOIOptions = {}): void {
    const { suppressEvents = false } = options;
    // TODO: Account for VOILUTFunction
    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,
        voiLUTFunction: image.voiLUTFunction,
      };
 
      const { lower, upper } = windowLevelUtil.toLowHighRange(
        wwToUse,
        wcToUse,
        image.voiLUTFunction
      );
      voiRange = { lower, upper };
    } else {
      const { lower, upper } = voiRange;
      const { windowCenter, windowWidth } = windowLevelUtil.toWindowLevel(
        lower,
        upper
      );
 
      if (!viewport.voi) {
        viewport.voi = {
          windowWidth: 0,
          windowCenter: 0,
          voiLUTFunction: image.voiLUTFunction,
        };
      }
 
      viewport.voi.windowWidth = windowWidth;
      viewport.voi.windowCenter = windowCenter;
    }
 
    this.voiRange = voiRange;
    const eventDetail: VoiModifiedEventDetail = {
      viewportId: this.id,
      range: voiRange,
    };
 
    if (!suppressEvents) {
      triggerEvent(this.element, Events.VOI_MODIFIED, eventDetail);
    }
  }
 
  private getTransferFunction() {
    const defaultActor = this.getDefaultActor();
 
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const imageActor = defaultActor.actor as ImageActor;
 
    return imageActor.getProperty().getRGBTransferFunction(0);
  }
 
  private setVOIGPU(voiRange: VOIRange, options: SetVOIOptions = {}): void {
    const {
      suppressEvents = false,
      forceRecreateLUTFunction = false,
      voiUpdatedWithSetProperties = false,
    } = options;
 
    if (
      voiRange &&
      this.voiRange &&
      this.voiRange.lower === voiRange.lower &&
      this.voiRange.upper === voiRange.upper &&
      !forceRecreateLUTFunction &&
      !this.stackInvalidated
    ) {
      return;
    }
 
    const defaultActor = this.getDefaultActor();
    Iif (!defaultActor) {
      return;
    }
 
    Iif (!isImageActor(defaultActor)) {
      return;
    }
    const imageActor = defaultActor.actor as ImageActor;
 
    let voiRangeToUse = voiRange;
 
    Iif (typeof voiRangeToUse === 'undefined') {
      const imageData = imageActor.getMapper().getInputData();
      const range = imageData.getPointData().getScalars().getRange();
      const maxVoiRange = { lower: range[0], upper: range[1] };
      voiRangeToUse = maxVoiRange;
    }
 
    // scaling logic here
    // https://github.com/Kitware/vtk-js/blob/master/Sources/Rendering/OpenGL/ImageMapper/index.js#L540-L549
    imageActor.getProperty().setUseLookupTableScalarRange(true);
 
    let transferFunction = imageActor.getProperty().getRGBTransferFunction(0);
 
    const isSigmoidTFun =
      this.VOILUTFunction === VOILUTFunctionType.SAMPLED_SIGMOID;
 
    // use the old cfun if it exists for linear case
    if (isSigmoidTFun || !transferFunction || forceRecreateLUTFunction) {
      const transferFunctionCreator = isSigmoidTFun
        ? createSigmoidRGBTransferFunction
        : createLinearRGBTransferFunction;
 
      transferFunction = transferFunctionCreator(
        voiRangeToUse
      ) as vtkColorTransferFunction;
 
      Iif (this.invert) {
        invertRgbTransferFunction(transferFunction);
      }
 
      imageActor.getProperty().setRGBTransferFunction(0, transferFunction);
      this.initialTransferFunctionNodes =
        getTransferFunctionNodes(transferFunction);
    }
 
    Eif (!isSigmoidTFun) {
      // @ts-ignore vtk type error
      transferFunction.setRange(voiRangeToUse.lower, voiRangeToUse.upper);
    }
 
    this.voiRange = voiRangeToUse;
 
    // if voiRange is set by setProperties we need to lock it if it is not locked already
    if (!this.voiUpdatedWithSetProperties) {
      this.voiUpdatedWithSetProperties = voiUpdatedWithSetProperties;
    }
 
    Iif (suppressEvents) {
      return;
    }
 
    const eventDetail: VoiModifiedEventDetail = {
      viewportId: this.id,
      range: voiRangeToUse,
      VOILUTFunction: this.VOILUTFunction,
    };
 
    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) {
    Iif (this.scaling.PT) {
      return;
    }
 
    // if don't exist
    // These ratios are constant across all frames, so only need one.
    const { suvbw, suvlbm, suvbsa } = imageIdScalingFactor;
 
    const ptScaling = {} as PTScaling;
 
    Eif (suvlbm) {
      ptScaling.suvbwToSuvlbm = suvlbm / suvbw;
    }
 
    Eif (suvbsa) {
      ptScaling.suvbwToSuvbsa = suvbsa / suvbw;
    }
 
    this.scaling.PT = ptScaling;
  }
 
  /**
   * 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.
   */
  public 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 imageId = image.imageId;
    const props = getImageDataMetadataUtil(image);
 
    const {
      numberOfComponents,
      origin,
      direction,
      dimensions,
      spacing,
      numVoxels,
      imagePixelModule,
      voiLUTFunction,
      modality,
      scalingFactor,
      calibration,
    } = props;
 
    if (modality === 'PT' && scalingFactor) {
      this._addScalingToViewport(scalingFactor);
    }
 
    this.modality = modality;
    const voiLUTFunctionEnum = this._getValidVOILUTFunction(voiLUTFunction);
    this.VOILUTFunction = voiLUTFunctionEnum;
 
    this.calibration = calibration;
    let imagePlaneModule = this._getImagePlaneModule(imageId);
 
    Eif (!this.useCPURendering) {
      imagePlaneModule = this.calibrateIfNecessary(imageId, imagePlaneModule);
    }
 
    return {
      bitsAllocated: imagePixelModule.bitsAllocated,
      numberOfComponents,
      origin,
      direction,
      dimensions,
      spacing,
      numVoxels,
      imagePlaneModule,
      imagePixelModule,
    };
  }
 
  /**
   * Matches images for overlay by comparing their orientation, position, and dimensions.
   * @param currentImageId - The ID of the current image.
   * @param targetOverlayImageId - The ID of the target overlay image.
   * @returns The ID of the matched image, or undefined if no match is found.
   */
  private matchImagesForOverlay(
    currentImageId: string,
    targetOverlayImageId: string
  ): string | undefined {
    const matchImagesForOverlay = (targetImageId: string) => {
      // Retrieve image plane metadata for both overlay and current images
      const overlayImagePlaneModule = metaData.get(
        MetadataModules.IMAGE_PLANE,
        targetOverlayImageId
      );
      const currentImagePlaneModule = metaData.get(
        MetadataModules.IMAGE_PLANE,
        targetImageId
      );
 
      const overlayOrientation =
        overlayImagePlaneModule.imageOrientationPatient;
      const currentOrientation =
        currentImagePlaneModule.imageOrientationPatient;
 
      if (overlayOrientation && currentOrientation) {
        // Compare image orientations
        const closeEnough = isEqual(
          overlayImagePlaneModule.imageOrientationPatient,
          currentImagePlaneModule.imageOrientationPatient
        );
 
        Eif (closeEnough) {
          // Compare image positions
          const referencePosition =
            overlayImagePlaneModule.imagePositionPatient;
          const currentPosition = currentImagePlaneModule.imagePositionPatient;
 
          Eif (referencePosition && currentPosition) {
            const closeEnough = isEqual(referencePosition, currentPosition);
 
            if (closeEnough) {
              // Compare image dimensions
              const referenceRows = overlayImagePlaneModule.rows;
              const referenceColumns = overlayImagePlaneModule.columns;
              const currentRows = currentImagePlaneModule.rows;
              const currentColumns = currentImagePlaneModule.columns;
 
              Eif (
                referenceRows === currentRows &&
                referenceColumns === currentColumns
              ) {
                return targetImageId;
              }
            }
          }
        }
      } else E{
        // If orientation information is not available, compare dimensions only
        const referenceRows = overlayImagePlaneModule.rows;
        const referenceColumns = overlayImagePlaneModule.columns;
        const currentRows = currentImagePlaneModule.rows;
        const currentColumns = currentImagePlaneModule.columns;
 
        if (
          referenceRows === currentRows &&
          referenceColumns === currentColumns
        ) {
          return targetImageId;
        }
      }
    };
 
    return matchImagesForOverlay(currentImageId);
  }
 
  /**
   * Gets the view reference data for a given image slice.  This uses the
   * image plane module to read a default focal point/normal, and also returns
   * the referenced image id and the frame of reference uid.
   */
  public getImagePlaneReferenceData(
    sliceIndex = this.getCurrentImageIdIndex()
  ): ViewReference {
    const imageId = this.imageIds[sliceIndex];
    if (!imageId) {
      return;
    }
    const imagePlaneModule = metaData.get(MetadataModules.IMAGE_PLANE, imageId);
    if (!imagePlaneModule) {
      return;
    }
    const { imagePositionPatient, frameOfReferenceUID: FrameOfReferenceUID } =
      imagePlaneModule;
    let { rowCosines, columnCosines } = imagePlaneModule;
    // Values are null, not undefined, so need to assign instead of defaulting
    rowCosines ||= [1, 0, 0];
    columnCosines ||= [0, 1, 0];
    const viewPlaneNormal = vec3.cross(
      [0, 0, 0],
      columnCosines,
      rowCosines
    ) as Point3;
    return {
      FrameOfReferenceUID,
      viewPlaneNormal,
      cameraFocalPoint: imagePositionPatient as Point3,
      referencedImageId: imageId,
      sliceIndex,
    };
  }
 
  /**
   * 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]],
    };
  }
 
  createVTKImageData({
    origin,
    direction,
    dimensions,
    spacing,
    numberOfComponents,
    pixelArray,
  }) {
    const values = new pixelArray.constructor(pixelArray.length);
 
    // Todo: I guess nothing should be done for use16bit?
    const scalarArray = vtkDataArray.newInstance({
      name: 'Pixels',
      numberOfComponents: numberOfComponents,
      values: values,
    });
 
    const imageData = vtkImageData.newInstance();
 
    imageData.setDimensions(dimensions);
    imageData.setSpacing(spacing);
    imageData.setDirection(direction);
    imageData.setOrigin(origin);
    imageData.getPointData().setScalars(scalarArray);
 
    return imageData;
  }
  /**
   * Creates vtkImagedata based on the image object, it creates
   * 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,
    numberOfComponents,
    pixelArray,
  }): void {
    try {
      this._imageData = this.createVTKImageData({
        origin,
        direction,
        dimensions,
        spacing,
        numberOfComponents,
        pixelArray,
      });
    } catch (e) {
      log.error(e);
    }
  }
 
  /**
   * 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: string[],
    currentImageIdIndex = 0
  ): Promise<string> {
    this._throwIfDestroyed();
 
    this.imageIds = imageIds;
 
    Iif (currentImageIdIndex > imageIds.length) {
      throw new Error(
        'Current image index is greater than the number of images in the stack'
      );
    }
 
    this.imageKeyToIndexMap.clear();
    imageIds.forEach((imageId, index) => {
      this.imageKeyToIndexMap.set(imageId, index);
      this.imageKeyToIndexMap.set(imageIdToURI(imageId), index);
    });
    this.currentImageIdIndex = currentImageIdIndex;
    this.targetImageIdIndex = currentImageIdIndex;
    const imageRetrieveConfiguration = metaData.get(
      imageRetrieveMetadataProvider.IMAGE_RETRIEVE_CONFIGURATION,
      imageIds[currentImageIdIndex],
      'stack'
    );
 
    this.imagesLoader = imageRetrieveConfiguration
      ? (imageRetrieveConfiguration.create || createProgressive)(
          imageRetrieveConfiguration
        )
      : this;
 
    // reset the stack
    this.stackInvalidated = true;
    this.flipVertical = false;
    this.flipHorizontal = false;
    this.voiRange = null;
    this.interpolationType = InterpolationType.LINEAR;
    this.invert = false;
    this.viewportStatus = ViewportStatus.LOADING;
 
    this.fillWithBackgroundColor();
 
    Iif (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(this.element, Events.VIEWPORT_NEW_IMAGE_SET, eventDetail);
 
    return imageId;
  }
 
  /**
   * Throws an error if you are using a destroyed instance of the stack viewport
   */
  private _throwIfDestroyed() {
    Iif (this.isDisabled) {
      throw new Error(
        'The stack viewport has been destroyed and is no longer usable. Renderings will not be performed. If you ' +
          'are using the same viewportId and have re-enabled the viewport, you need to grab the new viewport instance ' +
          'using renderingEngine.getViewport(viewportId), instead of using your lexical scoped reference to the viewport instance.'
      );
    }
  }
 
  /**
   * 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);
    const dataType = imageData.getPointData().getScalars().getDataType();
 
    // using epsilon comparison for float numbers comparison.
    const isSameXSpacing = isEqual(xSpacing, image.columnPixelSpacing);
    const isSameYSpacing = isEqual(ySpacing, image.rowPixelSpacing);
 
    // using spacing, size, and direction only for now
    const isXSpacingValid =
      isSameXSpacing || (image.columnPixelSpacing === null && xSpacing === 1.0);
    const isYSpacingValid =
      isSameYSpacing || (image.rowPixelSpacing === null && ySpacing === 1.0);
    const isXVoxelsMatching = xVoxels === image.columns;
    const isYVoxelsMatching = yVoxels === image.rows;
    const isRowCosinesMatching = isEqual(
      imagePlaneModule.rowCosines,
      rowCosines as Point3
    );
    const isColumnCosinesMatching = isEqual(
      imagePlaneModule.columnCosines,
      columnCosines as Point3
    );
    const isDataTypeMatching =
      dataType === image.voxelManager.getScalarData().constructor.name;
 
    const result =
      isXSpacingValid &&
      isYSpacingValid &&
      isXVoxelsMatching &&
      isYVoxelsMatching &&
      isRowCosinesMatching &&
      isColumnCosinesMatching &&
      isDataTypeMatching;
 
    return result;
  }
 
  /**
   * 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);
 
    // change actor referencedId to image.imageId
    const actor = this.getActor(this.id);
    if (actor) {
      actor.referencedId = image.imageId;
    }
 
    // Update the pixel data in the vtkImageData object with the pixelData
    // from the loaded Cornerstone image
    updateVTKImageDataWithCornerstoneImage(this._imageData, image);
  }
 
  /**
   * 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 _loadAndDisplayImage(
    imageId: string,
    imageIdIndex: number
  ): Promise<string> {
    return this.useCPURendering
      ? this._loadAndDisplayImageCPU(imageId, imageIdIndex)
      : this._loadAndDisplayImageGPU(imageId, imageIdIndex);
  }
 
  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.
        if (this.currentImageIdIndex !== imageIdIndex) {
          return;
        }
 
        const pixelData = image.voxelManager.getScalarData();
 
        // handle the case where the pixelData is a Float32Array
        // CPU path cannot handle it, it should be converted to Uint16Array
        // and via the Modality LUT we can display it properly
        const preScale = image.preScale;
        const scalingParams = preScale?.scalingParameters;
 
        const scaledWithNonIntegers =
          (preScale?.scaled && scalingParams?.rescaleIntercept % 1 !== 0) ||
          scalingParams?.rescaleSlope % 1 !== 0;
 
        if (pixelData instanceof Float32Array && scaledWithNonIntegers) {
          const floatMinMax = {
            min: image.minPixelValue,
            max: image.maxPixelValue,
          };
          const floatRange = Math.abs(floatMinMax.max - floatMinMax.min);
          const intRange = 65535;
          const slope = floatRange / intRange;
          const intercept = floatMinMax.min;
          const numPixels = pixelData.length;
          const intPixelData = new Uint16Array(numPixels);
 
          let min = 65535;
 
          let max = 0;
 
          for (let i = 0; i < numPixels; i++) {
            const rescaledPixel = Math.floor(
              (pixelData[i] - intercept) / slope
            );
 
            intPixelData[i] = rescaledPixel;
            min = Math.min(min, rescaledPixel);
            max = Math.max(max, rescaledPixel);
          }
 
          // reset the properties since basically the image has changed
          image.minPixelValue = min;
          image.maxPixelValue = max;
          image.slope = slope;
          image.intercept = intercept;
          // voxelManager, when present, overrides getPixelData()
          if (image.voxelManager) {
            image.voxelManager.getScalarData = () => intPixelData;
          } else {
            image.getPixelData = () => intPixelData;
          }
 
          image.preScale = {
            ...image.preScale,
            scaled: false,
          };
        }
 
        this._setCSImage(image);
        this.viewportStatus = ViewportStatus.PRE_RENDER;
 
        const eventDetail: EventTypes.StackNewImageEventDetail = {
          image,
          imageId,
          imageIdIndex,
          viewportId: this.id,
          renderingEngineId: this.renderingEngineId,
        };
 
        triggerEvent(this.element, Events.STACK_NEW_IMAGE, eventDetail);
 
        this._updateToDisplayImageCPU(image);
 
        // 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);
          }
        );
      }
 
      const priority = -5;
      const requestType = RequestType.Interaction;
      const additionalDetails = { imageId, imageIdIndex };
      const options = {
        useRGBA: true,
        requestType,
      };
 
      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
      );
    });
  }
 
  public successCallback(imageId, image) {
    const imageIdIndex = this.imageIds.indexOf(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.
    if (this.currentImageIdIndex !== imageIdIndex) {
      return;
    }
 
    // If Photometric Interpretation is not the same for the next image we are trying to load
    // invalidate the stack to recreate the VTK imageData.  Get the PMI from
    // the base csImage if imageFrame isn't defined, which happens when the images
    // come from the volume
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const csImgFrame = (this.csImage as any)?.imageFrame;
    const imgFrame = image?.imageFrame;
    const photometricInterpretation =
      csImgFrame?.photometricInterpretation ||
      this.csImage?.photometricInterpretation;
    const newPhotometricInterpretation =
      imgFrame?.photometricInterpretation || image?.photometricInterpretation;
 
    if (photometricInterpretation !== newPhotometricInterpretation) {
      this.stackInvalidated = true;
    }
 
    this._setCSImage(image);
 
    const eventDetail: EventTypes.StackNewImageEventDetail = {
      image,
      imageId,
      imageIdIndex,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
 
    this._updateActorToDisplayImageId(image);
    triggerEvent(this.element, Events.STACK_NEW_IMAGE, eventDetail);
 
    // 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;
  }
 
  public errorCallback(imageId, permanent, error) {
    if (!permanent) {
      return;
    }
    const imageIdIndex = this.imageIds.indexOf(imageId);
    const eventDetail = {
      error,
      imageIdIndex,
      imageId,
    };
 
    triggerEvent(eventTarget, Events.IMAGE_LOAD_ERROR, eventDetail);
  }
 
  public getLoaderImageOptions(imageId: string) {
    const imageIdIndex = this.imageIds.indexOf(imageId);
    const { transferSyntaxUID } = metaData.get('transferSyntax', imageId) || {};
 
    const options = {
      useRGBA: false,
      transferSyntaxUID,
      priority: 5,
      requestType: RequestType.Interaction,
      additionalDetails: { imageId, imageIdIndex },
    };
    return options;
  }
 
  public async loadImages(
    imageIds: string[],
    listener: ImageLoadListener
  ): Promise<unknown> {
    const resultList = await Promise.allSettled(
      imageIds.map((imageId) => {
        const options = this.getLoaderImageOptions(
          imageId
        ) as ImageLoaderOptions;
 
        return loadAndCacheImage(imageId, options).then(
          (image) => {
            listener.successCallback(imageId, image);
            return imageId;
          },
          (error) => {
            listener.errorCallback(imageId, true, error);
            return imageId;
          }
        );
      })
    );
    const errorList = resultList.filter((item) => item.status === 'rejected');
    Iif (errorList && errorList.length) {
      const event = new CustomEvent(Events.IMAGE_LOAD_ERROR, {
        detail: errorList,
        cancelable: true,
      });
      eventTarget.dispatchEvent(event);
    }
    return resultList;
  }
 
  private _loadAndDisplayImageGPU(imageId: string, imageIdIndex: number) {
    Iif (!imageId) {
      console.warn('No image id set yet to load');
      return;
    }
    const eventDetail: EventTypes.PreStackNewImageEventDetail = {
      imageId,
      imageIdIndex,
      viewportId: this.id,
      renderingEngineId: this.renderingEngineId,
    };
    triggerEvent(this.element, Events.PRE_STACK_NEW_IMAGE, eventDetail);
 
    return this.imagesLoader.loadImages([imageId], this).then((v) => {
      return imageId;
    });
  }
 
  /**
   * Renders the given Cornerstone image object in the viewport.
   * This method is intended to be used by utilities to render
   * an individual image, rather than by applications that want to display
   * a complete image stack. If you want to load and display a complete
   * image stack, use the setStack method instead of this one.
   *
   * The rendered image will appear in the viewport's element.
   * Use this method if you have other means of loading and the
   * cornerstone image object is already available.
   *
   * If you don't understand the difference between this method and
   * setStack, you probably want to use setStack.
   *
   * @param image - The Cornerstone image object to render.
   */
  public renderImageObject = (image) => {
    this._setCSImage(image);
 
    const renderFn = this.useCPURendering
      ? this._updateToDisplayImageCPU
      : this._updateActorToDisplayImageId;
 
    renderFn.call(this, image);
  };
 
  private _setCSImage = (image) => {
    image.isPreScaled = image.preScale?.scaled;
    this.csImage = image;
  };
 
  private _updateToDisplayImageCPU(image: IImage) {
    const metadata = this.getImageDataMetadata(image);
 
    const viewport = getDefaultViewport(
      this.canvas,
      image,
      this.modality,
      this._cpuFallbackEnabledElement.viewport.colormap
    );
 
    const { windowCenter, windowWidth, voiLUTFunction } = viewport.voi;
    this.voiRange = windowLevelUtil.toLowHighRange(
      windowWidth,
      windowCenter,
      voiLUTFunction
    );
 
    this._cpuFallbackEnabledElement.image = image;
    this._cpuFallbackEnabledElement.metadata = {
      ...metadata,
    };
    this.cpuImagePixelData = image.voxelManager.getScalarData();
 
    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
    );
  }
 
  public getSliceViewInfo(): {
    width: number;
    height: number;
    sliceIndex: number;
    slicePlane: number;
    sliceToIndexMatrix: mat4;
    indexToSliceMatrix: mat4;
  } {
    throw new Error('Method not implemented.');
  }
 
  /**
   * This method is used to add images to the stack viewport.
   * It takes an array of stack inputs, each containing an imageId and an actor UID.
   * For each stack input, it retrieves the image from the cache and creates a VTK image data object.
   * It then creates an actor mapper for the image data and adds it to the list of actors.
   * Finally, it sets the actors for the stack viewport.
   *
   * @param  stackInputs - An array of stack inputs, each containing an image ID and an actor UID.
   */
  public addImages(stackInputs: IStackInput[]) {
    const actors = [];
    stackInputs.forEach((stackInput) => {
      const { imageId, ...rest } = stackInput;
      const image = cache.getImage(imageId);
 
      const { origin, dimensions, direction, spacing, numberOfComponents } =
        this.getImageDataMetadata(image);
 
      const imagedata = this.createVTKImageData({
        origin,
        dimensions,
        direction,
        spacing,
        numberOfComponents,
        pixelArray: image.voxelManager.getScalarData(),
      });
      const imageActor = this.createActorMapper(imagedata);
      Eif (imageActor) {
        actors.push({
          uid: stackInput.actorUID ?? uuidv4(),
          actor: imageActor,
          referencedId: imageId,
          ...rest,
        });
        if (stackInput.callback) {
          stackInput.callback({ imageActor, imageId: stackInput.imageId });
        }
      }
    });
    this.addActors(actors);
  }
 
  /**
   * 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();
    const viewPresentation = this.getViewPresentation();
 
    // Cache camera props so we can trigger one camera changed event after
    // The full transition.
    // const previousCameraProps = this.getCamera();
    if (sameImageData && !this.stackInvalidated) {
      // 3a. If we can reuse it, replace the scalar data under the hood
      this._updateVTKImageDataFromCornerstoneImage(image);
 
      this.resetCameraNoEvent();
      this.setViewPresentation(viewPresentation);
 
      // set the flip and view up back to the previous value since the restore camera props
      // rely on the correct flip value
      // this.setCameraNoEvent({
      //   flipHorizontal: previousCameraProps.flipHorizontal,
      //   flipVertical: previousCameraProps.flipVertical,
      //   viewUp: previousCameraProps.viewUp,
      // });
 
      // This is necessary to initialize the clipping range and it is not related
      // to our custom slabThickness.
      // Todo: i'm not sure if this is needed
      // @ts-ignore: vtkjs incorrect typing
      // activeCamera.setFreezeFocalPoint(true);
 
      this._setPropertiesFromCache();
      this.stackActorReInitialized = false;
 
      return;
    }
 
    const {
      origin,
      direction,
      dimensions,
      spacing,
      numberOfComponents,
      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
 
    const pixelArray = image.voxelManager.getScalarData();
    this._createVTKImageData({
      origin,
      direction,
      dimensions,
      spacing,
      numberOfComponents,
      pixelArray,
    });
 
    // 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 oldActors = this.getActors();
    if (oldActors.length && oldActors[0].uid === this.id) {
      oldActors[0].actor = actor;
    } else {
      oldActors.unshift({ uid: this.id, actor, referencedId: image.imageId });
    }
    this.setActors(oldActors);
 
    // 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);
 
    const previousCamera = this.getCamera();
    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();
 
    // set the view presentation back to the original one to restore the pan and zoom
    this.setViewPresentation(viewPresentation);
 
    this.triggerCameraEvent(this.getCamera(), previousCamera);
 
    // This is necessary to initialize the clipping range and it is not related
    // to our custom slabThickness.
    // @ts-ignore: vtkjs incorrect typing
    //Todo: i'm not sure if this is needed
    // activeCamera.setFreezeFocalPoint(true);
 
    const monochrome1 =
      imagePixelModule.photometricInterpretation === 'MONOCHROME1';
 
    // invalidate the stack so that we can set the voi range
    this.stackInvalidated = true;
 
    const voiRange = this._getInitialVOIRange(image);
    this.setVOI(voiRange, {
      forceRecreateLUTFunction: !!monochrome1,
    });
 
    this.initialInvert = !!monochrome1;
 
    // should carry over the invert color from the previous image if has been applied
    this.setInvertColor(this.invert || this.initialInvert);
 
    // Saving position of camera on render, to cache the panning
    this.stackInvalidated = false;
 
    this.stackActorReInitialized = true;
 
    if (this._publishCalibratedEvent) {
      this.triggerCalibrationEvent();
    }
  }
 
  private _getInitialVOIRange(image: IImage) {
    Iif (this.voiRange && this.voiUpdatedWithSetProperties) {
      return this.voiRange;
    }
    const { windowCenter, windowWidth, voiLUTFunction } = image;
 
    let voiRange = this._getVOIRangeFromWindowLevel(
      windowWidth,
      windowCenter,
      voiLUTFunction
    );
 
    // Get the range for the PT since if it is prescaled
    // we set a default range of 0-5
    voiRange = this._getPTPreScaledRange() || voiRange;
 
    return voiRange;
  }
 
  private _getPTPreScaledRange() {
    if (!this._isCurrentImagePTPrescaled()) {
      return undefined;
    }
 
    return this._getDefaultPTPrescaledVOIRange();
  }
 
  private _isCurrentImagePTPrescaled() {
    if (this.modality !== 'PT' || !this.csImage.isPreScaled) {
      return false;
    }
 
    Iif (!this.csImage.preScale?.scalingParameters.suvbw) {
      return false;
    }
 
    return true;
  }
 
  private _getDefaultPTPrescaledVOIRange() {
    return { lower: 0, upper: 5 };
  }
 
  private _getVOIRangeFromWindowLevel(
    windowWidth: number | number[],
    windowCenter: number | number[],
    voiLUTFunction: VOILUTFunctionType = VOILUTFunctionType.LINEAR
  ): { lower: number; upper: number } | undefined {
    let center, width;
 
    if (typeof windowCenter === 'number' && typeof windowWidth === 'number') {
      center = windowCenter;
      width = windowWidth;
    } else Eif (Array.isArray(windowCenter) && Array.isArray(windowWidth)) {
      center = windowCenter[0];
      width = windowWidth[0];
    }
 
    // If center and width are defined, convert them to low-high range
    Eif (center !== undefined && width !== undefined) {
      return windowLevelUtil.toLowHighRange(width, center, voiLUTFunction);
    }
  }
 
  /**
   * Loads the image based on the provided imageIdIndex
   * @param imageIdIndex - number represents imageId index
   */
  private async _setImageIdIndex(imageIdIndex: number): Promise<string> {
    Iif (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;
    this.viewportStatus = ViewportStatus.PRE_RENDER;
 
    // 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
    );
 
    //Check if there is any existing specific options for images if not we don't
    //want to re-render the viewport to its default properties
    if (this.perImageIdDefaultProperties.size >= 1) {
      const defaultProperties = this.perImageIdDefaultProperties.get(imageId);
      if (defaultProperties !== undefined) {
        this.setProperties(defaultProperties);
      } else Eif (this.globalDefaultProperties !== undefined) {
        this.setProperties(this.globalDefaultProperties);
      }
    }
 
    return imageId;
  }
 
  private resetCameraCPU({
    resetPan = true,
    resetZoom = true,
  }: {
    resetPan?: boolean;
    resetZoom?: boolean;
  }) {
    const { image } = this._cpuFallbackEnabledElement;
 
    if (!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 the rotation and flip must be reset together.
    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;
 
    Iif (isNaN(this.targetImageIdIndex)) {
      // Scrolling before things are ready to display or on empty viewport
      return;
    }
    const currentTargetImageIdIndex = this.targetImageIdIndex;
    const numberOfFrames = imageIds.length;
 
    let newTargetImageIdIndex = currentTargetImageIdIndex + delta;
 
    Iif (loop) {
      newTargetImageIdIndex =
        (newTargetImageIdIndex + numberOfFrames) % numberOfFrames;
    } else {
      newTargetImageIdIndex = Math.max(
        0,
        Math.min(numberOfFrames - 1, newTargetImageIdIndex)
      );
    }
 
    this.targetImageIdIndex = newTargetImageIdIndex;
 
    const targetImageId = imageIds[newTargetImageIdIndex];
 
    const imageAlreadyLoaded = cache.isLoaded(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).
    if (imageAlreadyLoaded || !debounce) {
      this.setImageIdIndex(newTargetImageIdIndex);
    } else E{
      clearTimeout(this.debouncedTimeout);
      this.debouncedTimeout = window.setTimeout(() => {
        this.setImageIdIndex(newTargetImageIdIndex);
      }, 40);
    }
 
    const eventData: StackViewportScrollEventDetail = {
      newImageIdIndex: newTargetImageIdIndex,
      imageId: targetImageId,
      direction: delta,
    };
 
    if (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
   */
  public setImageIdIndex(imageIdIndex: number): Promise<string> {
    this._throwIfDestroyed();
 
    // If we are already on this imageId index, stop here
    if (this.currentImageIdIndex === imageIdIndex) {
      return Promise.resolve(this.getCurrentImageId());
    }
 
    // Otherwise, get the imageId and attempt to display it
    const imageIdPromise = this._setImageIdIndex(imageIdIndex);
    this.targetImageIdIndex = imageIdIndex;
 
    return imageIdPromise;
  }
 
  /**
   * 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);
  }
 
  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;
  }
 
  public jumpToWorld(worldPos: Point3): boolean {
    const imageIds = this.getImageIds();
    const imageData = this.getImageData();
    const { direction, spacing } = imageData;
 
    const imageId = getClosestImageId(
      { direction, spacing, imageIds },
      worldPos,
      this.getCamera().viewPlaneNormal,
      { ignoreSpacing: true }
    );
 
    const index = imageIds.indexOf(imageId);
 
    if (index === -1) {
      return false;
    }
 
    this.setImageIdIndex(index);
    this.render();
 
    return true;
  }
 
  private canvasToWorldCPU = (
    canvasPos: Point2,
    worldPos: Point3 = [0, 0, 0]
  ): Point3 => {
    if (!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();
 
    // 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;
  };
 
  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 indexPoint: Point2 = [
      vec3.dot(diff, iVector) / spacing[0],
      vec3.dot(diff, jVector) / spacing[1],
    ];
 
    // pixel to canvas
    const canvasPoint = pixelToCanvas(
      this._cpuFallbackEnabledElement,
      indexPoint
    );
    return canvasPoint;
  };
 
  private canvasToWorldGPUContextPool = (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 devicePixelRatio = window.devicePixelRatio || 1;
    const { width, height } = this.canvas;
    const aspectRatio = width / height;
 
    // Convert canvas coordinates to normalized display coordinates
    const canvasPosWithDPR = [
      canvasPos[0] * devicePixelRatio,
      canvasPos[1] * devicePixelRatio,
    ];
 
    // Normalize to [0,1] range
    const normalizedDisplay = [
      canvasPosWithDPR[0] / width,
      1 - canvasPosWithDPR[1] / height, // Flip Y axis
      0,
    ];
 
    // Transform from normalized display to world coordinates
    const projCoords = renderer.normalizedDisplayToProjection(
      normalizedDisplay[0],
      normalizedDisplay[1],
      normalizedDisplay[2]
    );
    const viewCoords = renderer.projectionToView(
      projCoords[0],
      projCoords[1],
      projCoords[2],
      aspectRatio
    );
    const worldCoord = renderer.viewToWorld(
      viewCoords[0],
      viewCoords[1],
      viewCoords[2]
    );
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    return [worldCoord[0], worldCoord[1], worldCoord[2]];
  };
 
  private canvasToWorldGPUTiled = (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 worldToCanvasGPUContextPool = (worldPos: Point3): Point2 => {
    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 devicePixelRatio = window.devicePixelRatio || 1;
 
    const { width, height } = this.canvas;
 
    const aspectRatio = width / height;
 
    const viewCoords = renderer.worldToView(
      worldPos[0],
      worldPos[1],
      worldPos[2]
    );
 
    const projCoords = renderer.viewToProjection(
      viewCoords[0],
      viewCoords[1],
      viewCoords[2],
      aspectRatio
    );
 
    const normalizedDisplay = renderer.projectionToNormalizedDisplay(
      projCoords[0],
      projCoords[1],
      projCoords[2]
    );
 
    const canvasX = normalizedDisplay[0] * width;
    const canvasY = (1 - normalizedDisplay[1]) * height;
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    const canvasCoordWithDPR = [
      canvasX / devicePixelRatio,
      canvasY / devicePixelRatio,
    ] as Point2;
 
    return canvasCoordWithDPR;
  };
 
  private worldToCanvasGPUTiled = (worldPos: Point3): Point2 => {
    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 = [
      displayCoord[0] - this.sx,
      displayCoord[1] - this.sy,
    ] as Point2;
 
    // set clipping range back to original to be able
    vtkCamera.setClippingRange(crange[0], crange[1]);
 
    const devicePixelRatio = window.devicePixelRatio || 1;
    const canvasCoordWithDPR = [
      canvasCoord[0] / devicePixelRatio,
      canvasCoord[1] / devicePixelRatio,
    ] as Point2;
 
    return canvasCoordWithDPR;
  };
 
  /**
   * Get the renderer for this viewport - handles ContextPoolRenderingEngine
   */
  public getRendererContextPool(): vtkRenderer {
    const renderingEngine = this.getRenderingEngine();
    return renderingEngine.getRenderer(this.id);
  }
 
  /**
   * Returns the `vtkRenderer` responsible for rendering the `Viewport`.
   *
   * @returns The `vtkRenderer` for the `Viewport`.
   */
  public getRendererTiled(): vtkRenderer {
    const renderingEngine = this.getRenderingEngine();
 
    if (!renderingEngine || renderingEngine.hasBeenDestroyed) {
      throw new Error('Rendering engine has been destroyed');
    }
 
    return renderingEngine.offscreenMultiRenderWindow?.getRenderer(this.id);
  }
 
  private _getVOIRangeForCurrentImage() {
    const { windowCenter, windowWidth, voiLUTFunction } = this.csImage;
 
    return this._getVOIRangeFromWindowLevel(
      windowWidth,
      windowCenter,
      voiLUTFunction
    );
  }
 
  private _getValidVOILUTFunction(
    voiLUTFunction: VOILUTFunctionType | unknown
  ): VOILUTFunctionType {
    Iif (
      !Object.values(VOILUTFunctionType).includes(
        voiLUTFunction as VOILUTFunctionType
      )
    ) {
      return VOILUTFunctionType.LINEAR;
    }
    return voiLUTFunction as VOILUTFunctionType;
  }
 
  /**
   * Returns the index of the imageId being renderer
   *
   * @returns currently shown imageId index
   */
  public getCurrentImageIdIndex = (): number => {
    return this.currentImageIdIndex;
  };
 
  /**
   * returns the slice index of the view
   * @returns slice index
   */
  public getSliceIndex = (): number => {
    return this.currentImageIdIndex;
  };
 
  /**
   * Returns information about the current slice view.
   * @returns An object containing the slice index and slice axis.
   * @throws Error if the view is oblique.
   */
  public getSliceInfo(): {
    sliceIndex: number;
    slicePlane: number;
    width: number;
    height: number;
  } {
    const sliceIndex = this.getSliceIndex();
    const { dimensions } = this.getImageData();
    return {
      width: dimensions[0],
      height: dimensions[1],
      sliceIndex,
      slicePlane: 2,
    };
  }
 
  /**
   * Determines if a given ViewReference is viewable in this StackViewport.
   *
   * @param viewRef - The ViewReference to check.
   * @param options - Additional options for compatibility checking.
   * @returns True if the ViewReference is viewable, false otherwise.
   */
  public isReferenceViewable(
    viewRef: ViewReference,
    options: ReferenceCompatibleOptions = {}
  ): boolean {
    const testIndex = this.getCurrentImageIdIndex();
    const currentImageId = this.imageIds[testIndex];
    Iif (!currentImageId || !viewRef) {
      return false;
    }
    const { referencedImageId, multiSliceReference } = viewRef;
 
    // Optimize the return for the exact match cases
    Eif (referencedImageId) {
      if (referencedImageId === currentImageId) {
        return true;
      }
      viewRef.referencedImageURI ||= imageIdToURI(referencedImageId);
      const { referencedImageURI: referencedImageURI } = viewRef;
      const foundSliceIndex = this.imageKeyToIndexMap.get(referencedImageURI);
      Eif (options.asOverlay) {
        const matchedImageId = this.matchImagesForOverlay(
          currentImageId,
          referencedImageId
        );
        if (matchedImageId) {
          return true;
        }
      }
      Eif (foundSliceIndex === undefined) {
        return false;
      }
      if (options.withNavigation) {
        return true;
      }
      const rangeEndSliceIndex =
        multiSliceReference &&
        this.imageKeyToIndexMap.get(multiSliceReference.referencedImageId);
      return testIndex <= rangeEndSliceIndex && testIndex >= foundSliceIndex;
    }
 
    // Apply asVolume to withOrientation to indicate allowing changing orientation
    // only if this gets converted to a volume.
    if (
      !super.isReferenceViewable(viewRef, {
        ...options,
        withOrientation: options?.asVolume,
      })
    ) {
      return false;
    }
 
    if (viewRef.volumeId || viewRef.FrameOfReferenceUID) {
      return options.asVolume;
    }
 
    // if camera focal point is provided, we can use that as a point
    // Todo: handle the case where the nearby project is not desired
    const { cameraFocalPoint } = viewRef;
 
    if (options.asNearbyProjection && cameraFocalPoint) {
      const { spacing, direction, origin } = this.getImageData();
 
      const viewPlaneNormal = direction.slice(6, 9) as Point3;
 
      const sliceThickness = getSpacingInNormalDirection(
        { direction, spacing },
        viewPlaneNormal
      );
 
      // Project the cameraFocalPoint onto the image plane
      const diff = vec3.subtract(vec3.create(), cameraFocalPoint, origin);
      const distanceToPlane = vec3.dot(diff, viewPlaneNormal);
 
      // Define a threshold (e.g., half the slice thickness)
      const threshold = sliceThickness / 2;
 
      if (Math.abs(distanceToPlane) <= threshold) {
        return true;
      }
    }
 
    return false;
  }
 
  /**
   * Gets a standard target to show this image instance.
   * Returns undefined if the requested slice index is not available.
   *
   * If using sliceIndex for requesting a specific reference, the slice index MUST come
   * from the stack of image ids.  Using slice index from a volume or from a different
   * stack of images ids, EVEN if they contain the same set of images will result in
   * random images being chosen.
   */
  public getViewReference(
    viewRefSpecifier: ViewReferenceSpecifier = {}
  ): ViewReference {
    const { sliceIndex = this.getCurrentImageIdIndex() } = viewRefSpecifier;
    const reference = super.getViewReference(viewRefSpecifier);
    const referencedImageId = this.getCurrentImageId(sliceIndex);
    Iif (!referencedImageId) {
      return;
    }
    reference.referencedImageId = referencedImageId;
    Iif (this.getCurrentImageIdIndex() !== sliceIndex) {
      const referenceData = this.getImagePlaneReferenceData(
        sliceIndex as number
      );
      if (!referenceData) {
        return;
      }
      Object.assign(reference, referenceData);
    }
    return reference;
  }
 
  /**
   * Applies the view reference, which may navigate the slice index and apply
   * other camera modifications.
   * Assumes that the slice index is correct for this viewport
   */
  public setViewReference(viewRef: ViewReference): void {
    Iif (!viewRef?.referencedImageId) {
      if (viewRef?.sliceIndex !== undefined) {
        this.scroll(viewRef.sliceIndex - this.targetImageIdIndex);
      }
      return;
    }
    const { referencedImageId } = viewRef;
    viewRef.referencedImageURI ||= imageIdToURI(referencedImageId);
    const { referencedImageURI: referencedImageURI } = viewRef;
    const sliceIndex = this.imageKeyToIndexMap.get(referencedImageURI);
    Iif (sliceIndex === undefined) {
      log.error(`No image URI found for ${referencedImageURI}`);
      return;
    }
 
    this.scroll(sliceIndex - this.targetImageIdIndex);
  }
 
  /**
   * Returns the imageId string for the specified view, using the
   * `imageId:<imageId>` URN format.
   */
  public getViewReferenceId(specifier: ViewReferenceSpecifier = {}): string {
    const { sliceIndex = this.currentImageIdIndex } = specifier;
    return `imageId:${this.imageIds[sliceIndex]}`;
  }
 
  /**
   *
   * 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;
  };
 
  public getSliceIndexForImage(reference: string | ViewReference) {
    if (!reference) {
      return;
    }
    if (typeof reference === 'string') {
      return this.imageKeyToIndexMap.get(reference);
    }
    if (reference.referencedImageId) {
      return this.imageKeyToIndexMap.get(reference.referencedImageId);
    }
    return;
  }
 
  /**
   * Returns the list of image Ids for the current viewport
   * @returns list of strings for image Ids
   */
  public getImageIds = (): string[] => {
    return this.imageIds;
  };
 
  /**
   * Returns the currently rendered imageId
   * @returns string for imageId
   */
  public getCurrentImageId = (
    index = this.getCurrentImageIdIndex()
  ): string => {
    return this.imageIds[index];
  };
 
  /**
   * 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.imageKeyToIndexMap.has(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 => {
    return this.imageKeyToIndexMap.has(imageURI);
  };
 
  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 = () => {
    if (!this.useCPURendering) {
      throw new Error(
        'Custom cpu rendering pipeline should only be hit in CPU rendering mode'
      );
    }
 
    if (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,
      viewportStatus: this.viewportStatus,
    };
  };
 
  private unsetColormapCPU() {
    delete this._cpuFallbackEnabledElement.viewport.colormap;
    this._cpuFallbackEnabledElement.renderingTools = {};
 
    this.cpuRenderingInvalidated = true;
 
    this.fillWithBackgroundColor();
 
    this.render();
  }
 
  private setColormapCPU(colormapData: CPUFallbackColormapData) {
    this.colormap = colormapData;
    const colormap = colormapUtils.getColormap(colormapData.name);
 
    this._cpuFallbackEnabledElement.viewport.colormap = colormap;
    this._cpuFallbackEnabledElement.renderingTools = {};
 
    this.fillWithBackgroundColor();
    this.cpuRenderingInvalidated = true;
 
    this.render();
 
    const eventDetail = {
      viewportId: this.id,
      colormap: colormapData,
    };
    triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
  }
 
  private setColormapGPU(colormap: ColormapPublic) {
    const ActorEntry = this.getDefaultActor();
    const actor = ActorEntry.actor as ImageActor;
    const actorProp = actor.getProperty();
    const rgbTransferFunction = actorProp.getRGBTransferFunction();
 
    const colormapObj =
      colormapUtils.getColormap(colormap.name) ||
      vtkColorMaps.getPresetByName(colormap.name);
 
    Iif (!rgbTransferFunction) {
      const cfun = vtkColorTransferFunction.newInstance();
      cfun.applyColorMap(colormapObj);
      cfun.setMappingRange(this.voiRange.lower, this.voiRange.upper);
      actorProp.setRGBTransferFunction(0, cfun);
    } else {
      rgbTransferFunction.applyColorMap(colormapObj);
      rgbTransferFunction.setMappingRange(
        this.voiRange.lower,
        this.voiRange.upper
      );
      actorProp.setRGBTransferFunction(0, rgbTransferFunction);
    }
 
    this.colormap = colormap;
    this.render();
 
    const eventDetail = {
      viewportId: this.id,
      colormap,
    };
 
    triggerEvent(this.element, Events.COLORMAP_MODIFIED, eventDetail);
  }
 
  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 = getImagePlaneModule(imageId);
 
    this.hasPixelSpacing =
      !imagePlaneModule.usingDefaultValues ||
      this.calibration?.scale > 0 ||
      this.calibration?.rowPixelSpacing > 0;
 
    this.calibration ||= imagePlaneModule.calibration;
 
    return imagePlaneModule;
  }
 
  public isInAcquisitionPlane(): boolean {
    return true;
  }
 
  private renderingPipelineFunctions = {
    getImageData: {
      cpu: this.getImageDataCPU,
      gpu: this.getImageDataGPU,
    },
    setColormap: {
      cpu: this.setColormapCPU,
      gpu: this.setColormapGPU,
    },
    getCamera: {
      cpu: this.getCameraCPU,
      gpu: super.getCamera,
    },
    setCamera: {
      cpu: this.setCameraCPU,
      gpu: super.setCamera,
    },
    getPan: {
      cpu: this.getPanCPU,
      gpu: super.getPan,
    },
    setPan: {
      cpu: this.setPanCPU,
      gpu: super.setPan,
    },
    getZoom: {
      cpu: this.getZoomCPU,
      gpu: super.getZoom,
    },
    setZoom: {
      cpu: this.setZoomCPU,
      gpu: super.setZoom,
    },
    setVOI: {
      cpu: this.setVOICPU,
      gpu: this.setVOIGPU,
    },
    getRotation: {
      cpu: this.getRotationCPU,
      gpu: this.getRotationGPU,
    },
    setInterpolationType: {
      cpu: this.setInterpolationTypeCPU,
      gpu: this.setInterpolationTypeGPU,
    },
    setInvertColor: {
      cpu: this.setInvertColorCPU,
      gpu: this.setInvertColorGPU,
    },
    resetCamera: {
      cpu: (
        options: { resetPan?: boolean; resetZoom?: boolean } = {}
      ): boolean => {
        const { resetPan = true, resetZoom = true } = options;
        this.resetCameraCPU({ resetPan, resetZoom });
        return true;
      },
      gpu: (
        options: { resetPan?: boolean; resetZoom?: boolean } = {}
      ): boolean => {
        const { resetPan = true, resetZoom = true } = options;
        this.resetCameraGPU({ resetPan, resetZoom });
        return true;
      },
    },
    canvasToWorld: {
      cpu: this.canvasToWorldCPU,
      gpu: {
        tiled: this.canvasToWorldGPUTiled,
        contextPool: this.canvasToWorldGPUContextPool,
      },
    },
    worldToCanvas: {
      cpu: this.worldToCanvasCPU,
      gpu: {
        tiled: this.worldToCanvasGPUTiled,
        contextPool: this.worldToCanvasGPUContextPool,
      },
    },
    getRenderer: {
      cpu: () => this.getCPUFallbackError('getRenderer'),
      gpu: {
        tiled: this.getRendererTiled,
        contextPool: this.getRendererContextPool,
      },
    },
    getDefaultActor: {
      cpu: () => this.getCPUFallbackError('getDefaultActor'),
      gpu: super.getDefaultActor,
    },
    getActors: {
      cpu: () => this.getCPUFallbackError('getActors'),
      gpu: super.getActors,
    },
    getActor: {
      cpu: () => this.getCPUFallbackError('getActor'),
      gpu: super.getActor,
    },
    setActors: {
      cpu: () => this.getCPUFallbackError('setActors'),
      gpu: super.setActors,
    },
    addActors: {
      cpu: () => this.getCPUFallbackError('addActors'),
      gpu: super.addActors,
    },
    addActor: {
      cpu: () => this.getCPUFallbackError('addActor'),
      gpu: super.addActor,
    },
    removeAllActors: {
      cpu: () => this.getCPUFallbackError('removeAllActors'),
      gpu: super.removeAllActors,
    },
    unsetColormap: {
      cpu: this.unsetColormapCPU,
      gpu: this.unsetColormapGPU,
    },
  };
}
 
export default StackViewport;