All files / Sources/Common/Core/Math index.js

77.23% Statements 916/1186
66.03% Branches 245/371
67.28% Functions 72/107
77.94% Lines 873/1120

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                  1x               1x 1x     5x           451x 1353x 1353x 1353x             6166x 94502x 94502x 94502x                   5310x 5310x 168638x   5310x     1x     128946x             1x                                                                             1x 1x     8x 8x 54x   8x                                                                                     2x 2x       2x       77009x 77009x     1x       832x 832x 832x 832x       7906x 7906x 7906x 7906x       197x 197x 197x 197x                   321x 321x 321x 321x                   7312x       2x 2x 2x 2x 2x 2x 2x 2x 2x       3178x 3178x 3178x 3178x 3178x 3178x 3178x       6866x   386x       6480x                       1312x 1312x 1307x 1307x 1307x   1312x       7x 7x 7x 7x             7x 4x 4x 4x 3x 3x 3x 3x             7x 7x 7x 7x   7x                               7x 7x 7x 7x     7x 7x 7x 7x                                                                                                 635x               7x 7x 7x       80x 80x 80x 80x                                 2x 2x 2x 2x                                                                         2x 6x 6x 6x   2x                         1158x 49x   1109x 1109x                 100x     100x 300x 300x     300x     300x           100x 100x 100x 100x 100x   100x 100x   100x 100x 100x   100x   100x 100x     100x 100x 100x 100x 100x 100x 100x 100x   100x 100x     100x 100x 100x         100x 100x 100x   100x 100x 100x   100x 100x 100x     100x 100x 100x       20x 20x 20x 20x 20x 20x 20x 20x 20x     20x 20x 20x   20x 20x 20x   20x 20x 20x     20x     20x 20x 20x     20x 20x 20x       10x 10x 10x   10x 10x 10x       703x 703x 703x 2109x   2109x   2109x             5007x 1x       5007x 5007x     5007x   33219x 248438x   248438x 4592914x                   704x 704x 704x 704x 704x 704x 704x 704x 704x     704x 704x 704x       102x 102x 102x 102x 102x 102x 102x 102x 102x     102x 102x 102x   102x 102x 102x   102x 102x 102x     102x 102x       102x 102x 102x   102x 102x 102x   102x 102x 102x       506x                                 1964x 2x       126213x   1962x     1x     104x   312x 312x         5019x 28362x 220318x   28362x   5019x               20x       202x 202x 202x 202x   202x 202x 202x   202x 202x 202x   202x   202x 202x 202x   202x 202x 202x   202x 202x 202x   202x 202x 202x       1388x 833x   555x 555x 555x     555x       56x 56x 56x   56x                                       1015x 1015x   1015x 12170218x 12170218x 12170218x 12170218x       1015x 1015x 8344x 8344x       1015x 6897x 6897x 61149x 497056x     6897x 1015x       5882x 2811x   3071x     5882x 53820x 441110x     441110x         97736x 343374x 324773x 324773x 2332x   322441x 322441x 322441x 164294x     324773x 324773x 324773x 324773x 324773x 324773x 324773x 324773x 324773x     324773x 1836671x     324773x 1903935x     324773x 2019730x   324773x 6409882x           5882x 59702x 59702x 59702x         1015x           1015x   7329x 7329x 7329x   55946x   11632x 11632x     7329x 5762x 5762x 5762x             1015x   1015x 120236x 63905x       1015x         1015x       202x     202x 202x 202x 202x     202x 202x 202x   202x 202x 202x   202x 202x         202x 202x     202x 202x 202x 202x       1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x         200x 1800x       200x 200x       200x 600x 600x 600x 600x 600x 600x 600x 600x         200x 200x 200x 200x 200x 200x 106x 106x   200x 73x   200x   138x 138x       200x 200x 200x 200x 200x 64x   64x       200x         200x 200x 103x 103x 927x               200x 200x 200x     200x 103x 927x         200x 64x   200x 138x                         202x     202x     202x 1x 1x       201x       201x   603x   1x 1x 1x 2x 1x 1x       1x             1x             1x 1x   1x 1x 1x 1x 1x         1x 1x         1x 3x 3x       1x 1x                 200x 200x 200x 400x 171x 171x       200x 151x 151x 151x 151x     200x 100x 100x 100x 100x       200x 400x 110x 110x 110x       200x 8x 8x 8x       200x           100x     100x 100x 41x 369x         100x 100x 100x 100x 100x 100x     100x 41x 41x 41x                             754x       754x         754x 10611x 190733x 35557x       10611x       10611x         754x 10611x 90061x 90061x 553255x   90061x         10611x 100672x 100672x 643316x   100672x   100672x 27924x 27924x           10611x 8293x 154231x 154231x 154231x   8293x         10611x   10611x         10611x 9857x 9857x 90061x       754x                         6861x 118233x 118233x 118233x   118233x 57561x 409566x   60672x 6861x     118233x         6861x 118233x 118233x 1102387x   118233x           359x 9x 9x   9x   5x     4x 4x   4x 4x 4x     350x 100x   50x     50x 50x               250x     250x     250x   250x         504x 504x         504x       504x 6611x 114233x   6611x   6611x   6611x 114233x       504x       3x 3x     3x 6x 9x 4x           3x 6x 3x       3x 1x   2x       6x         4x 1x 1x                 3x   3x 3x     3x 9x 18x 27x           3x 6x 3x         3x       3x 6x     3x                         4x 1x 1x     3x 3x   3x       3x     3x                 3x 3x   3x 9x 9x 5x 5x           3x 1x     1x           2x     2x 2x               2x                   2x 2x 2x     2x 6x   12x 18x       12x 12x           2x 4x 2x       2x     2x 2x 4x 4x 4x 8x               2x                     2x       2x                                                                             24564x 24564x 24564x 24564x   24564x 24564x   24564x 2736x 21828x 10918x   24564x 9552x 15012x 1358x   24564x   24564x 24564x       24564x 24564x 12276x 12288x 2736x   9552x   24564x 1358x             24564x 24564x 24564x       26882x 26882x 26882x 26882x 26882x           26882x   4333x 4333x 4333x 22549x   4380x 4380x 4380x 18169x   4231x 4231x 4231x 13938x   4751x 4751x 4751x 9187x   4219x 4219x 4219x     4968x 4968x 4968x       26882x 26882x 26882x   26882x 26882x 26882x     26882x 26882x 26882x         405306x 405306x 405306x 405306x   405306x 393830x   11476x     405306x 396518x   8788x     405306x 383899x   21407x   405306x 405306x 405306x 405306x 405306x 405306x       810612x 810612x 810612x 810612x 810612x 810612x 810612x   810612x 16498x 810612x 24825x 810612x 43038x   810612x 810612x 810612x       405306x 405306x 405306x 405306x                   405306x 22350x 405306x 26446x 405306x 38588x         405306x 405306x 405306x 405306x 14740x 14740x 14740x   405306x 405306x 405306x     405306x 405306x 405306x       810612x                 810612x 60237x 810612x 65560x 810612x 85714x     810612x 810612x 810612x       810612x 810612x 810612x       405306x 405306x 405306x       22x 22x 22x 22x 22x 22x 22x       1135x                                 31x 10x   21x 10x   11x       6x 6x 6x   6x                                         1x     1x                                                                                                                                                                                     1x 1x   554761x 1x 1x         1x                                                               55x 55x 55x 165x 165x     55x       110x 110x 110x 110x 275x 275x 715x 715x 715x 171x 171x 171x           110x 110x       55x 55x 165x 165x     55x                                                                                                                                                                                                                                                                                                    
import seedrandom from 'seedrandom';
import macro from 'vtk.js/Sources/macros';
import {
  IDENTITY,
  IDENTITY_3X3,
  EPSILON,
  VTK_SMALL_NUMBER,
} from 'vtk.js/Sources/Common/Core/Math/Constants';
 
const { vtkErrorMacro, vtkWarningMacro } = macro;
 
// ----------------------------------------------------------------------------
/* eslint-disable camelcase                                                  */
/* eslint-disable no-cond-assign                                             */
/* eslint-disable no-bitwise                                                 */
/* eslint-disable no-multi-assign                                            */
// ----------------------------------------------------------------------------
let randomSeedValue = 0;
const VTK_MAX_ROTATIONS = 20;
 
function notImplemented(method) {
  return () => vtkErrorMacro(`vtkMath::${method} - NOT IMPLEMENTED`);
}
 
// Swap rows for n by n matrix
function swapRowsMatrix_nxn(matrix, n, row1, row2) {
  let tmp;
  for (let i = 0; i < n; i++) {
    tmp = matrix[row1 * n + i];
    matrix[row1 * n + i] = matrix[row2 * n + i];
    matrix[row2 * n + i] = tmp;
  }
}
 
// Swap columns for n by n matrix
function swapColumnsMatrix_nxn(matrix, n, column1, column2) {
  let tmp;
  for (let i = 0; i < n; i++) {
    tmp = matrix[i * n + column1];
    matrix[i * n + column1] = matrix[i * n + column2];
    matrix[i * n + column2] = tmp;
  }
}
 
// ----------------------------------------------------------------------------
// Global methods
// ----------------------------------------------------------------------------
 
export function createArray(size = 3) {
  // faster than Array.from and/or while loop
  const res = Array(size);
  for (let i = 0; i < size; ++i) {
    res[i] = 0;
  }
  return res;
}
 
export const Pi = () => Math.PI;
 
export function radiansFromDegrees(deg) {
  return (deg / 180) * Math.PI;
}
 
export function degreesFromRadians(rad) {
  return (rad * 180) / Math.PI;
}
 
export const { round, floor, ceil, min, max } = Math;
 
export function arrayMin(arr, offset = 0, stride = 1) {
  let minValue = Infinity;
  for (let i = offset, len = arr.length; i < len; i += stride) {
    if (arr[i] < minValue) {
      minValue = arr[i];
    }
  }
 
  return minValue;
}
 
export function arrayMax(arr, offset = 0, stride = 1) {
  let maxValue = -Infinity;
  for (let i = offset, len = arr.length; i < len; i += stride) {
    if (maxValue < arr[i]) {
      maxValue = arr[i];
    }
  }
 
  return maxValue;
}
 
export function arrayRange(arr, offset = 0, stride = 1) {
  let minValue = Infinity;
  let maxValue = -Infinity;
  for (let i = offset, len = arr.length; i < len; i += stride) {
    if (arr[i] < minValue) {
      minValue = arr[i];
    }
    if (maxValue < arr[i]) {
      maxValue = arr[i];
    }
  }
 
  return [minValue, maxValue];
}
 
