File: ccDBRoot.cpp

package info (click to toggle)
cloudcompare 2.10.1-2
  • links: PTS
  • area: main
  • in suites: buster
  • size: 55,916 kB
  • sloc: cpp: 219,837; ansic: 29,944; makefile: 67; sh: 45
file content (2311 lines) | stat: -rw-r--r-- 65,065 bytes parent folder | download | duplicates (2)
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
//##########################################################################
//#                                                                        #
//#                              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)             #
//#                                                                        #
//##########################################################################

#include "ccDBRoot.h"

//Local
#include "ccGLWindow.h"

//Qt
#include <QApplication>
#include <QHeaderView>
#include <QInputDialog>
#include <QMenu>
#include <QMessageBox>
#include <QMimeData>
#include <QRegExp>
#include <QStandardItemModel>
#include <QTreeView>

//qCC_db
#include <cc2DLabel.h>
#include <ccFacet.h>
#include <ccGBLSensor.h>
#include <ccGenericPointCloud.h>
#include <ccGenericPrimitive.h>
#include <ccHObject.h>
#include <ccLog.h>
#include <ccMaterialSet.h>
#include <ccMesh.h>
#include <ccPlane.h>
#include <ccPointCloud.h>
#include <ccPolyline.h>
#include <ccScalarField.h>

//CClib
#include <CCMiscTools.h>

//common
#include <ccPickOneElementDlg.h>

//local
#include "ccPropertiesTreeDelegate.h"
#include "ccSelectChildrenDlg.h"
#include "mainwindow.h"

//system
#include <algorithm>
#include <cassert>
#include <cstring>

//Minimum width of the left column of the properties tree view
static const int c_propViewLeftColumnWidth = 115;

//test whether a cloud can be deleted or moved
static bool CanDetachCloud(const ccHObject* obj)
{
	if (!obj)
	{
		assert(false);
		return false;
	}

	ccHObject* parent = obj->getParent();
	if (!parent)
	{
		assert(false);
		return true;
	}

	//can't delete the vertices of a mesh or the verties of a polyline
	bool blocked = (	(parent->isKindOf(CC_TYPES::MESH) && (ccHObjectCaster::ToGenericMesh(parent)->getAssociatedCloud() == obj))
						||	(parent->isKindOf(CC_TYPES::POLY_LINE) && (dynamic_cast<ccPointCloud*>(ccHObjectCaster::ToPolyline(parent)->getAssociatedCloud()) == obj)) );

	return !blocked;
}

class DBRootIcons
{
public:
	const QIcon &icon( CC_CLASS_ENUM id, bool locked )
	{
		if ( mIconMap.isEmpty() )
		{
			init();
		}
		
		if ( !mIconMap.contains( id ) )
		{
			return (locked ? mDefaultIcons.second : mDefaultIcons.first);
		}
		
		const int		index = mIconMap[id];
		const IconPair	&icons = mIconList[index];
		
		if ( !locked )
		{
			return icons.first;
		}
		
		// If we don't have a locked icon for this class, return the unlocked one
		return (icons.second.isNull() ? icons.first : icons.second);
	}
	
private:
	using IconPair = QPair<QIcon, QIcon>;	// unlocked icon, locked icon (if any)
	using IconPairList = QVector<IconPair>;
	using IconMap = QMap<CC_CLASS_ENUM, int>;
	
	void	init()
	{
		// Special case for default - no icon in general, but a lock if locked
		mDefaultIcons = { {}, QIcon(QStringLiteral(":/CC/images/dbLockSymbol.png")) };
		
		const int	hObjectIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbHObjectSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbHObjectSymbolLocked.png")) } );
		
		const int	cloudIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbCloudSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbCloudSymbolLocked.png")) } );
		
		const int	geomIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbMiscGeomSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbMiscGeomSymbolLocked.png")) } );
		
		const int	meshIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbMeshSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbMeshSymbolLocked.png")) } );
		
		const int	subMeshIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbSubMeshSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbSubMeshSymbolLocked.png")) } );
		
		const int	polyLineIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbPolylineSymbol.png")),
							{} } );
		
		const int	octreeIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbOctreeSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbOctreeSymbolLocked.png")) } );
		
		const int	calibratedImageIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbCalibratedImageSymbol.png")),
							{} } );
		
		const int	imageIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbImageSymbol.png")),
							{} } );
		
		const int	sensorIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbGBLSensorSymbol.png")),
							{} } );
		
		const int	cameraSensorIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbCamSensorSymbol.png")),
							{} } );
		
		const int	materialSetIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbMaterialSymbol.png")),
							{} } );
		
		const int	containerIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbContainerSymbol.png")),
							QIcon(QStringLiteral(":/CC/images/dbContainerSymbolLocked.png")) } );
		
		const int	labelIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbLabelSymbol.png")),
							{} } );
		
		const int	viewportObjIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbViewportSymbol.png")),
							{} } );
		
		const int	viewportLabelIndex = mIconList.count();
		mIconList.append( { QIcon(QStringLiteral(":/CC/images/dbAreaLabelSymbol.png")),
							{} } );
		
		mIconMap = {
			{ CC_TYPES::HIERARCHY_OBJECT, hObjectIndex },
			{ CC_TYPES::POINT_CLOUD, cloudIndex },
			{ CC_TYPES::PLANE, geomIndex },
			{ CC_TYPES::SPHERE, geomIndex },
			{ CC_TYPES::TORUS, geomIndex },
			{ CC_TYPES::CYLINDER, geomIndex },
			{ CC_TYPES::CONE, geomIndex },
			{ CC_TYPES::BOX, geomIndex },
			{ CC_TYPES::DISH, geomIndex },
			{ CC_TYPES::EXTRU, geomIndex },
			{ CC_TYPES::FACET, geomIndex },
			{ CC_TYPES::QUADRIC, geomIndex },
			{ CC_TYPES::MESH, meshIndex },
			{ CC_TYPES::MESH_GROUP, subMeshIndex },
			{ CC_TYPES::SUB_MESH, subMeshIndex },
			{ CC_TYPES::POLY_LINE, polyLineIndex },
			{ CC_TYPES::POINT_OCTREE, octreeIndex },
			{ CC_TYPES::CALIBRATED_IMAGE, calibratedImageIndex },
			{ CC_TYPES::IMAGE, imageIndex },
			{ CC_TYPES::SENSOR, sensorIndex },
			{ CC_TYPES::GBL_SENSOR, sensorIndex },
			{ CC_TYPES::CAMERA_SENSOR, cameraSensorIndex },
			{ CC_TYPES::MATERIAL_SET, materialSetIndex },
			{ CC_TYPES::NORMALS_ARRAY, containerIndex },
			{ CC_TYPES::NORMAL_INDEXES_ARRAY, containerIndex },
			{ CC_TYPES::RGB_COLOR_ARRAY, containerIndex },
			{ CC_TYPES::TEX_COORDS_ARRAY, containerIndex },
			{ CC_TYPES::TRANS_BUFFER, containerIndex },
			{ CC_TYPES::LABEL_2D, labelIndex },
			{ CC_TYPES::VIEWPORT_2D_OBJECT, viewportObjIndex },
			{ CC_TYPES::VIEWPORT_2D_LABEL, viewportLabelIndex },
		};
	}
	
	IconPair		mDefaultIcons;
	IconPairList	mIconList;
	IconMap			mIconMap;
};

Q_GLOBAL_STATIC( DBRootIcons, gDBRootIcons )


