All files / engine/Source/Scene VoxelPrimitive.js

86.78% Statements 427/492
73.23% Branches 104/142
88.73% Functions 63/71
87.11% Lines 426/489

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                                                                                                        39x           39x           39x               39x           39x           39x               39x           39x               39x               39x               39x               39x               39x               39x                 39x               39x                 39x               39x                 39x               39x                 39x               39x               39x               39x               39x               39x               39x               39x           39x             39x           39x           39x           39x           39x           39x             39x           39x             39x           39x             39x           39x           39x           39x           39x           39x             39x           39x           39x           39x           39x                                                                       39x             39x   39x 39x 39x 1092x 1092x 1092x                                         39x                             39x                       39x                         39x                                                   39x                               39x                                   39x     39x 39x                 39x   39x 39x 39x 39x   39x     39x 39x 39x     1x                   5x                         116x                         16x                                                   4x                                       43x                           54x                                                   64x                         64x                         1x                         1x                       1x       1x     1x                                                             2x       1x     1x                       2x       1x     1x 1x 1x                         2x       1x     1x 1x 1x                               2x       1x     1x                             82x       1x     1x                           2x       1x     1x                         3x       39x     39x                         3x       39x     39x                         5x       40x     40x                               5x       40x     40x                             16x       1x                         3x     2x   2x 2x 2x 2x                   2x 1x   1x   2x                                                     227x         1x 1x 1x 1x 1x 1x               1x 110x 110x     110x     110x 110x 38x     38x 34x 34x       38x           72x 72x 72x 3x 3x       72x 3x     69x     69x         69x 69x   69x             69x 15x     69x 53x     16x     1x     16x         16x 10x 10x       16x 16x       16x 16x 4x 4x       4x       16x 13x 13x         16x 16x 16x               16x       16x           16x       16x 16x           16x           16x 16x         16x         16x         16x         16x             16x           16x   16x     16x         16x 16x       16x 16x 16x 14x   2x 2x                         16x         16x 16x   16x                 1x 1x 1x                     72x   72x         69x     3x 3x   3x                     38x   38x 38x   38x 38x     38x 38x 515x 515x     515x             515x               38x       38x       38x       38x       38x       38x       38x         38x         38x 3x 3x 3x   38x       38x     38x 38x 38x   38x                     111x         111x                         555x 555x   555x 555x 156x   555x     1x 1x 1x 1x 1x 1x                 42x   42x 42x       42x       42x       42x       42x         42x   34x         34x         34x         34x             8x           8x         8x             42x 42x 42x     42x         42x           42x 42x             42x 3x     39x       39x       39x         39x     1x                   8x   8x           8x     8x       8x         8x             8x 8x         8x 8x           8x           8x                             38x 38x       38x   38x 38x 38x 38x 38x 38x     38x       38x       38x       38x       38x                         3x 3x 33x   3x     3x                       69x 69x                                                                                       16x 16x 16x                                                                                                         1x 52x                                   1x 34x 34x 10x     34x 34x 10x       34x 34x 34x 34x   34x     1x                   1x                                                     1x                                                               16x         16x           16x 16x 16x 16x       16x 16x 16x 128x             16x 128x 128x   128x 128x 128x 128x 128x 128x                                                                 16x 16x 16x 16x 16x   16x     1x 1x 1x 1x                         1x 1x 1x     27x                       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       1x       1x 1x 1x 1x 1x   1x   1x             1x   1x   1x 1x           1x           1x             1x                       1x                 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x       1x 1x     1x      
import buildVoxelDrawCommands from "./buildVoxelDrawCommands.js";
import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import Cartesian4 from "../Core/Cartesian4.js";
import Cartographic from "../Core/Cartographic.js";
import Cesium3DTilesetStatistics from "./Cesium3DTilesetStatistics.js";
import CesiumMath from "../Core/Math.js";
import Check from "../Core/Check.js";
import Color from "../Core/Color.js";
import ClippingPlaneCollection from "./ClippingPlaneCollection.js";
import clone from "../Core/clone.js";
import CustomShader from "./Model/CustomShader.js";
import Frozen from "../Core/Frozen.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import Event from "../Core/Event.js";
import JulianDate from "../Core/JulianDate.js";
import Material from "./Material.js";
import Matrix3 from "../Core/Matrix3.js";
import Matrix4 from "../Core/Matrix4.js";
import MetadataComponentType from "./MetadataComponentType.js";
import MetadataType from "./MetadataType.js";
import oneTimeWarning from "../Core/oneTimeWarning.js";
import PolylineCollection from "./PolylineCollection.js";
import VerticalExaggeration from "../Core/VerticalExaggeration.js";
import VoxelContent from "./VoxelContent.js";
import VoxelShapeType from "./VoxelShapeType.js";
import VoxelTraversal from "./VoxelTraversal.js";
import VoxelMetadataOrder from "./VoxelMetadataOrder.js";
 
/**
 * A primitive that renders voxel data from a {@link VoxelProvider}.
 *
 * @alias VoxelPrimitive
 * @constructor
 *
 * @param {object} [options] Object with the following properties:
 * @param {VoxelProvider} [options.provider] The voxel provider that supplies the primitive with tile data.
 * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The model matrix used to transform the primitive.
 * @param {CustomShader} [options.customShader] The custom shader used to style the primitive.
 * @param {Clock} [options.clock] The clock used to control time dynamic behavior.
 * @param {boolean} [options.calculateStatistics] Generate statistics for performance profile.
 *
 * @see VoxelProvider
 * @see Cesium3DTilesVoxelProvider
 * @see VoxelShapeType
 * @see {@link https://github.com/CesiumGS/cesium/tree/main/Documentation/CustomShaderGuide|Custom Shader Guide}
 *
 * @experimental This feature is not final and is subject to change without Cesium's standard deprecation policy.
 */