export const ceilLog2 = notImplemented('ceilLog2');
export const factorial = notImplemented('factorial');
 
export function nearestPowerOfTwo(xi) {
  let v = 1;
  while (v < xi) {
    v *= 2;
  }
  return v;
}
 
export function isPowerOfTwo(x) {
  return x === nearestPowerOfTwo(x);
}
 
export function binomial(m, n) {
  let r = 1;
  for (let i = 1; i <= n; ++i) {
    r *= (m - i + 1) / i;
  }
  return Math.floor(r);
}
 
export function beginCombination(m, n) {
  if (m < n) {
    return 0;
  }
 
  const r = createArray(n);
  for (let i = 0; i < n; ++i) {
    r[i] = i;
  }
  return r;
}
 
export function nextCombination(m, n, r) {
  let status = 0;
  for (let i = n - 1; i >= 0; --i) {
    if (r[i] < m - n + i) {
      let j = r[i] + 1;
      while (i < n) {
        r[i++] = j++;
      }
      status = 1;
      break;
    }
  }
  return status;
}
 
export function randomSeed(seed) {
  seedrandom(`${seed}`, { global: true });
  randomSeedValue = seed;
}
 
export function getSeed() {
  return randomSeedValue;
}
 
export function random(minValue = 0, maxValue = 1) {
  const delta = maxValue - minValue;
  return minValue + delta * Math.random();
}
 
export const gaussian = notImplemented('gaussian');
 
// Vect3 operations
export function add(a, b, out) {
  out[0] = a[0] + b[0];
  out[1] = a[1] + b[1];
  out[2] = a[2] + b[2];
  return out;
}
 
export function subtract(a, b, out) {
  out[0] = a[0] - b[0];
  out[1] = a[1] - b[1];
  out[2] = a[2] - b[2];
  return out;
}
 
export function multiplyScalar(vec, scalar) {
  vec[0] *= scalar;
  vec[1] *= scalar;
  vec[2] *= scalar;
  return vec;
}
 
export function multiplyScalar2D(vec, scalar) {
  vec[0] *= scalar;
  vec[1] *= scalar;
  return vec;
}
 
export function multiplyAccumulate(a, b, scalar, out) {
  out[0] = a[0] + b[0] * scalar;
  out[1] = a[1] + b[1] * scalar;
  out[2] = a[2] + b[2] * scalar;
  return out;
}
 
export function multiplyAccumulate2D(a, b, scalar, out) {
  out[0] = a[0] + b[0] * scalar;
  out[1] = a[1] + b[1] * scalar;
  return out;
}
 
export function dot(x, y) {
  return x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
}
 
export function outer(x, y, out_3x3) {
  out_3x3[0] = x[0] * y[0];
  out_3x3[1] = x[0] * y[1];
  out_3x3[2] = x[0] * y[2];
  out_3x3[3] = x[1] * y[0];
  out_3x3[4] = x[1] * y[1];
  out_3x3[5] = x[1] * y[2];
  out_3x3[6] = x[2] * y[0];
  out_3x3[7] = x[2] * y[1];
  out_3x3[8] = x[2] * y[2];
}
 
export function cross(x, y, out) {
  const Zx = x[1] * y[2] - x[2] * y[1];
  const Zy = x[2] * y[0] - x[0] * y[2];
  const Zz = x[0] * y[1] - x[1] * y[0];
  out[0] = Zx;
  out[1] = Zy;
  out[2] = Zz;
  return out;
}
 
export function norm(x, n = 3) {
  switch (n) {
    case 1:
      return Math.abs(x);
    case 2:
      return Math.sqrt(x[0] * x[0] + x[1] * x[1]);
    case 3:
      return Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
    default: {
      let sum = 0;
      for (let i = 0; i < n; i++) {
        sum += x[i] * x[i];
      }
      return Math.sqrt(sum);
    }
  }
}
 
export function normalize(x) {
  const den = norm(x);
  if (den !== 0.0) {
    x[0] /= den;
    x[1] /= den;
    x[2] /= den;
  }
  return den;
}
 
export function perpendiculars(x, y, z, theta) {
  const x2 = x[0] * x[0];
  const y2 = x[1] * x[1];
  const z2 = x[2] * x[2];
  const r = Math.sqrt(x2 + y2 + z2);
 
  let dx;
  let dy;
  let dz;
 
  // transpose the vector to avoid divide-by-zero error
  if (x2 > y2 && x2 > z2) {
    dx = 0;
    dy = 1;
    dz = 2;
  } else if (y2 > z2) {
    dx = 1;
    dy = 2;
    dz = 0;
  } else E{
    dx = 2;
    dy = 0;
    dz = 1;
  }
 
  const a = x[dx] / r;
  const b = x[dy] / r;
  const c = x[dz] / r;
  const tmp = Math.sqrt(a * a + c * c);
 
  Iif (theta !== 0) {
    const sintheta = Math.sin(theta);
    const costheta = Math.cos(theta);
 
    if (y) {
      y[dx] = (c * costheta - a * b * sintheta) / tmp;
      y[dy] = sintheta * tmp;
      y[dz] = (-(a * costheta) - b * c * sintheta) / tmp;
    }
 
    if (z) {
      z[dx] = (-(c * sintheta) - a * b * costheta) / tmp;
      z[dy] = costheta * tmp;
      z[dz] = (a * sintheta - b * c * costheta) / tmp;
    }
  } else {
    if (y) {
      y[dx] = c / tmp;
      y[dy] = 0;
      y[dz] = -a / tmp;
    }
 
    if (z) {
      z[dx] = (-a * b) / tmp;
      z[dy] = tmp;
      z[dz] = (-b * c) / tmp;
    }
  }
}
 
export function projectVector(a, b, projection) {
  const bSquared = dot(b, b);
 
  if (bSquared === 0) {
    projection[0] = 0;
    projection[1] = 0;
    projection[2] = 0;
    return false;
  }
 
  const scale = dot(a, b) / bSquared;
 
  for (let i = 0; i < 3; i++) {
    projection[i] = b[i];
  }
  multiplyScalar(projection, scale);
 
  return true;
}
 
export function dot2D(x, y) {
  return x[0] * y[0] + x[1] * y[1];
}
 
export function projectVector2D(a, b, projection) {
  const bSquared = dot2D(b, b);
 
  if (bSquared === 0) {
    projection[0] = 0;
    projection[1] = 0;
    return false;
  }
 
  const scale = dot2D(a, b) / bSquared;
 
  for (let i = 0; i < 2; i++) {
    projection[i] = b[i];
  }
  multiplyScalar2D(projection, scale);
 
  return true;
}
 
export function distance2BetweenPoints(x, y) {
  return (
    (x[0] - y[0]) * (x[0] - y[0]) +
    (x[1] - y[1]) * (x[1] - y[1]) +
    (x[2] - y[2]) * (x[2] - y[2])
  );
}
 
export function angleBetweenVectors(v1, v2) {
  const crossVect = [0, 0, 0];
  cross(v1, v2, crossVect);
  return Math.atan2(norm(crossVect), dot(v1, v2));
}
 
export function signedAngleBetweenVectors(v1, v2, vN) {
  const crossVect = [0, 0, 0];
  cross(v1, v2, crossVect);
  const angle = Math.atan2(norm(crossVect), dot(v1, v2));
  return dot(crossVect, vN) >= 0 ? angle : -angle;
}
 
export function gaussianAmplitude(mean, variance, position) {
  const distanceFromMean = Math.abs(mean - position);
  return (
    (1 / Math.sqrt(2 * Math.PI * variance)) *
    Math.exp(-(distanceFromMean ** 2) / (2 * variance))
  );
}
 
export function gaussianWeight(mean, variance, position) {
  const distanceFromMean = Math.abs(mean - position);
  return Math.exp(-(distanceFromMean ** 2) / (2 * variance));
}
 
export function outer2D(x, y, out_2x2) {
  out_2x2[0] = x[0] * y[0];
  out_2x2[1] = x[0] * y[1];
  out_2x2[2] = x[1] * y[0];
  out_2x2[3] = x[1] * y[1];
}
 
export function norm2D(x2D) {
  return Math.sqrt(x2D[0] * x2D[0] + x2D[1] * x2D[1]);
}
 
export function normalize2D(x) {
  const den = norm2D(x);
  if (den !== 0.0) {
    x[0] /= den;
    x[1] /= den;
  }
  return den;
}
 
export function rowsToMat4(row0, row1, row2, row3, mat) {
  for (let i = 0; i < 4; i++) {
    mat[i] = row0[i];
    mat[4 + i] = row1[i];
    mat[8 + i] = row2[i];
    mat[12 + i] = row3[i];
  }
  return mat;
}
 
export function columnsToMat4(column0, column1, column2, column3, mat) {
  for (let i = 0; i < 4; i++) {
    mat[4 * i] = column0[i];
    mat[4 * i + 1] = column1[i];
    mat[4 * i + 2] = column2[i];
    mat[4 * i + 3] = column3[i];
  }
  return mat;
}
 
export function rowsToMat3(row0, row1, row2, mat) {
  for (let i = 0; i < 3; i++) {
    mat[i] = row0[i];
    mat[3 + i] = row1[i];
    mat[6 + i] = row2[i];
  }
  return mat;
}
 
export function columnsToMat3(column0, column1, column2, mat) {
  for (let i = 0; i < 3; i++) {
    mat[3 * i] = column0[i];
    mat[3 * i + 1] = column1[i];
    mat[3 * i + 2] = column2[i];
  }
  return mat;
}
 
export function determinant2x2(...args) {
  if (args.length === 2) {
    return args[0][0] * args[1][1] - args[1][0] * args[0][1];
  }
  if (args.length === 4) {
    return args[0] * args[3] - args[1] * args[2];
  }
  return Number.NaN;
}
 