ccDBRoot::ccDBRoot(ccCustomQTreeView* dbTreeWidget, QTreeView* propertiesTreeWidget, QObject* parent) : QAbstractItemModel(parent)
{
	m_treeRoot = new ccHObject("DB Tree");

	//DB Tree
	assert(dbTreeWidget);
	m_dbTreeWidget = dbTreeWidget;
	m_dbTreeWidget->setModel(this);
	m_dbTreeWidget->header()->hide();

	//drag & drop support
	m_dbTreeWidget->setDragEnabled(true);
	m_dbTreeWidget->setAcceptDrops(true);
	m_dbTreeWidget->setDropIndicatorShown(true);

	//already done in ui file!
	//m_dbTreeWidget->setDragDropMode(QAbstractItemView::InternalMove);
	//m_dbTreeWidget->setEditTriggers(QAbstractItemView::EditKeyPressed);
	//m_dbTreeWidget->setDragDropMode(QAbstractItemView::InternalMove);
	//m_dbTreeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
	//m_dbTreeWidget->setUniformRowHeights(true);

	//context menu on DB tree elements
	m_dbTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	m_expandBranch = new QAction("Expand branch", this);
	m_collapseBranch = new QAction("Collapse branch", this);
	m_gatherInformation = new QAction("Information (recursive)", this);
	m_sortChildrenType = new QAction("Sort children by type", this);
	m_sortChildrenAZ = new QAction("Sort children by name (A-Z)", this);
	m_sortChildrenZA = new QAction("Sort children by name (Z-A)", this);
	m_selectByTypeAndName = new QAction("Select children by type and/or name", this);
	m_deleteSelectedEntities = new QAction("Delete", this);
	m_toggleSelectedEntities = new QAction("Toggle", this);
	m_toggleSelectedEntitiesVisibility = new QAction("Toggle visibility", this);
	m_toggleSelectedEntitiesColor = new QAction("Toggle color", this);
	m_toggleSelectedEntitiesNormals = new QAction("Toggle normals", this);
	m_toggleSelectedEntitiesMat = new QAction("Toggle materials/textures", this);
	m_toggleSelectedEntitiesSF = new QAction("Toggle SF", this);
	m_toggleSelectedEntities3DName = new QAction("Toggle 3D name", this);
	m_addEmptyGroup = new QAction("Add empty group", this);
	m_alignCameraWithEntity = new QAction("Align camera", this);
	m_alignCameraWithEntityReverse = new QAction("Align camera (reverse)", this);
	m_enableBubbleViewMode = new QAction("Bubble-view", this);
	m_editLabelScalarValue = new QAction("Edit scalar value", this);

	m_contextMenuPos = QPoint(-1,-1);

	//connect custom context menu actions
	connect(m_dbTreeWidget,						SIGNAL(customContextMenuRequested(const QPoint&)),	this, SLOT(showContextMenu(const QPoint&)));
	connect(m_expandBranch,						SIGNAL(triggered()),								this, SLOT(expandBranch()));
	connect(m_collapseBranch,					SIGNAL(triggered()),								this, SLOT(collapseBranch()));
	connect(m_gatherInformation,				SIGNAL(triggered()),								this, SLOT(gatherRecursiveInformation()));
	connect(m_sortChildrenAZ,					SIGNAL(triggered()),								this, SLOT(sortChildrenAZ()));
	connect(m_sortChildrenZA,					SIGNAL(triggered()),								this, SLOT(sortChildrenZA()));
	connect(m_sortChildrenType,					SIGNAL(triggered()),								this, SLOT(sortChildrenType()));
	connect(m_selectByTypeAndName,              SIGNAL(triggered()),								this, SLOT(selectByTypeAndName()));
	connect(m_deleteSelectedEntities,			SIGNAL(triggered()),								this, SLOT(deleteSelectedEntities()));
	connect(m_toggleSelectedEntities,			SIGNAL(triggered()),								this, SLOT(toggleSelectedEntities()));
	connect(m_toggleSelectedEntitiesVisibility,	SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesVisibility()));
	connect(m_toggleSelectedEntitiesColor,		SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesColor()));
	connect(m_toggleSelectedEntitiesNormals,	SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesNormals()));
	connect(m_toggleSelectedEntitiesMat,		SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesMat()));
	connect(m_toggleSelectedEntitiesSF,			SIGNAL(triggered()),								this, SLOT(toggleSelectedEntitiesSF()));
	connect(m_toggleSelectedEntities3DName,		SIGNAL(triggered()),								this, SLOT(toggleSelectedEntities3DName()));
	connect(m_addEmptyGroup,					SIGNAL(triggered()),								this, SLOT(addEmptyGroup()));
	connect(m_alignCameraWithEntity,			SIGNAL(triggered()),								this, SLOT(alignCameraWithEntityDirect()));
	connect(m_alignCameraWithEntityReverse,		SIGNAL(triggered()),								this, SLOT(alignCameraWithEntityIndirect()));
	connect(m_enableBubbleViewMode,				SIGNAL(triggered()),								this, SLOT(enableBubbleViewMode()));
	connect(m_editLabelScalarValue,				SIGNAL(triggered()),								this, SLOT(editLabelScalarValue()));

	//other DB tree signals/slots connection
	connect(m_dbTreeWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(changeSelection(const QItemSelection&, const QItemSelection&)));

	//Properties Tree
	assert(propertiesTreeWidget);
	m_propertiesTreeWidget = propertiesTreeWidget;
	m_propertiesModel = new QStandardItemModel(0, 2, parent);
	m_ccPropDelegate = new ccPropertiesTreeDelegate(m_propertiesModel, m_propertiesTreeWidget);
	m_propertiesTreeWidget->setItemDelegate(m_ccPropDelegate);
	m_propertiesTreeWidget->setModel(m_propertiesModel);
	//already done in ui file!
	//m_propertiesTreeWidget->setSelectionMode(QAbstractItemView::NoSelection);
	//m_propertiesTreeWidget->setAllColumnsShowFocus(true);
	//m_propertiesTreeWidget->header()->setStretchLastSection(true);
	m_propertiesTreeWidget->header()->setSectionResizeMode(QHeaderView::Interactive);
	m_propertiesTreeWidget->setEnabled(false);

	//Properties tree signals/slots connection
	connect(m_ccPropDelegate, SIGNAL(ccObjectPropertiesChanged(ccHObject*)), this, SLOT(updateCCObject(ccHObject*)));
	connect(m_ccPropDelegate, SIGNAL(ccObjectAppearanceChanged(ccHObject*)), this, SLOT(redrawCCObject(ccHObject*)));
	connect(m_ccPropDelegate, SIGNAL(ccObjectAndChildrenAppearanceChanged(ccHObject*)), this, SLOT(redrawCCObjectAndChildren(ccHObject*)));
}

ccDBRoot::~ccDBRoot()
{
	delete m_ccPropDelegate;
	delete m_propertiesModel;
	delete m_treeRoot;
}

void ccDBRoot::unloadAll()
{
	if (!m_treeRoot)
	{
		return;
	}

	while (m_treeRoot->getChildrenNumber() > 0)
	{
		int i = static_cast<int>(m_treeRoot->getChildrenNumber())-1;
		ccHObject* object = m_treeRoot->getChild(i);
		assert(object);

		object->prepareDisplayForRefresh_recursive();

		beginRemoveRows(index(object).parent(),i,i);
		m_treeRoot->removeChild(i);
		endRemoveRows();
	}

	emit dbIsEmpty();

	updatePropertiesView();

	MainWindow::RefreshAllGLWindow(false);
}

ccHObject* ccDBRoot::getRootEntity()
{
	return m_treeRoot;
}

void ccDBRoot::addElement(ccHObject* object, bool autoExpand/*=true*/)
{
	if (!m_treeRoot)
	{
		assert(false);
		return;
	}
	if (!object)
	{
		assert(false);
		return;
	}

	bool wasEmpty = (m_treeRoot->getChildrenNumber() == 0);

	//look for object's parent
	ccHObject* parentObject = object->getParent();
	if (!parentObject)
	{
		//if the object has no parent, it will be inserted at tree root
		parentObject = m_treeRoot;
		m_treeRoot->addChild(object);
	}
	else
	{
		//DGM TODO: how could we check that the object is not already inserted in the DB tree?
		//The double insertion can cause serious damage to it (not sure why excatly though).

		//The code below doesn't work because the 'index' method will always return a valid index
		//as soon as the object has a parent (index creation is a purely 'logical' approach)
		//QModelIndex nodeIndex = index(object);
		//if (nodeIndex.isValid())
		//	return;
	}

	//look for insert node index in tree
	QModelIndex insertNodeIndex = index(parentObject);
	int childPos = parentObject->getChildIndex(object);

	//row insertion operation (start)
	beginInsertRows(insertNodeIndex, childPos, childPos);

	//row insertion operation (end)
	endInsertRows();

	if (autoExpand)
	{
		//expand the parent (just in case)
		m_dbTreeWidget->expand(index(parentObject));
		//and the child
		m_dbTreeWidget->expand(index(object));
	}
	else //if (parentObject)
	{
		m_dbTreeWidget->expand(insertNodeIndex);
	}

	if (wasEmpty && m_treeRoot->getChildrenNumber() != 0)
	{
		emit dbIsNotEmptyAnymore();
	}
}

void ccDBRoot::expandElement(ccHObject* object, bool state)
{
	if (!object || !m_dbTreeWidget)
	{
		return;
	}

	m_dbTreeWidget->setExpanded(index(object), state);
}

void ccDBRoot::removeElements(ccHObject::Container& objects)
{
	if (objects.empty())
	{
		assert(false);
		return;
	}

	//we hide properties view in case this is the deleted object that is currently selected
	hidePropertiesView();

	//every object in tree must have a parent!
	for (ccHObject* object : objects)
	{
		ccHObject* parent = object->getParent();
		if (!parent)
		{
			ccLog::Warning(QString("[ccDBRoot::removeElements] Internal error: object '%1' has no parent").arg(object->getName()));
			continue;
		}

		//just in case
		object->prepareDisplayForRefresh();

		int childPos = parent->getChildIndex(object);
		assert(childPos >= 0);
		{
			//row removal operation (start)
			beginRemoveRows(index(parent), childPos, childPos);

			parent->removeChild(childPos);

			//row removal operation (end)
			endRemoveRows();
		}
	}

	//we restore properties view
	updatePropertiesView();

	if (m_treeRoot->getChildrenNumber() == 0)
	{
		emit dbIsEmpty();
	}
}