function VoxelPrimitive(options) {
  options = options ?? Frozen.EMPTY_OBJECT;
 
  /**
   * @type {boolean}
   * @private
   */
  this._ready = false;
 
  /**
   * @type {VoxelProvider}
   * @private
   */
  this._provider = options.provider ?? VoxelPrimitive.DefaultProvider;
 
  /**
   * This member is not created until the provider and shape are ready.
   *
   * @type {VoxelTraversal}
   * @private
   */
  this._traversal = undefined;
 
  /**
   * @type {Cesium3DTilesetStatistics}
   * @private
   */
  this._statistics = new Cesium3DTilesetStatistics();
 
  /**
   * @type {boolean}
   * @private
   */
  this._calculateStatistics = options.calculateStatistics ?? false;
 
  /**
   * This member is not created until the provider is ready.
   *
   * @type {VoxelShape}
   * @private
   */
  this._shape = undefined;
 
  /**
   * @type {boolean}
   * @private
   */
  this._shapeVisible = false;
 
  /**
   * This member is not created until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._dimensions = new Cartesian3();
 
  /**
   * This member is not created until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._inputDimensions = new Cartesian3();
 
  /**
   * This member is not created until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._paddingBefore = new Cartesian3();
 
  /**
   * This member is not created until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._paddingAfter = new Cartesian3();
 
  /**
   * This member is not known until the provider is ready.
   *
   * @type {number}
   * @private
   */
  this._availableLevels = 1;
 
  /**
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._minBounds = new Cartesian3();
 
  /**
   * Used to detect if the shape is dirty.
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._minBoundsOld = new Cartesian3();
 
  /**
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._maxBounds = new Cartesian3();
 
  /**
   * Used to detect if the shape is dirty.
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._maxBoundsOld = new Cartesian3();
 
  /**
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._minClippingBounds = new Cartesian3();
 
  /**
   * Used to detect if the clipping is dirty.
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._minClippingBoundsOld = new Cartesian3();
 
  /**
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._maxClippingBounds = new Cartesian3();
 
  /**
   * Used to detect if the clipping is dirty.
   * This member is not known until the provider is ready.
   *
   * @type {Cartesian3}
   * @private
   */
  this._maxClippingBoundsOld = new Cartesian3();
 
  /**
   * Vertical exaggeration applied to the voxel shape
   *
   * @type {number}
   * @private
   */
  this._verticalExaggeration = 1.0;
 
  /**
   * The height relative to which the shape is exaggerated.
   *
   * @type {number}
   * @private
   */
  this._verticalExaggerationRelativeHeight = 0.0;
 
  /**
   * Clipping planes on the primitive
   *
   * @type {ClippingPlaneCollection}
   * @private
   */
  this._clippingPlanes = undefined;
 
  /**
   * Keeps track of when the clipping planes change
   *
   * @type {number}
   * @private
   */
  this._clippingPlanesState = 0;
 
  /**
   * Keeps track of when the clipping planes are enabled / disabled
   *
   * @type {boolean}
   * @private
   */
  this._clippingPlanesEnabled = false;
 
  /**
   * The primitive's model matrix.
   *
   * @type {Matrix4}
   * @private
   */
  this._modelMatrix = Matrix4.clone(options.modelMatrix ?? Matrix4.IDENTITY);
 
  /**
   * Used to detect if the model matrix is dirty.
   *
   * @type {Matrix4}
   * @private
   */
  this._modelMatrixOld = Matrix4.clone(this._modelMatrix);
 
  /**
   * @type {CustomShader}
   * @private
   */
  this._customShader =
    options.customShader ?? VoxelPrimitive.DefaultCustomShader;
 
  /**
   * @type {Event}
   * @private
   */
  this._customShaderCompilationEvent = new Event();
 
  /**
   * @type {boolean}
   * @private
   */
  this._shaderDirty = true;
 
  /**
   * @type {DrawCommand}
   * @private
   */
  this._drawCommand = undefined;
 
  /**
   * @type {DrawCommand}
   * @private
   */
  this._drawCommandPick = undefined;
 
  /**
   * @type {object}
   * @private
   */
  this._pickId = undefined;
 
  /**
   * @type {Clock}
   * @private
   */
  this._clock = options.clock;
 
  // Transforms and other values that are computed when the shape changes
  /**
   * @type {Matrix4}
   * @private
   */
  this._transformPositionLocalToWorld = new Matrix4();
 
  /**
   * @type {Matrix4}
   * @private
   */
  this._transformPositionWorldToLocal = new Matrix4();
 
  /**
   * Transforms a plane in Hessian normal form from local space to view space.
   * @type {Matrix4}
   * @private
   */
  this._transformPlaneLocalToView = new Matrix4();
 
  /**
   * @type {Matrix3}
   * @private
   */
  this._transformDirectionWorldToLocal = new Matrix3();
 
  // Rendering
  /**
   * @type {boolean}
   * @private
   */
  this._nearestSampling = false;
 
  /**
   * @type {number}
   * @private
   */
  this._levelBlendFactor = 0.0;
 
  /**
   * @type {number}
   * @private
   */
  this._stepSizeMultiplier = 1.0;
 
  /**
   * @type {boolean}
   * @private
   */
  this._depthTest = true;
 
  /**
   * @type {boolean}
   * @private
   */
  this._useLogDepth = undefined;
 
  /**
   * @type {number}
   * @private
   */
  this._screenSpaceError = 4.0; // in pixels
 
  // Debug / statistics
  /**
   * @type {PolylineCollection}
   * @private
   */
  this._debugPolylines = new PolylineCollection();
 
  /**
   * @type {boolean}
   * @private
   */
  this._debugDraw = false;
 
  /**
   * @type {boolean}
   * @private
   */
  this._disableRender = false;
 
  /**
   * @type {boolean}
   * @private
   */
  this._disableUpdate = false;
 
  /**
   * @type {Object<string, any>}
   * @private
   */
  this._uniforms = {
    octreeInternalNodeTexture: undefined,
    octreeInternalNodeTilesPerRow: 0,
    octreeInternalNodeTexelSizeUv: new Cartesian2(),
    octreeLeafNodeTexture: undefined,
    octreeLeafNodeTilesPerRow: 0,
    octreeLeafNodeTexelSizeUv: new Cartesian2(),
    megatextureTextures: [],
    megatextureSliceDimensions: new Cartesian2(),
    megatextureTileDimensions: new Cartesian2(),
    megatextureVoxelSizeUv: new Cartesian2(),
    megatextureSliceSizeUv: new Cartesian2(),
    megatextureTileSizeUv: new Cartesian2(),
    dimensions: new Cartesian3(),
    inputDimensions: new Cartesian3(),
    paddingBefore: new Cartesian3(),
    paddingAfter: new Cartesian3(),
    transformPositionViewToLocal: new Matrix4(),
    transformDirectionViewToLocal: new Matrix3(),
    cameraPositionLocal: new Cartesian3(),
    cameraDirectionLocal: new Cartesian3(),
    cameraTileCoordinates: new Cartesian4(),
    cameraTileUv: new Cartesian3(),
    ndcSpaceAxisAlignedBoundingBox: new Cartesian4(),
    clippingPlanesTexture: undefined,
    clippingPlanesMatrix: new Matrix4(),
    renderBoundPlanesTexture: undefined,
    stepSize: 0,
    pickColor: new Color(),
  };
 
  /**
   * Shape specific shader defines from the previous shape update. Used to detect if the shader needs to be rebuilt.
   * @type {Object<string, any>}
   * @private
   */
  this._shapeDefinesOld = {};
 
  /**
   * Map uniform names to functions that return the uniform values.
   * @type {Object<string, function():any>}
   * @private
   */
  this._uniformMap = {};
 
  const uniforms = this._uniforms;
  const uniformMap = this._uniformMap;
  for (const key in uniforms) {
    Eif (uniforms.hasOwnProperty(key)) {
      const name = `u_${key}`;
      uniformMap[name] = function () {
        return uniforms[key];
      };
    }
  }
 
  /**
   * The event fired to indicate that a tile's content was loaded.
   * <p>
   * This event is fired during the tileset traversal while the frame is being rendered
   * so that updates to the tile take effect in the same frame.  Do not create or modify
   * Cesium entities or primitives during the event listener.
   * </p>
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.tileLoad.addEventListener(function() {
   *     console.log('A tile was loaded.');
   * });
   */
  this.tileLoad = new Event();
 
  /**
   * This event fires once for each visible tile in a frame.
   * <p>
   * This event is fired during the traversal while the frame is being rendered.
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.tileVisible.addEventListener(function() {
   *     console.log('A tile is visible.');
   * });
   *
   */
  this.tileVisible = new Event();
 
  /**
   * The event fired to indicate that a tile's content failed to load.
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.tileFailed.addEventListener(function() {
   *     console.log('An error occurred loading tile.');
   * });
   */
  this.tileFailed = new Event();
 
  /**
   * The event fired to indicate that a tile's content was unloaded.
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.tileUnload.addEventListener(function() {
   *     console.log('A tile was unloaded from the cache.');
   * });
   *
   */
  this.tileUnload = new Event();
 
  /**
   * The event fired to indicate progress of loading new tiles. This event is fired when a new tile
   * is requested, when a requested tile is finished downloading, and when a downloaded tile has been
   * processed and is ready to render.
   * <p>
   * The number of pending tile requests, <code>numberOfPendingRequests</code>, and number of tiles
   * processing, <code>numberOfTilesProcessing</code> are passed to the event listener.
   * </p>
   * <p>
   * This event is fired at the end of the frame after the scene is rendered.
   * </p>
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.loadProgress.addEventListener(function(numberOfPendingRequests, numberOfTilesProcessing) {
   *     if ((numberOfPendingRequests === 0) && (numberOfTilesProcessing === 0)) {
   *         console.log('Finished loading');
   *         return;
   *     }
   *
   *     console.log(`Loading: requests: ${numberOfPendingRequests}, processing: ${numberOfTilesProcessing}`);
   * });
   */
  this.loadProgress = new Event();
 
  /**
   * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. The voxel
   * primitive is completely loaded for this view.
   * <p>
   * This event is fired at the end of the frame after the scene is rendered.
   * </p>
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.allTilesLoaded.addEventListener(function() {
   *     console.log('All tiles are loaded');
   * });
   */
  this.allTilesLoaded = new Event();
 
  /**
   * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. This event
   * is fired once when all tiles in the initial view are loaded.
   * <p>
   * This event is fired at the end of the frame after the scene is rendered.
   * </p>
   *
   * @type {Event}
   *
   * @example
   * voxelPrimitive.initialTilesLoaded.addEventListener(function() {
   *     console.log('Initial tiles are loaded');
   * });
   *
   * @see Cesium3DTileset#allTilesLoaded
   */
  this.initialTilesLoaded = new Event();
 
  // If the provider fails to initialize the primitive will fail too.
  const provider = this._provider;
  initialize(this, provider);
}
 