export function LUFactor3x3(mat_3x3, index_3) {
  let maxI;
  let tmp;
  let largest;
  const scale = [0, 0, 0];
 
  // Loop over rows to get implicit scaling information
  for (let i = 0; i < 3; i++) {
    largest = Math.abs(mat_3x3[i * 3]);
    Iif ((tmp = Math.abs(mat_3x3[i * 3 + 1])) > largest) {
      largest = tmp;
    }
    Iif ((tmp = Math.abs(mat_3x3[i * 3 + 2])) > largest) {
      largest = tmp;
    }
    scale[i] = 1 / largest;
  }
 
  // Loop over all columns using Crout's method
 
  // first column
  largest = scale[0] * Math.abs(mat_3x3[0]);
  maxI = 0;
  if ((tmp = scale[1] * Math.abs(mat_3x3[3])) >= largest) {
    largest = tmp;
    maxI = 1;
  }
  if ((tmp = scale[2] * Math.abs(mat_3x3[6])) >= largest) {
    maxI = 2;
  }
  if (maxI !== 0) {
    swapRowsMatrix_nxn(mat_3x3, 3, maxI, 0);
    scale[maxI] = scale[0];
  }
  index_3[0] = maxI;
 
  mat_3x3[3] /= mat_3x3[0];
  mat_3x3[6] /= mat_3x3[0];
 
  // second column
  mat_3x3[4] -= mat_3x3[3] * mat_3x3[1];
  mat_3x3[7] -= mat_3x3[6] * mat_3x3[1];
  largest = scale[1] * Math.abs(mat_3x3[4]);
  maxI = 1;
  if ((tmp = scale[2] * Math.abs(mat_3x3[7])) >= largest) {
    maxI = 2;
    swapRowsMatrix_nxn(mat_3x3, 3, 1, 2);
    scale[2] = scale[1];
  }
  index_3[1] = maxI;
  mat_3x3[7] /= mat_3x3[4];
 
  // third column
  mat_3x3[5] -= mat_3x3[3] * mat_3x3[2];
  mat_3x3[8] -= mat_3x3[6] * mat_3x3[2] + mat_3x3[7] * mat_3x3[5];
  index_3[2] = 2;
}
 
export function LUSolve3x3(mat_3x3, index_3, x_3) {
  // forward substitution
  let sum = x_3[index_3[0]];
  x_3[index_3[0]] = x_3[0];
  x_3[0] = sum;
 
  sum = x_3[index_3[1]];
  x_3[index_3[1]] = x_3[1];
  x_3[1] = sum - mat_3x3[3] * x_3[0];
 
  sum = x_3[index_3[2]];
  x_3[index_3[2]] = x_3[2];
  x_3[2] = sum - mat_3x3[6] * x_3[0] - mat_3x3[7] * x_3[1];
 
  // back substitution
  x_3[2] /= mat_3x3[8];
  x_3[1] = (x_3[1] - mat_3x3[5] * x_3[2]) / mat_3x3[4];
  x_3[0] = (x_3[0] - mat_3x3[1] * x_3[1] - mat_3x3[2] * x_3[2]) / mat_3x3[0];
}
 
export function linearSolve3x3(mat_3x3, x_3, y_3) {
  const a1 = mat_3x3[0];
  const b1 = mat_3x3[1];
  const c1 = mat_3x3[2];
  const a2 = mat_3x3[3];
  const b2 = mat_3x3[4];
  const c2 = mat_3x3[5];
  const a3 = mat_3x3[6];
  const b3 = mat_3x3[7];
  const c3 = mat_3x3[8];
 
  // Compute the adjoint
  const d1 = +determinant2x2(b2, b3, c2, c3);
  const d2 = -determinant2x2(a2, a3, c2, c3);
  const d3 = +determinant2x2(a2, a3, b2, b3);
 
  const e1 = -determinant2x2(b1, b3, c1, c3);
  const e2 = +determinant2x2(a1, a3, c1, c3);
  const e3 = -determinant2x2(a1, a3, b1, b3);
 
  const f1 = +determinant2x2(b1, b2, c1, c2);
  const f2 = -determinant2x2(a1, a2, c1, c2);
  const f3 = +determinant2x2(a1, a2, b1, b2);
 
  // Compute the determinant
  const det = a1 * d1 + b1 * d2 + c1 * d3;
 
  // Multiply by the adjoint
  const v1 = d1 * x_3[0] + e1 * x_3[1] + f1 * x_3[2];
  const v2 = d2 * x_3[0] + e2 * x_3[1] + f2 * x_3[2];
  const v3 = d3 * x_3[0] + e3 * x_3[1] + f3 * x_3[2];
 
  // Divide by the determinant
  y_3[0] = v1 / det;
  y_3[1] = v2 / det;
  y_3[2] = v3 / det;
}
 
export function multiply3x3_vect3(mat_3x3, in_3, out_3) {
  const x = mat_3x3[0] * in_3[0] + mat_3x3[1] * in_3[1] + mat_3x3[2] * in_3[2];
  const y = mat_3x3[3] * in_3[0] + mat_3x3[4] * in_3[1] + mat_3x3[5] * in_3[2];
  const z = mat_3x3[6] * in_3[0] + mat_3x3[7] * in_3[1] + mat_3x3[8] * in_3[2];
 
  out_3[0] = x;
  out_3[1] = y;
  out_3[2] = z;
}
 
export function multiply3x3_mat3(a_3x3, b_3x3, out_3x3) {
  const copyA = [...a_3x3];
  const copyB = [...b_3x3];
  for (let i = 0; i < 3; i++) {
    out_3x3[i] =
      copyA[0] * copyB[i] + copyA[1] * copyB[i + 3] + copyA[2] * copyB[i + 6];
    out_3x3[i + 3] =
      copyA[3] * copyB[i] + copyA[4] * copyB[i + 3] + copyA[5] * copyB[i + 6];
    out_3x3[i + 6] =
      copyA[6] * copyB[i] + copyA[7] * copyB[i + 3] + copyA[8] * copyB[i + 6];
  }
}
 
export function multiplyMatrix(a, b, rowA, colA, rowB, colB, outRowAColB) {
  // we need colA == rowB
  if (colA !== rowB) {
    vtkErrorMacro('Number of columns of A must match number of rows of B.');
  }
 
  // If a or b is used to store the result, copying them is required
  const copyA = [...a];
  const copyB = [...b];
  // output matrix is rowA*colB
  // output row
  for (let i = 0; i < rowA; i++) {
    // output col
    for (let j = 0; j < colB; j++) {
      outRowAColB[i * colB + j] = 0;
      // sum for this point
      for (let k = 0; k < colA; k++) {
        outRowAColB[i * colB + j] += copyA[i * colA + k] * copyB[j + colB * k];
      }
    }
  }
}
 
export function transpose3x3(in_3x3, outT_3x3) {
  let tmp;
 
  // off-diagonal elements
  tmp = in_3x3[3];
  outT_3x3[3] = in_3x3[1];
  outT_3x3[1] = tmp;
  tmp = in_3x3[6];
  outT_3x3[6] = in_3x3[2];
  outT_3x3[2] = tmp;
  tmp = in_3x3[7];
  outT_3x3[7] = in_3x3[5];
  outT_3x3[5] = tmp;
 
  // on-diagonal elements
  outT_3x3[0] = in_3x3[0];
  outT_3x3[4] = in_3x3[4];
  outT_3x3[8] = in_3x3[8];
}
 
export function invert3x3(in_3x3, outI_3x3) {
  const a1 = in_3x3[0];
  const b1 = in_3x3[1];
  const c1 = in_3x3[2];
  const a2 = in_3x3[3];
  const b2 = in_3x3[4];
  const c2 = in_3x3[5];
  const a3 = in_3x3[6];
  const b3 = in_3x3[7];
  const c3 = in_3x3[8];
 
  // Compute the adjoint
  const d1 = +determinant2x2(b2, b3, c2, c3);
  const d2 = -determinant2x2(a2, a3, c2, c3);
  const d3 = +determinant2x2(a2, a3, b2, b3);
 
  const e1 = -determinant2x2(b1, b3, c1, c3);
  const e2 = +determinant2x2(a1, a3, c1, c3);
  const e3 = -determinant2x2(a1, a3, b1, b3);
 
  const f1 = +determinant2x2(b1, b2, c1, c2);
  const f2 = -determinant2x2(a1, a2, c1, c2);
  const f3 = +determinant2x2(a1, a2, b1, b2);
 
  // Divide by the determinant
  const det = a1 * d1 + b1 * d2 + c1 * d3;
  Iif (det === 0) {
    vtkWarningMacro('Matrix has 0 determinant');
  }
 
  outI_3x3[0] = d1 / det;
  outI_3x3[3] = d2 / det;
  outI_3x3[6] = d3 / det;
 
  outI_3x3[1] = e1 / det;
  outI_3x3[4] = e2 / det;
  outI_3x3[7] = e3 / det;
 
  outI_3x3[2] = f1 / det;
  outI_3x3[5] = f2 / det;
  outI_3x3[8] = f3 / det;
}
 
export function determinant3x3(mat_3x3) {
  return (
    mat_3x3[0] * mat_3x3[4] * mat_3x3[8] +
    mat_3x3[3] * mat_3x3[7] * mat_3x3[2] +
    mat_3x3[6] * mat_3x3[1] * mat_3x3[5] -
    mat_3x3[0] * mat_3x3[7] * mat_3x3[5] -
    mat_3x3[3] * mat_3x3[1] * mat_3x3[8] -
    mat_3x3[6] * mat_3x3[4] * mat_3x3[2]
  );
}
 
/**
 * Returns true if elements of both arrays are equals.
 * @param {Array} a an array of numbers (vector, point, matrix...)
 * @param {Array} b an array of numbers (vector, point, matrix...)
 * @param {Number} eps tolerance
 */
export function areEquals(a, b, eps = EPSILON) {
  if (a.length !== b.length) {
    return false;
  }
 
  function isEqual(element, index) {
    return Math.abs(element - b[index]) <= eps;
  }
  return a.every(isEqual);
}
 
export const areMatricesEqual = areEquals;
 
export function identity3x3(mat_3x3) {
  for (let i = 0; i < 3; i++) {
    /* eslint-disable-next-line no-multi-assign */
    mat_3x3[i * 3] = mat_3x3[i * 3 + 1] = mat_3x3[i * 3 + 2] = 0;
    mat_3x3[i * 3 + i] = 1;
  }
}
 
export function identity(n, mat) {
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      mat[i * n + j] = 0;
    }
    mat[i * n + i] = 1;
  }
  return mat;
}
 
export function isIdentity(mat, eps = EPSILON) {
  return areMatricesEqual(mat, IDENTITY, eps);
}
 
export function isIdentity3x3(mat, eps = EPSILON) {
  return areMatricesEqual(mat, IDENTITY_3X3, eps);
}
 