void ccDBRoot::removeElement(ccHObject* object)
{
	if (!object)
	{
		assert(false);
		return;
	}

	//we hide properties view in case this is the deleted object that is currently selected
	hidePropertiesView();

	//every object in tree must have a parent!
	ccHObject* parent = object->getParent();
	if (!parent)
	{
		ccLog::Warning("[ccDBRoot::removeElement] Internal error: object has no parent");
		return;
	}

	//just in case
	object->prepareDisplayForRefresh();

	int childPos = parent->getChildIndex(object);
	assert(childPos >= 0);
	{
		//row removal operation (start)
		beginRemoveRows(index(parent), childPos, childPos);

		parent->removeChild(childPos);

		//row removal operation (end)
		endRemoveRows();
	}

	//we restore properties view
	updatePropertiesView();

	if (m_treeRoot->getChildrenNumber() == 0)
	{
		emit dbIsEmpty();
	}
}

void ccDBRoot::deleteSelectedEntities()
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	if (selectedIndexes.empty())
	{
		return;
	}
	unsigned selCount = static_cast<unsigned>(selectedIndexes.size());

	hidePropertiesView();
	bool verticesWarningIssued = false;

	//we remove all objects that are children of other deleted ones!
	//(otherwise we may delete the parent before the child!)
	//TODO DGM: not sure this is still necessary with the new dependency mechanism
	std::vector<ccHObject*> toBeDeleted;
	for (unsigned i = 0; i < selCount; ++i)
	{
		ccHObject* obj = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
		//we don't take care of parent-less objects (i.e. the tree root)
		if (!obj->getParent() || obj->isLocked())
		{
			ccLog::Warning(QString("Object '%1' can't be deleted this way (locked)").arg(obj->getName()));
			continue;
		}

		//we don't consider objects that are 'descendent' of others in the selection
		bool isDescendent = false;
		for (unsigned j = 0; j < selCount; ++j)
		{
			if (i != j)
			{
				ccHObject* otherObj = static_cast<ccHObject*>(selectedIndexes[j].internalPointer());
				if (otherObj->isAncestorOf(obj))
				{
					isDescendent = true;
					break;
				}
			}
		}

		if (!isDescendent)
		{
			//last check: mesh vertices
			if (obj->isKindOf(CC_TYPES::POINT_CLOUD) && !CanDetachCloud(obj))
			{
				if (!verticesWarningIssued)
				{
					ccLog::Warning("Vertices can't be deleted without their parent mesh");
					verticesWarningIssued = true;
				}
				continue;
			}

			toBeDeleted.push_back(obj);
		}
	}

	qism->clear();

	while (!toBeDeleted.empty())
	{
		ccHObject* object = toBeDeleted.back();
		assert(object);
		toBeDeleted.pop_back();

		object->prepareDisplayForRefresh_recursive();

		if (object->isKindOf(CC_TYPES::MESH))
		{
			//specific case: the object is a mesh and its parent is its vertices!
			//(can happen if a Delaunay mesh is computed directly in CC)
			if (object->getParent() && object->getParent() == ccHObjectCaster::ToGenericMesh(object)->getAssociatedCloud())
			{
				object->getParent()->setVisible(true);
			}
		}

		ccHObject* parent = object->getParent();
		int childPos = parent->getChildIndex(object);
		assert(childPos >= 0);

		beginRemoveRows(index(object).parent(), childPos, childPos);
		parent->removeChild(childPos);
		endRemoveRows();
	}

	updatePropertiesView();

	if (m_treeRoot->getChildrenNumber() == 0)
	{
		emit dbIsEmpty();
	}

	MainWindow::RefreshAllGLWindow(false);
}

QVariant ccDBRoot::data(const QModelIndex &index, int role) const
{
	if (!index.isValid())
	{
		return QVariant();
	}

	const ccHObject *item = static_cast<const ccHObject*>(index.internalPointer());
	assert(item);
	if (!item)
	{
		return QVariant();
	}

	switch (role)
	{
	case Qt::DisplayRole:
	{
		QString baseName(item->getName());
		if (baseName.isEmpty())
			baseName = QStringLiteral("no name");
		//specific case
		if (item->isA(CC_TYPES::LABEL_2D))
			baseName = QStringLiteral("2D label: ")+baseName;
		else if (item->isA(CC_TYPES::VIEWPORT_2D_LABEL))
			baseName = QStringLiteral("2D area label: ")+baseName;

		return baseName;
	}
	
	case Qt::EditRole:
	{
		return item->getName();
	}

	case Qt::DecorationRole:
	{
		// does the object have an "embedded icon"? - It may be the case for ccHObject defined in plugins
		QIcon icon = item->getIcon();
		if (!icon.isNull())
		{
			return icon;
		}

		const bool locked = item->isLocked();
		
		switch (item->getClassID())
		{
			case CC_TYPES::HIERARCHY_OBJECT:
				if ( item->getChildrenNumber() )
				{
					return gDBRootIcons->icon( item->getClassID(), locked );
				}
				
				return {};
				
			default:
			{
				return gDBRootIcons->icon( item->getClassID(), locked );
			}
		}
		break;
	}

	case Qt::CheckStateRole:
	{
		// Don't include checkboxes for hierarchy objects if they have no children or only contain hierarchy objects (recursively)
		if ( item->getClassID() == CC_TYPES::HIERARCHY_OBJECT )
		{
			if ( item->getChildrenNumber() == 0 )
			{
				return {};
			}
			
			ccHObject::Container	drawableObjects;
			
			unsigned int	count = item->filterChildren( drawableObjects, true, CC_TYPES::HIERARCHY_OBJECT, true );
			
			if ( item->getChildCountRecursive() == count )
			{
				return {};
			}
		}
		
		if (item->isEnabled())
			return Qt::Checked;
		else
			return Qt::Unchecked;
	}

	default:
		//unhandled role
		break;
	}

	return QVariant();
}

bool ccDBRoot::setData(const QModelIndex &index, const QVariant &value, int role)
{
	if (index.isValid())
	{
		if (role == Qt::EditRole)
		{
			if (value.toString().isEmpty())
			{
				return false;
			}

			ccHObject *item = static_cast<ccHObject*>(index.internalPointer());
			assert(item);
			if (item)
			{
				item->setName(value.toString());

				//particular cases:
				// - labels name is their title (so we update them)
				// - name might be displayed in 3D
				if (item->nameShownIn3D() || item->isKindOf(CC_TYPES::LABEL_2D))
					if (item->isEnabled() && item->isVisible() && item->getDisplay())
						item->getDisplay()->redraw();

				reflectObjectPropChange(item);

				emit dataChanged(index, index);
			}

			return true;
		}
		else if (role == Qt::CheckStateRole)
		{
			ccHObject *item = static_cast<ccHObject*>(index.internalPointer());
			assert(item);
			if (item)
			{
				if (value == Qt::Checked)
					item->setEnabled(true);
				else
					item->setEnabled(false);

				redrawCCObjectAndChildren(item);
				//reflectObjectPropChange(item);
			}

			return true;
		}
	}

	return false;
}


QModelIndex ccDBRoot::index(int row, int column, const QModelIndex &parentIndex) const
{
	if (!hasIndex(row, column, parentIndex))
	{
		return QModelIndex();
	}

	ccHObject *parent = (parentIndex.isValid() ? static_cast<ccHObject*>(parentIndex.internalPointer()) : m_treeRoot);
	assert(parent);
	if (!parent)
	{
		return QModelIndex();
	}
	
	ccHObject *child = parent->getChild(row);
	return child ? createIndex(row, column, child) : QModelIndex();
}

QModelIndex ccDBRoot::index(ccHObject* object)
{
	assert(object);

	if (object == m_treeRoot)
	{
		return QModelIndex();
	}

	ccHObject* parent = object->getParent();
	if (!parent)
	{
		//DGM: actually, it can happen (for instance if the entity is displayed in the local DB of a 3D view)
		//ccLog::Error(QString("An error occurred while creating DB tree index: object '%1' has no parent").arg(object->getName()));
		return QModelIndex();
	}

	int pos = parent->getChildIndex(object);
	assert(pos >= 0);

	return createIndex(pos, 0, object);
}

QModelIndex ccDBRoot::parent(const QModelIndex &index) const
{
	if (!index.isValid())
	{
		return QModelIndex();
	}

	ccHObject *childItem = static_cast<ccHObject*>(index.internalPointer());
	if (!childItem)
	{
		assert(false);
		return QModelIndex();
	}
	ccHObject *parentItem = childItem->getParent();

	assert(parentItem);
	if (!parentItem || parentItem == m_treeRoot)
	{
		return QModelIndex();
	}

	return createIndex(parentItem->getIndex(), 0, parentItem);
}

int ccDBRoot::rowCount(const QModelIndex &parent) const
{
	ccHObject *parentItem = nullptr;
	if (!parent.isValid())
		parentItem = m_treeRoot;
	else
		parentItem = static_cast<ccHObject*>(parent.internalPointer());

	assert(parentItem);
	return (parentItem ? parentItem->getChildrenNumber() : 0);
}

int ccDBRoot::columnCount(const QModelIndex &parent) const
{
	return 1;
}