function initialize(primitive, provider) {
  // Set the bounds
  const {
    shape: shapeType,
    minBounds = VoxelShapeType.getMinBounds(shapeType),
    maxBounds = VoxelShapeType.getMaxBounds(shapeType),
  } = provider;
 
  primitive.minBounds = minBounds;
  primitive.maxBounds = maxBounds;
  primitive.minClippingBounds = minBounds.clone();
  primitive.maxClippingBounds = maxBounds.clone();
 
  checkTransformAndBounds(primitive);
 
  // Create the shape object, and update it so it is valid for VoxelTraversal
  const ShapeConstructor = VoxelShapeType.getShapeConstructor(shapeType);
  primitive._shape = new ShapeConstructor();
  primitive._shapeVisible = updateShapeAndTransforms(primitive);
}
 
Object.defineProperties(VoxelPrimitive.prototype, {
  /**
   * Gets a value indicating whether or not the primitive is ready for use.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {boolean}
   * @readonly
   */
  ready: {
    get: function () {
      return this._ready;
    },
  },
 
  /**
   * Gets the {@link VoxelProvider} associated with this primitive.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {VoxelProvider}
   * @readonly
   */
  provider: {
    get: function () {
      return this._provider;
    },
  },
 
  /**
   * Gets the bounding sphere.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {BoundingSphere}
   * @readonly
   */
  boundingSphere: {
    get: function () {
      return this._shape.boundingSphere;
    },
  },
 
  /**
   * Gets the oriented bounding box.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {OrientedBoundingBox}
   * @readonly
   */
  orientedBoundingBox: {
    get: function () {
      return this._shape.orientedBoundingBox;
    },
  },
 
  /**
   * Gets the model matrix.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Matrix4}
   * @readonly
   */
  modelMatrix: {
    get: function () {
      return this._modelMatrix;
    },
    set: function (modelMatrix) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.object("modelMatrix", modelMatrix);
      //>>includeEnd('debug');
 
      this._modelMatrix = Matrix4.clone(modelMatrix, this._modelMatrix);
    },
  },
 
  /**
   * Gets the shape type.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {VoxelShapeType}
   * @readonly
   */
  shape: {
    get: function () {
      return this._provider.shape;
    },
  },
 
  /**
   * Gets the dimensions of each voxel tile, in z-up orientation.
   * Does not include padding.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   * @readonly
   */
  dimensions: {
    get: function () {
      return this._dimensions;
    },
  },
 
  /**
   * Gets the dimensions of one tile of the input voxel data, in the input orientation.
   * Includes padding.
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   * @readonly
   */
  inputDimensions: {
    get: function () {
      return this._inputDimensions;
    },
  },
 
  /**
   * Gets the padding before the voxel data.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   * @readonly
   */
  paddingBefore: {
    get: function () {
      return this._paddingBefore;
    },
  },
 
  /**
   * Gets the padding after the voxel data.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   * @readonly
   */
  paddingAfter: {
    get: function () {
      return this._paddingAfter;
    },
  },
 
  /**
   * Gets the minimum value per channel of the voxel data.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {number[][]}
   * @readonly
   */
  minimumValues: {
    get: function () {
      return this._provider.minimumValues;
    },
  },
 
  /**
   * Gets the maximum value per channel of the voxel data.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {number[][]}
   * @readonly
   */
  maximumValues: {
    get: function () {
      return this._provider.maximumValues;
    },
  },
 
  /**
   * Gets or sets whether or not this primitive should be displayed.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {boolean}
   */
  show: {
    get: function () {
      return !this._disableRender;
    },
    set: function (show) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.bool("show", show);
      //>>includeEnd('debug');
 
      this._disableRender = !show;
    },
  },
 
  /**
   * Gets or sets whether or not the primitive should update when the view changes.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {boolean}
   */
  disableUpdate: {
    get: function () {
      return this._disableUpdate;
    },
    set: function (disableUpdate) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.bool("disableUpdate", disableUpdate);
      //>>includeEnd('debug');
 
      this._disableUpdate = disableUpdate;
    },
  },
 
  /**
   * Gets or sets whether or not to render debug visualizations.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {boolean}
   */
  debugDraw: {
    get: function () {
      return this._debugDraw;
    },
    set: function (debugDraw) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.bool("debugDraw", debugDraw);
      //>>includeEnd('debug');
 
      this._debugDraw = debugDraw;
    },
  },
 
  /**
   * Gets or sets whether or not to test against depth when rendering.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {boolean}
   */
  depthTest: {
    get: function () {
      return this._depthTest;
    },
    set: function (depthTest) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.bool("depthTest", depthTest);
      //>>includeEnd('debug');
 
      Eif (this._depthTest !== depthTest) {
        this._depthTest = depthTest;
        this._shaderDirty = true;
      }
    },
  },
 
  /**
   * Gets or sets the nearest sampling.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {boolean}
   */
  nearestSampling: {
    get: function () {
      return this._nearestSampling;
    },
    set: function (nearestSampling) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.bool("nearestSampling", nearestSampling);
      //>>includeEnd('debug');
 
      Eif (this._nearestSampling !== nearestSampling) {
        this._nearestSampling = nearestSampling;
        this._shaderDirty = true;
      }
    },
  },
 
  /**
   * Controls how quickly to blend between different levels of the tree.
   * 0.0 means an instantaneous pop.
   * 1.0 means a full linear blend.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {number}
   * @private
   */
  levelBlendFactor: {
    get: function () {
      return this._levelBlendFactor;
    },
    set: function (levelBlendFactor) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number("levelBlendFactor", levelBlendFactor);
      //>>includeEnd('debug');
 
      this._levelBlendFactor = CesiumMath.clamp(levelBlendFactor, 0.0, 1.0);
    },
  },
 
  /**
   * Gets or sets the screen space error in pixels. If the screen space size
   * of a voxel is greater than the screen space error, the tile is subdivided.
   * Lower screen space error corresponds with higher detail rendering, but could
   * result in worse performance and higher memory consumption.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {number}
   */
  screenSpaceError: {
    get: function () {
      return this._screenSpaceError;
    },
    set: function (screenSpaceError) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number("screenSpaceError", screenSpaceError);
      //>>includeEnd('debug');
 
      this._screenSpaceError = screenSpaceError;
    },
  },
 
  /**
   * Gets or sets the step size multiplier used during raymarching.
   * The lower the value, the higher the rendering quality, but
   * also the worse the performance.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {number}
   */
  stepSize: {
    get: function () {
      return this._stepSizeMultiplier;
    },
    set: function (stepSize) {
      //>>includeStart('debug', pragmas.debug);
      Check.typeOf.number("stepSize", stepSize);
      //>>includeEnd('debug');
 
      this._stepSizeMultiplier = stepSize;
    },
  },
 
  /**
   * Gets or sets the minimum bounds in the shape's local coordinate system.
   * Voxel data is stretched or squashed to fit the bounds.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   */
  minBounds: {
    get: function () {
      return this._minBounds;
    },
    set: function (minBounds) {
      //>>includeStart('debug', pragmas.debug);
      Check.defined("minBounds", minBounds);
      //>>includeEnd('debug');
 
      this._minBounds = Cartesian3.clone(minBounds, this._minBounds);
    },
  },
 
  /**
   * Gets or sets the maximum bounds in the shape's local coordinate system.
   * Voxel data is stretched or squashed to fit the bounds.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   */
  maxBounds: {
    get: function () {
      return this._maxBounds;
    },
    set: function (maxBounds) {
      //>>includeStart('debug', pragmas.debug);
      Check.defined("maxBounds", maxBounds);
      //>>includeEnd('debug');
 
      this._maxBounds = Cartesian3.clone(maxBounds, this._maxBounds);
    },
  },
 
  /**
   * Gets or sets the minimum clipping location in the shape's local coordinate system.
   * Any voxel content outside the range is clipped.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   */
  minClippingBounds: {
    get: function () {
      return this._minClippingBounds;
    },
    set: function (minClippingBounds) {
      //>>includeStart('debug', pragmas.debug);
      Check.defined("minClippingBounds", minClippingBounds);
      //>>includeEnd('debug');
 
      this._minClippingBounds = Cartesian3.clone(
        minClippingBounds,
        this._minClippingBounds,
      );
    },
  },
 
  /**
   * Gets or sets the maximum clipping location in the shape's local coordinate system.
   * Any voxel content outside the range is clipped.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Cartesian3}
   */
  maxClippingBounds: {
    get: function () {
      return this._maxClippingBounds;
    },
    set: function (maxClippingBounds) {
      //>>includeStart('debug', pragmas.debug);
      Check.defined("maxClippingBounds", maxClippingBounds);
      //>>includeEnd('debug');
 
      this._maxClippingBounds = Cartesian3.clone(
        maxClippingBounds,
        this._maxClippingBounds,
      );
    },
  },
 
  /**
   * The {@link ClippingPlaneCollection} used to selectively disable rendering the primitive.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {ClippingPlaneCollection}
   */
  clippingPlanes: {
    get: function () {
      return this._clippingPlanes;
    },
    set: function (clippingPlanes) {
      // Don't need to check if undefined, it's handled in the setOwner function
      ClippingPlaneCollection.setOwner(clippingPlanes, this, "_clippingPlanes");
    },
  },
 
  /**
   * Gets or sets the custom shader. If undefined, {@link VoxelPrimitive.DefaultCustomShader} is set.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {CustomShader}
   * @see {@link https://github.com/CesiumGS/cesium/tree/main/Documentation/CustomShaderGuide|Custom Shader Guide}
   */
  customShader: {
    get: function () {
      return this._customShader;
    },
    set: function (customShader) {
      Eif (this._customShader !== customShader) {
        // Delete old custom shader entries from the uniform map
        const uniformMap = this._uniformMap;
        const oldCustomShader = this._customShader;
        const oldCustomShaderUniformMap = oldCustomShader.uniformMap;
        for (const uniformName in oldCustomShaderUniformMap) {
          if (oldCustomShaderUniformMap.hasOwnProperty(uniformName)) {
            // If the custom shader was set but the voxel shader was never
            // built, the custom shader uniforms wouldn't have been added to
            // the uniform map. But it doesn't matter because the delete
            // operator ignores if the key doesn't exist.
            delete uniformMap[uniformName];
          }
        }
 
        if (!defined(customShader)) {
          this._customShader = VoxelPrimitive.DefaultCustomShader;
        } else {
          this._customShader = customShader;
        }
        this._shaderDirty = true;
      }
    },
  },
 
  /**
   * Gets an event that is raised whenever a custom shader is compiled.
   *
   * @memberof VoxelPrimitive.prototype
   * @type {Event}
   * @readonly
   */
  customShaderCompilationEvent: {
    get: function () {
      return this._customShaderCompilationEvent;
    },
  },
 
  /**
   *  Loading and rendering information for requested content
   * To use `visited` and `numberOfTilesWithContentReady` statistics, set options._calculateStatistics` to `true` in the constructor.
   * @type {Cesium3DTilesetStatistics}
   * @readonly
   * @private
   */
  statistics: {
    get: function () {
      return this._statistics;
    },
  },
});
 