export function quaternionToMatrix3x3(quat_4, mat_3x3) {
  const ww = quat_4[0] * quat_4[0];
  const wx = quat_4[0] * quat_4[1];
  const wy = quat_4[0] * quat_4[2];
  const wz = quat_4[0] * quat_4[3];
 
  const xx = quat_4[1] * quat_4[1];
  const yy = quat_4[2] * quat_4[2];
  const zz = quat_4[3] * quat_4[3];
 
  const xy = quat_4[1] * quat_4[2];
  const xz = quat_4[1] * quat_4[3];
  const yz = quat_4[2] * quat_4[3];
 
  const rr = xx + yy + zz;
  // normalization factor, just in case quaternion was not normalized
  let f = 1 / (ww + rr);
  const s = (ww - rr) * f;
  f *= 2;
 
  mat_3x3[0] = xx * f + s;
  mat_3x3[3] = (xy + wz) * f;
  mat_3x3[6] = (xz - wy) * f;
 
  mat_3x3[1] = (xy - wz) * f;
  mat_3x3[4] = yy * f + s;
  mat_3x3[7] = (yz + wx) * f;
 
  mat_3x3[2] = (xz + wy) * f;
  mat_3x3[5] = (yz - wx) * f;
  mat_3x3[8] = zz * f + s;
}
 
export function roundNumber(num, digits = 0) {
  if (!`${num}`.includes('e')) {
    return +`${Math.round(`${num}e+${digits}`)}e-${digits}`;
  }
  const arr = `${num}`.split('e');
  let sig = '';
  Iif (+arr[1] + digits > 0) {
    sig = '+';
  }
  return +`${Math.round(`${+arr[0]}e${sig}${+arr[1] + digits}`)}e-${digits}`;
}
 
export function roundVector(vector, out = [0, 0, 0], digits = 0) {
  out[0] = roundNumber(vector[0], digits);
  out[1] = roundNumber(vector[1], digits);
  out[2] = roundNumber(vector[2], digits);
 
  return out;
}
 
export function jacobiN(a, n, w, v) {
  let i;
  let j;
  let k;
  let iq;
  let ip;
  let numPos;
  let tresh;
  let theta;
  let t;
  let tau;
  let sm;
  let s;
  let h;
  let g;
  let c;
  let tmp;
  const b = createArray(n);
  const z = createArray(n);
 
  const vtkROTATE = (aa, ii, jj) => {
    g = aa[ii];
    h = aa[jj];
    aa[ii] = g - s * (h + g * tau);
    aa[jj] = h + s * (g - h * tau);
  };
 
  // initialize
  identity(n, v);
  for (ip = 0; ip < n; ip++) {
    b[ip] = w[ip] = a[ip + ip * n];
    z[ip] = 0.0;
  }
 
  // begin rotation sequence
  for (i = 0; i < VTK_MAX_ROTATIONS; i++) {
    sm = 0.0;
    for (ip = 0; ip < n - 1; ip++) {
      for (iq = ip + 1; iq < n; iq++) {
        sm += Math.abs(a[ip * n + iq]);
      }
    }
    if (sm === 0.0) {
      break;
    }
 
    // first 3 sweeps
    if (i < 3) {
      tresh = (0.2 * sm) / (n * n);
    } else {
      tresh = 0.0;
    }
 
    for (ip = 0; ip < n - 1; ip++) {
      for (iq = ip + 1; iq < n; iq++) {
        g = 100.0 * Math.abs(a[ip * n + iq]);
 
        // after 4 sweeps
        if (
          i > 3 &&
          Math.abs(w[ip]) + g === Math.abs(w[ip]) &&
          Math.abs(w[iq]) + g === Math.abs(w[iq])
        ) {
          a[ip * n + iq] = 0.0;
        } else if (Math.abs(a[ip * n + iq]) > tresh) {
          h = w[iq] - w[ip];
          if (Math.abs(h) + g === Math.abs(h)) {
            t = a[ip * n + iq] / h;
          } else {
            theta = (0.5 * h) / a[ip * n + iq];
            t = 1.0 / (Math.abs(theta) + Math.sqrt(1.0 + theta * theta));
            if (theta < 0.0) {
              t = -t;
            }
          }
          c = 1.0 / Math.sqrt(1 + t * t);
          s = t * c;
          tau = s / (1.0 + c);
          h = t * a[ip * n + iq];
          z[ip] -= h;
          z[iq] += h;
          w[ip] -= h;
          w[iq] += h;
          a[ip * n + iq] = 0.0;
 
          // ip already shifted left by 1 unit
          for (j = 0; j <= ip - 1; j++) {
            vtkROTATE(a, j * n + ip, j * n + iq);
          }
          // ip and iq already shifted left by 1 unit
          for (j = ip + 1; j <= iq - 1; j++) {
            vtkROTATE(a, ip * n + j, j * n + iq);
          }
          // iq already shifted left by 1 unit
          for (j = iq + 1; j < n; j++) {
            vtkROTATE(a, ip * n + j, iq * n + j);
          }
          for (j = 0; j < n; j++) {
            vtkROTATE(v, j * n + ip, j * n + iq);
          }
        }
      }
    }
 
    for (ip = 0; ip < n; ip++) {
      b[ip] += z[ip];
      w[ip] = b[ip];
      z[ip] = 0.0;
    }
  }
 
  // this is NEVER called
  Iif (i >= VTK_MAX_ROTATIONS) {
    vtkWarningMacro('vtkMath::Jacobi: Error extracting eigenfunctions');
    return 0;
  }
 
  // sort eigenfunctions: these changes do not affect accuracy
  for (j = 0; j < n - 1; j++) {
    // boundary incorrect
    k = j;
    tmp = w[k];
    for (i = j + 1; i < n; i++) {
      // boundary incorrect, shifted already
      if (w[i] >= tmp || Math.abs(w[i] - tmp) < VTK_SMALL_NUMBER) {
        // why exchange if same?
        k = i;
        tmp = w[k];
      }
    }
    if (k !== j) {
      w[k] = w[j];
      w[j] = tmp;
      swapColumnsMatrix_nxn(v, n, j, k);
    }
  }
  // ensure eigenvector consistency (i.e., Jacobi can compute vectors that
  // are negative of one another (.707,.707,0) and (-.707,-.707,0). This can
  // reek havoc in hyperstreamline/other stuff. We will select the most
  // positive eigenvector.
  const ceil_half_n = (n >> 1) + (n & 1);
 
  for (numPos = 0, i = 0; i < n * n; i++) {
    if (v[i] >= 0.0) {
      numPos++;
    }
  }
  //    if ( numPos < ceil(double(n)/double(2.0)) )
  Iif (numPos < ceil_half_n) {
    for (i = 0; i < n; i++) {
      v[i * n + j] *= -1.0;
    }
  }
  return 1;
}
 
export function matrix3x3ToQuaternion(mat_3x3, quat_4) {
  const tmp = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
 
  // on-diagonal elements
  tmp[0] = mat_3x3[0] + mat_3x3[4] + mat_3x3[8];
  tmp[5] = mat_3x3[0] - mat_3x3[4] - mat_3x3[8];
  tmp[10] = -mat_3x3[0] + mat_3x3[4] - mat_3x3[8];
  tmp[15] = -mat_3x3[0] - mat_3x3[4] + mat_3x3[8];
 
  // off-diagonal elements
  tmp[1] = tmp[4] = mat_3x3[7] - mat_3x3[5];
  tmp[2] = tmp[8] = mat_3x3[2] - mat_3x3[6];
  tmp[3] = tmp[12] = mat_3x3[3] - mat_3x3[1];
 
  tmp[6] = tmp[9] = mat_3x3[3] + mat_3x3[1];
  tmp[7] = tmp[13] = mat_3x3[2] + mat_3x3[6];
  tmp[11] = tmp[14] = mat_3x3[7] + mat_3x3[5];
 
  const eigenvectors = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  const eigenvalues = [0, 0, 0, 0];
 
  // convert into format that JacobiN can use,
  // then use Jacobi to find eigenvalues and eigenvectors
  // tmp is copied because jacobiN may modify it
  const NTemp = [...tmp];
  jacobiN(NTemp, 4, eigenvalues, eigenvectors);
 
  // the first eigenvector is the one we want
  quat_4[0] = eigenvectors[0];
  quat_4[1] = eigenvectors[4];
  quat_4[2] = eigenvectors[8];
  quat_4[3] = eigenvectors[12];
}
 
export function multiplyQuaternion(quat_1, quat_2, quat_out) {
  const ww = quat_1[0] * quat_2[0];
  const wx = quat_1[0] * quat_2[1];
  const wy = quat_1[0] * quat_2[2];
  const wz = quat_1[0] * quat_2[3];
 
  const xw = quat_1[1] * quat_2[0];
  const xx = quat_1[1] * quat_2[1];
  const xy = quat_1[1] * quat_2[2];
  const xz = quat_1[1] * quat_2[3];
 
  const yw = quat_1[2] * quat_2[0];
  const yx = quat_1[2] * quat_2[1];
  const yy = quat_1[2] * quat_2[2];
  const yz = quat_1[2] * quat_2[3];
 
  const zw = quat_1[3] * quat_2[0];
  const zx = quat_1[3] * quat_2[1];
  const zy = quat_1[3] * quat_2[2];
  const zz = quat_1[3] * quat_2[3];
 
  quat_out[0] = ww - xx - yy - zz;
  quat_out[1] = wx + xw + yz - zy;
  quat_out[2] = wy - xz + yw + zx;
  quat_out[3] = wz + xy - yx + zw;
}
 