void ccDBRoot::changeSelection(const QItemSelection & selected, const QItemSelection & deselected)
{
	//first unselect
	QModelIndexList deselectedItems = deselected.indexes();
	{
		for (int i = 0; i < deselectedItems.count(); ++i)
		{
			ccHObject* element = static_cast<ccHObject*>(deselectedItems.at(i).internalPointer());
			assert(element);
			if (element)
			{
				element->setSelected(false);
				element->prepareDisplayForRefresh();
			}
		}
	}

	//then select
	QModelIndexList selectedItems = selected.indexes();
	{
		for (int i = 0; i < selectedItems.count(); ++i)
		{
			ccHObject* element = static_cast<ccHObject*>(selectedItems.at(i).internalPointer());
			assert(element);
			if (element)
			{
				element->setSelected(true);
				element->prepareDisplayForRefresh();
			}
		}
	}

	updatePropertiesView();

	MainWindow::RefreshAllGLWindow();

	emit selectionChanged();
}

void ccDBRoot::unselectEntity(ccHObject* obj)
{
	if (obj && obj->isSelected())
	{
		QModelIndex objIndex = index(obj);
		if (objIndex.isValid())
		{
			QItemSelectionModel* selectionModel = m_dbTreeWidget->selectionModel();
			assert(selectionModel);
			selectionModel->select(objIndex, QItemSelectionModel::Deselect);
		}
	}
}

void ccDBRoot::unselectAllEntities()
{
	QItemSelectionModel* selectionModel = m_dbTreeWidget->selectionModel();
	assert(selectionModel);

	selectionModel->clear();
}

void ccDBRoot::selectEntity(ccHObject* obj, bool forceAdditiveSelection/*=false*/)
{
	bool additiveSelection = forceAdditiveSelection || (QApplication::keyboardModifiers () & Qt::ControlModifier);

	QItemSelectionModel* selectionModel = m_dbTreeWidget->selectionModel();
	assert(selectionModel);

	//valid object? then we will try to select (or toggle) it
	if (obj)
	{
		QModelIndex selectedIndex = index(obj);
		if (selectedIndex.isValid())
		{
			//if CTRL is pushed (or additive selection is forced)
			if (additiveSelection)
			{
				//default case: toggle current item selection state
				if (!obj->isSelected())
				{
					QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
					if (!selectedIndexes.empty())
					{
						//special case: labels can only be merged with labels!
						if (obj->isA(CC_TYPES::LABEL_2D) != static_cast<ccHObject*>(selectedIndexes[0].internalPointer())->isA(CC_TYPES::LABEL_2D))
						{
							ccLog::Warning("[Selection] Labels and other entities can't be mixed (release the CTRL key to start a new selection)");
							return;
						}
					}
				}
				selectionModel->select(selectedIndex,QItemSelectionModel::Toggle);
				obj->setSelected(true);
			}
			else
			{
				if (selectionModel->isSelected(selectedIndex))	//nothing to do
					return;
				selectionModel->select(selectedIndex,QItemSelectionModel::ClearAndSelect);
				obj->setSelected(true);
			}

			//hack: auto-scroll to selected element
			if (obj->isSelected() && !additiveSelection)
				m_dbTreeWidget->scrollTo(selectedIndex);
		}
	}
	//otherwise we clear current selection (if CTRL is not pushed)
	else if (!additiveSelection)
	{
		selectionModel->clear();
	}
}

void ccDBRoot::selectEntities(std::unordered_set<int> entIDs)
{
	bool ctrlPushed = (QApplication::keyboardModifiers () & Qt::ControlModifier);

	//convert input list of IDs to proper entities
	ccHObject::Container entities;
	{
		try
		{
			entities.reserve(entIDs.size());
		}
		catch (const std::bad_alloc&)
		{
			ccLog::Warning("[ccDBRoot::selectEntities] Not enough memory");
			return;
		}

		for (std::unordered_set<int>::const_iterator it = entIDs.begin(); it != entIDs.end(); ++it)
		{
			ccHObject* obj = find(*it);
			if (obj)
				entities.push_back(obj);
		}
	}

	selectEntities(entities, ctrlPushed);
}

void ccDBRoot::selectEntities(const ccHObject::Container& entities, bool incremental/*=false*/)
{
	//selection model
	QItemSelectionModel* selectionModel = m_dbTreeWidget->selectionModel();
	assert(selectionModel);

	//count the number of lables
	size_t labelCount = 0;
	{
		for (size_t i = 0; i < entities.size(); ++i)
		{
			ccHObject* ent = entities[i];
			if (!ent)
			{
				assert(false);
				continue;
			}
			if (ent->isA(CC_TYPES::LABEL_2D))
				++labelCount;
		}
	}

	//create new selection structure
	QItemSelection newSelection;
	{
		//shall we keep labels?
		bool keepLabels = false;
		{
			QModelIndexList formerSelectedIndexes = selectionModel->selectedIndexes();
			if (formerSelectedIndexes.isEmpty() || !incremental)
				keepLabels = (labelCount == entities.size()); //yes if they are the only selected entities
			else if (incremental)
				keepLabels = static_cast<ccHObject*>(formerSelectedIndexes[0].internalPointer())->isA(CC_TYPES::LABEL_2D); //yes if previously selected entities were already labels
		}

		for (size_t i = 0; i < entities.size(); ++i)
		{
			ccHObject* ent = entities[i];
			if (ent)
			{
				//filter input selection (can't keep both labels and standard entities --> we can't mix them!)
				bool isLabel = ent->isA(CC_TYPES::LABEL_2D);
				if (isLabel == keepLabels && (!incremental || !ent->isSelected()))
				{
					QModelIndex selectedIndex = index(ent);
					if (selectedIndex.isValid())
						newSelection.merge(QItemSelection(selectedIndex,selectedIndex),QItemSelectionModel::Select);
				}
			}
		}
	}

	//default behavior: clear previous selection if CTRL is not pushed
	selectionModel->select(newSelection,incremental ? QItemSelectionModel::Select : QItemSelectionModel::ClearAndSelect);
}

ccHObject* ccDBRoot::find(int uniqueID) const
{
	return m_treeRoot->find(uniqueID);
}

void ccDBRoot::showPropertiesView(ccHObject* obj)
{
	m_ccPropDelegate->fillModel(obj);

	m_propertiesTreeWidget->setEnabled(true);
	m_propertiesTreeWidget->setColumnWidth(0, c_propViewLeftColumnWidth);
	//m_propertiesTreeWidget->setColumnWidth(1, m_propertiesTreeWidget->width() - c_propViewLeftColumnWidth);
}

void ccDBRoot::hidePropertiesView()
{
	m_ccPropDelegate->unbind();
	m_propertiesModel->clear();
	m_propertiesTreeWidget->setEnabled(false);
}

void ccDBRoot::reflectObjectPropChange(ccHObject* obj)
{
	assert(m_ccPropDelegate);
	assert(m_propertiesTreeWidget);
	if (!m_propertiesTreeWidget->isEnabled() || m_ccPropDelegate->getCurrentObject() != obj)
	{
		showPropertiesView(obj);
	}
}

void ccDBRoot::updatePropertiesView()
{
	assert(m_dbTreeWidget);
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	if (selectedIndexes.size() == 1)
		showPropertiesView(static_cast<ccHObject*>(selectedIndexes[0].internalPointer()));
	else
		hidePropertiesView();
}

void ccDBRoot::updateCCObject(ccHObject* object)
{
	assert(object);

	QModelIndex idx = index(object);

	if (idx.isValid())
		emit dataChanged(idx,idx);
}

void ccDBRoot::redrawCCObject(ccHObject* object)
{
	assert(object);

	object->redrawDisplay();
}

void ccDBRoot::redrawCCObjectAndChildren(ccHObject* object)
{
	assert(object);

	object->prepareDisplayForRefresh_recursive();
	object->refreshDisplay_recursive(/*only2D=*/false);
}

int ccDBRoot::countSelectedEntities(CC_CLASS_ENUM filter)
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();

	if (selCount == 0 || filter == CC_TYPES::OBJECT)
		return selCount;

	int realCount = 0;
	for (int i = 0; i < selCount; ++i)
	{
		ccHObject* object = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
		if (object && object->isKindOf(filter))
			++realCount;
	}

	return realCount;
}