const scratchIntersect = new Cartesian4();
const scratchNdcAabb = new Cartesian4();
const scratchTransformPositionLocalToWorld = new Matrix4();
const scratchTransformPositionLocalToProjection = new Matrix4();
const scratchCameraPositionShapeUv = new Cartesian3();
const scratchCameraTileCoordinates = new Cartesian4();
 
/**
 * Updates the voxel primitive.
 *
 * @param {FrameState} frameState
 * @private
 */
VoxelPrimitive.prototype.update = function (frameState) {
  const provider = this._provider;
  const uniforms = this._uniforms;
 
  // Update the custom shader in case it has texture uniforms.
  this._customShader.update(frameState);
 
  // Initialize from the ready provider. This only happens once.
  const context = frameState.context;
  if (!this._ready) {
    initFromProvider(this, provider, context);
    // Set the primitive as ready after the first frame render since the user might set up events subscribed to
    // the post render event, and the primitive may not be ready for those past the first frame.
    frameState.afterRender.push(() => {
      this._ready = true;
      return true;
    });
 
    // Don't render until the next frame after ready is set to true
    return;
  }
 
  // Check if the shape is dirty before updating it. This needs to happen every
  // frame because the member variables can be modified externally via the
  // getters.
  const shapeDirty = checkTransformAndBounds(this);
  const exaggerationChanged = updateVerticalExaggeration(this, frameState);
  if (shapeDirty || exaggerationChanged) {
    this._shapeVisible = updateShapeAndTransforms(this);
    Iif (checkShapeDefines(this)) {
      this._shaderDirty = true;
    }
  }
  if (!this._shapeVisible) {
    return;
  }
 
  this._shape.updateViewTransforms(frameState);
 
  // Update the traversal and prepare for rendering.
  const keyframeLocation = getKeyframeLocation(
    provider.timeIntervalCollection,
    this._clock,
  );
 
  const traversal = this._traversal;
  const sampleCountOld = traversal._sampleCount;
 
  traversal.update(
    frameState,
    keyframeLocation,
    shapeDirty, // recomputeBoundingVolumes
    this._disableUpdate, // pauseUpdate
  );
 
  if (sampleCountOld !== traversal._sampleCount) {
    this._shaderDirty = true;
  }
 
  if (!traversal.isRenderable(traversal.rootNode)) {
    return;
  }
 
  if (this._debugDraw) {
    // Debug draw bounding boxes and other things. Must go after traversal update
    // because that's what updates the tile bounding boxes.
    debugDraw(this, frameState);
  }
 
  Iif (this._disableRender) {
    return;
  }
 
  // Check if log depth changed
  if (this._useLogDepth !== frameState.useLogDepth) {
    this._useLogDepth = frameState.useLogDepth;
    this._shaderDirty = true;
  }
 
  // Check if clipping planes changed
  const clippingPlanesChanged = updateClippingPlanes(this, frameState);
  Iif (clippingPlanesChanged) {
    this._shaderDirty = true;
  }
 
  const leafNodeTexture = traversal.leafNodeTexture;
  if (defined(leafNodeTexture)) {
    uniforms.octreeLeafNodeTexture = traversal.leafNodeTexture;
    uniforms.octreeLeafNodeTexelSizeUv = Cartesian2.clone(
      traversal.leafNodeTexelSizeUv,
      uniforms.octreeLeafNodeTexelSizeUv,
    );
    uniforms.octreeLeafNodeTilesPerRow = traversal.leafNodeTilesPerRow;
  }
 
  // Rebuild shaders
  if (this._shaderDirty) {
    buildVoxelDrawCommands(this, context);
    this._shaderDirty = false;
  }
 
  // Calculate the NDC-space AABB to "scissor" the fullscreen quad
  const transformPositionWorldToProjection =
    context.uniformState.viewProjection;
  const { orientedBoundingBox } = this._shape;
  const ndcAabb = orientedBoundingBoxToNdcAabb(
    orientedBoundingBox,
    transformPositionWorldToProjection,
    scratchNdcAabb,
  );
 
  // If the object is offscreen, don't render it.
  const offscreen =
    ndcAabb.x === +1.0 ||
    ndcAabb.y === +1.0 ||
    ndcAabb.z === -1.0 ||
    ndcAabb.w === -1.0;
  Iif (offscreen) {
    return;
  }
 
  // Prepare to render: update uniforms that can change every frame
  // Using a uniform instead of going through RenderState's scissor because the viewport is not accessible here, and the scissor command needs pixel coordinates.
  uniforms.ndcSpaceAxisAlignedBoundingBox = Cartesian4.clone(
    ndcAabb,
    uniforms.ndcSpaceAxisAlignedBoundingBox,
  );
  const transformPositionViewToWorld = context.uniformState.inverseView;
  const transformPositionViewToLocal = Matrix4.multiplyTransformation(
    this._transformPositionWorldToLocal,
    transformPositionViewToWorld,
    uniforms.transformPositionViewToLocal,
  );
 
  this._transformPlaneLocalToView = Matrix4.transpose(
    transformPositionViewToLocal,
    this._transformPlaneLocalToView,
  );
 
  const transformDirectionViewToWorld =
    context.uniformState.inverseViewRotation;
  uniforms.transformDirectionViewToLocal = Matrix3.multiply(
    this._transformDirectionWorldToLocal,
    transformDirectionViewToWorld,
    uniforms.transformDirectionViewToLocal,
  );
  uniforms.cameraPositionLocal = Matrix4.multiplyByPoint(
    this._transformPositionWorldToLocal,
    frameState.camera.positionWC,
    uniforms.cameraPositionLocal,
  );
  uniforms.cameraDirectionLocal = Matrix3.multiplyByVector(
    this._transformDirectionWorldToLocal,
    frameState.camera.directionWC,
    uniforms.cameraDirectionLocal,
  );
  const cameraTileCoordinates = getTileCoordinates(
    this,
    uniforms.cameraPositionLocal,
    scratchCameraTileCoordinates,
  );
  uniforms.cameraTileCoordinates = Cartesian4.fromElements(
    Math.floor(cameraTileCoordinates.x),
    Math.floor(cameraTileCoordinates.y),
    Math.floor(cameraTileCoordinates.z),
    cameraTileCoordinates.w,
    uniforms.cameraTileCoordinates,
  );
  uniforms.cameraTileUv = Cartesian3.fromElements(
    cameraTileCoordinates.x - Math.floor(cameraTileCoordinates.x),
    cameraTileCoordinates.y - Math.floor(cameraTileCoordinates.y),
    cameraTileCoordinates.z - Math.floor(cameraTileCoordinates.z),
    uniforms.cameraTileUv,
  );
  uniforms.stepSize = this._stepSizeMultiplier;
 
  updateRenderBoundPlanes(this, frameState);
 
  // Render the primitive
  const command = frameState.passes.pick
    ? this._drawCommandPick
    : frameState.passes.pickVoxel
      ? this._drawCommandPickVoxel
      : this._drawCommand;
  command.boundingVolume = this._shape.boundingSphere;
  frameState.commandList.push(command);
};
 