export function orthogonalize3x3(a_3x3, out_3x3) {
  // copy the matrix
  for (let i = 0; i < 9; i++) {
    out_3x3[i] = a_3x3[i];
  }
 
  // Pivot the matrix to improve accuracy
  const scale = createArray(3);
  const index = createArray(3);
  let largest;
 
  // Loop over rows to get implicit scaling information
  for (let i = 0; i < 3; i++) {
    const x1 = Math.abs(out_3x3[i * 3]);
    const x2 = Math.abs(out_3x3[i * 3 + 1]);
    const x3 = Math.abs(out_3x3[i * 3 + 2]);
    largest = x2 > x1 ? x2 : x1;
    largest = x3 > largest ? x3 : largest;
    scale[i] = 1;
    if (largest !== 0) {
      scale[i] /= largest;
    }
  }
 
  // first column
  const x1 = Math.abs(out_3x3[0]) * scale[0];
  const x2 = Math.abs(out_3x3[3]) * scale[1];
  const x3 = Math.abs(out_3x3[6]) * scale[2];
  index[0] = 0;
  largest = x1;
  if (x2 >= largest) {
    largest = x2;
    index[0] = 1;
  }
  if (x3 >= largest) {
    index[0] = 2;
  }
  if (index[0] !== 0) {
    // swap vectors
    swapColumnsMatrix_nxn(out_3x3, 3, index[0], 0);
    scale[index[0]] = scale[0];
  }
 
  // second column
  const y2 = Math.abs(out_3x3[4]) * scale[1];
  const y3 = Math.abs(out_3x3[7]) * scale[2];
  index[1] = 1;
  largest = y2;
  if (y3 >= largest) {
    index[1] = 2;
    // swap vectors
    swapColumnsMatrix_nxn(out_3x3, 3, 1, 2);
  }
 
  // third column
  index[2] = 2;
 
  // A quaternion can only describe a pure rotation, not
  // a rotation with a flip, therefore the flip must be
  // removed before the matrix is converted to a quaternion.
  let flip = 0;
  if (determinant3x3(out_3x3) < 0) {
    flip = 1;
    for (let i = 0; i < 9; i++) {
      out_3x3[i] = -out_3x3[i];
    }
  }
 
  // Do orthogonalization using a quaternion intermediate
  // (this, essentially, does the orthogonalization via
  // diagonalization of an appropriately constructed symmetric
  // 4x4 matrix rather than by doing SVD of the 3x3 matrix)
  const quat = createArray(4);
  matrix3x3ToQuaternion(out_3x3, quat);
  quaternionToMatrix3x3(quat, out_3x3);
 
  // Put the flip back into the orthogonalized matrix.
  if (flip) {
    for (let i = 0; i < 9; i++) {
      out_3x3[i] = -out_3x3[i];
    }
  }
 
  // Undo the pivoting
  if (index[1] !== 1) {
    swapColumnsMatrix_nxn(out_3x3, 3, index[1], 1);
  }
  if (index[0] !== 0) {
    swapColumnsMatrix_nxn(out_3x3, 3, index[0], 0);
  }
}
 
export function diagonalize3x3(a_3x3, w_3, v_3x3) {
  let i;
  let j;
  let k;
  let maxI;
  let tmp;
  let maxVal;
 
  // a is copied because jacobiN may modify it
  const copyA = [...a_3x3];
 
  // diagonalize using Jacobi
  jacobiN(copyA, 3, w_3, v_3x3);
 
  // if all the eigenvalues are the same, return identity matrix
  if (w_3[0] === w_3[1] && w_3[0] === w_3[2]) {
    identity3x3(v_3x3);
    return;
  }
 
  // transpose temporarily, it makes it easier to sort the eigenvectors
  transpose3x3(v_3x3, v_3x3);
 
  // if two eigenvalues are the same, re-orthogonalize to optimally line
  // up the eigenvectors with the x, y, and z axes
  for (i = 0; i < 3; i++) {
    // two eigenvalues are the same
    if (w_3[(i + 1) % 3] === w_3[(i + 2) % 3]) {
      // find maximum element of the independent eigenvector
      maxVal = Math.abs(v_3x3[i * 3]);
      maxI = 0;
      for (j = 1; j < 3; j++) {
        if (maxVal < (tmp = Math.abs(v_3x3[i * 3 + j]))) {
          maxVal = tmp;
          maxI = j;
        }
      }
      // swap the eigenvector into its proper position
      Iif (maxI !== i) {
        tmp = w_3[maxI];
        w_3[maxI] = w_3[i];
        w_3[i] = tmp;
        swapRowsMatrix_nxn(v_3x3, 3, i, maxI);
      }
      // maximum element of eigenvector should be positive
      Iif (v_3x3[maxI * 3 + maxI] < 0) {
        v_3x3[maxI * 3] = -v_3x3[maxI * 3];
        v_3x3[maxI * 3 + 1] = -v_3x3[maxI * 3 + 1];
        v_3x3[maxI * 3 + 2] = -v_3x3[maxI * 3 + 2];
      }
 
      // re-orthogonalize the other two eigenvectors
      j = (maxI + 1) % 3;
      k = (maxI + 2) % 3;
 
      v_3x3[j * 3] = 0.0;
      v_3x3[j * 3 + 1] = 0.0;
      v_3x3[j * 3 + 2] = 0.0;
      v_3x3[j * 3 + j] = 1.0;
      const vectTmp1 = cross(
        [v_3x3[maxI * 3], v_3x3[maxI * 3 + 1], v_3x3[maxI * 3 + 2]],
        [v_3x3[j * 3], v_3x3[j * 3 + 1], v_3x3[j * 3 + 2]],
        []
      );
      normalize(vectTmp1);
      const vectTmp2 = cross(
        vectTmp1,
        [v_3x3[maxI * 3], v_3x3[maxI * 3 + 1], v_3x3[maxI * 3 + 2]],
        []
      );
      for (let t = 0; t < 3; t++) {
        v_3x3[k * 3 + t] = vectTmp1[t];
        v_3x3[j * 3 + t] = vectTmp2[t];
      }
 
      // transpose vectors back to columns
      transpose3x3(v_3x3, v_3x3);
      return;
    }
  }
 
  // the three eigenvalues are different, just sort the eigenvectors
  // to align them with the x, y, and z axes
 
  // find the vector with the largest x element, make that vector
  // the first vector
  maxVal = Math.abs(v_3x3[0]);
  maxI = 0;
  for (i = 1; i < 3; i++) {
    if (maxVal < (tmp = Math.abs(v_3x3[i * 3]))) {
      maxVal = tmp;
      maxI = i;
    }
  }
  // swap eigenvalue and eigenvector
  if (maxI !== 0) {
    const eigenValTmp = w_3[maxI];
    w_3[maxI] = w_3[0];
    w_3[0] = eigenValTmp;
    swapRowsMatrix_nxn(v_3x3, 3, maxI, 0);
  }
  // do the same for the y element
  if (Math.abs(v_3x3[4]) < Math.abs(v_3x3[7])) {
    const eigenValTmp = w_3[2];
    w_3[2] = w_3[1];
    w_3[1] = eigenValTmp;
    swapRowsMatrix_nxn(v_3x3, 3, 1, 2);
  }
 
  // ensure that the sign of the eigenvectors is correct
  for (i = 0; i < 2; i++) {
    if (v_3x3[i * 3 + i] < 0) {
      v_3x3[i * 3] = -v_3x3[i * 3];
      v_3x3[i * 3 + 1] = -v_3x3[i * 3 + 1];
      v_3x3[i * 3 + 2] = -v_3x3[i * 3 + 2];
    }
  }
  // set sign of final eigenvector to ensure that determinant is positive
  if (determinant3x3(v_3x3) < 0) {
    v_3x3[6] = -v_3x3[6];
    v_3x3[7] = -v_3x3[7];
    v_3x3[8] = -v_3x3[8];
  }
 
  // transpose the eigenvectors back again
  transpose3x3(v_3x3, v_3x3);
}
 
export function singularValueDecomposition3x3(a_3x3, u_3x3, w_3, vT_3x3) {
  let i;
  // copy so that A can be used for U or VT without risk
  const B = [...a_3x3];
 
  // temporarily flip if determinant is negative
  const d = determinant3x3(B);
  if (d < 0) {
    for (i = 0; i < 9; i++) {
      B[i] = -B[i];
    }
  }
 
  // orthogonalize, diagonalize, etc.
  orthogonalize3x3(B, u_3x3);
  transpose3x3(B, B);
  multiply3x3_mat3(B, u_3x3, vT_3x3);
  diagonalize3x3(vT_3x3, w_3, vT_3x3);
  multiply3x3_mat3(u_3x3, vT_3x3, u_3x3);
  transpose3x3(vT_3x3, vT_3x3);
 
  // re-create the flip
  if (d < 0) {
    w_3[0] = -w_3[0];
    w_3[1] = -w_3[1];
    w_3[2] = -w_3[2];
  }
}
 
/**
 * Factor linear equations Ax = b using LU decomposition A = LU. Output factorization LU is in matrix A.
 * @param {Matrix} A square matrix
 * @param {Number} index integer array of pivot indices index[0->n-1]
 * @param {Number} size matrix size
 */
export function luFactorLinearSystem(A, index, size) {
  let i;
  let j;
  let k;
  let largest;
  let maxI = 0;
  let sum;
  let temp1;
  let temp2;
  const scale = createArray(size);
 
  //
  // Loop over rows to get implicit scaling information
  //
  for (i = 0; i < size; i++) {
    for (largest = 0.0, j = 0; j < size; j++) {
      if ((temp2 = Math.abs(A[i * size + j])) > largest) {
        largest = temp2;
      }
    }
 
    Iif (largest === 0.0) {
      vtkWarningMacro('Unable to factor linear system');
      return 0;
    }
    scale[i] = 1.0 / largest;
  }
  //
  // Loop over all columns using Crout's method
  //
  for (j = 0; j < size; j++) {
    for (i = 0; i < j; i++) {
      sum = A[i * size + j];
      for (k = 0; k < i; k++) {
        sum -= A[i * size + k] * A[k * size + j];
      }
      A[i * size + j] = sum;
    }
    //
    // Begin search for largest pivot element
    //
    for (largest = 0.0, i = j; i < size; i++) {
      sum = A[i * size + j];
      for (k = 0; k < j; k++) {
        sum -= A[i * size + k] * A[k * size + j];
      }
      A[i * size + j] = sum;
 
      if ((temp1 = scale[i] * Math.abs(sum)) >= largest) {
        largest = temp1;
        maxI = i;
      }
    }
    //
    // Check for row interchange
    //
    if (j !== maxI) {
      for (k = 0; k < size; k++) {
        temp1 = A[maxI * size + k];
        A[maxI * size + k] = A[j * size + k];
        A[j * size + k] = temp1;
      }
      scale[maxI] = scale[j];
    }
    //
    // Divide by pivot element and perform elimination
    //
    index[j] = maxI;
 
    Iif (Math.abs(A[j * size + j]) <= VTK_SMALL_NUMBER) {
      vtkWarningMacro('Unable to factor linear system');
      return 0;
    }
 
    if (j !== size - 1) {
      temp1 = 1.0 / A[j * size + j];
      for (i = j + 1; i < size; i++) {
        A[i * size + j] *= temp1;
      }
    }
  }
  return 1;
}
 