size_t ccDBRoot::getSelectedEntities(	ccHObject::Container& selectedEntities,
										CC_CLASS_ENUM filter/*=CC_TYPES::OBJECT*/,
										dbTreeSelectionInfo* info/*=nullptr*/ )
{
	selectedEntities.clear();

	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();

	try
	{
		int selCount = selectedIndexes.size();
		for (int i = 0; i < selCount; ++i)
		{
			ccHObject* object = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
			if (object && object->isKindOf(filter))
				selectedEntities.push_back(object);
		}
	}
	catch (const std::bad_alloc&)
	{
		//not enough memory!
	}

	if (info)
	{
		info->reset();
		info->selCount = selectedIndexes.size();

		for (size_t i = 0; i < info->selCount; ++i)
		{
			ccHObject* obj = selectedEntities[i];

			info->sfCount += obj->hasScalarFields() ? 1 : 0;
			info->colorCount += obj->hasColors() ? 1 : 0;
			info->normalsCount += obj->hasNormals() ? 1 : 0;

			if (obj->isA(CC_TYPES::HIERARCHY_OBJECT))
			{
				info->groupCount++;
			}
			else if(obj->isKindOf(CC_TYPES::POINT_CLOUD))
			{
				ccGenericPointCloud* genericCloud = ccHObjectCaster::ToGenericPointCloud(obj);
				info->cloudCount++;
				info->octreeCount += genericCloud->getOctree() != nullptr ? 1 : 0;
				ccPointCloud* qccCloud = ccHObjectCaster::ToPointCloud(obj);
				info->gridCound += qccCloud->gridCount();
			}
			else if (obj->isKindOf(CC_TYPES::MESH))
			{
				info->meshCount++;

				if (obj->isKindOf(CC_TYPES::PLANE))
					info->planeCount++;
			}
			else if (obj->isKindOf(CC_TYPES::POLY_LINE))
			{
				info->polylineCount++;
			}
			else if(obj->isKindOf(CC_TYPES::SENSOR))
			{
				info->sensorCount++;
				if (obj->isKindOf(CC_TYPES::GBL_SENSOR))
					info->gblSensorCount++;
				if (obj->isKindOf(CC_TYPES::CAMERA_SENSOR))
					info->cameraSensorCount++;
			}
			else if (obj->isKindOf(CC_TYPES::POINT_KDTREE))
			{
				info->kdTreeCount++;
			}
		}
	}

	return selectedEntities.size();
}

Qt::DropActions ccDBRoot::supportedDropActions() const
{
	return Qt::MoveAction;
}

Qt::ItemFlags ccDBRoot::flags(const QModelIndex &index) const
{
	if (!index.isValid())
		return Qt::NoItemFlags;

	Qt::ItemFlags defaultFlags = QAbstractItemModel::flags(index);

	//common flags
	defaultFlags |= (Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);

	//class type based filtering
	const ccHObject *item = static_cast<const ccHObject*>(index.internalPointer());
	assert(item);
	if (item && !item->isLocked()) //locked items cannot be drag-dropped
	{
		if (item->isA(CC_TYPES::HIERARCHY_OBJECT)								||
			(item->isKindOf(CC_TYPES::POINT_CLOUD) && CanDetachCloud(item))		|| //vertices can't be displaced
			(item->isKindOf(CC_TYPES::MESH) && !item->isA(CC_TYPES::SUB_MESH))	|| //a sub-mesh can't leave its parent mesh
			item->isKindOf(CC_TYPES::IMAGE)										||
			item->isKindOf(CC_TYPES::LABEL_2D)									||
			item->isKindOf(CC_TYPES::CAMERA_SENSOR)								||
			item->isKindOf(CC_TYPES::PRIMITIVE)									||
			item->isKindOf(CC_TYPES::FACET)										||
			item->isKindOf(CC_TYPES::CUSTOM_H_OBJECT))

		{
			defaultFlags |= (Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled);
		}
		else if (item->isKindOf(CC_TYPES::POLY_LINE))
		{
			const ccPolyline* poly = static_cast<const ccPolyline*>(item);
			//we can only displace a polyline if it is not dependent on it's father!
			const ccHObject* polyVertices = dynamic_cast<const ccHObject*>(poly->getAssociatedCloud());
			if (polyVertices != poly->getParent())
			{
				defaultFlags |= (Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled);
			}
		}
		else if (item->isKindOf(CC_TYPES::VIEWPORT_2D_OBJECT))
		{
			defaultFlags |= Qt::ItemIsDragEnabled;
		}
	}

	return defaultFlags;
}

QMap<int,QVariant> ccDBRoot::itemData(const QModelIndex& index) const
{
	QMap<int,QVariant> map = QAbstractItemModel::itemData(index);

	if (index.isValid())
	{
		const ccHObject* object = static_cast<const ccHObject*>(index.internalPointer());
		if (object)
			map.insert(Qt::UserRole,QVariant(object->getUniqueID()));
	}

	return map;
}


bool ccDBRoot::dropMimeData(const QMimeData* data, Qt::DropAction action, int destRow, int destColumn, const QModelIndex& destParent)
{
	if (action != Qt::MoveAction)
	{
		return false;
	}

	//default mime type for QAbstractItemModel items)
	if (!data->hasFormat("application/x-qabstractitemmodeldatalist"))
	{
		return false;
	}

	//new parent (can't be a leaf object!)
	ccHObject* newParent = destParent.isValid() ? static_cast<ccHObject*>(destParent.internalPointer()) : m_treeRoot;
	if (newParent && newParent->isLeaf())
	{
		return false;
	}

	//decode data
	QByteArray encoded = data->data("application/x-qabstractitemmodeldatalist");
	QDataStream stream(&encoded, QIODevice::ReadOnly);
	while (!stream.atEnd())
	{
		//decode current item index data (row, col, data 'roles' map)
		int srcRow, srcCol;
		QMap<int, QVariant> roleDataMap;
		stream >> srcRow >> srcCol >> roleDataMap;
		if (!roleDataMap.contains(Qt::UserRole))
			continue;

		//selected item
		int uniqueID = roleDataMap.value(Qt::UserRole).toInt();
		ccHObject *item = m_treeRoot->find(uniqueID);
		if (!item)
			continue;
		//ccLog::Print(QString("[Drag & Drop] Source: %1").arg(item->getName()));

		//old parent
		ccHObject* oldParent = item->getParent();
		//ccLog::Print(QString("[Drag & Drop] Parent: %1").arg(oldParent ? oldParent->getName() : "none")));

		//let's check if we can actually move the entity
		if (oldParent)
		{
			if (item->isKindOf(CC_TYPES::POINT_CLOUD))
			{
				//point cloud == mesh vertices?
				if (oldParent->isKindOf(CC_TYPES::MESH) && ccHObjectCaster::ToGenericMesh(oldParent)->getAssociatedCloud() == item)
				{
					if (oldParent != newParent)
					{
						ccLog::Error("Vertices can't leave their parent mesh");
						return false;
					}
				}
			}
			else if (item->isKindOf(CC_TYPES::MESH))
			{
				//a sub-mesh can't leave its parent mesh
				if (item->isA(CC_TYPES::SUB_MESH))
				{
					assert(false);
					ccLog::Error("Sub-meshes can't leave their mesh group");
					return false;
				}
				//a mesh can't leave its associated cloud
				else if (oldParent->isKindOf(CC_TYPES::POINT_CLOUD) && ccHObjectCaster::ToGenericMesh(item)->getAssociatedCloud() == oldParent)
				{
					if (oldParent != newParent)
					{
						ccLog::Error("Meshes can't leave their associated cloud (vertices set)");
						return false;
					}
				}
			}
			else if (/*item->isKindOf(CC_TYPES::PRIMITIVE) || */item->isKindOf(CC_TYPES::IMAGE))
			{
				if (oldParent != newParent)
				{
					ccLog::Error("This kind of entity can't leave their parent");
					return false;
				}
			}
			else if (oldParent != newParent)
			{
				//a label or a group of labels can't be moved to another cloud!
				//ccHObject::Container labels;
				//if (item->isA(CC_TYPES::LABEL_2D))
				//	labels.push_back(item);
				//else
				//	item->filterChildren(labels, true, CC_TYPES::LABEL_2D);

				////for all labels in the sub-tree
				//for (ccHObject::Container::const_iterator it = labels.begin(); it != labels.end(); ++it)
				//{
				//	if ((*it)->isA(CC_TYPES::LABEL_2D)) //Warning: cc2DViewportLabel is also a kind of 'CC_TYPES::LABEL_2D'!
				//	{
				//		cc2DLabel* label = static_cast<cc2DLabel*>(*it);
				//		bool canMove = false;
				//		for (unsigned j = 0; j < label->size(); ++j)
				//		{
				//			assert(label->getPoint(j).cloud);
				//			//3 options to allow moving a label:
				//			if (item->isAncestorOf(label->getPoint(j).cloud) //label's cloud is inside sub-tree
				//				|| newParent == label->getPoint(j).cloud //destination is label's cloud
				//				|| label->getPoint(j).cloud->isAncestorOf(newParent)) //destination is below label's cloud
				//			{
				//				canMove = true;
				//				break;
				//			}
				//		}

				//		if (!canMove)
				//		{
				//			ccLog::Error("Labels (or group of) can't leave their parent");
				//			return false;
				//		}
				//	}
				//}
			}
		}

		//special case: moving an item inside the same 'parent'
		if (oldParent && newParent == oldParent)
		{
			int oldRow = oldParent->getChildIndex(item);
			if (destRow < 0)
			{
				assert(oldParent->getChildrenNumber() != 0);
				destRow = static_cast<int>(oldParent->getChildrenNumber())-1;
			}
			else if (oldRow < destRow)
			{
				assert(destRow > 0);
				--destRow;
			}
			else if (oldRow == destRow)
			{
				return false; //nothing to do
			}
		}

		//remove link with old parent (only CHILD/PARENT related flags!)
		int itemDependencyFlags = item->getDependencyFlagsWith(oldParent); //works even with nullptr
		int fatherDependencyFlags = oldParent ? oldParent->getDependencyFlagsWith(item) : 0;
		if (oldParent)
		{
			oldParent->removeDependencyFlag(item,ccHObject::DP_PARENT_OF_OTHER);
			item->removeDependencyFlag(oldParent,ccHObject::DP_PARENT_OF_OTHER);
		}

		//remove item from current position
		removeElement(item);

		//sets new parent
		assert(newParent);
		newParent->addChild(item,fatherDependencyFlags & ccHObject::DP_PARENT_OF_OTHER,destRow);
		item->addDependency(newParent,itemDependencyFlags & ccHObject::DP_PARENT_OF_OTHER);
		//restore other flags on old parent (as all flags have been removed when calling removeElement!)
		if (oldParent)
		{
			oldParent->addDependency(item,fatherDependencyFlags & (~ccHObject::DP_PARENT_OF_OTHER));
			item->addDependency(oldParent,itemDependencyFlags & (~ccHObject::DP_PARENT_OF_OTHER));
		}

		if (newParent->getDisplay() == 0)
			newParent->setDisplay(item->getDisplay());
		else if (item->getDisplay() == 0)
			item->setDisplay(newParent->getDisplay());

		//add item back
		addElement(item,false);
		item->prepareDisplayForRefresh();
	}

	MainWindow::RefreshAllGLWindow(false);

	return true;
}