function updateRenderBoundPlanes(primitive, frameState) {
  const uniforms = primitive._uniforms;
  const { renderBoundPlanes } = primitive._shape;
  if (!defined(renderBoundPlanes)) {
    return;
  }
  renderBoundPlanes.update(frameState, primitive._transformPlaneLocalToView);
  uniforms.renderBoundPlanesTexture = renderBoundPlanes.texture;
}
 
/**
 * Converts a position in local space to tile coordinates.
 *
 * @param {VoxelPrimitive} primitive The primitive to get the tile coordinates for.
 * @param {Cartesian3} positionLocal The position in local space to convert to tile coordinates.
 * @param {Cartesian4} result The result object to store the tile coordinates.
 * @returns {Cartesian4} The tile coordinates of the supplied position.
 * @private
 */
function getTileCoordinates(primitive, positionLocal, result) {
  const shapeUv = primitive._shape.convertLocalToShapeUvSpace(
    positionLocal,
    scratchCameraPositionShapeUv,
  );
 
  const availableLevels = primitive._availableLevels;
  const numTiles = 2 ** (availableLevels - 1);
 
  return Cartesian4.fromElements(
    shapeUv.x * numTiles,
    shapeUv.y * numTiles,
    shapeUv.z * numTiles,
    availableLevels - 1,
    result,
  );
}
 
const scratchExaggerationScale = new Cartesian3();
const scratchExaggerationCenter = new Cartesian3();
const scratchCartographicCenter = new Cartographic();
 
/**
 * Check for changes in the vertical exaggeration of the primitive
 * @param {VoxelPrimitive} primitive The primitive to update
 * @param {FrameState} frameState The current frame state
 * @returns {boolean} <code>true</code> if the exaggeration was changed
 * @private
 */
function updateVerticalExaggeration(primitive, frameState) {
  const { verticalExaggeration, verticalExaggerationRelativeHeight } =
    frameState;
 
  if (
    primitive._verticalExaggeration === verticalExaggeration &&
    primitive._verticalExaggerationRelativeHeight ===
      verticalExaggerationRelativeHeight
  ) {
    return false;
  }
 
  primitive._verticalExaggeration = verticalExaggeration;
  primitive._verticalExaggerationRelativeHeight =
    verticalExaggerationRelativeHeight;
  return true;
}
 
/**
 * Initialize primitive properties that are derived from the voxel provider
 * @param {VoxelPrimitive} primitive
 * @param {VoxelProvider} provider
 * @param {Context} context
 * @private
 */
function initFromProvider(primitive, provider, context) {
  const uniforms = primitive._uniforms;
 
  primitive._pickId = context.createPickId({ primitive });
  uniforms.pickColor = Color.clone(primitive._pickId.color, uniforms.pickColor);
 
  const { shaderDefines, shaderUniforms: shapeUniforms } = primitive._shape;
  primitive._shapeDefinesOld = clone(shaderDefines, true);
 
  // Add shape uniforms to the uniform map
  const uniformMap = primitive._uniformMap;
  for (const key in shapeUniforms) {
    Eif (shapeUniforms.hasOwnProperty(key)) {
      const name = `u_${key}`;
 
      //>>includeStart('debug', pragmas.debug);
      Iif (defined(uniformMap[name])) {
        oneTimeWarning(
          `VoxelPrimitive: Uniform name "${name}" is already defined`,
        );
      }
      //>>includeEnd('debug');
 
      uniformMap[name] = function () {
        return shapeUniforms[key];
      };
    }
  }
 
  // Set uniforms that come from the provider.
  // Note that minBounds and maxBounds can be set dynamically, so their uniforms aren't set here.
  primitive._dimensions = Cartesian3.clone(
    provider.dimensions,
    primitive._dimensions,
  );
  uniforms.dimensions = Cartesian3.clone(
    primitive._dimensions,
    uniforms.dimensions,
  );
  primitive._paddingBefore = Cartesian3.clone(
    provider.paddingBefore ?? Cartesian3.ZERO,
    primitive._paddingBefore,
  );
  uniforms.paddingBefore = Cartesian3.clone(
    primitive._paddingBefore,
    uniforms.paddingBefore,
  );
  primitive._paddingAfter = Cartesian3.clone(
    provider.paddingAfter ?? Cartesian3.ZERO,
    primitive._paddingAfter,
  );
  uniforms.paddingAfter = Cartesian3.clone(
    primitive._paddingAfter,
    uniforms.paddingAfter,
  );
  primitive._inputDimensions = Cartesian3.add(
    primitive._dimensions,
    primitive._paddingBefore,
    primitive._inputDimensions,
  );
  primitive._inputDimensions = Cartesian3.add(
    primitive._inputDimensions,
    primitive._paddingAfter,
    primitive._inputDimensions,
  );
  if (provider.metadataOrder === VoxelMetadataOrder.Y_UP) {
    const inputDimensionsY = primitive._inputDimensions.y;
    primitive._inputDimensions.y = primitive._inputDimensions.z;
    primitive._inputDimensions.z = inputDimensionsY;
  }
  uniforms.inputDimensions = Cartesian3.clone(
    primitive._inputDimensions,
    uniforms.inputDimensions,
  );
  primitive._availableLevels = provider.availableLevels ?? 1;
 
  // Create the VoxelTraversal, and set related uniforms
  const keyframeCount = provider.keyframeCount ?? 1;
  primitive._traversal = new VoxelTraversal(primitive, context, keyframeCount);
  primitive.statistics.texturesByteLength =
    primitive._traversal.textureMemoryByteLength;
  setTraversalUniforms(primitive._traversal, uniforms);
}
 
/**
 * Track changes in provider transform and primitive bounds
 * @param {VoxelPrimitive} primitive
 * @returns {boolean} Whether any of the transform or bounds changed
 * @private
 */
