/usr/include/openvdb/tools/MeshToVolume.h is in libopenvdb-dev 5.0.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012-2017 DreamWorks Animation LLC
//
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
//
// Redistributions of source code must retain the above copyright
// and license notice and the following restrictions and disclaimer.
//
// * Neither the name of DreamWorks Animation nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
// LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
//
///////////////////////////////////////////////////////////////////////////
/// @file MeshToVolume.h
///
/// @brief Convert polygonal meshes that consist of quads and/or triangles
/// into signed or unsigned distance field volumes.
///
/// @note The signed distance field conversion requires a closed surface
/// but not necessarily a manifold surface. Supports surfaces with
/// self intersections and degenerate faces and is independent of
/// mesh surface normals / polygon orientation.
///
/// @author Mihai Alden
#ifndef OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
#define OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
#include <openvdb/Platform.h> // for OPENVDB_HAS_CXX11
#include <openvdb/Types.h>
#include <openvdb/math/FiniteDifference.h> // for GodunovsNormSqrd
#include <openvdb/math/Proximity.h> // for closestPointOnTriangleToPoint
#include <openvdb/util/NullInterrupter.h>
#include <openvdb/util/Util.h>
#include "ChangeBackground.h"
#include "Prune.h" // for pruneInactive and pruneLevelSet
#include "SignedFloodFill.h" // for signedFloodFillWithValues
#include <tbb/blocked_range.h>
#include <tbb/enumerable_thread_specific.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_reduce.h>
#include <tbb/partitioner.h>
#include <tbb/task_group.h>
#include <tbb/task_scheduler_init.h>
#include <boost/integer_traits.hpp> // for const_max
#include <boost/shared_array.hpp>
#include <algorithm> // for std::sort()
#include <cmath> // for std::isfinite(), std::isnan()
#include <deque>
#include <limits>
#include <memory>
#include <sstream>
#include <type_traits>
#include <vector>
namespace openvdb {
OPENVDB_USE_VERSION_NAMESPACE
namespace OPENVDB_VERSION_NAME {
namespace tools {
////////////////////////////////////////
/// @brief Mesh to volume conversion flags
enum MeshToVolumeFlags {
/// Switch from the default signed distance field conversion that classifies
/// regions as either inside or outside the mesh boundary to a unsigned distance
/// field conversion that only computes distance values. This conversion type
/// does not require a closed watertight mesh.
UNSIGNED_DISTANCE_FIELD = 0x1,
/// Disable the cleanup step that removes voxels created by self intersecting
/// portions of the mesh.
DISABLE_INTERSECTING_VOXEL_REMOVAL = 0x2,
/// Disable the distance renormalization step that smooths out bumps caused
/// by self intersecting or overlapping portions of the mesh
DISABLE_RENORMALIZATION = 0x4,
/// Disable the cleanup step that removes active voxels that exceed the
/// narrow band limits. (Only relevant for small limits)
DISABLE_NARROW_BAND_TRIMMING = 0x8
};
/// @brief Convert polygonal meshes that consist of quads and/or triangles into
/// signed or unsigned distance field volumes.
///
/// @note Requires a closed surface but not necessarily a manifold surface.
/// Supports surfaces with self intersections and degenerate faces
/// and is independent of mesh surface normals.
///
/// @interface MeshDataAdapter
/// Expected interface for the MeshDataAdapter class
/// @code
/// struct MeshDataAdapter {
/// size_t polygonCount() const; // Total number of polygons
/// size_t pointCount() const; // Total number of points
/// size_t vertexCount(size_t n) const; // Vertex count for polygon n
///
/// // Return position pos in local grid index space for polygon n and vertex v
/// void getIndexSpacePoint(size_t n, size_t v, openvdb::Vec3d& pos) const;
/// };
/// @endcode
///
/// @param mesh mesh data access class that conforms to the MeshDataAdapter
/// interface
/// @param transform world-to-index-space transform
/// @param exteriorBandWidth exterior narrow band width in voxel units
/// @param interiorBandWidth interior narrow band width in voxel units
/// (set to std::numeric_limits<float>::max() to fill object
/// interior with distance values)
/// @param flags optional conversion flags defined in @c MeshToVolumeFlags
/// @param polygonIndexGrid optional grid output that will contain the closest-polygon
/// index for each voxel in the narrow band region
template <typename GridType, typename MeshDataAdapter>
inline typename GridType::Ptr
meshToVolume(
const MeshDataAdapter& mesh,
const math::Transform& transform,
float exteriorBandWidth = 3.0f,
float interiorBandWidth = 3.0f,
int flags = 0,
typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr);
/// @brief Convert polygonal meshes that consist of quads and/or triangles into
/// signed or unsigned distance field volumes.
///
/// @param interrupter a callback to interrupt the conversion process that conforms
/// to the util::NullInterrupter interface
/// @param mesh mesh data access class that conforms to the MeshDataAdapter
/// interface
/// @param transform world-to-index-space transform
/// @param exteriorBandWidth exterior narrow band width in voxel units
/// @param interiorBandWidth interior narrow band width in voxel units (set this value to
/// std::numeric_limits<float>::max() to fill interior regions
/// with distance values)
/// @param flags optional conversion flags defined in @c MeshToVolumeFlags
/// @param polygonIndexGrid optional grid output that will contain the closest-polygon
/// index for each voxel in the active narrow band region
template <typename GridType, typename MeshDataAdapter, typename Interrupter>
inline typename GridType::Ptr
meshToVolume(
Interrupter& interrupter,
const MeshDataAdapter& mesh,
const math::Transform& transform,
float exteriorBandWidth = 3.0f,
float interiorBandWidth = 3.0f,
int flags = 0,
typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid = nullptr);
////////////////////////////////////////
/// @brief Contiguous quad and triangle data adapter class
///
/// @details PointType and PolygonType must provide element access
/// through the square brackets operator.
/// @details Points are assumed to be in local grid index space.
/// @details The PolygonType tuple can have either three or four components
/// this property must be specified in a static member variable
/// named @c size, similar to the math::Tuple class.
/// @details A four component tuple can represent a quads or a triangle
/// if the fourth component set to @c util::INVALID_INDEX
template<typename PointType, typename PolygonType>
struct QuadAndTriangleDataAdapter {
QuadAndTriangleDataAdapter(const std::vector<PointType>& points,
const std::vector<PolygonType>& polygons)
: mPointArray(points.empty() ? nullptr : &points[0])
, mPointArraySize(points.size())
, mPolygonArray(polygons.empty() ? nullptr : &polygons[0])
, mPolygonArraySize(polygons.size())
{
}
QuadAndTriangleDataAdapter(const PointType * pointArray, size_t pointArraySize,
const PolygonType* polygonArray, size_t polygonArraySize)
: mPointArray(pointArray)
, mPointArraySize(pointArraySize)
, mPolygonArray(polygonArray)
, mPolygonArraySize(polygonArraySize)
{
}
size_t polygonCount() const { return mPolygonArraySize; }
size_t pointCount() const { return mPointArraySize; }
/// @brief Vertex count for polygon @a n
size_t vertexCount(size_t n) const {
return (PolygonType::size == 3 || mPolygonArray[n][3] == util::INVALID_IDX) ? 3 : 4;
}
/// @brief Returns position @a pos in local grid index space
/// for polygon @a n and vertex @a v
void getIndexSpacePoint(size_t n, size_t v, Vec3d& pos) const {
const PointType& p = mPointArray[mPolygonArray[n][int(v)]];
pos[0] = double(p[0]);
pos[1] = double(p[1]);
pos[2] = double(p[2]);
}
private:
PointType const * const mPointArray;
size_t const mPointArraySize;
PolygonType const * const mPolygonArray;
size_t const mPolygonArraySize;
}; // struct QuadAndTriangleDataAdapter
////////////////////////////////////////
// Convenience functions for the mesh to volume converter that wrap stl containers.
//
// Note the meshToVolume() method declared above is more flexible and better suited
// for arbitrary data structures.
/// @brief Convert a triangle mesh to a level set volume.
///
/// @return a grid of type @c GridType containing a narrow-band level set
/// representation of the input mesh.
///
/// @throw TypeError if @c GridType is not scalar or not floating-point
///
/// @note Requires a closed surface but not necessarily a manifold surface.
/// Supports surfaces with self intersections and degenerate faces
/// and is independent of mesh surface normals.
///
/// @param xform transform for the output grid
/// @param points list of world space point positions
/// @param triangles triangle index list
/// @param halfWidth half the width of the narrow band, in voxel units
template<typename GridType>
inline typename GridType::Ptr
meshToLevelSet(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
float halfWidth = float(LEVEL_SET_HALF_WIDTH));
/// Adds support for a @a interrupter callback used to cancel the conversion.
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToLevelSet(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
float halfWidth = float(LEVEL_SET_HALF_WIDTH));
/// @brief Convert a quad mesh to a level set volume.
///
/// @return a grid of type @c GridType containing a narrow-band level set
/// representation of the input mesh.
///
/// @throw TypeError if @c GridType is not scalar or not floating-point
///
/// @note Requires a closed surface but not necessarily a manifold surface.
/// Supports surfaces with self intersections and degenerate faces
/// and is independent of mesh surface normals.
///
/// @param xform transform for the output grid
/// @param points list of world space point positions
/// @param quads quad index list
/// @param halfWidth half the width of the narrow band, in voxel units
template<typename GridType>
inline typename GridType::Ptr
meshToLevelSet(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec4I>& quads,
float halfWidth = float(LEVEL_SET_HALF_WIDTH));
/// Adds support for a @a interrupter callback used to cancel the conversion.
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToLevelSet(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec4I>& quads,
float halfWidth = float(LEVEL_SET_HALF_WIDTH));
/// @brief Convert a triangle and quad mesh to a level set volume.
///
/// @return a grid of type @c GridType containing a narrow-band level set
/// representation of the input mesh.
///
/// @throw TypeError if @c GridType is not scalar or not floating-point
///
/// @note Requires a closed surface but not necessarily a manifold surface.
/// Supports surfaces with self intersections and degenerate faces
/// and is independent of mesh surface normals.
///
/// @param xform transform for the output grid
/// @param points list of world space point positions
/// @param triangles triangle index list
/// @param quads quad index list
/// @param halfWidth half the width of the narrow band, in voxel units
template<typename GridType>
inline typename GridType::Ptr
meshToLevelSet(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float halfWidth = float(LEVEL_SET_HALF_WIDTH));
/// Adds support for a @a interrupter callback used to cancel the conversion.
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToLevelSet(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float halfWidth = float(LEVEL_SET_HALF_WIDTH));
/// @brief Convert a triangle and quad mesh to a signed distance field
/// with an asymmetrical narrow band.
///
/// @return a grid of type @c GridType containing a narrow-band signed
/// distance field representation of the input mesh.
///
/// @throw TypeError if @c GridType is not scalar or not floating-point
///
/// @note Requires a closed surface but not necessarily a manifold surface.
/// Supports surfaces with self intersections and degenerate faces
/// and is independent of mesh surface normals.
///
/// @param xform transform for the output grid
/// @param points list of world space point positions
/// @param triangles triangle index list
/// @param quads quad index list
/// @param exBandWidth the exterior narrow-band width in voxel units
/// @param inBandWidth the interior narrow-band width in voxel units
template<typename GridType>
inline typename GridType::Ptr
meshToSignedDistanceField(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float exBandWidth,
float inBandWidth);
/// Adds support for a @a interrupter callback used to cancel the conversion.
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToSignedDistanceField(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float exBandWidth,
float inBandWidth);
/// @brief Convert a triangle and quad mesh to an unsigned distance field.
///
/// @return a grid of type @c GridType containing a narrow-band unsigned
/// distance field representation of the input mesh.
///
/// @throw TypeError if @c GridType is not scalar or not floating-point
///
/// @note Does not requires a closed surface.
///
/// @param xform transform for the output grid
/// @param points list of world space point positions
/// @param triangles triangle index list
/// @param quads quad index list
/// @param bandWidth the width of the narrow band, in voxel units
template<typename GridType>
inline typename GridType::Ptr
meshToUnsignedDistanceField(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float bandWidth);
/// Adds support for a @a interrupter callback used to cancel the conversion.
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToUnsignedDistanceField(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float bandWidth);
////////////////////////////////////////
/// @brief Return a grid of type @c GridType containing a narrow-band level set
/// representation of a box.
///
/// @param bbox a bounding box in world units
/// @param xform world-to-index-space transform
/// @param halfWidth half the width of the narrow band, in voxel units
template<typename GridType, typename VecType>
inline typename GridType::Ptr
createLevelSetBox(const math::BBox<VecType>& bbox,
const openvdb::math::Transform& xform,
typename VecType::ValueType halfWidth = LEVEL_SET_HALF_WIDTH);
////////////////////////////////////////
/// @brief Traces the exterior voxel boundary of closed objects in the input
/// volume @a tree. Exterior voxels are marked with a negative sign,
/// voxels with a value below @c 0.75 are left unchanged and act as
/// the boundary layer.
///
/// @note Does not propagate sign information into tile regions.
template <typename FloatTreeT>
inline void
traceExteriorBoundaries(FloatTreeT& tree);
////////////////////////////////////////
/// @brief Extracts and stores voxel edge intersection data from a mesh.
class MeshToVoxelEdgeData
{
public:
//////////
///@brief Internal edge data type.
struct EdgeData {
EdgeData(float dist = 1.0)
: mXDist(dist), mYDist(dist), mZDist(dist)
, mXPrim(util::INVALID_IDX)
, mYPrim(util::INVALID_IDX)
, mZPrim(util::INVALID_IDX)
{
}
//@{
/// Required by several of the tree nodes
/// @note These methods don't perform meaningful operations.
bool operator< (const EdgeData&) const { return false; }
bool operator> (const EdgeData&) const { return false; }
template<class T> EdgeData operator+(const T&) const { return *this; }
template<class T> EdgeData operator-(const T&) const { return *this; }
EdgeData operator-() const { return *this; }
//@}
bool operator==(const EdgeData& rhs) const
{
return mXPrim == rhs.mXPrim && mYPrim == rhs.mYPrim && mZPrim == rhs.mZPrim;
}
float mXDist, mYDist, mZDist;
Index32 mXPrim, mYPrim, mZPrim;
};
using TreeType = tree::Tree4<EdgeData, 5, 4, 3>::Type;
using Accessor = tree::ValueAccessor<TreeType>;
//////////
MeshToVoxelEdgeData();
/// @brief Threaded method to extract voxel edge data, the closest
/// intersection point and corresponding primitive index,
/// from the given mesh.
///
/// @param pointList List of points in grid index space, preferably unique
/// and shared by different polygons.
/// @param polygonList List of triangles and/or quads.
void convert(const std::vector<Vec3s>& pointList, const std::vector<Vec4I>& polygonList);
/// @brief Returns intersection points with corresponding primitive
/// indices for the given @c ijk voxel.
void getEdgeData(Accessor& acc, const Coord& ijk,
std::vector<Vec3d>& points, std::vector<Index32>& primitives);
/// @return An accessor of @c MeshToVoxelEdgeData::Accessor type that
/// provides random read access to the internal tree.
Accessor getAccessor() { return Accessor(mTree); }
private:
void operator=(const MeshToVoxelEdgeData&) {}
TreeType mTree;
class GenEdgeData;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Internal utility objects and implementation details
namespace mesh_to_volume_internal {
template<typename PointType>
struct TransformPoints {
TransformPoints(const PointType* pointsIn, PointType* pointsOut,
const math::Transform& xform)
: mPointsIn(pointsIn), mPointsOut(pointsOut), mXform(&xform)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
Vec3d pos;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
const PointType& wsP = mPointsIn[n];
pos[0] = double(wsP[0]);
pos[1] = double(wsP[1]);
pos[2] = double(wsP[2]);
pos = mXform->worldToIndex(pos);
PointType& isP = mPointsOut[n];
isP[0] = typename PointType::value_type(pos[0]);
isP[1] = typename PointType::value_type(pos[1]);
isP[2] = typename PointType::value_type(pos[2]);
}
}
PointType const * const mPointsIn;
PointType * const mPointsOut;
math::Transform const * const mXform;
}; // TransformPoints
template<typename ValueType>
struct Tolerance
{
static ValueType epsilon() { return ValueType(1e-7); }
static ValueType minNarrowBandWidth() { return ValueType(1.0 + 1e-6); }
};
////////////////////////////////////////
template<typename TreeType>
class CombineLeafNodes
{
public:
using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
using LeafNodeType = typename TreeType::LeafNodeType;
using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
CombineLeafNodes(TreeType& lhsDistTree, Int32TreeType& lhsIdxTree,
LeafNodeType ** rhsDistNodes, Int32LeafNodeType ** rhsIdxNodes)
: mDistTree(&lhsDistTree)
, mIdxTree(&lhsIdxTree)
, mRhsDistNodes(rhsDistNodes)
, mRhsIdxNodes(rhsIdxNodes)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
tree::ValueAccessor<TreeType> distAcc(*mDistTree);
tree::ValueAccessor<Int32TreeType> idxAcc(*mIdxTree);
using DistValueType = typename LeafNodeType::ValueType;
using IndexValueType = typename Int32LeafNodeType::ValueType;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
const Coord& origin = mRhsDistNodes[n]->origin();
LeafNodeType* lhsDistNode = distAcc.probeLeaf(origin);
Int32LeafNodeType* lhsIdxNode = idxAcc.probeLeaf(origin);
DistValueType* lhsDistData = lhsDistNode->buffer().data();
IndexValueType* lhsIdxData = lhsIdxNode->buffer().data();
const DistValueType* rhsDistData = mRhsDistNodes[n]->buffer().data();
const IndexValueType* rhsIdxData = mRhsIdxNodes[n]->buffer().data();
for (Index32 offset = 0; offset < LeafNodeType::SIZE; ++offset) {
if (rhsIdxData[offset] != Int32(util::INVALID_IDX)) {
const DistValueType& lhsValue = lhsDistData[offset];
const DistValueType& rhsValue = rhsDistData[offset];
if (rhsValue < lhsValue) {
lhsDistNode->setValueOn(offset, rhsValue);
lhsIdxNode->setValueOn(offset, rhsIdxData[offset]);
} else if (math::isExactlyEqual(rhsValue, lhsValue)) {
lhsIdxNode->setValueOn(offset,
std::min(lhsIdxData[offset], rhsIdxData[offset]));
}
}
}
delete mRhsDistNodes[n];
delete mRhsIdxNodes[n];
}
}
private:
TreeType * const mDistTree;
Int32TreeType * const mIdxTree;
LeafNodeType ** const mRhsDistNodes;
Int32LeafNodeType ** const mRhsIdxNodes;
}; // class CombineLeafNodes
////////////////////////////////////////
template<typename TreeType>
struct StashOriginAndStoreOffset
{
using LeafNodeType = typename TreeType::LeafNodeType;
StashOriginAndStoreOffset(std::vector<LeafNodeType*>& nodes, Coord* coordinates)
: mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
mCoordinates[n] = origin;
origin[0] = static_cast<int>(n);
}
}
LeafNodeType ** const mNodes;
Coord * const mCoordinates;
};
template<typename TreeType>
struct RestoreOrigin
{
using LeafNodeType = typename TreeType::LeafNodeType;
RestoreOrigin(std::vector<LeafNodeType*>& nodes, const Coord* coordinates)
: mNodes(nodes.empty() ? nullptr : &nodes[0]), mCoordinates(coordinates)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
Coord& origin = const_cast<Coord&>(mNodes[n]->origin());
origin[0] = mCoordinates[n][0];
}
}
LeafNodeType ** const mNodes;
Coord const * const mCoordinates;
};
template<typename TreeType>
class ComputeNodeConnectivity
{
public:
using LeafNodeType = typename TreeType::LeafNodeType;
ComputeNodeConnectivity(const TreeType& tree, const Coord* coordinates,
size_t* offsets, size_t numNodes, const CoordBBox& bbox)
: mTree(&tree)
, mCoordinates(coordinates)
, mOffsets(offsets)
, mNumNodes(numNodes)
, mBBox(bbox)
{
}
ComputeNodeConnectivity(const ComputeNodeConnectivity&) = default;
// Disallow assignment
ComputeNodeConnectivity& operator=(const ComputeNodeConnectivity&) = delete;
void operator()(const tbb::blocked_range<size_t>& range) const {
size_t* offsetsNextX = mOffsets;
size_t* offsetsPrevX = mOffsets + mNumNodes;
size_t* offsetsNextY = mOffsets + mNumNodes * 2;
size_t* offsetsPrevY = mOffsets + mNumNodes * 3;
size_t* offsetsNextZ = mOffsets + mNumNodes * 4;
size_t* offsetsPrevZ = mOffsets + mNumNodes * 5;
tree::ValueAccessor<const TreeType> acc(*mTree);
Coord ijk;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
const Coord& origin = mCoordinates[n];
offsetsNextX[n] = findNeighbourNode(acc, origin, Coord(LeafNodeType::DIM, 0, 0));
offsetsPrevX[n] = findNeighbourNode(acc, origin, Coord(-LeafNodeType::DIM, 0, 0));
offsetsNextY[n] = findNeighbourNode(acc, origin, Coord(0, LeafNodeType::DIM, 0));
offsetsPrevY[n] = findNeighbourNode(acc, origin, Coord(0, -LeafNodeType::DIM, 0));
offsetsNextZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, LeafNodeType::DIM));
offsetsPrevZ[n] = findNeighbourNode(acc, origin, Coord(0, 0, -LeafNodeType::DIM));
}
}
size_t findNeighbourNode(tree::ValueAccessor<const TreeType>& acc,
const Coord& start, const Coord& step) const
{
Coord ijk = start + step;
CoordBBox bbox(mBBox);
while (bbox.isInside(ijk)) {
const LeafNodeType* node = acc.probeConstLeaf(ijk);
if (node) return static_cast<size_t>(node->origin()[0]);
ijk += step;
}
return boost::integer_traits<size_t>::const_max;
}
private:
TreeType const * const mTree;
Coord const * const mCoordinates;
size_t * const mOffsets;
const size_t mNumNodes;
const CoordBBox mBBox;
}; // class ComputeNodeConnectivity
template<typename TreeType>
struct LeafNodeConnectivityTable
{
enum { INVALID_OFFSET = boost::integer_traits<size_t>::const_max };
using LeafNodeType = typename TreeType::LeafNodeType;
LeafNodeConnectivityTable(TreeType& tree)
{
mLeafNodes.reserve(tree.leafCount());
tree.getNodes(mLeafNodes);
if (mLeafNodes.empty()) return;
CoordBBox bbox;
tree.evalLeafBoundingBox(bbox);
const tbb::blocked_range<size_t> range(0, mLeafNodes.size());
// stash the leafnode origin coordinate and temporarily store the
// linear offset in the origin.x variable.
std::unique_ptr<Coord[]> coordinates{new Coord[mLeafNodes.size()]};
tbb::parallel_for(range,
StashOriginAndStoreOffset<TreeType>(mLeafNodes, coordinates.get()));
// build the leafnode offset table
mOffsets.reset(new size_t[mLeafNodes.size() * 6]);
tbb::parallel_for(range, ComputeNodeConnectivity<TreeType>(
tree, coordinates.get(), mOffsets.get(), mLeafNodes.size(), bbox));
// restore the leafnode origin coordinate
tbb::parallel_for(range, RestoreOrigin<TreeType>(mLeafNodes, coordinates.get()));
}
size_t size() const { return mLeafNodes.size(); }
std::vector<LeafNodeType*>& nodes() { return mLeafNodes; }
const std::vector<LeafNodeType*>& nodes() const { return mLeafNodes; }
const size_t* offsetsNextX() const { return mOffsets.get(); }
const size_t* offsetsPrevX() const { return mOffsets.get() + mLeafNodes.size(); }
const size_t* offsetsNextY() const { return mOffsets.get() + mLeafNodes.size() * 2; }
const size_t* offsetsPrevY() const { return mOffsets.get() + mLeafNodes.size() * 3; }
const size_t* offsetsNextZ() const { return mOffsets.get() + mLeafNodes.size() * 4; }
const size_t* offsetsPrevZ() const { return mOffsets.get() + mLeafNodes.size() * 5; }
private:
std::vector<LeafNodeType*> mLeafNodes;
std::unique_ptr<size_t[]> mOffsets;
}; // struct LeafNodeConnectivityTable
template<typename TreeType>
class SweepExteriorSign
{
public:
enum Axis { X_AXIS = 0, Y_AXIS = 1, Z_AXIS = 2 };
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
using ConnectivityTable = LeafNodeConnectivityTable<TreeType>;
SweepExteriorSign(Axis axis, const std::vector<size_t>& startNodeIndices,
ConnectivityTable& connectivity)
: mStartNodeIndices(startNodeIndices.empty() ? nullptr : &startNodeIndices[0])
, mConnectivity(&connectivity)
, mAxis(axis)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
std::vector<LeafNodeType*>& nodes = mConnectivity->nodes();
// Z Axis
size_t idxA = 0, idxB = 1;
Index step = 1;
const size_t* nextOffsets = mConnectivity->offsetsNextZ();
const size_t* prevOffsets = mConnectivity->offsetsPrevZ();
if (mAxis == Y_AXIS) {
idxA = 0;
idxB = 2;
step = LeafNodeType::DIM;
nextOffsets = mConnectivity->offsetsNextY();
prevOffsets = mConnectivity->offsetsPrevY();
} else if (mAxis == X_AXIS) {
idxA = 1;
idxB = 2;
step = LeafNodeType::DIM * LeafNodeType::DIM;
nextOffsets = mConnectivity->offsetsNextX();
prevOffsets = mConnectivity->offsetsPrevX();
}
Coord ijk(0, 0, 0);
int& a = ijk[idxA];
int& b = ijk[idxB];
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
size_t startOffset = mStartNodeIndices[n];
size_t lastOffset = startOffset;
Index pos(0);
for (a = 0; a < int(LeafNodeType::DIM); ++a) {
for (b = 0; b < int(LeafNodeType::DIM); ++b) {
pos = LeafNodeType::coordToOffset(ijk);
size_t offset = startOffset;
// sweep in +axis direction until a boundary voxel is hit.
while ( offset != ConnectivityTable::INVALID_OFFSET &&
traceVoxelLine(*nodes[offset], pos, step) ) {
lastOffset = offset;
offset = nextOffsets[offset];
}
// find last leafnode in +axis direction
offset = lastOffset;
while (offset != ConnectivityTable::INVALID_OFFSET) {
lastOffset = offset;
offset = nextOffsets[offset];
}
// sweep in -axis direction until a boundary voxel is hit.
offset = lastOffset;
pos += step * (LeafNodeType::DIM - 1);
while ( offset != ConnectivityTable::INVALID_OFFSET &&
traceVoxelLine(*nodes[offset], pos, -step)) {
offset = prevOffsets[offset];
}
}
}
}
}
bool traceVoxelLine(LeafNodeType& node, Index pos, Index step) const {
ValueType* data = node.buffer().data();
bool isOutside = true;
for (Index i = 0; i < LeafNodeType::DIM; ++i) {
ValueType& dist = data[pos];
if (dist < ValueType(0.0)) {
isOutside = true;
} else {
// Boundary voxel check. (Voxel that intersects the surface)
if (!(dist > ValueType(0.75))) isOutside = false;
if (isOutside) dist = ValueType(-dist);
}
pos += step;
}
return isOutside;
}
private:
size_t const * const mStartNodeIndices;
ConnectivityTable * const mConnectivity;
const Axis mAxis;
}; // class SweepExteriorSign
template<typename LeafNodeType>
inline void
seedFill(LeafNodeType& node)
{
using ValueType = typename LeafNodeType::ValueType;
using Queue = std::deque<Index>;
ValueType* data = node.buffer().data();
// find seed points
Queue seedPoints;
for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
if (data[pos] < 0.0) seedPoints.push_back(pos);
}
if (seedPoints.empty()) return;
// clear sign information
for (Queue::iterator it = seedPoints.begin(); it != seedPoints.end(); ++it) {
ValueType& dist = data[*it];
dist = -dist;
}
// flood fill
Coord ijk(0, 0, 0);
Index pos(0), nextPos(0);
while (!seedPoints.empty()) {
pos = seedPoints.back();
seedPoints.pop_back();
ValueType& dist = data[pos];
if (!(dist < ValueType(0.0))) {
dist = -dist; // flip sign
ijk = LeafNodeType::offsetToLocalCoord(pos);
if (ijk[0] != 0) { // i - 1, j, k
nextPos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
}
if (ijk[0] != (LeafNodeType::DIM - 1)) { // i + 1, j, k
nextPos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
}
if (ijk[1] != 0) { // i, j - 1, k
nextPos = pos - LeafNodeType::DIM;
if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
}
if (ijk[1] != (LeafNodeType::DIM - 1)) { // i, j + 1, k
nextPos = pos + LeafNodeType::DIM;
if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
}
if (ijk[2] != 0) { // i, j, k - 1
nextPos = pos - 1;
if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
}
if (ijk[2] != (LeafNodeType::DIM - 1)) { // i, j, k + 1
nextPos = pos + 1;
if (data[nextPos] > ValueType(0.75)) seedPoints.push_back(nextPos);
}
}
}
} // seedFill()
template<typename LeafNodeType>
inline bool
scanFill(LeafNodeType& node)
{
bool updatedNode = false;
using ValueType = typename LeafNodeType::ValueType;
ValueType* data = node.buffer().data();
Coord ijk(0, 0, 0);
bool updatedSign = true;
while (updatedSign) {
updatedSign = false;
for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
ValueType& dist = data[pos];
if (!(dist < ValueType(0.0)) && dist > ValueType(0.75)) {
ijk = LeafNodeType::offsetToLocalCoord(pos);
// i, j, k - 1
if (ijk[2] != 0 && data[pos - 1] < ValueType(0.0)) {
updatedSign = true;
dist = ValueType(-dist);
// i, j, k + 1
} else if (ijk[2] != (LeafNodeType::DIM - 1) && data[pos + 1] < ValueType(0.0)) {
updatedSign = true;
dist = ValueType(-dist);
// i, j - 1, k
} else if (ijk[1] != 0 && data[pos - LeafNodeType::DIM] < ValueType(0.0)) {
updatedSign = true;
dist = ValueType(-dist);
// i, j + 1, k
} else if (ijk[1] != (LeafNodeType::DIM - 1)
&& data[pos + LeafNodeType::DIM] < ValueType(0.0))
{
updatedSign = true;
dist = ValueType(-dist);
// i - 1, j, k
} else if (ijk[0] != 0
&& data[pos - LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
{
updatedSign = true;
dist = ValueType(-dist);
// i + 1, j, k
} else if (ijk[0] != (LeafNodeType::DIM - 1)
&& data[pos + LeafNodeType::DIM * LeafNodeType::DIM] < ValueType(0.0))
{
updatedSign = true;
dist = ValueType(-dist);
}
}
} // end value loop
updatedNode |= updatedSign;
} // end update loop
return updatedNode;
} // scanFill()
template<typename TreeType>
class SeedFillExteriorSign
{
public:
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
SeedFillExteriorSign(std::vector<LeafNodeType*>& nodes, bool* changedNodeMask)
: mNodes(nodes.empty() ? nullptr : &nodes[0])
, mChangedNodeMask(changedNodeMask)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
if (mChangedNodeMask[n]) {
//seedFill(*mNodes[n]);
mChangedNodeMask[n] = scanFill(*mNodes[n]);
}
}
}
LeafNodeType ** const mNodes;
bool * const mChangedNodeMask;
};
template<typename ValueType>
struct FillArray
{
FillArray(ValueType* array, const ValueType v) : mArray(array), mValue(v) { }
void operator()(const tbb::blocked_range<size_t>& range) const {
const ValueType v = mValue;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
mArray[n] = v;
}
}
ValueType * const mArray;
const ValueType mValue;
};
template<typename ValueType>
inline void
fillArray(ValueType* array, const ValueType val, const size_t length)
{
const auto grainSize = std::max<size_t>(
length / tbb::task_scheduler_init::default_num_threads(), 1024);
const tbb::blocked_range<size_t> range(0, length, grainSize);
tbb::parallel_for(range, FillArray<ValueType>(array, val), tbb::simple_partitioner());
}
template<typename TreeType>
class SyncVoxelMask
{
public:
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
SyncVoxelMask(std::vector<LeafNodeType*>& nodes,
const bool* changedNodeMask, bool* changedVoxelMask)
: mNodes(nodes.empty() ? nullptr : &nodes[0])
, mChangedNodeMask(changedNodeMask)
, mChangedVoxelMask(changedVoxelMask)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
if (mChangedNodeMask[n]) {
bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
ValueType* data = mNodes[n]->buffer().data();
for (Index pos = 0; pos < LeafNodeType::SIZE; ++pos) {
if (mask[pos]) {
data[pos] = ValueType(-data[pos]);
mask[pos] = false;
}
}
}
}
}
LeafNodeType ** const mNodes;
bool const * const mChangedNodeMask;
bool * const mChangedVoxelMask;
};
template<typename TreeType>
class SeedPoints
{
public:
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
using ConnectivityTable = LeafNodeConnectivityTable<TreeType>;
SeedPoints(ConnectivityTable& connectivity,
bool* changedNodeMask, bool* nodeMask, bool* changedVoxelMask)
: mConnectivity(&connectivity)
, mChangedNodeMask(changedNodeMask)
, mNodeMask(nodeMask)
, mChangedVoxelMask(changedVoxelMask)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
if (!mChangedNodeMask[n]) {
bool changedValue = false;
changedValue |= processZ(n, /*firstFace=*/true);
changedValue |= processZ(n, /*firstFace=*/false);
changedValue |= processY(n, /*firstFace=*/true);
changedValue |= processY(n, /*firstFace=*/false);
changedValue |= processX(n, /*firstFace=*/true);
changedValue |= processX(n, /*firstFace=*/false);
mNodeMask[n] = changedValue;
}
}
}
bool processZ(const size_t n, bool firstFace) const
{
const size_t offset =
firstFace ? mConnectivity->offsetsPrevZ()[n] : mConnectivity->offsetsNextZ()[n];
if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
const Index lastOffset = LeafNodeType::DIM - 1;
const Index lhsOffset =
firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
Index tmpPos(0), pos(0);
bool changedValue = false;
for (Index x = 0; x < LeafNodeType::DIM; ++x) {
tmpPos = x << (2 * LeafNodeType::LOG2DIM);
for (Index y = 0; y < LeafNodeType::DIM; ++y) {
pos = tmpPos + (y << LeafNodeType::LOG2DIM);
if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
changedValue = true;
mask[pos + lhsOffset] = true;
}
}
}
}
return changedValue;
}
return false;
}
bool processY(const size_t n, bool firstFace) const
{
const size_t offset =
firstFace ? mConnectivity->offsetsPrevY()[n] : mConnectivity->offsetsNextY()[n];
if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
const Index lastOffset = LeafNodeType::DIM * (LeafNodeType::DIM - 1);
const Index lhsOffset =
firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
Index tmpPos(0), pos(0);
bool changedValue = false;
for (Index x = 0; x < LeafNodeType::DIM; ++x) {
tmpPos = x << (2 * LeafNodeType::LOG2DIM);
for (Index z = 0; z < LeafNodeType::DIM; ++z) {
pos = tmpPos + z;
if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
changedValue = true;
mask[pos + lhsOffset] = true;
}
}
}
}
return changedValue;
}
return false;
}
bool processX(const size_t n, bool firstFace) const
{
const size_t offset =
firstFace ? mConnectivity->offsetsPrevX()[n] : mConnectivity->offsetsNextX()[n];
if (offset != ConnectivityTable::INVALID_OFFSET && mChangedNodeMask[offset]) {
bool* mask = &mChangedVoxelMask[n * LeafNodeType::SIZE];
const ValueType* lhsData = mConnectivity->nodes()[n]->buffer().data();
const ValueType* rhsData = mConnectivity->nodes()[offset]->buffer().data();
const Index lastOffset = LeafNodeType::DIM * LeafNodeType::DIM * (LeafNodeType::DIM-1);
const Index lhsOffset =
firstFace ? 0 : lastOffset, rhsOffset = firstFace ? lastOffset : 0;
Index tmpPos(0), pos(0);
bool changedValue = false;
for (Index y = 0; y < LeafNodeType::DIM; ++y) {
tmpPos = y << LeafNodeType::LOG2DIM;
for (Index z = 0; z < LeafNodeType::DIM; ++z) {
pos = tmpPos + z;
if (lhsData[pos + lhsOffset] > ValueType(0.75)) {
if (rhsData[pos + rhsOffset] < ValueType(0.0)) {
changedValue = true;
mask[pos + lhsOffset] = true;
}
}
}
}
return changedValue;
}
return false;
}
ConnectivityTable * const mConnectivity;
bool * const mChangedNodeMask;
bool * const mNodeMask;
bool * const mChangedVoxelMask;
};
////////////////////////////////////////
template<typename TreeType, typename MeshDataAdapter>
struct ComputeIntersectingVoxelSign
{
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
using PointArray = boost::shared_array<Vec3d>;
using MaskArray = boost::shared_array<bool>;
using LocalData = std::pair<PointArray, MaskArray>;
using LocalDataTable = tbb::enumerable_thread_specific<LocalData>;
ComputeIntersectingVoxelSign(
std::vector<LeafNodeType*>& distNodes,
const TreeType& distTree,
const Int32TreeType& indexTree,
const MeshDataAdapter& mesh)
: mDistNodes(distNodes.empty() ? nullptr : &distNodes[0])
, mDistTree(&distTree)
, mIndexTree(&indexTree)
, mMesh(&mesh)
, mLocalDataTable(new LocalDataTable())
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
tree::ValueAccessor<const Int32TreeType> idxAcc(*mIndexTree);
ValueType nval;
CoordBBox bbox;
Index xPos(0), yPos(0);
Coord ijk, nijk, nodeMin, nodeMax;
Vec3d cp, xyz, nxyz, dir1, dir2;
LocalData& localData = mLocalDataTable->local();
PointArray& points = localData.first;
if (!points) points.reset(new Vec3d[LeafNodeType::SIZE * 2]);
MaskArray& mask = localData.second;
if (!mask) mask.reset(new bool[LeafNodeType::SIZE]);
typename LeafNodeType::ValueOnCIter it;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
LeafNodeType& node = *mDistNodes[n];
ValueType* data = node.buffer().data();
const Int32LeafNodeType* idxNode = idxAcc.probeConstLeaf(node.origin());
const Int32* idxData = idxNode->buffer().data();
nodeMin = node.origin();
nodeMax = nodeMin.offsetBy(LeafNodeType::DIM - 1);
// reset computed voxel mask.
memset(mask.get(), 0, sizeof(bool) * LeafNodeType::SIZE);
for (it = node.cbeginValueOn(); it; ++it) {
Index pos = it.pos();
ValueType& dist = data[pos];
if (dist < 0.0 || dist > 0.75) continue;
ijk = node.offsetToGlobalCoord(pos);
xyz[0] = double(ijk[0]);
xyz[1] = double(ijk[1]);
xyz[2] = double(ijk[2]);
bbox.min() = Coord::maxComponent(ijk.offsetBy(-1), nodeMin);
bbox.max() = Coord::minComponent(ijk.offsetBy(1), nodeMax);
bool flipSign = false;
for (nijk[0] = bbox.min()[0]; nijk[0] <= bbox.max()[0] && !flipSign; ++nijk[0]) {
xPos = (nijk[0] & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
for (nijk[1]=bbox.min()[1]; nijk[1] <= bbox.max()[1] && !flipSign; ++nijk[1]) {
yPos = xPos + ((nijk[1] & (LeafNodeType::DIM-1u)) << LeafNodeType::LOG2DIM);
for (nijk[2] = bbox.min()[2]; nijk[2] <= bbox.max()[2]; ++nijk[2]) {
pos = yPos + (nijk[2] & (LeafNodeType::DIM - 1u));
const Int32& polyIdx = idxData[pos];
if (polyIdx == Int32(util::INVALID_IDX) || !(data[pos] < -0.75))
continue;
const Index pointIndex = pos * 2;
if (!mask[pos]) {
mask[pos] = true;
nxyz[0] = double(nijk[0]);
nxyz[1] = double(nijk[1]);
nxyz[2] = double(nijk[2]);
Vec3d& point = points[pointIndex];
point = closestPoint(nxyz, polyIdx);
Vec3d& direction = points[pointIndex + 1];
direction = nxyz - point;
direction.normalize();
}
dir1 = xyz - points[pointIndex];
dir1.normalize();
if (points[pointIndex + 1].dot(dir1) > 0.0) {
flipSign = true;
break;
}
}
}
}
if (flipSign) {
dist = -dist;
} else {
for (Int32 m = 0; m < 26; ++m) {
nijk = ijk + util::COORD_OFFSETS[m];
if (!bbox.isInside(nijk) && distAcc.probeValue(nijk, nval) && nval<-0.75) {
nxyz[0] = double(nijk[0]);
nxyz[1] = double(nijk[1]);
nxyz[2] = double(nijk[2]);
cp = closestPoint(nxyz, idxAcc.getValue(nijk));
dir1 = xyz - cp;
dir1.normalize();
dir2 = nxyz - cp;
dir2.normalize();
if (dir2.dot(dir1) > 0.0) {
dist = -dist;
break;
}
}
}
}
} // active voxel loop
} // leaf node loop
}
private:
Vec3d closestPoint(const Vec3d& center, Int32 polyIdx) const
{
Vec3d a, b, c, cp, uvw;
const size_t polygon = size_t(polyIdx);
mMesh->getIndexSpacePoint(polygon, 0, a);
mMesh->getIndexSpacePoint(polygon, 1, b);
mMesh->getIndexSpacePoint(polygon, 2, c);
cp = closestPointOnTriangleToPoint(a, c, b, center, uvw);
if (4 == mMesh->vertexCount(polygon)) {
mMesh->getIndexSpacePoint(polygon, 3, b);
c = closestPointOnTriangleToPoint(a, b, c, center, uvw);
if ((center - c).lengthSqr() < (center - cp).lengthSqr()) {
cp = c;
}
}
return cp;
}
LeafNodeType ** const mDistNodes;
TreeType const * const mDistTree;
Int32TreeType const * const mIndexTree;
MeshDataAdapter const * const mMesh;
SharedPtr<LocalDataTable> mLocalDataTable;
}; // ComputeIntersectingVoxelSign
////////////////////////////////////////
template<typename LeafNodeType>
inline void
maskNodeInternalNeighbours(const Index pos, bool (&mask)[26])
{
using NodeT = LeafNodeType;
const Coord ijk = NodeT::offsetToLocalCoord(pos);
// Face adjacent neighbours
// i+1, j, k
mask[0] = ijk[0] != (NodeT::DIM - 1);
// i-1, j, k
mask[1] = ijk[0] != 0;
// i, j+1, k
mask[2] = ijk[1] != (NodeT::DIM - 1);
// i, j-1, k
mask[3] = ijk[1] != 0;
// i, j, k+1
mask[4] = ijk[2] != (NodeT::DIM - 1);
// i, j, k-1
mask[5] = ijk[2] != 0;
// Edge adjacent neighbour
// i+1, j, k-1
mask[6] = mask[0] && mask[5];
// i-1, j, k-1
mask[7] = mask[1] && mask[5];
// i+1, j, k+1
mask[8] = mask[0] && mask[4];
// i-1, j, k+1
mask[9] = mask[1] && mask[4];
// i+1, j+1, k
mask[10] = mask[0] && mask[2];
// i-1, j+1, k
mask[11] = mask[1] && mask[2];
// i+1, j-1, k
mask[12] = mask[0] && mask[3];
// i-1, j-1, k
mask[13] = mask[1] && mask[3];
// i, j-1, k+1
mask[14] = mask[3] && mask[4];
// i, j-1, k-1
mask[15] = mask[3] && mask[5];
// i, j+1, k+1
mask[16] = mask[2] && mask[4];
// i, j+1, k-1
mask[17] = mask[2] && mask[5];
// Corner adjacent neighbours
// i-1, j-1, k-1
mask[18] = mask[1] && mask[3] && mask[5];
// i-1, j-1, k+1
mask[19] = mask[1] && mask[3] && mask[4];
// i+1, j-1, k+1
mask[20] = mask[0] && mask[3] && mask[4];
// i+1, j-1, k-1
mask[21] = mask[0] && mask[3] && mask[5];
// i-1, j+1, k-1
mask[22] = mask[1] && mask[2] && mask[5];
// i-1, j+1, k+1
mask[23] = mask[1] && mask[2] && mask[4];
// i+1, j+1, k+1
mask[24] = mask[0] && mask[2] && mask[4];
// i+1, j+1, k-1
mask[25] = mask[0] && mask[2] && mask[5];
}
template<typename Compare, typename LeafNodeType>
inline bool
checkNeighbours(const Index pos, const typename LeafNodeType::ValueType * data, bool (&mask)[26])
{
using NodeT = LeafNodeType;
// i, j, k - 1
if (mask[5] && Compare::check(data[pos - 1])) return true;
// i, j, k + 1
if (mask[4] && Compare::check(data[pos + 1])) return true;
// i, j - 1, k
if (mask[3] && Compare::check(data[pos - NodeT::DIM])) return true;
// i, j + 1, k
if (mask[2] && Compare::check(data[pos + NodeT::DIM])) return true;
// i - 1, j, k
if (mask[1] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM])) return true;
// i + 1, j, k
if (mask[0] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
// i+1, j, k-1
if (mask[6] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM])) return true;
// i-1, j, k-1
if (mask[7] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - 1])) return true;
// i+1, j, k+1
if (mask[8] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + 1])) return true;
// i-1, j, k+1
if (mask[9] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + 1])) return true;
// i+1, j+1, k
if (mask[10] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
// i-1, j+1, k
if (mask[11] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM])) return true;
// i+1, j-1, k
if (mask[12] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
// i-1, j-1, k
if (mask[13] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM])) return true;
// i, j-1, k+1
if (mask[14] && Compare::check(data[pos - NodeT::DIM + 1])) return true;
// i, j-1, k-1
if (mask[15] && Compare::check(data[pos - NodeT::DIM - 1])) return true;
// i, j+1, k+1
if (mask[16] && Compare::check(data[pos + NodeT::DIM + 1])) return true;
// i, j+1, k-1
if (mask[17] && Compare::check(data[pos + NodeT::DIM - 1])) return true;
// i-1, j-1, k-1
if (mask[18] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
// i-1, j-1, k+1
if (mask[19] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
// i+1, j-1, k+1
if (mask[20] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM + 1])) return true;
// i+1, j-1, k-1
if (mask[21] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM - NodeT::DIM - 1])) return true;
// i-1, j+1, k-1
if (mask[22] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
// i-1, j+1, k+1
if (mask[23] && Compare::check(data[pos - NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
// i+1, j+1, k+1
if (mask[24] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM + 1])) return true;
// i+1, j+1, k-1
if (mask[25] && Compare::check(data[pos + NodeT::DIM * NodeT::DIM + NodeT::DIM - 1])) return true;
return false;
}
template<typename Compare, typename AccessorType>
inline bool
checkNeighbours(const Coord& ijk, AccessorType& acc, bool (&mask)[26])
{
for (Int32 m = 0; m < 26; ++m) {
if (!mask[m] && Compare::check(acc.getValue(ijk + util::COORD_OFFSETS[m]))) {
return true;
}
}
return false;
}
template<typename TreeType>
struct ValidateIntersectingVoxels
{
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
struct IsNegative { static bool check(const ValueType v) { return v < ValueType(0.0); } };
ValidateIntersectingVoxels(TreeType& tree, std::vector<LeafNodeType*>& nodes)
: mTree(&tree)
, mNodes(nodes.empty() ? nullptr : &nodes[0])
{
}
void operator()(const tbb::blocked_range<size_t>& range) const
{
tree::ValueAccessor<const TreeType> acc(*mTree);
bool neighbourMask[26];
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
LeafNodeType& node = *mNodes[n];
ValueType* data = node.buffer().data();
typename LeafNodeType::ValueOnCIter it;
for (it = node.cbeginValueOn(); it; ++it) {
const Index pos = it.pos();
ValueType& dist = data[pos];
if (dist < 0.0 || dist > 0.75) continue;
// Mask node internal neighbours
maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
const bool hasNegativeNeighbour =
checkNeighbours<IsNegative, LeafNodeType>(pos, data, neighbourMask) ||
checkNeighbours<IsNegative>(node.offsetToGlobalCoord(pos), acc, neighbourMask);
if (!hasNegativeNeighbour) {
// push over boundary voxel distance
dist = ValueType(0.75) + Tolerance<ValueType>::epsilon();
}
}
}
}
TreeType * const mTree;
LeafNodeType ** const mNodes;
}; // ValidateIntersectingVoxels
template<typename TreeType>
struct RemoveSelfIntersectingSurface
{
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
struct Comp { static bool check(const ValueType v) { return !(v > ValueType(0.75)); } };
RemoveSelfIntersectingSurface(std::vector<LeafNodeType*>& nodes,
TreeType& distTree, Int32TreeType& indexTree)
: mNodes(nodes.empty() ? nullptr : &nodes[0])
, mDistTree(&distTree)
, mIndexTree(&indexTree)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const
{
tree::ValueAccessor<const TreeType> distAcc(*mDistTree);
tree::ValueAccessor<Int32TreeType> idxAcc(*mIndexTree);
bool neighbourMask[26];
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
LeafNodeType& distNode = *mNodes[n];
ValueType* data = distNode.buffer().data();
typename Int32TreeType::LeafNodeType* idxNode =
idxAcc.probeLeaf(distNode.origin());
typename LeafNodeType::ValueOnCIter it;
for (it = distNode.cbeginValueOn(); it; ++it) {
const Index pos = it.pos();
if (!(data[pos] > 0.75)) continue;
// Mask node internal neighbours
maskNodeInternalNeighbours<LeafNodeType>(pos, neighbourMask);
const bool hasBoundaryNeighbour =
checkNeighbours<Comp, LeafNodeType>(pos, data, neighbourMask) ||
checkNeighbours<Comp>(distNode.offsetToGlobalCoord(pos),distAcc,neighbourMask);
if (!hasBoundaryNeighbour) {
distNode.setValueOff(pos);
idxNode->setValueOff(pos);
}
}
}
}
LeafNodeType * * const mNodes;
TreeType * const mDistTree;
Int32TreeType * const mIndexTree;
}; // RemoveSelfIntersectingSurface
////////////////////////////////////////
template<typename NodeType>
struct ReleaseChildNodes
{
ReleaseChildNodes(NodeType ** nodes) : mNodes(nodes) {}
void operator()(const tbb::blocked_range<size_t>& range) const {
using NodeMaskType = typename NodeType::NodeMaskType;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
const_cast<NodeMaskType&>(mNodes[n]->getChildMask()).setOff();
}
}
NodeType ** const mNodes;
};
template<typename TreeType>
inline void
releaseLeafNodes(TreeType& tree)
{
using RootNodeType = typename TreeType::RootNodeType;
using NodeChainType = typename RootNodeType::NodeChainType;
using InternalNodeType = typename boost::mpl::at<NodeChainType, boost::mpl::int_<1> >::type;
std::vector<InternalNodeType*> nodes;
tree.getNodes(nodes);
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
ReleaseChildNodes<InternalNodeType>(nodes.empty() ? nullptr : &nodes[0]));
}
template<typename TreeType>
struct StealUniqueLeafNodes
{
using LeafNodeType = typename TreeType::LeafNodeType;
StealUniqueLeafNodes(TreeType& lhsTree, TreeType& rhsTree,
std::vector<LeafNodeType*>& overlappingNodes)
: mLhsTree(&lhsTree)
, mRhsTree(&rhsTree)
, mNodes(&overlappingNodes)
{
}
void operator()() const {
std::vector<LeafNodeType*> rhsLeafNodes;
rhsLeafNodes.reserve(mRhsTree->leafCount());
//mRhsTree->getNodes(rhsLeafNodes);
//releaseLeafNodes(*mRhsTree);
mRhsTree->stealNodes(rhsLeafNodes);
tree::ValueAccessor<TreeType> acc(*mLhsTree);
for (size_t n = 0, N = rhsLeafNodes.size(); n < N; ++n) {
if (!acc.probeLeaf(rhsLeafNodes[n]->origin())) {
acc.addLeaf(rhsLeafNodes[n]);
} else {
mNodes->push_back(rhsLeafNodes[n]);
}
}
}
private:
TreeType * const mLhsTree;
TreeType * const mRhsTree;
std::vector<LeafNodeType*> * const mNodes;
};
template<typename DistTreeType, typename IndexTreeType>
inline void
combineData(DistTreeType& lhsDist, IndexTreeType& lhsIdx,
DistTreeType& rhsDist, IndexTreeType& rhsIdx)
{
using DistLeafNodeType = typename DistTreeType::LeafNodeType;
using IndexLeafNodeType = typename IndexTreeType::LeafNodeType;
std::vector<DistLeafNodeType*> overlappingDistNodes;
std::vector<IndexLeafNodeType*> overlappingIdxNodes;
// Steal unique leafnodes
tbb::task_group tasks;
tasks.run(StealUniqueLeafNodes<DistTreeType>(lhsDist, rhsDist, overlappingDistNodes));
tasks.run(StealUniqueLeafNodes<IndexTreeType>(lhsIdx, rhsIdx, overlappingIdxNodes));
tasks.wait();
// Combine overlapping leaf nodes
if (!overlappingDistNodes.empty() && !overlappingIdxNodes.empty()) {
tbb::parallel_for(tbb::blocked_range<size_t>(0, overlappingDistNodes.size()),
CombineLeafNodes<DistTreeType>(lhsDist, lhsIdx,
&overlappingDistNodes[0], &overlappingIdxNodes[0]));
}
}
/// @brief TBB body object to voxelize a mesh of triangles and/or quads into a collection
/// of VDB grids, namely a squared distance grid, a closest primitive grid and an
/// intersecting voxels grid (masks the mesh intersecting voxels)
/// @note Only the leaf nodes that intersect the mesh are allocated, and only voxels in
/// a narrow band (of two to three voxels in proximity to the mesh's surface) are activated.
/// They are populated with distance values and primitive indices.
template<typename TreeType>
struct VoxelizationData {
using Ptr = std::unique_ptr<VoxelizationData>;
using ValueType = typename TreeType::ValueType;
using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
using UCharTreeType = typename TreeType::template ValueConverter<unsigned char>::Type;
using FloatTreeAcc = tree::ValueAccessor<TreeType>;
using Int32TreeAcc = tree::ValueAccessor<Int32TreeType>;
using UCharTreeAcc = tree::ValueAccessor<UCharTreeType>;
VoxelizationData()
: distTree(std::numeric_limits<ValueType>::max())
, distAcc(distTree)
, indexTree(Int32(util::INVALID_IDX))
, indexAcc(indexTree)
, primIdTree(MaxPrimId)
, primIdAcc(primIdTree)
, mPrimCount(0)
{
}
TreeType distTree;
FloatTreeAcc distAcc;
Int32TreeType indexTree;
Int32TreeAcc indexAcc;
UCharTreeType primIdTree;
UCharTreeAcc primIdAcc;
unsigned char getNewPrimId() {
if (mPrimCount == MaxPrimId || primIdTree.leafCount() > 1000) {
mPrimCount = 0;
primIdTree.clear();
}
return mPrimCount++;
}
private:
enum { MaxPrimId = 100 };
unsigned char mPrimCount;
};
template<typename TreeType, typename MeshDataAdapter, typename Interrupter = util::NullInterrupter>
class VoxelizePolygons
{
public:
using VoxelizationDataType = VoxelizationData<TreeType>;
using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
VoxelizePolygons(DataTable& dataTable,
const MeshDataAdapter& mesh,
Interrupter* interrupter = nullptr)
: mDataTable(&dataTable)
, mMesh(&mesh)
, mInterrupter(interrupter)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
typename VoxelizationDataType::Ptr& dataPtr = mDataTable->local();
if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
Triangle prim;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
if (this->wasInterrupted()) {
tbb::task::self().cancel_group_execution();
break;
}
const size_t numVerts = mMesh->vertexCount(n);
// rasterize triangles and quads.
if (numVerts == 3 || numVerts == 4) {
prim.index = Int32(n);
mMesh->getIndexSpacePoint(n, 0, prim.a);
mMesh->getIndexSpacePoint(n, 1, prim.b);
mMesh->getIndexSpacePoint(n, 2, prim.c);
evalTriangle(prim, *dataPtr);
if (numVerts == 4) {
mMesh->getIndexSpacePoint(n, 3, prim.b);
evalTriangle(prim, *dataPtr);
}
}
}
}
private:
bool wasInterrupted() const { return mInterrupter && mInterrupter->wasInterrupted(); }
struct Triangle { Vec3d a, b, c; Int32 index; };
struct SubTask
{
enum { POLYGON_LIMIT = 1000 };
SubTask(const Triangle& prim, DataTable& dataTable,
int subdivisionCount, size_t polygonCount)
: mLocalDataTable(&dataTable)
, mPrim(prim)
, mSubdivisionCount(subdivisionCount)
, mPolygonCount(polygonCount)
{
}
void operator()() const
{
if (mSubdivisionCount <= 0 || mPolygonCount >= POLYGON_LIMIT) {
typename VoxelizationDataType::Ptr& dataPtr = mLocalDataTable->local();
if (!dataPtr) dataPtr.reset(new VoxelizationDataType());
voxelizeTriangle(mPrim, *dataPtr);
} else {
spawnTasks(mPrim, *mLocalDataTable, mSubdivisionCount, mPolygonCount);
}
}
DataTable * const mLocalDataTable;
Triangle const mPrim;
int const mSubdivisionCount;
size_t const mPolygonCount;
}; // struct SubTask
inline static int evalSubdivisionCount(const Triangle& prim)
{
const double ax = prim.a[0], bx = prim.b[0], cx = prim.c[0];
const double dx = std::max(ax, std::max(bx, cx)) - std::min(ax, std::min(bx, cx));
const double ay = prim.a[1], by = prim.b[1], cy = prim.c[1];
const double dy = std::max(ay, std::max(by, cy)) - std::min(ay, std::min(by, cy));
const double az = prim.a[2], bz = prim.b[2], cz = prim.c[2];
const double dz = std::max(az, std::max(bz, cz)) - std::min(az, std::min(bz, cz));
return int(std::max(dx, std::max(dy, dz)) / double(TreeType::LeafNodeType::DIM * 2));
}
void evalTriangle(const Triangle& prim, VoxelizationDataType& data) const
{
const size_t polygonCount = mMesh->polygonCount();
const int subdivisionCount =
polygonCount < SubTask::POLYGON_LIMIT ? evalSubdivisionCount(prim) : 0;
if (subdivisionCount <= 0) {
voxelizeTriangle(prim, data);
} else {
spawnTasks(prim, *mDataTable, subdivisionCount, polygonCount);
}
}
static void spawnTasks(
const Triangle& mainPrim, DataTable& dataTable, int subdivisionCount, size_t polygonCount)
{
subdivisionCount -= 1;
polygonCount *= 4;
tbb::task_group tasks;
const Vec3d ac = (mainPrim.a + mainPrim.c) * 0.5;
const Vec3d bc = (mainPrim.b + mainPrim.c) * 0.5;
const Vec3d ab = (mainPrim.a + mainPrim.b) * 0.5;
Triangle prim;
prim.index = mainPrim.index;
prim.a = mainPrim.a;
prim.b = ab;
prim.c = ac;
tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
prim.a = ab;
prim.b = bc;
prim.c = ac;
tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
prim.a = ab;
prim.b = mainPrim.b;
prim.c = bc;
tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
prim.a = ac;
prim.b = bc;
prim.c = mainPrim.c;
tasks.run(SubTask(prim, dataTable, subdivisionCount, polygonCount));
tasks.wait();
}
static void voxelizeTriangle(const Triangle& prim, VoxelizationDataType& data)
{
std::deque<Coord> coordList;
Coord ijk, nijk;
ijk = Coord::floor(prim.a);
coordList.push_back(ijk);
computeDistance(ijk, prim, data);
unsigned char primId = data.getNewPrimId();
data.primIdAcc.setValueOnly(ijk, primId);
while (!coordList.empty()) {
ijk = coordList.back();
coordList.pop_back();
for (Int32 i = 0; i < 26; ++i) {
nijk = ijk + util::COORD_OFFSETS[i];
if (primId != data.primIdAcc.getValue(nijk)) {
data.primIdAcc.setValueOnly(nijk, primId);
if(computeDistance(nijk, prim, data)) coordList.push_back(nijk);
}
}
}
}
static bool computeDistance(const Coord& ijk, const Triangle& prim, VoxelizationDataType& data)
{
Vec3d uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
using ValueType = typename TreeType::ValueType;
const ValueType dist = ValueType((voxelCenter -
closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, voxelCenter, uvw)).lengthSqr());
const ValueType oldDist = data.distAcc.getValue(ijk);
if (dist < oldDist) {
data.distAcc.setValue(ijk, dist);
data.indexAcc.setValue(ijk, prim.index);
} else if (math::isExactlyEqual(dist, oldDist)) {
// makes reduction deterministic when different polygons
// produce the same distance value.
data.indexAcc.setValueOnly(ijk, std::min(prim.index, data.indexAcc.getValue(ijk)));
}
return !(dist > 0.75); // true if the primitive intersects the voxel.
}
DataTable * const mDataTable;
MeshDataAdapter const * const mMesh;
Interrupter * const mInterrupter;
}; // VoxelizePolygons
////////////////////////////////////////
template<typename TreeType>
struct DiffLeafNodeMask
{
using AccessorType = typename tree::ValueAccessor<TreeType>;
using LeafNodeType = typename TreeType::LeafNodeType;
using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
DiffLeafNodeMask(const TreeType& rhsTree,
std::vector<BoolLeafNodeType*>& lhsNodes)
: mRhsTree(&rhsTree), mLhsNodes(lhsNodes.empty() ? nullptr : &lhsNodes[0])
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
tree::ValueAccessor<const TreeType> acc(*mRhsTree);
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
BoolLeafNodeType* lhsNode = mLhsNodes[n];
const LeafNodeType* rhsNode = acc.probeConstLeaf(lhsNode->origin());
if (rhsNode) lhsNode->topologyDifference(*rhsNode, false);
}
}
private:
TreeType const * const mRhsTree;
BoolLeafNodeType ** const mLhsNodes;
};
template<typename LeafNodeTypeA, typename LeafNodeTypeB>
struct UnionValueMasks
{
UnionValueMasks(std::vector<LeafNodeTypeA*>& nodesA, std::vector<LeafNodeTypeB*>& nodesB)
: mNodesA(nodesA.empty() ? nullptr : &nodesA[0])
, mNodesB(nodesB.empty() ? nullptr : &nodesB[0])
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
mNodesA[n]->topologyUnion(*mNodesB[n]);
}
}
private:
LeafNodeTypeA ** const mNodesA;
LeafNodeTypeB ** const mNodesB;
};
template<typename TreeType>
struct ConstructVoxelMask
{
using LeafNodeType = typename TreeType::LeafNodeType;
using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
ConstructVoxelMask(BoolTreeType& maskTree, const TreeType& tree,
std::vector<LeafNodeType*>& nodes)
: mTree(&tree)
, mNodes(nodes.empty() ? nullptr : &nodes[0])
, mLocalMaskTree(false)
, mMaskTree(&maskTree)
{
}
ConstructVoxelMask(ConstructVoxelMask& rhs, tbb::split)
: mTree(rhs.mTree)
, mNodes(rhs.mNodes)
, mLocalMaskTree(false)
, mMaskTree(&mLocalMaskTree)
{
}
void operator()(const tbb::blocked_range<size_t>& range)
{
using Iterator = typename LeafNodeType::ValueOnCIter;
tree::ValueAccessor<const TreeType> acc(*mTree);
tree::ValueAccessor<BoolTreeType> maskAcc(*mMaskTree);
Coord ijk, nijk, localCorod;
Index pos, npos;
for (size_t n = range.begin(); n != range.end(); ++n) {
LeafNodeType& node = *mNodes[n];
CoordBBox bbox = node.getNodeBoundingBox();
bbox.expand(-1);
BoolLeafNodeType& maskNode = *maskAcc.touchLeaf(node.origin());
for (Iterator it = node.cbeginValueOn(); it; ++it) {
ijk = it.getCoord();
pos = it.pos();
localCorod = LeafNodeType::offsetToLocalCoord(pos);
if (localCorod[2] < int(LeafNodeType::DIM - 1)) {
npos = pos + 1;
if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
} else {
nijk = ijk.offsetBy(0, 0, 1);
if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
}
if (localCorod[2] > 0) {
npos = pos - 1;
if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
} else {
nijk = ijk.offsetBy(0, 0, -1);
if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
}
if (localCorod[1] < int(LeafNodeType::DIM - 1)) {
npos = pos + LeafNodeType::DIM;
if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
} else {
nijk = ijk.offsetBy(0, 1, 0);
if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
}
if (localCorod[1] > 0) {
npos = pos - LeafNodeType::DIM;
if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
} else {
nijk = ijk.offsetBy(0, -1, 0);
if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
}
if (localCorod[0] < int(LeafNodeType::DIM - 1)) {
npos = pos + LeafNodeType::DIM * LeafNodeType::DIM;
if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
} else {
nijk = ijk.offsetBy(1, 0, 0);
if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
}
if (localCorod[0] > 0) {
npos = pos - LeafNodeType::DIM * LeafNodeType::DIM;
if (!node.isValueOn(npos)) maskNode.setValueOn(npos);
} else {
nijk = ijk.offsetBy(-1, 0, 0);
if (!acc.isValueOn(nijk)) maskAcc.setValueOn(nijk);
}
}
}
}
void join(ConstructVoxelMask& rhs) { mMaskTree->merge(*rhs.mMaskTree); }
private:
TreeType const * const mTree;
LeafNodeType ** const mNodes;
BoolTreeType mLocalMaskTree;
BoolTreeType * const mMaskTree;
};
/// @note The interior and exterior widths should be in world space units and squared.
template<typename TreeType, typename MeshDataAdapter>
struct ExpandNarrowband
{
using ValueType = typename TreeType::ValueType;
using LeafNodeType = typename TreeType::LeafNodeType;
using NodeMaskType = typename LeafNodeType::NodeMaskType;
using Int32TreeType = typename TreeType::template ValueConverter<Int32>::Type;
using Int32LeafNodeType = typename Int32TreeType::LeafNodeType;
using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
using BoolLeafNodeType = typename BoolTreeType::LeafNodeType;
struct Fragment
{
Int32 idx, x, y, z;
ValueType dist;
Fragment() : idx(0), x(0), y(0), z(0), dist(0.0) {}
Fragment(Int32 idx_, Int32 x_, Int32 y_, Int32 z_, ValueType dist_)
: idx(idx_), x(x_), y(y_), z(z_), dist(dist_)
{
}
bool operator<(const Fragment& rhs) const { return idx < rhs.idx; }
}; // struct Fragment
////////////////////
ExpandNarrowband(
std::vector<BoolLeafNodeType*>& maskNodes,
BoolTreeType& maskTree,
TreeType& distTree,
Int32TreeType& indexTree,
const MeshDataAdapter& mesh,
ValueType exteriorBandWidth,
ValueType interiorBandWidth,
ValueType voxelSize)
: mMaskNodes(maskNodes.empty() ? nullptr : &maskNodes[0])
, mMaskTree(&maskTree)
, mDistTree(&distTree)
, mIndexTree(&indexTree)
, mMesh(&mesh)
, mNewMaskTree(false)
, mDistNodes()
, mUpdatedDistNodes()
, mIndexNodes()
, mUpdatedIndexNodes()
, mExteriorBandWidth(exteriorBandWidth)
, mInteriorBandWidth(interiorBandWidth)
, mVoxelSize(voxelSize)
{
}
ExpandNarrowband(const ExpandNarrowband& rhs, tbb::split)
: mMaskNodes(rhs.mMaskNodes)
, mMaskTree(rhs.mMaskTree)
, mDistTree(rhs.mDistTree)
, mIndexTree(rhs.mIndexTree)
, mMesh(rhs.mMesh)
, mNewMaskTree(false)
, mDistNodes()
, mUpdatedDistNodes()
, mIndexNodes()
, mUpdatedIndexNodes()
, mExteriorBandWidth(rhs.mExteriorBandWidth)
, mInteriorBandWidth(rhs.mInteriorBandWidth)
, mVoxelSize(rhs.mVoxelSize)
{
}
void join(ExpandNarrowband& rhs)
{
mDistNodes.insert(mDistNodes.end(), rhs.mDistNodes.begin(), rhs.mDistNodes.end());
mIndexNodes.insert(mIndexNodes.end(), rhs.mIndexNodes.begin(), rhs.mIndexNodes.end());
mUpdatedDistNodes.insert(mUpdatedDistNodes.end(),
rhs.mUpdatedDistNodes.begin(), rhs.mUpdatedDistNodes.end());
mUpdatedIndexNodes.insert(mUpdatedIndexNodes.end(),
rhs.mUpdatedIndexNodes.begin(), rhs.mUpdatedIndexNodes.end());
mNewMaskTree.merge(rhs.mNewMaskTree);
}
void operator()(const tbb::blocked_range<size_t>& range)
{
tree::ValueAccessor<BoolTreeType> newMaskAcc(mNewMaskTree);
tree::ValueAccessor<TreeType> distAcc(*mDistTree);
tree::ValueAccessor<Int32TreeType> indexAcc(*mIndexTree);
std::vector<Fragment> fragments;
fragments.reserve(256);
std::unique_ptr<LeafNodeType> newDistNodePt;
std::unique_ptr<Int32LeafNodeType> newIndexNodePt;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
BoolLeafNodeType& maskNode = *mMaskNodes[n];
if (maskNode.isEmpty()) continue;
// Setup local caches
const Coord& origin = maskNode.origin();
LeafNodeType * distNodePt = distAcc.probeLeaf(origin);
Int32LeafNodeType * indexNodePt = indexAcc.probeLeaf(origin);
assert(!distNodePt == !indexNodePt);
bool usingNewNodes = false;
if (!distNodePt && !indexNodePt) {
const ValueType backgroundDist = distAcc.getValue(origin);
if (!newDistNodePt.get() && !newIndexNodePt.get()) {
newDistNodePt.reset(new LeafNodeType(origin, backgroundDist));
newIndexNodePt.reset(new Int32LeafNodeType(origin, indexAcc.getValue(origin)));
} else {
if ((backgroundDist < ValueType(0.0)) !=
(newDistNodePt->getValue(0) < ValueType(0.0))) {
newDistNodePt->buffer().fill(backgroundDist);
}
newDistNodePt->setOrigin(origin);
newIndexNodePt->setOrigin(origin);
}
distNodePt = newDistNodePt.get();
indexNodePt = newIndexNodePt.get();
usingNewNodes = true;
}
// Gather neighbour information
CoordBBox bbox(Coord::max(), Coord::min());
for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
bbox.expand(it.getCoord());
}
bbox.expand(1);
gatherFragments(fragments, bbox, distAcc, indexAcc);
// Compute first voxel layer
bbox = maskNode.getNodeBoundingBox();
NodeMaskType mask;
bool updatedLeafNodes = false;
for (typename BoolLeafNodeType::ValueOnIter it = maskNode.beginValueOn(); it; ++it) {
const Coord ijk = it.getCoord();
if (updateVoxel(ijk, 5, fragments, *distNodePt, *indexNodePt, &updatedLeafNodes)) {
for (Int32 i = 0; i < 6; ++i) {
const Coord nijk = ijk + util::COORD_OFFSETS[i];
if (bbox.isInside(nijk)) {
mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
} else {
newMaskAcc.setValueOn(nijk);
}
}
for (Int32 i = 6; i < 26; ++i) {
const Coord nijk = ijk + util::COORD_OFFSETS[i];
if (bbox.isInside(nijk)) {
mask.setOn(BoolLeafNodeType::coordToOffset(nijk));
}
}
}
}
if (updatedLeafNodes) {
// Compute second voxel layer
mask -= indexNodePt->getValueMask();
for (typename NodeMaskType::OnIterator it = mask.beginOn(); it; ++it) {
const Index pos = it.pos();
const Coord ijk = maskNode.origin() + LeafNodeType::offsetToLocalCoord(pos);
if (updateVoxel(ijk, 6, fragments, *distNodePt, *indexNodePt)) {
for (Int32 i = 0; i < 6; ++i) {
newMaskAcc.setValueOn(ijk + util::COORD_OFFSETS[i]);
}
}
}
// Export new distance values
if (usingNewNodes) {
newDistNodePt->topologyUnion(*newIndexNodePt);
mDistNodes.push_back(newDistNodePt.release());
mIndexNodes.push_back(newIndexNodePt.release());
} else {
mUpdatedDistNodes.push_back(distNodePt);
mUpdatedIndexNodes.push_back(indexNodePt);
}
}
} // end leafnode loop
}
//////////
BoolTreeType& newMaskTree() { return mNewMaskTree; }
std::vector<LeafNodeType*>& newDistNodes() { return mDistNodes; }
std::vector<LeafNodeType*>& updatedDistNodes() { return mUpdatedDistNodes; }
std::vector<Int32LeafNodeType*>& newIndexNodes() { return mIndexNodes; }
std::vector<Int32LeafNodeType*>& updatedIndexNodes() { return mUpdatedIndexNodes; }
private:
/// @note The output fragment list is ordered by the primitive index
void
gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
tree::ValueAccessor<TreeType>& distAcc, tree::ValueAccessor<Int32TreeType>& indexAcc)
{
fragments.clear();
const Coord nodeMin = bbox.min() & ~(LeafNodeType::DIM - 1);
const Coord nodeMax = bbox.max() & ~(LeafNodeType::DIM - 1);
CoordBBox region;
Coord ijk;
for (ijk[0] = nodeMin[0]; ijk[0] <= nodeMax[0]; ijk[0] += LeafNodeType::DIM) {
for (ijk[1] = nodeMin[1]; ijk[1] <= nodeMax[1]; ijk[1] += LeafNodeType::DIM) {
for (ijk[2] = nodeMin[2]; ijk[2] <= nodeMax[2]; ijk[2] += LeafNodeType::DIM) {
if (LeafNodeType* distleaf = distAcc.probeLeaf(ijk)) {
region.min() = Coord::maxComponent(bbox.min(), ijk);
region.max() = Coord::minComponent(bbox.max(),
ijk.offsetBy(LeafNodeType::DIM - 1));
gatherFragments(fragments, region, *distleaf, *indexAcc.probeLeaf(ijk));
}
}
}
}
std::sort(fragments.begin(), fragments.end());
}
void
gatherFragments(std::vector<Fragment>& fragments, const CoordBBox& bbox,
const LeafNodeType& distLeaf, const Int32LeafNodeType& idxLeaf) const
{
const typename LeafNodeType::NodeMaskType& mask = distLeaf.getValueMask();
const ValueType* distData = distLeaf.buffer().data();
const Int32* idxData = idxLeaf.buffer().data();
for (int x = bbox.min()[0]; x <= bbox.max()[0]; ++x) {
const Index xPos = (x & (LeafNodeType::DIM - 1u)) << (2 * LeafNodeType::LOG2DIM);
for (int y = bbox.min()[1]; y <= bbox.max()[1]; ++y) {
const Index yPos = xPos + ((y & (LeafNodeType::DIM - 1u)) << LeafNodeType::LOG2DIM);
for (int z = bbox.min()[2]; z <= bbox.max()[2]; ++z) {
const Index pos = yPos + (z & (LeafNodeType::DIM - 1u));
if (mask.isOn(pos)) {
fragments.push_back(Fragment(idxData[pos],x,y,z, std::abs(distData[pos])));
}
}
}
}
}
/// @note This method expects the fragment list to be ordered by the primitive index
/// to avoid redundant distance computations.
ValueType
computeDistance(const Coord& ijk, const Int32 manhattanLimit,
const std::vector<Fragment>& fragments, Int32& closestPrimIdx) const
{
Vec3d a, b, c, uvw, voxelCenter(ijk[0], ijk[1], ijk[2]);
double primDist, tmpDist, dist = std::numeric_limits<double>::max();
Int32 lastIdx = Int32(util::INVALID_IDX);
for (size_t n = 0, N = fragments.size(); n < N; ++n) {
const Fragment& fragment = fragments[n];
if (lastIdx == fragment.idx) continue;
const Int32 dx = std::abs(fragment.x - ijk[0]);
const Int32 dy = std::abs(fragment.y - ijk[1]);
const Int32 dz = std::abs(fragment.z - ijk[2]);
const Int32 manhattan = dx + dy + dz;
if (manhattan > manhattanLimit) continue;
lastIdx = fragment.idx;
const size_t polygon = size_t(lastIdx);
mMesh->getIndexSpacePoint(polygon, 0, a);
mMesh->getIndexSpacePoint(polygon, 1, b);
mMesh->getIndexSpacePoint(polygon, 2, c);
primDist = (voxelCenter -
closestPointOnTriangleToPoint(a, c, b, voxelCenter, uvw)).lengthSqr();
// Split quad into a second triangle
if (4 == mMesh->vertexCount(polygon)) {
mMesh->getIndexSpacePoint(polygon, 3, b);
tmpDist = (voxelCenter - closestPointOnTriangleToPoint(
a, b, c, voxelCenter, uvw)).lengthSqr();
if (tmpDist < primDist) primDist = tmpDist;
}
if (primDist < dist) {
dist = primDist;
closestPrimIdx = lastIdx;
}
}
return ValueType(std::sqrt(dist)) * mVoxelSize;
}
/// @note Returns true if the current voxel was updated and neighbouring
/// voxels need to be evaluated.
bool
updateVoxel(const Coord& ijk, const Int32 manhattanLimit,
const std::vector<Fragment>& fragments,
LeafNodeType& distLeaf, Int32LeafNodeType& idxLeaf, bool* updatedLeafNodes = nullptr)
{
Int32 closestPrimIdx = 0;
const ValueType distance = computeDistance(ijk, manhattanLimit, fragments, closestPrimIdx);
const Index pos = LeafNodeType::coordToOffset(ijk);
const bool inside = distLeaf.getValue(pos) < ValueType(0.0);
bool activateNeighbourVoxels = false;
if (!inside && distance < mExteriorBandWidth) {
if (updatedLeafNodes) *updatedLeafNodes = true;
activateNeighbourVoxels = (distance + mVoxelSize) < mExteriorBandWidth;
distLeaf.setValueOnly(pos, distance);
idxLeaf.setValueOn(pos, closestPrimIdx);
} else if (inside && distance < mInteriorBandWidth) {
if (updatedLeafNodes) *updatedLeafNodes = true;
activateNeighbourVoxels = (distance + mVoxelSize) < mInteriorBandWidth;
distLeaf.setValueOnly(pos, -distance);
idxLeaf.setValueOn(pos, closestPrimIdx);
}
return activateNeighbourVoxels;
}
//////////
BoolLeafNodeType ** const mMaskNodes;
BoolTreeType * const mMaskTree;
TreeType * const mDistTree;
Int32TreeType * const mIndexTree;
MeshDataAdapter const * const mMesh;
BoolTreeType mNewMaskTree;
std::vector<LeafNodeType*> mDistNodes, mUpdatedDistNodes;
std::vector<Int32LeafNodeType*> mIndexNodes, mUpdatedIndexNodes;
const ValueType mExteriorBandWidth, mInteriorBandWidth, mVoxelSize;
}; // struct ExpandNarrowband
template<typename TreeType>
struct AddNodes {
using LeafNodeType = typename TreeType::LeafNodeType;
AddNodes(TreeType& tree, std::vector<LeafNodeType*>& nodes)
: mTree(&tree) , mNodes(&nodes)
{
}
void operator()() const {
tree::ValueAccessor<TreeType> acc(*mTree);
std::vector<LeafNodeType*>& nodes = *mNodes;
for (size_t n = 0, N = nodes.size(); n < N; ++n) {
acc.addLeaf(nodes[n]);
}
}
TreeType * const mTree;
std::vector<LeafNodeType*> * const mNodes;
}; // AddNodes
template<typename TreeType, typename Int32TreeType, typename BoolTreeType, typename MeshDataAdapter>
inline void
expandNarrowband(
TreeType& distTree,
Int32TreeType& indexTree,
BoolTreeType& maskTree,
std::vector<typename BoolTreeType::LeafNodeType*>& maskNodes,
const MeshDataAdapter& mesh,
typename TreeType::ValueType exteriorBandWidth,
typename TreeType::ValueType interiorBandWidth,
typename TreeType::ValueType voxelSize)
{
ExpandNarrowband<TreeType, MeshDataAdapter> expandOp(maskNodes, maskTree,
distTree, indexTree, mesh, exteriorBandWidth, interiorBandWidth, voxelSize);
tbb::parallel_reduce(tbb::blocked_range<size_t>(0, maskNodes.size()), expandOp);
tbb::parallel_for(tbb::blocked_range<size_t>(0, expandOp.updatedIndexNodes().size()),
UnionValueMasks<typename TreeType::LeafNodeType, typename Int32TreeType::LeafNodeType>(
expandOp.updatedDistNodes(), expandOp.updatedIndexNodes()));
tbb::task_group tasks;
tasks.run(AddNodes<TreeType>(distTree, expandOp.newDistNodes()));
tasks.run(AddNodes<Int32TreeType>(indexTree, expandOp.newIndexNodes()));
tasks.wait();
maskTree.clear();
maskTree.merge(expandOp.newMaskTree());
}
////////////////////////////////////////
// Transform values (sqrt, world space scaling and sign flip if sdf)
template<typename TreeType>
struct TransformValues
{
using LeafNodeType = typename TreeType::LeafNodeType;
using ValueType = typename TreeType::ValueType;
TransformValues(std::vector<LeafNodeType*>& nodes,
ValueType voxelSize, bool unsignedDist)
: mNodes(&nodes[0])
, mVoxelSize(voxelSize)
, mUnsigned(unsignedDist)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
typename LeafNodeType::ValueOnIter iter;
const bool udf = mUnsigned;
const ValueType w[2] = { -mVoxelSize, mVoxelSize };
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
ValueType& val = const_cast<ValueType&>(iter.getValue());
val = w[udf || (val < ValueType(0.0))] * std::sqrt(std::abs(val));
}
}
}
private:
LeafNodeType * * const mNodes;
const ValueType mVoxelSize;
const bool mUnsigned;
};
// Inactivate values outside the (exBandWidth, inBandWidth) range.
template<typename TreeType>
struct InactivateValues
{
using LeafNodeType = typename TreeType::LeafNodeType;
using ValueType = typename TreeType::ValueType;
InactivateValues(std::vector<LeafNodeType*>& nodes,
ValueType exBandWidth, ValueType inBandWidth)
: mNodes(nodes.empty() ? nullptr : &nodes[0])
, mExBandWidth(exBandWidth)
, mInBandWidth(inBandWidth)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
typename LeafNodeType::ValueOnIter iter;
const ValueType exVal = mExBandWidth;
const ValueType inVal = -mInBandWidth;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
for (iter = mNodes[n]->beginValueOn(); iter; ++iter) {
ValueType& val = const_cast<ValueType&>(iter.getValue());
const bool inside = val < ValueType(0.0);
if (inside && !(val > inVal)) {
val = inVal;
iter.setValueOff();
} else if (!inside && !(val < exVal)) {
val = exVal;
iter.setValueOff();
}
}
}
}
private:
LeafNodeType * * const mNodes;
const ValueType mExBandWidth, mInBandWidth;
};
template<typename TreeType>
struct OffsetValues
{
using LeafNodeType = typename TreeType::LeafNodeType;
using ValueType = typename TreeType::ValueType;
OffsetValues(std::vector<LeafNodeType*>& nodes, ValueType offset)
: mNodes(nodes.empty() ? nullptr : &nodes[0]), mOffset(offset)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
const ValueType offset = mOffset;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
for (; iter; ++iter) {
ValueType& val = const_cast<ValueType&>(iter.getValue());
val += offset;
}
}
}
private:
LeafNodeType * * const mNodes;
const ValueType mOffset;
};
template<typename TreeType>
struct Renormalize
{
using LeafNodeType = typename TreeType::LeafNodeType;
using ValueType = typename TreeType::ValueType;
Renormalize(const TreeType& tree, const std::vector<LeafNodeType*>& nodes,
ValueType* buffer, ValueType voxelSize)
: mTree(&tree)
, mNodes(nodes.empty() ? nullptr : &nodes[0])
, mBuffer(buffer)
, mVoxelSize(voxelSize)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const
{
using Vec3Type = math::Vec3<ValueType>;
tree::ValueAccessor<const TreeType> acc(*mTree);
Coord ijk;
Vec3Type up, down;
const ValueType dx = mVoxelSize, invDx = ValueType(1.0) / mVoxelSize;
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
typename LeafNodeType::ValueOnCIter iter = mNodes[n]->cbeginValueOn();
for (; iter; ++iter) {
const ValueType phi0 = *iter;
ijk = iter.getCoord();
up[0] = acc.getValue(ijk.offsetBy(1, 0, 0)) - phi0;
up[1] = acc.getValue(ijk.offsetBy(0, 1, 0)) - phi0;
up[2] = acc.getValue(ijk.offsetBy(0, 0, 1)) - phi0;
down[0] = phi0 - acc.getValue(ijk.offsetBy(-1, 0, 0));
down[1] = phi0 - acc.getValue(ijk.offsetBy(0, -1, 0));
down[2] = phi0 - acc.getValue(ijk.offsetBy(0, 0, -1));
const ValueType normSqGradPhi = math::GodunovsNormSqrd(phi0 > 0.0, down, up);
const ValueType diff = math::Sqrt(normSqGradPhi) * invDx - ValueType(1.0);
const ValueType S = phi0 / (math::Sqrt(math::Pow2(phi0) + normSqGradPhi));
bufferData[iter.pos()] = phi0 - dx * S * diff;
}
}
}
private:
TreeType const * const mTree;
LeafNodeType const * const * const mNodes;
ValueType * const mBuffer;
const ValueType mVoxelSize;
};
template<typename TreeType>
struct MinCombine
{
using LeafNodeType = typename TreeType::LeafNodeType;
using ValueType = typename TreeType::ValueType;
MinCombine(std::vector<LeafNodeType*>& nodes, const ValueType* buffer)
: mNodes(nodes.empty() ? nullptr : &nodes[0]), mBuffer(buffer)
{
}
void operator()(const tbb::blocked_range<size_t>& range) const {
for (size_t n = range.begin(), N = range.end(); n < N; ++n) {
const ValueType* bufferData = &mBuffer[n * LeafNodeType::SIZE];
typename LeafNodeType::ValueOnIter iter = mNodes[n]->beginValueOn();
for (; iter; ++iter) {
ValueType& val = const_cast<ValueType&>(iter.getValue());
val = std::min(val, bufferData[iter.pos()]);
}
}
}
private:
LeafNodeType * * const mNodes;
ValueType const * const mBuffer;
};
} // mesh_to_volume_internal namespace
////////////////////////////////////////
// Utility method implementation
template <typename FloatTreeT>
inline void
traceExteriorBoundaries(FloatTreeT& tree)
{
using ConnectivityTable = mesh_to_volume_internal::LeafNodeConnectivityTable<FloatTreeT>;
ConnectivityTable nodeConnectivity(tree);
std::vector<size_t> zStartNodes, yStartNodes, xStartNodes;
for (size_t n = 0; n < nodeConnectivity.size(); ++n) {
if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevX()[n]) {
xStartNodes.push_back(n);
}
if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevY()[n]) {
yStartNodes.push_back(n);
}
if (ConnectivityTable::INVALID_OFFSET == nodeConnectivity.offsetsPrevZ()[n]) {
zStartNodes.push_back(n);
}
}
using SweepingOp = mesh_to_volume_internal::SweepExteriorSign<FloatTreeT>;
tbb::parallel_for(tbb::blocked_range<size_t>(0, zStartNodes.size()),
SweepingOp(SweepingOp::Z_AXIS, zStartNodes, nodeConnectivity));
tbb::parallel_for(tbb::blocked_range<size_t>(0, yStartNodes.size()),
SweepingOp(SweepingOp::Y_AXIS, yStartNodes, nodeConnectivity));
tbb::parallel_for(tbb::blocked_range<size_t>(0, xStartNodes.size()),
SweepingOp(SweepingOp::X_AXIS, xStartNodes, nodeConnectivity));
const size_t numLeafNodes = nodeConnectivity.size();
const size_t numVoxels = numLeafNodes * FloatTreeT::LeafNodeType::SIZE;
std::unique_ptr<bool[]> changedNodeMaskA{new bool[numLeafNodes]};
std::unique_ptr<bool[]> changedNodeMaskB{new bool[numLeafNodes]};
std::unique_ptr<bool[]> changedVoxelMask{new bool[numVoxels]};
mesh_to_volume_internal::fillArray(changedNodeMaskA.get(), true, numLeafNodes);
mesh_to_volume_internal::fillArray(changedNodeMaskB.get(), false, numLeafNodes);
mesh_to_volume_internal::fillArray(changedVoxelMask.get(), false, numVoxels);
const tbb::blocked_range<size_t> nodeRange(0, numLeafNodes);
bool nodesUpdated = false;
do {
tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedFillExteriorSign<FloatTreeT>(
nodeConnectivity.nodes(), changedNodeMaskA.get()));
tbb::parallel_for(nodeRange, mesh_to_volume_internal::SeedPoints<FloatTreeT>(
nodeConnectivity, changedNodeMaskA.get(), changedNodeMaskB.get(),
changedVoxelMask.get()));
changedNodeMaskA.swap(changedNodeMaskB);
nodesUpdated = false;
for (size_t n = 0; n < numLeafNodes; ++n) {
nodesUpdated |= changedNodeMaskA[n];
if (nodesUpdated) break;
}
if (nodesUpdated) {
tbb::parallel_for(nodeRange, mesh_to_volume_internal::SyncVoxelMask<FloatTreeT>(
nodeConnectivity.nodes(), changedNodeMaskA.get(), changedVoxelMask.get()));
}
} while (nodesUpdated);
} // void traceExteriorBoundaries()
////////////////////////////////////////
template <typename GridType, typename MeshDataAdapter, typename Interrupter>
inline typename GridType::Ptr
meshToVolume(
Interrupter& interrupter,
const MeshDataAdapter& mesh,
const math::Transform& transform,
float exteriorBandWidth,
float interiorBandWidth,
int flags,
typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid)
{
using GridTypePtr = typename GridType::Ptr;
using TreeType = typename GridType::TreeType;
using LeafNodeType = typename TreeType::LeafNodeType;
using ValueType = typename GridType::ValueType;
using Int32GridType = typename GridType::template ValueConverter<Int32>::Type;
using Int32TreeType = typename Int32GridType::TreeType;
using BoolTreeType = typename TreeType::template ValueConverter<bool>::Type;
//////////
// Setup
GridTypePtr distGrid(new GridType(std::numeric_limits<ValueType>::max()));
distGrid->setTransform(transform.copy());
ValueType exteriorWidth = ValueType(exteriorBandWidth);
ValueType interiorWidth = ValueType(interiorBandWidth);
// Note: inf interior width is all right, this value makes the converter fill
// interior regions with distance values.
if (!std::isfinite(exteriorWidth) || std::isnan(interiorWidth)) {
std::stringstream msg;
msg << "Illegal narrow band width: exterior = " << exteriorWidth
<< ", interior = " << interiorWidth;
OPENVDB_LOG_DEBUG(msg.str());
return distGrid;
}
const ValueType voxelSize = ValueType(transform.voxelSize()[0]);
if (!std::isfinite(voxelSize) || math::isZero(voxelSize)) {
std::stringstream msg;
msg << "Illegal transform, voxel size = " << voxelSize;
OPENVDB_LOG_DEBUG(msg.str());
return distGrid;
}
// Convert narrow band width from voxel units to world space units.
exteriorWidth *= voxelSize;
// Avoid the unit conversion if the interior band width is set to
// inf or std::numeric_limits<float>::max().
if (interiorWidth < std::numeric_limits<ValueType>::max()) {
interiorWidth *= voxelSize;
}
const bool computeSignedDistanceField = (flags & UNSIGNED_DISTANCE_FIELD) == 0;
const bool removeIntersectingVoxels = (flags & DISABLE_INTERSECTING_VOXEL_REMOVAL) == 0;
const bool renormalizeValues = (flags & DISABLE_RENORMALIZATION) == 0;
const bool trimNarrowBand = (flags & DISABLE_NARROW_BAND_TRIMMING) == 0;
Int32GridType* indexGrid = nullptr;
typename Int32GridType::Ptr temporaryIndexGrid;
if (polygonIndexGrid) {
indexGrid = polygonIndexGrid;
} else {
temporaryIndexGrid.reset(new Int32GridType(Int32(util::INVALID_IDX)));
indexGrid = temporaryIndexGrid.get();
}
indexGrid->newTree();
indexGrid->setTransform(transform.copy());
if (computeSignedDistanceField) {
distGrid->setGridClass(GRID_LEVEL_SET);
} else {
distGrid->setGridClass(GRID_UNKNOWN);
interiorWidth = ValueType(0.0);
}
TreeType& distTree = distGrid->tree();
Int32TreeType& indexTree = indexGrid->tree();
//////////
// Voxelize mesh
{
using VoxelizationDataType = mesh_to_volume_internal::VoxelizationData<TreeType>;
using DataTable = tbb::enumerable_thread_specific<typename VoxelizationDataType::Ptr>;
DataTable data;
using Voxelizer =
mesh_to_volume_internal::VoxelizePolygons<TreeType, MeshDataAdapter, Interrupter>;
const tbb::blocked_range<size_t> polygonRange(0, mesh.polygonCount());
tbb::parallel_for(polygonRange, Voxelizer(data, mesh, &interrupter));
for (typename DataTable::iterator i = data.begin(); i != data.end(); ++i) {
VoxelizationDataType& dataItem = **i;
mesh_to_volume_internal::combineData(
distTree, indexTree, dataItem.distTree, dataItem.indexTree);
}
}
// The progress estimates are based on the observed average time for a few different
// test cases and is only intended to provide some rough progression feedback to the user.
if (interrupter.wasInterrupted(30)) return distGrid;
//////////
// Classify interior and exterior regions
if (computeSignedDistanceField) {
// Determines the inside/outside state for the narrow band of voxels.
traceExteriorBoundaries(distTree);
std::vector<LeafNodeType*> nodes;
nodes.reserve(distTree.leafCount());
distTree.getNodes(nodes);
const tbb::blocked_range<size_t> nodeRange(0, nodes.size());
using SignOp =
mesh_to_volume_internal::ComputeIntersectingVoxelSign<TreeType, MeshDataAdapter>;
tbb::parallel_for(nodeRange, SignOp(nodes, distTree, indexTree, mesh));
if (interrupter.wasInterrupted(45)) return distGrid;
// Remove voxels created by self intersecting portions of the mesh.
if (removeIntersectingVoxels) {
tbb::parallel_for(nodeRange,
mesh_to_volume_internal::ValidateIntersectingVoxels<TreeType>(distTree, nodes));
tbb::parallel_for(nodeRange,
mesh_to_volume_internal::RemoveSelfIntersectingSurface<TreeType>(
nodes, distTree, indexTree));
tools::pruneInactive(distTree, /*threading=*/true);
tools::pruneInactive(indexTree, /*threading=*/true);
}
}
if (interrupter.wasInterrupted(50)) return distGrid;
if (distTree.activeVoxelCount() == 0) {
distTree.clear();
distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
return distGrid;
}
// Transform values (world space scaling etc.).
{
std::vector<LeafNodeType*> nodes;
nodes.reserve(distTree.leafCount());
distTree.getNodes(nodes);
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
mesh_to_volume_internal::TransformValues<TreeType>(
nodes, voxelSize, !computeSignedDistanceField));
}
// Propagate sign information into tile regions.
if (computeSignedDistanceField) {
distTree.root().setBackground(exteriorWidth, /*updateChildNodes=*/false);
tools::signedFloodFillWithValues(distTree, exteriorWidth, -interiorWidth);
} else {
tools::changeBackground(distTree, exteriorWidth);
}
if (interrupter.wasInterrupted(54)) return distGrid;
//////////
// Expand the narrow band region
const ValueType minBandWidth = voxelSize * ValueType(2.0);
if (interiorWidth > minBandWidth || exteriorWidth > minBandWidth) {
// Create the initial voxel mask.
BoolTreeType maskTree(false);
{
std::vector<LeafNodeType*> nodes;
nodes.reserve(distTree.leafCount());
distTree.getNodes(nodes);
mesh_to_volume_internal::ConstructVoxelMask<TreeType> op(maskTree, distTree, nodes);
tbb::parallel_reduce(tbb::blocked_range<size_t>(0, nodes.size()), op);
}
// Progress estimation
unsigned maxIterations = std::numeric_limits<unsigned>::max();
float progress = 54.0f, step = 0.0f;
double estimated =
2.0 * std::ceil((std::max(interiorWidth, exteriorWidth) - minBandWidth) / voxelSize);
if (estimated < double(maxIterations)) {
maxIterations = unsigned(estimated);
step = 40.0f / float(maxIterations);
}
std::vector<typename BoolTreeType::LeafNodeType*> maskNodes;
unsigned count = 0;
while (true) {
if (interrupter.wasInterrupted(int(progress))) return distGrid;
const size_t maskNodeCount = maskTree.leafCount();
if (maskNodeCount == 0) break;
maskNodes.clear();
maskNodes.reserve(maskNodeCount);
maskTree.getNodes(maskNodes);
const tbb::blocked_range<size_t> range(0, maskNodes.size());
tbb::parallel_for(range,
mesh_to_volume_internal::DiffLeafNodeMask<TreeType>(distTree, maskNodes));
mesh_to_volume_internal::expandNarrowband(distTree, indexTree, maskTree, maskNodes,
mesh, exteriorWidth, interiorWidth, voxelSize);
if ((++count) >= maxIterations) break;
progress += step;
}
}
if (interrupter.wasInterrupted(94)) return distGrid;
if (!polygonIndexGrid) indexGrid->clear();
/////////
// Renormalize distances to smooth out bumps caused by self intersecting
// and overlapping portions of the mesh and renormalize the level set.
if (computeSignedDistanceField && renormalizeValues) {
std::vector<LeafNodeType*> nodes;
nodes.reserve(distTree.leafCount());
distTree.getNodes(nodes);
std::unique_ptr<ValueType[]> buffer{new ValueType[LeafNodeType::SIZE * nodes.size()]};
const ValueType offset = ValueType(0.8 * voxelSize);
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
mesh_to_volume_internal::OffsetValues<TreeType>(nodes, -offset));
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
mesh_to_volume_internal::Renormalize<TreeType>(
distTree, nodes, buffer.get(), voxelSize));
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
mesh_to_volume_internal::MinCombine<TreeType>(nodes, buffer.get()));
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
mesh_to_volume_internal::OffsetValues<TreeType>(
nodes, offset - mesh_to_volume_internal::Tolerance<ValueType>::epsilon()));
}
if (interrupter.wasInterrupted(99)) return distGrid;
/////////
// Remove active voxels that exceed the narrow band limits
if (trimNarrowBand && std::min(interiorWidth, exteriorWidth) < voxelSize * ValueType(4.0)) {
std::vector<LeafNodeType*> nodes;
nodes.reserve(distTree.leafCount());
distTree.getNodes(nodes);
tbb::parallel_for(tbb::blocked_range<size_t>(0, nodes.size()),
mesh_to_volume_internal::InactivateValues<TreeType>(
nodes, exteriorWidth, computeSignedDistanceField ? interiorWidth : exteriorWidth));
tools::pruneLevelSet(
distTree, exteriorWidth, computeSignedDistanceField ? -interiorWidth : -exteriorWidth);
}
return distGrid;
}
template <typename GridType, typename MeshDataAdapter>
inline typename GridType::Ptr
meshToVolume(
const MeshDataAdapter& mesh,
const math::Transform& transform,
float exteriorBandWidth,
float interiorBandWidth,
int flags,
typename GridType::template ValueConverter<Int32>::Type * polygonIndexGrid)
{
util::NullInterrupter nullInterrupter;
return meshToVolume<GridType>(nullInterrupter, mesh, transform,
exteriorBandWidth, interiorBandWidth, flags, polygonIndexGrid);
}
////////////////////////////////////////
//{
/// @cond OPENVDB_MESH_TO_VOLUME_INTERNAL
/// @internal This overload is enabled only for grids with a scalar, floating-point ValueType.
template<typename GridType, typename Interrupter>
inline typename std::enable_if<std::is_floating_point<typename GridType::ValueType>::value,
typename GridType::Ptr>::type
doMeshConversion(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float exBandWidth,
float inBandWidth,
bool unsignedDistanceField = false)
{
if (points.empty()) {
return typename GridType::Ptr(new GridType(typename GridType::ValueType(exBandWidth)));
}
const size_t numPoints = points.size();
std::unique_ptr<Vec3s[]> indexSpacePoints{new Vec3s[numPoints]};
// transform points to local grid index space
tbb::parallel_for(tbb::blocked_range<size_t>(0, numPoints),
mesh_to_volume_internal::TransformPoints<Vec3s>(
&points[0], indexSpacePoints.get(), xform));
const int conversionFlags = unsignedDistanceField ? UNSIGNED_DISTANCE_FIELD : 0;
if (quads.empty()) {
QuadAndTriangleDataAdapter<Vec3s, Vec3I>
mesh(indexSpacePoints.get(), numPoints, &triangles[0], triangles.size());
return meshToVolume<GridType>(mesh, xform, exBandWidth, inBandWidth, conversionFlags);
} else if (triangles.empty()) {
QuadAndTriangleDataAdapter<Vec3s, Vec4I>
mesh(indexSpacePoints.get(), numPoints, &quads[0], quads.size());
return meshToVolume<GridType>(mesh, xform, exBandWidth, inBandWidth, conversionFlags);
}
// pack primitives
const size_t numPrimitives = triangles.size() + quads.size();
std::unique_ptr<Vec4I[]> prims{new Vec4I[numPrimitives]};
for (size_t n = 0, N = triangles.size(); n < N; ++n) {
const Vec3I& triangle = triangles[n];
Vec4I& prim = prims[n];
prim[0] = triangle[0];
prim[1] = triangle[1];
prim[2] = triangle[2];
prim[3] = util::INVALID_IDX;
}
const size_t offset = triangles.size();
for (size_t n = 0, N = quads.size(); n < N; ++n) {
prims[offset + n] = quads[n];
}
QuadAndTriangleDataAdapter<Vec3s, Vec4I>
mesh(indexSpacePoints.get(), numPoints, prims.get(), numPrimitives);
return meshToVolume<GridType>(interrupter, mesh, xform,
exBandWidth, inBandWidth, conversionFlags);
}
/// @internal This overload is enabled only for grids that do not have a scalar,
/// floating-point ValueType.
template<typename GridType, typename Interrupter>
inline typename std::enable_if<!std::is_floating_point<typename GridType::ValueType>::value,
typename GridType::Ptr>::type
doMeshConversion(
Interrupter&,
const math::Transform& /*xform*/,
const std::vector<Vec3s>& /*points*/,
const std::vector<Vec3I>& /*triangles*/,
const std::vector<Vec4I>& /*quads*/,
float /*exBandWidth*/,
float /*inBandWidth*/,
bool /*unsignedDistanceField*/ = false)
{
OPENVDB_THROW(TypeError,
"mesh to volume conversion is supported only for scalar floating-point grids");
}
/// @endcond
//}
////////////////////////////////////////
template<typename GridType>
inline typename GridType::Ptr
meshToLevelSet(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
float halfWidth)
{
util::NullInterrupter nullInterrupter;
std::vector<Vec4I> quads(0);
return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
halfWidth, halfWidth);
}
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToLevelSet(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
float halfWidth)
{
std::vector<Vec4I> quads(0);
return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
halfWidth, halfWidth);
}
template<typename GridType>
inline typename GridType::Ptr
meshToLevelSet(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec4I>& quads,
float halfWidth)
{
util::NullInterrupter nullInterrupter;
std::vector<Vec3I> triangles(0);
return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
halfWidth, halfWidth);
}
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToLevelSet(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec4I>& quads,
float halfWidth)
{
std::vector<Vec3I> triangles(0);
return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
halfWidth, halfWidth);
}
template<typename GridType>
inline typename GridType::Ptr
meshToLevelSet(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float halfWidth)
{
util::NullInterrupter nullInterrupter;
return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
halfWidth, halfWidth);
}
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToLevelSet(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float halfWidth)
{
return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
halfWidth, halfWidth);
}
template<typename GridType>
inline typename GridType::Ptr
meshToSignedDistanceField(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float exBandWidth,
float inBandWidth)
{
util::NullInterrupter nullInterrupter;
return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles,
quads, exBandWidth, inBandWidth);
}
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToSignedDistanceField(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float exBandWidth,
float inBandWidth)
{
return doMeshConversion<GridType>(interrupter, xform, points, triangles,
quads, exBandWidth, inBandWidth);
}
template<typename GridType>
inline typename GridType::Ptr
meshToUnsignedDistanceField(
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float bandWidth)
{
util::NullInterrupter nullInterrupter;
return doMeshConversion<GridType>(nullInterrupter, xform, points, triangles, quads,
bandWidth, bandWidth, true);
}
template<typename GridType, typename Interrupter>
inline typename GridType::Ptr
meshToUnsignedDistanceField(
Interrupter& interrupter,
const openvdb::math::Transform& xform,
const std::vector<Vec3s>& points,
const std::vector<Vec3I>& triangles,
const std::vector<Vec4I>& quads,
float bandWidth)
{
return doMeshConversion<GridType>(interrupter, xform, points, triangles, quads,
bandWidth, bandWidth, true);
}
////////////////////////////////////////////////////////////////////////////////
// Required by several of the tree nodes
inline std::ostream&
operator<<(std::ostream& ostr, const MeshToVoxelEdgeData::EdgeData& rhs)
{
ostr << "{[ " << rhs.mXPrim << ", " << rhs.mXDist << "]";
ostr << " [ " << rhs.mYPrim << ", " << rhs.mYDist << "]";
ostr << " [ " << rhs.mZPrim << ", " << rhs.mZDist << "]}";
return ostr;
}
// Required by math::Abs
inline MeshToVoxelEdgeData::EdgeData
Abs(const MeshToVoxelEdgeData::EdgeData& x)
{
return x;
}
////////////////////////////////////////
class MeshToVoxelEdgeData::GenEdgeData
{
public:
GenEdgeData(
const std::vector<Vec3s>& pointList,
const std::vector<Vec4I>& polygonList);
void run(bool threaded = true);
GenEdgeData(GenEdgeData& rhs, tbb::split);
inline void operator() (const tbb::blocked_range<size_t> &range);
inline void join(GenEdgeData& rhs);
inline TreeType& tree() { return mTree; }
private:
void operator=(const GenEdgeData&) {}
struct Primitive { Vec3d a, b, c, d; Int32 index; };
template<bool IsQuad>
inline void voxelize(const Primitive&);
template<bool IsQuad>
inline bool evalPrimitive(const Coord&, const Primitive&);
inline bool rayTriangleIntersection( const Vec3d& origin, const Vec3d& dir,
const Vec3d& a, const Vec3d& b, const Vec3d& c, double& t);
TreeType mTree;
Accessor mAccessor;
const std::vector<Vec3s>& mPointList;
const std::vector<Vec4I>& mPolygonList;
// Used internally for acceleration
using IntTreeT = TreeType::ValueConverter<Int32>::Type;
IntTreeT mLastPrimTree;
tree::ValueAccessor<IntTreeT> mLastPrimAccessor;
}; // class MeshToVoxelEdgeData::GenEdgeData
inline
MeshToVoxelEdgeData::GenEdgeData::GenEdgeData(
const std::vector<Vec3s>& pointList,
const std::vector<Vec4I>& polygonList)
: mTree(EdgeData())
, mAccessor(mTree)
, mPointList(pointList)
, mPolygonList(polygonList)
, mLastPrimTree(Int32(util::INVALID_IDX))
, mLastPrimAccessor(mLastPrimTree)
{
}
inline
MeshToVoxelEdgeData::GenEdgeData::GenEdgeData(GenEdgeData& rhs, tbb::split)
: mTree(EdgeData())
, mAccessor(mTree)
, mPointList(rhs.mPointList)
, mPolygonList(rhs.mPolygonList)
, mLastPrimTree(Int32(util::INVALID_IDX))
, mLastPrimAccessor(mLastPrimTree)
{
}
inline void
MeshToVoxelEdgeData::GenEdgeData::run(bool threaded)
{
if (threaded) {
tbb::parallel_reduce(tbb::blocked_range<size_t>(0, mPolygonList.size()), *this);
} else {
(*this)(tbb::blocked_range<size_t>(0, mPolygonList.size()));
}
}
inline void
MeshToVoxelEdgeData::GenEdgeData::join(GenEdgeData& rhs)
{
using RootNodeType = TreeType::RootNodeType;
using NodeChainType = RootNodeType::NodeChainType;
static_assert(boost::mpl::size<NodeChainType>::value > 1, "expected tree height > 1");
using InternalNodeType = boost::mpl::at<NodeChainType, boost::mpl::int_<1> >::type;
Coord ijk;
Index offset;
rhs.mTree.clearAllAccessors();
TreeType::LeafIter leafIt = rhs.mTree.beginLeaf();
for ( ; leafIt; ++leafIt) {
ijk = leafIt->origin();
TreeType::LeafNodeType* lhsLeafPt = mTree.probeLeaf(ijk);
if (!lhsLeafPt) {
mAccessor.addLeaf(rhs.mAccessor.probeLeaf(ijk));
InternalNodeType* node = rhs.mAccessor.getNode<InternalNodeType>();
node->stealNode<TreeType::LeafNodeType>(ijk, EdgeData(), false);
rhs.mAccessor.clear();
} else {
TreeType::LeafNodeType::ValueOnCIter it = leafIt->cbeginValueOn();
for ( ; it; ++it) {
offset = it.pos();
const EdgeData& rhsValue = it.getValue();
if (!lhsLeafPt->isValueOn(offset)) {
lhsLeafPt->setValueOn(offset, rhsValue);
} else {
EdgeData& lhsValue = const_cast<EdgeData&>(lhsLeafPt->getValue(offset));
if (rhsValue.mXDist < lhsValue.mXDist) {
lhsValue.mXDist = rhsValue.mXDist;
lhsValue.mXPrim = rhsValue.mXPrim;
}
if (rhsValue.mYDist < lhsValue.mYDist) {
lhsValue.mYDist = rhsValue.mYDist;
lhsValue.mYPrim = rhsValue.mYPrim;
}
if (rhsValue.mZDist < lhsValue.mZDist) {
lhsValue.mZDist = rhsValue.mZDist;
lhsValue.mZPrim = rhsValue.mZPrim;
}
}
} // end value iteration
}
} // end leaf iteration
}
inline void
MeshToVoxelEdgeData::GenEdgeData::operator()(const tbb::blocked_range<size_t> &range)
{
Primitive prim;
for (size_t n = range.begin(); n < range.end(); ++n) {
const Vec4I& verts = mPolygonList[n];
prim.index = Int32(n);
prim.a = Vec3d(mPointList[verts[0]]);
prim.b = Vec3d(mPointList[verts[1]]);
prim.c = Vec3d(mPointList[verts[2]]);
if (util::INVALID_IDX != verts[3]) {
prim.d = Vec3d(mPointList[verts[3]]);
voxelize<true>(prim);
} else {
voxelize<false>(prim);
}
}
}
template<bool IsQuad>
inline void
MeshToVoxelEdgeData::GenEdgeData::voxelize(const Primitive& prim)
{
std::deque<Coord> coordList;
Coord ijk, nijk;
ijk = Coord::floor(prim.a);
coordList.push_back(ijk);
evalPrimitive<IsQuad>(ijk, prim);
while (!coordList.empty()) {
ijk = coordList.back();
coordList.pop_back();
for (Int32 i = 0; i < 26; ++i) {
nijk = ijk + util::COORD_OFFSETS[i];
if (prim.index != mLastPrimAccessor.getValue(nijk)) {
mLastPrimAccessor.setValue(nijk, prim.index);
if(evalPrimitive<IsQuad>(nijk, prim)) coordList.push_back(nijk);
}
}
}
}
template<bool IsQuad>
inline bool
MeshToVoxelEdgeData::GenEdgeData::evalPrimitive(const Coord& ijk, const Primitive& prim)
{
Vec3d uvw, org(ijk[0], ijk[1], ijk[2]);
bool intersecting = false;
double t;
EdgeData edgeData;
mAccessor.probeValue(ijk, edgeData);
// Evaluate first triangle
double dist = (org -
closestPointOnTriangleToPoint(prim.a, prim.c, prim.b, org, uvw)).lengthSqr();
if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.c, prim.b, t)) {
if (t < edgeData.mXDist) {
edgeData.mXDist = float(t);
edgeData.mXPrim = prim.index;
intersecting = true;
}
}
if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.c, prim.b, t)) {
if (t < edgeData.mYDist) {
edgeData.mYDist = float(t);
edgeData.mYPrim = prim.index;
intersecting = true;
}
}
if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.c, prim.b, t)) {
if (t < edgeData.mZDist) {
edgeData.mZDist = float(t);
edgeData.mZPrim = prim.index;
intersecting = true;
}
}
if (IsQuad) {
// Split quad into a second triangle and calculate distance.
double secondDist = (org -
closestPointOnTriangleToPoint(prim.a, prim.d, prim.c, org, uvw)).lengthSqr();
if (secondDist < dist) dist = secondDist;
if (rayTriangleIntersection(org, Vec3d(1.0, 0.0, 0.0), prim.a, prim.d, prim.c, t)) {
if (t < edgeData.mXDist) {
edgeData.mXDist = float(t);
edgeData.mXPrim = prim.index;
intersecting = true;
}
}
if (rayTriangleIntersection(org, Vec3d(0.0, 1.0, 0.0), prim.a, prim.d, prim.c, t)) {
if (t < edgeData.mYDist) {
edgeData.mYDist = float(t);
edgeData.mYPrim = prim.index;
intersecting = true;
}
}
if (rayTriangleIntersection(org, Vec3d(0.0, 0.0, 1.0), prim.a, prim.d, prim.c, t)) {
if (t < edgeData.mZDist) {
edgeData.mZDist = float(t);
edgeData.mZPrim = prim.index;
intersecting = true;
}
}
}
if (intersecting) mAccessor.setValue(ijk, edgeData);
return (dist < 0.86602540378443861);
}
inline bool
MeshToVoxelEdgeData::GenEdgeData::rayTriangleIntersection(
const Vec3d& origin, const Vec3d& dir,
const Vec3d& a, const Vec3d& b, const Vec3d& c,
double& t)
{
// Check if ray is parallel with triangle
Vec3d e1 = b - a;
Vec3d e2 = c - a;
Vec3d s1 = dir.cross(e2);
double divisor = s1.dot(e1);
if (!(std::abs(divisor) > 0.0)) return false;
// Compute barycentric coordinates
double inv_divisor = 1.0 / divisor;
Vec3d d = origin - a;
double b1 = d.dot(s1) * inv_divisor;
if (b1 < 0.0 || b1 > 1.0) return false;
Vec3d s2 = d.cross(e1);
double b2 = dir.dot(s2) * inv_divisor;
if (b2 < 0.0 || (b1 + b2) > 1.0) return false;
// Compute distance to intersection point
t = e2.dot(s2) * inv_divisor;
return (t < 0.0) ? false : true;
}
////////////////////////////////////////
inline
MeshToVoxelEdgeData::MeshToVoxelEdgeData()
: mTree(EdgeData())
{
}
inline void
MeshToVoxelEdgeData::convert(
const std::vector<Vec3s>& pointList,
const std::vector<Vec4I>& polygonList)
{
GenEdgeData converter(pointList, polygonList);
converter.run();
mTree.clear();
mTree.merge(converter.tree());
}
inline void
MeshToVoxelEdgeData::getEdgeData(
Accessor& acc,
const Coord& ijk,
std::vector<Vec3d>& points,
std::vector<Index32>& primitives)
{
EdgeData data;
Vec3d point;
Coord coord = ijk;
if (acc.probeValue(coord, data)) {
if (data.mXPrim != util::INVALID_IDX) {
point[0] = double(coord[0]) + data.mXDist;
point[1] = double(coord[1]);
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mXPrim);
}
if (data.mYPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]) + data.mYDist;
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mYPrim);
}
if (data.mZPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]);
point[2] = double(coord[2]) + data.mZDist;
points.push_back(point);
primitives.push_back(data.mZPrim);
}
}
coord[0] += 1;
if (acc.probeValue(coord, data)) {
if (data.mYPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]) + data.mYDist;
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mYPrim);
}
if (data.mZPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]);
point[2] = double(coord[2]) + data.mZDist;
points.push_back(point);
primitives.push_back(data.mZPrim);
}
}
coord[2] += 1;
if (acc.probeValue(coord, data)) {
if (data.mYPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]) + data.mYDist;
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mYPrim);
}
}
coord[0] -= 1;
if (acc.probeValue(coord, data)) {
if (data.mXPrim != util::INVALID_IDX) {
point[0] = double(coord[0]) + data.mXDist;
point[1] = double(coord[1]);
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mXPrim);
}
if (data.mYPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]) + data.mYDist;
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mYPrim);
}
}
coord[1] += 1;
if (acc.probeValue(coord, data)) {
if (data.mXPrim != util::INVALID_IDX) {
point[0] = double(coord[0]) + data.mXDist;
point[1] = double(coord[1]);
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mXPrim);
}
}
coord[2] -= 1;
if (acc.probeValue(coord, data)) {
if (data.mXPrim != util::INVALID_IDX) {
point[0] = double(coord[0]) + data.mXDist;
point[1] = double(coord[1]);
point[2] = double(coord[2]);
points.push_back(point);
primitives.push_back(data.mXPrim);
}
if (data.mZPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]);
point[2] = double(coord[2]) + data.mZDist;
points.push_back(point);
primitives.push_back(data.mZPrim);
}
}
coord[0] += 1;
if (acc.probeValue(coord, data)) {
if (data.mZPrim != util::INVALID_IDX) {
point[0] = double(coord[0]);
point[1] = double(coord[1]);
point[2] = double(coord[2]) + data.mZDist;
points.push_back(point);
primitives.push_back(data.mZPrim);
}
}
}
template<typename GridType, typename VecType>
inline typename GridType::Ptr
createLevelSetBox(const math::BBox<VecType>& bbox,
const openvdb::math::Transform& xform,
typename VecType::ValueType halfWidth)
{
const Vec3s pmin = Vec3s(xform.worldToIndex(bbox.min()));
const Vec3s pmax = Vec3s(xform.worldToIndex(bbox.max()));
Vec3s points[8];
points[0] = Vec3s(pmin[0], pmin[1], pmin[2]);
points[1] = Vec3s(pmin[0], pmin[1], pmax[2]);
points[2] = Vec3s(pmax[0], pmin[1], pmax[2]);
points[3] = Vec3s(pmax[0], pmin[1], pmin[2]);
points[4] = Vec3s(pmin[0], pmax[1], pmin[2]);
points[5] = Vec3s(pmin[0], pmax[1], pmax[2]);
points[6] = Vec3s(pmax[0], pmax[1], pmax[2]);
points[7] = Vec3s(pmax[0], pmax[1], pmin[2]);
Vec4I faces[6];
faces[0] = Vec4I(0, 1, 2, 3); // bottom
faces[1] = Vec4I(7, 6, 5, 4); // top
faces[2] = Vec4I(4, 5, 1, 0); // front
faces[3] = Vec4I(6, 7, 3, 2); // back
faces[4] = Vec4I(0, 3, 7, 4); // left
faces[5] = Vec4I(1, 5, 6, 2); // right
QuadAndTriangleDataAdapter<Vec3s, Vec4I> mesh(points, 8, faces, 6);
return meshToVolume<GridType>(mesh, xform, halfWidth, halfWidth);
}
} // namespace tools
} // namespace OPENVDB_VERSION_NAME
} // namespace openvdb
#endif // OPENVDB_TOOLS_MESH_TO_VOLUME_HAS_BEEN_INCLUDED
// Copyright (c) 2012-2017 DreamWorks Animation LLC
// All rights reserved. This software is distributed under the
// Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
|