void ccDBRoot::expandBranch()
{
	expandOrCollapseHoveredBranch(true);
}

void ccDBRoot::collapseBranch()
{
	expandOrCollapseHoveredBranch(false);
}

void ccDBRoot::expandOrCollapseHoveredBranch(bool expand)
{
	//not initialized?
	if (m_contextMenuPos.x() < 0 || m_contextMenuPos.y() < 0)
		return;

	QModelIndex clickIndex = m_dbTreeWidget->indexAt(m_contextMenuPos);
	if (!clickIndex.isValid())
		return;
	ccHObject* item = static_cast<ccHObject*>(clickIndex.internalPointer());
	assert(item);

	if (!item || item->getChildrenNumber() == 0)
		return;

	//we recursively expand sub-branches
	ccHObject::Container toExpand;
	try
	{
		toExpand.push_back(item);
		while (!toExpand.empty())
		{
			item = toExpand.back();
			toExpand.pop_back();

			QModelIndex itemIndex = index(item);
			if (itemIndex.isValid())
			{
				if (expand)
					m_dbTreeWidget->expand(itemIndex);
				else
					m_dbTreeWidget->collapse(itemIndex);
			}

			assert(item->getChildrenNumber() != 0);
			for (unsigned i=0; i<item->getChildrenNumber(); ++i)
			{
				if (item->getChild(i)->getChildrenNumber() != 0)
					toExpand.push_back(item->getChild(i));
			}
		}
	}
	catch (const std::bad_alloc&)
	{
		//not enough memory!
	}
}

void ccDBRoot::alignCameraWithEntity(bool reverse)
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();
	if (selCount == 0)
		return;

	ccHObject* obj = static_cast<ccHObject*>(selectedIndexes[0].internalPointer());
	if (!obj)
		return;
	ccGenericGLDisplay* display = obj->getDisplay();
	if (!display)
	{
		ccLog::Warning("[alignCameraWithEntity] Selected entity has no associated display");
		return;
	}
	assert(display);
	ccGLWindow* win = static_cast<ccGLWindow*>(display);

	//plane normal
	CCVector3d planeNormal;
	CCVector3d planeVertDir;
	CCVector3 center;

	if (obj->isA(CC_TYPES::LABEL_2D)) //2D label with 3 points?
	{
		cc2DLabel* label = static_cast<cc2DLabel*>(obj);
		//work only with labels with 3 points!
		if (label->size() == 3)
		{
			const cc2DLabel::PickedPoint& A = label->getPoint(0);
			const CCVector3* _A = A.cloud->getPoint(A.index);
			const cc2DLabel::PickedPoint& B = label->getPoint(1);
			const CCVector3* _B = B.cloud->getPoint(B.index);
			const cc2DLabel::PickedPoint& C = label->getPoint(2);
			const CCVector3* _C = C.cloud->getPoint(C.index);
			CCVector3 N = (*_B - *_A).cross(*_C - *_A);
			planeNormal = CCVector3d::fromArray(N.u);
			planeVertDir = /*(*_B-*_A)*/win->getCurrentUpDir();
			center = (*_A + *_B + *_C) / 3;
		}
		else
		{
			assert(false);
			return;
		}
	}
	else if (obj->isA(CC_TYPES::PLANE)) //plane
	{
		ccPlane* plane = static_cast<ccPlane*>(obj);
		//3rd column = plane normal!
		planeNormal = CCVector3d::fromArray(plane->getNormal().u);
		planeVertDir = CCVector3d::fromArray(plane->getTransformation().getColumnAsVec3D(1).u);
		center = plane->getOwnBB().getCenter();
	}
	else if (obj->isA(CC_TYPES::FACET)) //facet
	{
		ccFacet* facet = static_cast<ccFacet*>(obj);
		planeNormal = CCVector3d::fromArray(facet->getNormal().u);
		CCVector3d planeHorizDir(0, 1, 0);
		CCLib::CCMiscTools::ComputeBaseVectors(planeNormal,planeHorizDir,planeVertDir);
		center = facet->getBB_recursive(false,false).getCenter();
	}
	else
	{
		assert(false);
		return;
	}

	//we can now make the camera look in the direction of the normal
	if (!reverse)
		planeNormal *= -1;
	win->setCustomView(planeNormal,planeVertDir);

	//output the transformation matrix that would make this normal points towards +Z
	{
		ccGLMatrixd transMat;
		transMat.setTranslation(-center);
		ccGLMatrixd viewMat = win->getViewportParameters().viewMat;
		viewMat = viewMat * transMat;
		viewMat.setTranslation(viewMat.getTranslationAsVec3D() + CCVector3d::fromArray(center.u));

		ccLog::Print("[Align camera] Corresponding view matrix:");
		ccLog::Print(viewMat.toString(12,' ')); //full precision
		ccLog::Print("[Orientation] You can copy this matrix values (CTRL+C) and paste them in the 'Apply transformation tool' dialog");
	}
}

void ccDBRoot::gatherRecursiveInformation()
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();
	if (selCount == 0)
		return;

	struct GlobalInfo
	{
		//properties
		unsigned pointCount;
		unsigned triangleCount;
		unsigned colorCount;
		unsigned normalCount;
		unsigned materialCount;
		unsigned scalarFieldCount;

		//entities
		unsigned cloudCount;
		unsigned meshCount;
		unsigned octreeCount;
		unsigned imageCount;
		unsigned sensorCount;
		unsigned labelCount;
	}
	info;

	memset(&info, 0, sizeof(GlobalInfo));

	//init the list of entities to process
	ccHObject::Container toProcess;
	try
	{
		toProcess.resize(selCount);
	}
	catch (const std::bad_alloc&)
	{
		ccLog::Error("Not engough memory");
		return;
	}

	for (int i = 0; i < selCount; ++i)
	{
			toProcess[i] = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
	}

	ccHObject::Container alreadyProcessed;
	while (!toProcess.empty())
	{
		ccHObject* ent = toProcess.back();
		toProcess.pop_back();

		//we don't process entities twice!
		if (std::find(alreadyProcessed.begin(), alreadyProcessed.end(), ent) != alreadyProcessed.end())
		{
			continue;
		}

		//gather information from current entity
		if (ent->isA(CC_TYPES::POINT_CLOUD))
		{
			ccPointCloud* cloud = static_cast<ccPointCloud*>(ent);
			info.cloudCount++;

			unsigned cloudSize = cloud->size();
			info.pointCount += cloudSize;
			info.colorCount += (cloud->hasColors() ? cloudSize : 0);
			info.normalCount += (cloud->hasNormals() ? cloudSize : 0);
			info.scalarFieldCount += cloud->getNumberOfScalarFields();
		}
		else if (ent->isKindOf(CC_TYPES::MESH))
		{
			ccMesh* mesh = static_cast<ccMesh*>(ent);

			info.meshCount++;
			unsigned meshSize = mesh->size();
			info.triangleCount += meshSize;
			info.normalCount += (mesh->hasTriNormals() ? meshSize : 0);
			info.materialCount += (mesh->getMaterialSet() ? (unsigned)mesh->getMaterialSet()->size() : 0);
		}
		else if (ent->isKindOf(CC_TYPES::LABEL_2D))
		{
			info.labelCount++;
		}
		else if (ent->isKindOf(CC_TYPES::SENSOR))
		{
			info.sensorCount++;
		}
		else if (ent->isKindOf(CC_TYPES::POINT_OCTREE))
		{
			info.octreeCount++;
		}
		else if (ent->isKindOf(CC_TYPES::IMAGE))
		{
			info.imageCount++;
		}

		//we can add its children to the 'toProcess' list and itself to the 'processed' list
		try
		{
			for (unsigned i = 0; i < ent->getChildrenNumber(); ++i)
			{
				toProcess.push_back(ent->getChild(i));
			}
			alreadyProcessed.push_back(ent);
		}
		catch (const std::bad_alloc&)
		{
			ccLog::Error("Not engough memory");
			return;
		}
	}

	//output information
	{
		QStringList infoStr;

		const QString separator("--------------------------");

		infoStr << QString("Point(s):\t\t%L1").arg(info.pointCount);
		infoStr << QString("Triangle(s):\t\t%L1").arg(info.triangleCount);

		infoStr << separator;
		if (info.colorCount)
			infoStr << QString("Color(s):\t\t%L1").arg(info.colorCount);
		if (info.normalCount)
			infoStr << QString("Normal(s):\t\t%L1").arg(info.normalCount);
		if (info.scalarFieldCount)
			infoStr << QString("Scalar field(s):\t\t%L1").arg(info.scalarFieldCount);
		if (info.materialCount)
			infoStr << QString("Material(s):\t\t%L1").arg(info.materialCount);

		infoStr << separator;
		infoStr << QString("Cloud(s):\t\t%L1").arg(info.cloudCount);
		infoStr << QString("Mesh(es):\t\t%L1").arg(info.meshCount);
		if (info.octreeCount)
			infoStr << QString("Octree(s):\t\t%L1").arg(info.octreeCount);
		if (info.imageCount)
			infoStr << QString("Image(s):\t\t%L1").arg(info.imageCount);
		if (info.labelCount)
			infoStr << QString("Label(s):\t\t%L1").arg(info.labelCount);
		if (info.sensorCount)
			infoStr << QString("Sensor(s):\t\t%L1").arg(info.sensorCount);

		//display info box
		QMessageBox::information(MainWindow::TheInstance(),
								 "Information",
								 infoStr.join("\n"));
	}
}