function checkTransformAndBounds(primitive) {
  const numChanges =
    updateBound(primitive, "_modelMatrix", "_modelMatrixOld") +
    updateBound(primitive, "_minBounds", "_minBoundsOld") +
    updateBound(primitive, "_maxBounds", "_maxBoundsOld") +
    updateBound(primitive, "_minClippingBounds", "_minClippingBoundsOld") +
    updateBound(primitive, "_maxClippingBounds", "_maxClippingBoundsOld");
  return numChanges > 0;
}
 
/**
 * Compare old and new values of a bound and update the old if it is different.
 * @param {VoxelPrimitive} primitive The primitive with bounds properties
 * @param {string} newBoundKey A key pointing to a bounds property of type Cartesian3 or Matrix4
 * @param {string} oldBoundKey A key pointing to a bounds property of the same type as the property at newBoundKey
 * @returns {number} 1 if the bound value changed, 0 otherwise
 *
 * @private
 */
function updateBound(primitive, newBoundKey, oldBoundKey) {
  const newBound = primitive[newBoundKey];
  const oldBound = primitive[oldBoundKey];
 
  const changed = !newBound.equals(oldBound);
  if (changed) {
    newBound.clone(oldBound);
  }
  return changed ? 1 : 0;
}
 
const scratchExaggeratedMinBounds = new Cartesian3();
const scratchExaggeratedMaxBounds = new Cartesian3();
const scratchExaggeratedMinClippingBounds = new Cartesian3();
const scratchExaggeratedMaxClippingBounds = new Cartesian3();
const scratchExaggeratedModelMatrix = new Matrix4();
const scratchCompoundModelMatrix = new Matrix4();
 
/**
 * Update the shape and related transforms
 * @param {VoxelPrimitive} primitive
 * @returns {boolean} True if the shape is visible
 * @private
 */
function updateShapeAndTransforms(primitive) {
  const verticalExaggeration = primitive._verticalExaggeration;
  const verticalExaggerationRelativeHeight =
    primitive._verticalExaggerationRelativeHeight;
  const exaggeratedMinBounds = Cartesian3.clone(
    primitive._minBounds,
    scratchExaggeratedMinBounds,
  );
  const exaggeratedMaxBounds = Cartesian3.clone(
    primitive._maxBounds,
    scratchExaggeratedMaxBounds,
  );
  const exaggeratedMinClippingBounds = Cartesian3.clone(
    primitive._minClippingBounds,
    scratchExaggeratedMinClippingBounds,
  );
  const exaggeratedMaxClippingBounds = Cartesian3.clone(
    primitive._maxClippingBounds,
    scratchExaggeratedMaxClippingBounds,
  );
  const exaggeratedModelMatrix = Matrix4.clone(
    primitive._modelMatrix,
    scratchExaggeratedModelMatrix,
  );
 
  if (primitive.shape === VoxelShapeType.ELLIPSOID) {
    // Apply the exaggeration by stretching the height bounds
    exaggeratedMinBounds.z = VerticalExaggeration.getHeight(
      primitive._minBounds.z,
      verticalExaggeration,
      verticalExaggerationRelativeHeight,
    );
    exaggeratedMaxBounds.z = VerticalExaggeration.getHeight(
      primitive._maxBounds.z,
      verticalExaggeration,
      verticalExaggerationRelativeHeight,
    );
    exaggeratedMinClippingBounds.z = VerticalExaggeration.getHeight(
      primitive._minClippingBounds.z,
      verticalExaggeration,
      verticalExaggerationRelativeHeight,
    );
    exaggeratedMaxClippingBounds.z = VerticalExaggeration.getHeight(
      primitive._maxClippingBounds.z,
      verticalExaggeration,
      verticalExaggerationRelativeHeight,
    );
  } else {
    // Apply the exaggeration via the model matrix
    const exaggerationScale = Cartesian3.fromElements(
      1.0,
      1.0,
      verticalExaggeration,
      scratchExaggerationScale,
    );
    Matrix4.multiplyByScale(
      exaggeratedModelMatrix,
      exaggerationScale,
      exaggeratedModelMatrix,
    );
    Matrix4.multiplyByTranslation(
      exaggeratedModelMatrix,
      computeBoxExaggerationTranslation(primitive),
      exaggeratedModelMatrix,
    );
  }
 
  const provider = primitive._provider;
  const shapeTransform = provider.shapeTransform ?? Matrix4.IDENTITY;
  const globalTransform = provider.globalTransform ?? Matrix4.IDENTITY;
 
  // Compound model matrix = global transform * model matrix * shape transform
  const compoundModelMatrix = Matrix4.multiplyTransformation(
    globalTransform,
    exaggeratedModelMatrix,
    scratchCompoundModelMatrix,
  );
  Matrix4.multiplyTransformation(
    compoundModelMatrix,
    shapeTransform,
    compoundModelMatrix,
  );
 
  const shape = primitive._shape;
  const visible = shape.update(
    compoundModelMatrix,
    exaggeratedMinBounds,
    exaggeratedMaxBounds,
    exaggeratedMinClippingBounds,
    exaggeratedMaxClippingBounds,
  );
  if (!visible) {
    return false;
  }
 
  primitive._transformPositionLocalToWorld = Matrix4.clone(
    shape.shapeTransform,
    primitive._transformPositionLocalToWorld,
  );
  primitive._transformPositionWorldToLocal = Matrix4.inverse(
    primitive._transformPositionLocalToWorld,
    primitive._transformPositionWorldToLocal,
  );
  primitive._transformDirectionWorldToLocal = Matrix4.getMatrix3(
    primitive._transformPositionWorldToLocal,
    primitive._transformDirectionWorldToLocal,
  );
 
  return true;
}
 
const scratchExaggerationTranslation = new Cartesian3();
 
/**
 * Compute the translation to apply to box shapes to account for vertical exaggeration
 *
 * @param {VoxelPrimitive} primitive
 * @returns {Cartesian3} The translation to apply to the box to account for vertical exaggeration
 * @private
 */
function computeBoxExaggerationTranslation(primitive) {
  const verticalExaggeration = primitive._verticalExaggeration;
  const verticalExaggerationRelativeHeight =
    primitive._verticalExaggerationRelativeHeight;
 
  // Compute translation based on box center, relative height, and exaggeration
  const {
    shapeTransform = Matrix4.IDENTITY,
    globalTransform = Matrix4.IDENTITY,
  } = primitive._provider;
 
  // Find the Cartesian position of the center of the OBB
  const initialCenter = Matrix4.getTranslation(
    shapeTransform,
    scratchExaggerationCenter,
  );
  const intermediateCenter = Matrix4.multiplyByPoint(
    primitive._modelMatrix,
    initialCenter,
    scratchExaggerationCenter,
  );
  const transformedCenter = Matrix4.multiplyByPoint(
    globalTransform,
    intermediateCenter,
    scratchExaggerationCenter,
  );
 
  // Find the cartographic height
  const ellipsoid = Ellipsoid.WGS84;
  const centerCartographic = ellipsoid.cartesianToCartographic(
    transformedCenter,
    scratchCartographicCenter,
  );
 
  let centerHeight = 0.0;
  Iif (defined(centerCartographic)) {
    centerHeight = centerCartographic.height;
  }
 
  // Find the shift that will put the center in the right position relative
  // to relativeHeight, after it is scaled by verticalExaggeration
  const exaggeratedHeight = VerticalExaggeration.getHeight(
    centerHeight,
    verticalExaggeration,
    verticalExaggerationRelativeHeight,
  );
 
  return Cartesian3.fromElements(
    0.0,
    0.0,
    (exaggeratedHeight - centerHeight) / verticalExaggeration,
    scratchExaggerationTranslation,
  );
}
 
/**
 * Set uniforms that come from the traversal.
 * @param {VoxelTraversal} traversal
 * @param {object} uniforms
 * @private
 */