export function luSolveLinearSystem(A, index, x, size) {
  let i;
  let j;
  let ii;
  let idx;
  let sum;
  //
  // Proceed with forward and backsubstitution for L and U
  // matrices.  First, forward substitution.
  //
  for (ii = -1, i = 0; i < size; i++) {
    idx = index[i];
    sum = x[idx];
    x[idx] = x[i];
 
    if (ii >= 0) {
      for (j = ii; j <= i - 1; j++) {
        sum -= A[i * size + j] * x[j];
      }
    } else if (sum !== 0.0) {
      ii = i;
    }
 
    x[i] = sum;
  }
  //
  // Now, back substitution
  //
  for (i = size - 1; i >= 0; i--) {
    sum = x[i];
    for (j = i + 1; j < size; j++) {
      sum -= A[i * size + j] * x[j];
    }
    x[i] = sum / A[i * size + i];
  }
}
 
export function solveLinearSystem(A, x, size) {
  // if we solving something simple, just solve it
  if (size === 2) {
    const y = createArray(2);
    const det = determinant2x2(A[0], A[1], A[2], A[3]);
 
    if (det === 0.0) {
      // Unable to solve linear system
      return 0;
    }
 
    y[0] = (A[3] * x[0] - A[1] * x[1]) / det;
    y[1] = (-(A[2] * x[0]) + A[0] * x[1]) / det;
 
    x[0] = y[0];
    x[1] = y[1];
    return 1;
  }
 
  if (size === 1) {
    if (A[0] === 0.0) {
      // Unable to solve linear system
      return 0;
    }
 
    x[0] /= A[0];
    return 1;
  }
 
  //
  // System of equations is not trivial, use Crout's method
  //
 
  // Check on allocation of working vectors
  const index = createArray(size);
 
  // Factor and solve matrix
  Iif (luFactorLinearSystem(A, index, size) === 0) {
    return 0;
  }
  luSolveLinearSystem(A, index, x, size);
 
  return 1;
}
 
// Note that A is modified during the inversion !
export function invertMatrix(A, AI, size, index = null, column = null) {
  const tmp1Size = index || createArray(size);
  const tmp2Size = column || createArray(size);
 
  // Factor matrix; then begin solving for inverse one column at a time.
  // Note: tmp1Size returned value is used later, tmp2Size is just working
  // memory whose values are not used in LUSolveLinearSystem
  Iif (luFactorLinearSystem(A, tmp1Size, size, tmp2Size) === 0) {
    return null;
  }
 
  for (let j = 0; j < size; j++) {
    for (let i = 0; i < size; i++) {
      tmp2Size[i] = 0.0;
    }
    tmp2Size[j] = 1.0;
 
    luSolveLinearSystem(A, tmp1Size, tmp2Size, size);
 
    for (let i = 0; i < size; i++) {
      AI[i * size + j] = tmp2Size[i];
    }
  }
 
  return AI;
}
 
export function estimateMatrixCondition(A, size) {
  let minValue = +Number.MAX_VALUE;
  let maxValue = -Number.MAX_VALUE;
 
  // find the maximum value
  for (let i = 0; i < size; i++) {
    for (let j = i; j < size; j++) {
      if (Math.abs(A[i * size + j]) > maxValue) {
        maxValue = Math.abs(A[i * size + j]);
      }
    }
  }
 
  // find the minimum diagonal value
  for (let i = 0; i < size; i++) {
    if (Math.abs(A[i * size + i]) < minValue) {
      minValue = Math.abs(A[i * size + i]);
    }
  }
 
  if (minValue === 0.0) {
    return Number.MAX_VALUE;
  }
  return maxValue / minValue;
}
 
export function jacobi(a_3x3, w, v) {
  return jacobiN(a_3x3, 3, w, v);
}
 
export function solveHomogeneousLeastSquares(numberOfSamples, xt, xOrder, mt) {
  // check dimensional consistency
  if (numberOfSamples < xOrder) {
    vtkWarningMacro('Insufficient number of samples. Underdetermined.');
    return 0;
  }
 
  let i;
  let j;
  let k;
 
  // set up intermediate variables
  // Allocate matrix to hold X times transpose of X
  const XXt = createArray(xOrder * xOrder); // size x by x
  // Allocate the array of eigenvalues and eigenvectors
  const eigenvals = createArray(xOrder);
  const eigenvecs = createArray(xOrder * xOrder);
 
  // Calculate XXt upper half only, due to symmetry
  for (k = 0; k < numberOfSamples; k++) {
    for (i = 0; i < xOrder; i++) {
      for (j = i; j < xOrder; j++) {
        XXt[i * xOrder + j] += xt[k * xOrder + i] * xt[k * xOrder + j];
      }
    }
  }
 
  // now fill in the lower half of the XXt matrix
  for (i = 0; i < xOrder; i++) {
    for (j = 0; j < i; j++) {
      XXt[i * xOrder + j] = XXt[j * xOrder + i];
    }
  }
 
  // Compute the eigenvectors and eigenvalues
  jacobiN(XXt, xOrder, eigenvals, eigenvecs);
 
  // Smallest eigenval is at the end of the list (xOrder-1), and solution is
  // corresponding eigenvec.
  for (i = 0; i < xOrder; i++) {
    mt[i] = eigenvecs[i * xOrder + xOrder - 1];
  }
 
  return 1;
}
 
export function solveLeastSquares(
  numberOfSamples,
  xt,
  xOrder,
  yt,
  yOrder,
  mt,
  checkHomogeneous = true
) {
  // check dimensional consistency
  if (numberOfSamples < xOrder || numberOfSamples < yOrder) {
    vtkWarningMacro('Insufficient number of samples. Underdetermined.');
    return 0;
  }
 
  const homogenFlags = createArray(yOrder);
  let allHomogeneous = 1;
  let hmt;
  let homogRC = 0;
  let i;
  let j;
  let k;
  let someHomogeneous = 0;
 
  // Ok, first init some flags check and see if all the systems are homogeneous
  if (checkHomogeneous) {
    // If Y' is zero, it's a homogeneous system and can't be solved via
    // the pseudoinverse method. Detect this case, warn the user, and
    // invoke SolveHomogeneousLeastSquares instead. Note that it doesn't
    // really make much sense for yOrder to be greater than one in this case,
    // since that's just yOrder occurrences of a 0 vector on the RHS, but
    // we allow it anyway. N
 
    // Initialize homogeneous flags on a per-right-hand-side basis
    for (j = 0; j < yOrder; j++) {
      homogenFlags[j] = 1;
    }
    for (i = 0; i < numberOfSamples; i++) {
      for (j = 0; j < yOrder; j++) {
        if (Math.abs(yt[i * yOrder + j]) > VTK_SMALL_NUMBER) {
          allHomogeneous = 0;
          homogenFlags[j] = 0;
        }
      }
    }
 
    // If we've got one system, and it's homogeneous, do it and bail out quickly.
    if (allHomogeneous && yOrder === 1) {
      vtkWarningMacro(
        'Detected homogeneous system (Y=0), calling SolveHomogeneousLeastSquares()'
      );
      return solveHomogeneousLeastSquares(numberOfSamples, xt, xOrder, mt);
    }
 
    // Ok, we've got more than one system of equations.
    // Figure out if we need to calculate the homogeneous equation solution for
    // any of them.
    Iif (allHomogeneous) {
      someHomogeneous = 1;
    } else {
      for (j = 0; j < yOrder; j++) {
        Iif (homogenFlags[j]) {
          someHomogeneous = 1;
        }
      }
    }
  }
 
  // If necessary, solve the homogeneous problem
  Iif (someHomogeneous) {
    // hmt is the homogeneous equation version of mt, the general solution.
    // hmt should be xOrder x yOrder, but since we are solving only the homogeneous part, here it is xOrder x 1
    hmt = createArray(xOrder);
 
    // Ok, solve the homogeneous problem
    homogRC = solveHomogeneousLeastSquares(numberOfSamples, xt, xOrder, hmt);
  }
 
  // set up intermediate variables
  const XXt = createArray(xOrder * xOrder); // size x by x
  const XXtI = createArray(xOrder * xOrder); // size x by x
  const XYt = createArray(xOrder * yOrder); // size x by y
 
  // first find the pseudoinverse matrix
  for (k = 0; k < numberOfSamples; k++) {
    for (i = 0; i < xOrder; i++) {
      // first calculate the XXt matrix, only do the upper half (symmetrical)
      for (j = i; j < xOrder; j++) {
        XXt[i * xOrder + j] += xt[k * xOrder + i] * xt[k * xOrder + j];
      }
 
      // now calculate the XYt matrix
      for (j = 0; j < yOrder; j++) {
        XYt[i * yOrder + j] += xt[k * xOrder + i] * yt[k * yOrder + j];
      }
    }
  }
 
  // now fill in the lower half of the XXt matrix
  for (i = 0; i < xOrder; i++) {
    for (j = 0; j < i; j++) {
      XXt[i * xOrder + j] = XXt[j * xOrder + i];
    }
  }
 
  const successFlag = invertMatrix(XXt, XXtI, xOrder);
 
  // next get the inverse of XXt
  if (successFlag) {
    for (i = 0; i < xOrder; i++) {
      for (j = 0; j < yOrder; j++) {
        mt[i * yOrder + j] = 0.0;
        for (k = 0; k < xOrder; k++) {
          mt[i * yOrder + j] += XXtI[i * xOrder + k] * XYt[k * yOrder + j];
        }
      }
    }
  }
 
  // Fix up any of the solutions that correspond to the homogeneous equation
  // problem.
  Iif (someHomogeneous) {
    for (j = 0; j < yOrder; j++) {
      if (homogenFlags[j]) {
        // Fix this one
        for (i = 0; i < xOrder; i++) {
          mt[i * yOrder + j] = hmt[i * yOrder];
        }
      }
    }
  }
 
  Iif (someHomogeneous) {
    return homogRC && successFlag;
  }
 
  return successFlag;
}
 