void ccDBRoot::sortChildrenAZ()
{
	sortSelectedEntitiesChildren(SORT_A2Z);
}

void ccDBRoot::sortChildrenZA()
{
	sortSelectedEntitiesChildren(SORT_Z2A);
}

void ccDBRoot::sortChildrenType()
{
	sortSelectedEntitiesChildren(SORT_BY_TYPE);
}

void ccDBRoot::sortSelectedEntitiesChildren(SortRules sortRule)
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();
	if (selCount == 0)
		return;

	for (int i = 0; i < selCount; ++i)
	{
		ccHObject* item = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
		unsigned childCount = (item ? item->getChildrenNumber() : 0);
		if (childCount > 1)
		{
			//remove all children from DB tree
			beginRemoveRows(selectedIndexes[i], 0, childCount - 1);

			//row removal operation (end)
			endRemoveRows();

			//sort
			for (unsigned k = 0; k < childCount - 1; ++k)
			{
				unsigned firstChildIndex = k;
				ccHObject* firstChild = item->getChild(k);
				QString firstChildName = firstChild->getName().toUpper();

				for (unsigned j = k + 1; j < childCount; ++j)
				{
					bool swap = false;
					QString currentName = item->getChild(j)->getName().toUpper();
					switch (sortRule)
					{
					case SORT_A2Z:
						swap = (firstChildName.compare(currentName) > 0);
						break;
					case SORT_Z2A:
						swap = (firstChildName.compare(currentName) < 0);
						break;
					case SORT_BY_TYPE:
						if (firstChild->getClassID() == item->getChild(j)->getClassID())
							swap = (firstChildName.compare(currentName) > 0); //A2Z in second choice
						else
							swap = (firstChild->getClassID() > item->getChild(j)->getClassID());
						break;
					}

					if (swap)
					{
						firstChildIndex = j;
						firstChildName = currentName;
					}
				}

				if (k != firstChildIndex)
					item->swapChildren(k, firstChildIndex);
			}

			//add children back
			beginInsertRows(selectedIndexes[i], 0, childCount - 1);

			//row insertion operation (end)
			endInsertRows();
		}
	}
}

void ccDBRoot::selectByTypeAndName()
{
	ccSelectChildrenDlg scDlg(MainWindow::TheInstance());
	scDlg.addType("Point cloud",       CC_TYPES::POINT_CLOUD);
	scDlg.addType("Poly-line",         CC_TYPES::POLY_LINE);
	scDlg.addType("Mesh",              CC_TYPES::MESH);
	scDlg.addType("  Sub-mesh",        CC_TYPES::SUB_MESH);
	scDlg.addType("  Primitive",       CC_TYPES::PRIMITIVE);
	scDlg.addType("    Plane",         CC_TYPES::PLANE);
	scDlg.addType("    Sphere",        CC_TYPES::SPHERE);
	scDlg.addType("    Torus",         CC_TYPES::TORUS);
	scDlg.addType("    Cylinder",      CC_TYPES::CYLINDER);
	scDlg.addType("    Cone",          CC_TYPES::CONE);
	scDlg.addType("    Box",           CC_TYPES::BOX);
	scDlg.addType("    Dish",          CC_TYPES::DISH);
	scDlg.addType("    Extrusion",     CC_TYPES::EXTRU);
	scDlg.addType("Sensor",            CC_TYPES::SENSOR);
	scDlg.addType("  GBL/TLS sensor",  CC_TYPES::GBL_SENSOR);
	scDlg.addType("  Camera sensor",   CC_TYPES::CAMERA_SENSOR);
	scDlg.addType("Image",             CC_TYPES::IMAGE);
	scDlg.addType("Facet",             CC_TYPES::FACET);
	scDlg.addType("Label",             CC_TYPES::LABEL_2D);
	scDlg.addType("Area label",        CC_TYPES::VIEWPORT_2D_LABEL);
	scDlg.addType("Octree",            CC_TYPES::POINT_OCTREE);
	scDlg.addType("Kd-tree",           CC_TYPES::POINT_KDTREE);
	scDlg.addType("Viewport",          CC_TYPES::VIEWPORT_2D_OBJECT);
	scDlg.addType("Custom Types",      CC_TYPES::CUSTOM_H_OBJECT);

	if (!scDlg.exec())
		return;

	// for type checking
	CC_CLASS_ENUM type = CC_TYPES::OBJECT; // all objects are matched by def
	bool exclusive = false;

	if (scDlg.getTypeIsUsed()) // we are using type checking
	{
		type = scDlg.getSelectedType();

		//some types are exclusive, some are generic, and some can be both
		//(e.g. Meshes)
		//
		//For generic-only types the match type gets overridden and forced to
		//false because exclusive match makes no sense!
		switch (type)
		{
		case CC_TYPES::HIERARCHY_OBJECT: //returned if no type is selected (i.e. all objects are selected!)
		case CC_TYPES::PRIMITIVE:
		case CC_TYPES::SENSOR:
		case CC_TYPES::IMAGE:
			exclusive = false;
			break;
		default:
			exclusive = scDlg.getStrictMatchState();
			break;
		}
	}


	// for name matching - def values
	bool regex = false;
	QString name; // an empty string by default

	if (scDlg.getNameMatchIsUsed())
	{
		regex = scDlg.getNameIsRegex();
		name = scDlg.getSelectedName();
	}


	selectChildrenByTypeAndName(type, exclusive, name, regex);
}

/* name is optional, if passed it is used to restrict the selection by type */
void ccDBRoot::selectChildrenByTypeAndName(CC_CLASS_ENUM type,
										   bool typeIsExclusive/*=true*/,
										   QString name/*=QString()*/,
										   bool nameIsRegex/*= false*/)
{
	//not initialized?
	if (m_contextMenuPos.x() < 0 || m_contextMenuPos.y() < 0)
		return;

	QModelIndex clickIndex = m_dbTreeWidget->indexAt(m_contextMenuPos);
	if (!clickIndex.isValid())
		return;
	ccHObject* item = static_cast<ccHObject*>(clickIndex.internalPointer());
	assert(item);

	if (!item || item->getChildrenNumber() == 0)
		return;

	ccHObject::Container filteredByType;
	item->filterChildren(filteredByType, true, type, typeIsExclusive);

	// The case of an empty filteredByType is handled implicitly, to make
	// the ctrlPushed behavior below more consistent (i.e. when no object
	// is found and Control was NOT pressed the selection will still be
	// cleared).
	ccHObject::Container toSelect;
	try
	{
		if (name.isEmpty())
		{
			toSelect = filteredByType;
		}
		else
		{
			for (size_t i=0; i<filteredByType.size(); ++i)
			{
				ccHObject* child = filteredByType[i];

				if (nameIsRegex) // regex matching
				{

					QRegularExpression re(name);
					QRegularExpressionMatch match = re.match(child->getName());
					bool hasMatch = match.hasMatch(); // true
					if (hasMatch)
						toSelect.push_back(child);

				}

				else if (child->getName().compare(name) == 0) // simple comparison
					toSelect.push_back(child);
			}
		}
	}
	catch (const std::bad_alloc&)
	{
		ccLog::Warning("[selectChildrenByTypeAndName] Not enough memory");
		return;
	}

	bool ctrlPushed = (QApplication::keyboardModifiers () & Qt::ControlModifier);
	selectEntities(toSelect, ctrlPushed);
}