function setTraversalUniforms(traversal, uniforms) {
  uniforms.octreeInternalNodeTexture = traversal.internalNodeTexture;
  uniforms.octreeInternalNodeTexelSizeUv = Cartesian2.clone(
    traversal.internalNodeTexelSizeUv,
    uniforms.octreeInternalNodeTexelSizeUv,
  );
  uniforms.octreeInternalNodeTilesPerRow = traversal.internalNodeTilesPerRow;
 
  const megatextures = traversal.megatextures;
  const megatexture = megatextures[0];
  const megatextureLength = megatextures.length;
  uniforms.megatextureTextures = new Array(megatextureLength);
  for (let i = 0; i < megatextureLength; i++) {
    uniforms.megatextureTextures[i] = megatextures[i].texture;
  }
 
  uniforms.megatextureSliceDimensions = Cartesian2.clone(
    megatexture.sliceCountPerRegion,
    uniforms.megatextureSliceDimensions,
  );
  uniforms.megatextureTileDimensions = Cartesian2.clone(
    megatexture.regionCountPerMegatexture,
    uniforms.megatextureTileDimensions,
  );
  uniforms.megatextureVoxelSizeUv = Cartesian2.clone(
    megatexture.voxelSizeUv,
    uniforms.megatextureVoxelSizeUv,
  );
  uniforms.megatextureSliceSizeUv = Cartesian2.clone(
    megatexture.sliceSizeUv,
    uniforms.megatextureSliceSizeUv,
  );
  uniforms.megatextureTileSizeUv = Cartesian2.clone(
    megatexture.regionSizeUv,
    uniforms.megatextureTileSizeUv,
  );
}
 
/**
 * Track changes in shape-related shader defines
 * @param {VoxelPrimitive} primitive
 * @returns {boolean} True if any of the shape defines changed, requiring a shader rebuild
 * @private
 */
function checkShapeDefines(primitive) {
  const { shaderDefines } = primitive._shape;
  const shapeDefinesChanged = Object.keys(shaderDefines).some(
    (key) => shaderDefines[key] !== primitive._shapeDefinesOld[key],
  );
  Iif (shapeDefinesChanged) {
    primitive._shapeDefinesOld = clone(shaderDefines, true);
  }
  return shapeDefinesChanged;
}
 
/**
 * Find the keyframe location to render at. Doesn't need to be a whole number.
 * @param {TimeIntervalCollection} timeIntervalCollection
 * @param {Clock} clock
 * @returns {number}
 *
 * @private
 */
function getKeyframeLocation(timeIntervalCollection, clock) {
  Eif (!defined(timeIntervalCollection) || !defined(clock)) {
    return 0.0;
  }
  let date = clock.currentTime;
  let timeInterval;
  let timeIntervalIndex = timeIntervalCollection.indexOf(date);
  if (timeIntervalIndex >= 0) {
    timeInterval = timeIntervalCollection.get(timeIntervalIndex);
  } else {
    // Date fell outside the range
    timeIntervalIndex = ~timeIntervalIndex;
    if (timeIntervalIndex === timeIntervalCollection.length) {
      // Date past range
      timeIntervalIndex = timeIntervalCollection.length - 1;
      timeInterval = timeIntervalCollection.get(timeIntervalIndex);
      date = timeInterval.stop;
    } else {
      // Date before range
      timeInterval = timeIntervalCollection.get(timeIntervalIndex);
      date = timeInterval.start;
    }
  }
  // De-lerp between the start and end of the interval
  const totalSeconds = JulianDate.secondsDifference(
    timeInterval.stop,
    timeInterval.start,
  );
  const secondsDifferenceStart = JulianDate.secondsDifference(
    date,
    timeInterval.start,
  );
  const t = secondsDifferenceStart / totalSeconds;
 
  return timeIntervalIndex + t;
}
 
/**
 * Update the clipping planes state and associated uniforms
 *
 * @param {VoxelPrimitive} primitive
 * @param {FrameState} frameState
 * @returns {boolean} Whether the clipping planes changed, requiring a shader rebuild
 * @private
 */
function updateClippingPlanes(primitive, frameState) {
  const clippingPlanes = primitive.clippingPlanes;
  Eif (!defined(clippingPlanes)) {
    return false;
  }
 
  clippingPlanes.update(frameState);
 
  const { clippingPlanesState, enabled } = clippingPlanes;
 
  if (enabled) {
    const uniforms = primitive._uniforms;
    uniforms.clippingPlanesTexture = clippingPlanes.texture;
 
    // Compute the clipping plane's transformation to local space and then take the inverse
    // transpose to properly transform the hessian normal form of the plane.
 
    // transpose(inverse(worldToLocal * clippingPlaneLocalToWorld))
    // transpose(inverse(clippingPlaneLocalToWorld) * inverse(worldToLocal))
    // transpose(inverse(clippingPlaneLocalToWorld) * localToWorld)
 
    uniforms.clippingPlanesMatrix = Matrix4.transpose(
      Matrix4.multiplyTransformation(
        Matrix4.inverse(
          clippingPlanes.modelMatrix,
          uniforms.clippingPlanesMatrix,
        ),
        primitive._transformPositionLocalToWorld,
        uniforms.clippingPlanesMatrix,
      ),
      uniforms.clippingPlanesMatrix,
    );
  }
 
  if (
    primitive._clippingPlanesState === clippingPlanesState &&
    primitive._clippingPlanesEnabled === enabled
  ) {
    return false;
  }
  primitive._clippingPlanesState = clippingPlanesState;
  primitive._clippingPlanesEnabled = enabled;
 
  return true;
}
 
/**
 * Returns true if this object was destroyed; otherwise, false.
 * <br /><br />
 * If this object was destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
 *
 * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
 *
 * @see VoxelPrimitive#destroy
 */
VoxelPrimitive.prototype.isDestroyed = function () {
  return false;
};
 
/**
 * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
 * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
 * <br /><br />
 * Once an object is destroyed, it should not be used; calling any function other than
 * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.  Therefore,
 * assign the return value (<code>undefined</code>) to the object as done in the example.
 *
 * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
 *
 * @see VoxelPrimitive#isDestroyed
 *
 * @example
 * voxelPrimitive = voxelPrimitive && voxelPrimitive.destroy();
 */
VoxelPrimitive.prototype.destroy = function () {
  const drawCommand = this._drawCommand;
  if (defined(drawCommand)) {
    drawCommand.shaderProgram =
      drawCommand.shaderProgram && drawCommand.shaderProgram.destroy();
  }
  const drawCommandPick = this._drawCommandPick;
  if (defined(drawCommandPick)) {
    drawCommandPick.shaderProgram =
      drawCommandPick.shaderProgram && drawCommandPick.shaderProgram.destroy();
  }
 
  this._pickId = this._pickId && this._pickId.destroy();
  this._traversal = this._traversal && this._traversal.destroy();
  this.statistics.texturesByteLength = 0;
  this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
 
  return destroyObject(this);
};
 
const corners = new Array(
  new Cartesian4(-1.0, -1.0, -1.0, 1.0),
  new Cartesian4(+1.0, -1.0, -1.0, 1.0),
  new Cartesian4(-1.0, +1.0, -1.0, 1.0),
  new Cartesian4(+1.0, +1.0, -1.0, 1.0),
  new Cartesian4(-1.0, -1.0, +1.0, 1.0),
  new Cartesian4(+1.0, -1.0, +1.0, 1.0),
  new Cartesian4(-1.0, +1.0, +1.0, 1.0),
  new Cartesian4(+1.0, +1.0, +1.0, 1.0),
);
const vertexNeighborIndices = new Array(
  1,
  2,
  4,
  0,
  3,
  5,
  0,
  3,
  6,
  1,
  2,
  7,
  0,
  5,
  6,
  1,
  4,
  7,
  2,
  4,
  7,
  3,
  5,
  6,
);
 
const scratchCornersClipSpace = new Array(
  new Cartesian4(),
  new Cartesian4(),
  new Cartesian4(),
  new Cartesian4(),
  new Cartesian4(),
  new Cartesian4(),
  new Cartesian4(),
  new Cartesian4(),
);
 
/**
 * Projects all 8 corners of the oriented bounding box to NDC space and finds the
 * resulting NDC axis aligned bounding box. To avoid projecting a vertex that is
 * behind the near plane, it uses the intersection point of each of the vertex's
 * edges against the near plane as part of the AABB calculation. This is done in
 * clip space prior to perspective division.
 *
 * @function
 *
 * @param {OrientedBoundingBox} orientedBoundingBox
 * @param {Matrix4} worldToProjection
 * @param {Cartesian4} result
 * @returns {Cartesian4}
 *
 * @private
 */