export function hex2float(hexStr, outFloatArray = [0, 0.5, 1]) {
  switch (hexStr.length) {
    case 3: // abc => #aabbcc
      outFloatArray[0] = (parseInt(hexStr[0], 16) * 17) / 255;
      outFloatArray[1] = (parseInt(hexStr[1], 16) * 17) / 255;
      outFloatArray[2] = (parseInt(hexStr[2], 16) * 17) / 255;
      return outFloatArray;
    case 4: // #abc => #aabbcc
      outFloatArray[0] = (parseInt(hexStr[1], 16) * 17) / 255;
      outFloatArray[1] = (parseInt(hexStr[2], 16) * 17) / 255;
      outFloatArray[2] = (parseInt(hexStr[3], 16) * 17) / 255;
      return outFloatArray;
    case 6: // ab01df => #ab01df
      outFloatArray[0] = parseInt(hexStr.substr(0, 2), 16) / 255;
      outFloatArray[1] = parseInt(hexStr.substr(2, 2), 16) / 255;
      outFloatArray[2] = parseInt(hexStr.substr(4, 2), 16) / 255;
      return outFloatArray;
    case 7: // #ab01df
      outFloatArray[0] = parseInt(hexStr.substr(1, 2), 16) / 255;
      outFloatArray[1] = parseInt(hexStr.substr(3, 2), 16) / 255;
      outFloatArray[2] = parseInt(hexStr.substr(5, 2), 16) / 255;
      return outFloatArray;
    case 9: // #ab01df00
      outFloatArray[0] = parseInt(hexStr.substr(1, 2), 16) / 255;
      outFloatArray[1] = parseInt(hexStr.substr(3, 2), 16) / 255;
      outFloatArray[2] = parseInt(hexStr.substr(5, 2), 16) / 255;
      outFloatArray[3] = parseInt(hexStr.substr(7, 2), 16) / 255;
      return outFloatArray;
    default:
      return outFloatArray;
  }
}
 
export function rgb2hsv(rgb, hsv) {
  let h;
  let s;
  const [r, g, b] = rgb;
  const onethird = 1.0 / 3.0;
  const onesixth = 1.0 / 6.0;
  const twothird = 2.0 / 3.0;
 
  let cmax = r;
  let cmin = r;
 
  if (g > cmax) {
    cmax = g;
  } else if (g < cmin) {
    cmin = g;
  }
  if (b > cmax) {
    cmax = b;
  } else if (b < cmin) {
    cmin = b;
  }
  const v = cmax;
 
  if (v > 0.0) {
    s = (cmax - cmin) / cmax;
  } else E{
    s = 0.0;
  }
  if (s > 0) {
    if (r === cmax) {
      h = (onesixth * (g - b)) / (cmax - cmin);
    } else if (g === cmax) {
      h = onethird + (onesixth * (b - r)) / (cmax - cmin);
    } else {
      h = twothird + (onesixth * (r - g)) / (cmax - cmin);
    }
    if (h < 0.0) {
      h += 1.0;
    }
  } else E{
    h = 0.0;
  }
 
  // Set the values back to the array
  hsv[0] = h;
  hsv[1] = s;
  hsv[2] = v;
}
 
export function hsv2rgb(hsv, rgb) {
  const [h, s, v] = hsv;
  const onethird = 1.0 / 3.0;
  const onesixth = 1.0 / 6.0;
  const twothird = 2.0 / 3.0;
  const fivesixth = 5.0 / 6.0;
  let r;
  let g;
  let b;
 
  // compute RGB from HSV
  if (h > onesixth && h <= onethird) {
    // green/red
    g = 1.0;
    r = (onethird - h) / onesixth;
    b = 0.0;
  } else if (h > onethird && h <= 0.5) {
    // green/blue
    g = 1.0;
    b = (h - onethird) / onesixth;
    r = 0.0;
  } else if (h > 0.5 && h <= twothird) {
    // blue/green
    b = 1.0;
    g = (twothird - h) / onesixth;
    r = 0.0;
  } else if (h > twothird && h <= fivesixth) {
    // blue/red
    b = 1.0;
    r = (h - twothird) / onesixth;
    g = 0.0;
  } else if (h > fivesixth && h <= 1.0) {
    // red/blue
    r = 1.0;
    b = (1.0 - h) / onesixth;
    g = 0.0;
  } else {
    // red/green
    r = 1.0;
    g = h / onesixth;
    b = 0.0;
  }
 
  // add Saturation to the equation.
  r = s * r + (1.0 - s);
  g = s * g + (1.0 - s);
  b = s * b + (1.0 - s);
 
  r *= v;
  g *= v;
  b *= v;
 
  // Assign back to the array
  rgb[0] = r;
  rgb[1] = g;
  rgb[2] = b;
}
 
export function lab2xyz(lab, xyz) {
  // LAB to XYZ
  const [L, a, b] = lab;
  let var_Y = (L + 16) / 116;
  let var_X = a / 500 + var_Y;
  let var_Z = var_Y - b / 200;
 
  if (var_Y ** 3 > 0.008856) {
    var_Y **= 3;
  } else {
    var_Y = (var_Y - 16.0 / 116.0) / 7.787;
  }
 
  if (var_X ** 3 > 0.008856) {
    var_X **= 3;
  } else {
    var_X = (var_X - 16.0 / 116.0) / 7.787;
  }
 
  if (var_Z ** 3 > 0.008856) {
    var_Z **= 3;
  } else {
    var_Z = (var_Z - 16.0 / 116.0) / 7.787;
  }
  const ref_X = 0.9505;
  const ref_Y = 1.0;
  const ref_Z = 1.089;
  xyz[0] = ref_X * var_X; // ref_X = 0.9505  Observer= 2 deg Illuminant= D65
  xyz[1] = ref_Y * var_Y; // ref_Y = 1.000
  xyz[2] = ref_Z * var_Z; // ref_Z = 1.089
}
 
export function xyz2lab(xyz, lab) {
  const [x, y, z] = xyz;
  const ref_X = 0.9505;
  const ref_Y = 1.0;
  const ref_Z = 1.089;
  let var_X = x / ref_X; // ref_X = 0.9505  Observer= 2 deg, Illuminant= D65
  let var_Y = y / ref_Y; // ref_Y = 1.000
  let var_Z = z / ref_Z; // ref_Z = 1.089
 
  if (var_X > 0.008856) var_X **= 1.0 / 3.0;
  else var_X = 7.787 * var_X + 16.0 / 116.0;
  if (var_Y > 0.008856) var_Y **= 1.0 / 3.0;
  else var_Y = 7.787 * var_Y + 16.0 / 116.0;
  if (var_Z > 0.008856) var_Z **= 1.0 / 3.0;
  else var_Z = 7.787 * var_Z + 16.0 / 116.0;
 
  lab[0] = 116 * var_Y - 16;
  lab[1] = 500 * (var_X - var_Y);
  lab[2] = 200 * (var_Y - var_Z);
}
 
export function xyz2rgb(xyz, rgb) {
  const [x, y, z] = xyz;
  let r = x * 3.2406 + y * -1.5372 + z * -0.4986;
  let g = x * -0.9689 + y * 1.8758 + z * 0.0415;
  let b = x * 0.0557 + y * -0.204 + z * 1.057;
 
  // The following performs a "gamma correction" specified by the sRGB color
  // space.  sRGB is defined by a canonical definition of a display monitor and
  // has been standardized by the International Electrotechnical Commission (IEC
  // 61966-2-1).  The nonlinearity of the correction is designed to make the
  // colors more perceptually uniform.  This color space has been adopted by
  // several applications including Adobe Photoshop and Microsoft Windows color
  // management.  OpenGL is agnostic on its RGB color space, but it is reasonable
  // to assume it is close to this one.
  if (r > 0.0031308) r = 1.055 * r ** (1 / 2.4) - 0.055;
  else r *= 12.92;
  if (g > 0.0031308) g = 1.055 * g ** (1 / 2.4) - 0.055;
  else g *= 12.92;
  if (b > 0.0031308) b = 1.055 * b ** (1 / 2.4) - 0.055;
  else b *= 12.92;
 
  // Clip colors. ideally we would do something that is perceptually closest
  // (since we can see colors outside of the display gamut), but this seems to
  // work well enough.
  let maxVal = r;
  if (maxVal < g) maxVal = g;
  if (maxVal < b) maxVal = b;
  if (maxVal > 1.0) {
    r /= maxVal;
    g /= maxVal;
    b /= maxVal;
  }
  if (r < 0) r = 0;
  if (g < 0) g = 0;
  if (b < 0) b = 0;
 
  // Push values back to array
  rgb[0] = r;
  rgb[1] = g;
  rgb[2] = b;
}
 
export function rgb2xyz(rgb, xyz) {
  let [r, g, b] = rgb;
  // The following performs a "gamma correction" specified by the sRGB color
  // space.  sRGB is defined by a canonical definition of a display monitor and
  // has been standardized by the International Electrotechnical Commission (IEC
  // 61966-2-1).  The nonlinearity of the correction is designed to make the
  // colors more perceptually uniform.  This color space has been adopted by
  // several applications including Adobe Photoshop and Microsoft Windows color
  // management.  OpenGL is agnostic on its RGB color space, but it is reasonable
  // to assume it is close to this one.
  if (r > 0.04045) r = ((r + 0.055) / 1.055) ** 2.4;
  else r /= 12.92;
  if (g > 0.04045) g = ((g + 0.055) / 1.055) ** 2.4;
  else g /= 12.92;
  if (b > 0.04045) b = ((b + 0.055) / 1.055) ** 2.4;
  else b /= 12.92;
 
  // Observer. = 2 deg, Illuminant = D65
  xyz[0] = r * 0.4124 + g * 0.3576 + b * 0.1805;
  xyz[1] = r * 0.2126 + g * 0.7152 + b * 0.0722;
  xyz[2] = r * 0.0193 + g * 0.1192 + b * 0.9505;
}
 
export function rgb2lab(rgb, lab) {
  const xyz = [0, 0, 0];
  rgb2xyz(rgb, xyz);
  xyz2lab(xyz, lab);
}
 
export function lab2rgb(lab, rgb) {
  const xyz = [0, 0, 0];
  lab2xyz(lab, xyz);
  xyz2rgb(xyz, rgb);
}
 
export function uninitializeBounds(bounds) {
  bounds[0] = 1.0;
  bounds[1] = -1.0;
  bounds[2] = 1.0;
  bounds[3] = -1.0;
  bounds[4] = 1.0;
  bounds[5] = -1.0;
  return bounds;
}
 
export function areBoundsInitialized(bounds) {
  return !(bounds[1] - bounds[0] < 0.0);
}
 
/**
 * @deprecated please use vtkBoundingBox.addPoints(vtkBoundingBox.reset([]), points)
 */
export function computeBoundsFromPoints(point1, point2, bounds) {
  bounds[0] = Math.min(point1[0], point2[0]);
  bounds[1] = Math.max(point1[0], point2[0]);
  bounds[2] = Math.min(point1[1], point2[1]);
  bounds[3] = Math.max(point1[1], point2[1]);
  bounds[4] = Math.min(point1[2], point2[2]);
  bounds[5] = Math.max(point1[2], point2[2]);
  return bounds;
}
 
