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
|
//##########################################################################
//# #
//# CLOUDCOMPARE #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) #
//# #
//##########################################################################
#ifdef CC_SHP_SUPPORT
#include "ShpFilter.h"
//Local
#include "ui_saveSHPFileDlg.h"
#include "ui_importDBFFieldDlg.h"
#include "ShpDBFFields.h"
//qCC_db
#include <ccPolyline.h>
#include <ccGenericPointCloud.h>
#include <ccGenericMesh.h>
#include <ccPointCloud.h>
#include <ccScalarField.h>
#include <ccProgressDialog.h>
#include <ccMesh.h>
//Qt
#include <QFileInfo>
//CCLib
#include <MeshSamplingTools.h>
//System
#include <array>
using FieldIndexAndName = QPair<int, QString>;
//Specific value for NaN
static const double ESRI_NO_DATA = -1.0e38;
static const int32_t ESRI_SHAPE_FILE_CODE = 9994;
static const size_t ESRI_HEADER_SIZE = 100;
static const size_t ESRI_FILE_LENGTH_OFFSET = 24;
//! ESRI Shapefile's shape types
enum class ESRI_SHAPE_TYPE : int32_t
{
NULL_SHAPE = 0,
//below this point are 2D types
POINT = 1,
POLYLINE = 3,
POLYGON = 5,
MULTI_POINT = 8,
//below this point are 3D types
POINT_Z = 11,
POLYLINE_Z = 13,
POLYGON_Z = 15,
MULTI_POINT_Z = 18,
POINT_M = 21,
POLYLINE_M = 23,
POLYGON_M = 25,
MULTI_POINT_M = 28,
MULTI_PATCH = 31
};
//! Returns true if the code corresponds to a valid ESRI Shape Type
/**
* \param code The code to check (typically read from a file)
**/
static inline bool isValidESRIShapeCode(int32_t code)
{
if (code < static_cast<int32_t >(ESRI_SHAPE_TYPE::NULL_SHAPE))
return false;
if (code > static_cast<int32_t >(ESRI_SHAPE_TYPE::MULTI_PATCH))
return false;
switch (static_cast<ESRI_SHAPE_TYPE >(code))
{
case ESRI_SHAPE_TYPE::NULL_SHAPE:
case ESRI_SHAPE_TYPE::POINT:
case ESRI_SHAPE_TYPE::POLYLINE:
case ESRI_SHAPE_TYPE::POLYGON:
case ESRI_SHAPE_TYPE::MULTI_POINT:
case ESRI_SHAPE_TYPE::POINT_Z:
case ESRI_SHAPE_TYPE::POLYLINE_Z:
case ESRI_SHAPE_TYPE::POLYGON_Z:
case ESRI_SHAPE_TYPE::MULTI_POINT_Z:
case ESRI_SHAPE_TYPE::POINT_M:
case ESRI_SHAPE_TYPE::POLYLINE_M:
case ESRI_SHAPE_TYPE::POLYGON_M:
case ESRI_SHAPE_TYPE::MULTI_POINT_M:
case ESRI_SHAPE_TYPE::MULTI_PATCH:
return true;
default:
return false;
}
}
//! Returns whether the shape type contains the 3rd dimensions Z
static inline bool isESRIShape3D(ESRI_SHAPE_TYPE shapeType)
{
switch (shapeType)
{
case ESRI_SHAPE_TYPE::POINT_Z:
case ESRI_SHAPE_TYPE::POLYLINE_Z:
case ESRI_SHAPE_TYPE::POLYGON_Z:
case ESRI_SHAPE_TYPE::MULTI_POINT_Z:
case ESRI_SHAPE_TYPE::MULTI_PATCH:
return true;
default:
return false;
}
}
//! Returns whether the shape type contains the additional measures dimension
static inline bool hasMeasurements(ESRI_SHAPE_TYPE shapeType)
{
switch (shapeType)
{
case ESRI_SHAPE_TYPE::POINT_Z:
case ESRI_SHAPE_TYPE::POLYLINE_Z:
case ESRI_SHAPE_TYPE::POLYGON_Z:
case ESRI_SHAPE_TYPE::MULTI_POINT_Z:
case ESRI_SHAPE_TYPE::POINT_M:
case ESRI_SHAPE_TYPE::POLYLINE_M:
case ESRI_SHAPE_TYPE::POLYGON_M:
case ESRI_SHAPE_TYPE::MULTI_POINT_M:
case ESRI_SHAPE_TYPE::MULTI_PATCH:
return true;
default:
return false;
}
}
enum class ESRI_PART_TYPE : int32_t
{
TRIANGLE_STRIP = 0,
TRIANGLE_FAN = 1,
OUTER_RING = 2,
INNER_RING = 3,
FIRST_RING = 4,
RING = 5,
};
static bool isValidEsriPartType(int32_t code)
{
if (code < static_cast<int32_t >(ESRI_PART_TYPE::TRIANGLE_STRIP))
return false;
if (code > static_cast<int32_t >(ESRI_PART_TYPE::RING))
return false;
switch (static_cast<ESRI_PART_TYPE >(code))
{
case ESRI_PART_TYPE::TRIANGLE_STRIP:
case ESRI_PART_TYPE::TRIANGLE_FAN:
case ESRI_PART_TYPE::INNER_RING:
case ESRI_PART_TYPE::OUTER_RING:
case ESRI_PART_TYPE::FIRST_RING:
case ESRI_PART_TYPE::RING:
return true;
default:
return false;
}
}
static inline bool isESRINoData(double m)
{
return m <= ESRI_NO_DATA;
}
static int32_t sizeofMultiPointZ(size_t numPoints) noexcept
{
size_t recordLength = 0;
recordLength += sizeof(int32_t); // shapeType
recordLength += (4 * sizeof(double)); // x,y bbox
recordLength += sizeof(int32_t); // numPoints
recordLength += (2 * numPoints * sizeof(double)); // xs, ys
recordLength += (2 * sizeof(double)); // zRange
recordLength += (numPoints * sizeof(double)); // zs
recordLength += (2 * sizeof(double)); // mRange
recordLength += (numPoints * sizeof(double)); // Measures
recordLength /= 2; // 16bit words
return static_cast<int32_t>(recordLength);
}
static int32_t sizeofPolyLine(ESRI_SHAPE_TYPE polylineType, size_t numPoints, size_t numParts = 1)
{
switch (polylineType)
{
case ESRI_SHAPE_TYPE::POLYLINE:
case ESRI_SHAPE_TYPE::POLYLINE_M:
case ESRI_SHAPE_TYPE::POLYLINE_Z:
case ESRI_SHAPE_TYPE::POLYGON:
case ESRI_SHAPE_TYPE::POLYGON_M:
case ESRI_SHAPE_TYPE::POLYGON_Z:
break;
default:
throw std::invalid_argument("Type is not a polygon or polyline");
}
size_t recordLength = 0;
recordLength += sizeof(int32_t); // ShapeType
recordLength += (4 * sizeof(double)); // MBR
recordLength += sizeof(int32_t); // nbParts
recordLength += sizeof(int32_t); // nbPoints
recordLength += (numParts * sizeof(int32_t)); // Parts
recordLength += (numPoints * 2 * sizeof(double)); //Points
if (isESRIShape3D(polylineType))
{
recordLength += 2 * sizeof(double);
recordLength += numPoints * sizeof(double);
}
if (hasMeasurements(polylineType))
{
recordLength += 2 * sizeof(double);
recordLength += numPoints * sizeof(double);
}
return static_cast<int32_t>(recordLength / 2);
}
static int32_t sizeofMultipatch(size_t numPoints, size_t numParts = 1)
{
size_t recordSize = 0;
recordSize += sizeof(int32_t); // ShapeType
recordSize += (4 * sizeof(double)); // MBR
recordSize += sizeof(int32_t); // nbParts
recordSize += sizeof(int32_t); // nbPoints
recordSize += (numParts * sizeof(int32_t)); // Parts
recordSize += (numParts * sizeof(int32_t)); // Parts Type
recordSize += (numPoints * 2 * sizeof(double)); //Points
recordSize += (2 * sizeof(double)); // zRange
recordSize += (numPoints) * sizeof(double); // Zs
recordSize += (2 * sizeof(double)); // mRange
recordSize += (numPoints) * sizeof(double); // Measures
return static_cast<int32_t>(recordSize / 2); // 16bit words
}
static bool areVerticesCounterClockwise(const CCLib::GenericIndexedCloudPersist *vertices,
int32_t numPoints,
unsigned char dim1,
unsigned char dim2)
{
//http://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order
//or http://en.wikipedia.org/wiki/Shoelace_formula
double sum = 0.0;
unsigned realNumPoints = vertices->size();
for (int32_t i = 0; i + 1 < numPoints; ++i)
{
CCVector3 P1;
CCVector3 P2;
vertices->getPoint(i, P1);
vertices->getPoint((i + 1) % realNumPoints, P2);
sum += (P2.u[dim1] - P2.u[dim1]) * (P2.u[dim2] + P1.u[dim2]);
}
//negative sum = counter-clockwise
return sum < 0.0;
}
static CCVector2d minMaxOfEnabledScalarField(const CCLib::GenericIndexedCloudPersist *cloud)
{
CCVector2d minMax(std::numeric_limits<double>::max(), std::numeric_limits<double>::min());
if (cloud->isScalarFieldEnabled())
{
for (unsigned i = 0; i < cloud->size(); ++i)
{
auto scalar = static_cast<double>(cloud->getPointScalarValue(i));
minMax.x = std::min(minMax.x, scalar);
minMax.y = std::max(minMax.y, scalar);
}
}
if (minMax.x == std::numeric_limits<double>::max())
{
minMax.x = minMax.y = ESRI_NO_DATA;
}
return minMax;
}
static bool bBoxOfHObjectContainer(const ccHObject::Container& objects, CCVector3d &bbMinCorner, CCVector3d bbMaxCorner)
{
bool isValid = false;
for (ccHObject *obj : objects)
{
CCVector3d minC;
CCVector3d maxC;
if (obj->getGlobalBB(minC, maxC))
{
if (isValid)
{
bbMinCorner.x = std::min(bbMinCorner.x, minC.x);
bbMinCorner.y = std::min(bbMinCorner.y, minC.y);
bbMinCorner.z = std::min(bbMinCorner.z, minC.z);
bbMaxCorner.x = std::max(bbMaxCorner.x, maxC.x);
bbMaxCorner.y = std::max(bbMaxCorner.y, maxC.y);
bbMaxCorner.z = std::max(bbMaxCorner.z, maxC.z);
}
else
{
bbMinCorner = minC;
bbMaxCorner = maxC;
isValid = true;
}
}
}
return isValid;
}
//! Computes the range (min & max) of the enabled scalar field
//! for each object in the container
/**
* @param objects containter of objects to compute the range on
* @return 2D vector, x is the min, y in the max
*/
CCVector2d mRangeOfContainer(ccHObject::Container &objects)
{
CCVector2d range(std::numeric_limits<double>::max(), std::numeric_limits<double>::min());
auto updateRange = [&range](const CCLib::GenericIndexedCloudPersist *cloud)
{
if (!cloud->isScalarFieldEnabled())
return;
unsigned numPoints = cloud->size();
for (unsigned i = 0; i < numPoints; ++i)
{
ScalarType val = cloud->getPointScalarValue(i);
if (val != NAN_VALUE)
{
auto m = static_cast<double>(val);
range.x = std::min(range.x, m);
range.y = std::max(range.y, m);
}
}
};
//call the same method on the first child so as to get its type
for (ccHObject *obj : objects)
{
switch (obj->getClassID())
{
case CC_TYPES::POINT_CLOUD:
{
const ccGenericPointCloud *cloud = ccHObjectCaster::ToGenericPointCloud(obj);
updateRange(cloud);
break;
}
case CC_TYPES::POLY_LINE:
{
const ccPolyline *poly = ccHObjectCaster::ToPolyline(obj);
const CCLib::GenericIndexedCloudPersist *vertices = poly->getAssociatedCloud();
updateRange(vertices);
break;
}
default:
break;
}
}
if (range.x == std::numeric_limits<double>::max())
{
range.x = 0.0;
range.y = 0.0;
}
return range;
}
static void updateFileLength(QDataStream& out, int32_t newFileLentgh)
{
qint64 oldPos = out.device()->pos();
QDataStream::ByteOrder oldOrder = out.byteOrder();
out.device()->seek(ESRI_FILE_LENGTH_OFFSET);
out.setByteOrder(QDataStream::BigEndian);
out << newFileLentgh;
out.device()->seek(oldPos);
out.setByteOrder(oldOrder);
}
struct ShapeFileHeader
{
int32_t fileLength = ESRI_HEADER_SIZE;
int32_t version = 1000;
int32_t shapeTypeInt = static_cast<int32_t >(ESRI_SHAPE_TYPE::NULL_SHAPE);
CCVector3d pointMin;
CCVector3d pointMax;
CCVector2d mRange; // x is the min, y is the max
CC_FILE_ERROR readFrom(QDataStream& sin);
CC_FILE_ERROR writeTo(QDataStream& out);
};
CC_FILE_ERROR ShapeFileHeader::readFrom(QDataStream &sin)
{
sin.setByteOrder(QDataStream::BigEndian);
int32_t fileCode;
sin >> fileCode;
if (fileCode != ESRI_SHAPE_FILE_CODE)
{
ccLog::Warning("[SHP] wrong file code (%d), is this a shape file?", fileCode);
return CC_FERR_MALFORMED_FILE;
}
sin.skipRawData(5 * sizeof(int32_t));
sin >> fileLength;
fileLength *= 2; //fileLength is measured in 16-bit words
sin.setByteOrder(QDataStream::LittleEndian);
sin >> version >> shapeTypeInt;
if (!isValidESRIShapeCode(shapeTypeInt))
{
ccLog::Warning("[SHP] invalid shape type code in header (%d)", shapeTypeInt);
return CC_FERR_MALFORMED_FILE;
}
sin >> pointMin.x >> pointMin.y >> pointMax.x >> pointMax.y;
sin >> pointMin.z >> pointMax.z;
pointMin.z = std::isnan(pointMin.z) ? 0 : pointMin.z;
pointMax.z = std::isnan(pointMax.z) ? 0 : pointMax.z;
sin >> mRange.x >> mRange.y;
if (sin.status() != QDataStream::Ok)
{
ccLog::Warning("[SHP] Something went wrong reading the shp header");
return CC_FERR_READING;
}
return CC_FERR_NO_ERROR;
}
CC_FILE_ERROR ShapeFileHeader::writeTo(QDataStream& out)
{
out.setByteOrder(QDataStream::BigEndian);
out << ESRI_SHAPE_FILE_CODE;
constexpr size_t numBytesToSkip = 5 * sizeof(int32_t);
constexpr char skipValues[numBytesToSkip] = {0};
out.writeRawData(skipValues, numBytesToSkip);
out << fileLength;
out.setByteOrder(QDataStream::LittleEndian);
out << version;
out << shapeTypeInt;
out << pointMin.x << pointMin.y << pointMax.x << pointMax.y;
out << pointMin.z << pointMax.z;
out << mRange.x << mRange.y;
assert(out.device()->pos() == ESRI_HEADER_SIZE);
return CC_FERR_NO_ERROR;
}
//! Shape File Save dialog
class SaveSHPFileDialog : public QDialog, public Ui::SaveSHPFileDlg
{
public:
//! Default constructor
explicit SaveSHPFileDialog(QWidget* parent = nullptr)
: QDialog(parent)
, Ui::SaveSHPFileDlg()
{
setupUi(this);
}
};
//! Shape File Load dialog (to choose an 'altitude' field)
class ImportDBFFieldDialog : public QDialog, public Ui::ImportDBFFieldDlg
{
public:
//! Default constructor
explicit ImportDBFFieldDialog(QWidget* parent = nullptr)
: QDialog(parent)
, Ui::ImportDBFFieldDlg()
{
setupUi(this);
}
};
bool ShpFilter::canLoadExtension(const QString& upperCaseExt) const
{
return (upperCaseExt == "SHP");
}
bool ShpFilter::canSave(CC_CLASS_ENUM type, bool& multiple, bool& exclusive) const
{
if (type == CC_TYPES::POLY_LINE ||
type == CC_TYPES::POINT_CLOUD ||
type == CC_TYPES::HIERARCHY_OBJECT ||
type == CC_TYPES::MESH)
{
multiple = true;
exclusive = true;
return true;
}
return false;
}
static QString ToString(ESRI_PART_TYPE type)
{
switch (type)
{
case ESRI_PART_TYPE::TRIANGLE_STRIP:
return "Triangle Strip";
case ESRI_PART_TYPE::TRIANGLE_FAN:
return "Triangle Fan";
case ESRI_PART_TYPE::INNER_RING:
return "Inner Ring";
case ESRI_PART_TYPE::OUTER_RING:
return "Outer Ring";
case ESRI_PART_TYPE::FIRST_RING:
return "First Ring";
case ESRI_PART_TYPE::RING:
return "Ring";
default:
return "Unknown";
}
}
static QString ToString(ESRI_SHAPE_TYPE type)
{
switch (type)
{
case ESRI_SHAPE_TYPE::NULL_SHAPE:
return "Unhandled";
case ESRI_SHAPE_TYPE::POINT:
return "2D point";
case ESRI_SHAPE_TYPE::POLYLINE:
return "2D polyline";
case ESRI_SHAPE_TYPE::POLYGON:
return "2D polygon";
case ESRI_SHAPE_TYPE::MULTI_POINT:
return "2D point cloud";
case ESRI_SHAPE_TYPE::POINT_Z:
return "3D point";
case ESRI_SHAPE_TYPE::POLYLINE_Z:
return "3D polyline";
case ESRI_SHAPE_TYPE::POLYGON_Z:
return "3D polygon";
case ESRI_SHAPE_TYPE::MULTI_POINT_Z:
return "3D point cloud";
case ESRI_SHAPE_TYPE::POINT_M:
return "2D point (+measure)";
case ESRI_SHAPE_TYPE::POLYLINE_M:
return "2D polyline (+measure)";
case ESRI_SHAPE_TYPE::POLYGON_M:
return "2D polygon (+measure)";
case ESRI_SHAPE_TYPE::MULTI_POINT_M:
return "2D point cloud (+measure)";
case ESRI_SHAPE_TYPE::MULTI_PATCH:
return "Multi patch";
default:
return "Unknown";
}
return QString("Unknown");
}
static void GetSupportedShapes(ccHObject* baseEntity, ccHObject::Container& shapes, ESRI_SHAPE_TYPE& shapeType)
{
shapeType = ESRI_SHAPE_TYPE::NULL_SHAPE;
if (!baseEntity)
{
assert(false);
shapes.clear();
return;
}
switch (baseEntity->getClassID())
{
case CC_TYPES::POINT_CLOUD:
{
unsigned count = ccHObjectCaster::ToGenericPointCloud(baseEntity)->size();
if (count != 0)
{
shapeType = ESRI_SHAPE_TYPE::MULTI_POINT_Z;
shapes.push_back(baseEntity);
}
break;
}
case CC_TYPES::POLY_LINE:
{
shapeType = ESRI_SHAPE_TYPE::POLYLINE_Z;
shapes.push_back(baseEntity);
break;
}
case CC_TYPES::MESH:
{
shapeType = ESRI_SHAPE_TYPE::MULTI_PATCH;
shapes.push_back(baseEntity);
break;
}
case CC_TYPES::HIERARCHY_OBJECT:
//we only allow groups with children of the same type!
if (baseEntity->getChildrenNumber())
{
ccHObject* child = baseEntity->getChild(0);
assert(child);
if (!child)
return;
//first we check that all entities have the same type
for (unsigned i = 1; i < baseEntity->getChildrenNumber(); ++i)
{
if (baseEntity->getChild(i) && baseEntity->getChild(i)->getClassID() != child->getClassID())
{
//mixed shapes are not allowed in shape files
return;
}
}
//call the same method on the first child so as to get its type
GetSupportedShapes(child, shapes, shapeType);
if (shapeType == ESRI_SHAPE_TYPE::NULL_SHAPE)
return;
//then add the remaining children
for (unsigned i = 1; i < baseEntity->getChildrenNumber(); ++i)
{
ESRI_SHAPE_TYPE otherShapeType = ESRI_SHAPE_TYPE::NULL_SHAPE;
ccHObject* child = baseEntity->getChild(i);
if (child)
GetSupportedShapes(child, shapes, otherShapeType);
if (otherShapeType != shapeType)
{
if (child)
ccLog::Warning(QString("[SHP] Entity %1 has not the same type (%2) as the others in the selection (%3)! Can't mix types...")
.arg(child->getName())
.arg(ToString(otherShapeType))
.arg(ToString(shapeType)));
//mixed shapes are not allowed in shape files
shapes.clear();
return;
}
}
}
break;
default:
//nothing to do
break;
}
}
static std::vector<int32_t> readParts(QDataStream& shpStream, int32_t numParts)
{
std::vector<int32_t> startIndexes;
try
{
startIndexes.resize(numParts, 0);
}
catch (const std::bad_alloc&)
{
shpStream.skipRawData(sizeof(int32_t) * numParts);
return startIndexes;
}
for (int32_t i = 0; i != numParts; ++i)
{
shpStream >> startIndexes[i];
}
return startIndexes;
}
static std::vector<CCVector3> readPoints(QDataStream& shpStream, int32_t numPoints, const CCVector3d& Pshift)
{
std::vector<CCVector3> points;
try
{
points.resize(numPoints);
}
catch (const std::bad_alloc&)
{
//not enough memory
return points;
}
for (int32_t i = 0; i < numPoints; ++i)
{
double x;
double y;
shpStream >> x >> y;
points[i].x = static_cast<PointCoordinateType>(x + Pshift.x);
points[i].y = static_cast<PointCoordinateType>(y + Pshift.y);
points[i].z = 0;
}
return points;
}
static std::vector<ScalarType> readMeasures(QDataStream& shpStream, int32_t numPoints)
{
std::vector<ScalarType> scalarValues;
//M boundaries
double mMin;
double mMax;
shpStream >> mMin >> mMax;
if (!isESRINoData(mMin) && !isESRINoData(mMax))
{
try
{
scalarValues.resize(numPoints);
}
catch (const std::bad_alloc&)
{
return scalarValues;
}
}
//M values (an array of length NumPoints)
if (!scalarValues.empty())
{
for (int32_t i = 0; i < numPoints; ++i)
{
double m;
shpStream >> m;
scalarValues[i] = (isESRINoData(m) ? NAN_VALUE : static_cast<ScalarType>(m));
}
}
else
{
shpStream.skipRawData(numPoints * sizeof(double));
}
return scalarValues;
}
//! Builds the ccPointCloud of vertices
//! Returns nullptr if out of memory
ccPointCloud *buildVertices(const std::vector<CCVector3> &points, int32_t firstIndex, int32_t lastIndex)
{
int32_t vertCount = lastIndex - firstIndex + 1;
auto *vertices = new ccPointCloud("vertices");
if (!vertices->reserve(vertCount))
{
delete vertices;
return nullptr;
}
for (int32_t j = 0; j < vertCount; ++j)
{
vertices->addPoint(points[firstIndex + j]);
}
vertices->setEnabled(false);
return vertices;
}
//! Creates the ccMesh
ccMesh *createMesh(
const std::vector<CCVector3> &points,
const std::vector<ScalarType> &scalarValues,
int32_t firstIndex,
int32_t lastIndex)
{
int32_t vertCount = lastIndex - firstIndex + 1;
if (vertCount < 3)
{
return nullptr;
}
ccPointCloud *vertices = buildVertices(points, firstIndex, lastIndex);
if (!vertices)
{
return nullptr;
}
if (!scalarValues.empty())
{
bool areAllValuesOfPartsNans = true;
if (firstIndex < scalarValues.size() && lastIndex < scalarValues.size())
{
areAllValuesOfPartsNans = std::all_of(scalarValues.begin() + firstIndex,
scalarValues.begin() + lastIndex,
[](ScalarType val)
{ return std::isnan(val); });
}
if (!areAllValuesOfPartsNans)
{
auto *sf = new ccScalarField("Measures");
if (!sf->reserveSafe(vertCount))
{
ccLog::Warning(QString("[SHP] Mesh: not enough memory to load scalar values!"));
sf->release();
} else
{
for (int32_t j = 0; j < vertCount; ++j)
{
sf->addElement(scalarValues[j + firstIndex]);
}
sf->computeMinAndMax();
int sfIdx = vertices->addScalarField(sf);
vertices->setCurrentDisplayedScalarField(sfIdx);
vertices->showSF(true);
vertices->enableScalarField();
}
}
}
return new ccMesh(vertices);
}
//! Builds the patches that where read from a MultiPatch record of a Shapefile
//! patches are build as meshes, each part is its own mesh
//! The only supported Patches/Part types are Triangle_Fan & Triangle_Strip
CC_FILE_ERROR buildPatches(
ccHObject &container,
const std::vector<int32_t> &startIndexes,
const std::vector<int32_t> &partTypes,
const std::vector<CCVector3> &points,
const std::vector<ScalarType> &scalarValues)
{
size_t numParts = startIndexes.size();
size_t numPoints = points.size();
for (int32_t i = 0; i < numParts; ++i)
{
if (!isValidEsriPartType(partTypes[i]))
{
ccLog::Warning("[SHP] Multipatch part %d has an invalid part type (%d)", i, partTypes[i]);
continue;
}
auto type = static_cast<ESRI_PART_TYPE>(partTypes[i]);
const int32_t &firstIndex = startIndexes[i];
const int32_t &lastIndex = static_cast<const int32_t &>((i + 1 < numParts ? startIndexes[i + 1] : numPoints) -1);
const int32_t vertCount = lastIndex - firstIndex + 1;
switch (type)
{
case ESRI_PART_TYPE::TRIANGLE_STRIP:
{
ccMesh *mesh = createMesh(points, scalarValues, firstIndex, lastIndex);
for (int32_t j = 2; j < vertCount; ++j)
{
mesh->addTriangle(j - 2, j - 1, j);
}
container.addChild(mesh);
break;
}
case ESRI_PART_TYPE::TRIANGLE_FAN:
{
ccMesh *mesh = createMesh(points, scalarValues, firstIndex, lastIndex);
for (int32_t j = 2; j < vertCount; ++j)
{
mesh->addTriangle(0, j - 1, j);
}
container.addChild(mesh);
break;
}
default:
ccLog::Print(QString("[SHP] Cannot handle Patch of type: %1").arg(ToString(type)));
return CC_FERR_BAD_ENTITY_TYPE;
}
}
return CC_FERR_NO_ERROR;
}
static CC_FILE_ERROR LoadMultiPatch(QDataStream &shpStream,
ccHObject &container,
CCVector3d Pshift)
{
// skip record bbox
shpStream.skipRawData(4 * sizeof(double));
int32_t numParts;
int32_t numPoints;
shpStream >> numParts >> numPoints;
std::vector<int32_t> startIndexes = readParts(shpStream, numParts);
if (startIndexes.empty())
{
return CC_FERR_NOT_ENOUGH_MEMORY;
}
std::vector<int32_t> partTypes = readParts(shpStream, numParts);
if (partTypes.empty())
{
return CC_FERR_NOT_ENOUGH_MEMORY;
}
std::vector<CCVector3> points = readPoints(shpStream, numPoints, Pshift);
if (points.empty())
{
return CC_FERR_NOT_ENOUGH_MEMORY;
}
//Z boundaries
shpStream.skipRawData(2 * sizeof(double));
//Z coordinates (an array of length NumPoints)
for (int32_t i = 0; i < numPoints; ++i)
{
double z;
shpStream >> z;
points[i].z = static_cast<PointCoordinateType>(z + Pshift.z);
}
std::vector<ScalarType> scalarValues = readMeasures(shpStream, numPoints);
return buildPatches(container, startIndexes, partTypes, points, scalarValues);
}
//! Saves the cloud to the shape file according to the specification
/**
*
* @param stream Output stream of the shapefile
* @param cloud The cloud to save (pointcloud or vertices)
* @param bbMing Min point of the cloud
* @param bbMaxg Mxx point of the cloud
*/
static void save3DCloud(QDataStream &stream, const ccGenericPointCloud *cloud, const CCVector3d &bbMing, const CCVector3d &bbMaxg)
{
const unsigned numPoints = cloud->size();
CCVector3 P;
// Points (x ,y)
for (unsigned i = 0; i < numPoints; ++i)
{
cloud->getPoint(i, P);
CCVector3d Pg = cloud->toGlobal3d(P);
stream << Pg.x << Pg.y;
}
// Z Coordinates
stream << bbMing.z << bbMaxg.z;
for (unsigned i = 0; i < numPoints; ++i)
{
cloud->getPoint(i, P);
CCVector3d Pg = cloud->toGlobal3d(P);
stream << Pg.z;
}
// Measures
bool hasSF = cloud->isScalarFieldEnabled();
double mMin = ESRI_NO_DATA;
double mMax = ESRI_NO_DATA;
if (hasSF)
{
mMin = std::numeric_limits<double>::max();
mMax = std::numeric_limits<double>::min();
for (unsigned i = 0; i < numPoints; ++i)
{
auto scalar = static_cast<double >(cloud->getPointScalarValue(i));
mMin = std::min(mMin, scalar);
mMax = std::max(mMax, scalar);
}
}
stream << mMin << mMax;
auto scalar = ESRI_NO_DATA;
for (unsigned i = 0; i < numPoints; ++i)
{
if (hasSF)
{
scalar = static_cast<double>(cloud->getPointScalarValue(i));
}
stream << scalar;
}
}
static inline bool isTriangleStrip(const CCLib::VerticesIndexes *idx)
{
return (idx->i3 - 1) == idx->i2 && (idx->i3 - 2) == idx->i1;
}
static inline bool isTriangleFan(const CCLib::VerticesIndexes *idx)
{
return idx->i1 == 0 && idx->i2 == (idx->i3 - 1);
}
/**
* Tells wether the mesh's vertices are organised in triangle fan or triangle strip fashion.
* @param mesh
* @param[out] type
* @return CC_FERR_BAD_ENTITY_TYPE if the mesh is neither a triangle fan or triangle strip
*/
CC_FILE_ERROR findTriangleOrganisation(ccMesh *mesh, ESRI_PART_TYPE &type)
{
const CCLib::VerticesIndexes *firstVert = mesh->getNextTriangleVertIndexes();
if (!isTriangleFan(firstVert) && !isTriangleStrip(firstVert))
return CC_FERR_BAD_ENTITY_TYPE;
const CCLib::VerticesIndexes *secondVert = mesh->getNextTriangleVertIndexes();
if (isTriangleStrip(secondVert))
{
for (unsigned i = 2; i < mesh->size(); ++i)
{
CCLib::VerticesIndexes *idx = mesh->getNextTriangleVertIndexes();
if (!isTriangleStrip(idx))
return CC_FERR_BAD_ENTITY_TYPE;
}
type = ESRI_PART_TYPE::TRIANGLE_STRIP;
return CC_FERR_NO_ERROR;
}
else if (isTriangleFan(secondVert))
{
for (unsigned i = 2; i < mesh->size(); ++i)
{
CCLib::VerticesIndexes *idx = mesh->getNextTriangleVertIndexes();
if (!isTriangleFan(idx))
return CC_FERR_BAD_ENTITY_TYPE;
}
type = ESRI_PART_TYPE::TRIANGLE_FAN;
return CC_FERR_NO_ERROR;
}
else
{
return CC_FERR_BAD_ENTITY_TYPE;
}
}
CC_FILE_ERROR SaveMesh(ccMesh *mesh, QDataStream &stream, int32_t recordNumber, int32_t &recordSize)
{
ESRI_PART_TYPE triangleType;
if (findTriangleOrganisation(mesh, triangleType) == CC_FERR_BAD_ENTITY_TYPE)
return CC_FERR_BAD_ENTITY_TYPE;
ccLog::Print(QString("[SHP] Triangle type: %1").arg(ToString(triangleType)));
ccGenericPointCloud *vertices = mesh->getAssociatedCloud();
int32_t numParts = 1;
unsigned numPoints = vertices->size();
recordSize = sizeofMultipatch(numPoints, numParts);
// Record Header
stream.setByteOrder(QDataStream::BigEndian);
stream << recordNumber << recordSize;
qint64 recordStart = stream.device()->pos();
stream.setByteOrder(QDataStream::LittleEndian);
stream << static_cast<int32_t >(ESRI_SHAPE_TYPE::MULTI_PATCH);
CCVector3d bbMing, bbMaxg;
mesh->getGlobalBB(bbMing, bbMaxg);
stream << bbMing.x << bbMing.y << bbMaxg.x << bbMaxg.y;
stream << numParts << numPoints;
stream << static_cast<int32_t>(0); // Parts
stream << static_cast<int32_t>(triangleType); // Parts Type
save3DCloud(stream, vertices, bbMing, bbMaxg);
qint64 recordEnd = stream.device()->pos();
qint64 bytesWritten = recordEnd - recordStart;
assert(bytesWritten == 2 * recordSize);
return CC_FERR_NO_ERROR;
}
static CC_FILE_ERROR LoadPolyline(QDataStream &shpStream,
ccHObject &container,
int32_t index,
ESRI_SHAPE_TYPE shapeType,
const CCVector3d &Pshift,
bool preserveCoordinateShift,
bool load2DPolyAs3DPoly = true)
{
// skip record bbox
shpStream.skipRawData(4 * sizeof(double));
int32_t numParts;
int32_t numPoints;
shpStream >> numParts >> numPoints;
std::vector<int32_t> startIndexes = readParts(shpStream, numParts);
if (startIndexes.empty())
{
return CC_FERR_NOT_ENOUGH_MEMORY;
}
//for each part, the index of its first point in the points array
//FIXME: we should use this information and create as many polylines as necessary!
//Points (An array of length NumPoints)
std::vector<CCVector3> points = readPoints(shpStream, numPoints, Pshift);
if (points.empty())
{
return CC_FERR_NOT_ENOUGH_MEMORY;
}
//3D polylines
bool is3D = isESRIShape3D(shapeType);
if (is3D)
{
//Z boundaries
shpStream.skipRawData(2 * sizeof(double));
//Z coordinates (an array of length NumPoints)
for (int32_t i = 0; i < numPoints; ++i)
{
double z;
shpStream >> z;
points[i].z = static_cast<PointCoordinateType>(z + Pshift.z);
}
}
//3D polylines or 2D polylines + measurement
std::vector<ScalarType> scalarValues;
if (hasMeasurements(shapeType))
{
scalarValues = readMeasures(shpStream, numPoints);
if (scalarValues.empty())
{
//not enough memory to load scalar values!
ccLog::Warning(QString("[SHP] Polyline #%1: not enough memory to load scalar values!").arg(index));
}
}
//and of course the polyline(s)
for (int32_t i = 0; i < numParts; ++i)
{
const int32_t& firstIndex = startIndexes[i];
const int32_t& lastIndex = (i + 1 < numParts ? startIndexes[i + 1] : numPoints) - 1;
int32_t vertCount = lastIndex - firstIndex + 1;
//test if the polyline is closed
bool isClosed = false;
if (vertCount > 2 && (points[firstIndex] - points[lastIndex]).norm() < ZERO_TOLERANCE)
{
vertCount--;
isClosed = true;
}
//vertices
ccPointCloud* vertices = new ccPointCloud("vertices");
if (!vertices->reserve(vertCount))
{
delete vertices;
return CC_FERR_NOT_ENOUGH_MEMORY;
}
for (int32_t j = 0; j < vertCount; ++j)
{
vertices->addPoint(points[firstIndex + j]);
}
vertices->setEnabled(false);
if (preserveCoordinateShift)
{
vertices->setGlobalShift(Pshift);
}
//polyline
ccPolyline* poly = new ccPolyline(vertices);
poly->addChild(vertices);
if (preserveCoordinateShift)
{
poly->setGlobalShift(Pshift); //shouldn't be necessary but who knows ;)
}
if (!poly->reserve(vertCount))
{
delete poly;
return CC_FERR_NOT_ENOUGH_MEMORY;
}
poly->addPointIndex(0, static_cast<unsigned>(vertCount));
poly->showSF(vertices->sfShown());
QString name = QString("Polyline #%1").arg(index);
if (numParts != 1)
name += QString(".%1").arg(i + 1);
poly->setName(name);
poly->setClosed(isClosed);
poly->set2DMode(!is3D && !load2DPolyAs3DPoly);
if (!scalarValues.empty())
{
bool allNans = std::all_of(
scalarValues.begin() + firstIndex,
scalarValues.begin() + lastIndex,
[](ScalarType v) {return std::isnan(v);}
);
if (!allNans)
{
auto* sf = new ccScalarField("Measures");
if (!sf->reserveSafe(vertCount))
{
ccLog::Warning(QString("[SHP] Polyline #%1.%2: not enough memory to load scalar values!").arg(index).arg(i + 1));
sf->release();
sf = nullptr;
}
for (int32_t j = 0; j < vertCount; ++j)
{
sf->addElement(scalarValues[j + firstIndex]);
}
sf->computeMinAndMax();
int sfIdx = vertices->addScalarField(sf);
vertices->setCurrentDisplayedScalarField(sfIdx);
vertices->showSF(true);
vertices->enableScalarField();
}
}
container.addChild(poly);
}
return CC_FERR_NO_ERROR;
}
static CC_FILE_ERROR SavePolyline(ccPolyline *poly,
QDataStream &out,
int32_t &recordSize,
int32_t recordNumber,
ESRI_SHAPE_TYPE outputShapeType,
int vertDim = 2)
{
assert(vertDim >= 0 && vertDim < 3);
const auto Z = static_cast<unsigned char>(vertDim);
const unsigned char X = Z == 2 ? 0 : Z + 1;
const unsigned char Y = X == 2 ? 0 : X + 1;
if (!poly)
{
assert(false);
return CC_FERR_BAD_ENTITY_TYPE;
}
CCLib::GenericIndexedCloudPersist* vertices = poly->getAssociatedCloud();
if (!vertices)
return CC_FERR_BAD_ENTITY_TYPE;
int32_t realNumPoints = poly->size();
switch (outputShapeType)
{
case ESRI_SHAPE_TYPE::POLYGON:
case ESRI_SHAPE_TYPE::POLYGON_M:
case ESRI_SHAPE_TYPE::POLYGON_Z:
if (realNumPoints < 3)
{
ccLog::Warning("[SHP] Polyline doest not have enough points to be saved as polygon");
return CC_FERR_BAD_ENTITY_TYPE;
}
break;
case ESRI_SHAPE_TYPE::POLYLINE:
case ESRI_SHAPE_TYPE::POLYLINE_M:
case ESRI_SHAPE_TYPE::POLYLINE_Z:
if (realNumPoints < 2)
{
ccLog::Warning("[SHP] Polyline does not have enough points to be saved");
return CC_FERR_BAD_ENTITY_TYPE;
}
break;
default:
assert(false);
return CC_FERR_BAD_ENTITY_TYPE;
}
bool isClosed = poly->isClosed();
int32_t numPoints = realNumPoints;
if (isClosed)
numPoints++;
if (numPoints > std::numeric_limits<int32_t>::max())
{
ccLog::Warning("[SHP] Polyline has to many points to be saved");
return CC_FERR_BAD_ENTITY_TYPE;
}
int32_t numParts = 1;
recordSize = sizeofPolyLine(outputShapeType, numPoints, numParts);
out.setByteOrder(QDataStream::BigEndian);
out << recordNumber << recordSize;
qint64 recordStart = out.device()->pos();
out.setByteOrder(QDataStream::LittleEndian);
out << static_cast<int32_t>(outputShapeType);
CCVector3d bbMing;
CCVector3d bbMaxg;
poly->getGlobalBB(bbMing, bbMaxg);
out << bbMing.u[X] << bbMing.u[Y] << bbMaxg.u[X] << bbMaxg.u[Y];
out << numParts;
out << numPoints;
//for each part, the index of its first point in the points array
out << static_cast<int32_t>(0);
//for polygons we must list the vertices in the right order:
//"The neighborhood to the right of an observer walking along
//the ring in vertex order is the inside of the polygon"
//== clockwise order
bool inverseOrder = false;
if (outputShapeType == ESRI_SHAPE_TYPE::POLYGON || outputShapeType == ESRI_SHAPE_TYPE::POLYGON_Z)
{
assert(isClosed);
assert(numPoints > 2);
unsigned char dim1 = X;
unsigned char dim2 = Y;
if (outputShapeType == ESRI_SHAPE_TYPE::POLYGON_Z)
{
CCVector3d diag = bbMaxg - bbMing;
//in 3D we have to guess the 'flat' dimension
unsigned char minDim = diag.u[1] < diag.u[0] ? 1 : 0;
if (diag.u[2] < diag.u[minDim])
minDim = 2;
dim1 = minDim == 2 ? 0 : minDim + 1;
dim2 = dim1 == 2 ? 0 : dim1 + 1;
}
inverseOrder = areVerticesCounterClockwise(vertices, numPoints, dim1, dim2);
}
//Points (An array of length NumPoints)
for (int32_t i = 0; i < numPoints; ++i)
{
int32_t ii = (inverseOrder ? numPoints - 1 - i : i);
const CCVector3* P = vertices->getPoint(ii % realNumPoints); //warning: handle loop if polyline is closed
CCVector3d Pg = poly->toGlobal3d(*P);
out << Pg.u[X] << Pg.u[Y];
}
//3D polylines
if (isESRIShape3D(outputShapeType))
{
//Z boundaries
out << bbMing.u[Z] << bbMaxg.u[Z];
//Z coordinates (for each part - just one here)
for (int32_t i = 0; i < numPoints; ++i)
{
int32_t ii = (inverseOrder ? numPoints - 1 - i : i);
const CCVector3 *P = vertices->getPoint(ii % realNumPoints); //warning: handle loop if polyline is closed
CCVector3d Pg = poly->toGlobal3d(*P);
out << Pg.u[Z];
}
}
if (hasMeasurements(outputShapeType))
{
//M boundaries
bool hasSF = vertices->isScalarFieldEnabled();
CCVector2d minMax = minMaxOfEnabledScalarField(vertices);
out << minMax.x << minMax.y;
//M values (for each part - just one here)
if (hasSF)
{
for (int32_t i = 0; i < numPoints; ++i)
{
ScalarType scalar = vertices->getPointScalarValue(i % realNumPoints);
out << (scalar == NAN_VALUE ? ESRI_NO_DATA : static_cast<double>(scalar));
}
}
else
{
for (int32_t i = 0; i < numPoints; ++i)
out << ESRI_NO_DATA;
}
}
assert(out.device()->pos() - recordStart == recordSize * 2);
return CC_FERR_NO_ERROR;
}
static CC_FILE_ERROR LoadCloud(QDataStream &shpStream,
ccHObject &container,
int32_t index,
ESRI_SHAPE_TYPE shapeType,
const CCVector3d &Pshift,
bool preserveCoordinateShift)
{
// Skip record bbox
shpStream.skipRawData(4 * sizeof(double));
int32_t numPoints;
shpStream >> numPoints;
auto* cloud = new ccPointCloud(QString("Cloud #%1").arg(index));
if (!cloud->reserve(numPoints))
{
delete cloud;
return CC_FERR_NOT_ENOUGH_MEMORY;
}
if (preserveCoordinateShift)
{
cloud->setGlobalShift(Pshift);
}
//Points (An array of length NumPoints)
for (int32_t i = 0; i < numPoints; ++i)
{
double x;
double y;
shpStream >> x >> y;
CCVector3 P(static_cast<PointCoordinateType>(x + Pshift.x),
static_cast<PointCoordinateType>(y + Pshift.y),
0);
cloud->addPoint(P);
}
//3D clouds
if (isESRIShape3D(shapeType))
{
//Z boundaries
shpStream.skipRawData(2 * sizeof(double));
//Z coordinates (an array of length NumPoints)
for (int32_t i = 0; i < numPoints; ++i)
{
double z;
shpStream >> z;
const CCVector3* P = cloud->getPoint(i);
const_cast<CCVector3*>(P)->z = static_cast<PointCoordinateType>(z + Pshift.z);
}
cloud->invalidateBoundingBox();
}
//3D clouds or 2D clouds + measurement
if (hasMeasurements(shapeType))
{
//M boundaries
ccScalarField* sf = nullptr;
double mMin;
double mMax;
shpStream >> mMin >> mMax;
if (mMin != ESRI_NO_DATA && mMax != ESRI_NO_DATA)
{
sf = new ccScalarField("Measures");
if (!sf->reserveSafe(numPoints))
{
ccLog::Warning("[SHP] Not enough memory to load scalar values!");
sf->release();
sf = nullptr;
}
}
//M values (an array of length NumPoints)
if (sf)
{
for (int32_t i = 0; i < numPoints; ++i)
{
double m;
shpStream >> m;
ScalarType s = isESRINoData(m) ? NAN_VALUE : static_cast<ScalarType>(m);
sf->addElement(s);
}
bool allNans = std::all_of(sf->begin(), sf->end(), [](ScalarType s) { return std::isnan(s); });
if (!allNans)
{
sf->computeMinAndMax();
int sfIdx = cloud->addScalarField(sf);
cloud->setCurrentDisplayedScalarField(sfIdx);
cloud->showSF(true);
}
else
{
sf->release();
}
}
else
{
shpStream.skipRawData(numPoints * sizeof(double));
}
}
container.addChild(cloud);
return CC_FERR_NO_ERROR;
}
static CC_FILE_ERROR SaveAsCloud(ccGenericPointCloud* cloud, QDataStream& out, int32_t recordNumber, int32_t& recordSize)
{
if (!cloud)
{
assert(false);
return CC_FERR_BAD_ENTITY_TYPE;
}
if (cloud->size() > static_cast<unsigned >(std::numeric_limits<int32_t>::max()))
{
ccLog::Print("[SHP] Cloud is to big to be saved");
return CC_FERR_BAD_ENTITY_TYPE;
}
recordSize = sizeofMultiPointZ(cloud->size());
out.setByteOrder(QDataStream::BigEndian);
out << recordNumber << recordSize;
CCVector3d bbMing;
CCVector3d bbMaxg;
cloud->getGlobalBB(bbMing, bbMaxg);
int64_t recordStart = out.device()->pos();
out.setByteOrder(QDataStream::LittleEndian);
out << static_cast<int32_t>(ESRI_SHAPE_TYPE::MULTI_POINT_Z);
out << bbMing.x << bbMing.y << bbMaxg.x << bbMaxg.y;
out << static_cast<int32_t >(cloud->size());
save3DCloud(out, cloud, bbMing, bbMaxg);
assert(out.device()->pos() - recordStart == recordSize * 2);
return CC_FERR_NO_ERROR;
}
static CC_FILE_ERROR LoadSinglePoint(QDataStream &shpStream,
ccPointCloud *&singlePoints,
ESRI_SHAPE_TYPE shapeType,
const CCVector3d &Pshift,
bool preserveCoordinateShift)
{
if (!singlePoints)
{
singlePoints = new ccPointCloud("Points");
if (preserveCoordinateShift)
{
singlePoints->setGlobalShift(Pshift);
}
}
double x;
double y;
shpStream >> x >> y;
CCVector3 P(static_cast<PointCoordinateType>(x + Pshift.x),
static_cast<PointCoordinateType>(y + Pshift.y),
0);
if (isESRIShape3D(shapeType))
{
double z;
shpStream >> z;
P.z = static_cast<PointCoordinateType>(z + Pshift.z);
}
ScalarType s = NAN_VALUE;
if (hasMeasurements(shapeType))
{
double m;
shpStream >> m;
if (!isESRINoData(m))
{
s = static_cast<ScalarType>(m);
//add a SF to the cloud if not done already
if (!singlePoints->hasScalarFields())
{
int sfIdx = singlePoints->addScalarField("Measures");
if (sfIdx >= 0)
{
//set the SF value for the previous points
singlePoints->setCurrentScalarField(sfIdx);
for (unsigned i = 0; i < singlePoints->size(); ++i)
{
singlePoints->setPointScalarValue(i, NAN_VALUE);
}
}
}
}
}
//make sure to reserve the point cloud memory AFTER declaring the scalar field
//(otherwise the SF won't be reserved...)
if (singlePoints->size() == singlePoints->capacity() && !singlePoints->reserve(singlePoints->size() + 256)) //256 each time because it appears some SHP files have many isolated points...
{
delete singlePoints;
singlePoints = nullptr;
return CC_FERR_NOT_ENOUGH_MEMORY;
}
singlePoints->addPoint(P);
if (singlePoints->getCurrentOutScalarField())
singlePoints->getCurrentOutScalarField()->addElement(s);
return CC_FERR_NO_ERROR;
}
CC_FILE_ERROR ShpFilter::saveToFile(ccHObject* entity, const QString& filename, const SaveParameters& parameters)
{
std::vector<GenericDBFField*> fields;
return saveToFile(entity, fields, filename, parameters);
}
CC_FILE_ERROR ShpFilter::saveToFile(ccHObject* entity, const std::vector<GenericDBFField*>& fields, const QString& filename, const SaveParameters& parameters)
{
if (!entity)
return CC_FERR_BAD_ENTITY_TYPE;
//this filter only supports point clouds, meshes and polylines!
ESRI_SHAPE_TYPE inputShapeType = ESRI_SHAPE_TYPE::NULL_SHAPE;
ccHObject::Container toSave;
GetSupportedShapes(entity, toSave, inputShapeType);
if (inputShapeType == ESRI_SHAPE_TYPE::NULL_SHAPE || toSave.empty())
{
return CC_FERR_BAD_ENTITY_TYPE;
}
CCVector3d bbMinCorner, bbMaxCorner;
if (!bBoxOfHObjectContainer(toSave, bbMinCorner, bbMaxCorner))
{
ccLog::Error("Entity(ies) has(ve) an invalid bounding box?!");
return CC_FERR_BAD_ENTITY_TYPE;
}
bool save3DPolysAs2D = false;
int poly2DVertDim = 2;
bool save3DPolyHeightInDBF = false;
if (parameters.alwaysDisplaySaveDialog && inputShapeType == ESRI_SHAPE_TYPE::POLYLINE_Z)
{
//display SHP save dialog
SaveSHPFileDialog ssfDlg(nullptr);
ssfDlg.save3DPolyAs2DCheckBox->setChecked(m_save3DPolyAs2D);
ssfDlg.save3DPolyHeightInDBFCheckBox->setChecked(m_save3DPolyHeightInDBF);
ssfDlg.dimComboBox->setCurrentIndex(m_poly2DVertDim);
if (!ssfDlg.exec())
return CC_FERR_CANCELED_BY_USER;
save3DPolysAs2D = ssfDlg.save3DPolyAs2DCheckBox->isChecked();
poly2DVertDim = ssfDlg.dimComboBox->currentIndex();
save3DPolyHeightInDBF = ssfDlg.save3DPolyHeightInDBFCheckBox->isChecked();
}
assert(poly2DVertDim >= 0 && poly2DVertDim < 3);
const auto Z = static_cast<unsigned char>(poly2DVertDim);
const unsigned char X = Z == 2 ? 0 : Z + 1;
const unsigned char Y = X == 2 ? 0 : X + 1;
ESRI_SHAPE_TYPE outputShapeType = inputShapeType;
// Promote to polygon
if (m_closedPolylinesAsPolygons && outputShapeType == ESRI_SHAPE_TYPE::POLYLINE_Z)
{
auto isClosed = [](const ccHObject *obj) {return static_cast<const ccPolyline*>(obj)->isClosed();};
bool allClosed = std::all_of(toSave.begin(), toSave.end(), isClosed);
if (allClosed)
{
outputShapeType = ESRI_SHAPE_TYPE::POLYGON_Z;
}
}
// Demote to 2D polyline/polygon and remove "measure" dimension if not needed
if (save3DPolysAs2D)
{
auto hasSF = [](const ccHObject *obj){ return static_cast<const ccPolyline*>(obj)->isScalarFieldEnabled(); };
bool anyHasSF = std::any_of(toSave.begin(), toSave.end(), hasSF);
if (anyHasSF)
{
if (outputShapeType == ESRI_SHAPE_TYPE::POLYLINE_Z)
outputShapeType = ESRI_SHAPE_TYPE::POLYLINE_M;
else
outputShapeType = ESRI_SHAPE_TYPE::POLYGON_M;
}
else
{
if (outputShapeType == ESRI_SHAPE_TYPE::POLYLINE_Z)
outputShapeType = ESRI_SHAPE_TYPE::POLYLINE;
else
outputShapeType = ESRI_SHAPE_TYPE::POLYGON;
}
}
ccLog::Print("[SHP] Output type: " + ToString(outputShapeType));
QFileInfo fi(filename);
QString baseFileName = fi.path() + QString("/") + fi.completeBaseName();
//the main file (suffix should be ".shp")
QString shpFilename = baseFileName + QString(".shp");
QFile file(shpFilename);
if (!file.open(QIODevice::WriteOnly))
return CC_FERR_WRITING;
//index file (same base name + ".shx")
QString indexFilename = baseFileName + QString(".shx");
QFile indexFile(indexFilename);
if (!indexFile.open(QIODevice::WriteOnly))
return CC_FERR_WRITING;
QDataStream shpStream(&file);
QDataStream idxStream(&indexFile);
CCVector2d mRange(0.0, 0.0);
if (hasMeasurements(outputShapeType))
{
mRange = mRangeOfContainer(toSave);
}
if (!isESRIShape3D(outputShapeType))
{
bbMinCorner.u[Z] = 0.0;
bbMaxCorner.u[Z] = 0.0;
}
ShapeFileHeader hdr;
hdr.pointMin = CCVector3d(bbMinCorner.u[X], bbMinCorner.u[Y], bbMinCorner.u[Z]);
hdr.pointMax = CCVector3d(bbMaxCorner.u[X], bbMaxCorner.u[Y], bbMaxCorner.u[Z]);
hdr.shapeTypeInt = static_cast<int32_t>(outputShapeType);
hdr.mRange = mRange;
hdr.writeTo(shpStream);
hdr.writeTo(idxStream);
//save shapes
unsigned shapeIndex = 0;
for (ccHObject *child : toSave)
{
//check entity eligibility
if (child->isA(CC_TYPES::POLY_LINE))
{
if (static_cast<ccPolyline*>(child)->size() < 2)
{
ccLog::Warning(QString("Polyline '%1' is too small! It won't be saved...").arg(child->getName()));
continue;
}
}
int32_t recordSize = 0;
qint64 recordStart = shpStream.device()->pos();
CC_FILE_ERROR error = CC_FERR_NO_ERROR;
switch (outputShapeType)
{
case ESRI_SHAPE_TYPE::POLYLINE:
case ESRI_SHAPE_TYPE::POLYLINE_Z:
case ESRI_SHAPE_TYPE::POLYLINE_M:
case ESRI_SHAPE_TYPE::POLYGON:
case ESRI_SHAPE_TYPE::POLYGON_Z:
case ESRI_SHAPE_TYPE::POLYGON_M:
assert(child->isKindOf(CC_TYPES::POLY_LINE));
error = SavePolyline(static_cast<ccPolyline *>(child), shpStream, recordSize, shapeIndex,
outputShapeType, poly2DVertDim);
break;
case ESRI_SHAPE_TYPE::MULTI_POINT_Z:
assert(child->isKindOf(CC_TYPES::POINT_CLOUD));
error = SaveAsCloud(ccHObjectCaster::ToGenericPointCloud(child), shpStream, shapeIndex, recordSize);
break;
case ESRI_SHAPE_TYPE::MULTI_PATCH:
error = SaveMesh(ccHObjectCaster::ToMesh(child), shpStream, shapeIndex, recordSize);
break;
default:
assert(false);
break;
}
if (error != CC_FERR_NO_ERROR)
return error;
//write corresponding entry in index SHX file
idxStream << static_cast<int32_t>(recordStart / 2);
idxStream << static_cast<int32_t>(recordSize);
ccLog::PrintDebug("[SHP] Saved shape #%d (%d bytes)", shapeIndex, recordSize * 2);
shapeIndex++;
}
//update file lengths
updateFileLength(shpStream, shpStream.device()->pos() / 2);
updateFileLength(idxStream, idxStream.device()->pos() / 2);
file.close();
indexFile.close();
CC_FILE_ERROR result = CC_FERR_NO_ERROR;
//eventually, we create the DB file (suffix should be ".dbf")
QString dbfFilename = baseFileName + QString(".dbf");
DBFHandle dbfHandle = DBFCreate(qPrintable(dbfFilename));
if (dbfHandle)
{
while (true) //trick: we use 'while' to be able to break anytime
{
//always write an 'index' table
{
int fieldIdx = DBFAddField(dbfHandle, "local_idx", FTInteger, 6, 0);
if (fieldIdx >= 0)
{
for (size_t i = 0; i < toSave.size(); ++i)
DBFWriteIntegerAttribute(dbfHandle, static_cast<int>(i), fieldIdx, static_cast<int>(i)+1);
}
else
{
ccLog::Warning(QString("[SHP] Failed to save field 'index' (default)"));
result = CC_FERR_WRITING;
break;
}
}
//write the '3D polylines height' field if request
if (save3DPolyHeightInDBF)
{
int fieldIdx = DBFAddField(dbfHandle, "height", FTDouble, 8, 8);
if (fieldIdx >= 0)
{
for (size_t i = 0; i < toSave.size(); ++i)
{
ccPolyline* poly = static_cast<ccPolyline*>(toSave[i]);
double height = 0.0;
if (poly && poly->size() != 0)
{
const CCVector3* P0 = poly->getPoint(0);
CCVector3d Pg0 = poly->toGlobal3d(*P0);
height = Pg0.u[Z];
}
DBFWriteDoubleAttribute(dbfHandle, static_cast<int>(i), fieldIdx, height);
}
}
else
{
ccLog::Warning(QString("[SHP] Failed to save field 'height' (3D polylines height)"));
result = CC_FERR_WRITING;
break;
}
}
//and write the other tables (specified by the user)
for (GenericDBFField* field: fields)
{
if (field->is3D()) //3D case
{
int xFieldIdx = DBFAddField(dbfHandle, qPrintable(field->name() + QString("_x")), field->type(), field->width(), field->decimal());
int yFieldIdx = DBFAddField(dbfHandle, qPrintable(field->name() + QString("_y")), field->type(), field->width(), field->decimal());
int zFieldIdx = DBFAddField(dbfHandle, qPrintable(field->name() + QString("_z")), field->type(), field->width(), field->decimal());
if (xFieldIdx >= 0 && yFieldIdx >= 0 && zFieldIdx >= 0)
{
if (!field->save(dbfHandle, xFieldIdx, yFieldIdx, zFieldIdx))
xFieldIdx = -1;
}
if (xFieldIdx < 0)
{
ccLog::Warning(QString("[SHP] Failed to save field '%1'").arg(field->name()));
result = CC_FERR_WRITING;
break;
}
}
else //1D case
{
int fieldIdx = DBFAddField(dbfHandle, qPrintable(field->name()), field->type(), field->width(), field->decimal());
if (fieldIdx >= 0)
{
if (!field->save(dbfHandle, fieldIdx))
fieldIdx = -1;
}
if (fieldIdx < 0)
{
ccLog::Warning(QString("[SHP] Failed to save field '%1'").arg(field->name()));
result = CC_FERR_WRITING;
break;
}
}
}
break;
}
DBFClose(dbfHandle);
}
else
{
result = CC_FERR_WRITING;
}
return result;
}
CC_FILE_ERROR ShpFilter::loadFile(const QString &filename, ccHObject &container, LoadParameters ¶meters)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
return CC_FERR_READING;
if (file.size() < ESRI_HEADER_SIZE)
{
ccLog::Warning("[SHP] File is too small to be valid");
return CC_FERR_MALFORMED_FILE;
}
QDataStream shpStream(&file);
ShapeFileHeader hdr;
CC_FILE_ERROR error = hdr.readFrom(shpStream);
if (error != CC_FERR_NO_ERROR)
return error;
//global shift
CCVector3d Pshift(0, 0, 0);
bool preserveCoordinateShift = true;
CCVector3d Pmin = hdr.pointMin;
if (HandleGlobalShift(Pmin, Pshift, preserveCoordinateShift, parameters))
{
ccLog::Warning("[SHP] Entities will be recentered! Translation: (%.2f ; %.2f ; %.2f)", Pshift.x, Pshift.y, Pshift.z);
}
//progress bar
QScopedPointer<ccProgressDialog> pDlg(nullptr);
qint64 fileSize = file.size();
if (parameters.parentWidget)
{
pDlg.reset(new ccProgressDialog(true, parameters.parentWidget));
pDlg->setMaximum(static_cast<int>(fileSize));
pDlg->setMethodTitle(QObject::tr("Load SHP file"));
pDlg->setInfo(QObject::tr("File size: %1").arg(fileSize));
pDlg->start();
QApplication::processEvents();
}
//load shapes
error = CC_FERR_NO_ERROR;
ccPointCloud* singlePoints = nullptr;
//we also keep track of the polylines 'record number' (if any)
QMap<ccPolyline*, int32_t> polyIDs;
int32_t maxPolyID = 0;
int32_t maxPointID = 0;
bool is3DShape = false;
while (hdr.fileLength - shpStream.device()->pos() > 0)
{
if (shpStream.status() != QDataStream::Ok )
{
ccLog::Warning("[SHP] Something went wrong reading the file");
return CC_FERR_READING;
}
int32_t recordNumber;
int32_t recordSize;
int32_t shapeTypeInt;
shpStream.setByteOrder(QDataStream::BigEndian);
shpStream >> recordNumber >> recordSize;
recordSize *= 2; //recordSize is measured in 16-bit words
shpStream.setByteOrder(QDataStream::LittleEndian);
int64_t recordStart = shpStream.device()->pos();
shpStream >> shapeTypeInt;
if (!isValidESRIShapeCode(shapeTypeInt))
{
ccLog::Warning("[SHP] Shape %d has an invalid shape code (%d)", recordNumber, shapeTypeInt);
return CC_FERR_READING;
}
auto shapeType = static_cast<ESRI_SHAPE_TYPE >(shapeTypeInt);
if (recordNumber < 64)
ccLog::Print(QString("[SHP] Record #%1 - type: %2 (%3 bytes)").arg(recordNumber).arg(ToString(shapeType)).arg(recordSize));
else if (recordNumber == 64)
ccLog::Print("[SHP] Records won't be displayed in the Console anymore to avoid flooding it...");
switch (shapeType)
{
case ESRI_SHAPE_TYPE::POLYLINE_Z:
case ESRI_SHAPE_TYPE::POLYGON_Z:
is3DShape = true;
case ESRI_SHAPE_TYPE::POLYLINE:
case ESRI_SHAPE_TYPE::POLYGON:
case ESRI_SHAPE_TYPE::POLYLINE_M:
case ESRI_SHAPE_TYPE::POLYGON_M:
{
unsigned childCountBefore = container.getChildrenNumber();
error = LoadPolyline(shpStream, container, recordNumber, shapeType, Pshift, preserveCoordinateShift);
if (error == CC_FERR_NO_ERROR && shapeType == ESRI_SHAPE_TYPE::POLYLINE)
{
unsigned childCountAfter = container.getChildrenNumber();
//warning: we can load mutliple polylines for a single record!
for (unsigned i = childCountBefore; i < childCountAfter; ++i)
{
ccHObject* child = container.getChild(i);
assert(child && child->isA(CC_TYPES::POLY_LINE));
polyIDs[static_cast<ccPolyline*>(child)] = recordNumber;
if (recordNumber > maxPolyID)
maxPolyID = recordNumber;
}
}
}
break;
case ESRI_SHAPE_TYPE::MULTI_POINT_Z:
case ESRI_SHAPE_TYPE::MULTI_POINT_M:
is3DShape = true;
case ESRI_SHAPE_TYPE::MULTI_POINT:
error = LoadCloud(shpStream, container, recordNumber, shapeType, Pshift, preserveCoordinateShift);
break;
case ESRI_SHAPE_TYPE::POINT_Z:
case ESRI_SHAPE_TYPE::POINT_M:
is3DShape = true;
case ESRI_SHAPE_TYPE::POINT:
error = LoadSinglePoint(shpStream, singlePoints, shapeType, Pshift, preserveCoordinateShift);
if (error == CC_FERR_NO_ERROR && recordNumber > maxPointID)
{
maxPointID = recordNumber;
}
break;
case ESRI_SHAPE_TYPE::MULTI_PATCH:
error = LoadMultiPatch(shpStream, container, Pshift);
case ESRI_SHAPE_TYPE::NULL_SHAPE:
//ignored
break;
default:
//unhandled entity
shpStream.skipRawData(recordSize - sizeof(shapeTypeInt));
ccLog::Warning("[SHP] Unhandled type!");
break;
}
assert(shpStream.device()->pos() - recordStart == recordSize);
if (error != CC_FERR_NO_ERROR)
{
break;
}
if (pDlg)
{
pDlg->setValue(static_cast<int>(shpStream.device()->pos()));
if (pDlg->wasCanceled())
{
error = CC_FERR_CANCELED_BY_USER;
break;
}
}
}
//try to load the DBF to see if there's a 'height' field or something similar for polylines
bool hasPolylines = (!polyIDs.empty());
bool hasPoints = (singlePoints && singlePoints->size() != 0 &&
maxPointID == static_cast<int32_t>(singlePoints->size()));
if (!is3DShape && error == CC_FERR_NO_ERROR && (hasPolylines || hasPoints))
{
QFileInfo fi(filename);
QString baseFileName = fi.path() + QString("/") + fi.completeBaseName();
//try to load the DB file (suffix should be ".dbf")
QString dbfFilename = baseFileName + QString(".dbf");
DBFHandle dbfHandle = DBFOpen(qPrintable(dbfFilename), "rb");
if (dbfHandle)
{
int fieldCount = DBFGetFieldCount(dbfHandle);
int recordCount = DBFGetRecordCount(dbfHandle);
if (fieldCount == 0)
{
ccLog::Warning("[SHP] No field in the associated DBF file!");
}
else if (hasPolylines && recordCount < static_cast<int>(maxPolyID))
{
ccLog::Warning("[SHP] No enough records in the associated DBF file!");
}
else if (hasPoints && recordCount < static_cast<int>(singlePoints->size()))
{
ccLog::Warning("[SHP] No enough records in the associated DBF file!");
}
else
{
QList<FieldIndexAndName> candidateFields;
for (int i = 0; i < fieldCount; ++i)
{
char fieldName[256];
DBFFieldType fieldType = DBFGetFieldInfo(dbfHandle, i, fieldName, nullptr, nullptr);
if (fieldType == FTDouble || fieldType == FTInteger)
{
candidateFields.push_back(FieldIndexAndName(i, QString(fieldName)));
}
}
if (!candidateFields.empty())
{
//create a list of available fields
ImportDBFFieldDialog lsfDlg(nullptr);
for (QList<FieldIndexAndName>::const_iterator it = candidateFields.begin(); it != candidateFields.end(); ++it)
{
lsfDlg.listWidget->addItem(it->second);
}
lsfDlg.scaleDoubleSpinBox->setValue(m_dbfFieldImportScale);
lsfDlg.okPushButton->setVisible(false);
if (lsfDlg.exec())
{
m_dbfFieldImportScale = lsfDlg.scaleDoubleSpinBox->value();
//look for the selected index
int index = -1;
for (int i = 0; i < candidateFields.size(); ++i)
{
if (lsfDlg.listWidget->isItemSelected(lsfDlg.listWidget->item(i)))
{
index = candidateFields[i].first;
break;
}
}
if (index >= 0)
{
double scale = m_dbfFieldImportScale;
//read values
DBFFieldType fieldType = DBFGetFieldInfo(dbfHandle, index, nullptr, nullptr, nullptr);
if (hasPolylines)
{
//for each poyline
for (QMap<ccPolyline*, int32_t>::iterator it = polyIDs.begin(); it != polyIDs.end(); ++it)
{
//get the height
double z = 0.0;
if (fieldType == FTDouble)
z = DBFReadDoubleAttribute(dbfHandle, it.value() - 1, index);
else //if (fieldType == FTInteger)
z = static_cast<double>(DBFReadIntegerAttribute(dbfHandle, it.value() - 1, index));
z *= scale;
//translate the polyline
CCVector3 T(0, 0, static_cast<PointCoordinateType>(z));
ccGLMatrix trans;
trans.setTranslation(T);
ccPolyline* poly = it.key();
if (poly)
{
poly->applyGLTransformation_recursive(&trans);
//this transformation is of no interest for the user
poly->resetGLTransformationHistory_recursive();
//add the 'const altitude' meta-data as well
poly->setMetaData(ccPolyline::MetaKeyConstAltitude(), QVariant(z));
}
}
}
else if (hasPoints)
{
//for each point
for (unsigned i = 0; i < singlePoints->size(); ++i)
{
//get the height
double z = 0.0;
if (fieldType == FTDouble)
z = DBFReadDoubleAttribute(dbfHandle, static_cast<int>(i), index);
else //if (fieldType == FTInteger)
z = static_cast<double>(DBFReadIntegerAttribute(dbfHandle, static_cast<int>(i), index));
z *= scale;
//set the point height
const_cast<CCVector3*>(singlePoints->getPoint(i))->z = z;
}
singlePoints->invalidateBoundingBox();
}
else
{
assert(false);
}
}
}
}
else
{
ccLog::Warning("[SHP] No numerical field in the associated DBF file!");
}
}
}
else
{
ccLog::Warning(QString("[SHP] Failed to load associated DBF file ('%1')").arg(dbfFilename));
}
}
if (singlePoints)
{
if (singlePoints->size() == 0)
{
delete singlePoints;
singlePoints = nullptr;
}
else
{
CCLib::ScalarField* sf = singlePoints->getScalarField(0);
if (sf)
{
sf->computeMinAndMax();
singlePoints->showSF(true);
}
singlePoints->shrinkToFit();
container.addChild(singlePoints);
}
}
return error;
}
#endif //CC_SHP_SUPPORT
|