void ccDBRoot::toggleSelectedEntitiesProperty(TOGGLE_PROPERTY prop)
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();
	if (selCount == 0)
		return;

	//hide properties view
	hidePropertiesView();

	for (int i=0; i<selCount; ++i)
	{
		ccHObject* item = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
		if (!item)
		{
			assert(false);
			continue;
		}
		switch (prop)
		{
		case TG_ENABLE: //enable state
			item->setEnabled(!item->isEnabled());
			break;
		case TG_VISIBLE: //visibility
			item->toggleVisibility();
			break;
		case TG_COLOR: //color
			item->toggleColors();
			break;
		case TG_NORMAL: //normal
			item->toggleNormals();
			break;
		case TG_SF: //SF
			item->toggleSF();
			break;
		case TG_MATERIAL: //Materials/textures
			item->toggleMaterials();
			break;
		case TG_3D_NAME: //3D name
			item->toggleShowName();
			break;
		}
		item->prepareDisplayForRefresh();
	}

	//we restablish properties view
	updatePropertiesView();

	MainWindow::RefreshAllGLWindow(false);
}

void ccDBRoot::addEmptyGroup()
{
	//not initialized?
	if (m_contextMenuPos.x() < 0 || m_contextMenuPos.y() < 0)
		return;

	QModelIndex index = m_dbTreeWidget->indexAt(m_contextMenuPos);
	ccHObject* newGroup = new ccHObject("Group");
	if (index.isValid())
	{
		ccHObject* parent = static_cast<ccHObject*>(index.internalPointer());
		if (parent)
			parent->addChild(newGroup);
	}

	addElement(newGroup);
}

void ccDBRoot::enableBubbleViewMode()
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();
	if (selCount == 0)
		return;

	for (int i = 0; i < selCount; ++i)
	{
		ccHObject* item = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
		if (item &&item->isA(CC_TYPES::GBL_SENSOR))
		{
			static_cast<ccGBLSensor*>(item)->applyViewport();
		}
	}

	MainWindow::RefreshAllGLWindow(false);
}

void ccDBRoot::editLabelScalarValue()
{
	QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();
	QModelIndexList selectedIndexes = qism->selectedIndexes();
	int selCount = selectedIndexes.size();
	if (selCount == 0)
	{
		return;
	}

	ccHObject* obj = static_cast<ccHObject*>(selectedIndexes[0].internalPointer());
	cc2DLabel* label = ccHObjectCaster::To2DLabel(obj);
	if (!label || label->size() != 1)
	{
		return;
	}

	const cc2DLabel::PickedPoint& P = label->getPoint(0);
	if (!P.cloud)
	{
		assert(false);
		return;
	}

	if (!P.cloud->isA(CC_TYPES::POINT_CLOUD) || !P.cloud->hasScalarFields())
	{
		return;
	}
	
	ccPointCloud* pc = static_cast<ccPointCloud*>(P.cloud);
	ccScalarField* sf = pc->getCurrentDisplayedScalarField();
	if (!sf)
	{
		ccLog::Warning("[editLabelScalarValue] No active scalar field");
		return;
	}

	ScalarType s = sf->getValue(P.index);

	bool ok = false;
	double newValue = QInputDialog::getDouble(MainWindow::TheInstance(), "Edit scalar value", QString("%1 (%2) =").arg(sf->getName()).arg(P.index), s, -2147483647, 2147483647, 6, &ok);
	if (!ok)
	{
		//process cancelled by the user
		return;
	}

	ScalarType newS = static_cast<ScalarType>(newValue);
	if (s != newS)
	{
		//update the value and update the display
		sf->setValue(P.index, newS);
		sf->computeMinAndMax();
		pc->redrawDisplay();
	}
}

void ccDBRoot::showContextMenu(const QPoint& menuPos)
{
	m_contextMenuPos = menuPos;

	//build custom context menu
	QMenu menu;

	QModelIndex index = m_dbTreeWidget->indexAt(menuPos);
	if (index.isValid())
	{
		QItemSelectionModel* qism = m_dbTreeWidget->selectionModel();

		//selected items?
		QModelIndexList selectedIndexes = qism->selectedIndexes();
		int selCount = selectedIndexes.size();
		if (selCount)
		{
			bool toggleVisibility = false;
			bool toggleOtherProperties = false;
			bool toggleMaterials = false;
			bool hasMoreThanOneChild = false;
			bool hasExactlyOnePlanarEntity = false;
			bool leafObject = false;
			bool hasExacltyOneGBLSenor = false;
			bool hasExactlyOnePlane = false;
			bool canEditLabelScalarValue = false;
			for (int i = 0; i < selCount; ++i)
			{
				ccHObject* item = static_cast<ccHObject*>(selectedIndexes[i].internalPointer());
				if (!item)
				{
					assert(false);
					continue;
				}
				if (item->getChildrenNumber() > 1)
				{
					hasMoreThanOneChild = true;
				}
				leafObject |= item->isLeaf();
				if (!item->isA(CC_TYPES::HIERARCHY_OBJECT))
				{
					toggleVisibility = true;
					if (item->isKindOf(CC_TYPES::POINT_CLOUD))
					{
						toggleOtherProperties = true;
					}
					else if (item->isKindOf(CC_TYPES::MESH))
					{
						toggleMaterials = true;
						toggleOtherProperties = true;
					}

					if (selCount == 1)
					{
						if (item->isA(CC_TYPES::LABEL_2D))
						{
							hasExactlyOnePlanarEntity = (static_cast<cc2DLabel*>(item)->size() == 3);
							cc2DLabel* label = ccHObjectCaster::To2DLabel(item);
							if (label)
							{
								canEditLabelScalarValue = (	label->size() == 1
														&&	label->getPoint(0).cloud
														&&	label->getPoint(0).cloud->hasScalarFields()
														&&	label->getPoint(0).cloud->isA(CC_TYPES::POINT_CLOUD)
														&&	static_cast<ccPointCloud*>(label->getPoint(0).cloud)->getCurrentDisplayedScalarField() != 0
														);
							}
							else
							{
								assert(false);
							}
						}
						else if (item->isA(CC_TYPES::PLANE) || item->isA(CC_TYPES::FACET))
						{
							hasExactlyOnePlanarEntity = true;
							hasExactlyOnePlane = item->isKindOf(CC_TYPES::PLANE);
						}
						else if (item->isA(CC_TYPES::GBL_SENSOR))
						{
							hasExacltyOneGBLSenor = true;
						}
					}
				}
			}

			if (hasExactlyOnePlanarEntity)
			{
				menu.addAction(m_alignCameraWithEntity);
				menu.addAction(m_alignCameraWithEntityReverse);
				menu.addSeparator();
			}
			if (hasExactlyOnePlane)
			{
				MainWindow::TheInstance()->addEditPlaneAction( menu );
			}
			if (hasExacltyOneGBLSenor)
			{
				menu.addAction(m_enableBubbleViewMode);
			}
			
			menu.addAction(m_gatherInformation);
			menu.addSeparator();
			menu.addAction(m_toggleSelectedEntities);
			if (toggleVisibility)
			{
				menu.addAction(m_toggleSelectedEntitiesVisibility);
			}
			if (toggleOtherProperties)
			{
				menu.addAction(m_toggleSelectedEntitiesColor);
				menu.addAction(m_toggleSelectedEntitiesNormals);
				menu.addAction(m_toggleSelectedEntitiesSF);
			}
			if (toggleMaterials)
			{
				menu.addAction(m_toggleSelectedEntitiesMat);
			}
			menu.addAction(m_toggleSelectedEntities3DName);
			menu.addSeparator();
			menu.addAction(m_deleteSelectedEntities);
			if (selCount == 1 && hasMoreThanOneChild)
			{
				menu.addSeparator();
				menu.addAction(m_sortChildrenAZ);
				menu.addAction(m_sortChildrenZA);
				menu.addAction(m_sortChildrenType);
			}

			if (selCount == 1 && !leafObject)
			{
				menu.addSeparator();
				menu.addAction(m_selectByTypeAndName);
				menu.addSeparator();
				menu.addAction(m_addEmptyGroup);
			}

			if (canEditLabelScalarValue)
			{
				menu.addSeparator();
				menu.addAction(m_editLabelScalarValue);
			}

			menu.addSeparator();
		}

		menu.addAction(m_expandBranch);
		menu.addAction(m_collapseBranch);
	}
	else
	{
		menu.addSeparator();
		menu.addAction(m_addEmptyGroup);
	}

	menu.exec(m_dbTreeWidget->mapToGlobal(menuPos));
}

QItemSelectionModel::SelectionFlags ccCustomQTreeView::selectionCommand(const QModelIndex& index, const QEvent* event/*=0*/) const
{
	if (index.isValid())
	{
		//special case: labels can only be merged with labels!
		QModelIndexList selectedIndexes = selectionModel()->selectedIndexes();
		if (!selectedIndexes.empty() && !selectionModel()->isSelected(index))
		{
			ccHObject* selectedItem = static_cast<ccHObject*>(index.internalPointer());
			if (selectedItem && selectedItem->isA(CC_TYPES::LABEL_2D) != static_cast<ccHObject*>(selectedIndexes[0].internalPointer())->isA(CC_TYPES::LABEL_2D))
				return QItemSelectionModel::ClearAndSelect;
		}
	}

	return QTreeView::selectionCommand(index,event);
}