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 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834
|
/******************************************************************************
*
* Project: High Performance Image Reprojector
* Purpose: Implementation of the GDALWarpKernel class. Implements the actual
* image warping for a "chunk" of input and output imagery already
* loaded into memory.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "gdalwarper.h"
#include <cfloat>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <limits>
#include <mutex>
#include <new>
#include <utility>
#include <vector>
#include "cpl_atomic_ops.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_mask.h"
#include "cpl_multiproc.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
#include "cpl_worker_thread_pool.h"
#include "cpl_quad_tree.h"
#include "gdal.h"
#include "gdal_alg.h"
#include "gdal_alg_priv.h"
#include "gdal_thread_pool.h"
#include "gdalwarpkernel_opencl.h"
// #define CHECK_SUM_WITH_GEOS
#ifdef CHECK_SUM_WITH_GEOS
#include "ogr_geometry.h"
#include "ogr_geos.h"
#endif
// We restrict to 64bit processors because they are guaranteed to have SSE2.
// Could possibly be used too on 32bit, but we would need to check at runtime.
#if defined(__x86_64) || defined(_M_X64)
#include "gdalsse_priv.h"
#if __SSE4_1__
#include <smmintrin.h>
#endif
#if __SSE3__
#include <pmmintrin.h>
#endif
#endif
CPL_CVSID("$Id$")
constexpr double BAND_DENSITY_THRESHOLD = 0.0000000001;
constexpr float SRC_DENSITY_THRESHOLD = 0.000000001f;
// #define INSTANTIATE_FLOAT64_SSE2_IMPL
static const int anGWKFilterRadius[] = {
0, // Nearest neighbour
1, // Bilinear
2, // Cubic Convolution (Catmull-Rom)
2, // Cubic B-Spline
3, // Lanczos windowed sinc
0, // Average
0, // Mode
0, // Reserved GRA_Gauss=7
0, // Max
0, // Min
0, // Med
0, // Q1
0, // Q3
0, // Sum
0, // RMS
};
static double GWKBilinear(double dfX);
static double GWKCubic(double dfX);
static double GWKBSpline(double dfX);
static double GWKLanczosSinc(double dfX);
static const FilterFuncType apfGWKFilter[] = {
nullptr, // Nearest neighbour
GWKBilinear, // Bilinear
GWKCubic, // Cubic Convolution (Catmull-Rom)
GWKBSpline, // Cubic B-Spline
GWKLanczosSinc, // Lanczos windowed sinc
nullptr, // Average
nullptr, // Mode
nullptr, // Reserved GRA_Gauss=7
nullptr, // Max
nullptr, // Min
nullptr, // Med
nullptr, // Q1
nullptr, // Q3
nullptr, // Sum
nullptr, // RMS
};
// TODO(schwehr): Can we make these functions have a const * const arg?
static double GWKBilinear4Values(double *padfVals);
static double GWKCubic4Values(double *padfVals);
static double GWKBSpline4Values(double *padfVals);
static double GWKLanczosSinc4Values(double *padfVals);
static const FilterFunc4ValuesType apfGWKFilter4Values[] = {
nullptr, // Nearest neighbour
GWKBilinear4Values, // Bilinear
GWKCubic4Values, // Cubic Convolution (Catmull-Rom)
GWKBSpline4Values, // Cubic B-Spline
GWKLanczosSinc4Values, // Lanczos windowed sinc
nullptr, // Average
nullptr, // Mode
nullptr, // Reserved GRA_Gauss=7
nullptr, // Max
nullptr, // Min
nullptr, // Med
nullptr, // Q1
nullptr, // Q3
nullptr, // Sum
nullptr, // RMS
};
int GWKGetFilterRadius(GDALResampleAlg eResampleAlg)
{
static_assert(CPL_ARRAYSIZE(anGWKFilterRadius) == GRA_LAST_VALUE + 1,
"Bad size of anGWKFilterRadius");
return anGWKFilterRadius[eResampleAlg];
}
FilterFuncType GWKGetFilterFunc(GDALResampleAlg eResampleAlg)
{
static_assert(CPL_ARRAYSIZE(apfGWKFilter) == GRA_LAST_VALUE + 1,
"Bad size of apfGWKFilter");
return apfGWKFilter[eResampleAlg];
}
FilterFunc4ValuesType GWKGetFilterFunc4Values(GDALResampleAlg eResampleAlg)
{
static_assert(CPL_ARRAYSIZE(apfGWKFilter4Values) == GRA_LAST_VALUE + 1,
"Bad size of apfGWKFilter4Values");
return apfGWKFilter4Values[eResampleAlg];
}
#ifdef HAVE_OPENCL
static CPLErr GWKOpenCLCase(GDALWarpKernel *);
#endif
static CPLErr GWKGeneralCase(GDALWarpKernel *);
static CPLErr GWKRealCase(GDALWarpKernel *poWK);
static CPLErr GWKNearestNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK);
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK);
static CPLErr GWKCubicNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK);
static CPLErr GWKCubicNoMasksOrDstDensityOnlyFloat(GDALWarpKernel *poWK);
#ifdef INSTANTIATE_FLOAT64_SSE2_IMPL
static CPLErr GWKCubicNoMasksOrDstDensityOnlyDouble(GDALWarpKernel *poWK);
#endif
static CPLErr GWKCubicSplineNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK);
static CPLErr GWKNearestByte(GDALWarpKernel *poWK);
static CPLErr GWKNearestNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK);
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK);
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyFloat(GDALWarpKernel *poWK);
#ifdef INSTANTIATE_FLOAT64_SSE2_IMPL
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyDouble(GDALWarpKernel *poWK);
#endif
static CPLErr GWKCubicNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK);
static CPLErr GWKCubicSplineNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK);
static CPLErr GWKNearestShort(GDALWarpKernel *poWK);
static CPLErr GWKNearestNoMasksOrDstDensityOnlyFloat(GDALWarpKernel *poWK);
static CPLErr GWKNearestFloat(GDALWarpKernel *poWK);
static CPLErr GWKAverageOrMode(GDALWarpKernel *);
static CPLErr GWKSumPreserving(GDALWarpKernel *);
static CPLErr GWKCubicNoMasksOrDstDensityOnlyUShort(GDALWarpKernel *);
static CPLErr GWKCubicSplineNoMasksOrDstDensityOnlyUShort(GDALWarpKernel *);
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyUShort(GDALWarpKernel *);
/************************************************************************/
/* GWKJobStruct */
/************************************************************************/
struct GWKJobStruct
{
std::mutex &mutex;
std::condition_variable &cv;
int &counter;
bool &stopFlag;
GDALWarpKernel *poWK;
int iYMin;
int iYMax;
int (*pfnProgress)(GWKJobStruct *psJob);
void *pTransformerArg;
void (*pfnFunc)(
void *); // used by GWKRun() to assign the proper pTransformerArg
GWKJobStruct(std::mutex &mutex_, std::condition_variable &cv_,
int &counter_, bool &stopFlag_)
: mutex(mutex_), cv(cv_), counter(counter_), stopFlag(stopFlag_),
poWK(nullptr), iYMin(0), iYMax(0), pfnProgress(nullptr),
pTransformerArg(nullptr), pfnFunc(nullptr)
{
}
};
struct GWKThreadData
{
std::unique_ptr<CPLJobQueue> poJobQueue{};
std::unique_ptr<std::vector<GWKJobStruct>> threadJobs{};
int nMaxThreads{0};
int counter{0};
bool stopFlag{false};
std::mutex mutex{};
std::condition_variable cv{};
bool bTransformerArgInputAssignedToThread{false};
void *pTransformerArgInput{
nullptr}; // owned by calling layer. Not to be destroyed
std::map<GIntBig, void *> mapThreadToTransformerArg{};
int nTotalThreadCountForThisRun = 0;
int nCurThreadCountForThisRun = 0;
};
/************************************************************************/
/* GWKProgressThread() */
/************************************************************************/
// Return TRUE if the computation must be interrupted.
static int GWKProgressThread(GWKJobStruct *psJob)
{
bool stop = false;
{
std::lock_guard<std::mutex> lock(psJob->mutex);
psJob->counter++;
stop = psJob->stopFlag;
}
psJob->cv.notify_one();
return stop;
}
/************************************************************************/
/* GWKProgressMonoThread() */
/************************************************************************/
// Return TRUE if the computation must be interrupted.
static int GWKProgressMonoThread(GWKJobStruct *psJob)
{
GDALWarpKernel *poWK = psJob->poWK;
if (!poWK->pfnProgress(
poWK->dfProgressBase +
poWK->dfProgressScale *
(++psJob->counter / static_cast<double>(psJob->iYMax)),
"", poWK->pProgress))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
psJob->stopFlag = true;
return TRUE;
}
return FALSE;
}
/************************************************************************/
/* GWKGenericMonoThread() */
/************************************************************************/
static CPLErr GWKGenericMonoThread(GDALWarpKernel *poWK,
void (*pfnFunc)(void *pUserData))
{
GWKThreadData td;
// NOTE: the mutex is not used.
GWKJobStruct job(td.mutex, td.cv, td.counter, td.stopFlag);
job.poWK = poWK;
job.iYMin = 0;
job.iYMax = poWK->nDstYSize;
job.pfnProgress = GWKProgressMonoThread;
job.pTransformerArg = poWK->pTransformerArg;
pfnFunc(&job);
return td.stopFlag ? CE_Failure : CE_None;
}
/************************************************************************/
/* GWKThreadsCreate() */
/************************************************************************/
void *GWKThreadsCreate(char **papszWarpOptions,
GDALTransformerFunc /* pfnTransformer */,
void *pTransformerArg)
{
const char *pszWarpThreads =
CSLFetchNameValue(papszWarpOptions, "NUM_THREADS");
if (pszWarpThreads == nullptr)
pszWarpThreads = CPLGetConfigOption("GDAL_NUM_THREADS", "1");
int nThreads = 0;
if (EQUAL(pszWarpThreads, "ALL_CPUS"))
nThreads = CPLGetNumCPUs();
else
nThreads = atoi(pszWarpThreads);
if (nThreads <= 1)
nThreads = 0;
if (nThreads > 128)
nThreads = 128;
GWKThreadData *psThreadData = new GWKThreadData();
auto poThreadPool =
nThreads > 0 ? GDALGetGlobalThreadPool(nThreads) : nullptr;
if (nThreads && poThreadPool)
{
psThreadData->nMaxThreads = nThreads;
psThreadData->threadJobs.reset(new std::vector<GWKJobStruct>(
nThreads,
GWKJobStruct(psThreadData->mutex, psThreadData->cv,
psThreadData->counter, psThreadData->stopFlag)));
psThreadData->poJobQueue = poThreadPool->CreateJobQueue();
psThreadData->pTransformerArgInput = pTransformerArg;
}
return psThreadData;
}
/************************************************************************/
/* GWKThreadsEnd() */
/************************************************************************/
void GWKThreadsEnd(void *psThreadDataIn)
{
if (psThreadDataIn == nullptr)
return;
GWKThreadData *psThreadData = static_cast<GWKThreadData *>(psThreadDataIn);
if (psThreadData->poJobQueue)
{
for (auto &pair : psThreadData->mapThreadToTransformerArg)
{
CPLAssert(pair.second != psThreadData->pTransformerArgInput);
GDALDestroyTransformer(pair.second);
}
psThreadData->poJobQueue.reset();
}
delete psThreadData;
}
/************************************************************************/
/* ThreadFuncAdapter() */
/************************************************************************/
static void ThreadFuncAdapter(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GWKThreadData *psThreadData =
static_cast<GWKThreadData *>(psJob->poWK->psThreadData);
// Look if we have already a per-thread transformer
void *pTransformerArg = nullptr;
const GIntBig nThreadId = CPLGetPID();
{
std::lock_guard<std::mutex> lock(psThreadData->mutex);
++psThreadData->nCurThreadCountForThisRun;
auto oIter = psThreadData->mapThreadToTransformerArg.find(nThreadId);
if (oIter != psThreadData->mapThreadToTransformerArg.end())
{
pTransformerArg = oIter->second;
}
else if (!psThreadData->bTransformerArgInputAssignedToThread &&
psThreadData->nCurThreadCountForThisRun ==
psThreadData->nTotalThreadCountForThisRun)
{
// If we are the last thread to be started, temporarily borrow the
// original transformer
psThreadData->bTransformerArgInputAssignedToThread = true;
pTransformerArg = psThreadData->pTransformerArgInput;
psThreadData->mapThreadToTransformerArg[nThreadId] =
pTransformerArg;
}
}
// If no transformer assigned to current thread, instantiate one
if (pTransformerArg == nullptr)
{
CPLAssert(psThreadData->pTransformerArgInput != nullptr);
CPLAssert(!psThreadData->bTransformerArgInputAssignedToThread);
// This somehow assumes that GDALCloneTransformer() is thread-safe
// which should normally be the case.
pTransformerArg =
GDALCloneTransformer(psThreadData->pTransformerArgInput);
// Lock for the stop flag and the transformer map.
std::lock_guard<std::mutex> lock(psThreadData->mutex);
if (!pTransformerArg)
{
psJob->stopFlag = true;
return;
}
psThreadData->mapThreadToTransformerArg[nThreadId] = pTransformerArg;
}
psJob->pTransformerArg = pTransformerArg;
psJob->pfnFunc(pData);
// Give back original transformer, if borrowed.
{
std::lock_guard<std::mutex> lock(psThreadData->mutex);
if (psThreadData->bTransformerArgInputAssignedToThread &&
pTransformerArg == psThreadData->pTransformerArgInput)
{
psThreadData->mapThreadToTransformerArg.erase(
psThreadData->mapThreadToTransformerArg.find(nThreadId));
psThreadData->bTransformerArgInputAssignedToThread = false;
}
}
}
/************************************************************************/
/* GWKRun() */
/************************************************************************/
static CPLErr GWKRun(GDALWarpKernel *poWK, const char *pszFuncName,
void (*pfnFunc)(void *pUserData))
{
const int nDstYSize = poWK->nDstYSize;
CPLDebug("GDAL",
"GDALWarpKernel()::%s() "
"Src=%d,%d,%dx%d Dst=%d,%d,%dx%d",
pszFuncName, poWK->nSrcXOff, poWK->nSrcYOff, poWK->nSrcXSize,
poWK->nSrcYSize, poWK->nDstXOff, poWK->nDstYOff, poWK->nDstXSize,
poWK->nDstYSize);
if (!poWK->pfnProgress(poWK->dfProgressBase, "", poWK->pProgress))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
return CE_Failure;
}
GWKThreadData *psThreadData =
static_cast<GWKThreadData *>(poWK->psThreadData);
if (psThreadData == nullptr || psThreadData->poJobQueue == nullptr)
{
return GWKGenericMonoThread(poWK, pfnFunc);
}
int nThreads = std::min(psThreadData->nMaxThreads, nDstYSize / 2);
// Config option mostly useful for tests to be able to test multithreading
// with small rasters
const int nWarpChunkSize =
atoi(CPLGetConfigOption("WARP_THREAD_CHUNK_SIZE", "65536"));
if (nWarpChunkSize > 0)
{
GIntBig nChunks =
static_cast<GIntBig>(nDstYSize) * poWK->nDstXSize / nWarpChunkSize;
if (nThreads > nChunks)
nThreads = static_cast<int>(nChunks);
}
if (nThreads <= 0)
nThreads = 1;
CPLDebug("WARP", "Using %d threads", nThreads);
auto &jobs = *psThreadData->threadJobs;
CPLAssert(static_cast<int>(jobs.size()) >= nThreads);
// Fill-in job structures.
for (int i = 0; i < nThreads; ++i)
{
auto &job = jobs[i];
job.poWK = poWK;
job.iYMin =
static_cast<int>(static_cast<int64_t>(i) * nDstYSize / nThreads);
job.iYMax = static_cast<int>(static_cast<int64_t>(i + 1) * nDstYSize /
nThreads);
if (poWK->pfnProgress != GDALDummyProgress)
job.pfnProgress = GWKProgressThread;
job.pfnFunc = pfnFunc;
}
{
std::unique_lock<std::mutex> lock(psThreadData->mutex);
psThreadData->nTotalThreadCountForThisRun = nThreads;
psThreadData->nCurThreadCountForThisRun = 0;
// Start jobs.
for (int i = 0; i < nThreads; ++i)
{
auto &job = jobs[i];
psThreadData->poJobQueue->SubmitJob(ThreadFuncAdapter,
static_cast<void *>(&job));
}
/* --------------------------------------------------------------------
*/
/* Report progress. */
/* --------------------------------------------------------------------
*/
if (poWK->pfnProgress != GDALDummyProgress)
{
int &counter = psThreadData->counter;
while (counter < nDstYSize)
{
psThreadData->cv.wait(lock);
if (!poWK->pfnProgress(
poWK->dfProgressBase +
poWK->dfProgressScale *
(counter / static_cast<double>(nDstYSize)),
"", poWK->pProgress))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
psThreadData->stopFlag = true;
break;
}
}
}
}
/* -------------------------------------------------------------------- */
/* Wait for all jobs to complete. */
/* -------------------------------------------------------------------- */
psThreadData->poJobQueue->WaitCompletion();
return psThreadData->stopFlag ? CE_Failure : CE_None;
}
/************************************************************************/
/* ==================================================================== */
/* GDALWarpKernel */
/* ==================================================================== */
/************************************************************************/
/**
* \class GDALWarpKernel "gdalwarper.h"
*
* Low level image warping class.
*
* This class is responsible for low level image warping for one
* "chunk" of imagery. The class is essentially a structure with all
* data members public - primarily so that new special-case functions
* can be added without changing the class declaration.
*
* Applications are normally intended to interactive with warping facilities
* through the GDALWarpOperation class, though the GDALWarpKernel can in
* theory be used directly if great care is taken in setting up the
* control data.
*
* <h3>Design Issues</h3>
*
* The intention is that PerformWarp() would analyze the setup in terms
* of the datatype, resampling type, and validity/density mask usage and
* pick one of many specific implementations of the warping algorithm over
* a continuum of optimization vs. generality. At one end there will be a
* reference general purpose implementation of the algorithm that supports
* any data type (working internally in double precision complex), all three
* resampling types, and any or all of the validity/density masks. At the
* other end would be highly optimized algorithms for common cases like
* nearest neighbour resampling on GDT_Byte data with no masks.
*
* The full set of optimized versions have not been decided but we should
* expect to have at least:
* - One for each resampling algorithm for 8bit data with no masks.
* - One for each resampling algorithm for float data with no masks.
* - One for each resampling algorithm for float data with any/all masks
* (essentially the generic case for just float data).
* - One for each resampling algorithm for 8bit data with support for
* input validity masks (per band or per pixel). This handles the common
* case of nodata masking.
* - One for each resampling algorithm for float data with support for
* input validity masks (per band or per pixel). This handles the common
* case of nodata masking.
*
* Some of the specializations would operate on all bands in one pass
* (especially the ones without masking would do this), while others might
* process each band individually to reduce code complexity.
*
* <h3>Masking Semantics</h3>
*
* A detailed explanation of the semantics of the validity and density masks,
* and their effects on resampling kernels is needed here.
*/
/************************************************************************/
/* GDALWarpKernel Data Members */
/************************************************************************/
/**
* \var GDALResampleAlg GDALWarpKernel::eResample;
*
* Resampling algorithm.
*
* The resampling algorithm to use. One of GRA_NearestNeighbour, GRA_Bilinear,
* GRA_Cubic, GRA_CubicSpline, GRA_Lanczos, GRA_Average, GRA_RMS,
* GRA_Mode or GRA_Sum.
*
* This field is required. GDT_NearestNeighbour may be used as a default
* value.
*/
/**
* \var GDALDataType GDALWarpKernel::eWorkingDataType;
*
* Working pixel data type.
*
* The datatype of pixels in the source image (papabySrcimage) and
* destination image (papabyDstImage) buffers. Note that operations on
* some data types (such as GDT_Byte) may be much better optimized than other
* less common cases.
*
* This field is required. It may not be GDT_Unknown.
*/
/**
* \var int GDALWarpKernel::nBands;
*
* Number of bands.
*
* The number of bands (layers) of imagery being warped. Determines the
* number of entries in the papabySrcImage, papanBandSrcValid,
* and papabyDstImage arrays.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::nSrcXSize;
*
* Source image width in pixels.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::nSrcYSize;
*
* Source image height in pixels.
*
* This field is required.
*/
/**
* \var double GDALWarpKernel::dfSrcXExtraSize;
*
* Number of pixels included in nSrcXSize that are present on the edges of
* the area of interest to take into account the width of the kernel.
*
* This field is required.
*/
/**
* \var double GDALWarpKernel::dfSrcYExtraSize;
*
* Number of pixels included in nSrcYExtraSize that are present on the edges of
* the area of interest to take into account the height of the kernel.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::papabySrcImage;
*
* Array of source image band data.
*
* This is an array of pointers (of size GDALWarpKernel::nBands) pointers
* to image data. Each individual band of image data is organized as a single
* block of image data in left to right, then bottom to top order. The actual
* type of the image data is determined by GDALWarpKernel::eWorkingDataType.
*
* To access the pixel value for the (x=3, y=4) pixel (zero based) of
* the second band with eWorkingDataType set to GDT_Float32 use code like
* this:
*
* \code
* float dfPixelValue;
* int nBand = 2-1; // Band indexes are zero based.
* int nPixel = 3; // Zero based.
* int nLine = 4; // Zero based.
*
* assert( nPixel >= 0 && nPixel < poKern->nSrcXSize );
* assert( nLine >= 0 && nLine < poKern->nSrcYSize );
* assert( nBand >= 0 && nBand < poKern->nBands );
* dfPixelValue = ((float *) poKern->papabySrcImage[nBand])
* [nPixel + nLine * poKern->nSrcXSize];
* \endcode
*
* This field is required.
*/
/**
* \var GUInt32 **GDALWarpKernel::papanBandSrcValid;
*
* Per band validity mask for source pixels.
*
* Array of pixel validity mask layers for each source band. Each of
* the mask layers is the same size (in pixels) as the source image with
* one bit per pixel. Note that it is legal (and common) for this to be
* NULL indicating that none of the pixels are invalidated, or for some
* band validity masks to be NULL in which case all pixels of the band are
* valid. The following code can be used to test the validity of a particular
* pixel.
*
* \code
* int bIsValid = TRUE;
* int nBand = 2-1; // Band indexes are zero based.
* int nPixel = 3; // Zero based.
* int nLine = 4; // Zero based.
*
* assert( nPixel >= 0 && nPixel < poKern->nSrcXSize );
* assert( nLine >= 0 && nLine < poKern->nSrcYSize );
* assert( nBand >= 0 && nBand < poKern->nBands );
*
* if( poKern->papanBandSrcValid != NULL
* && poKern->papanBandSrcValid[nBand] != NULL )
* {
* GUInt32 *panBandMask = poKern->papanBandSrcValid[nBand];
* int iPixelOffset = nPixel + nLine * poKern->nSrcXSize;
*
* bIsValid = CPLMaskGet(panBandMask, iPixelOffset)
* }
* \endcode
*/
/**
* \var GUInt32 *GDALWarpKernel::panUnifiedSrcValid;
*
* Per pixel validity mask for source pixels.
*
* A single validity mask layer that applies to the pixels of all source
* bands. It is accessed similarly to papanBandSrcValid, but without the
* extra level of band indirection.
*
* This pointer may be NULL indicating that all pixels are valid.
*
* Note that if both panUnifiedSrcValid, and papanBandSrcValid are available,
* the pixel isn't considered to be valid unless both arrays indicate it is
* valid.
*/
/**
* \var float *GDALWarpKernel::pafUnifiedSrcDensity;
*
* Per pixel density mask for source pixels.
*
* A single density mask layer that applies to the pixels of all source
* bands. It contains values between 0.0 and 1.0 indicating the degree to
* which this pixel should be allowed to contribute to the output result.
*
* This pointer may be NULL indicating that all pixels have a density of 1.0.
*
* The density for a pixel may be accessed like this:
*
* \code
* float fDensity = 1.0;
* int nPixel = 3; // Zero based.
* int nLine = 4; // Zero based.
*
* assert( nPixel >= 0 && nPixel < poKern->nSrcXSize );
* assert( nLine >= 0 && nLine < poKern->nSrcYSize );
* if( poKern->pafUnifiedSrcDensity != NULL )
* fDensity = poKern->pafUnifiedSrcDensity
* [nPixel + nLine * poKern->nSrcXSize];
* \endcode
*/
/**
* \var int GDALWarpKernel::nDstXSize;
*
* Width of destination image in pixels.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::nDstYSize;
*
* Height of destination image in pixels.
*
* This field is required.
*/
/**
* \var GByte **GDALWarpKernel::papabyDstImage;
*
* Array of destination image band data.
*
* This is an array of pointers (of size GDALWarpKernel::nBands) pointers
* to image data. Each individual band of image data is organized as a single
* block of image data in left to right, then bottom to top order. The actual
* type of the image data is determined by GDALWarpKernel::eWorkingDataType.
*
* To access the pixel value for the (x=3, y=4) pixel (zero based) of
* the second band with eWorkingDataType set to GDT_Float32 use code like
* this:
*
* \code
* float dfPixelValue;
* int nBand = 2-1; // Band indexes are zero based.
* int nPixel = 3; // Zero based.
* int nLine = 4; // Zero based.
*
* assert( nPixel >= 0 && nPixel < poKern->nDstXSize );
* assert( nLine >= 0 && nLine < poKern->nDstYSize );
* assert( nBand >= 0 && nBand < poKern->nBands );
* dfPixelValue = ((float *) poKern->papabyDstImage[nBand])
* [nPixel + nLine * poKern->nSrcYSize];
* \endcode
*
* This field is required.
*/
/**
* \var GUInt32 *GDALWarpKernel::panDstValid;
*
* Per pixel validity mask for destination pixels.
*
* A single validity mask layer that applies to the pixels of all destination
* bands. It is accessed similarly to papanUnitifiedSrcValid, but based
* on the size of the destination image.
*
* This pointer may be NULL indicating that all pixels are valid.
*/
/**
* \var float *GDALWarpKernel::pafDstDensity;
*
* Per pixel density mask for destination pixels.
*
* A single density mask layer that applies to the pixels of all destination
* bands. It contains values between 0.0 and 1.0.
*
* This pointer may be NULL indicating that all pixels have a density of 1.0.
*
* The density for a pixel may be accessed like this:
*
* \code
* float fDensity = 1.0;
* int nPixel = 3; // Zero based.
* int nLine = 4; // Zero based.
*
* assert( nPixel >= 0 && nPixel < poKern->nDstXSize );
* assert( nLine >= 0 && nLine < poKern->nDstYSize );
* if( poKern->pafDstDensity != NULL )
* fDensity = poKern->pafDstDensity[nPixel + nLine * poKern->nDstXSize];
* \endcode
*/
/**
* \var int GDALWarpKernel::nSrcXOff;
*
* X offset to source pixel coordinates for transformation.
*
* See pfnTransformer.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::nSrcYOff;
*
* Y offset to source pixel coordinates for transformation.
*
* See pfnTransformer.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::nDstXOff;
*
* X offset to destination pixel coordinates for transformation.
*
* See pfnTransformer.
*
* This field is required.
*/
/**
* \var int GDALWarpKernel::nDstYOff;
*
* Y offset to destination pixel coordinates for transformation.
*
* See pfnTransformer.
*
* This field is required.
*/
/**
* \var GDALTransformerFunc GDALWarpKernel::pfnTransformer;
*
* Source/destination location transformer.
*
* The function to call to transform coordinates between source image
* pixel/line coordinates and destination image pixel/line coordinates.
* See GDALTransformerFunc() for details of the semantics of this function.
*
* The GDALWarpKern algorithm will only ever use this transformer in
* "destination to source" mode (bDstToSrc=TRUE), and will always pass
* partial or complete scanlines of points in the destination image as
* input. This means, among other things, that it is safe to the the
* approximating transform GDALApproxTransform() as the transformation
* function.
*
* Source and destination images may be subsets of a larger overall image.
* The transformation algorithms will expect and return pixel/line coordinates
* in terms of this larger image, so coordinates need to be offset by
* the offsets specified in nSrcXOff, nSrcYOff, nDstXOff, and nDstYOff before
* passing to pfnTransformer, and after return from it.
*
* The GDALWarpKernel::pfnTransformerArg value will be passed as the callback
* data to this function when it is called.
*
* This field is required.
*/
/**
* \var void *GDALWarpKernel::pTransformerArg;
*
* Callback data for pfnTransformer.
*
* This field may be NULL if not required for the pfnTransformer being used.
*/
/**
* \var GDALProgressFunc GDALWarpKernel::pfnProgress;
*
* The function to call to report progress of the algorithm, and to check
* for a requested termination of the operation. It operates according to
* GDALProgressFunc() semantics.
*
* Generally speaking the progress function will be invoked for each
* scanline of the destination buffer that has been processed.
*
* This field may be NULL (internally set to GDALDummyProgress()).
*/
/**
* \var void *GDALWarpKernel::pProgress;
*
* Callback data for pfnProgress.
*
* This field may be NULL if not required for the pfnProgress being used.
*/
/************************************************************************/
/* GDALWarpKernel() */
/************************************************************************/
GDALWarpKernel::GDALWarpKernel()
: papszWarpOptions(nullptr), eResample(GRA_NearestNeighbour),
eWorkingDataType(GDT_Unknown), nBands(0), nSrcXSize(0), nSrcYSize(0),
dfSrcXExtraSize(0.0), dfSrcYExtraSize(0.0), papabySrcImage(nullptr),
papanBandSrcValid(nullptr), panUnifiedSrcValid(nullptr),
pafUnifiedSrcDensity(nullptr), nDstXSize(0), nDstYSize(0),
papabyDstImage(nullptr), panDstValid(nullptr), pafDstDensity(nullptr),
dfXScale(1.0), dfYScale(1.0), dfXFilter(0.0), dfYFilter(0.0), nXRadius(0),
nYRadius(0), nFiltInitX(0), nFiltInitY(0), nSrcXOff(0), nSrcYOff(0),
nDstXOff(0), nDstYOff(0), pfnTransformer(nullptr),
pTransformerArg(nullptr), pfnProgress(GDALDummyProgress),
pProgress(nullptr), dfProgressBase(0.0), dfProgressScale(1.0),
padfDstNoDataReal(nullptr), psThreadData(nullptr)
{
}
/************************************************************************/
/* ~GDALWarpKernel() */
/************************************************************************/
GDALWarpKernel::~GDALWarpKernel()
{
}
/************************************************************************/
/* PerformWarp() */
/************************************************************************/
/**
* \fn CPLErr GDALWarpKernel::PerformWarp();
*
* This method performs the warp described in the GDALWarpKernel.
*
* @return CE_None on success or CE_Failure if an error occurs.
*/
CPLErr GDALWarpKernel::PerformWarp()
{
const CPLErr eErr = Validate();
if (eErr != CE_None)
return eErr;
// See #2445 and #3079.
if (nSrcXSize <= 0 || nSrcYSize <= 0)
{
if (!pfnProgress(dfProgressBase + dfProgressScale, "", pProgress))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
return CE_Failure;
}
return CE_None;
}
/* -------------------------------------------------------------------- */
/* Pre-calculate resampling scales and window sizes for filtering. */
/* -------------------------------------------------------------------- */
dfXScale = static_cast<double>(nDstXSize) / (nSrcXSize - dfSrcXExtraSize);
dfYScale = static_cast<double>(nDstYSize) / (nSrcYSize - dfSrcYExtraSize);
if (nSrcXSize >= nDstXSize && nSrcXSize <= nDstXSize + dfSrcXExtraSize)
dfXScale = 1.0;
if (nSrcYSize >= nDstYSize && nSrcYSize <= nDstYSize + dfSrcYExtraSize)
dfYScale = 1.0;
if (dfXScale < 1.0)
{
double dfXReciprocalScale = 1.0 / dfXScale;
const int nXReciprocalScale =
static_cast<int>(dfXReciprocalScale + 0.5);
if (fabs(dfXReciprocalScale - nXReciprocalScale) < 0.05)
dfXScale = 1.0 / nXReciprocalScale;
}
if (dfYScale < 1.0)
{
double dfYReciprocalScale = 1.0 / dfYScale;
const int nYReciprocalScale =
static_cast<int>(dfYReciprocalScale + 0.5);
if (fabs(dfYReciprocalScale - nYReciprocalScale) < 0.05)
dfYScale = 1.0 / nYReciprocalScale;
}
// XSCALE and YSCALE undocumented for now. Can help in some cases.
// Best would probably be a per-pixel scale computation.
const char *pszXScale = CSLFetchNameValue(papszWarpOptions, "XSCALE");
if (pszXScale != nullptr && !EQUAL(pszXScale, "FROM_GRID_SAMPLING"))
dfXScale = CPLAtof(pszXScale);
const char *pszYScale = CSLFetchNameValue(papszWarpOptions, "YSCALE");
if (pszYScale != nullptr)
dfYScale = CPLAtof(pszYScale);
// If the xscale is significantly lower than the yscale, this is highly
// suspicious of a situation of wrapping a very large virtual file in
// geographic coordinates with left and right parts being close to the
// antimeridian. In that situation, the xscale computed by the above method
// is completely wrong. Prefer doing an average of a few sample points
// instead
if ((dfYScale / dfXScale > 100 ||
(pszXScale != nullptr && EQUAL(pszXScale, "FROM_GRID_SAMPLING"))))
{
// Sample points along a grid
const int nPointsX = std::min(10, nDstXSize);
const int nPointsY = std::min(10, nDstYSize);
const int nPoints = 3 * nPointsX * nPointsY;
std::vector<double> padfX;
std::vector<double> padfY;
std::vector<double> padfZ(nPoints);
std::vector<int> pabSuccess(nPoints);
for (int iY = 0; iY < nPointsY; iY++)
{
for (int iX = 0; iX < nPointsX; iX++)
{
const double dfX =
nPointsX == 1
? 0.0
: static_cast<double>(iX) * nDstXSize / (nPointsX - 1);
const double dfY =
nPointsY == 1
? 0.0
: static_cast<double>(iY) * nDstYSize / (nPointsY - 1);
// Reproject each destination sample point and its neighbours
// at (x+1,y) and (x,y+1), so as to get the local scale.
padfX.push_back(dfX);
padfY.push_back(dfY);
padfX.push_back((iX == nPointsX - 1) ? dfX - 1 : dfX + 1);
padfY.push_back(dfY);
padfX.push_back(dfX);
padfY.push_back((iY == nPointsY - 1) ? dfY - 1 : dfY + 1);
}
}
pfnTransformer(pTransformerArg, TRUE, nPoints, &padfX[0], &padfY[0],
&padfZ[0], &pabSuccess[0]);
// Compute the xscale at each sampling point
std::vector<double> adfXScales;
for (int i = 0; i < nPoints; i += 3)
{
if (pabSuccess[i] && pabSuccess[i + 1] && pabSuccess[i + 2])
{
const double dfPointXScale =
1.0 / std::max(std::abs(padfX[i + 1] - padfX[i]),
std::abs(padfX[i + 2] - padfX[i]));
adfXScales.push_back(dfPointXScale);
}
}
// Sort by increasing xcale
std::sort(adfXScales.begin(), adfXScales.end());
if (!adfXScales.empty())
{
// Compute the average of scales, but eliminate outliers small
// scales, if some samples are just along the discontinuity.
const double dfMaxPointXScale = adfXScales.back();
double dfSumPointXScale = 0;
int nCountPointScale = 0;
for (double dfPointXScale : adfXScales)
{
if (dfPointXScale > dfMaxPointXScale / 10)
{
dfSumPointXScale += dfPointXScale;
nCountPointScale++;
}
}
if (nCountPointScale > 0) // should always be true
{
const double dfXScaleFromSampling =
dfSumPointXScale / nCountPointScale;
#if DEBUG_VERBOSE
CPLDebug("WARP", "Correcting dfXScale from %f to %f", dfXScale,
dfXScaleFromSampling);
#endif
dfXScale = dfXScaleFromSampling;
}
}
}
#if DEBUG_VERBOSE
CPLDebug("WARP", "dfXScale = %f, dfYScale = %f", dfXScale, dfYScale);
#endif
const int bUse4SamplesFormula = dfXScale >= 0.95 && dfYScale >= 0.95;
// Safety check for callers that would use GDALWarpKernel without using
// GDALWarpOperation.
if ((eResample == GRA_CubicSpline || eResample == GRA_Lanczos ||
((eResample == GRA_Cubic || eResample == GRA_Bilinear) &&
!bUse4SamplesFormula)) &&
atoi(CSLFetchNameValueDef(papszWarpOptions, "EXTRA_ELTS", "0")) !=
WARP_EXTRA_ELTS)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Source arrays must have WARP_EXTRA_ELTS extra elements at "
"their end. "
"See GDALWarpKernel class definition. If this condition is "
"fulfilled, define a EXTRA_ELTS=%d warp options",
WARP_EXTRA_ELTS);
return CE_Failure;
}
dfXFilter = anGWKFilterRadius[eResample];
dfYFilter = anGWKFilterRadius[eResample];
nXRadius = dfXScale < 1.0 ? static_cast<int>(ceil(dfXFilter / dfXScale))
: static_cast<int>(dfXFilter);
nYRadius = dfYScale < 1.0 ? static_cast<int>(ceil(dfYFilter / dfYScale))
: static_cast<int>(dfYFilter);
// Filter window offset depends on the parity of the kernel radius.
nFiltInitX = ((anGWKFilterRadius[eResample] + 1) % 2) - nXRadius;
nFiltInitY = ((anGWKFilterRadius[eResample] + 1) % 2) - nYRadius;
bApplyVerticalShift =
CPLFetchBool(papszWarpOptions, "APPLY_VERTICAL_SHIFT", false);
dfMultFactorVerticalShift = CPLAtof(CSLFetchNameValueDef(
papszWarpOptions, "MULT_FACTOR_VERTICAL_SHIFT", "1.0"));
/* -------------------------------------------------------------------- */
/* Set up resampling functions. */
/* -------------------------------------------------------------------- */
if (CPLFetchBool(papszWarpOptions, "USE_GENERAL_CASE", false))
return GWKGeneralCase(this);
#if defined(HAVE_OPENCL)
if ((eWorkingDataType == GDT_Byte || eWorkingDataType == GDT_CInt16 ||
eWorkingDataType == GDT_UInt16 || eWorkingDataType == GDT_Int16 ||
eWorkingDataType == GDT_CFloat32 || eWorkingDataType == GDT_Float32) &&
(eResample == GRA_Bilinear || eResample == GRA_Cubic ||
eResample == GRA_CubicSpline || eResample == GRA_Lanczos) &&
!bApplyVerticalShift &&
CPLFetchBool(papszWarpOptions, "USE_OPENCL", true))
{
const CPLErr eResult = GWKOpenCLCase(this);
// CE_Warning tells us a suitable OpenCL environment was not available
// so we fall through to other CPU based methods.
if (eResult != CE_Warning)
return eResult;
}
#endif // defined HAVE_OPENCL
const bool bNoMasksOrDstDensityOnly =
papanBandSrcValid == nullptr && panUnifiedSrcValid == nullptr &&
pafUnifiedSrcDensity == nullptr && panDstValid == nullptr;
if (eWorkingDataType == GDT_Byte && eResample == GRA_NearestNeighbour &&
bNoMasksOrDstDensityOnly)
return GWKNearestNoMasksOrDstDensityOnlyByte(this);
if (eWorkingDataType == GDT_Byte && eResample == GRA_Bilinear &&
bNoMasksOrDstDensityOnly)
return GWKBilinearNoMasksOrDstDensityOnlyByte(this);
if (eWorkingDataType == GDT_Byte && eResample == GRA_Cubic &&
bNoMasksOrDstDensityOnly)
return GWKCubicNoMasksOrDstDensityOnlyByte(this);
if (eWorkingDataType == GDT_Byte && eResample == GRA_CubicSpline &&
bNoMasksOrDstDensityOnly)
return GWKCubicSplineNoMasksOrDstDensityOnlyByte(this);
if (eWorkingDataType == GDT_Byte && eResample == GRA_NearestNeighbour)
return GWKNearestByte(this);
if ((eWorkingDataType == GDT_Int16 || eWorkingDataType == GDT_UInt16) &&
eResample == GRA_NearestNeighbour && bNoMasksOrDstDensityOnly)
return GWKNearestNoMasksOrDstDensityOnlyShort(this);
if ((eWorkingDataType == GDT_Int16) && eResample == GRA_Cubic &&
bNoMasksOrDstDensityOnly)
return GWKCubicNoMasksOrDstDensityOnlyShort(this);
if ((eWorkingDataType == GDT_Int16) && eResample == GRA_CubicSpline &&
bNoMasksOrDstDensityOnly)
return GWKCubicSplineNoMasksOrDstDensityOnlyShort(this);
if ((eWorkingDataType == GDT_Int16) && eResample == GRA_Bilinear &&
bNoMasksOrDstDensityOnly)
return GWKBilinearNoMasksOrDstDensityOnlyShort(this);
if ((eWorkingDataType == GDT_UInt16) && eResample == GRA_Cubic &&
bNoMasksOrDstDensityOnly)
return GWKCubicNoMasksOrDstDensityOnlyUShort(this);
if ((eWorkingDataType == GDT_UInt16) && eResample == GRA_CubicSpline &&
bNoMasksOrDstDensityOnly)
return GWKCubicSplineNoMasksOrDstDensityOnlyUShort(this);
if ((eWorkingDataType == GDT_UInt16) && eResample == GRA_Bilinear &&
bNoMasksOrDstDensityOnly)
return GWKBilinearNoMasksOrDstDensityOnlyUShort(this);
if ((eWorkingDataType == GDT_Int16 || eWorkingDataType == GDT_UInt16) &&
eResample == GRA_NearestNeighbour)
return GWKNearestShort(this);
if (eWorkingDataType == GDT_Float32 && eResample == GRA_NearestNeighbour &&
bNoMasksOrDstDensityOnly)
return GWKNearestNoMasksOrDstDensityOnlyFloat(this);
if (eWorkingDataType == GDT_Float32 && eResample == GRA_NearestNeighbour)
return GWKNearestFloat(this);
if (eWorkingDataType == GDT_Float32 && eResample == GRA_Bilinear &&
bNoMasksOrDstDensityOnly)
return GWKBilinearNoMasksOrDstDensityOnlyFloat(this);
if (eWorkingDataType == GDT_Float32 && eResample == GRA_Cubic &&
bNoMasksOrDstDensityOnly)
return GWKCubicNoMasksOrDstDensityOnlyFloat(this);
#ifdef INSTANTIATE_FLOAT64_SSE2_IMPL
if (eWorkingDataType == GDT_Float64 && eResample == GRA_Bilinear &&
bNoMasksOrDstDensityOnly)
return GWKBilinearNoMasksOrDstDensityOnlyDouble(this);
if (eWorkingDataType == GDT_Float64 && eResample == GRA_Cubic &&
bNoMasksOrDstDensityOnly)
return GWKCubicNoMasksOrDstDensityOnlyDouble(this);
#endif
if (eResample == GRA_Average)
return GWKAverageOrMode(this);
if (eResample == GRA_RMS)
return GWKAverageOrMode(this);
if (eResample == GRA_Mode)
return GWKAverageOrMode(this);
if (eResample == GRA_Max)
return GWKAverageOrMode(this);
if (eResample == GRA_Min)
return GWKAverageOrMode(this);
if (eResample == GRA_Med)
return GWKAverageOrMode(this);
if (eResample == GRA_Q1)
return GWKAverageOrMode(this);
if (eResample == GRA_Q3)
return GWKAverageOrMode(this);
if (eResample == GRA_Sum)
return GWKSumPreserving(this);
if (!GDALDataTypeIsComplex(eWorkingDataType))
{
return GWKRealCase(this);
}
return GWKGeneralCase(this);
}
/************************************************************************/
/* Validate() */
/************************************************************************/
/**
* \fn CPLErr GDALWarpKernel::Validate()
*
* Check the settings in the GDALWarpKernel, and issue a CPLError()
* (and return CE_Failure) if the configuration is considered to be
* invalid for some reason.
*
* This method will also do some standard defaulting such as setting
* pfnProgress to GDALDummyProgress() if it is NULL.
*
* @return CE_None on success or CE_Failure if an error is detected.
*/
CPLErr GDALWarpKernel::Validate()
{
if (static_cast<size_t>(eResample) >=
(sizeof(anGWKFilterRadius) / sizeof(anGWKFilterRadius[0])))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unsupported resampling method %d.",
static_cast<int>(eResample));
return CE_Failure;
}
return CE_None;
}
/************************************************************************/
/* GWKOverlayDensity() */
/* */
/* Compute the final density for the destination pixel. This */
/* is a function of the overlay density (passed in) and the */
/* original density. */
/************************************************************************/
static void GWKOverlayDensity(const GDALWarpKernel *poWK, GPtrDiff_t iDstOffset,
double dfDensity)
{
if (dfDensity < 0.0001 || poWK->pafDstDensity == nullptr)
return;
poWK->pafDstDensity[iDstOffset] = static_cast<float>(
1.0 - (1.0 - dfDensity) * (1.0 - poWK->pafDstDensity[iDstOffset]));
}
/************************************************************************/
/* GWKRoundValueT() */
/************************************************************************/
template <class T, bool is_signed> struct sGWKRoundValueT
{
static T eval(double);
};
template <class T> struct sGWKRoundValueT<T, true> /* signed */
{
static T eval(double dfValue)
{
return static_cast<T>(floor(dfValue + 0.5));
}
};
template <class T> struct sGWKRoundValueT<T, false> /* unsigned */
{
static T eval(double dfValue)
{
return static_cast<T>(dfValue + 0.5);
}
};
template <class T> static T GWKRoundValueT(double dfValue)
{
return sGWKRoundValueT<T, std::numeric_limits<T>::is_signed>::eval(dfValue);
}
template <> float GWKRoundValueT<float>(double dfValue)
{
return static_cast<float>(dfValue);
}
#ifdef notused
template <> double GWKRoundValueT<double>(double dfValue)
{
return dfValue;
}
#endif
/************************************************************************/
/* GWKClampValueT() */
/************************************************************************/
template <class T> static CPL_INLINE T GWKClampValueT(double dfValue)
{
if (dfValue < std::numeric_limits<T>::min())
return std::numeric_limits<T>::min();
else if (dfValue > std::numeric_limits<T>::max())
return std::numeric_limits<T>::max();
else
return GWKRoundValueT<T>(dfValue);
}
template <> float GWKClampValueT<float>(double dfValue)
{
return static_cast<float>(dfValue);
}
#ifdef notused
template <> double GWKClampValueT<double>(double dfValue)
{
return dfValue;
}
#endif
/************************************************************************/
/* GWKSetPixelValueRealT() */
/************************************************************************/
template <class T>
static bool GWKSetPixelValueRealT(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iDstOffset, double dfDensity,
T value)
{
T *pDst = reinterpret_cast<T *>(poWK->papabyDstImage[iBand]);
/* -------------------------------------------------------------------- */
/* If the source density is less than 100% we need to fetch the */
/* existing destination value, and mix it with the source to */
/* get the new "to apply" value. Also compute composite */
/* density. */
/* */
/* We avoid mixing if density is very near one or risk mixing */
/* in very extreme nodata values and causing odd results (#1610) */
/* -------------------------------------------------------------------- */
if (dfDensity < 0.9999)
{
if (dfDensity < 0.0001)
return true;
double dfDstDensity = 1.0;
if (poWK->pafDstDensity != nullptr)
dfDstDensity = poWK->pafDstDensity[iDstOffset];
else if (poWK->panDstValid != nullptr &&
!CPLMaskGet(poWK->panDstValid, iDstOffset))
dfDstDensity = 0.0;
// It seems like we also ought to be testing panDstValid[] here!
const double dfDstReal = pDst[iDstOffset];
// The destination density is really only relative to the portion
// not occluded by the overlay.
const double dfDstInfluence = (1.0 - dfDensity) * dfDstDensity;
const double dfReal = (value * dfDensity + dfDstReal * dfDstInfluence) /
(dfDensity + dfDstInfluence);
/* --------------------------------------------------------------------
*/
/* Actually apply the destination value. */
/* */
/* Avoid using the destination nodata value for integer datatypes
*/
/* if by chance it is equal to the computed pixel value. */
/* --------------------------------------------------------------------
*/
pDst[iDstOffset] = GWKClampValueT<T>(dfReal);
}
else
{
pDst[iDstOffset] = value;
}
if (poWK->padfDstNoDataReal != nullptr &&
poWK->padfDstNoDataReal[iBand] == static_cast<double>(pDst[iDstOffset]))
{
if (pDst[iDstOffset] == std::numeric_limits<T>::min())
pDst[iDstOffset] = std::numeric_limits<T>::min() + 1;
else
pDst[iDstOffset]--;
}
return true;
}
/************************************************************************/
/* GWKSetPixelValue() */
/************************************************************************/
static bool GWKSetPixelValue(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iDstOffset, double dfDensity,
double dfReal, double dfImag)
{
GByte *pabyDst = poWK->papabyDstImage[iBand];
/* -------------------------------------------------------------------- */
/* If the source density is less than 100% we need to fetch the */
/* existing destination value, and mix it with the source to */
/* get the new "to apply" value. Also compute composite */
/* density. */
/* */
/* We avoid mixing if density is very near one or risk mixing */
/* in very extreme nodata values and causing odd results (#1610) */
/* -------------------------------------------------------------------- */
if (dfDensity < 0.9999)
{
if (dfDensity < 0.0001)
return true;
double dfDstDensity = 1.0;
if (poWK->pafDstDensity != nullptr)
dfDstDensity = poWK->pafDstDensity[iDstOffset];
else if (poWK->panDstValid != nullptr &&
!CPLMaskGet(poWK->panDstValid, iDstOffset))
dfDstDensity = 0.0;
double dfDstReal = 0.0;
double dfDstImag = 0.0;
// It seems like we also ought to be testing panDstValid[] here!
// TODO(schwehr): Factor out this repreated type of set.
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
dfDstReal = pabyDst[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_Int16:
dfDstReal = reinterpret_cast<GInt16 *>(pabyDst)[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_UInt16:
dfDstReal = reinterpret_cast<GUInt16 *>(pabyDst)[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_Int32:
dfDstReal = reinterpret_cast<GInt32 *>(pabyDst)[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_UInt32:
dfDstReal = reinterpret_cast<GUInt32 *>(pabyDst)[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_Int64:
dfDstReal = static_cast<double>(
reinterpret_cast<std::int64_t *>(pabyDst)[iDstOffset]);
dfDstImag = 0.0;
break;
case GDT_UInt64:
dfDstReal = static_cast<double>(
reinterpret_cast<std::uint64_t *>(pabyDst)[iDstOffset]);
dfDstImag = 0.0;
break;
case GDT_Float32:
dfDstReal = reinterpret_cast<float *>(pabyDst)[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_Float64:
dfDstReal = reinterpret_cast<double *>(pabyDst)[iDstOffset];
dfDstImag = 0.0;
break;
case GDT_CInt16:
dfDstReal = reinterpret_cast<GInt16 *>(pabyDst)[iDstOffset * 2];
dfDstImag =
reinterpret_cast<GInt16 *>(pabyDst)[iDstOffset * 2 + 1];
break;
case GDT_CInt32:
dfDstReal = reinterpret_cast<GInt32 *>(pabyDst)[iDstOffset * 2];
dfDstImag =
reinterpret_cast<GInt32 *>(pabyDst)[iDstOffset * 2 + 1];
break;
case GDT_CFloat32:
dfDstReal = reinterpret_cast<float *>(pabyDst)[iDstOffset * 2];
dfDstImag =
reinterpret_cast<float *>(pabyDst)[iDstOffset * 2 + 1];
break;
case GDT_CFloat64:
dfDstReal = reinterpret_cast<double *>(pabyDst)[iDstOffset * 2];
dfDstImag =
reinterpret_cast<double *>(pabyDst)[iDstOffset * 2 + 1];
break;
default:
CPLAssert(false);
return false;
}
// The destination density is really only relative to the portion
// not occluded by the overlay.
const double dfDstInfluence = (1.0 - dfDensity) * dfDstDensity;
dfReal = (dfReal * dfDensity + dfDstReal * dfDstInfluence) /
(dfDensity + dfDstInfluence);
dfImag = (dfImag * dfDensity + dfDstImag * dfDstInfluence) /
(dfDensity + dfDstInfluence);
}
/* -------------------------------------------------------------------- */
/* Actually apply the destination value. */
/* */
/* Avoid using the destination nodata value for integer datatypes */
/* if by chance it is equal to the computed pixel value. */
/* -------------------------------------------------------------------- */
// TODO(schwehr): Can we make this a template?
#define CLAMP(type) \
do \
{ \
type *_pDst = reinterpret_cast<type *>(pabyDst); \
if (dfReal < static_cast<double>(std::numeric_limits<type>::min())) \
_pDst[iDstOffset] = \
static_cast<type>(std::numeric_limits<type>::min()); \
else if (dfReal > \
static_cast<double>(std::numeric_limits<type>::max())) \
_pDst[iDstOffset] = \
static_cast<type>(std::numeric_limits<type>::max()); \
else \
_pDst[iDstOffset] = (std::numeric_limits<type>::is_signed) \
? static_cast<type>(floor(dfReal + 0.5)) \
: static_cast<type>(dfReal + 0.5); \
if (poWK->padfDstNoDataReal != nullptr && \
poWK->padfDstNoDataReal[iBand] == \
static_cast<double>(_pDst[iDstOffset])) \
{ \
if (_pDst[iDstOffset] == \
static_cast<type>(std::numeric_limits<type>::min())) \
_pDst[iDstOffset] = \
static_cast<type>(std::numeric_limits<type>::min() + 1); \
else \
_pDst[iDstOffset]--; \
} \
} while (false)
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
CLAMP(GByte);
break;
case GDT_Int16:
CLAMP(GInt16);
break;
case GDT_UInt16:
CLAMP(GUInt16);
break;
case GDT_UInt32:
CLAMP(GUInt32);
break;
case GDT_Int32:
CLAMP(GInt32);
break;
case GDT_UInt64:
CLAMP(std::uint64_t);
break;
case GDT_Int64:
CLAMP(std::int64_t);
break;
case GDT_Float32:
reinterpret_cast<float *>(pabyDst)[iDstOffset] =
static_cast<float>(dfReal);
break;
case GDT_Float64:
reinterpret_cast<double *>(pabyDst)[iDstOffset] = dfReal;
break;
case GDT_CInt16:
{
typedef GInt16 T;
if (dfReal < static_cast<double>(std::numeric_limits<T>::min()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2] =
std::numeric_limits<T>::min();
else if (dfReal >
static_cast<double>(std::numeric_limits<T>::max()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2] =
std::numeric_limits<T>::max();
else
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2] =
static_cast<T>(floor(dfReal + 0.5));
if (dfImag < static_cast<double>(std::numeric_limits<T>::min()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2 + 1] =
std::numeric_limits<T>::min();
else if (dfImag >
static_cast<double>(std::numeric_limits<T>::max()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2 + 1] =
std::numeric_limits<T>::max();
else
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2 + 1] =
static_cast<T>(floor(dfImag + 0.5));
break;
}
case GDT_CInt32:
{
typedef GInt32 T;
if (dfReal < static_cast<double>(std::numeric_limits<T>::min()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2] =
std::numeric_limits<T>::min();
else if (dfReal >
static_cast<double>(std::numeric_limits<T>::max()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2] =
std::numeric_limits<T>::max();
else
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2] =
static_cast<T>(floor(dfReal + 0.5));
if (dfImag < static_cast<double>(std::numeric_limits<T>::min()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2 + 1] =
std::numeric_limits<T>::min();
else if (dfImag >
static_cast<double>(std::numeric_limits<T>::max()))
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2 + 1] =
std::numeric_limits<T>::max();
else
reinterpret_cast<T *>(pabyDst)[iDstOffset * 2 + 1] =
static_cast<T>(floor(dfImag + 0.5));
break;
}
case GDT_CFloat32:
reinterpret_cast<float *>(pabyDst)[iDstOffset * 2] =
static_cast<float>(dfReal);
reinterpret_cast<float *>(pabyDst)[iDstOffset * 2 + 1] =
static_cast<float>(dfImag);
break;
case GDT_CFloat64:
reinterpret_cast<double *>(pabyDst)[iDstOffset * 2] = dfReal;
reinterpret_cast<double *>(pabyDst)[iDstOffset * 2 + 1] = dfImag;
break;
default:
return false;
}
return true;
}
/************************************************************************/
/* GWKSetPixelValueReal() */
/************************************************************************/
static bool GWKSetPixelValueReal(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iDstOffset, double dfDensity,
double dfReal)
{
GByte *pabyDst = poWK->papabyDstImage[iBand];
/* -------------------------------------------------------------------- */
/* If the source density is less than 100% we need to fetch the */
/* existing destination value, and mix it with the source to */
/* get the new "to apply" value. Also compute composite */
/* density. */
/* */
/* We avoid mixing if density is very near one or risk mixing */
/* in very extreme nodata values and causing odd results (#1610) */
/* -------------------------------------------------------------------- */
if (dfDensity < 0.9999)
{
if (dfDensity < 0.0001)
return true;
double dfDstReal = 0.0;
double dfDstDensity = 1.0;
if (poWK->pafDstDensity != nullptr)
dfDstDensity = poWK->pafDstDensity[iDstOffset];
else if (poWK->panDstValid != nullptr &&
!CPLMaskGet(poWK->panDstValid, iDstOffset))
dfDstDensity = 0.0;
// It seems like we also ought to be testing panDstValid[] here!
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
dfDstReal = pabyDst[iDstOffset];
break;
case GDT_Int16:
dfDstReal = reinterpret_cast<GInt16 *>(pabyDst)[iDstOffset];
break;
case GDT_UInt16:
dfDstReal = reinterpret_cast<GUInt16 *>(pabyDst)[iDstOffset];
break;
case GDT_Int32:
dfDstReal = reinterpret_cast<GInt32 *>(pabyDst)[iDstOffset];
break;
case GDT_UInt32:
dfDstReal = reinterpret_cast<GUInt32 *>(pabyDst)[iDstOffset];
break;
case GDT_Int64:
dfDstReal = static_cast<double>(
reinterpret_cast<std::int64_t *>(pabyDst)[iDstOffset]);
break;
case GDT_UInt64:
dfDstReal = static_cast<double>(
reinterpret_cast<std::uint64_t *>(pabyDst)[iDstOffset]);
break;
case GDT_Float32:
dfDstReal = reinterpret_cast<float *>(pabyDst)[iDstOffset];
break;
case GDT_Float64:
dfDstReal = reinterpret_cast<double *>(pabyDst)[iDstOffset];
break;
default:
CPLAssert(false);
return false;
}
// The destination density is really only relative to the portion
// not occluded by the overlay.
const double dfDstInfluence = (1.0 - dfDensity) * dfDstDensity;
dfReal = (dfReal * dfDensity + dfDstReal * dfDstInfluence) /
(dfDensity + dfDstInfluence);
}
/* -------------------------------------------------------------------- */
/* Actually apply the destination value. */
/* */
/* Avoid using the destination nodata value for integer datatypes */
/* if by chance it is equal to the computed pixel value. */
/* -------------------------------------------------------------------- */
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
CLAMP(GByte);
break;
case GDT_Int16:
CLAMP(GInt16);
break;
case GDT_UInt16:
CLAMP(GUInt16);
break;
case GDT_UInt32:
CLAMP(GUInt32);
break;
case GDT_Int32:
CLAMP(GInt32);
break;
case GDT_UInt64:
CLAMP(std::uint64_t);
break;
case GDT_Int64:
CLAMP(std::int64_t);
break;
case GDT_Float32:
reinterpret_cast<float *>(pabyDst)[iDstOffset] =
static_cast<float>(dfReal);
break;
case GDT_Float64:
reinterpret_cast<double *>(pabyDst)[iDstOffset] = dfReal;
break;
default:
return false;
}
return true;
}
/************************************************************************/
/* GWKGetPixelValue() */
/************************************************************************/
/* It is assumed that panUnifiedSrcValid has been checked before */
static bool GWKGetPixelValue(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iSrcOffset, double *pdfDensity,
double *pdfReal, double *pdfImag)
{
GByte *pabySrc = poWK->papabySrcImage[iBand];
if (poWK->papanBandSrcValid != nullptr &&
poWK->papanBandSrcValid[iBand] != nullptr &&
!CPLMaskGet(poWK->papanBandSrcValid[iBand], iSrcOffset))
{
*pdfDensity = 0.0;
return false;
}
// TODO(schwehr): Fix casting.
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
*pdfReal = pabySrc[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_Int16:
*pdfReal = reinterpret_cast<GInt16 *>(pabySrc)[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_UInt16:
*pdfReal = reinterpret_cast<GUInt16 *>(pabySrc)[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_Int32:
*pdfReal = reinterpret_cast<GInt32 *>(pabySrc)[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_UInt32:
*pdfReal = reinterpret_cast<GUInt32 *>(pabySrc)[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_Int64:
*pdfReal = static_cast<double>(
reinterpret_cast<std::int64_t *>(pabySrc)[iSrcOffset]);
*pdfImag = 0.0;
break;
case GDT_UInt64:
*pdfReal = static_cast<double>(
reinterpret_cast<std::uint64_t *>(pabySrc)[iSrcOffset]);
*pdfImag = 0.0;
break;
case GDT_Float32:
*pdfReal = reinterpret_cast<float *>(pabySrc)[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_Float64:
*pdfReal = reinterpret_cast<double *>(pabySrc)[iSrcOffset];
*pdfImag = 0.0;
break;
case GDT_CInt16:
*pdfReal = reinterpret_cast<GInt16 *>(pabySrc)[iSrcOffset * 2];
*pdfImag = reinterpret_cast<GInt16 *>(pabySrc)[iSrcOffset * 2 + 1];
break;
case GDT_CInt32:
*pdfReal = reinterpret_cast<GInt32 *>(pabySrc)[iSrcOffset * 2];
*pdfImag = reinterpret_cast<GInt32 *>(pabySrc)[iSrcOffset * 2 + 1];
break;
case GDT_CFloat32:
*pdfReal = reinterpret_cast<float *>(pabySrc)[iSrcOffset * 2];
*pdfImag = reinterpret_cast<float *>(pabySrc)[iSrcOffset * 2 + 1];
break;
case GDT_CFloat64:
*pdfReal = reinterpret_cast<double *>(pabySrc)[iSrcOffset * 2];
*pdfImag = reinterpret_cast<double *>(pabySrc)[iSrcOffset * 2 + 1];
break;
default:
*pdfDensity = 0.0;
return false;
}
if (poWK->pafUnifiedSrcDensity != nullptr)
*pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
else
*pdfDensity = 1.0;
return *pdfDensity != 0.0;
}
/************************************************************************/
/* GWKGetPixelValueReal() */
/************************************************************************/
static bool GWKGetPixelValueReal(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iSrcOffset, double *pdfDensity,
double *pdfReal)
{
GByte *pabySrc = poWK->papabySrcImage[iBand];
if (poWK->papanBandSrcValid != nullptr &&
poWK->papanBandSrcValid[iBand] != nullptr &&
!CPLMaskGet(poWK->papanBandSrcValid[iBand], iSrcOffset))
{
*pdfDensity = 0.0;
return false;
}
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
*pdfReal = pabySrc[iSrcOffset];
break;
case GDT_Int16:
*pdfReal = reinterpret_cast<GInt16 *>(pabySrc)[iSrcOffset];
break;
case GDT_UInt16:
*pdfReal = reinterpret_cast<GUInt16 *>(pabySrc)[iSrcOffset];
break;
case GDT_Int32:
*pdfReal = reinterpret_cast<GInt32 *>(pabySrc)[iSrcOffset];
break;
case GDT_UInt32:
*pdfReal = reinterpret_cast<GUInt32 *>(pabySrc)[iSrcOffset];
break;
case GDT_Int64:
*pdfReal = static_cast<double>(
reinterpret_cast<std::int64_t *>(pabySrc)[iSrcOffset]);
break;
case GDT_UInt64:
*pdfReal = static_cast<double>(
reinterpret_cast<std::uint64_t *>(pabySrc)[iSrcOffset]);
break;
case GDT_Float32:
*pdfReal = reinterpret_cast<float *>(pabySrc)[iSrcOffset];
break;
case GDT_Float64:
*pdfReal = reinterpret_cast<double *>(pabySrc)[iSrcOffset];
break;
default:
CPLAssert(false);
return false;
}
if (poWK->pafUnifiedSrcDensity != nullptr)
*pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
else
*pdfDensity = 1.0;
return *pdfDensity != 0.0;
}
/************************************************************************/
/* GWKGetPixelRow() */
/************************************************************************/
/* It is assumed that adfImag[] is set to 0 by caller code for non-complex */
/* data-types. */
static bool GWKGetPixelRow(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iSrcOffset, int nHalfSrcLen,
double *padfDensity, double adfReal[],
double *padfImag)
{
// We know that nSrcLen is even, so we can *always* unroll loops 2x.
const int nSrcLen = nHalfSrcLen * 2;
bool bHasValid = false;
if (padfDensity != nullptr)
{
// Init the density.
for (int i = 0; i < nSrcLen; i += 2)
{
padfDensity[i] = 1.0;
padfDensity[i + 1] = 1.0;
}
if (poWK->panUnifiedSrcValid != nullptr)
{
for (int i = 0; i < nSrcLen; i += 2)
{
if (CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset + i))
bHasValid = true;
else
padfDensity[i] = 0.0;
if (CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset + i + 1))
bHasValid = true;
else
padfDensity[i + 1] = 0.0;
}
// Reset or fail as needed.
if (bHasValid)
bHasValid = false;
else
return false;
}
if (poWK->papanBandSrcValid != nullptr &&
poWK->papanBandSrcValid[iBand] != nullptr)
{
for (int i = 0; i < nSrcLen; i += 2)
{
if (CPLMaskGet(poWK->papanBandSrcValid[iBand], iSrcOffset + i))
bHasValid = true;
else
padfDensity[i] = 0.0;
if (CPLMaskGet(poWK->papanBandSrcValid[iBand],
iSrcOffset + i + 1))
bHasValid = true;
else
padfDensity[i + 1] = 0.0;
}
// Reset or fail as needed.
if (bHasValid)
bHasValid = false;
else
return false;
}
}
// TODO(schwehr): Fix casting.
// Fetch data.
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
{
GByte *pSrc =
reinterpret_cast<GByte *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_Int16:
{
GInt16 *pSrc =
reinterpret_cast<GInt16 *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_UInt16:
{
GUInt16 *pSrc =
reinterpret_cast<GUInt16 *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_Int32:
{
GInt32 *pSrc =
reinterpret_cast<GInt32 *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_UInt32:
{
GUInt32 *pSrc =
reinterpret_cast<GUInt32 *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_Int64:
{
auto pSrc =
reinterpret_cast<std::int64_t *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = static_cast<double>(pSrc[i]);
adfReal[i + 1] = static_cast<double>(pSrc[i + 1]);
}
break;
}
case GDT_UInt64:
{
auto pSrc =
reinterpret_cast<std::uint64_t *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = static_cast<double>(pSrc[i]);
adfReal[i + 1] = static_cast<double>(pSrc[i + 1]);
}
break;
}
case GDT_Float32:
{
float *pSrc =
reinterpret_cast<float *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_Float64:
{
double *pSrc =
reinterpret_cast<double *>(poWK->papabySrcImage[iBand]);
pSrc += iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[i];
adfReal[i + 1] = pSrc[i + 1];
}
break;
}
case GDT_CInt16:
{
GInt16 *pSrc =
reinterpret_cast<GInt16 *>(poWK->papabySrcImage[iBand]);
pSrc += 2 * iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[2 * i];
padfImag[i] = pSrc[2 * i + 1];
adfReal[i + 1] = pSrc[2 * i + 2];
padfImag[i + 1] = pSrc[2 * i + 3];
}
break;
}
case GDT_CInt32:
{
GInt32 *pSrc =
reinterpret_cast<GInt32 *>(poWK->papabySrcImage[iBand]);
pSrc += 2 * iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[2 * i];
padfImag[i] = pSrc[2 * i + 1];
adfReal[i + 1] = pSrc[2 * i + 2];
padfImag[i + 1] = pSrc[2 * i + 3];
}
break;
}
case GDT_CFloat32:
{
float *pSrc =
reinterpret_cast<float *>(poWK->papabySrcImage[iBand]);
pSrc += 2 * iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[2 * i];
padfImag[i] = pSrc[2 * i + 1];
adfReal[i + 1] = pSrc[2 * i + 2];
padfImag[i + 1] = pSrc[2 * i + 3];
}
break;
}
case GDT_CFloat64:
{
double *pSrc =
reinterpret_cast<double *>(poWK->papabySrcImage[iBand]);
pSrc += 2 * iSrcOffset;
for (int i = 0; i < nSrcLen; i += 2)
{
adfReal[i] = pSrc[2 * i];
padfImag[i] = pSrc[2 * i + 1];
adfReal[i + 1] = pSrc[2 * i + 2];
padfImag[i + 1] = pSrc[2 * i + 3];
}
break;
}
default:
CPLAssert(false);
if (padfDensity)
memset(padfDensity, 0, nSrcLen * sizeof(double));
return false;
}
if (padfDensity == nullptr)
return true;
if (poWK->pafUnifiedSrcDensity == nullptr)
{
for (int i = 0; i < nSrcLen; i += 2)
{
// Take into account earlier calcs.
if (padfDensity[i] > SRC_DENSITY_THRESHOLD)
{
padfDensity[i] = 1.0;
bHasValid = true;
}
if (padfDensity[i + 1] > SRC_DENSITY_THRESHOLD)
{
padfDensity[i + 1] = 1.0;
bHasValid = true;
}
}
}
else
{
for (int i = 0; i < nSrcLen; i += 2)
{
if (padfDensity[i] > SRC_DENSITY_THRESHOLD)
padfDensity[i] = poWK->pafUnifiedSrcDensity[iSrcOffset + i];
if (padfDensity[i] > SRC_DENSITY_THRESHOLD)
bHasValid = true;
if (padfDensity[i + 1] > SRC_DENSITY_THRESHOLD)
padfDensity[i + 1] =
poWK->pafUnifiedSrcDensity[iSrcOffset + i + 1];
if (padfDensity[i + 1] > SRC_DENSITY_THRESHOLD)
bHasValid = true;
}
}
return bHasValid;
}
/************************************************************************/
/* GWKGetPixelT() */
/************************************************************************/
template <class T>
static bool GWKGetPixelT(const GDALWarpKernel *poWK, int iBand,
GPtrDiff_t iSrcOffset, double *pdfDensity, T *pValue)
{
T *pSrc = reinterpret_cast<T *>(poWK->papabySrcImage[iBand]);
if ((poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset)) ||
(poWK->papanBandSrcValid != nullptr &&
poWK->papanBandSrcValid[iBand] != nullptr &&
!CPLMaskGet(poWK->papanBandSrcValid[iBand], iSrcOffset)))
{
*pdfDensity = 0.0;
return false;
}
*pValue = pSrc[iSrcOffset];
if (poWK->pafUnifiedSrcDensity == nullptr)
*pdfDensity = 1.0;
else
*pdfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
return *pdfDensity != 0.0;
}
/************************************************************************/
/* GWKBilinearResample() */
/* Set of bilinear interpolators */
/************************************************************************/
static bool GWKBilinearResample4Sample(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal,
double *pdfImag)
{
// Save as local variables to avoid following pointers.
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
int iSrcX = static_cast<int>(floor(dfSrcX - 0.5));
int iSrcY = static_cast<int>(floor(dfSrcY - 0.5));
double dfRatioX = 1.5 - (dfSrcX - iSrcX);
double dfRatioY = 1.5 - (dfSrcY - iSrcY);
bool bShifted = false;
if (iSrcX == -1)
{
iSrcX = 0;
dfRatioX = 1;
}
if (iSrcY == -1)
{
iSrcY = 0;
dfRatioY = 1;
}
GPtrDiff_t iSrcOffset = iSrcX + static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
// Shift so we don't overrun the array.
if (static_cast<GPtrDiff_t>(nSrcXSize) * nSrcYSize == iSrcOffset + 1 ||
static_cast<GPtrDiff_t>(nSrcXSize) * nSrcYSize ==
iSrcOffset + nSrcXSize + 1)
{
bShifted = true;
--iSrcOffset;
}
double adfDensity[2] = {0.0, 0.0};
double adfReal[2] = {0.0, 0.0};
double adfImag[2] = {0.0, 0.0};
double dfAccumulatorReal = 0.0;
double dfAccumulatorImag = 0.0;
double dfAccumulatorDensity = 0.0;
double dfAccumulatorDivisor = 0.0;
const GPtrDiff_t nSrcPixels =
static_cast<GPtrDiff_t>(nSrcXSize) * nSrcYSize;
// Get pixel row.
if (iSrcY >= 0 && iSrcY < nSrcYSize && iSrcOffset >= 0 &&
iSrcOffset < nSrcPixels &&
GWKGetPixelRow(poWK, iBand, iSrcOffset, 1, adfDensity, adfReal,
adfImag))
{
double dfMult1 = dfRatioX * dfRatioY;
double dfMult2 = (1.0 - dfRatioX) * dfRatioY;
// Shifting corrected.
if (bShifted)
{
adfReal[0] = adfReal[1];
adfImag[0] = adfImag[1];
adfDensity[0] = adfDensity[1];
}
// Upper Left Pixel.
if (iSrcX >= 0 && iSrcX < nSrcXSize &&
adfDensity[0] > SRC_DENSITY_THRESHOLD)
{
dfAccumulatorDivisor += dfMult1;
dfAccumulatorReal += adfReal[0] * dfMult1;
dfAccumulatorImag += adfImag[0] * dfMult1;
dfAccumulatorDensity += adfDensity[0] * dfMult1;
}
// Upper Right Pixel.
if (iSrcX + 1 >= 0 && iSrcX + 1 < nSrcXSize &&
adfDensity[1] > SRC_DENSITY_THRESHOLD)
{
dfAccumulatorDivisor += dfMult2;
dfAccumulatorReal += adfReal[1] * dfMult2;
dfAccumulatorImag += adfImag[1] * dfMult2;
dfAccumulatorDensity += adfDensity[1] * dfMult2;
}
}
// Get pixel row.
if (iSrcY + 1 >= 0 && iSrcY + 1 < nSrcYSize &&
iSrcOffset + nSrcXSize >= 0 && iSrcOffset + nSrcXSize < nSrcPixels &&
GWKGetPixelRow(poWK, iBand, iSrcOffset + nSrcXSize, 1, adfDensity,
adfReal, adfImag))
{
double dfMult1 = dfRatioX * (1.0 - dfRatioY);
double dfMult2 = (1.0 - dfRatioX) * (1.0 - dfRatioY);
// Shifting corrected
if (bShifted)
{
adfReal[0] = adfReal[1];
adfImag[0] = adfImag[1];
adfDensity[0] = adfDensity[1];
}
// Lower Left Pixel
if (iSrcX >= 0 && iSrcX < nSrcXSize &&
adfDensity[0] > SRC_DENSITY_THRESHOLD)
{
dfAccumulatorDivisor += dfMult1;
dfAccumulatorReal += adfReal[0] * dfMult1;
dfAccumulatorImag += adfImag[0] * dfMult1;
dfAccumulatorDensity += adfDensity[0] * dfMult1;
}
// Lower Right Pixel.
if (iSrcX + 1 >= 0 && iSrcX + 1 < nSrcXSize &&
adfDensity[1] > SRC_DENSITY_THRESHOLD)
{
dfAccumulatorDivisor += dfMult2;
dfAccumulatorReal += adfReal[1] * dfMult2;
dfAccumulatorImag += adfImag[1] * dfMult2;
dfAccumulatorDensity += adfDensity[1] * dfMult2;
}
}
/* -------------------------------------------------------------------- */
/* Return result. */
/* -------------------------------------------------------------------- */
if (dfAccumulatorDivisor == 1.0)
{
*pdfReal = dfAccumulatorReal;
*pdfImag = dfAccumulatorImag;
*pdfDensity = dfAccumulatorDensity;
return false;
}
else if (dfAccumulatorDivisor < 0.00001)
{
*pdfReal = 0.0;
*pdfImag = 0.0;
*pdfDensity = 0.0;
return false;
}
else
{
*pdfReal = dfAccumulatorReal / dfAccumulatorDivisor;
*pdfImag = dfAccumulatorImag / dfAccumulatorDivisor;
*pdfDensity = dfAccumulatorDensity / dfAccumulatorDivisor;
return true;
}
}
template <class T>
static bool GWKBilinearResampleNoMasks4SampleT(const GDALWarpKernel *poWK,
int iBand, double dfSrcX,
double dfSrcY, T *pValue)
{
const int iSrcX = static_cast<int>(floor(dfSrcX - 0.5));
const int iSrcY = static_cast<int>(floor(dfSrcY - 0.5));
GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * poWK->nSrcXSize;
const double dfRatioX = 1.5 - (dfSrcX - iSrcX);
const double dfRatioY = 1.5 - (dfSrcY - iSrcY);
const T *const pSrc = reinterpret_cast<T *>(poWK->papabySrcImage[iBand]);
if (iSrcX >= 0 && iSrcX + 1 < poWK->nSrcXSize && iSrcY >= 0 &&
iSrcY + 1 < poWK->nSrcYSize)
{
const double dfAccumulator =
(pSrc[iSrcOffset] * dfRatioX +
pSrc[iSrcOffset + 1] * (1.0 - dfRatioX)) *
dfRatioY +
(pSrc[iSrcOffset + poWK->nSrcXSize] * dfRatioX +
pSrc[iSrcOffset + 1 + poWK->nSrcXSize] * (1.0 - dfRatioX)) *
(1.0 - dfRatioY);
*pValue = GWKRoundValueT<T>(dfAccumulator);
return true;
}
double dfAccumulatorDivisor = 0.0;
double dfAccumulator = 0.0;
// Upper Left Pixel.
if (iSrcX >= 0 && iSrcX < poWK->nSrcXSize && iSrcY >= 0 &&
iSrcY < poWK->nSrcYSize)
{
const double dfMult = dfRatioX * dfRatioY;
dfAccumulatorDivisor += dfMult;
dfAccumulator += pSrc[iSrcOffset] * dfMult;
}
// Upper Right Pixel.
if (iSrcX + 1 >= 0 && iSrcX + 1 < poWK->nSrcXSize && iSrcY >= 0 &&
iSrcY < poWK->nSrcYSize)
{
const double dfMult = (1.0 - dfRatioX) * dfRatioY;
dfAccumulatorDivisor += dfMult;
dfAccumulator += pSrc[iSrcOffset + 1] * dfMult;
}
// Lower Right Pixel.
if (iSrcX + 1 >= 0 && iSrcX + 1 < poWK->nSrcXSize && iSrcY + 1 >= 0 &&
iSrcY + 1 < poWK->nSrcYSize)
{
const double dfMult = (1.0 - dfRatioX) * (1.0 - dfRatioY);
dfAccumulatorDivisor += dfMult;
dfAccumulator += pSrc[iSrcOffset + 1 + poWK->nSrcXSize] * dfMult;
}
// Lower Left Pixel.
if (iSrcX >= 0 && iSrcX < poWK->nSrcXSize && iSrcY + 1 >= 0 &&
iSrcY + 1 < poWK->nSrcYSize)
{
const double dfMult = dfRatioX * (1.0 - dfRatioY);
dfAccumulatorDivisor += dfMult;
dfAccumulator += pSrc[iSrcOffset + poWK->nSrcXSize] * dfMult;
}
/* -------------------------------------------------------------------- */
/* Return result. */
/* -------------------------------------------------------------------- */
double dfValue = 0.0;
if (dfAccumulatorDivisor < 0.00001)
{
*pValue = 0;
return false;
}
else if (dfAccumulatorDivisor == 1.0)
{
dfValue = dfAccumulator;
}
else
{
dfValue = dfAccumulator / dfAccumulatorDivisor;
}
*pValue = GWKRoundValueT<T>(dfValue);
return true;
}
/************************************************************************/
/* GWKCubicResample() */
/* Set of bicubic interpolators using cubic convolution. */
/************************************************************************/
// http://verona.fi-p.unam.mx/boris/practicas/CubConvInterp.pdf Formula 18
// or http://en.wikipedia.org/wiki/Cubic_Hermite_spline : CINTx(p_1,p0,p1,p2)
// http://en.wikipedia.org/wiki/Bicubic_interpolation: matrix notation
// TODO(schwehr): Use an inline function.
#define CubicConvolution(distance1, distance2, distance3, f0, f1, f2, f3) \
(f1 + 0.5 * (distance1 * (f2 - f0) + \
distance2 * (2.0 * f0 - 5.0 * f1 + 4.0 * f2 - f3) + \
distance3 * (3.0 * (f1 - f2) + f3 - f0)))
/************************************************************************/
/* GWKCubicComputeWeights() */
/************************************************************************/
// adfCoeffs[2] = 1.0 - (adfCoeffs[0] + adfCoeffs[1] - adfCoeffs[3]);
// TODO(schwehr): Use an inline function.
#define GWKCubicComputeWeights(dfX_, adfCoeffs) \
{ \
const double dfX = dfX_; \
const double dfHalfX = 0.5 * dfX; \
const double dfThreeX = 3.0 * dfX; \
const double dfHalfX2 = dfHalfX * dfX; \
\
adfCoeffs[0] = dfHalfX * (-1 + dfX * (2 - dfX)); \
adfCoeffs[1] = 1 + dfHalfX2 * (-5 + dfThreeX); \
adfCoeffs[2] = dfHalfX * (1 + dfX * (4 - dfThreeX)); \
adfCoeffs[3] = dfHalfX2 * (-1 + dfX); \
}
// TODO(schwehr): Use an inline function.
#define CONVOL4(v1, v2) \
((v1)[0] * (v2)[0] + (v1)[1] * (v2)[1] + (v1)[2] * (v2)[2] + \
(v1)[3] * (v2)[3])
#if 0
// Optimal (in theory...) for max 2 convolutions: 14 multiplications
// instead of 17.
// TODO(schwehr): Use an inline function.
#define GWKCubicComputeWeights_Optim2MAX(dfX_, adfCoeffs, dfHalfX) \
{ \
const double dfX = dfX_; \
dfHalfX = 0.5 * dfX; \
const double dfThreeX = 3.0 * dfX; \
const double dfXMinus1 = dfX - 1; \
\
adfCoeffs[0] = -1 + dfX * (2 - dfX); \
adfCoeffs[1] = dfX * (-5 + dfThreeX); \
/*adfCoeffs[2] = 1 + dfX * (4 - dfThreeX);*/ \
adfCoeffs[2] = -dfXMinus1 - adfCoeffs[1]; \
/*adfCoeffs[3] = dfX * (-1 + dfX); */ \
adfCoeffs[3] = dfXMinus1 - adfCoeffs[0]; \
}
// TODO(schwehr): Use an inline function.
#define CONVOL4_Optim2MAX(adfCoeffs, v, dfHalfX) \
((v)[1] + (dfHalfX) * ((adfCoeffs)[0] * (v)[0] + (adfCoeffs)[1] * (v)[1] + \
(adfCoeffs)[2] * (v)[2] + (adfCoeffs)[3] * (v)[3]))
#endif
static bool GWKCubicResample4Sample(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal,
double *pdfImag)
{
const int iSrcX = static_cast<int>(dfSrcX - 0.5);
const int iSrcY = static_cast<int>(dfSrcY - 0.5);
GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * poWK->nSrcXSize;
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
double adfDensity[4] = {};
double adfReal[4] = {};
double adfImag[4] = {};
// Get the bilinear interpolation at the image borders.
if (iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 ||
iSrcY + 2 >= poWK->nSrcYSize)
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal, pdfImag);
double adfValueDens[4] = {};
double adfValueReal[4] = {};
double adfValueImag[4] = {};
double adfCoeffsX[4] = {};
GWKCubicComputeWeights(dfDeltaX, adfCoeffsX);
for (GPtrDiff_t i = -1; i < 3; i++)
{
if (!GWKGetPixelRow(poWK, iBand, iSrcOffset + i * poWK->nSrcXSize - 1,
2, adfDensity, adfReal, adfImag) ||
adfDensity[0] < SRC_DENSITY_THRESHOLD ||
adfDensity[1] < SRC_DENSITY_THRESHOLD ||
adfDensity[2] < SRC_DENSITY_THRESHOLD ||
adfDensity[3] < SRC_DENSITY_THRESHOLD)
{
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal, pdfImag);
}
adfValueDens[i + 1] = CONVOL4(adfCoeffsX, adfDensity);
adfValueReal[i + 1] = CONVOL4(adfCoeffsX, adfReal);
adfValueImag[i + 1] = CONVOL4(adfCoeffsX, adfImag);
}
/* -------------------------------------------------------------------- */
/* For now, if we have any pixels missing in the kernel area, */
/* we fallback on using bilinear interpolation. Ideally we */
/* should do "weight adjustment" of our results similarly to */
/* what is done for the cubic spline and lanc. interpolators. */
/* -------------------------------------------------------------------- */
double adfCoeffsY[4] = {};
GWKCubicComputeWeights(dfDeltaY, adfCoeffsY);
*pdfDensity = CONVOL4(adfCoeffsY, adfValueDens);
*pdfReal = CONVOL4(adfCoeffsY, adfValueReal);
*pdfImag = CONVOL4(adfCoeffsY, adfValueImag);
return true;
}
// We do not define USE_SSE_CUBIC_IMPL since in practice, it gives zero
// perf benefit.
#if defined(USE_SSE_CUBIC_IMPL) && (defined(__x86_64) || defined(_M_X64))
/************************************************************************/
/* XMMLoad4Values() */
/* */
/* Load 4 packed byte or uint16, cast them to float and put them in a */
/* m128 register. */
/************************************************************************/
static CPL_INLINE __m128 XMMLoad4Values(const GByte *ptr)
{
#ifdef CPL_CPU_REQUIRES_ALIGNED_ACCESS
unsigned int i;
memcpy(&i, ptr, 4);
__m128i xmm_i = _mm_cvtsi32_si128(s);
#else
__m128i xmm_i = _mm_cvtsi32_si128(*(unsigned int *)(ptr));
#endif
// Zero extend 4 packed unsigned 8-bit integers in a to packed
// 32-bit integers.
#if __SSE4_1__
xmm_i = _mm_cvtepu8_epi32(xmm_i);
#else
xmm_i = _mm_unpacklo_epi8(xmm_i, _mm_setzero_si128());
xmm_i = _mm_unpacklo_epi16(xmm_i, _mm_setzero_si128());
#endif
return _mm_cvtepi32_ps(xmm_i);
}
static CPL_INLINE __m128 XMMLoad4Values(const GUInt16 *ptr)
{
#ifdef CPL_CPU_REQUIRES_ALIGNED_ACCESS
GUInt64 i;
memcpy(&i, ptr, 8);
__m128i xmm_i = _mm_cvtsi64_si128(s);
#else
__m128i xmm_i = _mm_cvtsi64_si128(*(GUInt64 *)(ptr));
#endif
// Zero extend 4 packed unsigned 16-bit integers in a to packed
// 32-bit integers.
#if __SSE4_1__
xmm_i = _mm_cvtepu16_epi32(xmm_i);
#else
xmm_i = _mm_unpacklo_epi16(xmm_i, _mm_setzero_si128());
#endif
return _mm_cvtepi32_ps(xmm_i);
}
/************************************************************************/
/* XMMHorizontalAdd() */
/* */
/* Return the sum of the 4 floating points of the register. */
/************************************************************************/
#if __SSE3__
static CPL_INLINE float XMMHorizontalAdd(__m128 v)
{
__m128 shuf = _mm_movehdup_ps(v); // (v3 , v3 , v1 , v1)
__m128 sums = _mm_add_ps(v, shuf); // (v3+v3, v3+v2, v1+v1, v1+v0)
shuf = _mm_movehl_ps(shuf, sums); // (v3 , v3 , v3+v3, v3+v2)
sums = _mm_add_ss(sums, shuf); // (v1+v0)+(v3+v2)
return _mm_cvtss_f32(sums);
}
#else
static CPL_INLINE float XMMHorizontalAdd(__m128 v)
{
__m128 shuf = _mm_movehl_ps(v, v); // (v3 , v2 , v3 , v2)
__m128 sums = _mm_add_ps(v, shuf); // (v3+v3, v2+v2, v3+v1, v2+v0)
shuf = _mm_shuffle_ps(sums, sums, 1); // (v2+v0, v2+v0, v2+v0, v3+v1)
sums = _mm_add_ss(sums, shuf); // (v2+v0)+(v3+v1)
return _mm_cvtss_f32(sums);
}
#endif
#endif // defined(USE_SSE_CUBIC_IMPL) && (defined(__x86_64) || defined(_M_X64))
/************************************************************************/
/* GWKCubicResampleSrcMaskIsDensity4SampleRealT() */
/************************************************************************/
// Note: if USE_SSE_CUBIC_IMPL, only instantiate that for Byte and UInt16,
// because there are a few assumptions above those types.
template <class T>
static CPL_INLINE bool GWKCubicResampleSrcMaskIsDensity4SampleRealT(
const GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal)
{
const int iSrcX = static_cast<int>(dfSrcX - 0.5);
const int iSrcY = static_cast<int>(dfSrcY - 0.5);
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * poWK->nSrcXSize;
// Get the bilinear interpolation at the image borders.
if (iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 ||
iSrcY + 2 >= poWK->nSrcYSize)
{
double adfImagIgnored[4] = {};
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal, adfImagIgnored);
}
#if defined(USE_SSE_CUBIC_IMPL) && (defined(__x86_64) || defined(_M_X64))
const float fDeltaX = static_cast<float>(dfSrcX) - 0.5f - iSrcX;
const float fDeltaY = static_cast<float>(dfSrcY) - 0.5f - iSrcY;
// TODO(schwehr): Explain the magic numbers.
float afTemp[4 + 4 + 4 + 1];
float *pafAligned =
reinterpret_cast<float *>(afTemp + ((size_t)afTemp & 0xf));
float *pafCoeffs = pafAligned;
float *pafDensity = pafAligned + 4;
float *pafValue = pafAligned + 8;
const float fHalfDeltaX = 0.5f * fDeltaX;
const float fThreeDeltaX = 3.0f * fDeltaX;
const float fHalfDeltaX2 = fHalfDeltaX * fDeltaX;
pafCoeffs[0] = fHalfDeltaX * (-1 + fDeltaX * (2 - fDeltaX));
pafCoeffs[1] = 1 + fHalfDeltaX2 * (-5 + fThreeDeltaX);
pafCoeffs[2] = fHalfDeltaX * (1 + fDeltaX * (4 - fThreeDeltaX));
pafCoeffs[3] = fHalfDeltaX2 * (-1 + fDeltaX);
__m128 xmmCoeffs = _mm_load_ps(pafCoeffs);
const __m128 xmmThreshold = _mm_load1_ps(&SRC_DENSITY_THRESHOLD);
__m128 xmmMaskLowDensity = _mm_setzero_ps();
for (GPtrDiff_t i = -1, iOffset = iSrcOffset - poWK->nSrcXSize - 1; i < 3;
i++, iOffset += poWK->nSrcXSize)
{
const __m128 xmmDensity =
_mm_loadu_ps(poWK->pafUnifiedSrcDensity + iOffset);
xmmMaskLowDensity = _mm_or_ps(xmmMaskLowDensity,
_mm_cmplt_ps(xmmDensity, xmmThreshold));
pafDensity[i + 1] = XMMHorizontalAdd(_mm_mul_ps(xmmCoeffs, xmmDensity));
const __m128 xmmValues =
XMMLoad4Values(((T *)poWK->papabySrcImage[iBand]) + iOffset);
pafValue[i + 1] = XMMHorizontalAdd(_mm_mul_ps(xmmCoeffs, xmmValues));
}
if (_mm_movemask_ps(xmmMaskLowDensity))
{
double adfImagIgnored[4] = {};
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal, adfImagIgnored);
}
const float fHalfDeltaY = 0.5f * fDeltaY;
const float fThreeDeltaY = 3.0f * fDeltaY;
const float fHalfDeltaY2 = fHalfDeltaY * fDeltaY;
pafCoeffs[0] = fHalfDeltaY * (-1 + fDeltaY * (2 - fDeltaY));
pafCoeffs[1] = 1 + fHalfDeltaY2 * (-5 + fThreeDeltaY);
pafCoeffs[2] = fHalfDeltaY * (1 + fDeltaY * (4 - fThreeDeltaY));
pafCoeffs[3] = fHalfDeltaY2 * (-1 + fDeltaY);
xmmCoeffs = _mm_load_ps(pafCoeffs);
const __m128 xmmDensity = _mm_load_ps(pafDensity);
const __m128 xmmValue = _mm_load_ps(pafValue);
*pdfDensity = XMMHorizontalAdd(_mm_mul_ps(xmmCoeffs, xmmDensity));
*pdfReal = XMMHorizontalAdd(_mm_mul_ps(xmmCoeffs, xmmValue));
// We did all above computations on float32 whereas the general case is
// float64. Not sure if one is fundamentally more correct than the other
// one, but we want our optimization to give the same result as the
// general case as much as possible, so if the resulting value is
// close to some_int_value + 0.5, redo the computation with the general
// case.
// Note: If other types than Byte or UInt16, will need changes.
if (fabs(*pdfReal - static_cast<int>(*pdfReal) - 0.5) > .007)
return true;
#endif // defined(USE_SSE_CUBIC_IMPL) && (defined(__x86_64) || defined(_M_X64))
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
double adfValueDens[4] = {};
double adfValueReal[4] = {};
double adfCoeffsX[4] = {};
GWKCubicComputeWeights(dfDeltaX, adfCoeffsX);
double adfCoeffsY[4] = {};
GWKCubicComputeWeights(dfDeltaY, adfCoeffsY);
for (GPtrDiff_t i = -1; i < 3; i++)
{
const GPtrDiff_t iOffset = iSrcOffset + i * poWK->nSrcXSize - 1;
#if !(defined(USE_SSE_CUBIC_IMPL) && (defined(__x86_64) || defined(_M_X64)))
if (poWK->pafUnifiedSrcDensity[iOffset + 0] < SRC_DENSITY_THRESHOLD ||
poWK->pafUnifiedSrcDensity[iOffset + 1] < SRC_DENSITY_THRESHOLD ||
poWK->pafUnifiedSrcDensity[iOffset + 2] < SRC_DENSITY_THRESHOLD ||
poWK->pafUnifiedSrcDensity[iOffset + 3] < SRC_DENSITY_THRESHOLD)
{
double adfImagIgnored[4] = {};
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal,
adfImagIgnored);
}
#endif
adfValueDens[i + 1] =
CONVOL4(adfCoeffsX, poWK->pafUnifiedSrcDensity + iOffset);
adfValueReal[i + 1] = CONVOL4(
adfCoeffsX,
reinterpret_cast<T *>(poWK->papabySrcImage[iBand]) + iOffset);
}
*pdfDensity = CONVOL4(adfCoeffsY, adfValueDens);
*pdfReal = CONVOL4(adfCoeffsY, adfValueReal);
return true;
}
/************************************************************************/
/* GWKCubicResampleSrcMaskIsDensity4SampleReal() */
/* Bi-cubic when source has and only has pafUnifiedSrcDensity. */
/************************************************************************/
static bool GWKCubicResampleSrcMaskIsDensity4SampleReal(
const GDALWarpKernel *poWK, int iBand, double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal)
{
const int iSrcX = static_cast<int>(dfSrcX - 0.5);
const int iSrcY = static_cast<int>(dfSrcY - 0.5);
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * poWK->nSrcXSize;
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
// Get the bilinear interpolation at the image borders.
if (iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 ||
iSrcY + 2 >= poWK->nSrcYSize)
{
double adfImagIgnored[4] = {};
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal, adfImagIgnored);
}
double adfCoeffsX[4] = {};
GWKCubicComputeWeights(dfDeltaX, adfCoeffsX);
double adfCoeffsY[4] = {};
GWKCubicComputeWeights(dfDeltaY, adfCoeffsY);
double adfValueDens[4] = {};
double adfValueReal[4] = {};
double adfDensity[4] = {};
double adfReal[4] = {};
double adfImagIgnored[4] = {};
for (GPtrDiff_t i = -1; i < 3; i++)
{
if (!GWKGetPixelRow(poWK, iBand, iSrcOffset + i * poWK->nSrcXSize - 1,
2, adfDensity, adfReal, adfImagIgnored) ||
adfDensity[0] < SRC_DENSITY_THRESHOLD ||
adfDensity[1] < SRC_DENSITY_THRESHOLD ||
adfDensity[2] < SRC_DENSITY_THRESHOLD ||
adfDensity[3] < SRC_DENSITY_THRESHOLD)
{
return GWKBilinearResample4Sample(poWK, iBand, dfSrcX, dfSrcY,
pdfDensity, pdfReal,
adfImagIgnored);
}
adfValueDens[i + 1] = CONVOL4(adfCoeffsX, adfDensity);
adfValueReal[i + 1] = CONVOL4(adfCoeffsX, adfReal);
}
*pdfDensity = CONVOL4(adfCoeffsY, adfValueDens);
*pdfReal = CONVOL4(adfCoeffsY, adfValueReal);
return true;
}
template <class T>
static bool GWKCubicResampleNoMasks4SampleT(const GDALWarpKernel *poWK,
int iBand, double dfSrcX,
double dfSrcY, T *pValue)
{
const int iSrcX = static_cast<int>(dfSrcX - 0.5);
const int iSrcY = static_cast<int>(dfSrcY - 0.5);
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * poWK->nSrcXSize;
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
const double dfDeltaY2 = dfDeltaY * dfDeltaY;
const double dfDeltaY3 = dfDeltaY2 * dfDeltaY;
// Get the bilinear interpolation at the image borders.
if (iSrcX - 1 < 0 || iSrcX + 2 >= poWK->nSrcXSize || iSrcY - 1 < 0 ||
iSrcY + 2 >= poWK->nSrcYSize)
return GWKBilinearResampleNoMasks4SampleT(poWK, iBand, dfSrcX, dfSrcY,
pValue);
double adfCoeffs[4] = {};
GWKCubicComputeWeights(dfDeltaX, adfCoeffs);
double adfValue[4] = {};
for (GPtrDiff_t i = -1; i < 3; i++)
{
const GPtrDiff_t iOffset = iSrcOffset + i * poWK->nSrcXSize - 1;
adfValue[i + 1] = CONVOL4(
adfCoeffs,
reinterpret_cast<T *>(poWK->papabySrcImage[iBand]) + iOffset);
}
const double dfValue =
CubicConvolution(dfDeltaY, dfDeltaY2, dfDeltaY3, adfValue[0],
adfValue[1], adfValue[2], adfValue[3]);
*pValue = GWKClampValueT<T>(dfValue);
return true;
}
/************************************************************************/
/* GWKLanczosSinc() */
/************************************************************************/
/*
* Lanczos windowed sinc interpolation kernel with radius r.
* /
* | sinc(x) * sinc(x/r), if |x| < r
* L(x) = | 1, if x = 0 ,
* | 0, otherwise
* \
*
* where sinc(x) = sin(PI * x) / (PI * x).
*/
static double GWKLanczosSinc(double dfX)
{
if (dfX == 0.0)
return 1.0;
const double dfPIX = M_PI * dfX;
const double dfPIXoverR = dfPIX / 3;
const double dfPIX2overR = dfPIX * dfPIXoverR;
return sin(dfPIX) * sin(dfPIXoverR) / dfPIX2overR;
}
static double GWKLanczosSinc4Values(double *padfValues)
{
for (int i = 0; i < 4; i++)
{
if (padfValues[i] == 0.0)
{
padfValues[i] = 1.0;
}
else
{
const double dfPIX = M_PI * padfValues[i];
const double dfPIXoverR = dfPIX / 3;
const double dfPIX2overR = dfPIX * dfPIXoverR;
padfValues[i] = sin(dfPIX) * sin(dfPIXoverR) / dfPIX2overR;
}
}
return padfValues[0] + padfValues[1] + padfValues[2] + padfValues[3];
}
/************************************************************************/
/* GWKBilinear() */
/************************************************************************/
static double GWKBilinear(double dfX)
{
double dfAbsX = fabs(dfX);
if (dfAbsX <= 1.0)
return 1 - dfAbsX;
else
return 0.0;
}
static double GWKBilinear4Values(double *padfValues)
{
double dfAbsX0 = fabs(padfValues[0]);
double dfAbsX1 = fabs(padfValues[1]);
double dfAbsX2 = fabs(padfValues[2]);
double dfAbsX3 = fabs(padfValues[3]);
if (dfAbsX0 <= 1.0)
padfValues[0] = 1 - dfAbsX0;
else
padfValues[0] = 0.0;
if (dfAbsX1 <= 1.0)
padfValues[1] = 1 - dfAbsX1;
else
padfValues[1] = 0.0;
if (dfAbsX2 <= 1.0)
padfValues[2] = 1 - dfAbsX2;
else
padfValues[2] = 0.0;
if (dfAbsX3 <= 1.0)
padfValues[3] = 1 - dfAbsX3;
else
padfValues[3] = 0.0;
return padfValues[0] + padfValues[1] + padfValues[2] + padfValues[3];
}
/************************************************************************/
/* GWKCubic() */
/************************************************************************/
static double GWKCubic(double dfX)
{
// http://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm
// W(x) formula with a = -0.5 (cubic hermite spline )
// or
// https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf
// k(x) (formula 8) with (B,C)=(0,0.5) the Catmull-Rom spline
double dfAbsX = fabs(dfX);
if (dfAbsX <= 1.0)
{
double dfX2 = dfX * dfX;
return dfX2 * (1.5 * dfAbsX - 2.5) + 1;
}
else if (dfAbsX <= 2.0)
{
double dfX2 = dfX * dfX;
return dfX2 * (-0.5 * dfAbsX + 2.5) - 4 * dfAbsX + 2;
}
else
return 0.0;
}
static double GWKCubic4Values(double *padfValues)
{
const double dfAbsX_0 = fabs(padfValues[0]);
const double dfAbsX_1 = fabs(padfValues[1]);
const double dfAbsX_2 = fabs(padfValues[2]);
const double dfAbsX_3 = fabs(padfValues[3]);
const double dfX2_0 = padfValues[0] * padfValues[0];
const double dfX2_1 = padfValues[1] * padfValues[1];
const double dfX2_2 = padfValues[2] * padfValues[2];
const double dfX2_3 = padfValues[3] * padfValues[3];
double dfVal0 = 0.0;
if (dfAbsX_0 <= 1.0)
dfVal0 = dfX2_0 * (1.5 * dfAbsX_0 - 2.5) + 1.0;
else if (dfAbsX_0 <= 2.0)
dfVal0 = dfX2_0 * (-0.5 * dfAbsX_0 + 2.5) - 4.0 * dfAbsX_0 + 2.0;
double dfVal1 = 0.0;
if (dfAbsX_1 <= 1.0)
dfVal1 = dfX2_1 * (1.5 * dfAbsX_1 - 2.5) + 1.0;
else if (dfAbsX_1 <= 2.0)
dfVal1 = dfX2_1 * (-0.5 * dfAbsX_1 + 2.5) - 4.0 * dfAbsX_1 + 2.0;
double dfVal2 = 0.0;
if (dfAbsX_2 <= 1.0)
dfVal2 = dfX2_2 * (1.5 * dfAbsX_2 - 2.5) + 1.0;
else if (dfAbsX_2 <= 2.0)
dfVal2 = dfX2_2 * (-0.5 * dfAbsX_2 + 2.5) - 4.0 * dfAbsX_2 + 2.0;
double dfVal3 = 0.0;
if (dfAbsX_3 <= 1.0)
dfVal3 = dfX2_3 * (1.5 * dfAbsX_3 - 2.5) + 1.0;
else if (dfAbsX_3 <= 2.0)
dfVal3 = dfX2_3 * (-0.5 * dfAbsX_3 + 2.5) - 4.0 * dfAbsX_3 + 2.0;
padfValues[0] = dfVal0;
padfValues[1] = dfVal1;
padfValues[2] = dfVal2;
padfValues[3] = dfVal3;
return dfVal0 + dfVal1 + dfVal2 + dfVal3;
}
/************************************************************************/
/* GWKBSpline() */
/************************************************************************/
// https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf
// Equation 8 with (B,C)=(1,0)
// 1/6 * ( 3 * |x|^3 - 6 * |x|^2 + 4) |x| < 1
// 1/6 * ( -|x|^3 + 6 |x|^2 - 12|x| + 8) |x| >= 1 and |x| < 2
static double GWKBSpline(double x)
{
const double xp2 = x + 2.0;
const double xp1 = x + 1.0;
const double xm1 = x - 1.0;
// This will most likely be used, so we'll compute it ahead of time to
// avoid stalling the processor.
const double xp2c = xp2 * xp2 * xp2;
// Note that the test is computed only if it is needed.
// TODO(schwehr): Make this easier to follow.
return xp2 > 0.0
? ((xp1 > 0.0)
? ((x > 0.0)
? ((xm1 > 0.0) ? -4.0 * xm1 * xm1 * xm1 : 0.0) +
6.0 * x * x * x
: 0.0) +
-4.0 * xp1 * xp1 * xp1
: 0.0) +
xp2c
: 0.0; // * 0.166666666666666666666
}
static double GWKBSpline4Values(double *padfValues)
{
for (int i = 0; i < 4; i++)
{
const double x = padfValues[i];
const double xp2 = x + 2.0;
const double xp1 = x + 1.0;
const double xm1 = x - 1.0;
// This will most likely be used, so we'll compute it ahead of time to
// avoid stalling the processor.
const double xp2c = xp2 * xp2 * xp2;
// Note that the test is computed only if it is needed.
// TODO(schwehr): Make this easier to follow.
padfValues[i] =
(xp2 > 0.0)
? ((xp1 > 0.0)
? ((x > 0.0)
? ((xm1 > 0.0) ? -4.0 * xm1 * xm1 * xm1 : 0.0) +
6.0 * x * x * x
: 0.0) +
-4.0 * xp1 * xp1 * xp1
: 0.0) +
xp2c
: 0.0; // * 0.166666666666666666666
}
return padfValues[0] + padfValues[1] + padfValues[2] + padfValues[3];
}
/************************************************************************/
/* GWKResampleWrkStruct */
/************************************************************************/
typedef struct _GWKResampleWrkStruct GWKResampleWrkStruct;
typedef bool (*pfnGWKResampleType)(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal,
double *pdfImag,
GWKResampleWrkStruct *psWrkStruct);
struct _GWKResampleWrkStruct
{
pfnGWKResampleType pfnGWKResample;
// Space for saved X weights.
double *padfWeightsX;
bool *pabCalcX;
double *padfWeightsY; // Only used by GWKResampleOptimizedLanczos.
int iLastSrcX; // Only used by GWKResampleOptimizedLanczos.
int iLastSrcY; // Only used by GWKResampleOptimizedLanczos.
double dfLastDeltaX; // Only used by GWKResampleOptimizedLanczos.
double dfLastDeltaY; // Only used by GWKResampleOptimizedLanczos.
// Space for saving a row of pixels.
double *padfRowDensity;
double *padfRowReal;
double *padfRowImag;
};
/************************************************************************/
/* GWKResampleCreateWrkStruct() */
/************************************************************************/
static bool GWKResample(const GDALWarpKernel *poWK, int iBand, double dfSrcX,
double dfSrcY, double *pdfDensity, double *pdfReal,
double *pdfImag, GWKResampleWrkStruct *psWrkStruct);
static bool GWKResampleOptimizedLanczos(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal,
double *pdfImag,
GWKResampleWrkStruct *psWrkStruct);
static GWKResampleWrkStruct *GWKResampleCreateWrkStruct(GDALWarpKernel *poWK)
{
const int nXDist = (poWK->nXRadius + 1) * 2;
const int nYDist = (poWK->nYRadius + 1) * 2;
GWKResampleWrkStruct *psWrkStruct = static_cast<GWKResampleWrkStruct *>(
CPLMalloc(sizeof(GWKResampleWrkStruct)));
// Alloc space for saved X weights.
psWrkStruct->padfWeightsX =
static_cast<double *>(CPLCalloc(nXDist, sizeof(double)));
psWrkStruct->pabCalcX =
static_cast<bool *>(CPLMalloc(nXDist * sizeof(bool)));
psWrkStruct->padfWeightsY =
static_cast<double *>(CPLCalloc(nYDist, sizeof(double)));
psWrkStruct->iLastSrcX = -10;
psWrkStruct->iLastSrcY = -10;
psWrkStruct->dfLastDeltaX = -10;
psWrkStruct->dfLastDeltaY = -10;
// Alloc space for saving a row of pixels.
if (poWK->pafUnifiedSrcDensity == nullptr &&
poWK->panUnifiedSrcValid == nullptr &&
poWK->papanBandSrcValid == nullptr)
{
psWrkStruct->padfRowDensity = nullptr;
}
else
{
psWrkStruct->padfRowDensity =
static_cast<double *>(CPLCalloc(nXDist, sizeof(double)));
}
psWrkStruct->padfRowReal =
static_cast<double *>(CPLCalloc(nXDist, sizeof(double)));
psWrkStruct->padfRowImag =
static_cast<double *>(CPLCalloc(nXDist, sizeof(double)));
if (poWK->eResample == GRA_Lanczos)
{
psWrkStruct->pfnGWKResample = GWKResampleOptimizedLanczos;
const double dfXScale = poWK->dfXScale;
if (dfXScale < 1.0)
{
int iMin = poWK->nFiltInitX;
int iMax = poWK->nXRadius;
while (iMin * dfXScale < -3.0)
iMin++;
while (iMax * dfXScale > 3.0)
iMax--;
for (int i = iMin; i <= iMax; ++i)
{
psWrkStruct->padfWeightsX[i - poWK->nFiltInitX] =
GWKLanczosSinc(i * dfXScale);
}
}
const double dfYScale = poWK->dfYScale;
if (dfYScale < 1.0)
{
int jMin = poWK->nFiltInitY;
int jMax = poWK->nYRadius;
while (jMin * dfYScale < -3.0)
jMin++;
while (jMax * dfYScale > 3.0)
jMax--;
for (int j = jMin; j <= jMax; ++j)
{
psWrkStruct->padfWeightsY[j - poWK->nFiltInitY] =
GWKLanczosSinc(j * dfYScale);
}
}
}
else
psWrkStruct->pfnGWKResample = GWKResample;
return psWrkStruct;
}
/************************************************************************/
/* GWKResampleDeleteWrkStruct() */
/************************************************************************/
static void GWKResampleDeleteWrkStruct(GWKResampleWrkStruct *psWrkStruct)
{
CPLFree(psWrkStruct->padfWeightsX);
CPLFree(psWrkStruct->padfWeightsY);
CPLFree(psWrkStruct->pabCalcX);
CPLFree(psWrkStruct->padfRowDensity);
CPLFree(psWrkStruct->padfRowReal);
CPLFree(psWrkStruct->padfRowImag);
CPLFree(psWrkStruct);
}
/************************************************************************/
/* GWKResample() */
/************************************************************************/
static bool GWKResample(const GDALWarpKernel *poWK, int iBand, double dfSrcX,
double dfSrcY, double *pdfDensity, double *pdfReal,
double *pdfImag, GWKResampleWrkStruct *psWrkStruct)
{
// Save as local variables to avoid following pointers in loops.
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
double dfAccumulatorReal = 0.0;
double dfAccumulatorImag = 0.0;
double dfAccumulatorDensity = 0.0;
double dfAccumulatorWeight = 0.0;
const int iSrcX = static_cast<int>(floor(dfSrcX - 0.5));
const int iSrcY = static_cast<int>(floor(dfSrcY - 0.5));
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
const double dfXScale = poWK->dfXScale;
const double dfYScale = poWK->dfYScale;
const int nXDist = (poWK->nXRadius + 1) * 2;
// Space for saved X weights.
double *padfWeightsX = psWrkStruct->padfWeightsX;
bool *pabCalcX = psWrkStruct->pabCalcX;
// Space for saving a row of pixels.
double *padfRowDensity = psWrkStruct->padfRowDensity;
double *padfRowReal = psWrkStruct->padfRowReal;
double *padfRowImag = psWrkStruct->padfRowImag;
// Mark as needing calculation (don't calculate the weights yet,
// because a mask may render it unnecessary).
memset(pabCalcX, false, nXDist * sizeof(bool));
FilterFuncType pfnGetWeight = apfGWKFilter[poWK->eResample];
CPLAssert(pfnGetWeight);
// Skip sampling over edge of image.
int j = poWK->nFiltInitY;
int jMax = poWK->nYRadius;
if (iSrcY + j < 0)
j = -iSrcY;
if (iSrcY + jMax >= nSrcYSize)
jMax = nSrcYSize - iSrcY - 1;
int iMin = poWK->nFiltInitX;
int iMax = poWK->nXRadius;
if (iSrcX + iMin < 0)
iMin = -iSrcX;
if (iSrcX + iMax >= nSrcXSize)
iMax = nSrcXSize - iSrcX - 1;
const int bXScaleBelow1 = (dfXScale < 1.0);
const int bYScaleBelow1 = (dfYScale < 1.0);
GPtrDiff_t iRowOffset =
iSrcOffset + static_cast<GPtrDiff_t>(j - 1) * nSrcXSize + iMin;
// Loop over pixel rows in the kernel.
for (; j <= jMax; ++j)
{
iRowOffset += nSrcXSize;
// Get pixel values.
// We can potentially read extra elements after the "normal" end of the
// source arrays, but the contract of papabySrcImage[iBand],
// papanBandSrcValid[iBand], panUnifiedSrcValid and pafUnifiedSrcDensity
// is to have WARP_EXTRA_ELTS reserved at their end.
if (!GWKGetPixelRow(poWK, iBand, iRowOffset, (iMax - iMin + 2) / 2,
padfRowDensity, padfRowReal, padfRowImag))
continue;
// Calculate the Y weight.
double dfWeight1 = (bYScaleBelow1)
? pfnGetWeight((j - dfDeltaY) * dfYScale)
: pfnGetWeight(j - dfDeltaY);
// Iterate over pixels in row.
double dfAccumulatorRealLocal = 0.0;
double dfAccumulatorImagLocal = 0.0;
double dfAccumulatorDensityLocal = 0.0;
double dfAccumulatorWeightLocal = 0.0;
for (int i = iMin; i <= iMax; ++i)
{
// Skip sampling if pixel has zero density.
if (padfRowDensity != nullptr &&
padfRowDensity[i - iMin] < SRC_DENSITY_THRESHOLD)
continue;
double dfWeight2 = 0.0;
// Make or use a cached set of weights for this row.
if (pabCalcX[i - iMin])
{
// Use saved weight value instead of recomputing it.
dfWeight2 = padfWeightsX[i - iMin];
}
else
{
// Calculate & save the X weight.
padfWeightsX[i - iMin] = dfWeight2 =
(bXScaleBelow1) ? pfnGetWeight((i - dfDeltaX) * dfXScale)
: pfnGetWeight(i - dfDeltaX);
pabCalcX[i - iMin] = true;
}
// Accumulate!
dfAccumulatorRealLocal += padfRowReal[i - iMin] * dfWeight2;
dfAccumulatorImagLocal += padfRowImag[i - iMin] * dfWeight2;
if (padfRowDensity != nullptr)
dfAccumulatorDensityLocal +=
padfRowDensity[i - iMin] * dfWeight2;
dfAccumulatorWeightLocal += dfWeight2;
}
dfAccumulatorReal += dfAccumulatorRealLocal * dfWeight1;
dfAccumulatorImag += dfAccumulatorImagLocal * dfWeight1;
dfAccumulatorDensity += dfAccumulatorDensityLocal * dfWeight1;
dfAccumulatorWeight += dfAccumulatorWeightLocal * dfWeight1;
}
if (dfAccumulatorWeight < 0.000001 ||
(padfRowDensity != nullptr && dfAccumulatorDensity < 0.000001))
{
*pdfDensity = 0.0;
return false;
}
// Calculate the output taking into account weighting.
if (dfAccumulatorWeight < 0.99999 || dfAccumulatorWeight > 1.00001)
{
*pdfReal = dfAccumulatorReal / dfAccumulatorWeight;
*pdfImag = dfAccumulatorImag / dfAccumulatorWeight;
if (padfRowDensity != nullptr)
*pdfDensity = dfAccumulatorDensity / dfAccumulatorWeight;
else
*pdfDensity = 1.0;
}
else
{
*pdfReal = dfAccumulatorReal;
*pdfImag = dfAccumulatorImag;
if (padfRowDensity != nullptr)
*pdfDensity = dfAccumulatorDensity;
else
*pdfDensity = 1.0;
}
return true;
}
/************************************************************************/
/* GWKResampleOptimizedLanczos() */
/************************************************************************/
static bool GWKResampleOptimizedLanczos(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY,
double *pdfDensity, double *pdfReal,
double *pdfImag,
GWKResampleWrkStruct *psWrkStruct)
{
// Save as local variables to avoid following pointers in loops.
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
double dfAccumulatorReal = 0.0;
double dfAccumulatorImag = 0.0;
double dfAccumulatorDensity = 0.0;
double dfAccumulatorWeight = 0.0;
const int iSrcX = static_cast<int>(floor(dfSrcX - 0.5));
const int iSrcY = static_cast<int>(floor(dfSrcY - 0.5));
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
const double dfXScale = poWK->dfXScale;
const double dfYScale = poWK->dfYScale;
// Space for saved X weights.
double *padfWeightsX = psWrkStruct->padfWeightsX;
double *padfWeightsY = psWrkStruct->padfWeightsY;
// Space for saving a row of pixels.
double *padfRowDensity = psWrkStruct->padfRowDensity;
double *padfRowReal = psWrkStruct->padfRowReal;
double *padfRowImag = psWrkStruct->padfRowImag;
// Skip sampling over edge of image.
int jMin = poWK->nFiltInitY;
int jMax = poWK->nYRadius;
if (iSrcY + jMin < 0)
jMin = -iSrcY;
if (iSrcY + jMax >= nSrcYSize)
jMax = nSrcYSize - iSrcY - 1;
int iMin = poWK->nFiltInitX;
int iMax = poWK->nXRadius;
if (iSrcX + iMin < 0)
iMin = -iSrcX;
if (iSrcX + iMax >= nSrcXSize)
iMax = nSrcXSize - iSrcX - 1;
if (dfXScale < 1.0)
{
while (iMin * dfXScale < -3.0)
iMin++;
while (iMax * dfXScale > 3.0)
iMax--;
// padfWeightsX computed in GWKResampleCreateWrkStruct.
}
else
{
while (iMin - dfDeltaX < -3.0)
iMin++;
while (iMax - dfDeltaX > 3.0)
iMax--;
if (iSrcX != psWrkStruct->iLastSrcX ||
dfDeltaX != psWrkStruct->dfLastDeltaX)
{
// Optimisation of GWKLanczosSinc(i - dfDeltaX) based on the
// following trigonometric formulas.
// TODO(schwehr): Move this somewhere where it can be rendered at
// LaTeX. sin(M_PI * (dfBase + k)) = sin(M_PI * dfBase) * cos(M_PI *
// k) + cos(M_PI * dfBase) * sin(M_PI * k) sin(M_PI * (dfBase + k))
// = dfSinPIBase * cos(M_PI * k) + dfCosPIBase * sin(M_PI * k)
// sin(M_PI * (dfBase + k)) = dfSinPIBase * cos(M_PI * k)
// sin(M_PI * (dfBase + k)) = dfSinPIBase * (((k % 2) == 0) ? 1 :
// -1)
// sin(M_PI / dfR * (dfBase + k)) = sin(M_PI / dfR * dfBase) *
// cos(M_PI / dfR * k) + cos(M_PI / dfR * dfBase) * sin(M_PI / dfR *
// k) sin(M_PI / dfR * (dfBase + k)) = dfSinPIBaseOverR * cos(M_PI /
// dfR * k) + dfCosPIBaseOverR * sin(M_PI / dfR * k)
const double dfSinPIDeltaXOver3 = sin((-M_PI / 3.0) * dfDeltaX);
const double dfSin2PIDeltaXOver3 =
dfSinPIDeltaXOver3 * dfSinPIDeltaXOver3;
// Ok to use sqrt(1-sin^2) since M_PI / 3 * dfDeltaX < PI/2.
const double dfCosPIDeltaXOver3 = sqrt(1.0 - dfSin2PIDeltaXOver3);
const double dfSinPIDeltaX =
(3.0 - 4 * dfSin2PIDeltaXOver3) * dfSinPIDeltaXOver3;
const double dfInvPI2Over3 = 3.0 / (M_PI * M_PI);
const double dfInvPI2Over3xSinPIDeltaX =
dfInvPI2Over3 * dfSinPIDeltaX;
const double dfInvPI2Over3xSinPIDeltaXxm0d5SinPIDeltaXOver3 =
-0.5 * dfInvPI2Over3xSinPIDeltaX * dfSinPIDeltaXOver3;
const double dfSinPIOver3 = 0.8660254037844386;
const double dfInvPI2Over3xSinPIDeltaXxSinPIOver3xCosPIDeltaXOver3 =
dfSinPIOver3 * dfInvPI2Over3xSinPIDeltaX * dfCosPIDeltaXOver3;
const double padfCst[] = {
dfInvPI2Over3xSinPIDeltaX * dfSinPIDeltaXOver3,
dfInvPI2Over3xSinPIDeltaXxm0d5SinPIDeltaXOver3 -
dfInvPI2Over3xSinPIDeltaXxSinPIOver3xCosPIDeltaXOver3,
dfInvPI2Over3xSinPIDeltaXxm0d5SinPIDeltaXOver3 +
dfInvPI2Over3xSinPIDeltaXxSinPIOver3xCosPIDeltaXOver3};
for (int i = iMin; i <= iMax; ++i)
{
const double dfX = i - dfDeltaX;
if (dfX == 0.0)
padfWeightsX[i - poWK->nFiltInitX] = 1.0;
else
padfWeightsX[i - poWK->nFiltInitX] =
padfCst[(i + 3) % 3] / (dfX * dfX);
#if DEBUG_VERBOSE
// TODO(schwehr): AlmostEqual.
// CPLAssert(fabs(padfWeightsX[i-poWK->nFiltInitX] -
// GWKLanczosSinc(dfX, 3.0)) < 1e-10);
#endif
}
psWrkStruct->iLastSrcX = iSrcX;
psWrkStruct->dfLastDeltaX = dfDeltaX;
}
}
if (dfYScale < 1.0)
{
while (jMin * dfYScale < -3.0)
jMin++;
while (jMax * dfYScale > 3.0)
jMax--;
// padfWeightsY computed in GWKResampleCreateWrkStruct.
}
else
{
while (jMin - dfDeltaY < -3.0)
jMin++;
while (jMax - dfDeltaY > 3.0)
jMax--;
if (iSrcY != psWrkStruct->iLastSrcY ||
dfDeltaY != psWrkStruct->dfLastDeltaY)
{
const double dfSinPIDeltaYOver3 = sin((-M_PI / 3.0) * dfDeltaY);
const double dfSin2PIDeltaYOver3 =
dfSinPIDeltaYOver3 * dfSinPIDeltaYOver3;
// Ok to use sqrt(1-sin^2) since M_PI / 3 * dfDeltaY < PI/2.
const double dfCosPIDeltaYOver3 = sqrt(1.0 - dfSin2PIDeltaYOver3);
const double dfSinPIDeltaY =
(3.0 - 4.0 * dfSin2PIDeltaYOver3) * dfSinPIDeltaYOver3;
const double dfInvPI2Over3 = 3.0 / (M_PI * M_PI);
const double dfInvPI2Over3xSinPIDeltaY =
dfInvPI2Over3 * dfSinPIDeltaY;
const double dfInvPI2Over3xSinPIDeltaYxm0d5SinPIDeltaYOver3 =
-0.5 * dfInvPI2Over3xSinPIDeltaY * dfSinPIDeltaYOver3;
const double dfSinPIOver3 = 0.8660254037844386;
const double dfInvPI2Over3xSinPIDeltaYxSinPIOver3xCosPIDeltaYOver3 =
dfSinPIOver3 * dfInvPI2Over3xSinPIDeltaY * dfCosPIDeltaYOver3;
const double padfCst[] = {
dfInvPI2Over3xSinPIDeltaY * dfSinPIDeltaYOver3,
dfInvPI2Over3xSinPIDeltaYxm0d5SinPIDeltaYOver3 -
dfInvPI2Over3xSinPIDeltaYxSinPIOver3xCosPIDeltaYOver3,
dfInvPI2Over3xSinPIDeltaYxm0d5SinPIDeltaYOver3 +
dfInvPI2Over3xSinPIDeltaYxSinPIOver3xCosPIDeltaYOver3};
for (int j = jMin; j <= jMax; ++j)
{
const double dfY = j - dfDeltaY;
if (dfY == 0.0)
padfWeightsY[j - poWK->nFiltInitY] = 1.0;
else
padfWeightsY[j - poWK->nFiltInitY] =
padfCst[(j + 3) % 3] / (dfY * dfY);
#if DEBUG_VERBOSE
// TODO(schwehr): AlmostEqual.
// CPLAssert(fabs(padfWeightsY[j-poWK->nFiltInitY] -
// GWKLanczosSinc(dfY, 3.0)) < 1e-10);
#endif
}
psWrkStruct->iLastSrcY = iSrcY;
psWrkStruct->dfLastDeltaY = dfDeltaY;
}
}
GPtrDiff_t iRowOffset =
iSrcOffset + static_cast<GPtrDiff_t>(jMin - 1) * nSrcXSize + iMin;
// If we have no density information, we can simply compute the
// accumulated weight.
if (padfRowDensity == nullptr)
{
double dfRowAccWeight = 0.0;
for (int i = iMin; i <= iMax; ++i)
{
dfRowAccWeight += padfWeightsX[i - poWK->nFiltInitX];
}
double dfColAccWeight = 0.0;
for (int j = jMin; j <= jMax; ++j)
{
dfColAccWeight += padfWeightsY[j - poWK->nFiltInitY];
}
dfAccumulatorWeight = dfRowAccWeight * dfColAccWeight;
}
const bool bIsNonComplex = !GDALDataTypeIsComplex(poWK->eWorkingDataType);
// Loop over pixel rows in the kernel.
int nCountValid = 0;
for (int j = jMin; j <= jMax; ++j)
{
iRowOffset += nSrcXSize;
// Get pixel values.
// We can potentially read extra elements after the "normal" end of the
// source arrays, but the contract of papabySrcImage[iBand],
// papanBandSrcValid[iBand], panUnifiedSrcValid and pafUnifiedSrcDensity
// is to have WARP_EXTRA_ELTS reserved at their end.
if (!GWKGetPixelRow(poWK, iBand, iRowOffset, (iMax - iMin + 2) / 2,
padfRowDensity, padfRowReal, padfRowImag))
continue;
const double dfWeight1 = padfWeightsY[j - poWK->nFiltInitY];
// Iterate over pixels in row.
if (padfRowDensity != nullptr)
{
for (int i = iMin; i <= iMax; ++i)
{
// Skip sampling if pixel has zero density.
if (padfRowDensity[i - iMin] < SRC_DENSITY_THRESHOLD)
continue;
nCountValid++;
// Use a cached set of weights for this row.
const double dfWeight2 =
dfWeight1 * padfWeightsX[i - poWK->nFiltInitX];
// Accumulate!
dfAccumulatorReal += padfRowReal[i - iMin] * dfWeight2;
dfAccumulatorImag += padfRowImag[i - iMin] * dfWeight2;
dfAccumulatorDensity += padfRowDensity[i - iMin] * dfWeight2;
dfAccumulatorWeight += dfWeight2;
}
}
else if (bIsNonComplex)
{
double dfRowAccReal = 0.0;
for (int i = iMin; i <= iMax; ++i)
{
const double dfWeight2 = padfWeightsX[i - poWK->nFiltInitX];
// Accumulate!
dfRowAccReal += padfRowReal[i - iMin] * dfWeight2;
}
dfAccumulatorReal += dfRowAccReal * dfWeight1;
}
else
{
double dfRowAccReal = 0.0;
double dfRowAccImag = 0.0;
for (int i = iMin; i <= iMax; ++i)
{
const double dfWeight2 = padfWeightsX[i - poWK->nFiltInitX];
// Accumulate!
dfRowAccReal += padfRowReal[i - iMin] * dfWeight2;
dfRowAccImag += padfRowImag[i - iMin] * dfWeight2;
}
dfAccumulatorReal += dfRowAccReal * dfWeight1;
dfAccumulatorImag += dfRowAccImag * dfWeight1;
}
}
if (dfAccumulatorWeight < 0.000001 ||
(padfRowDensity != nullptr &&
(dfAccumulatorDensity < 0.000001 ||
nCountValid < (jMax - jMin + 1) * (iMax - iMin + 1) / 2)))
{
*pdfDensity = 0.0;
return false;
}
// Calculate the output taking into account weighting.
if (dfAccumulatorWeight < 0.99999 || dfAccumulatorWeight > 1.00001)
{
const double dfInvAcc = 1.0 / dfAccumulatorWeight;
*pdfReal = dfAccumulatorReal * dfInvAcc;
*pdfImag = dfAccumulatorImag * dfInvAcc;
if (padfRowDensity != nullptr)
*pdfDensity = dfAccumulatorDensity * dfInvAcc;
else
*pdfDensity = 1.0;
}
else
{
*pdfReal = dfAccumulatorReal;
*pdfImag = dfAccumulatorImag;
if (padfRowDensity != nullptr)
*pdfDensity = dfAccumulatorDensity;
else
*pdfDensity = 1.0;
}
return true;
}
/************************************************************************/
/* GWKResampleNoMasksT() */
/************************************************************************/
template <class T>
static bool GWKResampleNoMasksT(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, T *pValue,
double *padfWeight)
{
// Commonly used; save locally.
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
const int iSrcX = static_cast<int>(floor(dfSrcX - 0.5));
const int iSrcY = static_cast<int>(floor(dfSrcY - 0.5));
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
const int nXRadius = poWK->nXRadius;
const int nYRadius = poWK->nYRadius;
// Politely refuse to process invalid coordinates or obscenely small image.
if (iSrcX >= nSrcXSize || iSrcY >= nSrcYSize || nXRadius > nSrcXSize ||
nYRadius > nSrcYSize)
return GWKBilinearResampleNoMasks4SampleT(poWK, iBand, dfSrcX, dfSrcY,
pValue);
T *pSrcBand = reinterpret_cast<T *>(poWK->papabySrcImage[iBand]);
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
const FilterFuncType pfnGetWeight = apfGWKFilter[poWK->eResample];
CPLAssert(pfnGetWeight);
const FilterFunc4ValuesType pfnGetWeight4Values =
apfGWKFilter4Values[poWK->eResample];
CPLAssert(pfnGetWeight4Values);
const double dfXScale = std::min(poWK->dfXScale, 1.0);
const double dfYScale = std::min(poWK->dfYScale, 1.0);
// Loop over all rows in the kernel.
double dfAccumulatorWeightHorizontal = 0.0;
double dfAccumulatorWeightVertical = 0.0;
int iMin = 1 - nXRadius;
if (iSrcX + iMin < 0)
iMin = -iSrcX;
int iMax = nXRadius;
if (iSrcX + iMax >= nSrcXSize - 1)
iMax = nSrcXSize - 1 - iSrcX;
int i = iMin; // Used after for.
int iC = 0; // Used after for.
for (; i + 2 < iMax; i += 4, iC += 4)
{
padfWeight[iC] = (i - dfDeltaX) * dfXScale;
padfWeight[iC + 1] = padfWeight[iC] + dfXScale;
padfWeight[iC + 2] = padfWeight[iC + 1] + dfXScale;
padfWeight[iC + 3] = padfWeight[iC + 2] + dfXScale;
dfAccumulatorWeightHorizontal += pfnGetWeight4Values(padfWeight + iC);
}
for (; i <= iMax; ++i, ++iC)
{
const double dfWeight = pfnGetWeight((i - dfDeltaX) * dfXScale);
padfWeight[iC] = dfWeight;
dfAccumulatorWeightHorizontal += dfWeight;
}
int j = 1 - nYRadius;
if (iSrcY + j < 0)
j = -iSrcY;
int jMax = nYRadius;
if (iSrcY + jMax >= nSrcYSize - 1)
jMax = nSrcYSize - 1 - iSrcY;
double dfAccumulator = 0.0;
for (; j <= jMax; ++j)
{
const GPtrDiff_t iSampJ =
iSrcOffset + static_cast<GPtrDiff_t>(j) * nSrcXSize;
// Loop over all pixels in the row.
double dfAccumulatorLocal = 0.0;
double dfAccumulatorLocal2 = 0.0;
iC = 0;
i = iMin;
// Process by chunk of 4 cols.
for (; i + 2 < iMax; i += 4, iC += 4)
{
// Retrieve the pixel & accumulate.
dfAccumulatorLocal += pSrcBand[i + iSampJ] * padfWeight[iC];
dfAccumulatorLocal += pSrcBand[i + 1 + iSampJ] * padfWeight[iC + 1];
dfAccumulatorLocal2 +=
pSrcBand[i + 2 + iSampJ] * padfWeight[iC + 2];
dfAccumulatorLocal2 +=
pSrcBand[i + 3 + iSampJ] * padfWeight[iC + 3];
}
dfAccumulatorLocal += dfAccumulatorLocal2;
if (i < iMax)
{
dfAccumulatorLocal += pSrcBand[i + iSampJ] * padfWeight[iC];
dfAccumulatorLocal += pSrcBand[i + 1 + iSampJ] * padfWeight[iC + 1];
i += 2;
iC += 2;
}
if (i == iMax)
{
dfAccumulatorLocal += pSrcBand[i + iSampJ] * padfWeight[iC];
}
// Calculate the Y weight.
const double dfWeight = pfnGetWeight((j - dfDeltaY) * dfYScale);
dfAccumulator += dfWeight * dfAccumulatorLocal;
dfAccumulatorWeightVertical += dfWeight;
}
const double dfAccumulatorWeight =
dfAccumulatorWeightHorizontal * dfAccumulatorWeightVertical;
*pValue = GWKClampValueT<T>(dfAccumulator / dfAccumulatorWeight);
return true;
}
/* We restrict to 64bit processors because they are guaranteed to have SSE2 */
/* Could possibly be used too on 32bit, but we would need to check at runtime */
#if defined(__x86_64) || defined(_M_X64)
/************************************************************************/
/* GWKResampleNoMasks_SSE2_T() */
/************************************************************************/
template <class T>
static bool GWKResampleNoMasks_SSE2_T(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, T *pValue,
double *padfWeight)
{
// Commonly used; save locally.
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
const int iSrcX = static_cast<int>(floor(dfSrcX - 0.5));
const int iSrcY = static_cast<int>(floor(dfSrcY - 0.5));
const GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
const int nXRadius = poWK->nXRadius;
const int nYRadius = poWK->nYRadius;
// Politely refuse to process invalid coordinates or obscenely small image.
if (iSrcX >= nSrcXSize || iSrcY >= nSrcYSize || nXRadius > nSrcXSize ||
nYRadius > nSrcYSize)
return GWKBilinearResampleNoMasks4SampleT(poWK, iBand, dfSrcX, dfSrcY,
pValue);
const T *pSrcBand =
reinterpret_cast<const T *>(poWK->papabySrcImage[iBand]);
const FilterFuncType pfnGetWeight = apfGWKFilter[poWK->eResample];
CPLAssert(pfnGetWeight);
const FilterFunc4ValuesType pfnGetWeight4Values =
apfGWKFilter4Values[poWK->eResample];
CPLAssert(pfnGetWeight4Values);
const double dfDeltaX = dfSrcX - 0.5 - iSrcX;
const double dfDeltaY = dfSrcY - 0.5 - iSrcY;
const double dfXScale = std::min(poWK->dfXScale, 1.0);
const double dfYScale = std::min(poWK->dfYScale, 1.0);
// Loop over all rows in the kernel.
double dfAccumulatorWeightHorizontal = 0.0;
double dfAccumulatorWeightVertical = 0.0;
double dfAccumulator = 0.0;
int iMin = 1 - nXRadius;
if (iSrcX + iMin < 0)
iMin = -iSrcX;
int iMax = nXRadius;
if (iSrcX + iMax >= nSrcXSize - 1)
iMax = nSrcXSize - 1 - iSrcX;
int i, iC;
for (iC = 0, i = iMin; i + 2 < iMax; i += 4, iC += 4)
{
padfWeight[iC] = (i - dfDeltaX) * dfXScale;
padfWeight[iC + 1] = padfWeight[iC] + dfXScale;
padfWeight[iC + 2] = padfWeight[iC + 1] + dfXScale;
padfWeight[iC + 3] = padfWeight[iC + 2] + dfXScale;
dfAccumulatorWeightHorizontal += pfnGetWeight4Values(padfWeight + iC);
}
for (; i <= iMax; ++i, ++iC)
{
double dfWeight = pfnGetWeight((i - dfDeltaX) * dfXScale);
padfWeight[iC] = dfWeight;
dfAccumulatorWeightHorizontal += dfWeight;
}
int j = 1 - nYRadius;
if (iSrcY + j < 0)
j = -iSrcY;
int jMax = nYRadius;
if (iSrcY + jMax >= nSrcYSize - 1)
jMax = nSrcYSize - 1 - iSrcY;
// Process by chunk of 4 rows.
for (; j + 2 < jMax; j += 4)
{
const GPtrDiff_t iSampJ =
iSrcOffset + static_cast<GPtrDiff_t>(j) * nSrcXSize;
// Loop over all pixels in the row.
iC = 0;
i = iMin;
// Process by chunk of 4 cols.
XMMReg4Double v_acc_1 = XMMReg4Double::Zero();
XMMReg4Double v_acc_2 = XMMReg4Double::Zero();
XMMReg4Double v_acc_3 = XMMReg4Double::Zero();
XMMReg4Double v_acc_4 = XMMReg4Double::Zero();
for (; i + 2 < iMax; i += 4, iC += 4)
{
// Retrieve the pixel & accumulate.
XMMReg4Double v_pixels_1 =
XMMReg4Double::Load4Val(pSrcBand + i + iSampJ);
XMMReg4Double v_pixels_2 =
XMMReg4Double::Load4Val(pSrcBand + i + iSampJ + nSrcXSize);
XMMReg4Double v_pixels_3 =
XMMReg4Double::Load4Val(pSrcBand + i + iSampJ + 2 * nSrcXSize);
XMMReg4Double v_pixels_4 =
XMMReg4Double::Load4Val(pSrcBand + i + iSampJ + 3 * nSrcXSize);
XMMReg4Double v_padfWeight =
XMMReg4Double::Load4Val(padfWeight + iC);
v_acc_1 += v_pixels_1 * v_padfWeight;
v_acc_2 += v_pixels_2 * v_padfWeight;
v_acc_3 += v_pixels_3 * v_padfWeight;
v_acc_4 += v_pixels_4 * v_padfWeight;
}
if (i < iMax)
{
XMMReg2Double v_pixels_1 =
XMMReg2Double::Load2Val(pSrcBand + i + iSampJ);
XMMReg2Double v_pixels_2 =
XMMReg2Double::Load2Val(pSrcBand + i + iSampJ + nSrcXSize);
XMMReg2Double v_pixels_3 =
XMMReg2Double::Load2Val(pSrcBand + i + iSampJ + 2 * nSrcXSize);
XMMReg2Double v_pixels_4 =
XMMReg2Double::Load2Val(pSrcBand + i + iSampJ + 3 * nSrcXSize);
XMMReg2Double v_padfWeight =
XMMReg2Double::Load2Val(padfWeight + iC);
v_acc_1.AddToLow(v_pixels_1 * v_padfWeight);
v_acc_2.AddToLow(v_pixels_2 * v_padfWeight);
v_acc_3.AddToLow(v_pixels_3 * v_padfWeight);
v_acc_4.AddToLow(v_pixels_4 * v_padfWeight);
i += 2;
iC += 2;
}
double dfAccumulatorLocal_1 = v_acc_1.GetHorizSum();
double dfAccumulatorLocal_2 = v_acc_2.GetHorizSum();
double dfAccumulatorLocal_3 = v_acc_3.GetHorizSum();
double dfAccumulatorLocal_4 = v_acc_4.GetHorizSum();
if (i == iMax)
{
dfAccumulatorLocal_1 +=
static_cast<double>(pSrcBand[i + iSampJ]) * padfWeight[iC];
dfAccumulatorLocal_2 +=
static_cast<double>(pSrcBand[i + iSampJ + nSrcXSize]) *
padfWeight[iC];
dfAccumulatorLocal_3 +=
static_cast<double>(pSrcBand[i + iSampJ + 2 * nSrcXSize]) *
padfWeight[iC];
dfAccumulatorLocal_4 +=
static_cast<double>(pSrcBand[i + iSampJ + 3 * nSrcXSize]) *
padfWeight[iC];
}
// Calculate the Y weight.
const double dfWeight0 = (j - dfDeltaY) * dfYScale;
const double dfWeight1 = dfWeight0 + dfYScale;
const double dfWeight2 = dfWeight1 + dfYScale;
const double dfWeight3 = dfWeight2 + dfYScale;
double adfWeight[4] = {dfWeight0, dfWeight1, dfWeight2, dfWeight3};
dfAccumulatorWeightVertical += pfnGetWeight4Values(adfWeight);
dfAccumulator += adfWeight[0] * dfAccumulatorLocal_1;
dfAccumulator += adfWeight[1] * dfAccumulatorLocal_2;
dfAccumulator += adfWeight[2] * dfAccumulatorLocal_3;
dfAccumulator += adfWeight[3] * dfAccumulatorLocal_4;
}
for (; j <= jMax; ++j)
{
const GPtrDiff_t iSampJ =
iSrcOffset + static_cast<GPtrDiff_t>(j) * nSrcXSize;
// Loop over all pixels in the row.
iC = 0;
i = iMin;
// Process by chunk of 4 cols.
XMMReg4Double v_acc = XMMReg4Double::Zero();
for (; i + 2 < iMax; i += 4, iC += 4)
{
// Retrieve the pixel & accumulate.
XMMReg4Double v_pixels =
XMMReg4Double::Load4Val(pSrcBand + i + iSampJ);
XMMReg4Double v_padfWeight =
XMMReg4Double::Load4Val(padfWeight + iC);
v_acc += v_pixels * v_padfWeight;
}
double dfAccumulatorLocal = v_acc.GetHorizSum();
if (i < iMax)
{
dfAccumulatorLocal += pSrcBand[i + iSampJ] * padfWeight[iC];
dfAccumulatorLocal += pSrcBand[i + 1 + iSampJ] * padfWeight[iC + 1];
i += 2;
iC += 2;
}
if (i == iMax)
{
dfAccumulatorLocal +=
static_cast<double>(pSrcBand[i + iSampJ]) * padfWeight[iC];
}
// Calculate the Y weight.
double dfWeight = pfnGetWeight((j - dfDeltaY) * dfYScale);
dfAccumulator += dfWeight * dfAccumulatorLocal;
dfAccumulatorWeightVertical += dfWeight;
}
const double dfAccumulatorWeight =
dfAccumulatorWeightHorizontal * dfAccumulatorWeightVertical;
*pValue = GWKClampValueT<T>(dfAccumulator / dfAccumulatorWeight);
return true;
}
/************************************************************************/
/* GWKResampleNoMasksT<GByte>() */
/************************************************************************/
template <>
bool GWKResampleNoMasksT<GByte>(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, GByte *pValue,
double *padfWeight)
{
return GWKResampleNoMasks_SSE2_T(poWK, iBand, dfSrcX, dfSrcY, pValue,
padfWeight);
}
/************************************************************************/
/* GWKResampleNoMasksT<GInt16>() */
/************************************************************************/
template <>
bool GWKResampleNoMasksT<GInt16>(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, GInt16 *pValue,
double *padfWeight)
{
return GWKResampleNoMasks_SSE2_T(poWK, iBand, dfSrcX, dfSrcY, pValue,
padfWeight);
}
/************************************************************************/
/* GWKResampleNoMasksT<GUInt16>() */
/************************************************************************/
template <>
bool GWKResampleNoMasksT<GUInt16>(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, GUInt16 *pValue,
double *padfWeight)
{
return GWKResampleNoMasks_SSE2_T(poWK, iBand, dfSrcX, dfSrcY, pValue,
padfWeight);
}
/************************************************************************/
/* GWKResampleNoMasksT<float>() */
/************************************************************************/
template <>
bool GWKResampleNoMasksT<float>(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, float *pValue,
double *padfWeight)
{
return GWKResampleNoMasks_SSE2_T(poWK, iBand, dfSrcX, dfSrcY, pValue,
padfWeight);
}
#ifdef INSTANTIATE_FLOAT64_SSE2_IMPL
/************************************************************************/
/* GWKResampleNoMasksT<double>() */
/************************************************************************/
template <>
bool GWKResampleNoMasksT<double>(const GDALWarpKernel *poWK, int iBand,
double dfSrcX, double dfSrcY, double *pValue,
double *padfWeight)
{
return GWKResampleNoMasks_SSE2_T(poWK, iBand, dfSrcX, dfSrcY, pValue,
padfWeight);
}
#endif /* INSTANTIATE_FLOAT64_SSE2_IMPL */
#endif /* defined(__x86_64) || defined(_M_X64) */
/************************************************************************/
/* GWKRoundSourceCoordinates() */
/************************************************************************/
static void GWKRoundSourceCoordinates(
int nDstXSize, double *padfX, double *padfY, double *padfZ, int *pabSuccess,
double dfSrcCoordPrecision, double dfErrorThreshold,
GDALTransformerFunc pfnTransformer, void *pTransformerArg, double dfDstXOff,
double dfDstY)
{
double dfPct = 0.8;
if (dfErrorThreshold > 0 && dfSrcCoordPrecision / dfErrorThreshold >= 10.0)
{
dfPct = 1.0 - 2 * 1.0 / (dfSrcCoordPrecision / dfErrorThreshold);
}
const double dfExactTransformThreshold = 0.5 * dfPct * dfSrcCoordPrecision;
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
const double dfXBefore = padfX[iDstX];
const double dfYBefore = padfY[iDstX];
padfX[iDstX] = floor(padfX[iDstX] / dfSrcCoordPrecision + 0.5) *
dfSrcCoordPrecision;
padfY[iDstX] = floor(padfY[iDstX] / dfSrcCoordPrecision + 0.5) *
dfSrcCoordPrecision;
// If we are in an uncertainty zone, go to non-approximated
// transformation.
// Due to the 80% of half-precision threshold, dfSrcCoordPrecision must
// be at least 10 times greater than the approximation error.
if (fabs(dfXBefore - padfX[iDstX]) > dfExactTransformThreshold ||
fabs(dfYBefore - padfY[iDstX]) > dfExactTransformThreshold)
{
padfX[iDstX] = iDstX + dfDstXOff;
padfY[iDstX] = dfDstY;
padfZ[iDstX] = 0.0;
pfnTransformer(pTransformerArg, TRUE, 1, padfX + iDstX,
padfY + iDstX, padfZ + iDstX, pabSuccess + iDstX);
padfX[iDstX] = floor(padfX[iDstX] / dfSrcCoordPrecision + 0.5) *
dfSrcCoordPrecision;
padfY[iDstX] = floor(padfY[iDstX] / dfSrcCoordPrecision + 0.5) *
dfSrcCoordPrecision;
}
}
}
/************************************************************************/
/* GWKOpenCLCase() */
/* */
/* This is identical to GWKGeneralCase(), but functions via */
/* OpenCL. This means we have vector optimization (SSE) and/or */
/* GPU optimization depending on our prefs. The code itself is */
/* general and not optimized, but by defining constants we can */
/* make some pretty darn good code on the fly. */
/************************************************************************/
#if defined(HAVE_OPENCL)
static CPLErr GWKOpenCLCase(GDALWarpKernel *poWK)
{
const int nDstXSize = poWK->nDstXSize;
const int nDstYSize = poWK->nDstYSize;
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
const int nDstXOff = poWK->nDstXOff;
const int nDstYOff = poWK->nDstYOff;
const int nSrcXOff = poWK->nSrcXOff;
const int nSrcYOff = poWK->nSrcYOff;
bool bUseImag = false;
cl_channel_type imageFormat;
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
imageFormat = CL_UNORM_INT8;
break;
case GDT_UInt16:
imageFormat = CL_UNORM_INT16;
break;
case GDT_CInt16:
bUseImag = true;
CPL_FALLTHROUGH
case GDT_Int16:
imageFormat = CL_SNORM_INT16;
break;
case GDT_CFloat32:
bUseImag = true;
CPL_FALLTHROUGH
case GDT_Float32:
imageFormat = CL_FLOAT;
break;
default:
// No support for higher precision formats.
CPLDebug("OpenCL", "Unsupported resampling OpenCL data type %d.",
static_cast<int>(poWK->eWorkingDataType));
return CE_Warning;
}
OCLResampAlg resampAlg;
switch (poWK->eResample)
{
case GRA_Bilinear:
resampAlg = OCL_Bilinear;
break;
case GRA_Cubic:
resampAlg = OCL_Cubic;
break;
case GRA_CubicSpline:
resampAlg = OCL_CubicSpline;
break;
case GRA_Lanczos:
resampAlg = OCL_Lanczos;
break;
default:
// No support for higher precision formats.
CPLDebug("OpenCL",
"Unsupported resampling OpenCL resampling alg %d.",
static_cast<int>(poWK->eResample));
return CE_Warning;
}
struct oclWarper *warper = nullptr;
cl_int err;
CPLErr eErr = CE_None;
// TODO(schwehr): Fix indenting.
try
{
// Using a factor of 2 or 4 seems to have much less rounding error
// than 3 on the GPU.
// Then the rounding error can cause strange artifacts under the
// right conditions.
warper = GDALWarpKernelOpenCL_createEnv(
nSrcXSize, nSrcYSize, nDstXSize, nDstYSize, imageFormat,
poWK->nBands, 4, bUseImag, poWK->papanBandSrcValid != nullptr,
poWK->pafDstDensity, poWK->padfDstNoDataReal, resampAlg, &err);
if (err != CL_SUCCESS || warper == nullptr)
{
eErr = CE_Warning;
if (warper != nullptr)
throw eErr;
return eErr;
}
CPLDebug("GDAL",
"GDALWarpKernel()::GWKOpenCLCase() "
"Src=%d,%d,%dx%d Dst=%d,%d,%dx%d",
nSrcXOff, nSrcYOff, nSrcXSize, nSrcYSize, nDstXOff, nDstYOff,
nDstXSize, nDstYSize);
if (!poWK->pfnProgress(poWK->dfProgressBase, "", poWK->pProgress))
{
CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated");
eErr = CE_Failure;
throw eErr;
}
/* ====================================================================
*/
/* Loop over bands. */
/* ====================================================================
*/
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
if (poWK->papanBandSrcValid != nullptr &&
poWK->papanBandSrcValid[iBand] != nullptr)
{
GDALWarpKernelOpenCL_setSrcValid(
warper,
reinterpret_cast<int *>(poWK->papanBandSrcValid[iBand]),
iBand);
if (err != CL_SUCCESS)
{
CPLError(
CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
eErr = CE_Failure;
throw eErr;
}
}
err = GDALWarpKernelOpenCL_setSrcImg(
warper, poWK->papabySrcImage[iBand], iBand);
if (err != CL_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
eErr = CE_Failure;
throw eErr;
}
err = GDALWarpKernelOpenCL_setDstImg(
warper, poWK->papabyDstImage[iBand], iBand);
if (err != CL_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
eErr = CE_Failure;
throw eErr;
}
}
/* --------------------------------------------------------------------
*/
/* Allocate x,y,z coordinate arrays for transformation ... one */
/* scanlines worth of positions. */
/* --------------------------------------------------------------------
*/
// For x, 2 *, because we cache the precomputed values at the end.
double *padfX =
static_cast<double *>(CPLMalloc(2 * sizeof(double) * nDstXSize));
double *padfY =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
int *pabSuccess =
static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
const double dfSrcCoordPrecision = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "SRC_COORD_PRECISION", "0"));
const double dfErrorThreshold = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "ERROR_THRESHOLD", "0"));
// Precompute values.
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfX[nDstXSize + iDstX] = iDstX + 0.5 + poWK->nDstXOff;
/* ====================================================================
*/
/* Loop over output lines. */
/* ====================================================================
*/
for (int iDstY = 0; iDstY < nDstYSize && eErr == CE_None; ++iDstY)
{
/* ----------------------------------------------------------------
*/
/* Setup points to transform to source image space. */
/* ----------------------------------------------------------------
*/
memcpy(padfX, padfX + nDstXSize, sizeof(double) * nDstXSize);
const double dfYConst = iDstY + 0.5 + poWK->nDstYOff;
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfY[iDstX] = dfYConst;
memset(padfZ, 0, sizeof(double) * nDstXSize);
/* ----------------------------------------------------------------
*/
/* Transform the points from destination pixel/line
* coordinates*/
/* to source pixel/line coordinates. */
/* ----------------------------------------------------------------
*/
poWK->pfnTransformer(poWK->pTransformerArg, TRUE, nDstXSize, padfX,
padfY, padfZ, pabSuccess);
if (dfSrcCoordPrecision > 0.0)
{
GWKRoundSourceCoordinates(
nDstXSize, padfX, padfY, padfZ, pabSuccess,
dfSrcCoordPrecision, dfErrorThreshold, poWK->pfnTransformer,
poWK->pTransformerArg, 0.5 + nDstXOff,
iDstY + 0.5 + nDstYOff);
}
err = GDALWarpKernelOpenCL_setCoordRow(
warper, padfX, padfY, nSrcXOff, nSrcYOff, pabSuccess, iDstY);
if (err != CL_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
eErr = CE_Failure;
break;
}
// Update the valid & density masks because we don't do so in the
// kernel.
for (int iDstX = 0; iDstX < nDstXSize && eErr == CE_None; iDstX++)
{
const double dfX = padfX[iDstX];
const double dfY = padfY[iDstX];
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
// See GWKGeneralCase() for appropriate commenting.
if (!pabSuccess[iDstX] || dfX < nSrcXOff || dfY < nSrcYOff)
continue;
int iSrcX = static_cast<int>(dfX) - nSrcXOff;
int iSrcY = static_cast<int>(dfY) - nSrcYOff;
if (iSrcX < 0 || iSrcX >= nSrcXSize || iSrcY < 0 ||
iSrcY >= nSrcYSize)
continue;
GPtrDiff_t iSrcOffset =
iSrcX + static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
double dfDensity = 1.0;
if (poWK->pafUnifiedSrcDensity != nullptr && iSrcX >= 0 &&
iSrcY >= 0 && iSrcX < nSrcXSize && iSrcY < nSrcYSize)
dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
GWKOverlayDensity(poWK, iDstOffset, dfDensity);
// Because this is on the bit-wise level, it can't be done well
// in OpenCL.
if (poWK->panDstValid != nullptr)
poWK->panDstValid[iDstOffset >> 5] |=
0x01 << (iDstOffset & 0x1f);
}
}
CPLFree(padfX);
CPLFree(padfY);
CPLFree(padfZ);
CPLFree(pabSuccess);
if (eErr != CE_None)
throw eErr;
err = GDALWarpKernelOpenCL_runResamp(
warper, poWK->pafUnifiedSrcDensity, poWK->panUnifiedSrcValid,
poWK->pafDstDensity, poWK->panDstValid, poWK->dfXScale,
poWK->dfYScale, poWK->dfXFilter, poWK->dfYFilter, poWK->nXRadius,
poWK->nYRadius, poWK->nFiltInitX, poWK->nFiltInitY);
if (err != CL_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
eErr = CE_Failure;
throw eErr;
}
/* ====================================================================
*/
/* Loop over output lines. */
/* ====================================================================
*/
for (int iDstY = 0; iDstY < nDstYSize && eErr == CE_None; iDstY++)
{
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
void *rowReal = nullptr;
void *rowImag = nullptr;
GByte *pabyDst = poWK->papabyDstImage[iBand];
err = GDALWarpKernelOpenCL_getRow(warper, &rowReal, &rowImag,
iDstY, iBand);
if (err != CL_SUCCESS)
{
CPLError(
CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
eErr = CE_Failure;
throw eErr;
}
// Copy the data from the warper to GDAL's memory.
switch (poWK->eWorkingDataType)
{
case GDT_Byte:
memcpy(&(pabyDst[iDstY * nDstXSize]), rowReal,
sizeof(GByte) * nDstXSize);
break;
case GDT_Int16:
memcpy(&(reinterpret_cast<GInt16 *>(
pabyDst)[iDstY * nDstXSize]),
rowReal, sizeof(GInt16) * nDstXSize);
break;
case GDT_UInt16:
memcpy(&(reinterpret_cast<GUInt16 *>(
pabyDst)[iDstY * nDstXSize]),
rowReal, sizeof(GUInt16) * nDstXSize);
break;
case GDT_Float32:
memcpy(&(reinterpret_cast<float *>(
pabyDst)[iDstY * nDstXSize]),
rowReal, sizeof(float) * nDstXSize);
break;
case GDT_CInt16:
{
GInt16 *pabyDstI16 = &(reinterpret_cast<GInt16 *>(
pabyDst)[iDstY * nDstXSize]);
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
pabyDstI16[iDstX * 2] =
static_cast<GInt16 *>(rowReal)[iDstX];
pabyDstI16[iDstX * 2 + 1] =
static_cast<GInt16 *>(rowImag)[iDstX];
}
}
break;
case GDT_CFloat32:
{
float *pabyDstF32 = &(reinterpret_cast<float *>(
pabyDst)[iDstY * nDstXSize]);
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
pabyDstF32[iDstX * 2] =
static_cast<float *>(rowReal)[iDstX];
pabyDstF32[iDstX * 2 + 1] =
static_cast<float *>(rowImag)[iDstX];
}
}
break;
default:
// No support for higher precision formats.
CPLError(CE_Failure, CPLE_AppDefined,
"Unsupported resampling OpenCL data type %d.",
static_cast<int>(poWK->eWorkingDataType));
eErr = CE_Failure;
throw eErr;
}
}
}
}
catch (const CPLErr &)
{
}
if ((err = GDALWarpKernelOpenCL_deleteEnv(warper)) != CL_SUCCESS)
{
CPLError(CE_Failure, CPLE_AppDefined,
"OpenCL routines reported failure (%d) on line %d.",
static_cast<int>(err), __LINE__);
return CE_Failure;
}
return eErr;
}
#endif /* defined(HAVE_OPENCL) */
/************************************************************************/
/* GWKCheckAndComputeSrcOffsets() */
/************************************************************************/
static CPL_INLINE bool
GWKCheckAndComputeSrcOffsets(GWKJobStruct *psJob, int *_pabSuccess, int _iDstX,
int _iDstY, double *_padfX, double *_padfY,
int _nSrcXSize, int _nSrcYSize,
GPtrDiff_t &iSrcOffset)
{
const GDALWarpKernel *_poWK = psJob->poWK;
for (int iTry = 0; iTry < 2; ++iTry)
{
if (iTry == 1)
{
// If the source coordinate is slightly outside of the source raster
// retry to transform it alone, so that the exact coordinate
// transformer is used.
_padfX[_iDstX] = _iDstX + 0.5 + _poWK->nDstXOff;
_padfY[_iDstX] = _iDstY + 0.5 + _poWK->nDstYOff;
double dfZ = 0;
_poWK->pfnTransformer(psJob->pTransformerArg, TRUE, 1,
_padfX + _iDstX, _padfY + _iDstX, &dfZ,
_pabSuccess + _iDstX);
}
if (!_pabSuccess[_iDstX])
return false;
// If this happens this is likely the symptom of a bug somewhere.
if (CPLIsNan(_padfX[_iDstX]) || CPLIsNan(_padfY[_iDstX]))
{
static bool bNanCoordFound = false;
if (!bNanCoordFound)
{
CPLDebug("WARP",
"GWKCheckAndComputeSrcOffsets(): "
"NaN coordinate found on point %d.",
_iDstX);
bNanCoordFound = true;
}
return false;
}
/* --------------------------------------------------------------------
*/
/* Figure out what pixel we want in our source raster, and skip */
/* further processing if it is well off the source image. */
/* --------------------------------------------------------------------
*/
/* We test against the value before casting to avoid the */
/* problem of asymmetric truncation effects around zero. That is */
/* -0.5 will be 0 when cast to an int. */
if (_padfX[_iDstX] < _poWK->nSrcXOff)
{
// If the source coordinate is slightly outside of the source raster
// retry to transform it alone, so that the exact coordinate
// transformer is used.
if (iTry == 0 && _padfX[_iDstX] > _poWK->nSrcXOff - 1)
continue;
return false;
}
if (_padfY[_iDstX] < _poWK->nSrcYOff)
{
// If the source coordinate is slightly outside of the source raster
// retry to transform it alone, so that the exact coordinate
// transformer is used.
if (iTry == 0 && _padfY[_iDstX] > _poWK->nSrcYOff - 1)
continue;
return false;
}
// Check for potential overflow when casting from float to int, (if
// operating outside natural projection area, padfX/Y can be a very huge
// positive number before doing the actual conversion), as such cast is
// undefined behavior that can trigger exception with some compilers
// (see #6753)
if (_padfX[_iDstX] + 1e-10 > _nSrcXSize + _poWK->nSrcXOff)
{
// If the source coordinate is slightly outside of the source raster
// retry to transform it alone, so that the exact coordinate
// transformer is used.
if (iTry == 0 && _padfX[_iDstX] < _nSrcXSize + _poWK->nSrcXOff + 1)
continue;
return false;
}
if (_padfY[_iDstX] + 1e-10 > _nSrcYSize + _poWK->nSrcYOff)
{
// If the source coordinate is slightly outside of the source raster
// retry to transform it alone, so that the exact coordinate
// transformer is used.
if (iTry == 0 && _padfY[_iDstX] < _nSrcYSize + _poWK->nSrcYOff + 1)
continue;
return false;
}
break;
}
int iSrcX = static_cast<int>(_padfX[_iDstX] + 1.0e-10) - _poWK->nSrcXOff;
int iSrcY = static_cast<int>(_padfY[_iDstX] + 1.0e-10) - _poWK->nSrcYOff;
if (iSrcX == _nSrcXSize)
iSrcX--;
if (iSrcY == _nSrcYSize)
iSrcY--;
// Those checks should normally be OK given the previous ones.
CPLAssert(iSrcX >= 0);
CPLAssert(iSrcY >= 0);
CPLAssert(iSrcX < _nSrcXSize);
CPLAssert(iSrcY < _nSrcYSize);
iSrcOffset = iSrcX + static_cast<GPtrDiff_t>(iSrcY) * _nSrcXSize;
return true;
}
/************************************************************************/
/* GWKGeneralCase() */
/* */
/* This is the most general case. It attempts to handle all */
/* possible features with relatively little concern for */
/* efficiency. */
/************************************************************************/
static void GWKGeneralCaseThread(void *pData)
{
GWKJobStruct *psJob = reinterpret_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
const int iYMin = psJob->iYMin;
const int iYMax = psJob->iYMax;
int nDstXSize = poWK->nDstXSize;
int nSrcXSize = poWK->nSrcXSize;
int nSrcYSize = poWK->nSrcYSize;
/* -------------------------------------------------------------------- */
/* Allocate x,y,z coordinate arrays for transformation ... one */
/* scanlines worth of positions. */
/* -------------------------------------------------------------------- */
// For x, 2 *, because we cache the precomputed values at the end.
double *padfX =
static_cast<double *>(CPLMalloc(2 * sizeof(double) * nDstXSize));
double *padfY =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
int *pabSuccess = static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
const bool bUse4SamplesFormula =
poWK->dfXScale >= 0.95 && poWK->dfYScale >= 0.95;
GWKResampleWrkStruct *psWrkStruct = nullptr;
if (poWK->eResample != GRA_NearestNeighbour)
{
psWrkStruct = GWKResampleCreateWrkStruct(poWK);
}
const double dfSrcCoordPrecision = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "SRC_COORD_PRECISION", "0"));
const double dfErrorThreshold = CPLAtof(
CSLFetchNameValueDef(poWK->papszWarpOptions, "ERROR_THRESHOLD", "0"));
// Precompute values.
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfX[nDstXSize + iDstX] = iDstX + 0.5 + poWK->nDstXOff;
/* ==================================================================== */
/* Loop over output lines. */
/* ==================================================================== */
for (int iDstY = iYMin; iDstY < iYMax; iDstY++)
{
/* --------------------------------------------------------------------
*/
/* Setup points to transform to source image space. */
/* --------------------------------------------------------------------
*/
memcpy(padfX, padfX + nDstXSize, sizeof(double) * nDstXSize);
const double dfY = iDstY + 0.5 + poWK->nDstYOff;
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfY[iDstX] = dfY;
memset(padfZ, 0, sizeof(double) * nDstXSize);
/* --------------------------------------------------------------------
*/
/* Transform the points from destination pixel/line coordinates */
/* to source pixel/line coordinates. */
/* --------------------------------------------------------------------
*/
poWK->pfnTransformer(psJob->pTransformerArg, TRUE, nDstXSize, padfX,
padfY, padfZ, pabSuccess);
if (dfSrcCoordPrecision > 0.0)
{
GWKRoundSourceCoordinates(
nDstXSize, padfX, padfY, padfZ, pabSuccess, dfSrcCoordPrecision,
dfErrorThreshold, poWK->pfnTransformer, psJob->pTransformerArg,
0.5 + poWK->nDstXOff, iDstY + 0.5 + poWK->nDstYOff);
}
/* ====================================================================
*/
/* Loop over pixels in output scanline. */
/* ====================================================================
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
GPtrDiff_t iSrcOffset = 0;
if (!GWKCheckAndComputeSrcOffsets(psJob, pabSuccess, iDstX, iDstY,
padfX, padfY, nSrcXSize,
nSrcYSize, iSrcOffset))
continue;
/* --------------------------------------------------------------------
*/
/* Do not try to apply transparent/invalid source pixels to the
*/
/* destination. This currently ignores the multi-pixel input
*/
/* of bilinear and cubic resamples. */
/* --------------------------------------------------------------------
*/
double dfDensity = 1.0;
if (poWK->pafUnifiedSrcDensity != nullptr)
{
dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
if (dfDensity < SRC_DENSITY_THRESHOLD)
continue;
}
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset))
continue;
/* ====================================================================
*/
/* Loop processing each band. */
/* ====================================================================
*/
bool bHasFoundDensity = false;
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
double dfBandDensity = 0.0;
double dfValueReal = 0.0;
double dfValueImag = 0.0;
/* --------------------------------------------------------------------
*/
/* Collect the source value. */
/* --------------------------------------------------------------------
*/
if (poWK->eResample == GRA_NearestNeighbour || nSrcXSize == 1 ||
nSrcYSize == 1)
{
// FALSE is returned if dfBandDensity == 0, which is
// checked below.
CPL_IGNORE_RET_VAL(GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity, &dfValueReal,
&dfValueImag));
}
else if (poWK->eResample == GRA_Bilinear && bUse4SamplesFormula)
{
GWKBilinearResample4Sample(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal, &dfValueImag);
}
else if (poWK->eResample == GRA_Cubic && bUse4SamplesFormula)
{
GWKCubicResample4Sample(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal, &dfValueImag);
}
else
#ifdef DEBUG
// Only useful for clang static analyzer.
if (psWrkStruct != nullptr)
#endif
{
psWrkStruct->pfnGWKResample(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal, &dfValueImag, psWrkStruct);
}
// If we didn't find any valid inputs skip to next band.
if (dfBandDensity < BAND_DENSITY_THRESHOLD)
continue;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate transformation is
// from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
bHasFoundDensity = true;
/* --------------------------------------------------------------------
*/
/* We have a computed value from the source. Now apply it
* to */
/* the destination pixel. */
/* --------------------------------------------------------------------
*/
GWKSetPixelValue(poWK, iBand, iDstOffset, dfBandDensity,
dfValueReal, dfValueImag);
}
if (!bHasFoundDensity)
continue;
/* --------------------------------------------------------------------
*/
/* Update destination density/validity masks. */
/* --------------------------------------------------------------------
*/
GWKOverlayDensity(poWK, iDstOffset, dfDensity);
if (poWK->panDstValid != nullptr)
{
CPLMaskSet(poWK->panDstValid, iDstOffset);
}
} /* Next iDstX */
/* --------------------------------------------------------------------
*/
/* Report progress to the user, and optionally cancel out. */
/* --------------------------------------------------------------------
*/
if (psJob->pfnProgress && psJob->pfnProgress(psJob))
break;
}
/* -------------------------------------------------------------------- */
/* Cleanup and return. */
/* -------------------------------------------------------------------- */
CPLFree(padfX);
CPLFree(padfY);
CPLFree(padfZ);
CPLFree(pabSuccess);
if (psWrkStruct)
GWKResampleDeleteWrkStruct(psWrkStruct);
}
static CPLErr GWKGeneralCase(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKGeneralCase", GWKGeneralCaseThread);
}
/************************************************************************/
/* GWKRealCase() */
/* */
/* General case for non-complex data types. */
/************************************************************************/
static void GWKRealCaseThread(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
const int iYMin = psJob->iYMin;
const int iYMax = psJob->iYMax;
const int nDstXSize = poWK->nDstXSize;
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
/* -------------------------------------------------------------------- */
/* Allocate x,y,z coordinate arrays for transformation ... one */
/* scanlines worth of positions. */
/* -------------------------------------------------------------------- */
// For x, 2 *, because we cache the precomputed values at the end.
double *padfX =
static_cast<double *>(CPLMalloc(2 * sizeof(double) * nDstXSize));
double *padfY =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
int *pabSuccess = static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
const bool bUse4SamplesFormula =
poWK->dfXScale >= 0.95 && poWK->dfYScale >= 0.95;
GWKResampleWrkStruct *psWrkStruct = nullptr;
if (poWK->eResample != GRA_NearestNeighbour)
{
psWrkStruct = GWKResampleCreateWrkStruct(poWK);
}
const double dfSrcCoordPrecision = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "SRC_COORD_PRECISION", "0"));
const double dfErrorThreshold = CPLAtof(
CSLFetchNameValueDef(poWK->papszWarpOptions, "ERROR_THRESHOLD", "0"));
const bool bSrcMaskIsDensity = poWK->panUnifiedSrcValid == nullptr &&
poWK->papanBandSrcValid == nullptr &&
poWK->pafUnifiedSrcDensity != nullptr;
// Precompute values.
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfX[nDstXSize + iDstX] = iDstX + 0.5 + poWK->nDstXOff;
/* ==================================================================== */
/* Loop over output lines. */
/* ==================================================================== */
for (int iDstY = iYMin; iDstY < iYMax; iDstY++)
{
/* --------------------------------------------------------------------
*/
/* Setup points to transform to source image space. */
/* --------------------------------------------------------------------
*/
memcpy(padfX, padfX + nDstXSize, sizeof(double) * nDstXSize);
const double dfY = iDstY + 0.5 + poWK->nDstYOff;
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfY[iDstX] = dfY;
memset(padfZ, 0, sizeof(double) * nDstXSize);
/* --------------------------------------------------------------------
*/
/* Transform the points from destination pixel/line coordinates */
/* to source pixel/line coordinates. */
/* --------------------------------------------------------------------
*/
poWK->pfnTransformer(psJob->pTransformerArg, TRUE, nDstXSize, padfX,
padfY, padfZ, pabSuccess);
if (dfSrcCoordPrecision > 0.0)
{
GWKRoundSourceCoordinates(
nDstXSize, padfX, padfY, padfZ, pabSuccess, dfSrcCoordPrecision,
dfErrorThreshold, poWK->pfnTransformer, psJob->pTransformerArg,
0.5 + poWK->nDstXOff, iDstY + 0.5 + poWK->nDstYOff);
}
/* ====================================================================
*/
/* Loop over pixels in output scanline. */
/* ====================================================================
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
GPtrDiff_t iSrcOffset = 0;
if (!GWKCheckAndComputeSrcOffsets(psJob, pabSuccess, iDstX, iDstY,
padfX, padfY, nSrcXSize,
nSrcYSize, iSrcOffset))
continue;
/* --------------------------------------------------------------------
*/
/* Do not try to apply transparent/invalid source pixels to the
*/
/* destination. This currently ignores the multi-pixel input
*/
/* of bilinear and cubic resamples. */
/* --------------------------------------------------------------------
*/
double dfDensity = 1.0;
if (poWK->pafUnifiedSrcDensity != nullptr)
{
dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
if (dfDensity < SRC_DENSITY_THRESHOLD)
continue;
}
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset))
continue;
/* ====================================================================
*/
/* Loop processing each band. */
/* ====================================================================
*/
bool bHasFoundDensity = false;
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
double dfBandDensity = 0.0;
double dfValueReal = 0.0;
/* --------------------------------------------------------------------
*/
/* Collect the source value. */
/* --------------------------------------------------------------------
*/
if (poWK->eResample == GRA_NearestNeighbour || nSrcXSize == 1 ||
nSrcYSize == 1)
{
// FALSE is returned if dfBandDensity == 0, which is
// checked below.
CPL_IGNORE_RET_VAL(GWKGetPixelValueReal(
poWK, iBand, iSrcOffset, &dfBandDensity, &dfValueReal));
}
else if (poWK->eResample == GRA_Bilinear && bUse4SamplesFormula)
{
double dfValueImagIgnored = 0.0;
GWKBilinearResample4Sample(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal, &dfValueImagIgnored);
}
else if (poWK->eResample == GRA_Cubic && bUse4SamplesFormula)
{
if (bSrcMaskIsDensity)
{
if (poWK->eWorkingDataType == GDT_Byte)
{
GWKCubicResampleSrcMaskIsDensity4SampleRealT<GByte>(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal);
}
else if (poWK->eWorkingDataType == GDT_UInt16)
{
GWKCubicResampleSrcMaskIsDensity4SampleRealT<
GUInt16>(poWK, iBand,
padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff,
&dfBandDensity, &dfValueReal);
}
else
{
GWKCubicResampleSrcMaskIsDensity4SampleReal(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal);
}
}
else
{
double dfValueImagIgnored = 0.0;
GWKCubicResample4Sample(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal, &dfValueImagIgnored);
}
}
else
#ifdef DEBUG
// Only useful for clang static analyzer.
if (psWrkStruct != nullptr)
#endif
{
double dfValueImagIgnored = 0.0;
psWrkStruct->pfnGWKResample(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &dfBandDensity,
&dfValueReal, &dfValueImagIgnored, psWrkStruct);
}
// If we didn't find any valid inputs skip to next band.
if (dfBandDensity < BAND_DENSITY_THRESHOLD)
continue;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate transformation is
// from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
bHasFoundDensity = true;
/* --------------------------------------------------------------------
*/
/* We have a computed value from the source. Now apply it
* to */
/* the destination pixel. */
/* --------------------------------------------------------------------
*/
GWKSetPixelValueReal(poWK, iBand, iDstOffset, dfBandDensity,
dfValueReal);
}
if (!bHasFoundDensity)
continue;
/* --------------------------------------------------------------------
*/
/* Update destination density/validity masks. */
/* --------------------------------------------------------------------
*/
GWKOverlayDensity(poWK, iDstOffset, dfDensity);
if (poWK->panDstValid != nullptr)
{
CPLMaskSet(poWK->panDstValid, iDstOffset);
}
} // Next iDstX.
/* --------------------------------------------------------------------
*/
/* Report progress to the user, and optionally cancel out. */
/* --------------------------------------------------------------------
*/
if (psJob->pfnProgress && psJob->pfnProgress(psJob))
break;
}
/* -------------------------------------------------------------------- */
/* Cleanup and return. */
/* -------------------------------------------------------------------- */
CPLFree(padfX);
CPLFree(padfY);
CPLFree(padfZ);
CPLFree(pabSuccess);
if (psWrkStruct)
GWKResampleDeleteWrkStruct(psWrkStruct);
}
static CPLErr GWKRealCase(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKRealCase", GWKRealCaseThread);
}
/************************************************************************/
/* GWKResampleNoMasksOrDstDensityOnlyThreadInternal() */
/************************************************************************/
template <class T, GDALResampleAlg eResample, int bUse4SamplesFormula>
static void GWKResampleNoMasksOrDstDensityOnlyThreadInternal(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
const int iYMin = psJob->iYMin;
const int iYMax = psJob->iYMax;
const int nDstXSize = poWK->nDstXSize;
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
/* -------------------------------------------------------------------- */
/* Allocate x,y,z coordinate arrays for transformation ... one */
/* scanlines worth of positions. */
/* -------------------------------------------------------------------- */
// For x, 2 *, because we cache the precomputed values at the end.
double *padfX =
static_cast<double *>(CPLMalloc(2 * sizeof(double) * nDstXSize));
double *padfY =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
int *pabSuccess = static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
const int nXRadius = poWK->nXRadius;
double *padfWeight =
static_cast<double *>(CPLCalloc(1 + nXRadius * 2, sizeof(double)));
const double dfSrcCoordPrecision = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "SRC_COORD_PRECISION", "0"));
const double dfErrorThreshold = CPLAtof(
CSLFetchNameValueDef(poWK->papszWarpOptions, "ERROR_THRESHOLD", "0"));
// Precompute values.
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfX[nDstXSize + iDstX] = iDstX + 0.5 + poWK->nDstXOff;
/* ==================================================================== */
/* Loop over output lines. */
/* ==================================================================== */
for (int iDstY = iYMin; iDstY < iYMax; iDstY++)
{
/* --------------------------------------------------------------------
*/
/* Setup points to transform to source image space. */
/* --------------------------------------------------------------------
*/
memcpy(padfX, padfX + nDstXSize, sizeof(double) * nDstXSize);
const double dfY = iDstY + 0.5 + poWK->nDstYOff;
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfY[iDstX] = dfY;
memset(padfZ, 0, sizeof(double) * nDstXSize);
/* --------------------------------------------------------------------
*/
/* Transform the points from destination pixel/line coordinates */
/* to source pixel/line coordinates. */
/* --------------------------------------------------------------------
*/
poWK->pfnTransformer(psJob->pTransformerArg, TRUE, nDstXSize, padfX,
padfY, padfZ, pabSuccess);
if (dfSrcCoordPrecision > 0.0)
{
GWKRoundSourceCoordinates(
nDstXSize, padfX, padfY, padfZ, pabSuccess, dfSrcCoordPrecision,
dfErrorThreshold, poWK->pfnTransformer, psJob->pTransformerArg,
0.5 + poWK->nDstXOff, iDstY + 0.5 + poWK->nDstYOff);
}
/* ====================================================================
*/
/* Loop over pixels in output scanline. */
/* ====================================================================
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
GPtrDiff_t iSrcOffset = 0;
if (!GWKCheckAndComputeSrcOffsets(psJob, pabSuccess, iDstX, iDstY,
padfX, padfY, nSrcXSize,
nSrcYSize, iSrcOffset))
continue;
/* ====================================================================
*/
/* Loop processing each band. */
/* ====================================================================
*/
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
T value = 0;
if (eResample == GRA_NearestNeighbour)
{
value = reinterpret_cast<T *>(
poWK->papabySrcImage[iBand])[iSrcOffset];
}
else if (bUse4SamplesFormula)
{
if (eResample == GRA_Bilinear)
GWKBilinearResampleNoMasks4SampleT(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &value);
else
GWKCubicResampleNoMasks4SampleT(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &value);
}
else
{
GWKResampleNoMasksT(
poWK, iBand, padfX[iDstX] - poWK->nSrcXOff,
padfY[iDstX] - poWK->nSrcYOff, &value, padfWeight);
}
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate transformation is
// from target to source
value = GWKClampValueT<T>(
value * poWK->dfMultFactorVerticalShift - padfZ[iDstX]);
}
if (poWK->pafDstDensity)
poWK->pafDstDensity[iDstOffset] = 1.0f;
reinterpret_cast<T *>(poWK->papabyDstImage[iBand])[iDstOffset] =
value;
}
}
/* --------------------------------------------------------------------
*/
/* Report progress to the user, and optionally cancel out. */
/* --------------------------------------------------------------------
*/
if (psJob->pfnProgress && psJob->pfnProgress(psJob))
break;
}
/* -------------------------------------------------------------------- */
/* Cleanup and return. */
/* -------------------------------------------------------------------- */
CPLFree(padfX);
CPLFree(padfY);
CPLFree(padfZ);
CPLFree(pabSuccess);
CPLFree(padfWeight);
}
template <class T, GDALResampleAlg eResample>
static void GWKResampleNoMasksOrDstDensityOnlyThread(void *pData)
{
GWKResampleNoMasksOrDstDensityOnlyThreadInternal<T, eResample, FALSE>(
pData);
}
template <class T, GDALResampleAlg eResample>
static void GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
CPLAssert(eResample == GRA_Bilinear || eResample == GRA_Cubic);
const bool bUse4SamplesFormula =
poWK->dfXScale >= 0.95 && poWK->dfYScale >= 0.95;
if (bUse4SamplesFormula)
GWKResampleNoMasksOrDstDensityOnlyThreadInternal<T, eResample, TRUE>(
pData);
else
GWKResampleNoMasksOrDstDensityOnlyThreadInternal<T, eResample, FALSE>(
pData);
}
static CPLErr GWKNearestNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKNearestNoMasksOrDstDensityOnlyByte",
GWKResampleNoMasksOrDstDensityOnlyThread<GByte, GRA_NearestNeighbour>);
}
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKBilinearNoMasksOrDstDensityOnlyByte",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<GByte,
GRA_Bilinear>);
}
static CPLErr GWKCubicNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicNoMasksOrDstDensityOnlyByte",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<GByte, GRA_Cubic>);
}
static CPLErr GWKCubicNoMasksOrDstDensityOnlyFloat(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicNoMasksOrDstDensityOnlyFloat",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<float, GRA_Cubic>);
}
#ifdef INSTANTIATE_FLOAT64_SSE2_IMPL
static CPLErr GWKCubicNoMasksOrDstDensityOnlyDouble(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicNoMasksOrDstDensityOnlyDouble",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<double, GRA_Cubic>);
}
#endif
static CPLErr GWKCubicSplineNoMasksOrDstDensityOnlyByte(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicSplineNoMasksOrDstDensityOnlyByte",
GWKResampleNoMasksOrDstDensityOnlyThread<GByte, GRA_CubicSpline>);
}
/************************************************************************/
/* GWKNearestByte() */
/* */
/* Case for 8bit input data with nearest neighbour resampling */
/* using valid flags. Should be as fast as possible for this */
/* particular transformation type. */
/************************************************************************/
template <class T> static void GWKNearestThread(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
const int iYMin = psJob->iYMin;
const int iYMax = psJob->iYMax;
const int nDstXSize = poWK->nDstXSize;
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
/* -------------------------------------------------------------------- */
/* Allocate x,y,z coordinate arrays for transformation ... one */
/* scanlines worth of positions. */
/* -------------------------------------------------------------------- */
// For x, 2 *, because we cache the precomputed values at the end.
double *padfX =
static_cast<double *>(CPLMalloc(2 * sizeof(double) * nDstXSize));
double *padfY =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
int *pabSuccess = static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
const double dfSrcCoordPrecision = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "SRC_COORD_PRECISION", "0"));
const double dfErrorThreshold = CPLAtof(
CSLFetchNameValueDef(poWK->papszWarpOptions, "ERROR_THRESHOLD", "0"));
// Precompute values.
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfX[nDstXSize + iDstX] = iDstX + 0.5 + poWK->nDstXOff;
/* ==================================================================== */
/* Loop over output lines. */
/* ==================================================================== */
for (int iDstY = iYMin; iDstY < iYMax; iDstY++)
{
/* --------------------------------------------------------------------
*/
/* Setup points to transform to source image space. */
/* --------------------------------------------------------------------
*/
memcpy(padfX, padfX + nDstXSize, sizeof(double) * nDstXSize);
const double dfY = iDstY + 0.5 + poWK->nDstYOff;
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
padfY[iDstX] = dfY;
memset(padfZ, 0, sizeof(double) * nDstXSize);
/* --------------------------------------------------------------------
*/
/* Transform the points from destination pixel/line coordinates */
/* to source pixel/line coordinates. */
/* --------------------------------------------------------------------
*/
poWK->pfnTransformer(psJob->pTransformerArg, TRUE, nDstXSize, padfX,
padfY, padfZ, pabSuccess);
if (dfSrcCoordPrecision > 0.0)
{
GWKRoundSourceCoordinates(
nDstXSize, padfX, padfY, padfZ, pabSuccess, dfSrcCoordPrecision,
dfErrorThreshold, poWK->pfnTransformer, psJob->pTransformerArg,
0.5 + poWK->nDstXOff, iDstY + 0.5 + poWK->nDstYOff);
}
/* ====================================================================
*/
/* Loop over pixels in output scanline. */
/* ====================================================================
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
GPtrDiff_t iSrcOffset = 0;
if (!GWKCheckAndComputeSrcOffsets(psJob, pabSuccess, iDstX, iDstY,
padfX, padfY, nSrcXSize,
nSrcYSize, iSrcOffset))
continue;
/* --------------------------------------------------------------------
*/
/* Do not try to apply invalid source pixels to the dest. */
/* --------------------------------------------------------------------
*/
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset))
continue;
/* --------------------------------------------------------------------
*/
/* Do not try to apply transparent source pixels to the
* destination.*/
/* --------------------------------------------------------------------
*/
double dfDensity = 1.0;
if (poWK->pafUnifiedSrcDensity != nullptr)
{
dfDensity = poWK->pafUnifiedSrcDensity[iSrcOffset];
if (dfDensity < SRC_DENSITY_THRESHOLD)
continue;
}
/* ====================================================================
*/
/* Loop processing each band. */
/* ====================================================================
*/
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
T value = 0;
double dfBandDensity = 0.0;
/* --------------------------------------------------------------------
*/
/* Collect the source value. */
/* --------------------------------------------------------------------
*/
if (GWKGetPixelT(poWK, iBand, iSrcOffset, &dfBandDensity,
&value))
{
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate transformation
// is from target to source
value = GWKClampValueT<T>(
value * poWK->dfMultFactorVerticalShift -
padfZ[iDstX]);
}
if (dfBandDensity < 1.0)
{
if (dfBandDensity == 0.0)
{
// Do nothing.
}
else
{
// Let the general code take care of mixing.
GWKSetPixelValueRealT(poWK, iBand, iDstOffset,
dfBandDensity, value);
}
}
else
{
reinterpret_cast<T *>(
poWK->papabyDstImage[iBand])[iDstOffset] = value;
}
}
}
/* --------------------------------------------------------------------
*/
/* Mark this pixel valid/opaque in the output. */
/* --------------------------------------------------------------------
*/
GWKOverlayDensity(poWK, iDstOffset, dfDensity);
if (poWK->panDstValid != nullptr)
{
CPLMaskSet(poWK->panDstValid, iDstOffset);
}
} /* Next iDstX */
/* --------------------------------------------------------------------
*/
/* Report progress to the user, and optionally cancel out. */
/* --------------------------------------------------------------------
*/
if (psJob->pfnProgress && psJob->pfnProgress(psJob))
break;
}
/* -------------------------------------------------------------------- */
/* Cleanup and return. */
/* -------------------------------------------------------------------- */
CPLFree(padfX);
CPLFree(padfY);
CPLFree(padfZ);
CPLFree(pabSuccess);
}
static CPLErr GWKNearestByte(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKNearestByte", GWKNearestThread<GByte>);
}
static CPLErr GWKNearestNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKNearestNoMasksOrDstDensityOnlyShort",
GWKResampleNoMasksOrDstDensityOnlyThread<GInt16, GRA_NearestNeighbour>);
}
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKBilinearNoMasksOrDstDensityOnlyShort",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<GInt16,
GRA_Bilinear>);
}
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyUShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKBilinearNoMasksOrDstDensityOnlyUShort",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<GUInt16,
GRA_Bilinear>);
}
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyFloat(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKBilinearNoMasksOrDstDensityOnlyFloat",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<float,
GRA_Bilinear>);
}
#ifdef INSTANTIATE_FLOAT64_SSE2_IMPL
static CPLErr GWKBilinearNoMasksOrDstDensityOnlyDouble(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKBilinearNoMasksOrDstDensityOnlyDouble",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<double,
GRA_Bilinear>);
}
#endif
static CPLErr GWKCubicNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicNoMasksOrDstDensityOnlyShort",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<GInt16, GRA_Cubic>);
}
static CPLErr GWKCubicNoMasksOrDstDensityOnlyUShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicNoMasksOrDstDensityOnlyUShort",
GWKResampleNoMasksOrDstDensityOnlyHas4SampleThread<GUInt16, GRA_Cubic>);
}
static CPLErr GWKCubicSplineNoMasksOrDstDensityOnlyShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicSplineNoMasksOrDstDensityOnlyShort",
GWKResampleNoMasksOrDstDensityOnlyThread<GInt16, GRA_CubicSpline>);
}
static CPLErr GWKCubicSplineNoMasksOrDstDensityOnlyUShort(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKCubicSplineNoMasksOrDstDensityOnlyUShort",
GWKResampleNoMasksOrDstDensityOnlyThread<GUInt16, GRA_CubicSpline>);
}
static CPLErr GWKNearestShort(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKNearestShort", GWKNearestThread<GInt16>);
}
static CPLErr GWKNearestNoMasksOrDstDensityOnlyFloat(GDALWarpKernel *poWK)
{
return GWKRun(
poWK, "GWKNearestNoMasksOrDstDensityOnlyFloat",
GWKResampleNoMasksOrDstDensityOnlyThread<float, GRA_NearestNeighbour>);
}
static CPLErr GWKNearestFloat(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKNearestFloat", GWKNearestThread<float>);
}
/************************************************************************/
/* GWKAverageOrMode() */
/* */
/************************************************************************/
static void GWKAverageOrModeThread(void *pData);
static CPLErr GWKAverageOrMode(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKAverageOrMode", GWKAverageOrModeThread);
}
// Overall logic based on GWKGeneralCaseThread().
static void GWKAverageOrModeThread(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
const int iYMin = psJob->iYMin;
const int iYMax = psJob->iYMax;
const int nDstXSize = poWK->nDstXSize;
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
/* -------------------------------------------------------------------- */
/* Find out which algorithm to use (small optim.) */
/* -------------------------------------------------------------------- */
int nAlgo = 0;
// These vars only used with nAlgo == 3.
int *panVals = nullptr;
int nBins = 0;
int nBinsOffset = 0;
// Only used with nAlgo = 2.
float *pafRealVals = nullptr;
float *pafImagVals = nullptr;
int *panRealSums = nullptr;
int *panImagSums = nullptr;
// Only used with nAlgo = 6.
float quant = 0.5;
// To control array allocation only when data type is complex
const bool bIsComplex = GDALDataTypeIsComplex(poWK->eWorkingDataType) != 0;
if (poWK->eResample == GRA_Average)
{
nAlgo = GWKAOM_Average;
}
else if (poWK->eResample == GRA_RMS)
{
nAlgo = GWKAOM_RMS;
}
else if (poWK->eResample == GRA_Mode)
{
// TODO check color table count > 256.
if (poWK->eWorkingDataType == GDT_Byte ||
poWK->eWorkingDataType == GDT_UInt16 ||
poWK->eWorkingDataType == GDT_Int16)
{
nAlgo = GWKAOM_Imode;
// In the case of a paletted or non-paletted byte band,
// Input values are between 0 and 255.
if (poWK->eWorkingDataType == GDT_Byte)
{
nBins = 256;
}
// In the case of Int16, input values are between -32768 and 32767.
else if (poWK->eWorkingDataType == GDT_Int16)
{
nBins = 65536;
nBinsOffset = 32768;
}
// In the case of UInt16, input values are between 0 and 65537.
else if (poWK->eWorkingDataType == GDT_UInt16)
{
nBins = 65536;
}
panVals =
static_cast<int *>(VSI_MALLOC_VERBOSE(nBins * sizeof(int)));
if (panVals == nullptr)
return;
}
else
{
nAlgo = GWKAOM_Fmode;
if (nSrcXSize > 0 && nSrcYSize > 0)
{
pafRealVals = static_cast<float *>(
VSI_MALLOC3_VERBOSE(nSrcXSize, nSrcYSize, sizeof(float)));
panRealSums = static_cast<int *>(
VSI_MALLOC3_VERBOSE(nSrcXSize, nSrcYSize, sizeof(int)));
if (pafRealVals == nullptr || panRealSums == nullptr)
{
VSIFree(pafRealVals);
VSIFree(panRealSums);
return;
}
}
}
}
else if (poWK->eResample == GRA_Max)
{
nAlgo = GWKAOM_Max;
}
else if (poWK->eResample == GRA_Min)
{
nAlgo = GWKAOM_Min;
}
else if (poWK->eResample == GRA_Med)
{
nAlgo = GWKAOM_Quant;
quant = 0.5;
}
else if (poWK->eResample == GRA_Q1)
{
nAlgo = GWKAOM_Quant;
quant = 0.25;
}
else if (poWK->eResample == GRA_Q3)
{
nAlgo = GWKAOM_Quant;
quant = 0.75;
}
#ifdef disabled
else if (poWK->eResample == GRA_Sum)
{
nAlgo = GWKAOM_Sum;
}
#endif
else
{
// Other resample algorithms not permitted here.
CPLDebug("GDAL", "GDALWarpKernel():GWKAverageOrModeThread() ERROR, "
"illegal resample");
return;
}
CPLDebug("GDAL", "GDALWarpKernel():GWKAverageOrModeThread() using algo %d",
nAlgo);
/* -------------------------------------------------------------------- */
/* Allocate x,y,z coordinate arrays for transformation ... two */
/* scanlines worth of positions. */
/* -------------------------------------------------------------------- */
double *padfX =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfY =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfX2 =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfY2 =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
double *padfZ2 =
static_cast<double *>(CPLMalloc(sizeof(double) * nDstXSize));
int *pabSuccess = static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
int *pabSuccess2 = static_cast<int *>(CPLMalloc(sizeof(int) * nDstXSize));
const double dfSrcCoordPrecision = CPLAtof(CSLFetchNameValueDef(
poWK->papszWarpOptions, "SRC_COORD_PRECISION", "0"));
const double dfErrorThreshold = CPLAtof(
CSLFetchNameValueDef(poWK->papszWarpOptions, "ERROR_THRESHOLD", "0"));
const int nXMargin =
2 * std::max(1, static_cast<int>(std::ceil(1. / poWK->dfXScale)));
const int nYMargin =
2 * std::max(1, static_cast<int>(std::ceil(1. / poWK->dfYScale)));
/* ==================================================================== */
/* Loop over output lines. */
/* ==================================================================== */
for (int iDstY = iYMin; iDstY < iYMax; iDstY++)
{
/* --------------------------------------------------------------------
*/
/* Setup points to transform to source image space. */
/* --------------------------------------------------------------------
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
padfX[iDstX] = iDstX + poWK->nDstXOff;
padfY[iDstX] = iDstY + poWK->nDstYOff;
padfZ[iDstX] = 0.0;
padfX2[iDstX] = iDstX + 1.0 + poWK->nDstXOff;
padfY2[iDstX] = iDstY + 1.0 + poWK->nDstYOff;
padfZ2[iDstX] = 0.0;
}
/* --------------------------------------------------------------------
*/
/* Transform the points from destination pixel/line coordinates */
/* to source pixel/line coordinates. */
/* --------------------------------------------------------------------
*/
poWK->pfnTransformer(psJob->pTransformerArg, TRUE, nDstXSize, padfX,
padfY, padfZ, pabSuccess);
poWK->pfnTransformer(psJob->pTransformerArg, TRUE, nDstXSize, padfX2,
padfY2, padfZ2, pabSuccess2);
if (dfSrcCoordPrecision > 0.0)
{
GWKRoundSourceCoordinates(
nDstXSize, padfX, padfY, padfZ, pabSuccess, dfSrcCoordPrecision,
dfErrorThreshold, poWK->pfnTransformer, psJob->pTransformerArg,
poWK->nDstXOff, iDstY + poWK->nDstYOff);
GWKRoundSourceCoordinates(
nDstXSize, padfX2, padfY2, padfZ2, pabSuccess2,
dfSrcCoordPrecision, dfErrorThreshold, poWK->pfnTransformer,
psJob->pTransformerArg, 1.0 + poWK->nDstXOff,
iDstY + 1.0 + poWK->nDstYOff);
}
/* ====================================================================
*/
/* Loop over pixels in output scanline. */
/* ====================================================================
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
GPtrDiff_t iSrcOffset = 0;
double dfDensity = 1.0;
bool bHasFoundDensity = false;
if (!pabSuccess[iDstX] || !pabSuccess2[iDstX])
continue;
// Add some checks so that padfX[iDstX] - poWK->nSrcXOff is in
// reasonable range (https://github.com/OSGeo/gdal/issues/2365)
if (!(padfX[iDstX] - poWK->nSrcXOff >= -nXMargin &&
padfX2[iDstX] - poWK->nSrcXOff >= -nXMargin &&
padfY[iDstX] - poWK->nSrcYOff >= -nYMargin &&
padfY2[iDstX] - poWK->nSrcYOff >= -nYMargin &&
padfX[iDstX] - poWK->nSrcXOff - nSrcXSize <= nXMargin &&
padfX2[iDstX] - poWK->nSrcXOff - nSrcXSize <= nXMargin &&
padfY[iDstX] - poWK->nSrcYOff - nSrcYSize <= nYMargin &&
padfY2[iDstX] - poWK->nSrcYOff - nSrcYSize <= nYMargin))
{
continue;
}
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
// Compute corners in source crs.
// The transformation might not have preserved ordering of
// coordinates so do the necessary swapping (#5433).
// NOTE: this is really an approximative fix. To do something
// more precise we would for example need to compute the
// transformation of coordinates in the
// [iDstX,iDstY]x[iDstX+1,iDstY+1] square back to source
// coordinates, and take the bounding box of the got source
// coordinates.
if (padfX[iDstX] > padfX2[iDstX])
std::swap(padfX[iDstX], padfX2[iDstX]);
// Detect situations where the target pixel is close to the
// antimeridian and when padfX[iDstX] and padfX2[iDstX] are very
// close to the left-most and right-most columns of the source
// raster. The 2 value below was experimentally determined to
// avoid false-positives and false-negatives.
// Addresses https://github.com/OSGeo/gdal/issues/6478
bool bWrapOverX = false;
const int nThresholdWrapOverX = std::min(2, nSrcXSize / 10);
if (poWK->nSrcXOff == 0 &&
padfX[iDstX] * poWK->dfXScale < nThresholdWrapOverX &&
(nSrcXSize - padfX2[iDstX]) * poWK->dfXScale <
nThresholdWrapOverX)
{
bWrapOverX = true;
std::swap(padfX[iDstX], padfX2[iDstX]);
padfX2[iDstX] += nSrcXSize;
}
const double dfXMin = padfX[iDstX] - poWK->nSrcXOff;
int iSrcXMin =
static_cast<int>(std::min(std::max(floor(dfXMin + 1e-10), 0.0),
static_cast<double>(nSrcXSize)));
const double dfXMax = padfX2[iDstX] - poWK->nSrcXOff;
int iSrcXMax = static_cast<int>(
std::min(ceil(dfXMax - 1e-10), static_cast<double>(INT_MAX)));
if (!bWrapOverX)
iSrcXMax = std::min(iSrcXMax, nSrcXSize);
if (iSrcXMin == iSrcXMax && iSrcXMax < nSrcXSize)
iSrcXMax++;
if (padfY[iDstX] > padfY2[iDstX])
std::swap(padfY[iDstX], padfY2[iDstX]);
const double dfYMin = padfY[iDstX] - poWK->nSrcYOff;
int iSrcYMin =
static_cast<int>(std::min(std::max(floor(dfYMin + 1e-10), 0.0),
static_cast<double>(nSrcYSize)));
const double dfYMax = padfY2[iDstX] - poWK->nSrcYOff;
int iSrcYMax = static_cast<int>(
std::min(ceil(dfYMax - 1e-10), static_cast<double>(nSrcYSize)));
if (iSrcYMin == iSrcYMax && iSrcYMax < nSrcYSize)
iSrcYMax++;
/* ====================================================================
*/
/* Loop processing each band. */
/* ====================================================================
*/
for (int iBand = 0; iBand < poWK->nBands; iBand++)
{
double dfBandDensity = 0.0;
double dfValueReal = 0.0;
double dfValueImag = 0.0;
double dfValueRealTmp = 0.0;
double dfValueImagTmp = 0.0;
/* --------------------------------------------------------------------
*/
/* Collect the source value. */
/* --------------------------------------------------------------------
*/
// Loop over source lines and pixels - 3 possible algorithms.
#define COMPUTE_WEIGHT_Y(iSrcY) \
((iSrcY == iSrcYMin) \
? ((iSrcYMin + 1 == iSrcYMax) ? 1.0 : 1 - (dfYMin - iSrcYMin)) \
: (iSrcY + 1 == iSrcYMax) ? 1 - (iSrcYMax - dfYMax) \
: 1.0)
#define COMPUTE_WEIGHT(iSrcX, dfWeightY) \
((iSrcX == iSrcXMin) ? ((iSrcXMin + 1 == iSrcXMax) \
? dfWeightY \
: dfWeightY * (1 - (dfXMin - iSrcXMin))) \
: (iSrcX + 1 == iSrcXMax) ? dfWeightY * (1 - (iSrcXMax - dfXMax)) \
: dfWeightY)
// poWK->eResample == GRA_Average.
if (nAlgo == GWKAOM_Average)
{
double dfTotalReal = 0.0;
double dfTotalImag = 0.0;
double dfTotalWeight = 0.0;
// This code adapted from GDALDownsampleChunk32R_AverageT()
// in gcore/overview.cpp.
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
const double dfWeightY = COMPUTE_WEIGHT_Y(iSrcY);
iSrcOffset = iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
{
continue;
}
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
const double dfWeight =
COMPUTE_WEIGHT(iSrcX, dfWeightY);
dfTotalWeight += dfWeight;
dfTotalReal += dfValueRealTmp * dfWeight;
if (bIsComplex)
{
dfTotalImag += dfValueImagTmp * dfWeight;
}
}
}
}
if (dfTotalWeight > 0)
{
dfValueReal = dfTotalReal / dfTotalWeight;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
if (bIsComplex)
{
dfValueImag = dfTotalImag / dfTotalWeight;
}
dfBandDensity = 1;
bHasFoundDensity = true;
}
} // GRA_Average.
// poWK->eResample == GRA_RMS.
if (nAlgo == GWKAOM_RMS)
{
double dfTotalReal = 0.0;
double dfTotalImag = 0.0;
double dfTotalWeight = 0.0;
// This code adapted from GDALDownsampleChunk32R_AverageT()
// in gcore/overview.cpp.
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
const double dfWeightY = COMPUTE_WEIGHT_Y(iSrcY);
iSrcOffset = iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
{
continue;
}
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
const double dfWeight =
COMPUTE_WEIGHT(iSrcX, dfWeightY);
dfTotalWeight += dfWeight;
dfTotalReal +=
dfValueRealTmp * dfValueRealTmp * dfWeight;
if (bIsComplex)
dfTotalImag += dfValueImagTmp *
dfValueImagTmp * dfWeight;
}
}
}
if (dfTotalWeight > 0)
{
dfValueReal = sqrt(dfTotalReal / dfTotalWeight);
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
if (bIsComplex)
dfValueImag = sqrt(dfTotalImag / dfTotalWeight);
dfBandDensity = 1;
bHasFoundDensity = true;
}
} // GRA_RMS.
#ifdef disabled
else if (nAlgo == GWKAOM_Sum)
// poWK->eResample == GRA_Sum
{
double dfTotalReal = 0.0;
double dfTotalImag = 0.0;
bool bFoundValid = false;
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
const double dfWeightY = COMPUTE_WEIGHT_Y(iSrcY);
iSrcOffset = iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
{
continue;
}
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
const double dfWeight =
COMPUTE_WEIGHT(iSrcX, dfWeightY);
bFoundValid = true;
dfTotalReal += dfValueRealTmp * dfWeight;
if (bIsComplex)
{
dfTotalImag += dfValueImagTmp * dfWeight;
}
}
}
}
if (bFoundValid)
{
dfValueReal = dfTotalReal;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
if (bIsComplex)
{
dfValueImag = dfTotalImag;
}
dfBandDensity = 1;
bHasFoundDensity = true;
}
} // GRA_Sum.
#endif
else if (nAlgo == GWKAOM_Imode || nAlgo == GWKAOM_Fmode)
// poWK->eResample == GRA_Mode
{
// This code adapted from GDALDownsampleChunk32R_Mode() in
// gcore/overview.cpp.
if (nAlgo == GWKAOM_Fmode) // int32 or float.
{
// Does it make sense it makes to run a
// majority filter on floating point data? But, here it
// is for the sake of compatibility. It won't look
// right on RGB images by the nature of the filter.
int iMaxInd = 0;
int iMaxVal = -1;
int i = 0;
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
iSrcOffset =
iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) *
nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
continue;
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
const float fVal =
static_cast<float>(dfValueRealTmp);
// Check array for existing entry.
for (i = 0; i < iMaxInd; ++i)
if (pafRealVals[i] == fVal &&
++panRealSums[i] >
panRealSums[iMaxVal])
{
iMaxVal = i;
break;
}
// Add to arr if entry not already there.
if (i == iMaxInd)
{
pafRealVals[iMaxInd] = fVal;
panRealSums[iMaxInd] = 1;
if (iMaxVal < 0)
iMaxVal = iMaxInd;
++iMaxInd;
}
}
}
}
if (iMaxVal != -1)
{
dfValueReal = pafRealVals[iMaxVal];
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal *
poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
dfBandDensity = 1;
bHasFoundDensity = true;
}
}
else // byte or int16.
{
int nMaxVal = 0;
int iMaxInd = -1;
memset(panVals, 0, nBins * sizeof(int));
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
iSrcOffset =
iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) *
nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
continue;
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
const int nVal =
static_cast<int>(dfValueRealTmp);
if (++panVals[nVal + nBinsOffset] > nMaxVal)
{
// Sum the density.
// Is it the most common value so far?
iMaxInd = nVal;
nMaxVal = panVals[nVal + nBinsOffset];
}
}
}
}
if (iMaxInd != -1)
{
dfValueReal = iMaxInd;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal *
poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
dfBandDensity = 1;
bHasFoundDensity = true;
}
}
} // GRA_Mode.
else if (nAlgo == GWKAOM_Max)
// poWK->eResample == GRA_Max.
{
bool bFoundValid = false;
double dfTotalReal = std::numeric_limits<double>::lowest();
// This code adapted from nAlgo 1 method, GRA_Average.
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
iSrcOffset = iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
{
continue;
}
// Returns pixel value if it is not no data.
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
bFoundValid = true;
if (dfTotalReal < dfValueRealTmp)
{
dfTotalReal = dfValueRealTmp;
}
}
}
}
if (bFoundValid)
{
dfValueReal = dfTotalReal;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
dfBandDensity = 1;
bHasFoundDensity = true;
}
} // GRA_Max.
else if (nAlgo == GWKAOM_Min)
// poWK->eResample == GRA_Min.
{
bool bFoundValid = false;
double dfTotalReal = std::numeric_limits<double>::max();
// This code adapted from nAlgo 1 method, GRA_Average.
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
iSrcOffset = iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
{
continue;
}
// Returns pixel value if it is not no data.
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
bFoundValid = true;
if (dfTotalReal > dfValueRealTmp)
{
dfTotalReal = dfValueRealTmp;
}
}
}
}
if (bFoundValid)
{
dfValueReal = dfTotalReal;
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
dfBandDensity = 1;
bHasFoundDensity = true;
}
} // GRA_Min.
else if (nAlgo == GWKAOM_Quant)
// poWK->eResample == GRA_Med | GRA_Q1 | GRA_Q3.
{
bool bFoundValid = false;
std::vector<double> dfRealValuesTmp;
// This code adapted from nAlgo 1 method, GRA_Average.
for (int iSrcY = iSrcYMin; iSrcY < iSrcYMax; iSrcY++)
{
iSrcOffset = iSrcXMin +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
for (int iSrcX = iSrcXMin; iSrcX < iSrcXMax;
iSrcX++, iSrcOffset++)
{
if (bWrapOverX)
iSrcOffset =
(iSrcX % nSrcXSize) +
static_cast<GPtrDiff_t>(iSrcY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid,
iSrcOffset))
{
continue;
}
// Returns pixel value if it is not no data.
if (GWKGetPixelValue(
poWK, iBand, iSrcOffset, &dfBandDensity,
&dfValueRealTmp, &dfValueImagTmp) &&
dfBandDensity > BAND_DENSITY_THRESHOLD)
{
bFoundValid = true;
dfRealValuesTmp.push_back(dfValueRealTmp);
}
}
}
if (bFoundValid)
{
std::sort(dfRealValuesTmp.begin(),
dfRealValuesTmp.end());
int quantIdx = static_cast<int>(
std::ceil(quant * dfRealValuesTmp.size() - 1));
dfValueReal = dfRealValuesTmp[quantIdx];
if (poWK->bApplyVerticalShift)
{
if (!std::isfinite(padfZ[iDstX]))
continue;
// Subtract padfZ[] since the coordinate
// transformation is from target to source
dfValueReal =
dfValueReal * poWK->dfMultFactorVerticalShift -
padfZ[iDstX];
}
dfBandDensity = 1;
bHasFoundDensity = true;
dfRealValuesTmp.clear();
}
} // Quantile.
/* --------------------------------------------------------------------
*/
/* We have a computed value from the source. Now apply it
* to */
/* the destination pixel. */
/* --------------------------------------------------------------------
*/
if (bHasFoundDensity)
{
// TODO: Should we compute dfBandDensity in fct of
// nCount/nCount2, or use as a threshold to set the dest
// value?
// dfBandDensity = (float) nCount / nCount2;
// if( (float) nCount / nCount2 > 0.1 )
// or fix gdalwarp crop_to_cutline to crop partially
// overlapping pixels.
GWKSetPixelValue(poWK, iBand, iDstOffset, dfBandDensity,
dfValueReal, dfValueImag);
}
}
if (!bHasFoundDensity)
continue;
/* --------------------------------------------------------------------
*/
/* Update destination density/validity masks. */
/* --------------------------------------------------------------------
*/
GWKOverlayDensity(poWK, iDstOffset, dfDensity);
if (poWK->panDstValid != nullptr)
{
CPLMaskSet(poWK->panDstValid, iDstOffset);
}
} /* Next iDstX */
/* --------------------------------------------------------------------
*/
/* Report progress to the user, and optionally cancel out. */
/* --------------------------------------------------------------------
*/
if (psJob->pfnProgress && psJob->pfnProgress(psJob))
break;
}
/* -------------------------------------------------------------------- */
/* Cleanup and return. */
/* -------------------------------------------------------------------- */
CPLFree(padfX);
CPLFree(padfY);
CPLFree(padfZ);
CPLFree(padfX2);
CPLFree(padfY2);
CPLFree(padfZ2);
CPLFree(pabSuccess);
CPLFree(pabSuccess2);
VSIFree(panVals);
VSIFree(pafRealVals);
VSIFree(panRealSums);
if (bIsComplex)
{
VSIFree(pafImagVals);
VSIFree(panImagSums);
}
}
/************************************************************************/
/* getOrientation() */
/************************************************************************/
typedef std::pair<double, double> XYPair;
// Returns 1 whether (p1,p2,p3) is clockwise oriented,
// -1 if it is counter-clockwise oriented,
// or 0 if it is colinear.
static int getOrientation(const XYPair &p1, const XYPair &p2, const XYPair &p3)
{
const double p1x = p1.first;
const double p1y = p1.second;
const double p2x = p2.first;
const double p2y = p2.second;
const double p3x = p3.first;
const double p3y = p3.second;
const double val = (p2y - p1y) * (p3x - p2x) - (p2x - p1x) * (p3y - p2y);
if (std::abs(val) < 1e-20)
return 0;
else if (val > 0)
return 1;
else
return -1;
}
/************************************************************************/
/* isConvex() */
/************************************************************************/
typedef std::vector<XYPair> XYPoly;
// poly must be closed
static bool isConvex(const XYPoly &poly)
{
const size_t n = poly.size();
size_t i = 0;
int last_orientation = getOrientation(poly[i], poly[i + 1], poly[i + 2]);
++i;
for (; i < n - 2; ++i)
{
const int orientation =
getOrientation(poly[i], poly[i + 1], poly[i + 2]);
if (orientation != 0)
{
if (last_orientation == 0)
last_orientation = orientation;
else if (orientation != last_orientation)
return false;
}
}
return true;
}
/************************************************************************/
/* pointIntersectsConvexPoly() */
/************************************************************************/
// Returns whether xy intersects poly, that must be closed and convex.
static bool pointIntersectsConvexPoly(const XYPair &xy, const XYPoly &poly)
{
const size_t n = poly.size();
double dx1 = xy.first - poly[0].first;
double dy1 = xy.second - poly[0].second;
double dx2 = poly[1].first - poly[0].first;
double dy2 = poly[1].second - poly[0].second;
double prevCrossProduct = dx1 * dy2 - dx2 * dy1;
// Check if the point remains on the same side (left/right) of all edges
for (size_t i = 2; i < n; i++)
{
dx1 = xy.first - poly[i - 1].first;
dy1 = xy.second - poly[i - 1].second;
dx2 = poly[i].first - poly[i - 1].first;
dy2 = poly[i].second - poly[i - 1].second;
double crossProduct = dx1 * dy2 - dx2 * dy1;
if (std::abs(prevCrossProduct) < 1e-20)
prevCrossProduct = crossProduct;
else if (prevCrossProduct * crossProduct < 0)
return false;
}
return true;
}
/************************************************************************/
/* getIntersection() */
/************************************************************************/
/* Returns intersection of [p1,p2] with [p3,p4], if
* it is a single point, and the 2 segments are not colinear.
*/
static bool getIntersection(const XYPair &p1, const XYPair &p2,
const XYPair &p3, const XYPair &p4, XYPair &xy)
{
const double x1 = p1.first;
const double y1 = p1.second;
const double x2 = p2.first;
const double y2 = p2.second;
const double x3 = p3.first;
const double y3 = p3.second;
const double x4 = p4.first;
const double y4 = p4.second;
const double t_num = (x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4);
const double denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (t_num * denom < 0 || std::abs(t_num) > std::abs(denom) || denom == 0)
return false;
const double u_num = (x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2);
if (u_num * denom < 0 || std::abs(u_num) > std::abs(denom))
return false;
const double t = t_num / denom;
xy.first = x1 + t * (x2 - x1);
xy.second = y1 + t * (y2 - y1);
return true;
}
/************************************************************************/
/* getConvexPolyIntersection() */
/************************************************************************/
// poly1 and poly2 must be closed and convex.
// The returned intersection will not necessary be closed.
static void getConvexPolyIntersection(const XYPoly &poly1, const XYPoly &poly2,
XYPoly &intersection)
{
intersection.clear();
// Add all points of poly1 inside poly2
for (size_t i = 0; i < poly1.size() - 1; ++i)
{
if (pointIntersectsConvexPoly(poly1[i], poly2))
intersection.push_back(poly1[i]);
}
if (intersection.size() == poly1.size() - 1)
{
// poly1 is inside poly2
return;
}
// Add all points of poly2 inside poly1
for (size_t i = 0; i < poly2.size() - 1; ++i)
{
if (pointIntersectsConvexPoly(poly2[i], poly1))
intersection.push_back(poly2[i]);
}
// Compute the intersection of all edges of both polygons
XYPair xy;
for (size_t i1 = 0; i1 < poly1.size() - 1; ++i1)
{
for (size_t i2 = 0; i2 < poly2.size() - 1; ++i2)
{
if (getIntersection(poly1[i1], poly1[i1 + 1], poly2[i2],
poly2[i2 + 1], xy))
{
intersection.push_back(xy);
}
}
}
if (intersection.empty())
return;
// Find lowest-left point in intersection set
double lowest_x = std::numeric_limits<double>::max();
double lowest_y = std::numeric_limits<double>::max();
for (const auto &pair : intersection)
{
const double x = pair.first;
const double y = pair.second;
if (y < lowest_y || (y == lowest_y && x < lowest_x))
{
lowest_x = x;
lowest_y = y;
}
}
const auto sortFunc = [&](const XYPair &p1, const XYPair &p2)
{
const double p1x_diff = p1.first - lowest_x;
const double p1y_diff = p1.second - lowest_y;
const double p2x_diff = p2.first - lowest_x;
const double p2y_diff = p2.second - lowest_y;
if (p2y_diff == 0.0 && p1y_diff == 0.0)
{
if (p1x_diff >= 0)
{
if (p2x_diff >= 0)
return p1.first < p2.first;
return true;
}
else
{
if (p2x_diff >= 0)
return false;
return p1.first < p2.first;
}
}
if (p2x_diff == 0.0 && p1x_diff == 0.0)
return p1.second < p2.second;
double tan_p1;
if (p1x_diff == 0.0)
tan_p1 = p1y_diff == 0.0 ? 0.0 : std::numeric_limits<double>::max();
else
tan_p1 = p1y_diff / p1x_diff;
double tan_p2;
if (p2x_diff == 0.0)
tan_p2 = p2y_diff == 0.0 ? 0.0 : std::numeric_limits<double>::max();
else
tan_p2 = p2y_diff / p2x_diff;
if (tan_p1 >= 0)
{
if (tan_p2 >= 0)
return tan_p1 < tan_p2;
else
return true;
}
else
{
if (tan_p2 >= 0)
return false;
else
return tan_p1 < tan_p2;
}
};
// Sort points by increasing atan2(y-lowest_y, x-lowest_x) to form a convex
// hull
std::sort(intersection.begin(), intersection.end(), sortFunc);
// Remove duplicated points
size_t j = 1;
for (size_t i = 1; i < intersection.size(); ++i)
{
if (intersection[i] != intersection[i - 1])
{
if (j < i)
intersection[j] = intersection[i];
++j;
}
}
intersection.resize(j);
}
/************************************************************************/
/* getArea() */
/************************************************************************/
// poly may or may not be closed.
static double getArea(const XYPoly &poly)
{
// CPLAssert(poly.size() >= 2);
const size_t nPointCount = poly.size();
double dfAreaSum =
poly[0].first * (poly[1].second - poly[nPointCount - 1].second);
for (size_t i = 1; i < nPointCount - 1; i++)
{
dfAreaSum += poly[i].first * (poly[i + 1].second - poly[i - 1].second);
}
dfAreaSum += poly[nPointCount - 1].first *
(poly[0].second - poly[nPointCount - 2].second);
return 0.5 * std::fabs(dfAreaSum);
}
/************************************************************************/
/* GWKSumPreserving() */
/************************************************************************/
static void GWKSumPreservingThread(void *pData);
static CPLErr GWKSumPreserving(GDALWarpKernel *poWK)
{
return GWKRun(poWK, "GWKSumPreserving", GWKSumPreservingThread);
}
static void GWKSumPreservingThread(void *pData)
{
GWKJobStruct *psJob = static_cast<GWKJobStruct *>(pData);
GDALWarpKernel *poWK = psJob->poWK;
const int iYMin = psJob->iYMin;
const int iYMax = psJob->iYMax;
const bool bIsAffineNoRotation =
GDALTransformIsAffineNoRotation(poWK->pfnTransformer,
poWK->pTransformerArg) &&
// for debug/testing purposes
CPLTestBool(
CPLGetConfigOption("GDAL_WARP_USE_AFFINE_OPTIMIZATION", "YES"));
const int nDstXSize = poWK->nDstXSize;
const int nSrcXSize = poWK->nSrcXSize;
const int nSrcYSize = poWK->nSrcYSize;
std::vector<double> adfX0(nSrcXSize + 1);
std::vector<double> adfY0(nSrcXSize + 1);
std::vector<double> adfZ0(nSrcXSize + 1);
std::vector<double> adfX1(nSrcXSize + 1);
std::vector<double> adfY1(nSrcXSize + 1);
std::vector<double> adfZ1(nSrcXSize + 1);
std::vector<int> abSuccess0(nSrcXSize + 1);
std::vector<int> abSuccess1(nSrcXSize + 1);
CPLRectObj sGlobalBounds;
sGlobalBounds.minx = -2 * poWK->dfXScale;
sGlobalBounds.miny = iYMin - 2 * poWK->dfYScale;
sGlobalBounds.maxx = nDstXSize + 2 * poWK->dfXScale;
sGlobalBounds.maxy = iYMax + 2 * poWK->dfYScale;
CPLQuadTree *hQuadTree = CPLQuadTreeCreate(&sGlobalBounds, nullptr);
struct SourcePixel
{
int iSrcX;
int iSrcY;
// Coordinates of source pixel in target pixel coordinates
double dfDstX0;
double dfDstY0;
double dfDstX1;
double dfDstY1;
double dfDstX2;
double dfDstY2;
double dfDstX3;
double dfDstY3;
// Source pixel total area (might be larger than the one described
// by above coordinates, if the pixel was crossing the antimeridian
// and split)
double dfArea;
};
std::vector<SourcePixel> sourcePixels;
XYPoly discontinuityLeft(5);
XYPoly discontinuityRight(5);
/* ==================================================================== */
/* First pass: transform the 4 corners of each potential */
/* contributing source pixel to target pixel coordinates. */
/* ==================================================================== */
// Special case for top line
{
int iY = 0;
for (int iX = 0; iX <= nSrcXSize; ++iX)
{
adfX1[iX] = iX + poWK->nSrcXOff;
adfY1[iX] = iY + poWK->nSrcYOff;
adfZ1[iX] = 0;
}
poWK->pfnTransformer(psJob->pTransformerArg, FALSE, nSrcXSize + 1,
adfX1.data(), adfY1.data(), adfZ1.data(),
abSuccess1.data());
for (int iX = 0; iX <= nSrcXSize; ++iX)
{
if (abSuccess1[iX] && !std::isfinite(adfX1[iX]))
abSuccess1[iX] = FALSE;
else
{
adfX1[iX] -= poWK->nDstXOff;
adfY1[iX] -= poWK->nDstYOff;
}
}
}
const auto getInsideXSign = [poWK, nDstXSize](double dfX)
{
return dfX - poWK->nDstXOff >= -2 * poWK->dfXScale &&
dfX - poWK->nDstXOff <= nDstXSize + 2 * poWK->dfXScale
? 1
: -1;
};
const auto FindDiscontinuity =
[poWK, psJob, getInsideXSign](
double dfXLeft, double dfXRight, double dfY,
int XLeftReprojectedInsideSign, double &dfXMidReprojectedLeft,
double &dfXMidReprojectedRight, double &dfYMidReprojected)
{
for (int i = 0; i < 10 && dfXRight - dfXLeft > 1e-8; ++i)
{
double dfXMid = (dfXLeft + dfXRight) / 2;
double dfXMidReprojected = dfXMid;
dfYMidReprojected = dfY;
double dfZ = 0;
int nSuccess = 0;
poWK->pfnTransformer(psJob->pTransformerArg, FALSE, 1,
&dfXMidReprojected, &dfYMidReprojected, &dfZ,
&nSuccess);
if (XLeftReprojectedInsideSign != getInsideXSign(dfXMidReprojected))
{
dfXRight = dfXMid;
dfXMidReprojectedRight = dfXMidReprojected;
}
else
{
dfXLeft = dfXMid;
dfXMidReprojectedLeft = dfXMidReprojected;
}
}
};
for (int iY = 0; iY < nSrcYSize; ++iY)
{
std::swap(adfX0, adfX1);
std::swap(adfY0, adfY1);
std::swap(adfZ0, adfZ1);
std::swap(abSuccess0, abSuccess1);
for (int iX = 0; iX <= nSrcXSize; ++iX)
{
adfX1[iX] = iX + poWK->nSrcXOff;
adfY1[iX] = iY + 1 + poWK->nSrcYOff;
adfZ1[iX] = 0;
}
poWK->pfnTransformer(psJob->pTransformerArg, FALSE, nSrcXSize + 1,
adfX1.data(), adfY1.data(), adfZ1.data(),
abSuccess1.data());
for (int iX = 0; iX <= nSrcXSize; ++iX)
{
if (abSuccess1[iX] && !std::isfinite(adfX1[iX]))
abSuccess1[iX] = FALSE;
else
{
adfX1[iX] -= poWK->nDstXOff;
adfY1[iX] -= poWK->nDstYOff;
}
}
for (int iX = 0; iX < nSrcXSize; ++iX)
{
if (abSuccess0[iX] && abSuccess0[iX + 1] && abSuccess1[iX] &&
abSuccess1[iX + 1])
{
/* --------------------------------------------------------------------
*/
/* Do not try to apply transparent source pixels to the
* destination.*/
/* --------------------------------------------------------------------
*/
const auto iSrcOffset =
iX + static_cast<GPtrDiff_t>(iY) * nSrcXSize;
if (poWK->panUnifiedSrcValid != nullptr &&
!CPLMaskGet(poWK->panUnifiedSrcValid, iSrcOffset))
{
continue;
}
if (poWK->pafUnifiedSrcDensity != nullptr)
{
if (poWK->pafUnifiedSrcDensity[iSrcOffset] <
SRC_DENSITY_THRESHOLD)
continue;
}
SourcePixel sp;
sp.dfArea = 0;
sp.dfDstX0 = adfX0[iX];
sp.dfDstY0 = adfY0[iX];
sp.dfDstX1 = adfX0[iX + 1];
sp.dfDstY1 = adfY0[iX + 1];
sp.dfDstX2 = adfX1[iX + 1];
sp.dfDstY2 = adfY1[iX + 1];
sp.dfDstX3 = adfX1[iX];
sp.dfDstY3 = adfY1[iX];
// Detect pixel that likely cross the anti-meridian and
// introduce a discontinuity when reprojected.
if (getInsideXSign(adfX0[iX]) !=
getInsideXSign(adfX0[iX + 1]) &&
getInsideXSign(adfX0[iX]) == getInsideXSign(adfX1[iX]) &&
getInsideXSign(adfX0[iX + 1]) ==
getInsideXSign(adfX1[iX + 1]) &&
(adfY1[iX] - adfY0[iX]) * (adfY1[iX + 1] - adfY0[iX + 1]) >
0)
{
double dfXMidReprojectedLeftTop = 0;
double dfXMidReprojectedRightTop = 0;
double dfYMidReprojectedTop = 0;
FindDiscontinuity(
iX + poWK->nSrcXOff, iX + poWK->nSrcXOff + 1,
iY + poWK->nSrcYOff, getInsideXSign(adfX0[iX]),
dfXMidReprojectedLeftTop, dfXMidReprojectedRightTop,
dfYMidReprojectedTop);
double dfXMidReprojectedLeftBottom = 0;
double dfXMidReprojectedRightBottom = 0;
double dfYMidReprojectedBottom = 0;
FindDiscontinuity(
iX + poWK->nSrcXOff, iX + poWK->nSrcXOff + 1,
iY + poWK->nSrcYOff + 1, getInsideXSign(adfX1[iX]),
dfXMidReprojectedLeftBottom,
dfXMidReprojectedRightBottom, dfYMidReprojectedBottom);
discontinuityLeft[0] = XYPair(adfX0[iX], adfY0[iX]);
discontinuityLeft[1] =
XYPair(dfXMidReprojectedLeftTop, dfYMidReprojectedTop);
discontinuityLeft[2] = XYPair(dfXMidReprojectedLeftBottom,
dfYMidReprojectedBottom);
discontinuityLeft[3] = XYPair(adfX1[iX], adfY1[iX]);
discontinuityLeft[4] = XYPair(adfX0[iX], adfY0[iX]);
discontinuityRight[0] =
XYPair(adfX0[iX + 1], adfY0[iX + 1]);
discontinuityRight[1] =
XYPair(dfXMidReprojectedRightTop, dfYMidReprojectedTop);
discontinuityRight[2] = XYPair(dfXMidReprojectedRightBottom,
dfYMidReprojectedBottom);
discontinuityRight[3] =
XYPair(adfX1[iX + 1], adfY1[iX + 1]);
discontinuityRight[4] =
XYPair(adfX0[iX + 1], adfY0[iX + 1]);
sp.dfArea = getArea(discontinuityLeft) +
getArea(discontinuityRight);
if (getInsideXSign(adfX0[iX]) >= 1)
{
sp.dfDstX1 = dfXMidReprojectedLeftTop;
sp.dfDstY1 = dfYMidReprojectedTop;
sp.dfDstX2 = dfXMidReprojectedLeftBottom;
sp.dfDstY2 = dfYMidReprojectedBottom;
}
else
{
sp.dfDstX0 = dfXMidReprojectedRightTop;
sp.dfDstY0 = dfYMidReprojectedTop;
sp.dfDstX3 = dfXMidReprojectedRightBottom;
sp.dfDstY3 = dfYMidReprojectedBottom;
}
}
// Bounding box of source pixel (expressed in target pixel
// coordinates)
CPLRectObj sRect;
sRect.minx = std::min(std::min(sp.dfDstX0, sp.dfDstX1),
std::min(sp.dfDstX2, sp.dfDstX3));
sRect.miny = std::min(std::min(sp.dfDstY0, sp.dfDstY1),
std::min(sp.dfDstY2, sp.dfDstY3));
sRect.maxx = std::max(std::max(sp.dfDstX0, sp.dfDstX1),
std::max(sp.dfDstX2, sp.dfDstX3));
sRect.maxy = std::max(std::max(sp.dfDstY0, sp.dfDstY1),
std::max(sp.dfDstY2, sp.dfDstY3));
if (!(sRect.minx < nDstXSize && sRect.maxx > 0 &&
sRect.miny < iYMax && sRect.maxy > iYMin))
{
continue;
}
sp.iSrcX = iX;
sp.iSrcY = iY;
if (!bIsAffineNoRotation)
{
// Check polygon validity (no self-crossing)
XYPair xy;
if (getIntersection(XYPair(sp.dfDstX0, sp.dfDstY0),
XYPair(sp.dfDstX1, sp.dfDstY1),
XYPair(sp.dfDstX2, sp.dfDstY2),
XYPair(sp.dfDstX3, sp.dfDstY3), xy) ||
getIntersection(XYPair(sp.dfDstX1, sp.dfDstY1),
XYPair(sp.dfDstX2, sp.dfDstY2),
XYPair(sp.dfDstX0, sp.dfDstY0),
XYPair(sp.dfDstX3, sp.dfDstY3), xy))
{
continue;
}
}
CPLQuadTreeInsertWithBounds(
hQuadTree,
reinterpret_cast<void *>(
static_cast<uintptr_t>(sourcePixels.size())),
&sRect);
sourcePixels.push_back(sp);
}
}
}
std::vector<double> adfRealValue(poWK->nBands);
std::vector<double> adfImagValue(poWK->nBands);
std::vector<double> adfBandDensity(poWK->nBands);
std::vector<double> adfWeight(poWK->nBands);
#ifdef CHECK_SUM_WITH_GEOS
auto hGEOSContext = OGRGeometry::createGEOSContext();
auto seq1 = GEOSCoordSeq_create_r(hGEOSContext, 5, 2);
GEOSCoordSeq_setXY_r(hGEOSContext, seq1, 0, 0.0, 0.0);
GEOSCoordSeq_setXY_r(hGEOSContext, seq1, 1, 1.0, 0.0);
GEOSCoordSeq_setXY_r(hGEOSContext, seq1, 2, 1.0, 1.0);
GEOSCoordSeq_setXY_r(hGEOSContext, seq1, 3, 0.0, 1.0);
GEOSCoordSeq_setXY_r(hGEOSContext, seq1, 4, 0.0, 0.0);
auto hLR1 = GEOSGeom_createLinearRing_r(hGEOSContext, seq1);
auto hP1 = GEOSGeom_createPolygon_r(hGEOSContext, hLR1, nullptr, 0);
auto seq2 = GEOSCoordSeq_create_r(hGEOSContext, 5, 2);
auto hLR2 = GEOSGeom_createLinearRing_r(hGEOSContext, seq2);
auto hP2 = GEOSGeom_createPolygon_r(hGEOSContext, hLR2, nullptr, 0);
#endif
const XYPoly xy1{
{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}, {0.0, 1.0}, {0.0, 0.0}};
XYPoly xy2(5);
XYPoly xy2_triangle(4);
XYPoly intersection;
/* ==================================================================== */
/* Loop over output lines. */
/* ==================================================================== */
for (int iDstY = iYMin; iDstY < iYMax; iDstY++)
{
CPLRectObj sRect;
sRect.miny = iDstY;
sRect.maxy = iDstY + 1;
/* ====================================================================
*/
/* Loop over pixels in output scanline. */
/* ====================================================================
*/
for (int iDstX = 0; iDstX < nDstXSize; iDstX++)
{
sRect.minx = iDstX;
sRect.maxx = iDstX + 1;
int nSourcePixels = 0;
void **pahSourcePixel =
CPLQuadTreeSearch(hQuadTree, &sRect, &nSourcePixels);
if (nSourcePixels == 0)
{
CPLFree(pahSourcePixel);
continue;
}
std::fill(adfRealValue.begin(), adfRealValue.end(), 0);
std::fill(adfImagValue.begin(), adfImagValue.end(), 0);
std::fill(adfBandDensity.begin(), adfBandDensity.end(), 0);
std::fill(adfWeight.begin(), adfWeight.end(), 0);
double dfDensity = 0;
double dfTotalWeight = 0;
/* ====================================================================
*/
/* Iterate over each contributing source pixel to add its
*/
/* value weighed by the ratio of the area of its
* intersection */
/* with the target pixel divided by the area of the source
*/
/* pixel. */
/* ====================================================================
*/
for (int i = 0; i < nSourcePixels; ++i)
{
const int iSourcePixel = static_cast<int>(
reinterpret_cast<uintptr_t>(pahSourcePixel[i]));
auto &sp = sourcePixels[iSourcePixel];
double dfWeight = 0.0;
if (bIsAffineNoRotation)
{
// Optimization since the source pixel is a rectangle in
// target pixel coordinates
double dfSrcMinX = std::min(sp.dfDstX0, sp.dfDstX2);
double dfSrcMaxX = std::max(sp.dfDstX0, sp.dfDstX2);
double dfSrcMinY = std::min(sp.dfDstY0, sp.dfDstY2);
double dfSrcMaxY = std::max(sp.dfDstY0, sp.dfDstY2);
double dfIntersMinX = std::max<double>(dfSrcMinX, iDstX);
double dfIntersMaxX = std::min(dfSrcMaxX, iDstX + 1.0);
double dfIntersMinY = std::max<double>(dfSrcMinY, iDstY);
double dfIntersMaxY = std::min(dfSrcMaxY, iDstY + 1.0);
dfWeight =
((dfIntersMaxX - dfIntersMinX) *
(dfIntersMaxY - dfIntersMinY)) /
((dfSrcMaxX - dfSrcMinX) * (dfSrcMaxY - dfSrcMinY));
}
else
{
// Compute the polygon of the source pixel in target pixel
// coordinates, and shifted to the target pixel (unit square
// coordinates)
xy2[0] = {sp.dfDstX0 - iDstX, sp.dfDstY0 - iDstY};
xy2[1] = {sp.dfDstX1 - iDstX, sp.dfDstY1 - iDstY};
xy2[2] = {sp.dfDstX2 - iDstX, sp.dfDstY2 - iDstY};
xy2[3] = {sp.dfDstX3 - iDstX, sp.dfDstY3 - iDstY};
xy2[4] = {sp.dfDstX0 - iDstX, sp.dfDstY0 - iDstY};
if (isConvex(xy2))
{
getConvexPolyIntersection(xy1, xy2, intersection);
if (intersection.size() >= 3)
{
dfWeight = getArea(intersection);
}
}
else
{
// Split xy2 into 2 triangles.
xy2_triangle[0] = xy2[0];
xy2_triangle[1] = xy2[1];
xy2_triangle[2] = xy2[2];
xy2_triangle[3] = xy2[0];
getConvexPolyIntersection(xy1, xy2_triangle,
intersection);
if (intersection.size() >= 3)
{
dfWeight = getArea(intersection);
}
xy2_triangle[1] = xy2[2];
xy2_triangle[2] = xy2[3];
getConvexPolyIntersection(xy1, xy2_triangle,
intersection);
if (intersection.size() >= 3)
{
dfWeight += getArea(intersection);
}
}
if (dfWeight > 0.0)
{
if (sp.dfArea == 0)
sp.dfArea = getArea(xy2);
dfWeight /= sp.dfArea;
}
#ifdef CHECK_SUM_WITH_GEOS
GEOSCoordSeq_setXY_r(hGEOSContext, seq2, 0,
sp.dfDstX0 - iDstX,
sp.dfDstY0 - iDstY);
GEOSCoordSeq_setXY_r(hGEOSContext, seq2, 1,
sp.dfDstX1 - iDstX,
sp.dfDstY1 - iDstY);
GEOSCoordSeq_setXY_r(hGEOSContext, seq2, 2,
sp.dfDstX2 - iDstX,
sp.dfDstY2 - iDstY);
GEOSCoordSeq_setXY_r(hGEOSContext, seq2, 3,
sp.dfDstX3 - iDstX,
sp.dfDstY3 - iDstY);
GEOSCoordSeq_setXY_r(hGEOSContext, seq2, 4,
sp.dfDstX0 - iDstX,
sp.dfDstY0 - iDstY);
double dfWeightGEOS = 0.0;
auto hIntersection =
GEOSIntersection_r(hGEOSContext, hP1, hP2);
if (hIntersection)
{
double dfIntersArea = 0.0;
if (GEOSArea_r(hGEOSContext, hIntersection,
&dfIntersArea) &&
dfIntersArea > 0)
{
double dfSourceArea = 0.0;
if (GEOSArea_r(hGEOSContext, hP2, &dfSourceArea))
{
dfWeightGEOS = dfIntersArea / dfSourceArea;
}
}
GEOSGeom_destroy_r(hGEOSContext, hIntersection);
}
if (fabs(dfWeight - dfWeightGEOS) > 1e-5 * dfWeightGEOS)
{
/* ok */ printf("dfWeight=%f dfWeightGEOS=%f\n",
dfWeight, dfWeightGEOS);
printf("xy2: "); // ok
for (const auto &xy : xy2)
printf("[%f, %f], ", xy.first, xy.second); // ok
printf("\n"); // ok
printf("intersection: "); // ok
for (const auto &xy : intersection)
printf("[%f, %f], ", xy.first, xy.second); // ok
printf("\n"); // ok
}
#endif
}
if (dfWeight > 0.0)
{
const GPtrDiff_t iSrcOffset =
sp.iSrcX +
static_cast<GPtrDiff_t>(sp.iSrcY) * nSrcXSize;
dfTotalWeight += dfWeight;
if (poWK->pafUnifiedSrcDensity != nullptr)
{
dfDensity +=
dfWeight * poWK->pafUnifiedSrcDensity[iSrcOffset];
}
else
{
dfDensity += dfWeight;
}
for (int iBand = 0; iBand < poWK->nBands; ++iBand)
{
// Returns pixel value if it is not no data.
double dfBandDensity;
double dfRealValue;
double dfImagValue;
if (!(GWKGetPixelValue(poWK, iBand, iSrcOffset,
&dfBandDensity, &dfRealValue,
&dfImagValue) &&
dfBandDensity > BAND_DENSITY_THRESHOLD))
{
continue;
}
adfRealValue[iBand] += dfRealValue * dfWeight;
adfImagValue[iBand] += dfImagValue * dfWeight;
adfBandDensity[iBand] += dfBandDensity * dfWeight;
adfWeight[iBand] += dfWeight;
}
}
}
CPLFree(pahSourcePixel);
/* --------------------------------------------------------------------
*/
/* Update destination pixel value. */
/* --------------------------------------------------------------------
*/
bool bHasFoundDensity = false;
const GPtrDiff_t iDstOffset =
iDstX + static_cast<GPtrDiff_t>(iDstY) * nDstXSize;
for (int iBand = 0; iBand < poWK->nBands; ++iBand)
{
if (adfWeight[iBand] > 0)
{
const double dfBandDensity =
adfBandDensity[iBand] / adfWeight[iBand];
if (dfBandDensity > BAND_DENSITY_THRESHOLD)
{
bHasFoundDensity = true;
GWKSetPixelValue(poWK, iBand, iDstOffset, dfBandDensity,
adfRealValue[iBand],
adfImagValue[iBand]);
}
}
}
if (!bHasFoundDensity)
continue;
/* --------------------------------------------------------------------
*/
/* Update destination density/validity masks. */
/* --------------------------------------------------------------------
*/
GWKOverlayDensity(poWK, iDstOffset, dfDensity / dfTotalWeight);
if (poWK->panDstValid != nullptr)
{
CPLMaskSet(poWK->panDstValid, iDstOffset);
}
}
/* --------------------------------------------------------------------
*/
/* Report progress to the user, and optionally cancel out. */
/* --------------------------------------------------------------------
*/
if (psJob->pfnProgress && psJob->pfnProgress(psJob))
break;
}
#ifdef CHECK_SUM_WITH_GEOS
GEOSGeom_destroy_r(hGEOSContext, hP1);
GEOSGeom_destroy_r(hGEOSContext, hP2);
OGRGeometry::freeGEOSContext(hGEOSContext);
#endif
CPLQuadTreeDestroy(hQuadTree);
}
|