export function clampValue(value, minValue, maxValue) {
  if (value < minValue) {
    return minValue;
  }
  if (value > maxValue) {
    return maxValue;
  }
  return value;
}
 
export function clampVector(vector, minVector, maxVector, out = [0, 0, 0]) {
  out[0] = clampValue(vector[0], minVector[0], maxVector[0]);
  out[1] = clampValue(vector[1], minVector[1], maxVector[1]);
  out[2] = clampValue(vector[2], minVector[2], maxVector[2]);
 
  return out;
}
 
export function clampAndNormalizeValue(value, range) {
  let result = 0;
  if (range[0] !== range[1]) {
    // clamp
    if (value < range[0]) {
      result = range[0];
    } else if (value > range[1]) {
      result = range[1];
    } else {
      result = value;
    }
    // normalize
    result = (result - range[0]) / (range[1] - range[0]);
  }
 
  return result;
}
 
export const getScalarTypeFittingRange = notImplemented(
  'GetScalarTypeFittingRange'
);
export const getAdjustedScalarRange = notImplemented('GetAdjustedScalarRange');
 
export function extentIsWithinOtherExtent(extent1, extent2) {
  if (!extent1 || !extent2) {
    return 0;
  }
 
  for (let i = 0; i < 6; i += 2) {
    if (
      extent1[i] < extent2[i] ||
      extent1[i] > extent2[i + 1] ||
      extent1[i + 1] < extent2[i] ||
      extent1[i + 1] > extent2[i + 1]
    ) {
      return 0;
    }
  }
 
  return 1;
}
 
export function boundsIsWithinOtherBounds(bounds1_6, bounds2_6, delta_3) {
  if (!bounds1_6 || !bounds2_6) {
    return 0;
  }
  for (let i = 0; i < 6; i += 2) {
    if (
      bounds1_6[i] + delta_3[i / 2] < bounds2_6[i] ||
      bounds1_6[i] - delta_3[i / 2] > bounds2_6[i + 1] ||
      bounds1_6[i + 1] + delta_3[i / 2] < bounds2_6[i] ||
      bounds1_6[i + 1] - delta_3[i / 2] > bounds2_6[i + 1]
    ) {
      return 0;
    }
  }
  return 1;
}
 
export function pointIsWithinBounds(point_3, bounds_6, delta_3) {
  if (!point_3 || !bounds_6 || !delta_3) {
    return 0;
  }
  for (let i = 0; i < 3; i++) {
    if (
      point_3[i] + delta_3[i] < bounds_6[2 * i] ||
      point_3[i] - delta_3[i] > bounds_6[2 * i + 1]
    ) {
      return 0;
    }
  }
  return 1;
}
 
export function solve3PointCircle(p1, p2, p3, center) {
  const v21 = createArray(3);
  const v32 = createArray(3);
  const v13 = createArray(3);
  const v12 = createArray(3);
  const v23 = createArray(3);
  const v31 = createArray(3);
 
  for (let i = 0; i < 3; ++i) {
    v21[i] = p1[i] - p2[i];
    v32[i] = p2[i] - p3[i];
    v13[i] = p3[i] - p1[i];
    v12[i] = -v21[i];
    v23[i] = -v32[i];
    v31[i] = -v13[i];
  }
 
  const norm12 = norm(v12);
  const norm23 = norm(v23);
  const norm13 = norm(v13);
 
  const crossv21v32 = createArray(3);
  cross(v21, v32, crossv21v32);
  const normCross = norm(crossv21v32);
 
  const radius = (norm12 * norm23 * norm13) / (2 * normCross);
 
  const normCross22 = 2 * normCross * normCross;
  const alpha = (norm23 * norm23 * dot(v21, v31)) / normCross22;
  const beta = (norm13 * norm13 * dot(v12, v32)) / normCross22;
  const gamma = (norm12 * norm12 * dot(v13, v23)) / normCross22;
 
  for (let i = 0; i < 3; ++i) {
    center[i] = alpha * p1[i] + beta * p2[i] + gamma * p3[i];
  }
  return radius;
}
 
export const inf = Infinity;
export const negInf = -Infinity;
 
export const isInf = (value) => !Number.isFinite(value);
export const { isFinite, isNaN } = Number;
export const isNan = isNaN;
 
// JavaScript - add-on ----------------------
 
export function createUninitializedBounds() {
  return [].concat([
    Number.MAX_VALUE,
    -Number.MAX_VALUE, // X
    Number.MAX_VALUE,
    -Number.MAX_VALUE, // Y
    Number.MAX_VALUE,
    -Number.MAX_VALUE, // Z
  ]);
}
 
export function getMajorAxisIndex(vector) {
  let maxValue = -1;
  let axisIndex = -1;
  for (let i = 0; i < vector.length; i++) {
    const value = Math.abs(vector[i]);
    if (value > maxValue) {
      axisIndex = i;
      maxValue = value;
    }
  }
 
  return axisIndex;
}
 
// Return the closest orthogonal matrix of 1, -1 and 0
// It works for both column major and row major matrices
// This function iteratively associate a column with a row by choosing
// the greatest absolute value from the remaining row and columns
// For each association, a -1 or a 1 is set in the output, depending on
// the sign of the value in the original matrix
export function getSparseOrthogonalMatrix(matrix, n = 3) {
  // Initialize rows and columns to available indices
  const rows = new Array(n);
  const cols = new Array(n);
  for (let i = 0; i < n; ++i) {
    rows[i] = i;
    cols[i] = i;
  }
  // No need for the last iteration: i = 0
  for (let i = n - 1; i > 0; i--) {
    // Loop invariant:
    // rows[0:i] and cols[0:i] contain the remaining rows and columns
    // rows]i:n[ and cols]i:n[ contain the associations found (rows[k] is associated with cols[k])
    let bestValue = -Infinity;
    let bestRowI = 0;
    let bestColI = 0;
    for (let rowI = 0; rowI <= i; ++rowI) {
      const row = rows[rowI];
      for (let colI = 0; colI <= i; ++colI) {
        const col = cols[colI];
        const absVal = Math.abs(matrix[row + n * col]);
        if (absVal > bestValue) {
          bestValue = absVal;
          bestRowI = rowI;
          bestColI = colI;
        }
      }
    }
    // Found an association between rows[bestRowI] and cols[bestColI]
    // Put both at the end of their array by swapping with i
    [rows[i], rows[bestRowI]] = [rows[bestRowI], rows[i]];
    [cols[i], cols[bestColI]] = [cols[bestColI], cols[i]];
  }
 
  // Convert row/column association to a matrix
  const output = new Array(n * n).fill(0);
  for (let i = 0; i < n; ++i) {
    const matIdx = rows[i] + n * cols[i];
    output[matIdx] = matrix[matIdx] < 0 ? -1 : 1;
  }
 
  return output;
}
 
export function floatToHex2(value) {
  const integer = Math.floor(value * 255);
  if (integer > 15) {
    return integer.toString(16);
  }
  return `0${integer.toString(16)}`;
}
 
export function floatRGB2HexCode(rgbArray, prefix = '#') {
  return `${prefix}${rgbArray.map(floatToHex2).join('')}`;
}
 
function floatToChar(f) {
  return Math.round(f * 255);
}
 
export function float2CssRGBA(rgbArray) {
  if (rgbArray.length === 3) {
    return `rgb(${rgbArray.map(floatToChar).join(', ')})`;
  }
  return `rgba(${floatToChar(rgbArray[0] || 0)}, ${floatToChar(
    rgbArray[1] || 0
  )}, ${floatToChar(rgbArray[2] || 0)}, ${rgbArray[3] || 0})`;
}
 
// ----------------------------------------------------------------------------
// Only Static API
// ----------------------------------------------------------------------------
 
export default {
  Pi,
  radiansFromDegrees,
  degreesFromRadians,
  round,
  floor,
  ceil,
  ceilLog2,
  min,
  max,
  arrayMin,
  arrayMax,
  arrayRange,
  isPowerOfTwo,
  nearestPowerOfTwo,
  factorial,
  binomial,
  beginCombination,
  nextCombination,
  randomSeed,
  getSeed,
  random,
  gaussian,
  add,
  subtract,
  multiplyScalar,
  multiplyScalar2D,
  multiplyAccumulate,
  multiplyAccumulate2D,
  dot,
  outer,
  cross,
  norm,
  normalize,
  perpendiculars,
  projectVector,
  projectVector2D,
  distance2BetweenPoints,
  angleBetweenVectors,
  gaussianAmplitude,
  gaussianWeight,
  dot2D,
  outer2D,
  norm2D,
  normalize2D,
  determinant2x2,
  LUFactor3x3,
  LUSolve3x3,
  linearSolve3x3,
  multiply3x3_vect3,
  multiply3x3_mat3,
  multiplyMatrix,
  transpose3x3,
  invert3x3,
  identity3x3,
  identity,
  isIdentity,
  isIdentity3x3,
  determinant3x3,
  quaternionToMatrix3x3,
  areEquals,
  areMatricesEqual,
  roundNumber,
  roundVector,
  matrix3x3ToQuaternion,
  multiplyQuaternion,
  orthogonalize3x3,
  diagonalize3x3,
  singularValueDecomposition3x3,
  solveLinearSystem,
  invertMatrix,
  luFactorLinearSystem,
  luSolveLinearSystem,
  estimateMatrixCondition,
  jacobi,
  jacobiN,
  solveHomogeneousLeastSquares,
  solveLeastSquares,
  hex2float,
  rgb2hsv,
  hsv2rgb,
  lab2xyz,
  xyz2lab,
  xyz2rgb,
  rgb2xyz,
  rgb2lab,
  lab2rgb,
  uninitializeBounds,
  areBoundsInitialized,
  computeBoundsFromPoints,
  clampValue,
  clampVector,
  clampAndNormalizeValue,
  getScalarTypeFittingRange,
  getAdjustedScalarRange,
  extentIsWithinOtherExtent,
  boundsIsWithinOtherBounds,
  pointIsWithinBounds,
  solve3PointCircle,
  inf,
  negInf,
  isInf,
  isNan: isNaN,
  isNaN,
  isFinite,
 
  // JS add-on
  createUninitializedBounds,
  getMajorAxisIndex,
  getSparseOrthogonalMatrix,
  floatToHex2,
  floatRGB2HexCode,
  float2CssRGBA,
};