function orientedBoundingBoxToNdcAabb(
  orientedBoundingBox,
  worldToProjection,
  result,
) {
  const transformPositionLocalToWorld = Matrix4.fromRotationTranslation(
    orientedBoundingBox.halfAxes,
    orientedBoundingBox.center,
    scratchTransformPositionLocalToWorld,
  );
  const transformPositionLocalToProjection = Matrix4.multiply(
    worldToProjection,
    transformPositionLocalToWorld,
    scratchTransformPositionLocalToProjection,
  );
 
  let ndcMinX = +Number.MAX_VALUE;
  let ndcMaxX = -Number.MAX_VALUE;
  let ndcMinY = +Number.MAX_VALUE;
  let ndcMaxY = -Number.MAX_VALUE;
  let cornerIndex;
 
  // Convert all points to clip space
  const cornersClipSpace = scratchCornersClipSpace;
  const cornersLength = corners.length;
  for (cornerIndex = 0; cornerIndex < cornersLength; cornerIndex++) {
    Matrix4.multiplyByVector(
      transformPositionLocalToProjection,
      corners[cornerIndex],
      cornersClipSpace[cornerIndex],
    );
  }
 
  for (cornerIndex = 0; cornerIndex < cornersLength; cornerIndex++) {
    const position = cornersClipSpace[cornerIndex];
    if (position.z >= -position.w) {
      // Position is past near plane, so there's no need to clip.
      const ndcX = position.x / position.w;
      const ndcY = position.y / position.w;
      ndcMinX = Math.min(ndcMinX, ndcX);
      ndcMaxX = Math.max(ndcMaxX, ndcX);
      ndcMinY = Math.min(ndcMinY, ndcY);
      ndcMaxY = Math.max(ndcMaxY, ndcY);
    } else E{
      for (let neighborIndex = 0; neighborIndex < 3; neighborIndex++) {
        const neighborVertexIndex =
          vertexNeighborIndices[cornerIndex * 3 + neighborIndex];
        const neighborPosition = cornersClipSpace[neighborVertexIndex];
        if (neighborPosition.z >= -neighborPosition.w) {
          // Position is behind the near plane and neighbor is after, so get intersection point on the near plane.
          const distanceToPlaneFromPosition = position.z + position.w;
          const distanceToPlaneFromNeighbor =
            neighborPosition.z + neighborPosition.w;
          const t =
            distanceToPlaneFromPosition /
            (distanceToPlaneFromPosition - distanceToPlaneFromNeighbor);
 
          const intersect = Cartesian4.lerp(
            position,
            neighborPosition,
            t,
            scratchIntersect,
          );
          const intersectNdcX = intersect.x / intersect.w;
          const intersectNdcY = intersect.y / intersect.w;
          ndcMinX = Math.min(ndcMinX, intersectNdcX);
          ndcMaxX = Math.max(ndcMaxX, intersectNdcX);
          ndcMinY = Math.min(ndcMinY, intersectNdcY);
          ndcMaxY = Math.max(ndcMaxY, intersectNdcY);
        }
      }
    }
  }
 
  // Clamp the NDC values to -1 to +1 range even if they extend much further.
  ndcMinX = CesiumMath.clamp(ndcMinX, -1.0, +1.0);
  ndcMinY = CesiumMath.clamp(ndcMinY, -1.0, +1.0);
  ndcMaxX = CesiumMath.clamp(ndcMaxX, -1.0, +1.0);
  ndcMaxY = CesiumMath.clamp(ndcMaxY, -1.0, +1.0);
  result = Cartesian4.fromElements(ndcMinX, ndcMinY, ndcMaxX, ndcMaxY, result);
 
  return result;
}
 
const polylineAxisDistance = 30000000.0;
const polylineXAxis = new Cartesian3(polylineAxisDistance, 0.0, 0.0);
const polylineYAxis = new Cartesian3(0.0, polylineAxisDistance, 0.0);
const polylineZAxis = new Cartesian3(0.0, 0.0, polylineAxisDistance);
 
/**
 * Draws the tile bounding boxes and axes.
 *
 * @function
 *
 * @param {VoxelPrimitive} that
 * @param {FrameState} frameState
 *
 * @private
 */
function debugDraw(that, frameState) {
  const traversal = that._traversal;
  const polylines = that._debugPolylines;
  polylines.removeAll();
 
  function makePolylineLineSegment(startPos, endPos, color, thickness) {
    polylines.add({
      positions: [startPos, endPos],
      width: thickness,
      material: Material.fromType("Color", {
        color: color,
      }),
    });
  }
 
  function makePolylineBox(orientedBoundingBox, color, thickness) {
    // Normally would want to use a scratch variable to store the corners, but
    // polylines don't clone the positions.
    const corners = orientedBoundingBox.computeCorners();
    makePolylineLineSegment(corners[0], corners[1], color, thickness);
    makePolylineLineSegment(corners[2], corners[3], color, thickness);
    makePolylineLineSegment(corners[4], corners[5], color, thickness);
    makePolylineLineSegment(corners[6], corners[7], color, thickness);
    makePolylineLineSegment(corners[0], corners[2], color, thickness);
    makePolylineLineSegment(corners[4], corners[6], color, thickness);
    makePolylineLineSegment(corners[1], corners[3], color, thickness);
    makePolylineLineSegment(corners[5], corners[7], color, thickness);
    makePolylineLineSegment(corners[0], corners[4], color, thickness);
    makePolylineLineSegment(corners[2], corners[6], color, thickness);
    makePolylineLineSegment(corners[1], corners[5], color, thickness);
    makePolylineLineSegment(corners[3], corners[7], color, thickness);
  }
 
  function drawTile(tile) {
    Iif (!traversal.isRenderable(tile)) {
      return;
    }
 
    const level = tile.level;
    const startThickness = 5.0;
    const thickness = Math.max(1.0, startThickness / Math.pow(2.0, level));
    const colors = [Color.RED, Color.LIME, Color.BLUE];
    const color = colors[level % 3];
 
    makePolylineBox(tile.orientedBoundingBox, color, thickness);
 
    Iif (defined(tile.children)) {
      for (let i = 0; i < 8; i++) {
        drawTile(tile.children[i]);
      }
    }
  }
 
  makePolylineBox(that._shape.orientedBoundingBox, Color.WHITE, 5.0);
 
  drawTile(traversal.rootNode);
 
  const axisThickness = 10.0;
  makePolylineLineSegment(
    Cartesian3.ZERO,
    polylineXAxis,
    Color.RED,
    axisThickness,
  );
  makePolylineLineSegment(
    Cartesian3.ZERO,
    polylineYAxis,
    Color.LIME,
    axisThickness,
  );
  makePolylineLineSegment(
    Cartesian3.ZERO,
    polylineZAxis,
    Color.BLUE,
    axisThickness,
  );
 
  polylines.update(frameState);
}
 
/**
 * The default custom shader used by the primitive.
 *
 * @type {CustomShader}
 * @constant
 * @readonly
 *
 * @private
 */
VoxelPrimitive.DefaultCustomShader = new CustomShader({
  fragmentShaderText: `void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)
{
    material.diffuse = vec3(1.0);
    material.alpha = 1.0;
}`,
});
 
function DefaultVoxelProvider() {
  this.ready = true;
  this.shape = VoxelShapeType.BOX;
  this.dimensions = new Cartesian3(1, 1, 1);
  this.names = ["data"];
  this.types = [MetadataType.SCALAR];
  this.componentTypes = [MetadataComponentType.FLOAT32];
  this.maximumTileCount = 1;
}
 
DefaultVoxelProvider.prototype.requestData = function (options) {
  const tileLevel = defined(options) ? (options.tileLevel ?? 0) : 0;
  Iif (tileLevel >= 1) {
    return undefined;
  }
 
  const content = new VoxelContent({ metadata: [new Float32Array(1)] });
  return Promise.resolve(content);
};
 
VoxelPrimitive.DefaultProvider = new DefaultVoxelProvider();
 
export default VoxelPrimitive;